Skip to content

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.

86.0 KB
Raw Blame
const { test } = require('node:test');
const assert = require('node:assert');
const path = require('node:path');
const fs = require('node:fs');
const { validateAppSpec, columnTypeMap, relationshipFor, lookupColumnsFor, childRelationshipsFor, relationshipSchemaName, manyToManySchemaName, resolveSampleRecords, migrateAppSpec, quickCreateEnabledFor, dashboardNameKey } = require(path.join(__dirname, '..', 'lib', 'app-spec.js'));

const sample = JSON.parse(
  fs.readFileSync(path.join(__dirname, '..', '..', 'samples', 'app-spec.project-tracker.json'), 'utf8')
);
const desk = JSON.parse(
  fs.readFileSync(path.join(__dirname, '..', '..', 'samples', 'app-spec.support-desk.json'), 'utf8')
);
const cloneDesk = () => JSON.parse(JSON.stringify(desk));

test('validateAppSpec accepts the sample', () => {
  const r = validateAppSpec(sample);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec returns structured errors for malformed collections instead of throwing', () => {
  for (const spec of [
    { entities: {} },
    { forms: {} },
    { entities: [null] },
    { forms: [null] },
  ]) {
    assert.doesNotThrow(() => validateAppSpec(spec));
    const result = validateAppSpec(spec);
    assert.equal(result.ok, false, JSON.stringify(spec));
  }
});

test('relationshipSchemaName: all-custom default is unchanged (backward compatible)', () => {
  const rel = { type: 'OneToMany', referenced: 'new_customer', referencing: 'new_ticket' };
  assert.strictEqual(relationshipSchemaName(rel, 'new'), 'new_customer_new_ticket');
  // With no prefix supplied, the legacy composed name is returned unchanged.
  assert.strictEqual(relationshipSchemaName(rel), 'new_customer_new_ticket');
});

test('relationshipSchemaName: a relationship to a SYSTEM table is auto-prefixed (the build-halt fix)', () => {
  const rel = { type: 'OneToMany', referenced: 'systemuser', referencing: 'contoso_teammember' };
  // systemuser has no publisher prefix, so the naive `systemuser_contoso_teammember` would be
  // rejected by Dataverse. The prefix is prepended and the redundant one on the child is stripped.
  assert.strictEqual(relationshipSchemaName(rel, 'contoso'), 'contoso_systemuser_teammember');
});

test('relationshipSchemaName: account-referenced default is also prefixed', () => {
  const rel = { type: 'OneToMany', referenced: 'account', referencing: 'contoso_project' };
  assert.strictEqual(relationshipSchemaName(rel, 'contoso'), 'contoso_account_project');
});

test('relationshipSchemaName: an explicit schemaName is honored verbatim', () => {
  const rel = { type: 'OneToMany', referenced: 'systemuser', referencing: 'contoso_teammember', schemaName: 'contoso_myrel' };
  assert.strictEqual(relationshipSchemaName(rel, 'contoso'), 'contoso_myrel');
});

test('manyToManySchemaName: system-table N:N is auto-prefixed', () => {
  const rel = { type: 'ManyToMany', entity1: 'systemuser', entity2: 'contoso_project' };
  // #3: the pair is sorted alphabetically before composing, so 'contoso_project' precedes 'systemuser'.
  assert.strictEqual(manyToManySchemaName(rel, 'contoso'), 'contoso_project_systemuser');
  // all-custom is unchanged
  assert.strictEqual(manyToManySchemaName({ entity1: 'new_a', entity2: 'new_b' }, 'new'), 'new_a_new_b');
});

test('manyToManySchemaName: #3 name is STABLE regardless of authoring order (alphabetical)', () => {
  // The same N:N authored in either order must yield ONE schema name (fixes the V1/V2 reversal that
  // broke a data-load assuming a fixed order).
  const ab = manyToManySchemaName({ entity1: 'new_workitem', entity2: 'new_customerrequest' }, 'new');
  const ba = manyToManySchemaName({ entity1: 'new_customerrequest', entity2: 'new_workitem' }, 'new');
  assert.strictEqual(ab, ba, 'declaration order must not change the name');
  assert.strictEqual(ab, 'new_customerrequest_new_workitem', 'entities sorted alphabetically');
  // An explicit schemaName still wins verbatim (author override).
  assert.strictEqual(manyToManySchemaName({ entity1: 'new_b', entity2: 'new_a', schemaName: 'new_myrel' }, 'new'), 'new_myrel');
});

test('validateAppSpec accepts a sitemap icon referencing a declared image web resource', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.webResources = (s.webResources || []).concat([{ name: 'new_ic.png', type: 'png', contentBase64: 'AAAA' }]);
  s.appShell.areas[0].groups[0].subAreas[0].icon = 'new_ic.png';
  s.appShell.areas[0].groups[0].subAreas[0].vectorIcon = 'Home';
  s.appShell.areas[0].icon = 'new_ic.png';
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec rejects a sitemap icon referencing an undeclared web resource', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.appShell.areas[0].groups[0].subAreas[0].icon = 'new_missing.png';
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /icon 'new_missing\.png' is not a declared web resource/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec TOLERATES a platform icon reference (OOB / $webresource path) on a subarea — the download→build round-trip fix (Symptom B)', () => {
  // A downloaded app carries live/OOB icon PATHS on its entity subareas (e.g. the OOB CDSEntity icon).
  // These are NOT declared web resources — the build must accept them as-is, not reject the round-trip.
  const OOB = '/WebResources/msdyn_OmnichannelBase/_imgs/SitemapIcon/CDSEntity';
  for (const iconVal of [OOB, '$webresource:crba3_appicon.svg']) {
    const s = JSON.parse(JSON.stringify(sample));
    s.appShell.areas[0].groups[0].subAreas[0].icon = iconVal;
    const r = validateAppSpec(s, { profile: 'deploy' });
    assert.ok(!r.errors.some((e) => /is not a declared web resource/.test(e)), `platform icon '${iconVal}' must pass: ${JSON.stringify(r.errors)}`);
  }
});

test('validateAppSpec WARNS (does not error) on a dropped BARE-TOKEN entity-subarea vectorIcon (no silent drop)', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.appShell.areas[0].groups[0].subAreas[0].vectorIcon = 'Shop'; // bare Fluent token on an entity subarea
  const r = validateAppSpec(s, { profile: 'deploy' });
  assert.ok(!r.errors.some((e) => /vectorIcon/.test(e)), 'a bare-token vectorIcon does not block the build');
  assert.ok((r.warnings || []).some((w) => /vectorIcon 'Shop' is a bare token/.test(w)), `it is surfaced as a warning: ${JSON.stringify(r.warnings)}`);
});

test('validateAppSpec WARNS on a custom-prefixed platform icon ref that is NOT declared (cross-env portability); no warning once declared', () => {
  // A hand-authored spec referencing its OWN custom web resource by PATH but not declaring it will dangle
  // on a fresh env — surface it (a downloaded spec auto-declares, so this only helps hand-authored specs).
  const pfx = (sample.solution.publisherPrefix || 'new').toLowerCase();
  const s = JSON.parse(JSON.stringify(sample));
  s.appShell.areas[0].groups[0].subAreas[0].vectorIcon = `/WebResources/${pfx}_undeclared.svg`;
  const r = validateAppSpec(s, { profile: 'deploy' });
  assert.ok(r.ok, 'a custom-but-undeclared icon ref does not block the build');
  assert.ok((r.warnings || []).some((w) => /points at a custom web resource.*NOT declared in webResources/.test(w)), `portability warning fires: ${JSON.stringify(r.warnings)}`);

  // Declaring the web resource silences the warning (the build recreates it → portable).
  const s2 = JSON.parse(JSON.stringify(s));
  s2.webResources = (s2.webResources || []).concat([{ name: `${pfx}_undeclared.svg`, type: 'svg', content: '<svg/>' }]);
  const r2 = validateAppSpec(s2, { profile: 'deploy' });
  assert.ok(!(r2.warnings || []).some((w) => /NOT declared in webResources/.test(w)), 'declaring the WR silences the portability warning');

  // An OOB/system reference (different prefix, or a non-WebResources /_imgs/ path) is NOT flagged.
  const s3 = JSON.parse(JSON.stringify(sample));
  s3.appShell.areas[0].groups[0].subAreas[0].icon = '/WebResources/msdyn_OmnichannelBase/_imgs/SitemapIcon/CDSEntity';
  const r3 = validateAppSpec(s3, { profile: 'deploy' });
  assert.ok(!(r3.warnings || []).some((w) => /NOT declared in webResources/.test(w)), 'an OOB/system icon ref is not flagged (present on every env)');
});

// URL scheme allowlist: only http(s) URLs may be shipped in an app the maker renders.
test('validateAppSpec rejects a sitemap subArea url with a non-http(s) scheme', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.appShell.areas[0].groups[0].subAreas.push({ title: 'Evil', url: 'javascript:alert(1)' });
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /url must be an http\(s\) URL/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec accepts a sitemap subArea url with https', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.appShell.areas[0].groups[0].subAreas.push({ title: 'Docs', url: 'https://learn.microsoft.com/' });
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec rejects an iframe dashboard tile url with a non-http(s) scheme', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.dashboards = [{ name: 'Ops', tiles: [{ type: 'iframe', name: 'Map', url: 'javascript:alert(1)' }] }];
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /iframe tile url must be an http\(s\)/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects a sitemap icon referencing a non-image web resource', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.webResources = (s.webResources || []).concat([{ name: 'new_logic.js', type: 'js', content: 'x' }]);
  s.appShell.areas[0].groups[0].subAreas[0].icon = 'new_logic.js';
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /must be an image web resource/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec accepts a table vectorIcon referencing a declared SVG web resource', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.webResources = (s.webResources || []).concat([{ name: 'new_tableicon', type: 'svg', content: '<svg/>' }]);
  s.entities[0].vectorIcon = 'new_tableicon';
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec rejects a table vectorIcon that is not a declared web resource (the glimmer cause)', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.entities[0].vectorIcon = 'AccessTimeFilled'; // a Fluent token, NOT a web resource
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /vectorIcon 'AccessTimeFilled' is not a declared web resource/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects a table vectorIcon that is a non-SVG web resource', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.webResources = (s.webResources || []).concat([{ name: 'new_tableicon_png', type: 'png', contentBase64: 'AAAA' }]);
  s.entities[0].vectorIcon = 'new_tableicon_png';
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /vectorIcon 'new_tableicon_png' must be an SVG web resource/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects a table (raster) icon that is an SVG web resource (use vectorIcon)', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.webResources = (s.webResources || []).concat([{ name: 'new_svgicon', type: 'svg', content: '<svg/>' }]);
  s.entities[0].icon = 'new_svgicon';
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /must be a raster image web resource/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec accepts an app.icon referencing a declared image web resource', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.webResources = (s.webResources || []).concat([{ name: 'new_appicon', type: 'png', contentBase64: 'AAAA' }]);
  s.app.icon = 'new_appicon';
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec rejects an app.icon that is not a declared web resource', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.app.icon = 'new_missingappicon';
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /app\.icon 'new_missingappicon' is not a declared web resource/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec accepts pages[] + a page sitemap subarea', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.pages = [{ name: 'Overview', dataSources: ['new_project'], prompt: 'kpis', codeFile: 'overview.tsx' }];
  s.appShell.areas[0].groups[0].subAreas.push({ page: 'Overview', title: 'Overview' });
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec rejects a page with no source/codeFile and a subarea referencing an unknown page', () => {
  const s = cloneDesk();
  s.pages = [{ name: 'Overview' }]; // no source, no codeFile
  s.appShell.areas[0].groups[0].subAreas.push({ title: 'Overview', page: 'Nope' });
  const r = validateAppSpec(s); // default deploy profile
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /page 'Overview': must be implemented/.test(e)), JSON.stringify(r.errors));
  assert.ok(r.errors.some((e) => /unknown page 'Nope'/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects a subarea that sets both an entity and a page', () => {
  const s = JSON.parse(JSON.stringify(sample));
  s.pages = [{ name: 'Overview', codeFile: 'o.tsx' }];
  s.appShell.areas[0].groups[0].subAreas.push({ entity: 'new_project', page: 'Overview', title: 'Both' });
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /sets multiple targets/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects a form referencing an unknown entity', () => {
  const bad = JSON.parse(JSON.stringify(sample));
  bad.forms[0].entity = 'new_missing';
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => e.includes('new_missing')));
});

test('validateAppSpec rejects a Choice column with no options', () => {
  const bad = JSON.parse(JSON.stringify(sample));
  delete bad.entities[0].columns[1].options;
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => e.includes('Choice needs options')));
});

test('columnTypeMap maps Choice to the Dataverse picklist type', () => {
  assert.strictEqual(columnTypeMap('Choice').dv, 'picklist');
});

test('resolveSampleRecords resolves inline AND global Choice labels (and multi-select tokens) to option ints', () => {
  const spec = { globalChoices: [{ name: 'new_tierset', options: ['Platinum', 'Gold', 'Silver', 'Bronze'] }] };
  const entity = {
    columns: [
      { schemaName: 'new_tier', type: 'Choice', globalChoice: 'new_tierset' }, // global
      { schemaName: 'new_pri', type: 'Choice', options: ['Low', 'High'] },      // inline
      { schemaName: 'new_tags', type: 'MultiChoice', options: ['A', 'B', 'C'] },// multi-select
    ],
  };
  const [r] = resolveSampleRecords(entity, [{ new_tier: 'Silver', new_pri: 'High', new_tags: 'A,C', new_name: 'Acme' }], spec);
  assert.strictEqual(r.new_tier, 100000002, 'global-choice label -> option int');
  assert.strictEqual(r.new_pri, 100000001, 'inline-choice label -> option int');
  assert.strictEqual(r.new_tags, '100000000,100000002', 'multi-select tokens resolved');
  assert.strictEqual(r.new_name, 'Acme', 'non-choice value passes through');
});

test('resolveSampleRecords renders a single MultiChoice label as a comma-string, not a bare Int32', () => {
  // regression: a multi-select picklist needs Edm.String even for one value
  // ("Cannot convert '100000002' (Int32) to Edm.String").
  const entity = { columns: [{ schemaName: 'new_certs', type: 'MultiChoice', options: ['Plumbing', 'HVAC', 'Electrical'] }] };
  const [one] = resolveSampleRecords(entity, [{ new_certs: 'HVAC' }], {});
  assert.strictEqual(one.new_certs, '100000001', 'single multi-select value is a STRING');
  assert.strictEqual(typeof one.new_certs, 'string', 'never a bare number');
  const [many] = resolveSampleRecords(entity, [{ new_certs: 'Plumbing,Electrical' }], {});
  assert.strictEqual(many.new_certs, '100000000,100000002', 'multiple values comma-joined as a string');
});

test('resolveSampleRecords leaves raw ints and unknown tokens untouched', () => {
  const entity = { columns: [{ schemaName: 'new_pri', type: 'Choice', options: ['Low', 'High'] }] };
  const [r] = resolveSampleRecords(entity, [{ new_pri: 100000001 }], {});
  assert.strictEqual(r.new_pri, 100000001, 'raw option int unchanged');
  const [r2] = resolveSampleRecords(entity, [{ new_pri: 'Nope' }], {});
  assert.strictEqual(r2.new_pri, 'Nope', 'unknown label passes through (lint flags it)');
});

// --- Rich-spec validation (charts / sub-grids / relational sample data) ----

test('validateAppSpec accepts the relational support-desk sample', () => {
  const r = validateAppSpec(desk);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('relationshipFor matches the OneToMany by referenced/referencing (case-insensitive)', () => {
  const rel = relationshipFor(desk, 'NEW_Customer', 'new_ticket');
  assert.ok(rel, 'found the customer->ticket relationship');
  assert.strictEqual(rel.lookup.schemaName, 'new_CustomerId');
  assert.strictEqual(relationshipFor(desk, 'new_ticket', 'new_customer'), null, 'direction matters');
  assert.strictEqual(relationshipFor(desk, 'new_customer', 'new_comment'), null, 'no transitive match');
});

test('validateAppSpec rejects a chart whose groupBy is not a Choice column', () => {
  const bad = cloneDesk();
  bad.charts[0].groupBy = 'new_duedate'; // a DateTime, not a Choice
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /groupBy/.test(e) && /Choice/.test(e)));
});

test('validateAppSpec rejects an unknown chartType', () => {
  const bad = cloneDesk();
  bad.charts[0].chartType = 'Donut';
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /chartType/.test(e)));
});

test('#4 validateAppSpec flags a sampleData Choice value that is not a declared option label', () => {
  const bad = cloneDesk();
  bad.sampleData.new_ticket[0].new_priority = 'Urgent'; // not in Low/Medium/High/Critical -> silent bad @wire
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(
    r.errors.some((e) => /Urgent/.test(e) && /new_priority/.test(e) && /option label/.test(e)),
    JSON.stringify(r.errors)
  );
});

test('#4 choice-label lint has no false positives: a declared label and a raw option int both pass', () => {
  const okSpec = cloneDesk();
  okSpec.sampleData.new_ticket[0].new_priority = 'Critical'; // valid label
  okSpec.sampleData.new_ticket[0].new_status = 100000001; // raw option int passes through unchanged
  const r = validateAppSpec(okSpec);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('#4 MultiChoice lint checks each comma token; a bad token is flagged, labels+ints pass', () => {
  const bad = cloneDesk();
  bad.entities
    .find((e) => e.schemaName === 'new_ticket')
    .columns.push({ schemaName: 'new_tags', displayName: 'Tags', type: 'MultiChoice', options: ['A', 'B', 'C'] });
  bad.sampleData.new_ticket[0].new_tags = 'A,Zzz'; // Zzz is not a declared option
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /Zzz/.test(e) && /new_tags/.test(e)), JSON.stringify(r.errors));

  const okSpec = cloneDesk();
  okSpec.entities
    .find((e) => e.schemaName === 'new_ticket')
    .columns.push({ schemaName: 'new_tags', displayName: 'Tags', type: 'MultiChoice', options: ['A', 'B', 'C'] });
  okSpec.sampleData.new_ticket[0].new_tags = 'A,100000002'; // label + raw int
  const ok = validateAppSpec(okSpec);
  assert.strictEqual(ok.ok, true, JSON.stringify(ok.errors));
});

test('validateAppSpec rejects a chart missing a name', () => {
  const bad = cloneDesk();
  delete bad.charts[0].name;
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /name is required/.test(e)));
});

test('validateAppSpec rejects a sub-grid childEntity with no OneToMany relationship', () => {
  const bad = cloneDesk();
  // comment is not a direct child of customer (only ticket is) -> invalid sub-grid.
  bad.forms[0].subgrids[0].childEntity = 'new_comment';
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /no OneToMany or ManyToMany relationship/.test(e)));
});

test('validateAppSpec rejects a sub-grid referencing an unknown childEntity', () => {
  const bad = cloneDesk();
  bad.forms[0].subgrids[0].childEntity = 'new_missing';
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /unknown childEntity/.test(e)));
});

test('validateAppSpec rejects an invalid formType', () => {
  const bad = cloneDesk();
  bad.forms[0].formType = 'Card2';
  const r = validateAppSpec(bad);
  assert.ok(!r.ok && r.errors.some((e) => /formType must be one of/.test(e)));
});

test('validateAppSpec accepts a valid forms[].formId (GUID) and rejects a malformed one', () => {
  const ok = cloneDesk();
  ok.forms[0].formId = '3024db08-9559-4d89-be11-d5cefa01a21f';
  assert.ok(validateAppSpec(ok).ok, JSON.stringify(validateAppSpec(ok).errors));
  const bad = cloneDesk();
  bad.forms[0].formId = "not-a-guid' or 1 eq 1"; // also guards the unquoted Edm.Guid OData interpolation
  const r = validateAppSpec(bad);
  assert.ok(!r.ok && r.errors.some((e) => /formId .* is not a valid GUID/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects sub-grids on a non-Main form', () => {
  const bad = cloneDesk(); // desk forms[0] (Customer) has a Tickets sub-grid
  bad.forms[0].formType = 'QuickCreate';
  const r = validateAppSpec(bad);
  assert.ok(!r.ok && r.errors.some((e) => /can't host sub-grids/.test(e)));
});

test('validateAppSpec accepts a command referencing a declared web resource', () => {
  const ok = cloneDesk();
  ok.webResources = [{ name: 'new_ticket.js', type: 'js', content: 'x' }];
  ok.commands = [{ entity: 'new_ticket', label: 'Escalate', library: 'new_ticket.js', function: 'T.escalate' }];
  const r = validateAppSpec(ok);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec rejects a command referencing an undeclared web resource', () => {
  const bad = cloneDesk();
  bad.commands = [{ entity: 'new_ticket', label: 'Escalate', library: 'missing.js', function: 'T.escalate' }];
  const r = validateAppSpec(bad);
  assert.ok(!r.ok && r.errors.some((e) => /is not a declared webResources/.test(e)));
});

test('validateAppSpec rejects a command with no function', () => {
  const bad = cloneDesk();
  bad.webResources = [{ name: 'new_ticket.js', type: 'js', content: 'x' }];
  bad.commands = [{ entity: 'new_ticket', label: 'Escalate', library: 'new_ticket.js' }];
  const r = validateAppSpec(bad);
  assert.ok(!r.ok && r.errors.some((e) => /function .* is required/.test(e)));
});

test('validateAppSpec accepts a dashboard with chart + list tiles on declared view/chart', () => {
  const ok = cloneDesk();
  // The chart and its view must be on the SAME table (a mismatch cross-wires the tile, #586 item 3).
  const chart = ok.charts[0];
  const view = ok.views.find((v) => v.entity === chart.entity);
  ok.dashboards = [{ name: 'Ops', tiles: [
    { type: 'chart', chart: chart.name, view: view.name },
    { type: 'list', view: ok.views[0].name, name: 'List' },
  ] }];
  const r = validateAppSpec(ok);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

// #586 item 3: view and chart names are unique only PER TABLE, and the build resolves both on the
// tile's table. Same names across tables are legitimate; a tile that mixes tables, or cannot say
// which table it means, is not.
test('validateAppSpec accepts same-named charts on two tables when each tile stays on one table', () => {
  const ok = cloneDesk();
  const ticketChart = ok.charts.find((c) => c.entity === 'new_ticket');
  ok.charts.push({ ...ticketChart, entity: 'new_customer', groupBy: 'new_segment' }); // same name, other table
  ok.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', chart: ticketChart.name, view: 'Active Tickets' }] }];
  const r = validateAppSpec(ok);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test("validateAppSpec rejects a chart tile whose chart is declared on a different table than its view", () => {
  const bad = cloneDesk();
  const ticketChart = bad.charts.find((c) => c.entity === 'new_ticket');
  bad.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', chart: ticketChart.name, view: 'Active Customers' }] }];
  const r = validateAppSpec(bad);
  assert.ok(r.errors.some((e) => /chart tile shows new_customer .* is declared on new_ticket/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec requires a tile to name its table when its view name exists on more than one', () => {
  const spec = cloneDesk();
  const customerView = spec.views.find((v) => v.entity === 'new_customer');
  spec.views.push({ ...customerView, name: 'Active Tickets' }); // now "Active Tickets" exists on two tables
  spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets', name: 'List' }] }];
  const ambiguous = validateAppSpec(spec);
  assert.ok(ambiguous.errors.some((e) => /declared on more than one table .* set the tile's entity/.test(e)), JSON.stringify(ambiguous.errors));
  spec.dashboards[0].tiles[0].entity = 'new_ticket';
  const pinned = validateAppSpec(spec);
  assert.strictEqual(pinned.ok, true, JSON.stringify(pinned.errors));
});

test("validateAppSpec rejects a tile whose entity does not declare the view it names", () => {
  const bad = cloneDesk();
  bad.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Customers', entity: 'new_ticket', name: 'List' }] }];
  const r = validateAppSpec(bad);
  assert.ok(r.errors.some((e) => /names view 'Active Customers' on new_ticket, but that view is declared on new_customer/.test(e)), JSON.stringify(r.errors));
});

// #586 item 4: a sitemap subarea and the build find a dashboard by NAME, through a Dataverse filter
// that ignores case, most accents and trailing spaces, so two such names collapse into one dashboard
// and the other leaves the nav.
test('validateAppSpec rejects two dashboards whose names Dataverse would treat as one', () => {
  const bad = cloneDesk();
  const tile = { type: 'list', view: bad.views[0].name, name: 'List' };
  for (const [first, second] of [['Overview', 'OVERVIEW '], ['Café', 'CAFE'], ['Overview', 'Overview']]) {
    bad.dashboards = [{ name: first, tiles: [tile] }, { name: second, tiles: [tile] }];
    const r = validateAppSpec(bad);
    assert.ok(r.errors.some((e) => e.includes(`dashboard '${second}': has the same name as dashboard '${first}'`)), `${first} / ${second}: ${JSON.stringify(r.errors)}`);
  }
  // Differences the server keeps must stay legal: a leading space, and a vowel sign (a letter, not an accent).
  for (const [first, second] of [['Overview', 'Pipeline'], ['Overview', ' Overview'], ['कार', 'कर']]) {
    bad.dashboards = [{ name: first, tiles: [tile] }, { name: second, tiles: [tile] }];
    assert.strictEqual(validateAppSpec(bad).ok, true, `${JSON.stringify(first)} / ${JSON.stringify(second)} are distinct`);
  }
});

// Every pair below was written to a live English environment and read back with `eq`; `server` is what
// Dataverse answered. The key must agree, except where it deliberately folds MORE (a false rejection
// is loud and fixed by a rename; a missed collision silently drops a dashboard).
test('dashboardNameKey folds exactly what the server was measured to ignore', () => {
  const MEASURED = [
    ['Alpha', 'ALPHA', true], ['Café', 'Cafe', true], ['Résumé', 'Re\u0301sume\u0301', true],
    ['Bravo', 'Bravo ', true], ['Charlie ', 'Charlie', true], [' Delta', 'Delta', false],
    ['Echo\u00a0', 'Echo', false], ['Foxtrot\t', 'Foxtrot', false], ['कार', 'कर', false], ['กิน', 'กน', false],
    ['ばす', 'はす', true], ['مُحَمَّد', 'محمد', false], ['йод', 'иод', false], ['ёж', 'еж', true], ['Жук', 'ЖУК', true],
    ['Straße', 'Strasse', true], ['Golf', 'Golf', true], ['Æther', 'AEther', true], ['file', 'file', true],
    ['Άλφα', 'Αλφα', true], ['Việt', 'Viet', true], ['שָׁלוֹם', 'שלום', true], ['Tăng', 'Tang', true],
    ['Øre', 'Ore', true], ['Łódź', 'Lodz', true], ['Đà', 'Da', true], ['Œuvre', 'Oeuvre', true],
    ['İstanbul', 'Istanbul', true], ['カナ', 'カナ', true], ['カナ', 'かな', true], ['λόγος', 'λόγοσ', true],
    ['عـلم', 'علم', true], ['क़', 'क', true],
  ];
  for (const [a, b, server] of MEASURED) {
    assert.strictEqual(dashboardNameKey(a) === dashboardNameKey(b), server, `${JSON.stringify(a)} vs ${JSON.stringify(b)}: the server says ${server ? 'equal' : 'distinct'}`);
  }
  // The one accepted over-fold: the server keeps a decomposed Hangul syllable distinct from its
  // precomposed form, which no keyboard produces for a dashboard name.
  assert.strictEqual(dashboardNameKey('한'), dashboardNameKey('\u1112\u1161\u11ab'));
  assert.notStrictEqual(dashboardNameKey('Sales Overview'), dashboardNameKey('SalesOverview'), 'inner space still counts');
  assert.strictEqual(dashboardNameKey(undefined), '');
});

// A column with no schemaName is reported by name. The sample-data gate resolves Choice values through
// the loader's helpers, which used to key every Choice/MultiChoice column by `schemaName.toLowerCase()`
// and threw a TypeError instead — taking validate, verify and even a teardown dry-run down with it.
test('validateAppSpec reports a Choice column with no schemaName instead of crashing on its sample data', () => {
  const s = cloneDesk();
  const e = s.entities[0];
  e.columns = [...(e.columns || []), { displayName: 'Tags', type: 'MultiChoice' }, { displayName: 'Tier', type: 'Choice', options: ['A', 'B'] }];
  s.sampleData = { [e.schemaName]: [{ [e.primaryAttribute.schemaName]: 'One' }] };
  let r;
  assert.doesNotThrow(() => { r = validateAppSpec(s); });
  assert.ok(r.errors.some((m) => /a column is missing schemaName/.test(m)), JSON.stringify(r.errors));
});

test('validateAppSpec accepts id-passthrough dashboard tiles (viewId/visualizationId + entity, no declared view/chart)', () => {
  const ok = cloneDesk();
  ok.views = []; ok.charts = []; // round-tripped spec declares no views/charts
  ok.dashboards = [{ name: 'Ops', tiles: [
    { type: 'chart', name: 'By Status', entity: ok.entities[0].schemaName, viewId: 'v1', visualizationId: 'c1' },
    { type: 'list', name: 'Active', entity: ok.entities[0].schemaName, viewId: 'v1' },
  ] }];
  const r = validateAppSpec(ok);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec rejects an id-based dashboard tile missing entity or viewId', () => {
  const noEntity = cloneDesk();
  noEntity.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', name: 'X', viewId: 'v1', visualizationId: 'c1' }] }];
  assert.ok(validateAppSpec(noEntity).errors.some((e) => /id-based chart tile needs entity/.test(e)));
  const noView = cloneDesk();
  noView.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', name: 'X', entity: noView.entities[0].schemaName, visualizationId: 'c1' }] }];
  assert.ok(validateAppSpec(noView).errors.some((e) => /also needs viewId/.test(e)));
});

test('validateAppSpec rejects a dashboard chart tile referencing an unknown chart', () => {
  const bad = cloneDesk();
  bad.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', chart: 'Nope', view: bad.views[0].name }] }];
  const r = validateAppSpec(bad);
  assert.ok(!r.ok && r.errors.some((e) => /unknown chart/.test(e)));
});

test('validateAppSpec accepts a quick-view placement referencing a QuickView form', () => {
  const ok = cloneDesk();
  ok.forms = [
    { entity: 'new_ticket', name: 'Ticket', formType: 'Main', quickViews: [{ lookup: 'new_customerid', targetEntity: 'new_customer', form: 'Customer QV' }] },
    { entity: 'new_customer', name: 'Customer QV', formType: 'QuickView' },
  ];
  const r = validateAppSpec(ok);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec: a quick-view matches its form by (name, targetEntity) — a same-named form on ANOTHER entity is not accepted', () => {
  const bad = cloneDesk();
  bad.forms = [
    { entity: 'new_ticket', name: 'Ticket', formType: 'Main', quickViews: [{ lookup: 'new_customerid', targetEntity: 'new_customer', form: 'Shared QV' }] },
    { entity: 'new_ticket', name: 'Shared QV', formType: 'QuickView' }, // same NAME but on new_ticket, not the targetEntity new_customer
  ];
  const r = validateAppSpec(bad);
  // Name-only matching would have (wrongly) accepted the new_ticket 'Shared QV'; (name, targetEntity) rejects it.
  assert.ok(!r.ok && r.errors.some((e) => /quickView references form 'Shared QV' \(a QuickView on 'new_customer'\) not found/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec: a quick-view prefers the QuickView form when a same-named Main exists on the SAME target entity', () => {
  const ok = cloneDesk();
  // new_customer has BOTH a Main and a QuickView named "Information"; the quick-view must resolve the
  // QuickView, not be rejected because the Main appears first (order-dependent name matching).
  ok.forms = [
    { entity: 'new_ticket', name: 'Ticket', formType: 'Main', quickViews: [{ lookup: 'new_customerid', targetEntity: 'new_customer', form: 'Information' }] },
    { entity: 'new_customer', name: 'Information', formType: 'Main' },      // same name, Main — appears FIRST
    { entity: 'new_customer', name: 'Information', formType: 'QuickView' }, // the intended target
  ];
  const r = validateAppSpec(ok);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec rejects two QuickView forms sharing (entity, name) — a quick-view reference would be ambiguous', () => {
  const bad = cloneDesk();
  bad.forms = [
    { entity: 'new_ticket', name: 'Ticket', formType: 'Main' },
    { entity: 'new_customer', name: 'Card', formType: 'QuickView' },
    { entity: 'new_customer', name: 'Card', formType: 'QuickView' }, // duplicate QuickView identity on new_customer
  ];
  const r = validateAppSpec(bad);
  assert.ok(!r.ok && r.errors.some((e) => /duplicate QuickView form 'Card'/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects a quick-view whose form is not a QuickView', () => {
  const bad = cloneDesk();
  bad.forms = [
    { entity: 'new_ticket', name: 'Ticket', formType: 'Main', quickViews: [{ lookup: 'new_customerid', targetEntity: 'new_customer', form: 'Customer' }] },
    { entity: 'new_customer', name: 'Customer', formType: 'Main' },
  ];
  const r = validateAppSpec(bad);
  assert.ok(!r.ok && r.errors.some((e) => /must have formType: "QuickView"/.test(e)));
});

test('validateAppSpec accepts a flyout command (children carry the actions); rejects a child with no function', () => {
  const ok = cloneDesk();
  ok.webResources = [{ name: 'new_ticket.js', type: 'js', content: 'x' }];
  ok.commands = [{ entity: 'new_ticket', label: 'More', type: 'FlyoutAnchor', children: [
    { label: 'Escalate', library: 'new_ticket.js', function: 'T.escalate' },
  ] }];
  assert.strictEqual(validateAppSpec(ok).ok, true, JSON.stringify(validateAppSpec(ok).errors));
  const bad = cloneDesk();
  bad.webResources = [{ name: 'new_ticket.js', type: 'js', content: 'x' }];
  bad.commands = [{ entity: 'new_ticket', label: 'More', type: 'FlyoutAnchor', children: [{ label: 'Escalate', library: 'new_ticket.js' }] }];
  const r = validateAppSpec(bad);
  assert.ok(!r.ok && r.errors.some((e) => /child 'Escalate'.*function .* is required/.test(e)));
});

test('validateAppSpec accepts a DashBoard sitemap subarea, rejects an unknown dashboard + a double-target subarea', () => {
  const ok = cloneDesk();
  ok.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: ok.views[0].name, name: 'L' }] }];
  ok.appShell.areas[0].groups[0].subAreas.push({ dashboard: 'Ops', title: 'Overview' });
  assert.strictEqual(validateAppSpec(ok).ok, true, JSON.stringify(validateAppSpec(ok).errors));

  const unknown = cloneDesk();
  unknown.appShell.areas[0].groups[0].subAreas.push({ dashboard: 'Nope', title: 'X' });
  assert.ok(validateAppSpec(unknown).errors.some((e) => /unknown dashboard 'Nope'/.test(e)));

  const dbl = cloneDesk();
  dbl.appShell.areas[0].groups[0].subAreas.push({ entity: 'new_ticket', url: 'https://x', title: 'Both' });
  assert.ok(validateAppSpec(dbl).errors.some((e) => /sets multiple targets/.test(e)));
});

test('validateAppSpec rejects an invalid form.layout value', () => {
  const bad = cloneDesk();
  bad.forms[0].layout = 'fancy';
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /layout must be/.test(e)));
});

test('validateAppSpec rejects $parent pointing at an entity with no relationship to the child', () => {
  const bad = cloneDesk();
  // bind a comment directly to a customer -> no customer->comment relationship.
  bad.sampleData.new_comment[0].$parent = { entity: 'new_customer', match: { new_name: 'Northwind Traders' } };
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /no OneToMany relationship from \$parent/.test(e)));
});

test('#1 validateAppSpec fails loud when a $parent.match resolves to NO parent sample record', () => {
  const bad = cloneDesk();
  // new_ticket[0] binds to a customer that has no matching sample row -> the lookup would be unset.
  bad.sampleData.new_ticket[0].$parent = { entity: 'new_customer', match: { new_name: 'Nonexistent Co' } };
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(
    r.errors.some((e) => /\$parent\.match/.test(e) && /matched no 'new_customer' sample record/.test(e) && /left unset/.test(e)),
    JSON.stringify(r.errors)
  );
});

test('#1 validateAppSpec validates $parents (junction) entries the same way as $parent', () => {
  const bad = cloneDesk();
  // A $parents entry whose match resolves to nothing must be flagged (not silently dropped).
  bad.sampleData.new_ticket[0] = {
    new_name: 'Junction row', new_priority: 'High', new_status: 'New',
    $parents: [{ entity: 'new_customer', match: { new_name: 'Ghost' } }],
  };
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /\$parents\.match/.test(e) && /matched no 'new_customer'/.test(e)), JSON.stringify(r.errors));
});

test('#1 a valid $parent.match that resolves to a real parent row still passes', () => {
  // The stock desk sample binds tickets to a real customer row — must remain valid.
  const r = validateAppSpec(cloneDesk());
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

// --- #544: self-referencing sample data, validated at LINT time -------------------------------
// The build halting partway through sample-data — after other data is already written — is the
// worst outcome, so the rules the seeder enforces at runtime are all gated here first.
function selfRefDesk() {
  const s = cloneDesk();
  s.entities.push({ schemaName: 'new_org', displayName: 'Org', pluralName: 'Orgs', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] });
  s.relationships.push({ type: 'OneToMany', referenced: 'new_org', referencing: 'new_org', lookup: { schemaName: 'new_ParentOrgId', displayName: 'Parent Org' } });
  s.sampleData.new_org = [
    { new_name: 'Root' },
    { new_name: 'Child', $parent: { entity: 'new_org', match: { new_name: 'Root' } } },
  ];
  return s;
}

test('#544 a self-referencing $parent hierarchy is VALID (the seeder creates it in waves)', () => {
  const r = validateAppSpec(selfRefDesk());
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('#544 a self-reference cycle is rejected at lint time, naming the record indices', () => {
  const s = selfRefDesk();
  s.sampleData.new_org[0].$parent = { entity: 'new_org', match: { new_name: 'Child' } };
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /\$parent cycle/.test(e) && /0, 1/.test(e)), JSON.stringify(r.errors));
});

test('#544 a row that is its own parent is rejected as a cycle', () => {
  const s = selfRefDesk();
  s.sampleData.new_org = [{ new_name: 'Loop', $parent: { entity: 'new_org', match: { new_name: 'Loop' } } }];
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /\$parent cycle/.test(e)), JSON.stringify(r.errors));
});

test('#544 TWO relationships for one pair make a $parent ambiguous unless it names the lookup', () => {
  const s = selfRefDesk();
  // A second 1:N on the same pair derives the same schema name. The ambiguity under test is the
  // $parent bind, so this one carries an explicit name — otherwise the collision gate rejects it first.
  s.relationships.push({ type: 'OneToMany', schemaName: 'new_org_group_ancestor', referenced: 'new_org', referencing: 'new_org', lookup: { schemaName: 'new_GroupAncestorId', displayName: 'Group Ancestor' } });
  const ambiguous = validateAppSpec(s);
  assert.strictEqual(ambiguous.ok, false);
  assert.ok(ambiguous.errors.some((e) => /ambiguous/.test(e) && /new_ParentOrgId/.test(e) && /new_GroupAncestorId/.test(e)), JSON.stringify(ambiguous.errors));

  s.sampleData.new_org[1].$parent.lookup = 'new_GroupAncestorId';
  const named = validateAppSpec(s);
  assert.strictEqual(named.ok, true, JSON.stringify(named.errors));
});

test('#544 a $parent.lookup that names no relationship lists the valid ones', () => {
  const s = selfRefDesk();
  s.sampleData.new_org[1].$parent.lookup = 'new_NotARelationship';
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /new_NotARelationship/.test(e) && /new_ParentOrgId/.test(e)), JSON.stringify(r.errors));
});

test('#544 a cross-entity $parent is unaffected by the self-reference checks', () => {
  // The stock desk binds tickets to customers; no self-reference exists anywhere in it.
  assert.strictEqual(validateAppSpec(cloneDesk()).ok, true);
});

test('#1 (hardening) a non-array $parents is rejected (it diverges from the seeder otherwise)', () => {
  const bad = cloneDesk();
  bad.sampleData.new_ticket[0] = { new_name: 'Row', new_priority: 'High', new_status: 'New',
    $parents: { entity: 'new_customer', match: { new_name: 'Northwind Traders' } } }; // object, not array
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /\$parents must be an array/.test(e)), JSON.stringify(r.errors));
});

test('#1 (hardening) an AMBIGUOUS $parent.match (matches >1 parent row) is rejected', () => {
  const bad = cloneDesk();
  // Two customers share the same segment; match on segment -> ambiguous (the seeder would pick one).
  const seg = bad.sampleData.new_customer[0].new_segment;
  bad.sampleData.new_customer[1].new_segment = seg;
  bad.sampleData.new_ticket[0].$parent = { entity: 'new_customer', match: { new_segment: seg } };
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /ambiguous/.test(e) && /matches 2/.test(e)), JSON.stringify(r.errors));
});

test('#6 (hardening) two Main forms on one entity flagged deactivateOtherMainForms is rejected', () => {
  const bad = cloneDesk();
  bad.forms = [
    { entity: 'new_ticket', type: 'main', name: 'Ticket A', layout: 'auto', deactivateOtherMainForms: true },
    { entity: 'new_ticket', type: 'main', name: 'Ticket B', layout: 'auto', deactivateOtherMainForms: true },
  ];
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /deactivateOtherMainForms/.test(e) && /at most one/.test(e)), JSON.stringify(r.errors));
});

test('#6 (hardening) a flagged Main form sharing its entity with ANOTHER Main form is rejected (the deactivation race)', () => {
  const bad = cloneDesk();
  bad.forms = [
    { entity: 'new_ticket', type: 'main', name: 'Ticket A', layout: 'auto', deactivateOtherMainForms: true },
    { entity: 'new_ticket', type: 'main', name: 'Ticket B', layout: 'auto' }, // unflagged sibling — would race
  ];
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /must be the ONLY Main form/.test(e)), JSON.stringify(r.errors));
});

test('#6 (hardening) a single flagged Main form (the only Main form for its entity) is accepted', () => {
  const ok = cloneDesk();
  ok.forms.find((f) => f.entity === 'new_customer').deactivateOtherMainForms = true;
  const r = validateAppSpec(ok);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

// --- Gap 3: lookupColumnsFor -----------------------------------------------------------------
test('lookupColumnsFor returns the 1:N lookups on the child (referencing) side, excludes N:N, dedupes', () => {
  const spec = {
    relationships: [
      { type: 'OneToMany', referenced: 'new_project', referencing: 'new_task', lookup: { schemaName: 'new_ProjectId', displayName: 'Project' } },
      { type: 'OneToMany', referenced: 'systemuser', referencing: 'new_task', lookup: { schemaName: 'new_AssignedTo', displayName: 'Assigned To' } },
      { type: 'ManyToMany', entity1: 'new_task', entity2: 'new_tag', intersectEntityName: 'new_task_tag' },
      { type: 'OneToMany', referenced: 'new_project', referencing: 'new_other', lookup: { schemaName: 'new_ProjectId', displayName: 'Project' } },
    ],
  };
  const forTask = lookupColumnsFor(spec, 'new_task');
  assert.deepStrictEqual(forTask.map((l) => l.logical), ['new_projectid', 'new_assignedto'], 'both 1:N lookups on new_task, N:N excluded, lowercased');
  assert.strictEqual(forTask[0].displayName, 'Project');
  // the parent side (new_project is referenced, not referencing) has no lookup column
  assert.deepStrictEqual(lookupColumnsFor(spec, 'new_project'), []);
});

// --- Gap 7: childRelationshipsFor (auto sub-grids) -------------------------------------------
test('childRelationshipsFor returns the child (many) side of each 1:N where the entity is the parent, plus N:N partners', () => {
  const spec = {
    relationships: [
      { type: 'OneToMany', referenced: 'new_project', referencing: 'new_task', lookup: { schemaName: 'new_ProjectId' } },
      { type: 'OneToMany', referenced: 'new_project', referencing: 'new_risk', lookup: { schemaName: 'new_ProjectId2' } },
      { type: 'ManyToMany', entity1: 'new_project', entity2: 'new_tag', intersectEntityName: 'new_project_tag' },
      { type: 'OneToMany', referenced: 'systemuser', referencing: 'new_project', lookup: { schemaName: 'new_OwnerId' } },
    ],
  };
  // new_project is the PARENT of task + risk, and an N:N partner of tag — its form should list all three.
  assert.deepStrictEqual(childRelationshipsFor(spec, 'new_project').map((c) => c.childEntity), ['new_task', 'new_risk', 'new_tag']);
  // new_task is only a child (referencing) — it has no child grids of its own here.
  assert.deepStrictEqual(childRelationshipsFor(spec, 'new_task'), []);
});

// === page-spec validation BEFORE any write ===
// These checks run on every validateAppSpec call — author plan, run-1/run-2, teardown, verify —
// so a malformed page spec is rejected before the pages phase writes anything. Design §7.2.

// A minimal v2 spec that passes everything EXCEPT the page rule under test. schemaVersion 2 so the
// stable-key rules apply; one entity so the base validation is satisfied.
function pageSpec(pages) {
  // Build a subarea per page so the every-page-placed rule does not add spurious
  // errors for tests that exercise OTHER page validations (key grammar, codeFile paths, etc.).
  // Rejection tests already check for their specific error via .some(), so an extra "unknown page"
  // error for an invalid key does not break them.
  const subAreas = (pages || []).filter(p => p && p.key).map(p => ({ page: p.key, title: p.name || p.key }));
  return {
    schemaVersion: 2,
    solution: { uniqueName: 'S', publisherPrefix: 'new' },
    app: { name: 'A' },
    entities: [{ schemaName: 'new_widget', primaryAttribute: { schemaName: 'new_name' }, columns: [] }],
    pages,
    appShell: { areas: subAreas.length ? [{ label: 'Main', groups: [{ label: 'Main', subAreas }] }] : [] },
  };
}

test('validateAppSpec rejects case-insensitive duplicate page names', () => {
  const r = validateAppSpec(pageSpec([
    { key: 'a', name: 'Overview', source: { kind: 'tsx', codeFile: 'a.tsx' } },
    { key: 'b', name: 'overview', source: { kind: 'tsx', codeFile: 'b.tsx' } },
  ]), { profile: 'plan' });
  assert.ok(!r.ok && r.errors.some((e) => /duplicate page name/i.test(e)), r.errors.join('; '));
});

test('validateAppSpec TOLERATES a duplicate page name when ALL colliding pages are pre-existing (have pageId) — degrades to a warning', () => {
  // The reported repro: a downloaded app carries two deployed pages that share a name. The build did
  // not create them and (for a form-only edit) is not changing them, so it must not be blocked — the
  // pages phase matches by id/key, not name. Degrade to a non-blocking warning.
  const G = '067e0090-250f-4de7-a054-24c4a070f958';
  const H = '5df2bb50-47ae-47e7-a335-cade1b463c11';
  const r = validateAppSpec(pageSpec([
    { key: 'supplier-scorecard', name: 'Supplier Scorecard', pageId: G, source: { kind: 'tsx', codeFile: 'a.tsx' } },
    { key: 'supplier-scorecard-2', name: 'Supplier Scorecard', pageId: H, source: { kind: 'tsx', codeFile: 'b.tsx' } },
  ]), { profile: 'deploy' });
  assert.ok(r.ok, `pre-existing dupe must not block the build: ${r.errors.join('; ')}`);
  assert.ok(!r.errors.some((e) => /duplicate page name/i.test(e)), 'no duplicate-page-name ERROR for a pre-existing dupe');
  assert.ok((r.warnings || []).some((w) => /pre-existing duplicate page name 'Supplier Scorecard'/.test(w)), 'a warning is emitted');
});

test('validateAppSpec still ERRORS when a NEW page (no pageId) collides with a pre-existing one — prevention', () => {
  // Adding a fresh page whose name duplicates an existing page IS a collision the run creates → block it.
  const G = '067e0090-250f-4de7-a054-24c4a070f958';
  const r = validateAppSpec(pageSpec([
    { key: 'supplier-scorecard', name: 'Supplier Scorecard', pageId: G, source: { kind: 'tsx', codeFile: 'a.tsx' } },
    { key: 'sc-new', name: 'supplier scorecard', source: { kind: 'tsx', codeFile: 'b.tsx' } },
  ]), { profile: 'deploy' });
  assert.ok(!r.ok && r.errors.some((e) => /duplicate page name/i.test(e)), 'a NEW page colliding with a pre-existing name is rejected');
});

test('validateAppSpec rejects duplicate implemented codeFile paths', () => {
  const r = validateAppSpec(pageSpec([
    { key: 'a', name: 'A', source: { kind: 'tsx', codeFile: 'pages/x.tsx' } },
    { key: 'b', name: 'B', source: { kind: 'tsx', codeFile: 'pages/x.tsx' } },
  ]), { profile: 'plan' });
  assert.ok(!r.ok && r.errors.some((e) => /duplicate .*codeFile|codeFile .*already/i.test(e)), r.errors.join('; '));
});

// Path aliases that resolve to the same file must be detected as duplicates.
// path.normalize('pages/./x.tsx') and path.normalize('pages/x.tsx') resolve identically; without
// normalization these would evade the duplicate check as different strings.
test('validateAppSpec rejects normalized path duplicates: pages/x.tsx vs pages/./x.tsx', () => {
  const r = validateAppSpec(pageSpec([
    { key: 'a', name: 'A', source: { kind: 'tsx', codeFile: 'pages/x.tsx' } },
    { key: 'b', name: 'B', source: { kind: 'tsx', codeFile: 'pages/./x.tsx' } },
  ]), { profile: 'plan' });
  assert.ok(!r.ok && r.errors.some((e) => /duplicate .*codeFile|codeFile .*already/i.test(e)), `pages/./x.tsx alias should be detected as duplicate: ${r.errors.join('; ')}`);
});

test('validateAppSpec rejects a codeFile that escapes the workspace (.. or absolute)', () => {
  for (const bad of ['../evil.tsx', '/etc/evil.tsx', 'C:/evil.tsx', 'a/../../evil.tsx']) {
    const r = validateAppSpec(pageSpec([{ key: 'a', name: 'A', source: { kind: 'tsx', codeFile: bad } }]), { profile: 'plan' });
    assert.ok(!r.ok && r.errors.some((e) => /codeFile.*(outside|escape|confin|absolute|\.\.)/i.test(e)), `${bad}: ${r.errors.join('; ')}`);
  }
});

test('validateAppSpec rejects an invalid stable key grammar', () => {
  for (const bad of ['Overview', 'wo_detail', '-lead', 'lead-', 'a b']) {
    const r = validateAppSpec(pageSpec([{ key: bad, name: 'A', source: { kind: 'tsx', codeFile: 'a.tsx' } }]), { profile: 'plan' });
    assert.ok(!r.ok && r.errors.some((e) => /key.*grammar|invalid.*key|key '/i.test(e)), `${bad}: ${r.errors.join('; ')}`);
  }
});

test('validateAppSpec accepts a unique-name, confined-path, well-keyed page set', () => {
  const r = validateAppSpec(pageSpec([
    { key: 'overview', name: 'Overview', source: { kind: 'tsx', codeFile: 'overview.tsx' } },
    { key: 'wo-detail', name: 'WO Detail', navigatesTo: [{ targetKey: 'overview' }], source: { kind: 'tsx', codeFile: 'pages/wo-detail.tsx' } },
  ]), { profile: 'deploy' });
  assert.ok(r.ok, r.errors.join('; '));
});

test('validateAppSpec rejects $parent with an empty match', () => {
  const bad = cloneDesk();
  bad.sampleData.new_ticket[0].$parent = { entity: 'new_customer', match: {} };
  const r = validateAppSpec(bad);
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /match must be a non-empty object/.test(e)));
});

// --- ai block validation -----------------------------------------------------------------

test('validateAppSpec accepts a well-formed ai block', () => {
  const s = cloneDesk();
  s.ai = {
    appFeatures: { formFill: true, nlSearch: true },
    summaries: { default: 'auto', tables: { new_ticket: { enabled: true, columns: ['new_status'] } } },
  };
  const r = validateAppSpec(s);
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec rejects an ai summaries table not in entities', () => {
  const s = cloneDesk();
  s.ai = { summaries: { tables: { not_a_table: { enabled: true } } } };
  const r = validateAppSpec(s);
  assert.ok(!r.ok && r.errors.some((e) => /unknown table 'not_a_table'/i.test(e)));
});

test('validateAppSpec rejects an unknown ai.appFeatures key', () => {
  const s = cloneDesk();
  s.ai = { appFeatures: { formFill: true, copilot: true } };
  const r = validateAppSpec(s);
  assert.ok(!r.ok && r.errors.some((e) => /unknown key 'copilot'/i.test(e)));
});

test('validateAppSpec rejects a non-boolean, non-integer ai.appFeatures value', () => {
  const s = cloneDesk();
  s.ai = { appFeatures: { nlSearch: 'yes' } };
  const r = validateAppSpec(s);
  assert.ok(!r.ok && r.errors.some((e) => /must be a boolean or an integer between 0 and 1000000/i.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec ACCEPTS an explicit numeric ai.appFeatures value (2 = on for everyone)', () => {
  // These map to NUMERIC Dataverse app settings. A boolean-only contract made the platform's other
  // documented values inexpressible, so `2` could never be requested at all (ADO 6560699).
  const s = cloneDesk();
  s.ai = { appFeatures: { formFill: 2, nlSearch: true, nlChart: 0, m365: false } };
  const r = validateAppSpec(s);
  assert.ok(r.ok, JSON.stringify(r.errors));
});

test('validateAppSpec rejects a negative, fractional or out-of-range ai.appFeatures value', () => {
  // The upper bound and the unsafe-integer rejection mirror the SDK's `MAX_SETTING_VALUE`: the SDK
  // THROWS for these, so a spec that validated cleanly would abort the build half-applied.
  for (const bad of [-1, 1.5, 1000001, Number.MAX_SAFE_INTEGER + 2, NaN, Infinity]) {
    const s = cloneDesk();
    s.ai = { appFeatures: { formFill: bad } };
    const r = validateAppSpec(s);
    assert.ok(!r.ok && r.errors.some((e) => /ai\.appFeatures\.formFill/.test(e)), `expected ${bad} to be rejected`);
  }
  // ...and the boundary itself is still accepted, so the bound is inclusive like the SDK's.
  const ok = cloneDesk();
  ok.ai = { appFeatures: { formFill: 1000000 } };
  assert.ok(validateAppSpec(ok).ok, 'the maximum value must remain valid');
});

test('validateAppSpec rejects ai.summaries.default with an invalid value', () => {
  const s = cloneDesk();
  s.ai = { summaries: { default: 'on' } };
  const r = validateAppSpec(s);
  assert.ok(!r.ok && r.errors.some((e) => /auto.*off|off.*auto/i.test(e)));
});

test('validateAppSpec rejects an unknown column in ai.summaries.tables columns[]', () => {
  const s = cloneDesk();
  s.ai = { summaries: { tables: { new_ticket: { columns: ['new_missing_col'] } } } };
  const r = validateAppSpec(s);
  assert.ok(!r.ok && r.errors.some((e) => /unknown column 'new_missing_col'/i.test(e)));
});

test('validateAppSpec passes when ai is absent (no regression)', () => {
  const r = validateAppSpec(cloneDesk());
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

// Every page must be an appShell subarea + accept optional pages[].pageId (edit-snapshot).
// v2PagesSpec builds a minimal schemaVersion-2 spec; subAreas is the sitemap group's subAreas array;
// extraPageFields is merged into the FIRST page (overview) so we can exercise per-page fields like pageId.
function v2PagesSpec(subAreas, extraPageFields) {
  const extra = extraPageFields || {};
  const spec = {
    schemaVersion: 2,
    solution: { uniqueName: 'S', publisherPrefix: 'new' },
    app: { name: 'A' },
    entities: [{ schemaName: 'new_order', displayName: 'Order', primaryAttribute: { schemaName: 'new_name', displayName: 'Order #' }, columns: [] }],
    pages: [
      Object.assign({ key: 'overview', name: 'Overview', source: { kind: 'tsx', codeFile: 'overview.tsx' }, navigatesTo: [{ targetKey: 'order-detail' }] }, extra),
      { key: 'order-detail', name: 'Order Detail', source: { kind: 'tsx', codeFile: 'order-detail.tsx' } },
    ],
    appShell: { areas: [{ label: 'Sales', groups: [{ label: 'Work', subAreas }] }] },
  };
  return migrateAppSpec(spec);
}

test('validateAppSpec REJECTS a headless page (nav target with no sitemap subarea) — deploy profile', () => {
  // order-detail is a navigatesTo target but has no appShell subarea => headless => must be rejected.
  const spec = v2PagesSpec([{ page: 'overview', title: 'Overview' }, { entity: 'new_order', title: 'Orders' }]);
  const r = validateAppSpec(spec, { profile: 'deploy' });
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /order-detail/.test(e) && /not placed in the sitemap/i.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec ACCEPTS when every page is a sitemap subarea', () => {
  const spec = v2PagesSpec([{ page: 'overview', title: 'Overview' }, { page: 'order-detail', title: 'Order Detail' }, { entity: 'new_order', title: 'Orders' }]);
  const r = validateAppSpec(spec, { profile: 'deploy' });
  assert.ok(r.ok, JSON.stringify(r.errors));
});

test('the structural profile does NOT enforce page placement (shape-only / eval-harness use)', () => {
  // order-detail is headless but structural profile skips the membership rule entirely.
  const spec = v2PagesSpec([{ page: 'overview', title: 'Overview' }]);
  const r = validateAppSpec(spec, { profile: 'structural' });
  assert.ok(!r.errors.some((e) => /not placed in the sitemap/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec ACCEPTS a valid pages[].pageId GUID (edit-snapshot)', () => {
  const spec = v2PagesSpec(
    [{ page: 'overview', title: 'Overview' }, { page: 'order-detail', title: 'Order Detail' }],
    { pageId: '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8' }
  );
  const r = validateAppSpec(spec, { profile: 'deploy' });
  assert.ok(r.ok, JSON.stringify(r.errors));
});

test('validateAppSpec REJECTS a non-GUID pages[].pageId', () => {
  const badSpec = v2PagesSpec(
    [{ page: 'overview', title: 'Overview' }, { page: 'order-detail', title: 'Order Detail' }],
    { pageId: 'not-a-guid' }
  );
  const r = validateAppSpec(badSpec, { profile: 'deploy' });
  assert.strictEqual(r.ok, false);
  assert.ok(r.errors.some((e) => /pageId/.test(e) && /GUID/i.test(e)), JSON.stringify(r.errors));
  const emptySpec = v2PagesSpec(
    [{ page: 'overview', title: 'Overview' }, { page: 'order-detail', title: 'Order Detail' }],
    { pageId: '' }
  );
  assert.ok(!validateAppSpec(emptySpec, { profile: 'deploy' }).ok, 'empty pageId is rejected');
});

// pages[].model is the id a download writes back and the build sends to pac's `--model`, so it is a short token.
test('validateAppSpec ACCEPTS a model id and REJECTS anything that is not one', () => {
  const withModel = (model) => v2PagesSpec([{ page: 'overview', title: 'Overview' }, { page: 'order-detail', title: 'Order Detail' }], { model });
  for (const good of ['gpt-4.1', 'gpt-5-mini', 'org/model:v2_1', 'claude-3-5-sonnet@20240620', 'model+tuned', 'm'.repeat(100)]) {
    const r = validateAppSpec(withModel(good), { profile: 'deploy' });
    assert.ok(r.ok, `${good}: ${JSON.stringify(r.errors)}`);
  }
  for (const bad of ['', ' gpt-4.1', 'gpt 4.1', '-gpt', 'gpt"4', 'm'.repeat(101), 41, null]) {
    const r = validateAppSpec(withModel(bad), { profile: 'deploy' });
    assert.ok(r.errors.some((e) => /page 'overview': model must be a model id such as 'gpt-4\.1'/.test(e)), `${JSON.stringify(bad)}: ${JSON.stringify(r.errors)}`);
  }
});

// --- entities[].quickCreate (Allow quick create table flag) --------------------------------------
function quickCreateSpec(entityExtra, forms) {
  return {
    schemaVersion: 2,
    solution: { uniqueName: 'S', publisherPrefix: 'new' },
    app: { name: 'A' },
    entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' }, columns: [], ...entityExtra }],
    forms: forms || [],
  };
}

test('validateAppSpec accepts a boolean entities[].quickCreate', () => {
  assert.ok(validateAppSpec(quickCreateSpec({ quickCreate: true }), { profile: 'deploy' }).ok, 'quickCreate:true is valid');
  assert.ok(validateAppSpec(quickCreateSpec({ quickCreate: false }), { profile: 'deploy' }).ok, 'quickCreate:false is valid');
  assert.ok(validateAppSpec(quickCreateSpec({}), { profile: 'deploy' }).ok, 'omitted quickCreate is valid');
});

test('validateAppSpec rejects a non-boolean entities[].quickCreate', () => {
  const r = validateAppSpec(quickCreateSpec({ quickCreate: 'yes' }), { profile: 'deploy' });
  assert.ok(!r.ok, 'quickCreate must be a boolean');
  assert.ok(r.errors.some((e) => /quickCreate must be a boolean/.test(e)), 'the error names the field');
});

// --- entities[].primaryAttribute.maxLength (the length of the table's name column) ----------------
// Accepted and ignored until the build began sending it, so a value the platform cannot take is refused at the spec gate, not
// part-way through a build. The platform's limit for a table's name column is 850, well under the 4,000 of other text columns:
// asked for more, the table create is refused — "The maximum length of Primary attribute '<name>' is <asked>. The maximum
// allowed limit is 850."
test('validateAppSpec accepts primaryAttribute.maxLength from 1 to 850, and an omitted one', () => {
  for (const maxLength of [undefined, 1, 100, 120, 849, 850]) {
    const primaryAttribute = { schemaName: 'new_name', displayName: 'Name', ...(maxLength === undefined ? {} : { maxLength }) };
    const r = validateAppSpec(quickCreateSpec({ primaryAttribute }), { profile: 'deploy' });
    assert.ok(r.ok, `${maxLength}: ${JSON.stringify(r.errors)}`);
  }
});

test('validateAppSpec rejects a primaryAttribute.maxLength that is not a whole number from 1 to 850, naming the field and the value', () => {
  for (const bad of [0, -1, 851, 4000, 4001, 12.5, '120', null, true, [], {}]) {
    const r = validateAppSpec(quickCreateSpec({ primaryAttribute: { schemaName: 'new_name', displayName: 'Name', maxLength: bad } }), { profile: 'deploy' });
    assert.ok(!r.ok, `${JSON.stringify(bad)} must be rejected`);
    assert.ok(r.errors.some((e) => e.startsWith('entity new_ticket: primaryAttribute.maxLength must be a whole number from 1 to 850 (got ')), `${JSON.stringify(bad)}: ${JSON.stringify(r.errors)}`);
  }
  assert.ok(validateAppSpec(quickCreateSpec({ primaryAttribute: { schemaName: 'new_name', maxLength: 851 } }), { profile: 'deploy' }).errors.some((e) => /\(got 851\)/.test(e)), 'the value is quoted back');
});

// /genpage and /app-builder reach the build through the provision-entities input gate, not validateAppSpec: it must refuse
// exactly what the spec gate refuses, because the length goes into the table request as it is written.
test('the provision-entities input gate applies the same primaryAttribute.maxLength rule as validateAppSpec', () => {
  const { validateProvisionInput } = require(path.join(__dirname, '..', 'lib', 'provision-input.js'));
  const lengthErrors = (errors) => errors.filter((e) => /primaryAttribute\.maxLength/.test(e)).map((e) => e.slice(e.indexOf('primaryAttribute.maxLength')));
  for (const maxLength of [undefined, 1, 120, 850, 851, 4000, 5000, 0, 1.5, -3, '120', null, true, [], {}]) {
    const primaryAttribute = { schemaName: 'new_name', displayName: 'Name', ...(maxLength === undefined ? {} : { maxLength }) };
    const spec = validateAppSpec(quickCreateSpec({ primaryAttribute }), { profile: 'deploy' });
    const input = validateProvisionInput({
      solution: { uniqueName: 'S', publisherPrefix: 'new' },
      entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute, columns: [] }],
      relationships: [],
    });
    const label = JSON.stringify(maxLength);
    assert.deepStrictEqual(lengthErrors(input.errors), lengthErrors(spec.errors), `${label}: the same verdict and wording from both gates`);
    assert.strictEqual(input.ok, spec.ok, label);
    const valid = maxLength === undefined || (Number.isInteger(maxLength) && maxLength >= 1 && maxLength <= 850);
    assert.strictEqual(lengthErrors(input.errors).length === 0, valid, `${label} is ${valid ? 'accepted' : 'rejected'}`);
  }
});

test('quickCreateEnabledFor: true for an explicit flag, a derived QuickCreate form, else false', () => {
  const entity = { schemaName: 'new_ticket', primaryAttribute: { schemaName: 'new_name' }, columns: [] };
  // explicit flag — the flag lives on the ENTITY object passed (quickCreateEnabledFor reads entity.quickCreate)
  const flagged = quickCreateSpec({ quickCreate: true });
  assert.strictEqual(quickCreateEnabledFor(flagged, flagged.entities[0]), true, 'explicit quickCreate:true');
  // derived from an authored QuickCreate form (case-insensitive entity match)
  assert.strictEqual(quickCreateEnabledFor(quickCreateSpec({}, [{ entity: 'New_Ticket', formType: 'QuickCreate' }]), entity), true, 'derived from a QuickCreate form');
  // a Main form does NOT enable it
  assert.strictEqual(quickCreateEnabledFor(quickCreateSpec({}, [{ entity: 'new_ticket', formType: 'Main' }]), entity), false, 'a Main form does not enable quick create');
  // neither → false
  assert.strictEqual(quickCreateEnabledFor(quickCreateSpec({}), entity), false, 'no flag and no QuickCreate form → false');
  // a QuickCreate form for a DIFFERENT entity does not enable this one
  assert.strictEqual(quickCreateEnabledFor(quickCreateSpec({}, [{ entity: 'new_other', formType: 'QuickCreate' }]), entity), false, 'a QuickCreate form for another entity does not leak');
});

// --- Security personas validation ---------------------------------------------
const withPersonas = (personas) => Object.assign(JSON.parse(JSON.stringify(sample)), { personas });

test('validateAppSpec accepts a well-formed persona', () => {
  const r = validateAppSpec(withPersonas([
    { persona: 'Agent', jobs: [{ name: 'Work tickets', privileges: [{ entity: 'pt_task', access: ['read', 'write', 'create'], scope: 'businessUnit' }] }] },
  ]));
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec accepts additionalPrivileges + a valid assignTo (GUIDs)', () => {
  const r = validateAppSpec(withPersonas([
    { persona: 'Agent', assignTo: { teams: ['00000000-0000-0000-0000-000000000001'] },
      additionalPrivileges: [{ entity: 'account', access: ['read'], scope: 'organization' }],
      jobs: [{ name: 'Work', privileges: [{ entity: 'pt_task', access: ['read'] }] }] },
  ]));
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

test('validateAppSpec rejects an unknown access level', () => {
  const r = validateAppSpec(withPersonas([
    { persona: 'Agent', jobs: [{ name: 'Work', privileges: [{ entity: 'pt_task', access: ['read', 'launch'] }] }] },
  ]));
  assert.ok(!r.ok && r.errors.some((e) => /unknown access 'launch'/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects an unknown privilege scope', () => {
  const r = validateAppSpec(withPersonas([
    { persona: 'Agent', jobs: [{ name: 'Work', privileges: [{ entity: 'pt_task', access: ['read'], scope: 'galaxy' }] }] },
  ]));
  assert.ok(!r.ok && r.errors.some((e) => /unknown scope 'galaxy'/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec requires a persona name and at least one job', () => {
  const r = validateAppSpec(withPersonas([{ jobs: [] }]));
  assert.ok(r.errors.some((e) => /persona \(the role name\) is required/.test(e)), JSON.stringify(r.errors));
  assert.ok(r.errors.some((e) => /at least one job/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects a job missing privileges[]', () => {
  const r = validateAppSpec(withPersonas([{ persona: 'Agent', jobs: [{ name: 'Work' }] }]));
  assert.ok(!r.ok && r.errors.some((e) => /privileges\[\] is required/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects duplicate persona names (case-insensitive)', () => {
  const r = validateAppSpec(withPersonas([
    { persona: 'Agent', jobs: [{ name: 'a', privileges: [{ entity: 'pt_task', access: ['read'] }] }] },
    { persona: 'agent', jobs: [{ name: 'b', privileges: [{ entity: 'pt_task', access: ['read'] }] }] },
  ]));
  assert.ok(!r.ok && r.errors.some((e) => /duplicate persona name/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects a non-boolean appAccess and a non-GUID assignTo id', () => {
  const r = validateAppSpec(withPersonas([
    { persona: 'Agent', appAccess: 'yes', assignTo: { users: ['not-a-guid'] },
      jobs: [{ name: 'Work', privileges: [{ entity: 'pt_task', access: ['read'] }] }] },
  ]));
  assert.ok(r.errors.some((e) => /appAccess must be a boolean/.test(e)), JSON.stringify(r.errors));
  assert.ok(r.errors.some((e) => /assignTo\.users contains a non-GUID/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects personas that is not an array', () => {
  const r = validateAppSpec(Object.assign(JSON.parse(JSON.stringify(sample)), { personas: {} }));
  assert.ok(!r.ok && r.errors.some((e) => /personas must be an array/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec: a spec with no personas is unaffected (additive)', () => {
  assert.strictEqual(validateAppSpec(sample).ok, true);
});

test('validateAppSpec rejects an unknown persona key (typo protection — e.g. appAcces)', () => {
  const r = validateAppSpec(withPersonas([
    { persona: 'Agent', appAcces: false, jobs: [{ name: 'Work', privileges: [{ entity: 'pt_task', access: ['read'] }] }] },
  ]));
  assert.ok(!r.ok && r.errors.some((e) => /unknown key 'appAcces'/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec rejects unknown job and privilege keys', () => {
  const rJob = validateAppSpec(withPersonas([
    { persona: 'Agent', jobs: [{ name: 'Work', scope: 'oops', privileges: [{ entity: 'pt_task', access: ['read'] }] }] },
  ]));
  assert.ok(rJob.errors.some((e) => /job: unknown key 'scope'/.test(e)), JSON.stringify(rJob.errors));
  const rPriv = validateAppSpec(withPersonas([
    { persona: 'Agent', jobs: [{ name: 'Work', privileges: [{ entity: 'pt_task', access: ['read'], scopes: 'user' }] }] },
  ]));
  assert.ok(rPriv.errors.some((e) => /privilege: unknown key 'scopes'/.test(e)), JSON.stringify(rPriv.errors));
});

test('validateAppSpec rejects a whitespace-only persona name', () => {
  const r = validateAppSpec(withPersonas([{ persona: '   ', jobs: [{ name: 'Work', privileges: [{ entity: 'pt_task', access: ['read'] }] }] }]));
  assert.ok(!r.ok && r.errors.some((e) => /cannot be blank\/whitespace-only/.test(e)), JSON.stringify(r.errors));
});

test('validateAppSpec detects whitespace-distinct persona names as duplicates (SDK trims)', () => {
  const r = validateAppSpec(withPersonas([
    { persona: 'Agent', jobs: [{ name: 'a', privileges: [{ entity: 'pt_task', access: ['read'] }] }] },
    { persona: '  Agent  ', jobs: [{ name: 'b', privileges: [{ entity: 'pt_task', access: ['read'] }] }] },
  ]));
  assert.ok(!r.ok && r.errors.some((e) => /duplicate persona name/.test(e)), JSON.stringify(r.errors));
});

// --- views[]: a column reference must be a STRING (#525) ---------------------------------------
//
// `viewDef` maps every entry with `String(name).toLowerCase()`, so a non-string is not rejected —
// it is STRINGIFIED. An object becomes the literal `[object object]`, which reaches the view's
// fetchxml and is refused by the platform with an opaque metadata error, mid-build, after the
// solution and tables already exist.
//
// The damage outlives the run: the savedquery row is created carrying that fetchxml, and every
// later read of it also fails, so the next build dies at the same step. Dataverse reports the row
// as system-defined and refuses to delete it, so recovering means tearing the table down.
//
// `{ "name": "..." }` is not a wild guess either — it is exactly the shape `forms[]` uses for its
// fields, so an author moving between the two surfaces writes it naturally.
const viewSpec = (view) => {
  const s = cloneDesk();
  s.views = [Object.assign({ entity: 'new_customer', name: 'Active Customers' }, view)];
  return s;
};
const viewErrors = (view) => (validateAppSpec(viewSpec(view)).errors || []);

test('validateAppSpec rejects a non-string entry in views[].columns (#525)', () => {
  for (const bad of [{ name: 'new_name' }, 42, null, ['new_name'], true]) {
    const errs = viewErrors({ columns: ['new_name', bad] });
    assert.ok(
      errs.some((e) => /columns/.test(e) && /string/.test(e)),
      `${JSON.stringify(bad)} must be rejected as a column; got ${JSON.stringify(errs)}`
    );
    // The message has to name the view, or an author with a dozen views cannot act on it.
    assert.ok(errs.some((e) => /Active Customers/.test(e)), `the error must name the view; got ${JSON.stringify(errs)}`);
  }
});

test('validateAppSpec rejects a blank column name, which fetchxml cannot express either', () => {
  for (const bad of ['', '   ']) {
    const errs = viewErrors({ columns: [bad] });
    assert.ok(errs.some((e) => /columns/.test(e)), `${JSON.stringify(bad)} must be rejected; got ${JSON.stringify(errs)}`);
  }
});

test('validateAppSpec rejects a non-string sort/filter attribute for the same reason', () => {
  // `viewDef` stringifies these two the same way (`String(s.attr)` / `String(f.attr)`), so they
  // carry the identical failure and were fixed together rather than one at a time.
  const sortErrs = viewErrors({ columns: ['new_name'], sort: [{ attr: { name: 'new_name' }, dir: 'asc' }] });
  assert.ok(sortErrs.some((e) => /sort/.test(e) && /string/.test(e)), `got ${JSON.stringify(sortErrs)}`);
  const filterErrs = viewErrors({ columns: ['new_name'], filters: [{ attr: { name: 'new_name' }, op: 'eq', value: 'x' }] });
  assert.ok(filterErrs.some((e) => /filter/.test(e) && /string/.test(e)), `got ${JSON.stringify(filterErrs)}`);
});

test('validateAppSpec still accepts a well-formed view (the guard adds no false positive)', () => {
  const r = validateAppSpec(viewSpec({ columns: ['new_name', 'new_segment'], sort: [{ attr: 'new_name', dir: 'asc' }], filters: [{ attr: 'new_segment', op: 'eq', value: 'SMB' }] }));
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
  // Omitted collections must stay optional — the primary name column is substituted downstream.
  assert.strictEqual(validateAppSpec(viewSpec({})).ok, true);
});

test('the whole shipped sample set still validates (no regression from the views guard)', () => {
  for (const s of [sample, desk]) {
    const r = validateAppSpec(s);
    assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
  }
});

// --- an entity reference is a METADATA NAME, so it must be a string too (#525's sibling) ---------
//
// `String([["new_ticket"]])` is `"new_ticket"`, so a one-element nested array passed every
// entity-membership check and then threw a RAW TypeError deep in the build, where the engine calls
// `.toLowerCase()` on the array itself. These are valid JSON, so they reach the CLI from a spec file
// — unlike a Symbol or a throwing getter, which cannot survive JSON.
test('a nested-array entity reference is a structured error, not a late TypeError', () => {
  const NESTED = [['new_ticket']];
  const cases = [
    ['chart', (s) => { s.charts = [{ name: 'C', entity: NESTED, chartType: 'Column', groupBy: 'new_priority' }]; }],
    ['form subgrid childEntity', (s) => { s.forms = [{ entity: 'new_customer', name: 'F', subgrids: [{ childEntity: NESTED }] }]; }],
    ['sitemap subArea', (s) => { s.appShell.areas[0].groups[0].subAreas.push({ entity: NESTED, title: 'X' }); }],
    ['dashboard chart tile', (s) => { s.dashboards = [{ name: 'D', tiles: [{ type: 'chart', viewId: '11111111-1111-1111-1111-111111111111', visualizationId: '22222222-2222-2222-2222-222222222222', entity: NESTED }] }]; }],
    ['dashboard list tile', (s) => { s.dashboards = [{ name: 'D2', tiles: [{ type: 'list', viewId: '11111111-1111-1111-1111-111111111111', entity: NESTED }] }]; }],
  ];
  for (const [label, mutate] of cases) {
    const spec = cloneDesk();
    mutate(spec);
    let res;
    assert.doesNotThrow(() => { res = validateAppSpec(spec, { profile: 'plan' }); },
      `${label}: validation must not throw on a JSON-representable wrong type`);
    assert.strictEqual(res.ok, false, `${label}: must be rejected`);
    assert.ok((res.errors || []).some((e) => /must be a table name \(a string\)/.test(e)),
      `${label}: expected a table-name type error; got ${JSON.stringify(res.errors)}`);
  }
});

test('the value describer cannot itself throw (BigInt / a throwing getter)', () => {
  // A validator that crashes while formatting its own error message is worse than one that misses
  // the case: the caller gets a stack trace instead of a finding.
  for (const [label, bad] of [
    ['BigInt', 10n],
    ['throwing getter', Object.defineProperty({}, 'toJSON', { get() { throw new Error('nope'); } })],
  ]) {
    const spec = cloneDesk();
    spec.views = [{ entity: 'new_customer', name: 'V', columns: [bad] }];
    let res;
    assert.doesNotThrow(() => { res = validateAppSpec(spec, { profile: 'plan' }); }, `${label} must not crash the validator`);
    assert.strictEqual(res.ok, false, `${label} must still be rejected`);
  }
});

// --- AB#6686426: default-form selection must be deterministic --------------------------------------
//
// Promotion used to run INSIDE the concurrent per-form build, so every Main form on an owned custom
// table promoted itself and the LAST to finish won. Which form a table opened with therefore depended
// on completion order — an alternate read-only or OnSave-blocked form could silently become the
// default. Promotion is now ONE serialized pass after every form exists, choosing an explicit
// `isDefault` first and otherwise the first Main form in spec order.

const deskWithForms = (forms) => { const s = cloneDesk(); s.forms = forms; return s; };
const mainForm = (name, over = {}) => ({
  entity: desk.entities[0].schemaName, name, formType: 'Main',
  sections: [{ label: 'General', columns: [desk.entities[0].primaryAttribute.schemaName] }], ...over,
});

test('AB#6686426: isDefault must be a boolean', () => {
  const r = validateAppSpec(deskWithForms([mainForm('A', { isDefault: 'yes' })]), { profile: 'plan' });
  assert.strictEqual(r.ok, false);
  assert.match((r.errors || []).join(' | '), /isDefault must be a boolean/);
});

test('AB#6686426: two Main forms cannot both claim isDefault', () => {
  const r = validateAppSpec(deskWithForms([mainForm('A', { isDefault: true }), mainForm('B', { isDefault: true })]), { profile: 'plan' });
  assert.strictEqual(r.ok, false);
  assert.match((r.errors || []).join(' | '), /exactly one form can be the table's default/);
});

test('AB#6686426: isDefault on a NON-Main form is rejected — only Main forms are promoted', () => {
  const r = validateAppSpec(deskWithForms([mainForm('QC', { formType: 'QuickCreate', isDefault: true })]), { profile: 'plan' });
  assert.strictEqual(r.ok, false);
  assert.match((r.errors || []).join(' | '), /only meaningful on a Main form/);
});

test('AB#6686426: one isDefault among several Main forms is valid', () => {
  const r = validateAppSpec(deskWithForms([mainForm('A'), mainForm('B', { isDefault: true }), mainForm('C')]), { profile: 'plan' });
  assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});

// #583 Gap 1 — an app's scope is defined as much by what it deliberately leaves out as by what it
// includes, and the exclusions are what let a reviewer tell two apps over the same tables apart.
// Nothing recorded them, so they lived only in the authoring conversation.
//
// `excludes[]` is DOCUMENTARY, like `jobs[].surfaces`: personaRoleSpecFor() projects explicit fields
// only, so it can never reach the SDK and be silently discarded there — the failure class #583 Gap 3
// describes for `aiDescription`.
function personaSpec(persona) {
  return {
    schemaVersion: 2,
    solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },
    app: { name: 'Contoso' },
    entities: [{ schemaName: 'contoso_order', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],
    appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [] }] }] },
    personas: [Object.assign({
      persona: 'Dispatcher',
      jobs: [{ name: 'Assign work', surfaces: ['Active Work'], privileges: [{ entity: 'contoso_order', access: ['read'] }] }],
    }, persona)],
  };
}

test('#583 a persona may record deliberate exclusions, and a malformed one is rejected', () => {
  const ok = validateAppSpec(personaSpec({ excludes: ['Approving budgets — handled in the Finance app'] }), { profile: 'plan' });
  assert.strictEqual(ok.ok, true, JSON.stringify(ok.errors));

  // A persona with no excludes is unaffected — this cannot break an existing spec.
  assert.strictEqual(validateAppSpec(personaSpec({}), { profile: 'plan' }).ok, true);

  const notArray = validateAppSpec(personaSpec({ excludes: 'Approving budgets' }), { profile: 'plan' });
  assert.ok(notArray.errors.some((e) => /excludes must be an array of strings/.test(e)),
    `a bare string must be rejected, not treated as a one-item list; got ${JSON.stringify(notArray.errors)}`);

  for (const bad of [[''], ['   '], [42], [null]]) {
    const r = validateAppSpec(personaSpec({ excludes: bad }), { profile: 'plan' });
    assert.ok(r.errors.some((e) => /each excludes\[\] entry must be a non-empty string/.test(e)),
      `${JSON.stringify(bad)} must be rejected — a blank exclusion documents nothing`);
  }
});

// --- a sample ROW must be a real record object ---------------------------------------------------
// The seeder spreads each row into a column map, and JS spreads a non-object into something
// plausible rather than failing, so these reached Dataverse as garbage instead of being rejected
// (MEASURED): null throws a raw TypeError; "abc" becomes { "0":"a","1":"b","2":"c" }; 42 and true
// become {}; ["x"] becomes { "0":"x" }. The sample-data phase runs AFTER tables, forms and views
// are deployed, so without this gate a typo halts the build halfway and leaves artifacts behind.
test('a non-object sample row is rejected at the gate, with its index and type named', () => {
  const spec = {
    schemaVersion: 2,
    solution: { uniqueName: 'c', publisherPrefix: 'co' },
    app: { name: 'C' },
    entities: [{ schemaName: 'co_order', primaryAttribute: { schemaName: 'co_name' }, columns: [] }],
    sampleData: { co_order: [null, 'abc', 42, true, ['x']] },
  };
  const v = validateAppSpec(spec, { profile: 'plan' });
  const hits = (v.errors || []).filter((e) => /sampleData\['co_order'\]\[\d+\]/.test(e));
  assert.strictEqual(hits.length, 5, `every bad row must be named; got ${JSON.stringify(v.errors)}`);
  assert.ok(hits.some((e) => /\[0\].*got null/.test(e)), 'null is named as null, not as object');
  assert.ok(hits.some((e) => /\[1\].*got string/.test(e)));
  assert.ok(hits.some((e) => /\[4\].*got an array/.test(e)), 'typeof [] is object, so it needs its own wording');
});

test('ordinary sample rows still validate (the gate must not reject real data)', () => {
  const spec = {
    schemaVersion: 2,
    solution: { uniqueName: 'c', publisherPrefix: 'co' },
    app: { name: 'C' },
    entities: [{ schemaName: 'co_order', primaryAttribute: { schemaName: 'co_name' }, columns: [] }],
    sampleData: { co_order: [{ co_name: 'First' }, { co_name: 'Second' }] },
  };
  const v = validateAppSpec(spec, { profile: 'plan' });
  const hits = (v.errors || []).filter((e) => /sampleData/.test(e));
  assert.deepStrictEqual(hits, [], `valid rows must pass; got ${JSON.stringify(hits)}`);
});

// A secret environment variable must not carry its value in the spec (the spec is a file that gets shared and committed): a
// defaultValue on one is an error when the spec is about to deploy, a warning when it is only read for its shape, and the value is
// never repeated in either message.
test('validateAppSpec: a secret environment variable with a defaultValue is a deploy error, a structural warning, and is never echoed', () => {
  const spec = {
    minimumPluginVersion: '2.21.0', schemaVersion: 2,
    solution: { uniqueName: 'ContosoSol', displayName: 'Contoso Sol', publisherPrefix: 'contoso' },
    app: { name: 'Config App', uniqueName: 'contoso_configapp' },
    entities: [{ schemaName: 'contoso_ticket', displayName: 'Ticket', pluralName: 'Tickets', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' } }],
    environmentVariables: [{ schemaName: 'contoso_ApiKey', type: 'secret', defaultValue: 'Sup3rS3cretValue' }],
  };
  const expected = 'environmentVariables[0].defaultValue is not allowed for a secret variable (supply a Key Vault reference through deployment settings)';
  const deploy = validateAppSpec(spec, { profile: 'deploy' });
  const structural = validateAppSpec(spec, { profile: 'structural' });
  assert.deepStrictEqual(deploy.errors, [expected]);
  assert.deepStrictEqual(structural.warnings, [expected]);
  assert.deepStrictEqual(structural.errors, []);
  assert.ok(!JSON.stringify([deploy, structural]).includes('Sup3rS3cretValue'), 'the secret is not repeated');
  const plain = { ...spec, environmentVariables: [{ schemaName: 'contoso_ApiKey', type: 'secret' }] };
  assert.deepStrictEqual(validateAppSpec(plain, { profile: 'deploy' }).errors, [], 'a secret without a value is fine');
});