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
Document server logic response shapes for frontend integration (#104)
Priyanshu Agrawal6c662936fc9a
diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonindex 225de9349..38a41fe07 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": "1.2.2",+ "version": "1.2.3","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro, with more site types coming soon.","author": {"name": "Microsoft",diff --git a/plugins/power-pages/skills/add-server-logic/SKILL.md b/plugins/power-pages/skills/add-server-logic/SKILL.mdindex 9eee64197..39aa44f46 100644--- a/plugins/power-pages/skills/add-server-logic/SKILL.md+++ b/plugins/power-pages/skills/add-server-logic/SKILL.md@@ -662,6 +662,12 @@ function get() {- The server logic can add additional validation, transformation, or logging around the custom action call — it doesn't have to be a pass-through- When Custom API response properties are known (from Phase 2.1.2), map them to the response object for clarity+#### 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).++See `${CLAUDE_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.+#### Referencing Secrets in CodeWhen the server logic needs a secret value identified in Phase 2.3, **never hardcode the value**. Instead, read it at runtime from a site setting backed by an environment variable:@@ -1043,6 +1049,8 @@ Following the reference:- Replace placeholder data, mock handlers, or temporary actions when they are meant to be backed by the new server logic endpoints- Add or preserve loading, success, empty, and error states so the UI behaves like a finished feature- **For validate-and-execute endpoints**: The frontend must call the server logic endpoint for the protected operation (e.g., status transition) — it must NOT make a separate Web API PATCH for the same field. Ensure the UI for that operation (e.g., a "Submit" or "Approve" button) calls the server logic service function, not the Web API service+- **For Dataverse-backed endpoints**: Match the frontend parsing to the response shape chosen in Phase 5.3. See "Dataverse Connector Response Format" in the frontend integration reference for the exact parsing per shape.+- **If the response shape is unclear**: Do not guess. After the site is deployed, invoke `/test-site` against the live site so the actual server logic response can be captured from the network tab and used to drive the integration### 9.4 Git Commitdiff --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 d03da66aa..6a8c3f168 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@@ -45,6 +45,191 @@ Server logic endpoints return responses in a standard JSON envelope:All frontend helpers and service wrappers should unwrap `.data` from this envelope rather than treating the entire response body as the function's return value.+## Dataverse Connector Response Format++When a server logic function returns the raw result of a `Server.Connector.Dataverse.*` method, the shape that reaches the client is **double-wrapped**. This is the most common source of bugs in client integration code.++Reference: [Microsoft Learn — How to interact with Dataverse tables using server logic](https://learn.microsoft.com/en-us/power-pages/configure/server-logic-operations).++### 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:++```json+{+ "requestId": "…",+ "success": true,+ "serverLogicName": "dataverse-crud-operations",+ "data": "{\"Body\":\"{\\\"@odata.context\\\":\\\"…\\\",\\\"value\\\":[{…}, {…}]}\",\"StatusCode\":200,\"Headers\":{…}}",+ "error": null+}+```++To reach the Dataverse records the client must parse **twice**:++```javascript+const envelope = responseBody; // server logic envelope+const outer = JSON.parse(envelope.data); // { Body: "<json string>", StatusCode, Headers }+const body = JSON.parse(outer.Body); // { "@odata.context": "...", value: [...] } (for RetrieveMultipleRecords)+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).++### Three approaches — pick one and apply it consistently++For Dataverse-backed server logic there are three valid response shapes: **raw passthrough** (return the connector result as-is and parse it twice on the client), **server envelope that still wraps the connector result** (preserve the connector metadata but add an outer status wrapper), and **fully normalized** (unwrap everything server-side and return only what the UI needs). Pick one shape for each endpoint and apply it consistently across the server logic and the frontend integration.++**Approach A — Return the raw Dataverse response, double-parse on the client**++This is the pattern shown in the Microsoft Learn sample. Useful when the server logic is a thin CRUD passthrough driven by `entitySetName` query parameters.++Server logic:++```javascript+function get() {+ try {+ Server.Logger.Log("GET called");+ const entitySetName = Server.Context.QueryParameters["entitySetName"];+ const additionalParameters = Server.Context.QueryParameters["additionalParameters"];+ if (!Server.Context.QueryParameters["id"]) {+ return Server.Connector.Dataverse.RetrieveMultipleRecords(entitySetName, additionalParameters);+ }+ const id = Server.Context.QueryParameters["id"];+ return Server.Connector.Dataverse.RetrieveRecord(entitySetName, id, additionalParameters);+ } catch (err) {+ Server.Logger.Error("GET failed: " + err.message);+ return JSON.stringify({ status: "error", method: "GET", message: err.message });+ }+}+```++Client (matches the Microsoft Learn sample exactly):++```javascript+ajaxCall('Loading...', {+ type: 'GET',+ url: '/_api/serverlogics/dataverse-crud-operations?entitySetName=contacts&additionalParameters=$select=fullname,firstname,lastname,emailaddress1,telephone1',+ contentType: 'application/json'+}).done(res => {+ const outer = JSON.parse(res.data);+ const body = JSON.parse(outer.Body);+ 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.++Server logic:++```javascript+function get() {+ try {+ Server.Logger.Log("GET called");+ const entitySetName = Server.Context.QueryParameters["entitySetName"];+ const result = Server.Connector.Dataverse.RetrieveMultipleRecords(entitySetName);+ return JSON.stringify({ status: "success", data: result });+ } catch (err) {+ Server.Logger.Error("GET failed: " + err.message);+ return JSON.stringify({ status: "error", message: err.message });+ }+}+```++Client — note the extra `data` layer before reaching `Body`:++```typescript+const envelope = await powerPagesFetch<{ data: string | null; success: boolean; error: string | null }>(+ '/_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 body = JSON.parse(outer.Body); // { "@odata.context": "...", value: [...] }+const records = body.value;+```++Do **not** use the Approach A parsing path (`JSON.parse(envelope.data) → JSON.parse(outer.Body)`) against this shape — that skips the `payload.data` unwrap and reads `Body` off the wrong object.++**Approach C — Unwrap server-side and return a clean shape (recommended for most new code)**++Return a stable, documented shape from the function. Client code then only unwraps the outer envelope and parses `data` once. Prefer this when the server logic serves a specific feature (not a generic CRUD passthrough).++Server logic:++```javascript+function get() {+ try {+ Server.Logger.Log("getContacts GET called");+ const dvResponse = Server.Connector.Dataverse.RetrieveMultipleRecords(+ "contacts",+ "?$select=contactid,firstname,lastname,emailaddress1,telephone1"+ );+ const body = JSON.parse(dvResponse.Body);+ const contacts = (body.value || []).map(r => ({+ id: r.contactid,+ firstName: r.firstname,+ lastName: r.lastname,+ email: r.emailaddress1,+ phone: r.telephone1+ }));+ return JSON.stringify({ status: "success", contacts });+ } catch (err) {+ Server.Logger.Error("getContacts GET failed: " + err.message);+ return JSON.stringify({ status: "error", message: err.message });+ }+}+```++Client:++```typescript+const envelope = await powerPagesFetch<{ data: string | null; success: boolean; error: string | null }>(+ '/_api/serverlogics/getContacts',+ { method: 'GET' }+);+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[] };+return payload.contacts;+```++For writes, return the new id from the server logic explicitly rather than relying on the `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 });+```++### When the response shape is unknown++If the frontend integration is failing because the exact Dataverse response shape is unclear for a specific operation (custom actions, bound actions, non-standard query options), invoke `/test-site` against the deployed site. The test-site skill captures live `/_api/serverlogics/` responses and reports the exact `envelope.data` and (when present) `outer.Body` shapes so the frontend integration can be written against the real response, not a guessed one.++### 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.+- `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.+- 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 Approaches### 1. Sites Using `shell.safeAjax`@@ -92,14 +277,20 @@ export async function callServerLogic<T = unknown>(? `/_api/serverlogics/${endpointName}?${new URLSearchParams(params)}`: `/_api/serverlogics/${endpointName}`;- const envelope = await powerPagesFetch<{ data: string; success: boolean; error: string | null }>(url, {+ const envelope = await powerPagesFetch<{ data: string | null; success: boolean; error: string | null }>(url, {method,body: body ? JSON.stringify(body) : undefined,});+ if (!envelope) {+ throw new Error(`Empty response from ${endpointName}`);+ }if (!envelope.success) {throw new Error(envelope.error ?? 'Server logic call failed');}+ if (envelope.data == null) {+ throw new Error(`Missing response data from ${endpointName}`);+ }return JSON.parse(envelope.data) as T;}diff --git a/plugins/power-pages/skills/test-site/SKILL.md b/plugins/power-pages/skills/test-site/SKILL.mdindex 6c6b2680c..f96cb275b 100644--- a/plugins/power-pages/skills/test-site/SKILL.md+++ b/plugins/power-pages/skills/test-site/SKILL.md@@ -22,6 +22,7 @@ Test a deployed, activated Power Pages site at runtime. Navigate the site in a b- **Non-destructive**: This skill is read-only — it does not create, modify, or delete any files or data. It only observes the site via the browser.- **API-first testing**: The primary goal beyond page loads is verifying that all `/_api/` (Web API / OData) requests return successful responses.+- **Response-shape discovery**: For `/_api/serverlogics/` endpoints the test run must also capture and report the actual response body shape so frontend integrations can be written against the real response, not a guessed one. If frontend parsing or field access does not match the observed shape, report the mismatch and describe the parsing or field-access changes needed — this skill does not modify any code.- **User-controlled authentication**: Never attempt to log in automatically. Always ask the user to log in via the browser window when authentication is required.- **Bounded crawling**: Cap page crawling at 25 pages to prevent infinite loops on sites with dynamic or paginated URLs.@@ -320,6 +321,44 @@ For each captured API request, evaluate:| 500 | **Fail** | Server error — internal Dataverse or plugin error || Other 4xx/5xx | **Fail** | Unexpected error |+#### 5.3b Inspect Server Logic Response Shapes++Server logic endpoints (`/_api/serverlogics/<name>`) commonly return a standard envelope whose `data` field is typically a string on success, but it is not guaranteed to be one in every response — in failure or edge cases `data` may be `null`, absent, a non-JSON string, or another non-string value. When the server logic returns serialized JSON (common), `data` must be parsed to reveal the actual payload — and that payload itself may be nested further. Frontend code often parses to the wrong level, reads the wrong keys, or treats `data` as the final object, producing silent UI failures. Test-site must surface the exact observed shape so the frontend can be corrected rather than assuming `data` is always directly parseable.++For each `/_api/serverlogics/` request observed on any tested page:++1. Record the endpoint name from the URL (`/_api/serverlogics/<endpointName>`), the HTTP method, query string parameters, and HTTP status code.+2. When the request was a GET (no CSRF token required), re-execute it from the browser with `browser_evaluate` so the full response body is captured. Progressively parse the payload — keep parsing string-typed fields until further parsing fails — and record the shape at each level. Use a script of this form, replacing the URL with the observed one:++ ```javascript+ async () => {+ const res = await fetch('<observed-url>', { credentials: 'include', headers: { 'Content-Type': 'application/json' } });+ const status = res.status;+ const text = await res.text();+ const levels = [];+ let current;+ try { current = JSON.parse(text); } catch { return { status, rawSample: text.slice(0, 2000) }; }+ levels.push({ type: Array.isArray(current) ? 'array' : typeof current, keys: current && typeof current === 'object' && !Array.isArray(current) ? Object.keys(current) : null, firstItemKeys: Array.isArray(current) && current[0] && typeof current[0] === 'object' ? Object.keys(current[0]) : null });+ // Progressively parse common nested-string fields (data, Body, body, payload, result)+ const nestedKeys = ['data', 'Body', 'body', 'payload', 'result'];+ while (current && typeof current === 'object') {+ const next = nestedKeys.find(k => typeof current[k] === 'string');+ if (!next) break;+ let parsed;+ try { parsed = JSON.parse(current[next]); } catch { break; }+ levels.push({ parsedFrom: next, type: Array.isArray(parsed) ? 'array' : typeof parsed, keys: parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? Object.keys(parsed) : null, firstItemKeys: Array.isArray(parsed) && parsed[0] && typeof parsed[0] === 'object' ? Object.keys(parsed[0]) : null });+ current = parsed;+ }+ return { status, levels, rawSample: text.slice(0, 2000) };+ }+ ```++3. For non-GET server logic requests, do **not** re-execute them (they may mutate data). Rely on the already-captured `browser_network_requests` entry and report whatever response metadata is available. Note in the report that the body was not re-captured.+4. Build a "Server Logic Response Shapes" section for the Phase 6 report. For each endpoint record: endpoint name, HTTP method, status, the chain of parse levels (what key was parsed at each step, resulting type, keys at that level, and first-item keys when the level is an array), and a raw sample (first ~2000 chars, matching the slice in the script above). If `envelope.success === false` and `envelope.error` is present, report the error verbatim.+5. Compare the observed shape to how the frontend actually consumes it (service files, hooks, components found in the repo). If there is a mismatch — e.g. the UI reads `envelope.data.value` as an object but the actual payload is a string that needs parsing, or expects a field name that doesn't appear in the observed keys — identify the mismatch and recommend the minimal frontend change needed to match the real shape. Be specific about the parsing or field access change required, but do **not** modify frontend code or create a commit in this skill; leave implementation to a separate editing/remediation skill or phase.++Record the findings and any recommended frontend fixes for the Phase 6 report.+#### 5.4 Provide Actionable Guidance for FailuresFor each failed API request, provide specific remediation:@@ -452,6 +491,27 @@ API endpoints tested: 3 | Passed: 2 | Failed: 1If no API requests were captured, note: "No API requests (`/_api/` or OData) were detected during testing. This site may not use the Web API, or API calls may require specific user interactions to trigger."+#### 6.3b Present Server Logic Response Shapes++If any `/_api/serverlogics/` requests were captured in Phase 5.3b, add a dedicated subsection so the frontend integration can be written against the real response. Show the full chain of parse levels — one block per distinct endpoint:++```+## Server Logic Response Shapes++### /_api/serverlogics/<endpoint-name> (GET, 200)++- Level 0 (raw body): object, keys: [requestId, success, serverLogicName, data, error]+- Level 1 (parsed from `data`): object, keys: [status, items, count]+- Level 1 `items` property: array; first item keys: [id, name, ...]+- Raw sample: `{"requestId":"...","success":true,"data":"{\"status\":\"success\",\"items\":[{\"id\":\"...\",\"name\":\"...\"}],\"count\":1}", ...}`++Frontend parsing required:+ const level1 = JSON.parse(envelope.data);+ const items = level1.items;+```++If a frontend mismatch was detected, list the files and lines that would need to change and the specific parsing/field access correction required — do not apply or commit the change in this skill. This section is the primary deliverable when a developer asks "I don't know what shape my server logic returns — what does the frontend need to do?"+#### 6.4 Present Authenticated Test Results (If Applicable)If Phase 5.6 was executed, present results in separate tables: