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
Update Power Pages skills to use ToDo list for better task tracking (#13)
Priyanshu Agrawalb8e90612c356
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 8708707af..b8a4a5020 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -1,6 +1,6 @@{"name": "power-platform-skills",- "description": "Directory of Claude Code extensions for Power Platform development",+ "description": "Directory of agent plugins for Power Platform development","owner": {"name": "Microsoft"},@@ -12,27 +12,15 @@"author": {"name": "Microsoft"},+ "tags": [+ "power platform",+ "power pages",+ "microsoft power platform",+ "microsoft"+ ],"source": "./plugins/power-pages","category": "development",- "strict": false,- "lspServers": {- "typescript": {- "command": "typescript-language-server",- "args": [- "--stdio"- ],- "extensionToLanguage": {- ".ts": "typescript",- ".tsx": "typescriptreact",- ".js": "javascript",- ".jsx": "javascriptreact",- ".mts": "typescript",- ".cts": "typescript",- ".mjs": "javascript",- ".cjs": "javascript"- }- }- }+ "strict": false},{"name": "power-apps",diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.mddeleted file mode 120000index be77ac83a..000000000--- a/.claude/CLAUDE.md+++ /dev/null@@ -1 +0,0 @@-../AGENTS.md\ No newline at end of filediff --git a/AGENTS.md b/AGENTS.mdindex 89fb7a732..921924374 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,18 +1,13 @@# Power Platform Skills - Development Guidelines-This file provides generic instructions for Claude Code when working on this plugin marketplace. For plugin-specific guidelines, see the `AGENTS.md` file in each plugin's folder.+This file provides guidance to AI Agents when working with code in this repository.-## Official Documentation+## What This Repo Is-**Always refer to official Claude Code documentation when modifying plugin structure:**--- **Skills**: https://code.claude.com/docs/en/skills-- **Plugins Reference**: https://code.claude.com/docs/en/plugins-reference+A **plugin marketplace** for Power Platform development by Microsoft. The marketplace manifest (`.claude-plugin/marketplace.json`) references individual plugins in `plugins/`. Each plugin has its own `AGENTS.md` with plugin-specific guidance.## Repository Structure-This repository is a **plugin marketplace** containing multiple plugins:-```power-platform-skills/├── .claude-plugin/@@ -30,137 +25,39 @@ power-platform-skills/└── README.md # Repository overview```-**Important**:-- The root `.claude-plugin/marketplace.json` defines the marketplace and lists available plugins-- Each plugin in `plugins/` has its own `.claude-plugin/plugin.json` manifest-- Each plugin has its own `AGENTS.md` with plugin-specific guidelines-- Plugin components (agents, commands, skills, shared) must be at the plugin root, not inside `.claude-plugin/`--## When Modifying Skills--Skills use YAML frontmatter. Reference the official docs for all available fields:--```yaml-----name: skill-name # Optional: defaults to directory name-description: What this skill does # Recommended: Claude uses for auto-loading-user-invocable: true # Optional: default true-disable-model-invocation: false # Optional: default false-allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task"] # Optional: tool restrictions-argument-hint: [project-path] # Optional: autocomplete hint-context: fork # Optional: run in subagent-agent: Explore # Optional: subagent type-model: opus # Optional: model override-----```--## When Modifying Agents--Agents support optional frontmatter:--```yaml-----description: What this agent specializes in-capabilities: ["task1", "task2"]-----```--## When Modifying plugin.json--Refer to https://code.claude.com/docs/en/plugins-reference for all available fields.--Required: `name`-Recommended: `version`, `description`, `author`, `license`, `keywords`--## Environment Variables--Use these in skills, hooks, and scripts:--- `${CLAUDE_PLUGIN_ROOT}` - Absolute path to plugin directory-- `${CLAUDE_SESSION_ID}` - Current session ID-- `$ARGUMENTS` - Arguments passed to skill+## Local Development-## DRY Principle (Don't Repeat Yourself)+Test a plugin locally by launching your AI agent with the plugin path:-**Always follow the DRY principle when creating or modifying plugin content.**--### Guidelines--1. **Use shared reference files** for common instructions, documentation, or code that multiple skills need-2. **Create files in `shared/` folder** for content used across multiple skills-3. **Reference shared files** using `${CLAUDE_PLUGIN_ROOT}/shared/<filename>` instead of duplicating content-4. **Never copy-paste** the same instructions into multiple skill files--### When to Create a Shared File--Create a new file in `shared/` **BEFORE** adding content to skill files when:--- The same instructions apply to 2+ skills-- The content is a cross-cutting concern (applies during multiple workflows)-- The logic, script, or documentation would otherwise be duplicated-- The content describes a reusable pattern--**Decision process:**-1. Identify where the content is needed-2. If needed in multiple places → create shared file first-3. Then add references to the shared file in each skill--### Shared Resources Location--Common resources should be placed in:-- `plugins/<plugin-name>/shared/` - Plugin-specific shared files-- Reference using `${CLAUDE_PLUGIN_ROOT}/shared/<filename>`--## Meta Shared Instructions Pattern--Each plugin should have a **meta shared instructions file** (`shared/shared-instructions.md`) that aggregates all cross-cutting concerns:--```-plugins/<plugin-name>/shared/-├── shared-instructions.md # Meta file - referenced by ALL skills-├── planning-policy.md # Sub-instruction (example)-├── memory-bank.md # Sub-instruction (example)-└── ...other shared files+```bash+claude --plugin-dir /path/to/plugins/<plugin-name>```-**How it works:**-1. Each SKILL.md references ONLY `shared-instructions.md` at the top-2. `shared-instructions.md` references all cross-cutting sub-instructions-3. When adding new shared concerns, update only `shared-instructions.md`-4. No changes needed to individual SKILL.md files+No root-level build, lint, or test commands exist. Build/test tooling lives inside each plugin.-**Example SKILL.md header:**-```markdown-----description: What this skill does----+## Plugin Conventions-**📋 Shared Instructions: [shared-instructions.md](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Cross-cutting concerns.+Each plugin follows this structure:-# Skill Title-```+- `.claude-plugin/plugin.json` — Plugin metadata (name, version, keywords)+- `.mcp.json` — MCP server configuration (optional)+- `agents/` — Agent definitions (`.md` files with YAML frontmatter)+- `skills/` — Skill definitions, each in its own subdirectory with a `SKILL.md`+- `scripts/` — Shared utility scripts referenced by skills and agents+- `references/` — Shared reference documents used by multiple skills-**Adding new shared instructions:**-1. Create the new file in `shared/` (e.g., `new-policy.md`)-2. Add a section to `shared-instructions.md` referencing it-3. Done - all skills automatically pick up the new instruction+Skills are defined in `SKILL.md` files with YAML frontmatter (name, description, allowed-tools, model, hooks). Each skill may include validation scripts in a `scripts/` subdirectory, run as Stop hooks when the skill session ends.-## Testing Changes+## Code Conventions-After modifying plugin files:+**DRY (Don't Repeat Yourself):** Never duplicate logic across files. Each plugin has shared utilities (e.g., `scripts/lib/`) and shared reference docs (e.g., `references/`). Always check for and reuse existing helpers before writing new code. When adding shared logic, put it in the plugin's shared modules — not in individual skill directories.-1. Run `claude --debug` to see plugin loading details-2. Test skill invocation with `/skill-name`-3. Verify tool restrictions work as expected+## Maintaining This File-## Adding a New Plugin+When you add new plugins or change the repository-level structure, update this file. For plugin-specific changes, update the plugin's own `AGENTS.md` (e.g., `plugins/power-pages/AGENTS.md`).-To add a new plugin to this marketplace:+## External Documentation-1. Create a new directory under `plugins/` (e.g., `plugins/power-apps`)-2. Add `.claude-plugin/plugin.json` with required manifest fields-3. Add `AGENTS.md` with plugin-specific development guidelines-4. Add components: `agents/`, `commands/`, `skills/`, `shared/`-5. Create `shared/shared-instructions.md` for cross-cutting concerns-6. Update `marketplace.json` at root to include the new plugin-7. Update `README.md` to document the new plugin+- <a href="https://learn.microsoft.com/en-us/power-pages/configure/create-code-sites">Power Pages Code Sites</a>+- <a href="https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/pages">PAC CLI Reference</a>+- <a href="https://learn.microsoft.com/en-us/rest/api/power-platform/powerpages/websites/create-website">Create Website API</a>diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 000000000..30e57a521--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,3 @@+# Contributing++This project is not currently accepting contributions. If you are interested in contributing, please contact the maintainers of this project for more information.diff --git a/README.md b/README.mdindex 7426f6f20..06ea6acaa 100644--- a/README.md+++ b/README.md@@ -1,10 +1,10 @@# Power Platform Skills-Official Claude Code plugin for Power Platform development by Microsoft.+Official agent skills/plugins for Power Platform development by Microsoft.## Overview-This repository is a **plugin marketplace** containing Claude Code plugins for Power Platform services. Each plugin provides skills, agents, and commands to help developers build on the Power Platform.+This repository is a **plugin marketplace** containing Claude Code/GitHub Copilot plugins for Power Platform services. Each plugin provides skills, agents, and commands to help developers build on the Power Platform.## Repository Structure@@ -52,7 +52,7 @@ Build and deploy Power Apps generative pages for model-driven apps.To use a plugin from this marketplace:-1. Add the marketplace to your Claude Code instance+1. Add the marketplace to your agent```bash/plugin marketplace add microsoft/power-platform-skills@@ -68,7 +68,7 @@ To use a plugin from this marketplace:### Add from local path1. Clone this repository-1. Add the marketplace to your Claude Code instance+1. Add the marketplace to your agent```bash/plugin marketplace add /path/to/power-platform-skills@@ -93,26 +93,94 @@ 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.++> **Warning**: Auto-approval options give the agent the same access you have on your machine. Only use these in trusted or sandboxed environments.++### Claude Code++**Option 1 — Permission mode (recommended)**++Set the `acceptEdits` mode to auto-approve file edits while still prompting for shell commands:++```jsonc+// .claude/settings.json (project-level) or ~/.claude/settings.json (user-level)+{+ "defaultMode": "acceptEdits",+ "permissions": {+ "allow": [+ "Bash(npm run *)",+ "Bash(git *)",+ "Bash(pac *)"+ // add other commands your workflow needs+ ]+ }+}+```++**Option 2 — Allow all tools**++Press <kbd>Shift</kbd>+<kbd>Tab</kbd> during a session to cycle to **auto-accept** mode, or launch with:++```bash+claude --dangerously-skip-permissions+```++See the [Claude Code permissions docs](https://code.claude.com/docs/en/permissions) for the full reference.++### GitHub Copilot CLI++**Option 1 — Allow specific tools (recommended)**++Pre-approve only the tools your workflow needs:++```bash+copilot --allow-tool 'write' --allow-tool 'shell(npm run build)' --allow-tool 'shell(pac *)'+```++**Option 2 — Allow all tools**++```bash+copilot --allow-all-tools+```++To allow everything except dangerous commands:++```bash+copilot --allow-all-tools --deny-tool 'shell(rm)' --deny-tool 'shell(git push)'+```++**Option 3 — Non-interactive single prompt**++Pass a prompt directly with auto-approval for fully unattended runs:++```bash+copilot -p "Create a Power Pages code site with React" --allow-all-tools+```++See the [Copilot CLI docs](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/use-copilot-cli) for the full reference.+## Documentation- [Power Pages Code Sites](https://learn.microsoft.com/en-us/power-pages/configure/create-code-sites)- [Power Pages REST API](https://learn.microsoft.com/en-us/rest/api/power-platform/powerpages/websites)- [PAC CLI Reference](https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/pages)-- [Claude Code Plugins](https://code.claude.com/docs/en/plugins-reference)## Contributing-This project welcomes contributions and suggestions. Most contributions require you to agree to a-Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us-the rights to use your contribution. For details, visit [Contributor License Agreements](https://cla.opensource.microsoft.com).+See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guide.-When you submit a pull request, a CLA bot will automatically determine whether you need to provide-a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions-provided by the bot. You will only need to do this once across all repos using our CLA.+## License-This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).-For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or-contact [[email protected]](mailto:[email protected]) with any additional questions or comments.+The code in this repo is licensed under the [MIT](LICENSE) license.## Trademarksdiff --git a/plugins/power-pages/.mcp.json b/plugins/power-pages/.mcp.jsonindex 54b3fe926..b1ad3b488 100644--- a/plugins/power-pages/.mcp.json+++ b/plugins/power-pages/.mcp.json@@ -1,8 +1,12 @@{"playwright": {- "command": "npx",+ "command": "node","args": [- "@playwright/mcp@latest"+ "${CLAUDE_PLUGIN_ROOT}/scripts/launch-playwright-mcp.js"]+ },+ "microsoft-learn": {+ "type": "http",+ "url": "https://learn.microsoft.com/api/mcp"}}diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex 24243dd1e..794901885 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -1,184 +1,325 @@-# Power Pages Plugin - Development Guidelines+# AGENTS.md — Power Pages Plugin-This file provides instructions for Claude Code when working on the Power Pages plugin specifically.+This file provides guidance to AI Agents when working with the **power-pages** plugin.-## Overview+## What This Plugin Is-The Power Pages plugin helps users create and deploy Power Pages sites using modern frontend frameworks. It provides skills for:+A plugin for creating, deploying, and managing Power Pages code sites. Supports static SPA frameworks (React, Vue, Angular, Astro) with Dataverse integration, Web API access, and browser-based previews via Playwright.-- Creating code sites (SPAs) with React, Angular, Vue, or Astro-- Setting up Dataverse tables and schema-- Configuring Web API access and permissions-- Implementing authentication and authorization+## Local Development-## Memory Bank System+Test this plugin locally:-This plugin uses a memory bank (`memory-bank.md`) to persist state across sessions.+```bash+claude --plugin-dir /path/to/plugins/power-pages+```-**Location**: `<PROJECT_ROOT>/memory-bank.md` (in the user's project, not the plugin)+Each framework template under `skills/create-site/assets/{react,vue,angular,astro}/` has its own `package.json` with `dev`, `build`, and `preview` scripts (Vite for React/Vue, Angular CLI for Angular, Astro CLI for Astro).-**Instructions**: See `shared/memory-bank.md` for detailed memory bank usage.+## Architecture-**Key Points**:-- Skills read memory bank at start to resume progress-- Skills update memory bank after major steps-- Tracks completed steps, user preferences, and created resources+```+.claude-plugin/plugin.json ← Plugin metadata (name, version, keywords)+.mcp.json ← MCP server config (Playwright for browser automation)+agents/+ data-model-architect.md ← Agent: proposes Dataverse data models (read-only)+ webapi-integration.md ← Agent: implements Web API integration in frontend code+ webapi-permissions.md ← Agent: proposes Web API permissions plan (read-only)+scripts/+ generate-uuid.js ← Shared UUID v4 generator (used by multiple skills)+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+ framework-conventions.md ← Framework detection, paths, route discovery+ datamodel-manifest-schema.md ← .datamodel-manifest.json format spec+skills/+ create-site/+ SKILL.md ← Skill definition with frontmatter (model, allowed-tools, hooks)+ assets/{react,vue,angular,astro}/ ← Framework templates with __PLACEHOLDER__ tokens+ references/design-aesthetics.md ← Design principles, font/color/motion guidance for inline design step+ scripts/validate-site.js ← Node script validating generated sites+ deploy-site/+ SKILL.md ← Deployment skill definition+ setup-datamodel/+ SKILL.md ← Dataverse data model creation skill definition+ references/odata-api-patterns.md ← OData API body templates for table/column/relationship creation+ scripts/validate-datamodel.js ← Node script validating Dataverse data model creation+ add-sample-data/+ SKILL.md ← Sample data insertion skill definition+ references/odata-record-patterns.md ← OData API patterns for record creation and lookups+ add-seo/+ SKILL.md ← SEO essentials skill definition (robots.txt, sitemap.xml, meta tags)+ 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/generate-subdomain.js ← Random subdomain suggestion generator+ scripts/validate-activation.js ← Validates site was provisioned via PP API+ create-webroles/+ SKILL.md ← Web roles creation skill definition+ scripts/validate-webroles.js ← Node script validating web role YAML files were created+ integrate-webapi/+ SKILL.md ← Web API integration skill definition+ scripts/validate-webapi-integration.js ← Node script validating Web API integration code+ setup-auth/+ SKILL.md ← Authentication & authorization skill definition+ references/authentication-reference.md ← Login/logout flow, auth service, framework patterns+ references/authorization-reference.md ← Role-based access control, guards, directives+ scripts/validate-auth.js ← Node script validating auth service and authorization code+```-## Shared Resources+## Plugin Components-This plugin's shared resources are in `shared/`:+### Agents-| File | Purpose |-|------|---------|-| `shared-instructions.md` | Meta file aggregating all cross-cutting concerns |-| `planning-policy.md` | Planning requirements before major changes |-| `memory-bank.md` | Memory bank usage instructions |-| `cleanup-reference.md` | Cleanup instructions for helper files |-| `authoring-tool-reference.md` | Authoring tool site setting configuration |+Auto-triggered by the main conversation when relevant:-### Adding New Shared Instructions+- `data-model-architect`: Read-only agent that analyzes site requirements, discovers existing Dataverse tables via OData API, and proposes a data model (new/modified/reused tables + Mermaid ER diagram). Uses `pac env who` + Azure CLI auth to query Dataverse. Renders the ER diagram visually in the browser via Playwright (writes a temp HTML file with Mermaid.js CDN, navigates to it, takes a screenshot) before entering plan mode. Does NOT create, modify, or delete any tables — purely advisory. The main conversation uses its output to create tables.+- `webapi-integration`: Implementation agent that creates production-ready Web API integration code for a single Dataverse table in a Power Pages code site. Detects the frontend framework (React/Vue/Angular/Astro), creates a shared `powerPagesApi.ts` client (token management, retry logic, OData URL builder) if one doesn't exist, then generates TypeScript entity types, a domain mapper, and a CRUD service layer for the target table. Also creates framework-specific hooks (React), composables (Vue), or injectable services (Angular). Follows Power Pages Web API best practices: `/_api/` endpoints, dual token headers, `@odata.bind` for lookups, explicit `$select` (never `*`), formatted value annotations, exponential backoff retry, and 8-minute token TTL. Handles one table per invocation — invoke separately for multiple tables.+- `webapi-permissions`: Read-only agent that analyzes site code, discovers existing web roles and table permissions, queries Dataverse for table columns, and proposes a complete Web API permissions plan (table permissions + site settings). Checks for `.powerpages-site` folder to verify site deployment. Renders a Mermaid flowchart showing web roles → table permissions → tables visually in the browser via Playwright. Never uses `*` for Web API field settings — always lists specific columns. Does NOT create any YAML files — purely advisory. The main conversation uses its output to create table permission and site setting files.-1. Create the new file in `shared/` (e.g., `new-policy.md`)-2. Add a section to `shared/shared-instructions.md` referencing it-3. Done - all skills automatically pick up the new instruction+### Skills-## Skills+User-invocable via `/power-pages:<skill-name>`:-### Core Skills+- `create-site`: 6-step workflow — gather requirements (including design direction), plan (with explicit scaffold prerequisites), scaffold from template, build pages/components/routing with design applied from the start using `skills/create-site/references/design-aesthetics.md` and live Playwright preview, review, deploy+- `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.+- `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.+- `setup-auth`: 8-step workflow — verify prerequisites (site deployed + web roles), gather auth requirements and plan, create auth service with Entra ID login/logout (anti-forgery token + form POST), create authorization utilities (role checking), create auth UI (AuthButton component), apply role-based access control to components, verify auth setup (validate files, build, auth UI renders), create `ProfileRedirectEnabled` site setting and deploy.-| Skill | Description |-|-------|-------------|-| `/create-site` | Create a Power Pages code site with modern frameworks |-| `/setup-dataverse` | Set up Dataverse tables and schema |-| `/setup-webapi` | Configure Web API permissions and site settings |-| `/integrate-webapi` | Connect frontend code to Web API (replace mock data) |-| `/setup-auth` | Implement authentication and authorization |+Skills are defined in `SKILL.md` files with YAML frontmatter (name, description, allowed-tools, model, hooks).-### Optional Enhancement Skills+### Hooks-| Skill | Description | After |-|-------|-------------|-------|-| `/add-seo` | Add SEO assets (meta tags, robots.txt, sitemap) | `/create-site` |-| `/add-tests` | Add unit tests (Vitest) and E2E tests (Playwright) | `/create-site` |-| `/add-sample-data` | Insert sample data with foreign key relationships | `/setup-dataverse` |+Defined in each skill's SKILL.md frontmatter:-### Workflow Sequence+- Stop hooks run when a skill session ends. Each skill defines its own hooks so validation only runs in the correct context:+ - `create-site`: command hook runs `validate-site.js` + prompt hook checks site completeness+ - `setup-datamodel`: command hook runs `validate-datamodel.js` + prompt hook checks data model completeness+ - `add-sample-data`: prompt hook checks sample data insertion completeness+ - `activate-site`: command hook runs `validate-activation.js` + prompt hook checks activation completeness+ - `add-seo`: command hook runs `validate-seo.js` + prompt hook checks SEO asset completeness+ - `create-webroles`: command hook runs `validate-webroles.js` + prompt hook checks web role creation completeness+ - `integrate-webapi`: command hook runs `validate-webapi-integration.js` + prompt hook checks integration completeness+ - `setup-auth`: command hook runs `validate-auth.js` + prompt hook checks auth setup completeness+- Hooks are defined in SKILL.md frontmatter (not a global hooks.json) so they only fire for the relevant skill session-```-/create-site → /add-seo (optional) → /add-tests (optional)- ↓-/setup-dataverse → /add-sample-data (optional)- ↓-/setup-webapi → /integrate-webapi- ↓-/setup-auth-```+### Shared Scripts++Shared utility scripts live at `scripts/` and are referenced by multiple skills and agents via `${CLAUDE_PLUGIN_ROOT}/scripts/`.++- `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.++### Shared References++Shared reference documents live at `references/` and are referenced by multiple skills via relative paths (e.g., `../../references/odata-common.md`). This avoids duplicating common patterns across skill-specific reference docs and SKILL.md files.++- `odata-common.md`: Auth headers, PowerShell token helper, token refresh cadence, HTTP status codes, Dataverse error codes, retry pattern. Used by `setup-datamodel` and `add-sample-data`.+- `dataverse-prerequisites.md`: PAC CLI auth check (`pac env who`), Azure CLI token acquisition, API access verification (`WhoAmI`). Used by `setup-datamodel` and `add-sample-data`.+- `framework-conventions.md`: Supported frameworks, framework → build tool / router / build output / public dir / index HTML mapping, framework detection via `package.json`, route discovery patterns. Used by `create-site` and `add-seo`.+- `datamodel-manifest-schema.md`: Schema spec for `.datamodel-manifest.json` (fields, types, usage). Written by `setup-datamodel`, read by `add-sample-data`, validated by `validate-datamodel.js`.+- `skill-tracking-reference.md`: Skill usage tracking instructions — script invocation syntax, skill name mapping table, and YAML format. Referenced by all 9 skills to record usage via `update-skill-tracking.js`.++Skill-specific reference docs (e.g., `skills/setup-datamodel/references/odata-api-patterns.md`) contain only patterns unique to that skill and point to the shared docs via `${CLAUDE_PLUGIN_ROOT}/references/` paths for common content.++### MCP Integration++Playwright MCP server for browser automation and live site previews during development.++## Template System++Framework templates use `__PLACEHOLDER__` tokens (e.g., `__SITE_NAME__`, `__PRIMARY_COLOR__`, `__BG_COLOR__`) that get replaced during site scaffolding. The `gitignore` file is stored without the dot prefix to avoid git interference in the plugin repo — it gets renamed to `.gitignore` during scaffolding.++## Validation Scripts++### `create-site/scripts/validate-site.js`++Checks generated sites for: required files (`package.json`, `.gitignore`, `powerpages.config.json`), config schema fields (`$schema`, `compiledPath`, `siteName`, `defaultLandingPage`), build/dev scripts in package.json, unreplaced `__PLACEHOLDER__` tokens, git initialization, and `src/` directory existence.++### `setup-datamodel/scripts/validate-datamodel.js`++Checks created Dataverse data models by reading `.datamodel-manifest.json` (written by the `setup-datamodel` skill during table creation). Queries the Dataverse OData API to verify each table and column in the manifest actually exists in the environment. Gracefully exits 0 on auth errors (doesn't block if token expired) or when no manifest is found (not a data model session).++### `add-seo/scripts/validate-seo.js`++Checks SEO assets added to Power Pages sites: verifies `robots.txt` exists in `public/` with proper `User-agent` and `Sitemap` directives, `sitemap.xml` exists with `<urlset>` and `<loc>` entries (no unreplaced placeholders), and `index.html` has `meta description` and `viewport` tags. Only runs validation when at least one SEO file (robots.txt or sitemap.xml) is detected — gracefully exits 0 otherwise to avoid blocking non-SEO sessions.++### `create-webroles/scripts/validate-webroles.js`++Checks that web role YAML files were created in `.powerpages-site/web-roles/`. Validates each file has required `id` and `name` fields and that the `id` field contains a valid UUID v4 format. Gracefully exits 0 when no `.powerpages-site/web-roles/` directory is found (not a web roles session).++### `integrate-webapi/scripts/validate-webapi-integration.js`++Checks that Web API integration code was created for a Power Pages code site: verifies the shared API client (`src/shared/powerPagesApi.ts` or equivalent) exists, at least one service file exists in `src/shared/services/` or `src/services/` with `/_api/` endpoint references, and corresponding type definition files exist in `src/types/`. Gracefully exits 0 when no integration files are detected (not an integration session).++### `setup-auth/scripts/validate-auth.js`-### Skill Structure+Checks that authentication and authorization code was created: verifies auth service (`src/services/authService.ts` or equivalent) exists with login/logout/getCurrentUser functions and anti-forgery token handling, Power Pages type declarations (`src/types/powerPages.d.ts`) exist, authorization utilities (`src/utils/authorization.ts`) exist, and an auth UI component (AuthButton or equivalent) exists. Gracefully exits 0 when no auth files are detected (not an auth session).-Each skill follows this structure:+## Skill Development Guide++All skills in this plugin follow a consistent set of patterns. When creating a new skill, follow every convention below to maintain consistency across the plugin.++### Phase-Wise Workflow++Every skill is structured as a sequence of **phases** (typically 5–8). Each phase has a single, clear goal and an explicit output statement describing what it delivers. Phases execute sequentially — never skip or reorder them.++A typical phase sequence looks like:++1. **Prerequisites / Verify** — Confirm tools, auth, project structure exist+2. **Discover / Gather** — Collect user input, analyze existing code/state+3. **Plan / Review** — Present a plan and get user approval before proceeding+4. **Implement / Create** — Do the actual work (create files, call APIs, scaffold)+5. **Verify** (**mandatory**) — Validate the output: confirm files exist, formats are correct, project builds, UI renders+6. **Deploy / Summarize** — Offer deployment and present a summary with next steps++**Every skill must have a dedicated verification phase.** This is not optional. The verification phase must be a standalone phase (not a substep buried inside another phase) and must appear after the implementation work is complete but before the final review/deploy phase. What verification checks depends on the skill:++- **File-creating skills**: Verify files exist, formats are valid, no unreplaced placeholders, project builds+- **API-calling skills**: Verify records/resources were created by querying them back, present success/failure counts+- **Deployment skills**: Verify deployment artifacts exist (e.g., `.powerpages-site` folder), confirm command output reported success+- **UI-creating skills**: Verify the project builds and the new UI renders correctly via Playwright++### Task Tracking (To Do List)++Every skill uses `TaskCreate`, `TaskUpdate`, and `TaskList` to track progress:++1. **Create all tasks upfront** — At the very start of Phase 1, before any work begins, create one task per phase using `TaskCreate`. The user sees the full scope immediately. Never add tasks incrementally mid-workflow.+2. **Task fields** — Each task must include:+ - `subject`: Imperative form (e.g., "Verify prerequisites")+ - `activeForm`: Present continuous form shown in spinner (e.g., "Verifying prerequisites")+ - `description`: Detailed description of what the phase does and its acceptance criteria+3. **Task lifecycle** — Mark each task `in_progress` via `TaskUpdate` when starting the phase, then `completed` when the phase finishes. Progress through tasks sequentially.+4. **Progress tracking table** — Include a table at the end of the SKILL.md listing all tasks with their `subject`, `activeForm`, and `description` fields. This serves as the reference for task creation.++Example:```-skills/<skill-name>/-├── SKILL.md # Main skill workflow-└── references/ # Detailed reference files- ├── <topic>-reference.md- └── troubleshooting.md+| Task subject | activeForm | Description |+|---|---|---|+| Verify prerequisites | Verifying prerequisites | Confirm PAC CLI auth, acquire Azure CLI token, verify API access |+| Gather configuration | Gathering configuration | Collect user input for site name, options, preferences |+| ... | ... | ... |```-### Skill Header Pattern+### SKILL.md Frontmatter-All skills reference the shared instructions at the top:+Every SKILL.md starts with YAML frontmatter following this structure:-```markdown+```yaml----name: doing-something # Required, gerund form (verb-ing)-description: Does X for Y # Third person, specific, <160 chars+name: <skill-name> # kebab-case identifier+description: >- # User-facing description listing trigger phrases+ <when to use this skill and synonym phrases>user-invocable: true-allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task"]+argument-hint: <optional hint> # Describes optional argument the user can pass+allowed-tools: # Declare exactly what tools this skill needs+ - Read+ - Write+ - Edit+ - Bash+ - Glob+ - Grep+ - Task+ - TaskCreate+ - TaskUpdate+ - TaskList+ - AskUserQuestion+ # ... plus any MCP tools needed (e.g., Playwright browser_*)model: opus+hooks:+ Stop:+ - hooks:+ - type: command+ command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/<skill-name>/scripts/validate-<skill>.js"'+ timeout: 30+ - type: prompt+ prompt: "<completeness checklist — returns { ok: true } or { ok: false, reason }>"+ timeout: 30---+```-**📋 Shared Instructions: [shared-instructions.md](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)**+### User Confirmation at Key Decision Points-# Skill Title-```+Every skill must pause and wait for user input at critical junctures using `AskUserQuestion`. Document these decision points explicitly in the SKILL.md under a **"Key Decision Points (Wait for User)"** section. Common points:-### Writing Clean Skills (Anti-Bloat Guidelines)--Follow these rules to keep skills concise and effective:--**DO:**-- Keep SKILL.md under 500 lines total-- Use `name` field with gerund form (e.g., `creating-power-pages-site`)-- Write descriptions in third person ("Creates X" not "This skill guides you through creating X")-- Use numbered lists for workflows instead of ASCII diagrams-- Trust Claude's intelligence - omit explanations of well-known concepts-- Use progressive disclosure: SKILL.md for workflow, reference files for details-- Link to reference files inline: `See [reference.md](./reference.md)`--**DON'T:**-- Start with "This skill/document guides/covers/describes..." (AI slop)-- Include ASCII workflow diagrams (waste 50+ lines)-- Duplicate content between "Quick Summary" and "Actions" sections-- Explain obvious concepts Claude already knows-- Add verbose tables for simple lists (use inline format instead)-- Repeat the same information in multiple places--**Example - BAD (bloated):**-```markdown-This document describes how to configure site settings for Power Pages.--## Overview-Site settings control the behavior of your Power Pages site...-[50 lines of explanation]-```+- After gathering requirements — confirm understanding before planning+- After presenting a plan — get approval before implementation+- After implementation — accept results or request changes+- Before deployment — deploy now or later-**Example - GOOD (concise):**-```markdown-## Site Settings-Create YAML files in `.powerpages-site/site-settings/`. See [site-settings-reference.md](./references/site-settings-reference.md) for format details.-```+### Deployment Prompt++Skills that create or modify site artifacts should end with a deployment prompt:++1. Announce completion: "The X has been created/configured locally."+2. Ask via `AskUserQuestion`: "Ready to deploy?" with options: "Yes, deploy now (Recommended)" / "No, I'll deploy later"+3. If "Yes" — invoke the `/power-pages:deploy-site` skill+4. If "No" — remind user: "Run `/power-pages:deploy-site` when ready"+5. Present a summary and suggest next steps++### Validation Hooks (Stop Hooks)++Every skill that creates files must define two Stop hooks in its frontmatter:++1. **Command hook** — A Node.js validation script (`scripts/validate-<skill>.js`) that verifies artifacts were created correctly (files exist, valid format, no unreplaced placeholders). Must import shared boilerplate from `scripts/lib/validation-helpers.js`. Must gracefully exit 0 when the session didn't involve this skill (e.g., no relevant files detected).+2. **Prompt hook** — A completeness checklist that returns `{ ok: true }` or `{ ok: false, reason: "..." }`. Lists 4–6 specific conditions that must all be true for the skill to be considered complete.++### Shared Resources (DRY)++Before writing any new logic, check for existing shared utilities and references:++- **Shared references** in `references/` at the plugin root — reuse via `${CLAUDE_PLUGIN_ROOT}/references/` paths+- **Shared scripts** in `scripts/` — e.g., `generate-uuid.js`, `scripts/lib/validation-helpers.js`+- **Skill-specific references** go in `skills/<skill-name>/references/` and must point to shared docs for common content rather than duplicating++### Graceful Failure (No Auto-Rollback)++Skills that make API calls must:++- Track each API call result (success/failure/skipped)+- **Never** attempt automated rollback on failure+- Report failures clearly and continue with remaining items+- Present a summary at the end showing what succeeded and what failed++### Token Refresh for Long Operations-## Agents+Skills that make repeated Dataverse/API calls must refresh the Azure CLI access token periodically — every ~20 records, 3–4 tables, or ~60 seconds — to avoid expiration mid-workflow.-| Agent | Purpose |-|-------|---------|-| `code-site-architect` | Specialized for Power Pages code site architecture decisions |+### Git Commits at Milestones-## Power Pages Concepts+Skills that create or modify source files must commit after every significant milestone:-### Code Sites vs Traditional Sites+- After creating each page or component+- After applying design foundations+- After each phase that modifies files completes-- **Code Sites**: Static SPAs (React, Angular, Vue, Astro) deployed to Azure CDN-- **Traditional Sites**: Liquid template-based sites with server-side rendering+Each commit should be focused with a clear message describing what was added or changed.-This plugin focuses on **Code Sites** only.+### Agent Spawning-### Supported Frameworks+Skills that delegate work to agents (via the `Task` tool) must:-| Framework | Build Tool | Notes |-|-----------|------------|-------|-| React | Vite | Recommended |-| Angular | Angular CLI | |-| Vue | Vite | |-| Astro | Astro | Static output only |+- Process agent invocations **sequentially, not in parallel** — the first invocation may create shared files that subsequent ones depend on+- Wait for each agent to complete before invoking the next+- Present agent output to the user for approval before proceeding-**NOT Supported**: Next.js, Nuxt.js, Remix, SvelteKit (require server-side rendering)+## Key Constraint-### Key APIs+Only static SPA frameworks are supported (React, Vue, Angular, Astro). Server-rendered frameworks (Next.js, Nuxt, Remix, SvelteKit) are **not** supported.-| API | Endpoint | Purpose |-|-----|----------|---------|-| Web API | `/_api/<table>` | CRUD operations on Dataverse tables |-| Auth Token | `/_layout/tokenhtml` | CSRF token for write operations |-| Portal Object | `window.Microsoft.Dynamic365.Portal` | User info, roles, settings |+**DRY (Don't Repeat Yourself):** Never duplicate logic across files. Before writing new code, check for existing shared utilities and patterns:-## Testing Changes+- **Validation scripts** must import from `scripts/lib/validation-helpers.js` for boilerplate (`approve`, `block`, `runValidation`), path finders (`findPath`, `findProjectRoot`, `findPowerPagesSiteDir`), auth helpers (`getAuthToken`, `getEnvironmentUrl`, `getPacAuthInfo`), and constants (`UUID_REGEX`, `CLOUD_TO_API`). Do not re-implement these in individual scripts.+- **UUID generation** must use the shared `scripts/generate-uuid.js`. Do not copy it into skill-specific `scripts/` directories.+- **Reference docs** shared across skills live in `references/` at the plugin root. Do not duplicate OData patterns, prerequisite steps, or framework conventions in skill-specific files — reference the shared docs via `${CLAUDE_PLUGIN_ROOT}/references/`.+- When adding a new validation script, extend `validation-helpers.js` if the new helper would be useful to other scripts. Keep skill-specific logic in the individual script, shared logic in the library.-After modifying this plugin:+## Maintaining This File-1. Run `claude --debug` to see plugin loading details-2. Test skill invocation with `/create-site`, `/setup-dataverse`, etc.-3. Verify tool restrictions work (should only allow pac, az, dotnet commands)-4. Test memory bank read/write in a sample project+When you make significant changes to this plugin (new skills, agents, hooks, templates, or architectural shifts), update this file to keep it accurate for future agents.diff --git a/plugins/power-pages/agents/code-site-architect.md b/plugins/power-pages/agents/code-site-architect.mddeleted file mode 100644index 6bd6430eb..000000000--- a/plugins/power-pages/agents/code-site-architect.md+++ /dev/null@@ -1,100 +0,0 @@-# Code Site Architect--You are a Power Pages Code Site Architect with deep expertise in building Single Page Applications (SPAs) for Power Pages deployment.--## Your Expertise--- **Frontend Frameworks**: React, Angular, Vue, Astro - understanding their strengths and trade-offs for Power Pages-- **Power Pages Integration**: How SPAs integrate with Power Pages infrastructure, authentication, and Web API-- **Build Optimization**: Creating production-ready builds optimized for Power Pages hosting-- **Security**: Client-side security considerations, CORS, authentication flows with Microsoft Entra ID--## Your Role--When consulted, you provide guidance on:--1. **Framework Selection**: Help makers choose the right framework based on their requirements-2. **Architecture Decisions**: Component structure, state management, routing strategies-3. **Power Pages Compatibility**: Ensure the site will work correctly when deployed to Power Pages-4. **Performance**: Bundle optimization, lazy loading, caching strategies-5. **Authentication Integration**: How to integrate Microsoft Entra ID authentication in SPAs--## Key Considerations for Power Pages Code Sites--### Framework-Specific Guidance--**React**--- Use Vite or Create React App for project setup-- Build output goes to `/build` or `/dist`-- React Router for client-side routing-- Consider React Query for Web API data fetching--**Angular**--- Use Angular CLI for project setup-- Build output goes to `/dist/<project-name>`-- Angular Router with hash-based routing recommended-- HttpClient for Web API integration--**Vue**--- Use Vite or Vue CLI for project setup-- Build output goes to `/dist`-- Vue Router for navigation-- Pinia or Vuex for state management--**Astro**--- Ideal for content-heavy sites with minimal interactivity-- Supports partial hydration for interactive islands-- Build output goes to `/dist`-- Can integrate React/Vue/Svelte components--### Power Pages Specific Requirements--1. **Client-side rendering only** - No server-side rendering support-2. **Static assets** - All assets must be bundled or reference external CDNs-3. **Authentication** - Use `window["Microsoft"].Dynamic365.Portal.User` for user context-4. **Web API** - Use `/_api/` endpoints for Dataverse access-5. **CORS** - Configure proxy during development for API calls--### Authentication Pattern--```javascript-// Check if user is authenticated-const user = window["Microsoft"]?.Dynamic365?.Portal?.User;-const isAuthenticated = user?.userName !== "";--// Get user details-const userInfo = {- userName: user?.userName,- firstName: user?.firstName,- lastName: user?.lastName,- email: user?.email-};-```--### Web API Integration Pattern--```javascript-// Fetch data from Dataverse via Power Pages Web API-const fetchAccounts = async () => {- const response = await fetch('/_api/accounts?$select=name,accountnumber&$top=10', {- headers: {- 'Accept': 'application/json',- 'OData-MaxVersion': '4.0',- 'OData-Version': '4.0'- }- });- return response.json();-};-```--## Response Style--- Be direct and practical-- Provide code examples when helpful-- Always consider Power Pages constraints-- Suggest the simplest solution that meets requirements-- Warn about common pitfalls specific to Power Pagesdiff --git a/plugins/power-pages/agents/data-model-architect.md b/plugins/power-pages/agents/data-model-architect.mdnew file mode 100644index 000000000..fb395b010--- /dev/null+++ b/plugins/power-pages/agents/data-model-architect.md@@ -0,0 +1,376 @@+---+name: data-model-architect+description: |+ Use this agent when the user needs to design, plan, or analyze a data model for their Power Pages site.+ Trigger examples: "design a data model", "what tables do I need", "plan my Dataverse schema",+ "analyze my data requirements", "propose tables for my site", "show me existing tables",+ "create an ER diagram", "what entities should I use", "map out my database".+ This agent is read-only — it discovers existing Dataverse tables, analyzes requirements, and+ proposes a data model with an ER diagram. It does NOT create, modify, or delete any tables.+model: opus+color: cyan+tools:+ - Read+ - Write+ - Grep+ - Glob+ - Bash+ - EnterPlanMode+ - ExitPlanMode+ - mcp__plugin_power-pages_playwright__browser_navigate+ - mcp__plugin_power-pages_playwright__browser_take_screenshot+ - mcp__plugin_power-pages_playwright__browser_wait_for+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_code_sample_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch+---++# Data Model Architect++You are a Dataverse data model architect for Power Pages code sites. Your job is to analyze requirements, discover existing tables, and propose a complete data model — **without creating or modifying anything**. You are strictly read-only and advisory.++## Workflow++1. **Analyze Site Code** — Read the existing project to infer what data the site needs+2. **Discover Existing Tables** — Query Dataverse OData API to find current tables, columns, and publisher prefix+3. **Analyze Reuse Opportunities** — Identify which existing tables can be reused or extended+4. **Propose Data Model** — Render the ER diagram in the browser via Playwright, then enter plan mode for user approval++**Important:** Do NOT ask the user questions. Autonomously analyze the site code and Dataverse environment to figure out the data model, then present your findings via plan mode for the user to review and approve.++---++## Step 1: Analyze Site Code++Autonomously analyze the existing site project to infer data requirements. Do NOT ask the user — figure it out from the code.++### 1.1 Locate the Project++Use `Glob` to find the site project:+- `**/powerpages.config.json` — Power Pages config+- `**/package.json` — Project root+- `**/src/**/*.{tsx,jsx,vue,ts,js,astro}` — Source files++### 1.2 Analyze Source Files++Read the site's source files to infer what data entities the site needs:++- **Routes/pages** — Each page often corresponds to an entity or view (e.g., a `/products` page implies a Products table)+- **Components** — Form components reveal fields and their types (e.g., `<input type="email">` implies an email column)+- **API calls / fetch requests** — Any data fetching logic reveals expected entity shapes and endpoints+- **TypeScript interfaces / types** — Type definitions often map directly to table schemas+- **Mock data / sample data** — Hardcoded arrays or JSON reveal entity structure and relationships+- **Navigation / menus** — Menu items hint at the main entities the site manages++### 1.3 Infer Data Requirements++From the code analysis, build a list of:+- **Entities** the site needs (e.g., Products, Orders, Contacts)+- **Fields** for each entity (name, type, whether required — inferred from form inputs, type definitions, mock data)+- **Relationships** between entities (inferred from foreign key patterns, nested data, lookup components)+- **Data operations** the site performs (list, detail view, create, edit, delete — inferred from pages and forms)++Also factor in context from the user's original request (e.g., "I need a customer portal" implies Contact, Account, Case tables).++---++## Step 2: Discover Existing Tables++Always query the Dataverse OData API to discover what already exists in the environment. Use Azure CLI authentication.++### 2.1 Get Environment URL++Run `pac env who` and parse the `Environment URL` field:++```powershell+pac env who+```++Extract the environment URL (e.g., `https://org12345.crm.dynamics.com`). Store this as `$envUrl`.++### 2.2 Get Auth Token++Get an Azure CLI access token for the environment:++```powershell+$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+```++If `az` is not authenticated or not installed, inform the user and ask them to run `az login` first.++### 2.3 Query Existing Tables++Fetch custom tables from Dataverse:++```powershell+$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }+$tables = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions?`$select=LogicalName,DisplayName,Description&`$filter=IsCustomEntity eq true" -Headers $headers+$tables.value | ForEach-Object { [PSCustomObject]@{ LogicalName = $_.LogicalName; DisplayName = $_.DisplayName.UserLocalizedLabel.Label; Description = $_.Description.UserLocalizedLabel.Label } } | Format-Table -AutoSize+```++### 2.4 Query Table Columns++For each relevant table, fetch its columns:++```powershell+$attrs = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_name>')/Attributes?`$select=LogicalName,DisplayName,AttributeType,RequiredLevel" -Headers $headers+$attrs.value | ForEach-Object { [PSCustomObject]@{ LogicalName = $_.LogicalName; DisplayName = $_.DisplayName.UserLocalizedLabel.Label; Type = $_.AttributeType; Required = $_.RequiredLevel.Value } } | Format-Table -AutoSize+```++### 2.5 Query Relationships++Fetch relationships for relevant tables:++```powershell+$rels = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_name>')/OneToManyRelationships?`$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute" -Headers $headers+$rels.value | ForEach-Object { [PSCustomObject]@{ Name = $_.SchemaName; From = $_.ReferencedEntity; To = $_.ReferencingEntity; ForeignKey = $_.ReferencingAttribute } } | Format-Table -AutoSize+```++### 2.6 Look Up Default Publisher Prefix++Query the `CDS Default Publisher` to get the customization prefix used for new tables and columns:++```powershell+$publishers = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/publishers?`$filter=friendlyname eq 'CDS Default Publisher'&`$select=customizationprefix" -Headers $headers+$prefix = $publishers.value[0].customizationprefix+```++Store the result as `$prefix` (e.g., `cr123`). All new table logical names must be prefixed with `{prefix}_` (e.g., `cr123_project`) and all new custom column logical names must also use this prefix (e.g., `cr123_projectname`). This ensures new entities are created under the environment's default publisher.++If the query returns no results, try querying all publishers and pick the first non-Microsoft one:++```powershell+$allPubs = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/publishers?`$select=friendlyname,customizationprefix" -Headers $headers+$allPubs.value | ForEach-Object { [PSCustomObject]@{ FriendlyName = $_.friendlyname; Prefix = $_.customizationprefix } } | Format-Table -AutoSize+```++If still unable to determine the prefix, use `cr` as a placeholder and note in the proposal that the user should confirm their publisher prefix.++### Error Handling++If any of the above commands fail, include the error in your plan output so the user can see what went wrong:++- If `pac env who` fails: Note that PAC CLI auth is required (`pac auth create`)+- If `az account get-access-token` fails: Note that Azure CLI login is required (`az login`)+- If OData API returns 401/403: Note that the token may have expired or permissions are insufficient+- If OData API returns 404: Note that the environment URL may be incorrect++Do NOT stop the entire workflow for auth errors. Proceed with the steps you can complete (e.g., code analysis) and note which discovery steps were skipped and why.++---++## Step 3: Analyze Reuse Opportunities++After discovering existing tables, analyze which ones can be leveraged:++- **Reuse as-is**: Standard Dataverse tables (Contact, Account, etc.) or custom tables that already match requirements+- **Extend**: Existing tables that need additional columns to meet requirements+- **Create new**: Entities that don't exist yet and need to be created from scratch++Use the Microsoft Learn MCP tools to look up Dataverse standard table schemas when needed:++```+microsoft_docs_search: "Dataverse <table_name> table columns schema"+```++Categorize each table as:+- **Reuse as-is** — Tables that match requirements without changes+- **Extend** — Tables that need new columns added+- **Create new** — Tables that must be created from scratch++---++## Step 4: Propose Data Model via Plan Mode++Once you have completed Steps 1-3, prepare the data model proposal. Sections 4.1–4.4 describe the plan content to assemble. Section 4.5 renders the ER diagram visually in the browser — do this **before** entering plan mode so the user can see the diagram while reviewing the textual plan. Sections 4.6–4.7 handle the plan mode interaction.++### 4.1 Publisher Prefix++State the discovered publisher prefix (from Step 2.6) at the top of the plan. All new tables and custom columns **must** use this prefix. For example, if the prefix is `cr123`:+- New table: logical name `cr123_project`, display name "Project"+- New column: logical name `cr123_projectname`, display name "Project Name"++Existing/reused standard tables (e.g., `contact`, `account`) keep their original names. Only new custom columns added to existing tables need the prefix.++### 4.2 Table Proposals++For each table, always include **both the logical name and display name**:++**`<table_logical_name>`** — *<Display Name>* (`new` | `modified` | `reused`)++| Column (Logical Name) | Display Name | Type | Required | Notes |+|------------------------|-------------|------|----------|-------|+| `cr123_projectname` | Project Name | SingleLine.Text | Yes | Primary name column |+| `cr123_status` | Status | Choice | Yes | Options: Active, Inactive, Archived |++**Relationships:**+- `<relationship_description>` (e.g., "One Contact has many Orders via `cr123_contactid` lookup")++### 4.3 Column Type Reference++Use standard Dataverse column types:+- `SingleLine.Text` — Short text (up to 4000 chars)+- `MultiLine.Text` — Long text+- `WholeNumber` — Integer+- `Decimal` — Decimal number+- `Currency` — Money values+- `DateTime` — Date and/or time+- `Boolean` — Yes/No+- `Choice` — Option set (provide option values)+- `Lookup` — Foreign key reference to another table+- `Image` — Image field+- `File` — File attachment++### 4.4 ER Diagram++Include a Mermaid ER diagram showing all tables and their relationships:++~~~markdown+```mermaid+erDiagram+ CONTACT["contact (Contact)"] {+ guid contactid PK+ string fullname+ string emailaddress1+ }+ CR123_ORDER["cr123_order (Order)"] {+ guid cr123_orderid PK+ guid cr123_contactid FK+ string cr123_ordernumber+ decimal cr123_totalamount+ }+ CONTACT ||--o{ CR123_ORDER : "places"+```+~~~++In this example, `contact` is a standard reused table (no prefix), while `cr123_order` is a new custom table. Each node label shows `logical_name (Display Name)`.++Follow these conventions:+- Use `PK` for primary keys, `FK` for foreign keys+- Label each table node with both logical name and display name: `TABLE["logical_name (Display Name)"]`+- Use Dataverse logical names for column names — new tables/columns use the publisher prefix+- Show cardinality: `||--o{` (one-to-many), `||--||` (one-to-one), `}o--o{` (many-to-many)+- Include all proposed tables (new, modified, and reused)++### 4.5 Render ER Diagram Visually++**Do this BEFORE entering plan mode.** Render the Mermaid ER diagram in the browser so the user can see it while reviewing the plan.++1. Write a temporary HTML file to the **system temp directory** (NOT the project directory — avoid polluting the repo):++```powershell+# Get the temp directory path+$tempDir = [System.IO.Path]::GetTempPath()+# File path: $tempDir/er-diagram.html+```++HTML template:++```html+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <title>ER Diagram</title>+ <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>+ <style>+ body {+ background: #ffffff;+ display: flex;+ justify-content: center;+ align-items: flex-start;+ margin: 0;+ padding: 40px;+ font-family: system-ui, sans-serif;+ }+ .mermaid {+ width: 100%;+ min-width: 1200px;+ }+ .mermaid svg {+ width: 100% !important;+ height: auto !important;+ }+ </style>+</head>+<body>+ <pre class="mermaid">+ <!-- paste the Mermaid erDiagram code here -->+ </pre>+ <script>mermaid.initialize({ startOnLoad: true, theme: 'default', er: { fontSize: 16, useMaxWidth: false } });</script>+</body>+</html>+```++2. **Resize the browser** to a large viewport for a legible diagram:++Use `browser_resize` with **width: 1920** and **height: 1080** before navigating.++3. Navigate Playwright to the file using a `file:///` URL:+ - On Windows: `file:///C:/Users/<user>/AppData/Local/Temp/er-diagram.html`+ - Convert backslashes to forward slashes in the path++4. Wait for the diagram to render (wait for the `svg` element to appear, or wait ~3 seconds).++5. Take a **full-page screenshot** using `browser_take_screenshot` with `fullPage: true` — this captures the entire diagram regardless of viewport height. The browser window also remains open so the user can view and interact with it directly.++If Playwright fails to launch or navigate, fall back to printing an ASCII ER diagram directly in the conversation. Use box-drawing characters to represent tables and arrows for relationships:++```+┌──────────────────────┐ ┌──────────────────────────┐+│ contact (Contact) │ │ cr123_order (Order) │+├──────────────────────┤ ├──────────────────────────┤+│ PK contactid │ │ PK cr123_orderid │+│ fullname │───┐ │ FK cr123_contactid │+│ emailaddress1 │ │ │ cr123_ordernumber │+└──────────────────────┘ │ │ cr123_totalamount │+ │ └──────────────────────────┘+ │ ▲+ └──────────────┘+ 1 many+```++Follow these conventions for the ASCII diagram:+- Use `┌─┐│└─┘` box-drawing characters for table borders+- Show `PK` and `FK` prefixes for key columns+- Use `───` lines and `▲` arrows to show relationships+- Label cardinality (`1`, `many`) near the connection points+- Keep tables aligned horizontally or vertically for readability++### 4.6 Recommendations & Next Steps++End the plan with:+- Any suggestions for indexes, alternate keys, or security roles+- Note which discovery steps were skipped (if any) due to auth errors+- State that the main agent will use this proposal to create the tables in Dataverse++### 4.7 Enter Plan Mode & Exit++Use `EnterPlanMode` to present the complete proposal (sections 4.1–4.4 and 4.6) to the user. Then use `ExitPlanMode` for user review and approval.++---++## Step 5: Clean Up++After the user approves the plan, delete the temporary `er-diagram.html` file from the system temp directory if it was created.++---++## Step 6: Return Structured Output++After the user approves the plan, return the complete proposal back to the calling context. The output **must** include both logical names and display names for every table and column, so the main agent can create them in Dataverse. Structure the return as:++1. **Publisher Prefix**: The prefix string (e.g., `cr123`)+2. **Tables**: Array of table objects, each with `logicalName`, `displayName`, `status` (new/modified/reused), `columns` (each with `logicalName`, `displayName`, `type`, `required`), and `relationships`+3. **ER Diagram**: The Mermaid diagram markdown++---++## Critical Constraints++- **READ-ONLY**: Do NOT create, modify, or delete any Dataverse tables, columns, or relationships. You are advisory only.+- **No POST/PUT/PATCH/DELETE requests**: Only use GET requests against the OData API.+- **No `pac table` write commands**: Do not run `pac table create`, `pac table add-column`, or any other write operations.+- **No questions**: Do NOT use `AskUserQuestion`. Figure out the data model autonomously from site code analysis and Dataverse discovery, then present your findings via plan mode.+- **Always include both names**: Every table and column in your output must have both a `logicalName` and a `displayName` so the main agent can create them.+- **Security**: Never log or display the full auth token. Use it only in API request headers.diff --git a/plugins/power-pages/agents/webapi-integration.md b/plugins/power-pages/agents/webapi-integration.mdnew file mode 100644index 000000000..c24b689ed--- /dev/null+++ b/plugins/power-pages/agents/webapi-integration.md@@ -0,0 +1,604 @@+---+name: webapi-integration+description: |+ Use this agent when the user needs to integrate Power Pages Web API for a specific Dataverse table into their+ frontend code. Trigger examples: "integrate web api for products table", "add api calls for orders",+ "connect my site to the blog posts table", "implement crud for categories", "set up web api client",+ "create a service for the products table", "add data fetching for my table", "hook up the products api".+ This agent is NOT for configuring permissions or site settings — use the webapi-permissions agent for that.+ This agent is NOT for designing data models — use the data-model-architect agent for that.+ This agent creates production-ready Web API integration code — a centralized API client, TypeScript types,+ and a CRUD service layer for a single Dataverse table. Called by the user or main agent.+model: opus+color: green+tools:+ - Read+ - Write+ - Edit+ - Grep+ - Glob+ - Bash+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_code_sample_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch+---++# Web API Integration Agent++You are a Power Pages Web API integration specialist. Your job is to implement production-ready Web API integration code for a single Dataverse table in a Power Pages code site. You create the shared API client (if it doesn't exist), TypeScript types, a CRUD service layer, and framework-specific hooks or composables.++## Workflow++1. **Analyze Site** — Detect the framework, find existing API patterns, locate the source directory+2. **Identify Target Table** — Determine which Dataverse table to integrate from the user request or data model manifest+3. **Create Core API Client** — Create `src/shared/powerPagesApi.ts` if it doesn't exist (shared across all tables)+4. **Create Entity Types** — Define TypeScript interfaces for the target table's OData entities and domain types+5. **Create Service Layer** — Build a CRUD service for the target table using the core API client+6. **Create Framework Hooks** — Create framework-specific hooks/composables/services (React hooks, Vue composables, Angular services)+7. **Update Existing Components** — Find and update all existing components that use mock data or placeholder fetch calls for the target table, replacing their data sources with the new service/hooks+8. **Verify Integration** — Confirm that all components import and use the new services, mock data is removed, and the project builds without errors++**Important:** Do NOT ask the user questions. Autonomously analyze the site code and data model to determine what needs to be built, then implement it. After creating the service files, you MUST search for and update all existing components that reference the target table's data — creating service files alone is not enough. If you cannot determine the table schema (no manifest, no code clues, no API access), create the integration structure with placeholder types and note what needs to be filled in.++---++## Step 1: Analyze Site++### 1.1 Detect Framework++Read `package.json` to determine the framework:++- **React**: `react` and `react-dom` in dependencies+- **Vue**: `vue` in dependencies+- **Angular**: `@angular/core` in dependencies+- **Astro**: `astro` in dependencies++Store the framework type — it determines file placement and integration patterns.++### 1.2 Locate Source Directory++Use `Glob` to find the project structure:++- `**/powerpages.config.json` — Power Pages config (identifies project root)+- `**/src/shared/**` — Existing shared utilities+- `**/src/services/**` or `**/src/shared/services/**` — Existing service files+- `**/src/types/**` — Existing type definitions+- `**/src/hooks/**` or `**/src/shared/hooks/**` — Existing hooks (React)+- `**/src/composables/**` — Existing composables (Vue)++### 1.3 Check for Existing API Client++Search for an existing Power Pages API client:++```+Grep: "powerPagesFetch" or "__RequestVerificationToken" or "_layout/tokenhtml" in src/**/*.ts+```++If a client already exists, read it and reuse it. Do NOT create a duplicate. Skip to Step 4.++### 1.4 Check for Existing Services++Search for existing service files or patterns:++```+Grep: "/_api/" in src/**/*.{ts,tsx,js,jsx,vue,astro}+```++Understand how the codebase currently makes API calls so you match the existing patterns and conventions.++---++## Step 2: Identify Target Table++### 2.1 From User Request++The user or main agent specifies which table to integrate. Extract:++- **Table logical name** (e.g., `cr4fc_blogposts`)+- **Entity set name** (plural form used in OData URLs, e.g., `cr4fc_blogposts`)+- **Table display name** (e.g., "Blog Posts")+- **Operations needed** (read, create, update, delete — default to all CRUD)+- **Publisher prefix** (e.g., `cr4fc`)++### 2.2 From Data Model Manifest++If the table details are not fully specified, check `.datamodel-manifest.json`:++```+Glob: **/.datamodel-manifest.json+```++Read the manifest to get table logical names, columns, types, and relationships. The manifest provides a useful starting point, but **column logical names may not match the actual Dataverse schema** — Dataverse can generate names like `cr87b_posttitle` when the display name is "Title" depending on context. Always verify against the actual metadata in Step 2.5.++### 2.3 From Site Code++If no manifest exists, analyze existing code for clues:++- TypeScript interfaces with Dataverse-style field names (e.g., `cr4fc_title`)+- Mock data arrays with column-like properties+- API endpoint patterns (`/_api/<entityset>`)+- Comments or TODOs mentioning table names++### 2.4 Entity Set Name++The OData entity set name is typically the table logical name pluralized. Common patterns:++- Names ending in consonant: add `s` → `cr4fc_blogpost` → `cr4fc_blogposts`+- Names ending in `y`: replace with `ies` → `cr4fc_category` → `cr4fc_categories`+- Names already plural: use as-is → `cr4fc_products` → `cr4fc_products`++If uncertain, use the name as provided by the user or manifest. The API-verified entity set name from Step 2.5 always takes precedence.++### 2.5 Verify Column Metadata via API++**Always attempt this step.** The manifest and user input may contain incorrect column logical names — Dataverse auto-generates logical names that can differ from display names (e.g., display name "Title" → logical name `cr87b_posttitle`). Querying the actual table metadata is the only way to get the real column schema.++#### 2.5.1 Get Environment URL and Token++Get the environment URL from the manifest's `environmentUrl` field, or fall back to `pac env who`:++```powershell+pac env who+# Extract the "Environment URL" value → $envUrl+```++Get an Azure CLI access token:++```powershell+$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }+```++#### 2.5.2 Query Entity Set Name++Get the actual OData entity set name from Dataverse (do not guess from pluralization):++```powershell+$entityDef = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_logical_name>')?`$select=EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute" -Headers $headers+$entitySetName = $entityDef.EntitySetName+$primaryIdAttribute = $entityDef.PrimaryIdAttribute+$primaryNameAttribute = $entityDef.PrimaryNameAttribute+```++Use the returned `EntitySetName` for all `/_api/` URLs. Use `PrimaryIdAttribute` as the record ID column name.++#### 2.5.3 Query Column Metadata++Fetch actual column logical names, display names, and types:++```powershell+$attrs = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_logical_name>')/Attributes?`$select=LogicalName,DisplayName,AttributeType,IsPrimaryId&`$filter=IsCustomAttribute eq true or IsPrimaryId eq true" -Headers $headers+$attrs.value | ForEach-Object { [PSCustomObject]@{ LogicalName = $_.LogicalName; DisplayName = $_.DisplayName.UserLocalizedLabel.Label; Type = $_.AttributeType } } | Format-Table -AutoSize+```++This returns the **real** column logical names. Cross-reference against the manifest:++- If a manifest column's `logicalName` does not appear in the API results, find the correct column by matching `DisplayName` instead and use the API's `LogicalName`.+- If a manifest column's `logicalName` does appear in the API results, use it as-is (confirmed correct).+- Add any columns from the API that are missing from the manifest but relevant to the integration.++#### 2.5.4 Query Lookup Relationships (if applicable)++If the table has lookup columns, fetch relationship metadata to get the correct Navigation Property names (case-sensitive, needed for `$expand` and `@odata.bind`):++```powershell+$rels = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_logical_name>')/ManyToOneRelationships?`$select=SchemaName,ReferencedEntity,ReferencingAttribute,ReferencingEntityNavigationPropertyName" -Headers $headers+$rels.value | ForEach-Object { [PSCustomObject]@{ NavigationProperty = $_.ReferencingEntityNavigationPropertyName; TargetTable = $_.ReferencedEntity; ForeignKey = $_.ReferencingAttribute } } | Format-Table -AutoSize+```++Use `ReferencingEntityNavigationPropertyName` as the Navigation Property name in `$expand` and `@odata.bind`. This is the **case-sensitive** name that must be used exactly.++#### 2.5.5 Graceful Fallback++If API calls fail (no PAC auth, no Azure CLI token, network error, 401/403):++- **Do NOT stop the workflow.** Fall back to the manifest or code analysis data from Steps 2.2–2.3.+- Log a warning noting that column names were not verified against the actual schema and may need manual correction.+- Continue with the best available data.++---++## Step 3: Create Core API Client++**Skip this step entirely if an API client already exists** (detected in Step 1.3). Read the existing client and import from it in subsequent steps.++Create `src/shared/powerPagesApi.ts` — a centralized fetch wrapper shared by all table services. This file is created once and reused for every future integration. It includes anti-forgery token management (8-min TTL cache, fetched from `/_layout/tokenhtml`), header builder, response parsing, retry logic (exponential backoff, 403 token refresh, 401 session expiry), error code constants, OData URL builder, pagination helpers, lookup binding, and file column helpers.++Read the complete file template:++Reference: `${CLAUDE_PLUGIN_ROOT}/references/webapi-core-client.md`++---++## Step 4: Create Entity Types++Create TypeScript type definitions for the target table. Place them following existing project conventions. If no convention exists, use `src/types/<tableName>.ts`. Define the raw OData entity interface, clean domain type, option set constants, create/update input types, and an entity-to-domain mapper function. Follow the lookup property rules for retrieval (`_value` GUID property in `$select`, Navigation Property in `$expand`) vs mutation (`@odata.bind` on Navigation Property).++Reference: `${CLAUDE_PLUGIN_ROOT}/references/webapi-service-patterns.md` — see "Entity Types (Step 4)" section.++---++## Step 5: Create Service Layer++Create a service module with CRUD operations for the target table. Place it following project conventions. Default: `src/shared/services/<tableName>Service.ts`. Implement list (paginated with `$top` + `@odata.nextLink`), get by ID, create (POST with `Prefer: return=representation` + Location header fallback), update (PATCH with `If-Match: *`), delete, and optionally M:N sync, count, aggregation, and file/image column operations.++Reference: `${CLAUDE_PLUGIN_ROOT}/references/webapi-service-patterns.md` — see "Service Layer (Step 5)" section.++---++## Step 6: Create Framework Hooks++Create framework-specific reactive data-fetching wrappers based on the detected framework: React custom hooks (+ DataverseImage component for image columns), Vue composables, Angular injectable services, or Astro direct imports.++Reference: `${CLAUDE_PLUGIN_ROOT}/references/webapi-service-patterns.md` — see "Framework Hooks (Step 6)" section.++---++## Step 7: Update Existing Components++**This is the most critical step.** Creating service files is not enough — you must find and update every existing component that references the target table's data so they use the new service layer instead of mock data or placeholder fetch calls. Without this step, the integration is incomplete.++### 7.1 Search for Mock Data and Placeholder Calls++Use these search patterns to find all components that need updating:++```+# Find hardcoded arrays that look like entity data+Grep: pattern="(const|let|var)\s+\w*(products|items|data|records)\w*\s*[=:]\s*\[" in src/**/*.{ts,tsx,js,jsx,vue,astro}++# Find TODO/FIXME comments about API integration+Grep: pattern="(TODO|FIXME|HACK|PLACEHOLDER).*(api|fetch|data|mock|hardcode)" in src/**/*.{ts,tsx,js,jsx,vue,astro}++# Find empty useEffect/onMounted blocks awaiting data+Grep: pattern="useEffect\(\s*\(\)\s*=>\s*\{" or "onMounted\(\s*\(\)\s*=>\s*\{" in src/**/*.{ts,tsx,js,jsx,vue}++# Find inline fetch calls to /_api/ that should use the service+Grep: pattern="fetch\(.*/_api/" in src/**/*.{ts,tsx,js,jsx,vue,astro}++# Find mock data files+Glob: src/**/mock*.{ts,js,json} or src/**/seed*.{ts,js,json} or src/**/*mock*.{ts,js}++# Find components that reference the table name in any form+Grep: pattern="<tableName>" (use the actual table display name, e.g., "product", "order", "blog") in src/**/*.{ts,tsx,js,jsx,vue,astro}+```++Adapt these patterns to the actual table name and project conventions.++### 7.2 Replace Mock Data with Service Calls++For each file found, make these changes:++**Add imports** for the new service and types at the top of the file:++```typescript+// BEFORE — no service imports, data is inline+const products = [+ { id: '1', name: 'Widget', price: 9.99 },+ { id: '2', name: 'Gadget', price: 19.99 },+];++// AFTER — import and use the service hook+import { useProducts } from '../shared/hooks/useProducts';+// or for non-React: import { listProducts } from '../shared/services/productService';+```++**Replace hardcoded arrays** with hook/service calls:++```typescript+// BEFORE — React component with mock data+function ProductList() {+ const products = [+ { id: '1', name: 'Widget', price: 9.99 },+ { id: '2', name: 'Gadget', price: 19.99 },+ ];+ return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>;+}++// AFTER — React component using the hook+function ProductList() {+ const { items: products, isLoading, error } = useProducts();++ if (isLoading) return <div>Loading...</div>;+ if (error) return <div>Error: {error}</div>;++ return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>;+}+```++**Replace inline fetch calls** with service functions:++```typescript+// BEFORE — raw fetch in component+useEffect(() => {+ fetch('/_api/cr4fc_products?$select=cr4fc_name,cr4fc_price')+ .then(res => res.json())+ .then(data => setProducts(data.value));+}, []);++// AFTER — use the service hook (handles auth, retry, types, pagination)+const { items: products, isLoading, error, refetch } = useProducts();+```++### 7.3 Handle State Management Updates++If the component uses state management (React Context, Vue store, etc.), update the data source within the provider/store rather than in individual components:++- **React Context**: Update the context provider to call the service hook and pass real data to consumers+- **Vue Pinia/Vuex store**: Update the store actions to call service functions+- **Angular NgRx/signals**: Update effects or signal computations to call the service++### 7.4 Delete Obsolete Mock Data++After confirming all components use the service layer:++- Delete mock data files (e.g., `src/data/mockProducts.ts`, `src/mocks/products.json`)+- Remove mock data arrays from components+- Remove mock data exports from barrel files (`index.ts`)+- If a service factory exists with a mock mode, keep the mock service for local dev but ensure production mode uses the real service++### 7.5 Preserve UI Structure++When updating components:++- **Keep all existing JSX/template markup intact** — only change the data source+- **Keep existing event handlers** — wire them to the new service's create/update/delete functions+- **Add loading and error states** if the component didn't have them (the hooks provide `isLoading` and `error`)+- **Keep existing styling and layout** — do not refactor the component structure++---++## Step 8: Verify Integration++After updating all components, verify that the integration is complete and working.++### 8.1 Check Imports++Verify that components which display or manipulate the target table's data now import from the service/hook files:++```+# Confirm service imports exist in components+Grep: pattern="import.*from.*(services|hooks|composables).*(tableName)" in src/**/*.{ts,tsx,js,jsx,vue,astro}+```++### 8.2 Check Mock Data Removal++Verify that hardcoded arrays and mock data related to the target table have been removed:++```+# Confirm no mock data remains for this table+Grep: pattern="(const|let|var)\s+\w*(tableName|items|data)\w*\s*=\s*\[" in src/**/*.{ts,tsx,js,jsx,vue,astro}++# Confirm mock data files are gone+Glob: src/**/mock*tableName*.{ts,js,json}+```++If mock data is intentionally kept (e.g., for a service factory with mock mode), that's acceptable — but the default/production code path must use the real service.++### 8.3 Check API Usage++Verify that components now call the service functions instead of using inline data:++```+# Confirm service function calls exist+Grep: pattern="(list|get|create|update|delete)(TableName)|use(TableName)" in src/**/*.{ts,tsx,js,jsx,vue,astro}++# Confirm no raw /_api/ fetch calls remain for this table+Grep: pattern="fetch\(.*/_api/.*tableName" in src/**/*.{ts,tsx,js,jsx,vue,astro}+```++### 8.4 Build Check++Run the project build to confirm no import or type errors were introduced:++```bash+npm run build+# or: npx tsc --noEmit (for TypeScript type-checking only)+```++If the build fails, fix the errors (typically missing imports, incorrect type names, or unused variables from removed mock data) before proceeding.++---++## File Placement Summary++Match existing project conventions. If none exist, use this default layout:++| File | Default Location |+|------|------------------|+| Core API client | `src/shared/powerPagesApi.ts` |+| Entity types + domain types + mapper | `src/types/<tableName>.ts` |+| Service (CRUD operations) | `src/shared/services/<tableName>Service.ts` |+| React hook | `src/shared/hooks/use<DomainName>.ts` |+| React DataverseImage component | `src/shared/components/DataverseImage.tsx` |+| Vue composable | `src/composables/use<DomainName>.ts` |+| Angular service | `src/app/services/<tableName>-api.service.ts` |++---++## Authentication Context++When the site needs to know the current portal user (e.g., for permission checks or displaying user info), use the Power Pages portal user object:++```typescript+export interface PortalUser {+ contactId?: string;+ userName?: string;+ firstName?: string;+ lastName?: string;+ email?: string;+ webRoles?: Array<{ name?: string } | string>;+}++export const getPortalUser = (): PortalUser | null => {+ if (typeof window === 'undefined') return null;+ const raw = (window as any).Microsoft?.Dynamic365?.Portal?.User;+ if (!raw?.userName) return null;+ return {+ contactId: raw.contactId ?? raw.userId,+ userName: raw.userName,+ firstName: raw.firstName,+ lastName: raw.lastName,+ email: raw.email ?? raw.emailAddress,+ webRoles: raw.webRoles,+ };+};++export const getCurrentContactId = (): string | undefined =>+ getPortalUser()?.contactId;+```++Include this in the core API client file only if the site's code requires user-scoped operations (e.g., "show my orders", "my profile").++---++## Site Settings Prerequisites++Web API calls will fail unless site settings (`Webapi/<table>/enabled`, `Webapi/<table>/fields`) and table permissions are configured. **This is handled by the `webapi-permissions` agent** — not this agent. After creating the integration code, note that the user should run the `webapi-permissions` agent if permissions are not yet set up.++---++## Service Factory Pattern (Optional)++When the project needs both mock data (for local development) and real Web API data (in production), implement a service factory that switches between modes:++```typescript+export type ServiceMode = 'mock' | 'webapi';++const inferServiceMode = (): ServiceMode => {+ const envMode = import.meta.env?.VITE_SERVICE_MODE?.toLowerCase();+ if (envMode === 'mock' || envMode === 'webapi') return envMode;+ return import.meta.env?.DEV ? 'mock' : 'webapi';+};++let currentMode = inferServiceMode();++// Registry maps mode to service implementations+const services: Record<ServiceMode, { products: typeof import('./productService') }> = {+ mock: { products: mockProductService },+ webapi: { products: webapiProductService },+};++export const getProductService = () => services[currentMode].products;+```++Only create a factory if the project already uses mock data or the user requests it. For simple integrations, import the service directly.++---++## Permission Check Pattern (Optional)++If the site has role-based access control, create a permission utility alongside the service:++```typescript+import { getPortalUser } from '../shared/powerPagesApi';++export const hasPermission = (action: 'create' | 'edit' | 'delete'): boolean => {+ const user = getPortalUser();+ if (!user) return false;++ const roles = (user.webRoles ?? [])+ .map(r => (typeof r === 'string' ? r : r?.name ?? '').toLowerCase())+ .filter(Boolean);++ switch (action) {+ case 'create':+ case 'edit':+ case 'delete':+ return roles.some(r => r.includes('editor') || r.includes('admin'));+ default:+ return false;+ }+};+```++For React, wrap this in a hook:++```typescript+export function usePermission(action: 'create' | 'edit' | 'delete') {+ return useMemo(() => hasPermission(action), [action]);+}+```++Only create this if the site's UI shows/hides controls based on user roles.++---++## Key Rules++1. **`/_api/` prefix** — Always use `/_api/` for Power Pages Web API URLs. Never use the Dataverse environment URL directly.+2. **Anti-forgery token required on mutations** — The `__RequestVerificationToken` header must be set on POST, PATCH, PUT, and DELETE requests. The server only validates the anti-forgery token on mutating requests — GET requests do not require it. However, the shared client sends it on all requests for simplicity, which is harmless. Fetch the token from `/_layout/tokenhtml` and parse the value from the returned HTML. No `Authorization` bearer header is needed — Power Pages uses cookie-based session auth for authenticated users (JWT bearer tokens are also supported via middleware, but cookie auth is the standard client-side pattern).+3. **No wildcard `$select`** — Always list specific columns. Wildcards expose unnecessary data and degrade performance.+4. **Always paginate** — Every list/query MUST include `$top`. Use `$top`/`$count` for the first page and `@odata.nextLink` cursors for subsequent pages. Dataverse does **not** support `$skip` — never use it. Use `fetchAllPages` only when all records are genuinely needed (dropdowns, lookups, exports). Never fetch unbounded data.+5. **Use `$count=true`** — Include on every list query to get total record count efficiently in `@odata.count` without fetching all rows. For count-only queries, combine with `$top=0`.+6. **`@odata.bind` for lookups** — Set lookup relationships using `[email protected]` annotation with the target entity set path, not raw GUID values. The Navigation Property name is **case-sensitive** and must match the schema name (typically PascalCase like `cr4fc_Category`). Using the logical name (all lowercase) causes "Undeclared Property" errors.+7. **Handle 204 responses** — PATCH and DELETE return empty bodies. Do not attempt to parse them.+8. **Handle POST responses** — Send `Prefer: return=representation` on POST, but the API may return just a success status (e.g., 204) without a body. Always handle both cases: parse the body if present, otherwise extract the created record ID from the `Location` or `OData-EntityId` response header using `extractRecordId()` and fetch the record with a separate GET.+9. **`If-Match: *`** — Required header for PATCH (update) operations.+10. **Formatted values** — Include `Prefer: odata.include-annotations="OData.Community.Display.V1.FormattedValue"` to get display names for lookups and option set labels.+11. **Escape OData strings** — Always use `escapeODataString()` for user-provided values in `$filter` to prevent injection.+12. **Safe `fetchAllPages` iteration limit** — Always cap the pagination loop (default 100 iterations) when following `@odata.nextLink` to prevent infinite loops.+13. **Cache the anti-forgery token** — Use an 8-minute TTL cache to avoid fetching from `/_layout/tokenhtml` on every request.+14. **Retry transient errors** — 429 and 5xx with exponential backoff. On 403, invalidate the cached anti-forgery token and retry. On 401, do **not** retry — the session has expired and the user must re-authenticate. Throw a clear "Session expired" error.+15. **Type everything** — Raw OData entity interface + clean domain type + mapper function.+16. **Match existing patterns** — If the project has conventions for file locations, naming, or code style, follow them exactly.+17. **One table per invocation** — This agent handles a single table. For multiple tables, the caller invokes it separately for each.+18. **Upload vs download URLs** — File upload uses `/_api/table(id)/column` (PATCH, no `/$value`). File download uses `/_api/table(id)/column/$value` (GET). File delete uses `/_api/table(id)/column` (DELETE). Do not confuse the URL patterns.+19. **File upload body is binary** — Send `ArrayBuffer` via `file.arrayBuffer()`, not JSON. Set `Content-Type` to the file's MIME type. Include `If-Match: *` and `x-ms-file-name` headers.+20. **File download uses blob response** — Set `Accept: */*` (not `application/json`). Parse response as blob, not JSON. Return `null` on 404 instead of throwing.+21. **Lookup GUID vs Navigation Property** — On GET, use `_{logicalname}_value` in `$select` for the raw GUID, and the Navigation Property in `$expand` for related data. On POST/PATCH, use `[email protected]` — never write directly to the `_value` property.+22. **Remind about permissions** — After creating integration code, note that the `webapi-permissions` agent must be run to configure site settings and table permissions if not already done.+23. **Disable `innererror` in production** — `Webapi/error/innererror = true` is useful for debugging but exposes internal Dataverse error details. Must be disabled before going live.+24. **Always update existing components** — Creating service files is not enough. After generating the API client, types, service, and hooks, you MUST search for and update all existing components that use mock data, hardcoded arrays, or placeholder fetch calls for the target table. Replace their data sources with the new service/hook. This is the most critical step — without it, the integration is incomplete.+25. **Supported OData query options** — Power Pages Web API supports exactly these query params: `$select`, `$expand`, `$filter`, `$apply`, `$count`, `$top`, `$orderby`, `$skiptoken`, and `fetchXml`. Any other query params (e.g., `$skip`, `$search`) will be rejected if query param validation is enabled. Use `$apply` for aggregation queries (groupby, aggregate) when the UI needs totals, averages, or grouped counts.+26. **Blocked entities** — Power Pages blocks Web API access to certain system entities including all `adx_*` portal configuration entities, `systemuser`, and other internal tables. Do not attempt to create integration code for these tables — the API will return 404. Only custom tables and supported OOB tables that have `Webapi/{table}/enabled = true` are accessible.+27. **Server-side response caching** — Power Pages caches GET responses server-side. The cache is automatically invalidated when a mutation (POST/PATCH/DELETE) occurs on the same entity set. This means data reads immediately after writes are consistent, but clients on separate sessions may briefly see stale data. Do not implement aggressive client-side caching on top of the server cache unless needed.+28. **Web API error codes** — Use the error codes exported from the core API client (`WebApiErrorCode`) for specific error handling in the UI. The server returns distinct hex codes for each permission denial type (read `90040120`, write `90040102`, create `90040103`, delete `90040104`), anti-forgery failures (`90040107`), and resource not found (`9004010c`). Use `isPermissionError()` to show a "contact your administrator" message instead of generic errors.+29. **Column permissions** — Power Pages enforces field-level access control via column permission profiles. If a column permission profile blocks a field, the Web API will silently omit it from the response even if it appears in `$select`. This can cause unexpected `undefined` values in mapped domain types. Design mappers with sensible defaults for all fields.+30. **Verify column names against actual metadata** — Never trust manifest or user-provided column logical names without verification. Dataverse auto-generates logical names that can differ from display names (e.g., display name "Title" on a Posts table → `cr87b_posttitle`, not `cr87b_title`). Always query `EntityDefinitions/Attributes` in Step 2.5 to get the real schema. If the API is unavailable, fall back to manifest data but warn that names may need correction.++---++## Completion Checklist++Before confirming that work is done, verify every item below. Do not skip any check.++### Files Created+- [ ] **Core API client** exists at `src/shared/powerPagesApi.ts` (or was already present and reused)+- [ ] **Entity types file** exists with: raw OData entity interface, clean domain type, option set constants (if applicable), create/update input types, and entity-to-domain mapper function+- [ ] **Service file** exists with all CRUD operations the user requested (list, get, create, update, delete)+- [ ] **Framework hooks/composables/services** exist matching the detected framework (React hook, Vue composable, Angular injectable service, or Astro direct import)+- [ ] **File/image helpers** exist in the service if the table has File or Image columns (download, upload, delete)+- [ ] **Aggregation helpers** exist in the service if the site UI needs grouped counts, sums, or averages++### Schema Verification+- [ ] Queried `EntityDefinitions/Attributes` to get actual column logical names (or noted fallback if API unavailable)+- [ ] Entity set name is from the API's `EntitySetName` (not guessed from pluralization)+- [ ] Column logical names in generated code match the actual Dataverse schema (not just manifest display names)+- [ ] Navigation property names are from the API's `ReferencingEntityNavigationPropertyName` (case-sensitive)++### Code Correctness+- [ ] All list/query operations include `$top` — no unbounded fetches+- [ ] All queries use explicit `$select` with specific columns — no wildcards+- [ ] All queries include `$count=true` for total record count+- [ ] Lookups on POST/PATCH use `[email protected]` — not raw GUID writes to `_value` properties+- [ ] Navigation property names are case-sensitive and match the schema (typically PascalCase)+- [ ] Update (PATCH) operations include the `If-Match: *` header+- [ ] Domain mappers provide sensible defaults for every field (guards against column permissions silently omitting values)+- [ ] OData string values in `$filter` use `escapeODataString()` to prevent injection+- [ ] File upload sends `ArrayBuffer` body with correct `Content-Type`, `If-Match: *`, and `x-ms-file-name` headers+- [ ] File download uses `Accept: */*` and returns `null` on 404 instead of throwing++### Existing Code Updated+- [ ] Searched for all components referencing the target table's data (mock arrays, hardcoded data, inline `/_api/` fetch calls, TODO/FIXME comments)+- [ ] Every component now imports from the new service/hooks — no mock data or placeholder fetch calls remain for this table+- [ ] Mock data files for this table are deleted (unless intentionally kept for a service factory)+- [ ] Loading and error states added to components that lacked them++### Build & Integration+- [ ] Project builds without errors (`npm run build` or `npx tsc --noEmit`)+- [ ] No unused imports or variables left behind from removed mock data+- [ ] File placement follows existing project conventions (or the default layout from the File Placement Summary)++### User Guidance+- [ ] Reminded user to run the `webapi-permissions` agent if table permissions and site settings are not yet configured+- [ ] Noted that `Webapi/error/innererror` should be disabled before going live (if mentioned in context)diff --git a/plugins/power-pages/agents/webapi-permissions.md b/plugins/power-pages/agents/webapi-permissions.mdnew file mode 100644index 000000000..8298a2642--- /dev/null+++ b/plugins/power-pages/agents/webapi-permissions.md@@ -0,0 +1,645 @@+---+name: webapi-permissions+description: |+ Use this agent when the user wants to enable Web API access for their Power Pages site, set up table permissions,+ or configure site settings for Web API. Trigger examples: "enable web api", "set up web api", "configure table permissions",+ "add web api access", "set up api for my tables", "enable api access for products table", "configure web api permissions".+ This agent is read-only — it analyzes the site, discovers tables and web roles, and proposes a permissions plan+ (table permissions + site settings + Web API config). It does NOT create any files. The main agent uses its output+ to create the actual YAML files.+model: opus+color: yellow+tools:+ - Read+ - Grep+ - Glob+ - Bash+ - Write+ - EnterPlanMode+ - ExitPlanMode+ - mcp__plugin_power-pages_playwright__browser_navigate+ - mcp__plugin_power-pages_playwright__browser_take_screenshot+ - mcp__plugin_power-pages_playwright__browser_wait_for+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_code_sample_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch+---++# Web API Permissions Architect++You are a Web API permissions architect for Power Pages code sites. Your job is to analyze the site, discover existing tables and web roles, and propose a complete permissions plan for enabling Web API access — **without creating or modifying any files**. You are strictly read-only and advisory. The main agent will use your output to create the actual table permission and site setting YAML files.++## Workflow++1. **Verify Site Deployment** — Check that `.powerpages-site` folder exists+2. **Discover Existing Configuration** — Read web roles, table permissions, and site settings+3. **Analyze Data Requirements** — Determine which tables need Web API access and what operations are needed+4. **Discover Table Columns** — Query Dataverse OData API to get the exact columns for each table+5. **Propose Permissions Plan** — Render a visual diagram and enter plan mode for user approval++**Important:** Do NOT ask the user questions. Autonomously analyze the site code, data model manifest, and Dataverse environment to figure out the permissions plan, then present your findings via plan mode for the user to review and approve.++---++## Step 1: Verify Site Deployment++Check that the site has been deployed at least once by looking for the `.powerpages-site` folder.++### 1.1 Locate the Project++Use `Glob` to find:+- `**/powerpages.config.json` — Power Pages config (identifies the project root)+- `**/.powerpages-site` — Deployment folder++### 1.2 Check Deployment Status++**If `.powerpages-site` folder does NOT exist:**++The site has not been deployed yet. The `.powerpages-site` folder is created when the site is first deployed using `pac pages upload-code-site`. Web API configuration requires this folder.++Enter plan mode and state:++> "The `.powerpages-site` folder was not found. This folder is created when the site is first deployed to Power Pages. You need to deploy your site first using `/power-pages:deploy-site` before Web API permissions can be configured."++Exit plan mode and stop. Do NOT proceed with the remaining steps.++**If `.powerpages-site` exists:** Proceed to Step 2.++---++## Step 2: Discover Existing Configuration++Read all existing web roles, table permissions, and site settings to understand the current state.++### 2.1 Discover Web Roles++Read all files in `.powerpages-site/web-roles/`:++```text+**/.powerpages-site/web-roles/*.yml+```++Each web role file has this format:++```yaml+anonymoususersrole: false+authenticatedusersrole: true+id: ce938206-701d-4902-85b2-b46b1dd169b9+name: Authenticated Users+```++Compile a list of all web roles with their `id`, `name`, and flags. You will need the role IDs to associate table permissions with roles.++**If no web roles exist:** Note this in your plan — the main agent will need to create web roles before table permissions can be set up. Suggest at minimum: `Anonymous Users` and `Authenticated Users`.++### 2.2 Discover Existing Table Permissions++Read all files in `.powerpages-site/table-permissions/`:++```text+**/.powerpages-site/table-permissions/*.tablepermission.yml+```++Each table permission file has this format (code site / git format — fields alphabetically sorted, `adx_` prefix stripped except for M2M relationships):++```yaml+adx_entitypermission_webrole:+- ce938206-701d-4902-85b2-b46b1dd169b9+append: true+appendto: true+create: true+delete: false+entitylogicalname: cra5b_order+entityname: Order - Authenticated Access+id: d75934c2-5ea2-4b95-9309-e15637820626+read: true+scope: 756150004+write: false+```++For permissions with parent relationships:++```yaml+adx_entitypermission_webrole:+- ce938206-701d-4902-85b2-b46b1dd169b9+append: false+appendto: true+create: true+delete: false+entitylogicalname: cra5b_orderitem+entityname: Order Item - Authenticated Access+id: a3b4c5d6-7890-4abc-def0-123456789012+parententitypermission: d75934c2-5ea2-4b95-9309-e15637820626+parentrelationshipname: cra5b_order_orderitem+read: true+scope: 756150003+write: false+```++Compile a list of existing table permissions noting which tables already have permissions configured.++### 2.3 Discover Existing Site Settings++Read all Web API-related site settings in `.powerpages-site/site-settings/`:++```text+**/.powerpages-site/site-settings/Webapi-*.sitesetting.yml+```++Each site setting has this format:++```yaml+description: Enable Web API access for cra5b_product table+id: a1b2c3d4-2111-4111-8111-111111111111+name: Webapi/cra5b_product/enabled+value: true+```++Fields setting (lists specific columns — **never** uses `*`):++```yaml+description: Allowed fields for cra5b_product Web API access+id: a1b2c3d4-2112-4111-8111-111111111112+name: Webapi/cra5b_product/fields+value: cra5b_productid,cra5b_name,cra5b_description,cra5b_price,cra5b_imageurl+```++Note which tables already have Web API enabled and which fields are currently exposed.++---++## Step 3: Analyze Data Requirements++Determine which tables need Web API access by analyzing the site code and data model.++### 3.1 Read Data Model Manifest++Check for `.datamodel-manifest.json` in the project root:++```text+**/.datamodel-manifest.json+```++If found, read it to get the list of tables and their columns. This is the preferred source for table discovery.++### 3.2 Analyze Site Code++If no manifest exists, analyze the source code to infer which tables need Web API access:++- **API calls / fetch requests** — Look for `/_api/` endpoints which indicate Web API usage patterns+- **TypeScript interfaces / types** — Type definitions often map to table schemas+- **Data services / hooks** — Custom hooks or service files that interact with Dataverse+- **Component data bindings** — What data each component displays or modifies++Look for patterns like:+```text+/_api/<table_plural_name>+fetch.*/_api/+```++### 3.3 Determine Access Patterns++For each table that needs Web API access, determine:++1. **Which web roles** need access (Anonymous Users for public read, Authenticated Users for CRUD, etc.)+2. **What operations** are needed per role:+ - `adx_read` — Can read records+ - `adx_create` — Can create new records+ - `adx_write` — Can update existing records. **Also required for file/image column uploads** — uploading a file uses `PATCH` which requires write permission even if the role doesn't need to update other fields on the record.+ - `adx_delete` — Can delete records+ - `adx_append` — Can associate records to other records (needed when this table has child relationships)+ - `adx_appendto` — Can be associated as a child to other records (needed when this table is referenced by lookups)++ **File/image upload detection:** If the integration code contains `uploadFileColumn`, `uploadFile`, or PATCH requests targeting a column endpoint (pattern: `/_api/<table>(<id>)/<column>`), the table requires `write: true`. Search for these patterns:+ ```text+ Grep: "uploadFileColumn|uploadFile|upload\w+Photo|upload\w+Image|upload\w+File" in src/**/*.ts+ ```+3. **Scope** — What records the role can access:+ - `756150000` — **Global**: Access all records. **Avoid Global scope whenever possible** — it grants unrestricted access to every record in the table. Only use Global for truly public, read-only reference data (e.g., product catalog for anonymous browsing) where no other scope is appropriate.+ - `756150001` — **Contact**: Access records associated with the current user's contact. **Recommend Contact scope for individual self-access** — use when each user should only see/manage their own records (e.g., orders, profiles, addresses).+ - `756150002` — **Account**: Access records associated with the current user's parent account. **Recommend Account scope for organizational collaboration** — use when users within the same organization need shared visibility (e.g., team members viewing company orders, shared projects).+ - `756150003` — **Parent**: Access records through parent table permission relationship (for child tables like order items that inherit access from a parent table).+ - `756150004` — **Self**: Access only the user's own contact record and records directly linked to it.++ **Scope Selection Guidance:**+ - Default to **Contact** (`756150001`) for user-specific data — it is the safest and most common choice+ - Use **Account** (`756150002`) when business logic requires shared access within an organization+ - Use **Parent** (`756150003`) for child tables that should inherit permissions from their parent table+ - Use **Self** (`756150004`) for the contact record itself or records directly owned by the user+ - Use **Global** (`756150000`) only as a last resort for genuinely public reference data, and only with read-only permissions++4. **Parent relationships** — If a table's permission scope is Parent (`756150003`), identify the parent table permission and relationship name++### 3.4 Identify Fields for Web API++For each table that needs Web API access, determine the specific columns to expose.++**CRITICAL SECURITY RULE: NEVER use `*` (wildcard) for the fields setting.** Always list specific column logical names. Using `*` exposes all columns including system columns and potentially sensitive data. This is a security risk.++#### Cross-Check with Integration Code++After determining which columns to include, verify that **every column referenced in the Web API integration code** is present in the proposed `Webapi/<table>/fields` setting. Missing columns will cause silent data gaps or API errors at runtime.++Search the source code for columns used in each table's service layer:++1. **`$select` statements** — Find column select arrays in service files:+ ```text+ Grep: "\$select|_SELECT" in src/**/*.ts+ ```++2. **POST/PATCH request bodies** — Find columns written in create/update operations:+ ```text+ Grep: "cr[a-z0-9]+_\w+" in src/shared/services/*.ts or src/services/*.ts+ ```++3. **Type definitions** — Check TypeScript entity interfaces for column names:+ ```text+ Grep: "cr[a-z0-9]+_\w+" in src/types/*.ts+ ```++For each table, compile the complete set of columns used in code and ensure the proposed `Webapi/<table>/fields` value includes **all of them**. If a column appears in the integration code but is missing from the fields setting, add it.++**Common omissions to check for:**+- Primary key column (e.g., `cr4fc_productid`) — always needed for CRUD+- Lookup GUID columns (e.g., `_cr4fc_category_value`) — needed for filtering and references+- File/image columns (e.g., `cr4fc_photo`) — needed in the fields list if the code downloads or uploads files. Also ensure `write: true` is set on the table permission if uploads are used (PATCH method).+- `createdon` / `modifiedon` — if displayed in the UI+- Columns used in `$filter` or `$orderby` — must be in the fields list to be queryable++---++## Step 4: Discover Table Columns++Query the Dataverse OData API to get the exact columns for each table, so you can list specific fields in the site settings.++### 4.1 Get Environment URL and Token++Follow the shared prerequisite pattern:++```powershell+# Get environment URL+pac env who+```++Extract the `Environment URL` (e.g., `https://org12345.crm.dynamics.com`). Store as `$envUrl`.++```powershell+# Get auth token+$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }+```++### 4.2 Query Table Columns++For each table that needs Web API access, fetch its columns:++```powershell+$attrs = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_logical_name>')/Attributes?`$select=LogicalName,DisplayName,AttributeType,IsPrimaryId&`$filter=IsCustomAttribute eq true or IsPrimaryId eq true" -Headers $headers+$attrs.value | ForEach-Object { [PSCustomObject]@{ LogicalName = $_.LogicalName; DisplayName = $_.DisplayName.UserLocalizedLabel.Label; Type = $_.AttributeType; IsPK = $_.IsPrimaryId } } | Format-Table -AutoSize+```++This query returns custom columns plus the primary key — these are the columns that should be included in the Web API fields setting.++**Field selection guidance:**+- Always include the primary key column (e.g., `cra5b_productid`)+- Include all custom columns the site actually uses (referenced in code, types, or API calls)+- Exclude system columns (`createdon`, `modifiedon`, `statecode`, `statuscode`, `versionnumber`, etc.) unless the site explicitly needs them+- Exclude sensitive columns that should not be exposed via client-side API++### 4.3 Query Relationships++For tables that have parent-child relationships (Parent scope permissions), fetch the relationship names:++```powershell+$rels = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<parent_table>')/OneToManyRelationships?`$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute" -Headers $headers+$rels.value | ForEach-Object { [PSCustomObject]@{ Name = $_.SchemaName; From = $_.ReferencedEntity; To = $_.ReferencingEntity; ForeignKey = $_.ReferencingAttribute } } | Format-Table -AutoSize+```++Use the relationship `SchemaName` as the `adx_parentrelationshipname` value in the child table permission.++### Error Handling++If any API calls fail:+- **`pac env who` fails**: Note that PAC CLI auth is required (`pac auth create`)+- **`az account get-access-token` fails**: Note that Azure CLI login is required (`az login`)+- **OData 401/403**: Token expired or insufficient privileges — note in plan+- **OData 404**: Table doesn't exist — exclude from plan++Do NOT stop the entire workflow for auth errors. Use the data model manifest and code analysis as fallback for table/column discovery, and note which API-based steps were skipped and why.++---++## Step 5: Propose Permissions Plan via Plan Mode++Once you have completed Steps 1-4, prepare the permissions proposal. Section 5.1-5.4 describe the plan content. Section 5.5 renders the diagram visually in the browser — do this **before** entering plan mode.++### 5.1 Table Permissions Plan++For each table permission to create, specify the complete YAML content:++**Permission Name Convention:** `<DisplayName> - <RoleName> <AccessType>` (e.g., `Product - Anonymous Read`, `Order - Authenticated Access`)++**File Name Convention:** `<PermissionName>.tablepermission.yml` using the permission name with spaces replaced by hyphens (e.g., `Product-Anonymous-Read.tablepermission.yml`)++For each permission, include:+- Which web role(s) it is associated with (by UUID from Step 2.1)+- CRUD + append/appendto flags+- Scope (Global, Contact, Account, Parent, or Self)+- Parent permission and relationship name (if Parent scope)+- The table logical name++**YAML format (Global or Contact scope):**++Code sites use git format — all fields are alphabetically sorted, `adx_` prefix is stripped from regular attributes, but **M2M relationships keep their `adx_` prefix**. Entity-specific ID fields become just `id`. Entity reference lookups store only the GUID (not a nested object).++```yaml+adx_entitypermission_webrole:+- <web-role-uuid>+append: false+appendto: false+create: false+delete: false+entitylogicalname: <table_logical_name>+entityname: <Display Name - Role Access>+id: <uuid-from-generate-uuid.js>+read: true+scope: <scope_code>+write: false+```++**YAML format (Parent scope):**++```yaml+adx_entitypermission_webrole:+- <web-role-uuid>+append: false+appendto: true+create: true+delete: false+entitylogicalname: <child_table_logical_name>+entityname: <Child Table - Role Access>+id: <uuid-from-generate-uuid.js>+parententitypermission: <parent-permission-uuid>+parentrelationshipname: <relationship_schema_name>+read: true+scope: 756150003+write: false+```++Note: `parententitypermission` is the UUID of the parent table permission (create the parent first, then reference its UUID here). It is NOT a nested object — just the GUID value.++**CRITICAL YAML RULES:**+- **Code site git format**: All field names have `adx_` prefix stripped EXCEPT `adx_entitypermission_webrole` (M2M relationship keeps prefix)+- The display name field is `entityname` (from Dataverse `adx_entityname`) — NOT `entitypermissionname`+- Every table permission MUST have an `id` field with a UUID v4 generated by `node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js"`+- Booleans MUST be unquoted lowercase: `true` or `false` — NEVER `"true"`, `"false"`, `True`, or `False`+- Numeric scope values MUST be unquoted integers: `756150000` — NEVER `"756150000"`+- UUIDs MUST be unquoted+- Web role UUIDs use array format with `-` prefix+- Fields MUST be alphabetically sorted (as shown in the examples above)+- No extra whitespace or comments++### 5.2 Site Settings Plan++For each table that needs Web API access, two site settings are required:++**1. Enable setting** (`Webapi/<table>/enabled`):++```yaml+description: Enable Web API access for <table_logical_name> table+id: <uuid-from-generate-uuid.js>+name: Webapi/<table_logical_name>/enabled+value: true+```++**2. Fields setting** (`Webapi/<table>/fields`):++```yaml+description: Allowed fields for <table_logical_name> Web API access+id: <uuid-from-generate-uuid.js>+name: Webapi/<table_logical_name>/fields+value: <comma-separated-list-of-column-logical-names>+```++**CRITICAL: The `value` in the fields setting MUST list specific column logical names, comma-separated, with NO spaces after commas. NEVER use `*` (wildcard). Using `*` is a security risk that exposes all columns including system and sensitive data.**++Example:+```yaml+value: cra5b_productid,cra5b_name,cra5b_description,cra5b_price,cra5b_imageurl+```++**Optionally**, if the `Webapi/error/innererror` setting does not already exist, suggest it for development/debugging:++```yaml+description: Enable detailed error messages for debugging+id: <uuid-from-generate-uuid.js>+name: Webapi/error/innererror+value: true+```++**File Name Convention:** `Webapi-<table_logical_name>-enabled.sitesetting.yml` and `Webapi-<table_logical_name>-fields.sitesetting.yml`++**Site Setting YAML RULES:**+- Boolean `value` field MUST be unquoted: `value: true` — NEVER `value: "true"`+- String `value` fields (like CSV field lists) are unquoted+- UUIDs MUST be unquoted+- The `name` field uses forward slashes: `Webapi/cra5b_product/enabled`+- The `id` must be a valid UUID v4 generated by the script++### 5.3 UUID Generation++All new table permissions and site settings need UUIDs for their `id` fields. Note in the plan that UUIDs must be generated using the shared script:++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js"+```++The main agent must run this script once per file it creates. **Never generate UUIDs manually.**++### 5.4 Permissions Diagram++Create a Mermaid flowchart diagram that visually shows the permissions structure. The diagram should illustrate:+- Web roles at the top+- Table permissions in the middle (showing scope and CRUD flags)+- Tables at the bottom+- Connections showing which roles have which permissions on which tables++Use this diagram pattern:++~~~markdown+```mermaid+flowchart TD+ subgraph Web Roles+ AR["Anonymous Users"]+ AU["Authenticated Users"]+ end++ subgraph Table Permissions+ TP1["Product - Anonymous Read<br/>Scope: Global<br/>Read: ✓ | Create: ✗ | Write: ✗ | Delete: ✗"]+ TP2["Order - Authenticated Access<br/>Scope: Self<br/>Read: ✓ | Create: ✓ | Write: ✗ | Delete: ✗"]+ TP3["Order Item - Authenticated Access<br/>Scope: Parent → Order<br/>Read: ✓ | Create: ✓ | Write: ✗ | Delete: ✗"]+ end++ subgraph Tables+ T1[("cra5b_product")]+ T2[("cra5b_order")]+ T3[("cra5b_orderitem")]+ end++ AR --> TP1+ AU --> TP2+ AU --> TP3+ TP1 --> T1+ TP2 --> T2+ TP3 --> T3+ TP2 -.->|parent| TP3+```+~~~++Conventions for the diagram:+- Web role nodes: rectangle with role name `["Role Name"]`+- Table permission nodes: rectangle with permission name, scope, and CRUD summary+- Table nodes: cylinder/database shape `[("table_logical_name")]`+- Solid arrows `-->`: role-to-permission and permission-to-table associations+- Dashed arrows `-.->|parent|`: parent-child permission relationships+- Use checkmarks `✓` and crosses `✗` for CRUD flags in the permission nodes+- Group nodes in subgraphs for visual clarity++### 5.5 Render Diagram Visually++**Do this BEFORE entering plan mode.** Render the Mermaid diagram in the browser so the user can see it while reviewing the plan.++1. Write a temporary HTML file to the **system temp directory** (NOT the project directory — avoid polluting the repo):++```powershell+# Get the temp directory path+$tempDir = [System.IO.Path]::GetTempPath()+# File path: $tempDir/permissions-diagram.html+```++HTML template:++```html+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <title>Web API Permissions Diagram</title>+ <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>+ <style>+ body {+ background: #ffffff;+ display: flex;+ justify-content: center;+ align-items: flex-start;+ margin: 0;+ padding: 40px;+ font-family: system-ui, sans-serif;+ }+ .mermaid {+ width: 100%;+ min-width: 1200px;+ }+ .mermaid svg {+ width: 100% !important;+ height: auto !important;+ }+ </style>+</head>+<body>+ <pre class="mermaid">+ <!-- paste the Mermaid flowchart code here -->+ </pre>+ <script>mermaid.initialize({ startOnLoad: true, theme: 'default', flowchart: { useMaxWidth: false }, themeVariables: { fontSize: '16px' } });</script>+</body>+</html>+```++2. **Resize the browser** to a large viewport for a legible diagram:++Use `browser_resize` with **width: 1920** and **height: 1080** before navigating.++3. Navigate Playwright to the file using a `file:///` URL:+ - On Windows: `file:///C:/Users/<user>/AppData/Local/Temp/permissions-diagram.html`+ - Convert backslashes to forward slashes in the path++4. Wait for the diagram to render (wait ~3 seconds for Mermaid to process).++5. Take a **full-page screenshot** using `browser_take_screenshot` with `fullPage: true` — this captures the entire diagram regardless of viewport height.++If Playwright fails, fall back to an ASCII representation:++```+┌─────────────────────┐ ┌──────────────────────────┐+│ Anonymous Users │ │ Authenticated Users │+└─────────┬───────────┘ └───────────┬──────────────┘+ │ │+ ▼ ▼+┌─────────────────────┐ ┌──────────────────────────┐+│ Product - Anon Read │ │ Order - Auth Access │+│ Scope: Global │ │ Scope: Self │+│ R:✓ C:✗ W:✗ D:✗ │ │ R:✓ C:✓ W:✗ D:✗ │+└─────────┬───────────┘ └───────────┬──────────────┘+ │ │ ┌─ parent+ ▼ ▼ ▼+┌─────────────────────┐ ┌──────────────────────────┐+│ cra5b_product │ │ OrderItem - Auth Access │+└─────────────────────┘ │ Scope: Parent │+ │ R:✓ C:✓ W:✗ D:✗ │+ └───────────┬──────────────┘+ ▼+ ┌──────────────────────────┐+ │ cra5b_orderitem │+ └──────────────────────────┘+```++### 5.6 Summary and Next Steps++End the plan with:+1. **Summary table** of all files to be created:++ | File | Type | Location |+ |------|------|----------|+ | `Product-Anonymous-Read.tablepermission.yml` | Table Permission | `.powerpages-site/table-permissions/` |+ | `Webapi-cra5b_product-enabled.sitesetting.yml` | Site Setting | `.powerpages-site/site-settings/` |+ | `Webapi-cra5b_product-fields.sitesetting.yml` | Site Setting | `.powerpages-site/site-settings/` |++2. **Missing prerequisites** — Note if web roles need to be created first+3. **Security notes** — Confirm that no wildcard `*` is used for fields+4. **Deployment reminder** — After the main agent creates the files, the site must be deployed using `/power-pages:deploy-site`+5. **Any discovery steps skipped** due to auth errors++### 5.7 Enter Plan Mode & Exit++Use `EnterPlanMode` to present the complete proposal (sections 5.1–5.4 and 5.6) to the user. Then use `ExitPlanMode` for user review and approval.++---++## Step 6: Clean Up++After the user approves the plan, delete the temporary `permissions-diagram.html` file from the system temp directory if it was created.++---++## Step 7: Return Structured Output++After the user approves the plan, return the complete proposal back to the calling context. The output **must** include enough detail for the main agent to create all files. Structure the return as:++1. **Web Roles Required** — List of web role names and UUIDs (existing ones discovered in Step 2.1, plus any new ones that need to be created first)+2. **Table Permissions** — Array of permission objects, each with: permission name, file name, table logical name, web role UUID(s), scope, CRUD flags, and optional parent permission/relationship+3. **Site Settings** — Array of setting objects, each with: setting name, file name, value (including the specific field list for each table)+4. **Files to Create** — Complete list of files with their full YAML content in **code site git format** (using placeholder `<GENERATE-UUID>` for IDs that need to be generated). Table permissions must use the git format: `adx_` prefix stripped from regular attributes, `adx_entitypermission_webrole` keeps prefix (M2M), display name field is `entityname`, entity references are GUIDs only, fields alphabetically sorted.+5. **Diagram** — The Mermaid diagram markdown++---++## Critical Constraints++- **READ-ONLY**: Do NOT create, modify, or delete any YAML files, table permissions, or site settings. You are advisory only. The main agent creates files based on your plan.+- **No file writes**: Do not use `Write` tool for any YAML files in `.powerpages-site/`. The only file you may write is the temporary `permissions-diagram.html` in the system temp directory for visualization.+- **Code site git format**: All YAML files must use the code site git format where `adx_` prefix is stripped from regular attributes but M2M relationships (like `adx_entitypermission_webrole`) keep the prefix. Entity-specific ID fields become just `id`. Entity reference lookups store only the GUID value. The display name field for table permissions is `entityname` (from Dataverse `adx_entityname`), NOT `entitypermissionname`. Fields must be alphabetically sorted.+- **NEVER use `*` for fields**: Always list specific column logical names in `Webapi/<table>/fields` settings. Using `*` is a security risk.+- **No questions**: Do NOT use `AskUserQuestion`. Autonomously analyze the site and environment, then present your findings via plan mode.+- **Boolean formatting**: All YAML booleans must be unquoted lowercase `true` or `false`. Never `"true"`, `"false"`, `True`, or `False`.+- **UUID generation**: Note that the main agent must use `node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js"` for all UUIDs. Never hardcode or manually generate UUIDs.+- **Security**: Never log or display the full auth token. Use it only in API request headers.diff --git a/plugins/power-pages/commands/add-sample-data.md b/plugins/power-pages/commands/add-sample-data.mddeleted file mode 100644index fb816505f..000000000--- a/plugins/power-pages/commands/add-sample-data.md+++ /dev/null@@ -1,10 +0,0 @@-# Add Sample Data--Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/add-sample-data/SKILL.md`.--**Important**:--- Do not announce steps - just execute them-- Check memory-bank.md for table mapping and publisher prefix-- Insert data in dependency order (parent tables before children)-- Verify data was created successfullydiff --git a/plugins/power-pages/commands/add-seo.md b/plugins/power-pages/commands/add-seo.mddeleted file mode 100644index 1fec66d12..000000000--- a/plugins/power-pages/commands/add-seo.md+++ /dev/null@@ -1,10 +0,0 @@-# Add SEO Assets--Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/add-seo/SKILL.md`.--**Important**:--- Do not announce steps - just execute them-- Check memory-bank.md for project context first-- Create all SEO assets (meta tags, robots.txt, sitemap.xml, favicon)-- Build and upload after completiondiff --git a/plugins/power-pages/commands/add-tests.md b/plugins/power-pages/commands/add-tests.mddeleted file mode 100644index 3ea387941..000000000--- a/plugins/power-pages/commands/add-tests.md+++ /dev/null@@ -1,10 +0,0 @@-# Add Tests--Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/add-tests/SKILL.md`.--**Important**:--- Do not announce steps - just execute them-- Check memory-bank.md for project context first-- Set up both unit tests (Vitest) and E2E tests (Playwright)-- Run tests to verify they pass before completingdiff --git a/plugins/power-pages/commands/create-site.md b/plugins/power-pages/commands/create-site.mddeleted file mode 100644index a04aedd55..000000000--- a/plugins/power-pages/commands/create-site.md+++ /dev/null@@ -1,13 +0,0 @@-# Create Power Pages Code Site--Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/create-site/SKILL.md`.--**Important**:--- Do not announce steps - just execute them-- Start by gathering requirements (ask what they want to build)-- Check prerequisites (PAC CLI and Azure CLI) before uploading-- Use the frontend-design skill when creating the site-- Create complete `powerpages.config.json` with siteName, defaultLandingPage, and compiledPath-- Execute all PAC CLI and API commands as specified-- Clean up any temporary helper scripts after completiondiff --git a/plugins/power-pages/commands/integrate-webapi.md b/plugins/power-pages/commands/integrate-webapi.mddeleted file mode 100644index 6d5b00097..000000000--- a/plugins/power-pages/commands/integrate-webapi.md+++ /dev/null@@ -1,12 +0,0 @@-# Integrate Web API--Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/integrate-webapi/SKILL.md`.--**Important**:--- Do not announce steps - just execute them-- Check memory-bank.md for table mapping and publisher prefix-- Create Web API service with CSRF token handling-- Find and replace ALL mock/static data with API calls-- Delete unused mock data files after replacement-- Build and upload after completiondiff --git a/plugins/power-pages/commands/setup-auth.md b/plugins/power-pages/commands/setup-auth.mddeleted file mode 100644index 76802d44d..000000000--- a/plugins/power-pages/commands/setup-auth.md+++ /dev/null@@ -1,12 +0,0 @@-# Setup Authentication--Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/SKILL.md`.--**Important**:--- Do not announce steps - just execute them-- Check memory-bank.md for project context first-- Verify /setup-webapi was completed (site must be uploaded)-- Create auth service, authorization utils, and UI components-- Build and upload after completion-- Clean up any temporary helper scripts after completiondiff --git a/plugins/power-pages/commands/setup-dataverse.md b/plugins/power-pages/commands/setup-dataverse.mddeleted file mode 100644index d92d70001..000000000--- a/plugins/power-pages/commands/setup-dataverse.md+++ /dev/null@@ -1,11 +0,0 @@-# Setup Dataverse Tables--Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/setup-dataverse/SKILL.md`.--**Important**:--- Do not announce steps - just execute them-- Check memory-bank.md for project context first-- Create tables in dependency order (parent tables before children)-- Execute all REST API commands as specified-- Clean up any temporary helper scripts after completiondiff --git a/plugins/power-pages/commands/setup-webapi.md b/plugins/power-pages/commands/setup-webapi.mddeleted file mode 100644index 763ac3418..000000000--- a/plugins/power-pages/commands/setup-webapi.md+++ /dev/null@@ -1,11 +0,0 @@-# Setup Web API Access--Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/setup-webapi/SKILL.md`.--**Important**:--- Do not announce steps - just execute them-- Check memory-bank.md for table mapping first-- Create site settings, web roles, and table permissions-- Build and upload after completion-- Clean up any temporary helper scripts after completiondiff --git a/plugins/power-pages/references/datamodel-manifest-schema.md b/plugins/power-pages/references/datamodel-manifest-schema.mdnew file mode 100644index 000000000..4f1e524a9--- /dev/null+++ b/plugins/power-pages/references/datamodel-manifest-schema.md@@ -0,0 +1,51 @@+# Data Model Manifest Schema++Shared reference for the `.datamodel-manifest.json` file format. This manifest is written by the `setup-datamodel` skill and read by `add-sample-data` and the `validate-datamodel.js` hook.++---++## Location++`<PROJECT_ROOT>/.datamodel-manifest.json`++## Schema++```json+{+ "environmentUrl": "https://org12345.crm.dynamics.com",+ "tables": [+ {+ "logicalName": "cr123_project",+ "displayName": "Project",+ "status": "new",+ "columns": [+ { "logicalName": "cr123_name", "type": "String" },+ { "logicalName": "cr123_description", "type": "Memo" },+ { "logicalName": "cr123_startdate", "type": "DateTime" },+ { "logicalName": "cr123_budget", "type": "Money" },+ { "logicalName": "cr123_isactive", "type": "Boolean" },+ { "logicalName": "cr123_status", "type": "Picklist" }+ ]+ }+ ]+}+```++## Fields++| Field | Type | Description |+|-------|------|-------------|+| `environmentUrl` | string | The Dataverse environment URL |+| `tables` | array | List of tables in the data model |+| `tables[].logicalName` | string | Dataverse logical name (e.g., `cr123_project`) |+| `tables[].displayName` | string | Human-readable display name |+| `tables[].status` | string | `new`, `modified`, or `reused` |+| `tables[].columns` | array | List of columns on the table |+| `tables[].columns[].logicalName` | string | Column logical name |+| `tables[].columns[].type` | string | Column type: `String`, `Memo`, `Integer`, `Decimal`, `Money`, `DateTime`, `Boolean`, `Picklist`, `Lookup` |++## Usage++- **Written by**: `setup-datamodel` skill (Step 8.3) — only includes tables and columns confirmed to exist+- **Read by**: `add-sample-data` skill (Step 2, Path A) — preferred source for table discovery+- **Validated by**: `validate-datamodel.js` hook — queries OData API to verify each table/column existsdiff --git a/plugins/power-pages/references/dataverse-prerequisites.md b/plugins/power-pages/references/dataverse-prerequisites.mdnew file mode 100644index 000000000..e87ffa9da--- /dev/null+++ b/plugins/power-pages/references/dataverse-prerequisites.md@@ -0,0 +1,42 @@+# Dataverse Prerequisites++Shared prerequisite steps for skills that interact with the Dataverse OData Web API. Used by `setup-datamodel`, `add-sample-data`, and any future skills that need Dataverse API access.++---++## 1. Check PAC CLI++Run `pac env who` to get the current environment URL:++```powershell+pac env who+```++Extract the `Environment URL` (e.g., `https://org12345.crm.dynamics.com`). Store as `$envUrl`.++**If `pac env who` fails**: Tell the user to authenticate first:++```powershell+pac auth create+```++## 2. Get Azure CLI Token++Get an access token for the Dataverse environment:++```powershell+$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+```++**If `az` fails**: Tell the user to run `az login` first.++## 3. Verify API Access++Make a lightweight test request to confirm the token works:++```powershell+$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }+Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/WhoAmI" -Headers $headers+```++If this returns a valid response, proceed. If it returns 401/403, the token is invalid — ask the user to re-authenticate.diff --git a/plugins/power-pages/references/framework-conventions.md b/plugins/power-pages/references/framework-conventions.mdnew file mode 100644index 000000000..4a826edae--- /dev/null+++ b/plugins/power-pages/references/framework-conventions.md@@ -0,0 +1,36 @@+# Framework Conventions++Shared reference for skills that need to detect the frontend framework and locate key files in a Power Pages code site. Used by `create-site`, `add-seo`, and any future skills that interact with the site project structure.++---++## Supported Frameworks++Only static SPA frameworks are supported. Server-rendered frameworks (Next.js, Nuxt.js, Remix, SvelteKit) are **not** supported.++## Framework Reference++| Framework | Build Tool | Router | Build Output | Public Directory | Index HTML |+|-----------|-----------|--------|--------------|-----------------|------------|+| React | Vite | react-router-dom | `dist` | `public/` | `index.html` (project root) |+| Vue | Vite | vue-router | `dist` | `public/` | `index.html` (project root) |+| Angular | Angular CLI | @angular/router | `dist/__SITE_NAME__/browser` | `public/` | `src/index.html` |+| Astro | Astro | File-based + View Transitions | `dist` | `public/` | `src/layouts/*.astro` or `src/pages/*.astro` |++## Framework Detection++Read `package.json` to determine the framework by checking dependencies:++- **React**: `react` and `react-dom` in dependencies+- **Vue**: `vue` in dependencies+- **Angular**: `@angular/core` in dependencies+- **Astro**: `astro` in dependencies++## Route Discovery++Scan the project router configuration to discover all existing page routes:++- **React**: Check `src/` for route definitions (react-router-dom)+- **Vue**: Check `src/router/` for vue-router config+- **Angular**: Check `src/app/` for Angular router config+- **Astro**: Scan `src/pages/` for file-based routesdiff --git a/plugins/power-pages/references/odata-common.md b/plugins/power-pages/references/odata-common.mdnew file mode 100644index 000000000..c477d8320--- /dev/null+++ b/plugins/power-pages/references/odata-common.md@@ -0,0 +1,104 @@+# OData Common Patterns++Shared reference for all skills that interact with the Dataverse OData Web API (v9.2). Covers authentication, token management, error handling, and retry logic.++---++## Authentication Header++All requests require the following headers:++```json+{+ "Authorization": "Bearer <token>",+ "Content-Type": "application/json",+ "Accept": "application/json",+ "OData-MaxVersion": "4.0",+ "OData-Version": "4.0"+}+```++PowerShell helper:++```powershell+$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+$headers = @{+ Authorization = "Bearer $token"+ "Content-Type" = "application/json"+ Accept = "application/json"+}+```++### Token Refresh++Azure CLI tokens expire after ~60 minutes. Refresh before each major step or every 20 records:++```powershell+$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+$headers["Authorization"] = "Bearer $token"+```++---++## Error Handling++### Common HTTP Status Codes++| Code | Meaning | Action |+|------|---------|--------|+| 200/204 | Success | Proceed |+| 400 | Bad request (malformed JSON, invalid field) | Fix the JSON body and retry |+| 401 | Unauthorized (token expired) | Refresh token and retry |+| 403 | Forbidden (insufficient privileges) | Inform user about permissions |+| 404 | Entity not found | Table/column/entity set doesn't exist — verify name and retry |+| 409 | Conflict (duplicate) | Table/column/record already exists — skip |+| 429 | Too many requests (throttled) | Wait 5 seconds, then retry |+| 500/502/503 | Server error | Wait 5 seconds, retry once, then report failure |++### Error Response Format++Dataverse OData errors follow this structure:++```json+{+ "error": {+ "code": "0x80060888",+ "message": "Entity 'cr123_project' already exists."+ }+}+```++Parse `error.message` for user-friendly reporting. Common error codes:++| Code | Meaning |+|------|---------|+| `0x80048408` | Privilege check failed |+| `0x80060888` | Entity already exists |+| `0x80044153` | Attribute already exists |+| `0x8004431A` | Relationship already exists |+| `0x80040237` | Record with matching key values already exists |++### Retry Pattern++For transient errors (401, 429, 5xx):++```powershell+$maxRetries = 2+for ($i = 0; $i -le $maxRetries; $i++) {+ try {+ $result = Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $body -ContentType "application/json"+ break+ } catch {+ $statusCode = $_.Exception.Response.StatusCode.value__+ if ($statusCode -eq 401) {+ # Refresh token and retry+ $token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+ $headers["Authorization"] = "Bearer $token"+ } elseif ($statusCode -in @(429, 500, 502, 503)) {+ Start-Sleep -Seconds 5+ } else {+ throw+ }+ }+}+```diff --git a/plugins/power-pages/references/skill-tracking-reference.md b/plugins/power-pages/references/skill-tracking-reference.mdnew file mode 100644index 000000000..0d0069289--- /dev/null+++ b/plugins/power-pages/references/skill-tracking-reference.md@@ -0,0 +1,49 @@+# Skill Usage Tracking++This document describes how to record skill usage in Power Pages code sites. Each skill invocation creates or updates site setting YAML files that track which AI skills were used, how many times, and which authoring tool invoked them.++Tracking only runs when `.powerpages-site/site-settings/` exists (site has been deployed at least once). The tracking settings get uploaded to Power Pages on the next deploy.++## How to Record Skill Usage++### Run the Tracking Script++Run the shared tracking script:++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/update-skill-tracking.js" --projectRoot "<PROJECT_ROOT>" --skillName "<PascalCaseName>" --authoringTool "<YourAgentName>"+```++- `--projectRoot`: The project root directory (containing `powerpages.config.json`)+- `--skillName`: The PascalCase skill name from the table below+- `--authoringTool`: Your agent name (e.g., `ClaudeCode`, `GitHubCopilot`). The script normalizes this value — any name containing "claude" becomes `ClaudeCode`, any name containing "github" or "copilot" becomes `GitHubCopilot`.++The script exits silently if `.powerpages-site/site-settings/` does not exist, so it is safe to call unconditionally.++## Skill Name Mapping++| Skill | PascalCase (`--skillName`) | Setting Name |+|-------|---------------------------|--------------|+| create-site | CreateSite | Site/AI/CreateSite |+| deploy-site | DeploySite | Site/AI/DeploySite |+| setup-datamodel | SetupDatamodel | Site/AI/SetupDatamodel |+| add-sample-data | AddSampleData | Site/AI/AddSampleData |+| activate-site | ActivateSite | Site/AI/ActivateSite |+| add-seo | AddSeo | Site/AI/AddSeo |+| create-webroles | CreateWebroles | Site/AI/CreateWebroles |+| integrate-webapi | IntegrateWebApi | Site/AI/IntegrateWebApi |+| setup-auth | SetupAuth | Site/AI/SetupAuth |++## YAML Format++The tracking script produces site setting files in code site git format (alphabetically sorted, unquoted values):++```yaml+description: Tracks usage count of the CreateSite skill+id: 778fa3d0-a2ef-4d2b-98b8-e6c7d8ce1444+name: Site/AI/CreateSite+value: 1+```++- **Skill counter** (`Site-AI-<SkillName>.sitesetting.yml`): Incremented each time the skill runs. The `id` is preserved across increments.+- **Authoring tool** (`Site-AI-AuthoringTool.sitesetting.yml`): Created once on first skill invocation. Subsequent runs preserve the original value.diff --git a/plugins/power-pages/references/webapi-core-client.md b/plugins/power-pages/references/webapi-core-client.mdnew file mode 100644index 000000000..c46c86782--- /dev/null+++ b/plugins/power-pages/references/webapi-core-client.md@@ -0,0 +1,426 @@+# Web API Core Client Template++This reference contains the complete `powerPagesApi.ts` template — the centralized Power Pages Web API client shared by all table services. Create this file at `src/shared/powerPagesApi.ts` (or reuse an existing one detected in Step 1.3).++Adapt imports and style to match the project's existing TypeScript conventions (semicolons, quotes, etc.).++## Complete File++```typescript+// src/shared/powerPagesApi.ts+// Centralized Power Pages Web API client with token management, retry logic, and OData helpers.++// ── Anti-Forgery Token ────────────────────────────────────────────────────────+// Power Pages Web API requires a __RequestVerificationToken header on every+// mutating request. The token is fetched from /_layout/tokenhtml and cached.+// No Authorization/Bearer header is needed — authenticated users get cookie-based+// session auth automatically.++const TOKEN_TTL_MS = 8 * 60 * 1000; // 8 min cache++let cachedAntiForgeryToken: string | null = null;+let cachedAntiForgeryTimestamp = 0;++const fetchAntiForgeryToken = async (): Promise<string> => {+ const now = Date.now();+ if (cachedAntiForgeryToken && now - cachedAntiForgeryTimestamp < TOKEN_TTL_MS) {+ return cachedAntiForgeryToken;+ }++ try {+ const response = await fetch('/_layout/tokenhtml', {});+ if (response.status !== 200) {+ throw new Error(`Failed to fetch token: ${response.status}`);+ }++ const tokenResponse = await response.text();+ const valueString = 'value="';+ const terminalString = '" />';+ const valueIndex = tokenResponse.indexOf(valueString);++ if (valueIndex === -1) {+ throw new Error('Token not found in response');+ }++ const token = tokenResponse.substring(+ valueIndex + valueString.length,+ tokenResponse.indexOf(terminalString, valueIndex)+ );++ cachedAntiForgeryToken = token || '';+ cachedAntiForgeryTimestamp = now;+ return cachedAntiForgeryToken;+ } catch (error) {+ console.warn('Failed to fetch anti-forgery token:', error);+ return '';+ }+};++// ── Header Builder ────────────────────────────────────────────────────────────++export const buildPowerPagesHeaders = async (+ incoming?: HeadersInit,+ options?: { accept?: string | null; contentType?: string | null; prefer?: string | null }+): Promise<Headers> => {+ const antiForgeryToken = await fetchAntiForgeryToken();+ const headers = new Headers({+ __RequestVerificationToken: antiForgeryToken,+ });++ if (options?.accept !== null) {+ headers.set('Accept', options?.accept ?? 'application/json');+ }+ if (options?.contentType !== null) {+ headers.set('Content-Type', options?.contentType ?? 'application/json');+ }+ if (options?.prefer !== null) {+ headers.set(+ 'Prefer',+ options?.prefer ?? 'odata.include-annotations="OData.Community.Display.V1.FormattedValue"'+ );+ }++ if (incoming) {+ const extra = new Headers(incoming);+ extra.forEach((value, key) => headers.set(key, value));+ }++ return headers;+};++// ── Response Parsing ──────────────────────────────────────────────────────────++export const parseResponseBody = async <T>(response: Response): Promise<T | null> => {+ if (response.status === 204 || response.status === 202) return null;++ const text = await response.text();+ if (!text || text.trim() === '') return null;++ try {+ return JSON.parse(text) as T;+ } catch {+ console.warn('Failed to parse response body as JSON');+ return null;+ }+};++// ── Create Response Helper ────────────────────────────────────────────────++/**+ * Extract the created record ID from a POST response.+ * Power Pages Web API may return the entity in the body (when Prefer: return=representation+ * is honored) or just a success status with the record URL in the Location header.+ */+export const extractRecordId = (response: Response): string | null => {+ const location = response.headers.get('Location') ?? response.headers.get('OData-EntityId');+ if (!location) return null;+ const match = location.match(/\(([0-9a-fA-F-]{36})\)/);+ return match ? match[1] : null;+};++// ── Retry Helpers ─────────────────────────────────────────────────────────────++const MAX_RETRIES = 3;+const INITIAL_RETRY_DELAY_MS = 1000;++const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>+ new Promise((resolve, reject) => {+ const timer = setTimeout(resolve, ms);+ signal?.addEventListener('abort', () => {+ clearTimeout(timer);+ reject(new DOMException('Aborted', 'AbortError'));+ });+ });++const isTransientError = (status: number): boolean =>+ status === 429 || (status >= 500 && status < 600);++// ── Core Fetch Wrapper ────────────────────────────────────────────────────────++export async function powerPagesFetch<T>(+ url: string,+ options?: RequestInit & { signal?: AbortSignal }+): Promise<T | null> {+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {+ const headers = await buildPowerPagesHeaders(options?.headers);++ const response = await fetch(url, { ...options, headers });++ // On 401, the user's session has expired — do not retry, prompt re-authentication+ if (response.status === 401) {+ throw new Error('Session expired. Please sign in again.');+ }++ // On 403, the anti-forgery token may have expired — refresh and retry+ if (response.status === 403 && attempt < MAX_RETRIES) {+ cachedAntiForgeryToken = null;+ continue;+ }++ if (isTransientError(response.status) && attempt < MAX_RETRIES) {+ const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt - 1);+ await sleep(delay, options?.signal);+ continue;+ }++ if (!response.ok) {+ let message = `Request failed with status ${response.status}`;+ try {+ const payload = await response.json();+ if (payload?.error?.message) message = payload.error.message;+ } catch { /* ignore parse errors */ }+ throw new Error(message);+ }++ return parseResponseBody<T>(response);+ }++ throw new Error('Max retries exceeded');+}++/**+ * Like powerPagesFetch but returns the raw Response object.+ * Useful when you need headers (e.g. OData-EntityId from POST).+ */+export async function powerPagesFetchResponse(+ url: string,+ options?: RequestInit & { signal?: AbortSignal }+): Promise<Response> {+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {+ const headers = await buildPowerPagesHeaders(options?.headers);++ const response = await fetch(url, { ...options, headers });++ // On 401, the user's session has expired — do not retry, prompt re-authentication+ if (response.status === 401) {+ throw new Error('Session expired. Please sign in again.');+ }++ // On 403, the anti-forgery token may have expired — refresh and retry+ if (response.status === 403 && attempt < MAX_RETRIES) {+ cachedAntiForgeryToken = null;+ continue;+ }++ if (isTransientError(response.status) && attempt < MAX_RETRIES) {+ const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt - 1);+ await sleep(delay, options?.signal);+ continue;+ }++ if (!response.ok) {+ let message = `Request failed with status ${response.status}`;+ try {+ const payload = await response.json();+ if (payload?.error?.message) message = payload.error.message;+ } catch { /* ignore */ }+ throw new Error(message);+ }++ return response;+ }++ throw new Error('Max retries exceeded');+}++// ── Web API Error Codes ──────────────────────────────────────────────────────+// These hex codes are returned by the Power Pages Web API on errors.+// Use them to provide specific error messages in the UI.++export const WebApiErrorCode = {+ ReadPermissionDenied: '90040120',+ WritePermissionDenied: '90040102',+ CreatePermissionDenied: '90040103',+ DeletePermissionDenied: '90040104',+ AppendPermissionDenied: '90040105',+ AppendToPermissionDenied: '90040106',+ AntiForgeryTokenInvalid: '90040107',+ ResourceNotFound: '9004010c',+ CdsError: '9004010d',+} as const;++/**+ * Parse the error code from a Web API error response.+ * Returns the hex code string (e.g., '90040120') or undefined.+ */+export const parseErrorCode = (error: unknown): string | undefined => {+ if (error && typeof error === 'object' && 'message' in error) {+ const msg = (error as Error).message;+ // The error code appears in the JSON: { error: { code: "90040120", message: "..." } }+ const match = msg.match(/[0-9a-f]{8}/i);+ return match?.[0]?.toLowerCase();+ }+ return undefined;+};++/**+ * Check if an error is a permission denied error (any CRUD operation).+ */+export const isPermissionError = (error: unknown): boolean => {+ const code = parseErrorCode(error);+ return code !== undefined && [+ WebApiErrorCode.ReadPermissionDenied,+ WebApiErrorCode.WritePermissionDenied,+ WebApiErrorCode.CreatePermissionDenied,+ WebApiErrorCode.DeletePermissionDenied,+ WebApiErrorCode.AppendPermissionDenied,+ WebApiErrorCode.AppendToPermissionDenied,+ ].includes(code as any);+};++// ── OData URL Builder ─────────────────────────────────────────────────────────++export const buildODataUrl = (+ entitySet: string,+ query?: Record<string, string | undefined>+): string => {+ if (!query) return `/_api/${entitySet}`;++ const parts: string[] = [];+ for (const [key, value] of Object.entries(query)) {+ if (value !== undefined && value !== null && value !== '') {+ const encoded = encodeURIComponent(value).replace(/%2C/g, ',');+ parts.push(`${key}=${encoded}`);+ }+ }++ return parts.length > 0 ? `/_api/${entitySet}?${parts.join('&')}` : `/_api/${entitySet}`;+};++export const escapeODataString = (value: string): string =>+ value.replace(/'/g, "''");++// ── OData Types ───────────────────────────────────────────────────────────────++export interface ODataCollectionResponse<T> {+ value: T[];+ '@odata.nextLink'?: string;+ '@odata.count'?: number;+}++export interface PaginatedResult<T> {+ items: T[];+ totalCount: number;+ nextLink?: string;+}++// ── Formatted Value Helper ────────────────────────────────────────────────────++/**+ * Extract a formatted value from an OData entity.+ * Formatted values are returned when the Prefer header includes+ * odata.include-annotations="OData.Community.Display.V1.FormattedValue".+ * Useful for option set labels and lookup display names.+ */+export const getFormattedValue = (+ record: Record<string, unknown>,+ logicalName: string+): string | undefined =>+ record[`${logicalName}@OData.Community.Display.V1.FormattedValue`] as string | undefined;++// ── Pagination Helper ─────────────────────────────────────────────────────────++const MAX_PAGINATION_ITERATIONS = 100;++export const fetchAllPages = async <T>(initialUrl: string): Promise<T[]> => {+ let nextUrl: string | undefined = initialUrl;+ const results: T[] = [];+ let iterations = 0;++ while (nextUrl) {+ if (++iterations > MAX_PAGINATION_ITERATIONS) {+ console.error('Exceeded maximum pagination iterations');+ break;+ }++ const response = await powerPagesFetch<ODataCollectionResponse<T>>(nextUrl);+ if (!response) break;++ results.push(...(response.value ?? []));+ nextUrl = response['@odata.nextLink'];+ }++ return results;+};++// ── Lookup Binding Helper ─────────────────────────────────────────────────────++/**+ * Set or clear a lookup relationship on a request body using @odata.bind.+ *+ * @param body - The request body object to modify+ * @param navigationProperty - The navigation property name (e.g., 'cr4fc_Category')+ * @param entitySetName - The target entity set (e.g., 'cr4fc_categories')+ * @param id - The target record ID. Pass null to unbind, undefined to skip.+ */+export const bindLookup = (+ body: Record<string, unknown>,+ navigationProperty: string,+ entitySetName: string,+ id?: string | null+): void => {+ if (id === null) {+ body[`${navigationProperty}@odata.bind`] = null;+ } else if (id) {+ body[`${navigationProperty}@odata.bind`] = `/${entitySetName}(${id})`;+ }+};++// ── File Column Helpers ───────────────────────────────────────────────────────++/**+ * Download a file or image column value as an object URL.+ * Returns null if no file is stored (404).+ */+export const fetchFileColumnUrl = async (+ table: string,+ recordId: string,+ column: string+): Promise<string | null> => {+ const headers = await buildPowerPagesHeaders(undefined, {+ accept: '*/*',+ contentType: null,+ prefer: null,+ });++ const response = await fetch(`/_api/${table}(${recordId})/${column}/$value`, { headers });++ if (response.status === 404) return null;+ if (!response.ok) throw new Error(`File download failed: ${response.status}`);++ const blob = await response.blob();+ return URL.createObjectURL(blob);+};++/**+ * Upload a file or image to a file column.+ * Note: Upload uses the column URL directly (no /$value), unlike download.+ */+export const uploadFileColumn = async (+ table: string,+ recordId: string,+ column: string,+ file: Blob,+ fileName?: string+): Promise<void> => {+ const headers = await buildPowerPagesHeaders(+ {+ 'If-Match': '*',+ ...(fileName ? { 'x-ms-file-name': fileName } : {}),+ },+ {+ accept: 'application/json',+ contentType: file.type || 'application/octet-stream',+ prefer: null,+ }+ );++ const response = await fetch(`/_api/${table}(${recordId})/${column}`, {+ method: 'PATCH',+ headers,+ body: await file.arrayBuffer(),+ });++ if (!response.ok) throw new Error(`File upload failed: ${response.status}`);+};+```diff --git a/plugins/power-pages/references/webapi-service-patterns.md b/plugins/power-pages/references/webapi-service-patterns.mdnew file mode 100644index 000000000..ad36b5d8c--- /dev/null+++ b/plugins/power-pages/references/webapi-service-patterns.md@@ -0,0 +1,683 @@+# Web API Service Patterns++This reference contains the code-generation patterns for entity types (Step 4), service layer (Step 5), and framework hooks (Step 6). All examples use the `Product` table as reference — replace table names, columns, entity set, and prefix with the actual target table.++---++## Entity Types (Step 4)++### OData Entity Interface++Define an interface matching the raw Dataverse column schema:++```typescript+// Raw OData entity — matches Dataverse column logical names exactly+export interface ProductEntity {+ cr4fc_productid: string;+ cr4fc_name?: string;+ cr4fc_description?: string;+ cr4fc_price?: number;+ cr4fc_status?: number;+ cr4fc_imageurl?: string;+ // Lookup raw values use _<navigation>_value pattern+ _cr4fc_category_value?: string;+ // Expanded navigation properties+ cr4fc_Category?: { cr4fc_categoryid: string; cr4fc_name?: string };+ createdon?: string;+ modifiedon?: string;+ // Index signature for OData formatted value annotations+ [key: string]: unknown;+}+```++**Naming rules:**+- Interface: PascalCase table name + `Entity` suffix+- Properties: exact Dataverse logical names (all lowercase with publisher prefix)+- Lookup raw values: `_<navigation_property>_value`+- Expanded lookups: PascalCase navigation property with nested object type+- Always include `[key: string]: unknown` for formatted value annotation access++### Domain Type++Define a clean application type that the UI consumes:++```typescript+// Clean domain type for UI consumption+export interface Product {+ id: string;+ name: string;+ description: string;+ price: number;+ status: 'active' | 'inactive' | 'archived';+ imageUrl: string;+ category: string;+ categoryId?: string;+ createdAt: string;+ updatedAt: string;+}+```++### Option Set Constants++If the table has choice/optionset columns, define typed constants:++```typescript+export const PRODUCT_STATUS = {+ active: 100000000,+ inactive: 100000001,+ archived: 100000002,+} as const;++export type ProductStatusKey = keyof typeof PRODUCT_STATUS;++const STATUS_LABELS = Object.fromEntries(+ Object.entries(PRODUCT_STATUS).map(([key, val]) => [val, key])+) as Record<number, ProductStatusKey>;+```++### Input Types++Define create/update input types that represent what the caller provides:++```typescript+export interface CreateProductInput {+ name: string;+ description?: string;+ price: number;+ status?: ProductStatusKey;+ imageUrl?: string;+ categoryId?: string;+}++export interface UpdateProductInput {+ name?: string;+ description?: string;+ price?: number;+ status?: ProductStatusKey;+ imageUrl?: string;+ categoryId?: string;+}+```++### Entity-to-Domain Mapper++Create a mapping function that converts the raw OData entity to the clean domain type:++```typescript+import { getFormattedValue } from '../shared/powerPagesApi';++export const mapProductEntity = (entity: ProductEntity): Product => ({+ id: entity.cr4fc_productid,+ name: entity.cr4fc_name ?? '',+ description: entity.cr4fc_description ?? '',+ price: entity.cr4fc_price ?? 0,+ status: STATUS_LABELS[entity.cr4fc_status ?? 0] ?? 'active',+ imageUrl: entity.cr4fc_imageurl ?? '',+ category: getFormattedValue(entity, '_cr4fc_category_value') ?? 'Uncategorized',+ categoryId: entity._cr4fc_category_value,+ createdAt: entity.createdon ?? new Date().toISOString(),+ updatedAt: entity.modifiedon ?? entity.createdon ?? new Date().toISOString(),+});+```++Use `getFormattedValue()` for lookup display names and option set labels — these come from the `Prefer: odata.include-annotations` header.++### Lookup Property Rules++Lookups in Dataverse expose **two distinct properties**. Understanding the difference is critical:++**On retrieval (GET):**+- **GUID property** — Automatically named `_{logicalname}_value`. Contains the raw lookup ID. Use for filtering, logic, and foreign-key references. Include in `$select`.+- **Navigation property** — Named after the relationship (e.g., `cr4fc_Category`). Use with `$expand` to fetch related record details. **Case-sensitive** — must match the schema name exactly (typically PascalCase).++```typescript+// $select includes the GUID property for the raw ID+'$select': '_{prefix}_categoryid_value,{prefix}_name'+// $expand uses the Navigation Property to get related data+'$expand': '{prefix}_Category($select={prefix}_categoryid,{prefix}_name)'+// $filter uses the GUID property+'$filter': `_{prefix}_categoryid_value eq ${categoryId}`+```++**On create/update (POST/PATCH):**+- You **cannot** set a lookup by sending a GUID to the `_value` property. You **must** use `@odata.bind` on the **Navigation Property**.+- Syntax: `"[email protected]": "/entity_set_name(GUID)"`++```typescript+// CORRECT — uses Navigation Property name (case-sensitive)+body['[email protected]'] = `/cr4fc_categories(${categoryId})`;++// WRONG — using the GUID property name causes "Undeclared Property" error+body['_cr4fc_categoryid_value'] = categoryId; // ❌ Does NOT work+```++**Common error:** If you get an "Undeclared Property" error on POST/PATCH, you are likely using the logical name (all lowercase) instead of the **Navigation Property name** (case-sensitive, matches the schema name).++**To clear a lookup**, set the `@odata.bind` annotation to `null`:++```typescript+body['[email protected]'] = null; // unbinds the relationship+```++---++## Service Layer (Step 5)++Create a service module with CRUD operations for the target table. Place it following project conventions. Default: `src/shared/services/<tableName>Service.ts`.++### Pagination Strategy++**Every list/query operation MUST be paginated.** Never fetch unbounded data. Two pagination approaches exist — choose based on the use case:++**Cursor-based pagination (`$top` + `@odata.nextLink`)** — Use for UI list views with paging controls. The `list` function below uses this approach. Always include `$count=true` to get the total record count efficiently without fetching all rows. **Note:** Dataverse Web API does **not** support the `$skip` query option. Use `@odata.nextLink` from each response to fetch the next page.++**Client-side pagination (`fetchAllPages`)** — Use only when you genuinely need every record (e.g., populating a local dropdown, building a lookup map, exporting data). Uses the `fetchAllPages` helper from the core API client which follows `@odata.nextLink` with a safety iteration limit.++**Never omit `$top`.** An API call without `$top` returns the server's default page size (typically 5000 records). Always set an explicit `$top` to control payload size.++### Select Columns++Always specify exact columns in `$select`. Never use `*`. Only include columns the site actually needs:++```typescript+const PRODUCT_SELECT = [+ 'cr4fc_productid',+ 'cr4fc_name',+ 'cr4fc_description',+ 'cr4fc_price',+ 'cr4fc_status',+ 'cr4fc_imageurl',+ '_cr4fc_category_value', // Lookup GUID — use for filtering/logic+ 'createdon',+ 'modifiedon',+].join(',');++// Expand uses the Navigation Property (case-sensitive) to fetch related record+const PRODUCT_EXPAND = 'cr4fc_Category($select=cr4fc_categoryid,cr4fc_name)';+```++### List (with pagination and filtering)++```typescript+import {+ powerPagesFetch,+ buildODataUrl,+ escapeODataString,+ type ODataCollectionResponse,+ type PaginatedResult,+} from '../shared/powerPagesApi';++export interface ListParams {+ pageSize?: number;+ nextLink?: string; // @odata.nextLink cursor from a previous response+ filter?: string;+ orderBy?: string;+ search?: string;+}++export const listProducts = async (params?: ListParams): Promise<PaginatedResult<Product>> => {+ const pageSize = params?.pageSize ?? 10;++ // If we have a nextLink from a previous response, use it directly.+ // Dataverse does NOT support $skip — pagination uses @odata.nextLink cursors.+ const url = params?.nextLink ?? buildODataUrl('cr4fc_products', {+ '$select': PRODUCT_SELECT,+ '$expand': PRODUCT_EXPAND,+ '$orderby': params?.orderBy ?? 'createdon desc',+ '$count': 'true',+ '$top': String(pageSize),+ '$filter': params?.filter,+ });++ const response = await powerPagesFetch<ODataCollectionResponse<ProductEntity>>(url);++ return {+ items: (response?.value ?? []).map(mapProductEntity),+ totalCount: response?.['@odata.count'] ?? response?.value?.length ?? 0,+ nextLink: response?.['@odata.nextLink'],+ };+};+```++### Get by ID++```typescript+export const getProductById = async (id: string): Promise<Product | null> => {+ const url = buildODataUrl(`cr4fc_products(${id})`, {+ '$select': PRODUCT_SELECT,+ '$expand': PRODUCT_EXPAND,+ });++ try {+ const entity = await powerPagesFetch<ProductEntity>(url);+ return entity ? mapProductEntity(entity) : null;+ } catch {+ return null;+ }+};+```++### Create (POST)++Send `Prefer: return=representation` to request the created entity in the response body. However, the API may return just a success status (e.g., 204) without a body — in that case, extract the created record ID from the `Location` response header and fetch the record:++```typescript+import {+ powerPagesFetchResponse,+ parseResponseBody,+ extractRecordId,+} from '../shared/powerPagesApi';++export const createProduct = async (payload: CreateProductInput): Promise<Product> => {+ const body: Record<string, unknown> = {+ cr4fc_name: payload.name,+ cr4fc_description: payload.description ?? '',+ cr4fc_price: payload.price,+ cr4fc_status: PRODUCT_STATUS[payload.status ?? 'active'],+ cr4fc_imageurl: payload.imageUrl ?? '',+ };++ // Bind lookups using @odata.bind+ if (payload.categoryId) {+ body['[email protected]'] = `/cr4fc_categories(${payload.categoryId})`;+ }++ // Use powerPagesFetchResponse to access headers — the API may return the+ // created entity in the body or just a success status with a Location header+ const response = await powerPagesFetchResponse('/_api/cr4fc_products', {+ method: 'POST',+ headers: { Prefer: 'return=representation' },+ body: JSON.stringify(body),+ });++ // Try to parse the entity from the response body+ const entity = await parseResponseBody<ProductEntity>(response);+ if (entity) return mapProductEntity(entity);++ // No body — extract the ID from the Location header and fetch the record+ const createdId = extractRecordId(response);+ if (createdId) {+ const created = await getProductById(createdId);+ if (created) return created;+ }++ throw new Error('Failed to retrieve created record — no response body or Location header');+};+```++### Update (PATCH)++Use `If-Match: *` header. Only include fields that are being updated. Refetch after PATCH since it returns no body:++```typescript+export const updateProduct = async (id: string, payload: UpdateProductInput): Promise<Product> => {+ const body: Record<string, unknown> = {};++ if (payload.name !== undefined) body.cr4fc_name = payload.name;+ if (payload.description !== undefined) body.cr4fc_description = payload.description;+ if (payload.price !== undefined) body.cr4fc_price = payload.price;+ if (payload.status !== undefined) body.cr4fc_status = PRODUCT_STATUS[payload.status];+ if (payload.imageUrl !== undefined) body.cr4fc_imageurl = payload.imageUrl;++ // Handle lookup bind/unbind+ if (payload.categoryId !== undefined) {+ if (payload.categoryId) {+ body['[email protected]'] = `/cr4fc_categories(${payload.categoryId})`;+ } else {+ body['[email protected]'] = null; // unbind+ }+ }++ await powerPagesFetch(`/_api/cr4fc_products(${id})`, {+ method: 'PATCH',+ headers: { 'If-Match': '*' },+ body: JSON.stringify(body),+ });++ const updated = await getProductById(id);+ if (!updated) throw new Error('Failed to fetch updated record');+ return updated;+};+```++### Delete (DELETE)++```typescript+export const deleteProduct = async (id: string): Promise<void> => {+ await powerPagesFetch(`/_api/cr4fc_products(${id})`, {+ method: 'DELETE',+ });+};+```++### Many-to-Many Relationship Sync++If the table has M:N relationships via a junction table (e.g., blog posts ↔ tags), implement a sync function that diffs current vs desired associations:++```typescript+export const syncProductTags = async (productId: string, tagIds: string[]): Promise<void> => {+ // 1. Fetch existing junction records+ const existing = await powerPagesFetch<ODataCollectionResponse<{+ cr4fc_product_tagid: string;+ _cr4fc_tag_value: string;+ }>>(+ buildODataUrl('cr4fc_product_tags', {+ '$select': 'cr4fc_product_tagid,_cr4fc_tag_value',+ '$filter': `_cr4fc_product_value eq ${productId}`,+ })+ );+ const existingTagIds = new Set(existing?.value.map(l => l._cr4fc_tag_value) ?? []);+ const targetTagIds = new Set(tagIds);++ // 2. Add new associations+ for (const tagId of targetTagIds) {+ if (!existingTagIds.has(tagId)) {+ await powerPagesFetch('/_api/cr4fc_product_tags', {+ method: 'POST',+ body: JSON.stringify({+ '[email protected]': `/cr4fc_products(${productId})`,+ '[email protected]': `/cr4fc_tags(${tagId})`,+ }),+ });+ }+ }++ // 3. Remove obsolete associations+ for (const link of existing?.value ?? []) {+ if (!targetTagIds.has(link._cr4fc_tag_value)) {+ await powerPagesFetch(`/_api/cr4fc_product_tags(${link.cr4fc_product_tagid})`, {+ method: 'DELETE',+ });+ }+ }+};+```++Only create this function if the target table actually has M:N relationships.++### Count Helper++Use `$count=true` with a minimal `$select` for efficient record counting:++```typescript+export const getProductCount = async (filter?: string): Promise<number> => {+ const url = buildODataUrl('cr4fc_products', {+ '$select': 'cr4fc_productid',+ '$filter': filter,+ '$count': 'true',+ '$top': '0', // Don't fetch records, just the count+ });++ const response = await powerPagesFetch<ODataCollectionResponse<ProductEntity>>(url);+ return response?.['@odata.count'] ?? 0;+};+```++### Aggregation Queries (`$apply`)++If the site needs aggregate data (totals, averages, grouped counts), use the OData `$apply` query option. Power Pages Web API supports `$apply` with `groupby`, `aggregate`, and `filter` transformations.++**Count by group:**++```typescript+export const getProductCountByStatus = async (): Promise<Array<{ status: number; statusLabel: string; count: number }>> => {+ const url = buildODataUrl('cr4fc_products', {+ '$apply': 'groupby((cr4fc_status),aggregate($count as count))',+ });++ const response = await powerPagesFetch<ODataCollectionResponse<Record<string, unknown>>>(url);+ return (response?.value ?? []).map(row => ({+ status: row['cr4fc_status'] as number,+ statusLabel: getFormattedValue(row, 'cr4fc_status') ?? String(row['cr4fc_status']),+ count: row['count'] as number,+ }));+};+```++**Sum/average:**++```typescript+export const getProductPriceStats = async (): Promise<{ total: number; avg: number }> => {+ const url = buildODataUrl('cr4fc_products', {+ '$apply': 'aggregate(cr4fc_price with sum as total,cr4fc_price with average as avg)',+ });++ const response = await powerPagesFetch<ODataCollectionResponse<Record<string, unknown>>>(url);+ const row = response?.value?.[0];+ return { total: (row?.['total'] as number) ?? 0, avg: (row?.['avg'] as number) ?? 0 };+};+```++Only create aggregation helpers if the site's UI actually needs them (dashboards, summary cards, charts).++### File & Image Column Operations++If the target table has **File** or **Image** columns, add download, upload, and delete methods to the service. These use the `fetchFileColumnUrl` and `uploadFileColumn` helpers from the core API client.++**Download** — returns an object URL for the blob, or `null` if no file exists (404):++```typescript+import { fetchFileColumnUrl, uploadFileColumn } from '../shared/powerPagesApi';++export const downloadProductPhoto = async (id: string): Promise<string | null> => {+ return fetchFileColumnUrl('cr4fc_products', id, 'cr4fc_photo');+};+```++**Upload** — sends raw binary via PATCH. Body is `ArrayBuffer`, not JSON:++```typescript+export const uploadProductPhoto = async (+ id: string,+ file: Blob,+ fileName?: string+): Promise<void> => {+ await uploadFileColumn('cr4fc_products', id, 'cr4fc_photo', file, fileName);+};+```++**Delete** — removes the file from the column without deleting the record:++```typescript+export const deleteProductPhoto = async (id: string): Promise<void> => {+ await powerPagesFetch(`/_api/cr4fc_products(${id})/cr4fc_photo`, {+ method: 'DELETE',+ headers: { 'If-Match': '*' },+ });+};+```++Only create these methods if the target table actually has File or Image columns (check the data model manifest for column types `File` or `Image`).++**Common pitfalls with file columns:**++| Mistake | Symptom | Fix |+|---------|---------|-----|+| Using `/$value` on upload URL | `405 Method Not Allowed` | Upload to `/_api/table(id)/column` (no `/$value`) |+| Sending JSON body for upload | `400 Bad Request` | Send `ArrayBuffer` via `file.arrayBuffer()` |+| Missing `If-Match: *` on upload | `412 Precondition Failed` | Add `If-Match: *` header |+| Using `$select` on `/$value` URL | `400 Bad Request` | OData query options are not supported on `/$value` |+| Missing `x-ms-file-name` header | File saved without name/extension | Include `x-ms-file-name` header with filename |+| Using `Accept: application/json` for download | Empty or error response | Use `Accept: */*` for blob downloads |++---++## Framework Hooks (Step 6)++Create framework-specific hooks, composables, or services based on the detected framework (from Step 1.1). These provide the reactive data-fetching layer that components will consume.++### React — Custom Hook++Create in `src/shared/hooks/` or `src/hooks/` (match existing convention):++```typescript+import { useState, useEffect, useCallback } from 'react';++export function useProducts(params?: ListParams) {+ const [data, setData] = useState<PaginatedResult<Product>>({+ items: [],+ totalCount: 0,+ });+ const [isLoading, setIsLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ const fetchData = useCallback(async (overrides?: Partial<ListParams>) => {+ setIsLoading(true);+ setError(null);+ try {+ const result = await listProducts({ ...params, ...overrides });+ setData(result);+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Failed to fetch data');+ } finally {+ setIsLoading(false);+ }+ }, [params?.pageSize, params?.filter, params?.orderBy]);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ const fetchNextPage = useCallback(() => {+ if (data.nextLink) fetchData({ nextLink: data.nextLink });+ }, [data.nextLink, fetchData]);++ return { ...data, isLoading, error, refetch: fetchData, fetchNextPage };+}+```++### React — DataverseImage Component++If the table has File or Image columns, create a reusable component for rendering Dataverse images. Handles loading states, fallbacks, and cleanup of object URLs:++```tsx+import { useState, useEffect } from 'react';+import { fetchFileColumnUrl } from '../shared/powerPagesApi';++interface DataverseImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {+ table: string; // Entity set name (e.g., 'cr4fc_products')+ recordId: string; // GUID of the record+ column: string; // File/image column logical name+ fallbackSrc?: string; // Fallback image URL if no file exists+ hasFile?: boolean; // Whether the record has a file (skip fetch if false)+}++function DataverseImage({+ table,+ recordId,+ column,+ fallbackSrc = '',+ hasFile = true,+ ...imgProps+}: DataverseImageProps) {+ const [src, setSrc] = useState(fallbackSrc);+ const [isLoading, setIsLoading] = useState(false);++ useEffect(() => {+ if (!hasFile) {+ if (fallbackSrc) setSrc(fallbackSrc);+ return;+ }++ let active = true;+ const loadImage = async () => {+ setIsLoading(true);+ try {+ const url = await fetchFileColumnUrl(table, recordId, column);+ if (active && url) setSrc(url);+ } catch (error) {+ console.warn('[DataverseImage] Failed to load image:', error);+ } finally {+ if (active) setIsLoading(false);+ }+ };++ loadImage();+ return () => { active = false; };+ }, [table, recordId, column, hasFile, fallbackSrc]);++ return <img src={src} {...imgProps} />;+}+```++Usage:+```tsx+<DataverseImage+ table="cr4fc_products"+ recordId={product.id}+ column="cr4fc_photo"+ fallbackSrc="/images/placeholder.png"+ hasFile={!!product.hasPhoto}+ alt={product.name}+ className="product-image"+/>+```++Only create this component if the table has image columns that need rendering in the UI.++### Vue — Composable++Create in `src/composables/`:++```typescript+import { ref, watch, type Ref } from 'vue';++export function useProducts(params?: Ref<ListParams | undefined>) {+ const items = ref<Product[]>([]);+ const totalCount = ref(0);+ const nextLink = ref<string | undefined>();+ const isLoading = ref(true);+ const error = ref<string | null>(null);++ const fetchData = async (overrides?: Partial<ListParams>) => {+ isLoading.value = true;+ error.value = null;+ try {+ const result = await listProducts({ ...params?.value, ...overrides });+ items.value = result.items;+ totalCount.value = result.totalCount;+ nextLink.value = result.nextLink;+ } catch (err) {+ error.value = err instanceof Error ? err.message : 'Failed to fetch data';+ } finally {+ isLoading.value = false;+ }+ };++ const fetchNextPage = () => {+ if (nextLink.value) fetchData({ nextLink: nextLink.value });+ };++ watch(params ?? ref(undefined), () => fetchData(), { immediate: true });++ return { items, totalCount, nextLink, isLoading, error, refetch: fetchData, fetchNextPage };+}+```++### Angular — Injectable Service++Create in `src/app/services/`:++```typescript+import { Injectable } from '@angular/core';++@Injectable({ providedIn: 'root' })+export class ProductApiService {+ list(params?: ListParams) { return listProducts(params); }+ getById(id: string) { return getProductById(id); }+ create(payload: CreateProductInput) { return createProduct(payload); }+ update(id: string, payload: UpdateProductInput) { return updateProduct(id, payload); }+ delete(id: string) { return deleteProduct(id); }+}+```++### Astro — Direct Import++For Astro, Web API calls only work client-side. Import the service in `<script>` tags or framework island components:++```astro+<script>+ import { listProducts } from '../shared/services/productService';+ // Client-side data fetching+</script>+```diff --git a/plugins/power-pages/scripts/generate-uuid.js b/plugins/power-pages/scripts/generate-uuid.jsnew file mode 100644index 000000000..883637628--- /dev/null+++ b/plugins/power-pages/scripts/generate-uuid.js@@ -0,0 +1,16 @@+#!/usr/bin/env node++// Generates a random UUID v4.+// Output: a UUID string like "778fa3d0-a2ef-4d2b-98b8-e6c7d8ce1444"+// Self-contained — no external dependencies required.++const { randomBytes } = require('crypto');++const bytes = randomBytes(16);+// Set version (4) and variant (RFC 4122) bits+bytes[6] = (bytes[6] & 0x0f) | 0x40;+bytes[8] = (bytes[8] & 0x3f) | 0x80;++const hex = bytes.toString('hex');+const uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;+process.stdout.write(uuid);diff --git a/plugins/power-pages/scripts/launch-playwright-mcp.js b/plugins/power-pages/scripts/launch-playwright-mcp.jsnew file mode 100644index 000000000..cef9017a3--- /dev/null+++ b/plugins/power-pages/scripts/launch-playwright-mcp.js@@ -0,0 +1,78 @@+#!/usr/bin/env node++// Launches the Playwright MCP server with the best available browser.+// Detects system-installed Chromium-based browsers in preference order,+// then falls back to Playwright's bundled Chromium.+// Self-contained — no external dependencies required.++const { execSync, spawn } = require('child_process');+const fs = require('fs');+const path = require('path');+const os = require('os');++function exists(filePath) {+ try { return fs.existsSync(filePath); } catch { return false; }+}++function whichExists(cmd) {+ try {+ execSync(`which ${cmd}`, { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+}++function detectBrowser() {+ const platform = os.platform();++ if (platform === 'win32') {+ const localAppData = process.env.LOCALAPPDATA || '';+ const programFiles = process.env.PROGRAMFILES || '';+ const programFilesX86 = process.env['PROGRAMFILES(X86)'] || '';++ // Edge — pre-installed on all Windows 10/11 machines+ const edgePaths = [+ path.join(programFilesX86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),+ path.join(programFiles, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),+ path.join(localAppData, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),+ ];+ for (const p of edgePaths) {+ if (exists(p)) return 'msedge';+ }++ // Chrome+ const chromePaths = [+ path.join(localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe'),+ path.join(programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'),+ path.join(programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'),+ ];+ for (const p of chromePaths) {+ if (exists(p)) return 'chrome';+ }+ } else if (platform === 'darwin') {+ // macOS+ if (exists('/Applications/Google Chrome.app')) return 'chrome';+ if (exists('/Applications/Microsoft Edge.app')) return 'msedge';+ } else {+ // Linux+ if (whichExists('google-chrome')) return 'chrome';+ if (whichExists('google-chrome-stable')) return 'chrome';+ if (whichExists('microsoft-edge')) return 'msedge';+ if (whichExists('microsoft-edge-stable')) return 'msedge';+ if (whichExists('chromium-browser')) return 'chromium';+ if (whichExists('chromium')) return 'chromium';+ }++ // Fallback: Playwright's bundled Chromium (requires `npx playwright install chromium`)+ return 'chromium';+}++const browser = detectBrowser();+const configPath = path.join(__dirname, 'playwright-mcp-config.json');+const child = spawn('npx', ['@playwright/mcp@latest', '--browser', browser, '--config', configPath], {+ stdio: 'inherit',+ shell: true,+});++child.on('exit', (code) => process.exit(code || 0));diff --git a/plugins/power-pages/scripts/lib/validation-helpers.js b/plugins/power-pages/scripts/lib/validation-helpers.jsnew file mode 100644index 000000000..0e0a3717b--- /dev/null+++ b/plugins/power-pages/scripts/lib/validation-helpers.js@@ -0,0 +1,150 @@+#!/usr/bin/env node++// Shared utilities for Power Pages validation hook scripts.+// Provides common boilerplate so each validator only contains its unique logic.++const fs = require('fs');+const path = require('path');+const { execSync } = require('child_process');++// Exit 0 = success (allow). Exit 2 = blocking error (stderr is fed back to Claude).+const approve = () => { process.exit(0); };+const block = (reason) => {+ process.stderr.write(reason);+ process.exit(2);+};++/**+ * Wraps stdin JSON parsing and try/catch boilerplate.+ * Calls `callback(cwd)` with the parsed working directory.+ * Approves automatically if cwd is missing or on any uncaught error.+ */+function runValidation(callback) {+ let inputData = '';+ process.stdin.on('data', chunk => (inputData += chunk));+ process.stdin.on('end', () => {+ try {+ const input = JSON.parse(inputData);+ const cwd = input.cwd;+ if (!cwd) approve();+ callback(cwd);+ } catch {+ approve();+ }+ });+}++/**+ * Searches for a file or directory in `dir` and one level of subdirectories.+ * @param {string} dir - Starting directory+ * @param {string} target - Relative path to look for (e.g. 'powerpages.config.json')+ * @returns {string|null} Full path if found, null otherwise+ */+function findPath(dir, target) {+ const direct = path.join(dir, target);+ if (fs.existsSync(direct)) return direct;++ try {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ if (entry.isDirectory() && entry.name !== 'node_modules' && entry.name !== '.git') {+ const sub = path.join(dir, entry.name, target);+ if (fs.existsSync(sub)) return sub;+ }+ }+ } catch {}++ return null;+}++/**+ * Finds the project root directory (containing powerpages.config.json).+ * @returns {string|null} Project root path, or null+ */+function findProjectRoot(dir) {+ const configPath = findPath(dir, 'powerpages.config.json');+ return configPath ? path.dirname(configPath) : null;+}++/**+ * Finds a subdirectory inside .powerpages-site/.+ * @param {string} dir - Starting directory+ * @param {string} subdir - Subdirectory name (e.g. 'site-settings', 'web-roles')+ * @returns {string|null} Full path to the subdirectory, or null+ */+function findPowerPagesSiteDir(dir, subdir) {+ return findPath(dir, path.join('.powerpages-site', subdir));+}++/** UUID v4 validation regex */+const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/**+ * Gets an Azure CLI access token for the given resource URL.+ * @returns {string|null} Access token, or null if unavailable+ */+function getAuthToken(resourceUrl) {+ try {+ return execSync(+ `az account get-access-token --resource "${resourceUrl}" --query accessToken -o tsv`,+ { encoding: 'utf8', timeout: 15000 }+ ).trim();+ } catch {+ return null;+ }+}++/**+ * Gets the environment URL from `pac env who`.+ * @returns {string|null} Environment URL, or null+ */+function getEnvironmentUrl() {+ try {+ const output = execSync('pac env who', { encoding: 'utf8', timeout: 15000 });+ const match = output.match(/Environment URL:\s*(https:\/\/[^\s]+)/i);+ return match ? match[1].replace(/\/+$/, '') : null;+ } catch {+ return null;+ }+}++/**+ * Gets PAC CLI auth info (environment ID and cloud).+ * @returns {{ environmentId: string, cloud: string }|null}+ */+function getPacAuthInfo() {+ try {+ const output = execSync('pac auth who', { encoding: 'utf8', timeout: 15000 });+ const envMatch = output.match(/Environment ID:\s*([0-9a-fA-F-]+)/i);+ const cloudMatch = output.match(/Cloud:\s*(\S+)/i);+ if (!envMatch) return null;+ return {+ environmentId: envMatch[1],+ cloud: cloudMatch ? cloudMatch[1] : 'Public',+ };+ } catch {+ return null;+ }+}++/** Cloud → Power Platform API base URL mapping */+const CLOUD_TO_API = {+ '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',+};++module.exports = {+ approve,+ block,+ runValidation,+ findPath,+ findProjectRoot,+ findPowerPagesSiteDir,+ UUID_REGEX,+ getAuthToken,+ getEnvironmentUrl,+ getPacAuthInfo,+ CLOUD_TO_API,+};diff --git a/plugins/power-pages/scripts/playwright-mcp-config.json b/plugins/power-pages/scripts/playwright-mcp-config.jsonnew file mode 100644index 000000000..bed28861b--- /dev/null+++ b/plugins/power-pages/scripts/playwright-mcp-config.json@@ -0,0 +1,10 @@+{+ "browser": {+ "launchOptions": {+ "args": ["--start-maximized"]+ },+ "contextOptions": {+ "viewport": null+ }+ }+}diff --git a/plugins/power-pages/scripts/update-skill-tracking.js b/plugins/power-pages/scripts/update-skill-tracking.jsnew file mode 100644index 000000000..336a68aed--- /dev/null+++ b/plugins/power-pages/scripts/update-skill-tracking.js@@ -0,0 +1,117 @@+#!/usr/bin/env node++// Updates skill usage tracking site settings for Power Pages code sites.+// Creates/increments a per-skill counter and records the authoring tool.+// Self-contained — no external dependencies required.+//+// Usage:+// node update-skill-tracking.js --projectRoot <path> --skillName <PascalCase> --authoringTool <value>+//+// Exits silently (code 0) if .powerpages-site/site-settings/ does not exist.++const fs = require('fs');+const path = require('path');+const { randomBytes } = require('crypto');++// --- CLI arg parsing ---++const args = process.argv.slice(2);+function getArg(name) {+ const idx = args.indexOf(`--${name}`);+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;+}++const projectRoot = getArg('projectRoot');+const skillName = getArg('skillName');+const authoringTool = getArg('authoringTool');++if (!projectRoot || !skillName || !authoringTool) {+ console.error('Usage: node update-skill-tracking.js --projectRoot <path> --skillName <PascalCase> --authoringTool <value>');+ process.exit(1);+}++// --- Normalize authoring tool name to PascalCase ---++function normalizeAuthoringTool(raw) {+ const lower = raw.toLowerCase();+ if (lower.includes('claude')) return 'ClaudeCode';+ if (lower.includes('github') || lower.includes('copilot')) return 'GitHubCopilot';+ return raw;+}++const normalizedAuthoringTool = normalizeAuthoringTool(authoringTool);++// --- Check for site-settings directory ---++const siteSettingsDir = path.join(projectRoot, '.powerpages-site', 'site-settings');+if (!fs.existsSync(siteSettingsDir)) {+ // Site has not been deployed yet — nothing to do+ process.exit(0);+}++// --- Helpers ---++function generateUuid() {+ const bytes = randomBytes(16);+ bytes[6] = (bytes[6] & 0x0f) | 0x40;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;+ const hex = bytes.toString('hex');+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;+}++function parseYaml(content) {+ const fields = {};+ for (const line of content.split('\n')) {+ const sep = line.indexOf(': ');+ if (sep !== -1) {+ fields[line.slice(0, sep)] = line.slice(sep + 2);+ }+ }+ return fields;+}++function writeYaml(fields) {+ const keys = Object.keys(fields).sort();+ return keys.map(k => `${k}: ${fields[k]}`).join('\n') + '\n';+}++// --- Skill counter setting ---++const skillSettingName = `Site/AI/${skillName}`;+const skillFileName = `Site-AI-${skillName}.sitesetting.yml`;+const skillFilePath = path.join(siteSettingsDir, skillFileName);++if (fs.existsSync(skillFilePath)) {+ const existing = parseYaml(fs.readFileSync(skillFilePath, 'utf8'));+ const currentValue = parseInt(existing.value, 10) || 0;+ existing.value = String(currentValue + 1);+ fs.writeFileSync(skillFilePath, writeYaml(existing), 'utf8');+ console.log(`Updated ${skillSettingName} counter to ${existing.value}`);+} else {+ const fields = {+ description: `Tracks usage count of the ${skillName} skill`,+ id: generateUuid(),+ name: skillSettingName,+ value: '1'+ };+ fs.writeFileSync(skillFilePath, writeYaml(fields), 'utf8');+ console.log(`Created ${skillSettingName} counter (value: 1)`);+}++// --- Authoring tool setting ---++const authoringFileName = 'Site-AI-AuthoringTool.sitesetting.yml';+const authoringFilePath = path.join(siteSettingsDir, authoringFileName);++if (!fs.existsSync(authoringFilePath)) {+ const fields = {+ description: 'Records which AI authoring tool was used',+ id: generateUuid(),+ name: 'Site/AI/AuthoringTool',+ value: normalizedAuthoringTool+ };+ fs.writeFileSync(authoringFilePath, writeYaml(fields), 'utf8');+ console.log(`Created Site/AI/AuthoringTool setting (value: ${normalizedAuthoringTool})`);+} else {+ console.log('Site/AI/AuthoringTool setting already exists — preserved');+}diff --git a/plugins/power-pages/shared/authoring-tool-reference.md b/plugins/power-pages/shared/authoring-tool-reference.mddeleted file mode 100644index 17ad60cf6..000000000--- a/plugins/power-pages/shared/authoring-tool-reference.md+++ /dev/null@@ -1,252 +0,0 @@-# AI Site Settings Reference--This document describes how to create site settings to track AI tooling usage in Power Pages sites.--## Overview--When a site is created or modified using Claude Code skills, site settings are added to track:-1. **Authoring tool** - Which tool created the site-2. **Skills used** - Which skills have been executed on the site--## Site Setting Details--### Authoring Tool Setting--| Property | Value |-|----------|-------|-| Setting Name | `Site/AI/AuthoringTool` |-| File Name | `Site-AI-AuthoringTool.sitesetting.yml` |-| Location | `.powerpages-site/site-settings/` |--| Value | Description |-|-------|-------------|-| `ClaudeCodeCLI` | Site created using Claude Code command-line interface |-| `ClaudeCodeVSCode` | Site created using Claude Code VS Code extension |--### Skill Tracking Settings--Each time a skill is used, create or update a site setting to track usage count:--| Property | Value |-|----------|-------|-| Setting Name | `Site/AI/<SkillName>` |-| File Name | `Site-AI-<SkillName>.sitesetting.yml` |-| Value | Integer count (increments each time skill is used) |--| Skill | Setting Name |-|-------|--------------|-| `/create-site` | `Site/AI/CreateSite` |-| `/add-seo` | `Site/AI/AddSeo` |-| `/add-tests` | `Site/AI/AddTests` |-| `/setup-dataverse` | `Site/AI/SetupDataverse` |-| `/add-sample-data` | `Site/AI/AddSampleData` |-| `/setup-webapi` | `Site/AI/SetupWebApi` |-| `/integrate-webapi` | `Site/AI/IntegrateWebApi` |-| `/setup-auth` | `Site/AI/SetupAuth` |--## YAML Format--### Authoring Tool--**File**: `.powerpages-site/site-settings/Site-AI-AuthoringTool.sitesetting.yml`--```yaml-description: Identifies the tool used to create this Power Pages site-id: <GENERATE_UUID>-name: Site/AI/AuthoringTool-value: ClaudeCodeCLI-```--### Skill Tracking--**File**: `.powerpages-site/site-settings/Site-AI-CreateSite.sitesetting.yml`--```yaml-description: Tracks usage count of /create-site skill on this site-id: <GENERATE_UUID>-name: Site/AI/CreateSite-value: 1-```--**Note**: The `value` is an integer that increments each time the skill is used (1, 2, 3, etc.).--## Detection Logic--The authoring tool value is determined by checking environment variables:--```powershell-$authoringTool = if ($env:TERM_PROGRAM -eq "vscode" -or $env:VSCODE_GIT_ASKPASS_NODE) {- "ClaudeCodeVSCode"-} else {- "ClaudeCodeCLI"-}-```--## PowerShell Helper Functions--### Create Authoring Tool Setting--```powershell-function New-AuthoringToolSetting {- param(- [Parameter(Mandatory=$true)]- [string]$ProjectRoot- )-- $siteSettingsPath = Join-Path $ProjectRoot ".powerpages-site\site-settings"-- if (-not (Test-Path $siteSettingsPath)) {- New-Item -ItemType Directory -Path $siteSettingsPath -Force | Out-Null- }-- $authoringTool = if ($env:TERM_PROGRAM -eq "vscode" -or $env:VSCODE_GIT_ASKPASS_NODE) {- "ClaudeCodeVSCode"- } else {- "ClaudeCodeCLI"- }-- $uuid = [guid]::NewGuid().ToString()-- $content = @"-description: Identifies the tool used to create this Power Pages site-id: $uuid-name: Site/AI/AuthoringTool-value: $authoringTool-"@-- $fileName = "Site-AI-AuthoringTool.sitesetting.yml"- $filePath = Join-Path $siteSettingsPath $fileName- Set-Content -Path $filePath -Value $content -Encoding UTF8- Write-Host "Created: $filePath (Value: $authoringTool)"-}-```--### Create/Update Skill Tracking Setting--```powershell-function New-SkillTrackingSetting {- param(- [Parameter(Mandatory=$true)]- [string]$ProjectRoot,- [Parameter(Mandatory=$true)]- [string]$SkillName # e.g., "CreateSite", "AddSeo", "AddTests", "SetupDataverse", "AddSampleData", "SetupWebApi", "IntegrateWebApi", "SetupAuth"- )-- $siteSettingsPath = Join-Path $ProjectRoot ".powerpages-site\site-settings"-- if (-not (Test-Path $siteSettingsPath)) {- New-Item -ItemType Directory -Path $siteSettingsPath -Force | Out-Null- }-- $fileName = "Site-AI-$SkillName.sitesetting.yml"- $filePath = Join-Path $siteSettingsPath $fileName-- # Check if setting already exists and get current count- $currentCount = 0- $existingId = $null- if (Test-Path $filePath) {- $existingContent = Get-Content $filePath -Raw- if ($existingContent -match 'value:\s*(\d+)') {- $currentCount = [int]$Matches[1]- }- if ($existingContent -match 'id:\s*([a-f0-9-]+)') {- $existingId = $Matches[1]- }- }-- $newCount = $currentCount + 1- $uuid = if ($existingId) { $existingId } else { [guid]::NewGuid().ToString() }- $skillSlug = $SkillName.ToLower() -replace '([a-z])([A-Z])', '$1-$2'-- $content = @"-description: Tracks usage count of /$skillSlug skill on this site-id: $uuid-name: Site/AI/$SkillName-value: $newCount-"@-- Set-Content -Path $filePath -Value $content -Encoding UTF8- Write-Host "Updated: $filePath (count: $newCount)"-}-```--## When to Create These Settings--### Authoring Tool Setting-- **After first upload** during `/create-site` (after `.powerpages-site` folder is created)-- If it already exists, do NOT overwrite (preserve original authoring tool)--### Skill Tracking Settings-- **Every skill** should update its tracking setting before final upload-- If setting exists, increment the count; if not, create with count = 1--| Skill | When to Update | Setting Name |-|-------|----------------|--------------|-| `/create-site` | After first upload, before second upload | `Site/AI/CreateSite` |-| `/add-seo` | Before final upload | `Site/AI/AddSeo` |-| `/add-tests` | Before final upload | `Site/AI/AddTests` |-| `/setup-dataverse` | Before final upload | `Site/AI/SetupDataverse` |-| `/add-sample-data` | Before final upload | `Site/AI/AddSampleData` |-| `/setup-webapi` | Before final upload | `Site/AI/SetupWebApi` |-| `/integrate-webapi` | Before final upload | `Site/AI/IntegrateWebApi` |-| `/setup-auth` | Before final upload | `Site/AI/SetupAuth` |--## Usage Examples--### In /create-site skill--```powershell-# After first upload creates .powerpages-site folder-New-AuthoringToolSetting -ProjectRoot $projectRoot-New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "CreateSite"-# Then upload again to push the settings-```--### In /add-seo skill--```powershell-New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "AddSeo"-# Then upload-```--### In /add-tests skill--```powershell-New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "AddTests"-# Then upload (if deploying tests to site)-```--### In /setup-dataverse skill--```powershell-New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupDataverse"-# Then upload-```--### In /add-sample-data skill--```powershell-New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "AddSampleData"-# Then upload-```--### In /setup-webapi skill--```powershell-New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupWebApi"-# Then upload-```--### In /integrate-webapi skill--```powershell-New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "IntegrateWebApi"-# Then upload-```--### In /setup-auth skill--```powershell-New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupAuth"-# Then upload-```diff --git a/plugins/power-pages/shared/cleanup-reference.md b/plugins/power-pages/shared/cleanup-reference.mddeleted file mode 100644index b984bfba6..000000000--- a/plugins/power-pages/shared/cleanup-reference.md+++ /dev/null@@ -1,19 +0,0 @@-# Cleanup Helper Files--After successfully completing a skill, remove any temporary helper scripts or files that were created in the project root during execution.--## What to Remove--Any temporary scripts or helper files created during the skill that are not part of the final site structure.--## What NOT to Remove--- `memory-bank.md` (needed for session continuity)-- `.powerpages-site/` folder and all its contents-- `src/` folder and source files-- Configuration files (`package.json`, `powerpages.config.json`, `tsconfig.json`, etc.)-- Any files that existed before running the skill--## When to Cleanup--Only clean up helper files after confirming the skill completed successfully and the setup is working correctly.diff --git a/plugins/power-pages/shared/memory-bank.md b/plugins/power-pages/shared/memory-bank.mddeleted file mode 100644index 97d9bc4ff..000000000--- a/plugins/power-pages/shared/memory-bank.md+++ /dev/null@@ -1,260 +0,0 @@-# Memory Bank Instructions--This document defines the memory bank system used to persist context across conversations and skill invocations. **All skills in this plugin follow these instructions.**--## Overview--The memory bank (`memory-bank.md`) is a markdown file stored in the project root that tracks:--- Project configuration and metadata-- Completed steps and progress-- User decisions and preferences-- Created resources (tables, permissions, etc.)-- Current status and next steps--## File Location--The memory bank is always stored at: `<PROJECT_ROOT>/memory-bank.md`-------## Before Starting Any Skill--**IMPORTANT**: Every skill MUST check for and read the memory bank before proceeding.--### Step 1: Locate the Memory Bank--1. If the user has specified a project path, check `<PROJECT_PATH>/memory-bank.md`-2. If continuing from a previous skill in the same session, use the known project path-3. If no path is known, ask the user for the project path--### Step 2: Read and Parse Context--If the memory bank exists, extract:--| Information | Purpose |-|-------------|---------|-| Project path, name, framework | Know what you're working with |-| Completed steps (checkboxes) | Skip steps already done |-| User preferences | Don't re-ask answered questions |-| Created resources | Know what tables/settings exist |-| Current status | Understand where to resume |--### Step 3: Resume or Continue--- **If the current skill's steps are already marked complete**: Ask if they want to modify, add more, or skip to next steps-- **If partially complete**: Inform the user and resume from the incomplete step-- **If not started**: Begin from the first step--### Step 4: Inform the User--Always tell the user what you found:--> "I found your project memory bank. [Summary: project name, framework, what's been completed]. Let's continue from [next step]."-------## After Each Major Step--Update the memory bank immediately after completing each major step. This ensures progress is saved even if the session ends unexpectedly.--### What to Update--1. **Mark completed steps** with `[x]`-2. **Record created resources** (tables, settings, files)-3. **Save user decisions** (framework choice, integration approach, etc.)-4. **Update current status** and next step-5. **Add timestamp** to "Last Updated"-6. **Add notes** for important context or decisions--### Update Frequency--Update after:--- Completing any workflow step-- User makes a significant decision-- Creating or modifying resources-- Encountering errors or issues worth noting-- Before ending a session-------## When to Create vs Update--| Scenario | Action |-|----------|--------|-| Memory bank doesn't exist | Create it after the first major step (e.g., after site creation) |-| Memory bank exists | Update it - preserve existing content, add new information |-| Continuing previous session | Read first, then update as you progress |--## Template Structure--```markdown-# Power Pages Project Memory Bank--> Last Updated: [TIMESTAMP]-> Session: [SESSION_ID or conversation context]--## Project Overview--| Property | Value |-|----------|-------|-| Project Name | [SITE_NAME] |-| Project Path | [FULL_PATH] |-| Framework | [React/Angular/Vue/Astro] |-| Created Date | [DATE] |-| Status | [In Progress/Site Created/Tables Setup/Deployed] |--## User Preferences--### Design Preferences-- Style: [Modern/Corporate/Creative/Elegant]-- Color Scheme: [Description or hex codes]-- Special Requirements: [Accessibility, mobile-first, etc.]--### Technical Preferences-- Data Integration: [MCP Server/OData API]-- Authentication: [Enabled/Disabled] - [Provider if enabled]--## Completed Steps--### /create-site-- [x] Requirements gathered-- [x] Framework selected: [FRAMEWORK]-- [x] Site created with features: [LIST]-- [x] powerpages.config.json created-- [x] Project built successfully-- [x] Prerequisites verified (PAC CLI, Azure CLI)-- [x] Uploaded to Power Pages (Inactive)-- [x] Site activated-- Website ID: [GUID]-- Site URL: [URL]--### /setup-dataverse-- [x] Site analyzed-- [x] Schema recommended-- [x] Integration approach chosen: [MCP/OData]-- [x] Tables created: [LIST]-- [x] Sample data inserted--### /setup-webapi-- [x] Site settings created for Web API-- [x] Table permissions configured-- [x] Frontend code updated-- [x] Project built and uploaded--## Created Resources--### Publisher Prefix--The publisher prefix is fetched dynamically from the Default solution's publisher via `Initialize-DataverseApi`:-- **Prefix**: `{prefix}` (e.g., `cr`, `contoso`, `new`)--### Dataverse Tables--| Table Name | Display Name | Columns | Sample Data |-|------------|--------------|---------|-------------|-| {prefix}_contactsubmission | Contact Submission | name, email, message, status | 3 records |-| {prefix}_product | Product | name, description, price, category | 5 records |--### Site Settings--| Setting | Value |-|---------|-------|-| Webapi/{prefix}_product/enabled | true |-| Webapi/{prefix}_product/fields | {prefix}_name,{prefix}_description,{prefix}_price,{prefix}_category |--## Current Status--**Last Action**: [Description of last completed action]--**Next Step**: [What the user should do next]--**Pending Items**:-- [ ] [Item 1]-- [ ] [Item 2]--## Notes & Issues--### Session Notes-- [Date]: [Note about decisions, issues, or context]--### Known Issues-- [Issue description and any workarounds]--## Quick Resume--To continue working on this project:--1. **Create Site**: `/create-site` (creates new site or updates existing)-2. **Setup Dataverse Tables**: `/setup-dataverse` (creates tables and sample data)-3. **Setup Web API**: `/setup-webapi` (enables Web API access and updates frontend)-4. **Manual**: Navigate to [PROJECT_PATH] and continue development-```--## Reading the Memory Bank--When reading the memory bank, extract:--1. **Project context**: Path, framework, name-2. **Completed work**: Check checkboxes to know what's done-3. **User preferences**: Apply these without re-asking-4. **Created resources**: Know what tables/settings exist-5. **Current status**: Understand where to resume--## Writing Guidelines--1. **Be concise**: Use tables and lists, not paragraphs-2. **Be specific**: Include exact values, paths, GUIDs-3. **Timestamp updates**: Always update "Last Updated"-4. **Preserve history**: Add to notes, don't overwrite-5. **Track decisions**: Record why choices were made--## Example: Checking Memory Bank--```text-At the start of /setup-dataverse:--1. Read memory-bank.md from project root-2. Check if /setup-dataverse steps are already marked complete-3. If tables are already created, ask user if they want to:- - Add more tables- - Modify existing tables- - Add more sample data- - Skip to next step-4. Apply saved preferences (e.g., MCP vs OData choice)-```--## Integration with Skills--Both skills should include these instructions:--### At Skill Start--```text-### Check Memory Bank--Before proceeding, check if a memory bank exists:--1. Look for `memory-bank.md` in the project root-2. If found, read it to understand:- - What steps have been completed- - What user preferences were chosen- - What resources already exist-3. Adjust your workflow to skip completed steps-4. Inform the user what you found and where you'll resume-```--### At Skill End / After Major Steps--```text-### Update Memory Bank--After completing this step, update the memory bank:--1. Create or update `memory-bank.md` in the project root-2. Mark completed steps with [x]-3. Record any new resources created-4. Update the "Current Status" section-5. Add any relevant notes-```diff --git a/plugins/power-pages/shared/planning-policy.md b/plugins/power-pages/shared/planning-policy.mddeleted file mode 100644index f6b112c32..000000000--- a/plugins/power-pages/shared/planning-policy.md+++ /dev/null@@ -1,40 +0,0 @@-# Planning Policy--**Before implementing major changes, Claude MUST enter plan mode first.**--## When Planning is Required--- Adding new features or components-- Modifying existing workflows or logic-- Changes affecting multiple files-- Schema, API, or configuration changes-- Adding new pages, forms, or UI components-- Modifying Dataverse table structures-- Changes to authentication or authorization--## How to Plan--1. **Enter Plan Mode**: Use the `/plan` command before writing any code-2. **Explore**: Read relevant files and understand the current implementation-3. **Design**: Create a clear implementation approach-4. **Present**: Show the plan to the user for approval-5. **Wait**: Do not proceed until the user approves-6. **Exit**: Use `ExitPlanMode` tool when ready to implement--## When Planning is NOT Required--- Single-line fixes (typos, minor corrections)-- Documentation-only updates-- Memory bank updates-- Adding comments or improving readability-- Running diagnostic commands--## Planning Checklist--Before exiting plan mode, ensure your plan covers:--- [ ] What files will be created or modified-- [ ] What the changes will do-- [ ] Any dependencies or prerequisites-- [ ] Potential risks or rollback steps-- [ ] Testing approachdiff --git a/plugins/power-pages/shared/shared-instructions.md b/plugins/power-pages/shared/shared-instructions.mddeleted file mode 100644index bc572cd87..000000000--- a/plugins/power-pages/shared/shared-instructions.md+++ /dev/null@@ -1,65 +0,0 @@-# Shared Instructions--**This file aggregates all cross-cutting instructions that apply to every skill in the Power Pages plugin.**--All skills reference this single file. When new shared instructions are added, update this file only - no changes needed to individual skills.-------## Planning Policy--**📋 [planning-policy.md](./planning-policy.md)**--Before implementing major changes, Claude MUST enter plan mode first. This ensures user approval before significant work begins.--**Key Points:**-- Use `/plan` command to enter plan mode before writing code for new features or multi-file changes-- Present plan for user approval-- Exit plan mode with `ExitPlanMode` tool when approved-------## Memory Bank--**📋 [memory-bank.md](./memory-bank.md)**--The memory bank persists context across sessions. Every skill reads it at start and updates it after major steps.--**Key Points:**-- Check for `<PROJECT_ROOT>/memory-bank.md` before starting-- Skip completed steps, resume from where the user left off-- Update after each major step to save progress-------## Cleanup--**📋 [cleanup-reference.md](./cleanup-reference.md)**--Remove temporary helper files after skill completion.--**Key Points:**-- Only clean up after confirming success-- Never remove `memory-bank.md`, `.powerpages-site/`, or source files-------## Authoring Tool--**📋 [authoring-tool-reference.md](./authoring-tool-reference.md)**--Configure the authoring tool site setting for Power Pages sites.--**Key Points:**-- Required for `.powerpages-site/` folder structure to work-- Create the site setting file when setting up site settings-------## Adding New Shared Instructions--When adding a new cross-cutting concern:--1. Create the new file in `shared/` (e.g., `new-policy.md`)-2. Add a section to THIS file referencing the new file-3. No changes needed to individual SKILL.md filesdiff --git a/plugins/power-pages/skills/activate-site/SKILL.md b/plugins/power-pages/skills/activate-site/SKILL.mdnew file mode 100644index 000000000..caad8e20e--- /dev/null+++ b/plugins/power-pages/skills/activate-site/SKILL.md@@ -0,0 +1,415 @@+---+name: activate-power-pages-site+description: >+ This skill should be used when the user asks to "activate site",+ "provision website", "activate a Power Pages website", "activate portal",+ "provision portal", "turn on my site", "enable website",+ or wants to activate/provision a Power Pages website in their+ Power Platform environment via the Power Platform REST API.+user-invocable: true+allowed-tools: ["Read", "Bash", "Glob", "Grep", "AskUserQuestion", "TaskCreate", "TaskUpdate", "TaskList"]+model: opus+hooks:+ Stop:+ - hooks:+ - type: command+ command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/activate-site/scripts/validate-activation.js"'+ timeout: 30+ - 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),+ 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.+ If incomplete, return { "ok": false, "reason": "<specific issues>" }. Otherwise return { "ok": true }.+ timeout: 30+---++# Activate Power Pages Site++Provision a new Power Pages website in a Power Platform environment via the Power Platform REST API.++> **Prerequisite:** This skill expects an existing Power Pages code site created via `/power-pages:create-site`. Run that skill first if the site does not exist yet.++## 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.+- **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+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++---++## 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.++### Actions++#### 1.1 Verify PAC CLI++Run `pac help` to check if the PAC CLI is installed and available on the system PATH.++```powershell+pac help+```++**If the command fails** (command not found / not recognized):++1. Tell the user: "PAC CLI is not installed. You can install it by running:"++ ```powershell+ dotnet tool install --global Microsoft.PowerApps.CLI.Tool+ ```++2. If `dotnet` is also not available, direct the user to https://aka.ms/PowerPlatformCLI for full installation instructions.+3. After installation, verify by running `pac help` again.++#### 1.2 Check Authentication++Run `pac auth who` to check current authentication status.++```powershell+pac auth who+```++**If authenticated**: Extract these values from the output:+- **Environment ID** — the GUID after `Environment ID:`+- **Organization ID** — the GUID after `Organization ID:` (this is the Dataverse org ID)+- **Cloud** — the value after `Cloud:` (e.g., `Public`, `UsGov`, `UsGovHigh`, `UsGovDod`, `China`)++**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++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:++```powershell+$token = az account get-access-token --resource "$ppApiBaseUrl" --query accessToken -o tsv+```++**If `az` is not installed or not logged in**: Instruct the user to install Azure CLI and run `az login`.++#### 1.5 Verify Token++Make a lightweight GET to verify the token works:++```powershell+$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }+Invoke-RestMethod -Uri "$ppApiBaseUrl/powerpages/environments/$environmentId/websites?api-version=2022-03-01-preview" -Headers $headers+```++**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.++**If successful**: Proceed to Phase 2.++### 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++---++## Phase 2: Gather Parameters++**Goal:** Determine the site name, generate or accept a subdomain, and look up the website record ID needed for the activation API call.++### Actions++#### 2.1 Read Site Name++Look for `powerpages.config.json` in the current directory or one level of subdirectories using `Glob`:++```text+**/powerpages.config.json+```++Read the file and extract the `siteName` field. If not found, ask the user for the site name using `AskUserQuestion`.++#### 2.2 Generate Subdomain Suggestion++> **CRITICAL — This step is MANDATORY. You MUST ask the user about the subdomain before proceeding. Do NOT skip this step or auto-select a subdomain without user input.**++Run the subdomain generator script to create a random suggestion:++```powershell+node "${CLAUDE_PLUGIN_ROOT}/skills/activate-site/scripts/generate-subdomain.js"+```++This outputs a string like `site-a3f2b1`. Resolve the correct site URL domain from the **Cloud** value obtained in Phase 1.2:++| Cloud | Site URL Domain |+|---|---|+| `Public` | `powerappsportals.com` |+| `UsGov` | `powerappsportals.us` |+| `UsGovHigh` | `high.powerappsportals.us` |+| `UsGovDod` | `appsplatform.us` |+| `China` | `powerappsportals.cn` |++Present the generated subdomain to the user and ask them to accept or enter their own using `AskUserQuestion`:++| Question | Header | Options |+|----------|--------|---------|+| Your site subdomain will be: **`<suggestion>`** (full URL: `https://<suggestion>.<siteUrlDomain>`). Would you like to use this subdomain or enter your own? | Subdomain | Use `<suggestion>` (Recommended), Enter a custom subdomain |++**If custom**: The user provides their own subdomain via "Other" free text input. Validate it is lowercase, alphanumeric with hyphens only, and 3-50 characters.++#### 2.3 Get Website Record ID++Run `pac pages list` to get the website record ID:++```powershell+pac pages list+```++Parse the output to find the website record that matches the site name. Extract the `Website Record ID` (GUID). If `pac pages list` returns no results or the command is not available, set `websiteRecordId` to `$null` — the API will create a new website record.++### Output++- Site name determined (from config file or user input)+- Subdomain chosen (generated or custom)+- Website record ID resolved (GUID or null)++---++## Phase 3: Confirm++**Goal:** Present all activation parameters to the user and get explicit approval before making the API call.++### Actions++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 |++**If "No"**: Stop the skill and inform the user they can re-run it later.++**If "Yes"**: Proceed to Phase 4.++### Output++- User has explicitly approved the activation parameters++---++## Phase 4: Activate++**Goal:** POST to the Power Platform websites API to start provisioning and capture the Operation-Location header for polling.++### Actions++#### 4.1 Refresh Token++Re-acquire the Azure CLI token in case it has expired since Phase 1:++```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>"+}+```++If `websiteRecordId` is null/empty, **omit** the field from the body entirely (do not send `null`).++#### 4.3 POST to Websites API++Use `Invoke-WebRequest` (NOT `Invoke-RestMethod`) to capture response headers — specifically the `Operation-Location` header needed for polling:++```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"]+```++Add the `websiteRecordId` field to the `$body` hashtable only if it is not null.++#### 4.4 Handle Responses++| Status Code | Meaning | 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 |++### Output++- API returned 202 Accepted+- `Operation-Location` URL captured for polling++---++## 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++**Goal:** Show the user the final site URL and suggest next steps.++### Actions++#### 6.1 Show Results++Present the activation summary to the user:++```+Power Pages site activated successfully!++ Site Name: <siteName>+ Site URL: https://<subdomain>.powerappsportals.com+ 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` |++#### 6.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++After the summary, suggest:+- Set up the data model: `/power-pages:setup-datamodel`+- Add sample data: `/power-pages:add-sample-data`+- View the site in the browser at the provisioned URL (note: it may take a few minutes for DNS to propagate)++### Output++- Activation summary presented with correct cloud-specific site URL+- Next steps suggested to the user++---++## Important Notes++### Progress Tracking++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 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 |++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 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.++**Begin with Phase 1: Verify Prerequisites**diff --git a/plugins/power-pages/skills/activate-site/scripts/generate-subdomain.js b/plugins/power-pages/skills/activate-site/scripts/generate-subdomain.jsnew file mode 100644index 000000000..d3856621d--- /dev/null+++ b/plugins/power-pages/skills/activate-site/scripts/generate-subdomain.js@@ -0,0 +1,8 @@+#!/usr/bin/env node++// Generates a random subdomain suggestion for Power Pages site activation.+// Mirrors Power Pages Studio logic: Math.random().toString(36) for base-36 suffix.+// Outputs format: site-uc8f3 (5 base-36 chars: 0-9 + a-z)++const suffix = Math.random().toString(36).slice(2, 7);+process.stdout.write(`site-${suffix}`);diff --git a/plugins/power-pages/skills/activate-site/scripts/validate-activation.js b/plugins/power-pages/skills/activate-site/scripts/validate-activation.jsnew file mode 100644index 000000000..d024b7b3d--- /dev/null+++ b/plugins/power-pages/skills/activate-site/scripts/validate-activation.js@@ -0,0 +1,55 @@+#!/usr/bin/env node++// 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.++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');++runValidation((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 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++ const found = websites.some(+ (w) => w.name && w.name.toLowerCase() === siteName.toLowerCase()+ );++ if (!found) {+ block(+ `Power Pages activation validation failed:\n- Website "${siteName}" not found in environment ${pacInfo.environmentId}. The site may not have been provisioned successfully.`+ );+ }++ 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/add-sample-data/SKILL.md b/plugins/power-pages/skills/add-sample-data/SKILL.mdindex 0b252cd07..cc9d192c2 100644--- a/plugins/power-pages/skills/add-sample-data/SKILL.md+++ b/plugins/power-pages/skills/add-sample-data/SKILL.md@@ -1,94 +1,325 @@----name: adding-sample-data-description: Inserts sample data into Dataverse tables with proper foreign key relationships. Use when populating tables with test data, adding demo content, or seeding databases.+name: add-sample-data+description: >+ This skill should be used when the user asks to "add sample data",+ "populate tables", "seed data", "add test records", "generate sample records",+ "insert demo data", "fill tables with data", "create test data",+ or wants to populate their Dataverse tables with sample records+ so they can test and demo their Power Pages site.user-invocable: true-allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "AskUserQuestion"]+allowed-tools: ["Read", "Write", "Bash", "Grep", "Glob", "AskUserQuestion", "Task", "TaskCreate", "TaskUpdate", "TaskList", "mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search", "mcp__plugin_power-pages_microsoft-learn__microsoft_code_sample_search", "mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch"]model: opus+hooks:+ Stop:+ - hooks:+ - type: prompt+ prompt: >+ If sample data was being added in this session (via /power-pages:add-sample-data),+ verify before allowing stop: 1) Tables were discovered (from .datamodel-manifest.json or OData API),+ 2) The user selected which tables to populate,+ 3) All records were inserted via OData API, 4) A verification summary was presented+ showing record counts per table. If incomplete, return { "ok": false, "reason": "<specific issues>" }.+ Otherwise return { "ok": true }.+ timeout: 30----**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.-# Add Sample Data-**References:** [sample-data](./references/sample-data-reference.md)+Populate Dataverse tables with sample records via OData API so users can test and demo their Power Pages sites.++## Core Principles-Inserts sample data into Dataverse tables created by `/setup-dataverse`.+- **Respect insertion order**: Always insert parent/referenced tables before child/referencing tables so lookup IDs are available when needed.+- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases -- create the todo list upfront with all phases before starting any work.+- **Fail gracefully**: On insertion failure, log the error and continue with remaining records -- never attempt automated rollback.-## Prerequisites+**Initial request:** $ARGUMENTS++----- Tables created with `/setup-dataverse`-- `$tableMap` available in memory bank with actual table names-- API authentication set up+## Phase 1: Verify Prerequisites-## Workflow+**Goal**: Confirm PAC CLI auth, acquire an Azure CLI token, and verify API access-1. **Check Context** → Read memory bank, get table mapping-2. **Check Existing Data** → Query tables to avoid duplicates-3. **Confirm with User** → Show what will be inserted-4. **Insert Tier 0** → Reference tables (categories, statuses)-5. **Insert Tier 1** → Primary entities with lookups-6. **Insert Tier 2** → Dependent records-7. **Verify Data** → Query with $expand to check relationships+**Actions**:+1. Create todo list with all 6 phases (see [Progress Tracking](#progress-tracking) table)+2. Follow the prerequisite steps in `${CLAUDE_PLUGIN_ROOT}/references/dataverse-prerequisites.md` to verify PAC CLI auth, acquire an Azure CLI token, and confirm API access. Store the environment URL as `$envUrl`.++**Output**: Authenticated session with valid token and confirmed API access----## Step 1: Check Context+## Phase 2: Discover Tables-Read `memory-bank.md` for:-- Table name mapping (`$tableMap`)-- Publisher prefix-- Environment URL+**Goal**: Find the custom tables available in the user's Dataverse environment-If `/setup-dataverse` not completed, tell user to run it first.+**Actions**:----+### Path A: Read `.datamodel-manifest.json` (Preferred)++Check if `.datamodel-manifest.json` exists in the project root (written by the `setup-datamodel` skill). If it exists, read it -- it already contains table logical names, display names, and column info.-## Step 2: Check Existing Data+```powershell+# Check if manifest exists+Test-Path ".datamodel-manifest.json"+```++See `${CLAUDE_PLUGIN_ROOT}/references/datamodel-manifest-schema.md` for the full manifest schema.++### Path B: Query OData API (Fallback)++If no manifest exists, discover custom tables via OData:```powershell-$api = Initialize-DataverseApi -EnvironmentUrl "https://<org>.crm.dynamics.com"--# Check record counts for each table-foreach ($purpose in $tableMap.Keys) {- $entitySet = $tableMap[$purpose].EntitySetName- $count = Get-ExistingRecordCount -EntitySetName $entitySet- Write-Host "$purpose ($entitySet): $count records"-}+$tables = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions?`$select=LogicalName,DisplayName,EntitySetName&`$filter=IsCustomEntity eq true" -Headers $headers```+For each discovered table, fetch its custom columns:++```powershell+$columns = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table>')/Attributes?`$select=LogicalName,DisplayName,AttributeType,RequiredLevel&`$filter=IsCustomAttribute eq true" -Headers $headers+```++### 2.1 Present Available Tables++Show the user the list of discovered tables with their columns so they can choose which to populate.++**Output**: List of discovered tables with their columns presented to the user+----## Step 3: Confirm with User+## Phase 3: Select Tables & Configure++**Goal**: Gather user preferences on which tables to populate and how many records to create++**Actions**:++### 3.1 Select Tables++Use `AskUserQuestion` to ask which tables they want to populate (use `multiSelect: true`). List all discovered tables as options.++### 3.2 Select Record Count++Use `AskUserQuestion` to ask how many sample records per table:++| Option | Description |+|--------|-------------|+| **5 records** | Quick test -- just enough to verify the setup |+| **10 records** | Light demo data for basic testing |+| **25 records** | Fuller dataset for realistic demos |+| **Custom** | Let the user specify a number |++### 3.3 Determine Insertion Order-Use `AskUserQuestion` to show:-- Tables that already have data (will skip or append)-- Tables that are empty (will populate)-- Sample records to be created+Analyze relationships between selected tables. Parent/referenced tables must be inserted first so their IDs are available for child/referencing table lookups.-Options:-- **Proceed** - Insert sample data-- **Skip existing** - Only populate empty tables-- **Cancel** - Don't insert any data+Build the insertion order:+1. Tables with no lookup dependencies (parent tables) -- insert first+2. Tables that reference already-inserted tables -- insert next+3. Continue until all tables are ordered++**Output**: Confirmed table selection, record count, and insertion order----## Step 4-6: Insert Data by Tier+## Phase 4: Generate & Review Sample Data++**Goal**: Generate contextually appropriate sample records and get user approval before inserting++**Actions**:++### 4.1 Generate Contextual Sample Data++For each selected table, generate sample records with contextually appropriate values based on column names and types:++- **String columns**: Generate realistic values matching the column name (e.g., "Email" -> `[email protected]`, "Phone" -> `(555) 123-4567`, "Name" -> realistic names)+- **Memo columns**: Generate short descriptive text relevant to the column name+- **Integer/Decimal/Currency columns**: Generate reasonable numeric values+- **DateTime columns**: Generate dates within a sensible range (past year to next month)+- **Boolean columns**: Mix of `true` and `false` values+- **Picklist/Choice columns**: Query valid options first (see references/odata-record-patterns.md), then use actual option values+- **Lookup columns**: Reference records from parent tables that will be/were already inserted++### 4.2 Present Sample Data Preview-See [sample-data-reference.md](./references/sample-data-reference.md#complete-sample-data-script).+For each table, show a markdown table previewing the sample records directly in the conversation:-**Tier 0** (reference tables): Categories, Statuses, Departments-**Tier 1** (primary entities): Products, Team Members-**Tier 2** (dependent): Testimonials, Contact Submissions+```markdown+### Project (cr123_project) -- 5 records-Use `New-DataverseRecordIfNotExists` to skip existing records.+| Name | Description | Status | Start Date |+|------|-------------|--------|------------|+| Website Redesign | Modernize the corporate website | 100000000 (Active) | 2025-03-15 |+| Mobile App | Build iOS and Android app | 100000001 (Planning) | 2025-04-01 |+| ... | ... | ... | ... |+```++Show relationship handling: which lookup fields reference which parent table records.++**Output**: Sample data plan ready for insertion. Proceed directly to Phase 5.----## Step 7: Verify Data+## Phase 5: Insert Sample Data++**Goal**: Execute OData POST calls to create all approved sample records with correct relationship handling++**Actions**:++Refer to `references/odata-record-patterns.md` for full patterns.++### 5.1 Get Entity Set Names++For each table, get the entity set name (needed for the API URL):```powershell-# Verify relationships with $expand-$products = Invoke-RestMethod -Uri "$baseUrl/$productEntitySet`?`$expand=${prefix}_categoryid" -Headers $headers+$entityDef = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table>')?`$select=EntitySetName" -Headers $headers+$entitySetName = $entityDef.EntitySetName+```++### 5.2 Get Picklist Options++For any picklist/choice columns, query valid option values before insertion:++```powershell+$picklistMeta = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table>')/Attributes(LogicalName='<column>')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?`$expand=OptionSet" -Headers $headers+```++Use the actual `Value` integers from the option set in your sample data.++### 5.3 Insert Parent Tables First++Insert records into parent/referenced tables first to capture their IDs:++```powershell+$body = @{+ cr123_name = "Sample Record"+ cr123_description = "A sample record for testing"+} | ConvertTo-Json++$response = Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/<EntitySetName>" -Headers $headers -Body $body -ContentType "application/json"```-Update memory-bank.md with sample data status.+Capture the returned record ID from the `OData-EntityId` response header or by querying back:++```powershell+# The ID is in the response headers+# Or query: GET {envUrl}/api/data/v9.2/<EntitySetName>?$filter=cr123_name eq 'Sample Record'&$select=cr123_<table>id+```++Store parent record IDs for use in child table lookups.++### 5.4 Insert Child Tables with Lookups++For child/referencing tables, use `@odata.bind` syntax to set lookup fields:++```powershell+$body = @{+ cr123_name = "Child Record"+ "[email protected]" = "/<ParentEntitySetName>(<parent_guid>)"+} | ConvertTo-Json++Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/<ChildEntitySetName>" -Headers $headers -Body $body -ContentType "application/json"+```++### 5.5 Track Progress++Track each insertion attempt:+- Record table name, record number, success/failure+- On failure, log the error message but continue with remaining records+- Do NOT attempt automated rollback on failure++### 5.6 Refresh Token Periodically++Refresh the Azure CLI token every 20 records to avoid expiration:++```powershell+$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+$headers["Authorization"] = "Bearer $token"+```++**Output**: All approved records inserted with parent-child relationships established++---++## Phase 6: Verify & Summarize++**Goal**: Confirm record counts and present a final summary to the user++**Actions**:++### 6.1 Verify Record Counts++For each table that was populated, query the record count:++```powershell+$count = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/<EntitySetName>?`$count=true&`$top=0" -Headers $headers+```++The `@odata.count` field in the response gives the total record count.++### 6.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 "AddSampleData"`.++### 6.3 Present Summary++Present a summary table:++| Table | Records Requested | Records Created | Failures |+|-------|-------------------|-----------------|----------|+| `cr123_project` (Project) | 10 | 10 | 0 |+| `cr123_task` (Task) | 10 | 9 | 1 |++Include:+- Total records created across all tables+- Any failures with error details+- Lookup relationships that were established++### 6.4 Suggest Next Steps++After the summary, suggest:+- Review the data in the Power Pages maker portal or model-driven app+- If the site is not yet built: `/power-pages:create-site`+- If the site is ready to deploy: `/power-pages:deploy-site`++**Output**: Verified record counts and summary presented to the user++---++## Important Notes++### Throughout All Phases++- **Use TaskCreate/TaskUpdate** to track progress at every phase+- **Ask for user confirmation** at key decision points (see list below)+- **Respect insertion order** -- always insert parent tables before child tables+- **Fail gracefully** -- log errors and continue, never rollback automatically+- **Refresh tokens** every 20 records to avoid expiration++### Key Decision Points (Wait for User)++1. After Phase 2: Confirm which tables to populate+2. After Phase 3: Confirm record count and insertion order+3. After Phase 6: Review summary and decide next steps++### Progress Tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Verify prerequisites | Verifying prerequisites | Confirm PAC CLI auth, acquire Azure CLI token, verify API access |+| Discover tables | Discovering tables | Read .datamodel-manifest.json or query OData API for custom tables |+| Select tables and configure | Configuring tables | User picks tables, record count, and determine insertion order |+| Generate and review sample data | Generating sample data | Generate contextual sample records, present preview, get user approval |+| Insert sample data | Inserting records | Execute OData POST calls with relationship handling and token refresh |+| Verify and summarize | Verifying results | Confirm record counts, present summary, suggest next steps |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`. This gives the user visibility into progress and keeps the workflow deterministic.++---++**Begin with Phase 1: Verify Prerequisites**diff --git a/plugins/power-pages/skills/add-sample-data/references/odata-record-patterns.md b/plugins/power-pages/skills/add-sample-data/references/odata-record-patterns.mdnew file mode 100644index 000000000..65e0191cc--- /dev/null+++ b/plugins/power-pages/skills/add-sample-data/references/odata-record-patterns.md@@ -0,0 +1,262 @@+# OData API Patterns for Record Creation++Reference document for the `add-sample-data` skill. Contains patterns for inserting records, setting lookup bindings, handling different column types, and querying record counts via the Dataverse OData Web API (v9.2).++> **Authentication, error handling, and retry patterns** are in the shared reference: `${CLAUDE_PLUGIN_ROOT}/references/odata-common.md`. Read that file first for headers, token refresh, HTTP status codes, and retry logic.++---++## Get Entity Set Name++Entity set names are required for all record operations. They differ from logical names (e.g., `cr123_project` → `cr123_projects`).++**Endpoint:** `GET {envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='<table>')?$select=EntitySetName`++```powershell+$entityDef = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='cr123_project')?`$select=EntitySetName" -Headers $headers+$entitySetName = $entityDef.EntitySetName # e.g., "cr123_projects"+```++---++## Insert a Record++**Endpoint:** `POST {envUrl}/api/data/v9.2/<EntitySetName>`++```powershell+$body = @{+ cr123_name = "Website Redesign"+ cr123_description = "Modernize the corporate website with a fresh design"+ cr123_startdate = "2025-06-15T10:30:00Z"+ cr123_budget = 15000.00+ cr123_isactive = $true+ cr123_status = 100000000+} | ConvertTo-Json++$response = Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/cr123_projects" -Headers $headers -Body $body -ContentType "application/json"+```++### Capturing the Created Record ID++The record ID is returned in the `OData-EntityId` response header. To capture it:++```powershell+$response = Invoke-WebRequest -Method Post -Uri "$envUrl/api/data/v9.2/cr123_projects" -Headers $headers -Body $body -ContentType "application/json"+$entityId = $response.Headers["OData-EntityId"] -replace '.*\(([^)]+)\).*', '$1'+```++Alternatively, use the `Prefer: return=representation` header to get the full record back:++```powershell+$headers["Prefer"] = "return=representation"+$response = Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/cr123_projects" -Headers $headers -Body $body -ContentType "application/json"+$recordId = $response.cr123_projectid+$headers.Remove("Prefer")+```++---++## Column Type Values++### String (SingleLine.Text)++Set as a plain string:++```json+{ "cr123_name": "Sample Value" }+```++### Memo (MultiLine.Text)++Set as a plain string (supports longer text):++```json+{ "cr123_description": "This is a longer description that can span multiple lines and paragraphs." }+```++### Integer (WholeNumber)++Set as an integer:++```json+{ "cr123_quantity": 42 }+```++### Decimal++Set as a decimal number:++```json+{ "cr123_rating": 4.75 }+```++### Currency (Money)++Set as a numeric value:++```json+{ "cr123_price": 99.99 }+```++### DateTime++Set as ISO 8601 format string:++```json+{ "cr123_startdate": "2025-06-15T10:30:00Z" }+```++For date-only fields:++```json+{ "cr123_birthdate": "2025-06-15" }+```++### Boolean++Set as `true` or `false`:++```json+{ "cr123_isactive": true }+```++### Choice / Picklist++Set as the integer option value (NOT the label text):++```json+{ "cr123_status": 100000000 }+```++Choice option values typically start at `100000000` and increment by 1.++### Lookup (Relationship Binding)++Use the `@odata.bind` annotation to reference a related record:++```json+{ "[email protected]": "/cr123_projects(00000000-0000-0000-0000-000000000001)" }+```++The format is: `"<lookup_logical_name>@odata.bind": "/<ReferencedEntitySetName>(<guid>)"`++---++## Getting Picklist Options++Before inserting records with picklist/choice columns, query the valid option values:++**Endpoint:** `GET {envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='<table>')/Attributes(LogicalName='<column>')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$expand=OptionSet`++```powershell+$picklistMeta = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='cr123_project')/Attributes(LogicalName='cr123_status')/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?`$expand=OptionSet" -Headers $headers++# Extract options+$options = $picklistMeta.OptionSet.Options+foreach ($opt in $options) {+ $value = $opt.Value # e.g., 100000000+ $label = $opt.Label.LocalizedLabels[0].Label # e.g., "Active"+}+```++Use these actual `Value` integers in your sample data — never guess option values.++---++## Lookup Binding Examples++### Single Lookup++A task referencing a project:++```powershell+$body = @{+ cr123_name = "Design mockups"+ cr123_duedate = "2025-07-01T00:00:00Z"+ "[email protected]" = "/cr123_projects($projectGuid)"+} | ConvertTo-Json++Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/cr123_tasks" -Headers $headers -Body $body -ContentType "application/json"+```++### Multiple Lookups++A record referencing multiple parent tables:++```powershell+$body = @{+ cr123_name = "Project Update Meeting"+ "[email protected]" = "/cr123_projects($projectGuid)"+ "[email protected]" = "/contacts($contactGuid)"+} | ConvertTo-Json+```++---++## Querying Record Count++Verify how many records exist in a table after insertion:++**Endpoint:** `GET {envUrl}/api/data/v9.2/<EntitySetName>?$count=true&$top=0`++```powershell+$result = Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/cr123_projects?`$count=true&`$top=0" -Headers $headers+$recordCount = $result."@odata.count"+```++The `$top=0` ensures no actual records are returned — only the count.++---++## Batch Operations (Optional)++For inserting many records efficiently, use OData batch requests to send multiple operations in a single HTTP call.++**Endpoint:** `POST {envUrl}/api/data/v9.2/$batch`++**Headers:**++```powershell+$batchId = [guid]::NewGuid().ToString()+$batchHeaders = @{+ Authorization = "Bearer $token"+ "Content-Type" = "multipart/mixed; boundary=batch_$batchId"+ Accept = "application/json"+}+```++**Body format:**++```+--batch_<batchId>+Content-Type: multipart/mixed; boundary=changeset_<changesetId>++--changeset_<changesetId>+Content-Type: application/http+Content-Transfer-Encoding: binary+Content-ID: 1++POST /api/data/v9.2/<EntitySetName> HTTP/1.1+Content-Type: application/json++{"cr123_name": "Record 1"}+--changeset_<changesetId>+Content-Type: application/http+Content-Transfer-Encoding: binary+Content-ID: 2++POST /api/data/v9.2/<EntitySetName> HTTP/1.1+Content-Type: application/json++{"cr123_name": "Record 2"}+--changeset_<changesetId>--+--batch_<batchId>--+```++**Note:** Batch requests share a single transaction per changeset — if one operation fails, all operations in that changeset are rolled back. Keep changesets small (5-10 operations) to limit blast radius of failures.++---++## Error Handling++See `${CLAUDE_PLUGIN_ROOT}/references/odata-common.md` for HTTP status codes, error response format, Dataverse error codes, and retry patterns.diff --git a/plugins/power-pages/skills/add-sample-data/references/sample-data-reference.md b/plugins/power-pages/skills/add-sample-data/references/sample-data-reference.mddeleted file mode 100644index 594d31be6..000000000--- a/plugins/power-pages/skills/add-sample-data/references/sample-data-reference.md+++ /dev/null@@ -1,462 +0,0 @@-# Sample Data Reference--## Insertion Order--Insert data by dependency tier:-1. **Tier 0** (reference tables) - Categories, Statuses, Departments (skip existing)-2. **Tier 1** (primary entities) - Products, Team Members (with lookups to Tier 0)-3. **Tier 2** (dependent tables) - Testimonials, Contact Submissions (with lookups to Tier 1)--**Important**: Check for existing data first. Never insert records with invalid lookup values.-```--## Check Existing Data--```powershell-function Get-ExistingRecordCount {- param([string]$EntitySetName)-- $result = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName/`$count" -Headers $headers- return [int]$result-}--function Get-ExistingRecordByName {- param(- [string]$EntitySetName,- [string]$NameColumn, # Usually "${publisherPrefix}_name" or the primary name attribute- [string]$NameValue- )-- $filter = "$NameColumn eq '$NameValue'"- $result = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName`?`$filter=$filter&`$top=1" -Headers $headers-- if ($result.value.Count -gt 0) {- return $result.value[0]- }- return $null-}--# Check existing data counts-# NOTE: Use $tableMap from Build-TableNameMapping for actual entity set names-Write-Host "`nChecking existing data in tables..." -ForegroundColor Cyan--# Build counts using table mapping (handles both reused and new tables)-$existingDataCounts = @{}-foreach ($purpose in @("category", "status", "department", "product", "teammember", "testimonial", "contactsubmission")) {- if ($tableMap.ContainsKey($purpose)) {- $entitySet = $tableMap[$purpose].EntitySetName- $existingDataCounts[$entitySet] = Get-ExistingRecordCount -EntitySetName $entitySet- }-}--Write-Host "`nExisting record counts:" -ForegroundColor Yellow-$existingDataCounts.GetEnumerator() | ForEach-Object {- $status = if ($_.Value -gt 0) { "[!]" } else { "[OK]" }- Write-Host " $status $($_.Key): $($_.Value) records"-}-```--## Create Record Helper Function--```powershell-function New-DataverseRecord {- param(- [string]$EntitySetName,- [hashtable]$Data- )-- $body = $Data | ConvertTo-Json -Depth 5- $response = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName" -Method Post -Headers $headers -Body $body- return $response-}-```--## Safe Record Creation (Skip If Exists)--```powershell-function New-DataverseRecordIfNotExists {- param(- [string]$EntitySetName,- [hashtable]$Data,- [string]$NameColumn = "${publisherPrefix}_name"- )-- $nameValue = $Data[$NameColumn]- $existing = Get-ExistingRecordByName -EntitySetName $EntitySetName -NameColumn $NameColumn -NameValue $nameValue-- if ($existing) {- Write-Host " [SKIP] Record '$nameValue' already exists - using existing" -ForegroundColor Yellow- return @{- Skipped = $true- Record = $existing- }- }-- Write-Host " [CREATE] Creating record '$nameValue'..." -ForegroundColor Cyan- $body = $Data | ConvertTo-Json -Depth 5- $response = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName" -Method Post -Headers $headers -Body $body- Write-Host " [OK] Record '$nameValue' created" -ForegroundColor Green-- return @{- Skipped = $false- Record = $response- }-}-```--## Foreign Key Syntax--When inserting records with lookup values, use the `@odata.bind` syntax:--```powershell-# Format: "[email protected]" = "/entitysetname(guid)"-# NOTE: Use $publisherPrefix from Initialize-DataverseApi--$product = @{- "${publisherPrefix}_name" = "Professional Consultation"- "${publisherPrefix}_description" = "One-on-one consultation with our expert team."- "${publisherPrefix}_price" = 299.99- # Reference category by its ID- "${publisherPrefix}[email protected]" = "/${publisherPrefix}_categories($categoryId)"-}-```--## Complete Sample Data Script--**IMPORTANT**: Use the `$tableMap` from `Build-TableNameMapping` to get the correct table names and entity set names. This ensures:-- **Reused tables**: Use their actual logical names and column names from Dataverse-- **New tables**: Use the publisher prefix pattern--```powershell-$api = Initialize-DataverseApi -EnvironmentUrl "https://orgname.crm.dynamics.com"-$publisherPrefix = $api.PublisherPrefix--# $tableMap should be built in STEP 5 using Build-TableNameMapping-# It maps table purposes to actual logical names and entity set names-```--### Helper Functions for Table Mapping--```powershell-# Get entity set name from table mapping-function Get-EntitySet { param([string]$Purpose) return $tableMap[$Purpose].EntitySetName }--# Get table logical name from mapping-function Get-TableName { param([string]$Purpose) return $tableMap[$Purpose].LogicalName }--# Get the primary key column name for a table-# For reused tables, this may differ from the standard pattern-function Get-PrimaryKeyColumn {- param([string]$Purpose)- $tableName = Get-TableName $Purpose- # Primary key is typically {tablename}id- return "${tableName}id"-}-```--```powershell-# ============================================-# TIER 0: Insert Reference/Lookup Data FIRST-# ============================================--Write-Host "`n=== TIER 0: Processing Reference/Lookup Data ===" -ForegroundColor Magenta--# --- Categories ----$categoryIds = @{}-$categoryEntitySet = Get-EntitySet "category"-$categoryPK = Get-PrimaryKeyColumn "category"--# NOTE: For reused tables, column names may use the existing table's prefix-# For new tables, use $publisherPrefix for column names-$categories = @(- @{ "${publisherPrefix}_name" = "Services"; "${publisherPrefix}_description" = "Professional services"; "${publisherPrefix}_displayorder" = 1; "${publisherPrefix}_isactive" = $true },- @{ "${publisherPrefix}_name" = "Packages"; "${publisherPrefix}_description" = "Bundled offerings"; "${publisherPrefix}_displayorder" = 2; "${publisherPrefix}_isactive" = $true },- @{ "${publisherPrefix}_name" = "Products"; "${publisherPrefix}_description" = "Physical and digital products"; "${publisherPrefix}_displayorder" = 3; "${publisherPrefix}_isactive" = $true }-)--Write-Host "Processing categories (using $categoryEntitySet)..." -ForegroundColor Cyan-foreach ($cat in $categories) {- $result = New-DataverseRecordIfNotExists -EntitySetName $categoryEntitySet -Data $cat -NameColumn "${publisherPrefix}_name"- $categoryIds[$cat["${publisherPrefix}_name"]] = $result.Record.$categoryPK-}--# --- Statuses ----$statusIds = @{}-$statusEntitySet = Get-EntitySet "status"-$statusPK = Get-PrimaryKeyColumn "status"--$statuses = @(- @{ "${publisherPrefix}_name" = "New"; "${publisherPrefix}_displayorder" = 1 },- @{ "${publisherPrefix}_name" = "Reviewed"; "${publisherPrefix}_displayorder" = 2 },- @{ "${publisherPrefix}_name" = "Responded"; "${publisherPrefix}_displayorder" = 3 },- @{ "${publisherPrefix}_name" = "Closed"; "${publisherPrefix}_displayorder" = 4 }-)--Write-Host "`nProcessing statuses (using $statusEntitySet)..." -ForegroundColor Cyan-foreach ($status in $statuses) {- $result = New-DataverseRecordIfNotExists -EntitySetName $statusEntitySet -Data $status -NameColumn "${publisherPrefix}_name"- $statusIds[$status["${publisherPrefix}_name"]] = $result.Record.$statusPK-}--# --- Departments ----$departmentIds = @{}-$departmentEntitySet = Get-EntitySet "department"-$departmentPK = Get-PrimaryKeyColumn "department"--$departments = @(- @{ "${publisherPrefix}_name" = "Executive"; "${publisherPrefix}_code" = "EXEC" },- @{ "${publisherPrefix}_name" = "Engineering"; "${publisherPrefix}_code" = "ENG" },- @{ "${publisherPrefix}_name" = "Customer Success"; "${publisherPrefix}_code" = "CS" },- @{ "${publisherPrefix}_name" = "Sales"; "${publisherPrefix}_code" = "SALES" }-)--Write-Host "`nProcessing departments (using $departmentEntitySet)..." -ForegroundColor Cyan-foreach ($dept in $departments) {- $result = New-DataverseRecordIfNotExists -EntitySetName $departmentEntitySet -Data $dept -NameColumn "${publisherPrefix}_name"- $departmentIds[$dept["${publisherPrefix}_name"]] = $result.Record.$departmentPK-}--# ============================================-# TIER 1: Insert Primary Entity Data-# ============================================--Write-Host "`n=== TIER 1: Processing Primary Entity Data ===" -ForegroundColor Magenta--# --- Products (with Category lookup) ----$productIds = @{}-$productEntitySet = Get-EntitySet "product"-$productPK = Get-PrimaryKeyColumn "product"--# NOTE: For lookup bindings, use the actual entity set name from the table mapping-$products = @(- @{- "${publisherPrefix}_name" = "Professional Consultation"- "${publisherPrefix}_description" = "One-on-one consultation with our expert team."- "${publisherPrefix}_price" = 299.99- "${publisherPrefix}_imageurl" = "https://images.unsplash.com/photo-1553877522-43269d4ea984?w=400"- "${publisherPrefix}_isactive" = $true- "${publisherPrefix}[email protected]" = "/$categoryEntitySet($($categoryIds['Services']))"- },- @{- "${publisherPrefix}_name" = "Enterprise Solution Package"- "${publisherPrefix}_description" = "Complete enterprise solution with 12 months support."- "${publisherPrefix}_price" = 4999.99- "${publisherPrefix}_imageurl" = "https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=400"- "${publisherPrefix}_isactive" = $true- "${publisherPrefix}[email protected]" = "/$categoryEntitySet($($categoryIds['Packages']))"- },- @{- "${publisherPrefix}_name" = "Starter Kit"- "${publisherPrefix}_description" = "Perfect for small businesses getting started."- "${publisherPrefix}_price" = 99.99- "${publisherPrefix}_imageurl" = "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400"- "${publisherPrefix}_isactive" = $true- "${publisherPrefix}[email protected]" = "/$categoryEntitySet($($categoryIds['Packages']))"- }-)--Write-Host "Processing products (using $productEntitySet)..." -ForegroundColor Cyan-foreach ($product in $products) {- $result = New-DataverseRecordIfNotExists -EntitySetName $productEntitySet -Data $product -NameColumn "${publisherPrefix}_name"- $productIds[$product["${publisherPrefix}_name"]] = $result.Record.$productPK-}--# --- Team Members (with Department lookup) ----$teamMemberIds = @{}-$teammemberEntitySet = Get-EntitySet "teammember"-$teammemberPK = Get-PrimaryKeyColumn "teammember"--$team = @(- @{- "${publisherPrefix}_name" = "Emily Rodriguez"- "${publisherPrefix}_title" = "Chief Executive Officer"- "${publisherPrefix}_email" = "[email protected]"- "${publisherPrefix}_bio" = "Emily has over 15 years of experience in technology leadership."- "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=300"- "${publisherPrefix}_linkedin" = "https://linkedin.com/in/emilyrodriguez"- "${publisherPrefix}_displayorder" = 1- "${publisherPrefix}[email protected]" = "/$departmentEntitySet($($departmentIds['Executive']))"- },- @{- "${publisherPrefix}_name" = "David Kim"- "${publisherPrefix}_title" = "Chief Technology Officer"- "${publisherPrefix}_email" = "[email protected]"- "${publisherPrefix}_bio" = "David brings deep technical expertise from his decade at leading tech companies."- "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=300"- "${publisherPrefix}_linkedin" = "https://linkedin.com/in/davidkim"- "${publisherPrefix}_displayorder" = 2- "${publisherPrefix}[email protected]" = "/$departmentEntitySet($($departmentIds['Engineering']))"- },- @{- "${publisherPrefix}_name" = "Lisa Thompson"- "${publisherPrefix}_title" = "Head of Customer Success"- "${publisherPrefix}_email" = "[email protected]"- "${publisherPrefix}_bio" = "Lisa ensures our customers achieve their goals."- "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1580489944761-15a19d654956?w=300"- "${publisherPrefix}_linkedin" = "https://linkedin.com/in/lisathompson"- "${publisherPrefix}_displayorder" = 3- "${publisherPrefix}[email protected]" = "/$departmentEntitySet($($departmentIds['Customer Success']))"- }-)--Write-Host "`nProcessing team members (using $teammemberEntitySet)..." -ForegroundColor Cyan-foreach ($member in $team) {- $result = New-DataverseRecordIfNotExists -EntitySetName $teammemberEntitySet -Data $member -NameColumn "${publisherPrefix}_name"- $teamMemberIds[$member["${publisherPrefix}_name"]] = $result.Record.$teammemberPK-}--# ============================================-# TIER 2: Insert Dependent Data-# ============================================--Write-Host "`n=== TIER 2: Processing Dependent Data ===" -ForegroundColor Magenta--# --- Contact Submissions (with Status lookup) ----$contactsubmissionEntitySet = Get-EntitySet "contactsubmission"--$contacts = @(- @{- "${publisherPrefix}_name" = "John Smith"- "${publisherPrefix}_email" = "[email protected]"- "${publisherPrefix}_message" = "I'm interested in learning more about your services."- "${publisherPrefix}_submissiondate" = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")- "${publisherPrefix}[email protected]" = "/$statusEntitySet($($statusIds['New']))"- },- @{- "${publisherPrefix}_name" = "Sarah Johnson"- "${publisherPrefix}_email" = "[email protected]"- "${publisherPrefix}_message" = "Looking for a partner for our upcoming project."- "${publisherPrefix}_submissiondate" = (Get-Date).AddDays(-2).ToString("yyyy-MM-ddTHH:mm:ssZ")- "${publisherPrefix}[email protected]" = "/$statusEntitySet($($statusIds['Reviewed']))"- },- @{- "${publisherPrefix}_name" = "Michael Chen"- "${publisherPrefix}_email" = "[email protected]"- "${publisherPrefix}_message" = "Questions about pricing and availability."- "${publisherPrefix}_submissiondate" = (Get-Date).AddDays(-5).ToString("yyyy-MM-ddTHH:mm:ssZ")- "${publisherPrefix}[email protected]" = "/$statusEntitySet($($statusIds['Responded']))"- }-)--Write-Host "Processing contact submissions (using $contactsubmissionEntitySet)..." -ForegroundColor Cyan-foreach ($contact in $contacts) {- New-DataverseRecordIfNotExists -EntitySetName $contactsubmissionEntitySet -Data $contact -NameColumn "${publisherPrefix}_name"-}--# --- Testimonials (with optional Product lookup) ----$testimonialEntitySet = Get-EntitySet "testimonial"--$testimonials = @(- @{- "${publisherPrefix}_name" = "Amanda Foster"- "${publisherPrefix}_quote" = "Their solution increased our efficiency by 40%."- "${publisherPrefix}_company" = "TechStart Inc."- "${publisherPrefix}_role" = "Operations Director"- "${publisherPrefix}_rating" = 5- "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=200"- "${publisherPrefix}_isactive" = $true- "${publisherPrefix}[email protected]" = "/$productEntitySet($($productIds['Enterprise Solution Package']))"- },- @{- "${publisherPrefix}_name" = "Robert Martinez"- "${publisherPrefix}_quote" = "The best investment we've made this year."- "${publisherPrefix}_company" = "Global Solutions Ltd"- "${publisherPrefix}_role" = "CEO"- "${publisherPrefix}_rating" = 5- "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200"- "${publisherPrefix}_isactive" = $true- "${publisherPrefix}[email protected]" = "/$productEntitySet($($productIds['Professional Consultation']))"- },- @{- "${publisherPrefix}_name" = "Jennifer Wu"- "${publisherPrefix}_quote" = "Delivered beyond expectations. Highly recommend."- "${publisherPrefix}_company" = "Innovate Partners"- "${publisherPrefix}_role" = "Managing Partner"- "${publisherPrefix}_rating" = 5- "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=200"- "${publisherPrefix}_isactive" = $true- # General testimonial - no specific product linked- }-)--Write-Host "`nProcessing testimonials (using $testimonialEntitySet)..." -ForegroundColor Cyan-foreach ($testimonial in $testimonials) {- New-DataverseRecordIfNotExists -EntitySetName $testimonialEntitySet -Data $testimonial -NameColumn "${publisherPrefix}_name"-}--Write-Host "`n=== Sample data processing complete ===" -ForegroundColor Green-```--## Verify Data and Relationships--**NOTE**: Use the `$tableMap` entity set names to query the correct tables (handles both reused and new tables).--```powershell-# Verify products with their categories (expanded relationship)-$productEntitySet = Get-EntitySet "product"-Write-Host "Products with Categories (from $productEntitySet):" -ForegroundColor Cyan-$products = Invoke-RestMethod -Uri "$baseUrl/$productEntitySet`?`$select=${publisherPrefix}_name,${publisherPrefix}_price&`$expand=${publisherPrefix}_categoryid(`$select=${publisherPrefix}_name)" -Headers $headers-$products.value | ForEach-Object {- Write-Host " $($_."${publisherPrefix}_name") - `$$($_."${publisherPrefix}_price") - Category: $($_."${publisherPrefix}_categoryid"."${publisherPrefix}_name")"-}--# Verify team members with their departments-$teammemberEntitySet = Get-EntitySet "teammember"-Write-Host "`nTeam Members with Departments (from $teammemberEntitySet):" -ForegroundColor Cyan-$members = Invoke-RestMethod -Uri "$baseUrl/$teammemberEntitySet`?`$select=${publisherPrefix}_name,${publisherPrefix}_title&`$expand=${publisherPrefix}_departmentid(`$select=${publisherPrefix}_name)" -Headers $headers-$members.value | ForEach-Object {- Write-Host " $($_."${publisherPrefix}_name") ($($_."${publisherPrefix}_title")) - Dept: $($_."${publisherPrefix}_departmentid"."${publisherPrefix}_name")"-}--# Verify contact submissions with their statuses-$contactsubmissionEntitySet = Get-EntitySet "contactsubmission"-Write-Host "`nContact Submissions with Statuses (from $contactsubmissionEntitySet):" -ForegroundColor Cyan-$submissions = Invoke-RestMethod -Uri "$baseUrl/$contactsubmissionEntitySet`?`$select=${publisherPrefix}_name,${publisherPrefix}_email&`$expand=${publisherPrefix}_statusid(`$select=${publisherPrefix}_name)" -Headers $headers-$submissions.value | ForEach-Object {- Write-Host " $($_."${publisherPrefix}_name") ($($_."${publisherPrefix}_email")) - Status: $($_."${publisherPrefix}_statusid"."${publisherPrefix}_name")"-}--# Verify testimonials with their linked products-$testimonialEntitySet = Get-EntitySet "testimonial"-Write-Host "`nTestimonials with Products (from $testimonialEntitySet):" -ForegroundColor Cyan-$testimonials = Invoke-RestMethod -Uri "$baseUrl/$testimonialEntitySet`?`$select=${publisherPrefix}_name,${publisherPrefix}_company&`$expand=${publisherPrefix}_productid(`$select=${publisherPrefix}_name)" -Headers $headers-$testimonials.value | ForEach-Object {- $productName = if ($_."${publisherPrefix}_productid") { $_."${publisherPrefix}_productid"."${publisherPrefix}_name" } else { "(General)" }- Write-Host " $($_."${publisherPrefix}_name") from $($_."${publisherPrefix}_company") - Product: $productName"-}-```--## Update Records--```powershell-function Update-DataverseRecord {- param(- [string]$EntitySetName,- [string]$RecordId,- [hashtable]$Data- )-- $body = $Data | ConvertTo-Json -Depth 5- Invoke-RestMethod -Uri "$baseUrl/$EntitySetName($RecordId)" -Method Patch -Headers $headers -Body $body-}--# Example: Update a product's price-Update-DataverseRecord -EntitySetName "${publisherPrefix}_products" -RecordId $productIds['Starter Kit'] -Data @{- "${publisherPrefix}_price" = 129.99-}-```--## Delete Records--```powershell-function Remove-DataverseRecord {- param(- [string]$EntitySetName,- [string]$RecordId- )-- Invoke-RestMethod -Uri "$baseUrl/$EntitySetName($RecordId)" -Method Delete -Headers $headers-}--# CAUTION: Delete records in reverse dependency order (TIER 2 -> TIER 1 -> TIER 0)-```diff --git a/plugins/power-pages/skills/add-seo/SKILL.md b/plugins/power-pages/skills/add-seo/SKILL.mdindex b779715c5..1f4b69ec0 100644--- a/plugins/power-pages/skills/add-seo/SKILL.md+++ b/plugins/power-pages/skills/add-seo/SKILL.md@@ -1,97 +1,385 @@----name: adding-seo-description: Adds SEO assets to Power Pages sites including meta tags, robots.txt, sitemap.xml, and favicon. Use when adding search engine optimization, social sharing images, or meta tags.+name: add-seo+description: >+ This skill should be used when the user asks to "add SEO", "add meta tags",+ "add robots.txt", "add sitemap", "improve SEO", "search engine optimization",+ "add open graph tags", "add favicon", "make site searchable",+ or wants to add SEO essentials (robots.txt, sitemap.xml, meta tags) to their+ Power Pages code site after creating it with /power-pages:create-site.user-invocable: true-allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "AskUserQuestion"]-model: haiku+allowed-tools: ["Read", "Write", "Edit", "Grep", "Glob", "Bash", "AskUserQuestion", "Task", "TaskCreate", "TaskUpdate", "TaskList", "mcp__plugin_power-pages_playwright__browser_navigate", "mcp__plugin_power-pages_playwright__browser_snapshot", "mcp__plugin_power-pages_playwright__browser_click", "mcp__plugin_power-pages_playwright__browser_close"]+model: opus+hooks:+ Stop:+ - hooks:+ - type: command+ command: "node \"${CLAUDE_PLUGIN_ROOT}/skills/add-seo/scripts/validate-seo.js\""+ timeout: 15+ - type: prompt+ prompt: "If SEO assets were being added in this session (via /power-pages:add-seo), verify before allowing stop: 1) robots.txt was created in the public directory, 2) sitemap.xml was created in the public directory with correct site URLs, 3) Meta tags (title, description, viewport, Open Graph) were added to index.html, 4) The user reviewed and approved the SEO additions, 5) A git commit was made with the SEO changes. If any of these are incomplete, return { \"ok\": false, \"reason\": \"<specific issues>\" }. If no SEO work happened or everything is complete, return { \"ok\": true }."+ timeout: 30----**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.+# Add SEO-# Add SEO Assets+Add essential SEO assets to a Power Pages code site: `robots.txt`, `sitemap.xml`, and meta tags.-**References:** [seo](./references/seo-reference.md)+> **Prerequisite:** This skill expects an existing Power Pages code site created via `/power-pages:create-site`. Run that skill first if the site does not exist yet.-Adds search engine optimization assets to an existing Power Pages code site.+## Core Principles-## Prerequisites+- **Crawlability first:** Every public page must be discoverable by search engines via a valid `robots.txt` and `sitemap.xml` before any other SEO work matters.+- **Accurate metadata:** Meta tags (title, description, Open Graph) must truthfully represent page content — misleading metadata harms rankings.+- **Framework-aware placement:** SEO assets must be placed in the correct location for the detected framework (public directory, layout component, etc.).-- Site created with `/create-site`-- `index.html` exists in project root+**Initial request:** $ARGUMENTS## Workflow-1. **Gather Info** → Ask site name, description, subdomain, primary color-2. **Update Meta Tags** → Add SEO and Open Graph meta tags to `index.html`-3. **Create robots.txt** → Search engine crawl directives-4. **Create sitemap.xml** → Site structure for search engines-5. **Add Favicon** → Placeholder favicon files (user replaces with actual assets)-6. **Build and Upload** → Deploy changes+1. **Phase 1: Verify Site Exists** → Locate the Power Pages project+2. **Phase 2: Gather SEO Configuration** → Site URL, pages, preferences+3. **Phase 3: Plan & Approve** → Present SEO additions inline, get user approval+4. **Phase 4: Add robots.txt** → Create robots.txt in public directory+5. **Phase 5: Add sitemap.xml** → Generate sitemap.xml from site routes+6. **Phase 6: Add Meta Tags** → Add title, description, viewport, Open Graph, and favicon to index.html+7. **Phase 7: Verify & Commit** → Verify via Playwright, commit changes----## Step 1: Gather Info+## Phase 1: Verify Site Exists-Use `AskUserQuestion` to collect:-1. Site name (for title and og:site_name)-2. Site description (150-160 chars for meta description)-3. Expected subdomain (for canonical URLs)-4. Primary brand color (hex, for theme-color)+**Goal:** Confirm a Power Pages code site exists and understand its structure.++### Actions++#### 1.1 Locate Project++Look for `powerpages.config.json` in the current directory or immediate subdirectories to find the project root.++```powershell+# Check current directory and subdirectories+Get-ChildItem -Path . -Filter "powerpages.config.json" -Recurse -Depth 1+```++**If not found**: Tell the user to create a site first with `/power-pages:create-site`.++#### 1.2 Read Existing Config++Read `powerpages.config.json` to get the site name and config:++```powershell+Get-Content "<PROJECT_ROOT>/powerpages.config.json" | ConvertFrom-Json+```++#### 1.3 Detect Framework & Discover Routes++Read `package.json` to determine the framework and locate key files. See `${CLAUDE_PLUGIN_ROOT}/references/framework-conventions.md` for the full framework → public directory → index HTML mapping and route discovery patterns.++Build a list of all routes (e.g., `/`, `/about`, `/contact`, `/blog`).++### Output++- Project root path identified+- Framework detected (React, Vue, Angular, or Astro)+- Full list of discoverable routes----## Step 2: Update Meta Tags+## Phase 2: Gather SEO Configuration++**Goal:** Collect all SEO preferences from the user before making any changes.++### Actions++Use `AskUserQuestion` to collect SEO preferences:++#### Call 1:-See [seo-reference.md](./references/seo-reference.md#meta-tags-template).+| Question | Header | Options |+|----------|--------|---------|+| What is the production URL for your site? (e.g., https://contoso.powerappsportals.com) | Site URL | *(free text — use single generic option so user types via "Other")* |+| Which pages should be excluded from search engine indexing? | Exclusions | None — index all pages (Recommended), Admin/auth pages only, Let me specify |-Update `index.html` with:-- Primary meta tags (title, description, keywords, author, robots)-- Canonical URL-- Open Graph tags (og:title, og:description, og:image, etc.)-- Twitter card tags-- Favicon links-- Theme color+#### Call 2:++| Question | Header | Options |+|----------|--------|---------|+| What meta description should appear in search results? | Description | *(free text — use single generic option so user types via "Other")* |+| Add Open Graph tags for social media sharing? | OG Tags | Yes — add Open Graph and Twitter Card tags (Recommended), No — skip social tags |++### Output++- Production URL confirmed+- Exclusion list finalized+- Meta description text+- Open Graph tag preference (yes/no)----## Step 3: Create robots.txt+## Phase 3: Plan & Approve++**Goal:** Present the full SEO plan to the user and get explicit approval before making changes.++### Actions++Present the SEO additions that will be made as a clear, inline summary:-Create `public/robots.txt`:+1. **robots.txt content** — which paths will be allowed/disallowed+2. **sitemap.xml content** — all discovered routes with the production URL and priority assignments+3. **Meta tags to add to index.html** — title, description, viewport, charset, Open Graph, Twitter Card+4. **Favicon** — link tag and placeholder SVG-```txt+After presenting the plan, use `AskUserQuestion` to get approval:++| Question | Header | Options |+|----------|--------|---------|+| Here is the SEO plan. How would you like to proceed? | SEO Plan Approval | Approve and proceed (Recommended), I'd like to make changes |++If the user chooses "I'd like to make changes", ask what they want to change, update the plan accordingly, and present the revised plan for approval again.++### Output++- User-approved SEO plan ready for implementation++---++## Phase 4: Add robots.txt++**Goal:** Create a valid `robots.txt` that tells search engines which pages to crawl.++### Actions++Create `robots.txt` in the public directory (`<PROJECT_ROOT>/public/robots.txt`):++```text+User-agent: *+Allow: /++Sitemap: <PRODUCTION_URL>/sitemap.xml+```++If the user specified pages to exclude, add `Disallow` directives:++```textUser-agent: *Allow: /-Sitemap: https://[subdomain].powerappsportals.com/sitemap.xml+Disallow: /admin/+Disallow: /auth/++Sitemap: <PRODUCTION_URL>/sitemap.xml```+### Output++- `public/robots.txt` created with correct directives+----## Step 4: Create sitemap.xml+## Phase 5: Add sitemap.xml++**Goal:** Generate a complete `sitemap.xml` listing all discoverable routes with proper priorities.++### Actions++Create `sitemap.xml` in the public directory (`<PROJECT_ROOT>/public/sitemap.xml`).++Generate entries for each discovered route using the production URL:++```xml+<?xml version="1.0" encoding="UTF-8"?>+<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">+ <url>+ <loc><PRODUCTION_URL>/</loc>+ <lastmod><TODAY_DATE></lastmod>+ <changefreq>weekly</changefreq>+ <priority>1.0</priority>+ </url>+ <url>+ <loc><PRODUCTION_URL>/about</loc>+ <lastmod><TODAY_DATE></lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.8</priority>+ </url>+ <!-- Additional routes... -->+</urlset>+```++**Priority rules:**+- Home page (`/`): `1.0`+- Top-level pages: `0.8`+- Sub-pages: `0.6`++**Exclusions:** Do not include routes the user chose to exclude (e.g., `/admin/*`, `/auth/*`).-Create `public/sitemap.xml` with entries for each page. See [seo-reference.md](./references/seo-reference.md#sitemapxml) for format.+### Output-Priority guidelines: Homepage=1.0, Main sections=0.8, Secondary=0.7, Blog=0.6, Legal=0.3+- `public/sitemap.xml` created with all routes, correct URLs, and no placeholders----## Step 5: Add Favicon Placeholders+## Phase 6: Add Meta Tags++**Goal:** Add comprehensive meta tags, Open Graph tags, and a favicon to the site's HTML.++### Actions++#### 6.1 Essential Meta Tags++Add or update meta tags in the site's `index.html` (location depends on framework — see Phase 1.3):++```html+<head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title><SITE_TITLE></title>+ <meta name="description" content="<META_DESCRIPTION>" />+ <meta name="robots" content="index, follow" />+ <link rel="canonical" href="<PRODUCTION_URL>/" />+ <link rel="sitemap" type="application/xml" href="/sitemap.xml" />+</head>+```++#### 6.2 Open Graph Tags (if user opted in)-Create placeholder files in `public/`:-- `favicon.ico` (48x48)-- `favicon-32x32.png` (32x32)-- `favicon-16x16.png` (16x16)-- `apple-touch-icon.png` (180x180)-- `og-image.png` (1200x630) - social sharing image+Add Open Graph and Twitter Card meta tags inside `<head>`:-Tell user to replace these with actual brand assets.+```html+<!-- Open Graph -->+<meta property="og:type" content="website" />+<meta property="og:title" content="<SITE_TITLE>" />+<meta property="og:description" content="<META_DESCRIPTION>" />+<meta property="og:url" content="<PRODUCTION_URL>/" />+<meta property="og:site_name" content="<SITE_TITLE>" />++<!-- Twitter Card -->+<meta name="twitter:card" content="summary" />+<meta name="twitter:title" content="<SITE_TITLE>" />+<meta name="twitter:description" content="<META_DESCRIPTION>" />+```++#### 6.3 Favicon++Check if a favicon already exists in the public directory. If not, add a simple SVG favicon link:++```html+<link rel="icon" type="image/svg+xml" href="/favicon.svg" />+```++Create a minimal placeholder `public/favicon.svg` using the site's primary color:++```xml+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">+ <rect width="100" height="100" rx="20" fill="<PRIMARY_COLOR>"/>+ <text x="50" y="70" font-size="50" text-anchor="middle" fill="white" font-family="system-ui, sans-serif" font-weight="bold"><FIRST_LETTER></text>+</svg>+```++Where `<FIRST_LETTER>` is the first letter of the site name and `<PRIMARY_COLOR>` is the primary theme color from the site's configuration.++#### 6.4 Astro-Specific Handling++For Astro sites, meta tags should be added to the base layout component (e.g., `src/layouts/Layout.astro`) rather than a root `index.html`. Astro uses component-based `<head>` management.++### Output++- Meta tags added to `index.html` (or Astro layout equivalent)+- Open Graph and Twitter Card tags added (if opted in)+- Favicon SVG created and linked (if not already present)----## Step 6: Build and Upload+## Phase 7: Verify & Commit++**Goal:** Confirm all SEO assets are in place, verify via Playwright, and commit changes.++### Actions++#### 7.1 Verify Files Exist++Confirm the following files were created/updated:+- `public/robots.txt`+- `public/sitemap.xml`+- `public/favicon.svg` (if created)+- `index.html` or equivalent (meta tags added)++#### 7.2 Verify via Playwright++If a dev server is running (or start one):++1. Navigate to the site root and use `browser_snapshot` to verify meta tags are present in the page source+2. Navigate to `/robots.txt` and verify it loads+3. Navigate to `/sitemap.xml` and verify it loads++#### 7.3 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 "AddSeo"`.++#### 7.4 Git Commit++> **CRITICAL — This step is MANDATORY. You MUST commit the SEO changes before finishing. Do NOT skip this step.**++Stage the specific SEO files and commit:```powershell-npm run build-pac pages upload-code-site --rootPath "<PROJECT_ROOT>"+git add public/robots.txt public/sitemap.xml public/favicon.svg index.html+git commit -m "Add SEO: robots.txt, sitemap.xml, meta tags, favicon"```-Update memory-bank.md with SEO status.+Adjust the file paths based on what was actually created (e.g., include `src/layouts/Layout.astro` instead of `index.html` for Astro sites, omit `favicon.svg` if it was not created). Only stage files that were created or modified by this skill.++#### 7.5 Present Summary++Present a summary of what was added:++| Asset | Status | Details |+|-------|--------|---------|+| `robots.txt` | Created | Allows all crawlers, references sitemap |+| `sitemap.xml` | Created | X URLs mapped with priorities |+| Meta tags | Added | title, description, viewport, canonical, robots |+| Open Graph | Added/Skipped | og:title, og:description, og:url, Twitter Card |+| Favicon | Created/Skipped | SVG favicon with site initial |++#### 7.6 Suggest Next Steps++After the summary, suggest:+- **Deploy the site** to make SEO changes live: `/power-pages:deploy-site`+- If data model is needed: `/power-pages:setup-datamodel`+- For more advanced SEO: consider structured data (JSON-LD), performance optimization, and accessibility audit++### Output++- All files verified on disk+- Playwright verification passed+- Git commit created with all SEO changes++---++## Important Notes++### Progress Tracking++Use `TaskCreate` at the start to track each phase:++| Task | Description |+|------|-------------|+| Phase 1 | Verify site exists and detect framework |+| Phase 2 | Gather SEO configuration from user |+| Phase 3 | Present plan and get user approval |+| Phase 4 | Create robots.txt |+| Phase 5 | Generate sitemap.xml |+| Phase 6 | Add meta tags, Open Graph, and favicon |+| Phase 7 | Verify via Playwright and commit |++Update each task with `TaskUpdate` as it is completed.++### Key Decision Points++- **Phase 1:** If `powerpages.config.json` is not found, stop and redirect the user to `/power-pages:create-site`.+- **Phase 2:** If the user specifies custom exclusions, confirm the exact paths before proceeding.+- **Phase 3:** Do not proceed to implementation until the user explicitly approves the plan.+- **Phase 6.4:** If the framework is Astro, meta tags go into the layout component, not `index.html`.+- **Phase 7.2:** If Playwright verification fails (e.g., robots.txt does not load), diagnose and fix before committing.++**Begin with Phase 1: Verify Site Exists**diff --git a/plugins/power-pages/skills/add-seo/references/seo-reference.md b/plugins/power-pages/skills/add-seo/references/seo-reference.mddeleted file mode 100644index 517923957..000000000--- a/plugins/power-pages/skills/add-seo/references/seo-reference.md+++ /dev/null@@ -1,152 +0,0 @@-# SEO Reference--## Meta Tags Template--Ensure the `index.html` file includes comprehensive meta tags for SEO and social sharing:--```html-<!DOCTYPE html>-<html lang="en">-<head>- <!-- Character encoding and viewport -->- <meta charset="UTF-8" />- <meta name="viewport" content="width=device-width, initial-scale=1.0" />-- <!-- Primary Meta Tags -->- <title>[SITE_NAME] - [Brief Description]</title>- <meta name="title" content="[SITE_NAME] - [Brief Description]" />- <meta name="description" content="[150-160 character description of the site's purpose and value proposition]" />- <meta name="keywords" content="[keyword1], [keyword2], [keyword3], [relevant keywords]" />- <meta name="author" content="[Company/Author Name]" />- <meta name="robots" content="index, follow" />-- <!-- Canonical URL -->- <link rel="canonical" href="https://[subdomain].powerappsportals.com/" />-- <!-- Open Graph / Facebook -->- <meta property="og:type" content="website" />- <meta property="og:url" content="https://[subdomain].powerappsportals.com/" />- <meta property="og:title" content="[SITE_NAME] - [Brief Description]" />- <meta property="og:description" content="[Description for social sharing]" />- <meta property="og:image" content="https://[subdomain].powerappsportals.com/og-image.png" />- <meta property="og:image:width" content="1200" />- <meta property="og:image:height" content="630" />- <meta property="og:site_name" content="[SITE_NAME]" />- <meta property="og:locale" content="en_US" />-- <!-- Twitter -->- <meta name="twitter:card" content="summary_large_image" />- <meta name="twitter:url" content="https://[subdomain].powerappsportals.com/" />- <meta name="twitter:title" content="[SITE_NAME] - [Brief Description]" />- <meta name="twitter:description" content="[Description for Twitter sharing]" />- <meta name="twitter:image" content="https://[subdomain].powerappsportals.com/og-image.png" />-- <!-- Favicon -->- <link rel="icon" type="image/x-icon" href="/favicon.ico" />- <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />- <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />- <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />-- <!-- Theme Color (for mobile browsers) -->- <meta name="theme-color" content="#[PRIMARY_COLOR_HEX]" />- <meta name="msapplication-TileColor" content="#[PRIMARY_COLOR_HEX]" />-- <!-- Additional SEO -->- <meta name="format-detection" content="telephone=no" />- <meta http-equiv="X-UA-Compatible" content="IE=edge" />-</head>-```--## Required SEO Assets--Place these assets in the `public/` folder:--| Asset | Size/Format | Purpose |-|-------|-------------|---------|-| `og-image.png` | 1200×630px | Social media sharing preview |-| `favicon.ico` | 48×48px | Browser tab icon |-| `favicon-32x32.png` | 32×32px | Modern browsers |-| `favicon-16x16.png` | 16×16px | Small displays |-| `apple-touch-icon.png` | 180×180px | iOS home screen |-| `robots.txt` | Text file | Search engine crawl directives |-| `sitemap.xml` | XML file | Site structure for search engines |-------## robots.txt--Create `robots.txt` in the `public/` folder:--```txt-# robots.txt for [SITE_NAME]-# https://[subdomain].powerappsportals.com/robots.txt--User-agent: *-Allow: /--# Sitemap location-Sitemap: https://[subdomain].powerappsportals.com/sitemap.xml--# Disallow admin or private paths (if any)-# Disallow: /admin/-# Disallow: /private/-```-------## sitemap.xml--Create `sitemap.xml` in the `public/` folder:--```xml-<?xml version="1.0" encoding="UTF-8"?>-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">- <!-- Homepage -->- <url>- <loc>https://[subdomain].powerappsportals.com/</loc>- <lastmod>[YYYY-MM-DD]</lastmod>- <changefreq>weekly</changefreq>- <priority>1.0</priority>- </url>-- <!-- About Page -->- <url>- <loc>https://[subdomain].powerappsportals.com/about</loc>- <lastmod>[YYYY-MM-DD]</lastmod>- <changefreq>monthly</changefreq>- <priority>0.8</priority>- </url>-- <!-- Contact Page -->- <url>- <loc>https://[subdomain].powerappsportals.com/contact</loc>- <lastmod>[YYYY-MM-DD]</lastmod>- <changefreq>monthly</changefreq>- <priority>0.8</priority>- </url>-- <!-- Services/Products Page -->- <url>- <loc>https://[subdomain].powerappsportals.com/services</loc>- <lastmod>[YYYY-MM-DD]</lastmod>- <changefreq>monthly</changefreq>- <priority>0.7</priority>- </url>-- <!-- Add all public pages in your SPA -->-</urlset>-```--**Priority guidelines**: Homepage=1.0, Main sections=0.8, Secondary pages=0.7, Blog=0.6, Legal=0.3--**SPA note**: Use history mode routing (`/about`) not hash routing (`/#/about`) for proper indexing.--## Framework-Specific Paths--| Framework | index.html | public/ folder |-|-----------|------------|----------------|-| React (Vite) | Project root | `public/` |-| React (CRA) | `public/` | `public/` |-| Vue | Project root | `public/` |-| Angular | `src/` | `src/` (add to `angular.json` assets) |-| Astro | Layout component | `public/` |diff --git a/plugins/power-pages/skills/add-seo/scripts/validate-seo.js b/plugins/power-pages/skills/add-seo/scripts/validate-seo.jsnew file mode 100644index 000000000..e1223a037--- /dev/null+++ b/plugins/power-pages/skills/add-seo/scripts/validate-seo.js@@ -0,0 +1,85 @@+#!/usr/bin/env node++// Validates SEO assets added to a Power Pages code site.+// Runs as a Stop hook to verify robots.txt, sitemap.xml, and meta tags were created.++const fs = require('fs');+const path = require('path');+const { approve, block, runValidation, findPath } = require('../../../scripts/lib/validation-helpers');++runValidation((cwd) => {+ const configPath = findPath(cwd, 'powerpages.config.json');+ if (!configPath) approve(); // Not a Power Pages project, skip++ const projectRoot = path.dirname(configPath);+ const publicDir = path.join(projectRoot, 'public');++ if (!fs.existsSync(publicDir)) approve();++ // Check if any SEO file exists — if none, this wasn't an SEO session, skip+ const hasRobots = fs.existsSync(path.join(publicDir, 'robots.txt'));+ const hasSitemap = fs.existsSync(path.join(publicDir, 'sitemap.xml'));+ if (!hasRobots && !hasSitemap) approve();++ const errors = [];++ // 1. robots.txt+ if (!hasRobots) {+ errors.push('Missing public/robots.txt');+ } else {+ const content = fs.readFileSync(path.join(publicDir, 'robots.txt'), 'utf8');+ if (!content.includes('User-agent:')) errors.push('robots.txt: missing User-agent directive');+ if (!content.toLowerCase().includes('sitemap:')) errors.push('robots.txt: missing Sitemap directive');+ }++ // 2. sitemap.xml+ if (!hasSitemap) {+ errors.push('Missing public/sitemap.xml');+ } else {+ const content = fs.readFileSync(path.join(publicDir, 'sitemap.xml'), 'utf8');+ if (!content.includes('<urlset')) errors.push('sitemap.xml: missing <urlset> element');+ if (!content.includes('<loc>')) errors.push('sitemap.xml: missing <loc> entries');+ if (content.includes('<PRODUCTION_URL>') || content.includes('<TODAY_DATE>')) {+ errors.push('sitemap.xml: contains unreplaced template placeholders');+ }+ }++ // 3. Meta tags in index.html+ const indexPath = findIndexHtml(projectRoot);+ if (indexPath) {+ const content = fs.readFileSync(indexPath, 'utf8');+ if (!content.includes('meta name="description"')) errors.push('index.html: missing meta description tag');+ if (!content.includes('meta name="viewport"')) errors.push('index.html: missing viewport meta tag');+ }++ if (errors.length > 0) {+ block('SEO validation failed:\n- ' + errors.join('\n- '));+ }++ approve();+});++function findIndexHtml(projectRoot) {+ const candidates = [+ path.join(projectRoot, 'index.html'),+ path.join(projectRoot, 'src', 'index.html'),+ ];++ for (const candidate of candidates) {+ if (fs.existsSync(candidate)) return candidate;+ }++ // For Astro, check layout files+ const layoutDir = path.join(projectRoot, 'src', 'layouts');+ if (fs.existsSync(layoutDir)) {+ try {+ for (const entry of fs.readdirSync(layoutDir, { withFileTypes: true })) {+ if (entry.isFile() && entry.name.endsWith('.astro')) {+ return path.join(layoutDir, entry.name);+ }+ }+ } catch {}+ }++ return null;+}diff --git a/plugins/power-pages/skills/add-tests/SKILL.md b/plugins/power-pages/skills/add-tests/SKILL.mddeleted file mode 100644index 11824f1af..000000000--- a/plugins/power-pages/skills/add-tests/SKILL.md+++ /dev/null@@ -1,122 +0,0 @@-----name: adding-tests-description: Adds unit tests (Vitest) and E2E tests (Playwright) to Power Pages sites. Use when setting up testing infrastructure, writing tests, or adding test coverage.-user-invocable: true-allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "AskUserQuestion"]-model: opus------**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.--# Add Tests--**References:** [testing](./references/testing-reference.md)--Adds testing infrastructure to an existing Power Pages code site.--## Prerequisites--- Site created with `/create-site`-- Framework identified (React/Vue/Angular/Astro)--## Workflow--1. **Check Context** → Read memory bank, identify framework-2. **Setup Unit Tests** → Install Vitest, configure, write component tests-3. **Setup E2E Tests** → Install Playwright, configure, write page tests-4. **Run Tests** → Verify all tests pass-5. **Update CI (Optional)** → Add test scripts to package.json-------## Step 1: Check Context--Read `memory-bank.md` and `package.json` to identify:-- Framework (React, Vue, Angular, Astro)-- Build tool (Vite, CRA, Angular CLI)-- Existing test setup (if any)-------## Step 2: Setup Unit Tests--See [testing-reference.md](./references/testing-reference.md#unit-tests).--### Install Dependencies--```powershell-# React (Vite)-npm install -D vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event jsdom--# Vue (Vite)-npm install -D vitest @vue/test-utils @testing-library/vue jsdom-```--### Configure Vitest--Add test config to `vite.config.ts` and create `src/test/setup.ts`.--### Write Tests--Create tests for key components:-- `src/components/Header.test.tsx`-- `src/components/[MainComponent].test.tsx`-- `src/utils/[utility].test.ts`-------## Step 3: Setup E2E Tests--See [testing-reference.md](./references/testing-reference.md#end-to-end-tests-playwright).--### Install Playwright--```powershell-npm install -D @playwright/test-npx playwright install-```--### Configure Playwright--Create `playwright.config.ts` with correct baseURL for framework.--### Write E2E Tests--Create tests in `e2e/` folder:-- `e2e/home.spec.ts` - Homepage tests-- `e2e/navigation.spec.ts` - Navigation tests-- `e2e/accessibility.spec.ts` - A11y checks-------## Step 4: Run Tests--```powershell-# Unit tests-npm run test:run--# E2E tests-npm run test:e2e-```--**All tests must pass before completing this skill.**-------## Step 5: Update Package Scripts--Ensure `package.json` has test scripts:--```json-{- "scripts": {- "test": "vitest",- "test:run": "vitest run",- "test:coverage": "vitest run --coverage",- "test:e2e": "playwright test",- "test:e2e:ui": "playwright test --ui"- }-}-```--Update memory-bank.md with testing status.diff --git a/plugins/power-pages/skills/add-tests/references/testing-reference.md b/plugins/power-pages/skills/add-tests/references/testing-reference.mddeleted file mode 100644index 95be4890d..000000000--- a/plugins/power-pages/skills/add-tests/references/testing-reference.md+++ /dev/null@@ -1,394 +0,0 @@-# Testing Reference--## Unit Tests--### Install Dependencies--```powershell-# React (Vite) - Vitest + React Testing Library-npm install -D vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event jsdom--# React (Create React App) - Already includes Jest + RTL-# No additional installation needed--# Angular - Already includes Jasmine + Karma-# No additional installation needed--# Vue (Vite) - Vitest + Vue Test Utils-npm install -D vitest @vue/test-utils @testing-library/vue jsdom--# Astro - Vitest-npm install -D vitest-```--### Configure Vitest (Vite Projects)--Add test configuration to `vite.config.ts`:--```typescript-/// <reference types="vitest" />-import { defineConfig } from 'vite'-import react from '@vitejs/plugin-react' // or vue()--export default defineConfig({- plugins: [react()],- test: {- globals: true,- environment: 'jsdom',- setupFiles: './src/test/setup.ts',- coverage: {- provider: 'v8',- reporter: ['text', 'html'],- },- },-})-```--Create `src/test/setup.ts`:--```typescript-import '@testing-library/jest-dom'-```--Add test scripts to `package.json`:--```json-{- "scripts": {- "test": "vitest",- "test:run": "vitest run",- "test:coverage": "vitest run --coverage"- }-}-```--### Example Component Test (React)--```typescript-// src/components/Header.test.tsx-import { render, screen } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { Header } from './Header'--describe('Header', () => {- it('renders the site title', () => {- render(<Header title="My Site" />)- expect(screen.getByRole('banner')).toHaveTextContent('My Site')- })-- it('toggles mobile menu on button click', async () => {- const user = userEvent.setup()- render(<Header title="My Site" />)-- const menuButton = screen.getByRole('button', { name: /menu/i })- await user.click(menuButton)-- expect(screen.getByRole('navigation')).toBeVisible()- })-})-```--### Example Utility Test--```typescript-// src/utils/formatters.test.ts-import { formatDate, formatCurrency } from './formatters'--describe('formatDate', () => {- it('formats ISO date to readable string', () => {- expect(formatDate('2024-01-15')).toBe('January 15, 2024')- })-- it('returns empty string for invalid date', () => {- expect(formatDate('invalid')).toBe('')- })-})--describe('formatCurrency', () => {- it('formats number as USD currency', () => {- expect(formatCurrency(1234.56)).toBe('$1,234.56')- })-})-```--### Run Unit Tests--```powershell-# Run all tests-npm test--# Run tests once (CI mode)-npm run test:run--# Run with coverage report-npm run test:coverage-```--**All unit tests must pass before proceeding to E2E tests.**-------## End-to-End Tests (Playwright)--### Install Playwright--```powershell-# Install Playwright-npm install -D @playwright/test--# Install browsers (Chromium, Firefox, WebKit)-npx playwright install-```--### Configure Playwright--Create `playwright.config.ts` in the project root:--```typescript-import { defineConfig, devices } from '@playwright/test'--export default defineConfig({- testDir: './e2e',- fullyParallel: true,- forbidOnly: !!process.env.CI,- retries: process.env.CI ? 2 : 0,- workers: process.env.CI ? 1 : undefined,- reporter: 'html',- use: {- baseURL: 'http://localhost:5173', // Adjust for your framework- trace: 'on-first-retry',- screenshot: 'only-on-failure',- },- projects: [- {- name: 'chromium',- use: { ...devices['Desktop Chrome'] },- },- {- name: 'firefox',- use: { ...devices['Desktop Firefox'] },- },- {- name: 'webkit',- use: { ...devices['Desktop Safari'] },- },- {- name: 'Mobile Chrome',- use: { ...devices['Pixel 5'] },- },- {- name: 'Mobile Safari',- use: { ...devices['iPhone 12'] },- },- ],- webServer: {- command: 'npm run dev',- url: 'http://localhost:5173',- reuseExistingServer: !process.env.CI,- },-})-```--### Framework-Specific URLs--| Framework | baseURL / webServer.url |-|-----------|-------------------------|-| Vite (React/Vue) | `http://localhost:5173` |-| Create React App | `http://localhost:3000` |-| Angular | `http://localhost:4200` |-| Astro | `http://localhost:4321` |--Add E2E test scripts to `package.json`:--```json-{- "scripts": {- "test:e2e": "playwright test",- "test:e2e:ui": "playwright test --ui",- "test:e2e:headed": "playwright test --headed",- "test:e2e:report": "playwright show-report"- }-}-```--### E2E Test Structure--```text-/e2e-├── home.spec.ts # Home page tests-├── navigation.spec.ts # Navigation tests-├── contact-form.spec.ts # Form submission tests-├── responsive.spec.ts # Mobile responsiveness tests-└── fixtures/- └── test-data.ts # Shared test data-```--### Example: Home Page Test--```typescript-// e2e/home.spec.ts-import { test, expect } from '@playwright/test'--test.describe('Home Page', () => {- test('should display hero section with correct content', async ({ page }) => {- await page.goto('/')-- await expect(page.getByRole('heading', { level: 1 })).toBeVisible()- await expect(page.getByRole('banner')).toBeVisible()-- const ctaButton = page.getByRole('link', { name: /get started/i })- await expect(ctaButton).toBeVisible()- })-- test('should have valid meta tags', async ({ page }) => {- await page.goto('/')-- await expect(page).toHaveTitle(/My Site/)-- const metaDescription = page.locator('meta[name="description"]')- await expect(metaDescription).toHaveAttribute('content', /.+/)- })-})-```--### Example: Navigation Test--```typescript-// e2e/navigation.spec.ts-import { test, expect } from '@playwright/test'--test.describe('Navigation', () => {- test('should navigate to all main pages', async ({ page }) => {- await page.goto('/')-- await page.getByRole('link', { name: /about/i }).click()- await expect(page).toHaveURL(/.*about/)- await expect(page.getByRole('heading', { name: /about/i })).toBeVisible()-- await page.getByRole('link', { name: /contact/i }).click()- await expect(page).toHaveURL(/.*contact/)- await expect(page.getByRole('heading', { name: /contact/i })).toBeVisible()-- await page.getByRole('link', { name: /home/i }).click()- await expect(page).toHaveURL('/')- })-- test('should toggle mobile menu on small screens', async ({ page }) => {- await page.setViewportSize({ width: 375, height: 667 })- await page.goto('/')-- const nav = page.getByRole('navigation')- await expect(nav).not.toBeVisible()-- await page.getByRole('button', { name: /menu/i }).click()- await expect(nav).toBeVisible()- })-})-```--### Example: Contact Form Test--```typescript-// e2e/contact-form.spec.ts-import { test, expect } from '@playwright/test'--test.describe('Contact Form', () => {- test.beforeEach(async ({ page }) => {- await page.goto('/contact')- })-- test('should display validation errors for empty form', async ({ page }) => {- await page.getByRole('button', { name: /submit/i }).click()-- await expect(page.getByText(/name is required/i)).toBeVisible()- await expect(page.getByText(/email is required/i)).toBeVisible()- })-- test('should show error for invalid email', async ({ page }) => {- await page.getByLabel(/name/i).fill('John Doe')- await page.getByLabel(/email/i).fill('invalid-email')- await page.getByLabel(/message/i).fill('Test message')-- await page.getByRole('button', { name: /submit/i }).click()-- await expect(page.getByText(/valid email/i)).toBeVisible()- })-- test('should submit form successfully with valid data', async ({ page }) => {- await page.getByLabel(/name/i).fill('John Doe')- await page.getByLabel(/email/i).fill('[email protected]')- await page.getByLabel(/message/i).fill('This is a test message')-- await page.getByRole('button', { name: /submit/i }).click()-- await expect(page.getByText(/thank you|success/i)).toBeVisible()- })-})-```--### Example: Accessibility Test--```typescript-// e2e/accessibility.spec.ts-import { test, expect } from '@playwright/test'--test.describe('Accessibility', () => {- test('should be navigable with keyboard', async ({ page }) => {- await page.goto('/')-- await page.keyboard.press('Tab')- const firstFocusable = page.locator(':focus')- await expect(firstFocusable).toBeVisible()-- const skipLink = page.getByRole('link', { name: /skip to/i })- if (await skipLink.isVisible()) {- await expect(skipLink).toBeFocused()- }- })-- test('should have proper heading hierarchy', async ({ page }) => {- await page.goto('/')-- const h1 = page.getByRole('heading', { level: 1 })- await expect(h1).toHaveCount(1)-- const headings = await page.getByRole('heading').all()- expect(headings.length).toBeGreaterThan(0)- })-- test('should have alt text for images', async ({ page }) => {- await page.goto('/')-- const images = await page.getByRole('img').all()- for (const img of images) {- const alt = await img.getAttribute('alt')- expect(alt).not.toBeNull()- expect(alt).not.toBe('')- }- })-})-```--### Run E2E Tests--```powershell-# Run all E2E tests-npm run test:e2e--# Run with UI mode (interactive debugging)-npm run test:e2e:ui--# Run in headed mode (see browser)-npm run test:e2e:headed--# Run specific test file-npx playwright test e2e/home.spec.ts--# Run tests in specific browser-npx playwright test --project=chromium--# View HTML report after tests-npm run test:e2e:report-```--**All E2E tests must pass before proceeding to build.**diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.mdindex ccae145c5..2c77259bb 100644--- a/plugins/power-pages/skills/create-site/SKILL.md+++ b/plugins/power-pages/skills/create-site/SKILL.md@@ -1,129 +1,507 @@----name: creating-power-pages-site-description: Creates Power Pages code sites (SPAs) using React, Angular, Vue, or Astro. Use when creating sites, portals, building websites, scaffolding projects, uploading to Power Pages, or activating sites.+name: create-power-pages-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-allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task", "ExitPlanMode"]+argument-hint: Optional site description+allowed-tools: ["Read", "Write", "Edit", "Grep", "Glob", "Bash", "WebSearch", "AskUserQuestion", "Task", "TaskCreate", "TaskUpdate", "TaskList", "mcp__plugin_power-pages_playwright__browser_navigate", "mcp__plugin_power-pages_playwright__browser_snapshot", "mcp__plugin_power-pages_playwright__browser_click", "mcp__plugin_power-pages_playwright__browser_close"]model: opus+hooks:+ Stop:+ - hooks:+ - type: command+ command: "node \"${CLAUDE_PLUGIN_ROOT}/skills/create-site/scripts/validate-site.js\""+ timeout: 15+ - type: prompt+ prompt: "If a Power Pages code site was being created in this session (via /power-pages:create-site), verify before allowing stop: 1) All user-requested features and pages were implemented — not just the scaffold, 2) Design changes were applied to real files — distinctive typography via Google Fonts (no generic Inter/Roboto/Arial), cohesive color palette via CSS variables, motion/animations, and backgrounds, 3) The user was given the dev server URL and asked to review the site, 4) No build errors remain unresolved, 5) Git commits were made at key milestones, 6) The user was asked about deploying via /power-pages:deploy-site. If any of these are incomplete, return { \"ok\": false, \"reason\": \"<specific issues>\" }. If no site creation happened or everything is complete, return { \"ok\": true }."+ timeout: 30----**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.-# Create Power Pages Code Site-**References:** [requirements](./references/requirements-reference.md) | [site-creation](./references/site-creation-reference.md) | [upload-activation](./references/upload-activation-reference.md) | [troubleshooting](./references/troubleshooting.md)+Guide the user through creating a complete, production-quality Power Pages code site from initial concept to deployed site. Follow a systematic approach: discover requirements, scaffold and launch immediately, plan components and design, implement with design applied, validate, review, and deploy.++## Core Principles-## Workflow+- **Use best judgement for design details**: Once the user picks an aesthetic direction and mood, make confident decisions about specific fonts, colors, page layouts, and component behavior. Do not ask the user to specify every detail — use the design reference and your own taste to make creative, distinctive choices.+- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases — create the todo list upfront with all phases before starting any work.+- **Scaffold early, design with intention**: Get the dev server running immediately after discovery so the user has something to look at. Then plan the design and features while the scaffold is live — apply the chosen aesthetic during implementation.+- **Live preview feedback loop**: The dev server MUST be running before any customization begins. Browse the site via Playwright (`browser_navigate` + `browser_snapshot`) to verify every significant change. Do NOT take screenshots — only use accessibility snapshots to check page structure and content.+- **Use real images**: Source high-quality photos from Unsplash wherever pages need visual content — hero sections, feature cards, about pages, backgrounds, etc. Use `https://images.unsplash.com/photo-{id}?w={width}&h={height}&fit=crop` URLs with specific photo IDs found via `WebSearch`. Never leave image placeholders or broken `<img>` tags pointing to nonexistent files.+- **Git checkpoints**: Commit after every individual page and component — each gets its own commit so breaking changes can be reverted.-1. **Plan** → Gather requirements, enter plan mode, get approval-2. **Create Site** → Use frontend-design skill, configure for Power Pages-3. **Preview & Approve** → User reviews site locally before upload-4. **Check Prerequisites** → Verify PAC CLI and Azure CLI-5. **Upload (Inactive)** → `pac pages upload-code-site`-6. **Activate** → Call CreateWebsite API or manual activation+**Constraint**: Only static SPA frameworks are supported (React, Vue, Angular, Astro). NOT supported: Next.js, Nuxt.js, Remix, SvelteKit, Liquid.++**Initial request:** $ARGUMENTS----## Step 1: Plan+## Phase 1: Discovery++**Goal**: Understand what site needs to be built and what problem it solves-### 1.1 Gather Requirements+**Actions**:+1. Create todo list with all 7 phases (see [Progress Tracking](#progress-tracking) table)+2. If site purpose is clear from arguments:+ - Summarize understanding+ - Identify site type (portal, dashboard, landing page, blog, etc.)+3. If site purpose is unclear, use `AskUserQuestion`:-Use `AskUserQuestion` to ask:-1. Site purpose and target audience-2. Audience type: internal or external-3. Framework: React (recommended), Angular, Vue, or Astro-4. Features: landing page, forms, auth, data display-5. Design preferences+ | Question | Header | Options |+ |----------|--------|---------|+ | What should the site be called? (e.g., "Contoso Portal", "HR Dashboard") | Site Name | *(free text — use a single generic option so the user types a custom name via "Other")* |+ | 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 |-**Constraint**: Only static SPA frameworks. NOT supported: Next.js, Nuxt.js, Remix, SvelteKit, Liquid.+4. Resolve the project location:+ - **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.-### 1.2 Enter Plan Mode+ After resolving, confirm: "The site will be created at `<resolved path>`."-Use `/plan` command to enter plan mode and create an implementation plan covering:-- Project structure and folder layout-- Components to be created-- Pages and routing approach-- Styling approach (CSS modules, Tailwind, etc.)-- Power Pages configuration (`powerpages.config.json`)-- Build and deployment steps+ Store this as `PROJECT_ROOT`.-### 1.3 Get Approval+5. From the user's answers, derive:+ - `__SITE_NAME__` (Title Case, e.g., `Contoso Portal`)+ - `__SITE_SLUG__` (kebab-case derived from site name, e.g., `contoso-portal`)+ - `__SITE_DESCRIPTION__` (one-line description based on name + purpose)+6. Summarize understanding and confirm with user before proceeding-Present the plan to the user. Use `ExitPlanMode` only after user approves. If user requests changes, update the plan and present again.+**Audience influences site generation:**+- **Internal**: Prioritize data tables, dashboards, authentication, navigation depth, functional over flashy design+- **External**: Prioritize landing page appeal, SEO-friendly structure, contact forms, clean marketing-oriented layout++**Output**: Clear statement of site purpose, framework, audience, derived naming values, and project location----## Step 2: Create the Site+## Phase 2: Scaffold & Launch Dev Server++**Goal**: Get a running site immediately so the user has something to preview while features and design are planned++> See `${CLAUDE_PLUGIN_ROOT}/references/framework-conventions.md` for the full framework → build tool → router → output path mapping.++**Actions**:++### 2.1 Copy Template++> `${CLAUDE_PLUGIN_ROOT}` is already resolved to the plugin's absolute path at runtime. Use it directly in Glob/Read paths — do NOT search for the plugin directory.++Read and copy all files from the matching asset template to the project directory:++| Framework | Asset Directory |+|-----------|----------------|+| React | `${CLAUDE_PLUGIN_ROOT}/skills/create-site/assets/react/` |+| Vue | `${CLAUDE_PLUGIN_ROOT}/skills/create-site/assets/vue/` |+| Angular | `${CLAUDE_PLUGIN_ROOT}/skills/create-site/assets/angular/` |+| Astro | `${CLAUDE_PLUGIN_ROOT}/skills/create-site/assets/astro/` |++Use `Glob` to discover all files in the asset directory, `Read` each file, then `Write` to the project directory preserving the relative path structure.++### 2.2 Replace Placeholders++After copying, replace all `__PLACEHOLDER__` tokens in every file. Use `Edit` with `replace_all: true` on each file.++- **Name/slug/description placeholders**: Use the actual values from Phase 1 (`__SITE_NAME__`, `__SITE_SLUG__`, `__SITE_DESCRIPTION__`).+- **Color placeholders**: Use neutral defaults for now — these will be replaced with the user's chosen palette during Implementation (Phase 5):++ | Placeholder | Default Value |+ |-------------|---------------|+ | `__PRIMARY_COLOR__` | `#3b82f6` |+ | `__SECONDARY_COLOR__` | `#6366f1` |+ | `__BG_COLOR__` | `#ffffff` |+ | `__SURFACE_COLOR__` | `#f8fafc` |+ | `__TEXT_COLOR__` | `#1e293b` |+ | `__TEXT_MUTED__` | `#64748b` |++### 2.3 Rename gitignore++Rename `gitignore` → `.gitignore` in the project root (stored without dot prefix to avoid git interference in the plugin repo).++### 2.4 Install Dependencies++Run `npm install` **before** initializing git so that `package-lock.json` is included in the initial commit:++```powershell+cd "<PROJECT_ROOT>"+npm install+```++### 2.5 Initialize Git Repository++Initialize a git repo and make the first commit. This captures all template files AND `package-lock.json` in one clean baseline:++```powershell+cd "<PROJECT_ROOT>"+git init+git add -A+git commit -m "Initial scaffold: __SITE_NAME__ (__FRAMEWORK__)"+```++From this point, **commit after every significant milestone** so any breaking change can be reverted.++### 2.6 Start Dev Server++**This MUST happen now — before any planning or customization begins.** The dev server gives the user a live preview while features and design are being planned:++```powershell+cd "<PROJECT_ROOT>"+npm run dev+```++Run `npm run dev` in the background using `Bash` with `run_in_background: true`. Note the local URL (typically `http://localhost:5173` for Vite or `http://localhost:4200` for Angular or `http://localhost:4321` for Astro).++### 2.7 Verify in Playwright & Share URL++Immediately after the dev server starts, verify the scaffold is working:++1. Use `mcp__plugin_power-pages_playwright__browser_navigate` to open the dev server URL+2. Use `mcp__plugin_power-pages_playwright__browser_snapshot` to verify the page loaded correctly (do NOT take screenshots — only use accessibility snapshots)+3. **Share the dev server URL with the user** so they can preview the site in their own browser (e.g., "Your site is running at `http://localhost:5173` — open it in your browser to follow along as I build.")++> **GATE: Do NOT proceed to Phase 3 until ALL of the following are true:**+> 1. Template files copied and placeholders replaced+> 2. Git repo initialized with initial scaffold commit+> 3. `npm install` completed successfully+> 4. Dev server is running in the background (`npm run dev`)+> 5. Playwright has opened the site and verified it loads via `browser_snapshot`+> 6. The dev server URL has been shared with the user+>+> If any of these are not done, complete them now before moving on.++**Output**: Running dev server with verified scaffold, URL shared with user++---++## Phase 3: Component Planning++**Goal**: Determine what pages, components, and design elements the site needs — while the user previews the running scaffold++**Actions**:+1. Use `AskUserQuestion` to collect feature and design requirements:++ | Question | Header | Options |+ |----------|--------|---------|+ | Which features? (multi-select) | Features | *(generate 3-4 context-aware options based on the site name, purpose, and audience from Phase 1)* |+ | What aesthetic direction do you want? | Aesthetic | Minimal & Clean (Recommended), Bold & Vibrant, Dark & Moody, Warm & Organic |+ | What's the overall mood? | Mood | Professional & Trustworthy (Recommended), Creative & Playful, Technical & Precise, Elegant & Premium |++ > **Feature options are NOT hardcoded.** Infer relevant features from Phase 1 answers. For example:+ > - "HR Dashboard" + Internal → Employee Directory, Leave Requests, Announcements, Org Chart+ > - "Contoso Portal" + External → Contact Form, Service Catalog, Knowledge Base, FAQ+ > - "Partner Hub" + Internal → Document Library, Partner Directory, Deal Tracker, Notifications+ >+ > Always generate options that make sense for the specific site — never reuse a fixed list.++2. Read the design aesthetics reference: `${CLAUDE_PLUGIN_ROOT}/skills/create-site/references/design-aesthetics.md`+3. **Map aesthetic + mood to design choices** using the Aesthetic x Mood Mapping table from the design reference. Record the chosen font direction, color direction, and motion direction.+4. Analyze requirements and determine needed components. Present component plan to user as a table:++ ```+ | Component Type | Count | Details |+ |---------------------|-------|---------|+ | Pages | 4 | Home, About, Services, Contact |+ | Shared Components | 3 | Navbar, Footer, ContactForm |+ | Design Elements | 4 | Google Fonts (Playfair Display + Source Sans Pro), Color palette (6 CSS vars), Page transitions, Gradient backgrounds |+ | Routes | 4 | /, /about, /services, /contact |+ ```++5. Use best judgement to determine the final color palette based on the chosen aesthetic + mood. These will replace the scaffold defaults during implementation:-1. Invoke `frontend-design` skill with Vite + no SSR constraints-2. Create `powerpages.config.json` with correct `compiledPath`-3. `npm run build`-4. Create `memory-bank.md`+ | Placeholder | Description | Value |+ |-------------|-------------|-------|+ | `__PRIMARY_COLOR__` | Primary hex color | *(choose based on aesthetic + mood)* |+ | `__SECONDARY_COLOR__` | Complementary hex color | *(choose based on aesthetic + mood)* |+ | `__BG_COLOR__` | Background color | *(choose based on aesthetic + mood)* |+ | `__SURFACE_COLOR__` | Surface/card color | *(choose based on aesthetic + mood)* |+ | `__TEXT_COLOR__` | Main text color | *(choose based on aesthetic + mood)* |+ | `__TEXT_MUTED__` | Muted text color | *(choose based on aesthetic + mood)* |++**Output**: Confirmed list of pages, components, design elements, and routes to create----## Step 3: Preview & Approve+## Phase 4: Plan Approval++**Goal**: Get user approval on the implementation plan++**Actions**:+1. Read the design aesthetics reference: `${CLAUDE_PLUGIN_ROOT}/skills/create-site/references/design-aesthetics.md`+2. Present the implementation plan directly to the user as a formatted message. **The plan MUST have ALL of the following sections:**++ **Section A — Design & Pages**+ - Pages to create (with content outline for each)+ - Components needed for each page+ - Routing and navigation structure+ - Design decisions (from the chosen design direction):+ - Typography: specific Google Fonts chosen+ - Color palette: full CSS variable set with hex values (replacing the scaffold defaults)+ - Motion/animation plan: page load, hover states, transitions+ - Background treatment: gradients, patterns, effects++ **Section B — Review & Deployment**+ - What to verify before handoff+ - Deployment options++ > **CRITICAL:** The plan is written for the user — do NOT reference internal phase numbers, tool names, or implementation details. Describe what will be built and what it will look like. The scaffold is already running — this plan covers what will be built on top of it.++3. Use `AskUserQuestion` to get approval:-1. Run `npm run dev` to start local server-2. **Ask user to preview** using `AskUserQuestion`: "Please review the site at http://localhost:xxxx. Ready to proceed with upload?"-3. User must confirm before continuing to upload+ | Question | Header | Options |+ |----------|--------|---------|+ | Does this plan look good? | Plan | Approve and start building (Recommended), I'd like to make changes |++ - **If "Approve"**: Proceed to Phase 5.+ - **If "I'd like to make changes"**: Ask what they want changed, update the plan, and re-present for approval.++**Output**: Approved implementation plan----## Step 4: Check Prerequisites+## Phase 5: Implementation++**Goal**: Build all pages, components, and design elements with the chosen aesthetic applied from the start++> **Prerequisite:** The dev server MUST already be running and verified via Playwright (completed in Phase 2). If it is not, go back and complete Phase 2.+>+> **Design reference:** Read `${CLAUDE_PLUGIN_ROOT}/skills/create-site/references/design-aesthetics.md` and apply its principles throughout this phase. All pages and components should be built with the chosen typography, color palette, motion, and backgrounds from the start — do NOT build with neutral styling first and redesign later.++**Actions**:++### 5.1 Create Todos for All Work++**Before writing any code**, use `TaskCreate` to create a todo for every piece of work. This gives the user full visibility into what will be built:++- **One todo per page** — e.g., "Create Contact page (`/contact`)", "Create Dashboard page (`/dashboard`)"+- **One todo per shared component** — e.g., "Create ContactForm component", "Create DataTable component"+- **One todo for routing** — "Update router with all new routes"+- **One todo for navigation** — "Update Layout/Header with navigation links"+- **One todo for design foundations** — "Apply design tokens (fonts, colors, motion, backgrounds)"++Each todo should have a clear `subject`, `activeForm`, and `description` that includes the file path and what the page/component does. Then work through the todos in order, marking each `in_progress` → `completed`.++### 5.2 Build Order++1. **Design foundations** — Replace the scaffold's default CSS variables with the chosen color palette, add Google Fonts, motion/animation utilities, and background treatments. Update the theme CSS file (e.g., `src/styles/theme.css`) with the actual hex values chosen in Phase 3, then commit.+2. **Shared components** — Build reusable components first so pages can use them+3. **Pages** — Create route components for each requested page+4. **Router** — Register all new routes+5. **Navigation** — Add links to the Layout/Header component++**Important**: Build real, functional UI with distinctive design applied — not placeholder "coming soon" pages, and not generic unstyled markup. Every page and component should reflect the chosen aesthetic from the moment it's created.++### 5.3 Source Real Images++Use high-quality photos from Unsplash wherever the site needs visual content. Do NOT use placeholder services (e.g., `placeholder.com`, `placehold.co`), broken `<img>` tags, or leave empty image slots.++**How to find images:**+1. Use `WebSearch` to search Unsplash for relevant photos (e.g., `site:unsplash.com modern office workspace`)+2. Pick specific photos and use their direct URL with sizing parameters: `https://images.unsplash.com/photo-{id}?w={width}&h={height}&fit=crop`+3. Choose images that match the site's aesthetic and mood++**Where to use images:**+- **Hero sections** — Striking, high-resolution photos that set the tone for the site+- **Feature/service cards** — Relevant photos that illustrate each feature or service+- **About/team sections** — Professional or contextual photos matching the site's purpose+- **Backgrounds** — Atmospheric photos used as full-bleed or overlay backgrounds+- **Content sections** — Supporting photos that break up text and add visual interest++**Guidelines:**+- Pick images that feel cohesive together — consistent style, lighting, and color tone+- Use appropriate sizing (`w=800` for cards, `w=1600` for heroes/backgrounds) to avoid slow loads+- Add descriptive `alt` text to every `<img>` for accessibility+- For icons and logos, use inline SVGs instead of photos++### 5.4 Git Commit Checkpoints++Commit after **every individual page and component** so breaking changes can be reverted. Each page and each component gets its own commit — do NOT batch multiple pages or components into a single commit.```powershell-# PAC CLI (install if missing: dotnet tool install --global Microsoft.PowerApps.CLI.Tool)-pac help+git add -A+git commit -m "<short description of what was added/changed>"+```++**When to commit:**+- After applying design foundations (fonts, colors, motion)+- After creating each page (e.g., "Add Home page", "Add Contact page")+- After creating each shared component (e.g., "Add Navbar component", "Add Footer component")+- After updating routing and navigation+- Before attempting anything risky or experimental-# Azure CLI (install if missing: winget install -e --id Microsoft.AzureCLI)-az --version+**If something breaks**, revert to the last good commit:-# Auth-pac auth list # create with: pac auth create-az account show # login with: az login-pac org who+```powershell+git revert HEAD```----+### 5.5 Live Verification++After each significant change (new page or component), browse the site via Playwright to ensure everything is up to the mark:++1. Use `mcp__plugin_power-pages_playwright__browser_navigate` to reload or navigate to the updated page+2. Use `mcp__plugin_power-pages_playwright__browser_snapshot` to verify the page structure and content are correct — do NOT take screenshots+3. If something looks wrong in the snapshot, fix it before proceeding++The user is previewing in their own browser via the dev server URL shared in Phase 2.7.-## Step 5: Upload to Power Pages+> **GATE: Do NOT proceed to Phase 6 until ALL customization is complete with design applied.** The site must have distinctive typography (Google Fonts — no generic Inter/Roboto/Arial), a cohesive color palette (CSS variables), motion/animations, and all requested pages/features before moving to review.-1. Run `pac auth list` to show available environments-2. **Ask user which environment** to upload to using `AskUserQuestion` (show org names from auth list)-3. If needed, switch auth: `pac auth select --index <n>` or `pac auth create`-4. **Build before upload**: `npm run build`-5. `pac pages upload-code-site --rootPath "<PROJECT_ROOT>"` (creates `.powerpages-site` folder)-6. **Create AI site settings** in `.powerpages-site/site-settings/` (see [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md)):- - `Site/AI/AuthoringTool` - ClaudeCodeCLI or ClaudeCodeVSCode- - `Site/AI/CreateSite` - true (skill tracking)-7. **Build and upload again**: `npm run build && pac pages upload-code-site --rootPath "<PROJECT_ROOT>"`-8. `pac pages list --verbose` to get Website ID+**Output**: All pages, components, and design elements implemented and verified----## Step 6: Activate Website+## Phase 6: Review & User Testing++**Goal**: Ensure the site meets user expectations and all pages work correctly++**Actions**:+1. Browse through each page via Playwright (`browser_navigate` + `browser_snapshot`) to verify all pages load correctly — do NOT take screenshots+2. Present a summary of what was built:+ ```+ | Component Type | Count | Details |+ |---------------------|-------|---------|+ | Pages | 4 | Home (/), About (/about), Services (/services), Contact (/contact) |+ | Shared Components | 3 | Navbar, Footer, ContactForm |+ | Design Elements | 4 | Playfair Display + Source Sans Pro, 6 CSS variables, fade-in transitions, gradient backgrounds |+ | Git Commits | 7 | scaffold + 6 feature commits |+ ```+3. Share the dev server URL with the user and list all available routes+4. Ask the user to review using `AskUserQuestion`:+ > "The site is ready for review at `<dev server URL>`. Please check it out in your browser. Would you like any changes?"+5. If the user requests changes, apply them and re-verify by browsing via `browser_snapshot`+6. Close the Playwright browser with `mcp__plugin_power-pages_playwright__browser_close` when done++**Output**: User-approved site ready for deployment++---++## Phase 7: Deployment & Next Steps++**Goal**: Deploy the site and suggest enhancements++> **This phase is MANDATORY. Do NOT end the session without asking about deployment.**++**Actions**:+1. Record skill usage:-1. Ask user for subdomain via `AskUserQuestion`-2. Get IDs: `pac org who`-3. Call CreateWebsite API via `az rest` (see [upload-activation-reference.md](./references/upload-activation-reference.md))-4. Poll operation status until complete-5. Verify: `pac pages list --verbose`-6. Fallback: Manual activation at make.powerpages.microsoft.com+ > Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`-Update memory-bank.md with Website ID, URL, completed steps.+ Follow the skill tracking instructions in the reference to record this skill's usage. Use `--skillName "CreateSite"`. Note: `.powerpages-site` may not exist for first-time sites — the script exits silently.-Cleanup helper files per [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md).+2. Use `AskUserQuestion` with options: **Deploy now (Recommended)**, **Skip for now**:+ > "Would you like to deploy your site to Power Pages now?"+3. If the user chooses to deploy, invoke the `/power-pages:deploy-site` skill.+4. Mark all todos complete+5. Present a final summary:+ - Site name and purpose+ - Framework and project location+ - Components created (X pages, Y components, Z design elements)+ - Key files and their purposes+ - Total file count and git commit count+6. Suggest optional enhancement skills:+ - `/power-pages:setup-datamodel` — Create Dataverse tables for dynamic content+ - `/power-pages:add-seo` — Add meta tags, robots.txt, sitemap.xml, favicon+ - `/power-pages:add-tests` — Add unit tests (Vitest) and E2E tests (Playwright)++**Output**: Deployed (or deployment-ready) site with clear next steps----## Optional Enhancements+## Important Notes++### Throughout All Phases++- **Use TaskCreate/TaskUpdate** to track progress at every phase+- **Ask for user confirmation** at key decision points (see list below)+- **Use best judgement** for design details — make confident, creative choices based on the user's aesthetic + mood selection without asking for every specific font, color, or layout decision+- **Apply design from the start** — never build neutral then restyle+- **Verify via Playwright** after every significant change+- **Commit after every page and component** — each gets its own dedicated commit, never batch multiple together+- **No screenshots** — only use `browser_snapshot` (accessibility snapshots) to verify pages; never use `browser_take_screenshot` as it clutters the user's directory. Give the user the dev server URL for visual preview.++### Key Decision Points (Wait for User)++1. After Phase 1: Confirm site purpose, framework, and project location+2. After Phase 4: Approve implementation plan+3. After Phase 6: Accept site or request changes+4. At Phase 7: Deploy or skip++### Progress Tracking-After site creation, suggest these optional skills:-- `/add-seo` - Add SEO assets (meta tags, robots.txt, sitemap.xml, favicon)-- `/add-tests` - Add unit tests (Vitest) and E2E tests (Playwright)+Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Discover site requirements | Discovering requirements | Collect site name, framework, purpose, audience, and project location |+| Scaffold and launch dev server | Scaffolding project | Copy template, replace placeholders with defaults, git init, npm install, start dev server, share URL |+| Plan site components | Planning components | Determine pages, components, design direction, and routes while user previews scaffold |+| Approve implementation plan | Getting plan approval | Present implementation plan covering design and pages, get user approval |+| Implement pages and components | Building site | Apply chosen design tokens, create all pages, components, routing, navigation |+| Review with user | Reviewing site | Navigate all pages, share URL, get user feedback, apply changes |+| Deploy and wrap up | Deploying site | Ask about deployment, present summary, suggest next steps |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`. This gives the user visibility into progress and keeps the workflow deterministic.++### Quality Standards++Every site must meet these standards before completion:+- Distinctive typography via Google Fonts (no generic Inter/Roboto/Arial)+- Cohesive color palette via CSS variables+- Motion/animations (page transitions, hover states)+- All requested pages and features implemented (not placeholders)+- All routes working and navigation complete+- Git commits at key milestones+- Verified via Playwright+- User reviewed and approved+- Deployment offered----## Next Steps+## Example Workflow++### User Request+"Create a partner portal for our consultants"++### Phase 1: Discovery+- Name: Partner Portal+- Framework: React+- Purpose: Company Portal+- Audience: Internal (partners, consultants)+- Location: New folder `partner-portal` in current directory++### Phase 2: Scaffold & Launch+- React template copied, default placeholders replaced+- Git initialized, npm installed, dev server running at `http://localhost:5173`+- Playwright verified scaffold loads+- URL shared with user — they can preview immediately++### Phase 3: Component Planning+- Features: Consultant Directory, Project Tracker, Document Library, Announcements+- Aesthetic: Minimal & Clean+- Mood: Professional & Trustworthy+- Component table presented and approved+- Design choices made: DM Sans + Space Grotesk, `#1e3a5f` primary, blue-gray palette++### Phase 4: Plan Approval+- Plan presented inline with design & pages + review & deployment sections+- User approved via AskUserQuestion++### Phase 5: Implementation+- Todos created for each page, component, routing, navigation, design foundations+- Built in order: design tokens (replace defaults with chosen palette) → shared components → pages → router → nav+- Git commits after each major piece+- Playwright verified each page++### Phase 6: Review+- Summary table presented+- User reviewed at `http://localhost:5173`, requested minor color adjustment+- Adjustment applied, re-verified++### Phase 7: Deploy+- User chose to deploy → invoked `/power-pages:deploy-site`+- Final summary presented with next step suggestions++----Suggest `/setup-dataverse` to create tables for dynamic content (forms, products, team members).+**Begin with Phase 1: Discovery**diff --git a/plugins/power-pages/skills/create-site/assets/angular/angular.json b/plugins/power-pages/skills/create-site/assets/angular/angular.jsonnew file mode 100644index 000000000..55d6bf6ba--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/angular.json@@ -0,0 +1,51 @@+{+ "$schema": "./node_modules/@angular/cli/lib/config/schema.json",+ "version": 1,+ "newProjectRoot": "projects",+ "projects": {+ "__SITE_SLUG__": {+ "projectType": "application",+ "root": "",+ "sourceRoot": "src",+ "prefix": "app",+ "architect": {+ "build": {+ "builder": "@angular-devkit/build-angular:application",+ "options": {+ "outputPath": "dist/__SITE_SLUG__",+ "index": "src/index.html",+ "browser": "src/main.ts",+ "tsConfig": "tsconfig.app.json",+ "assets": [+ { "glob": "**/*", "input": "public" }+ ],+ "styles": ["src/styles.css"]+ },+ "configurations": {+ "production": {+ "budgets": [+ { "type": "initial", "maximumWarning": "500kB", "maximumError": "1MB" },+ { "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" }+ ],+ "outputHashing": "all"+ },+ "development": {+ "optimization": false,+ "extractLicenses": false,+ "sourceMap": true+ }+ },+ "defaultConfiguration": "production"+ },+ "serve": {+ "builder": "@angular-devkit/build-angular:dev-server",+ "configurations": {+ "production": { "buildTarget": "__SITE_SLUG__:build:production" },+ "development": { "buildTarget": "__SITE_SLUG__:build:development" }+ },+ "defaultConfiguration": "development"+ }+ }+ }+ }+}diff --git a/plugins/power-pages/skills/create-site/assets/angular/gitignore b/plugins/power-pages/skills/create-site/assets/angular/gitignorenew file mode 100644index 000000000..b06ab183b--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/gitignore@@ -0,0 +1,48 @@+# Dependencies+node_modules++# Build output+dist+tmp+out-tsc++# Angular+.angular/cache++# TypeScript+*.tsbuildinfo++# Environment variables+.env+.env.local+.env*.local++# Logs+*.log+npm-debug.log*+yarn-debug.log*+pnpm-debug.log*++# Testing+coverage++# Editor+.vscode/*+!.vscode/settings.json+!.vscode/tasks.json+!.vscode/launch.json+!.vscode/extensions.json+.idea+*.suo+*.ntvs*+*.njsproj+*.sln+*.sw?++# Miscellaneous+.sass-cache+testem.log++# OS+.DS_Store+Thumbs.dbdiff --git a/plugins/power-pages/skills/create-site/assets/angular/package.json b/plugins/power-pages/skills/create-site/assets/angular/package.jsonnew file mode 100644index 000000000..b2cc416fb--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/package.json@@ -0,0 +1,29 @@+{+ "name": "__SITE_SLUG__",+ "private": true,+ "version": "0.0.0",+ "scripts": {+ "dev": "ng serve",+ "build": "ng build",+ "watch": "ng build --watch"+ },+ "dependencies": {+ "@angular/animations": "^19.1.0",+ "@angular/common": "^19.1.0",+ "@angular/compiler": "^19.1.0",+ "@angular/core": "^19.1.0",+ "@angular/forms": "^19.1.0",+ "@angular/platform-browser": "^19.1.0",+ "@angular/platform-browser-dynamic": "^19.1.0",+ "@angular/router": "^19.1.0",+ "rxjs": "~7.8.0",+ "tslib": "^2.6.0",+ "zone.js": "~0.15.0"+ },+ "devDependencies": {+ "@angular-devkit/build-angular": "^19.1.0",+ "@angular/cli": "^19.1.0",+ "@angular/compiler-cli": "^19.1.0",+ "typescript": "~5.7.0"+ }+}diff --git a/plugins/power-pages/skills/create-site/assets/angular/powerpages.config.json b/plugins/power-pages/skills/create-site/assets/angular/powerpages.config.jsonnew file mode 100644index 000000000..e338efb06--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/powerpages.config.json@@ -0,0 +1,6 @@+{+ "$schema": "https://www.schemastore.org/powerpages.config.json",+ "siteName": "__SITE_NAME__",+ "compiledPath": "dist/__SITE_SLUG__/browser",+ "defaultLandingPage": "index.html"+}diff --git a/plugins/power-pages/skills/create-site/assets/angular/public/.gitkeep b/plugins/power-pages/skills/create-site/assets/angular/public/.gitkeepnew file mode 100644index 000000000..e69de29bbdiff --git a/plugins/power-pages/skills/create-site/assets/angular/src/app/app.component.ts b/plugins/power-pages/skills/create-site/assets/angular/src/app/app.component.tsnew file mode 100644index 000000000..91dfe6f08--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/src/app/app.component.ts@@ -0,0 +1,15 @@+import { Component } from '@angular/core'+import { LayoutComponent } from './components/layout.component'+import { RouterOutlet } from '@angular/router'++@Component({+ selector: 'app-root',+ standalone: true,+ imports: [LayoutComponent, RouterOutlet],+ template: `+ <app-layout>+ <router-outlet />+ </app-layout>+ `,+})+export class AppComponent {}diff --git a/plugins/power-pages/skills/create-site/assets/angular/src/app/app.config.ts b/plugins/power-pages/skills/create-site/assets/angular/src/app/app.config.tsnew file mode 100644index 000000000..7c6887de4--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/src/app/app.config.ts@@ -0,0 +1,10 @@+import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'+import { provideRouter } from '@angular/router'+import { routes } from './app.routes'++export const appConfig: ApplicationConfig = {+ providers: [+ provideZoneChangeDetection({ eventCoalescing: true }),+ provideRouter(routes),+ ],+}diff --git a/plugins/power-pages/skills/create-site/assets/angular/src/app/app.routes.ts b/plugins/power-pages/skills/create-site/assets/angular/src/app/app.routes.tsnew file mode 100644index 000000000..0939247c8--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/src/app/app.routes.ts@@ -0,0 +1,8 @@+import { Routes } from '@angular/router'+import { HomeComponent } from './pages/home.component'+import { AboutComponent } from './pages/about.component'++export const routes: Routes = [+ { path: '', component: HomeComponent },+ { path: 'about', component: AboutComponent },+]diff --git a/plugins/power-pages/skills/create-site/assets/angular/src/app/components/layout.component.ts b/plugins/power-pages/skills/create-site/assets/angular/src/app/components/layout.component.tsnew file mode 100644index 000000000..3bf25acbf--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/src/app/components/layout.component.ts@@ -0,0 +1,30 @@+import { Component } from '@angular/core'+import { RouterLink, RouterLinkActive } from '@angular/router'++@Component({+ selector: 'app-layout',+ standalone: true,+ imports: [RouterLink, RouterLinkActive],+ template: `+ <div class="app">+ <header class="header">+ <nav class="nav">+ <a routerLink="/" class="logo">__SITE_NAME__</a>+ <div class="nav-links">+ <a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">Home</a>+ <a routerLink="/about" routerLinkActive="active">About</a>+ </div>+ </nav>+ </header>+ <main class="main">+ <ng-content />+ </main>+ <footer class="footer">+ <p>© {{ year }} __SITE_NAME__</p>+ </footer>+ </div>+ `,+})+export class LayoutComponent {+ year = new Date().getFullYear()+}diff --git a/plugins/power-pages/skills/create-site/assets/angular/src/app/pages/about.component.ts b/plugins/power-pages/skills/create-site/assets/angular/src/app/pages/about.component.tsnew file mode 100644index 000000000..3e98e46bc--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/src/app/pages/about.component.ts@@ -0,0 +1,13 @@+import { Component } from '@angular/core'++@Component({+ selector: 'app-about',+ standalone: true,+ template: `+ <div class="page">+ <h1>About</h1>+ <p>Learn more about __SITE_NAME__ and what we do.</p>+ </div>+ `,+})+export class AboutComponent {}diff --git a/plugins/power-pages/skills/create-site/assets/angular/src/app/pages/home.component.ts b/plugins/power-pages/skills/create-site/assets/angular/src/app/pages/home.component.tsnew file mode 100644index 000000000..0a996191e--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/src/app/pages/home.component.ts@@ -0,0 +1,39 @@+import { Component } from '@angular/core'+import { RouterLink } from '@angular/router'++@Component({+ selector: 'app-home',+ standalone: true,+ imports: [RouterLink],+ template: `+ <div class="page">+ <section class="hero">+ <h1>__SITE_NAME__</h1>+ <p class="hero-subtitle">__SITE_DESCRIPTION__</p>+ <div class="hero-actions">+ <a href="#features" class="btn btn-primary">Get Started</a>+ <a routerLink="/about" class="btn btn-secondary">Learn More</a>+ </div>+ </section>++ <section id="features" class="features">+ <h2>Features</h2>+ <div class="feature-grid">+ <div class="feature-card">+ <h3>Fast & Modern</h3>+ <p>Built with the latest web technologies for optimal performance.</p>+ </div>+ <div class="feature-card">+ <h3>Responsive Design</h3>+ <p>Looks great on every device, from desktop to mobile.</p>+ </div>+ <div class="feature-card">+ <h3>Easy to Customize</h3>+ <p>Theme system with CSS custom properties for quick styling.</p>+ </div>+ </div>+ </section>+ </div>+ `,+})+export class HomeComponent {}diff --git a/plugins/power-pages/skills/create-site/assets/angular/src/index.html b/plugins/power-pages/skills/create-site/assets/angular/src/index.htmlnew file mode 100644index 000000000..1681a851f--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/src/index.html@@ -0,0 +1,15 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>__SITE_NAME__</title>+ <meta name="description" content="__SITE_DESCRIPTION__" />+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />+ </head>+ <body>+ <app-root></app-root>+ </body>+</html>diff --git a/plugins/power-pages/skills/create-site/assets/angular/src/main.ts b/plugins/power-pages/skills/create-site/assets/angular/src/main.tsnew file mode 100644index 000000000..3a5904f3b--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/src/main.ts@@ -0,0 +1,5 @@+import { bootstrapApplication } from '@angular/platform-browser'+import { AppComponent } from './app/app.component'+import { appConfig } from './app/app.config'++bootstrapApplication(AppComponent, appConfig)diff --git a/plugins/power-pages/skills/create-site/assets/angular/src/styles.css b/plugins/power-pages/skills/create-site/assets/angular/src/styles.cssnew file mode 100644index 000000000..3fd01e58e--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/src/styles.css@@ -0,0 +1,253 @@+:root {+ --color-primary: __PRIMARY_COLOR__;+ --color-secondary: __SECONDARY_COLOR__;+ --color-bg: __BG_COLOR__;+ --color-surface: __SURFACE_COLOR__;+ --color-text: __TEXT_COLOR__;+ --color-text-muted: __TEXT_MUTED__;+ --font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;+ --max-width: 1200px;+ --header-height: 64px;+ --radius: 8px;+ --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);+ --shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);+ --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.07), 0 2px 4px rgba(0, 0, 0, 0.06);+ --transition: 150ms ease;+}++*,+*::before,+*::after {+ box-sizing: border-box;+ margin: 0;+ padding: 0;+}++html {+ font-size: 16px;+ scroll-behavior: smooth;+}++body {+ font-family: var(--font-family);+ background: var(--color-bg);+ color: var(--color-text);+ line-height: 1.6;+ min-height: 100vh;+ -webkit-font-smoothing: antialiased;+}++a {+ color: var(--color-primary);+ text-decoration: none;+ transition: color var(--transition);+}++a:hover {+ text-decoration: underline;+}++img {+ max-width: 100%;+ display: block;+}++.app {+ display: flex;+ flex-direction: column;+ min-height: 100vh;+}++.header {+ background: var(--color-surface);+ box-shadow: var(--shadow-sm);+ position: sticky;+ top: 0;+ z-index: 100;+ height: var(--header-height);+}++.nav {+ max-width: var(--max-width);+ margin: 0 auto;+ padding: 0 1.5rem;+ display: flex;+ align-items: center;+ justify-content: space-between;+ height: 100%;+}++.logo {+ font-weight: 700;+ font-size: 1.25rem;+ color: var(--color-primary);+}++.logo:hover {+ text-decoration: none;+ opacity: 0.9;+}++.nav-links {+ display: flex;+ gap: 1.5rem;+}++.nav-links a {+ color: var(--color-text);+ font-weight: 500;+ padding: 0.25rem 0;+ border-bottom: 2px solid transparent;+ transition: color var(--transition), border-color var(--transition);+}++.nav-links a:hover,+.nav-links a.active {+ color: var(--color-primary);+ text-decoration: none;+ border-bottom-color: var(--color-primary);+}++.main {+ flex: 1;+ max-width: var(--max-width);+ margin: 0 auto;+ padding: 2rem 1.5rem;+ width: 100%;+}++.footer {+ background: var(--color-surface);+ text-align: center;+ padding: 1.5rem;+ color: var(--color-text-muted);+ font-size: 0.875rem;+ margin-top: auto;+}++.page {+ max-width: 800px;+}++.page h1 {+ font-size: 2rem;+ margin-bottom: 1rem;+}++.hero {+ padding: 4rem 0 3rem;+ max-width: 640px;+}++.hero h1 {+ font-size: 3rem;+ font-weight: 800;+ line-height: 1.1;+ margin-bottom: 1rem;+}++.hero-subtitle {+ font-size: 1.25rem;+ color: var(--color-text-muted);+ margin-bottom: 2rem;+}++.hero-actions {+ display: flex;+ gap: 1rem;+ flex-wrap: wrap;+}++.btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 0.625rem 1.5rem;+ border-radius: var(--radius);+ font-weight: 600;+ font-size: 0.9375rem;+ transition: all var(--transition);+ cursor: pointer;+ border: none;+ text-decoration: none;+}++.btn:hover {+ text-decoration: none;+}++.btn-primary {+ background: var(--color-primary);+ color: #fff;+}++.btn-primary:hover {+ opacity: 0.9;+ color: #fff;+}++.btn-secondary {+ background: transparent;+ color: var(--color-primary);+ border: 1.5px solid var(--color-primary);+}++.btn-secondary:hover {+ background: var(--color-primary);+ color: #fff;+}++.features {+ padding: 3rem 0;+}++.features h2 {+ font-size: 1.75rem;+ margin-bottom: 2rem;+}++.feature-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));+ gap: 1.5rem;+}++.feature-card {+ background: var(--color-surface);+ border-radius: var(--radius);+ padding: 1.5rem;+ box-shadow: var(--shadow-sm);+ transition: box-shadow var(--transition);+}++.feature-card:hover {+ box-shadow: var(--shadow-md);+}++.feature-card h3 {+ font-size: 1.125rem;+ margin-bottom: 0.5rem;+}++.feature-card p {+ color: var(--color-text-muted);+ font-size: 0.9375rem;+}++@media (max-width: 768px) {+ .hero h1 {+ font-size: 2.25rem;+ }++ .hero-subtitle {+ font-size: 1.125rem;+ }++ .nav-links {+ gap: 1rem;+ }++ .feature-grid {+ grid-template-columns: 1fr;+ }+}diff --git a/plugins/power-pages/skills/create-site/assets/angular/tsconfig.app.json b/plugins/power-pages/skills/create-site/assets/angular/tsconfig.app.jsonnew file mode 100644index 000000000..bac1e0223--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/tsconfig.app.json@@ -0,0 +1,8 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "outDir": "./out-tsc/app"+ },+ "files": ["src/main.ts"],+ "include": ["src/**/*.d.ts"]+}diff --git a/plugins/power-pages/skills/create-site/assets/angular/tsconfig.json b/plugins/power-pages/skills/create-site/assets/angular/tsconfig.jsonnew file mode 100644index 000000000..da2791efa--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/angular/tsconfig.json@@ -0,0 +1,21 @@+{+ "compileOnSave": false,+ "compilerOptions": {+ "outDir": "./dist/out-tsc",+ "strict": true,+ "noImplicitOverride": true,+ "noPropertyAccessFromIndexSignature": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true,+ "sourceMap": true,+ "declaration": false,+ "downlevelIteration": true,+ "experimentalDecorators": true,+ "moduleResolution": "bundler",+ "importHelpers": true,+ "target": "ES2022",+ "module": "ES2022",+ "lib": ["ES2022", "dom"],+ "skipLibCheck": true+ }+}diff --git a/plugins/power-pages/skills/create-site/assets/astro/astro.config.mjs b/plugins/power-pages/skills/create-site/assets/astro/astro.config.mjsnew file mode 100644index 000000000..622044de5--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/astro/astro.config.mjs@@ -0,0 +1,8 @@+import { defineConfig } from 'astro/config'++export default defineConfig({+ output: 'static',+ build: {+ format: 'directory',+ },+})diff --git a/plugins/power-pages/skills/create-site/assets/astro/gitignore b/plugins/power-pages/skills/create-site/assets/astro/gitignorenew file mode 100644index 000000000..456349dca--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/astro/gitignore@@ -0,0 +1,39 @@+# Dependencies+node_modules++# Build output+dist++# Astro+.astro++# TypeScript+*.tsbuildinfo++# Environment variables+.env+.env.local+.env*.local++# Logs+*.log+npm-debug.log*+yarn-debug.log*+pnpm-debug.log*++# Testing+coverage++# Editor+.vscode/*+!.vscode/extensions.json+.idea+*.suo+*.ntvs*+*.njsproj+*.sln+*.sw?++# OS+.DS_Store+Thumbs.dbdiff --git a/plugins/power-pages/skills/create-site/assets/astro/package.json b/plugins/power-pages/skills/create-site/assets/astro/package.jsonnew file mode 100644index 000000000..7e65c9cd2--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/astro/package.json@@ -0,0 +1,14 @@+{+ "name": "__SITE_SLUG__",+ "private": true,+ "version": "0.0.0",+ "type": "module",+ "scripts": {+ "dev": "astro dev",+ "build": "astro build",+ "preview": "astro preview"+ },+ "dependencies": {+ "astro": "^5.2.0"+ }+}diff --git a/plugins/power-pages/skills/create-site/assets/astro/powerpages.config.json b/plugins/power-pages/skills/create-site/assets/astro/powerpages.config.jsonnew file mode 100644index 000000000..38b910994--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/astro/powerpages.config.json@@ -0,0 +1,6 @@+{+ "$schema": "https://www.schemastore.org/powerpages.config.json",+ "siteName": "__SITE_NAME__",+ "compiledPath": "dist",+ "defaultLandingPage": "index.html"+}diff --git a/plugins/power-pages/skills/create-site/assets/astro/public/.gitkeep b/plugins/power-pages/skills/create-site/assets/astro/public/.gitkeepnew file mode 100644index 000000000..e69de29bbdiff --git a/plugins/power-pages/skills/create-site/assets/astro/src/components/Footer.astro b/plugins/power-pages/skills/create-site/assets/astro/src/components/Footer.astronew file mode 100644index 000000000..0a195b973--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/astro/src/components/Footer.astro@@ -0,0 +1,3 @@+<footer class="footer">+ <p>© {new Date().getFullYear()} __SITE_NAME__</p>+</footer>diff --git a/plugins/power-pages/skills/create-site/assets/astro/src/components/Header.astro b/plugins/power-pages/skills/create-site/assets/astro/src/components/Header.astronew file mode 100644index 000000000..89d87dac8--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/astro/src/components/Header.astro@@ -0,0 +1,17 @@+---+interface Props {+ currentPath: string+}++const { currentPath } = Astro.props+---++<header class="header">+ <nav class="nav">+ <a href="/" class="logo">__SITE_NAME__</a>+ <div class="nav-links">+ <a href="/" class:list={[{ active: currentPath === '/' }]}>Home</a>+ <a href="/about" class:list={[{ active: currentPath === '/about/' || currentPath === '/about' }]}>About</a>+ </div>+ </nav>+</header>diff --git a/plugins/power-pages/skills/create-site/assets/astro/src/layouts/Layout.astro b/plugins/power-pages/skills/create-site/assets/astro/src/layouts/Layout.astronew file mode 100644index 000000000..a36c3961e--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/astro/src/layouts/Layout.astro@@ -0,0 +1,36 @@+---+import { ViewTransitions } from 'astro:transitions'+import Header from '../components/Header.astro'+import Footer from '../components/Footer.astro'+import '../styles/theme.css'++interface Props {+ title: string+}++const { title } = Astro.props+const pageTitle = title === 'Home' ? '__SITE_NAME__' : `${title} | __SITE_NAME__`+---++<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>{pageTitle}</title>+ <meta name="description" content="__SITE_DESCRIPTION__" />+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />+ <ViewTransitions />+ </head>+ <body>+ <div class="app">+ <Header currentPath={Astro.url.pathname} />+ <main class="main">+ <slot />+ </main>+ <Footer />+ </div>+ </body>+</html>diff --git a/plugins/power-pages/skills/create-site/assets/astro/src/pages/about.astro b/plugins/power-pages/skills/create-site/assets/astro/src/pages/about.astronew file mode 100644index 000000000..4301dd49d--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/astro/src/pages/about.astro@@ -0,0 +1,10 @@+---+import Layout from '../layouts/Layout.astro'+---++<Layout title="About">+ <div class="page">+ <h1>About</h1>+ <p>Learn more about __SITE_NAME__ and what we do.</p>+ </div>+</Layout>diff --git a/plugins/power-pages/skills/create-site/assets/astro/src/pages/index.astro b/plugins/power-pages/skills/create-site/assets/astro/src/pages/index.astronew file mode 100644index 000000000..42161b9cf--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/astro/src/pages/index.astro@@ -0,0 +1,32 @@+---+import Layout from '../layouts/Layout.astro'+---++<Layout title="Home">+ <section class="hero">+ <h1>__SITE_NAME__</h1>+ <p class="hero-subtitle">__SITE_DESCRIPTION__</p>+ <div class="hero-actions">+ <a href="#features" class="btn btn-primary">Get Started</a>+ <a href="/about" class="btn btn-secondary">Learn More</a>+ </div>+ </section>++ <section id="features" class="features">+ <h2>Features</h2>+ <div class="feature-grid">+ <div class="feature-card">+ <h3>Fast & Modern</h3>+ <p>Built with the latest web technologies for optimal performance.</p>+ </div>+ <div class="feature-card">+ <h3>Responsive Design</h3>+ <p>Looks great on every device, from desktop to mobile.</p>+ </div>+ <div class="feature-card">+ <h3>Easy to Customize</h3>+ <p>Theme system with CSS custom properties for quick styling.</p>+ </div>+ </div>+ </section>+</Layout>diff --git a/plugins/power-pages/skills/create-site/assets/astro/src/styles/theme.css b/plugins/power-pages/skills/create-site/assets/astro/src/styles/theme.cssnew file mode 100644index 000000000..778f1bb40--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/astro/src/styles/theme.css@@ -0,0 +1,258 @@+:root {+ --color-primary: __PRIMARY_COLOR__;+ --color-secondary: __SECONDARY_COLOR__;+ --color-bg: __BG_COLOR__;+ --color-surface: __SURFACE_COLOR__;+ --color-text: __TEXT_COLOR__;+ --color-text-muted: __TEXT_MUTED__;+ --font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;+ --max-width: 1200px;+ --header-height: 64px;+ --radius: 8px;+ --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);+ --shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);+ --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.07), 0 2px 4px rgba(0, 0, 0, 0.06);+ --transition: 150ms ease;+}++*,+*::before,+*::after {+ box-sizing: border-box;+ margin: 0;+ padding: 0;+}++html {+ font-size: 16px;+ scroll-behavior: smooth;+}++body {+ font-family: var(--font-family);+ background: var(--color-bg);+ color: var(--color-text);+ line-height: 1.6;+ min-height: 100vh;+ -webkit-font-smoothing: antialiased;+}++a {+ color: var(--color-primary);+ text-decoration: none;+ transition: color var(--transition);+}++a:hover {+ text-decoration: underline;+}++img {+ max-width: 100%;+ display: block;+}++.app {+ display: flex;+ flex-direction: column;+ min-height: 100vh;+}++.header {+ background: var(--color-surface);+ box-shadow: var(--shadow-sm);+ position: sticky;+ top: 0;+ z-index: 100;+ height: var(--header-height);+}++.nav {+ max-width: var(--max-width);+ margin: 0 auto;+ padding: 0 1.5rem;+ display: flex;+ align-items: center;+ justify-content: space-between;+ height: 100%;+}++.logo {+ font-weight: 700;+ font-size: 1.25rem;+ color: var(--color-primary);+}++.logo:hover {+ text-decoration: none;+ opacity: 0.9;+}++.nav-links {+ display: flex;+ gap: 1.5rem;+}++.nav-links a {+ color: var(--color-text);+ font-weight: 500;+ padding: 0.25rem 0;+ border-bottom: 2px solid transparent;+ transition: color var(--transition), border-color var(--transition);+}++.nav-links a:hover,+.nav-links a.active {+ color: var(--color-primary);+ text-decoration: none;+ border-bottom-color: var(--color-primary);+}++.main {+ flex: 1;+ max-width: var(--max-width);+ margin: 0 auto;+ padding: 2rem 1.5rem;+ width: 100%;+}++.footer {+ background: var(--color-surface);+ text-align: center;+ padding: 1.5rem;+ color: var(--color-text-muted);+ font-size: 0.875rem;+ margin-top: auto;+}++.page {+ max-width: 800px;+}++.page h1 {+ font-size: 2rem;+ margin-bottom: 1rem;+}++.hero {+ padding: 4rem 0 3rem;+ max-width: 640px;+}++.hero h1 {+ font-size: 3rem;+ font-weight: 800;+ line-height: 1.1;+ margin-bottom: 1rem;+}++.hero-subtitle {+ font-size: 1.25rem;+ color: var(--color-text-muted);+ margin-bottom: 2rem;+}++.hero-actions {+ display: flex;+ gap: 1rem;+ flex-wrap: wrap;+}++.btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 0.625rem 1.5rem;+ border-radius: var(--radius);+ font-weight: 600;+ font-size: 0.9375rem;+ transition: all var(--transition);+ cursor: pointer;+ border: none;+ text-decoration: none;+}++.btn:hover {+ text-decoration: none;+}++.btn-primary {+ background: var(--color-primary);+ color: #fff;+}++.btn-primary:hover {+ opacity: 0.9;+ color: #fff;+}++.btn-secondary {+ background: transparent;+ color: var(--color-primary);+ border: 1.5px solid var(--color-primary);+}++.btn-secondary:hover {+ background: var(--color-primary);+ color: #fff;+}++.features {+ padding: 3rem 0;+}++.features h2 {+ font-size: 1.75rem;+ margin-bottom: 2rem;+}++.feature-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));+ gap: 1.5rem;+}++.feature-card {+ background: var(--color-surface);+ border-radius: var(--radius);+ padding: 1.5rem;+ box-shadow: var(--shadow-sm);+ transition: box-shadow var(--transition);+}++.feature-card:hover {+ box-shadow: var(--shadow-md);+}++.feature-card h3 {+ font-size: 1.125rem;+ margin-bottom: 0.5rem;+}++.feature-card p {+ color: var(--color-text-muted);+ font-size: 0.9375rem;+}++::view-transition-old(root),+::view-transition-new(root) {+ animation-duration: 200ms;+}++@media (max-width: 768px) {+ .hero h1 {+ font-size: 2.25rem;+ }++ .hero-subtitle {+ font-size: 1.125rem;+ }++ .nav-links {+ gap: 1rem;+ }++ .feature-grid {+ grid-template-columns: 1fr;+ }+}diff --git a/plugins/power-pages/skills/create-site/assets/astro/tsconfig.json b/plugins/power-pages/skills/create-site/assets/astro/tsconfig.jsonnew file mode 100644index 000000000..bcbf8b509--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/astro/tsconfig.json@@ -0,0 +1,3 @@+{+ "extends": "astro/tsconfigs/strict"+}diff --git a/plugins/power-pages/skills/create-site/assets/react/gitignore b/plugins/power-pages/skills/create-site/assets/react/gitignorenew file mode 100644index 000000000..98ee4ab93--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/gitignore@@ -0,0 +1,42 @@+# Dependencies+node_modules++# Build output+dist+dist-ssr++# Vite+.vite+vite.config.js.timestamp-*+vite.config.ts.timestamp-*++# TypeScript+*.tsbuildinfo++# Environment variables+.env+.env.local+.env*.local++# Logs+*.log+npm-debug.log*+yarn-debug.log*+pnpm-debug.log*++# Testing+coverage++# Editor+.vscode/*+!.vscode/extensions.json+.idea+*.suo+*.ntvs*+*.njsproj+*.sln+*.sw?++# OS+.DS_Store+Thumbs.dbdiff --git a/plugins/power-pages/skills/create-site/assets/react/index.html b/plugins/power-pages/skills/create-site/assets/react/index.htmlnew file mode 100644index 000000000..cf73f8fa1--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/index.html@@ -0,0 +1,16 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>__SITE_NAME__</title>+ <meta name="description" content="__SITE_DESCRIPTION__" />+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/main.tsx"></script>+ </body>+</html>diff --git a/plugins/power-pages/skills/create-site/assets/react/package.json b/plugins/power-pages/skills/create-site/assets/react/package.jsonnew file mode 100644index 000000000..b7804e445--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/package.json@@ -0,0 +1,23 @@+{+ "name": "__SITE_SLUG__",+ "private": true,+ "version": "0.0.0",+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "tsc -b && vite build",+ "preview": "vite preview"+ },+ "dependencies": {+ "react": "^19.0.0",+ "react-dom": "^19.0.0",+ "react-router-dom": "^7.1.0"+ },+ "devDependencies": {+ "@types/react": "^19.0.0",+ "@types/react-dom": "^19.0.0",+ "@vitejs/plugin-react": "^4.3.0",+ "typescript": "~5.7.0",+ "vite": "^6.0.0"+ }+}diff --git a/plugins/power-pages/skills/create-site/assets/react/powerpages.config.json b/plugins/power-pages/skills/create-site/assets/react/powerpages.config.jsonnew file mode 100644index 000000000..38b910994--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/powerpages.config.json@@ -0,0 +1,6 @@+{+ "$schema": "https://www.schemastore.org/powerpages.config.json",+ "siteName": "__SITE_NAME__",+ "compiledPath": "dist",+ "defaultLandingPage": "index.html"+}diff --git a/plugins/power-pages/skills/create-site/assets/react/src/App.tsx b/plugins/power-pages/skills/create-site/assets/react/src/App.tsxnew file mode 100644index 000000000..c0d93e4d0--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/src/App.tsx@@ -0,0 +1,15 @@+import { Routes, Route } from 'react-router-dom'+import Layout from './components/Layout'+import Home from './pages/Home'+import About from './pages/About'++export default function App() {+ return (+ <Layout>+ <Routes>+ <Route path="/" element={<Home />} />+ <Route path="/about" element={<About />} />+ </Routes>+ </Layout>+ )+}diff --git a/plugins/power-pages/skills/create-site/assets/react/src/components/Layout.tsx b/plugins/power-pages/skills/create-site/assets/react/src/components/Layout.tsxnew file mode 100644index 000000000..0d5bef0d5--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/src/components/Layout.tsx@@ -0,0 +1,24 @@+import { type ReactNode } from 'react'+import { Link, useLocation } from 'react-router-dom'++export default function Layout({ children }: { children: ReactNode }) {+ const location = useLocation()++ return (+ <div className="app">+ <header className="header">+ <nav className="nav">+ <Link to="/" className="logo">__SITE_NAME__</Link>+ <div className="nav-links">+ <Link to="/" className={location.pathname === '/' ? 'active' : ''}>Home</Link>+ <Link to="/about" className={location.pathname === '/about' ? 'active' : ''}>About</Link>+ </div>+ </nav>+ </header>+ <main className="main">{children}</main>+ <footer className="footer">+ <p>© {new Date().getFullYear()} __SITE_NAME__</p>+ </footer>+ </div>+ )+}diff --git a/plugins/power-pages/skills/create-site/assets/react/src/main.tsx b/plugins/power-pages/skills/create-site/assets/react/src/main.tsxnew file mode 100644index 000000000..a114d89e6--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/src/main.tsx@@ -0,0 +1,13 @@+import { StrictMode } from 'react'+import { createRoot } from 'react-dom/client'+import { BrowserRouter } from 'react-router-dom'+import App from './App'+import './styles/theme.css'++createRoot(document.getElementById('root')!).render(+ <StrictMode>+ <BrowserRouter>+ <App />+ </BrowserRouter>+ </StrictMode>,+)diff --git a/plugins/power-pages/skills/create-site/assets/react/src/pages/About.tsx b/plugins/power-pages/skills/create-site/assets/react/src/pages/About.tsxnew file mode 100644index 000000000..1377d05c1--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/src/pages/About.tsx@@ -0,0 +1,8 @@+export default function About() {+ return (+ <div className="page">+ <h1>About</h1>+ <p>Learn more about __SITE_NAME__ and what we do.</p>+ </div>+ )+}diff --git a/plugins/power-pages/skills/create-site/assets/react/src/pages/Home.tsx b/plugins/power-pages/skills/create-site/assets/react/src/pages/Home.tsxnew file mode 100644index 000000000..5a4318505--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/src/pages/Home.tsx@@ -0,0 +1,32 @@+export default function Home() {+ return (+ <div className="page">+ <section className="hero">+ <h1>__SITE_NAME__</h1>+ <p className="hero-subtitle">__SITE_DESCRIPTION__</p>+ <div className="hero-actions">+ <a href="#features" className="btn btn-primary">Get Started</a>+ <a href="/about" className="btn btn-secondary">Learn More</a>+ </div>+ </section>++ <section id="features" className="features">+ <h2>Features</h2>+ <div className="feature-grid">+ <div className="feature-card">+ <h3>Fast & Modern</h3>+ <p>Built with the latest web technologies for optimal performance.</p>+ </div>+ <div className="feature-card">+ <h3>Responsive Design</h3>+ <p>Looks great on every device, from desktop to mobile.</p>+ </div>+ <div className="feature-card">+ <h3>Easy to Customize</h3>+ <p>Theme system with CSS custom properties for quick styling.</p>+ </div>+ </div>+ </section>+ </div>+ )+}diff --git a/plugins/power-pages/skills/create-site/assets/react/src/styles/theme.css b/plugins/power-pages/skills/create-site/assets/react/src/styles/theme.cssnew file mode 100644index 000000000..3fd01e58e--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/src/styles/theme.css@@ -0,0 +1,253 @@+:root {+ --color-primary: __PRIMARY_COLOR__;+ --color-secondary: __SECONDARY_COLOR__;+ --color-bg: __BG_COLOR__;+ --color-surface: __SURFACE_COLOR__;+ --color-text: __TEXT_COLOR__;+ --color-text-muted: __TEXT_MUTED__;+ --font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;+ --max-width: 1200px;+ --header-height: 64px;+ --radius: 8px;+ --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);+ --shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);+ --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.07), 0 2px 4px rgba(0, 0, 0, 0.06);+ --transition: 150ms ease;+}++*,+*::before,+*::after {+ box-sizing: border-box;+ margin: 0;+ padding: 0;+}++html {+ font-size: 16px;+ scroll-behavior: smooth;+}++body {+ font-family: var(--font-family);+ background: var(--color-bg);+ color: var(--color-text);+ line-height: 1.6;+ min-height: 100vh;+ -webkit-font-smoothing: antialiased;+}++a {+ color: var(--color-primary);+ text-decoration: none;+ transition: color var(--transition);+}++a:hover {+ text-decoration: underline;+}++img {+ max-width: 100%;+ display: block;+}++.app {+ display: flex;+ flex-direction: column;+ min-height: 100vh;+}++.header {+ background: var(--color-surface);+ box-shadow: var(--shadow-sm);+ position: sticky;+ top: 0;+ z-index: 100;+ height: var(--header-height);+}++.nav {+ max-width: var(--max-width);+ margin: 0 auto;+ padding: 0 1.5rem;+ display: flex;+ align-items: center;+ justify-content: space-between;+ height: 100%;+}++.logo {+ font-weight: 700;+ font-size: 1.25rem;+ color: var(--color-primary);+}++.logo:hover {+ text-decoration: none;+ opacity: 0.9;+}++.nav-links {+ display: flex;+ gap: 1.5rem;+}++.nav-links a {+ color: var(--color-text);+ font-weight: 500;+ padding: 0.25rem 0;+ border-bottom: 2px solid transparent;+ transition: color var(--transition), border-color var(--transition);+}++.nav-links a:hover,+.nav-links a.active {+ color: var(--color-primary);+ text-decoration: none;+ border-bottom-color: var(--color-primary);+}++.main {+ flex: 1;+ max-width: var(--max-width);+ margin: 0 auto;+ padding: 2rem 1.5rem;+ width: 100%;+}++.footer {+ background: var(--color-surface);+ text-align: center;+ padding: 1.5rem;+ color: var(--color-text-muted);+ font-size: 0.875rem;+ margin-top: auto;+}++.page {+ max-width: 800px;+}++.page h1 {+ font-size: 2rem;+ margin-bottom: 1rem;+}++.hero {+ padding: 4rem 0 3rem;+ max-width: 640px;+}++.hero h1 {+ font-size: 3rem;+ font-weight: 800;+ line-height: 1.1;+ margin-bottom: 1rem;+}++.hero-subtitle {+ font-size: 1.25rem;+ color: var(--color-text-muted);+ margin-bottom: 2rem;+}++.hero-actions {+ display: flex;+ gap: 1rem;+ flex-wrap: wrap;+}++.btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 0.625rem 1.5rem;+ border-radius: var(--radius);+ font-weight: 600;+ font-size: 0.9375rem;+ transition: all var(--transition);+ cursor: pointer;+ border: none;+ text-decoration: none;+}++.btn:hover {+ text-decoration: none;+}++.btn-primary {+ background: var(--color-primary);+ color: #fff;+}++.btn-primary:hover {+ opacity: 0.9;+ color: #fff;+}++.btn-secondary {+ background: transparent;+ color: var(--color-primary);+ border: 1.5px solid var(--color-primary);+}++.btn-secondary:hover {+ background: var(--color-primary);+ color: #fff;+}++.features {+ padding: 3rem 0;+}++.features h2 {+ font-size: 1.75rem;+ margin-bottom: 2rem;+}++.feature-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));+ gap: 1.5rem;+}++.feature-card {+ background: var(--color-surface);+ border-radius: var(--radius);+ padding: 1.5rem;+ box-shadow: var(--shadow-sm);+ transition: box-shadow var(--transition);+}++.feature-card:hover {+ box-shadow: var(--shadow-md);+}++.feature-card h3 {+ font-size: 1.125rem;+ margin-bottom: 0.5rem;+}++.feature-card p {+ color: var(--color-text-muted);+ font-size: 0.9375rem;+}++@media (max-width: 768px) {+ .hero h1 {+ font-size: 2.25rem;+ }++ .hero-subtitle {+ font-size: 1.125rem;+ }++ .nav-links {+ gap: 1rem;+ }++ .feature-grid {+ grid-template-columns: 1fr;+ }+}diff --git a/plugins/power-pages/skills/create-site/assets/react/tsconfig.json b/plugins/power-pages/skills/create-site/assets/react/tsconfig.jsonnew file mode 100644index 000000000..109f0ac28--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/tsconfig.json@@ -0,0 +1,20 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "useDefineForClassFields": true,+ "lib": ["ES2020", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "skipLibCheck": true,+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "isolatedModules": true,+ "moduleDetection": "force",+ "noEmit": true,+ "jsx": "react-jsx",+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noFallthroughCasesInSwitch": true+ },+ "include": ["src"]+}diff --git a/plugins/power-pages/skills/create-site/assets/react/vite.config.ts b/plugins/power-pages/skills/create-site/assets/react/vite.config.tsnew file mode 100644index 000000000..9f60fec98--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/react/vite.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from 'vite'+import react from '@vitejs/plugin-react'++export default defineConfig({+ plugins: [react()],+ build: {+ outDir: 'dist',+ },+})diff --git a/plugins/power-pages/skills/create-site/assets/vue/env.d.ts b/plugins/power-pages/skills/create-site/assets/vue/env.d.tsnew file mode 100644index 000000000..323c78a6c--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/env.d.ts@@ -0,0 +1,7 @@+/// <reference types="vite/client" />++declare module '*.vue' {+ import type { DefineComponent } from 'vue'+ const component: DefineComponent<{}, {}, any>+ export default component+}diff --git a/plugins/power-pages/skills/create-site/assets/vue/gitignore b/plugins/power-pages/skills/create-site/assets/vue/gitignorenew file mode 100644index 000000000..98ee4ab93--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/gitignore@@ -0,0 +1,42 @@+# Dependencies+node_modules++# Build output+dist+dist-ssr++# Vite+.vite+vite.config.js.timestamp-*+vite.config.ts.timestamp-*++# TypeScript+*.tsbuildinfo++# Environment variables+.env+.env.local+.env*.local++# Logs+*.log+npm-debug.log*+yarn-debug.log*+pnpm-debug.log*++# Testing+coverage++# Editor+.vscode/*+!.vscode/extensions.json+.idea+*.suo+*.ntvs*+*.njsproj+*.sln+*.sw?++# OS+.DS_Store+Thumbs.dbdiff --git a/plugins/power-pages/skills/create-site/assets/vue/index.html b/plugins/power-pages/skills/create-site/assets/vue/index.htmlnew file mode 100644index 000000000..703e98c01--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/index.html@@ -0,0 +1,16 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>__SITE_NAME__</title>+ <meta name="description" content="__SITE_DESCRIPTION__" />+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />+ </head>+ <body>+ <div id="app"></div>+ <script type="module" src="/src/main.ts"></script>+ </body>+</html>diff --git a/plugins/power-pages/skills/create-site/assets/vue/package.json b/plugins/power-pages/skills/create-site/assets/vue/package.jsonnew file mode 100644index 000000000..318173dcd--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/package.json@@ -0,0 +1,21 @@+{+ "name": "__SITE_SLUG__",+ "private": true,+ "version": "0.0.0",+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "vue-tsc -b && vite build",+ "preview": "vite preview"+ },+ "dependencies": {+ "vue": "^3.5.0",+ "vue-router": "^4.5.0"+ },+ "devDependencies": {+ "@vitejs/plugin-vue": "^5.2.0",+ "typescript": "~5.7.0",+ "vite": "^6.0.0",+ "vue-tsc": "^2.2.0"+ }+}diff --git a/plugins/power-pages/skills/create-site/assets/vue/powerpages.config.json b/plugins/power-pages/skills/create-site/assets/vue/powerpages.config.jsonnew file mode 100644index 000000000..38b910994--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/powerpages.config.json@@ -0,0 +1,6 @@+{+ "$schema": "https://www.schemastore.org/powerpages.config.json",+ "siteName": "__SITE_NAME__",+ "compiledPath": "dist",+ "defaultLandingPage": "index.html"+}diff --git a/plugins/power-pages/skills/create-site/assets/vue/src/App.vue b/plugins/power-pages/skills/create-site/assets/vue/src/App.vuenew file mode 100644index 000000000..9e3c2c27e--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/src/App.vue@@ -0,0 +1,9 @@+<template>+ <Layout>+ <RouterView />+ </Layout>+</template>++<script setup lang="ts">+import Layout from './components/Layout.vue'+</script>diff --git a/plugins/power-pages/skills/create-site/assets/vue/src/components/Layout.vue b/plugins/power-pages/skills/create-site/assets/vue/src/components/Layout.vuenew file mode 100644index 000000000..3c345fec1--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/src/components/Layout.vue@@ -0,0 +1,26 @@+<template>+ <div class="app">+ <header class="header">+ <nav class="nav">+ <RouterLink to="/" class="logo">__SITE_NAME__</RouterLink>+ <div class="nav-links">+ <RouterLink to="/" :class="{ active: route.path === '/' }">Home</RouterLink>+ <RouterLink to="/about" :class="{ active: route.path === '/about' }">About</RouterLink>+ </div>+ </nav>+ </header>+ <main class="main">+ <slot />+ </main>+ <footer class="footer">+ <p>© {{ year }} __SITE_NAME__</p>+ </footer>+ </div>+</template>++<script setup lang="ts">+import { useRoute } from 'vue-router'++const route = useRoute()+const year = new Date().getFullYear()+</script>diff --git a/plugins/power-pages/skills/create-site/assets/vue/src/main.ts b/plugins/power-pages/skills/create-site/assets/vue/src/main.tsnew file mode 100644index 000000000..2d2f526af--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/src/main.ts@@ -0,0 +1,6 @@+import { createApp } from 'vue'+import App from './App.vue'+import router from './router'+import './styles/theme.css'++createApp(App).use(router).mount('#app')diff --git a/plugins/power-pages/skills/create-site/assets/vue/src/pages/About.vue b/plugins/power-pages/skills/create-site/assets/vue/src/pages/About.vuenew file mode 100644index 000000000..7131f7c94--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/src/pages/About.vue@@ -0,0 +1,6 @@+<template>+ <div class="page">+ <h1>About</h1>+ <p>Learn more about __SITE_NAME__ and what we do.</p>+ </div>+</template>diff --git a/plugins/power-pages/skills/create-site/assets/vue/src/pages/Home.vue b/plugins/power-pages/skills/create-site/assets/vue/src/pages/Home.vuenew file mode 100644index 000000000..8359358c5--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/src/pages/Home.vue@@ -0,0 +1,30 @@+<template>+ <div class="page">+ <section class="hero">+ <h1>__SITE_NAME__</h1>+ <p class="hero-subtitle">__SITE_DESCRIPTION__</p>+ <div class="hero-actions">+ <a href="#features" class="btn btn-primary">Get Started</a>+ <RouterLink to="/about" class="btn btn-secondary">Learn More</RouterLink>+ </div>+ </section>++ <section id="features" class="features">+ <h2>Features</h2>+ <div class="feature-grid">+ <div class="feature-card">+ <h3>Fast & Modern</h3>+ <p>Built with the latest web technologies for optimal performance.</p>+ </div>+ <div class="feature-card">+ <h3>Responsive Design</h3>+ <p>Looks great on every device, from desktop to mobile.</p>+ </div>+ <div class="feature-card">+ <h3>Easy to Customize</h3>+ <p>Theme system with CSS custom properties for quick styling.</p>+ </div>+ </div>+ </section>+ </div>+</template>diff --git a/plugins/power-pages/skills/create-site/assets/vue/src/router/index.ts b/plugins/power-pages/skills/create-site/assets/vue/src/router/index.tsnew file mode 100644index 000000000..2ed463818--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/src/router/index.ts@@ -0,0 +1,13 @@+import { createRouter, createWebHistory } from 'vue-router'+import Home from '../pages/Home.vue'+import About from '../pages/About.vue'++const router = createRouter({+ history: createWebHistory(),+ routes: [+ { path: '/', component: Home },+ { path: '/about', component: About },+ ],+})++export default routerdiff --git a/plugins/power-pages/skills/create-site/assets/vue/src/styles/theme.css b/plugins/power-pages/skills/create-site/assets/vue/src/styles/theme.cssnew file mode 100644index 000000000..3fd01e58e--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/src/styles/theme.css@@ -0,0 +1,253 @@+:root {+ --color-primary: __PRIMARY_COLOR__;+ --color-secondary: __SECONDARY_COLOR__;+ --color-bg: __BG_COLOR__;+ --color-surface: __SURFACE_COLOR__;+ --color-text: __TEXT_COLOR__;+ --color-text-muted: __TEXT_MUTED__;+ --font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;+ --max-width: 1200px;+ --header-height: 64px;+ --radius: 8px;+ --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);+ --shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);+ --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.07), 0 2px 4px rgba(0, 0, 0, 0.06);+ --transition: 150ms ease;+}++*,+*::before,+*::after {+ box-sizing: border-box;+ margin: 0;+ padding: 0;+}++html {+ font-size: 16px;+ scroll-behavior: smooth;+}++body {+ font-family: var(--font-family);+ background: var(--color-bg);+ color: var(--color-text);+ line-height: 1.6;+ min-height: 100vh;+ -webkit-font-smoothing: antialiased;+}++a {+ color: var(--color-primary);+ text-decoration: none;+ transition: color var(--transition);+}++a:hover {+ text-decoration: underline;+}++img {+ max-width: 100%;+ display: block;+}++.app {+ display: flex;+ flex-direction: column;+ min-height: 100vh;+}++.header {+ background: var(--color-surface);+ box-shadow: var(--shadow-sm);+ position: sticky;+ top: 0;+ z-index: 100;+ height: var(--header-height);+}++.nav {+ max-width: var(--max-width);+ margin: 0 auto;+ padding: 0 1.5rem;+ display: flex;+ align-items: center;+ justify-content: space-between;+ height: 100%;+}++.logo {+ font-weight: 700;+ font-size: 1.25rem;+ color: var(--color-primary);+}++.logo:hover {+ text-decoration: none;+ opacity: 0.9;+}++.nav-links {+ display: flex;+ gap: 1.5rem;+}++.nav-links a {+ color: var(--color-text);+ font-weight: 500;+ padding: 0.25rem 0;+ border-bottom: 2px solid transparent;+ transition: color var(--transition), border-color var(--transition);+}++.nav-links a:hover,+.nav-links a.active {+ color: var(--color-primary);+ text-decoration: none;+ border-bottom-color: var(--color-primary);+}++.main {+ flex: 1;+ max-width: var(--max-width);+ margin: 0 auto;+ padding: 2rem 1.5rem;+ width: 100%;+}++.footer {+ background: var(--color-surface);+ text-align: center;+ padding: 1.5rem;+ color: var(--color-text-muted);+ font-size: 0.875rem;+ margin-top: auto;+}++.page {+ max-width: 800px;+}++.page h1 {+ font-size: 2rem;+ margin-bottom: 1rem;+}++.hero {+ padding: 4rem 0 3rem;+ max-width: 640px;+}++.hero h1 {+ font-size: 3rem;+ font-weight: 800;+ line-height: 1.1;+ margin-bottom: 1rem;+}++.hero-subtitle {+ font-size: 1.25rem;+ color: var(--color-text-muted);+ margin-bottom: 2rem;+}++.hero-actions {+ display: flex;+ gap: 1rem;+ flex-wrap: wrap;+}++.btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 0.625rem 1.5rem;+ border-radius: var(--radius);+ font-weight: 600;+ font-size: 0.9375rem;+ transition: all var(--transition);+ cursor: pointer;+ border: none;+ text-decoration: none;+}++.btn:hover {+ text-decoration: none;+}++.btn-primary {+ background: var(--color-primary);+ color: #fff;+}++.btn-primary:hover {+ opacity: 0.9;+ color: #fff;+}++.btn-secondary {+ background: transparent;+ color: var(--color-primary);+ border: 1.5px solid var(--color-primary);+}++.btn-secondary:hover {+ background: var(--color-primary);+ color: #fff;+}++.features {+ padding: 3rem 0;+}++.features h2 {+ font-size: 1.75rem;+ margin-bottom: 2rem;+}++.feature-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));+ gap: 1.5rem;+}++.feature-card {+ background: var(--color-surface);+ border-radius: var(--radius);+ padding: 1.5rem;+ box-shadow: var(--shadow-sm);+ transition: box-shadow var(--transition);+}++.feature-card:hover {+ box-shadow: var(--shadow-md);+}++.feature-card h3 {+ font-size: 1.125rem;+ margin-bottom: 0.5rem;+}++.feature-card p {+ color: var(--color-text-muted);+ font-size: 0.9375rem;+}++@media (max-width: 768px) {+ .hero h1 {+ font-size: 2.25rem;+ }++ .hero-subtitle {+ font-size: 1.125rem;+ }++ .nav-links {+ gap: 1rem;+ }++ .feature-grid {+ grid-template-columns: 1fr;+ }+}diff --git a/plugins/power-pages/skills/create-site/assets/vue/tsconfig.json b/plugins/power-pages/skills/create-site/assets/vue/tsconfig.jsonnew file mode 100644index 000000000..39980f876--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/tsconfig.json@@ -0,0 +1,20 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "useDefineForClassFields": true,+ "module": "ESNext",+ "lib": ["ES2020", "DOM", "DOM.Iterable"],+ "skipLibCheck": true,+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "isolatedModules": true,+ "moduleDetection": "force",+ "noEmit": true,+ "jsx": "preserve",+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noFallthroughCasesInSwitch": true+ },+ "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "env.d.ts"]+}diff --git a/plugins/power-pages/skills/create-site/assets/vue/vite.config.ts b/plugins/power-pages/skills/create-site/assets/vue/vite.config.tsnew file mode 100644index 000000000..af96a3ea8--- /dev/null+++ b/plugins/power-pages/skills/create-site/assets/vue/vite.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from 'vite'+import vue from '@vitejs/plugin-vue'++export default defineConfig({+ plugins: [vue()],+ build: {+ outDir: 'dist',+ },+})diff --git a/plugins/power-pages/skills/create-site/references/design-aesthetics.md b/plugins/power-pages/skills/create-site/references/design-aesthetics.mdnew file mode 100644index 000000000..f5921a709--- /dev/null+++ b/plugins/power-pages/skills/create-site/references/design-aesthetics.md@@ -0,0 +1,180 @@+# Design Aesthetics Reference++Design principles, typography, color, and motion guidance for Power Pages code sites. Used by the `create-site` skill during Step 6 (Design).++## Frontend Aesthetics Principles++> **CRITICAL: Follow these principles throughout ALL design decisions. Generic "AI slop" aesthetics are the enemy — make creative, distinctive choices that surprise and delight.**++### Typography+Choose fonts that are beautiful, unique, and interesting. Load from Google Fonts.++**Never use:** Inter, Roboto, Open Sans, Lato, Arial, default system fonts++**Recommended choices by mood:**+- Code/Technical aesthetic: JetBrains Mono, Fira Code, Space Grotesk+- Editorial/Content: Playfair Display, Crimson Pro, Fraunces+- Modern/Startup: Clash Display, Satoshi, Cabinet Grotesk+- Technical/Corporate: IBM Plex family, Source Sans 3+- Distinctive/Unique: Bricolage Grotesque, Obviously, Newsreader++**Pairing principle:** High contrast = interesting. Display + monospace, serif + geometric sans, variable font across weights. Use weight extremes — 100/200 vs 800/900, not 400 vs 600. Size jumps of 3x+, not 1.5x.++### Color & Theme+Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes. Draw from IDE themes and cultural aesthetics for inspiration.++**Never use:** Purple gradients on white backgrounds as the primary scheme. Avoid the cliched AI-generated color palette.++### Motion+Use animations for effects and micro-interactions. Prioritize CSS-only solutions. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (`animation-delay`) creates more delight than scattered micro-interactions.++### Backgrounds+Create atmosphere and depth rather than defaulting to solid colors. Layer CSS gradients, use geometric patterns, or add contextual effects that match the overall aesthetic.++---++## Aesthetic x Mood Mapping++Use this table to map aesthetic + mood preferences to concrete design choices:++| Aesthetic | Mood | Font Direction | Color Direction | Motion Direction |+|-----------|------|---------------|-----------------|------------------|+| Minimal & Clean | Professional | IBM Plex Sans + JetBrains Mono | Neutral with one sharp accent | Subtle fades, minimal |+| Minimal & Clean | Creative | Space Grotesk + Crimson Pro | Muted pastels with pop accent | Smooth reveals |+| Bold & Vibrant | Professional | Cabinet Grotesk + Fira Code | Strong primary + contrasting accent | Confident slide-ins |+| Bold & Vibrant | Creative | Clash Display + Bricolage Grotesque | Saturated complementary pair | Energetic staggers |+| Dark & Moody | Technical | JetBrains Mono + Space Grotesk | Dark base (IDE-inspired) + neon accent | Terminal-style fades |+| Dark & Moody | Elegant | Playfair Display + Source Sans 3 | Deep charcoals + gold/copper accent | Slow, cinematic reveals |+| Warm & Organic | Professional | Newsreader + IBM Plex Sans | Earth tones + warm accent | Gentle eases |+| Warm & Organic | Creative | Fraunces + Satoshi | Terracotta/sage/cream palette | Organic, springy motion |++If the user provides a specific inspiration reference, adapt the design choices to match while maintaining the site's functionality.++---++## Design Application Steps++Apply design changes in this order. After each subsection, verify via `browser_snapshot` and fix any issues before proceeding.++### Typography++1. **Add Google Fonts** — Add `<link>` tags to `index.html` (or the framework's HTML entry point) for the chosen fonts. Include the specific weights needed (e.g., 200, 400, 700, 900).++ ```html+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=<FONT_1>:<WEIGHTS>&family=<FONT_2>:<WEIGHTS>&display=swap" rel="stylesheet">+ ```++2. **Update CSS variables** — Set font families in the global CSS:++ ```css+ :root {+ --font-heading: '<Display Font>', sans-serif;+ --font-body: '<Body Font>', sans-serif;+ --font-mono: '<Mono Font>', monospace;+ }+ ```++3. **Apply to elements** — Update `body`, `h1`-`h6`, `code`, and any component-specific typography. Use extreme weight contrasts and large size jumps.++4. **Verify via `browser_snapshot`**++### Color Palette++1. **Define CSS variables** — Replace existing color variables (or add new ones) in the global CSS:++ ```css+ :root {+ --color-primary: <hex>;+ --color-secondary: <hex>;+ --color-accent: <hex>;+ --color-bg: <hex>;+ --color-surface: <hex>;+ --color-text: <hex>;+ --color-text-muted: <hex>;+ --color-border: <hex>;+ }+ ```++2. **Update component references** — Replace any hardcoded colors with the CSS variables. Use `Edit` with `replace_all: true` for bulk replacements.++3. **Verify via `browser_snapshot`**++### Backgrounds & Atmosphere++Add depth and atmosphere to key sections. Choose techniques matching the aesthetic:++- **Gradient backgrounds**: Layer multiple CSS gradients for depth+- **Geometric patterns**: SVG patterns via `background-image` or pseudo-elements+- **Ambient effects**: Subtle radial gradients, mesh gradients, or backdrop blur+- **Dark themes**: Use `background: linear-gradient(...)` with dark-to-darker transitions rather than flat `#000` or `#111`++Apply to the main layout container, hero sections, and card components. Update the global CSS and key layout components.++**Verify via `browser_snapshot`**++### Motion & Animation++Add CSS animations for high-impact moments. Prioritize CSS-only solutions:++1. **Page load sequence** — Stagger element reveals with `animation-delay`:++ ```css+ @keyframes fadeInUp {+ from { opacity: 0; transform: translateY(20px); }+ to { opacity: 1; transform: translateY(0); }+ }++ .animate-in {+ animation: fadeInUp 0.6s ease-out both;+ }+ .animate-in:nth-child(1) { animation-delay: 0.1s; }+ .animate-in:nth-child(2) { animation-delay: 0.2s; }+ .animate-in:nth-child(3) { animation-delay: 0.3s; }+ ```++2. **Hover states** — Add transitions to interactive elements (buttons, cards, links):++ ```css+ .card {+ transition: transform 0.2s ease, box-shadow 0.2s ease;+ }+ .card:hover {+ transform: translateY(-2px);+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);+ }+ ```++3. **Page transitions** — If the framework supports it, add route transition animations++4. **Apply animation classes** to key components (header, hero, cards, navigation items)++**Verify via `browser_snapshot`**++### Layout & Spacing Refinement++Refine the overall visual rhythm:++- Increase whitespace where the design feels cramped+- Use consistent spacing scale (e.g., 4, 8, 16, 24, 32, 48, 64, 96px)+- Ensure visual hierarchy through size contrast (headings should be dramatically larger than body text)+- Add container max-widths for readability (prose content at 65-75ch)++**Verify via `browser_snapshot`**++### Git Commit Checkpoints++Commit after each major design subsection:++```powershell+git add -A+git commit -m "<short description of design change>"+```++**When to commit:**+- After typography changes+- After color palette changes+- After background/atmosphere changes+- After motion/animation changes+- After layout refinementdiff --git a/plugins/power-pages/skills/create-site/references/requirements-reference.md b/plugins/power-pages/skills/create-site/references/requirements-reference.mddeleted file mode 100644index 8990e8583..000000000--- a/plugins/power-pages/skills/create-site/references/requirements-reference.md+++ /dev/null@@ -1,33 +0,0 @@-# Requirements Reference--## 1. Site Purpose--Ask the user (if not already specified):-- Purpose (portal, self-service, directory, etc.)-- Key functionality needed-- Target audience--## 2. Frontend Framework--Ask the maker which frontend framework they want to use:--| Option | Description |-|--------|-------------|-| **React (Recommended)** | Most popular choice with excellent ecosystem. Best for complex interactive UIs. |-| **Angular** | Full-featured framework by Google. Great for enterprise applications with built-in state management. |-| **Vue** | Progressive framework, easy to learn. Good balance of simplicity and power. |-| **Astro** | Modern static site generator with partial hydration. Best for content-focused sites with minimal JS. |--**Unsupported**: Next.js, Nuxt.js, Remix, SvelteKit, Liquid templates, server-side APIs, React Server Components (all require server runtime - only static HTML/CSS/JS supported).--## 3. Site Features--**Content**: Landing page, navigation, about, services/products, gallery, blog-**Interactive**: Contact form, search, filtering/sorting-**Data**: Authentication (Entra ID), Dataverse Web API, form submissions--## 4. Design Preferences--**Styles**: Modern/Minimalist, Corporate/Professional, Creative/Bold, Elegant/Luxury-**Colors**: User's brand colors or suggest based on industry (consider WCAG 2.1 AA contrast)-**Special**: Accessibility, mobile-first, branding guidelines, RTL supportdiff --git a/plugins/power-pages/skills/create-site/references/site-creation-reference.md b/plugins/power-pages/skills/create-site/references/site-creation-reference.mddeleted file mode 100644index 8a1145934..000000000--- a/plugins/power-pages/skills/create-site/references/site-creation-reference.md+++ /dev/null@@ -1,70 +0,0 @@-# Site Creation Reference--## Using frontend-design Skill--Invoke with gathered requirements. **Constraints**:-- Use Vite for React/Vue (not Next.js, Nuxt.js, Remix, or SSR frameworks)-- No Liquid templates-- Output must be static HTML/CSS/JS only--## Required Project Structure--```text-/site-project-├── src/ # Source code-├── public/ # Static assets-├── build/ or dist/ # Compiled output (after build)-├── package.json # Dependencies-├── powerpages.config.json # Power Pages configuration (create this)-└── README.md-```--## powerpages.config.json--Create this configuration file in the project root:--```json-{- "siteName": "<SITE_NAME>",- "defaultLandingPage": "index.html",- "compiledPath": "./build"-}-```--### Framework-Specific compiledPath--| Framework | compiledPath |-|-----------|--------------|-| React (Vite) | `"./dist"` |-| React (CRA) | `"./build"` |-| Vue | `"./dist"` |-| Angular | `"./dist/<project-name>"` |-| Astro | `"./dist"` |--## Build Commands--Run the appropriate build command for your framework:--```powershell-# React (Create React App or Vite)-npm run build--# Angular-ng build --configuration production--# Vue-npm run build--# Astro-npm run build-```--## Memory Bank Initialization--Create `memory-bank.md` in project root with:-- Project overview (name, path, framework, date, status)-- User preferences (style, colors, features)-- Completed steps checklist for `/create-site`-- Current status and next step--Update after each subsequent step is completed.diff --git a/plugins/power-pages/skills/create-site/references/troubleshooting.md b/plugins/power-pages/skills/create-site/references/troubleshooting.mddeleted file mode 100644index 793f5d610..000000000--- a/plugins/power-pages/skills/create-site/references/troubleshooting.md+++ /dev/null@@ -1,183 +0,0 @@-# Troubleshooting--## Upload Issues--### Upload Fails with JavaScript Error--Enable JavaScript file uploads:--1. Go to Power Platform admin center-2. Navigate to Environments → [Your Environment] → Settings-3. Go to Product → Privacy + Security-4. In "Blocked Attachments", remove `js` from the list-5. Save changes--### Site Shows as Inactive After Upload--This is expected. The upload creates an INACTIVE record. Follow the activation steps in [upload-activation-reference.md](./upload-activation-reference.md).--### Site Not Appearing in Inactive Sites--- Verify the upload completed successfully-- Check you're in the correct environment-- Run `pac pages list --verbose` to confirm the site exists--### Reactivation Fails--Ensure your user has appropriate permissions:-- System Administrator or System Customizer role in the environment-- Power Pages administrator access-------## Framework Issues--### Next.js or SSR Framework Used--Power Pages code sites **do not support** server-side rendering frameworks:--| Framework | Issue |-|-----------|-------|-| Next.js | Requires Node.js server runtime |-| Nuxt.js | Requires Node.js server runtime |-| Remix | Requires server-side rendering |-| SvelteKit | Server features not supported |--Power Pages serves only **static files** from Azure CDN.--**Solution**: Recreate the project using Vite + React/Vue, or use Angular/Astro with static export.--### Liquid Templates Not Working--Liquid templates are **only supported in classic Power Pages sites**, not in code sites:--- Code sites are pure SPAs with no server-side templating-- **Solution**: Use JavaScript/TypeScript to fetch data dynamically via Dataverse Web API-- For dynamic content, call the Web API and render with your chosen framework-------## Unit Test Issues--### Tests Failing--Investigate and fix before proceeding:--| Issue | Solution |-|-------|----------|-| Component tests failing | Check that components render correctly and handle props |-| Missing test dependencies | Run `npm install` to ensure all dev dependencies are installed |-| jsdom errors | Ensure `environment: 'jsdom'` is set in Vitest config |-| Import errors | Check that test setup file imports `@testing-library/jest-dom` |--```powershell-# Run tests in watch mode for debugging-npm test--# Run specific test file-npm test -- src/components/Header.test.tsx--# Run with verbose output-npm test -- --reporter=verbose-```--**Do not skip tests or proceed with failing tests** - fix all issues before building.-------## E2E Test Issues (Playwright)--### Common E2E Failures--| Issue | Solution |-|-------|----------|-| Browser not installed | Run `npx playwright install` |-| Server not starting | Check that `webServer.command` matches your dev script |-| Wrong port | Ensure `baseURL` matches your dev server port |-| Element not found | Use Playwright UI mode to debug selectors |-| Timeout errors | Increase timeout: `await expect().toBeVisible({ timeout: 10000 })` |-| Flaky tests | Add `await page.waitForLoadState('networkidle')` before assertions |--### Debugging Commands--```powershell-# Debug with UI mode (recommended)-npm run test:e2e:ui--# Debug with headed browser-npm run test:e2e:headed--# Run single test for debugging-npx playwright test e2e/home.spec.ts --headed--# Generate test code by recording actions-npx playwright codegen http://localhost:5173--# View trace for failed tests-npx playwright show-trace trace.zip-```--**Do not skip E2E tests or proceed with failing tests** - fix all issues before building.-------## Authentication Issues--### PAC CLI Not Authenticated--```powershell-# Check current auth-pac auth list--# Create new auth profile-pac auth create-```--### Azure CLI Not Authenticated--```powershell-# Check current auth-az account show--# Login-az login-```--### Wrong Environment--```powershell-# Check current environment-pac org who--# Switch environment-pac org select-```-------## Build Issues--### Build Fails--| Issue | Solution |-|-------|----------|-| TypeScript errors | Fix type errors before building |-| Missing dependencies | Run `npm install` |-| Out of memory | Increase Node memory: `NODE_OPTIONS=--max_old_space_size=4096 npm run build` |-| Path issues | Use absolute paths or verify relative paths are correct |--### Build Output Missing--- Check `powerpages.config.json` has the correct `compiledPath`-- Verify the build command completed successfully-- Check the build/dist folder exists and contains files-------## Reference Documentation--- [Create Code Sites in Power Pages](https://learn.microsoft.com/en-us/power-pages/configure/create-code-sites)-- [Reactivate a Website](https://learn.microsoft.com/en-us/power-pages/admin/reactivate-website)-- [PAC CLI Reference](https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/pages)-- [Playwright Documentation](https://playwright.dev/docs/intro)-- [Vitest Documentation](https://vitest.dev/guide/)diff --git a/plugins/power-pages/skills/create-site/references/upload-activation-reference.md b/plugins/power-pages/skills/create-site/references/upload-activation-reference.mddeleted file mode 100644index 275d512a3..000000000--- a/plugins/power-pages/skills/create-site/references/upload-activation-reference.md+++ /dev/null@@ -1,280 +0,0 @@-# Upload and Activation Reference--## Prerequisites--### Check PAC CLI--```powershell-pac help-```--**If not found**, install using .NET tool:--```powershell-dotnet tool install --global Microsoft.PowerApps.CLI.Tool-```--Verify after installation:--```powershell-pac help-```--### Check Azure CLI--```powershell-az --version-```--**If not found**, install using winget:--```powershell-winget install -e --id Microsoft.AzureCLI-```--Restart terminal after installation, then verify:--```powershell-az --version-```--### Verify Authentication--```powershell-# Check PAC CLI authentication-pac auth list--# If not authenticated-pac auth create--# Check Azure CLI authentication-az account show--# If not authenticated-az login-```--### Verify Environment Connection--```powershell-pac org who-```-------## Upload to Power Pages--### Create Authoring Tool Site Setting--**Before uploading**, create a site setting to track which Claude Code tool created the site.--**📖 See: [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md)**--Follow the instructions in the shared reference to create the `Site/AuthoringTool` setting with value `ClaudeCodeCLI` or `ClaudeCodeVSCode` based on the environment.--### Confirm Connected Account--**Before uploading**, confirm the connected account:--```powershell-pac auth list-```--Display the account information:-- Active profile (marked with `*`)-- Environment URL-- User email/account--Ask user to confirm before proceeding. If they need to switch accounts:--```powershell-pac auth create-```--### Upload Command--```powershell-pac pages upload-code-site --rootPath "<PROJECT_ROOT_PATH>"-```--**Example:**--```powershell-pac pages upload-code-site --rootPath "C:\repos\my-power-pages-site"-```--### Get Website Record ID--After upload, list sites to get the websiteRecordId:--```powershell-pac pages list --verbose-```--Note the **Website ID** (GUID) - this is needed for activation.-------## Preview Locally--Before activating, run the site locally to verify everything works:--```powershell-# React (Vite)-npm run dev--# React (Create React App)-npm start--# Angular-ng serve--# Vue-npm run dev--# Astro-npm run dev-```--Verify:-1. Open the local URL (usually `http://localhost:5173` or `http://localhost:3000`)-2. Test all pages and navigation-3. Verify forms and interactive elements work-4. Check responsive design on different screen sizes-------## Activate Website--After uploading, your site appears as **Inactive** in Power Pages. Activate it using the Power Platform API.--### Ask for Subdomain--Before activating, ask the user for their preferred subdomain:-- The URL prefix for their site (e.g., `my-site` → `my-site.powerappsportals.com`)-- Subdomain must be unique, lowercase, and contain only letters, numbers, and hyphens--### Get Required IDs--```powershell-pac org who-```--Note:-- **Environment ID** - The GUID of the environment-- **Organization ID** - The Dataverse organization ID--### Activate via API--```powershell-# Set variables (replace with actual values)-$environmentId = "<ENVIRONMENT_ID>"-$organizationId = "<ORGANIZATION_ID>"-$websiteRecordId = "<WEBSITE_RECORD_ID_FROM_UPLOAD>"-$siteName = "<SITE_NAME>"-$subdomain = "<USER_CHOSEN_SUBDOMAIN>"--# Create request body-$body = @{- dataverseOrganizationId = $organizationId- name = $siteName- selectedBaseLanguage = 1033- subdomain = $subdomain- templateName = "DefaultPortalTemplate"- websiteRecordId = $websiteRecordId-} | ConvertTo-Json -Compress--# Call CreateWebsite API-az rest `- --method POST `- --url "https://api.powerplatform.com/powerpages/environments/$environmentId/websites?api-version=2022-03-01-preview" `- --resource "https://api.powerplatform.com" `- --body $body `- --headers "Content-Type=application/json" `- --verbose-```--The `--resource` flag automatically handles authentication using your Azure CLI credentials.--### Monitor Activation Status--The API returns a `202 Accepted` response with an `Operation-Location` header. Poll this URL to check activation status:--```powershell-# Check operation status (URL from Operation-Location header)-$operationUrl = "<OPERATION_LOCATION_URL>"--az rest `- --method GET `- --url $operationUrl `- --resource "https://api.powerplatform.com"-```--Wait until the operation status shows as completed (typically 2-5 minutes).--### Verify Activation--```powershell-pac pages list --verbose-```--Your site should now show as **Active** with a URL.--**API Reference**: [CreateWebsite API - Microsoft Learn](https://learn.microsoft.com/en-us/rest/api/power-platform/powerpages/websites/create-website)-------## Fallback: Manual Activation--If the API activation fails (e.g., permissions issues, network errors), activate manually:--1. **Go to Power Pages home page**- - Navigate to [make.powerpages.microsoft.com](https://make.powerpages.microsoft.com)- - Select your environment--2. **Find your inactive site**- - Click on **Inactive sites** in the left navigation- - Your uploaded site will appear in the list--3. **Reactivate the site**- - Click the **Reactivate** button next to your site--4. **Configure site details**- - **Website name**: Enter or confirm the display name- - **Web address**: Enter the subdomain chosen earlier- - Click **Done**--5. **Wait for provisioning**- - The site will take a few minutes to provision- - Once complete, it will appear in **Active sites**--**Reference**: [Reactivate a website - Microsoft Learn](https://learn.microsoft.com/en-us/power-pages/admin/reactivate-website)-------## Update Memory Bank--After activation, update `memory-bank.md`:--```markdown-### /create-site-- [x] Requirements gathered-- [x] Framework selected: [FRAMEWORK]-- [x] Site created with features: [FEATURE_LIST]-- [x] powerpages.config.json created-- [x] SEO assets added (meta tags, favicon, robots.txt, sitemap.xml)-- [x] Unit tests written and passing-- [x] E2E tests written and passing (Playwright)-- [x] Project built successfully-- [x] Prerequisites verified (PAC CLI, Azure CLI)-- [x] Uploaded to Power Pages (Inactive)-- [x] Site activated-- Website ID: [GUID_FROM_PAC_PAGES_LIST]-- Site URL: [URL_FROM_ACTIVATION]--## Current Status--**Last Action**: Site activated successfully--**Next Step**: Run `/setup-dataverse` to create Dataverse tables for your site-```diff --git a/plugins/power-pages/skills/create-site/scripts/validate-site.js b/plugins/power-pages/skills/create-site/scripts/validate-site.jsnew file mode 100644index 000000000..12794d1ec--- /dev/null+++ b/plugins/power-pages/skills/create-site/scripts/validate-site.js@@ -0,0 +1,105 @@+#!/usr/bin/env node++// Validates Power Pages code site generation output.+// Runs as a Stop hook to verify the site was properly created.++const fs = require('fs');+const path = require('path');+const { approve, block, runValidation, findPath } = require('../../../scripts/lib/validation-helpers');++runValidation((cwd) => {+ const configPath = findPath(cwd, 'powerpages.config.json');+ if (!configPath) approve(); // Not a Power Pages project, skip++ const projectRoot = path.dirname(configPath);+ const errors = [];++ // 1. Required files+ for (const file of ['package.json', '.gitignore', 'powerpages.config.json']) {+ if (!fs.existsSync(path.join(projectRoot, file))) {+ errors.push(`Missing required file: ${file}`);+ }+ }++ // 2. powerpages.config.json fields+ try {+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));+ if (!config.$schema) errors.push('powerpages.config.json: missing $schema');+ if (!config.compiledPath) errors.push('powerpages.config.json: missing compiledPath');+ if (!config.siteName) errors.push('powerpages.config.json: missing siteName');+ if (!config.defaultLandingPage) errors.push('powerpages.config.json: missing defaultLandingPage');+ } catch {+ errors.push('powerpages.config.json: invalid JSON');+ }++ // 3. package.json has build script+ try {+ const pkg = JSON.parse(fs.readFileSync(path.join(projectRoot, 'package.json'), 'utf8'));+ if (!pkg.scripts || !pkg.scripts.build) errors.push('package.json: missing "build" script');+ if (!pkg.scripts || !pkg.scripts.dev) errors.push('package.json: missing "dev" script');+ } catch {}++ // 4. Unreplaced placeholders in source files+ const dirsToCheck = [path.join(projectRoot, 'src')];+ const rootFiles = ['index.html'].map(f => path.join(projectRoot, f));++ const placeholders = [];+ for (const dir of dirsToCheck) {+ if (fs.existsSync(dir)) placeholders.push(...findPlaceholders(dir));+ }+ for (const file of rootFiles) {+ if (fs.existsSync(file)) placeholders.push(...findPlaceholdersInFile(file));+ }+ if (placeholders.length > 0) {+ errors.push('Unreplaced placeholders found:\n ' + placeholders.slice(0, 5).join('\n '));+ if (placeholders.length > 5) {+ errors.push(` ...and ${placeholders.length - 5} more`);+ }+ }++ // 5. Git repository initialized+ if (!fs.existsSync(path.join(projectRoot, '.git'))) {+ errors.push('Git repository not initialized');+ }++ // 6. Source directory exists with content+ if (!fs.existsSync(path.join(projectRoot, 'src'))) {+ errors.push('Missing src/ directory');+ }++ if (errors.length > 0) {+ block('Power Pages site validation failed:\n- ' + errors.join('\n- '));+ }++ approve();+});++const PLACEHOLDER_RE = /__[A-Z][A-Z_]{2,}__/;++function findPlaceholdersInFile(filePath) {+ const results = [];+ try {+ const lines = fs.readFileSync(filePath, 'utf8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ if (PLACEHOLDER_RE.test(lines[i])) {+ results.push(`${path.basename(filePath)}:${i + 1}: ${lines[i].trim()}`);+ }+ }+ } catch {}+ return results;+}++function findPlaceholders(dir) {+ const results = [];+ try {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const fullPath = path.join(dir, entry.name);+ if (entry.isDirectory() && entry.name !== 'node_modules') {+ results.push(...findPlaceholders(fullPath));+ } else if (entry.isFile()) {+ results.push(...findPlaceholdersInFile(fullPath));+ }+ }+ } catch {}+ return results;+}diff --git a/plugins/power-pages/skills/create-webroles/SKILL.md b/plugins/power-pages/skills/create-webroles/SKILL.mdnew file mode 100644index 000000000..54ae7d385--- /dev/null+++ b/plugins/power-pages/skills/create-webroles/SKILL.md@@ -0,0 +1,296 @@+---+name: create-webroles+description: >+ This skill should be used when the user asks to "create web roles", "add web roles",+ "set up web roles", "add roles", "create roles for my site", "manage web roles",+ "add authenticated role", "add anonymous role", or wants to create web roles for+ their Power Pages code site. Web roles control access and permissions for site users.+user-invocable: true+allowed-tools: ["Read", "Write", "Bash", "Grep", "Glob", "AskUserQuestion", "Task", "TaskCreate", "TaskUpdate", "TaskList"]+model: opus+hooks:+ Stop:+ - hooks:+ - type: command+ command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/create-webroles/scripts/validate-webroles.js"'+ timeout: 15+ - type: prompt+ prompt: >+ If web roles were being created in this session (via /power-pages:create-webroles),+ verify before allowing stop: 1) The .powerpages-site/web-roles/ directory was checked+ for existing roles, 2) New web role YAML files were created with valid UUIDs generated+ by the generate-uuid.js script, 3) All web role files were verified (valid UUIDs, correct+ format, no duplicate flags), 4) The user was asked to deploy the site to apply the+ new roles. If any of these are incomplete, return { "ok": false, "reason": "<specific issues>" }.+ If no web role work happened or everything is complete, return { "ok": true }.+ timeout: 30+---++# Create Web Roles++Create web roles for a Power Pages code site. Web roles define the permissions and access levels for different types of site users.++## Core Principles++- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases — create the todo list upfront with all phases before starting any work.+- **Always use the UUID script**: Never generate UUIDs manually — always use `${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js` to produce valid UUID v4 values for each web role.+- **Preserve uniqueness constraints**: Only one role can have `anonymoususersrole: true` and only one can have `authenticatedusersrole: true`. Always check existing roles before setting these flags.++> **Prerequisite:** The site must be deployed at least once before web roles can be created, since deployment creates the `.powerpages-site` folder structure that stores web role definitions.++**Initial request:** $ARGUMENTS++---++## Workflow++1. **Phase 1: Verify Site Structure** → Check for `.powerpages-site/web-roles/` directory+2. **Phase 2: Discover Existing Roles** → Read current web role YAML files+3. **Phase 3: Determine New Roles** → Analyze the site and ask the user what roles are needed+4. **Phase 4: Create Web Role Files** → Generate YAML files with UUIDs from the Node script+5. **Phase 5: Verify Web Roles** → Validate all created files exist, have valid UUIDs, and flags are correct+6. **Phase 6: Review & Deploy** → Present summary and proceed to deployment++---++## Phase 1: Verify Site Structure++**Goal**: Confirm the `.powerpages-site/web-roles/` directory exists and is ready for web role files++**Actions**:++1. Look for the `.powerpages-site/web-roles/` directory in the project root. Use `Glob` to search:++ ```text+ **/.powerpages-site/web-roles+ ```++2. Also locate the project root by finding `powerpages.config.json`:++ ```text+ **/powerpages.config.json+ ```++3. **If `.powerpages-site` folder does NOT exist:**++ The site has not been deployed yet. The `.powerpages-site` folder is created automatically when the site is deployed for the first time using `pac pages upload-code-site`.++ Tell the user:++ > "The `.powerpages-site` folder was not found. This folder is created when the site is first deployed to Power Pages. I'll deploy your site first, and then we can create web roles."++ Use `AskUserQuestion` to confirm:++ | Question | Options |+ |----------|---------|+ | Your site needs to be deployed first so the `.powerpages-site` folder is created. Shall I deploy it now? | Yes, deploy now (Recommended), No, I'll do it later |++ **If "Yes, deploy now"**: Invoke the `/power-pages:deploy-site` skill to deploy the site. Once deployment completes and `.powerpages-site` is created, resume this workflow from Phase 2.++ **If "No, I'll do it later"**: Stop here — the user must deploy first before web roles can be created.++4. **If `.powerpages-site` exists but `web-roles/` subdirectory does NOT exist:**++ Create the `web-roles` directory:++ ```powershell+ New-Item -ItemType Directory -Path "<PROJECT_ROOT>/.powerpages-site/web-roles" -Force+ ```++ Proceed to Phase 2.++5. **If both exist:** Proceed to Phase 2.++**Output**: Confirmed `.powerpages-site/web-roles/` directory exists and is ready++---++## Phase 2: Discover Existing Roles++**Goal**: Identify all web roles already defined for the site++**Actions**:++1. Read all YAML files in the `.powerpages-site/web-roles/` directory. Each file represents one web role with this format:++ ```yaml+ anonymoususersrole: false+ authenticatedusersrole: false+ id: 778fa3d0-a2ef-4d2b-98b8-e6c7d8ce1444+ name: Administrators+ ```++2. Parse each file and compile a list of existing web roles (name, id, and flags).++3. Present the existing roles to the user:++ > "I found the following existing web roles in your site:"+ > - **Administrators** (id: `778fa3d0-...`, authenticated: false, anonymous: false)+ > - *(etc.)*++4. If no roles exist yet, inform the user:++ > "No web roles are currently defined for your site."++**Output**: Complete list of existing web roles with their names, IDs, and flags++---++## Phase 3: Determine New Roles++**Goal**: Decide which new web roles to create based on site needs and user input++**Actions**:++1. Based on the site's purpose and the existing roles, suggest appropriate web roles. Use `AskUserQuestion` to confirm with the user.++ Common web roles for Power Pages sites include:+ - **Administrators** — Full access to site management+ - **Authenticated Users** — Default role for logged-in users (set `authenticatedusersrole: true`)+ - **Anonymous Users** — Default role for non-logged-in visitors (set `anonymoususersrole: true`)+ - **Content Editors** — Users who can edit site content+ - **Moderators** — Users who can moderate community content+ - Custom roles based on business needs++2. Ask the user which roles they want to create:++ | Question | Options |+ |----------|---------|+ | Which web roles would you like to create for your site? You can select from suggestions or describe custom roles. | *(Provide relevant suggestions based on site context, existing roles, and business domain)* |++ CRITICAL: Do NOT suggest roles that already exist. Filter out any existing role names before presenting options.++3. Allow the user to specify custom role names as well.++**Output**: Confirmed list of new web roles to create++---++## Phase 4: Create Web Role Files++**Goal**: Generate properly formatted YAML files with valid UUIDs for each new web role++**Actions**:++For each new web role the user approved, create a YAML file in `.powerpages-site/web-roles/`.++### 4.1 Generate UUID++For each role, generate a UUID using the Node script. **NEVER generate UUIDs yourself — always use the script.**++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js"+```++### 4.2 Create the YAML File++The filename should be the role name in kebab-case with a `.yml` extension (e.g., `Administrators` → `administrators.yml`, `Content Editors` → `content-editors.yml`).++Write the file with this exact format (4 fields, no extra whitespace or comments):++```yaml+anonymoususersrole: <true if this is the anonymous users role, false otherwise>+authenticatedusersrole: <true if this is the authenticated users role, false otherwise>+id: <UUID from generate-uuid.js>+name: <Role Name>+```++**Rules:**+- Only ONE role can have `anonymoususersrole: true`+- Only ONE role can have `authenticatedusersrole: true`+- If an existing role already has one of these flags set to `true`, do not set it again on a new role+- Each role MUST have a unique UUID generated by the script — run the script once per role++**Output**: All new web role YAML files created++---++## Phase 5: Verify Web Roles++**Goal**: Validate that all created web role files exist, have valid format, and constraints are satisfied++**Actions**:++1. List all files in `.powerpages-site/web-roles/` and read each new file to confirm they were written correctly.++2. For each new web role file, verify:+ - The file exists at the expected path+ - The `id` field contains a valid UUID v4 format+ - The `name` field matches the expected role name+ - `anonymoususersrole` and `authenticatedusersrole` are valid booleans++3. Verify uniqueness constraints across ALL role files (existing + new):+ - At most one role has `anonymoususersrole: true`+ - At most one role has `authenticatedusersrole: true`+ - No duplicate `id` values exist across roles++4. If any file fails validation, fix the issue before proceeding.++**Output**: All web role files validated — correct format, valid UUIDs, no constraint violations++---++## Phase 6: Review & Deploy++**Goal**: Present a summary of created roles and offer deployment++**Actions**:++1. 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 "CreateWebroles"`.++2. Present a summary of what was created:++ > "I've created the following new web roles:"+ > | Role Name | ID | Anonymous | Authenticated |+ > |-----------|-----|-----------|---------------|+ > | Content Editors | `a1b2c3d4-...` | false | false |+ > | *(etc.)* |++3. Then ask the user if they want to deploy the site to apply the new roles:++ | Question | Options |+ |----------|---------|+ | The new web roles have been created locally. To apply them in Power Pages, the site needs to be deployed. Would you like to deploy now? | Yes, deploy now (Recommended), No, I'll deploy later |++4. **If "Yes, deploy now"**: Tell the user to invoke the deploy skill:++ > "Please run `/power-pages:deploy-site` to deploy your site and apply the new web roles."++5. **If "No, I'll deploy later"**: Acknowledge and remind them:++ > "No problem! Remember to deploy your site using `/power-pages:deploy-site` when you're ready to apply the new web roles to your Power Pages environment."++**Output**: Summary presented and deployment offered++---++## Important Notes++### Key Decision Points (Wait for User)++1. After Phase 1: Confirm deployment if `.powerpages-site` is missing+2. After Phase 3: Confirm which roles to create+3. After Phase 6: Deploy or skip++### Progress Tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Verify site structure | Verifying site structure | Check for `.powerpages-site/web-roles/` directory, create if needed |+| Discover existing roles | Discovering existing roles | Read current web role YAML files and compile list of existing roles |+| Determine new roles | Determining new roles | Analyze site needs and ask user which roles to create |+| Create web role files | Creating web role files | Generate YAML files with UUIDs from the Node script for each new role |+| Verify web roles | Verifying web roles | Validate all files exist, have valid UUIDs, and uniqueness constraints are satisfied |+| Review and deploy | Reviewing and deploying | Present summary of created roles and offer deployment |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`. This gives the user visibility into progress and keeps the workflow deterministic.++---++**Begin with Phase 1: Verify Site Structure**diff --git a/plugins/power-pages/skills/create-webroles/scripts/validate-webroles.js b/plugins/power-pages/skills/create-webroles/scripts/validate-webroles.jsnew file mode 100644index 000000000..b45fbe507--- /dev/null+++ b/plugins/power-pages/skills/create-webroles/scripts/validate-webroles.js@@ -0,0 +1,41 @@+#!/usr/bin/env node++// Validates that new web role YAML files were created in .powerpages-site/web-roles/.+// Runs as a Stop hook to verify the skill produced output.++const fs = require('fs');+const path = require('path');+const { approve, block, runValidation, findPowerPagesSiteDir, UUID_REGEX } = require('../../../scripts/lib/validation-helpers');++runValidation((cwd) => {+ const webRolesDir = findPowerPagesSiteDir(cwd, 'web-roles');+ if (!webRolesDir) approve(); // No .powerpages-site found — not a web roles session++ const files = fs.readdirSync(webRolesDir).filter(f => f.endsWith('.yml') || f.endsWith('.yaml'));+ if (files.length === 0) {+ block('Web roles validation failed:\n- No web role YAML files found in .powerpages-site/web-roles/');+ }++ const errors = [];++ for (const file of files) {+ const content = fs.readFileSync(path.join(webRolesDir, file), 'utf8');++ if (!content.includes('id:')) errors.push(`${file}: missing "id" field`);+ if (!content.includes('name:')) errors.push(`${file}: missing "name" field`);++ const idMatch = content.match(/^id:\s*(.+)$/m);+ if (idMatch) {+ const id = idMatch[1].trim();+ if (!UUID_REGEX.test(id)) {+ errors.push(`${file}: invalid UUID format in "id" field: ${id}`);+ }+ }+ }++ if (errors.length > 0) {+ block('Web roles validation failed:\n- ' + errors.join('\n- '));+ }++ approve();+});diff --git a/plugins/power-pages/skills/deploy-site/SKILL.md b/plugins/power-pages/skills/deploy-site/SKILL.mdnew file mode 100644index 000000000..e2f2f1d27--- /dev/null+++ b/plugins/power-pages/skills/deploy-site/SKILL.md@@ -0,0 +1,405 @@+---+name: deploy-power-pages-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"]+model: opus+---++# Deploy Power Pages Code Site++Guide the user through deploying an existing Power Pages code site to a Power Pages environment using PAC CLI. Follow a systematic approach: verify tooling, authenticate, confirm the target environment, build and upload the site, and handle any blockers.++## Core Principles++- **Verify before acting**: Always confirm PAC CLI availability, authentication status, and the target environment before attempting any deployment.+- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases — create the todo list upfront with all phases before starting any work.+- **Never change environment settings without consent**: If deployment requires modifying environment configuration (e.g., unblocking JavaScript attachments), always explain the change and get explicit user permission first.++**Initial request:** $ARGUMENTS++---++## Phase 1: Verify PAC CLI++**Goal**: Ensure PAC CLI is installed and available on the system PATH++**Actions**:+1. Create todo list with all 6 phases (see [Progress Tracking](#progress-tracking) table)+2. Run `pac help` to check if the PAC CLI is installed and available on the system PATH.++ ```powershell+ pac help+ ```++3. **If the command succeeds**: PAC CLI is installed. Proceed to Phase 2.++4. **If the command fails** (command not found / not recognized):++ 1. Inform the user that PAC CLI is required but not installed.+ 2. Fetch installation instructions from `https://aka.ms/PowerPlatformCLI` using the following approach:+ - Tell the user: "PAC CLI is not installed. You can install it by running:"++ ```powershell+ dotnet tool install --global Microsoft.PowerApps.CLI.Tool+ ```++ - If `dotnet` is also not available, direct the user to https://aka.ms/PowerPlatformCLI for full installation instructions including .NET SDK setup.++ 3. After installation, verify by running `pac help` again.+ 4. If it still fails, stop and ask the user to resolve the installation manually.++**Output**: PAC CLI installed and verified++---++## Phase 2: Verify Authentication++**Goal**: Ensure the user is authenticated with PAC CLI and has a valid session++**Actions**:+1. Run `pac auth who` to check the current authentication status.++ ```powershell+ pac auth who+ ```++2. **If authenticated**: Extract the following values from the output:+ - **Environment name** and **URL**+ - **Environment ID** — the GUID after `Environment ID:`+ - **Cloud** — the value after `Cloud:` (e.g., `Public`, `UsGov`, `UsGovHigh`, `UsGovDod`, `China`)++ Proceed to Phase 3.++3. **If not authenticated**:++ 1. Inform the user they are not authenticated with PAC CLI.+ 2. Use `AskUserQuestion` to ask for the environment URL:++ | Question | Header | Options |+ |----------|--------|---------|+ | You are not authenticated with PAC CLI. Please provide your Power Pages environment URL (e.g., `https://org12345.crm.dynamics.com`) so I can authenticate you. | Auth | *(free text input via "Other")* |++ Provide two placeholder options to guide the user:+ - "I'll paste the URL" (description: "Select 'Other' below and paste your environment URL")+ - "I don't know my URL" (description: "You can find it in the Power Platform admin center under Environments > your environment > Environment URL")++ 3. Once the user provides the URL, run the authentication command:++ ```powershell+ pac auth create --environment "<USER_PROVIDED_URL>"+ ```++ This will open a browser window for the user to sign in.++ 4. After the command completes, verify by running `pac auth who` again.+ 5. If authentication succeeds, proceed to Phase 3.+ 6. If authentication fails, present the error to the user and help them troubleshoot.++**Output**: Authenticated PAC CLI session with environment name and URL extracted++---++## Phase 3: Confirm Environment++**Goal**: Ensure the user is deploying to the correct target environment++**Actions**:+1. Present the current environment information to the user and ask them to confirm.++ Use `AskUserQuestion` with the following structure:++ | Question | Header | Options |+ |----------|--------|---------|+ | You are currently connected to environment: **<ENV_NAME>** (<ENV_URL>). Do you want to deploy to this environment? | Environment | Yes, use this environment, No, let me choose a different one |++2. **If "Yes, use this environment"**: Proceed to Phase 4.++3. **If "No, let me choose a different one"**:++ 1. Run `pac org list` to retrieve all available environments:++ ```powershell+ pac org list+ ```++ 2. Parse the output to extract environment names and URLs.+ 3. Use `AskUserQuestion` to present the available environments as options (pick up to 4 most relevant, or let user specify).+ 4. Once the user selects an environment, switch to it:++ ```powershell+ pac org select --environment "<SELECTED_ENV_ID_OR_URL>"+ ```++ 5. Verify the switch by running `pac auth who` again.++**Output**: Confirmed target environment for deployment++---++## Phase 4: Deploy the Code Site++**Goal**: Locate the project, build it, and upload to Power Pages++**Actions**:++### 4.1 Locate the Project Root++Determine the project root directory. The project root is the directory containing `powerpages.config.json`. Use `Glob` to search for it:++```text+**/powerpages.config.json+```++If found in the current working directory or a subdirectory, use that directory as `PROJECT_ROOT`. If multiple are found, ask the user which one to deploy using `AskUserQuestion`.++If not found, ask the user to provide the path to the project root.++### 4.2 Build the Site++Before uploading, ensure the site is built:++```powershell+cd "<PROJECT_ROOT>"+npm run build+```++If the build fails, stop and help the user fix the build errors before retrying.++### 4.3 Upload to Power Pages++Run the upload command:++```powershell+pac pages upload-code-site --rootPath "<PROJECT_ROOT>"+```++**If the upload succeeds**: Proceed to Phase 5 to verify the deployment.++**If the upload fails**: Check the error message:+- If the failure is related to **blocked JavaScript** (`.js`) attachments → proceed to **Phase 6**+- If the failure mentions **`.html` type attachments are currently blocked** → this is a **misleading error**. See [Troubleshooting: HTML Blocked Attachment Error](#troubleshooting-html-blocked-attachment-error) below+- For other errors → present the error to the user and help them troubleshoot++**Output**: Site built and uploaded to Power Pages++---++## Phase 5: Verify Deployment++**Goal**: Confirm the deployment was successful and handle post-deployment steps++**Actions**:++### 5.1 Verify `.powerpages-site` Folder++Confirm the `.powerpages-site` folder was created (first deploy) or still exists:++```powershell+Get-ChildItem -Path "<PROJECT_ROOT>/.powerpages-site" -ErrorAction SilentlyContinue+```++List its contents to confirm site configuration files are present (e.g., `web-roles/`, `site-settings/`, `table-permissions/`).++### 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 "DeploySite"`.++### 5.3 Confirm Upload Output++Review the output from the `pac pages upload-code-site` command in Phase 4 (or Phase 6 retry). Verify it reported a successful upload with no errors.++### 5.4 Commit Changes++Stage and commit deployment artifacts:++```powershell+git add -A+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.++#### 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:++```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+```++- **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.++#### 5.5.3 Ask About Activation (only if site is NOT already activated)++Ask the user if they want to activate the site using `AskUserQuestion`:++| Question | Header | Options |+|----------|--------|---------|+| Site deployed successfully! Would you like to activate (provision) the site now so it gets a live URL? | Activate | Activate now (Recommended) — Provision the site with a subdomain and make it live, Skip for now — I'll activate later |++**If "Activate now"**: Invoke the `/power-pages:activate-site` skill.+**If "Skip for now"**: Suggest next steps (see [Suggest Next Steps](#suggest-next-steps)).++**Output**: Deployment verified, changes committed, activation offered++---++## Phase 6: Handle Blocked JavaScript++**Goal**: Resolve blocked JavaScript attachment errors and retry deployment++**Actions**:++### 6.1 Explain the Issue++Tell the user:+> "The upload failed because JavaScript (.js) file attachments are blocked in your Power Pages environment. This is a security setting that prevents uploading .js files. To deploy a code site, this restriction needs to be relaxed for .js files."++### 6.2 Ask for Permission++Use `AskUserQuestion`:++| Question | Header | Options |+|----------|--------|---------|+| Would you like to remove the JavaScript (.js) block from the environment's blocked attachments list? This is required to deploy code sites. | Unblock JS | Yes, remove the .js block (Recommended), No, do not change environment settings |++**If "No"**: Stop and inform the user that the deployment cannot proceed without unblocking `.js` attachments.++**If "Yes"**: Proceed to 6.3.++### 6.3 Update Blocked Attachments++1. Run `pac env list-settings` to retrieve the current environment settings:++ ```powershell+ pac env list-settings+ ```++2. Find the `blockedattachments` property in the output. It will contain a semicolon-separated list of file extensions (e.g., `ade;adp;app;asa;ashx;asmx;asp;bas;bat;cdx;cer;chm;class;cmd;com;config;cnt;cpl;crt;csh;der;dll;exe;fxp;hlp;hta;htr;htw;ida;idc;idq;inf;ins;isp;its;js;jse;ksh;lnk;mad;maf;mag;mam;maq;mar;mas;mat;mau;mav;maw;mda;mdb;mde;mdt;mdw;mdz;msc;msh;msh1;msh1xml;msh2;msh2xml;mshxml;msi;msp;mst;ops;pcd;pif;prf;prg;printer;pst;reg;rem;scf;scr;sct;shb;shs;shtm;shtml;soap;stm;tmp;url;vb;vbe;vbs;vsmacros;vss;vst;vsw;ws;wsc;wsf;wsh`).++3. Remove `js` from the list. Parse the semicolon-separated values, filter out `js`, and rejoin with semicolons.++4. Update the setting:++ ```powershell+ pac env update-settings --name blockedattachments --value "<UPDATED_LIST_WITHOUT_JS>"+ ```++5. Confirm the update was successful.++### 6.4 Retry Upload++Run the upload command again:++```powershell+pac pages upload-code-site --rootPath "<PROJECT_ROOT>"+```++If it succeeds: Proceed to Phase 5 to verify the deployment.++If it fails again with a different error, present the error to the user and help troubleshoot.++**Output**: JavaScript unblocked and site deployed successfully++---++## Troubleshooting: HTML Blocked Attachment Error++If the upload fails with an error like:++```+Error: Unable to upload webfile name 'index.html' with record Id <GUID> as '.html' type attachments are currently blocked on this environment.+```++**This error is misleading.** The `.html` extension is not actually blocked — the real cause is a stale environment manifest file in the `.powerpages-site` folder. This manifest maps local files to Dataverse record IDs from a previous upload. When the mapping becomes outdated (e.g., after environment changes or record deletions), the upload fails with this confusing error.++### Fix++1. Locate the environment-specific manifest file in the `.powerpages-site` folder. It follows the naming pattern `<environment-host>-manifest.yml` (e.g., `demo1.crm.dynamics.com-manifest.yml`). List the folder contents to find it:++ ```powershell+ Get-ChildItem -Path "<PROJECT_ROOT>/.powerpages-site" -Filter "*-manifest.yml"+ ```++2. Delete the manifest file:++ ```powershell+ Remove-Item -Path "<PROJECT_ROOT>/.powerpages-site/<environment-host>-manifest.yml"+ ```++3. Retry the upload:++ ```powershell+ pac pages upload-code-site --rootPath "<PROJECT_ROOT>"+ ```++If the retry succeeds, proceed to Phase 5. If it fails with a different error, present the error to the user and help them troubleshoot.++> **Important**: Do NOT attempt to unblock `.html` in the environment's blocked attachments list — the error is not caused by the attachment block setting.++---++## Suggest Next Steps++If the user skips activation (or after activation completes), suggest:+- `/power-pages:activate-site` — Provision the site with a subdomain and make it live (if not already activated)+- `/power-pages:setup-datamodel` — Create Dataverse tables for dynamic content+- `/power-pages:add-seo` — Add meta tags, robots.txt, sitemap.xml, favicon++---++## Important Notes++### Throughout All Phases++- **Use TaskCreate/TaskUpdate** to track progress at every phase+- **Ask for user confirmation** at key decision points (see list below)+- **Present errors clearly** — when a command fails, show the user the relevant error output and explain what went wrong before suggesting fixes++### Key Decision Points (Wait for User)++1. After Phase 2: If not authenticated, get environment URL from user+2. At Phase 3: Confirm or switch the target environment+3. At Phase 4: If multiple `powerpages.config.json` found, ask which project to deploy+4. At Phase 5: Activate site now or later+5. At Phase 6: Get permission before modifying blocked attachments setting++### Progress Tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Verify PAC CLI installation | Verifying PAC CLI | Check if PAC CLI is installed, install if missing |+| Verify authentication | Verifying authentication | Check current auth status, authenticate if needed |+| Confirm target environment | Confirming environment | Show current environment, let user confirm or switch |+| Deploy the code site | Deploying site | Locate project root, build, and upload via pac pages upload-code-site |+| Verify deployment | Verifying deployment | Confirm .powerpages-site folder exists, review upload output, commit changes, offer activation |+| Handle blocked JavaScript | Resolving JS block | If upload fails due to blocked JS, offer to unblock and retry |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`. Phase 6 may be marked `completed` immediately if no JavaScript blocking issue is encountered. This gives the user visibility into progress and keeps the workflow deterministic.++---++**Begin with Phase 1: Verify PAC CLI**diff --git a/plugins/power-pages/skills/integrate-webapi/SKILL.md b/plugins/power-pages/skills/integrate-webapi/SKILL.mdindex 926bea8e1..5e7782840 100644--- a/plugins/power-pages/skills/integrate-webapi/SKILL.md+++ b/plugins/power-pages/skills/integrate-webapi/SKILL.md@@ -1,143 +1,485 @@----name: integrating-webapi-description: Integrates Web API into frontend code, replacing mock data with Dataverse API calls. Use when connecting frontend to Web API, replacing static data, or creating API services.+name: integrate-webapi+description: >+ This skill should be used when the user asks to "integrate web api", "add web api",+ "connect to dataverse", "add api integration", "set up web api calls",+ "integrate api for my tables", "add crud operations", "hook up web api",+ "add data fetching", "connect frontend to dataverse", or wants to integrate+ Power Pages Web API into their site's frontend code with proper permissions+ and deployment. This skill orchestrates the full integration lifecycle:+ code integration, permissions setup, and deployment.user-invocable: true-allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "AskUserQuestion"]+allowed-tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob", "AskUserQuestion", "Task", "TaskCreate", "TaskUpdate", "TaskList"]model: opus+hooks:+ Stop:+ - hooks:+ - type: command+ command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/integrate-webapi/scripts/validate-webapi-integration.js"'+ timeout: 15+ - type: prompt+ prompt: >+ If Web API integration was being performed in this session (via /power-pages:integrate-webapi),+ verify before allowing stop: 1) The site was analyzed and tables requiring Web API integration+ were identified, 2) The webapi-integration agent was invoked to create API client, types, and+ service files for each table, 3) All integration files were verified (types, services, hooks exist)+ and the project builds successfully, 4) Table permissions and site settings were configured+ (either via the webapi-permissions agent or by parsing a user-provided permissions diagram),+ 5) The user was asked whether to deploy the site.+ If any of these are incomplete, return { "ok": false, "reason": "<specific issues>" }.+ If no Web API integration work happened or everything is complete, return { "ok": true }.+ timeout: 30----**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.-# Integrate Web API-**References:** [frontend-integration](./references/frontend-integration-reference.md)+Integrate Power Pages Web API into a code site's frontend. This skill orchestrates the full lifecycle: analyzing where integrations are needed, implementing API client code for each table, configuring permissions and site settings, and deploying the site.++## Core Principles-Connects frontend code to Power Pages Web API, replacing all mock/static data.+- **One table at a time**: Process tables sequentially because the first table creates the shared `powerPagesApi.ts` client that subsequent tables reuse, and each agent invocation may modify shared files.+- **Permissions require deployment**: The `.powerpages-site` folder must exist before table permissions and site settings can be configured. Integration code can be written without it, but permissions cannot.+- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases — create the todo list upfront with all phases before starting any work.-## Prerequisites+> **Prerequisites:**+> - An existing Power Pages code site created via `/power-pages:create-site`+> - A Dataverse data model (tables/columns) already set up via `/power-pages:setup-datamodel` or created manually+> - The site must be deployed at least once (`.powerpages-site` folder must exist) for permissions setup-- Web API permissions configured with `/setup-webapi`-- Site settings created for tables-- Table permissions and web roles configured+**Initial request:** $ARGUMENTS++---## Workflow-1. **Check Context** → Read memory bank, get table mapping and publisher prefix-2. **Create Web API Service** → `src/services/webApi.ts` with CSRF handling-3. **Create Type Definitions** → TypeScript interfaces for entities-4. **Create Entity Services** → Typed wrappers per table-5. **Find Mock Data** → Search for all static/mock data-6. **Replace Mock Data** → Update components to use API-7. **Delete Mock Files** → Remove unused data files-8. **Build and Upload** → Deploy and verify+1. **Verify Site Exists** — Locate the Power Pages project and verify prerequisites+2. **Explore Integration Points** — Analyze site code and data model to identify tables needing Web API integration+3. **Review Integration Plan** — Present findings to the user and confirm which tables to integrate+4. **Implement Integrations** — Use the `webapi-integration` agent for each table+5. **Verify Integrations** — Validate all expected files exist and the project builds successfully+6. **Setup Permissions** — Choose permissions source (upload diagram or let the Web API Permissions Architect analyze), then configure table permissions and site settings+7. **Review & Deploy** — Ask the user to deploy the site and invoke `/power-pages:deploy-site` if confirmed----## Step 1: Check Context+## Phase 1: Verify Site Exists++**Goal**: Locate the Power Pages project root and confirm that prerequisites are met++**Actions**:++### 1.1 Locate Project++Look for `powerpages.config.json` in the current directory or immediate subdirectories to find the project root.++```powershell+Get-ChildItem -Path . -Filter "powerpages.config.json" -Recurse -Depth 1+```++**If not found**: Tell the user to create a site first with `/power-pages:create-site`.++### 1.2 Read Existing Config++Read `powerpages.config.json` to get the site name:++```powershell+Get-Content "<PROJECT_ROOT>/powerpages.config.json" | ConvertFrom-Json+```++### 1.3 Detect Framework-Read `memory-bank.md` for:-- Table name mapping (actual logical names and entity sets)-- Publisher prefix (for column names)-- Fields configured in site settings+Read `package.json` to determine the framework (React, Vue, Angular, or Astro). See `${CLAUDE_PLUGIN_ROOT}/references/framework-conventions.md` for the full framework detection mapping.++### 1.4 Check for Data Model++Look for `.datamodel-manifest.json` to discover available tables:++```text+**/.datamodel-manifest.json+```++If found, read it — this is the primary source for table discovery.++### 1.5 Check Deployment Status++Look for the `.powerpages-site` folder:++```text+**/.powerpages-site+```++**If not found**: Warn the user that the permissions phase (Phase 5) will require deployment first. The integration code (Phases 2–4) can still proceed.++**Output**: Confirmed project root, framework, data model availability, and deployment status----## Step 2: Create Web API Service+## Phase 2: Explore Integration Points++**Goal**: Analyze the site code and data model to identify all tables needing Web API integration++**Actions**:++Use the **Explore agent** (via `Task` tool with `agent_type: "explore"`) to analyze the site code and data model. The Explore agent should answer these questions:++### 2.1 Discover Tables++Ask the Explore agent to identify all Dataverse tables that need Web API integration by examining:++- `.datamodel-manifest.json` — List of tables and their columns+- `src/**/*.{ts,tsx,js,jsx,vue,astro}` — Source code files that reference table data, mock data, or placeholder API calls+- Existing `/_api/` fetch patterns in the code+- TypeScript interfaces or types that map to Dataverse table schemas+- Component files that display or manipulate data from Dataverse tables+- Mock data files or hardcoded arrays that should be replaced with API calls+- `TODO` or `FIXME` comments mentioning API integration++**Prompt for the Explore agent:**-Create `src/services/webApi.ts` with:-- CSRF token fetching from `/_layout/tokenhtml`-- Token caching and refresh on 403-- Generic CRUD operations (getAll, getById, create, update, delete)+> "Analyze this Power Pages code site and identify all Dataverse tables that need Web API integration. Check `.datamodel-manifest.json` for the data model, then search the source code for: mock data arrays, hardcoded data, placeholder fetch calls to `/_api/`, TypeScript interfaces matching Dataverse column patterns (publisher prefix like `cr*_`), TODO/FIXME comments about API integration, and components that display table data. For each table found, report: the table logical name, the entity set name (plural), which source files reference it, what operations are needed (read/create/update/delete), and whether an existing API client or service already exists in `src/shared/` or `src/services/`. Also check if `src/shared/powerPagesApi.ts` already exists."-See [frontend-integration-reference.md](./references/frontend-integration-reference.md#power-pages-web-api-service-typescript).+### 2.2 Identify Existing Integration Code++The Explore agent should also report:++- Whether `src/shared/powerPagesApi.ts` (or equivalent API client) already exists+- Which tables already have service files in `src/shared/services/` or `src/services/`+- Which tables already have type definitions in `src/types/`+- Any framework-specific hooks/composables already created++This avoids duplicating work that was already done.++### 2.3 Compile Integration Manifest++From the Explore agent's findings, compile a list of tables needing integration:++| Table | Logical Name | Entity Set | Operations | Files Referencing | Existing Service |+|-------|-------------|-----------|------------|-------------------|-----------------|+| Products | `cr4fc_product` | `cr4fc_products` | CRUD | `ProductList.tsx`, `ProductCard.tsx` | None |+| Categories | `cr4fc_category` | `cr4fc_categories` | Read | `CategoryFilter.tsx` | None |++**Output**: Complete integration manifest listing all tables, their operations, referencing files, and existing service status----## Step 3: Create Type Definitions+## Phase 3: Review Integration Plan-Create `src/types/entities.ts` with interfaces for each table:+**Goal**: Present the integration manifest to the user and confirm which tables to integrate-```typescript-export interface Product {- ${prefix}_productid: string;- ${prefix}_name: string;- // ... fields from site settings-}-```+**Actions**:++### 3.1 Present Findings++Show the user:+1. The tables that were identified for Web API integration+2. For each table: which files reference it, what operations are needed+3. Whether a shared API client already exists or needs to be created+4. Any tables that were skipped (already have services)++### 3.2 Confirm Tables++Use `AskUserQuestion` to confirm:++| Question | Options |+|----------|---------|+| I found the following tables that need Web API integration: **[list tables]**. Which tables should I integrate? | All of them (Recommended), Let me select specific tables, I need to add more tables |++If the user selects specific tables or adds more, update the integration manifest accordingly.++**Output**: User-confirmed list of tables to integrate----## Step 4: Create Entity Services+## Phase 4: Implement Integrations++**Goal**: Create Web API integration code for each confirmed table using the `webapi-integration` agent++**Actions**:++### 4.1 Invoke Agent Per Table-Create typed wrappers that include `$select` with allowed fields:+For each table, use the `Task` tool to invoke the `webapi-integration` agent at `${CLAUDE_PLUGIN_ROOT}/agents/webapi-integration.md`:-```typescript-export const productsApi = {- getAll: () => webApi.getAll<Product>('${prefix}_products', {- select: ['${prefix}_productid', '${prefix}_name', ...],- }),-};+**Prompt template for the agent:**++> "Integrate Power Pages Web API for the **[Table Display Name]** table.+> - Table logical name: `[logical_name]`+> - Entity set name: `[entity_set_name]`+> - Operations needed: [read/create/update/delete]+> - Framework: [React/Vue/Angular/Astro]+> - Project root: [path]+> - Source files referencing this table: [list of files]+> - Data model manifest path: [path to .datamodel-manifest.json if available]+>+> Create the TypeScript types, CRUD service layer, and framework-specific hooks/composables. Replace any mock data or placeholder API calls in the referencing source files with the new service."++### 4.2 Process Tables Sequentially++Process tables **one at a time** (not in parallel), because:+- The first table creates the shared `powerPagesApi.ts` client — subsequent tables reuse it+- Each agent invocation may modify shared files++### 4.3 Verify Each Integration++After each agent completes, verify the output:+- Check that the expected files were created (types, service, hook/composable)+- Confirm the shared API client exists after the first table is processed+- Note any issues reported by the agent++### 4.4 Git Commit++After all integrations are complete, stage and commit:++```powershell+git add -A+git commit -m "Add Web API integration for [table names]"```+**Output**: Integration code created for all confirmed tables, verified and committed+----## Step 5: Find Mock Data+## Phase 5: Verify Integrations-**CRITICAL**: Find ALL mock data before replacing.+**Goal**: Validate that all expected integration files exist, imports are correct, and the project builds successfully-```powershell-# Mock folders-Get-ChildItem -Path ./src -Directory -Recurse | Where-Object { $_.Name -match "^(mock|data|fixtures)$" }+**Actions**:++### 5.1 Verify File Inventory++For each integrated table, confirm the following files exist:+- **Type definition** in `src/types/` (e.g., `src/types/product.ts`)+- **Service file** in `src/shared/services/` or `src/services/` (e.g., `productService.ts`)+- **Framework-specific hook/composable** (e.g., `src/shared/hooks/useProducts.ts` for React, `src/composables/useProducts.ts` for Vue)-# Data files-Get-ChildItem -Path ./src -Recurse -Include "*.data.ts","*mock*.ts"+Also verify:+- **Shared API client** at `src/shared/powerPagesApi.ts` exists+- Each service file references `/_api/` endpoints+- Each service file imports from the shared API client-# Inline arrays-Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "const\s+\w+\s*=\s*\[" | Where-Object { $_.Line -match "\{" }+### 5.2 Verify Build++Run the project build to catch any import errors, type errors, or missing dependencies:++```powershell+npm run build```+If the build fails, fix the issues before proceeding. Common issues:+- Missing imports between generated files+- Type mismatches between service and type definitions+- Framework-specific compilation errors++### 5.3 Present Verification Results++Present a table summarizing the verification:++| Table | Types | Service | Hook/Composable | API References |+|-------|-------|---------|-----------------|----------------|+| Products | `src/types/product.ts` | `src/shared/services/productService.ts` | `src/shared/hooks/useProducts.ts` | `/_api/cr4fc_products` |+| ... | ... | ... | ... | ... |++**Build status**: Pass / Fail (with details)++**Output**: All integration files verified, project builds successfully+----## Step 6: Replace Mock Data+## Phase 6: Setup Permissions++**Goal**: Configure table permissions and site settings for all integrated tables using the `webapi-permissions` agent++**Actions**:++### 5.1 Check Deployment Prerequisite++The permissions agent requires the `.powerpages-site` folder. If it doesn't exist:++Use `AskUserQuestion`:++| Question | Options |+|----------|---------|+| The `.powerpages-site` folder was not found. The site needs to be deployed once before permissions can be configured. Would you like to deploy now? | Yes, deploy now (Recommended), Skip permissions for now — I'll set them up later |++**If "Yes, deploy now"**: Invoke `/power-pages:deploy-site` first, then resume this phase.++**If "Skip"**: Skip to Phase 7 with a note that permissions still need to be configured.++### 5.2 Choose Permissions Source++Ask the user how they want to define the permissions using the `AskUserQuestion` tool:++**Question**: "How would you like to define the Web API permissions for your site?"++| Option | Description |+|--------|-------------|+| **Upload an existing permissions diagram** | Provide an image (PNG/JPG) or Mermaid diagram of your existing permissions structure |+| **Let the Web API Permissions Architect figure it out** | The Web API Permissions Architect will analyze your site's code, data model, and Dataverse environment, then propose permissions automatically |++Route to the appropriate path:++#### Path A: Upload Existing Permissions Diagram++If the user chooses to upload an existing diagram:++1. Ask the user to provide their permissions diagram. Supported formats:+ - **Image file** (PNG, JPG) — Use the `Read` tool to view the image and extract web roles, table permissions, CRUD flags, scopes, and site settings from it+ - **Mermaid syntax** — The user can paste a Mermaid flowchart diagram text directly in chat+ - **Text description** — A structured list of web roles, table permissions, scopes, and site settings++2. Parse the diagram into the same structured format used by the webapi-permissions agent:+ - **Web roles**: Match with existing roles from `.powerpages-site/web-roles/` by name to get their UUIDs+ - **Table permissions**: Permission name, table logical name, web role UUID(s), scope, CRUD flags (read/create/write/delete/append/appendto), parent permission and relationship name (if Parent scope)+ - **Site settings**: `Webapi/<table>/enabled` and `Webapi/<table>/fields` — **CRITICAL: fields must list specific column logical names, NEVER use `*` wildcard**++3. Cross-check with existing configuration in `.powerpages-site/` to identify which permissions and site settings are new vs. already exist.++4. Generate a Mermaid flowchart from the parsed data (if the user provided an image or text) for visual confirmation.++5. Present the parsed permissions plan to the user for approval using `AskUserQuestion`:++ | Question | Options |+ |----------|---------|+ | Does this permissions plan look correct? | Approve and create files (Recommended), Request changes, Cancel |++6. Proceed directly to **section 5.4: Create Permission Files** with the parsed permissions data.++#### Path B: Let the Web API Permissions Architect Figure It Out++If the user chooses to let the Web API Permissions Architect figure it out, proceed to **section 5.3: Invoke Permissions Agent**.++### 5.3 Invoke Permissions Agent++Use the `Task` tool to invoke the `webapi-permissions` agent at `${CLAUDE_PLUGIN_ROOT}/agents/webapi-permissions.md`:++**Prompt:**++> "Analyze this Power Pages code site and set up Web API permissions. The following tables have been integrated with Web API: [list of tables integrated in Phase 4]. Check for existing web roles, table permissions, and site settings. Propose a complete permissions plan covering all integrated tables."++### 5.4 Create Permission Files++After the permissions data is available — either from the user's uploaded diagram (Path A) or from the `webapi-permissions` agent's approved plan (Path B) — create the actual YAML files:-For each component using static data:+- **Table permission files** in `.powerpages-site/table-permissions/`+- **Site setting files** in `.powerpages-site/site-settings/`-**Before:**-```tsx-const products = [{ id: 1, name: 'Widget' }];+For each file that needs a UUID, generate one using the shared script:++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js"```-**After:**-```tsx-const [products, setProducts] = useState<Product[]>([]);-useEffect(() => {- productsApi.getActive().then(setProducts);-}, []);+**CRITICAL YAML FORMATTING RULES when writing these files:**+- **Code site git format**: Table permission fields have `adx_` prefix stripped (e.g., `append`, `read`, `scope`) EXCEPT `adx_entitypermission_webrole` (M2M relationship keeps prefix). The display name field is `entityname` (NOT `entitypermissionname`). Entity reference lookups (like `parententitypermission`) store only the GUID, not a nested object.+- Boolean values MUST be unquoted: `value: true` — NEVER `value: "true"` or `value: "false"`+- Numeric values MUST be unquoted: `scope: 756150000` — NEVER `scope: "756150000"`+- UUIDs MUST be unquoted: `id: a1b2c3d4-...` — NEVER `id: "a1b2c3d4-..."`+- String values (like field lists) are also unquoted: `value: cr87b_name,cr87b_email`+- CRUD flags are unquoted booleans: `read: true` — NEVER `read: "true"`+- Fields MUST be alphabetically sorted+- Follow the exact YAML format specified by the permissions plan output++### 5.5 Git Commit++Stage and commit the permission files:++```powershell+git add -A+git commit -m "Add Web API permissions and site settings for [table names]"```-See [frontend-integration-reference.md](./references/frontend-integration-reference.md#mock-data-replacement-guide).+**Output**: Table permissions and site settings created, verified, and committed----## Step 7: Delete Mock Files+## Phase 7: Review & Deploy++**Goal**: Present a summary of all work performed and offer deployment++**Actions**:++### 7.1 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 "IntegrateWebApi"`.++### 7.2 Present Summary++Present a summary of everything that was done:++| Step | Status | Details |+|------|--------|---------|+| API Client | Created/Existed | `src/shared/powerPagesApi.ts` |+| Types | Created | `src/types/product.ts`, `src/types/category.ts` |+| Services | Created | `src/shared/services/productService.ts`, etc. |+| Hooks | Created | `src/shared/hooks/useProducts.ts`, etc. |+| Components Updated | X files | Mock data replaced with API calls |+| Table Permissions | Created | X permission files |+| Site Settings | Created | X setting files |++### 7.3 Ask to Deploy++Use `AskUserQuestion`:++| Question | Options |+|----------|---------|+| The Web API integration and permissions are ready. To make everything live, the site needs to be deployed. Would you like to deploy now? | Yes, deploy now (Recommended), No, I'll deploy later |++**If "Yes, deploy now"**: Invoke the `/power-pages:deploy-site` skill to deploy the site.-After replacing all usages:-1. Delete mock data files-2. Remove empty mock folders-3. Update barrel exports+**If "No, I'll deploy later"**: Acknowledge and remind:++> "No problem! Remember to deploy your site using `/power-pages:deploy-site` when you're ready. The Web API calls will not work until the site is deployed with the new permissions."++### 7.4 Post-Deploy Notes++After deployment (or if skipped), remind the user:++- **Test the API**: Open the deployed site and verify Web API calls work in the browser's Network tab+- **Check permissions**: If any API call returns 403, verify table permissions and site settings are correct+- **Disable innererror in production**: If `Webapi/error/innererror` was enabled for debugging, disable it before going live+- **Web roles**: Users must be assigned the appropriate web roles to access protected APIs++**Output**: Summary presented, deployment completed or deferred, post-deploy guidance provided----## Step 8: Build and Upload+## Important Notes-```powershell-npm run build-pac pages upload-code-site --rootPath "<PROJECT_ROOT>"-```+### Throughout All Phases-**Test in browser console:**-```javascript-fetch('/_api/${prefix}_products').then(r => r.json()).then(console.log)-```+- **Use TaskCreate/TaskUpdate** to track progress at every phase+- **Ask for user confirmation** at key decision points (see list below)+- **Process tables sequentially** — never in parallel, because the shared API client and shared files create ordering dependencies+- **Commit at milestones** — after integration code and after permission files+- **Verify each integration** — confirm expected files exist after each agent invocation++### Key Decision Points (Wait for User)++1. After Phase 2: Confirm which tables to integrate+2. After Phase 3: Approve integration plan+3. At Phase 6.1: Deploy now or skip permissions (if `.powerpages-site` missing)+4. At Phase 6.2: Choose permissions source (upload diagram or let the Web API Permissions Architect analyze)+5. At Phase 6.3/6.4: Approve permissions plan (via user review for Path A, or plan mode within the agent for Path B)+6. At Phase 7.2: Deploy now or deploy later++### Progress Tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Verify site exists | Verifying site prerequisites | Locate project root, detect framework, check data model and deployment status |+| Explore integration points | Analyzing code for integration points | Use Explore agent to discover tables, existing services, and compile integration manifest |+| Review integration plan | Reviewing integration plan with user | Present findings and confirm which tables to integrate |+| Implement integrations | Implementing Web API integrations | Invoke webapi-integration agent per table, verify output, git commit |+| Verify integrations | Verifying integrations | Validate all expected files exist, check imports and API references, run project build |+| Setup permissions | Configuring permissions and site settings | Choose permissions source (upload diagram or Web API Permissions Architect), create YAML files, git commit |+| Review and deploy | Reviewing summary and deploying | Present summary, ask about deployment, provide post-deploy guidance |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`. This gives the user visibility into progress and keeps the workflow deterministic.++----Update memory-bank.md with integration status.+**Begin with Phase 1: Verify Site Exists**diff --git a/plugins/power-pages/skills/integrate-webapi/references/frontend-integration-reference.md b/plugins/power-pages/skills/integrate-webapi/references/frontend-integration-reference.mddeleted file mode 100644index aa7a5df2d..000000000--- a/plugins/power-pages/skills/integrate-webapi/references/frontend-integration-reference.md+++ /dev/null@@ -1,721 +0,0 @@-# Frontend Integration Reference--## Web API Endpoint Format--The Power Pages Web API follows OData conventions.--**IMPORTANT - Table Names**: Use the **actual table logical names** from the `$tableMap` built in `/setup-dataverse`:-- For **reused/extended tables**: Use the existing logical name from Dataverse (e.g., `contoso_items`, `existing_productcategory`)-- For **new tables**: Use `{prefix}_tablename` pattern (e.g., `cr_product`)--The entity set name (used in URLs) is typically the pluralized form of the logical name.--**NOTE**: Replace `{prefix}` with your publisher prefix from `Initialize-DataverseApi` (e.g., `cr`, `contoso`, `new`).--```text-Base URL: https://<site-url>/_api/<entity-set-name>--Examples:-GET /_api/{prefix}_products # List all products-GET /_api/{prefix}_products(<guid>) # Get single product-GET /_api/{prefix}_products?$select={prefix}_name,{prefix}_price # Select specific fields-GET /_api/{prefix}_products?$filter={prefix}_isactive eq true # Filter records-GET /_api/{prefix}_products?$orderby={prefix}_name # Order results-GET /_api/{prefix}_products?$top=10 # Limit results-POST /_api/{prefix}_products # Create new product-PATCH /_api/{prefix}_products(<guid>) # Update product-DELETE /_api/{prefix}_products(<guid>) # Delete product-```--## CSRF Token Requirement--**IMPORTANT**: Power Pages requires a CSRF (Cross-Site Request Forgery) anti-forgery token for all non-GET requests (POST, PATCH, DELETE).--- The token must be fetched from `/_layout/tokenhtml`-- Include the token in the `__RequestVerificationToken` header-- GET requests do not require this token-- The token may expire, so handle 403 errors by refreshing the token--## Power Pages Web API Service (TypeScript)--Create a reusable API service for Web API calls.--**File: `src/services/webApi.ts`**--```typescript-// Power Pages Web API Service-const API_BASE = '/_api';--interface QueryOptions {- select?: string[];- filter?: string;- orderBy?: string;- top?: number;- expand?: string;-}--// Cache for the anti-forgery token-let cachedToken: string | null = null;--/**- * Fetches the CSRF anti-forgery token required for non-GET requests.- * Power Pages requires this token in the __RequestVerificationToken header- * for POST, PATCH, and DELETE operations.- */-async function fetchAntiForgeryToken(): Promise<string> {- // Return cached token if available- if (cachedToken) {- return cachedToken;- }-- try {- const tokenEndpoint = '/_layout/tokenhtml';- const response = await fetch(tokenEndpoint, {});-- if (response.status !== 200) {- throw new Error(`Failed to fetch token: ${response.status}`);- }-- const tokenResponse = await response.text();- const valueString = 'value="';- const terminalString = '" />';- const valueIndex = tokenResponse.indexOf(valueString);-- if (valueIndex === -1) {- throw new Error('Token not found in response');- }-- const requestVerificationToken = tokenResponse.substring(- valueIndex + valueString.length,- tokenResponse.indexOf(terminalString, valueIndex)- );-- cachedToken = requestVerificationToken || '';- return cachedToken;- } catch (error) {- console.warn('[Web API] Failed to fetch anti-forgery token:', error);- return '';- }-}--/**- * Clears the cached token. Call this if you receive a 403 error- * which may indicate the token has expired.- */-function clearTokenCache(): void {- cachedToken = null;-}--async function fetchWithAuth(url: string, options: RequestInit = {}) {- const method = options.method?.toUpperCase() || 'GET';- const headers: Record<string, string> = {- 'Content-Type': 'application/json',- 'Accept': 'application/json',- ...options.headers as Record<string, string>,- };-- // Add anti-forgery token for non-GET requests (POST, PATCH, DELETE)- if (method !== 'GET') {- const token = await fetchAntiForgeryToken();- if (token) {- headers['__RequestVerificationToken'] = token;- }- }-- const response = await fetch(url, {- ...options,- headers,- credentials: 'include', // Important for authenticated requests- });-- if (!response.ok) {- // If we get a 403, the token may have expired - clear the cache- if (response.status === 403) {- clearTokenCache();- }- const error = await response.json().catch(() => ({ message: response.statusText }));- throw new Error(error.message || `API Error: ${response.status}`);- }-- return response.json();-}--function buildQueryString(options: QueryOptions): string {- const params = new URLSearchParams();-- if (options.select?.length) {- params.append('$select', options.select.join(','));- }- if (options.filter) {- params.append('$filter', options.filter);- }- if (options.orderBy) {- params.append('$orderby', options.orderBy);- }- if (options.top) {- params.append('$top', options.top.toString());- }- if (options.expand) {- params.append('$expand', options.expand);- }-- const queryString = params.toString();- return queryString ? `?${queryString}` : '';-}--// Generic CRUD operations-export const webApi = {- // GET all records- async getAll<T>(entitySet: string, options: QueryOptions = {}): Promise<T[]> {- const queryString = buildQueryString(options);- const response = await fetchWithAuth(`${API_BASE}/${entitySet}${queryString}`);- return response.value;- },-- // GET single record by ID- async getById<T>(entitySet: string, id: string, options: Pick<QueryOptions, 'select' | 'expand'> = {}): Promise<T> {- const queryString = buildQueryString(options);- return fetchWithAuth(`${API_BASE}/${entitySet}(${id})${queryString}`);- },-- // POST create new record- async create<T>(entitySet: string, data: Partial<T>): Promise<T> {- return fetchWithAuth(`${API_BASE}/${entitySet}`, {- method: 'POST',- body: JSON.stringify(data),- });- },-- // PATCH update existing record- async update<T>(entitySet: string, id: string, data: Partial<T>): Promise<void> {- await fetchWithAuth(`${API_BASE}/${entitySet}(${id})`, {- method: 'PATCH',- body: JSON.stringify(data),- });- },-- // DELETE record- async delete(entitySet: string, id: string): Promise<void> {- await fetchWithAuth(`${API_BASE}/${entitySet}(${id})`, {- method: 'DELETE',- });- },-};-```--## Entity-Specific Services--Create typed wrappers for each entity.--**IMPORTANT**: Always include `$select` with the fields configured in site settings. Power Pages Web API returns an error if you request fields not listed in the `Webapi/<table>/fields` site setting. Omitting `$select` attempts to fetch all fields, which fails.--**NOTE**: Replace `{prefix}` with your publisher prefix (e.g., `cr`, `contoso`, `new`). The prefix is determined by your Dataverse environment's default publisher.--```typescript-// Entity-specific services-// IMPORTANT: The 'select' array must match the fields in your Webapi/<table>/fields site setting-// NOTE: Replace {prefix} with your actual publisher prefix (e.g., 'cr', 'contoso', 'new')--export const productsApi = {- getAll: (options?: QueryOptions) =>- webApi.getAll<Product>('{prefix}_products', {- select: ['{prefix}_productid', '{prefix}_name', '{prefix}_description', '{prefix}_price', '{prefix}_category', '{prefix}_imageurl', '{prefix}_isactive'],- ...options,- }),- getById: (id: string) =>- webApi.getById<Product>('{prefix}_products', id, {- select: ['{prefix}_productid', '{prefix}_name', '{prefix}_description', '{prefix}_price', '{prefix}_category', '{prefix}_imageurl', '{prefix}_isactive'],- }),- getActive: () =>- webApi.getAll<Product>('{prefix}_products', {- select: ['{prefix}_productid', '{prefix}_name', '{prefix}_description', '{prefix}_price', '{prefix}_category', '{prefix}_imageurl', '{prefix}_isactive'],- filter: '{prefix}_isactive eq true',- orderBy: '{prefix}_name',- }),-};--export const teamMembersApi = {- getAll: () =>- webApi.getAll<TeamMember>('{prefix}_teammembers', {- select: ['{prefix}_teammemberid', '{prefix}_name', '{prefix}_title', '{prefix}_email', '{prefix}_bio', '{prefix}_photourl', '{prefix}_linkedin', '{prefix}_displayorder'],- orderBy: '{prefix}_displayorder',- }),-};--export const testimonialsApi = {- getActive: () =>- webApi.getAll<Testimonial>('{prefix}_testimonials', {- select: ['{prefix}_testimonialid', '{prefix}_name', '{prefix}_quote', '{prefix}_company', '{prefix}_role', '{prefix}_rating', '{prefix}_photourl', '{prefix}_isactive'],- filter: '{prefix}_isactive eq true',- }),-};--export const faqsApi = {- getActive: () =>- webApi.getAll<FAQ>('{prefix}_faqs', {- select: ['{prefix}_faqid', '{prefix}_question', '{prefix}_answer', '{prefix}_category', '{prefix}_displayorder', '{prefix}_isactive'],- filter: '{prefix}_isactive eq true',- orderBy: '{prefix}_displayorder',- }),-};--export const contactApi = {- submit: (data: ContactSubmission) =>- webApi.create<ContactSubmission>('{prefix}_contactsubmissions', {- ...data,- {prefix}_submissiondate: new Date().toISOString(),- {prefix}_status: 1, // New- }),-};-```--## Type Definitions--**NOTE**: Replace `{prefix}` with your publisher prefix (e.g., `cr`, `contoso`, `new`).--```typescript-// NOTE: Replace {prefix} with your actual publisher prefix--export interface Product {- {prefix}_productid: string;- {prefix}_name: string;- {prefix}_description: string;- {prefix}_price: number;- {prefix}_category: string;- {prefix}_imageurl: string;- {prefix}_isactive: boolean;-}--export interface TeamMember {- {prefix}_teammemberid: string;- {prefix}_name: string;- {prefix}_title: string;- {prefix}_email: string;- {prefix}_bio: string;- {prefix}_photourl: string;- {prefix}_linkedin: string;- {prefix}_displayorder: number;-}--export interface Testimonial {- {prefix}_testimonialid: string;- {prefix}_name: string;- {prefix}_quote: string;- {prefix}_company: string;- {prefix}_role: string;- {prefix}_rating: number;- {prefix}_photourl: string;- {prefix}_isactive: boolean;-}--export interface FAQ {- {prefix}_faqid: string;- {prefix}_question: string;- {prefix}_answer: string;- {prefix}_category: string;- {prefix}_displayorder: number;- {prefix}_isactive: boolean;-}--export interface ContactSubmission {- {prefix}_name: string;- {prefix}_email: string;- {prefix}_message: string;- {prefix}_submissiondate?: string;- {prefix}_status?: number;-}-```--## React Hook for Data Fetching--**File: `src/hooks/useWebApi.ts`**--```typescript-import { useState, useEffect, useCallback } from 'react';-import { webApi, QueryOptions } from '../services/webApi';--interface UseDataverseResult<T> {- data: T[];- loading: boolean;- error: string | null;- refetch: () => Promise<void>;-}--export function useWebApi<T>(- entitySet: string,- options: QueryOptions = {},- deps: any[] = []-): UseDataverseResult<T> {- const [data, setData] = useState<T[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);-- const fetchData = useCallback(async () => {- setLoading(true);- setError(null);- try {- const result = await webApi.getAll<T>(entitySet, options);- setData(result);- } catch (err) {- setError(err instanceof Error ? err.message : 'Failed to fetch data');- } finally {- setLoading(false);- }- }, [entitySet, JSON.stringify(options)]);-- useEffect(() => {- fetchData();- }, [fetchData, ...deps]);-- return { data, loading, error, refetch: fetchData };-}--// Usage example (replace {prefix} with your publisher prefix):-// const { data: products, loading, error } = useWebApi<Product>('{prefix}_products', { filter: '{prefix}_isactive eq true' });-```--## Component Examples--### Data Display Component--**Before (static data):**--```tsx-const products = [- { id: 1, name: 'Product 1', price: 99.99 },- { id: 2, name: 'Product 2', price: 149.99 },-];--function ProductList() {- return (- <div>- {products.map(product => (- <ProductCard key={product.id} product={product} />- ))}- </div>- );-}-```--**After (Web API):**--```tsx-import { useState, useEffect } from 'react';-import { productsApi, Product } from '../services/webApi';--function ProductList() {- const [products, setProducts] = useState<Product[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);-- useEffect(() => {- async function loadProducts() {- try {- const data = await productsApi.getActive();- setProducts(data);- } catch (err) {- setError(err instanceof Error ? err.message : 'Failed to load products');- } finally {- setLoading(false);- }- }- loadProducts();- }, []);-- if (loading) return <div className="loading">Loading products...</div>;- if (error) return <div className="error">{error}</div>;-- return (- <div className="products-grid">- {products.map(product => (- <ProductCard key={product.{prefix}_productid} product={product} />- ))}- </div>- );-}-```--### Form Submission Component--```tsx-import { useState } from 'react';-import { contactApi, ContactSubmission } from '../services/webApi';--function ContactForm() {- // NOTE: Replace {prefix} with your actual publisher prefix- const [formData, setFormData] = useState<ContactSubmission>({- {prefix}_name: '',- {prefix}_email: '',- {prefix}_message: '',- });- const [submitting, setSubmitting] = useState(false);- const [submitted, setSubmitted] = useState(false);- const [error, setError] = useState<string | null>(null);-- const handleSubmit = async (e: React.FormEvent) => {- e.preventDefault();- setSubmitting(true);- setError(null);-- try {- await contactApi.submit(formData);- setSubmitted(true);- setFormData({ {prefix}_name: '', {prefix}_email: '', {prefix}_message: '' });- } catch (err) {- setError(err instanceof Error ? err.message : 'Failed to submit form');- } finally {- setSubmitting(false);- }- };-- if (submitted) {- return (- <div className="success-message">- <h3>Thank you!</h3>- <p>Your message has been sent. We'll get back to you soon.</p>- <button onClick={() => setSubmitted(false)}>Send another message</button>- </div>- );- }-- return (- <form onSubmit={handleSubmit} className="contact-form">- {error && <div className="error-message">{error}</div>}-- <div className="form-group">- <label htmlFor="name">Name</label>- <input- id="name"- type="text"- value={formData.{prefix}_name}- onChange={e => setFormData({ ...formData, {prefix}_name: e.target.value })}- required- />- </div>-- <div className="form-group">- <label htmlFor="email">Email</label>- <input- id="email"- type="email"- value={formData.{prefix}_email}- onChange={e => setFormData({ ...formData, {prefix}_email: e.target.value })}- required- />- </div>-- <div className="form-group">- <label htmlFor="message">Message</label>- <textarea- id="message"- value={formData.{prefix}_message}- onChange={e => setFormData({ ...formData, {prefix}_message: e.target.value })}- required- rows={5}- />- </div>-- <button type="submit" disabled={submitting}>- {submitting ? 'Sending...' : 'Send Message'}- </button>- </form>- );-}-```--## Mock Data Replacement Guide--**CRITICAL**: The Web API setup is NOT complete until ALL mock/static data has been replaced with Web API calls. This section provides systematic instructions to find and replace every instance.--### Step 1: Search for Mock Data Files--Search for dedicated mock data files and folders:--```bash-# Find common mock data folders-find . -type d -name "mock*" -o -name "data" -o -name "fixtures" -o -name "fake*" -o -name "dummy*" 2>/dev/null--# Find data files-find . -type f \( -name "*.data.ts" -o -name "*.data.js" -o -name "*mock*.ts" -o -name "*mock*.js" -o -name "*.json" \) -path "*/src/*" 2>/dev/null-```--**PowerShell equivalent:**-```powershell-# Find mock data folders-Get-ChildItem -Path . -Directory -Recurse | Where-Object { $_.Name -match "mock|data|fixtures|fake|dummy" }--# Find data files in src-Get-ChildItem -Path ./src -Recurse -Include "*.data.ts","*.data.js","*mock*.ts","*mock*.js","*.json"-```--### Step 2: Search for Inline Mock Data Patterns--Search for common patterns that indicate hardcoded data:--```bash-# Arrays of objects (common mock data pattern)-grep -rn "^\s*\[\s*{" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" src/--# Const arrays with data-grep -rn "const.*=\s*\[" --include="*.ts" --include="*.tsx" src/--# Export const arrays-grep -rn "export const.*\[\|export default \[" --include="*.ts" --include="*.tsx" src/-```--**PowerShell equivalent:**-```powershell-# Search for array declarations that look like mock data-Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "const\s+\w+\s*=\s*\[" | Where-Object { $_.Line -notmatch "useState|useEffect" }--# Search for exported arrays-Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "export (const|default)\s+.*\["-```--### Step 3: Identify Data by Entity Type--For each table configured for Web API, search for related mock data:--| Table | Search Patterns |-|-------|-----------------|-| Products | `product`, `products`, `item`, `items`, `catalog` |-| Team Members | `team`, `member`, `staff`, `employee`, `people` |-| Testimonials | `testimonial`, `review`, `feedback`, `quote` |-| FAQs | `faq`, `question`, `answer`, `help` |-| Contact | `contact`, `submission`, `inquiry`, `message` |--**Example search:**-```powershell-# Find all references to products data-Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "products?\s*[:=]?\s*\[" -CaseSensitive:$false-```--### Step 4: Replace Each Instance--For each mock data instance found:--**Before (mock data):**-```typescript-// src/data/products.ts-export const products = [- { id: 1, name: 'Widget', price: 29.99 },- { id: 2, name: 'Gadget', price: 49.99 },-];--// src/components/ProductList.tsx-import { products } from '../data/products';--function ProductList() {- return products.map(p => <ProductCard key={p.id} product={p} />);-}-```--**After (Web API):**-```typescript-// src/components/ProductList.tsx-import { useState, useEffect } from 'react';-import { productsApi, Product } from '../services/webApi';--function ProductList() {- const [products, setProducts] = useState<Product[]>([]);- const [loading, setLoading] = useState(true);-- useEffect(() => {- // productsApi.getActive() already includes $select with allowed fields- productsApi.getActive().then(setProducts).finally(() => setLoading(false));- }, []);-- if (loading) return <LoadingSpinner />;- return products.map(p => <ProductCard key={p.{prefix}_productid} product={p} />);-}-```--### Step 5: Delete or Archive Mock Data Files--After replacing all usages:--1. **Delete mock data files** that are no longer imported anywhere-2. **Remove mock data folders** if empty-3. **Update any barrel exports** (index.ts files) that re-exported mock data--```powershell-# Verify no imports remain for a mock file before deleting-Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "from ['\"].*products\.data"--# If no results, safe to delete-Remove-Item -Path "src\data\products.data.ts"-```--### Step 6: Verify Complete Replacement--**IMPORTANT**: Run these verification checks before marking the skill complete:--```powershell-# 1. Check for any remaining mock/data folders-Get-ChildItem -Path ./src -Directory -Recurse | Where-Object { $_.Name -match "^(mock|data|fixtures|fake|dummy)$" }--# 2. Check for suspicious const array declarations (review each match)-Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "const\s+\w+\s*:\s*\w+\[\]\s*=\s*\[" | Where-Object { $_.Line -match "\{" }--# 3. Check for JSON imports that might be mock data-Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "from ['\"].*\.json['\"]"--# 4. Verify all components use the webApi service-Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "webApi|productsApi|teamMembersApi|testimonialsApi|faqsApi|contactApi"-```--### Common Locations for Mock Data--| Location | Description | Action |-|----------|-------------|--------|-| `src/data/` | Dedicated data folder | Replace all, then delete folder |-| `src/mock/` | Mock data folder | Replace all, then delete folder |-| `src/constants/` | May contain data arrays | Review and replace data arrays |-| `src/fixtures/` | Test fixtures with data | Replace with API calls or test mocks |-| `*.json` in src | JSON data files | Replace imports with API calls |-| Component files | Inline const arrays | Move to useEffect with API calls |-| Context providers | Initial state with data | Initialize empty, fetch in useEffect |--### Mock Data Replacement Tracking--Track replacements in the memory bank:--```markdown-### Removed/Replaced Mock Data--| Location | Description | Replaced With | Verified |-|----------|-------------|---------------|----------|-| src/data/products.ts | Static product array | productsApi.getActive() | ✅ |-| src/data/team.ts | Team member list | teamMembersApi.getAll() | ✅ |-| src/components/FAQ.tsx | Inline FAQ array | faqsApi.getActive() | ✅ |-| src/data/ folder | Mock data folder | DELETED | ✅ |-```--## OData Query Reference--**NOTE**: Replace `{prefix}` with your publisher prefix (e.g., `cr`, `contoso`, `new`).--| Operation | Query String | Example |-|-----------|-------------|---------|-| Select fields | `$select=field1,field2` | `$select={prefix}_name,{prefix}_price` |-| Filter | `$filter=condition` | `$filter={prefix}_isactive eq true` |-| Order by | `$orderby=field [asc\|desc]` | `$orderby={prefix}_name desc` |-| Top N | `$top=N` | `$top=10` |-| Skip | `$skip=N` | `$skip=20` |-| Expand | `$expand=relationship` | `$expand={prefix}_category` |--### Filter Operators--| Operator | Description | Example |-|----------|-------------|---------|-| `eq` | Equal | `{prefix}_isactive eq true` |-| `ne` | Not equal | `{prefix}_status ne 0` |-| `gt` | Greater than | `{prefix}_price gt 100` |-| `ge` | Greater or equal | `{prefix}_price ge 100` |-| `lt` | Less than | `{prefix}_price lt 50` |-| `le` | Less or equal | `{prefix}_price le 50` |-| `and` | Logical AND | `{prefix}_isactive eq true and {prefix}_price gt 0` |-| `or` | Logical OR | `{prefix}_category eq 'A' or {prefix}_category eq 'B'` |-| `contains` | Contains string | `contains({prefix}_name,'search')` |-| `startswith` | Starts with | `startswith({prefix}_name,'Pro')` |-| `endswith` | Ends with | `endswith({prefix}_email,'@example.com')` |diff --git a/plugins/power-pages/skills/integrate-webapi/scripts/validate-webapi-integration.js b/plugins/power-pages/skills/integrate-webapi/scripts/validate-webapi-integration.jsnew file mode 100644index 000000000..354d0bf25--- /dev/null+++ b/plugins/power-pages/skills/integrate-webapi/scripts/validate-webapi-integration.js@@ -0,0 +1,114 @@+#!/usr/bin/env node++// Validates that Web API integration code was created for a Power Pages code site.+// Runs as a Stop hook to verify the skill produced output.++const fs = require('fs');+const path = require('path');+const { approve, block, runValidation, findProjectRoot } = require('../../../scripts/lib/validation-helpers');++runValidation((cwd) => {+ const projectRoot = findProjectRoot(cwd);+ if (!projectRoot) approve(); // Not a Power Pages project, skip++ // Check if any Web API integration files exist — if none, this wasn't an integration session+ const apiClientExists = findApiClient(projectRoot);+ const serviceFiles = findServiceFiles(projectRoot);++ if (!apiClientExists && serviceFiles.length === 0) approve();++ const errors = [];++ if (!apiClientExists) {+ errors.push('Missing shared API client (src/shared/powerPagesApi.ts or equivalent)');+ }++ if (serviceFiles.length === 0) {+ errors.push('No service files found in src/shared/services/ or src/services/');+ }++ for (const serviceFile of serviceFiles) {+ const content = fs.readFileSync(serviceFile, 'utf8');+ if (!content.includes('/_api/')) {+ errors.push(`${path.basename(serviceFile)}: missing /_api/ endpoint references`);+ }+ }++ const typeFiles = findTypeFiles(projectRoot);+ if (typeFiles.length === 0 && serviceFiles.length > 0) {+ errors.push('No type definition files found in src/types/ — services should have corresponding type definitions');+ }++ if (errors.length > 0) {+ block('Web API integration validation failed:\n- ' + errors.join('\n- '));+ }++ approve();+});++function findApiClient(projectRoot) {+ const candidates = [+ path.join(projectRoot, 'src', 'shared', 'powerPagesApi.ts'),+ path.join(projectRoot, 'src', 'shared', 'powerPagesApi.js'),+ path.join(projectRoot, 'src', 'services', 'powerPagesApi.ts'),+ path.join(projectRoot, 'src', 'services', 'powerPagesApi.js'),+ ];++ for (const candidate of candidates) {+ if (fs.existsSync(candidate)) return true;+ }++ // Fallback: search for any file containing powerPagesFetch export+ try {+ const sharedDir = path.join(projectRoot, 'src', 'shared');+ if (fs.existsSync(sharedDir)) {+ for (const file of fs.readdirSync(sharedDir)) {+ if (file.endsWith('.ts') || file.endsWith('.js')) {+ const content = fs.readFileSync(path.join(sharedDir, file), 'utf8');+ if (content.includes('powerPagesFetch') && content.includes('__RequestVerificationToken')) {+ return true;+ }+ }+ }+ }+ } catch {}++ return false;+}++function findServiceFiles(projectRoot) {+ const serviceDirs = [+ path.join(projectRoot, 'src', 'shared', 'services'),+ path.join(projectRoot, 'src', 'services'),+ ];++ const files = [];+ for (const dir of serviceDirs) {+ if (!fs.existsSync(dir)) continue;+ try {+ for (const file of fs.readdirSync(dir)) {+ if ((file.endsWith('Service.ts') || file.endsWith('Service.js')) && !file.startsWith('.')) {+ files.push(path.join(dir, file));+ }+ }+ } catch {}+ }++ return files;+}++function findTypeFiles(projectRoot) {+ const typesDir = path.join(projectRoot, 'src', 'types');+ if (!fs.existsSync(typesDir)) return [];++ const files = [];+ try {+ for (const file of fs.readdirSync(typesDir)) {+ if ((file.endsWith('.ts') || file.endsWith('.js')) && !file.startsWith('.') && file !== 'index.ts') {+ files.push(path.join(typesDir, file));+ }+ }+ } catch {}++ return files;+}diff --git a/plugins/power-pages/skills/setup-auth/SKILL.md b/plugins/power-pages/skills/setup-auth/SKILL.mdindex 022ced632..6977d1d1c 100644--- a/plugins/power-pages/skills/setup-auth/SKILL.md+++ b/plugins/power-pages/skills/setup-auth/SKILL.md@@ -1,129 +1,586 @@----name: setting-up-authentication-description: Configures authentication (login/logout) and role-based authorization for Power Pages. Use when setting up user login, Azure AD/Entra ID auth, logout, role-based access control, route protection, or conditional UI based on roles.+name: setup-auth+description: >+ This skill should be used when the user asks to "set up authentication",+ "add login", "add logout", "configure Entra ID", "set up Azure AD auth",+ "add Microsoft login", "enable authentication", "set up sign in",+ "add role-based access", "add authorization", "protect routes",+ "add auth to my site", "configure identity provider", or wants to set up+ authentication (login/logout via Microsoft Entra ID) and role-based+ authorization for their Power Pages code site.user-invocable: true-allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task", "ExitPlanMode"]+allowed-tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob", "AskUserQuestion", "Task", "TaskCreate", "TaskUpdate", "TaskList", "Skill"]model: opus+hooks:+ Stop:+ - hooks:+ - type: command+ command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/scripts/validate-auth.js"'+ timeout: 15+ - type: prompt+ prompt: >+ If authentication/authorization was being set up in this session (via /power-pages:setup-auth),+ verify before allowing stop: 1) The site was found and framework detected, 2) An auth service+ file was created (authService.ts/js) with login/logout functions, 3) PowerPages type declarations+ were created (powerPages.d.ts), 4) Authorization utilities were created (authorization.ts/js)+ with role-checking functions, 5) Auth UI component was created (AuthButton or equivalent),+ 6) All auth files were verified (exist, contain expected exports, project builds successfully),+ 7) The user was asked whether to deploy the site.+ If any of these are incomplete, return { "ok": false, "reason": "<specific issues>" }.+ If no auth setup work happened or everything is complete, return { "ok": true }.+ timeout: 30----**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.+# Set Up Authentication & Authorization-# Setup Authentication & Authorization+Configure authentication (login/logout via Microsoft Entra ID) and role-based authorization for a Power Pages code site. This skill creates an auth service, type declarations, authorization utilities, auth UI components, and role-based access control patterns appropriate to the site's framework.-**References:** [authentication](./references/authentication-reference.md) | [authorization](./references/authorization-reference.md)+## Core Principles++- **Client-side auth is UX only** — Power Pages authentication is server-side (session cookies). Client-side role checks control what users see, not what they can access. Server-side table permissions enforce actual security.+- **Framework-appropriate patterns** — Every auth artifact (hooks, composables, services, directives, guards) must match the detected framework's idioms and conventions.+- **Development parity** — Include mock data for local development so developers can test auth flows and role-based UI without deploying to Power Pages.++**Initial request:** $ARGUMENTS++> **Prerequisites:**+> - An existing Power Pages code site created via `/power-pages:create-site`+> - The site must be deployed at least once (`.powerpages-site` folder must exist)+> - Web roles must be created via `/power-pages:create-webroles`## Workflow-1. **Plan** → Check prerequisites, gather requirements, design auth approach, get approval-2. **Create Auth Service** → Login/logout methods, user info retrieval-3. **Create Authorization Utils** → Role checking, conditional rendering-4. **Create Auth UI** → Login/logout button, user profile-5. **Implement Role-Based UI** → Wrap components with role checks-6. **Build and Upload** → Deploy and verify+1. **Phase 1: Check Prerequisites** — Verify site exists, detect framework, check web roles+2. **Phase 2: Plan** — Gather auth requirements and present plan for approval+3. **Phase 3: Create Auth Service** — Auth service with login/logout and type declarations+4. **Phase 4: Create Authorization Utils** — Role-checking functions and wrapper components+5. **Phase 5: Create Auth UI** — Login/logout button integrated into navigation+6. **Phase 6: Implement Role-Based UI** — Apply role-based patterns to site components+7. **Phase 7: Verify Auth Setup** — Validate all auth files exist, build succeeds, auth UI renders+8. **Phase 8: Review & Deploy** — Summary and deployment prompt----## Step 1: Plan+## Phase 1: Check Prerequisites-### 1.1 Check Prerequisites+**Goal:** Confirm the project exists, identify the framework, verify deployment status and web roles, and check for existing auth code.-Read `memory-bank.md` for project context. Requires:-- Site uploaded to Power Pages (`/_layout/tokenhtml` endpoint needed)-- Web roles created (Authenticated Users must exist)+### Actions-If `/setup-webapi` not completed, tell user to run it first.+#### 1.1 Locate Project++Look for `powerpages.config.json` in the current directory or immediate subdirectories:++```text+**/powerpages.config.json+```-### 1.2 Gather Requirements+**If not found**: Tell the user to create a site first with `/power-pages:create-site`.++#### 1.2 Detect Framework++Read `package.json` to determine the framework (React, Vue, Angular, or Astro). See `${CLAUDE_PLUGIN_ROOT}/references/framework-conventions.md` for the full framework detection mapping.++#### 1.3 Check Deployment Status++Look for the `.powerpages-site` folder:++```text+**/.powerpages-site+```++**If not found**: Tell the user the site must be deployed first:++> "The `.powerpages-site` folder was not found. The site needs to be deployed at least once before authentication can be configured."Use `AskUserQuestion`:-- Which features? (Login/Logout only, User profile, Role-based content, All)-- Which roles need conditional UI? (None, Admin sections, Member content, Multiple)-### 1.3 Enter Plan Mode+| Question | Options |+|----------|---------|+| Your site needs to be deployed first. Would you like to deploy now? | Yes, deploy now (Recommended), No, I'll do it later |++**If "Yes, deploy now"**: Invoke `/power-pages:deploy-site`, then resume.++**If "No"**: Stop — the site must be deployed first.++#### 1.4 Check Web Roles++Look for web role YAML files in `.powerpages-site/web-roles/`:++```text+**/.powerpages-site/web-roles/*.yml+```++Read each file and compile a list of existing web roles (name, id, flags).-Use `/plan` command to enter plan mode and create an implementation plan covering:-- Files to create (`authService.ts`, `authorization.ts`, type definitions)-- Auth UI components (login button, user profile display)-- Role-based UI requirements (which components need role checks)-- Site settings to configure-- Testing approach+**If no web roles exist**: Warn the user that web roles are needed for authorization. Ask if they want to create them first:-### 1.4 Get Approval+| Question | Options |+|----------|---------|+| No web roles were found. Web roles are required for role-based authorization. Would you like to create them now? | Yes, create web roles first (Recommended), Skip — I'll add roles later |-Present the plan to the user. Use `ExitPlanMode` only after user approves. If user requests changes, update the plan and present again.+**If "Yes"**: Invoke `/power-pages:create-webroles`, then resume.++**If "Skip"**: Continue — auth service and login/logout will still work, but role-based authorization will need roles created later.++#### 1.5 Check for Existing Auth Code++Search for existing auth files to avoid duplicating work:++- `src/services/authService.ts` or `src/services/authService.js`+- `src/types/powerPages.d.ts`+- `src/utils/authorization.ts` or `src/utils/authorization.js`+- Auth components (e.g., `AuthButton.tsx`, `AuthButton.vue`)++If auth files already exist, present them to the user and ask whether to overwrite or skip.++### Output++- Project root path confirmed+- Framework identified (React, Vue, Angular, or Astro)+- Deployment status verified+- Web roles inventory compiled+- Existing auth code conflicts identified (if any)----## Step 2: Create Auth Service+## Phase 2: Plan++**Goal:** Gather authentication requirements from the user and present the implementation plan for approval.++### Actions++#### 2.1 Gather Requirements++Use `AskUserQuestion` to determine the scope:-See [authentication-reference.md](./references/authentication-reference.md).+| Question | Options |+|----------|---------|+| Which authentication features do you need? | Login & Logout + Role-based access control (Recommended), Login & Logout only, Role-based access control only (auth service already exists) |-Power Pages auth is **server-side** (session cookies, not client tokens):-- **Login**: POST to `/Account/Login/ExternalLogin` with anti-forgery token from `/_layout/tokenhtml`-- **Logout**: Redirect to `/Account/Login/LogOff`-- **User Info**: `window.Microsoft.Dynamic365.Portal.User` (userName, firstName, lastName, email, contactId, userRoles[])+If web roles were found in Phase 1.4, also ask:-Create:-1. `src/services/authService.ts`-2. `src/types/powerPages.d.ts`+| Question | Options |+|----------|---------|+| Which web roles should have access to protected areas of the site? | *(List discovered web role names as options)* |++#### 2.2 Present Plan for Approval++Present the implementation plan inline:++- Which files will be created (auth service, types, authorization utils, components)+- How the auth UI will be integrated into the site's navigation+- Which routes/components will be protected and with which roles+- The site setting that needs to be configured (`Authentication/Registration/ProfileRedirectEnabled = false`)++Use `AskUserQuestion` to get approval:++| Question | Options |+|----------|---------|+| Here is the implementation plan for authentication and authorization. Would you like to proceed? | Approve and proceed (Recommended), I'd like to make changes |++**If "Approve and proceed"**: Continue to Phase 3.++**If "I'd like to make changes"**: Ask the user what they want to change, revise the plan, and present it again for approval.++### Output++- Authentication scope confirmed (login/logout, role-based access, or both)+- Target web roles selected+- Implementation plan approved by user----## Step 3: Create Authorization Utils+## Phase 3: Create Auth Service++**Goal:** Create the authentication service, type declarations, and framework-specific auth hook/composable with local development mock support.-See [authorization-reference.md](./references/authorization-reference.md).+Reference: `${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/references/authentication-reference.md`-Create `src/utils/authorization.ts`:-- Role checking functions (case-insensitive)-- Common roles: "Administrators", "Authenticated Users"+### Actions-Create wrapper components:-- `RequireRole` - conditional rendering-- Route guard (if using client-side routing)+#### 3.1 Create Type Declarations++Create `src/types/powerPages.d.ts` with type definitions for the Power Pages portal object and user:++- `PowerPagesUser` interface — `userName`, `firstName`, `lastName`, `email`, `contactId`, `userRoles[]`+- `PowerPagesPortal` interface — `User`, `version`, `type`, `id`, `geo`, `tenant`, etc.+- Global `Window` interface extension for `Microsoft.Dynamic365.Portal`++#### 3.2 Create Auth Service++Create the auth service file based on the detected framework:++**All frameworks**: Create `src/services/authService.ts` with these functions:++- `getCurrentUser()` — reads from `window.Microsoft.Dynamic365.Portal.User`+- `isAuthenticated()` — checks if user exists and has `userName`+- `getTenantId()` — reads from portal config (`window.Microsoft.Dynamic365.Portal.tenant`)+- `fetchAntiForgeryToken()` — fetches from `/_layout/tokenhtml` and parses HTML response+- `login(returnUrl?)` — creates a form POST to `/Account/Login/ExternalLogin` with:+ - Anti-forgery token from `/_layout/tokenhtml`+ - Provider URL: `https://login.windows.net/{tenantId}/`+ - Return URL (defaults to current page)+- `logout(returnUrl?)` — redirects to `/Account/Login/LogOff`+- `getUserDisplayName()` — prefers full name, falls back to userName+- `getUserInitials()` — for avatar display++**CRITICAL**: Power Pages authentication is **server-side** (session cookies). The login flow posts a form to the server which redirects to Entra ID. There is no client-side token management. The `fetchAntiForgeryToken()` call gets a CSRF token for the form POST, not a bearer token.++#### 3.3 Create Framework-Specific Auth Hook/Composable++Based on the detected framework:++- **React**: Create `src/hooks/useAuth.ts` — custom hook returning `{ user, isAuthenticated, isLoading, displayName, initials, login, logout, refresh }`+- **Vue**: Create `src/composables/useAuth.ts` — composable using `ref`, `computed`, `onMounted` returning reactive auth state+- **Angular**: Create `src/app/services/auth.service.ts` — injectable service with `BehaviorSubject` for user state+- **Astro**: Create `src/services/authService.ts` only (no framework-specific wrapper needed — use the service directly in components)++#### 3.4 Add Mock Data for Local Development++Auth only works when served from Power Pages (not during local `npm run dev`). Add a development mock pattern in the auth service:++```typescript+// In development (localhost), return mock user data for testing+const isDevelopment = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';+```++The mock should return a fake user with configurable roles so developers can test role-based UI locally.++### Output++- `src/types/powerPages.d.ts` created with Power Pages type definitions+- `src/services/authService.ts` created with login/logout functions+- Framework-specific auth hook/composable created+- Local development mock data included----## Step 4: Create Auth UI+## Phase 4: Create Authorization Utils++**Goal:** Create role-checking utilities and framework-specific authorization components (guards, directives, wrapper components).++Reference: `${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/references/authorization-reference.md`++### Actions++#### 4.1 Create Core Authorization Utilities-Create login/logout button component:-- Shows "Sign In" when unauthenticated-- Shows user name + "Sign Out" when authenticated+Create `src/utils/authorization.ts` with:-Integrate into site navigation. Optionally create user profile component.+- `getUserRoles()` — returns array of role names from current user+- `hasRole(roleName)` — case-insensitive single role check+- `hasAnyRole(roleNames)` — OR check across multiple roles+- `hasAllRoles(roleNames)` — AND check across multiple roles+- `isAuthenticated()` — re-exports from auth service+- `isAdmin()` — checks for "Administrators" role+- `hasElevatedAccess(additionalRoles)` — checks admin or specified roles++#### 4.2 Create Framework-Specific Authorization Components++Based on the detected framework:++**React:**+- `src/components/RequireAuth.tsx` — renders children only for authenticated users, optional login prompt fallback+- `src/components/RequireRole.tsx` — renders children only for users with specified roles, supports `requireAll` mode+- `src/hooks/useAuthorization.ts` — hook returning `{ roles, hasRole, hasAnyRole, hasAllRoles, isAuthenticated, isAdmin }`++**Vue:**+- `src/composables/useAuthorization.ts` — composable with computed roles and role-checking functions+- `src/directives/vRole.ts` — `v-role` directive for declarative role-based visibility++**Angular:**+- `src/app/guards/auth.guard.ts` — `CanActivateFn` with route data for required roles+- `src/app/directives/has-role.directive.ts` — structural directive `*appHasRole="'RoleName'"`++**Astro:**+- `src/utils/authorization.ts` only (use directly in component scripts)++#### 4.3 Security Reminder++Add a comment at the top of the authorization utilities:++```typescript+// IMPORTANT: Client-side authorization is for UX only, not security.+// Server-side table permissions enforce actual access control.+// Always configure table permissions via /power-pages:integrate-webapi.+```++### Output++- `src/utils/authorization.ts` created with role-checking functions+- Framework-specific authorization components created (guards, directives, or wrapper components)+- Security reminder comments included----## Step 5: Implement Role-Based UI+## Phase 5: Create Auth UI++**Goal:** Create the login/logout button component and integrate it into the site's navigation.++### Actions++#### 5.1 Create Auth Button Component++Based on the detected framework, create a login/logout button component:++- **React**: `src/components/AuthButton.tsx` + `src/components/AuthButton.css`+- **Vue**: `src/components/AuthButton.vue`+- **Angular**: `src/app/components/auth-button/auth-button.component.ts` + template + styles+- **Astro**: `src/components/AuthButton.astro`++The component should:+- Show a "Sign In" button when the user is not authenticated+- Show the user's display name, avatar (initials-based), and a "Sign Out" button when authenticated+- Include a loading state while checking auth status+- Be styled to match the site's existing design (read existing CSS variables/theme)++#### 5.2 Integrate into Navigation++Find the site's navigation component and integrate the auth button:++1. Search for the nav/header component in the site's source code+2. Import the AuthButton component+3. Add it to the navigation bar (typically in the top-right area)-Identify components needing role-based visibility with user. Apply:+**Do NOT replace the existing navigation** — add the auth button alongside existing nav items.+#### 5.3 Git Commit++Stage and commit the auth files:++```powershell+git add -A+git commit -m "Add authentication service and auth UI component"+```++### Output++- Auth button component created for the detected framework+- Auth button integrated into the site's navigation+- Changes committed to git++---++## Phase 6: Implement Role-Based UI++**Goal:** Identify protected content areas and apply role-based authorization patterns to the site's components.++### Actions++#### 6.1 Identify Protected Content++Analyze the site's components to find content that should be role-gated:++- Admin-only sections (dashboards, settings)+- Authenticated-only content (profile, data views)+- Role-specific features (edit buttons, create forms)++Present findings to the user and confirm which areas to protect.++#### 6.2 Apply Authorization Patterns++Based on the user's choices, wrap the appropriate components:++**React example:**```tsx-<RequireRole roles={["Administrators"]}><AdminDashboard /></RequireRole>-<RequireAuth><MemberContent /></RequireAuth>-{hasRole("Administrators") && <EditButton />}+<RequireAuth fallback={<p>Please sign in to view this content.</p>}>+ <Dashboard />+</RequireAuth>++<RequireRole roles={['Administrators']} fallback={<p>Access denied.</p>}>+ <AdminPanel />+</RequireRole>+```++**Vue example:**+```vue+<div v-role="'Administrators'">+ <AdminPanel />+</div>```+**Angular example:**+```typescript+{ path: 'admin', component: AdminComponent, canActivate: [authGuard, roleGuard], data: { roles: ['Administrators'] } }+```++#### 6.3 Git Commit++Stage and commit:++```powershell+git add -A+git commit -m "Add role-based access control to site components"+```++### Output++- Protected content areas identified and confirmed with user+- Role-based authorization patterns applied to components+- Changes committed to git+----## Step 6: Build and Upload+## Phase 7: Verify Auth Setup++**Goal:** Validate that all auth files exist, the project builds, and the auth UI renders correctly.++### Actions++#### 7.1 Verify File Inventory++Confirm the following files were created:+- `src/types/powerPages.d.ts` — Power Pages type declarations+- `src/services/authService.ts` — Auth service with login/logout functions+- Framework-specific auth hook/composable (e.g., `src/hooks/useAuth.ts` for React)+- `src/utils/authorization.ts` — Role-checking utilities+- Framework-specific authorization components (e.g., `RequireAuth.tsx`, `RequireRole.tsx` for React)+- Auth button component (e.g., `src/components/AuthButton.tsx` for React)++Read each file and verify it contains the expected exports and functions:+- Auth service: `login`, `logout`, `getCurrentUser`, `isAuthenticated`, `fetchAntiForgeryToken`+- Authorization utils: `hasRole`, `hasAnyRole`, `hasAllRoles`, `getUserRoles`++#### 7.2 Verify Build++Run the project build to catch any import errors, type errors, or missing dependencies:```powershell-pac auth list # Show available environments+npm run build```-**Ask user which environment** to upload to using `AskUserQuestion` (show org names from auth list). Switch if needed: `pac auth select --index <n>`.+If the build fails, fix the issues before proceeding.++#### 7.3 Verify Auth UI Renders++Start the dev server and verify the auth button appears in the navigation:-**Create skill tracking setting, build, and upload:**```powershell-New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupAuth"-npm run build # Always build before upload-pac pages upload-code-site --rootPath "<PROJECT_ROOT>"+npm run dev```-See [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md) for helper function.+Use Playwright to navigate to the site and take a snapshot to confirm the auth button is visible:+- Navigate to `http://localhost:<port>`+- Take a browser snapshot+- Verify the auth button (Sign In / mock user) appears in the navigation area++If the auth button is not visible or the page has rendering errors, fix the issues.-**Required site setting**: `Authentication/Registration/ProfileRedirectEnabled` = `false` (redirects to home instead of profile after login). See [authentication-reference.md](./references/authentication-reference.md#site-settings).+### Output-**Verify**: Sign in → check user name displays → check roles → sign out.+- All auth files verified (present and contain expected exports)+- Project builds successfully+- Auth UI renders correctly in the browser++---++## Phase 8: Review & Deploy++**Goal:** Create required site settings, present a summary of all work, and prompt for deployment.++### Actions++#### 8.1 Create Site Setting++The site needs the `Authentication/Registration/ProfileRedirectEnabled` setting set to `false` to prevent Power Pages from redirecting users to a profile page after login (which doesn't exist in code sites).++Check if `.powerpages-site/site-settings/` exists. If it does, create the site setting file:++```powershell+node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js"+```++Create `.powerpages-site/site-settings/authentication-registration-profileredirectenabled.yml`:++```yaml+id: <UUID from generate-uuid.js>+name: Authentication/Registration/ProfileRedirectEnabled+value: false+```++#### 8.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 "SetupAuth"`.++#### 8.3 Present Summary++Present a summary of everything created:++| Component | File(s) | Status |+|-----------|---------|--------|+| Type Declarations | `src/types/powerPages.d.ts` | Created |+| Auth Service | `src/services/authService.ts` | Created |+| Auth Hook/Composable | `src/hooks/useAuth.ts` (or framework equivalent) | Created |+| Authorization Utils | `src/utils/authorization.ts` | Created |+| Auth Components | `RequireAuth`, `RequireRole` (or framework equivalent) | Created |+| Auth Button | `src/components/AuthButton.tsx` (or framework equivalent) | Created |+| Site Setting | `ProfileRedirectEnabled = false` | Created |++#### 8.4 Ask to Deploy++Use `AskUserQuestion`:++| Question | Options |+|----------|---------|+| Authentication and authorization are configured. To make login work, the site needs to be deployed. Would you like to deploy now? | Yes, deploy now (Recommended), No, I'll deploy later |++**If "Yes, deploy now"**: Invoke `/power-pages:deploy-site`.++**If "No"**: Remind the user:++> "Remember to deploy your site using `/power-pages:deploy-site` when you're ready. Authentication will not work until the site is deployed with the new site settings."++#### 8.5 Post-Deploy Notes++After deployment (or if skipped), remind the user:++- **Test on deployed site**: Auth only works on the deployed Power Pages site, not on `localhost`+- **Entra ID configuration**: The site's identity provider must be configured in the Power Pages admin center to use Microsoft Entra ID+- **Assign web roles**: Users must be assigned appropriate web roles in the Power Pages admin center+- **Table permissions**: Client-side auth checks are for UX only — configure server-side table permissions via `/power-pages:integrate-webapi` for actual data security+- **Local development**: The auth service includes mock data for testing on localhost — remove or disable before production++### Output++- `ProfileRedirectEnabled` site setting created+- Full summary presented to user+- Deployment prompted (or skipped with reminder)+- Post-deploy guidance provided++---++## Important Notes++### Progress Tracking++Use `TaskCreate` at the start to track each phase:++| Task | Description |+|------|-------------|+| Phase 1 | Check Prerequisites — verify site, framework, deployment, web roles |+| Phase 2 | Plan — gather requirements and get user approval |+| Phase 3 | Create Auth Service — auth service, types, framework hook/composable |+| Phase 4 | Create Authorization Utils — role-checking functions and components |+| Phase 5 | Create Auth UI — AuthButton component and navigation integration |+| Phase 6 | Implement Role-Based UI — apply authorization patterns to components |+| Phase 7 | Verify Auth Setup — validate files exist, build succeeds, auth UI renders |+| Phase 8 | Review & Deploy — site setting, summary, deployment prompt |++Update each task with `TaskUpdate` as phases are completed.++### Key Decision Points++- **Phase 1.3**: Deploy now or stop? (site must be deployed before auth setup)+- **Phase 1.4**: Create web roles now or skip? (roles needed for authorization)+- **Phase 1.5**: Overwrite or skip existing auth files?+- **Phase 2.1**: Which auth features to include? (login/logout, role-based, or both)+- **Phase 2.2**: Approve plan or request changes?+- **Phase 6.1**: Which content areas to protect with role-based access?+- **Phase 8.3**: Deploy now or later?++----Update memory-bank.md. Cleanup per [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md).+**Begin with Phase 1: Check Prerequisites**diff --git a/plugins/power-pages/skills/setup-auth/references/authentication-reference.md b/plugins/power-pages/skills/setup-auth/references/authentication-reference.mdindex 8ce2293ea..25e5ca599 100644--- a/plugins/power-pages/skills/setup-auth/references/authentication-reference.md+++ b/plugins/power-pages/skills/setup-auth/references/authentication-reference.md@@ -1,556 +1,408 @@# Authentication Reference-## Login Flow+This document provides the complete implementation patterns for Power Pages authentication using Microsoft Entra ID.-1. Fetch anti-forgery token from `/_layout/tokenhtml`-2. POST to `/Account/Login/ExternalLogin` with token, provider, returnUrl-3. User authenticates via AAD → session established-4. User info available in `window.Microsoft.Dynamic365.Portal.User`-5. Logout: redirect to `/Account/Login/LogOff`+## How Power Pages Authentication Works-## TypeScript Declarations+Power Pages authentication is **server-side** using session cookies. There is no client-side token management.-**File: `src/types/powerPages.d.ts`**+### Login Flow++1. Fetch an anti-forgery token from `/_layout/tokenhtml`+2. POST a form to `/Account/Login/ExternalLogin` with the token, provider URL, and return URL+3. Power Pages redirects the user to Microsoft Entra ID for authentication+4. After successful authentication, the session is established via cookies+5. User information becomes available in `window.Microsoft.Dynamic365.Portal.User`++### Logout Flow++1. Redirect the user to `/Account/Login/LogOff`+2. Power Pages clears the session cookies+3. `window.Microsoft.Dynamic365.Portal.User` becomes `undefined`++---++## Type Declarations++Create `src/types/powerPages.d.ts`:```typescript/**- * Power Pages Portal User Interface- * Available at window.Microsoft.Dynamic365.Portal.User when user is logged in+ * Power Pages portal user object.+ * Available at window.Microsoft.Dynamic365.Portal.User when authenticated.*/export interface PowerPagesUser {- /** Login username */userName: string;- /** User's first name */firstName: string;- /** User's last name */lastName: string;- /** User's email address */email: string;- /** Dataverse Contact ID (GUID) */contactId: string;- /** Array of web role names assigned to the user */userRoles: string[];}/**- * Power Pages Portal Configuration- * Available at window.Microsoft.Dynamic365.Portal+ * Power Pages portal configuration object.+ * Available at window.Microsoft.Dynamic365.Portal.*/export interface PowerPagesPortal {- /** Current user information (populated when logged in) */- User: PowerPagesUser;- /** Portal version */+ User: PowerPagesUser | undefined;version: string;- /** Portal type */type: string;- /** Portal ID */id: string;- /** Geographic region */geo: string;- /** Azure AD Tenant ID */tenant: string;- /** Correlation ID for debugging */correlationId: string;- /** Organization environment ID */orgEnvironmentId: string;- /** Organization ID */orgId: string;- /** Production or Trial indicator */portalProductionOrTrialType: string;- /** Telemetry enabled flag */- isTelemetryEnabled: string;- /** Instrumentation settings */- InstrumentationSettings: {- instrumentationKey: string;- collectorEndpoint: string;- };- /** Timer profile for batching */- timerProfileForBatching: string;- /** Active languages */- activeLanguages: string[];- /** Client API enabled flag */- isClientApiEnabled: string;+ isTelemetryEnabled: boolean;+ InstrumentationSettings: Record<string, unknown>;+ timerProfileForBatching: Record<string, unknown>;+ activeLanguages: unknown[];+ isClientApiEnabled: boolean;}-/**- * Microsoft namespace on window object- */-export interface MicrosoftNamespace {+interface MicrosoftNamespace {Dynamic365: {Portal: PowerPagesPortal;};}-/**- * Extend Window interface- */declare global {interface Window {- Microsoft?: MicrosoftNamespace;+ Microsoft: MicrosoftNamespace;}}--export {};```-## Authentication Service+----**File: `src/services/authService.ts`**+## Auth Service++Create `src/services/authService.ts`:```typescriptimport type { PowerPagesUser } from '../types/powerPages';-/**- * Authentication state- */-export interface AuthState {- isAuthenticated: boolean;- user: PowerPagesUser | null;- isLoading: boolean;-}+const isDevelopment =+ typeof window !== 'undefined' &&+ (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');++// Mock user for local development — auth only works on deployed Power Pages sites+const MOCK_USER: PowerPagesUser = {+ userName: '[email protected]',+ firstName: 'Dev',+ lastName: 'User',+ email: '[email protected]',+ contactId: '00000000-0000-0000-0000-000000000001',+ userRoles: ['Authenticated Users', 'Administrators'],+};/**- * Get the current Power Pages portal user- * Returns null if not authenticated or portal object not available+ * Returns the currently logged-in user, or undefined if not authenticated.*/-export function getCurrentUser(): PowerPagesUser | null {- try {- const portalUser = window.Microsoft?.Dynamic365?.Portal?.User;-- // Check if user is actually logged in (userName will be empty if not)- if (portalUser && portalUser.userName) {- return {- userName: portalUser.userName || '',- firstName: portalUser.firstName || '',- lastName: portalUser.lastName || '',- email: portalUser.email || '',- contactId: portalUser.contactId || '',- userRoles: portalUser.userRoles || [],- };- }-- return null;- } catch (error) {- console.warn('[Auth] Failed to get current user:', error);- return null;- }+export function getCurrentUser(): PowerPagesUser | undefined {+ if (isDevelopment) return MOCK_USER;+ return window.Microsoft?.Dynamic365?.Portal?.User;}/**- * Check if user is currently authenticated+ * Returns true if a user is currently logged in.*/export function isAuthenticated(): boolean {const user = getCurrentUser();- return user !== null && user.userName !== '';+ return !!user?.userName;}/**- * Get the tenant ID from the portal configuration+ * Returns the Entra ID tenant ID from the portal configuration.*/-export function getTenantId(): string {- try {- return window.Microsoft?.Dynamic365?.Portal?.tenant || '';- } catch {- return '';- }+export function getTenantId(): string | undefined {+ if (isDevelopment) return '00000000-0000-0000-0000-000000000000';+ return window.Microsoft?.Dynamic365?.Portal?.tenant;}/**- * Fetch the anti-forgery token required for login- * This token prevents CSRF attacks on the login form+ * Fetches the anti-forgery token required for the login form POST.+ * The token is embedded in an HTML response from /_layout/tokenhtml.*/-async function fetchAntiForgeryToken(): Promise<string> {- try {- const tokenEndpoint = '/_layout/tokenhtml';- const response = await fetch(tokenEndpoint);-- if (!response.ok) {- throw new Error(`Failed to fetch token: ${response.status}`);- }-- const tokenResponse = await response.text();-- // Parse the token from the HTML response- // Response format: <input name="__RequestVerificationToken" type="hidden" value="TOKEN_VALUE" />- const valueString = 'value="';- const terminalString = '" />';- const valueIndex = tokenResponse.indexOf(valueString);-- if (valueIndex === -1) {- throw new Error('Token not found in response');- }-- const token = tokenResponse.substring(- valueIndex + valueString.length,- tokenResponse.indexOf(terminalString, valueIndex)- );-- return token;- } catch (error) {- console.error('[Auth] Failed to fetch anti-forgery token:', error);- throw error;+export async function fetchAntiForgeryToken(): Promise<string> {+ const response = await fetch('/_layout/tokenhtml');+ const html = await response.text();+ const match = html.match(/value="([^"]+)"/);+ if (!match) {+ throw new Error('Failed to extract anti-forgery token from /_layout/tokenhtml');}+ return match[1];}/**- * Initiate login flow- * Creates a form submission to the Power Pages login endpoint- * This will redirect to Azure AD for authentication+ * Initiates login by posting a form to the Power Pages external login endpoint.+ * The browser will redirect to Microsoft Entra ID for authentication.*- * @param returnUrl - URL to redirect to after successful login (default: current page)+ * @param returnUrl - URL to return to after successful login (defaults to current page)*/export async function login(returnUrl?: string): Promise<void> {- try {- // Get anti-forgery token- const token = await fetchAntiForgeryToken();-- // Get tenant ID for AAD login- const tenantId = getTenantId();-- if (!tenantId) {- throw new Error('Tenant ID not available. Ensure site is loaded from Power Pages.');- }-- // Create form for submission- const form = document.createElement('form');- form.method = 'POST';- form.action = '/Account/Login/ExternalLogin';-- // Anti-forgery token- const tokenInput = document.createElement('input');- tokenInput.type = 'hidden';- tokenInput.name = '__RequestVerificationToken';- tokenInput.value = token;- form.appendChild(tokenInput);-- // Provider (Azure AD)- const providerInput = document.createElement('input');- providerInput.type = 'hidden';- providerInput.name = 'provider';- providerInput.value = `https://login.windows.net/${tenantId}/`;- form.appendChild(providerInput);-- // Return URL- const returnUrlInput = document.createElement('input');- returnUrlInput.type = 'hidden';- returnUrlInput.name = 'returnUrl';- returnUrlInput.value = returnUrl || window.location.pathname;- form.appendChild(returnUrlInput);-- // Submit the form- document.body.appendChild(form);- form.submit();- } catch (error) {- console.error('[Auth] Login failed:', error);- throw error;+ if (isDevelopment) {+ console.warn('[Auth] Login is not available in local development. Using mock user.');+ window.location.reload();+ return;+ }++ const token = await fetchAntiForgeryToken();+ const tenantId = getTenantId();++ const form = document.createElement('form');+ form.method = 'POST';+ form.action = '/Account/Login/ExternalLogin';++ const fields: Record<string, string> = {+ __RequestVerificationToken: token,+ provider: `https://login.windows.net/${tenantId}/`,+ returnUrl: returnUrl || window.location.pathname,+ };++ for (const [name, value] of Object.entries(fields)) {+ const input = document.createElement('input');+ input.type = 'hidden';+ input.name = name;+ input.value = value;+ form.appendChild(input);}++ document.body.appendChild(form);+ form.submit();}/**- * Logout the current user- * Redirects to the Power Pages logout endpoint+ * Logs the user out by redirecting to the Power Pages logout endpoint.*- * @param returnUrl - URL to redirect to after logout (default: home page)+ * @param returnUrl - URL to return to after logout (defaults to site root)*/-export function logout(returnUrl: string = '/'): void {- const encodedReturnUrl = encodeURIComponent(returnUrl);- window.location.href = `/Account/Login/LogOff?returnUrl=${encodedReturnUrl}`;+export function logout(returnUrl?: string): void {+ if (isDevelopment) {+ console.warn('[Auth] Logout is not available in local development.');+ window.location.reload();+ return;+ }++ const target = returnUrl || '/';+ window.location.href = `/Account/Login/LogOff?returnUrl=${encodeURIComponent(target)}`;}/**- * Get user's display name (full name or username)+ * Returns the user's display name (full name if available, otherwise userName).*/export function getUserDisplayName(): string {const user = getCurrentUser();-- if (!user) {- return '';- }-- // Prefer full name, fall back to username+ if (!user) return '';const fullName = [user.firstName, user.lastName].filter(Boolean).join(' ');return fullName || user.userName;}/**- * Get user's initials for avatar display+ * Returns the user's initials for avatar display.*/export function getUserInitials(): string {const user = getCurrentUser();-- if (!user) {- return '';- }-- const firstName = user.firstName || '';- const lastName = user.lastName || '';-- if (firstName && lastName) {- return `${firstName[0]}${lastName[0]}`.toUpperCase();+ if (!user) return '';+ if (user.firstName && user.lastName) {+ return `${user.firstName[0]}${user.lastName[0]}`.toUpperCase();}-- if (user.userName) {- return user.userName.substring(0, 2).toUpperCase();- }-- return '';+ return (user.userName?.[0] || '').toUpperCase();}```-## React Components+----### Auth Button Component+## Framework-Specific Patterns-**File: `src/components/AuthButton.tsx`**+### React: useAuth Hook-```tsx-import { useState, useEffect } from 'react';+Create `src/hooks/useAuth.ts`:++```typescript+import { useState, useEffect, useCallback } from 'react';+import type { PowerPagesUser } from '../types/powerPages';import {getCurrentUser,- login,- logout,+ isAuthenticated as checkAuth,getUserDisplayName,getUserInitials,- type PowerPagesUser+ login as authLogin,+ logout as authLogout,} from '../services/authService';-interface AuthButtonProps {- /** CSS class name for styling */- className?: string;- /** Show user avatar/initials when logged in */- showAvatar?: boolean;- /** Text for sign in button */- signInText?: string;- /** Text for sign out button */- signOutText?: string;+interface UseAuthReturn {+ user: PowerPagesUser | undefined;+ isAuthenticated: boolean;+ isLoading: boolean;+ displayName: string;+ initials: string;+ login: (returnUrl?: string) => Promise<void>;+ logout: (returnUrl?: string) => void;+ refresh: () => void;}-export function AuthButton({- className = '',- showAvatar = true,- signInText = 'Sign In',- signOutText = 'Sign Out'-}: AuthButtonProps) {- const [user, setUser] = useState<PowerPagesUser | null>(null);+export function useAuth(): UseAuthReturn {+ const [user, setUser] = useState<PowerPagesUser | undefined>(undefined);const [isLoading, setIsLoading] = useState(true);- useEffect(() => {- // Check authentication state on mount- const currentUser = getCurrentUser();- setUser(currentUser);+ const refresh = useCallback(() => {+ setUser(getCurrentUser());setIsLoading(false);}, []);- const handleLogin = async () => {- try {- setIsLoading(true);- await login();- // Note: Page will redirect, so we don't need to handle success- } catch (error) {- console.error('Login error:', error);- setIsLoading(false);- }- };+ useEffect(() => {+ refresh();+ }, [refresh]);- const handleLogout = () => {- logout();+ return {+ user,+ isAuthenticated: checkAuth(),+ isLoading,+ displayName: getUserDisplayName(),+ initials: getUserInitials(),+ login: authLogin,+ logout: authLogout,+ refresh,};+}+```++### React: AuthButton Component++Create `src/components/AuthButton.tsx`:++```tsx+import { useAuth } from '../hooks/useAuth';+import './AuthButton.css';++export function AuthButton() {+ const { isAuthenticated, isLoading, displayName, initials, login, logout } = useAuth();if (isLoading) {- return (- <div className={`auth-button auth-button--loading ${className}`}>- <span className="auth-button__spinner" />- </div>- );+ return <div className="auth-button auth-loading"><span className="auth-spinner" /></div>;}- if (user) {+ if (!isAuthenticated) {return (- <div className={`auth-button auth-button--authenticated ${className}`}>- {showAvatar && (- <div className="auth-button__avatar" title={getUserDisplayName()}>- {getUserInitials()}- </div>- )}- <span className="auth-button__name">{getUserDisplayName()}</span>- <button- type="button"- className="auth-button__logout"- onClick={handleLogout}- >- {signOutText}- </button>- </div>+ <button className="auth-button auth-sign-in" onClick={() => login()}>+ Sign In+ </button>);}return (- <button- type="button"- className={`auth-button auth-button--login ${className}`}- onClick={handleLogin}- >- {signInText}- </button>+ <div className="auth-button auth-signed-in">+ <span className="auth-avatar">{initials}</span>+ <span className="auth-name">{displayName}</span>+ <button className="auth-sign-out" onClick={() => logout()}>+ Sign Out+ </button>+ </div>);}```-### Auth Button Styles--**File: `src/components/AuthButton.css`**+Create `src/components/AuthButton.css`:```css.auth-button {- display: inline-flex;+ display: flex;align-items: center;gap: 0.5rem;}-.auth-button--loading {- opacity: 0.7;-}--.auth-button__spinner {- width: 1rem;- height: 1rem;- border: 2px solid currentColor;- border-top-color: transparent;- border-radius: 50%;- animation: spin 0.6s linear infinite;+.auth-sign-in {+ padding: 0.5rem 1rem;+ border: 1px solid currentColor;+ border-radius: 0.375rem;+ background: transparent;+ color: inherit;+ cursor: pointer;+ font-size: 0.875rem;+ transition: opacity 0.2s;}-@keyframes spin {- to { transform: rotate(360deg); }+.auth-sign-in:hover {+ opacity: 0.8;}-.auth-button--authenticated {+.auth-signed-in {display: flex;align-items: center;- gap: 0.75rem;+ gap: 0.5rem;}-.auth-button__avatar {+.auth-avatar {+ display: flex;+ align-items: center;+ justify-content: center;width: 2rem;height: 2rem;border-radius: 50%;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);- color: white;- display: flex;- align-items: center;- justify-content: center;+ color: #fff;font-size: 0.75rem;font-weight: 600;}-.auth-button__name {- font-weight: 500;+.auth-name {+ font-size: 0.875rem;}-.auth-button__logout,-.auth-button--login {- padding: 0.5rem 1rem;- border: 1px solid currentColor;- border-radius: 0.25rem;+.auth-sign-out {+ padding: 0.25rem 0.5rem;+ border: none;background: transparent;+ color: inherit;cursor: pointer;- font-size: 0.875rem;- transition: all 0.2s;+ font-size: 0.75rem;+ opacity: 0.7;+ transition: opacity 0.2s;}-.auth-button__logout:hover,-.auth-button--login:hover {- background: rgba(0, 0, 0, 0.05);+.auth-sign-out:hover {+ opacity: 1;}-```-## React Hook--**File: `src/hooks/useAuth.ts`**--```typescript-import { useState, useEffect, useCallback } from 'react';-import {- getCurrentUser,- isAuthenticated as checkIsAuthenticated,- login as performLogin,- logout as performLogout,- getUserDisplayName,- type PowerPagesUser-} from '../services/authService';--interface UseAuthReturn {- /** Current user or null if not authenticated */- user: PowerPagesUser | null;- /** Whether user is authenticated */- isAuthenticated: boolean;- /** Whether auth state is still loading */- isLoading: boolean;- /** User's display name */- displayName: string;- /** Initiate login flow */- login: (returnUrl?: string) => Promise<void>;- /** Logout user */- logout: (returnUrl?: string) => void;- /** Refresh auth state */- refresh: () => void;+.auth-spinner {+ display: inline-block;+ width: 1rem;+ height: 1rem;+ border: 2px solid currentColor;+ border-right-color: transparent;+ border-radius: 50%;+ animation: auth-spin 0.6s linear infinite;}-export function useAuth(): UseAuthReturn {- const [user, setUser] = useState<PowerPagesUser | null>(null);- const [isLoading, setIsLoading] = useState(true);-- const refresh = useCallback(() => {- const currentUser = getCurrentUser();- setUser(currentUser);- setIsLoading(false);- }, []);-- useEffect(() => {- refresh();- }, [refresh]);-- const login = useCallback(async (returnUrl?: string) => {- setIsLoading(true);- await performLogin(returnUrl);- }, []);-- const logout = useCallback((returnUrl?: string) => {- performLogout(returnUrl);- }, []);-- return {- user,- isAuthenticated: user !== null,- isLoading,- displayName: getUserDisplayName(),- login,- logout,- refresh,- };+@keyframes auth-spin {+ to { transform: rotate(360deg); }}```-## Vue 3 Composition API+### Vue 3: useAuth Composable-**File: `src/composables/useAuth.ts`**+Create `src/composables/useAuth.ts`:```typescriptimport { ref, computed, onMounted } from 'vue';+import type { PowerPagesUser } from '../types/powerPages';import {getCurrentUser,- login as performLogin,- logout as performLogout,+ isAuthenticated as checkAuth,getUserDisplayName,getUserInitials,- type PowerPagesUser+ login as authLogin,+ logout as authLogout,} from '../services/authService';export function useAuth() {- const user = ref<PowerPagesUser | null>(null);+ const user = ref<PowerPagesUser | undefined>(undefined);const isLoading = ref(true);- const isAuthenticated = computed(() => user.value !== null);+ const isAuthenticated = computed(() => checkAuth());const displayName = computed(() => getUserDisplayName());const initials = computed(() => getUserInitials());@@ -559,15 +411,6 @@ export function useAuth() {isLoading.value = false;}- async function login(returnUrl?: string) {- isLoading.value = true;- await performLogin(returnUrl);- }-- function logout(returnUrl?: string) {- performLogout(returnUrl);- }-onMounted(() => {refresh();});@@ -578,318 +421,108 @@ export function useAuth() {isLoading,displayName,initials,- login,- logout,+ login: authLogin,+ logout: authLogout,refresh,};}```-## Angular Service+### Angular: AuthService-**File: `src/app/services/auth.service.ts`**+Create `src/app/services/auth.service.ts`:```typescriptimport { Injectable } from '@angular/core';-import { BehaviorSubject, Observable } from 'rxjs';--interface PowerPagesUser {- userName: string;- firstName: string;- lastName: string;- email: string;- contactId: string;- userRoles: string[];-}+import { BehaviorSubject } from 'rxjs';+import type { PowerPagesUser } from '../../types/powerPages';+import {+ getCurrentUser,+ isAuthenticated as checkAuth,+ getUserDisplayName,+ getUserInitials,+ login as authLogin,+ logout as authLogout,+} from '../../services/authService';-@Injectable({- providedIn: 'root'-})+@Injectable({ providedIn: 'root' })export class AuthService {- private userSubject = new BehaviorSubject<PowerPagesUser | null>(null);+ private userSubject = new BehaviorSubject<PowerPagesUser | undefined>(undefined);private loadingSubject = new BehaviorSubject<boolean>(true);- user$: Observable<PowerPagesUser | null> = this.userSubject.asObservable();- isLoading$: Observable<boolean> = this.loadingSubject.asObservable();+ user$ = this.userSubject.asObservable();+ isLoading$ = this.loadingSubject.asObservable();constructor() {this.refresh();}- get currentUser(): PowerPagesUser | null {- return this.userSubject.value;- }-get isAuthenticated(): boolean {- return this.currentUser !== null;+ return checkAuth();}- refresh(): void {- try {- const portalUser = (window as any).Microsoft?.Dynamic365?.Portal?.User;-- if (portalUser && portalUser.userName) {- this.userSubject.next({- userName: portalUser.userName || '',- firstName: portalUser.firstName || '',- lastName: portalUser.lastName || '',- email: portalUser.email || '',- contactId: portalUser.contactId || '',- userRoles: portalUser.userRoles || [],- });- } else {- this.userSubject.next(null);- }- } catch {- this.userSubject.next(null);- }-- this.loadingSubject.next(false);+ get displayName(): string {+ return getUserDisplayName();}- async login(returnUrl?: string): Promise<void> {- this.loadingSubject.next(true);-- const token = await this.fetchAntiForgeryToken();- const tenantId = (window as any).Microsoft?.Dynamic365?.Portal?.tenant || '';-- const form = document.createElement('form');- form.method = 'POST';- form.action = '/Account/Login/ExternalLogin';-- this.addHiddenField(form, '__RequestVerificationToken', token);- this.addHiddenField(form, 'provider', `https://login.windows.net/${tenantId}/`);- this.addHiddenField(form, 'returnUrl', returnUrl || window.location.pathname);-- document.body.appendChild(form);- form.submit();+ get initials(): string {+ return getUserInitials();}- logout(returnUrl: string = '/'): void {- window.location.href = `/Account/Login/LogOff?returnUrl=${encodeURIComponent(returnUrl)}`;+ login(returnUrl?: string): Promise<void> {+ return authLogin(returnUrl);}- private async fetchAntiForgeryToken(): Promise<string> {- const response = await fetch('/_layout/tokenhtml');- const text = await response.text();-- const valueString = 'value="';- const terminalString = '" />';- const valueIndex = text.indexOf(valueString);-- return text.substring(- valueIndex + valueString.length,- text.indexOf(terminalString, valueIndex)- );+ logout(returnUrl?: string): void {+ authLogout(returnUrl);}- private addHiddenField(form: HTMLFormElement, name: string, value: string): void {- const input = document.createElement('input');- input.type = 'hidden';- input.name = name;- input.value = value;- form.appendChild(input);+ refresh(): void {+ this.userSubject.next(getCurrentUser());+ this.loadingSubject.next(false);}}```-## Vanilla JavaScript+### Vanilla JavaScript (Astro)-**File: `src/auth.js`**+For Astro projects, use `src/services/authService.ts` directly in component scripts. No additional wrapper needed.-```javascript-/**- * Power Pages Authentication Module- * Framework-agnostic authentication utilities- */+----/**- * Get the current user from Power Pages portal object- * @returns {Object|null} User object or null if not authenticated- */-function getCurrentUser() {- try {- const portalUser = window.Microsoft?.Dynamic365?.Portal?.User;-- if (portalUser && portalUser.userName) {- return {- userName: portalUser.userName || '',- firstName: portalUser.firstName || '',- lastName: portalUser.lastName || '',- email: portalUser.email || '',- contactId: portalUser.contactId || '',- userRoles: portalUser.userRoles || [],- };- }-- return null;- } catch (error) {- console.warn('[Auth] Failed to get current user:', error);- return null;- }-}--/**- * Check if user is authenticated- * @returns {boolean}- */-function isAuthenticated() {- const user = getCurrentUser();- return user !== null && user.userName !== '';-}--/**- * Fetch anti-forgery token- * @returns {Promise<string>}- */-async function fetchAntiForgeryToken() {- const response = await fetch('/_layout/tokenhtml');- const text = await response.text();-- const valueString = 'value="';- const terminalString = '" />';- const valueIndex = text.indexOf(valueString);-- return text.substring(- valueIndex + valueString.length,- text.indexOf(terminalString, valueIndex)- );-}--/**- * Initiate login flow- * @param {string} [returnUrl] - URL to redirect to after login- */-async function login(returnUrl) {- const token = await fetchAntiForgeryToken();- const tenantId = window.Microsoft?.Dynamic365?.Portal?.tenant || '';-- const form = document.createElement('form');- form.method = 'POST';- form.action = '/Account/Login/ExternalLogin';-- const fields = {- '__RequestVerificationToken': token,- 'provider': `https://login.windows.net/${tenantId}/`,- 'returnUrl': returnUrl || window.location.pathname- };+## Site Settings- Object.entries(fields).forEach(([name, value]) => {- const input = document.createElement('input');- input.type = 'hidden';- input.name = name;- input.value = value;- form.appendChild(input);- });+### Required: Disable Profile Redirect- document.body.appendChild(form);- form.submit();-}+Power Pages code sites do not have a built-in profile page. After login, Power Pages attempts to redirect to `/profile`, which returns a 404 on code sites. Disable this with a site setting:-/**- * Logout user- * @param {string} [returnUrl='/'] - URL to redirect to after logout- */-function logout(returnUrl = '/') {- window.location.href = `/Account/Login/LogOff?returnUrl=${encodeURIComponent(returnUrl)}`;-}+**Site setting name:** `Authentication/Registration/ProfileRedirectEnabled`+**Value:** `false`-// Export for module usage-export { getCurrentUser, isAuthenticated, login, logout };+Create as a YAML file in `.powerpages-site/site-settings/`:-// Also expose globally for non-module usage-window.PowerPagesAuth = { getCurrentUser, isAuthenticated, login, logout };+```yaml+id: <generated-uuid>+name: Authentication/Registration/ProfileRedirectEnabled+value: false```-## Site Settings+### Other Useful Settings-When implementing authentication, configure these site settings in Power Pages to customize the login behavior.--### Disable Profile Page Redirect--**IMPORTANT**: By default, Power Pages redirects users to the built-in profile page (`/profile`) after login. For code sites (SPAs), you should disable this so users are redirected to your app's home page instead.--| Setting Name | Value | Description |-|--------------|-------|-------------|-| `Authentication/Registration/ProfileRedirectEnabled` | `false` | Disables redirect to profile page after login |--#### How to Configure--1. **Via Power Pages Admin Center**:- - Go to **Set up** > **Site Settings**- - Click **+ New setting**- - Name: `Authentication/Registration/ProfileRedirectEnabled`- - Value: `false`- - Click **Save**--2. **Via PAC CLI**:- ```powershell- # Create site setting using PAC CLI- pac paportal download --path ./portal-data --modelVersion 2- # Add the setting to the site settings file and upload- pac paportal upload --path ./portal-data- ```--3. **Via Dataverse Web API**:- ```typescript- // Create site setting record- await fetch(`${dataverseUrl}/api/data/v9.2/adx_sitesettings`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'Authorization': `Bearer ${accessToken}`- },- body: JSON.stringify({- 'adx_name': 'Authentication/Registration/ProfileRedirectEnabled',- 'adx_value': 'false',- '[email protected]': `/adx_websites(${websiteId})`- })- });- ```--> **Note**: After setting this, users will be redirected to the `returnUrl` specified in the login form (see `login()` function in the Authentication Service section above), which defaults to the current page or home page.--### Other Useful Authentication Settings--| Setting Name | Value | Description |-|--------------|-------|-------------|-| `Authentication/Registration/Enabled` | `true` | Enable/disable registration |-| `Authentication/Registration/OpenRegistrationEnabled` | `true`/`false` | Allow open registration |-| `Authentication/Registration/InvitationEnabled` | `true`/`false` | Require invitation for registration |-| `Authentication/Registration/LocalLoginEnabled` | `true`/`false` | Enable local account login |+| Setting | Value | Description |+|---------|-------|-------------|+| `Authentication/Registration/Enabled` | `true` | Enable user registration |+| `Authentication/Registration/OpenRegistrationEnabled` | `true`/`false` | Allow self-registration |+| `Authentication/Registration/InvitationEnabled` | `true`/`false` | Allow invitation-based registration |+| `Authentication/Registration/LocalLoginEnabled` | `false` | Disable local (username/password) login when using Entra ID only |-## Important Notes+These can be configured via the Power Pages admin center, PAC CLI, or Dataverse Web API as needed.-### Local Development+----- Authentication **only works** when the site is served from Power Pages-- During local development (`npm run dev`), the `window.Microsoft.Dynamic365.Portal` object will not be available-- Create mock data for local testing:--```typescript-// src/mocks/portalUser.ts (for development only)-if (import.meta.env.DEV) {- (window as any).Microsoft = {- Dynamic365: {- Portal: {- User: {- userName: '[email protected]',- firstName: 'Dev',- lastName: 'User',- email: '[email protected]',- contactId: '00000000-0000-0000-0000-000000000000',- userRoles: ['Authenticated Users', 'Administrators'],- },- tenant: 'your-tenant-id',- },- },- };-}-```--### Security Considerations+## Important Notes-1. **Server-side validation**: Always validate permissions on the server (via table permissions)-2. **Client-side is cosmetic**: Role checks in the UI are for UX only, not security-3. **Anti-forgery tokens**: Required for all POST operations to prevent CSRF attacks-4. **Session timeout**: Handle cases where session expires during usage+- **Auth only works on deployed sites**: The `/_layout/tokenhtml` endpoint and `window.Microsoft.Dynamic365.Portal` object are only available when the site is served from Power Pages, not during local `npm run dev`.+- **Mock data for development**: The auth service includes a mock user pattern for local development. The mock user has configurable roles so developers can test role-based UI locally.+- **Security**: Always validate permissions server-side via table permissions. Client-side auth checks are for UX only — a direct API call bypasses all client-side checks.+- **Entra ID configuration**: The identity provider must be configured in the Power Pages admin center. This skill creates the client-side code but does not configure the identity provider itself.diff --git a/plugins/power-pages/skills/setup-auth/references/authorization-reference.md b/plugins/power-pages/skills/setup-auth/references/authorization-reference.mdindex bb589fe55..e7e1a0820 100644--- a/plugins/power-pages/skills/setup-auth/references/authorization-reference.md+++ b/plugins/power-pages/skills/setup-auth/references/authorization-reference.md@@ -1,444 +1,190 @@# Authorization Reference-User roles available at `window.Microsoft.Dynamic365.Portal.User.userRoles` (array of role names).+This document provides the complete implementation patterns for role-based authorization in Power Pages code sites.-**Built-in roles**: Anonymous Users, Authenticated Users, Administrators. Custom roles via Portal Management app.+## Core Authorization Utilities-## Authorization Utilities--**File: `src/utils/authorization.ts`**+Create `src/utils/authorization.ts`:```typescript-import { getCurrentUser } from '../services/authService';+// IMPORTANT: Client-side authorization is for UX only, not security.+// Server-side table permissions enforce actual access control.+// Always configure table permissions via /power-pages:integrate-webapi.++import { getCurrentUser, isAuthenticated as checkAuthenticated } from '../services/authService';/**- * Get all roles for the current user- * @returns Array of role names (empty if not authenticated)+ * Returns the current user's web roles as an array of strings.*/export function getUserRoles(): string[] {const user = getCurrentUser();- return user?.userRoles || [];+ return user?.userRoles ?? [];}/**- * Check if user has a specific role- * @param roleName - Role name to check (case-insensitive)+ * Checks if the current user has a specific role (case-insensitive).*/export function hasRole(roleName: string): boolean {- const roles = getUserRoles();- const normalizedRole = roleName.toLowerCase();- return roles.some(role => role.toLowerCase() === normalizedRole);+ return getUserRoles().some(+ (role) => role.toLowerCase() === roleName.toLowerCase()+ );}/**- * Check if user has ANY of the specified roles- * @param roleNames - Array of role names to check+ * Checks if the current user has ANY of the specified roles.*/export function hasAnyRole(roleNames: string[]): boolean {- return roleNames.some(role => hasRole(role));+ return roleNames.some((role) => hasRole(role));}/**- * Check if user has ALL of the specified roles- * @param roleNames - Array of role names to check+ * Checks if the current user has ALL of the specified roles.*/export function hasAllRoles(roleNames: string[]): boolean {- return roleNames.every(role => hasRole(role));+ return roleNames.every((role) => hasRole(role));}/**- * Check if user is authenticated (has any role other than Anonymous)+ * Re-export isAuthenticated for convenience.*/export function isAuthenticated(): boolean {- const user = getCurrentUser();- return user !== null && user.userName !== '';+ return checkAuthenticated();}/**- * Check if user is an administrator+ * Checks if the current user has the Administrators role.*/export function isAdmin(): boolean {return hasRole('Administrators');}/**- * Check if user has elevated permissions (admin or specific roles)- * @param additionalRoles - Additional roles that grant elevated access+ * Checks if the user has elevated access (admin or specified additional roles).*/export function hasElevatedAccess(additionalRoles: string[] = []): boolean {- return hasAnyRole(['Administrators', ...additionalRoles]);+ return isAdmin() || hasAnyRole(additionalRoles);}```-## React Components for Conditional Rendering+----### RequireAuth Component+## React Components-Show content only to authenticated users.+### RequireAuth-**File: `src/components/RequireAuth.tsx`**+Create `src/components/RequireAuth.tsx`:```tsx-import { ReactNode } from 'react';-import { isAuthenticated } from '../utils/authorization';+import type { ReactNode } from 'react';+import { useAuth } from '../hooks/useAuth';interface RequireAuthProps {- /** Content to show when authenticated */children: ReactNode;- /** Content to show when not authenticated (optional) */fallback?: ReactNode;- /** Whether to show a login prompt as fallback */- showLoginPrompt?: boolean;}-export function RequireAuth({- children,- fallback = null,- showLoginPrompt = false-}: RequireAuthProps) {- if (isAuthenticated()) {- return <>{children}</>;- }-- if (showLoginPrompt) {- return (- <div className="auth-required">- <p>Please sign in to access this content.</p>- <button onClick={() => import('../services/authService').then(m => m.login())}>- Sign In- </button>- </div>- );- }+/**+ * Renders children only when the user is authenticated.+ * Shows the fallback (or nothing) when not authenticated.+ */+export function RequireAuth({ children, fallback }: RequireAuthProps) {+ const { isAuthenticated, isLoading } = useAuth();- return <>{fallback}</>;+ if (isLoading) return null;+ if (!isAuthenticated) return <>{fallback}</> || null;+ return <>{children}</>;}```-### RequireRole Component+### RequireRole-Show content only to users with specific roles.--**File: `src/components/RequireRole.tsx`**+Create `src/components/RequireRole.tsx`:```tsx-import { ReactNode } from 'react';-import { hasAnyRole, hasAllRoles, isAuthenticated } from '../utils/authorization';+import type { ReactNode } from 'react';+import { useAuth } from '../hooks/useAuth';+import { hasAnyRole, hasAllRoles } from '../utils/authorization';interface RequireRoleProps {- /** Content to show when user has required roles */- children: ReactNode;- /** Role(s) required to view content */- roles: string | string[];- /** Require ALL roles (true) or ANY role (false, default) */+ roles: string[];requireAll?: boolean;- /** Content to show when user lacks required roles */- fallback?: ReactNode;- /** Show access denied message */- showAccessDenied?: boolean;-}--export function RequireRole({- children,- roles,- requireAll = false,- fallback = null,- showAccessDenied = false-}: RequireRoleProps) {- const roleArray = Array.isArray(roles) ? roles : [roles];-- // Check authentication first- if (!isAuthenticated()) {- if (showAccessDenied) {- return (- <div className="access-denied">- <p>Please sign in to access this content.</p>- </div>- );- }- return <>{fallback}</>;- }-- // Check roles- const hasAccess = requireAll- ? hasAllRoles(roleArray)- : hasAnyRole(roleArray);-- if (hasAccess) {- return <>{children}</>;- }-- if (showAccessDenied) {- return (- <div className="access-denied">- <p>You don't have permission to access this content.</p>- </div>- );- }-- return <>{fallback}</>;-}-```--### RoleSwitch Component--Show different content based on user roles.--**File: `src/components/RoleSwitch.tsx`**--```tsx-import { ReactNode } from 'react';-import { hasAnyRole, isAuthenticated } from '../utils/authorization';--interface RoleSwitchProps {- children: ReactNode;-}--interface RoleCaseProps {- /** Roles that can see this content */- roles: string | string[];- children: ReactNode;-}--interface RoleDefaultProps {children: ReactNode;+ fallback?: ReactNode;}-// Context to track if a case has matched-let matched = false;--export function RoleSwitch({ children }: RoleSwitchProps) {- matched = false;- return <>{children}</>;-}--export function RoleCase({ roles, children }: RoleCaseProps) {- if (matched) return null;-- const roleArray = Array.isArray(roles) ? roles : [roles];-- if (hasAnyRole(roleArray)) {- matched = true;- return <>{children}</>;- }-- return null;-}--export function AuthenticatedCase({ children }: RoleDefaultProps) {- if (matched) return null;-- if (isAuthenticated()) {- matched = true;- return <>{children}</>;- }-- return null;-}--export function AnonymousCase({ children }: RoleDefaultProps) {- if (matched) return null;+/**+ * Renders children only when the user has the required role(s).+ * By default checks if the user has ANY of the listed roles.+ * Set requireAll=true to require ALL roles.+ */+export function RequireRole({ roles, requireAll = false, children, fallback }: RequireRoleProps) {+ const { isAuthenticated, isLoading } = useAuth();- if (!isAuthenticated()) {- matched = true;- return <>{children}</>;- }+ if (isLoading) return null;+ if (!isAuthenticated) return <>{fallback}</> || null;- return null;-}+ const hasAccess = requireAll ? hasAllRoles(roles) : hasAnyRole(roles);+ if (!hasAccess) return <>{fallback}</> || null;-export function RoleDefault({ children }: RoleDefaultProps) {- if (matched) return null;return <>{children}</>;}--// Usage example:-// <RoleSwitch>-// <RoleCase roles="Administrators">-// <AdminDashboard />-// </RoleCase>-// <RoleCase roles={["Premium Members", "VIP"]}>-// <PremiumContent />-// </RoleCase>-// <AuthenticatedCase>-// <MemberContent />-// </AuthenticatedCase>-// <AnonymousCase>-// <PublicContent />-// </AnonymousCase>-// </RoleSwitch>```-## React Hook for Authorization+### useAuthorization Hook-**File: `src/hooks/useAuthorization.ts`**+Create `src/hooks/useAuthorization.ts`:```typescriptimport { useMemo } from 'react';+import { useAuth } from './useAuth';import {getUserRoles,hasRole,hasAnyRole,hasAllRoles,- isAuthenticated,- isAdmin+ isAdmin,} from '../utils/authorization';-interface UseAuthorizationReturn {- /** All roles for current user */- roles: string[];- /** Check if user has specific role */- hasRole: (role: string) => boolean;- /** Check if user has any of the roles */- hasAnyRole: (roles: string[]) => boolean;- /** Check if user has all of the roles */- hasAllRoles: (roles: string[]) => boolean;- /** Whether user is authenticated */- isAuthenticated: boolean;- /** Whether user is an administrator */- isAdmin: boolean;-}+export function useAuthorization() {+ const { isAuthenticated } = useAuth();-export function useAuthorization(): UseAuthorizationReturn {- const roles = useMemo(() => getUserRoles(), []);+ const roles = useMemo(() => getUserRoles(), [isAuthenticated]);return {roles,hasRole,hasAnyRole,hasAllRoles,- isAuthenticated: isAuthenticated(),+ isAuthenticated,isAdmin: isAdmin(),};}--// Usage:-// const { hasRole, isAdmin } = useAuthorization();-// if (hasRole('Premium Members')) { ... }```-## Route Protection (React Router)--**File: `src/components/ProtectedRoute.tsx`**--```tsx-import { ReactNode } from 'react';-import { Navigate, useLocation } from 'react-router-dom';-import { isAuthenticated, hasAnyRole } from '../utils/authorization';--interface ProtectedRouteProps {- children: ReactNode;- /** Roles required to access this route */- roles?: string[];- /** Redirect path when not authenticated */- loginPath?: string;- /** Redirect path when authenticated but lacking roles */- unauthorizedPath?: string;-}+----export function ProtectedRoute({- children,- roles,- loginPath = '/login',- unauthorizedPath = '/unauthorized'-}: ProtectedRouteProps) {- const location = useLocation();-- // Check authentication- if (!isAuthenticated()) {- // Save intended destination for redirect after login- return <Navigate to={loginPath} state={{ from: location }} replace />;- }+## Vue 3 Patterns- // Check roles if specified- if (roles && roles.length > 0 && !hasAnyRole(roles)) {- return <Navigate to={unauthorizedPath} replace />;- }+### useAuthorization Composable- return <>{children}</>;-}--// Usage in router:-// <Route-// path="/admin"-// element={-// <ProtectedRoute roles={['Administrators']}>-// <AdminPage />-// </ProtectedRoute>-// }-// />-```--### Login Page with Redirect--**File: `src/pages/LoginPage.tsx`**--```tsx-import { useEffect } from 'react';-import { useLocation, useNavigate } from 'react-router-dom';-import { login } from '../services/authService';-import { isAuthenticated } from '../utils/authorization';--export function LoginPage() {- const location = useLocation();- const navigate = useNavigate();- const from = (location.state as any)?.from?.pathname || '/';-- useEffect(() => {- // If already authenticated, redirect to intended destination- if (isAuthenticated()) {- navigate(from, { replace: true });- }- }, [from, navigate]);-- const handleLogin = async () => {- // Pass the intended destination as return URL- await login(from);- };-- return (- <div className="login-page">- <h1>Sign In Required</h1>- <p>Please sign in to access this page.</p>- <button onClick={handleLogin}>Sign In with Azure AD</button>- </div>- );-}-```--## Vue 3 Authorization Composable--**File: `src/composables/useAuthorization.ts`**+Create `src/composables/useAuthorization.ts`:```typescriptimport { computed } from 'vue';-import { getCurrentUser } from '../services/authService';+import { useAuth } from './useAuth';+import {+ getUserRoles,+ hasRole,+ hasAnyRole,+ hasAllRoles,+ isAdmin as checkAdmin,+} from '../utils/authorization';export function useAuthorization() {- const roles = computed(() => {- const user = getCurrentUser();- return user?.userRoles || [];- });-- const isAuthenticated = computed(() => {- const user = getCurrentUser();- return user !== null && user.userName !== '';- });-- function hasRole(roleName: string): boolean {- const normalizedRole = roleName.toLowerCase();- return roles.value.some(role => role.toLowerCase() === normalizedRole);- }+ const { isAuthenticated } = useAuth();- function hasAnyRole(roleNames: string[]): boolean {- return roleNames.some(role => hasRole(role));- }-- function hasAllRoles(roleNames: string[]): boolean {- return roleNames.every(role => hasRole(role));- }-- const isAdmin = computed(() => hasRole('Administrators'));+ const roles = computed(() => getUserRoles());+ const isAdmin = computed(() => checkAdmin());return {roles,@@ -451,388 +197,168 @@ export function useAuthorization() {}```-### Vue Directive for Role-Based Visibility+### v-role Directive-**File: `src/directives/vRole.ts`**+Create `src/directives/vRole.ts`:```typescriptimport type { Directive } from 'vue';-import { getCurrentUser } from '../services/authService';--function hasRole(roleName: string): boolean {- const user = getCurrentUser();- const roles = user?.userRoles || [];- return roles.some(role => role.toLowerCase() === roleName.toLowerCase());-}--function hasAnyRole(roleNames: string[]): boolean {- return roleNames.some(role => hasRole(role));-}+import { hasRole, hasAnyRole } from '../utils/authorization';/**- * Vue directive for role-based visibility+ * Directive for role-based element visibility.** Usage:- * v-role="'Administrators'"- * v-role="['Administrators', 'Managers']"+ * <div v-role="'Administrators'">Admin only</div>+ * <div v-role="['Administrators', 'Editors']">Admin or Editor</div>*/export const vRole: Directive<HTMLElement, string | string[]> = {mounted(el, binding) {- const roles = Array.isArray(binding.value) ? binding.value : [binding.value];-- if (!hasAnyRole(roles)) {+ const roles = binding.value;+ const visible = Array.isArray(roles) ? hasAnyRole(roles) : hasRole(roles);+ if (!visible) {el.style.display = 'none';}},updated(el, binding) {- const roles = Array.isArray(binding.value) ? binding.value : [binding.value];-- if (hasAnyRole(roles)) {- el.style.display = '';- } else {- el.style.display = 'none';- }+ const roles = binding.value;+ const visible = Array.isArray(roles) ? hasAnyRole(roles) : hasRole(roles);+ el.style.display = visible ? '' : 'none';},};--// Register in main.ts:-// app.directive('role', vRole);```-## Angular Authorization+---++## Angular Patterns### Auth Guard-**File: `src/app/guards/auth.guard.ts`**+Create `src/app/guards/auth.guard.ts`:```typescriptimport { inject } from '@angular/core';-import { Router, CanActivateFn } from '@angular/router';+import { type CanActivateFn, Router } from '@angular/router';import { AuthService } from '../services/auth.service';+import { hasAnyRole } from '../../utils/authorization';-export const authGuard: CanActivateFn = (route, state) => {+/**+ * Route guard that requires authentication.+ */+export const authGuard: CanActivateFn = () => {const authService = inject(AuthService);const router = inject(Router);- if (!authService.isAuthenticated) {- // Store intended URL for redirect after login- sessionStorage.setItem('redirectUrl', state.url);- router.navigate(['/login']);- return false;+ if (authService.isAuthenticated) {+ return true;}- return true;+ sessionStorage.setItem('redirectUrl', window.location.pathname);+ router.navigate(['/']);+ return false;};-export const roleGuard: CanActivateFn = (route, state) => {+/**+ * Route guard that requires specific roles.+ * Configure required roles in route data: { roles: ['Administrators'] }+ */+export const roleGuard: CanActivateFn = (route) => {const authService = inject(AuthService);const router = inject(Router);- // First check authenticationif (!authService.isAuthenticated) {- sessionStorage.setItem('redirectUrl', state.url);- router.navigate(['/login']);+ router.navigate(['/']);return false;}- // Then check roles- const requiredRoles = route.data['roles'] as string[];-- if (requiredRoles && requiredRoles.length > 0) {- const userRoles = authService.currentUser?.userRoles || [];- const hasRole = requiredRoles.some(role =>- userRoles.some(ur => ur.toLowerCase() === role.toLowerCase())- );-- if (!hasRole) {- router.navigate(['/unauthorized']);- return false;- }+ const requiredRoles = route.data?.['roles'] as string[] | undefined;+ if (requiredRoles && !hasAnyRole(requiredRoles)) {+ router.navigate(['/']);+ return false;}return true;};--// Usage in routes:-// {-// path: 'admin',-// component: AdminComponent,-// canActivate: [roleGuard],-// data: { roles: ['Administrators'] }-// }```-### Structural Directive for Role-Based Rendering+### HasRole Directive-**File: `src/app/directives/has-role.directive.ts`**+Create `src/app/directives/has-role.directive.ts`:```typescript-import { Directive, Input, TemplateRef, ViewContainerRef, OnInit } from '@angular/core';-import { AuthService } from '../services/auth.service';--@Directive({- selector: '[appHasRole]',- standalone: true-})-export class HasRoleDirective implements OnInit {- @Input('appHasRole') roles: string | string[] = [];-- constructor(- private templateRef: TemplateRef<any>,- private viewContainer: ViewContainerRef,- private authService: AuthService- ) {}-- ngOnInit() {- this.updateView();- }-- private updateView() {- const roleArray = Array.isArray(this.roles) ? this.roles : [this.roles];- const userRoles = this.authService.currentUser?.userRoles || [];-- const hasRole = roleArray.some(role =>- userRoles.some(ur => ur.toLowerCase() === role.toLowerCase())- );-- this.viewContainer.clear();-- if (hasRole) {- this.viewContainer.createEmbeddedView(this.templateRef);- }- }-}--// Usage in template:-// <button *appHasRole="'Administrators'">Admin Action</button>-// <div *appHasRole="['Administrators', 'Managers']">Management Section</div>-```--## Vanilla JavaScript--**File: `src/authorization.js`**--```javascript-/**- * Power Pages Authorization Module- * Framework-agnostic authorization utilities- */--/**- * Get user roles from portal object- * @returns {string[]}- */-function getUserRoles() {- try {- const user = window.Microsoft?.Dynamic365?.Portal?.User;- return user?.userRoles || [];- } catch {- return [];- }-}--/**- * Check if user has a specific role- * @param {string} roleName- * @returns {boolean}- */-function hasRole(roleName) {- const roles = getUserRoles();- const normalizedRole = roleName.toLowerCase();- return roles.some(role => role.toLowerCase() === normalizedRole);-}+import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';+import { hasRole } from '../../utils/authorization';/**- * Check if user has any of the specified roles- * @param {string[]} roleNames- * @returns {boolean}- */-function hasAnyRole(roleNames) {- return roleNames.some(role => hasRole(role));-}--/**- * Check if user is authenticated- * @returns {boolean}- */-function isAuthenticated() {- const user = window.Microsoft?.Dynamic365?.Portal?.User;- return user && user.userName !== '';-}--/**- * Show/hide element based on roles- * @param {HTMLElement} element- * @param {string|string[]} roles- */-function showForRoles(element, roles) {- const roleArray = Array.isArray(roles) ? roles : [roles];-- if (hasAnyRole(roleArray)) {- element.style.display = '';- } else {- element.style.display = 'none';- }-}--/**- * Initialize role-based visibility for elements with data-require-role attribute- * Usage: <div data-require-role="Administrators">Admin content</div>- * <div data-require-role="Admin,Manager">Multi-role content</div>+ * Structural directive for role-based element visibility.+ *+ * Usage:+ * <div *appHasRole="'Administrators'">Admin only</div>*/-function initRoleBasedVisibility() {- document.querySelectorAll('[data-require-role]').forEach(element => {- const rolesAttr = element.getAttribute('data-require-role');- const roles = rolesAttr.split(',').map(r => r.trim());- showForRoles(element, roles);- });-- // Handle authentication-required elements- document.querySelectorAll('[data-require-auth]').forEach(element => {- if (!isAuthenticated()) {- element.style.display = 'none';+@Directive({ selector: '[appHasRole]', standalone: true })+export class HasRoleDirective {+ @Input() set appHasRole(roleName: string) {+ if (hasRole(roleName)) {+ this.viewContainer.createEmbeddedView(this.templateRef);+ } else {+ this.viewContainer.clear();}- });-}+ }-// Auto-initialize when DOM is ready-if (document.readyState === 'loading') {- document.addEventListener('DOMContentLoaded', initRoleBasedVisibility);-} else {- initRoleBasedVisibility();+ constructor(+ private templateRef: TemplateRef<unknown>,+ private viewContainer: ViewContainerRef+ ) {}}--// Export for module usage-export { getUserRoles, hasRole, hasAnyRole, isAuthenticated, showForRoles };--// Expose globally-window.PowerPagesAuth = {- ...window.PowerPagesAuth,- getUserRoles,- hasRole,- hasAnyRole,- isAuthenticated,- showForRoles,-};```+---+## Common Usage Patterns-### Conditional Navigation Items+### Conditional Navigation```tsx-// React example-function Navigation() {- const { isAuthenticated, hasRole } = useAuthorization();-- return (- <nav>- <Link to="/">Home</Link>- <Link to="/products">Products</Link>-- {/* Only for authenticated users */}- {isAuthenticated && (- <Link to="/account">My Account</Link>- )}-- {/* Only for admins */}- {hasRole('Administrators') && (- <Link to="/admin">Admin Dashboard</Link>- )}-- {/* Only for premium members */}- {hasRole('Premium Members') && (- <Link to="/premium">Premium Content</Link>- )}- </nav>- );-}+{/* React example */}+<nav>+ <Link to="/">Home</Link>+ <RequireAuth>+ <Link to="/dashboard">Dashboard</Link>+ </RequireAuth>+ <RequireRole roles={['Administrators']}>+ <Link to="/admin">Admin</Link>+ </RequireRole>+</nav>```### Conditional Action Buttons```tsx-function ProductCard({ product, onEdit, onDelete }) {- const { hasRole } = useAuthorization();-- return (- <div className="product-card">- <h3>{product.name}</h3>- <p>{product.description}</p>-- {/* Edit/Delete only for admins or content managers */}- {hasRole('Administrators') || hasRole('Content Managers') ? (- <div className="product-actions">- <button onClick={() => onEdit(product)}>Edit</button>- <button onClick={() => onDelete(product)}>Delete</button>- </div>- ) : null}- </div>- );-}+<RequireRole roles={['Administrators', 'Content Editors']}>+ <button onClick={handleEdit}>Edit</button>+ <button onClick={handleDelete}>Delete</button>+</RequireRole>```### Content Sections by Role```tsx-function Dashboard() {- return (- <div className="dashboard">- <h1>Dashboard</h1>-- {/* Public section - everyone */}- <section className="public-stats">- <h2>Overview</h2>- <PublicStats />- </section>-- {/* Authenticated users section */}- <RequireAuth>- <section className="user-section">- <h2>Your Activity</h2>- <UserActivity />- </section>- </RequireAuth>-- {/* Admin-only section */}- <RequireRole roles="Administrators">- <section className="admin-section">- <h2>Admin Controls</h2>- <AdminControls />- </section>- </RequireRole>-- {/* Premium members section */}- <RequireRole roles={['Premium Members', 'VIP']}>- <section className="premium-section">- <h2>Premium Features</h2>- <PremiumFeatures />- </section>- </RequireRole>- </div>- );-}+<RequireAuth fallback={<p>Please sign in to view this content.</p>}>+ <p>Welcome, {displayName}!</p>++ <RequireRole roles={['Premium Users']} fallback={<p>Upgrade for premium content.</p>}>+ <PremiumContent />+ </RequireRole>+</RequireAuth>```+---+## Security Considerations**Client-side authorization is for UX only, not security.**-- Client-side: Hide/show UI elements (if bypassed: bad UX)-- Server-side: Table permissions enforce actual data access (if bypassed: security breach)--### Proper Security Setup--1. **Client-side** (this reference): Hide edit button for non-admins-2. **Server-side** (via `/setup-webapi`): Table permission allows only Administrators to PATCH records--If someone bypasses the UI and sends a PATCH request directly:-- **Without server-side protection**: Data gets modified (VULNERABILITY!)-- **With server-side protection**: Returns 403 Forbidden (SECURE)--### Testing Authorization--1. Test with different user accounts having different roles-2. Use browser dev tools to verify hidden elements can't be accessed-3. Test API calls directly to ensure table permissions are enforced-4. Never rely solely on client-side authorization+- The `window.Microsoft.Dynamic365.Portal.User.userRoles` array is set by the server and cannot be modified by the client in a way that affects server-side checks.+- However, hiding a UI element does NOT prevent a user from calling the underlying API directly.+- **Always configure server-side table permissions** to enforce data access control. Use `/power-pages:integrate-webapi` to set up proper table permissions and site settings.+- Test both: verify the UI shows/hides correctly AND verify direct API calls respect table permissions.diff --git a/plugins/power-pages/skills/setup-auth/scripts/validate-auth.js b/plugins/power-pages/skills/setup-auth/scripts/validate-auth.jsnew file mode 100644index 000000000..409bc5e26--- /dev/null+++ b/plugins/power-pages/skills/setup-auth/scripts/validate-auth.js@@ -0,0 +1,127 @@+#!/usr/bin/env node++// Validates that authentication and authorization code was created for a Power Pages code site.+// Runs as a Stop hook to verify the setup-auth skill produced output.++const fs = require('fs');+const path = require('path');+const { approve, block, runValidation, findProjectRoot } = require('../../../scripts/lib/validation-helpers');++runValidation((cwd) => {+ const projectRoot = findProjectRoot(cwd);+ if (!projectRoot) approve(); // Not a Power Pages project, skip++ // Check if any auth files exist — if none, this wasn't an auth session+ const authServiceExists = findAuthService(projectRoot);+ const typeDeclarationsExist = findTypeDeclarations(projectRoot);++ if (!authServiceExists && !typeDeclarationsExist) approve();++ const errors = [];++ if (!authServiceExists) {+ errors.push('Missing auth service (src/services/authService.ts or equivalent)');+ }++ if (!typeDeclarationsExist) {+ errors.push('Missing Power Pages type declarations (src/types/powerPages.d.ts)');+ }++ // Validate auth service content if it exists+ if (authServiceExists) {+ const content = fs.readFileSync(authServiceExists, 'utf8');+ if (!content.includes('login')) {+ errors.push('Auth service missing login function');+ }+ if (!content.includes('logout')) {+ errors.push('Auth service missing logout function');+ }+ if (!content.includes('getCurrentUser')) {+ errors.push('Auth service missing getCurrentUser function');+ }+ if (!content.includes('/_layout/tokenhtml') && !content.includes('fetchAntiForgeryToken')) {+ errors.push('Auth service missing anti-forgery token handling');+ }+ }++ // Check for authorization utilities+ const authzUtils = findAuthorizationUtils(projectRoot);+ if (!authzUtils) {+ errors.push('Missing authorization utilities (src/utils/authorization.ts or equivalent)');+ }++ // Check for auth UI component+ const authComponent = findAuthComponent(projectRoot);+ if (!authComponent) {+ errors.push('Missing auth UI component (AuthButton or equivalent)');+ }++ if (errors.length > 0) {+ block('Authentication setup validation failed:\n- ' + errors.join('\n- '));+ }++ approve();+});++function findAuthService(projectRoot) {+ const candidates = [+ path.join(projectRoot, 'src', 'services', 'authService.ts'),+ path.join(projectRoot, 'src', 'services', 'authService.js'),+ path.join(projectRoot, 'src', 'services', 'auth.service.ts'),+ path.join(projectRoot, 'src', 'services', 'auth.service.js'),+ ];++ for (const candidate of candidates) {+ if (fs.existsSync(candidate)) return candidate;+ }++ return null;+}++function findTypeDeclarations(projectRoot) {+ const candidates = [+ path.join(projectRoot, 'src', 'types', 'powerPages.d.ts'),+ path.join(projectRoot, 'src', 'types', 'powerPages.ts'),+ path.join(projectRoot, 'src', 'types', 'power-pages.d.ts'),+ ];++ for (const candidate of candidates) {+ if (fs.existsSync(candidate)) return true;+ }++ return false;+}++function findAuthorizationUtils(projectRoot) {+ const candidates = [+ path.join(projectRoot, 'src', 'utils', 'authorization.ts'),+ path.join(projectRoot, 'src', 'utils', 'authorization.js'),+ ];++ for (const candidate of candidates) {+ if (fs.existsSync(candidate)) return candidate;+ }++ return null;+}++function findAuthComponent(projectRoot) {+ const searchDirs = [+ path.join(projectRoot, 'src', 'components'),+ path.join(projectRoot, 'src', 'app', 'components'),+ ];++ for (const dir of searchDirs) {+ if (!fs.existsSync(dir)) continue;+ try {+ for (const file of fs.readdirSync(dir, { recursive: true })) {+ const name = typeof file === 'string' ? file : file.toString();+ if (name.toLowerCase().includes('auth') && (name.endsWith('.tsx') || name.endsWith('.vue') || name.endsWith('.ts') || name.endsWith('.astro'))) {+ return path.join(dir, name);+ }+ }+ } catch {}+ }++ return null;+}diff --git a/plugins/power-pages/skills/setup-datamodel/SKILL.md b/plugins/power-pages/skills/setup-datamodel/SKILL.mdnew file mode 100644index 000000000..b76997444--- /dev/null+++ b/plugins/power-pages/skills/setup-datamodel/SKILL.md@@ -0,0 +1,413 @@+---+name: setup-datamodel+description: >+ This skill should be used when the user asks to "create Dataverse tables",+ "set up the data model", "setup dataverse", "create tables for my site",+ "setup dataverse schema", "create the database", "build my data model",+ or wants to create Dataverse tables, columns, and relationships for their+ Power Pages site based on a data model proposal.+user-invocable: true+allowed-tools: ["Read", "Write", "Bash", "Grep", "Glob", "AskUserQuestion", "Task", "TaskCreate", "TaskUpdate", "TaskList", "mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search", "mcp__plugin_power-pages_microsoft-learn__microsoft_code_sample_search", "mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch"]+model: opus+hooks:+ Stop:+ - hooks:+ - type: command+ command: 'node "${CLAUDE_PLUGIN_ROOT}/skills/setup-datamodel/scripts/validate-datamodel.js"'+ timeout: 30+ - type: prompt+ prompt: >+ If a Dataverse data model was being set up in this session (via /power-pages:setup-datamodel),+ verify before allowing stop: 1) A data model was obtained (either the data-model-architect agent+ was invoked OR the user uploaded an existing ER diagram that was parsed), 2) The user approved+ the proposal, 3) All approved tables were created, 4) A summary was presented.+ If incomplete, return { "ok": false, "reason": "<specific issues>" }. Otherwise return { "ok": true }.+ timeout: 30+---++# Set Up Dataverse Data Model++Guide the user through creating Dataverse tables, columns, and relationships for their Power Pages site. Follow a systematic approach: verify prerequisites, obtain a data model (via AI analysis or user-provided diagram), review and approve, then create all schema objects via OData API.++## Core Principles++- **Never create without approval**: Always present the full data model proposal and get explicit user confirmation before making any Dataverse changes.+- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases — create the todo list upfront with all phases before starting any work.+- **Resilient execution**: Refresh tokens proactively, check for existing tables before creating, and report failures without automated rollback.++**Initial request:** $ARGUMENTS++---++## Phase 1: Verify Prerequisites++**Goal**: Confirm PAC CLI authentication, acquire an Azure CLI token, and verify API access++**Actions**:+1. Create todo list with all 8 phases (see [Progress Tracking](#progress-tracking) table)+2. Follow the prerequisite steps in `${CLAUDE_PLUGIN_ROOT}/references/dataverse-prerequisites.md` to verify PAC CLI auth, acquire an Azure CLI token, and confirm API access. Store the environment URL as `$envUrl`.++**Output**: Verified PAC CLI auth, valid Azure CLI token, confirmed API access, `$envUrl` stored++---++## Phase 2: Choose Data Model Source++**Goal**: Determine whether the user will upload an existing ER diagram or let AI analyze the site++**Actions**:+1. Ask the user how they want to define the data model using the `AskUserQuestion` tool:++ **Question**: "How would you like to define the data model for your site?"++ | Option | Description |+ |--------|-------------|+ | **Upload an existing ER diagram** | Provide an image (PNG/JPG) or Mermaid diagram of your existing data model |+ | **Let the Data Model Architect figure it out** | The Data Model Architect will analyze your site's source code and propose a data model automatically |++2. Route to the appropriate path:++### Path A: Upload Existing ER Diagram++If the user chooses to upload an existing diagram:++1. Ask the user to provide their ER diagram. Supported formats:+ - **Image file** (PNG, JPG) — Use the `Read` tool to view the image and extract tables, columns, relationships, and cardinalities from it+ - **Mermaid syntax** — The user can paste Mermaid ER diagram text directly in chat+ - **Text description** — A structured list of tables, columns, and relationships++2. Parse the diagram into the same structured format used by the data-model-architect agent:+ - Publisher prefix (ask the user, or retrieve from the environment via `pac env who`)+ - Table definitions: `logicalName`, `displayName`, `status` (new/modified/reused), `columns`, `relationships`+ - Column definitions: `logicalName`, `displayName`, `type`, `required`+ - Relationship definitions: type (1:N or M:N), referenced/referencing tables++3. Query existing Dataverse tables (same as Phase 3 would) to mark each table as `new`, `modified`, or `reused`.++4. Generate a Mermaid ER diagram from the parsed data (if the user provided an image or text) for visual confirmation.++5. Proceed directly to **Phase 4: Review Proposal** with the parsed data model.++### Path B: Let the Data Model Architect Figure It Out++If the user chooses to let the Data Model Architect figure it out, proceed to **Phase 3: Invoke Data Model Architect** (the existing automated flow).++**Output**: Data model source chosen and, for Path A, parsed data model ready for review++---++## Phase 3: Invoke Data Model Architect++**Goal**: Spawn the data-model-architect agent to autonomously analyze the site and propose a data model++**Actions**:+1. Use the `Task` tool to spawn the `data-model-architect` agent. This agent autonomously:+ - Analyzes the site's source code to infer data requirements+ - Queries existing Dataverse tables via OData GET requests+ - Identifies reuse opportunities (reuse, extend, or create new)+ - Proposes a complete data model with an ER diagram++2. Spawn the agent:++ ```+ Task tool:+ subagent_type: general-purpose+ prompt: |+ You are the data-model-architect agent. Follow the instructions in+ the agent definition file at:+ ${CLAUDE_PLUGIN_ROOT}/agents/data-model-architect.md++ Analyze the current project and Dataverse environment, then propose+ a complete data model. Return:+ 1. Publisher prefix+ 2. Table definitions (logicalName, displayName, status, columns, relationships)+ 3. Mermaid ER diagram+ ```++3. Wait for the agent to return its structured proposal before proceeding.++**Output**: Structured data model proposal from the agent (publisher prefix, table definitions, ER diagram)++---++## Phase 4: Review Proposal++**Goal**: Present the data model proposal to the user and get explicit approval before creating anything++**Actions**:++### 4.1 Present Proposal++Present the data model proposal directly to the user as a formatted message, including:++- Publisher prefix+- All proposed tables with columns (logical names + display names)+- Relationship descriptions+- Mermaid ER diagram+- Which tables are new vs. modified vs. reused++### 4.2 Get User Approval++Use `AskUserQuestion` to get approval:++| Question | Header | Options |+|----------|--------|---------|+| Does this data model look correct? | Data Model Proposal | Approve and create tables (Recommended), Request changes, Cancel |++- **If "Approve and create tables (Recommended)"**: Proceed to Phase 5+- **If "Request changes"**: Ask what they want changed, modify the proposal, and re-present for approval+- **If "Cancel"**: Stop the skill++Only proceed to creation after explicit user approval.++**Output**: User-approved data model proposal++---++## Phase 5: Pre-Creation Checks++**Goal**: Refresh the token, verify what already exists in Dataverse, and build the creation plan to avoid duplicates++**Actions**:++### 5.1 Refresh Token++Re-acquire the Azure CLI token (tokens expire after ~60 minutes):++```powershell+$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+```++### 5.2 Query Existing Tables++For each table in the approved proposal marked as `new`, check whether it already exists:++```powershell+$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }+Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table_logical_name>')" -Headers $headers+```++- **If 404**: Table does not exist, proceed to create it+- **If 200**: Table already exists — skip creation, warn the user++For tables marked as `modified`, verify the table exists (it should) and check which columns are missing.++### 5.3 Build Creation Plan++From the pre-creation checks, build a list of:++- Tables to create (new tables that don't exist yet)+- Columns to add (new columns on existing/modified tables)+- Relationships to create+- Tables/columns to skip (already exist)++Inform the user of any skipped items.++**Output**: Finalized creation plan with tables, columns, and relationships to create or skip++---++## Phase 6: Create Tables & Columns++**Goal**: Create each approved table and its columns using the Dataverse OData Web API++**Actions**:++Refer to `references/odata-api-patterns.md` for full JSON body templates.++### 6.1 Create Tables++For each new table, POST to the EntityDefinitions endpoint:++```powershell+$body = <JSON body from references/odata-api-patterns.md>+$headers = @{+ Authorization = "Bearer $token"+ "Content-Type" = "application/json"+ Accept = "application/json"+}+Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/EntityDefinitions" -Headers $headers -Body $body+```++Use the deep-insert pattern to create the table and its columns in a single POST request. See `references/odata-api-patterns.md` for the complete JSON structure.++### 6.2 Add Columns to Existing Tables++For tables marked as `modified`, add new columns one at a time:++```powershell+$body = <column JSON from references/odata-api-patterns.md>+Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table>')/Attributes" -Headers $headers -Body $body+```++### 6.3 Track Progress++Track each creation attempt and its result (success/failure/skipped). Do NOT attempt automated rollback on failure — report failures and continue with remaining items.++### 6.4 Refresh Token if Needed++If creating many tables, refresh the token between batches (every 3–4 tables) to avoid expiration:++```powershell+$token = az account get-access-token --resource "$envUrl" --query accessToken -o tsv+```++**Output**: All approved tables and columns created (or failures reported)++---++## Phase 7: Create Relationships++**Goal**: Create all relationships between the newly created and existing tables++**Actions**:++### 7.1 One-to-Many Relationships++Create lookup columns that establish 1:N relationships:++```powershell+$body = <relationship JSON from references/odata-api-patterns.md>+Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/RelationshipDefinitions" -Headers $headers -Body $body+```++### 7.2 Many-to-Many Relationships++Create M:N relationships (intersect tables are created automatically):++```powershell+$body = <M:N relationship JSON from references/odata-api-patterns.md>+Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/RelationshipDefinitions" -Headers $headers -Body $body+```++### 7.3 Track Relationship Creation++Track each relationship creation attempt. Report failures without rolling back.++**Output**: All approved relationships created (or failures reported)++---++## Phase 8: Publish & Verify++**Goal**: Publish all customizations, verify tables exist, write the manifest, and present a summary++**Actions**:++### 8.1 Publish Customizations++Publish all customizations so the new tables and columns become available:++```powershell+$publishBody = @{+ ParameterXml = "<importexportxml><entities><entity>$( ($tables | ForEach-Object { $_.logicalName }) -join '</entity><entity>' )</entity></entities></importexportxml>"+} | ConvertTo-Json++Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/PublishXml" -Headers $headers -Body $publishBody -ContentType "application/json"+```++See `references/odata-api-patterns.md` for the full PublishXml pattern.++### 8.2 Verify Tables Exist++For each created table, run a verification query:++```powershell+Invoke-RestMethod -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='<table>')?`$select=LogicalName,DisplayName" -Headers $headers+```++### 8.3 Write Manifest++After successful verification, write `.datamodel-manifest.json` to the project root. This file records which tables and columns were verified to exist, and is used by the validation hook.++```json+{+ "environmentUrl": "https://org12345.crm.dynamics.com",+ "tables": [+ {+ "logicalName": "cr123_project",+ "displayName": "Project",+ "status": "new",+ "columns": [+ { "logicalName": "cr123_name", "type": "String" },+ { "logicalName": "cr123_description", "type": "Memo" }+ ]+ }+ ]+}+```++Use the `Write` tool to create this file at `<PROJECT_ROOT>/.datamodel-manifest.json`. Only include tables and columns that were confirmed to exist in Step 8.2. See `${CLAUDE_PLUGIN_ROOT}/references/datamodel-manifest-schema.md` for the full schema specification.++### 8.4 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 "SetupDatamodel"`.++### 8.5 Present Summary++Present a summary to the user:++| Table | Status | Columns | Relationships |+|-------|--------|---------|---------------|+| `cr123_project` (Project) | Created | 5 columns | 2 relationships |+| `contact` (Contact) | Reused | 1 column added | — |+| `cr123_task` (Task) | Created | 4 columns | 1 relationship |++Include:+- Total tables created/modified/reused/failed+- Total columns created/skipped/failed+- Total relationships created/failed+- Any errors encountered with details+- Location of the manifest file (`.datamodel-manifest.json`)++### 8.6 Suggest Next Steps++After the summary, suggest:+- Review created tables in the Power Pages maker portal+- Populate tables with sample data for testing: `/power-pages:add-sample-data`+- Integrate tables with your site's frontend via Web API: `/power-pages:integrate-webapi`+- If the site is not yet built: `/power-pages:create-site`+- If the site is ready to deploy: `/power-pages:deploy-site`++**Output**: Published customizations, verified tables, manifest written, summary presented++---++## Important Notes++### Throughout All Phases++- **Use TaskCreate/TaskUpdate** to track progress at every phase+- **Ask for user confirmation** at key decision points (see list below)+- **Refresh tokens proactively** — re-acquire the Azure CLI token before any batch of API calls, especially if more than a few minutes have passed+- **Report failures without rollback** — track each creation attempt and continue with remaining items on failure++### Key Decision Points (Wait for User)++1. After Phase 2: Data model source chosen (upload vs. AI)+2. After Phase 4: Approve data model proposal before any creation+3. After Phase 5: Acknowledge any skipped items before proceeding+4. After Phase 8: Review summary and choose next steps++### Progress Tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Verify prerequisites | Verifying prerequisites | Confirm PAC CLI auth, acquire Azure CLI token, verify API access |+| Choose data model source | Choosing data model source | Ask user to upload ER diagram or let AI analyze the site |+| Invoke data model architect | Invoking data model architect | Spawn agent to analyze site and propose data model |+| Review and approve proposal | Reviewing proposal | Present data model proposal to user, get explicit approval |+| Pre-creation checks | Running pre-creation checks | Refresh token, query existing tables, build creation plan |+| Create tables and columns | Creating tables and columns | POST to OData API to create tables and columns |+| Create relationships | Creating relationships | POST to OData API to create 1:N and M:N relationships |+| Publish and verify | Publishing and verifying | Publish customizations, verify tables, write manifest, present summary |++Mark each task `in_progress` when starting it and `completed` when done via `TaskUpdate`. This gives the user visibility into progress and keeps the workflow deterministic.++---++**Begin with Phase 1: Verify Prerequisites**diff --git a/plugins/power-pages/skills/setup-datamodel/references/odata-api-patterns.md b/plugins/power-pages/skills/setup-datamodel/references/odata-api-patterns.mdnew file mode 100644index 000000000..dbedbd24d--- /dev/null+++ b/plugins/power-pages/skills/setup-datamodel/references/odata-api-patterns.md@@ -0,0 +1,407 @@+# OData API Patterns for Dataverse Table Creation++Reference document for the `setup-datamodel` skill. Contains full JSON body templates for creating tables, columns, and relationships via the Dataverse OData Web API (v9.2).++> **Authentication, error handling, and retry patterns** are in the shared reference: `${CLAUDE_PLUGIN_ROOT}/references/odata-common.md`. Read that file first for headers, token refresh, HTTP status codes, and retry logic.++---++## Create Table with Columns (Deep Insert)++Create a table and its columns in a single POST using deep insert. This is the preferred approach — it avoids multiple round-trips.++**Endpoint:** `POST {envUrl}/api/data/v9.2/EntityDefinitions`++```json+{+ "@odata.type": "Microsoft.Dynamics.CRM.EntityMetadata",+ "SchemaName": "<Prefix>_<TableName>",+ "DisplayName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [+ {+ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel",+ "Label": "<Display Name>",+ "LanguageCode": 1033+ }+ ]+ },+ "DisplayCollectionName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [+ {+ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel",+ "Label": "<Display Name Plural>",+ "LanguageCode": 1033+ }+ ]+ },+ "Description": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [+ {+ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel",+ "Label": "<Description>",+ "LanguageCode": 1033+ }+ ]+ },+ "HasActivities": false,+ "HasNotes": false,+ "OwnershipType": "UserOwned",+ "IsActivity": false,+ "Attributes": [+ {+ "@odata.type": "Microsoft.Dynamics.CRM.StringAttributeMetadata",+ "SchemaName": "<Prefix>_Name",+ "DisplayName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [+ {+ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel",+ "Label": "Name",+ "LanguageCode": 1033+ }+ ]+ },+ "IsPrimaryName": true,+ "RequiredLevel": { "Value": "ApplicationRequired" },+ "MaxLength": 200,+ "FormatName": { "Value": "Text" }+ }+ ]+}+```++**Important notes:**+- `SchemaName` uses PascalCase with prefix: `Cr123_ProjectName`+- `LogicalName` is auto-generated as lowercase: `cr123_projectname`+- Every table must have exactly one column with `"IsPrimaryName": true`+- `OwnershipType` can be `"UserOwned"` (supports security roles) or `"OrganizationOwned"` (shared across org)++---++## Column Type Mapping++Each Dataverse column type requires a specific `@odata.type` and set of properties. Below is the mapping from the data-model-architect's type names to OData metadata types.++### SingleLine.Text (String)++```json+{+ "@odata.type": "Microsoft.Dynamics.CRM.StringAttributeMetadata",+ "SchemaName": "<Prefix>_<ColumnName>",+ "DisplayName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "<Display Name>", "LanguageCode": 1033 }]+ },+ "RequiredLevel": { "Value": "None" },+ "MaxLength": 200,+ "FormatName": { "Value": "Text" }+}+```++`FormatName` values: `Text`, `Email`, `Url`, `Phone`, `TextArea`++### MultiLine.Text (Memo)++```json+{+ "@odata.type": "Microsoft.Dynamics.CRM.MemoAttributeMetadata",+ "SchemaName": "<Prefix>_<ColumnName>",+ "DisplayName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "<Display Name>", "LanguageCode": 1033 }]+ },+ "RequiredLevel": { "Value": "None" },+ "MaxLength": 10000,+ "Format": "TextArea"+}+```++### WholeNumber (Integer)++```json+{+ "@odata.type": "Microsoft.Dynamics.CRM.IntegerAttributeMetadata",+ "SchemaName": "<Prefix>_<ColumnName>",+ "DisplayName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "<Display Name>", "LanguageCode": 1033 }]+ },+ "RequiredLevel": { "Value": "None" },+ "MinValue": -2147483648,+ "MaxValue": 2147483647,+ "Format": "None"+}+```++### Decimal++```json+{+ "@odata.type": "Microsoft.Dynamics.CRM.DecimalAttributeMetadata",+ "SchemaName": "<Prefix>_<ColumnName>",+ "DisplayName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "<Display Name>", "LanguageCode": 1033 }]+ },+ "RequiredLevel": { "Value": "None" },+ "MinValue": -100000000000,+ "MaxValue": 100000000000,+ "Precision": 2+}+```++### Currency (Money)++```json+{+ "@odata.type": "Microsoft.Dynamics.CRM.MoneyAttributeMetadata",+ "SchemaName": "<Prefix>_<ColumnName>",+ "DisplayName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "<Display Name>", "LanguageCode": 1033 }]+ },+ "RequiredLevel": { "Value": "None" },+ "MinValue": 0,+ "MaxValue": 1000000000,+ "Precision": 2,+ "PrecisionSource": 2+}+```++### DateTime++```json+{+ "@odata.type": "Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",+ "SchemaName": "<Prefix>_<ColumnName>",+ "DisplayName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "<Display Name>", "LanguageCode": 1033 }]+ },+ "RequiredLevel": { "Value": "None" },+ "Format": "DateAndTime",+ "DateTimeBehavior": { "Value": "UserLocal" }+}+```++`Format` values: `DateAndTime`, `DateOnly`++### Boolean++```json+{+ "@odata.type": "Microsoft.Dynamics.CRM.BooleanAttributeMetadata",+ "SchemaName": "<Prefix>_<ColumnName>",+ "DisplayName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "<Display Name>", "LanguageCode": 1033 }]+ },+ "RequiredLevel": { "Value": "None" },+ "DefaultValue": false,+ "OptionSet": {+ "TrueOption": {+ "Value": 1,+ "Label": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "Yes", "LanguageCode": 1033 }]+ }+ },+ "FalseOption": {+ "Value": 0,+ "Label": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "No", "LanguageCode": 1033 }]+ }+ }+ }+}+```++### Choice (OptionSet / Picklist)++```json+{+ "@odata.type": "Microsoft.Dynamics.CRM.PicklistAttributeMetadata",+ "SchemaName": "<Prefix>_<ColumnName>",+ "DisplayName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "<Display Name>", "LanguageCode": 1033 }]+ },+ "RequiredLevel": { "Value": "None" },+ "OptionSet": {+ "@odata.type": "Microsoft.Dynamics.CRM.OptionSetMetadata",+ "IsGlobal": false,+ "OptionSetType": "Picklist",+ "Options": [+ {+ "Value": 100000000,+ "Label": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "Option 1", "LanguageCode": 1033 }]+ }+ },+ {+ "Value": 100000001,+ "Label": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "Option 2", "LanguageCode": 1033 }]+ }+ }+ ]+ }+}+```++**Choice option values** start at `100000000` and increment by 1 for each option.++### Lookup++Lookups are NOT created as standalone columns. They are created as part of a relationship definition. See the Relationships section below.++---++## Add Column to Existing Table++**Endpoint:** `POST {envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='<table>')/Attributes`++Use the same column JSON bodies as above. The column is added to the specified table.++```powershell+$body = '<column JSON>' | ConvertFrom-Json | ConvertTo-Json -Depth 20+Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/EntityDefinitions(LogicalName='cr123_project')/Attributes" -Headers $headers -Body $body+```++---++## Relationships++### One-to-Many (1:N) Relationship++Creates a lookup column on the "many" side that references the "one" side.++**Endpoint:** `POST {envUrl}/api/data/v9.2/RelationshipDefinitions`++```json+{+ "@odata.type": "Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",+ "SchemaName": "<prefix>_<ReferencedTable>_<ReferencingTable>",+ "ReferencedEntity": "<referenced_table_logical_name>",+ "ReferencingEntity": "<referencing_table_logical_name>",+ "CascadeConfiguration": {+ "Assign": "NoCascade",+ "Delete": "RemoveLink",+ "Merge": "NoCascade",+ "Reparent": "NoCascade",+ "Share": "NoCascade",+ "Unshare": "NoCascade",+ "RollupView": "NoCascade"+ },+ "Lookup": {+ "@odata.type": "Microsoft.Dynamics.CRM.LookupAttributeMetadata",+ "SchemaName": "<Prefix>_<ReferencedTable>Id",+ "DisplayName": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [+ {+ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel",+ "Label": "<Referenced Table Display Name>",+ "LanguageCode": 1033+ }+ ]+ },+ "RequiredLevel": { "Value": "None" }+ }+}+```++**Example:** Contact (one) → Orders (many):+- `ReferencedEntity`: `contact`+- `ReferencingEntity`: `cr123_order`+- `Lookup.SchemaName`: `Cr123_ContactId`++### Many-to-Many (M:N) Relationship++**Endpoint:** `POST {envUrl}/api/data/v9.2/RelationshipDefinitions`++```json+{+ "@odata.type": "Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",+ "SchemaName": "<prefix>_<Table1>_<Table2>",+ "Entity1LogicalName": "<table1_logical_name>",+ "Entity2LogicalName": "<table2_logical_name>",+ "IntersectEntityName": "<prefix>_<table1>_<table2>",+ "Entity1AssociatedMenuConfiguration": {+ "Behavior": "UseLabel",+ "Group": "Details",+ "Label": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "<Table2 Plural>", "LanguageCode": 1033 }]+ },+ "Order": 10000+ },+ "Entity2AssociatedMenuConfiguration": {+ "Behavior": "UseLabel",+ "Group": "Details",+ "Label": {+ "@odata.type": "Microsoft.Dynamics.CRM.Label",+ "LocalizedLabels": [{ "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "<Table1 Plural>", "LanguageCode": 1033 }]+ },+ "Order": 10000+ }+}+```++---++## Publish Customizations++After creating tables, columns, and relationships, publish them so they become available in the environment.++**Endpoint:** `POST {envUrl}/api/data/v9.2/PublishXml`++### Publish Specific Tables++```json+{+ "ParameterXml": "<importexportxml><entities><entity>cr123_project</entity><entity>cr123_task</entity></entities></importexportxml>"+}+```++```powershell+$tables = @("cr123_project", "cr123_task")+$entityXml = ($tables | ForEach-Object { "<entity>$_</entity>" }) -join ""+$publishBody = @{+ ParameterXml = "<importexportxml><entities>$entityXml</entities></importexportxml>"+} | ConvertTo-Json++Invoke-RestMethod -Method Post -Uri "$envUrl/api/data/v9.2/PublishXml" -Headers $headers -Body $publishBody -ContentType "application/json"+```++### Publish All Customizations (Fallback)++If publishing specific tables fails, publish everything:++```json+{+ "ParameterXml": "<importexportxml><entities><entity>all</entity></entities></importexportxml>"+}+```++---++## RequiredLevel Values++| Value | Meaning |+|-------|---------|+| `None` | Optional column |+| `ApplicationRequired` | Required by the application (shows asterisk in forms) |+| `SystemRequired` | Required by the system (cannot be changed) |++---++## Error Handling++See `${CLAUDE_PLUGIN_ROOT}/references/odata-common.md` for HTTP status codes, error response format, Dataverse error codes, and retry patterns.diff --git a/plugins/power-pages/skills/setup-datamodel/scripts/validate-datamodel.js b/plugins/power-pages/skills/setup-datamodel/scripts/validate-datamodel.jsnew file mode 100644index 000000000..ca9a40612--- /dev/null+++ b/plugins/power-pages/skills/setup-datamodel/scripts/validate-datamodel.js@@ -0,0 +1,74 @@+#!/usr/bin/env node++// Validates Dataverse data model creation output.+// Runs as a Stop hook to verify tables and columns were properly created.+// Reads .datamodel-manifest.json (written by the setup-datamodel skill) and+// queries the Dataverse OData API to confirm each table/column exists.++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');++runValidation((cwd) => {+ const manifestPath = findPath(cwd, '.datamodel-manifest.json');+ if (!manifestPath) approve(); // Not a data model session, skip++ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ if (!manifest.tables || manifest.tables.length === 0) approve();++ const envUrl = manifest.environmentUrl || getEnvironmentUrl();+ if (!envUrl) approve(); // Can't determine environment — don't block++ const token = getAuthToken(envUrl);+ if (!token) approve(); // Auth not available — don't block++ const errors = [];++ for (const table of manifest.tables) {+ const tableExists = 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);+ for (const col of table.columns) {+ if (!existingColumns.includes(col.logicalName)) {+ errors.push(`Missing column: ${table.logicalName}.${col.logicalName}`);+ }+ }+ }+ }++ if (errors.length > 0) {+ block('Dataverse data model validation failed:\n- ' + errors.join('\n- '));+ }++ approve();+});++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;+ } catch {+ return false;+ }+}++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);+ } catch {+ return [];+ }+}diff --git a/plugins/power-pages/skills/setup-dataverse/SKILL.md b/plugins/power-pages/skills/setup-dataverse/SKILL.mddeleted file mode 100644index a00de4c1e..000000000--- a/plugins/power-pages/skills/setup-dataverse/SKILL.md+++ /dev/null@@ -1,177 +0,0 @@-----name: setting-up-dataverse-tables-description: Creates Dataverse tables, columns, and relationships for Power Pages. Use when creating tables, defining schema, setting up entity relationships, or lookup fields.-user-invocable: true-allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task", "ExitPlanMode"]-model: opus------**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.--# Setup Dataverse Tables--**References:** [data-architecture](./references/data-architecture-reference.md) | [api-auth](./references/api-authentication-reference.md) | [table-management](./references/table-management-reference.md) | [relationships](./references/relationship-reference.md) | [troubleshooting](./references/troubleshooting.md)--Tables are created in **topological order** (referenced tables first) to maintain referential integrity.--## Workflow--1. **Plan** → Check context, analyze site, design schema, get approval-2. **Setup API Auth** → Get token and publisher prefix-3. **Review Existing Tables** → Reuse, extend, or create new-4. **Create Tables** → In dependency order with relationships-5. **Upload** → Create skill tracking setting and upload-------## Step 1: Plan--### 1.1 Check Context--Read `memory-bank.md`. If continuing from `/create-site`, proceed. Otherwise ask for project path or suggest `/create-site` first.--### 1.2 Analyze Site--Read `powerpages.config.json` and scan components for data patterns:--| Pattern | Table | Relationships |-|---------|-------|---------------|-| Contact form | `{prefix}_contactsubmission` | → status |-| Products | `{prefix}_product` | → category |-| Team members | `{prefix}_teammember` | → department |-| Testimonials | `{prefix}_testimonial` | → product (optional) |-| Blog | `{prefix}_blogpost` | → category, author |-| FAQ | `{prefix}_faq` | → faqcategory |--**Use standard Dataverse tables instead of creating new ones:**--| Need | Use This | NOT This |-|------|----------|----------|-| User profiles, customers | `contact` (standard) | `{prefix}_user` or `{prefix}_customer` |-| Organizations, companies | `account` (standard) | `{prefix}_company` |--The `contact` table is already integrated with Power Pages authentication - portal users are linked to Contact records. Extend it with custom columns if needed rather than creating a separate user table.--### 1.3 Build Dependency Graph--Topologically sort tables. Rules:-- No circular dependencies-- All referenced tables exist-- Self-references: create table first, add lookup after--### 1.4 Enter Plan Mode--Use `/plan` command to enter plan mode and create an implementation plan covering:-- ER model with all tables, columns, and relationships-- Tier classification (TIER 0 = reference tables, TIER 1 = primary entities, etc.)-- Creation order based on dependency graph-- Which existing tables will be reused vs. created-- Columns and data types for each table--### 1.5 Get Approval--Present the plan (including ER diagram) to the user. Use `ExitPlanMode` only after user approves. If user requests changes, update the plan and present again.-------## Step 2: Setup API Auth--```powershell-az account show-pac org who--$api = Initialize-DataverseApi -EnvironmentUrl "https://<org>.crm.dynamics.com"-$headers = $api.Headers-$baseUrl = $api.BaseUrl-$publisherPrefix = $api.PublisherPrefix # Use for all schema names-```-------## Step 3: Review Existing Tables--**ALWAYS query existing tables first before recommending creation:**--```powershell-# 1. Get ALL existing custom tables-$existingTables = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions?`$filter=IsCustomEntity eq true&`$select=SchemaName,LogicalName,DisplayName" -Headers $headers--# 2. Use Find-SimilarTables to match by purpose (category, product, team, etc.)-# 3. Use Compare-TableSchemas to check if columns match requirements-```--**Always recommend standard Dataverse tables for common needs:**-- `contact` - For users, customers, people (already linked to Power Pages auth)-- `account` - For organizations, companies, partners--These exist in every environment - extend with custom columns instead of creating new tables.--**Present findings to user with `AskUserQuestion`:**-- Show which existing tables can be reused (and what columns they have)-- Show which need extension (missing columns)-- Show which must be created new (no match found)--Options:-- **Use recommendations** - Reuse existing, extend where needed, create only new-- **Create all new** - Unique names for all tables-- **Review each** - Decide individually--Build `$tableMap` with `Build-TableNameMapping` - **critical for later steps**:-```powershell-$tableMap["category"].LogicalName # Actual table name (may be existing table)-$tableMap["category"].EntitySetName # For OData queries-$tableMap["category"].Source # "Reused", "Extended", or "Created"-```-------## Step 4: Create Tables--**Present the plan and get explicit confirmation before creating:**--Use `AskUserQuestion` to show:-- Tables to be reused (no changes)-- Tables to be extended (list columns to add)-- Tables to be created (list all columns)-- Relationships to be created--Options:-- **Proceed** - Create/extend tables as planned-- **Modify** - Let me adjust the plan-- **Cancel** - Don't make any changes--**Only after user confirms "Proceed"**, create in dependency order using:-- `New-DataverseTableIfNotExists`-- `Add-DataverseColumnIfNotExists`-- `Add-DataverseLookupIfNotExists`--**Phases**: Skip reusable → Extend existing → Create new → Add lookups-------## Step 5: Create Skill Tracking Setting and Upload--Create `Site/AI/SetupDataverse` site setting to track skill usage:--```powershell-New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupDataverse"-npm run build # Always build before upload-pac pages upload-code-site --rootPath "<PROJECT_ROOT>"-```--See [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md) for helper function.--Cleanup per [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md).-------## Optional Enhancements--After table creation, suggest:-- `/add-sample-data` - Insert sample data with proper foreign key relationships-------## Next Steps--Run `/setup-webapi` to configure table permissions.diff --git a/plugins/power-pages/skills/setup-dataverse/references/api-authentication-reference.md b/plugins/power-pages/skills/setup-dataverse/references/api-authentication-reference.mddeleted file mode 100644index 89257b706..000000000--- a/plugins/power-pages/skills/setup-dataverse/references/api-authentication-reference.md+++ /dev/null@@ -1,227 +0,0 @@-# API Authentication Reference--Uses Dataverse OData Web API with Azure CLI authentication (`az account get-access-token`).--## Prerequisites--Ensure Azure CLI is authenticated before proceeding:--```powershell-# Verify Azure CLI is logged in-az account show--# If not logged in, run:-az login-```--## Get Environment URL--Get your Dataverse environment URL:--```powershell-# Using PAC CLI-pac org who-```--This returns information including the environment URL (e.g., `https://orgname.crm.dynamics.com`).--## Get Access Token--```powershell-# Get access token using Azure CLI-$envUrl = "https://<org>.crm.dynamics.com" # Replace with your org URL-$token = (az account get-access-token --resource $envUrl --query accessToken -o tsv)-```--## Set Up API Headers--```powershell-# Set up headers for API calls-$headers = @{- "Authorization" = "Bearer $token"- "Content-Type" = "application/json"- "OData-MaxVersion" = "4.0"- "OData-Version" = "4.0"- "MSCRM.SolutionUniqueName" = "YourSolutionName" # Optional: add to a solution-}--$baseUrl = "$envUrl/api/data/v9.2"-```--## API Headers Reference--| Header | Value | Purpose |-|--------|-------|---------|-| `Authorization` | `Bearer <token>` | Authentication token |-| `Content-Type` | `application/json` | Request body format |-| `OData-MaxVersion` | `4.0` | Maximum OData version supported |-| `OData-Version` | `4.0` | OData version to use |-| `MSCRM.SolutionUniqueName` | Solution name | Add created items to a solution |-| `Prefer` | `return=representation` | Return created record with ID |--## Get Default Publisher Prefix--The publisher prefix is used for naming custom tables and columns. Fetch it dynamically to ensure consistency:--```powershell-function Get-DefaultPublisherPrefix {- param(- [Parameter(Mandatory=$true)]- [string]$BaseUrl,-- [Parameter(Mandatory=$true)]- [hashtable]$Headers- )-- # Query the CDS Default Publisher directly- $defaultPublisher = Invoke-RestMethod -Uri "$BaseUrl/publishers?`$filter=friendlyname eq 'CDS Default Publisher'&`$select=customizationprefix,friendlyname" -Headers $Headers-- if ($defaultPublisher.value.Count -eq 0) {- throw "Could not find CDS Default Publisher in the environment"- }-- $prefix = $defaultPublisher.value[0].customizationprefix- $publisherName = $defaultPublisher.value[0].friendlyname-- Write-Host "Default Publisher: $publisherName" -ForegroundColor Cyan- Write-Host "Customization Prefix: $prefix" -ForegroundColor Cyan-- return $prefix-}-```--## Complete Setup Script--```powershell-# Complete API setup script-function Initialize-DataverseApi {- param(- [Parameter(Mandatory=$true)]- [string]$EnvironmentUrl,-- [string]$SolutionName = $null- )-- # Get access token- $token = (az account get-access-token --resource $EnvironmentUrl --query accessToken -o tsv)-- if (-not $token) {- throw "Failed to get access token. Make sure you're logged in with 'az login'"- }-- # Set up headers- $headers = @{- "Authorization" = "Bearer $token"- "Content-Type" = "application/json"- "OData-MaxVersion" = "4.0"- "OData-Version" = "4.0"- "Prefer" = "return=representation"- }-- if ($SolutionName) {- $headers["MSCRM.SolutionUniqueName"] = $SolutionName- }-- $baseUrl = "$EnvironmentUrl/api/data/v9.2"-- # Get the default publisher prefix- $publisherPrefix = Get-DefaultPublisherPrefix -BaseUrl $baseUrl -Headers $headers-- # Store in script-level variables for reuse- $script:DataverseHeaders = $headers- $script:DataverseBaseUrl = $baseUrl- $script:PublisherPrefix = $publisherPrefix-- Write-Host "Dataverse API initialized successfully" -ForegroundColor Green- Write-Host " Environment: $EnvironmentUrl" -ForegroundColor Cyan- Write-Host " Base URL: $baseUrl" -ForegroundColor Cyan- Write-Host " Publisher Prefix: $publisherPrefix" -ForegroundColor Cyan-- return @{- Headers = $headers- BaseUrl = $baseUrl- PublisherPrefix = $publisherPrefix- }-}--# Usage example:-# $api = Initialize-DataverseApi -EnvironmentUrl "https://orgname.crm.dynamics.com"-# $headers = $api.Headers-# $baseUrl = $api.BaseUrl-# $publisherPrefix = $api.PublisherPrefix-```--## Token Refresh--Access tokens expire after approximately 1 hour. For long-running scripts, implement token refresh:--```powershell-function Get-FreshToken {- param([string]$EnvironmentUrl)-- return (az account get-access-token --resource $EnvironmentUrl --query accessToken -o tsv)-}--function Invoke-DataverseApi {- param(- [string]$Uri,- [string]$Method = "Get",- [hashtable]$Headers,- [string]$Body = $null,- [string]$EnvironmentUrl- )-- try {- if ($Body) {- return Invoke-RestMethod -Uri $Uri -Method $Method -Headers $Headers -Body $Body- } else {- return Invoke-RestMethod -Uri $Uri -Method $Method -Headers $Headers- }- } catch {- if ($_.Exception.Response.StatusCode -eq 401) {- # Token expired, refresh and retry- Write-Host "Token expired, refreshing..." -ForegroundColor Yellow- $newToken = Get-FreshToken -EnvironmentUrl $EnvironmentUrl- $Headers["Authorization"] = "Bearer $newToken"-- if ($Body) {- return Invoke-RestMethod -Uri $Uri -Method $Method -Headers $Headers -Body $Body- } else {- return Invoke-RestMethod -Uri $Uri -Method $Method -Headers $Headers- }- }- throw- }-}-```--## Verify Connection--Test the API connection:--```powershell-# Test API connection-try {- $whoami = Invoke-RestMethod -Uri "$baseUrl/WhoAmI" -Headers $headers- Write-Host "Connected as: $($whoami.UserId)" -ForegroundColor Green-} catch {- Write-Host "Connection failed: $($_.Exception.Message)" -ForegroundColor Red-}-```--## Required Permissions--To create tables and manage schema, you need one of these Dataverse security roles:--- **System Administrator** - Full access-- **System Customizer** - Can create and modify tables--To verify your permissions:--```powershell-# Get current user's security roles-$userId = (Invoke-RestMethod -Uri "$baseUrl/WhoAmI" -Headers $headers).UserId-$roles = Invoke-RestMethod -Uri "$baseUrl/systemusers($userId)/systemuserroles_association?`$select=name" -Headers $headers-Write-Host "Your security roles:" -ForegroundColor Cyan-$roles.value | ForEach-Object { Write-Host " - $($_.name)" }-```diff --git a/plugins/power-pages/skills/setup-dataverse/references/data-architecture-reference.md b/plugins/power-pages/skills/setup-dataverse/references/data-architecture-reference.mddeleted file mode 100644index a1827005e..000000000--- a/plugins/power-pages/skills/setup-dataverse/references/data-architecture-reference.md+++ /dev/null@@ -1,34 +0,0 @@-# Data Architecture Reference--## Relationship Types--- **1:N (One-to-Many)**: Parent table referenced by child via Lookup. Parent must exist first.-- **N:N (Many-to-Many)**: Junction table created automatically. Both tables must exist first.-- **Self-Referential**: Table references itself. Table must exist before adding self-lookup.--## Dependency Tiers--Create tables in order by their dependencies:-- **Tier 0**: Reference/lookup tables (no dependencies) - Category, Status, Department-- **Tier 1**: Primary entities (reference Tier 0) - Product→Category, Employee→Department-- **Tier 2**: Dependent/transaction tables (reference Tier 1) - Order→Customer, OrderLine→Order-- **Tier 3**: Deeply nested tables (rare)--## Common Relationship Patterns--| Site Feature | Tables | Relationships |-|--------------|--------|---------------|-| **Blog** | Category, Author, BlogPost, Comment | Category(0) -> BlogPost(1) -> Comment(2); Author(0) -> BlogPost(1) |-| **E-commerce** | Category, Product, Customer, Order, OrderLine | Category(0) -> Product(1); Customer(1) -> Order(2) -> OrderLine(3) <- Product(1) |-| **Event Registration** | EventType, Event, Attendee, Registration | EventType(0) -> Event(1); Attendee(1) -> Registration(2) <- Event(1) |-| **Support Portal** | Category, Priority, Ticket, Comment | Category(0), Priority(0) -> Ticket(1) -> Comment(2) |-| **Directory/Listing** | Category, Location, Listing, Review | Category(0), Location(0) -> Listing(1) -> Review(2) |-| **Job Board** | Department, JobType, JobPosting, Application | Department(0), JobType(0) -> JobPosting(1) -> Application(2) |--## Validation Rules--Before table creation, validate:-1. No circular dependencies-2. All referenced tables exist-3. Lookup targets have primary keys-4. Self-references: create table first, then add self-lookupdiff --git a/plugins/power-pages/skills/setup-dataverse/references/relationship-reference.md b/plugins/power-pages/skills/setup-dataverse/references/relationship-reference.mddeleted file mode 100644index 4568feb47..000000000--- a/plugins/power-pages/skills/setup-dataverse/references/relationship-reference.md+++ /dev/null@@ -1,312 +0,0 @@-# Relationship Reference--## Relationship Types--| Type | Description | Use Case |-|------|-------------|----------|-| **1:N (One-to-Many)** | One parent record can have many child records | Category -> Products |-| **N:N (Many-to-Many)** | Records can relate to multiple records in both tables | Products <-> Tags |-| **Self-Referential** | Table references itself | Employee -> Manager |--## Check If Relationship Exists--```powershell-function Test-RelationshipExists {- param([string]$RelationshipSchemaName)-- try {- $result = Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions(SchemaName='$RelationshipSchemaName')?`$select=SchemaName" -Headers $headers -ErrorAction Stop- return $true- } catch {- if ($_.Exception.Response.StatusCode -eq 404) {- return $false- }- throw- }-}-```--## Get Table Relationships--```powershell-function Get-TableRelationships {- param([string]$TableLogicalName)-- # Get 1:N relationships where this table is referenced- $oneToMany = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableLogicalName')/OneToManyRelationships" -Headers $headers-- # Get N:1 relationships where this table references others- $manyToOne = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableLogicalName')/ManyToOneRelationships" -Headers $headers-- Write-Host "`nRelationships for $TableLogicalName`:" -ForegroundColor Cyan-- Write-Host " Referenced by (1:N):" -ForegroundColor Yellow- $oneToMany.value | ForEach-Object {- Write-Host " - $($_.ReferencingEntity).$($_.ReferencingAttribute)"- }-- Write-Host " References (N:1):" -ForegroundColor Yellow- $manyToOne.value | ForEach-Object {- Write-Host " - $($_.ReferencedEntity) via $($_.ReferencingAttribute)"- }-- return @{- OneToMany = $oneToMany.value- ManyToOne = $manyToOne.value- }-}-```--## Create Lookup (1:N Relationship)--```powershell-function Add-DataverseLookup {- param(- [string]$SourceTable, # Table that will have the lookup column- [string]$TargetTable, # Table being referenced (must exist first!)- [string]$LookupSchemaName, # Schema name for the lookup column- [string]$LookupDisplayName, # Display name for the lookup column- [string]$RelationshipName # Unique name for the relationship- )-- # Create a 1:N relationship (Many source records -> One target record)- $relationship = @{- "@odata.type" = "Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata"- "SchemaName" = $RelationshipName- "ReferencedEntity" = $TargetTable # The "one" side (parent/lookup target)- "ReferencingEntity" = $SourceTable # The "many" side (child/has lookup)- "Lookup" = @{- "@odata.type" = "Microsoft.Dynamics.CRM.LookupAttributeMetadata"- "SchemaName" = $LookupSchemaName- "DisplayName" = @{- "@odata.type" = "Microsoft.Dynamics.CRM.Label"- "LocalizedLabels" = @(- @{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $LookupDisplayName; "LanguageCode" = 1033 }- )- }- }- "CascadeConfiguration" = @{- "Assign" = "NoCascade"- "Delete" = "RemoveLink" # When parent deleted, clear the lookup (don't delete children)- "Merge" = "NoCascade"- "Reparent" = "NoCascade"- "Share" = "NoCascade"- "Unshare" = "NoCascade"- }- }-- $body = $relationship | ConvertTo-Json -Depth 10- Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions" -Method Post -Headers $headers -Body $body-}-```--## Safe Lookup Creation (Skip If Exists)--```powershell-function Add-DataverseLookupIfNotExists {- param(- [string]$SourceTable,- [string]$TargetTable,- [string]$LookupSchemaName,- [string]$LookupDisplayName,- [string]$RelationshipName- )-- if (Test-RelationshipExists -RelationshipSchemaName $RelationshipName) {- Write-Host " [SKIP] Relationship '$RelationshipName' already exists" -ForegroundColor Yellow- return @{ Skipped = $true; Reason = "Already exists" }- }-- # Also check if the lookup column already exists (might be from a different relationship)- $lookupLogicalName = $LookupSchemaName.ToLower()- $sourceLogicalName = $SourceTable.ToLower()-- if (Test-ColumnExists -TableLogicalName $sourceLogicalName -ColumnLogicalName $lookupLogicalName) {- Write-Host " [SKIP] Lookup column '$LookupSchemaName' already exists on '$SourceTable'" -ForegroundColor Yellow- return @{ Skipped = $true; Reason = "Lookup column already exists" }- }-- Write-Host " [CREATE] Creating relationship '$RelationshipName' ($SourceTable -> $TargetTable)..." -ForegroundColor Cyan- $result = Add-DataverseLookup -SourceTable $SourceTable -TargetTable $TargetTable `- -LookupSchemaName $LookupSchemaName -LookupDisplayName $LookupDisplayName `- -RelationshipName $RelationshipName-- Write-Host " [OK] Relationship '$RelationshipName' created successfully" -ForegroundColor Green- return @{ Skipped = $false; Result = $result }-}-```--## Create Many-to-Many Relationship--```powershell-function Add-DataverseManyToMany {- param(- [string]$Table1, # First table in the relationship- [string]$Table2, # Second table in the relationship- [string]$RelationshipName, # Unique name for the relationship- [string]$IntersectEntityName # Name for the junction table (auto-created)- )-- # Create N:N relationship (junction table created automatically)- $relationship = @{- "@odata.type" = "Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata"- "SchemaName" = $RelationshipName- "Entity1LogicalName" = $Table1- "Entity2LogicalName" = $Table2- "IntersectEntityName" = $IntersectEntityName- "Entity1AssociatedMenuConfiguration" = @{- "Behavior" = "UseLabel"- "Group" = "Details"- "Label" = @{- "@odata.type" = "Microsoft.Dynamics.CRM.Label"- "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $Table2; "LanguageCode" = 1033 })- }- "Order" = 10000- }- "Entity2AssociatedMenuConfiguration" = @{- "Behavior" = "UseLabel"- "Group" = "Details"- "Label" = @{- "@odata.type" = "Microsoft.Dynamics.CRM.Label"- "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $Table1; "LanguageCode" = 1033 })- }- "Order" = 10000- }- }-- $body = $relationship | ConvertTo-Json -Depth 10- Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions" -Method Post -Headers $headers -Body $body-}-```--## Cascade Configuration Options--When creating relationships, you can configure cascade behavior:--| Option | Description |-|--------|-------------|-| `NoCascade` | No action on related records |-| `Cascade` | Perform action on all related records |-| `Active` | Perform action on active related records |-| `UserOwned` | Perform action on records owned by same user |-| `RemoveLink` | Clear the lookup value (recommended for Delete) |-| `Restrict` | Prevent action if related records exist |--## Relationship Naming Conventions--Follow this naming pattern for consistency, using the `$publisherPrefix` retrieved from `Initialize-DataverseApi`:--```text-{publisherPrefix}_{targetTable}_{sourceTable}--Examples (where $publisherPrefix = "cr"):-- {publisherPrefix}_category_product (Product -> Category)-- {publisherPrefix}_department_teammember (TeamMember -> Department)-- {publisherPrefix}_status_contactsubmission (ContactSubmission -> Status)-```--## Complete Example: Creating Relationships in Dependency Order--**IMPORTANT**: Use the `$tableMap` from `Build-TableNameMapping` to get the correct table names. This ensures:-- **Reused/Extended tables**: Use their actual logical names from Dataverse-- **New tables**: Use the publisher prefix pattern--```powershell-$api = Initialize-DataverseApi -EnvironmentUrl "https://orgname.crm.dynamics.com"-$publisherPrefix = $api.PublisherPrefix--# $tableMap should be built in STEP 5 using Build-TableNameMapping-# It maps table purposes to actual logical names-```--```powershell-# ============================================-# PHASE 3: Create Relationships-# ============================================--Write-Host "`n=== Processing Relationships ===" -ForegroundColor Magenta--# Helper to get actual table name from mapping-function Get-TableName { param([string]$Purpose) return $tableMap[$Purpose].LogicalName }--# --- TIER 1 -> TIER 0 Relationships ----Write-Host "Processing TIER 1 -> TIER 0 relationships..." -ForegroundColor Cyan--# Product -> Category (uses actual table names from mapping)-$productTable = Get-TableName "product"-$categoryTable = Get-TableName "category"-Add-DataverseLookupIfNotExists -SourceTable $productTable -TargetTable $categoryTable `- -LookupSchemaName "${publisherPrefix}_categoryid" -LookupDisplayName "Category" `- -RelationshipName "${publisherPrefix}_${categoryTable}_${productTable}"--# Team Member -> Department-$teammemberTable = Get-TableName "teammember"-$departmentTable = Get-TableName "department"-Add-DataverseLookupIfNotExists -SourceTable $teammemberTable -TargetTable $departmentTable `- -LookupSchemaName "${publisherPrefix}_departmentid" -LookupDisplayName "Department" `- -RelationshipName "${publisherPrefix}_${departmentTable}_${teammemberTable}"--# Contact Submission -> Status-$contactsubmissionTable = Get-TableName "contactsubmission"-$statusTable = Get-TableName "status"-Add-DataverseLookupIfNotExists -SourceTable $contactsubmissionTable -TargetTable $statusTable `- -LookupSchemaName "${publisherPrefix}_statusid" -LookupDisplayName "Status" `- -RelationshipName "${publisherPrefix}_${statusTable}_${contactsubmissionTable}"--# --- TIER 2 -> TIER 1 Relationships ----Write-Host "`nProcessing TIER 2 -> TIER 1 relationships..." -ForegroundColor Cyan--# Testimonial -> Product (optional relationship)-$testimonialTable = Get-TableName "testimonial"-Add-DataverseLookupIfNotExists -SourceTable $testimonialTable -TargetTable $productTable `- -LookupSchemaName "${publisherPrefix}_productid" -LookupDisplayName "Related Product" `- -RelationshipName "${publisherPrefix}_${productTable}_${testimonialTable}"--Write-Host "`n=== Relationship processing complete ===" -ForegroundColor Green-```--**NOTE**: When reusing existing tables, their logical names may differ from the expected pattern:-- New table: `cr_category` (follows `${publisherPrefix}_purpose` pattern)-- Reused table: `contoso_productcategory` or `existing_categories` (actual name from Dataverse)--The `$tableMap` handles this automatically by storing the actual logical names.--## Self-Referential Lookups--For tables that reference themselves (e.g., Employee -> Manager):--```powershell-# First, create the table-New-DataverseTable -SchemaName "${publisherPrefix}_employee" -DisplayName "Employee" -PluralDisplayName "Employees"--# Add regular columns-Add-DataverseColumn -TableName "${publisherPrefix}_employee" -SchemaName "${publisherPrefix}_title" -DisplayName "Job Title" -Type "String"--# Then add self-referential lookup (table must exist first!)-Add-DataverseLookup -SourceTable "${publisherPrefix}_employee" -TargetTable "${publisherPrefix}_employee" `- -LookupSchemaName "${publisherPrefix}_managerid" -LookupDisplayName "Manager" `- -RelationshipName "${publisherPrefix}_employee_manager"-```--## Verifying Relationships--```powershell-# Check if a relationship exists-$relationshipName = "${publisherPrefix}_category_product"-$relations = Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions?`$filter=SchemaName eq '$relationshipName'" -Headers $headers-if ($relations.value.Count -gt 0) {- Write-Host "Relationship exists" -ForegroundColor Green- Write-Host " Referenced Entity: $($relations.value[0].ReferencedEntity)"- Write-Host " Referencing Entity: $($relations.value[0].ReferencingEntity)"-} else {- Write-Host "Relationship not found" -ForegroundColor Yellow-}--# List all relationships for a table-$tableName = "${publisherPrefix}_product"-$tableRelations = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$tableName')/ManyToOneRelationships" -Headers $headers-Write-Host "Lookups on ${tableName}:" -ForegroundColor Cyan-$tableRelations.value | ForEach-Object {- Write-Host " $($_.SchemaName): -> $($_.ReferencedEntity)"-}-```diff --git a/plugins/power-pages/skills/setup-dataverse/references/table-management-reference.md b/plugins/power-pages/skills/setup-dataverse/references/table-management-reference.mddeleted file mode 100644index 62cda6a9d..000000000--- a/plugins/power-pages/skills/setup-dataverse/references/table-management-reference.md+++ /dev/null@@ -1,510 +0,0 @@-# Table Management Reference--## Query Existing Custom Tables--Before creating tables, review existing custom tables in the environment:--```powershell-# Get all custom tables (entities) in the environment-$existingTables = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions?`$filter=IsCustomEntity eq true&`$select=SchemaName,LogicalName,DisplayName,Description,PrimaryNameAttribute" -Headers $headers--Write-Host "Found $($existingTables.value.Count) custom tables in the environment:" -ForegroundColor Cyan-$existingTables.value | ForEach-Object {- $displayName = $_.DisplayName.UserLocalizedLabel.Label- Write-Host " - $($_.SchemaName) ($displayName)" -ForegroundColor Yellow-}-```--## Get Table Schema Details--```powershell-function Get-TableSchema {- param([string]$TableLogicalName)-- # Get table metadata with attributes- $tableInfo = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableLogicalName')?`$expand=Attributes(`$select=SchemaName,LogicalName,AttributeType,DisplayName,MaxLength)" -Headers $headers-- Write-Host "`nTable: $($tableInfo.SchemaName)" -ForegroundColor Cyan- Write-Host "Display Name: $($tableInfo.DisplayName.UserLocalizedLabel.Label)"- Write-Host "Primary Column: $($tableInfo.PrimaryNameAttribute)"- Write-Host "Columns:" -ForegroundColor Yellow-- $tableInfo.Attributes | Where-Object {- # Filter out system columns- $_.SchemaName -notmatch '^(Created|Modified|Owner|State|Status|Version|Import|Overridden|TimeZone|UTCConversion|Traversed)'- } | ForEach-Object {- $displayName = if ($_.DisplayName.UserLocalizedLabel) { $_.DisplayName.UserLocalizedLabel.Label } else { $_.SchemaName }- Write-Host " - $($_.SchemaName) ($($_.AttributeType)) - $displayName"- }-- return $tableInfo-}-```--## Compare Existing vs Required Tables--```powershell-function Compare-TableSchemas {- param(- [hashtable]$RequiredTables, # Purpose name -> array of required columns (e.g., "category", "product")- [array]$ExistingTables # From EntityDefinitions query- )-- $comparison = @{- Reusable = @() # Existing tables that match or exceed requirements- Extendable = @() # Existing tables that need additional columns- CreateNew = @() # Tables that don't exist and must be created- }-- foreach ($tablePurpose in $RequiredTables.Keys) {- # Search for existing tables that match this purpose (by name patterns)- $existing = Find-SimilarTables -Purpose $tablePurpose -ExistingTables $ExistingTables | Select-Object -First 1-- if ($existing) {- # Table exists - check if it has all required columns- $tableSchema = Get-TableSchema -TableLogicalName $existing.LogicalName- $existingColumns = $tableSchema.Attributes | Select-Object -ExpandProperty SchemaName- $requiredColumns = $RequiredTables[$tablePurpose]-- $missingColumns = $requiredColumns | Where-Object { $_ -notin $existingColumns }-- if ($missingColumns.Count -eq 0) {- $comparison.Reusable += @{- TablePurpose = $tablePurpose # Intended purpose (e.g., "category")- ActualLogicalName = $existing.LogicalName # Actual name in Dataverse (e.g., "cr_productcategory")- ActualSchemaName = $existing.SchemaName # Schema name (e.g., "cr_ProductCategory")- ExistingTable = $existing- Message = "All required columns present"- }- } else {- $comparison.Extendable += @{- TablePurpose = $tablePurpose- ActualLogicalName = $existing.LogicalName- ActualSchemaName = $existing.SchemaName- ExistingTable = $existing- MissingColumns = $missingColumns- Message = "Missing columns: $($missingColumns -join ', ')"- }- }- } else {- $comparison.CreateNew += @{- TablePurpose = $tablePurpose- # New tables will use the publisher prefix pattern- NewSchemaName = "${publisherPrefix}_$tablePurpose"- NewLogicalName = "${publisherPrefix}_$tablePurpose".ToLower()- RequiredColumns = $RequiredTables[$tablePurpose]- }- }- }-- return $comparison-}-```--## Build Table Name Mapping--After comparing tables and getting user decisions, build a mapping that tracks the actual logical names to use for each table purpose. This is **critical** for correctly referencing tables throughout the workflow.--```powershell-function Build-TableNameMapping {- param(- [object]$ComparisonResult, # From Compare-TableSchemas- [string]$PublisherPrefix # From Initialize-DataverseApi- )-- # Maps table purpose -> actual logical name and entity set name- # This ensures we use existing table names when reusing, and new names when creating- $tableMapping = @{}-- # Tables being reused - use their ACTUAL logical names- foreach ($table in $ComparisonResult.Reusable) {- $tableMapping[$table.TablePurpose] = @{- LogicalName = $table.ActualLogicalName- SchemaName = $table.ActualSchemaName- EntitySetName = $table.ActualLogicalName + "es" # Pluralized for OData (may need adjustment)- Source = "Reused"- }- Write-Host " [REUSE] $($table.TablePurpose) -> $($table.ActualLogicalName)" -ForegroundColor Yellow- }-- # Tables being extended - use their ACTUAL logical names- foreach ($table in $ComparisonResult.Extendable) {- $tableMapping[$table.TablePurpose] = @{- LogicalName = $table.ActualLogicalName- SchemaName = $table.ActualSchemaName- EntitySetName = $table.ActualLogicalName + "es"- Source = "Extended"- }- Write-Host " [EXTEND] $($table.TablePurpose) -> $($table.ActualLogicalName)" -ForegroundColor Cyan- }-- # Tables being created - use the publisher prefix pattern- foreach ($table in $ComparisonResult.CreateNew) {- $logicalName = "${PublisherPrefix}_$($table.TablePurpose)".ToLower()- $schemaName = "${PublisherPrefix}_$($table.TablePurpose)"- $tableMapping[$table.TablePurpose] = @{- LogicalName = $logicalName- SchemaName = $schemaName- EntitySetName = $logicalName + "s" # Standard pluralization for new tables- Source = "Created"- }- Write-Host " [CREATE] $($table.TablePurpose) -> $logicalName" -ForegroundColor Green- }-- return $tableMapping-}--# Example usage:-# $comparison = Compare-TableSchemas -RequiredTables $requiredTables -ExistingTables $existingTables.value-# $tableMap = Build-TableNameMapping -ComparisonResult $comparison -PublisherPrefix $publisherPrefix-#-# # Later, when referencing tables, use the mapping:-# $categoryTable = $tableMap["category"].LogicalName # e.g., "existing_productcategory" or "cr_category"-# $categoryEntitySet = $tableMap["category"].EntitySetName # e.g., "existing_productcategories" or "cr_categorys"-```--**IMPORTANT**: Always use the `$tableMap` to get the correct table names throughout the workflow:-- For relationships: `$tableMap["product"].LogicalName` instead of `"${publisherPrefix}_product"`-- For data queries: `$tableMap["category"].EntitySetName` instead of `"${publisherPrefix}_categories"`-- For column additions: `$tableMap["teammember"].LogicalName` instead of `"${publisherPrefix}_teammember"`--## Find Similar Tables--Search for tables with similar purposes but different names:--```powershell-function Find-SimilarTables {- param(- [string]$Purpose, # e.g., "category", "product", "contact"- [array]$ExistingTables- )-- # Common naming patterns to search for- $patterns = @{- "category" = @("category", "categories", "type", "types", "classification")- "product" = @("product", "products", "item", "items", "service", "services", "offering")- "contact" = @("contact", "contacts", "submission", "inquiry", "lead", "leads")- "team" = @("team", "employee", "staff", "member", "person", "people")- "testimonial" = @("testimonial", "review", "feedback", "rating")- }-- $searchTerms = $patterns[$Purpose]- if (-not $searchTerms) { $searchTerms = @($Purpose) }-- $matches = $ExistingTables | Where-Object {- $tableName = $_.SchemaName.ToLower()- $displayName = $_.DisplayName.UserLocalizedLabel.Label.ToLower()-- foreach ($term in $searchTerms) {- if ($tableName -match $term -or $displayName -match $term) {- return $true- }- }- return $false- }-- return $matches-}-```--## Check If Table/Column Exists--```powershell-function Test-TableExists {- param([string]$TableLogicalName)-- try {- $result = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableLogicalName')?`$select=LogicalName" -Headers $headers -ErrorAction Stop- return $true- } catch {- if ($_.Exception.Response.StatusCode -eq 404) {- return $false- }- throw- }-}--function Test-ColumnExists {- param(- [string]$TableLogicalName,- [string]$ColumnLogicalName- )-- try {- $result = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableLogicalName')/Attributes(LogicalName='$ColumnLogicalName')?`$select=LogicalName" -Headers $headers -ErrorAction Stop- return $true- } catch {- if ($_.Exception.Response.StatusCode -eq 404) {- return $false- }- throw- }-}-```--## Create Table Helper Function--**IMPORTANT**: Use the `$publisherPrefix` variable (retrieved via `Initialize-DataverseApi`) for all table and column schema names. Never hardcode prefixes.--```powershell-function New-DataverseTable {- param(- [string]$SchemaName,- [string]$DisplayName,- [string]$PluralDisplayName,- [string]$Description = "",- [string]$PrimaryColumnName = "${publisherPrefix}_name",- [string]$PrimaryColumnDisplayName = "Name"- )-- $tableDefinition = @{- "@odata.type" = "Microsoft.Dynamics.CRM.EntityMetadata"- "SchemaName" = $SchemaName- "DisplayName" = @{- "@odata.type" = "Microsoft.Dynamics.CRM.Label"- "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $DisplayName; "LanguageCode" = 1033 })- }- "DisplayCollectionName" = @{- "@odata.type" = "Microsoft.Dynamics.CRM.Label"- "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $PluralDisplayName; "LanguageCode" = 1033 })- }- "Description" = @{- "@odata.type" = "Microsoft.Dynamics.CRM.Label"- "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $Description; "LanguageCode" = 1033 })- }- "OwnershipType" = "UserOwned"- "HasNotes" = $false- "HasActivities" = $false- "PrimaryNameAttribute" = $PrimaryColumnName- "Attributes" = @(- @{- "@odata.type" = "Microsoft.Dynamics.CRM.StringAttributeMetadata"- "SchemaName" = $PrimaryColumnName- "AttributeType" = "String"- "FormatName" = @{ "Value" = "Text" }- "MaxLength" = 100- "DisplayName" = @{- "@odata.type" = "Microsoft.Dynamics.CRM.Label"- "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $PrimaryColumnDisplayName; "LanguageCode" = 1033 })- }- "IsPrimaryName" = $true- }- )- }-- $body = $tableDefinition | ConvertTo-Json -Depth 10- Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions" -Method Post -Headers $headers -Body $body-}-```--## Safe Table Creation (Skip If Exists)--```powershell-function New-DataverseTableIfNotExists {- param(- [string]$SchemaName,- [string]$DisplayName,- [string]$PluralDisplayName,- [string]$Description = "",- [string]$PrimaryColumnName = "${publisherPrefix}_name",- [string]$PrimaryColumnDisplayName = "Name"- )-- $logicalName = $SchemaName.ToLower()-- if (Test-TableExists -TableLogicalName $logicalName) {- Write-Host " [SKIP] Table '$SchemaName' already exists" -ForegroundColor Yellow- return @{ Skipped = $true; Reason = "Already exists" }- }-- Write-Host " [CREATE] Creating table '$SchemaName'..." -ForegroundColor Cyan- $result = New-DataverseTable -SchemaName $SchemaName -DisplayName $DisplayName `- -PluralDisplayName $PluralDisplayName -Description $Description `- -PrimaryColumnName $PrimaryColumnName -PrimaryColumnDisplayName $PrimaryColumnDisplayName-- Write-Host " [OK] Table '$SchemaName' created successfully" -ForegroundColor Green- return @{ Skipped = $false; Result = $result }-}-```--## Add Column Helper Function--```powershell-function Add-DataverseColumn {- param(- [string]$TableName,- [string]$SchemaName,- [string]$DisplayName,- [string]$Type, # String, Email, Url, Memo, Integer, Money, DateTime, Boolean- [int]$MaxLength = 100- )-- $columnTypes = @{- "String" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.StringAttributeMetadata"; "AttributeType" = "String"; "FormatName" = @{ "Value" = "Text" }; "MaxLength" = $MaxLength }- "Email" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.StringAttributeMetadata"; "AttributeType" = "String"; "FormatName" = @{ "Value" = "Email" }; "MaxLength" = $MaxLength }- "Url" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.StringAttributeMetadata"; "AttributeType" = "String"; "FormatName" = @{ "Value" = "Url" }; "MaxLength" = 200 }- "Memo" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.MemoAttributeMetadata"; "AttributeType" = "Memo"; "MaxLength" = $MaxLength }- "Integer" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.IntegerAttributeMetadata"; "AttributeType" = "Integer"; "MinValue" = -2147483648; "MaxValue" = 2147483647 }- "Money" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.MoneyAttributeMetadata"; "AttributeType" = "Money"; "PrecisionSource" = 2 }- "DateTime" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.DateTimeAttributeMetadata"; "AttributeType" = "DateTime"; "Format" = "DateAndTime" }- "Boolean" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.BooleanAttributeMetadata"; "AttributeType" = "Boolean" }- }-- $column = $columnTypes[$Type].Clone()- $column["SchemaName"] = $SchemaName- $column["DisplayName"] = @{- "@odata.type" = "Microsoft.Dynamics.CRM.Label"- "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $DisplayName; "LanguageCode" = 1033 })- }-- Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableName')/Attributes" -Method Post -Headers $headers -Body ($column | ConvertTo-Json -Depth 10)-}-```--## Safe Column Addition (Skip If Exists)--```powershell-function Add-DataverseColumnIfNotExists {- param(- [string]$TableName,- [string]$SchemaName,- [string]$DisplayName,- [string]$Type,- [int]$MaxLength = 100- )-- $columnLogicalName = $SchemaName.ToLower()- $tableLogicalName = $TableName.ToLower()-- if (Test-ColumnExists -TableLogicalName $tableLogicalName -ColumnLogicalName $columnLogicalName) {- Write-Host " [SKIP] Column '$SchemaName' already exists on '$TableName'" -ForegroundColor Yellow- return @{ Skipped = $true; Reason = "Already exists" }- }-- Write-Host " [CREATE] Adding column '$SchemaName' to '$TableName'..." -ForegroundColor Cyan- $result = Add-DataverseColumn -TableName $TableName -SchemaName $SchemaName `- -DisplayName $DisplayName -Type $Type -MaxLength $MaxLength-- Write-Host " [OK] Column '$SchemaName' added successfully" -ForegroundColor Green- return @{ Skipped = $false; Result = $result }-}-```--## Add Choice/Picklist Column--```powershell-function Add-DataversePicklist {- param(- [string]$TableName,- [string]$SchemaName,- [string]$DisplayName,- [hashtable[]]$Options # Array of @{ Value = 1; Label = "Option 1" }- )-- $optionMetadata = $Options | ForEach-Object {- @{- "Value" = $_.Value- "Label" = @{- "@odata.type" = "Microsoft.Dynamics.CRM.Label"- "LocalizedLabels" = @(@{- "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"- "Label" = $_.Label- "LanguageCode" = 1033- })- }- }- }-- $column = @{- "@odata.type" = "Microsoft.Dynamics.CRM.PicklistAttributeMetadata"- "SchemaName" = $SchemaName- "AttributeType" = "Picklist"- "DisplayName" = @{- "@odata.type" = "Microsoft.Dynamics.CRM.Label"- "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $DisplayName; "LanguageCode" = 1033 })- }- "OptionSet" = @{- "@odata.type" = "Microsoft.Dynamics.CRM.OptionSetMetadata"- "IsGlobal" = $false- "OptionSetType" = "Picklist"- "Options" = $optionMetadata- }- }-- Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableName')/Attributes" -Method Post -Headers $headers -Body ($column | ConvertTo-Json -Depth 10)-}--# Example usage:-# Add-DataversePicklist -TableName "${publisherPrefix}_contactsubmission" -SchemaName "${publisherPrefix}_status" -DisplayName "Status" -Options @(-# @{ Value = 1; Label = "New" },-# @{ Value = 2; Label = "Reviewed" },-# @{ Value = 3; Label = "Responded" },-# @{ Value = 4; Label = "Closed" }-# )-```--## Common Table Templates--**NOTE**: All examples below use `$publisherPrefix` variable. Initialize it first using:-```powershell-$api = Initialize-DataverseApi -EnvironmentUrl "https://orgname.crm.dynamics.com"-$publisherPrefix = $api.PublisherPrefix # e.g., "cr", "contoso", "new"-```--### Product/Service Table--```powershell-New-DataverseTable -SchemaName "${publisherPrefix}_product" -DisplayName "Product" -PluralDisplayName "Products" -Description "Products and services offered"--Add-DataverseColumn -TableName "${publisherPrefix}_product" -SchemaName "${publisherPrefix}_description" -DisplayName "Description" -Type "Memo" -MaxLength 4000-Add-DataverseColumn -TableName "${publisherPrefix}_product" -SchemaName "${publisherPrefix}_price" -DisplayName "Price" -Type "Money"-Add-DataverseColumn -TableName "${publisherPrefix}_product" -SchemaName "${publisherPrefix}_imageurl" -DisplayName "Image URL" -Type "Url"-Add-DataverseColumn -TableName "${publisherPrefix}_product" -SchemaName "${publisherPrefix}_isactive" -DisplayName "Is Active" -Type "Boolean"-```--### Team Member Table--```powershell-New-DataverseTable -SchemaName "${publisherPrefix}_teammember" -DisplayName "Team Member" -PluralDisplayName "Team Members" -Description "Team members displayed on the website"--Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_title" -DisplayName "Job Title" -Type "String"-Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_email" -DisplayName "Email" -Type "Email"-Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_bio" -DisplayName "Bio" -Type "Memo" -MaxLength 4000-Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_photourl" -DisplayName "Photo URL" -Type "Url"-Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_linkedin" -DisplayName "LinkedIn" -Type "Url"-Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_displayorder" -DisplayName "Display Order" -Type "Integer"-```--### Testimonial Table--```powershell-New-DataverseTable -SchemaName "${publisherPrefix}_testimonial" -DisplayName "Testimonial" -PluralDisplayName "Testimonials" -Description "Customer testimonials and reviews"--Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_quote" -DisplayName "Quote" -Type "Memo" -MaxLength 2000-Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_company" -DisplayName "Company" -Type "String"-Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_role" -DisplayName "Role" -Type "String"-Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_rating" -DisplayName "Rating" -Type "Integer"-Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_photourl" -DisplayName "Photo URL" -Type "Url"-Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_isactive" -DisplayName "Is Active" -Type "Boolean"-```--### Contact Submission Table--```powershell-New-DataverseTable -SchemaName "${publisherPrefix}_contactsubmission" -DisplayName "Contact Submission" -PluralDisplayName "Contact Submissions" -Description "Contact form submissions from the website"--Add-DataverseColumn -TableName "${publisherPrefix}_contactsubmission" -SchemaName "${publisherPrefix}_email" -DisplayName "Email" -Type "Email"-Add-DataverseColumn -TableName "${publisherPrefix}_contactsubmission" -SchemaName "${publisherPrefix}_message" -DisplayName "Message" -Type "Memo" -MaxLength 4000-Add-DataverseColumn -TableName "${publisherPrefix}_contactsubmission" -SchemaName "${publisherPrefix}_submissiondate" -DisplayName "Submission Date" -Type "DateTime"-```--### FAQ Table--```powershell-New-DataverseTable -SchemaName "${publisherPrefix}_faq" -DisplayName "FAQ" -PluralDisplayName "FAQs" -Description "Frequently asked questions" -PrimaryColumnName "${publisherPrefix}_question" -PrimaryColumnDisplayName "Question"--Add-DataverseColumn -TableName "${publisherPrefix}_faq" -SchemaName "${publisherPrefix}_answer" -DisplayName "Answer" -Type "Memo" -MaxLength 4000-Add-DataverseColumn -TableName "${publisherPrefix}_faq" -SchemaName "${publisherPrefix}_category" -DisplayName "Category" -Type "String"-Add-DataverseColumn -TableName "${publisherPrefix}_faq" -SchemaName "${publisherPrefix}_displayorder" -DisplayName "Display Order" -Type "Integer"-Add-DataverseColumn -TableName "${publisherPrefix}_faq" -SchemaName "${publisherPrefix}_isactive" -DisplayName "Is Active" -Type "Boolean"-```diff --git a/plugins/power-pages/skills/setup-dataverse/references/troubleshooting.md b/plugins/power-pages/skills/setup-dataverse/references/troubleshooting.mddeleted file mode 100644index 8efc7ddb3..000000000--- a/plugins/power-pages/skills/setup-dataverse/references/troubleshooting.md+++ /dev/null@@ -1,343 +0,0 @@-# Troubleshooting--## Existing Table Detection Issues--### Tables not found--- Ensure the filter `IsCustomEntity eq true` is correct for your needs-- Some tables may be managed or system tables that don't appear in custom entity queries--### Wrong publisher prefix--Tables may have different prefixes depending on the solution. **Always use `Initialize-DataverseApi` to fetch the correct prefix dynamically:**--```powershell-# Get the default publisher prefix-$api = Initialize-DataverseApi -EnvironmentUrl $envUrl-$publisherPrefix = $api.PublisherPrefix # e.g., "cr", "contoso", "new"--# Search for tables with any custom prefix-$allCustomTables = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions?`$filter=IsCustomEntity eq true" -Headers $headers-$allCustomTables.value | ForEach-Object { Write-Host $_.SchemaName }-```--Common prefixes: `cr_`, `new_`, `contoso_`, `msft_` - but always fetch dynamically to ensure consistency.--### System tables included--Add additional filters to exclude system tables:--```powershell-$filter = "IsCustomEntity eq true and IsManaged eq false"-```--### Case sensitivity--Table logical names are case-insensitive but schema names preserve case. Always use lowercase for logical names in API calls.--## Table Reuse Issues--### Existing table has different schema--If the existing table's schema is too different:--- Consider creating a new table with a unique name (e.g., `${publisherPrefix}_site_category` instead of `${publisherPrefix}_category`)-- Or extend the existing table and use only the columns you need--### Column type mismatch--Cannot change column types after creation. Options:--- Create a new column with a different name-- Use the existing column type if compatible-- Create an entirely new table--### Relationship conflicts--Verify existing relationships don't prevent your intended lookups:--```powershell-Get-TableRelationships -TableLogicalName "${publisherPrefix}_product"-```--### Missing required columns on reused table--Use `Add-DataverseColumnIfNotExists` to add only missing columns without errors.--## Dataverse Web API Errors--### Authentication errors--```text-Error: 401 Unauthorized-```--**Solutions:**--1. Verify Azure CLI is logged in: `az login`-2. Check access token is valid: `az account get-access-token --resource <env-url>`-3. Token may have expired (tokens last ~1 hour), get a fresh one-4. Ensure you're using the correct environment URL--### Permission errors--```text-Error: 403 Forbidden-```--**Solutions:**--Ensure you have appropriate Dataverse permissions:--- **System Administrator** - Full access-- **System Customizer** - Can create and modify tables--### Rate limiting--```text-Error: 429 Too Many Requests-```--**Solutions:**--- Add delays between API calls-- Batch operations where possible-- Retry with exponential backoff--```powershell-function Invoke-WithRetry {- param(- [scriptblock]$ScriptBlock,- [int]$MaxRetries = 3- )-- $retryCount = 0- while ($retryCount -lt $MaxRetries) {- try {- return & $ScriptBlock- } catch {- if ($_.Exception.Response.StatusCode -eq 429) {- $retryCount++- $waitTime = [math]::Pow(2, $retryCount)- Write-Host "Rate limited. Waiting $waitTime seconds..." -ForegroundColor Yellow- Start-Sleep -Seconds $waitTime- } else {- throw- }- }- }- throw "Max retries exceeded"-}-```--## Table Creation Fails--### Invalid schema name--```text-Error: "The schema name is invalid"-```--**Solutions:**--- Verify schema name uses the correct publisher prefix from `Initialize-DataverseApi` (e.g., `${publisherPrefix}_tablename`)-- Schema names must start with a letter-- Only alphanumeric characters and underscores allowed-- Maximum 128 characters--### Table already exists--```text-Error: "Entity with this name already exists"-```--**Solutions:**--- Use `Test-TableExists` before creating-- Use `New-DataverseTableIfNotExists` helper function-- Choose a unique schema name--### Missing required metadata--```text-Error: "Required field missing"-```--**Solutions:**--Ensure all required metadata fields are included:--- `SchemaName`-- `DisplayName` with `LocalizedLabels`-- `DisplayCollectionName` (plural name)-- `PrimaryNameAttribute`--## Relationship/Lookup Creation Fails--### Referenced entity not found--```text-Error: "Referenced entity '{prefix}_category' not found"-```--**Solutions:**--- Ensure the target table exists BEFORE creating the lookup-- Check creation order: TIER 0 tables must exist before TIER 1, etc.-- Verify the table logical name is correct (case-insensitive)-- Ensure you're using the correct publisher prefix from `Initialize-DataverseApi`--### Duplicate relationship name--```text-Error: "Relationship with this name already exists"-```--**Solutions:**--- Relationship names must be unique across the environment-- Use a consistent naming pattern: `{publisher}_{targettable}_{sourcetable}`-- Use `Test-RelationshipExists` before creating--### Invalid target entity--```text-Error: "Invalid target entity for relationship"-```--**Solutions:**--- The target table must have a primary key attribute-- Ensure the table is not a virtual entity or external data source--### Self-referential lookup fails--**Solution:** Create the table first, then add the self-lookup as a separate step:--```powershell-# Step 1: Create table-New-DataverseTable -SchemaName "${publisherPrefix}_employee" ...--# Step 2: Add self-referential lookup (table now exists)-Add-DataverseLookup -SourceTable "${publisherPrefix}_employee" -TargetTable "${publisherPrefix}_employee" ...-```--## Sample Data Insertion Fails--### Foreign key violation--```text-Error: "The specified lookup reference does not exist"-```--**Solutions:**--- Insert TIER 0 data first, then TIER 1, then TIER 2-- Verify the lookup ID is correct (GUIDs are case-insensitive)-- If reusing existing lookup tables, query for existing record IDs first--### Invalid @odata.bind syntax--```text-Error: "Invalid @odata.bind value"-```--**Solutions:**--Format must be exactly: `/entitysetname(guid)`--```powershell-# Correct (using $publisherPrefix variable)-"${publisherPrefix}[email protected]" = "/${publisherPrefix}_categories(12345678-1234-1234-1234-123456789012)"--# Wrong - missing leading slash-"${publisherPrefix}[email protected]" = "${publisherPrefix}_categories(12345678-1234-1234-1234-123456789012)"--# Wrong - using logical name instead of entity set name-"${publisherPrefix}[email protected]" = "/${publisherPrefix}_category(12345678-1234-1234-1234-123456789012)"-```--### Entity set not found--```text-Error: "Resource not found for segment '{prefix}_product'"-```--**Solutions:**--Use the plural entity set name, not the logical name:--- Table `{prefix}_product` has entity set `{prefix}_products` (usually adds 's')-- Table `{prefix}_category` has entity set `{prefix}_categories` (adds 'ies')--Find the correct entity set name:--```powershell-$tableName = "${publisherPrefix}_product"-$table = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$tableName')?`$select=EntitySetName" -Headers $headers-Write-Host "Entity set name: $($table.EntitySetName)"-```--### Duplicate record errors--If using `New-DataverseRecordIfNotExists`, records with the same name are skipped. If inserts still fail:--- Check for unique constraints on other columns-- Verify the name column matches your expectation--## Existing Data Conflicts--### Stale record IDs--If reusing tables, always query for current record IDs; don't use cached values:--```powershell-# Always get fresh IDs before inserting dependent records-$categories = Invoke-RestMethod -Uri "$baseUrl/${publisherPrefix}_categories?`$select=${publisherPrefix}_categoryid,${publisherPrefix}_name" -Headers $headers-$categoryIds = @{}-$categories.value | ForEach-Object { $categoryIds[$_."${publisherPrefix}_name"] = $_."${publisherPrefix}_categoryid" }-```--### Data format differences--Existing records may have different formats:--- Dates: Use ISO 8601 format `yyyy-MM-ddTHH:mm:ssZ`-- Currency: Ensure correct decimal precision-- Text: Check MaxLength constraints--### Orphaned lookups--When reusing tables, verify that lookup values still exist:--```powershell-# Check for orphaned references-$products = Invoke-RestMethod -Uri "$baseUrl/${publisherPrefix}_products?`$select=${publisherPrefix}_name&`$expand=${publisherPrefix}_categoryid(`$select=${publisherPrefix}_name)" -Headers $headers-$products.value | Where-Object { $_."${publisherPrefix}_categoryid" -eq $null } | ForEach-Object {- Write-Host "Orphaned product (no category): $($_."${publisherPrefix}_name")" -ForegroundColor Yellow-}-```--## Verifying Relationships--```powershell-# Check if a relationship exists-$relationshipName = "${publisherPrefix}_category_product"-$relations = Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions?`$filter=SchemaName eq '$relationshipName'" -Headers $headers-if ($relations.value.Count -gt 0) {- Write-Host "Relationship exists"-} else {- Write-Host "Relationship not found"-}--# List all relationships for a table-$tableName = "${publisherPrefix}_product"-$tableRelations = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$tableName')/OneToManyRelationships" -Headers $headers-$tableRelations.value | ForEach-Object { Write-Host $_.SchemaName }-```--## Reference Documentation--- [Dataverse Web API](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/overview)-- [Dataverse Entity Metadata](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-update-entity-definitions-using-web-api)-- [OData Query Options](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-data-web-api)diff --git a/plugins/power-pages/skills/setup-webapi/SKILL.md b/plugins/power-pages/skills/setup-webapi/SKILL.mddeleted file mode 100644index 29b399fa7..000000000--- a/plugins/power-pages/skills/setup-webapi/SKILL.md+++ /dev/null@@ -1,133 +0,0 @@-----name: setting-up-web-api-description: Configures Web API access, table permissions, web roles, and site settings for Power Pages. Use when setting up table permissions, entity permissions, CRUD access, or site settings for Web API.-user-invocable: true-allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task", "ExitPlanMode"]-model: opus------**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.--# Setup Web API--**References:** [site-settings](./references/site-settings-reference.md) | [web-roles](./references/web-roles-reference.md) | [table-permissions](./references/table-permissions-reference.md) | [troubleshooting](./references/troubleshooting.md)--## Workflow--1. **Plan** → Check context, design permissions strategy, get approval-2. **Create Site Settings** → `Webapi/{table}/enabled` and `fields` for each table-3. **Create Web Roles** → Verify/create Anonymous, Authenticated, custom roles-4. **Create Table Permissions** → Link to web roles with appropriate scope-5. **Build and Upload** → Deploy and verify-------## Step 1: Plan--### 1.1 Check Context--Read `memory-bank.md`. **Critical**: Get the **Table Name Mapping** - use actual logical names (may differ from `{prefix}_tablename` for reused tables).--If continuing from `/setup-dataverse`, list tables to configure. Otherwise ask for project path and tables.--### 1.2 Enter Plan Mode--Use `/plan` command to enter plan mode and create an implementation plan covering:-- Tables requiring Web API access-- Permissions matrix (which roles get which CRUD operations on which tables)-- Web roles to create or verify-- Site settings to create-- Security considerations (scope: Global vs Self)--### 1.3 Get Approval--Present the permissions plan to the user as a table showing:-- Table name → Web role → Permissions (Read/Create/Write/Delete) → Scope--Use `ExitPlanMode` only after user approves. If user requests changes, update the plan and present again.-------## Step 2: Create Site Settings--See [site-settings-reference.md](./references/site-settings-reference.md).--For each table, create in `.powerpages-site/site-settings/`:-1. `Webapi-<table>-enabled.sitesetting.yml`-2. `Webapi-<table>-fields.sitesetting.yml` - **explicit field names only, never `*`**--Also create authoring tool setting per [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md).-------## Step 3: Create Web Roles--See [web-roles-reference.md](./references/web-roles-reference.md).--Create roles **before** table permissions using YAML files in `.powerpages-site/web-roles/`.--| Feature | Role |-|---------|------|-| Public content | Anonymous Users |-| Form submissions | Anonymous Users (create-only) |-| User dashboard | Authenticated Users |-| Customer portal | Custom role |--**Steps:**-1. Check existing roles in `.powerpages-site/web-roles/` (created after first upload)-2. Create custom role YAML files as needed:- ```yaml- anonymoususersrole: false- authenticatedusersrole: false- id: <GENERATE_UUID>- name: Customers- ```-3. Upload to apply: `pac pages upload-code-site`-------## Step 4: Create Table Permissions--See [table-permissions-reference.md](./references/table-permissions-reference.md).--| Data Type | Scope | Permissions | Role |-|-----------|-------|-------------|------|-| Public content | Global | Read | Anonymous |-| Form submissions | Global | Create | Anonymous |-| User data | Self | Read, Write | Authenticated |--Use `New-TablePermission` and link to web roles from Step 3.-------## Step 5: Build and Upload--```powershell-pac auth list # Show available environments-```--**Ask user which environment** to upload to using `AskUserQuestion` (show org names from auth list). Switch if needed: `pac auth select --index <n>`.--**Create skill tracking setting, build, and upload:**-```powershell-New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupWebApi"-npm run build # Always build before upload-pac pages upload-code-site --rootPath "<PROJECT_ROOT>"-```--See [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md) for helper function.--**Test in browser console:**-```javascript-fetch('/_api/{prefix}_products').then(r => r.json()).then(d => console.log(d.value))-```--Update memory-bank.md. Cleanup per [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md).-------## Next Steps--Run `/integrate-webapi` to connect frontend code to the Web API (replace mock data with API calls).--Then run `/setup-auth` to add authentication and authorization.diff --git a/plugins/power-pages/skills/setup-webapi/references/site-settings-reference.md b/plugins/power-pages/skills/setup-webapi/references/site-settings-reference.mddeleted file mode 100644index 09f7cfe29..000000000--- a/plugins/power-pages/skills/setup-webapi/references/site-settings-reference.md+++ /dev/null@@ -1,283 +0,0 @@-# Site Settings Reference--## Folder Structure--Site settings in Power Pages code sites are stored in the `.powerpages-site/site-settings` folder. Each setting is a separate YAML file with a unique ID.--**IMPORTANT**: Use the **actual table logical names** from the `$tableMap` built in `/setup-dataverse`:-- For **reused/extended tables**: Use the existing logical name (e.g., `contoso_items`, `existing_productcategory`)-- For **new tables**: Use `{prefix}_tablename` pattern (e.g., `cr_product`)--```text-<PROJECT_ROOT>/-├── .powerpages-site/-│ ├── site-settings/-│ │ ├── Webapi-{actual_product_table}-enabled.sitesetting.yml-│ │ ├── Webapi-{actual_product_table}-fields.sitesetting.yml-│ │ ├── Webapi-{actual_teammember_table}-enabled.sitesetting.yml-│ │ └── ...-│ └── ...-```--## Site Setting File Format--Each site setting file follows this YAML format:--```yaml-description: <OPTIONAL_DESCRIPTION>-id: <UUID>-name: <SETTING_NAME>-value: <SETTING_VALUE>-```--**Important**: Field names do NOT include the `adx_` prefix (e.g., use `name` not `adx_name`).--### YAML Field Reference--| Field | Type | Required | Description |-|-------|------|----------|-------------|-| `id` | GUID | Yes | Unique identifier for this setting |-| `name` | string | Yes | Setting name (key) |-| `value` | string | Yes | Setting value |-| `description` | string | No | Optional description of the setting |--**File naming convention**: `<SETTING_NAME_WITH_DASHES>.sitesetting.yml`-- Replace `/` with `-` in the setting name-- Example: Setting `Webapi/{prefix}_product/enabled` → File `Webapi-{prefix}_product-enabled.sitesetting.yml`--### Generating Unique IDs--Each site setting must have a unique `id` field (UUID/GUID format: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`).--**Claude Code MUST generate UUIDs by running a CLI command** - never write UUID values directly. Use the Bash tool to execute the appropriate command based on the user's shell/platform:--| Shell/Platform | Command |-|----------------|---------|-| **PowerShell** (Windows) | `[guid]::NewGuid().ToString()` |-| **Bash** (Linux) | `cat /proc/sys/kernel/random/uuid` |-| **Bash/Zsh** (macOS) | `uuidgen \| tr '[:upper:]' '[:lower:]'` |--## Required Site Settings for Each Table--For each table that needs Web API access, create these settings:--### 1. Enable Web API for Table--**File**: `.powerpages-site/site-settings/Webapi-<TABLE_LOGICAL_NAME>-enabled.sitesetting.yml`--```yaml-description: Enable Web API access for the table-id: <GENERATE_UUID>-name: Webapi/<TABLE_LOGICAL_NAME>/enabled-value: true-```--**Example** for `{prefix}_product` table:--**File**: `.powerpages-site/site-settings/Webapi-{prefix}_product-enabled.sitesetting.yml`-```yaml-description: Enable Web API access for the {prefix}_product table-id: a1b2c3d4-e5f6-7890-abcd-ef1234567890-name: Webapi/{prefix}_product/enabled-value: true-```--### 2. Configure Allowed Fields--**SECURITY REQUIREMENT**: Always specify explicit field names. Never use `*` as it exposes all fields including sensitive system columns. Only include fields that are needed by the frontend.--**File**: `.powerpages-site/site-settings/Webapi-<TABLE_LOGICAL_NAME>-fields.sitesetting.yml`--```yaml-description: Allowed fields for Web API access-id: <GENERATE_UUID>-name: Webapi/<TABLE_LOGICAL_NAME>/fields-value: {prefix}_name,{prefix}_description,{prefix}_price,{prefix}_imageurl,{prefix}_isactive-```--Specify comma-separated field logical names that your frontend actually needs.--### 3. Enable Error Details (Development Only)--For debugging purposes, enable detailed error messages:--**File**: `.powerpages-site/site-settings/Webapi-error-innererror.sitesetting.yml`--```yaml-description: Enable detailed error messages for debugging-id: <GENERATE_UUID>-name: Webapi/error/innererror-value: true-```--**IMPORTANT**: Disable this in production by setting value to `false` or removing the setting.--## PowerShell Helper Scripts--### Create Site Settings for a Table--```powershell-function New-WebApiSiteSettings {- param(- [Parameter(Mandatory=$true)]- [string]$ProjectRoot,- [Parameter(Mandatory=$true)]- [string]$TableLogicalName,- [Parameter(Mandatory=$true)]- [string]$Fields # REQUIRED: Explicit field list (never use *)- )-- # Security check: Never allow wildcard- if ($Fields -eq "*") {- throw "Security Error: Wildcard (*) is not allowed for fields. Specify explicit field names."- }-- $siteSettingsPath = Join-Path $ProjectRoot ".powerpages-site\site-settings"-- # Create directory if it doesn't exist- if (-not (Test-Path $siteSettingsPath)) {- New-Item -ItemType Directory -Path $siteSettingsPath -Force | Out-Null- }-- # Generate UUIDs- $enabledUuid = [guid]::NewGuid().ToString()- $fieldsUuid = [guid]::NewGuid().ToString()-- # Create enabled setting- $enabledContent = @"-description: Enable Web API access for $TableLogicalName table-id: $enabledUuid-name: Webapi/$TableLogicalName/enabled-value: true-"@- $enabledFileName = "Webapi-$TableLogicalName-enabled.sitesetting.yml"- $enabledPath = Join-Path $siteSettingsPath $enabledFileName- Set-Content -Path $enabledPath -Value $enabledContent -Encoding UTF8- Write-Host "Created: $enabledPath"-- # Create fields setting- $fieldsContent = @"-description: Allowed fields for $TableLogicalName Web API access-id: $fieldsUuid-name: Webapi/$TableLogicalName/fields-value: $Fields-"@- $fieldsFileName = "Webapi-$TableLogicalName-fields.sitesetting.yml"- $fieldsPath = Join-Path $siteSettingsPath $fieldsFileName- Set-Content -Path $fieldsPath -Value $fieldsContent -Encoding UTF8- Write-Host "Created: $fieldsPath"-- return @{- TableName = $TableLogicalName- EnabledFile = $enabledFileName- FieldsFile = $fieldsFileName- }-}-```--### Example Usage--**IMPORTANT**: Use the `$tableMap` from `/setup-dataverse` to get the actual table logical names:-- For **reused/extended tables**: Use the existing logical name from Dataverse-- For **new tables**: Use `${publisherPrefix}_tablename` pattern--```powershell-$projectRoot = "<PROJECT_ROOT>" # Replace with actual path--# Get the publisher prefix first-$api = Initialize-DataverseApi -EnvironmentUrl $envUrl-$publisherPrefix = $api.PublisherPrefix--# The $tableMap should be retrieved from memory-bank.md or rebuilt from /setup-dataverse-# It maps table purposes to actual logical names-function Get-TableLogicalName { param([string]$Purpose) return $tableMap[$Purpose].LogicalName }--$productTable = Get-TableLogicalName "product"-$teammemberTable = Get-TableLogicalName "teammember"-$testimonialTable = Get-TableLogicalName "testimonial"-$faqTable = Get-TableLogicalName "faq"-$contactsubmissionTable = Get-TableLogicalName "contactsubmission"--# Configure each table with EXPLICIT field lists (never use *)-# NOTE: Use the actual table logical names from the mapping-New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName $productTable `- -Fields "${publisherPrefix}_name,${publisherPrefix}_description,${publisherPrefix}_price,${publisherPrefix}_category,${publisherPrefix}_imageurl,${publisherPrefix}_isactive"--New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName $teammemberTable `- -Fields "${publisherPrefix}_name,${publisherPrefix}_title,${publisherPrefix}_email,${publisherPrefix}_bio,${publisherPrefix}_photourl,${publisherPrefix}_linkedin,${publisherPrefix}_displayorder"--New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName $testimonialTable `- -Fields "${publisherPrefix}_name,${publisherPrefix}_quote,${publisherPrefix}_company,${publisherPrefix}_role,${publisherPrefix}_rating,${publisherPrefix}_photourl,${publisherPrefix}_isactive"--New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName $faqTable `- -Fields "${publisherPrefix}_question,${publisherPrefix}_answer,${publisherPrefix}_category,${publisherPrefix}_displayorder,${publisherPrefix}_isactive"--New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName $contactsubmissionTable `- -Fields "${publisherPrefix}_name,${publisherPrefix}_email,${publisherPrefix}_message,${publisherPrefix}_submissiondate,${publisherPrefix}_status"-```--### Create Error Setting--```powershell-function New-WebApiErrorSetting {- param(- [string]$ProjectRoot,- [bool]$Enabled = $true- )-- $siteSettingsPath = Join-Path $ProjectRoot ".powerpages-site\site-settings"- $errorUuid = [guid]::NewGuid().ToString()- $enabledValue = if ($Enabled) { "true" } else { "false" }-- $errorContent = @"-description: Enable detailed error messages for debugging-id: $errorUuid-name: Webapi/error/innererror-value: $enabledValue-"@- $errorFileName = "Webapi-error-innererror.sitesetting.yml"- $errorPath = Join-Path $siteSettingsPath $errorFileName- Set-Content -Path $errorPath -Value $errorContent -Encoding UTF8- Write-Host "Created error setting: $errorPath"-}--# Enable detailed errors for development-New-WebApiErrorSetting -ProjectRoot $projectRoot -Enabled $true-```--## Site Settings Quick Reference--| Setting | Purpose | Example Value |-|---------|---------|---------------|-| `Webapi/<table>/enabled` | Enable Web API for table | `true` |-| `Webapi/<table>/fields` | Allowed fields (comma-separated) | `{prefix}_name,{prefix}_price` |-| `Webapi/error/innererror` | Show detailed errors (dev only) | `true` |-| `Site/AI/AuthoringTool` | Tracks which tool created the site | `ClaudeCodeCLI` or `ClaudeCodeVSCode` |-| `Site/AI/<SkillName>` | Tracks which skills were used | `true` |--## AI Site Settings--When a site is created or modified using Claude Code, site settings track the tooling:--**📖 See: [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md)**--| Setting | Purpose |-|---------|---------|-| `Site/AI/AuthoringTool` | CLI or VS Code |-| `Site/AI/CreateSite` | /create-site skill used |-| `Site/AI/SetupDataverse` | /setup-dataverse skill used |-| `Site/AI/SetupWebApi` | /setup-webapi skill used |-| `Site/AI/SetupAuth` | /setup-auth skill used |--## Validation Checklist--Before uploading:--- [ ] All YAML files have valid syntax-- [ ] Each file has a unique UUID for the `id` field-- [ ] Fields are alphabetically sorted in the YAML file-- [ ] File extensions are `.yml` (not `.yaml`)-- [ ] Field names do NOT include `adx_` prefix-- [ ] Boolean values are unquoted (`true` not `"true"`)-- [ ] Field lists use explicit names (no wildcards)-- [ ] Error setting is disabled for productiondiff --git a/plugins/power-pages/skills/setup-webapi/references/table-permissions-reference.md b/plugins/power-pages/skills/setup-webapi/references/table-permissions-reference.mddeleted file mode 100644index 5bf0f3b66..000000000--- a/plugins/power-pages/skills/setup-webapi/references/table-permissions-reference.md+++ /dev/null@@ -1,305 +0,0 @@-# Table Permissions Reference--Table permissions control Web API data access. Create YAML files in `.powerpages-site/table-permissions/` and link to web roles.--## Permission Scopes--| Scope | Value | Description | Use Case |-|-------|-------|-------------|----------|-| **Global** | 756150000 | All records accessible | Public data (products, FAQs, testimonials) |-| **Contact** | 756150001 | Records linked to current contact | User-specific data |-| **Account** | 756150002 | Records linked to user's account | Organization data |-| **Parent** | 756150003 | Records linked via parent relationship | Hierarchical data |-| **Self** | 756150004 | Only records owned by current user | Private user data |--## CRUD Permissions--| Field | Description |-|-------|-------------|-| `read` | Can retrieve/query records |-| `create` | Can create new records |-| `write` | Can update existing records |-| `delete` | Can delete records |-| `append` | Can associate records to this entity |-| `appendto` | Can associate this entity to other records |--## Folder Structure--```-<PROJECT_ROOT>/-├── .powerpages-site/-│ ├── table-permissions/-│ │ ├── Product-Read-Permission.tablepermission.yml-│ │ ├── Contact-Self-Access.tablepermission.yml-│ │ └── ...-│ ├── web-roles/-│ │ ├── Anonymous-Users.webrole.yml-│ │ ├── Authenticated-Users.webrole.yml-│ │ └── ...-│ └── ...-```--## File Naming Convention--```-<Permission-Name>.tablepermission.yml-```--Example: `Product-Read-Permission.tablepermission.yml`--## YAML File Structure--```yaml-accountrelationship:-adx_entitypermission_webrole:-- f0323770-7314-4f33-b904-21523abfbcb7-append: false-appendto: false-contactrelationship:-create: false-delete: false-entitylogicalname: cr_product-entityname: Product Read Permission-id: b5d8334f-45fa-464c-ac1d-f7088325f697-parententitypermission:-parentrelationship:-read: true-scope: 756150000-write: false-```--**Important**:-- Fields are alphabetically sorted-- Field names do NOT include the `adx_` prefix (use `read` not `adx_read`)-- Exception: `adx_entitypermission_webrole` retains the full name (many-to-many relationship)--## YAML Field Reference--| Field | Type | Required | Description |-|-------|------|----------|-------------|-| `id` | GUID | Yes | Unique identifier for this permission |-| `entitylogicalname` | string | Yes | Dataverse table logical name |-| `entityname` | string | Yes | Display name for the permission |-| `scope` | int | Yes | Permission scope (see values above) |-| `read` | bool | No | Can retrieve/query records |-| `create` | bool | No | Can create new records |-| `write` | bool | No | Can update existing records |-| `delete` | bool | No | Can delete records |-| `append` | bool | No | Can associate records to this entity |-| `appendto` | bool | No | Can associate this entity to other records |-| `adx_entitypermission_webrole` | list | No | GUIDs of web roles with this permission |-| `parententitypermission` | GUID | No | Parent permission ID for hierarchical access |-| `parentrelationship` | string | No | Relationship name for parent scope |-| `accountrelationship` | string | No | Relationship name for account filtering |-| `contactrelationship` | string | No | Relationship name for contact filtering |--## Generating Unique IDs--**IMPORTANT**: Every table permission YAML file must have a unique `id` field (UUID/GUID format).--**Claude Code MUST generate UUIDs by running a CLI command** - never write UUID values directly. Use the Bash tool to execute the appropriate command based on the user's shell/platform:--| Shell/Platform | Command |-|----------------|---------|-| **PowerShell** (Windows) | `[guid]::NewGuid().ToString()` |-| **Bash** (Linux) | `cat /proc/sys/kernel/random/uuid` |-| **Bash/Zsh** (macOS) | `uuidgen \| tr '[:upper:]' '[:lower:]'` |--**Workflow:**-1. Run the UUID generation command via Bash tool-2. Capture the output-3. Use that value when writing the YAML file--## Getting Web Role GUIDs--Before creating table permissions, get the web role GUID from `.powerpages-site/web-roles/`. Each web role has a `.webrole.yml` file containing its `id`.--**Example web role file** (`.powerpages-site/web-roles/Anonymous-Users.webrole.yml`):-```yaml-anonymoususersrole: true-authenticatedusersrole: false-id: f0323770-7314-4f33-b904-21523abfbcb7-name: Anonymous Users-```--| Role | Description | Use Case |-|------|-------------|----------|-| **Anonymous Users** | Unauthenticated visitors | Public content access |-| **Authenticated Users** | Any logged-in user | Basic member features |-| **Administrators** | Full admin access | Site management |--## Using Table Name Mapping--**IMPORTANT**: Use the `$tableMap` from `/setup-dataverse` (stored in `memory-bank.md`) to get the correct table logical names:-- **Reused/Extended tables**: Use existing logical name (e.g., `contoso_items`)-- **New tables**: Use `{prefix}_tablename` pattern (e.g., `cr_product`)--## Common Permission Patterns--### Read-Only Public Data (Global Scope)--For tables like products, testimonials, FAQs that should be publicly readable.--**File**: `.powerpages-site/table-permissions/Product-Anonymous-Read.tablepermission.yml`-```yaml-adx_entitypermission_webrole:-- <ANONYMOUS_USERS_ROLE_ID>-append: false-appendto: false-create: false-delete: false-entitylogicalname: <TABLE_LOGICAL_NAME>-entityname: Product - Anonymous Read-id: <GENERATE_UUID>-parententitypermission:-read: true-scope: 756150000-write: false-```--### Create-Only (Form Submissions)--For contact forms where users can submit but not read others' submissions.--**File**: `.powerpages-site/table-permissions/Contact-Submission-Create.tablepermission.yml`-```yaml-adx_entitypermission_webrole:-- <ANONYMOUS_USERS_ROLE_ID>-append: false-appendto: false-create: true-delete: false-entitylogicalname: <TABLE_LOGICAL_NAME>-entityname: Contact Submission - Create Only-id: <GENERATE_UUID>-parententitypermission:-read: false-scope: 756150000-write: false-```--### User-Specific Data (Self Scope)--For data that users should only see their own records.--**File**: `.powerpages-site/table-permissions/User-Profile-Self-Access.tablepermission.yml`-```yaml-adx_entitypermission_webrole:-- <AUTHENTICATED_USERS_ROLE_ID>-append: false-appendto: false-create: true-delete: false-entitylogicalname: <TABLE_LOGICAL_NAME>-entityname: User Profile - Self Access-id: <GENERATE_UUID>-parententitypermission:-read: true-scope: 756150004-write: true-```--### Full CRUD Access--For authenticated users who need complete control (use with caution).--**File**: `.powerpages-site/table-permissions/Order-Full-Access.tablepermission.yml`-```yaml-adx_entitypermission_webrole:-- <AUTHENTICATED_USERS_ROLE_ID>-append: true-appendto: true-create: true-delete: true-entitylogicalname: <TABLE_LOGICAL_NAME>-entityname: Order - Full Access-id: <GENERATE_UUID>-parententitypermission:-read: true-scope: 756150001-write: true-```--## Parent-Child Table Permissions--When tables have relationships (e.g., Order → Order Items), use hierarchical permissions with the `parententitypermission` field and `Parent` scope.--**Creation Order:**-1. Create parent table permission first (e.g., for `{prefix}_order`)-2. Note the parent permission's `id` (GUID)-3. Create child permission with `parententitypermission` set to parent's ID-4. Set child's `scope` to `756150003` (Parent)-5. Set `parentrelationship` to the relationship name between child and parent tables--### Example: Parent Permission (Order)--**File**: `.powerpages-site/table-permissions/Order-User-Access.tablepermission.yml`-```yaml-adx_entitypermission_webrole:-- <AUTHENTICATED_USERS_ROLE_ID>-append: true-appendto: false-create: true-delete: false-entitylogicalname: {prefix}_order-entityname: Order - User Access-id: a1b2c3d4-e5f6-7890-abcd-ef1234567890-parententitypermission:-parentrelationship:-read: true-scope: 756150001-write: true-```--### Example: Child Permission (Order Items)--**File**: `.powerpages-site/table-permissions/Order-Item-Parent-Access.tablepermission.yml`-```yaml-adx_entitypermission_webrole:-- <AUTHENTICATED_USERS_ROLE_ID>-append: false-appendto: true-create: true-delete: true-entitylogicalname: {prefix}_orderitem-entityname: Order Item - Parent Access-id: b2c3d4e5-f6a7-8901-bcde-fa2345678901-parententitypermission: a1b2c3d4-e5f6-7890-abcd-ef1234567890-parentrelationship: {prefix}_order_orderitems-read: true-scope: 756150003-write: true-```--Users can only access order items that belong to orders they have access to.--## Validation Checklist--Before uploading:--- [ ] All YAML files have valid syntax-- [ ] Each file has a unique UUID for the `id` field (generated via CLI command)-- [ ] Fields are alphabetically sorted-- [ ] File extensions are `.yml` (not `.yaml`)-- [ ] Field names do NOT include `adx_` prefix (except `adx_entitypermission_webrole`)-- [ ] Boolean values are unquoted (`true` not `"true"`)-- [ ] All GUIDs are valid UUID format (lowercase with hyphens)-- [ ] Web role GUIDs exist in `.powerpages-site/web-roles/` folder--## Security Best Practices--1. **Least Privilege**: Grant only the minimum permissions needed-2. **Avoid Global Scope for Write**: Use Contact/Account/Self scopes for write operations-3. **Separate Read and Write**: Create different permissions for reading vs. modifying data-4. **Audit Regularly**: Review permissions periodically-5. **Test as Anonymous**: Verify anonymous users can only access intended data--## Permission Decision Matrix--| Data Type | Recommended Scope | Read | Create | Write | Delete |-|-----------|-------------------|------|--------|-------|--------|-| Public content (products, FAQs) | Global | Yes | No | No | No |-| Form submissions | Global | No | Yes | No | No |-| User profiles | Self | Yes | Yes | Yes | No |-| User's own orders | Contact | Yes | Yes | Yes | No |-| Admin data | N/A (via app) | No | No | No | No |diff --git a/plugins/power-pages/skills/setup-webapi/references/troubleshooting.md b/plugins/power-pages/skills/setup-webapi/references/troubleshooting.mddeleted file mode 100644index 833d892bf..000000000--- a/plugins/power-pages/skills/setup-webapi/references/troubleshooting.md+++ /dev/null@@ -1,348 +0,0 @@-# Troubleshooting Guide--**NOTE**: Replace `{prefix}` with your publisher prefix from `Initialize-DataverseApi`.--## Quick Reference--| Issue | Solution |-|-------|----------|-| `403 Forbidden` | Table permission not configured, not linked to web role, or missing/expired CSRF token |-| `404 Not Found` | Web API not enabled for table (check site setting) |-| `400 Bad Request` | Invalid OData query syntax, missing `$select`, or field not in allowed list |-| `500 Server Error` | Enable `Webapi/error/innererror` to see details |-| `CSRF Token Error` | Ensure `__RequestVerificationToken` header is included for POST/PATCH/DELETE requests |-| `Field not allowed` | Add `$select` param with only fields listed in `Webapi/<table>/fields` setting |--## Site Settings Not Being Applied--### Symptoms--- Web API returns 404 even though settings exist-- Settings don't appear in Power Pages Studio--### Solutions--1. **Validate YAML syntax**-- ```yaml- # Correct- id: a1b2c3d4-e5f6-7890-abcd-ef1234567890- name: Webapi/{prefix}_product/enabled- value: true-- # Incorrect (missing quotes can cause issues in some cases)- id: a1b2c3d4e5f6-7890-abcd-ef1234567890 # Invalid UUID format- ```--2. **Verify file extension is `.yml`** (not `.yaml`)--3. **Check that `id` is a valid UUID**-- ```powershell- # Generate a valid UUID- [guid]::NewGuid().ToString()- ```--4. **Re-upload the site after adding settings**-- ```powershell- pac pages upload-code-site --rootPath "<PROJECT_ROOT>"- ```--## Web API Returns 403 Forbidden--### Symptoms--- GET requests return 403-- POST/PATCH/DELETE requests fail with 403--### For GET Requests--1. **Verify table permission exists**-- ```powershell- # Check permissions in Dataverse- $baseUrl = "<ENV_URL>/api/data/v9.2"- Invoke-RestMethod -Uri "$baseUrl/adx_entitypermissions?`$filter=adx_entitylogicalname eq '{prefix}_product'" -Headers $headers- ```--2. **Check permission is linked to correct web role**- - For public access: Link to "Anonymous Users"- - For authenticated access: Link to "Authenticated Users"--3. **Verify permission has Read enabled**-- ```powershell- # Permission should have adx_read = true- ```--4. **Verify permission scope**- - Global (756150000) for public data- - Self (756150004) for user-specific data--### For POST/PATCH/DELETE Requests--1. **Ensure CSRF token is included**-- ```javascript- // Fetch token- const response = await fetch('/_layout/tokenhtml');- const html = await response.text();- const match = html.match(/value="([^"]+)"/);- const token = match ? match[1] : null;-- // Include in request- fetch('/_api/{prefix}_products', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- '__RequestVerificationToken': token- },- body: JSON.stringify(data)- });- ```--2. **Check if token expired**- - Clear cached token and fetch a new one- - Tokens can expire after extended inactivity--3. **Verify Create/Write/Delete permissions**- - POST requires `adx_create = true`- - PATCH requires `adx_write = true`- - DELETE requires `adx_delete = true`--## CSRF Token Issues--### Test Token Fetch Manually--```javascript-// In browser console-fetch('/_layout/tokenhtml')- .then(r => r.text())- .then(html => {- const match = html.match(/value="([^"]+)"/);- console.log('Token:', match ? match[1] : 'Not found');- });-```--### Common Token Problems--| Problem | Solution |-|---------|----------|-| Token not found | Ensure `/_layout/tokenhtml` is accessible |-| Token expired | Clear cache and fetch new token |-| Token not sent | Check header name is `__RequestVerificationToken` |-| Wrong token format | Parse HTML correctly to extract value |--## Web API Returns 404 Not Found--### Solutions--1. **Verify site setting exists and is enabled**-- ```yaml- name: Webapi/{prefix}_product/enabled- value: true # Must be boolean true, not string "true"- ```--2. **Check entity set name is correct**- - Use pluralized logical name- - Example: `{prefix}_product` table → `{prefix}_products` entity set--3. **Ensure table exists in Dataverse**-- ```powershell- # List tables- pac table list- ```--4. **Re-upload site settings**-- ```powershell- pac pages upload-code-site --rootPath "<PROJECT_ROOT>"- ```--## Web API Returns 400 Bad Request--### Common Causes--1. **Invalid OData query syntax**-- ```text- # Incorrect- /_api/{prefix}_products?filter={prefix}_isactive eq true-- # Correct ($ prefix required)- /_api/{prefix}_products?$filter={prefix}_isactive eq true- ```--2. **Missing $select when fields are restricted** (Most Common)-- When `Webapi/<table>/fields` site setting specifies allowed fields, you **must** use `$select` in your query. Without `$select`, the API tries to return all fields and fails because only configured fields are allowed.-- ```text- # Site setting- name: Webapi/{prefix}_product/fields- value: {prefix}_name,{prefix}_price,{prefix}_isactive-- # Incorrect (no $select - tries to fetch all fields)- /_api/{prefix}_products- /_api/{prefix}_products?$filter={prefix}_isactive eq true-- # Correct (only requests allowed fields)- /_api/{prefix}_products?$select={prefix}_name,{prefix}_price,{prefix}_isactive- /_api/{prefix}_products?$select={prefix}_name,{prefix}_price,{prefix}_isactive&$filter={prefix}_isactive eq true- ```-- **Solution**: Always include `$select` with fields that match your `Webapi/<table>/fields` site setting:-- ```typescript- // Always specify select with allowed fields- webApi.getAll<Product>('{prefix}_products', {- select: ['{prefix}_name', '{prefix}_price', '{prefix}_isactive'],- filter: '{prefix}_isactive eq true',- });- ```--3. **Field not in allowed fields list**- - Check `Webapi/<table>/fields` setting- - Add missing fields to the comma-separated list--3. **Invalid filter value**-- ```text- # Incorrect (string needs quotes)- $filter={prefix}_category eq Electronics-- # Correct- $filter={prefix}_category eq 'Electronics'- ```--4. **Invalid data type in request body**-- ```javascript- // Incorrect- { "{prefix}_price": "99.99" } // String instead of number-- // Correct- { "{prefix}_price": 99.99 }- ```--## Web API Returns 500 Server Error--### Enable Detailed Error Messages--1. **Create error setting**-- ```yaml- # File: Webapi-error-innererror.sitesetting.yml- id: <uuid>- name: Webapi/error/innererror- value: true- ```--2. **Upload and test again**-- ```powershell- pac pages upload-code-site --rootPath "<PROJECT_ROOT>"- ```--3. **Check browser Network tab for detailed error response**--### Common Server Errors--| Error Message | Solution |-|---------------|----------|-| "Entity not found" | Check table logical name |-| "Invalid field" | Field doesn't exist or not in allowed list |-| "Permission denied" | Check table permissions and web role |--## CORS Errors in Browser--Power Pages Web API should not have CORS issues when called from the same origin.--### If CORS Errors Occur--1. **Use relative URLs**-- ```javascript- // Correct- fetch('/_api/{prefix}_products')-- // Incorrect (may cause CORS issues)- fetch('https://site.powerappsportals.com/_api/{prefix}_products')- ```--2. **Check HTTP vs HTTPS**- - Ensure site URL and API URL use same protocol--3. **Verify origin matches**- - Request must come from same domain as the site--## Data Not Displaying--### Debugging Steps--1. **Check browser console for JavaScript errors**--2. **Verify API response in Network tab**- - Look for the `/_api/...` request- - Check response status and body--3. **Test API directly in browser**-- ```text- https://<site-url>/_api/{prefix}_products- ```--4. **Check field name mapping**- - Ensure frontend uses Dataverse column logical names- - Example: `{prefix}_productid` not `id`--5. **Verify data exists in Dataverse**-- ```powershell- # Query via Dataverse API- Invoke-RestMethod -Uri "$baseUrl/{prefix}_products" -Headers $headers- ```--## Debug Checklist--Use this checklist to systematically debug Web API issues:--- [ ] Site settings uploaded? (`pac pages upload-code-site`)-- [ ] Site setting syntax valid? (YAML format, boolean values)-- [ ] Table permission created? (check in Power Pages Studio)-- [ ] Permission linked to web role? (Anonymous Users for public)-- [ ] Permission has correct CRUD flags?-- [ ] CSRF token included for write operations?-- [ ] OData query syntax correct? (`$filter`, `$select`, etc.)-- [ ] **`$select` included with allowed fields?** (Required when `Webapi/<table>/fields` is set)-- [ ] Fields in allowed fields list?-- [ ] Entity set name correct? (pluralized)-- [ ] Data exists in Dataverse?-- [ ] Error details enabled for debugging?--## Verify in Power Pages Studio--### Check Site Settings--1. Go to Power Pages Studio-2. Navigate to **Setup > Site Settings**-3. Search for "Webapi"-4. Verify settings are present--### Check Table Permissions--1. Go to Power Pages Studio-2. Navigate to **Security > Table Permissions**-3. Verify permissions exist-4. Check they're linked to appropriate web roles--## Reference Documentation--- [Power Pages Web API Overview](https://learn.microsoft.com/en-us/power-pages/configure/web-api-overview)-- [Web API Operations](https://learn.microsoft.com/en-us/power-pages/configure/write-update-delete-operations)-- [Site Settings Reference](https://learn.microsoft.com/en-us/power-pages/configure/configure-site-settings)-- [Table Permissions](https://learn.microsoft.com/en-us/power-pages/security/table-permissions)-- [OData Query Options](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-data-web-api)diff --git a/plugins/power-pages/skills/setup-webapi/references/web-roles-reference.md b/plugins/power-pages/skills/setup-webapi/references/web-roles-reference.mddeleted file mode 100644index a646ee692..000000000--- a/plugins/power-pages/skills/setup-webapi/references/web-roles-reference.md+++ /dev/null@@ -1,218 +0,0 @@-# Web Roles Reference--Web roles define user groups with access levels. Create roles before table permissions.--## Built-in Web Roles--Power Pages creates these default web roles when a site is provisioned:--| Web Role | Description | Typical Use Case |-|----------|-------------|------------------|-| **Anonymous Users** | Unauthenticated site visitors | Public content, read-only product catalogs, FAQs |-| **Authenticated Users** | Any user who has signed in | Basic member features, form submissions |-| **Administrators** | Full administrative access | Site management, content editing |--### Role Hierarchy--Administrators → Authenticated Users (+ custom roles) → Anonymous Users--## Web Role YAML Files--Web roles are stored as YAML files in `.powerpages-site/web-roles/`.--### Folder Structure--```-<PROJECT_ROOT>/-├── .powerpages-site/-│ ├── web-roles/-│ │ ├── Anonymous-Users.webrole.yml-│ │ ├── Authenticated-Users.webrole.yml-│ │ ├── Administrators.webrole.yml-│ │ └── Customers.webrole.yml # Custom role-│ └── ...-```--### YAML Format--```yaml-anonymoususersrole: false-authenticatedusersrole: false-id: <GENERATE_UUID>-name: <ROLE_NAME>-```--### Field Reference--| Field | Type | Required | Description |-|-------|------|----------|-------------|-| `id` | GUID | Yes | Unique identifier for this role |-| `name` | string | Yes | Display name of the role |-| `anonymoususersrole` | bool | Yes | `true` only for Anonymous Users role |-| `authenticatedusersrole` | bool | Yes | `true` only for Authenticated Users role |--### Built-in Role Examples--**Anonymous-Users.webrole.yml**-```yaml-anonymoususersrole: true-authenticatedusersrole: false-id: f0323770-7314-4f33-b904-21523abfbcb7-name: Anonymous Users-```--**Authenticated-Users.webrole.yml**-```yaml-anonymoususersrole: false-authenticatedusersrole: true-id: ecac9573-effb-4d63-9b27-15861f70f3de-name: Authenticated Users-```--**Administrators.webrole.yml**-```yaml-anonymoususersrole: false-authenticatedusersrole: false-id: 4e4ee36e-6535-4657-b62a-c4972d932558-name: Administrators-```--### Custom Role Examples--**Customers.webrole.yml**-```yaml-anonymoususersrole: false-authenticatedusersrole: false-id: 7a8b9c0d-1e2f-3456-7890-abcdef123456-name: Customers-```--**Premium-Members.webrole.yml**-```yaml-anonymoususersrole: false-authenticatedusersrole: false-id: 1b2c3d4e-5f6a-7890-bcde-f12345678901-name: Premium Members-```--### Generating Unique IDs--Each web role must have a unique `id` (UUID/GUID format).--**Claude Code MUST generate UUIDs by running a CLI command** - never write UUID values directly. Use the Bash tool to execute the appropriate command based on the user's shell/platform:--| Shell/Platform | Command |-|----------------|---------|-| **PowerShell** (Windows) | `[guid]::NewGuid().ToString()` |-| **Bash** (Linux) | `cat /proc/sys/kernel/random/uuid` |-| **Bash/Zsh** (macOS) | `uuidgen \| tr '[:upper:]' '[:lower:]'` |--## Creating Web Roles--### Step 1: Check Existing Roles--After the first upload, check what roles exist in `.powerpages-site/web-roles/`:--```powershell-Get-ChildItem -Path ".powerpages-site\web-roles" -Filter "*.webrole.yml"-```--### Step 2: Create Custom Role YAML--Create a new `.webrole.yml` file for each custom role needed:--```powershell-$roleName = "Customers"-$roleId = [guid]::NewGuid().ToString()--$content = @"-anonymoususersrole: false-authenticatedusersrole: false-id: $roleId-name: $roleName-"@--$fileName = "$roleName.webrole.yml"-$filePath = ".powerpages-site\web-roles\$fileName"-Set-Content -Path $filePath -Value $content -Encoding UTF8-Write-Host "Created: $filePath"-```--### Step 3: Upload to Apply--```powershell-pac pages upload-code-site --rootPath "<PROJECT_ROOT>"-```--## Role Selection by Feature--| Site Feature | Required Roles |-|--------------|----------------|-| Public landing page | Anonymous Users |-| Product/Service catalog | Anonymous Users |-| Contact form submission | Anonymous Users (create-only) |-| User dashboard | Authenticated Users |-| Order history | Customers (custom) |-| Admin panel | Administrators |-| Premium content | Premium Members (custom) |--## Common Role Patterns--### Pattern 1: Public Website-- Anonymous Users (default)-- Administrators (default)--### Pattern 2: Member Portal-- Anonymous Users-- Authenticated Users-- Administrators--### Pattern 3: Customer Portal-- Anonymous Users-- Customers (custom)-- Support Agents (custom)-- Administrators--### Pattern 4: Subscription Site-- Anonymous Users-- Free Members (custom)-- Premium Members (custom)-- Administrators--## Querying Existing Roles (API)--To query existing roles from Dataverse (for verification):--```powershell-$envUrl = (pac org who --json | ConvertFrom-Json).OrgUrl-$token = (az account get-access-token --resource $envUrl --query accessToken -o tsv)-$headers = @{- "Authorization" = "Bearer $token"- "Content-Type" = "application/json"-}-$baseUrl = "$envUrl/api/data/v9.2"--# List all web roles for the website (use mspp_webroles, not adx_webroles)-$websiteId = "<WEBSITE_ID>"-$roles = Invoke-RestMethod `- -Uri "$baseUrl/mspp_webroles?`$filter=_mspp_websiteid_value eq $websiteId&`$select=mspp_webroleid,mspp_name" `- -Headers $headers--$roles.value | ForEach-Object {- Write-Host "Role: $($_.mspp_name) | ID: $($_.mspp_webroleid)"-}-```--## Validation Checklist--Before uploading:--- [ ] All YAML files have valid syntax-- [ ] Each file has a unique UUID for the `id` field-- [ ] File extension is `.yml` (not `.yaml`)-- [ ] `anonymoususersrole` and `authenticatedusersrole` are both `false` for custom roles-- [ ] Role names are descriptive and unique--## Next Steps--After creating web roles, create table permissions that reference these role IDs. See [table-permissions-reference.md](./table-permissions-reference.md).