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.

33.0 KB
Raw Blame
'use strict';

const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const {
  HOST, fixtureRelease, createFixture, writeJson, modifyJson, installPackage,
  addDependency, runValidator,
} = require('./helpers/mobile-release-fixture');

function blocked(result, expression = /BLOCKED:/) {
  assert.equal(result.status, 2, result.stderr);
  assert.match(result.stderr, /^BLOCKED:/);
  assert.match(result.stderr, expression);
  assert.doesNotMatch(result.stderr, /fixture-secret-do-not-echo/);
}

test('empty or invalid validator stdin is a non-blocking no-op', (t) => {
  const fixture = createFixture(t);
  const hook = path.join(fixture.pluginRoot, 'hooks/validate-package-deps.js');
  for (const input of ['', '{', '[]']) {
    const result = spawnSync(process.execPath, [hook], {
      cwd: fixture.projectRoot, encoding: 'utf8', input,
    });
    assert.equal(result.status, 0, result.stderr);
    assert.equal(result.stderr, '');
  }
});

test('allows the version-matched release and its shipped haptics, not a snapshot name allowlist', (t) => {
  const fixture = createFixture(t);
  const result = runValidator(fixture);
  assert.equal(result.status, 0, result.stderr);
});

test('explicit validation reuses one installed inventory per invocation without missing new native code', t => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'ordinary-wrapper', '1.0.0');
  const plugin = path.resolve(__dirname, '../..');
  const instrumented = `
    const fs = require('node:fs');
    const path = require('node:path');
    const root = process.argv[1];
    const plugin = process.argv[2];
    const release = JSON.parse(fs.readFileSync(process.argv[3], 'utf8')).releases[0];
    require(path.join(plugin, 'scripts/lib/mobile-published-packages.js')).projectContract = () => release;
    const original = fs.readdirSync;
    let scans = 0;
    fs.readdirSync = function (directory, ...args) {
      if (path.resolve(directory) === path.join(root, 'node_modules')) scans++;
      return original.call(this, directory, ...args);
    };
    process.on('exit', () => fs.writeSync(1, String(scans)));
    require(path.join(plugin, 'hooks/validate-package-deps.js'));
  `;
  const invoke = () => spawnSync(process.execPath, [
    '-e', instrumented, fixture.projectRoot, plugin, path.join(fixture.pluginRoot, 'shared/fixture-contracts.json'),
  ], {
    cwd: fixture.projectRoot, encoding: 'utf8',
    env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },
    input: JSON.stringify({ tool_name: 'Write', tool_input: {
      file_path: path.join(fixture.projectRoot, 'package.json'),
      validation_mode: 'explicit-mobile-workflow',
    } }),
  });
  const initial = invoke();
  assert.equal(initial.status, 0, initial.stderr);
  assert.equal(initial.stdout, '1');
  fs.writeFileSync(path.join(fixture.projectRoot, 'node_modules/ordinary-wrapper/Bridge.swift'), 'import Foundation\n');
  const changed = invoke();
  blocked(changed, /Native\/runtime dependency|Unreviewed native/);
  assert.equal(changed.stdout, '1', 'Fresh validation must rescan once rather than retain stale package evidence');
});

test('blocks a new ambiguous dependency without exact plan approval', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0');
  blocked(runValidator(fixture), /user-approved JavaScript Dependencies plan/);
});

test('allows the exact installed JS-only dependency approved in the plan', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0');
  const result = runValidator(fixture, { approved: ['[email protected]'] });
  assert.equal(result.status, 0, result.stderr);
});

test('blocks mismatched or non-exact JS approval', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0');
  for (const approved of ['[email protected]', 'react-native-calendars@^1.1314.0']) {
    blocked(runValidator(fixture, { approved: [approved] }), /user-approved JavaScript Dependencies plan/);
  }
});

test('does not let plan approval bypass known native or Microsoft native-family packages', (t) => {
  for (const name of ['expo-notifications', '@microsoft/power-apps-native-controls']) {
    const fixture = createFixture(t);
    addDependency(fixture.projectRoot, name, '1.0.0');
    blocked(runValidator(fixture, { approved: [`${name}@1.0.0`] }), /Native\/runtime dependency/);
  }
});

test('allows ordinary JS packages, including scoped dependencies', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'date-fns', '4.1.0');
  addDependency(fixture.projectRoot, '@scope/calendar-tools', '2.3.4');
  const result = runValidator(fixture);
  assert.equal(result.status, 0, result.stderr);
});

test('explicit admission inspects ordinary-name packages that depend on the existing native runtime', (t) => {
  for (const section of ['dependencies', 'optionalDependencies']) {
    const fixture = createFixture(t);
    addDependency(fixture.projectRoot, 'ordinary-runtime-wrapper', '1.0.0', {
      properties: { [section]: { expo: '1.0.0' } },
    });
    blocked(runValidator(fixture, { approved: ['[email protected]'] }), /Native\/runtime dependency/);
  }
});

test('the dispatcher uses the isolated policy and preserves exact JS-approval parsing', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0');
  const invoke = (approval) => spawnSync(process.execPath, [
    path.join(fixture.pluginRoot, 'scripts/validate-mobile-files.js'),
    '--project-root', fixture.projectRoot, '--file', 'package.json',
    '--approved-js-dependency', approval,
  ], { cwd: fixture.projectRoot, encoding: 'utf8', env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' } });
  const approved = invoke('[email protected]');
  assert.equal(approved.status, 0, approved.stderr);
  const invalid = invoke('react-native-calendars@^1.1314.0');
  assert.equal(invalid.status, 1);
  assert.match(invalid.stderr, /Invalid --approved-js-dependency/);
});

test('upgrade file validation skips lock and installed-inventory admission but retains package policy', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'expo-custom-module', '1.0.0');
  const invoke = (upgrade) => spawnSync(process.execPath, [
    path.join(fixture.pluginRoot, 'scripts/validate-mobile-files.js'),
    '--project-root', fixture.projectRoot, '--file', 'package.json',
    ...(upgrade ? ['--upgrade-only'] : []),
  ], { cwd: fixture.projectRoot, encoding: 'utf8', env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' } });
  const result = invoke(true);
  assert.equal(result.status, 0, result.stderr);
  assert.match(result.stderr, /WARNING:.*does not verify Dev Player\/Wrap compatibility/);
  blocked(invoke(false), /Native\/runtime dependency/);
  fs.writeFileSync(path.join(fixture.projectRoot, 'package-lock.json'), 'not JSON');
  fs.writeFileSync(path.join(fixture.projectRoot, 'node_modules/expo-custom-module/package.json'), 'not JSON');
  assert.equal(invoke(true).status, 0);
  fs.unlinkSync(path.join(fixture.projectRoot, 'package-lock.json'));
  assert.equal(invoke(true).status, 0);
  writeJson(path.join(fixture.projectRoot, 'package-lock.json'), { lockfileVersion: 3, packages: { '': {} } });
  addDependency(fixture.projectRoot, 'axios', '1.0.0');
  blocked(invoke(true), /Forbidden dependency/);
});

test('local changed-file validation permits preinstall/native drift but retains package policy', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, '@microsoft/power-apps-native-controls', '1.0.0');
  const invoke = (...flags) => spawnSync(process.execPath, [
    path.join(fixture.pluginRoot, 'scripts/validate-mobile-files.js'),
    '--project-root', fixture.projectRoot, '--file', 'package.json', ...flags,
  ], {
    cwd: fixture.projectRoot, encoding: 'utf8',
    env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },
  });
  blocked(invoke(), /Native\/runtime dependency/);
  const result = invoke('--local-development');
  assert.equal(result.status, 0, result.stderr);
  assert.match(result.stderr, /WARNING: Local development[\s\S]*\/debug-app/);
  fs.unlinkSync(path.join(fixture.projectRoot, 'package-lock.json'));
  fs.rmSync(path.join(fixture.projectRoot, 'node_modules'), { recursive: true });
  assert.equal(invoke('--local-development').status, 0);
  modifyJson(path.join(fixture.projectRoot, 'package.json'), (pkg) => { pkg.dependencies.axios = '1.0.0'; });
  blocked(invoke('--local-development'), /Forbidden dependency/);
  modifyJson(path.join(fixture.projectRoot, 'package.json'), (pkg) => {
    delete pkg.dependencies.axios;
    pkg.dependencies['expo-msal-intune'] = '1.0.0';
  });
  blocked(invoke('--local-development'), /Vendor-only dependency/);
  assert.equal(invoke('--local-development', '--upgrade-only').status, 1);
});

test('local JS installation requires exact approval without release admission', (t) => {
  const { fixture } = calendarFixture(t);
  addDependency(fixture.projectRoot, '@microsoft/power-apps-native-controls', '1.0.0');
  const before = JSON.parse(fs.readFileSync(path.join(fixture.projectRoot, 'package.json'), 'utf8'));
  delete before.dependencies['react-native-calendars'];
  writeJson(path.join(fixture.projectRoot, 'before-install.json'), before);
  const invoke = (...approved) => spawnSync(process.execPath, [
    path.join(fixture.pluginRoot, 'scripts/validate-mobile-files.js'),
    '--project-root', fixture.projectRoot, '--local-development', '--file', 'package.json',
    '--before-package-json', 'before-install.json',
    ...approved.flatMap((entry) => ['--approved-js-dependency', entry]),
  ], {
    cwd: fixture.projectRoot, encoding: 'utf8',
    env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },
  });
  blocked(invoke(), /user-approved JavaScript Dependencies plan/);
  blocked(invoke('[email protected]'), /user-approved JavaScript Dependencies plan/);
  const approved = invoke('[email protected]');
  assert.equal(approved.status, 0, approved.stderr);
  fs.writeFileSync(path.join(fixture.projectRoot, 'package-lock.json'), 'invalid and unrelated');
  fs.writeFileSync(path.join(fixture.projectRoot, 'node_modules/expo-haptics/package.json'), 'invalid and unrelated');
  assert.equal(invoke('[email protected]').status, 0);
  modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => {
    pkg.version = '1.1300.0';
  });
  blocked(invoke('[email protected]'), /installed at its exact approved version/);
  fs.writeFileSync(path.join(fixture.projectRoot, 'before-install.json'), 'invalid snapshot');
  blocked(invoke('[email protected]'), /previous package.json/);
});

test('ordinary local work never reapproves or scans unchanged JavaScript packages', (t) => {
  const { fixture } = calendarFixture(t);
  const content = fs.readFileSync(path.join(fixture.projectRoot, 'package.json'), 'utf8');
  fs.writeFileSync(path.join(fixture.projectRoot, 'package-lock.json'), 'invalid and unrelated');
  fs.writeFileSync(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), 'invalid existing installation');
  for (const options of [
    { input: { validation_scope: 'local-development' } },
    { tool: 'Edit', input: { validation_scope: 'local-development', old_string: content, new_string: content } },
  ]) {
    const result = runValidator(fixture, options);
    assert.equal(result.status, 0, result.stderr);
  }
});

test('local edits enforce approval for added and changed JS dependencies, not existing rows', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'react-native-existing-ui', '1.0.0');
  for (const version of ['1.0.0', '2.0.0']) {
    const before = fs.readFileSync(path.join(fixture.projectRoot, 'package.json'), 'utf8');
    addDependency(fixture.projectRoot, 'ordinary-js-library', version);
    const input = {
      validation_scope: 'local-development', old_string: before,
      new_string: fs.readFileSync(path.join(fixture.projectRoot, 'package.json'), 'utf8'),
    };
    blocked(runValidator(fixture, { tool: 'Edit', input }), /user-approved JavaScript Dependencies plan/);
    const result = runValidator(fixture, { tool: 'Edit', input, approved: [`ordinary-js-library@${version}`] });
    assert.equal(result.status, 0, result.stderr);
  }
});

test('local JS inspection follows nested, hoisted and aliased dependencies without reading the lock', (t) => {
  const { fixture } = calendarFixture(t);
  addDependency(fixture.projectRoot, '@scope/helper', '1.0.0', { section: null });
  addDependency(fixture.projectRoot, 'helper-alias', '1.0.0', {
    section: null, installPath: 'node_modules/react-native-calendars/node_modules/helper-alias',
    properties: { name: 'canonical-helper' },
  });
  modifyJson(path.join(fixture.projectRoot, 'node_modules/@scope/helper/package.json'), (pkg) => {
    pkg.dependencies = { 'react-native-calendars': '*' };
  });
  modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => {
    pkg.dependencies = { '@scope/helper': '*', 'helper-alias': 'npm:[email protected]' };
    pkg.optionalDependencies = { 'missing-optional-helper': '1.0.0' };
  });
  writeJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/node_modules/unrelated/package.json'), { invalid: true });
  fs.writeFileSync(path.join(fixture.projectRoot, 'package-lock.json'), 'invalid and unrelated');
  const invoke = () => runValidator(fixture, {
    approved: ['[email protected]'], input: { validation_scope: 'local-development' },
  });
  const result = invoke();
  assert.equal(result.status, 0, result.stderr);
  modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/node_modules/helper-alias/package.json'), (pkg) => {
    pkg.codegenConfig = {};
  });
  blocked(invoke(), /native\/runtime/i);
});

test('a local dependency snapshot cannot replace the manifest validation target', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'axios', '1.0.0');
  const result = spawnSync(process.execPath, [
    path.join(fixture.pluginRoot, 'scripts/validate-mobile-files.js'),
    '--project-root', fixture.projectRoot, '--local-development', '--file', 'package.json',
    '--before-package-json', 'package.json',
  ], {
    cwd: fixture.projectRoot, encoding: 'utf8',
    env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },
  });
  blocked(result, /separate pre-install snapshot/);
});

test('local JS approval cannot bypass native contents or transitive native dependencies', (t) => {
  for (const transitive of [false, true]) {
    const fixture = createFixture(t);
    addDependency(fixture.projectRoot, 'ordinary-js-wrapper', '1.0.0', {
      properties: transitive ? { dependencies: { 'native-child': '1.0.0' } } : { codegenConfig: {} },
    });
    if (transitive) addDependency(fixture.projectRoot, 'native-child', '1.0.0', {
      section: null, properties: { codegenConfig: {} },
    });
    blocked(runValidator(fixture, {
      approved: ['[email protected]'], input: { validation_scope: 'local-development' },
    }), /contains native\/runtime code/);
  }
});

test('old apps are admitted by their release, not by a newer default release', (t) => {
  const old = fixtureRelease();
  const newest = fixtureRelease(2);
  newest.managedDependencies.dependencies['expo-notifications'] = '2.0.0';
  newest.nativePackages['node_modules/expo-notifications'] = '2.0.0';
  const fixture = createFixture(t, {
    release: old,
    catalog: { schemaVersion: 1, defaultRelease: newest.id, releases: [old, newest] },
  });
  assert.equal(runValidator(fixture).status, 0);
  addDependency(fixture.projectRoot, 'expo-notifications', '2.0.0');
  blocked(runValidator(fixture), /Native\/runtime dependency/);
});

test('unknown, missing or malformed policy fails closed without reading template dependencies', (t) => {
  for (const mode of ['empty', 'missing', 'malformed']) {
    const fixture = createFixture(t);
    const policy = path.join(fixture.pluginRoot, 'shared/fixture-contracts.json');
    if (mode === 'empty') writeJson(policy, { schemaVersion: 1, defaultRelease: null, releases: [] });
    if (mode === 'missing') fs.rmSync(policy);
    if (mode === 'malformed') fs.writeFileSync(policy, '{"fixture-secret-do-not-echo":');
    blocked(runValidator(fixture), /verified mobile|mobile release policy|Unable to verify package dependencies/);
  }
});

test('does not exempt the bundled template path from release admission', (t) => {
  const fixture = createFixture(t);
  const template = path.join(fixture.pluginRoot, 'template');
  fs.cpSync(fixture.projectRoot, template, { recursive: true });
  fixture.projectRoot = template;
  addDependency(template, '@microsoft/power-apps-native-controls', '1.0.0');
  blocked(runValidator(fixture), /Native\/runtime dependency/);
});

test('rejects absent protected metadata and runtime versions changed to unknown values', (t) => {
  for (const edit of [
    (config) => { delete config.expo.extra.powerappsNative; },
    (config) => { config.expo.extra.powerappsNative.nativeRuntimeVersions.ios = 99; },
  ]) {
    const fixture = createFixture(t);
    modifyJson(path.join(fixture.projectRoot, 'app.json'), edit);
    blocked(runValidator(fixture), /metadata|runtime/);
  }
});

test('managed declarations must match the selected release even when the app lock was updated', (t) => {
  const fixture = createFixture(t);
  for (const file of ['package.json', 'package-lock.json']) {
    modifyJson(path.join(fixture.projectRoot, file), (data) => {
      const root = data.packages ? data.packages[''] : data;
      root.dependencies[HOST] = '^1.1.0';
    });
  }
  blocked(runValidator(fixture), /Managed dependency/);
});

test('a JS-only host remains runtime-sensitive and its installed version cannot drift', (t) => {
  const fixture = createFixture(t);
  modifyJson(path.join(fixture.projectRoot, 'node_modules', HOST, 'package.json'), (pkg) => { pkg.version = '1.0.1'; });
  modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => {
    lock.packages[`node_modules/${HOST}`].version = '1.0.1';
  });
  blocked(runValidator(fixture), /native inventory/);
});

test('nested first-party instances must match a reviewed identity and version', (t) => {
  const release = fixtureRelease();
  const nested = 'node_modules/expo/node_modules/@microsoft/power-apps-native-common';
  release.nativePackages[nested] = '1.0.0';
  const fixture = createFixture(t, { release });
  assert.equal(runValidator(fixture).status, 0);
  installPackage(fixture.projectRoot, nested, '1.0.1', { codegenConfig: {} });
  modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => { lock.packages[nested].version = '1.0.1'; });
  blocked(runValidator(fixture), /nested package versions/);
});

for (const [label, relativeFile, properties] of [
  ['native source', 'source/bridge/Bridge.swift', {}],
  ['podspec', 'ordinary-widget.podspec', {}],
  ['codegen', null, { codegenConfig: {} }],
  ['Expo module', 'expo-module.config.json', {}],
  ['Expo config plugin', 'app.plugin.js', {}],
  ['platform project', 'android/build.gradle', {}],
]) {
  test(`detects an ordinary-name dependency through ${label}`, (t) => {
    const fixture = createFixture(t);
    addDependency(fixture.projectRoot, 'ordinary-widget', '1.0.0', { properties });
    if (relativeFile) {
      const target = path.join(fixture.projectRoot, 'node_modules/ordinary-widget', relativeFile);
      fs.mkdirSync(path.dirname(target), { recursive: true });
      fs.writeFileSync(target, '');
    }
    blocked(runValidator(fixture, { approved: ['[email protected]'] }), /Native\/runtime dependency|Unreviewed native/);
  });
}

test('JS approval cannot hide native code in an ambiguous react-native package', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0', { properties: { codegenConfig: {} } });
  blocked(runValidator(fixture, { approved: ['[email protected]'] }), /Native\/runtime dependency/);
});

test('detects ordinary-name native modules in a JS dependency transitive closure', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'ordinary-ui', '1.0.0', { properties: { dependencies: { 'ordinary-bridge': '1.0.0' } } });
  addDependency(fixture.projectRoot, 'ordinary-bridge', '1.0.0', {
    section: null, installPath: 'node_modules/ordinary-ui/node_modules/ordinary-bridge', properties: { codegenConfig: {} },
  });
  blocked(runValidator(fixture), /Native\/runtime dependency/);
});

test('rejects malformed package, app, lock and installed JSON without leaking content', (t) => {
  for (const file of ['package.json', 'app.json', 'package-lock.json', `node_modules/${HOST}/package.json`]) {
    const fixture = createFixture(t);
    fs.writeFileSync(path.join(fixture.projectRoot, file), '{"fixture-secret-do-not-echo":');
    blocked(runValidator(fixture), /JSON|json|manifest/);
  }
});

test('preserves forbidden dependencies in every declaration section', (t) => {
  for (const section of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {
    const fixture = createFixture(t);
    addDependency(fixture.projectRoot, 'axios', '1.0.0', { section });
    blocked(runValidator(fixture), /Forbidden dependency `axios`/);
  }
});

test('preserves vendor-only archive requirements without echoing registry credentials', (t) => {
  const fixture = createFixture(t);
  modifyJson(path.join(fixture.projectRoot, 'package.json'), (pkg) => {
    pkg.dependencies['expo-msal-intune'] = 'https://user:[email protected]/archive.tgz';
  });
  blocked(runValidator(fixture), /Vendor-only dependency/);
});

test('allows a reviewed vendor archive declaration, never an arbitrary file path', (t) => {
  const release = fixtureRelease();
  release.managedDependencies.dependencies['expo-msal-intune'] = 'file:./vendor/fixture-auth-1.0.0.tgz';
  release.nativePackages['node_modules/expo-msal-intune'] = '1.0.0';
  const fixture = createFixture(t, { release });
  assert.equal(runValidator(fixture).status, 0);
  modifyJson(path.join(fixture.projectRoot, 'package.json'), (pkg) => {
    pkg.dependencies['expo-msal-intune'] = 'file:../outside.tgz';
  });
  blocked(runValidator(fixture), /Vendor-only dependency/);
});

test('legacy edits preserve their reconstructed baseline without requiring release metadata', (t) => {
  const fixture = createFixture(t);
  fs.rmSync(path.join(fixture.projectRoot, 'app.json'));
  addDependency(fixture.projectRoot, 'date-fns', '4.1.0');
  const result = runValidator(fixture, { explicit: false, tool: 'Edit', input: { old_string: '"fixture-before"', new_string: '"fixture-mobile-app"' } });
  assert.equal(result.status, 0, result.stderr);
});

test('legacy edits block known native declaration drift even after npm rewrites the lock', (t) => {
  const fixture = createFixture(t);
  const result = runValidator(fixture, {
    explicit: false, tool: 'Edit', input: { old_string: `"${HOST}": "^0.9.0"`, new_string: `"${HOST}": "^1.0.0"` },
  });
  blocked(result, /Native\/runtime dependency/);
});

test('legacy edits block installed native drift against the lock', (t) => {
  const fixture = createFixture(t);
  modifyJson(path.join(fixture.projectRoot, 'node_modules/expo/package.json'), (pkg) => { pkg.version = '1.0.1'; });
  blocked(runValidator(fixture, { explicit: false }), /native dependency drift/);
});

test('legacy validation rejects deletion of known or detected native baseline dependencies', (t) => {
  for (const tool of ['Write', 'Edit', 'MultiEdit']) {
    for (const name of ['expo', HOST, 'ordinary-native']) {
      const fixture = createFixture(t);
      if (name === 'ordinary-native') {
        addDependency(fixture.projectRoot, name, '1.0.0', { properties: { codegenConfig: {} } });
      }
      const file = path.join(fixture.projectRoot, 'package.json');
      const before = fs.readFileSync(file, 'utf8');
      modifyJson(file, (pkg) => { delete pkg.dependencies[name]; });
      const after = fs.readFileSync(file, 'utf8');
      const edit = { old_string: before, new_string: after };
      blocked(runValidator(fixture, {
        explicit: false, tool,
        input: tool === 'Write' ? {} : tool === 'MultiEdit' ? { edits: [edit] } : edit,
      }), /Native\/runtime dependency/);
    }
  }
});

test('legacy validation still allows deleting an ordinary JavaScript dependency', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'date-fns', '4.1.0');
  modifyJson(path.join(fixture.projectRoot, 'package.json'), (pkg) => { delete pkg.dependencies['date-fns']; });
  const result = runValidator(fixture, { explicit: false });
  assert.equal(result.status, 0, result.stderr);
});

test('legacy edits detect transitive native additions with an ordinary root package name', (t) => {
  const fixture = createFixture(t);
  addDependency(fixture.projectRoot, 'ordinary-ui', '1.0.0', { properties: { dependencies: { 'ordinary-bridge': '1.0.0' } } });
  addDependency(fixture.projectRoot, 'ordinary-bridge', '1.0.0', {
    section: null, installPath: 'node_modules/ordinary-ui/node_modules/ordinary-bridge', properties: { codegenConfig: {} },
  });
  const result = runValidator(fixture, {
    explicit: false, tool: 'Edit', input: { old_string: '', new_string: ',\n    "ordinary-ui": "1.0.0"' },
  });
  blocked(result, /Native\/runtime dependency/);
});

test('legacy fresh JS-only writes remain allowed without metadata or an installation', (t) => {
  const fixture = createFixture(t);
  fs.rmSync(path.join(fixture.projectRoot, 'node_modules'), { recursive: true });
  fs.rmSync(path.join(fixture.projectRoot, 'package-lock.json'));
  writeJson(path.join(fixture.projectRoot, 'package.json'), { dependencies: { 'date-fns': '4.1.0' } });
  assert.equal(runValidator(fixture, { explicit: false }).status, 0);
  writeJson(path.join(fixture.projectRoot, 'package.json'), { dependencies: { '@microsoft/power-apps-native-controls': '1.0.0' } });
  blocked(runValidator(fixture, { explicit: false }), /Native\/runtime dependency/);
});

test('legacy malformed package JSON also fails closed', (t) => {
  const fixture = createFixture(t);
  fs.writeFileSync(path.join(fixture.projectRoot, 'package.json'), '{');
  blocked(runValidator(fixture, { explicit: false }), /malformed package.json/);
});

function calendarFixture(t) {
  const release = fixtureRelease();
  for (const [name, version] of Object.entries({ react: '19.2.0', 'react-native': '0.83.6' })) {
    release.managedDependencies.dependencies[name] = version;
    release.nativePackages[`node_modules/${name}`] = version;
  }
  const fixture = createFixture(t, { release });
  const before = fs.readFileSync(path.join(fixture.projectRoot, 'package.json'), 'utf8');
  addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0', {
    properties: { peerDependencies: { react: '>=16.3.0', 'react-native': '>=0.60.0' } },
  });
  return { fixture, before };
}

function validateCalendarEdit(fixture, before, tool = 'Edit') {
  const after = fs.readFileSync(path.join(fixture.projectRoot, 'package.json'), 'utf8');
  const edit = { old_string: before, new_string: after };
  return runValidator(fixture, {
    explicit: false, tool, approved: ['[email protected]'],
    input: tool === 'MultiEdit' ? { edits: [edit] } : edit,
  });
}

test('legacy Edit and MultiEdit admit approved JS UI libraries using existing unchanged React/RN peers', (t) => {
  for (const tool of ['Edit', 'MultiEdit']) {
    const { fixture, before } = calendarFixture(t);
    const result = validateCalendarEdit(fixture, before, tool);
    assert.equal(result.status, 0, result.stderr);
    const unapproved = runValidator(fixture, {
      explicit: false, tool: 'Edit',
      input: { old_string: before, new_string: fs.readFileSync(path.join(fixture.projectRoot, 'package.json'), 'utf8') },
    });
    blocked(unapproved, /user-approved JavaScript Dependencies plan/);
  }
});

test('explicit admission preserves approved JavaScript UI reuse of unchanged React/RN peers', (t) => {
  const { fixture } = calendarFixture(t);
  const result = runValidator(fixture, { approved: ['[email protected]'] });
  assert.equal(result.status, 0, result.stderr);
});

test('legacy JS peer reuse does not excuse changed root runtime declarations or installed native versions', (t) => {
  for (const updateLock of [false, true]) {
    const { fixture, before } = calendarFixture(t);
    modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native/package.json'), (pkg) => { pkg.version = '0.83.7'; });
    if (updateLock) {
      for (const file of ['package.json', 'package-lock.json']) modifyJson(path.join(fixture.projectRoot, file), (value) => {
        (value.packages?.[''] || value).dependencies['react-native'] = '0.83.7';
        if (value.packages) value.packages['node_modules/react-native'].version = '0.83.7';
      });
    }
    blocked(validateCalendarEdit(fixture, before, 'MultiEdit'), /native dependency drift|Native\/runtime dependency/);
  }
});

test('updating the app lock cannot hide installed runtime drift against an unchanged exact before-pin', (t) => {
  const { fixture, before } = calendarFixture(t);
  modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native/package.json'), (pkg) => { pkg.version = '0.83.7'; });
  modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => { lock.packages['node_modules/react-native'].version = '0.83.7'; });
  blocked(validateCalendarEdit(fixture, before), /native dependency drift/);
});

test('approved JS UI may consume a JS transitive helper that reuses unchanged React/RN peers', (t) => {
  const { fixture, before } = calendarFixture(t);
  addDependency(fixture.projectRoot, 'react-native-swipe-gestures', '1.0.5', {
    section: null, properties: { peerDependencies: { react: '*', 'react-native': '*' } },
  });
  modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => {
    pkg.dependencies = { 'react-native-swipe-gestures': '^1.0.5' };
  });
  const result = validateCalendarEdit(fixture, before, 'MultiEdit');
  assert.equal(result.status, 0, result.stderr);
});

test('legacy JS peer reuse never admits native source, new native children or nested runtime peers', (t) => {
  for (const mutate of [
    (fixture) => modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => { pkg.codegenConfig = {}; }),
    (fixture) => {
      addDependency(fixture.projectRoot, 'react-native', '0.82.0', {
        section: null, installPath: 'node_modules/react-native-calendars/node_modules/react-native',
      });
    },
    (fixture) => {
      const dependencies = { 'ordinary-native-child': '1.0.0' };
      modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => { pkg.dependencies = dependencies; });
      addDependency(fixture.projectRoot, 'ordinary-native-child', '1.0.0', {
        section: null, properties: { codegenConfig: {} },
      });
    },
  ]) {
    const { fixture, before } = calendarFixture(t);
    mutate(fixture);
    blocked(validateCalendarEdit(fixture, before), /Native\/runtime dependency/);
  }
});

test('a newly introduced root native peer cannot be treated as an existing runtime', (t) => {
  const { fixture, before } = calendarFixture(t);
  addDependency(fixture.projectRoot, 'react-native-screens', '4.23.0');
  modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => {
    pkg.peerDependencies['react-native-screens'] = '>=4.0.0';
  });
  blocked(validateCalendarEdit(fixture, before), /Native\/runtime dependency/);
});

test('React as a hard native/runtime dependency does not borrow the unchanged-peer exception', (t) => {
  const { fixture, before } = calendarFixture(t);
  modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => {
    pkg.dependencies = { react: '19.2.0' };
  });
  blocked(validateCalendarEdit(fixture, before), /Native\/runtime dependency/);
});

test('JS alias support does not bypass forbidden-library and vendor-only rules', (t) => {
  for (const canonical of ['axios', 'lucide-react', 'expo-msal-intune']) {
    const fixture = createFixture(t);
    addDependency(fixture.projectRoot, 'friendly-alias', '1.0.0', { properties: { name: canonical } });
    for (const file of ['package.json', 'package-lock.json']) modifyJson(path.join(fixture.projectRoot, file), (value) => {
      (value.packages?.[''] || value).dependencies['friendly-alias'] = `npm:${canonical}@1.0.0`;
      if (value.packages) value.packages['node_modules/friendly-alias'].name = canonical;
    });
    blocked(runValidator(fixture), /Forbidden dependency|Vendor-only dependency/);
    blocked(runValidator(fixture, { explicit: false }), /Forbidden dependency|Vendor-only dependency/);
  }
});