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
'use strict';
// Guards the vendored, self-contained SDK bundle (scripts/vendor/cds-maker-sdk.cjs):
// it must load in plain Node (no browser), construct, serialize every artifact type
// headlessly via the xmldom DOM shim, and build a real Dataverse push payload.
// Rebuild the bundle with: node scripts/_vendor-build/build.js (see _vendor-build/).
const test = require('node:test');
const assert = require('node:assert');
const os = require('node:os');
const path = require('node:path');
const fs = require('node:fs');
const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
// The migration's pure intent helpers, used to drive the generic surface in the CONTRACT tests below.
const { formEventsRegionIntent, findFieldCellPointer } = require('../lib/artifact-intent.js');
const { appSitemapLinkRows } = require('./helpers/app-sitemap-link-rows.js');
// Every app the PLUGIN creates carries an icon: `ensureAppIcon` (sdk-build.js) resolves the author's
// `spec.app.icon` or generates an SVG web resource, and `appDef` passes its id as
// `iconWebResourceId`. These tests drive the SDK directly, so they must supply one too or they are
// exercising a path production never takes.
//
// The SDK now REQUIRES it: `appmodule.webresourceid` is a required attribute, and when no explicit id
// is given it auto-resolves an IMAGE web resource (PNG/JPG/GIF/ICO/SVG) and throws
// `APP_ICON_UNRESOLVED` if the environment has none. Previously it fell back to ANY unmanaged web
// resource — which on an org whose images are all managed returned a JAVASCRIPT file, and the platform
// rejected the create with an opaque "dependent component WebResource does not exist". Failing fast
// with a clear message is the better behaviour; these tests just have to stop relying on the old
// silent fallback. A synthetic id is right here — the mock transport never dereferences it.
const APP_ICON_ID = '11111111-2222-3333-4444-555555555555';
// Track temp workspace dirs created by the smoke tests and remove them once the suite finishes,
// so repeated runs don't leak directories into the test runner's temp folder.
const tempDirs = [];
function mkTempWorkspace(prefix) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
test.after(() => {
for (const dir of tempDirs) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
async function freshSdk(capture) {
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
const ws = mkTempWorkspace('sdk-smoke-');
const httpClient = {
get: async () => ({ status: 200, headers: {}, body: {} }),
post: async (url, body) => {
if (capture) capture.push({ url, body });
return { status: 204, headers: { 'odata-entityid': 'https://x/y(11111111-1111-1111-1111-111111111111)' }, body: {} };
},
patch: async () => ({ status: 204, headers: {}, body: {} }),
delete: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(ws), instanceUrl: 'https://example.crm.dynamics.com', httpClient });
await sdk.initWorkspace();
return sdk;
}
test('vendored bundle exports createMakerSdk', () => {
const mod = require(BUNDLE);
// hardening-2 exposes the FACTORY (the only entry the engine uses); the MakerSdk class is no
// longer a public export.
assert.strictEqual(typeof mod.createMakerSdk, 'function');
});
// The SDK's genPage compiler takes TypeScript from its host, and its `loadNodeTypeScript` helper loads
// it with a dynamic import that esbuild would otherwise follow: the compiler then made up 3.5 MB of a
// 4.4 MB bundle. The plugin passes its own compiler (lib/maker-sdk.js), so `_vendor-build/build.js` marks
// `typescript` external. A rebuild that drops that flag inlines it again, and this fails on the size of the text.
test('the vendored bundle does not carry the TypeScript compiler, and loading one fails closed', async () => {
const text = fs.readFileSync(BUNDLE, 'utf8');
assert.ok(text.length < 2 * 1024 * 1024, `bundle is ${Math.round(text.length / 1024)} KB — was the TypeScript compiler inlined?`);
const mod = require(BUNDLE);
assert.strictEqual(typeof mod.loadNodeTypeScript, 'function', 'the SDK still offers the loader');
// Only while `typescript` cannot be resolved from the bundle's folder: then the loader must reject
// with the resolution error, never resolve to something the bundle carried itself.
let resolvable = true;
try { require.resolve('typescript', { paths: [path.dirname(BUNDLE)] }); } catch { resolvable = false; }
if (!resolvable) await assert.rejects(mod.loadNodeTypeScript(), /Cannot find module 'typescript'/);
});
test('createArtifact serializes every artifact type headlessly (no browser)', async () => {
const sdk = await freshSdk();
for (const [type, def] of [
['view', { entityLogicalName: 'account', name: 'Smoke View' }],
['chart', { entityLogicalName: 'account', name: 'Smoke Chart' }],
['form', { entityLogicalName: 'account', name: 'Smoke Form' }],
['app', { name: 'Smoke App' }],
]) {
const a = await sdk.createArtifact(type, def);
assert.ok(a && a.id, `${type} artifact should have an id`);
}
});
test('pushArtifact builds a real FormXML payload headlessly', async () => {
const capture = [];
const sdk = await freshSdk(capture);
const form = await sdk.createArtifact('form', { entityLogicalName: 'account', name: 'Push Test Form' });
const result = await sdk.pushArtifact('form', form.id);
// The SDK renamed PushResult.success -> saved to force call sites to distinguish "the write
// committed" from "the runtime serves it" (`shipped`, true only on a VERIFIED publish). Accept
// either spelling so this pins the CONTRACT rather than one bundle generation.
assert.strictEqual(result.saved !== undefined ? result.saved : result.success, true);
assert.strictEqual(result.shipped, false, 'a push with no publish requested is saved but NOT shipped');
assert.ok(capture.length > 0, 'a POST should have been issued');
const body = capture[0].body;
assert.ok(typeof body.formxml === 'string' && body.formxml.includes('<form'), 'payload carries FormXML');
});
test('createWebResource posts base64 content + the right webresourcetype (Tier 2)', async () => {
const capture = [];
const sdk = await freshSdk(capture);
await sdk.createWebResource({ name: 'new_smoke.js', displayName: 'Smoke', type: 'js', content: 'function f(){return 1;}', publish: false });
const post = capture.find((c) => /webresourceset/.test(c.url));
assert.ok(post, 'a POST to /webresourceset was issued');
assert.strictEqual(post.body.webresourcetype, 3, 'js -> webresourcetype 3');
assert.strictEqual(post.body.name, 'new_smoke.js');
// content must be base64 (headless btoa/Buffer path), decoding back to the source
assert.strictEqual(Buffer.from(post.body.content, 'base64').toString('utf8'), 'function f(){return 1;}');
});
test('vendored SDK exposes the AI methods', () => {
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(require('os').tmpdir()), instanceUrl: 'https://x/', httpClient: { get: async () => ({}), post: async () => ({}), patch: async () => ({}), delete: async () => ({}), put: async () => ({}) } });
for (const m of ['retrieveSetting', 'saveSettingValue', 'getAiReadiness', 'setAppAiFeatures', 'configureRowSummary', 'removeRowSummary']) {
assert.strictEqual(typeof sdk[m], 'function', `sdk.${m} should be a function`);
}
});
test('vendored SDK exposes the consolidation methods', () => {
const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');
const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(require('os').tmpdir()), instanceUrl: 'https://x/', httpClient: { get: async () => ({}), post: async () => ({}), patch: async () => ({}), delete: async () => ({}), put: async () => ({}) } });
for (const m of ['resolveArtifact', 'findArtifact', 'deleteAppCascade', 'seedRecordGraph', 'enrichDefaultViews']) {
assert.strictEqual(typeof sdk[m], 'function', `sdk.${m} should be a function`);
}
});
test('CONTRACT: a canonical /bag/c <events> region wires a handler into the retained FormXML headlessly (Tier 2)', async () => {
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
const ws = mkTempWorkspace('sdk-evt-');
const FID = '22222222-2222-2222-2222-222222222222';
const formXml = '<form><tabs><tab name="general"><columns><column><sections><section><rows /></section></sections></column></columns></tab></tabs></form>';
let pushedXml = '';
const httpClient = {
get: async () => ({ status: 200, headers: { etag: 'W/"1"' }, body: { formid: FID, name: 'F', type: 2, objecttypecode: 'account', formxml: formXml } }),
post: async () => ({ status: 204, headers: {}, body: {} }),
patch: async (url, body) => { pushedXml = String((body && body.formxml) || ''); return { status: 204, headers: {}, body: {} }; },
delete: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(ws), instanceUrl: 'https://example.crm.dynamics.com', httpClient });
await sdk.initWorkspace();
return sdk.fetchArtifact('form', FID).then(async (fetched) => {
assert.ok(fetched, 'form fetched');
// The engine wires form JS by adding the root-bag <events> region via the generic surface (the
// retired addFormEventHandler is gone). The adapter mints the handlerUniqueId at serialize.
const bagC = (fetched.bag && fetched.bag.c) || [];
const nextI = bagC.reduce((m, e) => Math.max(m, e.i), -1) + 1;
await sdk.addElement('form', FID, '/bag/c', { i: nextI, node: formEventsRegionIntent([{ event: 'onload', library: 'new_smoke.js', function: 'Ticket.onLoad' }]) });
await sdk.pushArtifact('form', FID);
assert.match(pushedXml, /Ticket\.onLoad/, 'the handler function is baked into the pushed formxml');
assert.match(pushedXml, /handlerUniqueId/, 'the adapter minted the handlerUniqueId the caller omitted');
});
});
test('CONTRACT: removeElement drops a bound field from a fetched form (reconcile can DELETE a field, not only add)', async () => {
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
const ws = mkTempWorkspace('sdk-rmfield-');
const FID = '22222222-2222-2222-2222-222222222222';
// A fetched form whose retained formxml carries two bound fields (name + tier). The skill's form
// reconcile removes a field the edited spec dropped — findFieldCellPointer locates the cell and
// removeElement drops it. This locks that the bundle can do it via the generic surface.
const formXml =
'<form><tabs><tab id="{11111111-1111-1111-1111-111111111111}" name="general"><columns><column><sections>' +
'<section id="{55555555-5555-5555-5555-555555555555}" name="sec" columns="1"><rows>' +
'<row><cell id="{c1}"><control id="new_name" classid="{4273EDBD-AC1D-40d3-9FB2-095C621B552D}" datafieldname="new_name" /></cell></row>' +
'<row><cell id="{c2}"><control id="new_tier" classid="{4273EDBD-AC1D-40d3-9FB2-095C621B552D}" datafieldname="new_tier" /></cell></row>' +
'</rows></section></sections></column></columns></tab></tabs></form>';
let pushedXml = '';
const httpClient = {
get: async () => ({ status: 200, headers: { etag: 'W/"1"' }, body: { formid: FID, name: 'F', type: 2, objecttypecode: 'new_customer', formxml: formXml } }),
post: async () => ({ status: 204, headers: {}, body: {} }),
patch: async (url, body) => { pushedXml = String((body && body.formxml) || ''); return { status: 204, headers: {}, body: {} }; },
delete: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(ws), instanceUrl: 'https://example.crm.dynamics.com', httpClient });
await sdk.initWorkspace();
await sdk.fetchArtifact('form', FID);
const ptr = findFieldCellPointer(await sdk.getArtifact('form', FID), 'new_tier');
assert.ok(ptr, 'the cell hosting the dropped field is located in the canonical tree');
await sdk.removeElement('form', FID, ptr);
await sdk.pushArtifact('form', FID);
assert.ok(/datafieldname="new_name"/.test(pushedXml), 'the kept field survives the push');
assert.ok(!/datafieldname="new_tier"/.test(pushedXml), 'the removed field is gone from the pushed formxml');
});
// --- SDK safety-boundary contract invariants ------------------------------------------------
// Lock the behaviors the SKILL depends on so a future SDK hardening (GUID normalizer, safe DOM
// element factory, percent-encoding OData query builder) can't silently break the skill when the
// vendored bundle is rebuilt. Each test passes today AND must keep passing after the boundaries
// land — the assertions are chosen so a contract-breaking change (GUID-validating a logical name,
// double-encoding a filter, rejecting free-text XML values) fails here.
// A capturing httpClient that records every request and answers EntityDefinitions set-name lookups
// so queryRecords can resolve a logical name -> entity-set name headlessly.
function captureClient() {
const reqs = [];
const metaBody = (url) => {
const ln = (url.match(/LogicalName='([^']+)'/) || [])[1] || 'x';
return { MetadataId: '33333333-3333-3333-3333-333333333333', EntitySetName: `${ln}s`, LogicalName: ln };
};
const client = {
get: async (url) => {
reqs.push({ method: 'GET', url });
if (/EntityDefinitions\(LogicalName=/i.test(url)) return { status: 200, headers: {}, body: metaBody(url) };
return { status: 200, headers: {}, body: { value: [] } };
},
post: async (url, body) => { reqs.push({ method: 'POST', url, body }); return { status: 204, headers: { 'odata-entityid': 'https://x/y(44444444-4444-4444-4444-444444444444)' }, body: {} }; },
patch: async (url, body) => { reqs.push({ method: 'PATCH', url, body }); return { status: 204, headers: {}, body: {} }; },
delete: async (url) => { reqs.push({ method: 'DELETE', url }); return { status: 204, headers: {}, body: {} }; },
put: async (url, body) => { reqs.push({ method: 'PUT', url, body }); return { status: 204, headers: {}, body: {} }; },
};
return { client, reqs };
}
async function sdkWith(client) {
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
const ws = mkTempWorkspace('sdk-contract-');
const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(ws), instanceUrl: 'https://example.crm.dynamics.com', httpClient: client });
await sdk.initWorkspace();
return sdk;
}
// The wire $filter, decoded exactly once by URLSearchParams. Equals the raw OData filter whether the
// SDK sends it unencoded (today) or single-encoded (after the query builder lands); a DOUBLE-encoded
// value decodes to a still-encoded string and fails the equality — catching the classic regression.
function filterOf(url) {
return new URL(url).searchParams.get('$filter');
}
test('CONTRACT: queryRecords transmits a raw quoted-string OData filter that round-trips (raw filters stay supported; no double-encoding)', async () => {
const { client, reqs } = captureClient();
const sdk = await sdkWith(client);
const raw = `uniquename eq 'new_a b' and ismanaged eq false`;
await sdk.queryRecords('appmodule', { select: ['appmoduleid', 'name'], filter: raw, top: 1 });
const get = reqs.find((r) => r.method === 'GET' && /appmodules\?/.test(r.url));
assert.ok(get, 'a GET to the resolved entity set was issued');
assert.strictEqual(filterOf(get.url), raw, 'the raw filter must survive transport exactly once');
});
test('CONTRACT: queryRecords transmits an UNQUOTED GUID-literal filter unchanged (the solutioncomponent/sitemap pattern the skill uses)', async () => {
const { client, reqs } = captureClient();
const sdk = await sdkWith(client);
const raw = `objectid eq 11111111-1111-1111-1111-111111111111`;
await sdk.queryRecords('solutioncomponent', { select: ['_solutionid_value'], filter: raw, top: 1 });
const get = reqs.find((r) => r.method === 'GET' && /solutioncomponents\?/.test(r.url));
assert.strictEqual(filterOf(get.url), raw);
});
test('CONTRACT: name-based SDK methods accept logical/unique names verbatim (never forced through GUID validation)', async () => {
const { client, reqs } = captureClient();
const sdk = await sdkWith(client);
// The skill passes NAMES (not GUIDs) to these — a GUID normalizer applied here would reject them.
await sdk.resolveArtifact('app', { uniqueName: 'new_app' }); // teardown/verify resolve-by-name
await sdk.setEntityIcon('contoso_widget', { vector: 'contoso_icon', publish: false }); // table icon by logical name
await sdk.createRelationship({ type: 'OneToMany', schemaName: 'contoso_systemuser_teammember', referencedEntity: 'systemuser', referencingEntity: 'contoso_teammember', lookupSchemaName: 'contoso_LinkedUserId', lookupDisplayName: 'Linked User' });
try { await sdk.deleteTable('account'); } catch { /* the SDK's deleteTable throws a cosmetic not-found even on success */ }
// Decode each URL before matching: the SDK's OData query builder single-encodes query
// values (spaces -> %20, `$select` commas -> %2C), so a raw-string regex would miss the
// name even though it transmitted fine. The GUID-validation guard is unaffected — if any
// name-based method had rejected its name argument, the awaits above would have thrown
// before reaching these assertions. decodeURIComponent recovers the raw names to prove
// they survived transport (path segments like LogicalName='account' are unencoded already).
const wire = reqs.map((r) => `${r.method} ${decodeURIComponent(r.url)} ${JSON.stringify(r.body || '')}`).join('\n');
assert.match(wire, /uniquename eq 'new_app'/i, 'resolveArtifact accepted a unique name');
assert.match(wire, /contoso_widget/i, 'setEntityIcon accepted a table logical name');
assert.match(wire, /systemuser/, 'createRelationship kept the system-table logical name');
assert.match(wire, /LogicalName='account'/i, 'deleteTable accepted a table logical name');
});
test('CONTRACT: free-text sitemap titles/URLs are XML-escaped, not rejected (a safe DOM factory must escape VALUES, only validate NAMES)', async () => {
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
const { appDef } = require('../lib/sdk-build.js');
const spec = {
solution: { uniqueName: 'EscA', publisherPrefix: 'new' },
app: { name: 'R&D <Ops> "Hub"', description: 'a & b < c > d' },
entities: [{ schemaName: 'new_o', primaryAttribute: { schemaName: 'new_name' }, columns: [] }],
appShell: { areas: [{ label: 'Sales & Ops', groups: [{ label: 'A & B', subAreas: [
{ entity: 'new_o', title: 'Tom & "Jerry" <x>' },
{ url: 'https://x/y?a=1&b=2&c=<z>', title: 'Link & Go' },
] }] }] },
};
const def = appDef(spec, { forms: {}, views: {}, charts: {}, dashboards: {} });
// Drive the PUBLIC surface (the AppAdapter class is no longer a bundle export): create the app and
// capture the sitemapxml the push serializes.
let sitemapXml = '';
const ws = mkTempWorkspace('sdk-esc-');
// This test is about XML ESCAPING, not component pinning — but the push now resolves each sitemap
// table to an OData reference and reads the components back, both fail-closed. Answer those reads
// so an unrelated refusal cannot masquerade as an escaping failure.
const TABLE_METADATA_ID = '22222222-2222-2222-2222-222222222222';
const httpClient = {
get: async (url) => {
const m = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
if (m) return { status: 200, headers: {}, body: { LogicalName: m[1], MetadataId: TABLE_METADATA_ID, EntitySetName: `${m[1]}s` } };
if (/\/appmodulecomponents/.test(url)) return { status: 200, headers: {}, body: { value: [{ objectid: TABLE_METADATA_ID, componenttype: 1 }] } };
if (/\/appmodules/.test(url)) {
const row = { appmoduleid: '11111111-1111-1111-1111-111111111111', appmoduleidunique: '33333333-3333-3333-3333-333333333333' };
return { status: 200, headers: {}, body: /RetrieveUnpublishedMultiple/i.test(url) ? { value: [row] } : row };
}
return { status: 200, headers: {}, body: {} };
},
post: async (url, body) => { if (/\/sitemaps\b/.test(url) && body && body.sitemapxml) sitemapXml = String(body.sitemapxml); return { status: 204, headers: { 'odata-entityid': 'https://x/y(11111111-1111-1111-1111-111111111111)' }, body: {} }; },
patch: async () => ({ status: 204, headers: {}, body: {} }),
delete: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(ws), instanceUrl: 'https://example.crm.dynamics.com', httpClient });
await sdk.initWorkspace();
const art = await sdk.createArtifact('app', { name: spec.app.name, uniqueName: 'new_escapp', description: spec.app.description, siteMap: def.siteMap, components: def.components, iconWebResourceId: APP_ICON_ID });
await assert.doesNotReject(sdk.pushArtifact('app', art.id), 'special-char titles/URLs must serialize, not throw');
assert.ok(sitemapXml, 'the sitemap was serialized and posted');
assert.match(sitemapXml, /&/, 'ampersands in titles/URLs are escaped');
assert.match(sitemapXml, /a=1&b=2/, 'URL query separators are escaped in the attribute value (not lost or left raw)');
assert.ok(!/<Title[^>]*>[^<]*&(?!amp;|lt;|gt;|quot;|apos;|#)/.test(sitemapXml), 'no raw unescaped ampersand inside a Title');
});
test('CONTRACT: vendored deleteAppCascade returns a structured { success, deleted, failures, retained } result and RETAINS generative pages rather than cascading them', async () => {
// The app (and its sitemap) delete atomically. A generative page referenced by the sitemap is
// deliberately NOT deleted: a `uxagentproject` is REFERENCED by an app, not owned by one — another
// app's sitemap, or a form's UxAgentControl `RefId`, can point at the same row — so the SDK reports
// it in `retained[]` and leaves the decision to the caller. `scripts/lib/sdk-teardown.js` is that
// caller: it deletes only the pages the build's own page manifest records as authored here, and
// lets Dataverse's dependency graph reject anything still referenced.
//
// This test previously asserted the OPPOSITE contract — that a failed cascaded genpage delete set
// `success=false` and landed in `failures[]`. That was written against a bundle which cascaded
// genpage deletes. Keep it pinned to `retained[]`: silently reverting to a cascade would delete a
// page another app still surfaces.
//
// The sitemap is deliberately not the failing row here: it is not an independently addressable
// cascade target — it is deleted in the SAME atomic $batch change set as the app, so a sitemap
// failure rejects the whole call instead of landing in failures[].
const APP_ID = '77777777-7777-7777-7777-777777777777';
const APP_UNIQUE = '88888888-8888-8888-8888-888888888888';
const SITEMAP_ID = '99999999-9999-9999-9999-999999999999';
const GENPAGE_ID = '55555555-5555-5555-5555-555555555555';
const client = {
get: async (url) => {
if (/EntityDefinitions\(LogicalName=/i.test(url)) {
const ln = (url.match(/LogicalName='([^']+)'/) || [])[1] || 'x';
return { status: 200, headers: {}, body: { MetadataId: '33333333-3333-3333-3333-333333333333', EntitySetName: `${ln}s`, LogicalName: ln } };
}
const linked = appSitemapLinkRows(url, {
apps: [{ appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE, componentstate: 0 }],
components: [{ _appmoduleidunique_value: APP_UNIQUE, objectid: SITEMAP_ID, componenttype: 62 }],
});
if (linked !== undefined) return { status: 200, headers: {}, body: { value: linked } };
// The by-id app row supplies the conditional delete's ETag; the current layer above supplies
// the actual type-62 sitemap identity. Neither can be guessed from a matching name.
if (/\/appmodules\([^)]+\)/.test(url)) {
return { status: 200, headers: {}, body: { '@odata.etag': 'W/"1"', appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE, uniquename: 'new_cascadeapp', name: 'Cascade App' } };
}
// The by-id sitemap read supplies the ROW token the conditional delete carries. It answers
// with the single row (never a collection) and the token in the header and the body.
if (/\/sitemaps\([^)]+\)/.test(url)) {
return { status: 200, headers: { etag: 'W/"2"' }, body: { '@odata.etag': 'W/"2"', sitemapid: SITEMAP_ID } };
}
// Only a navigational <SubArea GenPageId="…"> counts as a live generative-page reference.
if (/\/sitemaps/.test(url)) {
return {
status: 200,
headers: {},
body: { value: [{ '@odata.etag': 'W/"2"', sitemapid: SITEMAP_ID, sitemapnameunique: 'new_cascadeapp', sitemapxml: `<SiteMap><Area><Group><SubArea Id="s1" GenPageId="${GENPAGE_ID}" /></Group></Area></SiteMap>` }] },
};
}
// The generative page owns one file row, which cascades before its parent.
if (/\/uxagentprojectfiles\?/.test(url)) return { status: 200, headers: {}, body: { value: [{ uxagentprojectfileid: '66666666-6666-6666-6666-666666666666' }] } };
return { status: 200, headers: {}, body: { value: [] } };
},
post: async () => ({ status: 204, headers: {}, body: {} }),
// The app + sitemap go out as one atomic change set; echo a well-formed multipart response so
// both operations read as 204 and the cascade proceeds to its generative-page children.
postRaw: async (_url, body) => {
const ids = [...String(body).matchAll(/^Content-ID:\s*(\S+)/gim)].map((m) => m[1]);
const parts = ids.flatMap((id) => ['--csr', 'Content-Type: application/http', `Content-ID: ${id}`, '', 'HTTP/1.1 204 No Content', '']);
return { status: 200, headers: {}, body: ['--br', 'Content-Type: multipart/mixed; boundary=csr', '', ...parts, '--csr--', '--br--', ''].join('\r\n') };
},
patch: async () => ({ status: 204, headers: {}, body: {} }),
delete: async (url) => {
// The DELETE /uxagentprojects(<id>) child cleanup fails; every other delete succeeds.
if (/\/uxagentprojects\(/.test(url)) return { status: 500, headers: {}, body: { error: { message: 'generative page locked' } } };
return { status: 204, headers: {}, body: {} };
},
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const sdk = await sdkWith(client);
const result = await sdk.deleteAppCascade(APP_ID, APP_UNIQUE);
assert.ok(result && typeof result === 'object', 'deleteAppCascade returns a structured result (not void)');
assert.ok(Array.isArray(result.deleted) && result.deleted.some((d) => d.type === 'app'), 'the primary app delete is reported in deleted[]');
assert.strictEqual(result.success, true, 'retaining a referenced generative page is not a failure');
assert.deepStrictEqual(result.failures, [], 'nothing was attempted against the genpage, so nothing failed');
assert.ok(
Array.isArray(result.retained) && result.retained.some((r) => r.type === 'genPage' && r.id === GENPAGE_ID),
'the referenced generative page is surfaced in retained[] so the caller can decide'
);
});
test('CONTRACT: vendored seedRecordGraph returns { createdIds: { <entity>: [ids] } } (the sample-data phase reads createdIds to bind children)', async () => {
// The build's sample-data phase (entity-provision.js) calls
// sdk.seedRecordGraph([{ entityLogical, matchOn?, records:[{ body, binds }] }],
// { entitySetFor, createdIds })
// and destructures `createdIds`, then reads createdIds[<entityLogical>] to bind children — so
// the bundle MUST keep returning that exact shape (not a bare id array) across a re-vendor.
// Stub CreateMultiple ({ Ids:[...] }) + an empty resolve-by-name GET; entitySetFor supplies the
// set name so no EntityDefinitions lookup is needed.
const client = {
get: async (url) => {
// The SDK resolves the collection URL from EntityDefinitions when no set name is cached.
const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
if (meta) return { status: 200, headers: {}, body: { EntitySetName: `${meta[1]}s`, LogicalName: meta[1] } };
return { status: 200, headers: {}, body: { value: [] } };
},
post: async (url, body) => {
if (/CreateMultiple/.test(url)) {
const n = ((body && body.Targets) || []).length;
return { status: 200, headers: {}, body: { Ids: Array.from({ length: n }, (_, i) => `wid-${i}`) } };
}
return { status: 204, headers: {}, body: {} };
},
patch: async () => ({ status: 204, headers: {}, body: {} }),
delete: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const sdk = await sdkWith(client);
const group = {
entityLogical: 'new_widget',
matchOn: 'new_name',
records: [{ body: { new_name: 'A' }, binds: [] }, { body: { new_name: 'B' }, binds: [] }],
};
const result = await sdk.seedRecordGraph([group], { createdIds: {} });
assert.ok(result && typeof result === 'object', 'seedRecordGraph returns a structured result');
assert.ok(result.createdIds && typeof result.createdIds === 'object', 'result carries a createdIds map keyed by entity logical name');
assert.deepStrictEqual(result.createdIds.new_widget, ['wid-0', 'wid-1'], 'createdIds[<entity>] lists the new row ids in order');
});
// #544 relies on two properties of the REAL bundle, neither of which a mock can prove. If a
// re-vendor changed either, the wave seeding in entity-provision.js would silently link sample rows
// to the wrong parents (or start failing again), so they are pinned here against the shipped bundle.
test('CONTRACT: seedRecordGraph resolves a bind against options.createdIds BY INDEX, and cannot resolve one into its own group', async () => {
const posts = [];
const client = {
get: async (url) => {
const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
if (meta) return { status: 200, headers: {}, body: { EntitySetName: `${meta[1]}s`, LogicalName: meta[1] } };
return { status: 200, headers: {}, body: { value: [] } };
},
post: async (url, body) => {
if (/CreateMultiple/.test(url)) {
posts.push(body);
const n = ((body && body.Targets) || []).length;
return { status: 200, headers: {}, body: { Ids: Array.from({ length: n }, (_, i) => `oid-${posts.length}-${i}`) } };
}
return { status: 204, headers: {}, body: {} };
},
patch: async () => ({ status: 204, headers: {}, body: {} }),
delete: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const sdk = await sdkWith(client);
const selfBind = { navProperty: 'new_ParentOrgId', parentEntity: 'new_org', parentIndex: 0 };
// (1) A self-bind whose parent is in the SAME group cannot resolve — the ids are published only
// after the group completes. This is the #544 failure, and it is a property of the SDK, not a bug
// in the plugin: it is why the plugin must split the rows into waves itself.
await assert.rejects(
sdk.seedRecordGraph([{ entityLogical: 'new_org', records: [{ body: { new_name: 'Root' }, binds: [] }, { body: { new_name: 'Child' }, binds: [selfBind] }] }], { createdIds: {} }),
/has no created id/,
'a same-group self-bind must still fail — the wave split is what makes it work'
);
// (2) The same bind DOES resolve when the parent id is supplied via options.createdIds, indexed
// by the parent's ORIGINAL position. A SPARSE array is what the plugin passes between waves
// (index 0 filled, later indices still empty), so the lookup must be positional, not dense.
const sparse = [];
sparse[0] = '11111111-1111-1111-1111-111111111111';
const res = await sdk.seedRecordGraph(
[{ entityLogical: 'new_org', records: [{ body: { new_name: 'Child' }, binds: [selfBind] }] }],
{ createdIds: { new_org: sparse } }
);
const target = posts[posts.length - 1].Targets[0];
assert.strictEqual(target['[email protected]'], `/new_orgs(${sparse[0]})`,
'the bind resolves to the id at options.createdIds[entity][parentIndex]');
assert.strictEqual(res.createdIds.new_org.length, 1, 'the returned ids cover only the rows in THIS call');
});
// These lock the four NEW behaviors the skill now wires: quick-create table flag, OData pagination,
// idempotent global choice, and authored-column full width. Each drives the real vendored bundle so a
// future re-vendor that regresses the behavior fails HERE (the mock-based engine tests can't catch it).
test('CONTRACT: updateTable({ quickCreateEnabled }) PUTs IsQuickCreateEnabled on the entity (the quick-create table flag)', async () => {
// The build's data-model phase calls sdk.updateTable(logical, { quickCreateEnabled: true }) to enable
// "Allow quick create" so an authored Quick Create form is reachable from the inline "+ New". The SDK
// GET-then-PUTs the full EntityDefinitions row with IsQuickCreateEnabled set (a plain Edm.Boolean flag).
const { client, reqs } = captureClient();
const sdk = await sdkWith(client);
await sdk.updateTable('contoso_widget', { quickCreateEnabled: true });
const put = reqs.find((r) => r.method === 'PUT' && /EntityDefinitions\(/i.test(r.url));
assert.ok(put, 'updateTable issues a PUT to EntityDefinitions');
assert.strictEqual(put.body && put.body.IsQuickCreateEnabled, true, 'the PUT body sets IsQuickCreateEnabled=true');
});
test('CONTRACT: queryRecords({ paginate:true }) follows @odata.nextLink to completion (full env-wide list, no single-page cap)', async () => {
// The cross-app page-sharing scan (sitemap-pages.js) enumerates EVERY appmodule with paginate:true so
// it can never miss an app past the ~5000-row server page. getAbsolute(nextLink) routes back through
// the injected httpClient.get, so page the result by inspecting the URL for the next-page marker.
const reqs = [];
const client = {
get: async (url) => {
reqs.push(url);
if (/EntityDefinitions\(LogicalName=/i.test(url)) return { status: 200, headers: {}, body: { EntitySetName: 'appmodules', LogicalName: 'appmodule' } };
if (/[?&]nextpage=1/.test(url)) return { status: 200, headers: {}, body: { value: [{ appmoduleid: 'a2' }] } };
return { status: 200, headers: {}, body: { value: [{ appmoduleid: 'a1' }], '@odata.nextLink': 'https://example.crm.dynamics.com/api/data/v9.0/appmodules?nextpage=1' } };
},
post: async () => ({ status: 204, headers: {}, body: {} }),
patch: async () => ({ status: 204, headers: {}, body: {} }),
delete: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const sdk = await sdkWith(client);
const rows = await sdk.queryRecords('appmodule', { select: ['appmoduleid'], paginate: true });
assert.deepStrictEqual(rows.map((r) => r.appmoduleid), ['a1', 'a2'], 'both pages are returned (nextLink was followed)');
assert.strictEqual(reqs.filter((u) => /appmodules/.test(u)).length, 2, 'exactly two data pages were fetched');
});
test('CONTRACT: queryRecords rejects paginate combined with top or fetchXml (both silently cap the result)', async () => {
// Dataverse honors $top as a hard cap and omits @odata.nextLink; FetchXML pages via a cookie, not
// @odata.nextLink. Either combined with paginate would silently return one page, so the SDK throws
// BEFORE any request — the scan must never pass top alongside paginate.
const { client } = captureClient();
const sdk = await sdkWith(client);
await assert.rejects(() => sdk.queryRecords('appmodule', { paginate: true, top: 1 }), /paginate.*top/i, 'paginate + top is rejected');
await assert.rejects(() => sdk.queryRecords('appmodule', { paginate: true, fetchXml: '<fetch/>' }), /paginate.*fetchXml|fetchXml.*paginate/i, 'paginate + fetchXml is rejected');
});
test('CONTRACT: queryRecords({ paginate:true }) THROWS on a malformed page instead of silently dropping rows', async () => {
// A well-formed OData collection page always carries `value` as an array (empty only on the last page).
// A missing/null/non-array `value` — or a bare-string `value` that `for..of` would iterate char-by-char
// — must fail LOUD (returning partial results silently under-counts, which is dangerous for the
// cross-app page scan and cascade-delete enumeration). Since the SDK's defect pass the single-page (non-paginate) path is
// just as strict: an absent collection is not an empty one, so a 2xx answer without `value` is a ConnectionError there too.
const meta = (url) => { const ln = (url.match(/LogicalName='([^']+)'/) || [])[1] || 'x'; return { status: 200, headers: {}, body: { MetadataId: '33333333-3333-3333-3333-333333333333', EntitySetName: `${ln}s`, LogicalName: ln } }; };
// (a) malformed MID-pagination: page 1 is a valid page + nextLink, page 2 has value:null → THROW (not page-1-only).
const midClient = {
get: async (url) => {
if (/EntityDefinitions\(LogicalName=/i.test(url)) return meta(url);
if (/[?&]np=1/.test(url)) return { status: 200, headers: {}, body: { value: null } };
return { status: 200, headers: {}, body: { value: [{ appmoduleid: 'a1' }], '@odata.nextLink': 'https://example.crm.dynamics.com/api/data/v9.0/appmodules?np=1' } };
},
post: async () => ({ status: 204, headers: {}, body: {} }), patch: async () => ({ status: 204, headers: {}, body: {} }), delete: async () => ({ status: 204, headers: {}, body: {} }), put: async () => ({ status: 204, headers: {}, body: {} }),
};
await assert.rejects(async () => (await sdkWith(midClient)).queryRecords('appmodule', { paginate: true }), /malformed page|value/i, 'a null mid-pagination value throws, not a silent page-1-only result');
// (b) bare-string `value` on the FIRST page → THROW (never fabricate single-char "rows" via for..of).
const strClient = {
get: async (url) => { if (/EntityDefinitions\(LogicalName=/i.test(url)) return meta(url); return { status: 200, headers: {}, body: { value: 'abc' } }; },
post: async () => ({ status: 204, headers: {}, body: {} }), patch: async () => ({ status: 204, headers: {}, body: {} }), delete: async () => ({ status: 204, headers: {}, body: {} }), put: async () => ({ status: 204, headers: {}, body: {} }),
};
await assert.rejects(async () => (await sdkWith(strClient)).queryRecords('appmodule', { paginate: true }), /malformed page|value/i, 'a bare-string value throws (no char-row fabrication)');
// (c) the single-page (non-paginate) path refuses a missing `value` too — never an empty result. It used to read it as empty.
const bodyOf = (body) => ({
get: async (url) => { if (/EntityDefinitions\(LogicalName=/i.test(url)) return meta(url); return { status: 200, headers: {}, body }; },
post: async () => ({ status: 204, headers: {}, body: {} }), patch: async () => ({ status: 204, headers: {}, body: {} }), delete: async () => ({ status: 204, headers: {}, body: {} }), put: async () => ({ status: 204, headers: {}, body: {} }),
});
await assert.rejects(async () => (await sdkWith(bodyOf({}))).queryRecords('appmodule', {}), (e) => e && e.code === 'CONNECTION_ERROR' && /malformed page/.test(e.message), 'a missing value is a ConnectionError, not an empty result');
await assert.rejects(async () => (await sdkWith(bodyOf({ value: 'abc' }))).queryRecords('appmodule', {}), (e) => e && e.code === 'CONNECTION_ERROR' && /malformed page/.test(e.message), 'and so is a value that is not an array');
// A well-formed EMPTY page is an empty result: the only absence there is.
assert.deepStrictEqual(await (await sdkWith(bodyOf({ value: [] }))).queryRecords('appmodule', {}), [], 'a well-formed empty page is still an empty result');
});
test('CONTRACT: createGlobalOptionSet is idempotent by Name — reuses an existing set (no duplicate POST), fixing rebuild id-loss', async () => {
// On a rebuild the option set already exists. The SDK probes GlobalOptionSetDefinitions(Name=...) and
// REUSES the existing MetadataId instead of a duplicate-Name POST that would fail — so the engine
// captures the id and columns bind to it (the old behavior lost the id and fell back to inline options).
const reqs = [];
const existingClient = {
get: async (url) => {
reqs.push({ method: 'GET', url });
if (/GlobalOptionSetDefinitions\(Name=/i.test(url)) return { status: 200, headers: {}, body: { MetadataId: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' } };
return { status: 200, headers: {}, body: { value: [] } };
},
post: async (url, body) => { reqs.push({ method: 'POST', url, body }); return { status: 204, headers: { 'odata-entityid': 'https://x/y(bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb)' }, body: {} }; },
patch: async () => ({ status: 204, headers: {}, body: {} }),
delete: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const reuseSdk = await sdkWith(existingClient);
const reused = await reuseSdk.createGlobalOptionSet({ name: 'new_sev', displayName: 'Sev', options: [{ value: 100000000, label: 'Low' }] });
assert.strictEqual(reused.metadataId, 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'the existing set MetadataId is returned');
assert.strictEqual(reqs.filter((r) => r.method === 'POST').length, 0, 'no duplicate-Name POST is issued when the set already exists');
// Absent (404 probe) → a normal create POST happens.
const created = [];
const absentClient = {
get: async (url) => { if (/GlobalOptionSetDefinitions\(Name=/i.test(url)) return { status: 404, headers: {}, body: {} }; return { status: 200, headers: {}, body: { value: [] } }; },
post: async (url, body) => { created.push({ url, body }); return { status: 204, headers: { 'odata-entityid': 'https://x/y(cccccccc-cccc-cccc-cccc-cccccccccccc)' }, body: {} }; },
patch: async () => ({ status: 204, headers: {}, body: {} }),
delete: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const freshSdk2 = await sdkWith(absentClient);
await freshSdk2.createGlobalOptionSet({ name: 'new_sev', displayName: 'Sev', options: [{ value: 100000000, label: 'Low' }] });
assert.strictEqual(created.length, 1, 'an absent set (404 probe) is created with one POST');
assert.ok(/GlobalOptionSetDefinitions/i.test(created[0].url), 'the create POSTs to GlobalOptionSetDefinitions');
});
// --- Security authoring surface -----------------------------------------------
test('CONTRACT: the vendored facade exposes the security-authoring methods the engine calls', async () => {
const sdk = await freshSdk();
for (const m of ['createPersonaRole', 'createSecurityRole', 'deleteSecurityRole', 'associateRecords']) {
assert.strictEqual(typeof sdk[m], 'function', `facade must expose ${m}()`);
}
});
test('CONTRACT: the vendored bundle still carries the exact SDK role-ownership marker the plugin hardcodes', () => {
// teardown + verify re-implement the SEC-1 ownership guard by string-matching this marker (the SDK
// does not export it). If a re-vendored bundle changes the marker text, teardown would stop
// recognizing its own roles (leak) and verify would false-fail — so pin the exact string here.
const { SDK_ROLE_MARKER } = require('../lib/app-spec.js');
const bundle = fs.readFileSync(BUNDLE, 'utf8');
assert.ok(bundle.includes(SDK_ROLE_MARKER), `the vendored bundle must contain the role marker '${SDK_ROLE_MARKER}'`);
});
// A custom nav glyph — and the download->build round-trip — depend on a PLATFORM-REF `VectorIcon`
// surviving serialization onto an ENTITY subarea. Reading the minified bundle cannot prove that; only
// the serialized payload can, so assert the bytes the SDK would POST.
test('CONTRACT: a platform-ref VectorIcon on an Entity subarea reaches the serialized sitemap XML', async () => {
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
const { appDef } = require('../lib/sdk-build.js');
const { buildSmokeSpec } = require('../smoke-eval.js');
const spec = buildSmokeSpec('t');
const def = appDef(spec, { forms: {}, views: {}, charts: {}, dashboards: {}, pages: {} });
let sitemapXml = '';
const TABLE_METADATA_ID = '22222222-2222-2222-2222-222222222222';
// The push resolves each sitemap table to an OData reference and reads the pinned components back,
// both fail-closed — answer those reads (same shape as the escaping contract above) so an unrelated
// refusal cannot masquerade as an icon-serialization failure.
const httpClient = {
get: async (url) => {
const m = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
if (m) return { status: 200, headers: {}, body: { LogicalName: m[1], MetadataId: TABLE_METADATA_ID, EntitySetName: `${m[1]}s` } };
if (/\/appmodulecomponents/.test(url)) return { status: 200, headers: {}, body: { value: [{ objectid: TABLE_METADATA_ID, componenttype: 1 }] } };
if (/\/appmodules/.test(url)) {
const row = { appmoduleid: '11111111-1111-1111-1111-111111111111', appmoduleidunique: '33333333-3333-3333-3333-333333333333' };
return { status: 200, headers: {}, body: /RetrieveUnpublishedMultiple/i.test(url) ? { value: [row] } : row };
}
return { status: 200, headers: {}, body: {} };
},
post: async (url, body) => {
if (/\/sitemaps\b/.test(url) && body && body.sitemapxml) sitemapXml = String(body.sitemapxml);
return { status: 204, headers: { 'odata-entityid': 'https://x/y(11111111-1111-1111-1111-111111111111)' }, body: {} };
},
patch: async () => ({ status: 204, headers: {}, body: {} }),
delete: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(mkTempWorkspace('sdk-vecicon-')), instanceUrl: 'https://example.crm.dynamics.com', httpClient });
await sdk.initWorkspace();
const art = await sdk.createArtifact('app', { name: spec.app.name, uniqueName: 'new_vecapp', description: '', siteMap: def.siteMap, components: def.components, iconWebResourceId: APP_ICON_ID });
await assert.doesNotReject(sdk.pushArtifact('app', art.id), 'the smoke spec must push without a component-verification refusal');
assert.ok(sitemapXml, 'the sitemap was serialized and posted');
assert.match(sitemapXml, /<SubArea[^>]*Entity="new_torder"[^>]*VectorIcon="\/WebResources\/new_tvec\.svg"/, 'platform-ref VectorIcon is serialized onto the Entity subarea');
// The bare token is absent only because appDef already removed it — asserting that here would
// re-test appDef, not the bundle. The test below establishes what the BUNDLE actually does.
assert.ok(!/VectorIcon="Grid"/.test(sitemapXml), 'appDef removed the bare token before the payload reached the SDK');
});
// Establishes WHERE the bare-Fluent-token guard lives, by pushing a hand-built siteMap that bypasses
// appDef entirely. The vendored SDK happily serializes `VectorIcon="Grid"` onto an Entity subarea —
// it has no such guard — which is exactly why `appDef` must drop it (lib/sdk-build.js) and why the
// drop cannot be delegated to the bundle. If a future re-vendor ADDS a guard, this test fails and
// tells us the defense moved, rather than silently leaving two layers that both assume the other.
test('CONTRACT: the vendored SDK does NOT filter a bare Fluent VectorIcon — appDef is the only guard', async () => {
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
let sitemapXml = '';
const TABLE_METADATA_ID = '22222222-2222-2222-2222-222222222222';
const httpClient = {
get: async (url) => {
const m = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
if (m) return { status: 200, headers: {}, body: { LogicalName: m[1], MetadataId: TABLE_METADATA_ID, EntitySetName: `${m[1]}s` } };
if (/\/appmodulecomponents/.test(url)) return { status: 200, headers: {}, body: { value: [{ objectid: TABLE_METADATA_ID, componenttype: 1 }] } };
if (/\/appmodules/.test(url)) {
const row = { appmoduleid: '11111111-1111-1111-1111-111111111111', appmoduleidunique: '33333333-3333-3333-3333-333333333333' };
return { status: 200, headers: {}, body: /RetrieveUnpublishedMultiple/i.test(url) ? { value: [row] } : row };
}
return { status: 200, headers: {}, body: {} };
},
post: async (url, body) => { if (/\/sitemaps\b/.test(url) && body && body.sitemapxml) sitemapXml = String(body.sitemapxml); return { status: 204, headers: { 'odata-entityid': 'https://x/y(11111111-1111-1111-1111-111111111111)' }, body: {} }; },
patch: async () => ({ status: 204, headers: {}, body: {} }),
delete: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
};
const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(mkTempWorkspace('sdk-vecraw-')), instanceUrl: 'https://example.crm.dynamics.com', httpClient });
await sdk.initWorkspace();
const siteMap = { areas: [{ id: 'area_0', title: 'Main', groups: [{ id: 'g0', title: 'G', subAreas: [
{ id: 's0', title: 'Orders', type: 'Entity', entity: 'new_torder', vectorIcon: 'Grid' },
] }] }] };
const art = await sdk.createArtifact('app', { name: 'Raw Token', uniqueName: 'new_rawtoken', description: '', siteMap, components: { forms: [], views: [], charts: [] }, iconWebResourceId: APP_ICON_ID });
await sdk.pushArtifact('app', art.id);
assert.match(sitemapXml, /<SubArea[^>]*Entity="new_torder"[^>]*VectorIcon="Grid"/, 'the bundle serializes a bare token when handed one — so the plugin must not hand it one');
});
test('CONTRACT: vendored publishArtifact RESOLVES with publish.kind on failure — it does NOT throw', async () => {
// This is the contract whose change slipped through unnoticed. The SDK moved publishArtifact from
// throwing to reporting by value; the engine discarded the result at all nine call sites, so every
// publish failure became invisible and `ok: true` was reported anyway. There was a method-PRESENCE
// guard for publishArtifact but no BEHAVIOURAL one, which is exactly the gap that let it land.
//
// A throw would also silently re-arm the transient-retry path, and a by-value failure would silently
// disarm it, so which one the bundle does is load-bearing and must be pinned rather than assumed.
const client = {
get: async (url) => {
if (/EntityDefinitions\(LogicalName=/i.test(url)) {
const ln = (url.match(/LogicalName='([^']+)'/) || [])[1] || 'x';
return { status: 200, headers: {}, body: { MetadataId: '33333333-3333-3333-3333-333333333333', EntitySetName: `${ln}s`, LogicalName: ln, PrimaryIdAttribute: `${ln}id`, PrimaryNameAttribute: 'name', SchemaName: ln, IsCustomEntity: true, ObjectTypeCode: 10001 } };
}
if (/\/systemforms\(/.test(url)) return { status: 200, headers: {}, body: { '@odata.etag': 'W/"1"', formid: FID, formxml: '<form/>', name: 'F', objecttypecode: 'account', type: 2 } };
return { status: 200, headers: {}, body: { value: [] } };
},
// Only PublishXml fails; everything else succeeds, so this isolates the publish half.
post: async (url) => (/PublishXml/i.test(url)
? { status: 500, headers: {}, body: { error: { message: 'PublishXml exploded' } } }
: { status: 204, headers: {}, body: {} }),
patch: async () => ({ status: 204, headers: {}, body: {} }),
put: async () => ({ status: 204, headers: {}, body: {} }),
delete: async () => ({ status: 204, headers: {}, body: {} }),
postRaw: async () => ({ status: 200, headers: {}, body: '' }),
};
const FID = '11111111-1111-1111-1111-111111111111';
const sdk = await sdkWith(client);
await sdk.fetchArtifact('form', FID);
let threw = null;
let result = null;
try { result = await sdk.publishArtifact('form', FID); } catch (e) { threw = e; }
assert.strictEqual(threw, null, 'publishArtifact must RESOLVE on a failed publish, not throw — the engine reads the result');
assert.ok(result && typeof result === 'object', 'it returns a structured result');
assert.ok(result.publish && result.publish.kind === 'failed', `publish.kind must be 'failed'; got ${JSON.stringify(result.publish)}`);
assert.strictEqual(result.shipped, false, 'a failed publish is not shipped');
});