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.

36.1 KB
Raw Blame
'use strict';

const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { loadCli } = require('./helpers/cli-harness.js');

const scriptPath = path.join(__dirname, '..', 'pcf-push.js');
const workspaceRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'pcf-push-workspace-'));

function resetWorkspace() {
  fs.rmSync(workspaceRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
  fs.mkdirSync(workspaceRoot, { recursive: true });
}

function makeProject(name, opts = {}) {
  const projectDir = path.join(workspaceRoot, name);
  fs.mkdirSync(path.join(projectDir, 'StarRating'), { recursive: true });
  fs.writeFileSync(path.join(projectDir, 'package.json'), JSON.stringify({ name, version: '1.0.0' }), 'utf8');
  fs.writeFileSync(path.join(projectDir, 'StarRating.pcfproj'), opts.pcfproj || productionPcfproj(), 'utf8');
  fs.writeFileSync(path.join(projectDir, 'StarRating', 'ControlManifest.Input.xml'), manifestXml(opts), 'utf8');
  return projectDir;
}

function productionPcfproj() {
  return [
    '<Project Sdk="Microsoft.NET.Sdk">',
    '  <Import Project="$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props" />',
    '  <PropertyGroup>',
    '    <Name>StarRating</Name>',
    '    <PcfBuildMode>production</PcfBuildMode>',
    '  </PropertyGroup>',
    '</Project>',
  ].join('\n');
}

function developmentPcfproj() {
  return productionPcfproj().replace('<PcfBuildMode>production</PcfBuildMode>', '<PcfBuildMode>development</PcfBuildMode>');
}

function ineffectivePcfproj() {
  return productionPcfproj()
    .replace('    <PcfBuildMode>production</PcfBuildMode>\n', '')
    .replace('  <Import Project="$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props" />', '  <PropertyGroup>\n    <PcfBuildMode>production</PcfBuildMode>\n  </PropertyGroup>\n  <Import Project="$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props" />');
}

function conditionedPcfproj() {
  return productionPcfproj()
    .replace('    <PcfBuildMode>production</PcfBuildMode>\n', '')
    .replace('  </PropertyGroup>', '  </PropertyGroup>\n  <PropertyGroup Condition="\'$(Configuration)\'==\'Release\'">\n    <PcfBuildMode>production</PcfBuildMode>\n  </PropertyGroup>');
}

function manifestXml(opts = {}) {
  const version = opts.version || '1.2.3';
  return [
    '<manifest>',
    `  <control namespace="Contoso.Controls" constructor="StarRating" version="${version}" display-name-key="StarRating" description-key="StarRating description" control-type="standard">`,
    '    <property name="value" display-name-key="Value" of-type="Whole.None" usage="bound" required="false" />',
    '    <resources><code path="index.ts" order="1" /></resources>',
    '  </control>',
    '</manifest>',
  ].join('\n');
}

async function run(argv, overrides = {}) {
  const calls = [];
  const emitted = { stdout: '', stderr: '', exitCode: null };
  const realAuth = require('../lib/dataverse-auth.js');
  const stubs = {
    './lib/dataverse-auth': {
      parseArgs: realAuth.parseArgs,
      validateFlags: realAuth.validateFlags,
      emitResult: (ok, payload) => {
        if (payload && typeof payload === 'object') emitted.stdout += `${JSON.stringify(payload)}\n`;
        else emitted.stderr += `${String(payload)}\n`;
        if (!ok && payload instanceof Error) emitted.stderr += `${payload.message}\n`;
        emitted.exitCode = ok ? 0 : 1;
        const err = new Error(`process.exit(${emitted.exitCode})`);
        err.exitCode = emitted.exitCode;
        throw err;
      },
    },
    './lib/pac-exec': {
      runPac: (args, options) => {
        calls.push(['runPac', args, options]);
        return overrides.runPac ? overrides.runPac(args, options) : { status: 0, stdout: 'pushed', stderr: '' };
      },
    },
    ...(overrides.requires || {}),
    './lib/pcf-dataverse': {
      makePcfSdk: async (env, workspace, httpClient) => {
        calls.push(['makePcfSdk', env, workspace]);
        if (overrides.makePcfSdk) return overrides.makePcfSdk(env, workspace, httpClient);
        return { tag: 'sdk' };
      },
      findCustomControl: async (sdk, name) => {
        calls.push(['findCustomControl', sdk, name]);
        if (overrides.findCustomControl) return overrides.findCustomControl(sdk, name);
        return { name, version: '1.2.3', componentState: 0 };
      },
      solutionPrefix: async (sdk, solution) => {
        calls.push(['solutionPrefix', sdk, solution]);
        if (overrides.solutionPrefix) return overrides.solutionPrefix(sdk, solution);
        return 'new';
      },
    },
  };
  const cli = loadCli(scriptPath, { argv, requires: stubs });
  cli.calls = calls;
  cli.emitted = emitted;
  assert.equal(typeof cli.main, 'function');
  try {
    await cli.main(argv);
  } catch (err) {
    if (!String(err && err.message).startsWith('process.exit(')) throw err;
  }
  if (emitted.exitCode !== null) {
    cli.stdoutText = () => emitted.stdout;
    cli.stderrText = () => emitted.stderr;
    Object.defineProperty(cli, 'exitCode', { get: () => emitted.exitCode });
  }
  return cli;
}

function withProcessRunnerStub(stub, fn) {
  const pacExecPath = require.resolve('../lib/pac-exec.js');
  const processRunnerPath = require.resolve('../lib/process-runner.js');
  const priorPacExec = require.cache[pacExecPath];
  const priorProcessRunner = require.cache[processRunnerPath];
  delete require.cache[pacExecPath];
  require.cache[processRunnerPath] = {
    id: processRunnerPath,
    filename: processRunnerPath,
    loaded: true,
    exports: stub,
  };
  return Promise.resolve()
    .then(fn)
    .finally(() => {
      delete require.cache[pacExecPath];
      if (priorPacExec) require.cache[pacExecPath] = priorPacExec;
      if (priorProcessRunner) require.cache[processRunnerPath] = priorProcessRunner;
      else delete require.cache[processRunnerPath];
    });
}

test.beforeEach(resetWorkspace);
test.after(() => fs.rmSync(workspaceRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));

test('happy path forwards exact pac argv, verifies registration, and writes a safe receipt', async () => {
  const projectDir = makeProject('happy');
  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--solution', 'ContosoPcf',
    '--verbosity', 'detailed',
  ]);

  assert.equal(cli.exitCode, 0);
  assert.deepEqual(cli.calls.find((call) => call[0] === 'runPac'), [
    'runPac',
    ['pcf', 'push', '--environment', 'https://contoso.crm.dynamics.com', '--solution-unique-name', 'ContosoPcf', '--verbosity', 'detailed'],
    { cwd: projectDir, timeoutMs: 15 * 60 * 1000 },
  ]);
  assert.deepEqual(cli.calls.filter((call) => call[0] === 'solutionPrefix').map((call) => call[2]), ['ContosoPcf']);
  assert.deepEqual(cli.calls.filter((call) => call[0] === 'findCustomControl').map((call) => call[2]), ['new_Contoso.Controls.StarRating']);

  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.ok, true);
  assert.deepEqual(payload.registered, { ok: true, version: '1.2.3', expected: '1.2.3' });
  assert.equal(payload.receipt, path.join(projectDir, 'pcf-receipt.json'));

  const receipt = JSON.parse(fs.readFileSync(path.join(projectDir, 'pcf-receipt.json'), 'utf8'));
  assert.equal(receipt.schemaVersion, 1);
  assert.equal(receipt.envOrigin, 'https://contoso.crm.dynamics.com');
  assert.equal(receipt.control, 'new_Contoso.Controls.StarRating');
  assert.equal(receipt.version, '1.2.3');
  assert.equal(receipt.solution, 'ContosoPcf');
  assert.equal(receipt.incremental, false);
  assert.deepEqual(receipt.tool.node, process.version);
  assert.match(receipt.pushedAt, /^\d{4}-\d{2}-\d{2}T/);
  assert.doesNotMatch(JSON.stringify(receipt), /token|Bearer|secret/i);
});

test('forwards --incremental with publisher prefix and skips read-back when --no-verify is set', async () => {
  const projectDir = makeProject('incremental');
  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
    '--incremental',
    '--no-verify',
  ]);

  assert.equal(cli.exitCode, 0);
  assert.deepEqual(cli.calls.find((call) => call[0] === 'runPac')[1], [
    'pcf', 'push', '--environment', 'https://contoso.crm.dynamics.com', '--publisher-prefix', 'abc', '--incremental', '--verbosity', 'minimal',
  ]);
  assert.equal(cli.calls.some((call) => call[0] === 'makePcfSdk'), false);
  const receipt = JSON.parse(fs.readFileSync(path.join(projectDir, 'pcf-receipt.json'), 'utf8'));
  assert.equal(receipt.publisherPrefix, 'abc');
  assert.equal(receipt.incremental, true);
  assert.deepEqual(receipt.registered, { ok: false, reason: 'not verified' });
});

test('rejects valued boolean deployment switches before project discovery or push', async () => {
  for (const [flag, value] of [['--allow-dev-bundle', 'false'], ['--no-verify', 'false'], ['--incremental', 'false']]) {
    let discovered = false;
    const cli = await run([
      '--project', 'D:\\tmp\\pcf-project',
      '--env', 'https://contoso.crm.dynamics.com',
      '--publisher-prefix', 'abc',
      `${flag}=${value}`,
    ], {
      requires: {
        './lib/pcf-build': {
          findControlProject: () => {
            discovered = true;
            return { error: 'project discovery should not run' };
          },
        },
      },
    });

    assert.equal(cli.exitCode, 1, flag);
    assert.match(cli.stderrText(), new RegExp(`${flag} does not take a value`), flag);
    assert.equal(cli.stdoutText(), '', flag);
    assert.equal(discovered, false, flag);
    assert.equal(cli.calls.some((call) => call[0] === 'runPac'), false, flag);
  }
});

test('rejects both solution and publisher-prefix as a usage error before push', async () => {
  const projectDir = makeProject('both-selectors');
  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--solution', 'One',
    '--publisher-prefix', 'abc',
  ]);

  assert.equal(cli.exitCode, 1);
  assert.match(cli.stderrText(), /Usage:/);
  assert.match(cli.stderrText(), /exactly one of --solution or --publisher-prefix/);
  assert.equal(cli.stdoutText(), '');
  assert.equal(cli.calls.some((call) => call[0] === 'runPac'), false);
});

test('push failure emits hints and appends the last 40 build log lines', async () => {
  const projectDir = makeProject('push-failure');
  fs.mkdirSync(path.join(projectDir, 'obj'), { recursive: true });
  fs.writeFileSync(path.join(projectDir, 'obj', 'pcf-push-build.log'), Array.from({ length: 45 }, (_, i) => `line-${i + 1}`).join('\n'), 'utf8');

  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
  ], {
    runPac: () => ({
      status: 1,
      stdout: 'Missing required tool dotnet',
      stderr: 'platform library fluent_9_68_0 with version 9.68.0 is not supported by the platform.',
    }),
  });

  assert.equal(cli.exitCode, 1);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.ok, false);
  assert.equal(payload.stage, 'push');
  assert.match(payload.hints.join('\n'), /Install or update the missing tool/);
  assert.match(payload.hints.join('\n'), /PLATFORM_LIB_VERSION/);
  assert.match(payload.hints.join('\n'), /pcf-upgrade\.js/);
  assert.equal(payload.logTail.length, 40);
  assert.equal(payload.logTail[0], 'line-6');
  assert.equal(payload.logTail[39], 'line-45');
});

test('a publish deadlock (SQL 1205) gets a wait-and-retry hint instead of the generic one', async () => {
  const projectDir = makeProject('publish-deadlock');

  // The stdout shape pac printed on a live push: the import succeeded, then the publish-all step
  // lost a deadlock to another publish running in the same environment.
  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
  ], {
    runPac: () => ({
      status: 1,
      stdout: [
        'Importing the temporary solution wrapper into the current org: done.',
        'Publishing All Customizations...',
        'Error:  Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205',
      ].join('\n'),
      stderr: '',
    }),
    // No Dataverse client can be made (no token), so the publish is not re-sent and pac's failure is reported with its hint.
    makePcfSdk: () => { throw new Error('az token unavailable'); },
  });

  assert.equal(cli.exitCode, 1);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.ok, false);
  assert.equal(payload.stage, 'push');
  assert.equal(payload.publishAttempts, 1);
  assert.match(payload.publishRetryError, /az token unavailable/);
  assert.equal(payload.hints.length, 1);
  assert.match(payload.hints[0], /deadlock victim \(SQL 1205\)/);
  // The inventory check needs --env: pcf-inventory.js rejects a call without it, so a hint that
  // omits it would hand the user a command that fails.
  assert.match(payload.hints[0], /pcf-inventory\.js --env <url> --control/);
  assert.match(payload.hints[0], /re-run the same push/);
  assert.doesNotMatch(payload.hints[0], /Review the pac pcf push output/);
});

// The pac output of a push whose import succeeded and whose publish-all step lost a SQL deadlock.
const DEADLOCK_TEXT = 'Error:  Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205';
const publishDeadlockPac = () => ({
  status: 1,
  stdout: ['Importing the temporary solution wrapper into the current org: done.', 'Publishing All Customizations...', DEADLOCK_TEXT].join('\n'),
  stderr: '',
});
// What the transport (lib/dataverse-auth.js makeRequest) resolves for a PublishAllXml: a JSON error answer, a deadlock victim, a success.
const wireJson = (statusCode, error) => ({ statusCode, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ error }) });
const deadlockAnswer = () => wireJson(500, { code: '0x80044150', message: ` ${DEADLOCK_TEXT.replace('Error:  ', '')}` });
const publishedAnswer = () => ({ statusCode: 204, headers: {}, body: '' });

// Runs a push whose publish re-send goes through the REAL stack: publishOnceClient, the shared HTTP client (sdk-http-client.js),
// makePcfSdk and the vendored SDK. Only the token, the transport and the waits are faked. `answers` are the transport's answers to each
// PublishAllXml in order (the last one repeats), so `posts` is what reached the wire, including any re-send a lower layer would add.
// Any other request fails the test: the re-send must send nothing but the publish.
async function runPublishRetry(name, answers, overrides = {}, clientDeps = {}) {
  const projectDir = makeProject(name);
  const posts = [];
  const sleeps = [];
  const realRetry = require('../lib/pcf-publish-retry.js');
  const { makePcfSdk } = require('../lib/pcf-dataverse.js');
  const request = async ({ method, url, body }) => {
    const pathname = new URL(url).pathname.replace(/^\/api\/data\/v[\d.]+/, '');
    if (!(method === 'POST' && pathname === '/PublishAllXml')) throw new Error(`unexpected request ${method} ${pathname}`);
    posts.push([method, pathname, body]);
    return answers[Math.min(posts.length - 1, answers.length - 1)];
  };
  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
  ], {
    runPac: publishDeadlockPac,
    makePcfSdk: (env, workspace, httpClient) => makePcfSdk(env, workspace, httpClient),
    requires: {
      './lib/pcf-publish-retry': {
        ...realRetry,
        publishOnceClient: (env) => realRetry.publishOnceClient(env, {
          getToken: () => 'fake-push-test-token-0123456789',
          request,
          sleep: async () => {},
          ...clientDeps,
        }),
        retryPublishAll: (dataverse, opts) => realRetry.retryPublishAll(dataverse, { ...opts, sleep: async (ms) => { sleeps.push(ms); } }),
      },
    },
    ...overrides,
  });
  return { cli, projectDir, posts, sleeps };
}

test('a publish deadlock is re-sent as PublishAllXml once and the push then succeeds without re-running pac', async () => {
  const { cli, posts, sleeps } = await runPublishRetry('publish-retry-ok', [publishedAnswer()]);

  assert.equal(cli.exitCode, 0);
  assert.equal(cli.calls.filter((call) => call[0] === 'runPac').length, 1);
  assert.deepEqual(posts, [['POST', '/PublishAllXml', '{}']]);
  assert.deepEqual(sleeps, [5000]);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.ok, true);
  assert.equal(payload.stage, 'done');
  assert.equal(payload.publishAttempts, 2);
  assert.deepEqual(payload.registered, { ok: true, version: '1.2.3', expected: '1.2.3' });
});

test('a publish that keeps deadlocking is sent at most twice more, then fails as before with the attempt count', async () => {
  const { cli, posts, sleeps } = await runPublishRetry('publish-retry-deadlock', [deadlockAnswer(), deadlockAnswer(), deadlockAnswer()]);

  assert.equal(cli.exitCode, 1);
  assert.equal(posts.length, 2);
  assert.deepEqual(sleeps, [5000, 15000]);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.ok, false);
  assert.equal(payload.stage, 'push');
  assert.equal(payload.status, 1);
  assert.equal(payload.publishAttempts, 3);
  assert.equal(payload.publishRetryError, undefined);
  assert.equal(payload.hints.length, 1);
  assert.match(payload.hints[0], /deadlock victim \(SQL 1205\)/);
  assert.equal(cli.calls.some((call) => call[0] === 'findCustomControl'), false);
});

test('a re-sent publish answered with another error is not sent again', async () => {
  const uniqueKey = wireJson(500, { code: '0x80044150', message: 'Sql error: duplicate key (Sql Number: 1205). CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 2627' });
  const { cli, posts } = await runPublishRetry('publish-retry-other', [uniqueKey, publishedAnswer()]);

  assert.equal(cli.exitCode, 1);
  assert.equal(posts.length, 1);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.stage, 'push');
  assert.equal(payload.publishAttempts, 2);
  assert.match(payload.publishRetryError, /^HTTP 500: .*Sql Number: 2627$/);
});

test('a re-sent publish whose answer was lost is not sent again', async () => {
  const lost = { error: 'socket hang up', code: 'ECONNRESET' };
  const { cli, posts } = await runPublishRetry('publish-retry-lost', [lost, publishedAnswer()]);

  assert.equal(cli.exitCode, 1);
  assert.equal(posts.length, 1);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.stage, 'push');
  assert.equal(payload.publishAttempts, 2);
  assert.match(payload.publishRetryError, /socket hang up/);
});

test('a SQL 1205 before the publish step, or any other push failure, is never re-sent', async () => {
  for (const [label, stdout] of [
    ['import deadlock', ['Importing the temporary solution wrapper into the current org...', DEADLOCK_TEXT].join('\n')],
    ['other publish error', ['Publishing All Customizations...', 'Error:  Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 2627'].join('\n')],
    ['tool failure', 'Missing required tool dotnet'],
  ]) {
    const { cli, posts } = await runPublishRetry(`publish-no-retry-${slugOf(label)}`, [publishedAnswer()], {
      runPac: () => ({ status: 1, stdout, stderr: '' }),
    });
    assert.equal(cli.exitCode, 1, label);
    assert.equal(posts.length, 0, label);
    assert.equal(cli.calls.some((call) => call[0] === 'makePcfSdk'), false, label);
    const payload = JSON.parse(cli.stdoutText());
    assert.equal(payload.stage, 'push', label);
    assert.equal(Object.prototype.hasOwnProperty.call(payload, 'publishAttempts'), false, label);
  }
});

// The shared HTTP client re-sends a publish refused with a 401 (after a token refresh) or a service-protection 429 on its own; under the
// deadlock re-send that would multiply the sends behind one reported attempt. Each answer must reach the wire exactly once.
for (const [label, answer, pattern] of [
  ['service-protection 429', { ...wireJson(429, { code: '0x80072322', message: 'Number of requests exceeded the limit of 6000 over time window of 300 seconds.' }), headers: { 'content-type': 'application/json', 'retry-after': '1' } }, /^HTTP 429: Number of requests exceeded/],
  ['401', wireJson(401, { code: '0x80072560', message: 'The user is not a member of the organization.' }), /^HTTP 401/],
]) {
  test(`a re-sent publish answered ${label} is sent exactly once and reported as two attempts`, async () => {
    const { cli, posts, sleeps } = await runPublishRetry(`publish-retry-${slugOf(label)}`, [answer, publishedAnswer()]);

    assert.equal(cli.exitCode, 1, label);
    assert.equal(posts.length, 1, label);
    assert.deepEqual(sleeps, [5000], label);
    const payload = JSON.parse(cli.stdoutText());
    assert.equal(payload.stage, 'push', label);
    assert.equal(payload.publishAttempts, 2, label);
    assert.match(payload.publishRetryError, pattern, label);
  });
}

test('a re-send that never reached the wire (no token) is not counted as an attempt', async () => {
  const { cli, posts } = await runPublishRetry('publish-retry-no-token', [publishedAnswer()], {}, {
    getToken: () => { throw new Error('az token unavailable'); },
  });

  assert.equal(cli.exitCode, 1);
  assert.equal(posts.length, 0);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.stage, 'push');
  assert.equal(payload.publishAttempts, 1);
  assert.match(payload.publishRetryError, /az token unavailable/);
});

function slugOf(label) {
  return label.replace(/\W+/g, '-');
}

test('push refusal from process-runner emits one JSON error through the real pac adapter', async () => {
  const projectDir = makeProject('runner-refusal');
  const refusal = Object.assign(new Error('cannot pass "%" to pac.cmd: a Windows batch file cannot receive % unchanged'), { code: 'EARGUMENT' });

  const cli = await withProcessRunnerStub({
    spawnResultSync: (name, args, options) => {
      assert.equal(name, 'pac');
      assert.deepEqual(args, ['pcf', 'push', '--environment', 'https://contoso.crm.dynamics.com', '--publisher-prefix', 'abc', '--verbosity', 'minimal']);
      assert.deepEqual(options, { encoding: 'utf8', cwd: projectDir, timeout: 15 * 60 * 1000 });
      return { status: null, stdout: '', stderr: '', error: refusal, signal: null };
    },
  }, () => run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
  ], {
    requires: { './lib/pac-exec': require('../lib/pac-exec.js') },
  }));

  assert.equal(cli.exitCode, 1);
  assert.equal(cli.stderrText(), '');
  const lines = cli.stdoutText().trim().split(/\r?\n/);
  assert.equal(lines.length, 1);
  const payload = JSON.parse(lines[0]);
  assert.equal(payload.ok, false);
  assert.equal(payload.stage, 'push');
  assert.equal(payload.status, 1);
  assert.match(payload.error, /cannot pass/);
  assert.match(payload.error, /Windows batch file/);
});

test('push failure scrubs build log tails before JSON output', async () => {
  const projectDir = makeProject('push-log-secret');
  fs.mkdirSync(path.join(projectDir, 'obj'), { recursive: true });
  fs.writeFileSync(path.join(projectDir, 'obj', 'pcf-push-build.log'), [
    'ordinary line',
    'client_secret=notasecret',
    'token eyJheader.eyJpayload.signature',
  ].join('\n'), 'utf8');

  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
  ], {
    runPac: () => ({ status: 1, stdout: '', stderr: '' }),
  });

  assert.equal(cli.exitCode, 1);
  const payload = JSON.parse(cli.stdoutText());
  assert.deepEqual(payload.logTail, ['ordinary line', 'client_secret=<redacted>', 'token <redacted-jwt>']);
  assert.doesNotMatch(JSON.stringify(payload), /notasecret|eyJheader/);
});

test('timeout reports best-effort state and log path without claiming the push was aborted', async () => {
  const projectDir = makeProject('timeout');
  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
  ], {
    runPac: () => ({ status: 1, stdout: '', stderr: '', error: Object.assign(new Error('spawnSync pac ETIMEDOUT'), { code: 'ETIMEDOUT' }), signal: 'SIGTERM' }),
  });

  assert.equal(cli.exitCode, 1);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.ok, false);
  assert.equal(payload.stage, 'push');
  assert.equal(payload.timedOut, true);
  assert.equal(payload.log, path.join(projectDir, 'obj', 'pcf-push-build.log'));
  assert.match(payload.message, /may still be running/i);
  assert.doesNotMatch(payload.message, /aborted|killed/i);
});

test('version mismatch makes the result fail with caching or publish guidance and still writes receipt', async () => {
  const projectDir = makeProject('mismatch');
  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
  ], {
    findCustomControl: async (sdk, name) => ({ name, version: '1.2.2', componentState: 0 }),
  });

  assert.equal(cli.exitCode, 1);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.ok, false);
  assert.deepEqual(payload.registered, {
    ok: false,
    version: '1.2.2',
    expected: '1.2.3',
    reason: 'Registered version does not match the manifest; Dataverse caching or the push/publish may not have taken effect yet.',
  });
  const receipt = JSON.parse(fs.readFileSync(path.join(projectDir, 'pcf-receipt.json'), 'utf8'));
  assert.deepEqual(receipt.registered, payload.registered);
});

test('read-back failures are captured in registered instead of crashing', async () => {
  const projectDir = makeProject('read-failure');
  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--solution', 'ContosoPcf',
  ], {
    solutionPrefix: async () => { throw new Error('publisher lookup failed'); },
  });

  assert.equal(cli.exitCode, 1);
  const payload = JSON.parse(cli.stdoutText());
  assert.deepEqual(payload.registered, { ok: false, reason: 'publisher lookup failed' });
});

test('refuses development and ineffective build modes unless --allow-dev-bundle is set', async () => {
  const devProject = makeProject('dev-mode', { pcfproj: developmentPcfproj() });
  const dev = await run(['--project', devProject, '--env', 'https://contoso.crm.dynamics.com', '--publisher-prefix', 'abc']);
  assert.equal(dev.exitCode, 1);
  assert.match(dev.stderrText(), /development bundle/i);
  assert.match(dev.stderrText(), /solution checker/i);
  assert.equal(dev.calls.some((call) => call[0] === 'runPac'), false);

  const ineffectiveProject = makeProject('ineffective-mode', { pcfproj: ineffectivePcfproj() });
  const ineffective = await run(['--project', ineffectiveProject, '--env', 'https://contoso.crm.dynamics.com', '--publisher-prefix', 'abc']);
  assert.equal(ineffective.exitCode, 1);
  assert.match(ineffective.stderrText(), /set but ineffective — move it below the Microsoft\.Common\.props import/);

  const allowed = await run(['--project', devProject, '--env', 'https://contoso.crm.dynamics.com', '--publisher-prefix', 'abc', '--allow-dev-bundle']);
  assert.equal(allowed.exitCode, 0);
  assert.equal(allowed.calls.some((call) => call[0] === 'runPac'), true);
});

test('refuses conditioned PcfBuildMode with Debug-specific guidance', async () => {
  const projectDir = makeProject('conditioned-mode', { pcfproj: conditionedPcfproj() });
  const cli = await run(['--project', projectDir, '--env', 'https://contoso.crm.dynamics.com', '--publisher-prefix', 'abc']);

  assert.equal(cli.exitCode, 1);
  assert.match(cli.stderrText(), /pac pcf push builds Debug/i);
  assert.match(cli.stderrText(), /make the production setting unconditional below the Microsoft\.Common\.props import/i);
  assert.doesNotMatch(cli.stderrText(), /move it below/);
  assert.equal(cli.calls.some((call) => call[0] === 'runPac'), false);
});

test('rejects invalid solution unique names before passing them to pac', async () => {
  const projectDir = makeProject('bad-solution-name');
  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--solution', 'Bad & Solution',
  ]);

  assert.equal(cli.exitCode, 1);
  assert.match(cli.stderrText(), /Solution unique name/);
  assert.equal(cli.calls.some((call) => call[0] === 'runPac'), false);
});

test('push failure emits scrubbed bounded stdout and stderr tails', async () => {
  const projectDir = makeProject('scrubbed-output');
  const jwt = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.signature';
  const stdout = Array.from({ length: 65 }, (_, i) => `out-${i + 1}`).join('\n') + `\nBearer secret-token\naccess_token=${jwt}`;
  const stderr = Array.from({ length: 64 }, (_, i) => `err-${i + 1}`).join('\n') + '\nclient_secret=abc123 password=p@ss';

  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
  ], {
    runPac: () => ({ status: 1, stdout, stderr }),
  });

  assert.equal(cli.exitCode, 1);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.stdout.length, 60);
  assert.equal(payload.stdout[0], 'out-8');
  assert.equal(payload.stdout.at(-2), 'Bearer <redacted>');
  assert.equal(payload.stdout.at(-1), 'access_token=<redacted>');
  assert.equal(payload.stderr.length, 60);
  assert.equal(payload.stderr[0], 'err-6');
  assert.equal(payload.stderr.at(-1), 'client_secret=<redacted> password=<redacted>');
  assert.doesNotMatch(JSON.stringify(payload), /secret-token|eyJhbGci|abc123|p@ss/);
});

test('push failure scrubs common secret shapes while preserving surrounding text', async () => {
  const projectDir = makeProject('secret-shapes');
  const rows = [
    ['query access token', 'prefix https://contoso.crm.dynamics.com/path?access_token=abc123&x=1 suffix', /abc123|\/path|\?access_token/, /prefix https:\/\/contoso\.crm\.dynamics\.com\/… suffix/],
    ['refresh token equals', 'prefix refresh_token=refresh-secret suffix', /refresh-secret/, /prefix refresh_token=<redacted> suffix/],
    ['id token colon', 'prefix id_token: id-secret suffix', /id-secret/, /prefix id_token: <redacted> suffix/],
    ['clientSecret json', 'prefix "clientSecret": "client-secret" suffix', /client-secret/, /prefix "clientSecret": "<redacted>" suffix/],
    ['pwd query', 'prefix https://example.test/callback?pwd=pwd-secret suffix', /pwd-secret|\/callback|\?pwd/, /prefix https:\/\/example\.test\/… suffix/],
    ['sig query', 'prefix https://storage.test/file.zip?sig=sig-secret suffix', /sig-secret|file\.zip|\?sig/, /prefix https:\/\/storage\.test\/… suffix/],
    ['diagnostic code equals', 'prefix error code=0x80040217 suffix', /auth-code-never-present/, /prefix error code=0x80040217 suffix/],
    ['authorization bearer', 'prefix Authorization: Bearer bearer-secret, suffix', /bearer-secret/, /prefix Authorization: Bearer <redacted>, suffix/],
    ['bare bearer', 'prefix Bearer bare-secret; suffix', /bare-secret/, /prefix Bearer <redacted>; suffix/],
    ['jwt', 'prefix eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.signature suffix', /eyJhbGci|eyJzdWIi|signature/, /prefix <redacted-jwt> suffix/],
    ['password json', 'prefix "password":"json-secret" suffix', /json-secret/, /prefix "password":"<redacted>" suffix/],
  ];

  const stdout = rows.map(([, line]) => line).join('\n');
  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
  ], {
    runPac: () => ({ status: 1, stdout, stderr: '' }),
  });

  assert.equal(cli.exitCode, 1);
  const payload = JSON.parse(cli.stdoutText());
  for (const [name, , secretPattern, surroundingPattern] of rows) {
    const line = payload.stdout.find((item) => surroundingPattern.test(item));
    assert.ok(line, `missing preserved surrounding text for ${name}: ${JSON.stringify(payload.stdout)}`);
    assert.doesNotMatch(line, secretPattern, name);
  }
});

test('push diagnostics preserve non-OAuth code text and URL schemes while redacting OAuth code contexts', async () => {
  const projectDir = makeProject('code-redaction-context');
  const stdout = [
    'error code=0x80040217',
    'exit code=1',
    'redirect http://localhost/callback?code=oauth-code&state=1',
    'authorization_code=form-code',
    'device_code=device-code',
  ].join('\n');

  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
  ], {
    runPac: () => ({ status: 1, stdout, stderr: '' }),
  });

  assert.equal(cli.exitCode, 1);
  const text = JSON.stringify(JSON.parse(cli.stdoutText()).stdout);
  assert.match(text, /error code=0x80040217/);
  assert.match(text, /exit code=1/);
  assert.match(text, /http:\/\/localhost\/…/);
  assert.match(text, /authorization_code=<redacted>/);
  assert.match(text, /device_code=<redacted>/);
  assert.doesNotMatch(text, /oauth-code|form-code|device-code/);
});

test('read-back exception text is scrubbed in stdout and receipt', async () => {
  const projectDir = makeProject('readback-secret');
  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--solution', 'ContosoPcf',
  ], {
    solutionPrefix: async () => { throw new Error('client_secret=notasecret eyJheader.eyJpayload.signature'); },
  });

  assert.equal(cli.exitCode, 1);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.registered.reason, 'client_secret=<redacted> <redacted-jwt>');
  const receipt = JSON.parse(fs.readFileSync(path.join(projectDir, 'pcf-receipt.json'), 'utf8'));
  assert.equal(receipt.registered.reason, 'client_secret=<redacted> <redacted-jwt>');
  assert.doesNotMatch(JSON.stringify(payload) + JSON.stringify(receipt), /notasecret|eyJheader/);
});

test('failed receipt write emits receipt-stage JSON and leaves no partial receipt behind', async () => {
  const projectDir = makeProject('receipt-write-failure');
  const realFs = require('node:fs');
  const fsStub = {
    ...realFs,
    renameSync: (from, to) => {
      if (String(to).endsWith('pcf-receipt.json')) throw new Error('rename failed');
      return realFs.renameSync(from, to);
    },
  };

  const cli = await run([
    '--project', projectDir,
    '--env', 'https://contoso.crm.dynamics.com',
    '--publisher-prefix', 'abc',
  ], { requires: { 'node:fs': fsStub } });

  assert.equal(cli.exitCode, 1);
  const payload = JSON.parse(cli.stdoutText());
  assert.equal(payload.ok, false);
  assert.equal(payload.stage, 'receipt');
  assert.match(payload.reason, /rename failed/);
  assert.deepEqual(payload.registered, { ok: true, version: '1.2.3', expected: '1.2.3' });
  assert.equal(realFs.existsSync(path.join(projectDir, 'pcf-receipt.json')), false);
  assert.deepEqual(realFs.readdirSync(projectDir).filter((entry) => entry.startsWith('.pcf-receipt-')), []);
});

// skill_completed telemetry: what a push's result says, in the closed vocabulary of lib/telemetry/skill-completed.js (a verbatim copy of
// model-apps', whose own suite holds the privacy contract) — never a control, solution or environment name.
test('pushCompletion maps each push result to its outcome, error class and registration', () => {
  const { pushCompletion } = require('../pcf-push.js');
  const info = (over) => ({ operation: 'control-push', incremental: false, registration: 'verified', steps: { push: { ok: 1 } }, ...over });
  assert.deepEqual(pushCompletion({ stage: 'done', ok: true, registered: true }), { outcome: 'success', eventInfo: info() });
  assert.deepEqual(pushCompletion({ stage: 'done', ok: true, registered: false, noVerify: true, incremental: true }),
    { outcome: 'success', eventInfo: info({ registration: 'skipped', incremental: true }) });
  assert.deepEqual(pushCompletion({ stage: 'done', ok: false, registered: false }),
    { outcome: 'failure', errorClass: 'verify-failed', eventInfo: info({ registration: 'not-verified' }) });
  assert.deepEqual(pushCompletion({ stage: 'receipt', registered: true }), { outcome: 'failure', errorClass: 'unexpected', eventInfo: info() });
  assert.deepEqual(pushCompletion({ stage: 'push', timedOut: true }),
    { outcome: 'failure', errorClass: 'timeout', eventInfo: info({ registration: 'not-verified', steps: { push: { error: 1 } }, haltPhase: 'push' }) });
  assert.deepEqual(pushCompletion({ stage: 'push' }),
    { outcome: 'failure', errorClass: 'deploy-failed', eventInfo: info({ registration: 'not-verified', steps: { push: { error: 1 } }, haltPhase: 'push' }) });
});