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.

22.8 KB
Raw Blame
#!/usr/bin/env node
'use strict';

// Writes two files into a working dir to make it editor-friendly:
//   package.json   — installable manifest with the deps from
//                    scripts/lib/supported-dependencies.js
//   genpage.d.ts   — ambient global declarations only: `window.Xrm` and
//                    the bare `Xrm` identifier with the navigation/utility
//                    surface used by generative pages, plus the
//                    `__genpage_*` window cache-key index signature
//                    `GeneratedComponentProps` is exported by
//                    RuntimeTypes.ts and is intentionally not re-declared
//                    here.
//
// Run by the /genpage orchestrator in Phase 0.5 (after working-dir creation).
// Keeps existing files by default, but an existing package.json must already list
// every package the requested features need — otherwise the run fails (exit 2) and
// names them, rather than report success over a manifest `npm install` cannot use.
// A package present at a different version is kept and reported as `versionDrift`.
// Pass --force to overwrite.
//
// Usage:
//   node generate-page-manifest.js <working-dir> <page-slug> [--features <list>] [--force]
//
// Arguments:
//   <working-dir>  Path to the working directory (relative or absolute)
//   <page-slug>    Used as the package "name" field (e.g., "account-card-gallery")
//
// Flags:
//   --features <list>  Comma-separated feature flags to include extra deps.
//                      Supported: charts, datepicker, timepicker
//   --force            Overwrite existing files instead of preserving them.
//
// Exit codes:
//   0 success
//   1 invalid arguments
//   2 I/O error, or an existing package.json that lacks a required package or cannot be verified

const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const {
  RUNTIME_DEPENDENCIES,
  DEV_DEPENDENCIES,
  buildDependencyMap,
  buildDevDependencyMap,
  FEATURE_RUNTIME_KEYS,
} = require('./lib/supported-dependencies.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');

const VALID_FEATURES = new Set(Object.keys(FEATURE_RUNTIME_KEYS));

function parseArgs(argv) {
  const args = { positional: [], features: [], force: false };
  for (let i = 0; i < argv.length; i++) {
    const a = argv[i];
    if (a === '--force') args.force = true;
    else if (a === '--features') {
      const list = argv[++i];
      if (!list) throw new Error('--features requires a comma-separated value');
      args.features = list.split(',').map((s) => s.trim()).filter(Boolean);
    } else if (a === '--help' || a === '-h') {
      printHelp();
      process.exit(0);
    } else if (a.startsWith('--')) {
      throw new Error(`Unknown flag: ${a}`);
    } else {
      args.positional.push(a);
    }
  }
  if (args.positional.length !== 2) {
    throw new Error('expected <working-dir> <page-slug> as positional arguments');
  }
  for (const f of args.features) {
    if (!VALID_FEATURES.has(f)) {
      throw new Error(`Unknown feature '${f}'. Valid: ${[...VALID_FEATURES].join(', ')}`);
    }
  }
  return args;
}

function printHelp() {
  console.log(`Usage: generate-page-manifest.js <working-dir> <page-slug> [options]

Options:
  --features <list>  Comma-separated feature flags (charts, datepicker, timepicker)
  --force            Overwrite existing package.json / genpage.d.ts
  --help             Show this message

Writes package.json and genpage.d.ts into <working-dir>.
`);
}

function buildPackageJson(slug, features) {
  return {
    name: slug,
    private: true,
    version: '0.0.1',
    description: `Local development manifest for genpage '${slug}' (auto-generated by /genpage Phase 0.5).`,
    dependencies: buildDependencyMap(features),
    devDependencies: buildDevDependencyMap(features),
    // No scripts — the runtime owns build and deploy.
    // The page is deployed from <page>.tsx itself: genpage-upload.js sends its text.
  };
}

// What an existing package.json lacks for the requested page, split by severity. A package ABSENT from
// both dependency sections breaks `npm install` for the page's imports, so the command must not report
// success. A package present at a DIFFERENT version is left alone: pinning or bumping a version is a
// legitimate edit, and failing on it would make every rerun fail unless `--force` discarded that edit.
// It is still reported (`drift`), so a pin left behind by an older plugin release is visible.
function comparePackageDependencies(pkg, expectedDependencies, expectedDevDependencies) {
  const section = (key) => (pkg && pkg[key] && typeof pkg[key] === 'object' && !Array.isArray(pkg[key]) ? pkg[key] : {});
  // Either section installs the package, so either satisfies it — but only with a version npm can use. A key
  // whose value is null, an object or an empty string installs nothing, so it counts as missing (not as a
  // version that drifted), and it never hides a usable entry for the same package in the other section.
  const usable = (v) => typeof v === 'string' && v.trim() !== '';
  const installed = {};
  for (const key of ['devDependencies', 'dependencies']) {
    for (const [name, version] of Object.entries(section(key))) if (usable(version)) installed[name] = version;
  }
  const missing = [];
  const drift = [];
  const check = (group, expected) => {
    for (const [name, version] of Object.entries(expected)) {
      if (!Object.prototype.hasOwnProperty.call(installed, name)) missing.push(`${group}.${name}=${version}`);
      else if (installed[name] !== version) drift.push(`${name} ${installed[name]} (generated pages expect ${version})`);
    }
  };
  check('dependencies', expectedDependencies);
  check('devDependencies', expectedDevDependencies);
  return { missing, drift };
}

function validateExistingPackageJson(filePath, expectedPkg) {
  let st = null;
  try {
    st = fs.lstatSync(filePath);
  } catch (err) {
    if (err.code === 'ENOENT') return null;
    const e = new Error(`existing package.json could not be inspected (${err.code || err.message})`);
    e.code = 'STALE_MANIFEST';
    throw e;
  }
  if (!st.isFile()) {
    // Not read through, and `--force` is no way out either: writeIfAllowed refuses a non-regular leaf.
    const kind = st.isSymbolicLink() ? 'symbolic link' : st.isDirectory() ? 'directory' : 'special file';
    const e = new Error(`existing package.json is a ${kind}, so its dependencies cannot be verified and it is never written through; replace it with a regular file and rerun`);
    e.code = 'STALE_MANIFEST';
    throw e;
  }

  let existing;
  try {
    // One leading UTF-8 byte-order mark is dropped: Windows PowerShell's `Set-Content -Encoding UTF8` writes
    // one, npm reads such a manifest fine, and JSON.parse refuses it — so a valid package.json halted every
    // rerun. The file itself is left as it is.
    existing = JSON.parse(fs.readFileSync(filePath, 'utf8').replace(/^\uFEFF/, ''));
  } catch (err) {
    const e = new Error(`existing package.json could not be parsed, so its dependencies cannot be verified (${err.message}); fix it or rerun with --force`);
    e.code = 'STALE_MANIFEST';
    throw e;
  }

  const { missing, drift } = comparePackageDependencies(existing, expectedPkg.dependencies, expectedPkg.devDependencies);
  if (missing.length > 0) {
    // Reruns without --force preserve user edits, so reporting success here would leave VS Code and
    // `npm install` with a package that cannot satisfy the feature imports the command just accepted.
    const e = new Error(
      `existing package.json is missing requested generated-page dependencies: ${missing.join(', ')}. ` +
      'Rerun with --force to regenerate it, or merge these dependencies by hand and rerun.'
    );
    e.code = 'STALE_MANIFEST';
    throw e;
  }
  return { drift };
}

// Static ambient declarations for the genux runtime. Same content for every
// working dir — no parameterization.
function buildAmbientDeclarations() {
  return `// Auto-generated by /genpage Phase 0.5 (do not edit by hand).
//
// Provides type definitions for runtime globals injected by the Power Apps
// model-driven app shell. After this file exists alongside the page's .tsx,
// the page can use \`window.Xrm.Navigation.navigateTo(...)\` without
// \`(window as any).\` casts.
//
// Regenerate by running:
//   node \${PLUGIN_ROOT}/scripts/generate-page-manifest.js <dir> <slug> --force

export {};

declare global {
    /** Subset of Xrm v9 surface used by generative pages. Extend as needed. */
    interface XrmShape {
        Navigation: {
            navigateTo: (
                pageInput: XrmPageInput,
                navigationOptions?: { target?: 1 | 2 },
            ) => Promise<XrmNavigationResult>;
            openForm: (
                formOptions: { entityName: string; entityId?: string },
                formParameters?: Record<string, unknown>,
            ) => Promise<unknown>;
            openUrl: (url: string, options?: { target?: 1 | 2 }) => void;
        };
        Utility: {
            getGlobalContext: () => XrmGlobalContext;
        };
    }

    type XrmPageInput =
        | { pageType: 'entityrecord'; entityName: string; entityId?: string }
        | { pageType: 'entitylist'; entityName: string }
        | {
            pageType: 'custom';
            pageId: string;
            entityName?: string;
            recordId?: string;
            data?: Record<string, unknown>;
        }
        | {
            /** Cross-page navigation between generative pages — see rules.md PAGEREF_ placeholder. */
            pageType: 'generative';
            pageId: string;
            entityName?: string;
            recordId?: string;
            data?: Record<string, unknown>;
        };

    interface XrmNavigationResult {
        savedEntityReference?: Array<{ entityType: string; id: string; name?: string }>;
    }

    interface XrmGlobalContext {
        userSettings: {
            userId: string;
            userName: string;
            languageId: number;
            dateFormattingInfo?: Record<string, unknown>;
        };
        organizationSettings: {
            organizationId: string;
            languageId: number;
            baseCurrency?: { id: string };
        };
        getClientUrl: () => string;
    }

    interface Window {
        /** Provided by the model-driven app shell. */
        Xrm: XrmShape;
    }

    /**
     * Bare \`Xrm\` identifier (used by generated pages as \`Xrm.Navigation...\`
     * without the \`window.\` prefix). Same shape as \`window.Xrm\`.
     */
    const Xrm: XrmShape;

    /**
     * Per-page cache keys MUST follow the pattern \`__genpage_<entity>_<v>\`
     * (see references/data-caching.md). The string-key index signature lets
     * TypeScript accept dynamic cache reads/writes without \`(window as any)\`.
     */
    interface Window {
        [cacheKey: \`__genpage_\${string}\`]: unknown;
    }
}
`;
}

// Windows can refuse a rename while another process briefly holds the destination — Defender, the
// search indexer and OneDrive all open a just-written file — and reports it as EPERM/EACCES/EBUSY.
// MEASURED: with `package.json` open in another program without delete-sharing, the rename failed
// with EPERM where an in-place write would have succeeded. A SHORT bounded retry absorbs the
// transient scanner case (graceful-fs retries renames on win32 for the same reason); a lock that
// outlasts it is reported as what it almost certainly is, so the user knows what to do.
const RENAME_RETRY_MS = [25, 50, 100, 200, 400];
const RENAME_LOCK_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);
function sleepSync(ms) {
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
function renameWithRetry(from, to) {
  for (let i = 0; ; i += 1) {
    try {
      fs.renameSync(from, to);
      return;
    } catch (err) {
      if (process.platform !== 'win32' || !RENAME_LOCK_CODES.has(err.code) || i >= RENAME_RETRY_MS.length) throw err;
      sleepSync(RENAME_RETRY_MS[i]);
    }
  }
}

function writeIfAllowed(filePath, content, force, approvedRoot) {
  if (typeof approvedRoot !== 'string' || !approvedRoot) {
    // Fail CLOSED, with the same code as every other refusal: without a root there is nothing to
    // confine the write to, so it must not happen.
    const e = new Error(`refusing to write ${filePath}: no approved root was given to confine it to`);
    e.code = 'UNSAFE_OUTPUT';
    throw e;
  }
  // Output confinement. Each part closes a hole a previous shape left open; a partial version of
  // this check is worse than none, because it reads as a guarantee it does not give.
  //
  // WHAT IS GUARANTEED: the file is written at the location the working directory resolves to, and
  // never through a link or into a file this tool does not own. `approvedRoot` is the realpath of
  // the working directory taken at startup; `main` refuses a working directory that is ITSELF a link
  // (a pre-planted link at the path a caller creates would redirect the whole run), while a linked
  // ANCESTOR is followed by design — macOS temp directories live under a symlinked `/var`, and a
  // junctioned project root is a normal setup.
  //
  // 1. RESOLVE WHERE THE WRITE WILL LAND. `realpath` the parent (the file itself may not exist yet)
  //    and require it to still be the approved root: this is what catches the working directory
  //    being swapped for a link AFTER startup. Every later operation uses this `resolved` path, never
  //    the lexical one, so the location that was checked is the location that is written.
  const dir = path.dirname(filePath);
  let realDir;
  try {
    realDir = fs.realpathSync(dir);
  } catch (err) {
    const e = new Error(`refusing to write ${filePath}: its directory could not be resolved (${err.code || err.message})`);
    e.code = 'UNSAFE_OUTPUT';
    throw e;
  }
  // `realpath` succeeds on a REGULAR FILE — it only resolves links, it does not assert a kind. So a
  // parent that is a file (or a link to one) passes resolution and the escape is caught only by the
  // write failing, which is an I/O error rather than a safety refusal. MEASURED on Windows, where
  // `lstat` of a child under a file reports ENOENT rather than ENOTDIR, so the fail-closed probe
  // below never sees it either. Prove the parent is a directory here instead.
  let dirSt;
  try {
    dirSt = fs.statSync(realDir);
  } catch (err) {
    const e = new Error(`refusing to write ${filePath}: its directory could not be inspected (${err.code || err.message})`);
    e.code = 'UNSAFE_OUTPUT';
    throw e;
  }
  if (!dirSt.isDirectory()) {
    const e = new Error(`refusing to write ${filePath}: ${realDir} is not a directory`);
    e.code = 'UNSAFE_OUTPUT';
    throw e;
  }
  const resolved = path.join(realDir, path.basename(filePath));
  const rel = path.relative(approvedRoot, resolved);
  if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
    const e = new Error(`refusing to write ${filePath}: it resolves to ${resolved}, outside the working directory ${approvedRoot}`);
    e.code = 'UNSAFE_OUTPUT';
    throw e;
  }

  // 2. PROBE THE LINK, NOT THE TARGET, AND FAIL CLOSED. `existsSync` FOLLOWS symlinks, so a DANGLING
  //    link — one whose target does not exist yet — reported "nothing here", skipped every check and
  //    `writeFileSync` then CREATED the file at the outside target. MEASURED: a `package.json`
  //    symlinked to a non-existent path outside the working directory was created there, which is
  //    worse than the overwrite this guard was first written for.
  //    Only ENOENT means "genuinely nothing there". Swallowing every error made EACCES/ENOTDIR — a
  //    probe that could not determine safety — indistinguishable from a clear slot, so the write
  //    proceeded on exactly the inputs least understood.
  let st = null;
  try {
    st = fs.lstatSync(resolved);
  } catch (err) {
    if (err.code !== 'ENOENT') {
      const e = new Error(`refusing to write ${filePath}: it could not be inspected (${err.code || err.message})`);
      e.code = 'UNSAFE_OUTPUT';
      throw e;
    }
  }

  // Without --force nothing that exists is written, whatever it is — so it is simply skipped. The
  // refusals below apply only to a write that would really happen; checking them first made a
  // hard-linked `package.json` abort a plain run, which then never wrote `genpage.d.ts` either.
  if (st && !force) {
    return { wrote: false, reason: 'exists (use --force to overwrite)' };
  }

  if (st && !st.isFile()) {
    // `--force` may overwrite the file this tool OWNS, never whatever that name points at. A symlink,
    // directory or special file is not ours, whether its target exists or not.
    const kind = st.isSymbolicLink() ? 'symlink' : st.isDirectory() ? 'directory' : 'special file';
    const e = new Error(`refusing to overwrite ${filePath}: it is not a regular file (${kind})`);
    e.code = 'UNSAFE_OUTPUT';
    throw e;
  }

  // 3. HARD LINKS. A hard link is a regular file and passes `isFile()`, but the inode is shared, so
  //    writing through it edits the outside file just as surely as a symlink would. A file this tool
  //    owns has exactly one name.
  if (st && st.nlink > 1) {
    const e = new Error(`refusing to overwrite ${filePath}: it is a hard link (${st.nlink} names share this file)`);
    e.code = 'UNSAFE_OUTPUT';
    throw e;
  }

  // A read-only file is a deliberate "do not modify". The in-place write this replaced refused it
  // (EACCES); a rename would silently replace it, because replacing a directory entry needs write
  // access to the DIRECTORY, not the file. Keep the old answer.
  if (st && !(st.mode & 0o200)) {
    const e = new Error(`refusing to overwrite ${filePath}: it is read-only`);
    e.code = 'IO_ERROR';
    throw e;
  }

  // 4. ATOMIC REPLACE. The checks above describe the past: anything that can write this directory can
  //    swap a symlink in between `lstat` and the write, and `writeFileSync` would follow it. Writing
  //    a fresh temp file and RENAMING over the target replaces the directory ENTRY, so a link
  //    installed after the checks is discarded rather than followed.
  //    The temp name is unique per call, and `wx` fails rather than reuse a name someone else
  //    created — in which case that file is NOT ours to delete. A replaced file keeps its permission
  //    bits (a rename would otherwise hand it the temp file's); a new one gets the process default.
  const tmp = path.join(realDir, `.${path.basename(filePath)}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`);
  let createdTmp = false;
  try {
    // Owned from the moment the exclusive open succeeds, not when the write returns: a write that
    // fails after the open (ENOSPC, EDQUOT, EIO) leaves the file behind, and fs.writeFileSync closes
    // it without removing it — so waiting for the write stranded a temp file on every failed run.
    const fd = fs.openSync(tmp, 'wx');
    createdTmp = true;
    try { fs.writeFileSync(fd, content); } finally { fs.closeSync(fd); }
    if (st) fs.chmodSync(tmp, st.mode & 0o777);
    renameWithRetry(tmp, resolved);
  } catch (err) {
    if (createdTmp) {
      try { fs.unlinkSync(tmp); } catch { /* already renamed, or removed by someone else */ }
    }
    const locked = process.platform === 'win32' && RENAME_LOCK_CODES.has(err.code);
    const e = new Error(locked
      ? `failed to write ${filePath}: it could not be replaced (${err.code}) — another program may have it open. Close it and retry.`
      : `failed to write ${filePath}: ${err.message}`);
    e.code = 'IO_ERROR';
    throw e;
  }
  return { wrote: true };
}

function main() {
  let args;
  try {
    args = parseArgs(process.argv.slice(2));
  } catch (err) {
    makeWritesBlocking(process.stdout, process.stderr);
    console.error(`error: ${err.message}`);
    process.exit(1);
  }

  const workingDir = path.resolve(args.positional[0]);
  const slug = args.positional[1];

  // The root every output is confined to: the working directory's realpath, taken ONCE here and
  // re-checked at write time (see writeIfAllowed). The working directory ITSELF must not be a link.
  // Callers create this directory (`mkdir -p <folder>`), and `mkdir -p` succeeds silently on a
  // symlink or junction that is already there — so a link pre-planted at that path would redirect
  // every write the run makes, with `--force` overwriting whatever it points at. A linked ANCESTOR
  // is still followed: that is a normal setup (macOS temp dirs sit under a symlinked `/var`), not a
  // redirect of the directory the caller named.
  let approvedRoot;
  try {
    if (!fs.existsSync(workingDir)) {
      makeWritesBlocking(process.stdout, process.stderr);
      console.error(`error: working directory does not exist: ${workingDir}`);
      process.exit(2);
    }
    if (fs.lstatSync(workingDir).isSymbolicLink()) {
      makeWritesBlocking(process.stdout, process.stderr);
      console.error(`error: refusing to use ${workingDir} as the working directory: it is a symbolic link or junction. Pass the directory it points to if that is intended.`);
      process.exit(2);
    }
    if (!fs.statSync(workingDir).isDirectory()) {
      makeWritesBlocking(process.stdout, process.stderr);
      console.error(`error: not a directory: ${workingDir}`);
      process.exit(2);
    }
    approvedRoot = fs.realpathSync(workingDir);
  } catch (err) {
    makeWritesBlocking(process.stdout, process.stderr);
    console.error(`error: failed to stat working directory: ${err.message}`);
    process.exit(2);
  }

  if (!/^[a-z][a-z0-9-]*$/.test(slug)) {
    makeWritesBlocking(process.stdout, process.stderr);
    console.error(`error: page-slug must be kebab-case (got: ${slug})`);
    process.exit(1);
  }

  let pkgResult;
  let dtsResult;
  try {
    const pkg = buildPackageJson(slug, args.features);
    const pkgPath = path.join(workingDir, 'package.json');
    const existing = args.force ? null : validateExistingPackageJson(pkgPath, pkg);
    pkgResult = writeIfAllowed(pkgPath, JSON.stringify(pkg, null, 2) + '\n', args.force, approvedRoot);
    if (existing && existing.drift.length && pkgResult && pkgResult.wrote === false) pkgResult.versionDrift = existing.drift;

    const dtsPath = path.join(workingDir, 'genpage.d.ts');
    dtsResult = writeIfAllowed(dtsPath, buildAmbientDeclarations(), args.force, approvedRoot);
  } catch (err) {
    makeWritesBlocking(process.stdout, process.stderr);
    console.error(`error: ${err.message}`);
    process.exit(2);
  }

  const summary = {
    workingDir,
    slug,
    features: args.features,
    files: {
      'package.json': pkgResult,
      'genpage.d.ts': dtsResult,
    },
  };
  console.log(JSON.stringify(summary, null, 2));
}

if (require.main === module) main();

module.exports = {
  parseArgs,
  buildPackageJson,
  buildAmbientDeclarations,
  comparePackageDependencies,
  validateExistingPackageJson,
  // Exported for the output-confinement tests: `--force` must overwrite the file this tool owns,
  // never whatever a symlink at that name points at.
  writeIfAllowed,
  RUNTIME_DEPENDENCIES,
  DEV_DEPENDENCIES,
};