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
Add /migrate-webapi-selectall: replace deprecated Web API wildcard fields settings with columns (#484)
Ramachandran R67368cc076a6
diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonindex ba73e795f..6e91e7418 100644--- a/plugins/power-pages/.claude-plugin/plugin.json+++ b/plugins/power-pages/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "2.6.4",+ "version": "2.6.5","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. Includes ALM orchestration (plan-alm) with a solution-splitting decision tree, per-solution pipelines, Azure Blob asset advisory, manifest schema v2 for multi-solution deployments, and force-link remediation for cross-host pipeline migrations.","author": {"name": "Microsoft",diff --git a/plugins/power-pages/.plugin/plugin.json b/plugins/power-pages/.plugin/plugin.jsonindex ba73e795f..6e91e7418 100644--- a/plugins/power-pages/.plugin/plugin.json+++ b/plugins/power-pages/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "2.6.4",+ "version": "2.6.5","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. Includes ALM orchestration (plan-alm) with a solution-splitting decision tree, per-solution pipelines, Azure Blob asset advisory, manifest schema v2 for multi-solution deployments, and force-link remediation for cross-host pipeline migrations.","author": {"name": "Microsoft",diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.mdindex b111f9af9..1a1682f5a 100644--- a/plugins/power-pages/README.md+++ b/plugins/power-pages/README.md@@ -38,7 +38,7 @@ This keeps hook behavior in one place and avoids relying on skill-frontmatter ho## Skills-The plugin provides 33 skills that cover the full lifecycle of a Power Pages site — scaffolding, deployment, data modeling, backend integration, authentication, ALM and CI/CD, security review, testing, auditing, and Bootstrap 3→5 migration. Each skill is invoked conversationally — just describe what you want to do.+The plugin provides 34 skills that cover the full lifecycle of a Power Pages site — scaffolding, deployment, data modeling, backend integration, authentication, ALM and CI/CD, security review, testing, auditing, and platform migrations. Each skill is invoked conversationally — just describe what you want to do.### Site scaffolding and deployment@@ -400,6 +400,17 @@ Migrates a traditional Power Pages site (Liquid web templates, not code sites) f- AI-assisted per-category fixes for grid, navbar, panel/card, and page-header changes- Uploads (auto-enabling the Bootstrap 5 runtime flag) and verifies the flip via `pac-log.txt`+#### `/migrate-webapi-selectall`++> "Replace every wildcard Web API fields setting with the columns my site actually uses"++Reviews every authored Power Pages Web API source call and response consumer, maps entity sets through Dataverse metadata, and replaces deprecated `Webapi/<table>/fields = *` values with evidence-backed explicit columns. Compiled and generated output is excluded. Works with both traditional/Liquid sites and React, Vue, Angular, or Astro SPA sites.++- Reports every wildcard with its exact proposed fix and every already-explicit configuration+- Adds missing `$select` projections where normal record reads relied on implicit selection+- Traces every call site reaching a table, including duplicated wrappers and differing query shapes+- Verifies all configuration scopes and deployment profiles contain zero wildcards+### Support#### `/report-issue`diff --git a/plugins/power-pages/references/approval-gates.md b/plugins/power-pages/references/approval-gates.mdindex dcd663860..91e721fc3 100644--- a/plugins/power-pages/references/approval-gates.md+++ b/plugins/power-pages/references/approval-gates.md@@ -697,6 +697,21 @@ New skill (migrates a traditional Power Pages site from Bootstrap 3 to Bootstrap| `migrate-bootstrap:6.residual-fixes` | gate | progress | 6 | Per-category consent — *"Apply the `<category>` fixes to `<N>` file(s)?"* — repeated per residual category; changes are local to the V5 copy. | nothing || `migrate-bootstrap:7.2.upload` | gate | final | 7.2 | First outward-facing change — *"Upload `<MIGRATED_FOLDER>` to `<ENV_NAME>`?"* — publishes the Bootstrap 5 site and auto-enables the runtime flag. | nothing |+---++### 6.32 `migrate-webapi-selectall` (6 calls / 5 gates + 1 sub-prompt)++Reviews traditional and SPA sites for deprecated Web API wildcard fields settings, derives least-privilege columns from every call chain, and applies only a complete approved migration.++| ID | Kind | Category | Phase | Trigger / question | Cancel leaves |+|---|---|---|---|---|---|+| `migrate-webapi-selectall:1.download-site` | gate | consent | 1 | Approves an optional site download after confirming environment, website name and ID, site type, data model, and target path. | nothing |+| `migrate-webapi-selectall:2.confirm-scope` | gate | plan | 2 | Confirms all configuration scopes, wildcard and explicit counts, and the source call inventory before schema retrieval. | draft migration report |+| Phase 3 environment URL | sub-prompt | — | 3.1 | Collects the environment URL only when project and PAC context cannot resolve it. This is read-only metadata input and grants no write consent. | draft migration report |+| `migrate-webapi-selectall:4.apply-plan` | gate | consent | 4 | Approves every wildcard replacement, required source projection, selected explicit hardening, and local edits. No partial wildcard option is offered. | reviewed migration report |+| `migrate-webapi-selectall:7.deploy` | gate | final | 7 | Approves one independently verified deployment after re-confirming environment, website, site type, data model, and profile. Repeat for another target. | local migration |+| `migrate-webapi-selectall:7.smoke-test` | gate | progress | 7 | Approves the listed read-path smoke test against the deployed site. Write, file, and image paths are never issued. | deployed migration unverified |+---### Cross-plugin shared skills — out of catalog scopediff --git a/plugins/power-pages/references/skill-tracking-reference.md b/plugins/power-pages/references/skill-tracking-reference.mdindex 223b50746..8c7bc1e84 100644--- a/plugins/power-pages/references/skill-tracking-reference.md+++ b/plugins/power-pages/references/skill-tracking-reference.md@@ -57,6 +57,7 @@ If the tracking script creates or updates site setting YAML files, include those| ensure-pipelines-host | EnsurePipelinesHost | Site/AI/Skills/EnsurePipelinesHost || force-link-environment | ForceLinkEnvironment | Site/AI/Skills/ForceLinkEnvironment || migrate-bootstrap | MigrateBootstrap | Site/AI/Skills/MigrateBootstrap |+| migrate-webapi-selectall | MigrateWebapiSelectall | Site/AI/Skills/MigrateWebapiSelectall |## YAML Formatdiff --git a/plugins/power-pages/scripts/tests/query-webapi-selectall-schema.test.js b/plugins/power-pages/scripts/tests/query-webapi-selectall-schema.test.jsnew file mode 100644index 000000000..a1e554ad8--- /dev/null+++ b/plugins/power-pages/scripts/tests/query-webapi-selectall-schema.test.js@@ -0,0 +1,236 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const test = require('node:test');+const { spawnSync } = require('node:child_process');++const schema = require(+ '../../skills/migrate-webapi-selectall/scripts/query-table-schema'+);++const ENVIRONMENT_URL_1 = 'https://placeholder.crm.dynamics.com';+const TABLE_LOGICAL_NAME_1 = 'table_1';+const TABLE_ENTITY_SET_NAME_1 = 'table_1_set';+const TABLE_PRIMARY_ID_1 = 'column_name_1_id';+const TABLE_LOGICAL_NAME_2 = 'table_2';+const TABLE_ENTITY_SET_NAME_2 = 'table_2_set';+const TABLE_PRIMARY_ID_2 = 'column_name_2_id';+const COLUMN_NAME_1 = 'column_name_1';+const LOOKUP_COLUMN_NAME_1 = 'lookup_column_name_1';+const RELATIONSHIP_NAME_1 = 'relationship_1';++test('builds bounded metadata URLs for one table', () => {+ const urls = schema.buildMetadataUrls(+ ENVIRONMENT_URL_1,+ TABLE_LOGICAL_NAME_1+ );++ assert.ok(urls.attributes.includes(+ `EntityDefinitions(LogicalName='${TABLE_LOGICAL_NAME_1}')/Attributes`+ ));+ assert.match(urls.attributes, /%24select=/);+ assert.match(urls.manyToMany, /ManyToManyRelationships/);+});++test('resolves both logical names and entity sets', () => {+ const definitions = [{+ LogicalName: TABLE_LOGICAL_NAME_1,+ EntitySetName: TABLE_ENTITY_SET_NAME_1,+ PrimaryIdAttribute: TABLE_PRIMARY_ID_1,+ }];++ assert.deepEqual(+ schema.resolveRequestedTables(+ definitions,+ [TABLE_LOGICAL_NAME_1, TABLE_ENTITY_SET_NAME_1]+ ),+ definitions+ );+});++test('rejects project root as schema output', () => {+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'webapi-schema-root-'));+ try {+ assert.throws(+ () => schema.validateOptions({+ environmentUrl: ENVIRONMENT_URL_1,+ projectRoot,+ output: projectRoot,+ tables: [TABLE_LOGICAL_NAME_1],+ }),+ /file inside the project root/+ );+ } finally {+ fs.rmSync(projectRoot, { recursive: true, force: true });+ }+});++test('rejects output through an escaping junction', (t) => {+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'webapi-schema-link-'));+ const projectRoot = path.join(workspace, 'project');+ const outside = path.join(workspace, 'outside');+ t.after(() => fs.rmSync(workspace, { recursive: true, force: true }));++ fs.mkdirSync(projectRoot);+ fs.mkdirSync(outside);+ fs.writeFileSync(+ path.join(outside, 'tables.txt'),+ `${TABLE_LOGICAL_NAME_1}\n`,+ 'utf8'+ );++ try {+ fs.symlinkSync(+ outside,+ path.join(projectRoot, 'linked'),+ process.platform === 'win32' ? 'junction' : 'dir'+ );+ } catch (error) {+ if (error.code === 'EPERM' || error.code === 'EACCES') {+ t.skip(`symlinks are unavailable: ${error.code}`);+ return;+ }+ throw error;+ }++ assert.throws(+ () => schema.validateOptions({+ environmentUrl: ENVIRONMENT_URL_1,+ projectRoot,+ output: path.join(projectRoot, 'linked', 'schema.json'),+ tables: [TABLE_LOGICAL_NAME_1],+ }),+ /inside the project root/+ );+ assert.throws(+ () => schema.validateOptions({+ environmentUrl: ENVIRONMENT_URL_1,+ projectRoot,+ output: path.join(projectRoot, 'schema.json'),+ tables: [],+ tablesFile: path.join(projectRoot, 'linked', 'tables.txt'),+ }),+ /Tables file must exist inside the project root/+ );+});++test('normalizes attributes and navigation metadata', () => {+ const normalized = schema.normalizeTableMetadata(+ {+ LogicalName: TABLE_LOGICAL_NAME_1,+ EntitySetName: TABLE_ENTITY_SET_NAME_1,+ PrimaryIdAttribute: TABLE_PRIMARY_ID_1,+ },+ [{+ LogicalName: LOOKUP_COLUMN_NAME_1,+ AttributeType: 'Lookup',+ IsValidForRead: true,+ IsValidForCreate: { Value: true },+ IsValidForUpdate: false,+ }],+ [{+ SchemaName: RELATIONSHIP_NAME_1,+ ReferencingEntity: TABLE_LOGICAL_NAME_1,+ ReferencedEntity: TABLE_LOGICAL_NAME_2,+ ReferencingAttribute: LOOKUP_COLUMN_NAME_1,+ ReferencingEntityNavigationPropertyName: LOOKUP_COLUMN_NAME_1,+ ReferencedEntityNavigationPropertyName: RELATIONSHIP_NAME_1,+ }],+ []+ );++ assert.deepEqual(+ normalized.lookupReadProperties,+ [`_${LOOKUP_COLUMN_NAME_1}_value`]+ );+ assert.deepEqual(normalized.navigationProperties, [{+ name: LOOKUP_COLUMN_NAME_1,+ targetLogicalName: TABLE_LOGICAL_NAME_2,+ lookupAttribute: LOOKUP_COLUMN_NAME_1,+ relationship: RELATIONSHIP_NAME_1,+ }]);+ assert.equal(normalized.attributes[0].isValidForCreate, true);+});++test('queries only resolved requested tables', async () => {+ const calls = [];+ const getAll = async (url) => {+ calls.push(url);+ if (/EntityDefinitions\?/.test(url)) {+ return [{+ LogicalName: TABLE_LOGICAL_NAME_1,+ EntitySetName: TABLE_ENTITY_SET_NAME_1,+ PrimaryIdAttribute: TABLE_PRIMARY_ID_1,+ }, {+ LogicalName: TABLE_LOGICAL_NAME_2,+ EntitySetName: TABLE_ENTITY_SET_NAME_2,+ PrimaryIdAttribute: TABLE_PRIMARY_ID_2,+ }];+ }+ if (/\/Attributes\?/.test(url)) {+ return [{+ LogicalName: COLUMN_NAME_1,+ AttributeType: 'String',+ IsValidForRead: true,+ IsValidForCreate: true,+ IsValidForUpdate: true,+ }];+ }+ return [];+ };++ const result = await schema.queryTableSchemas(+ ENVIRONMENT_URL_1,+ [TABLE_ENTITY_SET_NAME_1],+ {+ getAuthToken: () => 'token',+ odataGetAll: getAll,+ }+ );++ assert.equal(result.tables.length, 1);+ assert.equal(result.tables[0].logicalName, TABLE_LOGICAL_NAME_1);+ assert.equal(calls.filter(url => /\/Attributes\?/.test(url)).length, 1);+});++test('retries transient metadata throttling sequentially', async () => {+ let attempts = 0;+ const delays = [];+ const getAll = async (url) => {+ attempts += 1;+ if (attempts === 1) throw new Error('HTTP 429 throttled');+ if (/EntityDefinitions\?/.test(url)) {+ return [{+ LogicalName: TABLE_LOGICAL_NAME_1,+ EntitySetName: TABLE_ENTITY_SET_NAME_1,+ PrimaryIdAttribute: TABLE_PRIMARY_ID_1,+ }];+ }+ return [];+ };++ const result = await schema.queryTableSchemas(+ ENVIRONMENT_URL_1,+ [TABLE_LOGICAL_NAME_1],+ {+ getAuthToken: () => 'token',+ odataGetAll: getAll,+ sleep: async delay => delays.push(delay),+ }+ );++ assert.equal(result.tables.length, 1);+ assert.deepEqual(delays, [1000]);+});++test('query-table-schema answers --help before parsing arguments', () => {+ const scriptPath = require.resolve(+ '../../skills/migrate-webapi-selectall/scripts/query-table-schema'+ );+ const result = spawnSync(process.execPath, [scriptPath, '--help'], { encoding: 'utf8' });+ assert.equal(result.status, 0);+ assert.ok(result.stdout);+});diff --git a/plugins/power-pages/scripts/tests/render-migration-report.test.js b/plugins/power-pages/scripts/tests/render-migration-report.test.jsnew file mode 100644index 000000000..2b7b3a70e--- /dev/null+++ b/plugins/power-pages/scripts/tests/render-migration-report.test.js@@ -0,0 +1,195 @@+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const vm = require('node:vm');+const { spawnSync } = require('node:child_process');++const scriptPath = path.join(+ __dirname, '..', '..', 'skills', 'migrate-webapi-selectall', 'scripts', 'render-migration-report.js'+);++const attack = '<img src=x onerror="globalThis.pwned=1"> \' "</script><script>globalThis.pwned=2</script>';++function baseData(overrides = {}) {+ return Object.assign({+ REPORT_STATUS: 'Complete',+ SCOPE_NOTE: 'Reviewed 1 configuration scope and 4 source call sites.',+ WILDCARD_DATA: [],+ EXPLICIT_DATA: [],+ }, overrides);+}++function render(data) {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-report-'));+ const dataPath = path.join(tempDir, 'data.json');+ const outputPath = path.join(tempDir, 'migration-report.html');+ fs.writeFileSync(dataPath, JSON.stringify(data), 'utf8');++ const result = spawnSync(process.execPath, [scriptPath, '--output', outputPath, '--data', dataPath], {+ encoding: 'utf8',+ });+ assert.equal(result.status, 0, result.stderr || result.stdout);+ return { html: fs.readFileSync(outputPath, 'utf8'), outputPath, dataPath };+}++class FakeElement {+ constructor() {+ this.innerHTML = '';+ this.textContent = '';+ }+}++// Runs the inline renderer against a stub DOM.+function executeInlineRenderer(html) {+ const inline = html.match(/<script nonce="[^"]*">([\s\S]*?)<\/script>/);+ assert.ok(inline, 'expected an inline report renderer');++ const elements = new Map();+ const document = {+ getElementById(id) {+ if (!elements.has(id)) elements.set(id, new FakeElement());+ return elements.get(id);+ },+ querySelectorAll() { return []; },+ addEventListener() {},+ };++ const fakeWindow = { scrollTo() {}, matchMedia: () => ({ matches: false }) };+ vm.runInNewContext(inline[1], { document, console, window: fakeWindow });+ return elements;+}++test('render-migration-report keeps hostile setting and column values inert', () => {+ const { html } = render(baseData({+ WILDCARD_DATA: [{+ setting: attack,+ status: 'Migrated',+ usages: [{ location: attack, detail: attack }],+ fields: [attack, 'new_name'],+ finding: attack,+ fix: attack,+ }],+ EXPLICIT_DATA: [{+ setting: 'Webapi/contact/fields',+ status: 'Overbroad',+ usages: [{ location: 'sitesetting.yml:12', detail: attack }],+ fields: [attack],+ finding: attack,+ fix: attack,+ }],+ }));++ const elements = executeInlineRenderer(html);+ const rendered = elements.get('wildcardList').innerHTML + elements.get('explicitList').innerHTML;+ assert.doesNotMatch(rendered, /<img\b|<script\b|onclick=/i);+ assert.match(rendered, /<img src=x onerror="globalThis\.pwned=1">/);+});++test('render-migration-report counts resolved and blocked wildcards by status', () => {+ const { html } = render(baseData({+ WILDCARD_DATA: [+ { setting: 'Webapi/a/fields', status: 'Migrated', fields: ['a_name'] },+ { setting: 'Webapi/b/fields', status: 'Removed', fields: [] },+ { setting: 'Webapi/c/fields', status: 'Blocked', fields: [] },+ { setting: 'Webapi/d/fields', status: 'Pending', fields: [] },+ ],+ EXPLICIT_DATA: [{ setting: 'Webapi/e/fields', status: 'Least privilege', fields: ['e_name'] }],+ }));++ const elements = executeInlineRenderer(html);+ const stats = [...elements.get('statsGrid').innerHTML.matchAll(/stat-num[^>]*>(\d+)</g)].map(m => m[1]);+ // Found, resolved (Migrated + Removed), blocked, explicit.+ assert.deepEqual(stats, ['4', '2', '1', '1']);+ assert.equal(elements.get('badgeWildcard').textContent, 4);+ assert.equal(elements.get('badgeExplicit').textContent, 1);+});++test('render-migration-report omits zero-valued stat cards', () => {+ const { html } = render(baseData({+ WILDCARD_DATA: [{ setting: 'Webapi/a/fields', status: 'Migrated', fields: ['a_name'] }],+ }));++ const elements = executeInlineRenderer(html);+ const labels = [...elements.get('statsGrid').innerHTML.matchAll(/stat-label">([^<]+)</g)].map(m => m[1]);+ assert.deepEqual(labels, ['Wildcards Found', 'Wildcards Resolved']);+});++test('render-migration-report renders empty-state cards instead of entries', () => {+ const { html } = render(baseData());++ const elements = executeInlineRenderer(html);+ for (const id of ['wildcardList', 'explicitList']) {+ assert.match(elements.get(id).innerHTML, /class="card empty-note"/);+ assert.doesNotMatch(elements.get(id).innerHTML, /mig-table/);+ }+});++test('render-migration-report pairs each summary row with a hidden detail row', () => {+ const { html } = render(baseData({+ WILDCARD_DATA: [{+ setting: 'Webapi/account/fields',+ status: 'Migrated',+ usages: [{ location: 'src/a.js:4', detail: 'list view' }, { location: 'src/b.js:9', detail: 'detail view' }],+ fields: ['name', 'accountnumber', 'telephone1'],+ }],+ }));++ const rendered = executeInlineRenderer(html).get('wildcardList').innerHTML;+ const controls = rendered.match(/aria-controls="([^"]+)"/)[1];+ assert.match(rendered, new RegExp(`<tr class="row-detail" id="${controls}" hidden>`));+ assert.match(rendered, /aria-expanded="false"/);+ // Counts summarise the hidden detail row.+ assert.match(rendered, /<td class="col-num">2<\/td><td class="col-num">3<\/td>/);+});++test('render-migration-report stamps a human-readable UTC generated time', () => {+ const { html } = render(baseData());++ // Renderer supplies the stamp, not the caller.+ assert.match(html, /Generated [A-Z][a-z]+ \d{1,2}, \d{4} at \d{1,2}:\d{2}\s?[AP]M UTC/);+});++test('render-migration-report fails with no arguments', () => {+ const result = spawnSync(process.execPath, [scriptPath], { encoding: 'utf8' });+ assert.notEqual(result.status, 0);+ assert.match(result.stderr, /Usage:/);+});++test('render-migration-report answers --help before requiring flags', () => {+ const result = spawnSync(process.execPath, [scriptPath, '--help'], { encoding: 'utf8' });+ assert.equal(result.status, 0);+ assert.ok(result.stdout);+});++test('render-migration-report fails when a required key is missing', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'migration-report-'));+ const dataPath = path.join(tempDir, 'data.json');+ const data = baseData();+ delete data.WILDCARD_DATA;+ fs.writeFileSync(dataPath, JSON.stringify(data), 'utf8');++ const result = spawnSync(+ process.execPath,+ [scriptPath, '--output', path.join(tempDir, 'report.html'), '--data', dataPath],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 1);+ assert.match(result.stderr, /Missing required keys/);+ assert.match(result.stderr, /WILDCARD_DATA/);+});++test('render-migration-report refuses to overwrite an existing report', () => {+ const { outputPath, dataPath } = render(baseData());+ const original = fs.readFileSync(outputPath, 'utf8');++ const result = spawnSync(process.execPath, [scriptPath, '--output', outputPath, '--data', dataPath], {+ encoding: 'utf8',+ });++ assert.equal(result.status, 1);+ assert.match(result.stderr, /Output file already exists/);+ assert.equal(fs.readFileSync(outputPath, 'utf8'), original);+});diff --git a/plugins/power-pages/skills/migrate-webapi-selectall/SKILL.md b/plugins/power-pages/skills/migrate-webapi-selectall/SKILL.mdnew file mode 100644index 000000000..7b1844e91--- /dev/null+++ b/plugins/power-pages/skills/migrate-webapi-selectall/SKILL.md@@ -0,0 +1,463 @@+---+name: migrate-webapi-selectall+description: >-+ Reviews and migrates deprecated wildcard (*) values in Power Pages Web API+ fields site settings to least-privilege explicit Dataverse columns.+ Use whenever a user mentions Web API wildcard or select-all remediation,+ fields settings containing *, data-exposure review, wildcard deprecation+ readiness, or Web API failures after wildcard retirement. Applies to both+ traditional sites using HTML, CSS, JavaScript, Liquid, and downloaded YAML,+ and SPA sites using React, Vue, Angular, Astro, or TypeScript. The agent must+ inspect every source Web API call and consumer, report exact fixes for every+ wildcard, report every already-explicit configuration, apply approved edits,+ and verify no wildcard remains.+user-invocable: true+argument-hint: Optional Power Pages project path+allowed-tools: Read, Write, Edit, Bash, Grep, Glob, AskUserQuestion, TaskCreate, TaskUpdate, TaskList+model: opus+---++> **Plugin check**: Run `node "${PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.++# Migrate Power Pages Web API Wildcards++Replace every deprecated `Webapi/<table>/fields = *` value with the smallest+explicit column set proven by the site's actual Web API behavior.++The LLM owns source discovery, call-chain reasoning, field decisions, report+writing, and edits. Use the bundled script only to retrieve authoritative+Dataverse table schema; it must not decide which columns the code needs.++Support both:++- traditional sites with HTML, JavaScript, Liquid, web templates, and+ aggregate YAML;+- SPA sites with React, Vue, Angular, Astro, TypeScript, downloaded+ deployment YAML, or mixed custom JavaScript.++**Initial request:** $ARGUMENTS++## Non-negotiable rules++1. Review every discovered source table Web API call, including shared+ wrappers, dynamic builders, and response consumers.+2. Review every configuration scope and deployment-profile copy.+3. Map request `EntitySetName` values to setting logical names using table+ schema. Never singularize, pluralize, or guess.+4. Treat `*` as unsupported for reads, writes, aggregates, FetchXML, files,+ and images.+5. Give every wildcard an exact proposed replacement before editing anything.+6. Report every already-explicit fields setting, including missing and+ potentially unnecessary columns.+7. Never apply a partial wildcard plan. Resolve all wildcards and call-site+ rows first.+8. Keep reports free of absolute local paths, tokens, URLs, data values,+ filter literals, request bodies, response bodies, and source snippets, and+ build them only by rendering the bundled template with the bundled script.+9. Preserve unrelated YAML structure and values.+10. Verify with a fresh discovery pass, not remembered inventory.+11. Leave only the rendered report and its icon in the migration output+ directory.+12. Never download or upload site content until the user has explicitly+ confirmed the environment, website, site type, data model, and deployment+ profile. Neither transfer can be reverted.+13. Run smoke tests only after explicit approval, and never issue POST, PATCH,+ PUT, or DELETE Web API calls against a deployed site. Testing a write+ destroys real record data.++Read [references/column-analysis.md](references/column-analysis.md) before+analyzing calls. Read+[references/configuration-and-reporting.md](references/configuration-and-reporting.md)+before inventorying settings or writing the report. Read+[references/site-transfer.md](references/site-transfer.md) before any download+or upload.++## Phase 1: Prepare++**Goal:** Resolve the project, confirm the site, and protect existing work.++1. Create all seven tasks from [Progress tracking](#progress-tracking).+2. Resolve `PROJECT_ROOT` from `$ARGUMENTS` or the current directory.+3. Detect site markers independently:+ - `powerpages.config.json` indicates an SPA site;+ - root `website.yml`, root `sitesetting.yml`, or `.powerpages-site/`+ indicates downloaded declarative artifacts;+ - when both appear, scan both layouts.+4. Read `.solution-manifest.json` when present. This migration changes existing+ settings; do not create or select another solution.+5. Inspect git status. Never discard, hide, or include unrelated user changes.+6. Run `node --version`.+7. Confirm `assets/migration-report-template.html` and+ `scripts/render-migration-report.js` are readable, and stop if either is+ missing.+8. Read [references/site-transfer.md](references/site-transfer.md), then+ confirm the environment, website name and `WebSiteId`, site type, data+ model, deployment profile, and target path with the user. Check each+ against `pac auth who`, `pac env who`, and `pac pages list`, and stop on+ any mismatch. Never infer one from a folder name or an active default.++Analyzing the wrong site produces confident, wrong fixes, so settle identity+before reading any setting. Download only when the user wants a fresh copy or+`PROJECT_ROOT` holds no site content; downloading replaces local files and+cannot be reverted.++<!-- gate: migrate-webapi-selectall:1.download-site | category=consent | cancel-leaves=nothing -->++> 🚦 **Gate (consent · migrate-webapi-selectall:1.download-site):** Approve the download only after displaying the confirmed environment, website name and ID, site type, data model, target path, and the exact command. Canceling leaves local content untouched and continues against the existing copy.++Use `AskUserQuestion`: `Download the confirmed site` or `Use the local copy`.+Repeat step 3 after any download.++**Output:** Project root, site layouts, solution context, git state, confirmed+site identity, and a downloaded copy when approved.++## Phase 2: Build the complete inventory++**Goal:** Find every configuration and candidate source Web API call before+reasoning about columns.++### 2.1 Inventory configuration scopes++Use `Glob`, `Grep`, and `Read` to inspect:++- every `sitesetting.yml`;+- every `*.sitesetting.yml`;+- `.powerpages-site/site-settings/`;+- deployment-profile and environment-specific copies.++Record every `Webapi/<table>/fields` and `Webapi/<table>/enabled` entry with+its relative file, line, scope, key style, and current value. Classify fields+settings as:++- `wildcard`;+- `explicit`;+- `missing` for an enabled table;+- `duplicate` only within the same configuration scope.++Do not treat identical settings in different deployment profiles as+duplicates. Record every profile name and which settings it overrides. Never+assume the `default` profile is the intended deployment profile.++Query Dataverse once per unique table, never once per configuration.++### 2.2 Inventory source calls++Analyze only authoritative, editable source files. Never inspect compiled or+generated code.++For SPA sites:++1. Read `powerpages.config.json`, `package.json`, and present framework or+ bundler configuration before searching calls.+2. Treat `compiledPath` and every configured build-output directory as a hard+ exclusion.+3. Exclude `.powerpages-site/web-files/`, `node_modules/`, coverage and cache+ directories, source maps, minified bundles, framework output directories,+ and content-hashed assets matching+ `<entry-name>-<content-hash>.<extension>`.+4. Use `.powerpages-site/site-settings/` only for configuration inventory,+ never for source analysis.+5. Search editable roots such as configured source directories and framework+ application directories.++For traditional sites, search editable JavaScript, Liquid, web templates, web+files, and other authored source. Do not exclude an authored traditional web+file merely because it is deployed as a web file.++Search source extensions including `.js`, `.jsx`, `.ts`, `.tsx`, `.vue`,+`.html`, `.htm`, `.liquid`, `.aspx`, `.ascx`, `.cshtml`, and XML web+templates. If a call exists only in compiled, minified, generated, or+content-hashed output, record a `missing-source` blocker and stop the+migration. Do not infer columns from that output.++Search for:++- `/_api/`, encoded variants, split URL fragments, and API base constants;+- `fetch`, Axios, `XMLHttpRequest`, jQuery AJAX, `webapi.safeAjax`,+ `shell.ajaxSafePost`, and custom request wrappers;+- entity-set constants, query builders, FetchXML builders, and body builders;+- callers and consumers imported from other files.++For each source candidate, record relative path, line, method, endpoint+expression, and wrapper chain. A comment, example, or non-table endpoint still+needs an explicit disposition. Excluded build outputs are never recorded.++Write the settings inventory to+`docs/webapi-selectall-migration/migration-report.json` and render the draft+report as described in+[references/configuration-and-reporting.md](references/configuration-and-reporting.md).+Do not propose fields yet.++Stop if any in-scope source or configuration file cannot be read.++<!-- gate: migrate-webapi-selectall:2.confirm-scope | category=plan | cancel-leaves=draft-migration-report -->++> 🚦 **Gate (plan · migrate-webapi-selectall:2.confirm-scope):** Confirm the project, configuration scopes and profiles, wildcard count, explicit-setting count, and source inventory before schema retrieval. Canceling leaves only the read-only draft report.++Use `AskUserQuestion` to confirm or cancel. Expand the inventory and repeat this+phase if the user identifies another source or deployment scope.++## Phase 3: Retrieve schema and resolve columns++**Goal:** Use authoritative names while letting the LLM determine actual usage.++### 3.1 Retrieve only relevant table schema++Build the initial unique list containing:++- logical table names from all Web API settings;+- entity-set names from all candidate table calls;+- entity-set names directly present in bind targets or related-table calls.++Do not treat a navigation-property name as a table identifier. Its target+logical name is authoritative only after relationship metadata resolves it.++Resolve the environment URL from confirmed project context or `pac env who`.+If unavailable, ask for the URL as data gathering; never ask for or accept an+access token.++<!-- not-a-gate: environment URL supplies read-only metadata query input only -->++Write every deduplicated identifier, one per line, to+`docs/webapi-selectall-migration/table-identifiers.txt`. Run:++```bash+node "${PLUGIN_ROOT}/skills/migrate-webapi-selectall/scripts/query-table-schema.js" --project-root "<PROJECT_ROOT>" --environment-url "<ENVIRONMENT_URL>" --tables-file "<PROJECT_ROOT>/docs/webapi-selectall-migration/table-identifiers.txt" --output "<PROJECT_ROOT>/docs/webapi-selectall-migration/table-schema.json"+```++If an identifier does not resolve, trace the code or obtain the correct+contract; do not guess.++After the initial snapshot:++1. Match every used `$expand` navigation property against its source table's+ returned relationship metadata.+2. Collect only target logical names absent from all existing snapshots.+3. Write those names to+ `table-identifiers-pass-<N>.txt` and query them to+ `table-schema.pass-<N>.json`.+4. Repeat for nested expansion paths until every used navigation segment is+ resolved.++Treat `table-schema.json` and all numbered snapshots as one schema package.+Never requery a logical table already present in that package, and never+launch concurrent schema queries.++Identifier lists and schema snapshots are working files. Keep them until+verification finishes, then delete them in Phase 7.++### 3.2 Analyze every call and consumer++For every source inventory row:++1. Read the complete enclosing function or template block.+2. Trace imported wrappers, URL variables, query builders, body builders,+ response mappers, types, components, templates, and every caller.+3. Follow conditional branches, spreads, dynamic arrays, and runtime+ configuration.+4. Map the entity set to its logical table using the schema package.+5. Apply every rule in+ [references/column-analysis.md](references/column-analysis.md).+6. Record requirements per owning logical table, not merely per request.+7. Classify the row as `mapped`, `non-table`, or `not-a-call`.+8. Leave the row unresolved if any runtime branch or consumer remains unknown.++One logical table is normally reached from several places. Collect every call+site for a table before proposing its fields: duplicated or competing+wrappers, per-page scripts, different query shapes, and repeated calls in the+same file. A later call site for an already-analyzed table can still add+columns, so never stop at the first one.++For normal record GETs without `$select`, derive output fields from every+consumer and propose a source edit adding the smallest explicit projection.+Filters, ordering, and other query fields still belong in the fields setting,+even when they should not be added to the output projection.++Keep the response projection and fields-setting allowlist as separate sets.+Never add a filter-only, order-only, grouping-only, or write-only column to an+existing `$select` unless a response consumer also reads it.++### 3.3 Build configuration proposals++For each wildcard setting:++1. Union the proven requirements from every call site that reaches that+ logical table within the applicable site behavior.+2. Validate each proposed name against the schema package.+3. Link every proposed column to source path and line or a user-confirmed+ external contract.+4. Produce the exact replacement:++ ```text+ Webapi/<table>/fields = <column-name-1>,<column-name-2>,<column-name-3>+ ```++5. Keep the proposal unresolved if it is empty or any evidence is incomplete.++For each already-explicit setting:++- compare configured columns with proven required columns;+- classify it as exact, missing required columns, potentially overbroad, or+ externally justified;+- include an exact proposed fix for every gap;+- do not silently change it.++Update the report. Resolve all wildcard and call-site rows before continuing.++**Output:** Evidence-complete report with exact wildcard replacements and all+already-explicit configurations.++## Phase 4: Review the complete plan++**Goal:** Present the full exposure reduction before edits.++Show:++- wildcard issues found and the exact replacement for each;+- evidence for every proposed column;+- source GETs requiring `$select`;+- already-explicit settings and any missing or excess columns;+- any missing or duplicate settings found during inventory;+- zero unresolved call sites.++<!-- gate: migrate-webapi-selectall:4.apply-plan | category=consent | cancel-leaves=reviewed-migration-report -->++> 🚦 **Gate (consent · migrate-webapi-selectall:4.apply-plan):** Approve all wildcard replacements, required source projections, optional explicit-setting hardening, and local edits. Canceling preserves only the report.++Use `AskUserQuestion` with:++- `Apply all wildcard fixes and approved explicit fixes`;+- `Apply all wildcard fixes only`;+- `Cancel`.++Never offer a subset of wildcard fixes.++## Phase 5: Apply approved edits++**Goal:** Update source projections and every wildcard setting.++1. Use `Edit` to add approved `$select` projections. Preserve methods, filters,+ ordering, expansion, pagination, encoding, Liquid expressions, and error+ handling.+2. Use `Edit` to replace every wildcard value in every scope and profile.+ Preserve identifiers, key names, quoting, indentation, comments, and+ unrelated values.+3. Apply already-explicit changes only when included in the selected approval.+4. Re-read every changed block immediately and update report status.++If any edit fails or a file changed since review, stop. Do not continue with a+partial configuration set and do not perform a broad rollback over user work.++**Output:** All approved local edits and updated report.++## Phase 6: Verify independently++**Goal:** Prove the migration without trusting prior notes.++1. Repeat Phase 2 discovery from scratch.+2. Confirm every configuration scope contains zero+ `Webapi/<table>/fields` wildcard values.+3. Compare each migrated value with its approved exact replacement.+4. Reopen every call site and replay the coverage analysis:+ - mapped table and method remain correct;+ - required setting columns are present;+ - normal record GETs use explicit `$select`;+ - expanded, lookup, write, FetchXML, file, and image columns remain covered.+5. Run the existing project build for SPA sites. For traditional sites,+ inspect edited JavaScript and Liquid syntax and use existing site tests when+ available.+6. Finalize the report status and every entry status, then delete the previous+ `migration-report.html` and re-render it from the updated data file.++Do not claim full hardening while explicit configuration gaps remain. Use the+partial status defined in the reporting contract when applicable.++**Output:** Final report and verified local migration.++## Phase 7: Deploy and summarize++**Goal:** Publish only verified changes.++Re-confirm every identity detail in+[references/site-transfer.md](references/site-transfer.md) with the user+immediately before uploading, and display the exact command. Select the+deployment profile the user reviewed, and use `default` only when they name+it. Any change of environment, website, data model, or profile requires a+separate deployment approval.++<!-- gate: migrate-webapi-selectall:7.deploy | category=final | cancel-leaves=local-migration -->++> 🚦 **Gate (final · migrate-webapi-selectall:7.deploy):** Approve the verified migration for the displayed environment, website, site type, data model, and deployment profile. Canceling preserves local edits and the final report without changing the live site.++Use `AskUserQuestion`: `Deploy now` or `Keep local only`.++- Re-run `pac auth who` and `pac env who`, and stop on any mismatch.+ `pac pages upload-code-site` accepts no `--environment` and targets whatever+ the active authentication profile reports.+- For SPA sites, confirm `.powerpages-site` contains the approved+ configuration edits, run the existing production build, then run+ `pac pages upload-code-site --rootPath "<PROJECT_ROOT>" --siteName+ "<SITE_NAME>"`.+- For traditional sites, run `pac pages upload --path "<PROJECT_ROOT>"+ --environment "<ENVIRONMENT>" --modelVersion "<Standard|Enhanced>"+ --deploymentProfile "<PROFILE>"`.++Never substitute one upload command for the other. Each corrupts the other+site type, and the damage cannot be reverted.++After deployment, list the read paths a smoke test would exercise: GET calls,+`$select` projections, `$expand`, FetchXML, and aggregates. Never run one+unprompted.++<!-- gate: migrate-webapi-selectall:7.smoke-test | category=progress | cancel-leaves=deployed-migration-unverified -->++> 🚦 **Gate (progress · migrate-webapi-selectall:7.smoke-test):** Approve the listed read-path smoke test against the deployed site. Canceling skips it and reports the deployed migration as unverified.++Use `AskUserQuestion`: `Run the read-path smoke test` or `Skip verification`.++Never issue write, file, or image requests. Ask the user to exercise those+paths themselves against disposable records.++Treat HTTP 403 responses as evidence to investigate and never restore `*`. Do+not add a column under the prior approval. Return to Phase 3, update the exact+plan and report, repeat the Phase 4 approval, independently verify in Phase 6,+and obtain a new Phase 7 deployment approval.++Delete every working file created during the migration, keeping only+`docs/webapi-selectall-migration/migration-report.html` and the+`power-pages-icon.png` the renderer places beside it:++- `table-identifiers.txt` and `table-identifiers-pass-<N>.txt`;+- `table-schema.json` and `table-schema.pass-<N>.json`;+- `migration-report.json`.++Delete only files this migration created, and confirm the directory holds the+report and its icon alone. Skip cleanup while returning to an earlier phase,+and delete the regenerated files once that pass finishes.++Record usage by following+`${PLUGIN_ROOT}/references/skill-tracking-reference.md` with+`--skillName "MigrateWebapiSelectall"`.++Summarize wildcard counts, explicit reviews, source edits, report path,+verification, deployment, and every path left unverified.++## Progress tracking++Create these tasks before Phase 1:++| Task subject | activeForm | Description |+|---|---|---|+| Prepare migration project | Preparing migration project | Confirm the site, then resolve layouts and git state |+| Inventory Web API usage | Inventorying Web API usage | Find every configuration and source call |+| Resolve actual columns | Resolving actual columns | Retrieve schema and trace every consumer |+| Review migration plan | Reviewing migration plan | Present exact fixes and evidence |+| Apply approved migration | Applying approved migration | Edit projections and configurations |+| Verify migration results | Verifying migration results | Repeat discovery, build, and finalize report |+| Deploy and summarize | Deploying and summarizing | Publish after approval and report outcome |++Mark each task `in_progress` when starting and `completed` when finished.++---++**Begin with Phase 1: Prepare.**diff --git a/plugins/power-pages/skills/migrate-webapi-selectall/assets/migration-report-template.html b/plugins/power-pages/skills/migrate-webapi-selectall/assets/migration-report-template.htmlnew file mode 100644index 000000000..6a84776c8--- /dev/null+++ b/plugins/power-pages/skills/migrate-webapi-selectall/assets/migration-report-template.html@@ -0,0 +1,316 @@+<!DOCTYPE html>+<html lang="en" data-report-template-version="2">+<head>+<meta charset="UTF-8"/>+<meta name="viewport" content="width=device-width,initial-scale=1.0"/>+<meta name="color-scheme" content="light"/>+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-__ATTR_CSP_NONCE__'; style-src 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"/>+<title>Web API Wildcard Migration</title>+<style>+:root {+ --bg:#faf9f8; --surface:#ffffff; --surface2:#f3f2f1;+ --border:#e1dfdd;+ --text:#323130; --text-dim:#605e5c; --text-bright:#201f1e;+ --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;+ --critical:#d13438; --critical-bg:#d134380a; --critical-border:#d1343825;+ --warning:#ca5010; --warning-bg:#ca50100a; --warning-border:#ca501025;+ --pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1025;+ --info:#0078d4; --info-bg:#0078d40a; --info-border:#0078d425;+ --mono:'Cascadia Code','Consolas',monospace;+ --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;+ --radius:8px; --radius-sm:4px;+ --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);+ --topbar-h:72px;+}+*{margin:0;padding:0;box-sizing:border-box;}+html{scroll-behavior:smooth;}+body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14px;line-height:1.6;}+:focus-visible{outline:2px solid var(--accent);outline-offset:2px;}+.visually-hidden{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;}+.skip-link{position:absolute;top:-100px;left:12px;z-index:200;padding:10px 16px;color:var(--text-bright);background:var(--surface);border:1px solid var(--accent);border-radius:var(--radius);}+.skip-link:focus{top:12px;}++.topbar{z-index:100;background:var(--surface);box-shadow:var(--shadow-4);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;position:sticky;top:0;}+.topbar-left{display:flex;align-items:center;gap:14px;}+.logo{width:36px;height:36px;object-fit:contain;display:block;flex-shrink:0;}+.topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}+.topbar-sub{font-size:11px;color:var(--text-dim);margin-top:1px;}+.report-status{font-size:10px;font-weight:700;padding:3px 10px;border-radius:10px;text-transform:uppercase;letter-spacing:0.6px;background:var(--accent-bg);color:var(--accent);border:1px solid var(--accent-border);}++.layout{display:flex;min-height:calc(100vh - var(--topbar-h));}+.sidebar{width:240px;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;flex-shrink:0;}+.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:10px 22px;background:none;border:none;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;font-family:var(--sans);text-align:left;transition:all 0.15s;position:relative;}+.nav-btn:hover{color:var(--text);background:var(--surface2);}+.nav-btn.active{color:var(--accent);font-weight:600;border-left-color:var(--accent);background:var(--accent-bg);}+.nav-btn .nav-icon{font-size:14px;opacity:0.6;width:16px;text-align:center;}+.nav-btn.active .nav-icon{opacity:0.95;}+.nav-badge{position:absolute;right:14px;font-size:10px;font-family:var(--mono);padding:1px 6px;border-radius:8px;font-weight:700;background:var(--surface2);color:var(--text-dim);border:1px solid var(--border);}++.content{flex:1;min-width:0;padding:32px 40px 72px;max-width:1100px;}+.section{display:none;}+.section.active{display:block;animation:fadeIn 0.3s ease;}+@keyframes fadeIn{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}++h2{font-size:21px;font-weight:800;color:var(--text-bright);letter-spacing:-0.3px;margin-bottom:5px;}+.section-desc{font-size:13px;color:var(--text-dim);margin-bottom:20px;}++.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;margin-bottom:10px;transition:box-shadow 0.2s;}+.card:hover{box-shadow:var(--shadow-4);}++.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px;margin-bottom:20px;}+.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 16px;text-align:center;box-shadow:var(--shadow-4);}+.stat-num{font-size:28px;font-weight:800;font-family:var(--mono);line-height:1;}+.stat-label{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px;margin-top:6px;}++.severity{font-size:9px;font-weight:700;padding:3px 8px;border-radius:3px;font-family:var(--mono);display:inline-block;text-transform:uppercase;letter-spacing:0.5px;flex-shrink:0;}+.severity-critical{color:var(--critical);background:var(--critical-bg);border:1px solid var(--critical-border);}+.severity-warning{color:var(--warning);background:var(--warning-bg);border:1px solid var(--warning-border);}+.severity-info{color:var(--info);background:var(--info-bg);border:1px solid var(--info-border);}+.severity-pass{color:var(--pass);background:var(--pass-bg);border:1px solid var(--pass-border);}++.mig-table{width:100%;border-collapse:collapse;font-size:13px;margin:10px 0;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;}+.table-scroll{overflow-x:auto;}+.mig-table th{text-align:left;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.8px;color:var(--text-dim);padding:10px 12px;border-bottom:2px solid var(--border);background:var(--surface2);}+.mig-table td{padding:10px 12px;border-bottom:1px solid var(--border);vertical-align:top;}+.mig-table tbody tr:last-child td{border-bottom:none;}+.row-summary:hover td{background:var(--surface2);}+.col-toggle{width:36px;}+.col-num{width:90px;text-align:right;}+td.col-num{font-family:var(--mono);color:var(--text);text-align:right;}+.cell-setting{font-family:var(--mono);font-weight:600;color:var(--text-bright);overflow-wrap:anywhere;}+.row-toggle{background:none;border:none;cursor:pointer;color:var(--text-dim);font-size:12px;padding:0;line-height:1;}+.row-toggle[aria-expanded="true"] .chevron{transform:rotate(90deg);}+.chevron{display:inline-block;transition:transform 0.2s;}+.row-detail>td{background:var(--surface2);padding:4px 16px 16px 44px;}++.field-label{font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px;}+.field-block{margin-top:12px;}+.field-chips{display:flex;flex-wrap:wrap;gap:4px;}+.field-chip{font-family:var(--mono);font-size:11px;color:var(--text);background:var(--surface);border:1px solid var(--border);border-radius:3px;padding:2px 7px;overflow-wrap:anywhere;}+.usage-list{list-style:none;display:flex;flex-direction:column;gap:6px;}+.usage-loc{font-family:var(--mono);font-size:11px;color:var(--text-bright);background:var(--surface);border:1px solid var(--border);border-radius:3px;padding:1px 6px;margin-right:8px;overflow-wrap:anywhere;}+.usage-detail{font-size:12px;color:var(--text);}+.reasoning-block{background:var(--surface);border-left:2px solid var(--accent);border-radius:var(--radius-sm);padding:10px 14px;font-size:12px;color:var(--text);line-height:1.7;}+.fix-block{background:var(--pass-bg);border-left:2px solid var(--pass);border-radius:var(--radius-sm);padding:10px 14px;font-size:12px;color:var(--text);line-height:1.7;}+.empty-note{color:var(--text-dim);}++@media(max-width:900px){+ .layout{flex-direction:column;}+ .sidebar{width:100%;display:flex;overflow-x:auto;padding:0;border-right:none;border-bottom:1px solid var(--border);}+ .nav-btn{width:auto;white-space:nowrap;border-left:none;border-bottom:2px solid transparent;padding:12px 18px 12px 18px;}+ .nav-btn.active{border-left-color:transparent;border-bottom-color:var(--accent);}+ .nav-badge{position:static;margin-left:2px;}+ .content{padding:20px 16px 72px;}+}+@media(max-width:600px){+ /* Detail row repeats both counts; drop columns. */+ .mig-table .col-num{display:none;}+}+@media(prefers-reduced-motion:reduce){+ html{scroll-behavior:auto;}+ .section.active{animation:none;}+ .chevron{transition:none;}+}+@media(forced-colors:active){+ .card,.stat-card,.mig-table,.severity,.field-chip,.report-status{border:1px solid CanvasText;}+}+@media print{+ body{background:#fff;}+ .topbar,footer{position:static;}+ .sidebar,.col-toggle{display:none;}+ .section{display:block!important;animation:none;}+ .row-detail{display:table-row!important;}+ .card,.stat-card,.mig-table tr{box-shadow:none;break-inside:avoid;}+}+</style>+</head>+<body>++<a class="skip-link" href="#contentRoot">Skip to report content</a>++<div class="topbar">+ <div class="topbar-left">+ <img class="logo" src="./power-pages-icon.png" alt="Power Pages"/>+ <div>+ <div class="topbar-title">Web API Wildcard Migration</div>+ <div class="topbar-sub">Least-privilege field settings · Generated __GENERATED_AT__</div>+ </div>+ </div>+ <span class="report-status"><span class="visually-hidden">Report status: </span>__REPORT_STATUS__</span>+</div>++<div class="layout">+ <div class="sidebar" role="tablist" aria-label="Report sections">+ <button class="nav-btn active" role="tab" id="nav-overview" aria-controls="tab-overview" aria-selected="true" data-tab="overview"><span class="nav-icon" aria-hidden="true">◉</span> Overview</button>+ <button class="nav-btn" role="tab" id="nav-wildcard" aria-controls="tab-wildcard" aria-selected="false" tabindex="-1" data-tab="wildcard"><span class="nav-icon" aria-hidden="true">⚠</span> Wildcard Fields <span class="nav-badge" id="badgeWildcard"></span></button>+ <button class="nav-btn" role="tab" id="nav-explicit" aria-controls="tab-explicit" aria-selected="false" tabindex="-1" data-tab="explicit"><span class="nav-icon" aria-hidden="true">▦</span> Explicit Fields <span class="nav-badge" id="badgeExplicit"></span></button>+ </div>++ <div class="content" id="contentRoot">++ <div class="section active" id="tab-overview" role="tabpanel" aria-labelledby="nav-overview" tabindex="0">+ <h2>Overview</h2>+ <p class="section-desc">__SCOPE_NOTE__</p>+ <div class="stats-grid" id="statsGrid"></div>+ </div>++ <div class="section" id="tab-wildcard" role="tabpanel" aria-labelledby="nav-wildcard" tabindex="0">+ <h2>Wildcard Fields</h2>+ <p class="section-desc">Settings whose <code>fields</code> value used <code>*</code>. Expand a row to see every usage, the replacement columns, and the evidence behind them.</p>+ <div id="wildcardList"></div>+ </div>++ <div class="section" id="tab-explicit" role="tabpanel" aria-labelledby="nav-explicit" tabindex="0">+ <h2>Explicit Fields</h2>+ <p class="section-desc">Settings that already listed columns. Expand a row to compare the configured columns against the columns the site actually uses.</p>+ <div id="explicitList"></div>+ </div>++ </div>+</div>++<footer style="position:fixed;bottom:0;left:0;right:0;text-align:center;padding:10px;font-size:12px;color:#605e5c;border-top:1px solid #c8c6c4;background:#ffffff;z-index:100;">AI-generated content may be incorrect</footer>++<script nonce="__ATTR_CSP_NONCE__">+const WILDCARD_DATA = __JSON_WILDCARD_DATA__;+const EXPLICIT_DATA = __JSON_EXPLICIT_DATA__;++// Entry: { setting, status, usages: [{location, detail}], fields, finding, fix }+// Unknown status values fall back to neutral.+const STATUS_TONE = {+ migrated: 'pass', 'least privilege': 'pass',+ pending: 'warning', overbroad: 'warning', incomplete: 'warning',+ blocked: 'critical',+ removed: 'info',+};++// Resolved means the setting no longer carries `*`.+const RESOLVED_STATUS = ['migrated', 'removed'];++function esc(s) {+ if (s == null) return '';+ return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');+}++function escAttr(s) { return String(s == null ? '' : s).replace(/[^a-zA-Z0-9_-]/g, ''); }++function toneOf(status) { return STATUS_TONE[String(status || '').toLowerCase()] || 'info'; }++function fieldBlock(label, fields) {+ if (!Array.isArray(fields) || fields.length === 0) return '';+ const chips = fields.map(f => '<span class="field-chip">' + esc(f) + '</span>').join('');+ return '<div class="field-block"><div class="field-label">' + esc(label) + ' (' + fields.length + ')</div>' ++ '<div class="field-chips">' + chips + '</div></div>';+}++function usageBlock(usages) {+ if (!usages.length) return '';+ const items = usages.map(u =>+ '<li><span class="usage-loc">' + esc(u.location) + '</span>' ++ (u.detail ? '<span class="usage-detail">' + esc(u.detail) + '</span>' : '') + '</li>').join('');+ return '<div class="field-block"><div class="field-label">Usages (' + usages.length + ')</div>' ++ '<ul class="usage-list">' + items + '</ul></div>';+}++function textBlock(label, text, className) {+ if (!text) return '';+ return '<div class="field-block"><div class="field-label">' + esc(label) + '</div>' ++ '<div class="' + className + '">' + esc(text) + '</div></div>';+}++function rowsHtml(entry, index, prefix, fieldsLabel) {+ const detailId = prefix + '-detail-' + index;+ const usages = Array.isArray(entry.usages) ? entry.usages : [];+ const fields = Array.isArray(entry.fields) ? entry.fields : [];+ return '<tr class="row-summary">' ++ '<td class="col-toggle"><button type="button" class="row-toggle" aria-expanded="false" aria-controls="' + escAttr(detailId) + '">' ++ '<span class="chevron" aria-hidden="true">▶</span>' ++ '<span class="visually-hidden">Details for ' + esc(entry.setting) + '</span></button></td>' ++ '<td><span class="severity severity-' + toneOf(entry.status) + '">' + esc(entry.status) + '</span></td>' ++ '<td class="cell-setting">' + esc(entry.setting) + '</td>' ++ '<td class="col-num">' + usages.length + '</td>' ++ '<td class="col-num">' + fields.length + '</td>' ++ '</tr>' ++ '<tr class="row-detail" id="' + escAttr(detailId) + '" hidden><td colspan="5">' ++ usageBlock(usages) ++ fieldBlock(fieldsLabel, fields) ++ textBlock('Evidence', entry.finding, 'reasoning-block') ++ textBlock('Outcome', entry.fix, 'fix-block') ++ '</td></tr>';+}++function renderList(container, entries, prefix, fieldsLabel, emptyText) {+ if (!entries.length) {+ container.innerHTML = '<div class="card empty-note">' + esc(emptyText) + '</div>';+ return;+ }+ container.innerHTML = '<div class="table-scroll"><table class="mig-table">' ++ '<thead><tr><th class="col-toggle"><span class="visually-hidden">Expand</span></th>' ++ '<th>Status</th><th>Site setting</th>' ++ '<th class="col-num">Usages</th><th class="col-num">Columns</th></tr></thead><tbody>' ++ entries.map((e, i) => rowsHtml(e, i, prefix, fieldsLabel)).join('') ++ '</tbody></table></div>';+}++const wildcards = Array.isArray(WILDCARD_DATA) ? WILDCARD_DATA : [];+const explicits = Array.isArray(EXPLICIT_DATA) ? EXPLICIT_DATA : [];+const statusOf = (entry) => String(entry.status || '').toLowerCase();++const stats = [+ { num: wildcards.length, label: 'Wildcards Found', color: 'var(--warning)' },+ { num: wildcards.filter(e => RESOLVED_STATUS.includes(statusOf(e))).length, label: 'Wildcards Resolved', color: 'var(--pass)' },+ { num: wildcards.filter(e => statusOf(e) === 'blocked').length, label: 'Wildcards Blocked', color: 'var(--critical)' },+ { num: explicits.length, label: 'Explicit Settings', color: 'var(--accent)' },+];+document.getElementById('statsGrid').innerHTML = stats+ .filter(s => s.num > 0)+ .map(s => '<div class="stat-card"><div class="stat-num" style="color:' + s.color + '">' + s.num + '</div><div class="stat-label">' + esc(s.label) + '</div></div>')+ .join('');++document.getElementById('badgeWildcard').textContent = wildcards.length;+document.getElementById('badgeExplicit').textContent = explicits.length;++renderList(document.getElementById('wildcardList'), wildcards, 'wildcard', 'Replacement columns',+ 'No wildcard field settings were found in any configuration scope.');+renderList(document.getElementById('explicitList'), explicits, 'explicit', 'Configured columns',+ 'No already-explicit field settings were found in any configuration scope.');++const navButtons = Array.from(document.querySelectorAll('.nav-btn'));+// An explicit behavior overrides the CSS reduced-motion rule.+const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)');+function selectTab(btn) {+ navButtons.forEach(b => {+ const on = b === btn;+ b.classList.toggle('active', on);+ b.setAttribute('aria-selected', String(on));+ // Roving tabindex keeps a single tablist tab stop.+ b.tabIndex = on ? 0 : -1;+ document.getElementById('tab-' + b.dataset.tab).classList.toggle('active', on);+ });+ window.scrollTo({ top: 0, behavior: reduceMotion.matches ? 'auto' : 'smooth' });+}+navButtons.forEach((btn, index) => {+ btn.addEventListener('click', () => selectTab(btn));+ btn.addEventListener('keydown', event => {+ const step = event.key === 'ArrowRight' || event.key === 'ArrowDown' ? 1+ : event.key === 'ArrowLeft' || event.key === 'ArrowUp' ? -1 : 0;+ if (!step) return;+ event.preventDefault();+ const next = navButtons[(index + step + navButtons.length) % navButtons.length];+ selectTab(next);+ next.focus();+ });+});++document.addEventListener('click', event => {+ const toggle = event.target.closest('.row-toggle');+ if (!toggle) return;+ const detail = document.getElementById(toggle.getAttribute('aria-controls'));+ if (!detail) return;+ detail.hidden = !detail.hidden;+ toggle.setAttribute('aria-expanded', String(!detail.hidden));+});+</script>++</body>+</html>diff --git a/plugins/power-pages/skills/migrate-webapi-selectall/references/column-analysis.md b/plugins/power-pages/skills/migrate-webapi-selectall/references/column-analysis.mdnew file mode 100644index 000000000..6ecb43876--- /dev/null+++ b/plugins/power-pages/skills/migrate-webapi-selectall/references/column-analysis.md@@ -0,0 +1,119 @@+# Column Analysis Rules++Use these rules to determine the smallest explicit field list that preserves+each Power Pages Web API operation. Read every call chain and consumer; static+search results are an inventory, not the final answer.++## Contents++- [Evidence priority](#evidence-priority)+- [Endpoint mapping](#endpoint-mapping)+- [Read operations](#read-operations)+- [Write operations](#write-operations)+- [File and image operations](#file-and-image-operations)+- [Dynamic code](#dynamic-code)+- [Configuration proposal](#configuration-proposal)++## Evidence priority++Prefer evidence in this order:++1. Request syntax: `$select`, `$expand`, property paths, FetchXML, `$filter`,+ `$orderby`, and `$apply`.+2. Write payloads: POST, PATCH, PUT, deep inserts, and `@odata.bind`.+3. Response consumers: property access, destructuring, mappers, templates,+ framework bindings, and TypeScript interfaces.+4. Shared builders: callers, defaults, conditional branches, and runtime+ configuration.+5. Dataverse schema: canonical attributes, entity sets, lookups, and+ navigation properties.+6. User-confirmed integration contracts when repository evidence is+ incomplete.++Do not mark a proposal ready while a source wrapper, branch, or response+consumer remains unread. Never substitute compiled or generated code for+missing source.++## Endpoint mapping++Power Pages request paths use `EntitySetName`.+`Webapi/<table>/fields` settings use the table logical name. These names are+not reliably related by pluralization, so map them through the schema snapshot.++Classify search, summarization, cloud-flow, and server-logic routes under+`/_api/` as non-table endpoints only after confirming their public API shape.+Do not silently omit an unfamiliar endpoint.++## Read operations++For each table-returning GET:++- include root `$select` columns;+- include columns used by `$filter` and `$orderby`;+- include lookup read properties such as `_<lookup-column-name-1>_value` when+ consumed;+- include the source lookup attribute for single-valued `$expand` navigation;+- assign nested `$select`, filter, and order columns to the expanded table;+- include FetchXML attributes, conditions, ordering, grouping, and aggregate+ inputs on their owning entity or link-entity;+- include `$apply` group, filter, and aggregate inputs, excluding output+ aliases;+- add `$select` when a normal record GET omits it, deriving the projection from+ every response consumer.++Maintain two separate results:++- the response projection contains only columns returned to consumers;+- the fields-setting allowlist contains projection, filter, order, aggregate,+ lookup, property-route, and write requirements.++Do not widen an existing `$select` with a filter-only, order-only,+grouping-only, or write-only column.++`$top`, `$skip`, `$count`, paging cookies, aggregate aliases, formatted-value+annotations, and filter literals are not Dataverse columns.++## Write operations++For POST, PATCH, and PUT:++- include every payload property mapped to a Dataverse attribute;+- resolve `[email protected]` to the underlying lookup attribute;+- trace variables passed to `JSON.stringify`, HTTP clients, and custom+ wrappers;+- inspect conditional properties and every object spread source;+- assign deep-insert object fields to their related target table.++For property PUT or DELETE routes, include the property named in the URL. A+record DELETE adds no field requirement by itself, but the table setting still+needs a nonempty, evidence-backed field list.++## File and image operations++Treat file and image endpoints as explicit-column operations:++- include the file or image column in the route;+- include file name, size, MIME type, or image metadata only when separately+ read;+- never retain `*` as a compatibility workaround.++## Dynamic code++Trace dynamic entity sets, column arrays, URL fragments, query strings,+request bodies, and FetchXML through every caller and runtime branch.++When values come from external configuration, obtain the owning contract or+user confirmation. Do not infer fields from labels, singularization, naming+conventions, or likely primary keys.++## Configuration proposal++For each logical table and configuration scope, compute the sorted union of+proven columns across all reads and writes. Every proposed column needs:++- a relative source path and line, or a user-confirmed contract;+- the operation requiring it;+- its exact metadata-canonical name.++Do not add every metadata attribute, speculative identifiers, unrelated+server-side fields, or columns owned by expanded target tables.diff --git a/plugins/power-pages/skills/migrate-webapi-selectall/references/configuration-and-reporting.md b/plugins/power-pages/skills/migrate-webapi-selectall/references/configuration-and-reporting.mdnew file mode 100644index 000000000..89abdaf1f--- /dev/null+++ b/plugins/power-pages/skills/migrate-webapi-selectall/references/configuration-and-reporting.md@@ -0,0 +1,163 @@+# Configuration and Reporting Contract++## Contents++- [Configuration layouts](#configuration-layouts)+- [Configuration scopes](#configuration-scopes)+- [Report](#report)+- [Completion criteria](#completion-criteria)+- [Public references](#public-references)++## Configuration layouts++Scan every layout because framework choice does not determine serialization.++Traditional and downloaded declarative sites commonly use an aggregate file:++```text+sitesetting.yml+```++```yaml+- adx_name: Webapi/<table>/fields+ adx_sitesettingid: <site-setting-id-1>+ adx_value: <column-name-1>,<column-name-2>+```++SPA sites can contain the same aggregate shape at+`.powerpages-site/sitesetting.yml`, or one file per setting:++```text+.powerpages-site/site-settings/*.sitesetting.yml+```++```yaml+id: <site-setting-id-1>+name: Webapi/<table>/fields+value: <column-name-1>,<column-name-2>+```++Modular files can use either `name` and `value` or `adx_name` and+`adx_value`. Inspect deployment-profile copies too.++## Configuration scopes++Treat each aggregate `sitesetting.yml` as its own scope. Treat modular setting+files in the same `site-settings` directory as one scope. Deployment profiles+are separate scopes even when they contain the same setting name.++For each scope:++- pair `Webapi/<table>/enabled` with `Webapi/<table>/fields`;+- identify missing, duplicate, wildcard, and already-explicit field settings;+- preserve record identifiers, key style, quoting, comments, and unrelated+ values;+- use logical table names in settings and `EntitySetName` in requests.++Table permissions and column permissions remain separate authorization+layers. Replacing `*` reduces the exposed Web API surface but does not repair+overbroad record permissions.++## Report++Write the report data, then render it. Never hand-write report HTML; the+renderer is the encoding boundary that keeps setting names, column names, and+paths as data.++Write the data file to:++```text+docs/webapi-selectall-migration/migration-report.json+```++```json+{+ "REPORT_STATUS": "Complete | Partial | Draft | Failed",+ "SCOPE_NOTE": "<one sentence naming the configuration scopes, deployment profiles, and source call sites reviewed>",+ "WILDCARD_DATA": [+ {+ "setting": "Webapi/<table>/fields",+ "status": "Pending | Migrated | Removed | Blocked",+ "usages": [+ {+ "location": "<relative path>:<line>",+ "detail": "<what this call site reads>"+ }+ ],+ "fields": [+ "<column-name-1>",+ "<column-name-2>"+ ],+ "finding": "<evidence proving this column set>",+ "fix": "<what was changed, or what is still required>"+ }+ ],+ "EXPLICIT_DATA": [+ {+ "setting": "Webapi/<table>/fields",+ "status": "Least privilege | Incomplete | Overbroad",+ "usages": [+ {+ "location": "<relative path>:<line>",+ "detail": "<what this call site reads>"+ }+ ],+ "fields": [+ "<configured-column-1>"+ ],+ "finding": "<comparison against observed usage>",+ "fix": "<proposed change, or no change required>"+ }+ ]+}+```++Both arrays are required and may be empty. One setting gets one entry, however+many call sites it has: list every call site in `usages` so the report shows the+same table read through different wrappers or pages. `status` selects the badge+tone and the counters, so use the listed values. Use `Pending` in the draft+report before replacements are proposed, and `Blocked` for a wildcard whose+replacement cannot be proven, stating in its `fix` what the user has to decide.+Use an empty `fields` array when a setting is removed or blocked.++Render with:++```bash+node "${PLUGIN_ROOT}/skills/migrate-webapi-selectall/scripts/render-migration-report.js" --output "<PROJECT_ROOT>/docs/webapi-selectall-migration/migration-report.html" --data "<PROJECT_ROOT>/docs/webapi-selectall-migration/migration-report.json"+```++The renderer refuses to overwrite, so delete the previous+`migration-report.html` before re-rendering an updated report. It stamps the+generated time itself, and also writes `power-pages-icon.png` beside the+report; leave that file in place.++Record only relative paths, line numbers, table names, and column names. Never+include absolute local paths, source snippets, request or response bodies,+tokens, environment URLs, hostnames, filter literals, record identifiers, or+user data.++## Completion criteria++The wildcard migration is complete only when:++- every configuration file and deployment scope was inspected;+- every original wildcard has an approved explicit replacement;+- every candidate source `/_api/` occurrence has a resolved disposition;+- every proposed field has source or contract evidence and schema validation;+- every normal table GET has an explicit `$select`;+- a fresh independent pass finds zero wildcard field settings;+- the report includes every wildcard and already-explicit setting;+- only `migration-report.html` remains in the migration output directory.++If explicit settings still have unresolved missing or overbroad fields, set+`REPORT_STATUS` to `Partial` rather than claiming full Web API hardening.++## Public references++- [Important upcoming changes and deprecations in Power Pages](https://learn.microsoft.com/en-us/power-pages/important-changes-deprecations#wildcard-value--in-web-api-field-configuration)+- [Portals Web API overview](https://learn.microsoft.com/en-us/power-pages/configure/web-api-overview)+- [Query data using portals Web API](https://learn.microsoft.com/en-us/power-pages/configure/read-operations)+- [Use portals Web API write, update, and delete operations](https://learn.microsoft.com/en-us/power-pages/configure/write-update-delete-operations)+- [Overview of developer capabilities](https://learn.microsoft.com/en-us/power-pages/configure/developer-overview)+- [Create a code site using AI coding agents](https://learn.microsoft.com/en-us/power-pages/configure/create-code-site-using-claude-code)+- [Power Platform CLI pages commands](https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/pages)diff --git a/plugins/power-pages/skills/migrate-webapi-selectall/references/site-transfer.md b/plugins/power-pages/skills/migrate-webapi-selectall/references/site-transfer.mdnew file mode 100644index 000000000..d8d6a2455--- /dev/null+++ b/plugins/power-pages/skills/migrate-webapi-selectall/references/site-transfer.md@@ -0,0 +1,77 @@+# Site Transfer Safety++Download and upload move Power Pages configuration between Dataverse and the+local project. Neither operation has an undo, and both can destroy+configuration that this migration never touched.++## Identity to confirm++Establish every value below and have the user confirm it. Never infer one from+a folder name, a previous session, or the active default.++| Detail | Confirm with | Needed for |+|---|---|---|+| Environment | `pac auth who`, `pac env who` | download, upload |+| Website name and `WebSiteId` | `pac pages list`, `website.yml` | download, upload |+| Site type: traditional or SPA | `powerpages.config.json` presence | download, upload |+| Data model: Standard or Enhanced | user | traditional only |+| Deployment profile | user, and profile files in the project | upload |+| Target path | user | download |++Re-confirm the whole set whenever the environment, website, or data model+changes. One approval covers one target.++## Command matrix++| Site type | Download | Upload |+|---|---|---|+| Traditional | `pac pages download` | `pac pages upload` |+| SPA | `pac pages download-code-site` | `pac pages upload-code-site` |++```bash+pac pages list --environment "<ENVIRONMENT>"++pac pages download --path "<PATH>" --webSiteId "<WEBSITE_ID>" --environment "<ENVIRONMENT>" --modelVersion "<Standard|Enhanced>"++pac pages upload --path "<PROJECT_ROOT>" --environment "<ENVIRONMENT>" --modelVersion "<Standard|Enhanced>" --deploymentProfile "<PROFILE>"++pac pages download-code-site --path "<PATH>" --webSiteId "<WEBSITE_ID>" --environment "<ENVIRONMENT>"++pac pages upload-code-site --rootPath "<PROJECT_ROOT>" --siteName "<SITE_NAME>"+```++Pass `--modelVersion` explicitly on every traditional download and upload;+`Standard` and `Enhanced` may also be written as `1` and `2`.++## Failure modes++Each of these corrupts configuration and cannot be reverted.++- **Wrong upload command.** `pac pages upload` corrupts an SPA site's+ metadata, and `pac pages upload-code-site` corrupts a traditional site. A+ project holding `powerpages.config.json` is an SPA site even when it also+ contains `.powerpages-site/` artifacts.+- **Wrong data model.** `pac pages download` uses `Standard` when+ `--modelVersion` is omitted, so an Enhanced site downloads incomplete.+ Editing that copy and uploading it overwrites live configuration.+- **Unpinned environment.** `pac pages upload-code-site` accepts no+ `--environment` and targets whatever `pac auth who` reports. Re-run+ `pac auth who` immediately before it and stop on any mismatch.+- **Wrong website.** Sites in one environment differ only by name and+ `--webSiteId`. A wrong ID downloads another site over the target path.+ Before uploading, confirm the project's `website.yml` identity still matches+ the approved site.+- **Overwritten local work.** `--overwrite` replaces existing local content.+ Never pass it while the project holds unreviewed changes.+- **Stale local copy.** Uploading configuration downloaded before another+ maker's change reverts that change. Download fresh before editing when the+ local copy's age is unknown.+- **Unintended deployment profile.** `pac pages upload` uses `default` when+ `--deploymentProfile` is omitted, which can target the wrong environment's+ values.++## Public references++- [Power Platform CLI pages commands](https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/pages)+- [Tutorial: Use Power Platform CLI with Power Pages](https://learn.microsoft.com/en-us/power-pages/configure/power-platform-cli-tutorial)+- [Use deployment profiles](https://learn.microsoft.com/en-us/power-apps/maker/portals/power-apps-cli#use-deployment-profile)diff --git a/plugins/power-pages/skills/migrate-webapi-selectall/scripts/query-table-schema.js b/plugins/power-pages/skills/migrate-webapi-selectall/scripts/query-table-schema.jsnew file mode 100644index 000000000..51dfedbca--- /dev/null+++ b/plugins/power-pages/skills/migrate-webapi-selectall/scripts/query-table-schema.js@@ -0,0 +1,444 @@+#!/usr/bin/env node+'use strict';++const fs = require('fs');+const path = require('path');+const {+ getAuthToken,+ odataGetAll,+ validateDataverseEnvironmentUrl,+} = require('../../../scripts/lib/validation-helpers');++// Refresh the token periodically so long runs never expire.+const TABLES_PER_TOKEN_REFRESH = 4;+// Retry ceilings bound transient Dataverse throttling delays safely.+const MAX_RETRY_ATTEMPTS = 6;+const BASE_RETRY_DELAY_MS = 1000;+const MAX_RETRY_DELAY_MS = 30000;++const HELP = `+Retrieves Dataverse table schema for Web API wildcard migration analysis.++Usage:+ node query-table-schema.js --project-root <path> --environment-url <url>+ (--table <name> | --tables-file <file>) --output <file>++Options:+ --project-root Power Pages project root; input and output stay inside it+ --environment-url Dataverse environment URL+ --table Logical name or entity set name; repeatable+ --tables-file File of identifiers, one per line or a JSON array+ --output JSON schema snapshot to write, inside the project root+ --help Show this help message++Exit codes:+ 0 Snapshot written; prints { output, tableCount } to stdout+ 1 Invalid arguments, unresolved table, auth failure, or query failure++Example:+ node query-table-schema.js --project-root . --environment-url https://contoso.crm.dynamics.com --table account --output docs/webapi-selectall-migration/table-schema.json+`;++function parseArgs(argv) {+ const options = { tables: [] };+ for (let index = 0; index < argv.length; index += 1) {+ const argument = argv[index];+ if (!argument.startsWith('--')) {+ throw new Error(`Unexpected argument: ${argument}`);+ }+ const value = argv[index + 1];+ if (!value || value.startsWith('--')) {+ throw new Error(`Missing value for ${argument}.`);+ }+ index += 1;+ if (argument === '--table') {+ options.tables.push(value);+ } else if (argument === '--tables-file') {+ options.tablesFile = value;+ } else if (argument === '--environment-url') {+ options.environmentUrl = value;+ } else if (argument === '--project-root') {+ options.projectRoot = value;+ } else if (argument === '--output') {+ options.output = value;+ } else {+ throw new Error(`Unknown option: ${argument}`);+ }+ }+ return options;+}++function sleep(milliseconds) {+ return new Promise(resolve => setTimeout(resolve, milliseconds));+}++function isTransientError(error) {+ return /\b(?:408|429|500|502|503|504)\b|ECONNRESET|ETIMEDOUT|socket hang up/i+ .test(String(error?.message || error));+}++async function getAllWithRetry(getAll, url, token, wait = sleep) {+ let lastError;+ for (let attempt = 0; attempt < MAX_RETRY_ATTEMPTS; attempt += 1) {+ try {+ return await getAll(url, token);+ } catch (error) {+ lastError = error;+ if (!isTransientError(error) || attempt === MAX_RETRY_ATTEMPTS - 1) {+ throw error;+ }+ await wait(Math.min(MAX_RETRY_DELAY_MS, BASE_RETRY_DELAY_MS * (2 ** attempt)));+ }+ }+ throw lastError;+}++function realPath(candidate) {+ return fs.realpathSync.native+ ? fs.realpathSync.native(candidate)+ : fs.realpathSync(candidate);+}++function resolveThroughExistingAncestor(candidate) {+ const unresolved = [];+ let current = candidate;+ while (!fs.existsSync(current)) {+ const parent = path.dirname(current);+ if (parent === current) {+ throw new Error('Unable to resolve an existing path ancestor.');+ }+ unresolved.unshift(path.basename(current));+ current = parent;+ }+ return path.resolve(realPath(current), ...unresolved);+}++function isStrictlyInside(root, candidate) {+ const relative = path.relative(root, candidate);+ return relative !== '' &&+ !relative.startsWith(`..${path.sep}`) &&+ relative !== '..' &&+ !path.isAbsolute(relative);+}++function resolveOutputPath(projectRoot, candidate) {+ // Canonical paths prevent symlink and junction escapes.+ const resolved = resolveThroughExistingAncestor(candidate);+ if (resolved === projectRoot ||+ (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory())) {+ throw new Error('Output must be a file inside the project root.');+ }+ if (!isStrictlyInside(projectRoot, resolved)) {+ throw new Error('Output must remain inside the project root.');+ }+ return resolved;+}++function metadataUrl(environmentUrl, resource, select) {+ const url = new URL(`${environmentUrl}/api/data/v9.2/${resource}`);+ url.searchParams.set('$select', select);+ return url.href;+}++function buildMetadataUrls(environmentUrl, logicalName) {+ const escaped = logicalName.replace(/'/g, "''");+ const resource = `EntityDefinitions(LogicalName='${escaped}')`;+ return {+ attributes: metadataUrl(+ environmentUrl,+ `${resource}/Attributes`,+ 'LogicalName,AttributeType,IsValidForRead,IsValidForCreate,IsValidForUpdate'+ ),+ oneToMany: metadataUrl(+ environmentUrl,+ `${resource}/OneToManyRelationships`,+ 'SchemaName,ReferencingEntity,ReferencedEntity,ReferencingAttribute,ReferencingEntityNavigationPropertyName,ReferencedEntityNavigationPropertyName'+ ),+ manyToOne: metadataUrl(+ environmentUrl,+ `${resource}/ManyToOneRelationships`,+ 'SchemaName,ReferencingEntity,ReferencedEntity,ReferencingAttribute,ReferencingEntityNavigationPropertyName,ReferencedEntityNavigationPropertyName'+ ),+ manyToMany: metadataUrl(+ environmentUrl,+ `${resource}/ManyToManyRelationships`,+ 'SchemaName,Entity1LogicalName,Entity2LogicalName,Entity1NavigationPropertyName,Entity2NavigationPropertyName'+ ),+ };+}++function booleanValue(value) {+ if (typeof value === 'boolean') return value;+ if (value && typeof value.Value === 'boolean') return value.Value;+ return null;+}++function addNavigation(output, seen, navigation) {+ if (!navigation.name || !navigation.targetLogicalName) return;+ const key = `${navigation.name}:${navigation.targetLogicalName}`;+ if (seen.has(key)) return;+ seen.add(key);+ output.push(navigation);+}++function normalizeTableMetadata(definition, attributes, relationships, manyToMany) {+ const navigationProperties = [];+ const seenNavigation = new Set();++ // Navigation names require relationship metadata for expansions.+ for (const relationship of relationships) {+ if (relationship.ReferencingEntity === definition.LogicalName) {+ addNavigation(navigationProperties, seenNavigation, {+ name: relationship.ReferencingEntityNavigationPropertyName,+ targetLogicalName: relationship.ReferencedEntity,+ lookupAttribute: relationship.ReferencingAttribute,+ relationship: relationship.SchemaName,+ });+ }+ if (relationship.ReferencedEntity === definition.LogicalName) {+ addNavigation(navigationProperties, seenNavigation, {+ name: relationship.ReferencedEntityNavigationPropertyName,+ targetLogicalName: relationship.ReferencingEntity,+ lookupAttribute: null,+ relationship: relationship.SchemaName,+ });+ }+ }++ for (const relationship of manyToMany) {+ if (relationship.Entity1LogicalName === definition.LogicalName) {+ addNavigation(navigationProperties, seenNavigation, {+ name: relationship.Entity1NavigationPropertyName,+ targetLogicalName: relationship.Entity2LogicalName,+ lookupAttribute: null,+ relationship: relationship.SchemaName,+ });+ }+ if (relationship.Entity2LogicalName === definition.LogicalName) {+ addNavigation(navigationProperties, seenNavigation, {+ name: relationship.Entity2NavigationPropertyName,+ targetLogicalName: relationship.Entity1LogicalName,+ lookupAttribute: null,+ relationship: relationship.SchemaName,+ });+ }+ }++ const normalizedAttributes = attributes+ .filter(attribute => attribute.LogicalName)+ .map(attribute => ({+ logicalName: attribute.LogicalName,+ attributeType: attribute.AttributeType || null,+ isValidForRead: booleanValue(attribute.IsValidForRead),+ isValidForCreate: booleanValue(attribute.IsValidForCreate),+ isValidForUpdate: booleanValue(attribute.IsValidForUpdate),+ }))+ .sort((left, right) => left.logicalName.localeCompare(right.logicalName));+ const lookupTypes = new Set(['Customer', 'Lookup', 'Owner']);+ const lookupReadProperties = normalizedAttributes+ .filter(attribute => lookupTypes.has(attribute.attributeType))+ .map(attribute => `_${attribute.logicalName}_value`);++ return {+ logicalName: definition.LogicalName,+ entitySetName: definition.EntitySetName,+ primaryIdAttribute: definition.PrimaryIdAttribute,+ attributes: normalizedAttributes,+ lookupReadProperties,+ navigationProperties: navigationProperties.sort((left, right) =>+ left.name.localeCompare(right.name)+ ),+ };+}++function resolveRequestedTables(definitions, requested) {+ const byIdentifier = new Map();+ for (const definition of definitions) {+ if (definition.LogicalName) {+ byIdentifier.set(definition.LogicalName.toLowerCase(), definition);+ }+ if (definition.EntitySetName) {+ byIdentifier.set(definition.EntitySetName.toLowerCase(), definition);+ }+ }+ const resolved = [];+ const missing = [];+ for (const identifier of requested) {+ const definition = byIdentifier.get(identifier.toLowerCase());+ if (!definition) {+ missing.push(identifier);+ } else if (!resolved.some(item => item.LogicalName === definition.LogicalName)) {+ resolved.push(definition);+ }+ }+ if (missing.length > 0) {+ throw new Error(`Unknown table logical names or entity sets: ${missing.join(', ')}`);+ }+ return resolved;+}++async function queryTableSchemas(environmentUrl, requested, dependencies = {}) {+ const getToken = dependencies.getAuthToken || getAuthToken;+ const getAll = dependencies.odataGetAll || odataGetAll;+ const wait = dependencies.sleep || sleep;+ let token = getToken(environmentUrl);+ if (!token) {+ throw new Error('Authentication unavailable. Run az login --allow-no-subscriptions.');+ }+ const definitions = await getAllWithRetry(+ getAll,+ metadataUrl(+ environmentUrl,+ 'EntityDefinitions',+ 'LogicalName,EntitySetName,PrimaryIdAttribute'+ ),+ token,+ wait+ );+ const selected = resolveRequestedTables(definitions, requested);+ const tables = [];+ let queried = 0;++ for (let index = 0; index < selected.length; index += 1) {+ const definition = selected[index];+ if (queried > 0 && queried % TABLES_PER_TOKEN_REFRESH === 0) {+ token = getToken(environmentUrl);+ if (!token) throw new Error('Authentication expired while querying table schemas.');+ }+ const urls = buildMetadataUrls(environmentUrl, definition.LogicalName);+ const attributes = await getAllWithRetry(getAll, urls.attributes, token, wait);+ const oneToMany = await getAllWithRetry(getAll, urls.oneToMany, token, wait);+ const manyToOne = await getAllWithRetry(getAll, urls.manyToOne, token, wait);+ const manyToMany = await getAllWithRetry(getAll, urls.manyToMany, token, wait);+ const table = normalizeTableMetadata(+ definition,+ attributes,+ [...oneToMany, ...manyToOne],+ manyToMany+ );+ tables.push(table);+ queried += 1;+ }++ return {+ schemaVersion: 1,+ generatedAt: new Date().toISOString(),+ tables: tables.sort((left, right) => left.logicalName.localeCompare(right.logicalName)),+ };+}++function validateOptions(options) {+ if (!options.environmentUrl || !options.projectRoot || !options.output) {+ throw new Error(+ 'Usage: query-table-schema.js --project-root <path> --environment-url <url> ' ++ '--table <logical-name-or-entity-set> [--table <name>] ' ++ '[--tables-file <file>] --output <file>'+ );+ }+ const requestedProjectRoot = path.resolve(options.projectRoot);+ if (!fs.existsSync(requestedProjectRoot) ||+ !fs.statSync(requestedProjectRoot).isDirectory()) {+ throw new Error('Project root must be an existing directory.');+ }+ const projectRoot = realPath(requestedProjectRoot);+ const output = resolveOutputPath(projectRoot, path.resolve(options.output));+ let tablesFile = null;+ if (options.tablesFile) {+ const requestedTablesFile = path.resolve(options.tablesFile);+ if (!fs.existsSync(requestedTablesFile)) {+ throw new Error('Tables file must exist inside the project root.');+ }+ tablesFile = realPath(requestedTablesFile);+ if (!isStrictlyInside(projectRoot, tablesFile) ||+ !fs.statSync(tablesFile).isFile()) {+ throw new Error('Tables file must exist inside the project root.');+ }+ }+ return {+ environmentUrl: validateDataverseEnvironmentUrl(options.environmentUrl),+ projectRoot,+ output,+ tables: options.tables,+ tablesFile,+ };+}++function loadTableIdentifiers(options) {+ const values = [...options.tables];+ if (options.tablesFile) {+ const content = fs.readFileSync(options.tablesFile, 'utf8').trim();+ if (content.startsWith('[')) {+ const parsed = JSON.parse(content);+ if (!Array.isArray(parsed)) {+ throw new Error('Tables file JSON must contain an array.');+ }+ for (const value of parsed) values.push(value);+ } else if (content) {+ values.push(...content.split(/\r?\n/));+ }+ }+ const normalized = [...new Set(values.map(value => String(value).trim().toLowerCase())+ .filter(Boolean))];+ if (normalized.length === 0) {+ throw new Error('At least one table identifier is required.');+ }+ for (const table of normalized) {+ if (!/^[a-z_][a-z0-9_]*$/.test(table)) {+ throw new Error(`Invalid table identifier: ${table}`);+ }+ }+ return normalized;+}++function writeAtomicJson(projectRoot, filePath, value) {+ const output = resolveOutputPath(projectRoot, filePath);+ fs.mkdirSync(path.dirname(output), { recursive: true });+ const temporary = `${output}.${process.pid}.tmp`;+ try {+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');+ fs.renameSync(temporary, output);+ } catch (error) {+ // Never strand a partial .tmp file behind.+ fs.rmSync(temporary, { force: true });+ throw error;+ }+}++async function main() {+ if (process.argv.includes('--help')) {+ process.stdout.write(HELP);+ return;+ }++ let validated;+ try {+ validated = validateOptions(parseArgs(process.argv.slice(2)));+ const tables = loadTableIdentifiers(validated);+ const result = await queryTableSchemas(validated.environmentUrl, tables);+ writeAtomicJson(validated.projectRoot, validated.output, result);+ process.stdout.write(`${JSON.stringify({+ output: path.relative(validated.projectRoot, validated.output).split(path.sep).join('/'),+ tableCount: result.tables.length,+ })}\n`);+ } catch (error) {+ const message = validated?.environmentUrl+ ? error.message.replaceAll(validated.environmentUrl, '<environment>')+ : error.message;+ process.stderr.write(`${message}\n`);+ process.exitCode = 1;+ }+}++if (require.main === module) {+ main();+}++module.exports = {+ buildMetadataUrls,+ normalizeTableMetadata,+ parseArgs,+ queryTableSchemas,+ resolveRequestedTables,+ loadTableIdentifiers,+ validateOptions,+};diff --git a/plugins/power-pages/skills/migrate-webapi-selectall/scripts/render-migration-report.js b/plugins/power-pages/skills/migrate-webapi-selectall/scripts/render-migration-report.jsnew file mode 100644index 000000000..eb4b01d5d--- /dev/null+++ b/plugins/power-pages/skills/migrate-webapi-selectall/scripts/render-migration-report.js@@ -0,0 +1,76 @@+#!/usr/bin/env node+'use strict';++const fs = require('fs');+const path = require('path');+const { renderTemplate, parseArgs } = require('../../../scripts/lib/render-template');++const HELP = `+Renders the Web API wildcard migration report from a data file.++Usage:+ node render-migration-report.js --output <path> --data <json-file>++Options:+ --output HTML report to write; must not already exist+ --data JSON data file describing the migration+ --help Show this help message++Required keys in the data file:+ REPORT_STATUS, SCOPE_NOTE, WILDCARD_DATA, EXPLICIT_DATA++WILDCARD_DATA and EXPLICIT_DATA are arrays of:+ { setting, status, usages: [{ location, detail }], fields, finding, fix }++Exit codes:+ 0 Report written+ 1 Missing flag, unreadable data file, missing key, or existing output++Example:+ node render-migration-report.js --output docs/webapi-selectall-migration/migration-report.html --data docs/webapi-selectall-migration/migration-report.json+`;++// UTC keeps the stamp unambiguous across reader regions.+// dateStyle and timeStyle cannot combine with timeZoneName.+function formatGeneratedAt(now) {+ return new Intl.DateTimeFormat('en-US', {+ year: 'numeric',+ month: 'long',+ day: 'numeric',+ hour: 'numeric',+ minute: '2-digit',+ timeZone: 'UTC',+ timeZoneName: 'short',+ }).format(now);+}++function main() {+ if (process.argv.includes('--help')) {+ process.stdout.write(HELP);+ return;+ }++ const args = parseArgs(process.argv);+ if (!args.output || !args.data) {+ process.stderr.write('Usage: node render-migration-report.js --output <path> --data <json-file>\n');+ process.exit(1);+ }++ let data;+ try {+ data = JSON.parse(fs.readFileSync(path.resolve(args.data), 'utf8'));+ } catch (error) {+ process.stderr.write(`Could not read data file ${args.data}: ${error.message}\n`);+ process.exit(1);+ }++ renderTemplate({+ templatePath: path.join(__dirname, '..', 'assets', 'migration-report-template.html'),+ outputPath: path.resolve(args.output),+ // Renderer owns the stamp reflecting render time.+ dataObject: { ...data, GENERATED_AT: formatGeneratedAt(new Date()) },+ requiredKeys: ['REPORT_STATUS', 'SCOPE_NOTE', 'WILDCARD_DATA', 'EXPLICIT_DATA'],+ });+}++main();