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
fix(power-pages): correct server logic runtime guidance (#873)
Priyanshu Agrawal2277dab94216
diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonindex 60cc79b91..1f2d74329 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": "3.1.0",+ "version": "3.1.1","description": "Create and deploy Power Pages sites using modern development approaches. Supports Enhanced-model non-SPA sites using Liquid and Web Templates, plus SPA sites with React, Angular, Vue, or Astro. Adds multilingual localization and safe runtime LTR/RTL switching for React, Vue, and Angular runtime sites; Astro and Angular static localization are temporarily unavailable. 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 60cc79b91..1f2d74329 100644--- a/plugins/power-pages/.plugin/plugin.json+++ b/plugins/power-pages/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "3.1.0",+ "version": "3.1.1","description": "Create and deploy Power Pages sites using modern development approaches. Supports Enhanced-model non-SPA sites using Liquid and Web Templates, plus SPA sites with React, Angular, Vue, or Astro. Adds multilingual localization and safe runtime LTR/RTL switching for React, Vue, and Angular runtime sites; Astro and Angular static localization are temporarily unavailable. 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/scripts/tests/validate-serverlogic.test.js b/plugins/power-pages/scripts/tests/validate-serverlogic.test.jsindex ee0046e2a..33f7969ed 100644--- a/plugins/power-pages/scripts/tests/validate-serverlogic.test.js+++ b/plugins/power-pages/scripts/tests/validate-serverlogic.test.js@@ -3,6 +3,7 @@ const assert = require('node:assert/strict');const fs = require('fs');const path = require('path');const { spawnSync } = require('child_process');+const vm = require('node:vm');const { createTempProject, writeProjectFile } = require('./test-utils');@@ -267,3 +268,280 @@ test('split startswith( workaround passes validation', (t) => {const result = runValidator(projectRoot);assert.equal(result.status, 0, result.stderr);});++test('with-pattern rejects mixed-case substrings in raw source', (t) => {+ const projectRoot = createTempProject(t);+ setupProject(projectRoot);+ writeServerLogic(projectRoot, 'test-endpoint', VALID_JS.replace(+ '"test-endpoint GET called"', '"STARTSWITH(name)"'+ ), VALID_YML);+ const result = runValidator(projectRoot);+ assert.equal(result.status, 2);+ assert.match(result.stderr, /contains the substring 'with\('/);+});++test('runtime function pattern is rejected in callbacks and raw non-code text', (t) => {+ for (const source of [+ 'const rows = [1].map(function (r) { return r; });',+ 'const rows = [1].sort(function(a, b) { return a - b; });',+ 'const callback = function\n(r) { return r; };',+ 'const factory = Function ("return 1");',+ 'const text = "FUNCTION(";',+ '// callback: function (r)',+ 'const text = "myFunction(";',+ ]) {+ const projectRoot = createTempProject(t);+ setupProject(projectRoot);+ writeServerLogic(projectRoot, 'test-endpoint', VALID_JS.replace(+ ' return JSON.stringify',+ ` ${source}\n return JSON.stringify`+ ), VALID_YML);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 2, source);+ assert.match(result.stderr, /prohibited pattern.*Function\\s\*\\\(/);+ assert.match(result.stderr, /line\(s\) 4/);+ assert.match(result.stderr, /arrow functions/);+ }+});++test('arrow callbacks and named nested helpers pass validation', (t) => {+ const projectRoot = createTempProject(t);+ setupProject(projectRoot);+ writeServerLogic(projectRoot, 'test-endpoint', VALID_JS.replace(+ ' return JSON.stringify',+ ' function double(r) { return r * 2; }\n' ++ ' const rows = [2, 1].map(r => double(r)).sort((a, b) => a - b);\n' ++ ' return JSON.stringify'+ ), VALID_YML);+ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+});++const SKILL_DIR = path.join(__dirname, '../../skills/add-server-logic');+const frontendReference = fs.readFileSync(path.join(+ SKILL_DIR, 'references/frontend-integration-reference.md'+), 'utf8');+const skill = fs.readFileSync(path.join(SKILL_DIR, 'SKILL.md'), 'utf8');++function exampleAfter(document, heading) {+ const start = document.indexOf(heading);+ assert.notEqual(start, -1, `Missing heading: ${heading}`);+ // Git can check Markdown out with CRLF on Windows; accept either newline at both fences.+ const example = document.slice(start).match(/```javascript\r?\n([\s\S]*?)\r?\n```/);+ assert.ok(example, `Missing example: ${heading}`);+ return example[1];+}++function runExample(source, method, dataverse, context = {}) {+ const errors = [];+ const sandbox = {+ Server: {+ Context: context,+ Connector: { Dataverse: dataverse },+ Logger: { Log() {}, Error(message) { errors.push(message); } },+ },+ };+ vm.createContext(sandbox);+ vm.runInContext(source, sandbox);+ const payload = JSON.parse(vm.runInContext(`${method}()`, sandbox));+ return { payload, errors };+}++// The connector returns serialized HTTP metadata, with another JSON string in Body:+// '{"StatusCode":200,"Body":"{\"value\":[...]}","Headers":{...}}'+// Writes can have an empty Body; malformed read bodies must reach the handler's catch.+function connectorResponse(status, body, headers = {}) {+ return JSON.stringify({+ StatusCode: status,+ Body: body,+ IsSuccessStatusCode: status >= 200 && status < 300,+ Headers: headers,+ });+}++test('documentation examples execute with LF and CRLF line endings', () => {+ for (const newline of ['\n', '\r\n']) {+ const document = frontendReference.replace(/\r\n/g, '\n').replace(/\n/g, newline);+ const source = exampleAfter(document, '**Approach C');+ const { payload, errors } = runExample(source, 'get', {+ RetrieveMultipleRecords: () => connectorResponse(200, '{"value":[]}'),+ });+ assert.equal(payload.status, 'success');+ assert.deepEqual(payload.contacts, []);+ assert.deepEqual(errors, []);+ }+});++test('normalized read example returns rows from a serialized connector response', () => {+ const source = exampleAfter(frontendReference, '**Approach C');+ const { payload, errors } = runExample(source, 'get', {+ RetrieveMultipleRecords: (entitySet, options) => {+ assert.equal(entitySet, 'contacts');+ assert.equal(options, '$select=contactid,firstname,lastname,emailaddress1,telephone1');+ return connectorResponse(200, JSON.stringify({+ value: [+ { contactid: '1', firstname: 'Alex' },+ { contactid: '2', firstname: 'Sam' },+ { contactid: '3', firstname: 'Taylor' },+ ],+ }));+ },+ });+ assert.equal(payload.status, 'success');+ assert.deepEqual(payload.contacts.map(row => row.id), ['1', '2', '3']);+ assert.deepEqual(errors, []);+});++test('normalized read example logs HTTP and malformed payload failures', () => {+ const source = exampleAfter(frontendReference, '**Approach C');+ for (const response of [+ connectorResponse(403, '{"error":{"message":"Forbidden"}}'),+ connectorResponse(200, 'not-json'),+ connectorResponse(200, ''),+ connectorResponse(200, '{}'),+ 'not-json',+ ]) {+ const { payload, errors } = runExample(source, 'get', {+ RetrieveMultipleRecords: () => response,+ });+ assert.equal(payload.status, 'error', response);+ assert.equal(errors.length, 1, response);+ }+});++test('create example extracts a GUID from the connector header without parsing an empty body', () => {+ const source = exampleAfter(frontendReference, 'For writes, return the new id');+ const id = '11111111-2222-3333-4444-555555555555';+ for (const headerName of ['OData-EntityId', 'odata-entityid']) {+ const { payload, errors } = runExample(source, 'post', {+ CreateRecord: () => connectorResponse(204, '', {+ [headerName]: `https://contoso.crm.dynamics.com/api/data/v9.2/contacts(${id})`,+ }),+ }, { Body: '{"firstname":"Alex"}' });+ assert.equal(payload.status, 'success');+ assert.equal(payload.id, id);+ assert.deepEqual(errors, []);+ }+});++test('create example logs failed writes and missing or malformed record URLs', () => {+ const source = exampleAfter(frontendReference, 'For writes, return the new id');+ for (const response of [+ connectorResponse(403, ''),+ connectorResponse(204, ''),+ connectorResponse(204, '', { 'OData-EntityId': 'contacts(not-a-guid)' }),+ ]) {+ const { payload, errors } = runExample(source, 'post', {+ CreateRecord: () => response,+ }, { Body: '{"firstname":"Alex"}' });+ assert.equal(payload.status, 'error', response);+ assert.equal(errors.length, 1, response);+ }+});++test('validate-and-execute example reads the record body before checking a transition', () => {+ const source = exampleAfter(skill, '#### Validate-and-Execute Template');+ for (const updateStatus of [204, 403]) {+ const writes = [];+ const { payload, errors } = runExample(source, 'post', {+ RetrieveRecord: (table, id, options) => {+ assert.equal(table, '<table-name>');+ assert.equal(id, 'record-id');+ assert.equal(options, '$select=<status-field>');+ return connectorResponse(200, '{"<status-field>":"Draft"}');+ },+ UpdateRecord: (table, id, body) => {+ writes.push({ table, id, body: JSON.parse(body) });+ return connectorResponse(updateStatus, '');+ },+ }, { Body: '{"entityId":"record-id","targetStatus":"Submitted"}' });+ assert.deepEqual(writes, [{+ table: '<table-name>', id: 'record-id', body: { '<status-field>': 'Submitted' },+ }]);+ assert.equal(payload.status, updateStatus === 204 ? 'success' : 'error');+ assert.equal(errors.length, updateStatus === 204 ? 0 : 1);+ }+});++test('wrapped passthrough server and client examples preserve and parse the connector string', async () => {+ const section = frontendReference.slice(frontendReference.indexOf('**Approach B'));+ const server = exampleAfter(section, 'Server logic:');+ const client = exampleAfter(section, 'Client -');+ for (const status of [200, 403]) {+ const { payload, errors } = runExample(server, 'get', {+ RetrieveMultipleRecords: () => connectorResponse(status, '{"value":[{"contactid":"1"}]}'),+ }, { QueryParameters: { entitySetName: 'contacts' } });+ const result = vm.runInNewContext(`(async () => { ${client}\nreturn records; })()`, {+ powerPagesFetch: async () => ({ success: true, data: JSON.stringify(payload) }),+ });+ if (status === 200) {+ assert.equal(typeof payload.data, 'string');+ assert.deepEqual(JSON.parse(JSON.stringify(await result)), [{ contactid: '1' }]);+ assert.deepEqual(errors, []);+ } else {+ await assert.rejects(result, /Dataverse read failed/);+ assert.equal(errors.length, 1);+ }+ }+});++test('custom API templates parse connector status before reporting success', () => {+ const section = skill.slice(skill.indexOf('#### Custom Action Wrapping Template'));+ for (const [heading, method] of [+ ['**Unbound action:', 'post'],+ ['**Entity-bound action:', 'post'],+ ['**Unbound function (read-only, GET):', 'get'],+ ]) {+ const source = exampleAfter(section, heading);+ for (const status of [204, 403]) {+ const response = connectorResponse(status, '');+ const { payload, errors } = runExample(source, method, {+ InvokeCustomApi: () => response,+ }, { Body: '{"entityId":"record-id"}', QueryParameters: { param1: 'value' } });+ assert.equal(payload.status, status === 204 ? 'success' : 'error');+ if (status === 204) assert.equal(payload.data, response);+ assert.equal(errors.length, status === 204 ? 0 : 1);+ }+ }+});++test('server-side guidance examples pass the local validator', (t) => {+ const customSection = skill.slice(skill.indexOf('#### Custom Action Wrapping Template'));+ for (const source of [+ exampleAfter(frontendReference, '**Approach A'),+ exampleAfter(frontendReference, '**Approach B'),+ exampleAfter(frontendReference, '**Approach C'),+ exampleAfter(frontendReference, 'For writes, return the new id'),+ exampleAfter(skill, '#### Validate-and-Execute Template'),+ exampleAfter(customSection, '**Unbound action:'),+ exampleAfter(customSection, '**Entity-bound action:'),+ exampleAfter(customSection, '**Unbound function (read-only, GET):'),+ ]) {+ const projectRoot = createTempProject(t);+ setupProject(projectRoot);+ writeServerLogic(projectRoot, 'test-endpoint', source, VALID_YML);+ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ }+});++test('troubleshooting example captures inline logs or a trace identifier', async () => {+ const source = exampleAfter(skill, 'If `browser_network_requests`');+ for (const responseHeaders of [+ { 'x-ms-user-trace': Buffer.from('{"logs":[]}').toString('base64') },+ { 'x-ms-user-trace-id': 'example-trace-id' },+ {},+ ]) {+ const result = await vm.runInNewContext(`(async () => { ${source} })()`, {+ fetch: async () => ({+ status: 400,+ headers: new Headers(responseHeaders),+ text: async () => '{"success":false}',+ }),+ });+ assert.equal(result.status, 400);+ assert.equal(result.trace, responseHeaders['x-ms-user-trace'] ?? null);+ assert.equal(result.traceId, responseHeaders['x-ms-user-trace-id'] ?? null);+ }+});diff --git a/plugins/power-pages/skills/add-server-logic/SKILL.md b/plugins/power-pages/skills/add-server-logic/SKILL.mdindex 3bed6651a..842c0ac86 100644--- a/plugins/power-pages/skills/add-server-logic/SKILL.md+++ b/plugins/power-pages/skills/add-server-logic/SKILL.md@@ -468,6 +468,7 @@ Repeat this step for each approved server logic item. Create or update `<PROJECT5. **No imports or requires**: No `import`, `require`, or external dependencies.6. **No browser APIs**: No `fetch`, `XMLHttpRequest`, `setTimeout`, `setInterval`, `console.log`, or DOM APIs.7. **Async when needed**: Mark functions as `async` only when they use `await` (HttpClient calls). Dataverse connector methods (`Server.Connector.Dataverse.*`) are **synchronous** — do NOT use `async`/`await` with them.+8. **Callbacks**: Use arrow functions (`rows.map(r => r.id)`, `rows.sort((a, b) => a.rank - b.rank)`) or named helpers nested inside a handler.#### Prohibited Script Patterns@@ -475,7 +476,11 @@ The Power Pages server-side script validator rejects scripts containing certain| Pattern | Regex | Caveat ||---------|-------|--------|-| JavaScript `with` statement | `with\s*\(` | The regex matches the substring `with(` **anywhere** in the file — including inside string literals and inside other identifiers. OData filter functions like `startswith(`, `endswith(`, and `groupwith(` will trip it because they end with `with(`. |+| JavaScript `with` statement | `with\s*\(` (case-insensitive) | The regex matches the substring `with(` **anywhere** in the file — including inside string literals and inside other identifiers. OData filter functions like `startswith(`, `endswith(`, and `groupwith(` will trip it because they end with `with(`. |+| Anonymous functions and `Function` constructor | `Function\s*\(` (case-insensitive) | The runtime scans raw source, including comments, strings, and longer identifiers. Anonymous callbacks such as `.map(function (r) { ... })` are rejected. Use arrow callbacks or named nested helpers; top-level `function get()` remains valid. |++These restrictions apply to server logic `.js` files, not frontend JavaScript.+The local validator mirrors these runtime checks ([#870](https://github.com/microsoft/power-platform-skills/issues/870)).**Workaround for OData functions** — split the literal so `with(` is not contiguous in source:@@ -542,7 +547,11 @@ function post() {const targetStatus = body.targetStatus;// 1. Read the current record from Dataverse- const current = Server.Connector.Dataverse.RetrieveRecord("<table-name>", entityId, "?$select=<status-field>");+ const readResponse = JSON.parse(Server.Connector.Dataverse.RetrieveRecord("<table-name>", entityId, "$select=<status-field>"));+ if (readResponse.IsSuccessStatusCode === false || !(readResponse.StatusCode >= 200 && readResponse.StatusCode < 300)) {+ throw new Error("Dataverse read failed: " + readResponse.StatusCode);+ }+ const current = JSON.parse(readResponse.Body);const currentStatus = current["<status-field>"];// 2. Validate the transition@@ -566,7 +575,10 @@ function post() {// 3. Execute the write — server performs the Dataverse updateconst updateData = {};updateData["<status-field>"] = targetStatus;- Server.Connector.Dataverse.UpdateRecord("<table-name>", entityId, JSON.stringify(updateData));+ const writeResponse = JSON.parse(Server.Connector.Dataverse.UpdateRecord("<table-name>", entityId, JSON.stringify(updateData)));+ if (writeResponse.IsSuccessStatusCode === false || !(writeResponse.StatusCode >= 200 && writeResponse.StatusCode < 300)) {+ throw new Error("Dataverse update failed: " + writeResponse.StatusCode);+ }Server.Logger.Log("<name> transition executed: " + currentStatus + " → " + targetStatus);@@ -623,6 +635,10 @@ function post() {payload);+ const response = JSON.parse(result);+ if (response.IsSuccessStatusCode === false || !(response.StatusCode >= 200 && response.StatusCode < 300)) {+ throw new Error("Dataverse custom action failed: " + response.StatusCode);+ }Server.Logger.Log("<name> custom action completed successfully");return JSON.stringify({@@ -660,6 +676,10 @@ function post() {payload);+ const response = JSON.parse(result);+ if (response.IsSuccessStatusCode === false || !(response.StatusCode >= 200 && response.StatusCode < 300)) {+ throw new Error("Dataverse bound action failed: " + response.StatusCode);+ }Server.Logger.Log("<name> bound action completed for entity " + entityId);return JSON.stringify({@@ -694,6 +714,10 @@ function get() {null);+ const response = JSON.parse(result);+ if (response.IsSuccessStatusCode === false || !(response.StatusCode >= 200 && response.StatusCode < 300)) {+ throw new Error("Dataverse custom function failed: " + response.StatusCode);+ }Server.Logger.Log("<name> custom function completed successfully");return JSON.stringify({@@ -721,9 +745,18 @@ function get() {#### Dataverse Response Shape (Critical for Frontend Integration)-When a function returns the result of a `Server.Connector.Dataverse.*` method, the client sees a double-wrapped payload — the most common cause of broken frontend integrations. Before writing the function, pick one of three response shapes and record the choice for Phase 9: **Approach A — raw passthrough** (return the connector result as-is), **Approach B — envelope that wraps the connector result** (return `{ status, data: result }` without unwrapping `Body`), or **Approach C — fully normalized** (parse `Body` server-side and return a feature-specific shape — recommended for non-generic endpoints).+`Server.Connector.Dataverse.*` returns a JSON string.+Parse the connector result with `JSON.parse(result)` before accessing `StatusCode`, `Body`, or `Headers`; `Body` is another JSON string.+Check the connector status before reporting success.+Parse read bodies explicitly; an empty or malformed read body is an error, not an empty record set.+Successful writes can have an empty body, so do not parse it unless the operation returns a payload.+Pass read query options without a leading `?` (for example, `"$select=contactid,firstname"`); the connector inserts the query separator.++Before writing the function, pick a response shape and record it for Phase 9: **Approach A - raw passthrough** (return the connector string unchanged), **Approach B - wrapped passthrough** (return `{ status, data: result }`, where `data` remains a string), or **Approach C - normalized** (parse the connector result and its `Body` server-side, then return a feature-specific shape).+Prefer Approach C for feature endpoints.-See `${PLUGIN_ROOT}/skills/add-server-logic/references/frontend-integration-reference.md` → "Dataverse Connector Response Format" for the double-wrapping explanation, the `CreateRecord` / `entityid` header behavior, and server- and client-side examples for each shape.+Read `${PLUGIN_ROOT}/skills/add-server-logic/references/frontend-integration-reference.md` -> "Dataverse Connector Response Format" before implementing Dataverse reads or writes.+It contains server/client parsing examples and explains how to extract a GUID from the `CreateRecord` connector's `OData-EntityId` URL.#### Referencing Secrets in Code@@ -781,6 +814,8 @@ Before saving, verify the code against these constraints:| No external dependencies | No `import`, `require`, `module.exports` || No browser APIs | No `fetch`, `XMLHttpRequest`, `setTimeout`, `console.log`, `document`, `window` || Async only when needed | Only functions using `await` are marked `async` |+| Runtime patterns | Apply the raw-source checks in "Prohibited Script Patterns" |+| Dataverse results | Apply the parsing and status checks in "Dataverse Response Shape" || ECMAScript 2023 compliant | Standard JS features only (optional chaining, nullish coalescing, etc. are fine) |### 5.6 Git Commit@@ -1202,7 +1237,7 @@ Provide testing instructions:Use the frontend integration reference from Phase 9 for the exact calling pattern that matches the site's stack.5. **Check diagnostics** — Server.Logger output can be viewed in Power Pages design studio diagnostics-6. **If the endpoint returns an error or unexpected response** — see [Troubleshooting Server Logic Execution Errors](#troubleshooting-server-logic-execution-errors) for the Playwright + `X-Ms-UserTrace` debugging flow+6. **If the endpoint returns an error or unexpected response** - see [Troubleshooting Server Logic Execution Errors](#troubleshooting-server-logic-execution-errors) for the Playwright and `x-ms-user-trace` debugging flow**Output**: Code validated, API URL provided, test guidance given@@ -1297,7 +1332,9 @@ After deployment (or if skipped), remind the user:## Troubleshooting Server Logic Execution Errors-When a deployed server logic endpoint returns an error or unexpected response, the underlying cause is usually hidden inside the `X-Ms-UserTrace` response header — a base64-encoded blob containing the runtime diagnostic logs. The Power Pages Edge browser extension shows the same data, but inspecting the response header is the fastest path when iterating against a live site.+When a deployed server logic endpoint returns an error or unexpected response, inspect the `x-ms-user-trace` response header, which contains base64-encoded JSON diagnostic logs when the payload fits inline.+Larger traces use `x-ms-user-trace-id` instead; that value is an identifier, not base64-encoded logs.+The Power Pages Edge browser extension shows the same data.Use this flow whenever a server logic call fails or returns a different response than expected:@@ -1315,21 +1352,27 @@ Use `mcp__plugin_power-pages_playwright__browser_network_requests` to list netwo- The HTTP status code (e.g., 200, 400, 500)- The response body (often a generic error or empty payload when validation fails)-- **Most importantly: the `X-Ms-UserTrace` response header** — this is where the actual diagnostic logs live+- The `x-ms-user-trace` header (inline logs) or `x-ms-user-trace-id` header (a reference to a larger trace)If `browser_network_requests` does not surface the response headers directly, fall back to `mcp__plugin_power-pages_playwright__browser_evaluate` and read the headers from a `fetch()` call:```javascriptconst res = await fetch('/_api/serverlogics/<name>', { method: 'GET', credentials: 'include' });-const trace = res.headers.get('X-Ms-UserTrace');-return { status: res.status, body: await res.text(), trace };+const trace = res.headers.get('x-ms-user-trace');+const traceId = res.headers.get('x-ms-user-trace-id');+return { status: res.status, body: await res.text(), trace, traceId };```-### 3. Decode the `X-Ms-UserTrace` Header+### 3. Inspect the trace-The header value is base64-encoded JSON. Decode it.+Decode `x-ms-user-trace` as base64-encoded JSON when present.+If only `x-ms-user-trace-id` is present, use the Power Pages browser extension to inspect the trace; do not attempt to decode the identifier as logs.+If neither header is present, report that response diagnostics are unavailable rather than treating the absence as success.-The decoded payload contains the diagnostic log entries — including the actual error message, the prohibited pattern (if script validation failed).+The decoded payload contains diagnostic log entries, including the prohibited pattern if script validation failed.+For HTTP 200 responses with missing rows, log the connector result's type, parsed `StatusCode`, and record count.+Confirm both JSON layers were parsed before investigating table permissions.+Avoid logging record contents or secrets.After fixing, redeploy via `/deploy-site` and restart the site so the change is picked up immediately.@@ -1359,7 +1402,10 @@ After fixing, redeploy via `/deploy-site` and restart the site so the change is### SDK Pattern Source of Truth-Do not treat this skill file as the canonical SDK reference. The Phase 3 Microsoft Learn fetch is the source of truth for SDK usage patterns, supported methods, signatures, and connector behavior. Keep only task-specific decisions in the plan and implementation notes.+Use the Phase 3 Microsoft Learn fetch for SDK methods and signatures.+Apply the runtime constraints and response-shape corrections in Phase 5.3 even when a fetched sample omits them.+If the deployed runtime differs, inspect its diagnostic headers and connector result type before changing the integration.+Keep task-specific decisions in the plan and implementation notes.### Progress Trackingdiff --git a/plugins/power-pages/skills/add-server-logic/references/frontend-integration-reference.md b/plugins/power-pages/skills/add-server-logic/references/frontend-integration-reference.mdindex 6a8c3f168..1ce5394fa 100644--- a/plugins/power-pages/skills/add-server-logic/references/frontend-integration-reference.md+++ b/plugins/power-pages/skills/add-server-logic/references/frontend-integration-reference.md@@ -53,7 +53,12 @@ Reference: [Microsoft Learn — How to interact with Dataverse tables using serv### Shape of `Server.Connector.Dataverse.*` return values-The Dataverse connector methods (`RetrieveRecord`, `RetrieveMultipleRecords`, `CreateRecord`, `UpdateRecord`, `DeleteRecord`, `InvokeCustomApi`) return an object that contains the raw Dataverse HTTP response. When that object is returned from the server logic function, it is serialized into the envelope's `data` string. Concretely the client sees:+The Dataverse connector methods (`RetrieveRecord`, `RetrieveMultipleRecords`, `CreateRecord`, `UpdateRecord`, `DeleteRecord`, `InvokeCustomApi`) return a JSON string containing `StatusCode`, `Body`, and `Headers`.+`Body` is itself a JSON string for reads and can be empty for successful writes.+These methods are synchronous.+Parse the connector string before reading any properties; accessing `result.Body` on the unparsed string gives `undefined`.+Pass read query options without a leading `?`; the connector inserts that separator.+When the handler returns the connector string unchanged, the client sees:```json{@@ -74,7 +79,13 @@ const body = JSON.parse(outer.Body); // { "@odata.context": "...", value:const records = body.value; // the actual array```-For `RetrieveRecord`, `body` is the single record object (no `value` array). For `CreateRecord`, the new record's GUID is returned in the HTTP response header `entityid` — read it with `xhr.getResponseHeader('entityid')` (jQuery/safeAjax) or `response.headers.get('entityid')` (fetch).+For `RetrieveRecord`, `body` is the single record object (no `value` array).+For `CreateRecord`, the connector's `Headers["OData-EntityId"]` contains a full record URL, such as `https://contoso.crm.dynamics.com/api/data/v9.2/contacts(<guid>)`.+Extract the GUID in the final parentheses before passing it to `UpdateRecord` or `DeleteRecord`.+Header names are case-insensitive.+The Learn passthrough sample reads an outer HTTP `entityid` header; do not confuse that with the connector metadata inside `envelope.data`.+Prefer returning the parsed GUID explicitly, as shown in Approach C, rather than assuming the outer response forwards that header.+See [Dataverse create responses](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-entity-web-api).### Three approaches — pick one and apply it consistently@@ -104,7 +115,7 @@ function get() {}```-Client (matches the Microsoft Learn sample exactly):+Client:```javascriptajaxCall('Loading...', {@@ -112,22 +123,18 @@ ajaxCall('Loading...', {url: '/_api/serverlogics/dataverse-crud-operations?entitySetName=contacts&additionalParameters=$select=fullname,firstname,lastname,emailaddress1,telephone1',contentType: 'application/json'}).done(res => {+ if (!res.success) throw new Error(res.error || 'Server logic call failed');const outer = JSON.parse(res.data);+ if (outer.IsSuccessStatusCode === false || !(outer.StatusCode >= 200 && outer.StatusCode < 300)) {+ throw new Error('Dataverse read failed: ' + outer.StatusCode);+ }const body = JSON.parse(outer.Body);- const rows = (body.value || []).map(r => ({ ...r, id: r.contactid }));+ if (!Array.isArray(body.value)) throw new Error('Dataverse read returned no value array');+ const rows = body.value.map(r => ({ ...r, id: r.contactid }));render(rows);});```-For `CreateRecord` the new id comes from a response header:--```javascript-success: (res, status, xhr) => {- record.id = xhr.getResponseHeader('entityid');- addRecord(record);-}-```-**Approach B — Server envelope that still wraps the connector result**Use this when you want to add a stable top-level wrapper (e.g. `{ status, data }`) to every response but keep the raw connector result inside so generic handling code can read `Body`/`StatusCode`/`Headers` if needed.@@ -140,6 +147,10 @@ function get() {Server.Logger.Log("GET called");const entitySetName = Server.Context.QueryParameters["entitySetName"];const result = Server.Connector.Dataverse.RetrieveMultipleRecords(entitySetName);+ const response = JSON.parse(result);+ if (response.IsSuccessStatusCode === false || !(response.StatusCode >= 200 && response.StatusCode < 300)) {+ throw new Error("Dataverse read failed: " + response.StatusCode);+ }return JSON.stringify({ status: "success", data: result });} catch (err) {Server.Logger.Error("GET failed: " + err.message);@@ -148,19 +159,24 @@ function get() {}```-Client — note the extra `data` layer before reaching `Body`:+Client - parse the extra `data` string before reaching `Body`:-```typescript-const envelope = await powerPagesFetch<{ data: string | null; success: boolean; error: string | null }>(+```javascript+const envelope = await powerPagesFetch('/_api/serverlogics/contacts-crud',{ method: 'GET' });if (!envelope) throw new Error('Empty response from contacts-crud');if (!envelope.success) throw new Error(envelope.error ?? 'Failed');if (envelope.data == null) throw new Error('Missing response data from contacts-crud');-const payload = JSON.parse(envelope.data) as { status: string; data: { Body: string; StatusCode: number; Headers: Record<string, string> } };-const outer = payload.data; // connector result still wrapped here+const payload = JSON.parse(envelope.data); // { status: string, data: "<connector JSON string>" }+if (payload.status !== 'success') throw new Error(payload.message || 'Dataverse read failed');+const outer = JSON.parse(payload.data); // connector metadata+if (outer.IsSuccessStatusCode === false || !(outer.StatusCode >= 200 && outer.StatusCode < 300)) {+ throw new Error('Dataverse read failed: ' + outer.StatusCode);+}const body = JSON.parse(outer.Body); // { "@odata.context": "...", value: [...] }+if (!Array.isArray(body.value)) throw new Error('Dataverse read returned no value array');const records = body.value;```@@ -176,12 +192,16 @@ Server logic:function get() {try {Server.Logger.Log("getContacts GET called");- const dvResponse = Server.Connector.Dataverse.RetrieveMultipleRecords(+ const dvResponse = JSON.parse(Server.Connector.Dataverse.RetrieveMultipleRecords("contacts",- "?$select=contactid,firstname,lastname,emailaddress1,telephone1"- );+ "$select=contactid,firstname,lastname,emailaddress1,telephone1"+ ));+ if (dvResponse.IsSuccessStatusCode === false || !(dvResponse.StatusCode >= 200 && dvResponse.StatusCode < 300)) {+ throw new Error("Dataverse read failed: " + dvResponse.StatusCode);+ }const body = JSON.parse(dvResponse.Body);- const contacts = (body.value || []).map(r => ({+ if (!Array.isArray(body.value)) throw new Error("Dataverse read returned no value array");+ const contacts = body.value.map(r => ({id: r.contactid,firstName: r.firstname,lastName: r.lastname,@@ -207,15 +227,35 @@ if (!envelope) throw new Error('Empty response from getContacts');if (!envelope.success) throw new Error(envelope.error ?? 'Failed');if (envelope.data == null) throw new Error('Missing response data from getContacts');const payload = JSON.parse(envelope.data) as { status: string; contacts: Contact[] };+if (payload.status !== 'success') throw new Error('Dataverse read failed');return payload.contacts;```-For writes, return the new id from the server logic explicitly rather than relying on the `entityid` header:+For writes, return the new id from the server logic explicitly rather than relying on the outer `entityid` header:```javascript-const dvResponse = Server.Connector.Dataverse.CreateRecord("contacts", JSON.stringify(body));-const newId = dvResponse.Headers && dvResponse.Headers.entityid;-return JSON.stringify({ status: "success", id: newId });+function post() {+ try {+ Server.Logger.Log("createContact POST called");+ const dvResponse = JSON.parse(Server.Connector.Dataverse.CreateRecord("contacts", Server.Context.Body));+ if (dvResponse.IsSuccessStatusCode === false || !(dvResponse.StatusCode >= 200 && dvResponse.StatusCode < 300)) {+ throw new Error("Dataverse create failed: " + dvResponse.StatusCode);+ }+ // OData-EntityId is a record URL ending in "(<guid>)", not a bare GUID.+ // https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-entity-web-api+ const headers = dvResponse.Headers;+ const headerName = Object.keys(headers).find(key => key.toLowerCase() === "odata-entityid");+ const recordUrl = headers[headerName];+ const match = typeof recordUrl === "string"+ ? recordUrl.match(/\(([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)$/i)+ : null;+ if (!match) throw new Error("Dataverse create returned no valid OData-EntityId URL");+ return JSON.stringify({ status: "success", id: match[1] });+ } catch (err) {+ Server.Logger.Error("createContact POST failed: " + err.message);+ return JSON.stringify({ status: "error", message: err.message });+ }+}```### When the response shape is unknown@@ -224,10 +264,11 @@ If the frontend integration is failing because the exact Dataverse response shap### Key points for Dataverse-backed server logic-- `Server.Connector.Dataverse.*` methods return an object with `Body` (a JSON string), `StatusCode`, and `Headers`. They are **synchronous** — do not `await` them.-- When the server logic returns that object directly, the client must `JSON.parse(res.data)` to get the outer object and `JSON.parse(outer.Body)` to get the Dataverse payload.+- Parse the synchronous connector's JSON string before accessing `Body`, `StatusCode`, or `Headers`.+- Raw passthrough requires two client parses; wrapping the connector string in `{ status, data }` requires three.+- Check the connector's status before treating a response as successful; missing or malformed read bodies must surface as errors.- `RetrieveMultipleRecords` payloads have a `value` array; `RetrieveRecord` payloads are a single record object.-- `CreateRecord` returns the new record id via the `entityid` HTTP response header — not in the body.+- Extract the GUID from the connector's `OData-EntityId` URL for creates; successful writes may have an empty body.- For non-trivial features, prefer unwrapping `Body` inside the server logic and returning a feature-specific shape (Approach C) so the client integration is obvious and stable.## Recommended Approachesdiff --git a/plugins/power-pages/skills/add-server-logic/scripts/validate-serverlogic.js b/plugins/power-pages/skills/add-server-logic/scripts/validate-serverlogic.jsindex c73650caf..af2d15b9d 100644--- a/plugins/power-pages/skills/add-server-logic/scripts/validate-serverlogic.js+++ b/plugins/power-pages/skills/add-server-logic/scripts/validate-serverlogic.js@@ -203,19 +203,33 @@ runValidation((cwd) => {errors.push(`${dirName}.js: uses 'function delete()' — 'delete' is a reserved word, use 'del' instead`);}+ // Runtime pattern matching scans raw source, including comments and strings.+ // /Function\s*\(/i rejects `.map(function (r) {...})` as well as `Function("...")`.+ // Keep this case-insensitive and unanchored to match the observed runtime rule.+ // Tracking: https://github.com/microsoft/power-platform-skills/issues/870+ const functionMatches = [...content.matchAll(/function\s*\(/gi)];+ if (functionMatches.length > 0) {+ const lineNumbers = functionMatches.map(m => content.slice(0, m.index).split('\n').length);+ errors.push(+ `${dirName}.js: contains prohibited pattern /Function\\s*\\(/i on line(s) ${lineNumbers.join(', ')} - ` ++ `the Power Pages runtime blocks this even inside comments, string literals, and other identifiers. ` ++ `Use arrow functions for callbacks (e.g., rows.map(r => r.id)) or named nested helpers.`+ );+ }+// Check: no 'with(' substring anywhere in the raw source.- // The Power Pages server validator rejects scripts matching /with\s*\(/ to block+ // The Power Pages server validator rejects scripts matching /with\s*\(/i to block// the JavaScript `with` statement, but the regex also matches the substring inside// identifiers like `startswith(`, `endswith(`, and `groupwith(` — even inside string// literals — which causes runtime error: "Script validation failed: prohibited// pattern found - Pattern: with\s*\(". Run this on the raw content (not stripped)// because the server validator does the same.- const withMatches = [...content.matchAll(/with\s*\(/g)];+ const withMatches = [...content.matchAll(/with\s*\(/gi)];if (withMatches.length > 0) {const lineNumbers = withMatches.map(m => content.slice(0, m.index).split('\n').length);errors.push(`${dirName}.js: contains the substring 'with(' on line(s) ${lineNumbers.join(', ')} — ` +- `the Power Pages server validator's regex /with\\s*\\(/ blocks this even inside string literals ` ++ `the Power Pages server validator's regex /with\\s*\\(/i blocks this even inside string literals ` +`(e.g., OData functions like startswith(, endswith(). Split the literal so 'with(' is not contiguous, ` +`e.g., \`"startswith" + "(crd50_name,..."\` instead of \`"startswith(crd50_name,..."\`.`);