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(mobile-apps): correct Dataverse generation contracts (#526)
Shubham Agarwalb0f09ffd4c62
diff --git a/plugins/mobile-apps/scripts/build-dataverse-operation-manifest.js b/plugins/mobile-apps/scripts/build-dataverse-operation-manifest.jsindex ff79f30fb..407d0ed89 100644--- a/plugins/mobile-apps/scripts/build-dataverse-operation-manifest.js+++ b/plugins/mobile-apps/scripts/build-dataverse-operation-manifest.js@@ -51,6 +51,8 @@ const DERIVED_COLUMN_TYPES = new Set(['computed',]);const NULL_SOURCE_TYPE_IS_ORDINARY_TYPES = new Set([+ 'file',+ 'image','lookup','memo','multiline',@@ -1083,10 +1085,10 @@ function expectedColumnConstraints(column) {constraints.push(['defaultValue', Boolean(column.defaultValue), 'DefaultValue']);} else if (type === 'image') {constraints.push(- ['maxHeight', Number(column.maxHeight ?? 1440), 'MaxHeight',- (actual, expected) => Number(actual) >= expected],- ['maxWidth', Number(column.maxWidth ?? 1440), 'MaxWidth',+ ['maxSizeInKB', Number(column.maxSizeInKB ?? 10240), 'MaxSizeInKB',(actual, expected) => Number(actual) >= expected],+ ['canStoreFullImage', column.canStoreFullImage !== false, 'CanStoreFullImage',+ (actual, expected) => Boolean(actual) === expected],);} else if (type === 'file') {constraints.push(@@ -1215,6 +1217,33 @@ function columnCompatibility(tableName, column, liveColumn) {return compared;}+function imageConfigurationUpdate(column, liveColumn, comparison) {+ if (normalizeColumnType(column.type) !== 'image'+ || !['create', 'adapt'].includes(column.plannedDecision)+ || !liveColumn?.customizable+ || !liveColumn.imageUpdateDefinition+ || !comparison?.reasons?.length+ || !comparison.reasons.every((reason) => (+ reason.startsWith('CanStoreFullImage mismatch:')+ || reason.startsWith('MaxSizeInKB mismatch:')+ ))) {+ return null;+ }+ const payload = stableClone(liveColumn.imageUpdateDefinition);+ const metadataId = payload.MetadataId || liveColumn.metadataId;+ if (!metadataId || !payload.LogicalName || !payload.SchemaName) return null;+ delete payload['@odata.context'];+ delete payload['@odata.etag'];+ payload['@odata.type'] = 'Microsoft.Dynamics.CRM.ImageAttributeMetadata';+ payload.MetadataId = metadataId;+ payload.CanStoreFullImage = column.canStoreFullImage !== false;+ payload.MaxSizeInKB = Math.max(+ Number(payload.MaxSizeInKB || liveColumn.maxSizeInKB || 0),+ Number(column.maxSizeInKB || 10240),+ );+ return payload;+}+function columnPayload(column, effectiveLogicalName = column.logicalName) {const type = normalizeColumnType(column.type);const schemaName = column.adaptedSchemaName@@ -1327,8 +1356,11 @@ function columnPayload(column, effectiveLogicalName = column.logicalName) {return {'@odata.type': 'Microsoft.Dynamics.CRM.ImageAttributeMetadata',...common,- MaxHeight: Number(column.maxHeight || 1440),- MaxWidth: Number(column.maxWidth || 1440),+ MaxSizeInKB: Number(column.maxSizeInKB || 10240),+ CanStoreFullImage: column.canStoreFullImage !== false,+ ...(column.isPrimaryImage === undefined+ ? {}+ : { IsPrimaryImage: Boolean(column.isPrimaryImage) }),};}if (type === 'file') {@@ -1629,18 +1661,33 @@ function keyExists(key, snapshotTable, aliases, effectiveTable) {};}-function operation(index, id, phase, apiPath, body, solution) {+function operation(index, id, phase, apiPath, body, solution, method = 'POST') {return {index,id,phase,- method: 'POST',+ method,apiPath,body,solution,};}+function isImageConfigurationPut(item) {+ return item?.method === 'PUT'+ && item?.phase === 'extensions'+ && /^configure-image:[a-z0-9_]+:[a-z0-9_]+$/.test(String(item.id || ''))+ && /^EntityDefinitions\(LogicalName='[a-z0-9_]+'\)\/Attributes\(LogicalName='[a-z0-9_]+'\)$/.test(+ String(item.apiPath || ''),+ )+ && item.body?.['@odata.type'] === 'Microsoft.Dynamics.CRM.ImageAttributeMetadata'+ && typeof item.body?.MetadataId === 'string'+ && typeof item.body?.LogicalName === 'string'+ && typeof item.body?.SchemaName === 'string'+ && typeof item.body?.CanStoreFullImage === 'boolean'+ && Number.isInteger(Number(item.body?.MaxSizeInKB));+}+function xmlEscape(value) {return String(value).replace(/&/g, '&')@@ -1793,6 +1840,7 @@ function operationAffectedPublishTables(operation) {return [logicalNameFromSchemaName(operation.body?.SchemaName)];}if (String(operation?.id || '').startsWith('extend-column:')+ || String(operation?.id || '').startsWith('configure-image:')|| String(operation?.id || '').startsWith('create-key:')) {const match = String(operation.apiPath || '').match(/EntityDefinitions\(LogicalName='([^']+)'\)/,@@ -2509,6 +2557,7 @@ function buildManifest({);const canExtend = Boolean(live.detail.customizable && live.detail.canCreateAttributes);const createColumns = [];+ const imageConfigurationUpdates = [];let tableHasUnverified = false;let tableHasDeferred = false;@@ -2589,6 +2638,27 @@ function buildManifest({}continue;}+ const imageUpdatePayload = item.liveColumn+ ? imageConfigurationUpdate(column, item.liveColumn, item.comparison)+ : null;+ if (imageUpdatePayload) {+ imageConfigurationUpdates.push({+ column,+ effectiveLogicalName: columnTarget,+ payload: imageUpdatePayload,+ });+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: column.plannedDecision,+ operation: `configure-image:${effectiveName}:${columnTarget}`,+ reason: 'existing image column requires approved full-image configuration',+ }));+ continue;+ }if (!item.liveColumn) {if (normalizeColumnType(column.type) === 'lookup') {if (@@ -2738,10 +2808,24 @@ function buildManifest({));publishTables.add(effectiveName);}+ for (const update of imageConfigurationUpdates.sort((left, right) => (+ left.effectiveLogicalName.localeCompare(right.effectiveLogicalName)+ ))) {+ phaseOperations.extensions.push(operation(+ nextIndex++,+ `configure-image:${effectiveName}:${update.effectiveLogicalName}`,+ 'extensions',+ `EntityDefinitions(LogicalName='${effectiveName}')/Attributes(LogicalName='${update.effectiveLogicalName}')`,+ update.payload,+ context.solutionUniqueName,+ 'PUT',+ ));+ publishTables.add(effectiveName);+ }const tableDecision = tableHasUnverified? 'unverified'- : createColumns.length > 0+ : createColumns.length > 0 || imageConfigurationUpdates.length > 0? 'extend': table.plannedDecision === 'adapt'? 'adapt'@@ -2752,11 +2836,13 @@ function buildManifest({requestedName,effectiveName,decision: tableDecision,- operation: createColumns.length > 0 ? 'extensions-phase' : 'none',+ operation: createColumns.length > 0 || imageConfigurationUpdates.length > 0+ ? 'extensions-phase'+ : 'none',reason: tableHasUnverified? 'one or more columns remain unverified'- : createColumns.length > 0- ? `${createColumns.length} missing ordinary column(s) will be extended`+ : createColumns.length > 0 || imageConfigurationUpdates.length > 0+ ? `${createColumns.length} missing column(s) and ${imageConfigurationUpdates.length} image configuration update(s) will be applied`: tableHasDeferred? 'compatible table reused; unsupported additions are explicitly deferred': incompatible.length > 0@@ -3305,7 +3391,9 @@ function buildManifest({summary: {decisionCount: decisions.length,metadataOperationCount: operations.length,- metadataWriteCount: operations.filter((item) => item.method === 'POST').length,+ metadataWriteCount: operations.filter(+ (item) => ['POST', 'PUT', 'PATCH', 'DELETE'].includes(item.method),+ ).length,unresolvedCount: unverified.length,unverifiedCount: unverifiedFacts.length,conflictCount: conflicts.length,@@ -3495,8 +3583,11 @@ function validateManifest(manifest, {if (item.phase !== item.enclosingPhase) {errors.push(`operation ${item.id} phase does not match its container`);}- if (item.method !== 'POST') errors.push(`operation ${item.id} is not a POST`);- if (['DELETE', 'PATCH', 'PUT'].includes(item.method)) {+ if (item.method !== 'POST' && !isImageConfigurationPut(item)) {+ errors.push(`operation ${item.id} uses an unsupported method`);+ }+ if (['DELETE', 'PATCH'].includes(item.method)+ || (item.method === 'PUT' && !isImageConfigurationPut(item))) {errors.push(`operation ${item.id} is destructive or mutating in-place`);}}diff --git a/plugins/mobile-apps/scripts/create-dataverse-snapshot.js b/plugins/mobile-apps/scripts/create-dataverse-snapshot.jsindex 26f476370..b5fa2b2cf 100644--- a/plugins/mobile-apps/scripts/create-dataverse-snapshot.js+++ b/plugins/mobile-apps/scripts/create-dataverse-snapshot.js@@ -74,7 +74,13 @@ const ORDINARY_METADATA_FIELDS_BY_TYPE = {DecimalAttributeMetadata: ['MinValue', 'MaxValue', 'Precision'],DoubleAttributeMetadata: ['MinValue', 'MaxValue', 'Precision'],FileAttributeMetadata: ['MaxSizeInKB'],- ImageAttributeMetadata: ['MaxHeight', 'MaxWidth', 'MaxSizeInKB'],+ ImageAttributeMetadata: [+ 'CanStoreFullImage',+ 'IsPrimaryImage',+ 'MaxHeight',+ 'MaxWidth',+ 'MaxSizeInKB',+ ],IntegerAttributeMetadata: ['MinValue', 'MaxValue', 'Format'],MemoAttributeMetadata: ['MaxLength', 'Format'],MoneyAttributeMetadata: ['MinValue', 'MaxValue', 'Precision', 'PrecisionSource'],@@ -770,12 +776,15 @@ async function loadDetailedEntity(request, entity) {}const ordinaryConstraints = new Map();+ const imageUpdateDefinitions = new Map();const ordinaryTypes = [...new Set(attributes.map(ordinaryMetadataType).filter(Boolean))];for (const type of ordinaryTypes) {const fields = ORDINARY_METADATA_FIELDS_BY_TYPE[type];const metadata = await requestCollection(request,- `${root}/Attributes/Microsoft.Dynamics.CRM.${type}?$select=LogicalName,${fields.join(',')}`,+ type === 'ImageAttributeMetadata'+ ? `${root}/Attributes/Microsoft.Dynamics.CRM.${type}`+ : `${root}/Attributes/Microsoft.Dynamics.CRM.${type}?$select=LogicalName,${fields.join(',')}`,`${logicalName} ${type} ordinary metadata`,);for (const item of metadata) {@@ -786,6 +795,9 @@ async function loadDetailedEntity(request, entity) {}}ordinaryConstraints.set(item.LogicalName, constraints);+ if (type === 'ImageAttributeMetadata') {+ imageUpdateDefinitions.set(item.LogicalName, item);+ }}}@@ -911,6 +923,7 @@ async function loadDetailedEntity(request, entity) {columns: attributes.map((attribute) => {const computed = computedMetadata.get(attribute.LogicalName) || null;return {+ metadataId: attribute.MetadataId || null,logicalName: attribute.LogicalName,schemaName: attribute.SchemaName,type: canonicalAttributeType(@@ -943,6 +956,9 @@ async function loadDetailedEntity(request, entity) {attributeOf: attribute.AttributeOf || null,}: null,+ ...(imageUpdateDefinitions.has(attribute.LogicalName)+ ? { imageUpdateDefinition: imageUpdateDefinitions.get(attribute.LogicalName) }+ : {}),};}),manyToOneRelationships: manyToOneRelationships.map((relationship) => ({diff --git a/plugins/mobile-apps/scripts/dataverse-request.js b/plugins/mobile-apps/scripts/dataverse-request.jsindex f47fff22f..ebec88eac 100644--- a/plugins/mobile-apps/scripts/dataverse-request.js+++ b/plugins/mobile-apps/scripts/dataverse-request.js@@ -56,6 +56,9 @@ const fs = require('node:fs');const path = require('node:path');const { getAuthToken, makeRequest } = require('./lib/validation-helpers');+const READ_REQUEST_TIMEOUT_MS = 30000;+const MUTATION_REQUEST_TIMEOUT_MS = 120000;+function retryAfterDelayMs(retryAfter, fallbackMs, nowMs = Date.now()) {const safeFallback = Number.isFinite(fallbackMs) && fallbackMs >= 0? fallbackMs@@ -177,7 +180,9 @@ async function doRequest(envUrl, method, apiPath, body, token, includeHeaders, sheaders,body,includeHeaders,- timeout: 30000,+ timeout: isMutationMethod(method)+ ? MUTATION_REQUEST_TIMEOUT_MS+ : READ_REQUEST_TIMEOUT_MS,});return res;@@ -1062,6 +1067,8 @@ function extractGuid(headerValue) {if (require.main === module) main();module.exports = {+ MUTATION_REQUEST_TIMEOUT_MS,+ READ_REQUEST_TIMEOUT_MS,createDataverseRequestExecutor,doRequest,extractGuid,diff --git a/plugins/mobile-apps/scripts/tests/dataverse-operation-manifest.test.js b/plugins/mobile-apps/scripts/tests/dataverse-operation-manifest.test.jsindex 8f8c5b1c5..774bb9949 100644--- a/plugins/mobile-apps/scripts/tests/dataverse-operation-manifest.test.js+++ b/plugins/mobile-apps/scripts/tests/dataverse-operation-manifest.test.js@@ -45,7 +45,7 @@ function column(logicalName, type = 'String', overrides = {}) {precision: 2,},File: { maxSizeInKB: 32768 },- Image: { maxHeight: 1440, maxWidth: 1440 },+ Image: { maxHeight: 144, maxWidth: 144, maxSizeInKB: 10240, canStoreFullImage: true },Integer: { minValue: -2147483648, maxValue: 2147483647, format: 'None' },Memo: { maxLength: 10000, format: 'TextArea' },Money: {@@ -1096,8 +1096,8 @@ test('existing Dataverse File and Image virtual attributes are zero-write compatcontractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),contractColumn('cr1_document', 'file', 'create', { maxSizeInKB: 32768 }),contractColumn('cr1_photo', 'image', 'create', {- maxHeight: 1440,- maxWidth: 1440,+ maxSizeInKB: 10240,+ canStoreFullImage: true,}),]),],@@ -1110,8 +1110,10 @@ test('existing Dataverse File and Image virtual attributes are zero-write compat}),column('cr1_photo', 'Virtual', {typeName: 'ImageType',- maxHeight: 1440,- maxWidth: 1440,+ maxHeight: 144,+ maxWidth: 144,+ maxSizeInKB: 10240,+ canStoreFullImage: true,}),]);const manifest = buildManifest(buildInputs(contract, snapshot({@@ -1147,6 +1149,70 @@ test('existing Dataverse File and Image virtual attributes are zero-write compat}});+test('existing image full-size configuration is repaired once with a full-definition PUT', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [contractTable('cr1_item', 'extend', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ contractColumn('cr1_photo', 'image', 'create', {+ maxSizeInKB: 10240,+ canStoreFullImage: true,+ }),+ ])],+ };+ const imageDefinition = {+ MetadataId: '11111111-1111-1111-1111-111111111111',+ LogicalName: 'cr1_photo',+ SchemaName: 'cr1_photo',+ AttributeType: 'Virtual',+ AttributeTypeName: { Value: 'ImageType' },+ RequiredLevel: { Value: 'None' },+ MaxHeight: 144,+ MaxWidth: 144,+ MaxSizeInKB: 10240,+ CanStoreFullImage: false,+ };+ const existing = table('cr1_item', [+ column('cr1_name', 'String', { primaryName: true }),+ column('cr1_photo', 'Virtual', {+ metadataId: imageDefinition.MetadataId,+ typeName: 'ImageType',+ sourceType: null,+ customizable: true,+ maxHeight: 144,+ maxWidth: 144,+ maxSizeInKB: 10240,+ canStoreFullImage: false,+ imageUpdateDefinition: imageDefinition,+ }),+ ]);+ const repair = buildManifest(buildInputs(contract, snapshot({ tables: [existing] })));+ const update = repair.execution.phases[1].operations[0];++ assert.equal(repair.executable, true);+ assert.equal(repair.summary.metadataOperationCount, 2);+ assert.equal(update.id, 'configure-image:cr1_item:cr1_photo');+ assert.equal(update.method, 'PUT');+ assert.equal(+ update.apiPath,+ "EntityDefinitions(LogicalName='cr1_item')/Attributes(LogicalName='cr1_photo')",+ );+ assert.equal(update.body.MetadataId, imageDefinition.MetadataId);+ assert.equal(update.body.CanStoreFullImage, true);+ assert.equal(update.body.MaxHeight, 144);+ assert.equal(update.body.MaxWidth, 144);+ assert.equal(repair.execution.phases[4].operations.length, 1);++ const configured = structuredClone(existing);+ const configuredImage = configured.columns.find((item) => item.logicalName === 'cr1_photo');+ configuredImage.canStoreFullImage = true;+ configuredImage.imageUpdateDefinition.CanStoreFullImage = true;+ const rerun = buildManifest(buildInputs(contract, snapshot({ tables: [configured] })));+ assert.equal(rerun.executable, true);+ assert.equal(rerun.summary.metadataOperationCount, 0);+});+test('mechanical reconciliation never changes approved architecture decisions', () => {const contract = createContract();const manifest = buildManifest(buildInputs(contract, fullyAppliedSnapshot()));diff --git a/plugins/mobile-apps/scripts/tests/dataverse-planning-snapshot.test.js b/plugins/mobile-apps/scripts/tests/dataverse-planning-snapshot.test.jsindex 697a7b2aa..d3b38ea41 100644--- a/plugins/mobile-apps/scripts/tests/dataverse-planning-snapshot.test.js+++ b/plugins/mobile-apps/scripts/tests/dataverse-planning-snapshot.test.js@@ -925,6 +925,47 @@ test('computed metadata is explicitly unavailable when SourceTypeMask cannot beassert.match(computed.unavailableReason, /SourceTypeMask unavailable or malformed/);});+test('image metadata preserves full-image settings and its complete update definition', async () => {+ const imageDefinition = {+ MetadataId: 'image-id',+ LogicalName: 'new_photo',+ SchemaName: 'new_Photo',+ AttributeType: 'Virtual',+ AttributeTypeName: { Value: 'ImageType' },+ RequiredLevel: { Value: 'None' },+ MaxHeight: 144,+ MaxWidth: 144,+ MaxSizeInKB: 10240,+ CanStoreFullImage: false,+ IsPrimaryImage: false,+ };+ const table = await loadDetailedEntity(async (_method, apiPath) => {+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 200, data: { value: [{+ ...imageDefinition,+ IsCustomAttribute: true,+ IsManaged: false,+ IsCustomizable: { Value: true },+ IsValidForCreate: true,+ IsValidForRead: true,+ IsValidForUpdate: true,+ }] } };+ }+ if (apiPath.includes('ImageAttributeMetadata')) {+ return { status: 200, data: { value: [imageDefinition] } };+ }+ return { status: 200, data: { value: [] } };+ }, entity('new_issue', 'Issue'));++ const image = table.columns[0];+ assert.equal(image.metadataId, 'image-id');+ assert.equal(image.canStoreFullImage, false);+ assert.equal(image.maxSizeInKB, 10240);+ assert.equal(image.maxHeight, 144);+ assert.equal(image.maxWidth, 144);+ assert.deepEqual(image.imageUpdateDefinition, imageDefinition);+});+test('CLI request creation initializes one long-lived executor for the snapshot phase', async () => {let executorCreations = 0;let requests = 0;diff --git a/plugins/mobile-apps/scripts/tests/dataverse-request-metadata-batch.test.js b/plugins/mobile-apps/scripts/tests/dataverse-request-metadata-batch.test.jsindex 57b3bd0f6..1195a6a37 100644--- a/plugins/mobile-apps/scripts/tests/dataverse-request-metadata-batch.test.js+++ b/plugins/mobile-apps/scripts/tests/dataverse-request-metadata-batch.test.js@@ -11,6 +11,8 @@ const execFileAsync = promisify(execFile);const scriptPath = path.resolve(__dirname, '..', 'dataverse-request.js');const fakeAzPreload = path.join(__dirname, 'helpers', 'fake-az-preload.js');const {+ MUTATION_REQUEST_TIMEOUT_MS,+ READ_REQUEST_TIMEOUT_MS,createDataverseRequestExecutor,looksLikeDuplicate,operationFingerprint,@@ -22,6 +24,11 @@ const {validateJournalOperations,} = require('../dataverse-request');+test('metadata mutations allow longer server processing than reads', () => {+ assert.equal(READ_REQUEST_TIMEOUT_MS, 30000);+ assert.equal(MUTATION_REQUEST_TIMEOUT_MS, 120000);+});+function manifestStableJson(value) {function clone(item) {if (Array.isArray(item)) return item.map(clone);diff --git a/plugins/mobile-apps/scripts/tests/power-apps-cli-dataverse-contract.live.test.js b/plugins/mobile-apps/scripts/tests/power-apps-cli-dataverse-contract.live.test.jsnew file mode 100644index 000000000..0d4286ad8--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/power-apps-cli-dataverse-contract.live.test.js@@ -0,0 +1,85 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');+const test = require('node:test');++const { verifyDataverseServices } = require('../verify-dataverse-services');++const environmentId = process.env.POWER_APPS_LIVE_DATAVERSE_ENVIRONMENT_ID;+const environmentUrl = process.env.POWER_APPS_LIVE_DATAVERSE_URL;+const defaultCli = path.resolve(__dirname, '..', '..', 'template', 'node_modules', '.bin', 'power-apps');+const cliBin = process.env.POWER_APPS_LIVE_CLI_BIN || defaultCli;+const skipReason = environmentId && environmentUrl && fs.existsSync(cliBin)+ ? false+ : 'set Dataverse environment variables and POWER_APPS_LIVE_CLI_BIN';++function runCli(cwd, args) {+ const result = spawnSync(+ cliBin,+ args,+ { cwd, encoding: 'utf8', timeout: 90000, killSignal: 'SIGKILL' },+ );+ assert.equal(+ result.status,+ 0,+ `${args[0]} failed: ${result.stderr || result.stdout}`,+ );+ return result;+}++test('pinned Power Apps CLI emits a verifiable Dataverse service contract', {+ skip: skipReason,+ timeout: 210000,+}, (testContext) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'power-apps-dataverse-contract-'));+ testContext.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const templatePackage = JSON.parse(fs.readFileSync(path.resolve(+ __dirname,+ '..',+ '..',+ 'template',+ 'package.json',+ ), 'utf8'));+ const version = templatePackage.devDependencies['@microsoft/power-apps-cli'];+ assert.match(version, /^\d+\.\d+\.\d+$/);+ assert.equal(runCli(root, ['--version']).stdout.trim(), version);++ runCli(root, [+ 'init',+ '--non-interactive',+ '--environment-id',+ environmentId,+ '--app-type',+ 'MobileApp',+ '--display-name',+ 'Power Apps Dataverse Contract Probe',+ '--build-path',+ './dist',+ '--file-entry-point',+ 'index.html',+ '--app-url',+ 'http://localhost:8081',+ '--json',+ ]);+ runCli(root, [+ 'add-data-source',+ '--non-interactive',+ '--api-id',+ 'dataverse',+ '--org-url',+ environmentUrl,+ '--resource-name',+ 'systemuser',+ '--json',+ ]);++ const services = verifyDataverseServices(root, ['systemuser']);+ assert.equal(services.length, 1);+ assert.equal(services[0].logicalName, 'systemuser');+ assert.equal(services[0].entitySetName, 'systemusers');+ assert.equal(services[0].serviceFile, 'SystemusersService.ts');+});diff --git a/plugins/mobile-apps/scripts/tests/verify-dataverse-services.test.js b/plugins/mobile-apps/scripts/tests/verify-dataverse-services.test.jsnew file mode 100644index 000000000..a9505ba56--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/verify-dataverse-services.test.js@@ -0,0 +1,120 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const test = require('node:test');++const {+ configuredDataSources,+ verifyDataverseServices,+} = require('../verify-dataverse-services');++function project(testContext) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'verify-dataverse-services-'));+ testContext.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'src', 'generated', 'services'), { recursive: true });+ return root;+}++function writeService(root, name) {+ fs.writeFileSync(+ path.join(root, 'src', 'generated', 'services', name),+ 'export {};\n',+ );+}++test('accepts literal default.cds and entity-set-derived service names', (testContext) => {+ const root = project(testContext);+ fs.writeFileSync(path.join(root, 'power.config.json'), JSON.stringify({+ databaseReferences: {+ 'default.cds': {+ dataSources: {+ equipment: {+ logicalName: 'new_equipments',+ entitySetName: 'new_equipmentses',+ },+ users: {+ logicalName: 'systemuser',+ entitySetName: 'systemusers',+ },+ },+ },+ },+ }));+ writeService(root, 'New_equipmentsesService.ts');+ writeService(root, 'SystemusersService.ts');++ assert.deepEqual(verifyDataverseServices(root, ['new_equipments', 'systemuser']), [{+ logicalName: 'new_equipments',+ entitySetName: 'new_equipmentses',+ serviceFile: 'New_equipmentsesService.ts',+ }, {+ logicalName: 'systemuser',+ entitySetName: 'systemusers',+ serviceFile: 'SystemusersService.ts',+ }]);+});++test('retains compatibility with nested database reference shape', () => {+ const dataSources = { users: { logicalName: 'systemuser', entitySetName: 'systemusers' } };+ assert.equal(configuredDataSources({+ databaseReferences: { default: { cds: { dataSources } } },+ }), dataSources);+});++test('rejects missing config, entity-set metadata, and service files', (testContext) => {+ const root = project(testContext);+ assert.throws(+ () => verifyDataverseServices(root, ['systemuser']),+ /power.config.json was not generated/,+ );+ fs.writeFileSync(path.join(root, 'power.config.json'), JSON.stringify({+ databaseReferences: {+ 'default.cds': {+ dataSources: {+ users: { logicalName: 'systemuser' },+ },+ },+ },+ }));+ assert.throws(+ () => verifyDataverseServices(root, ['systemuser']),+ /missing entitySetName/,+ );+ fs.writeFileSync(path.join(root, 'power.config.json'), JSON.stringify({+ databaseReferences: {+ 'default.cds': {+ dataSources: {+ users: { logicalName: 'systemuser', entitySetName: 'systemusers' },+ },+ },+ },+ }));+ assert.throws(+ () => verifyDataverseServices(root, ['systemuser']),+ /missing service file/,+ );+ fs.writeFileSync(path.join(root, 'power.config.json'), JSON.stringify({+ databaseReferences: {+ 'default.cds': {+ dataSources: {+ equipment: {+ logicalName: 'new_equipments',+ entitySetName: 'new_equipmentses',+ },+ },+ },+ },+ }));+ writeService(root, 'New_equipmentsService.ts');+ assert.throws(+ () => verifyDataverseServices(root, ['new_equipments']),+ /missing service file/,+ );+});++test('empty required table set needs no generated config', () => {+ assert.deepEqual(verifyDataverseServices('/does/not/exist', []), []);+});diff --git a/plugins/mobile-apps/scripts/verify-dataverse-services.js b/plugins/mobile-apps/scripts/verify-dataverse-services.jsnew file mode 100644index 000000000..7e71aa99c--- /dev/null+++ b/plugins/mobile-apps/scripts/verify-dataverse-services.js@@ -0,0 +1,145 @@+#!/usr/bin/env node+'use strict';++const fs = require('node:fs');+const path = require('node:path');++function normalizeName(value) {+ return String(value || '').trim().toLowerCase();+}++function normalizedFileStem(value) {+ return normalizeName(value).replace(/[^a-z0-9]/g, '');+}++function configuredDataSources(config) {+ return config?.databaseReferences?.['default.cds']?.dataSources+ || config?.databaseReferences?.default?.cds?.dataSources;+}++function dataSourceEntries(dataSources) {+ if (Array.isArray(dataSources)) {+ return dataSources.map((value, index) => ({ key: String(index), value }));+ }+ if (!dataSources || typeof dataSources !== 'object') return [];+ return Object.entries(dataSources).map(([key, value]) => ({ key, value }));+}++function serviceFileFor(entry, serviceFiles) {+ const expectedStem = `${normalizedFileStem(entry?.value?.entitySetName)}service`;+ return serviceFiles.find((file) => (+ normalizedFileStem(file.replace(/\.ts$/i, '')) === expectedStem+ )) || null;+}++function verifyDataverseServices(projectRoot, logicalNames, fileSystem = fs) {+ const required = [...new Set((logicalNames || []).map(normalizeName).filter(Boolean))];+ if (required.length === 0) return [];+ const configPath = path.join(projectRoot, 'power.config.json');+ if (!fileSystem.existsSync(configPath)) throw new Error('power.config.json was not generated');+ let config;+ try {+ config = JSON.parse(fileSystem.readFileSync(configPath, 'utf8'));+ } catch (error) {+ throw new Error(`power.config.json is invalid: ${error.message}`);+ }+ const dataSources = configuredDataSources(config);+ if (dataSources === undefined) {+ throw new Error(+ 'power.config.json is missing Dataverse dataSources under '+ + 'databaseReferences["default.cds"] or databaseReferences.default.cds',+ );+ }+ const entries = dataSourceEntries(dataSources);+ const serviceDirectory = path.join(projectRoot, 'src', 'generated', 'services');+ const serviceFiles = fileSystem.existsSync(serviceDirectory)+ ? fileSystem.readdirSync(serviceDirectory, { withFileTypes: true })+ .filter((entry) => entry.isFile() && entry.name.endsWith('.ts'))+ .map((entry) => entry.name)+ : [];+ const results = [];+ const missing = [];+ for (const logicalName of required) {+ const entry = entries.find(({ value }) => normalizeName(value?.logicalName) === logicalName);+ const serviceFile = entry ? serviceFileFor(entry, serviceFiles) : null;+ if (!entry || !entry.value?.entitySetName || !serviceFile) {+ missing.push({+ logicalName,+ configured: Boolean(entry),+ entitySetName: entry?.value?.entitySetName || null,+ serviceFile,+ });+ continue;+ }+ results.push({+ logicalName,+ entitySetName: entry.value.entitySetName,+ serviceFile,+ });+ }+ if (missing.length > 0) {+ throw new Error(`required Dataverse service output is incomplete: ${missing.map((item) => (+ `${item.logicalName} (${item.configured ? 'configured' : 'missing config'}, `+ + `${item.entitySetName || 'missing entitySetName'}, ${item.serviceFile || 'missing service file'})`+ )).join('; ')}`);+ }+ return results;+}++function resolveInside(root, requested) {+ const file = path.resolve(root, requested);+ const relative = path.relative(root, file);+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {+ throw new Error(`path is outside project root: ${requested}`);+ }+ return file;+}++function parseArgs(argv) {+ const args = { tables: [] };+ for (let index = 2; index < argv.length; index += 1) {+ const token = argv[index];+ if (token === '--project-root') args.projectRoot = argv[++index];+ else if (token === '--manifest') args.manifest = argv[++index];+ else if (token === '--tables') {+ args.tables.push(...String(argv[++index] || '').split(','));+ } else if (token === '--table') args.tables.push(argv[++index]);+ else throw new Error(`Unknown argument: ${token}`);+ }+ if (!args.projectRoot) throw new Error('--project-root is required');+ if (!args.manifest && args.tables.length === 0) {+ throw new Error('--manifest or --tables is required');+ }+ return args;+}++function main(argv = process.argv) {+ try {+ const args = parseArgs(argv);+ const projectRoot = path.resolve(args.projectRoot);+ let logicalNames = args.tables;+ if (args.manifest) {+ const manifestPath = resolveInside(projectRoot, args.manifest);+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ if (!Array.isArray(manifest?.service?.requiredTables)) {+ throw new Error('manifest service.requiredTables must be an array');+ }+ logicalNames = manifest.service.requiredTables.map((item) => item.logicalName);+ }+ const services = verifyDataverseServices(projectRoot, logicalNames);+ process.stdout.write(`${JSON.stringify({ ok: true, count: services.length, services })}\n`);+ return 0;+ } catch (error) {+ process.stderr.write(`verify-dataverse-services: ${error.message}\n`);+ return 2;+ }+}++if (require.main === module) process.exitCode = main();++module.exports = {+ configuredDataSources,+ dataSourceEntries,+ main,+ verifyDataverseServices,+};diff --git a/plugins/mobile-apps/skills/add-dataverse/SKILL.md b/plugins/mobile-apps/skills/add-dataverse/SKILL.mdindex bd13ec28f..9cb8f0f9b 100644--- a/plugins/mobile-apps/skills/add-dataverse/SKILL.md+++ b/plugins/mobile-apps/skills/add-dataverse/SKILL.md@@ -903,7 +903,7 @@ Column shapes that have non-obvious gotchas (handle carefully):| Boolean | `Microsoft.Dynamics.CRM.BooleanAttributeMetadata` | `DefaultValue`, `OptionSet` with `TrueOption`/`FalseOption` || Choice (picklist) | `Microsoft.Dynamics.CRM.PicklistAttributeMetadata` | `OptionSet` with `IsGlobal: false`, `OptionSetType: "Picklist"`, `Options[]` — **option integer values start at `100000000` and increment by 1** || Lookup | via `RelationshipDefinitions` — see 1:N skeleton above | — |- | Image | `Microsoft.Dynamics.CRM.ImageAttributeMetadata` | `MaxHeight`, `MaxWidth` |+ | Image | `Microsoft.Dynamics.CRM.ImageAttributeMetadata` | `MaxSizeInKB` (default 10240), `CanStoreFullImage` || File | `Microsoft.Dynamics.CRM.FileAttributeMetadata` | `MaxSizeInKB` |**Common mistake:** omitting `FormatName` on String columns and `DateTimeBehavior` on DateTime columns. Both are required — Dataverse rejects the POST without them.@@ -927,7 +927,14 @@ Column shapes that have non-obvious gotchas (handle carefully):}}```-- **Image** — `@odata.type: Microsoft.Dynamics.CRM.ImageAttributeMetadata`, `MaxHeight`/`MaxWidth` required+- **Image** — `@odata.type: Microsoft.Dynamics.CRM.ImageAttributeMetadata`,+ `MaxSizeInKB` and `CanStoreFullImage`. Dataverse always reports+ `MaxHeight: 144` and `MaxWidth: 144` for the generated thumbnail; those values+ cannot be changed and must not be used as full-image dimensions. Set+ `CanStoreFullImage: true` when users must inspect or download the retained+ full-size image. Updating this setting requires retrieving the complete+ current `ImageAttributeMetadata`, changing the writable property, sending a+ full-definition `PUT`, and publishing customizations.- **File** — `@odata.type: Microsoft.Dynamics.CRM.FileAttributeMetadata`, `MaxSizeInKB` requiredIf the column type is not a simple string/int/boolean, surface a one-line confirmation to the user before posting.@@ -1027,7 +1034,24 @@ npx power-apps add-data-source --api-id dataverse --org-url <envUrl> --resource-Run **one at a time — sequentially**, not in parallel. The Power Apps CLI writes `src/generated/connectorSchemas.ts` and other generated files non-atomically; concurrent invocations corrupt them.-After generation, verify each required table appears in `power.config.json` `databaseReferences.default.cds.dataSources` and that a matching file exists in `src/generated/services/`. If any reused or custom table is missing, STOP before screen generation:+After generation, verify the output created by+`npx power-apps add-data-source` rather than guessing a JSON path or service+filename. The command writes Dataverse configuration under the literal+`databaseReferences["default.cds"].dataSources` key and derives service+filenames from each entry's `entitySetName`, which may differ from the table+logical name. The verifier also accepts the legacy nested+`databaseReferences.default.cds` shape:++```bash+node "${PLUGIN_ROOT}/scripts/verify-dataverse-services.js" \+ --project-root "<working_dir>" \+ --manifest "$OPERATION_MANIFEST"+```++For the standalone fallback path without a manifest, pass the resolved service+list as `--tables "<comma-separated-logical-names>"`. If any reused or custom+table is missing from config, lacks `entitySetName`, or has no matching generated+service, STOP before screen generation:```textBLOCKED: required Dataverse service missing for <logical-name>. Schema action=<reuse|extend|create>; app usage=<screens/hooks that require it>.