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.

25.8 KB
Raw Blame
#!/usr/bin/env node
// app-builder teardown: delete exactly the artifacts an App Spec declares, in
// dependency-safe order, via the SDK's delete methods — the first-class, classifier-safe
// counterpart to `build-model-app.js`. Auth is the caller's az token (same as the rest of
// the plugin). DRY-RUN BY DEFAULT — it lists what would be deleted and touches nothing; only
// `--apply` performs deletes. It removes ONLY artifacts whose identity is resolved from a
// name/logical/uniquename the given spec declares, so it can never wildcard-scan an org.
//
// Usage:
//   node scripts/teardown-model-app.js --env <orgUrl> --spec @<app-folder>/app-spec.json [--apply]
//        [--clear-workspace] [--workspace <dir>]  (--workspace names the build's workspace: teardown
//        fences its --changed-only snapshot there, and --clear-workspace removes it after a clean run)
//
// Order: app -> security roles -> dashboards -> command bars -> forms -> charts -> views
//   (then reset enriched default views) -> relationships -> AI row summaries -> tables
//   (reverse-topo) -> web resources (generated icon + page manifest + declared) ->
//   global choices -> solution. Forms/charts/views/relationships are deleted explicitly BEFORE
//   tables (a table delete does not reliably cascade cross-references). Command teardown removes
//   the whole command bar for an entity the spec authored commands on (the SDK models a command bar
//   per entity, not per button). The solution's PUBLISHER is never deleted (it may be shared); the
//   closing summary says so in one line.
const fs = require('node:fs');
const path = require('node:path');
const { validateAppSpec, migrateAppSpec } = require('./lib/app-spec.js');
const { runTeardown } = require('./lib/sdk-teardown.js');
const { classifyOps } = require('./lib/op-diff.js');
const { checkWorkspaceClearable } = require('./lib/workspace-paths.js');
const { createAzHttpClient } = require('./lib/sdk-http-client.js');
const { openStandaloneManagedFence } = require('./lib/managed-standalone-fence.js');
const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
const snapStore = require('./lib/apply-snapshot-store.js');
const { checkPageOwnershipClearable } = require('./lib/page-ownership-records.js');
const { makeTempWorkspace } = require('./lib/temp-workspace.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');
const { withAppBuildLease } = require('./lib/app-operation-lease.js');
const { appUniqueName } = require('./lib/app-unique-name.js');
const { assertTeardownClear } = require('./lib/configuration-create-guard.js');

// The highest folder on the way to `dir` that does not exist yet (`dir` itself when only it is missing), or null when `dir` exists: what
// the build lease's mkdir is about to create, so a clean teardown can remove it again (apply-snapshot-store.js removeCreatedDir).
function topmostMissingDir(dir) {
  let missing = null;
  for (let d = path.resolve(dir); !fs.existsSync(d); d = path.dirname(d)) {
    missing = d;
    if (path.dirname(d) === d) break;
  }
  return missing;
}

// #807: the refusal of a teardown whose workspace holds configuration create evidence (configuration-create-guard.js assertTeardownClear),
// as the structured result the CLI emits: the stop code, `retry` (never), and the unit and next step when the halt names them. Null when
// the workspace is clear. Any other error is not a verdict about the receipt and is thrown as it is.
function configurationRefusal(workspaceDir, log) {
  try {
    assertTeardownClear(workspaceDir);
    return null;
  } catch (error) {
    if (!error || typeof error.code !== 'string' || !error.code.startsWith('configuration-create-')) throw error;
    log(`\n✗ ${error.message} Nothing was deleted.`);
    return { ok: false, errors: [error.message], code: error.code, retry: error.retry, ...(error.unitId ? { unitId: error.unitId } : {}), ...(error.nextStep ? { nextStep: error.nextStep } : {}) };
  }
}

// Build an SDK client for teardown. Uses the same az-token HttpClient as build-model-app.js.
// `publicationBarrier` (lib/managed-standalone-fence.js): the managed debt of the app's workspace, checked at every publish request the client sends.
async function makeSdk(env, publicationBarrier) {
  const { createMakerSdk, createNodeWorkspaceStorage } = require('./lib/maker-sdk.js');
  const httpClient = createAzHttpClient(env, publicationBarrier ? { request: publicationBarrier.gateRequest() } : {});
  // Teardown uses a minimal SDK client (no workspace, no solution header) — just queryRecords
  // and delete methods. Use a throw-away temp dir since initWorkspace is mandatory.
  const sdkTempDir = makeTempWorkspace('teardown-');
  try {
    const sdk = createMakerSdk({
      workspaceStorage: createNodeWorkspaceStorage(sdkTempDir),
      instanceUrl: env,
      httpClient,
    });
    await sdk.initWorkspace();
    const cleanup = () => {
      fs.rmSync(sdkTempDir, { recursive: true, force: true });
    };
    return { sdk, cleanup };
  } catch (err) {
    // If SDK initialization fails, no caller-owned cleanup function exists yet; remove the
    // throwaway workspace here so an auth/SDK startup error does not leak temp directories.
    try {
      fs.rmSync(sdkTempDir, { recursive: true, force: true });
    } catch {
      // Preserve the SDK/auth startup error as the actionable failure; a best-effort temp cleanup
      // problem would otherwise mask the reason teardown could not even initialize.
    }
    throw err;
  }
}

// Turn engine progress events into a phase-grouped, status-marked teardown log — the same shape
// build-model-app.js uses: ▶ <phase>, then per step [n/total] with ✓ (deleted) / ⊘ (not found, kept on
// purpose, or not attempted — the label says which) / ✗ (failed). A dry-run lists the same plan with a ▢
// marker. `opts.counts` accumulates totals, with skips also tallied by kind for the summary.
function cliEmit(log, opts = {}) {
  const counts = opts.counts;
  let phase = null;
  return (e) => {
    if (e.phase !== phase) { phase = e.phase; log(`\n▶ ${phase}`); }
    if (e.status === 'start') return;
    if (!opts.apply) { log(`  [${e.n}/${e.total}] ▢ ${e.label}`); return; }
    if (counts) {
      counts[e.status] = (counts[e.status] || 0) + 1;
      if (e.status === 'skip') counts[e.skip || 'not-found'] = (counts[e.skip || 'not-found'] || 0) + 1;
    }
    const glyph = e.status === 'ok' ? '✓' : e.status === 'skip' ? '⊘' : '✗';
    const tail = e.status === 'error' && e.detail ? ` — ${e.detail}` : '';
    log(`  [${e.n}/${e.total}] ${glyph} ${e.label}${tail}`);
  };
}

async function teardownModelApp(spec, opts, deps) {
  const v = validateAppSpec(spec, { profile: 'structural' });
  if (!v.ok) {
    return { ok: false, errors: v.errors };
  }
  const log = deps.log || (() => undefined);
  const warn = deps.warn || ((message) => log(`⚠ teardown warning: ${message}`));
  const counts = { ok: 0, skip: 0, error: 0 };
  const emit = deps.emit || cliEmit(log, { apply: opts.apply, counts });
  // Fail-closed: a teardown --apply DELETES real artifacts (app, tables, solution), so it now requires
  // explicit --allow-destructive — the same authorization the builder's destructive gate uses (design
  // §11). Dry-run is unaffected (it only prints the plan). The op set is the pure planTeardown, reused
  // via op-diff so the gate and the engine can never disagree about what will be deleted.
  if (opts.apply && opts.allowDestructive !== true) {
    const diff = classifyOps(spec, {}, { teardown: true });
    if (diff.hasDestructive) {
      const preview = diff.destructive.slice(0, 8).map((o) => `  • ${o.label}`);
      const more = diff.destructive.length > preview.length ? `\n  … and ${diff.destructive.length - preview.length} more` : '';
      log(`\n✗ refusing to delete ${diff.destructive.length} artifact(s) without --allow-destructive:\n${preview.join('\n')}${more}\nRe-run with --allow-destructive to authorize teardown.`);
      return { ok: false, errors: [`teardown of ${diff.destructive.length} artifact(s) requires --allow-destructive`, ...diff.destructive.slice(0, 8).map((o) => o.label)] };
    }
  }
  // TOMBSTONE the changed-only snapshot BEFORE any delete (design core invariant): eligible:false +
  // teardown-in-progress debt + a rotated generation, so a partial/crashed teardown leaves the tombstone,
  // a surviving artifact can never be rebaselined as an eligible fast-path source, and a changed-only run
  // already in flight is fenced off (#587 item 1).
  //
  // The tombstone IS the fence, so failing to write it stops the teardown before it mutates (#587 item 2).
  // It used to warn and proceed — and if the app delete then failed after lower-level artifacts were
  // gone, the old ELIGIBLE snapshot survived describing a state that no longer existed. The usual cause
  // is a build holding the workspace lease right now; a stale lease is reclaimed automatically, so a
  // persistent failure means real contention or an unwritable workspace, and waiting is the fix.
  //
  // A workspace with NO snapshot gets a fresh tombstone too (a first changed-only build has none until it
  // finishes — see tombstoneSnapshot), creating the folder if it has to; `createdDir` is what to remove
  // again once the teardown is clean, so a folder that never had a workspace is left without one.
  // The configuration kinds are never deleted by a teardown: nothing proves this app owns an environment variable, a connection reference,
  // a Custom API or a duplicate rule (configurationTeardownNotes). Each declared item is named as kept — names only, never a value — and a
  // Custom API bound to a table the spec makes is called out, because Dataverse refuses that table's delete while the API exists. Named
  // before the fence below is taken, so nothing here can leave the fence or its heartbeat behind.
  for (const note of require('./lib/configuration-artifacts.js').configurationTeardownNotes(spec)) warn(note);
  // Nor is a field security profile deleted: users and teams can hold one beyond this app (fieldSecurityTeardownNotes). Each declared
  // profile is named as kept the same way, by name only.
  for (const note of require('./lib/field-security.js').fieldSecurityTeardownNotes(spec)) warn(note);
  let createdWorkspaceDir = null;
  let teardownId = null;
  let heartbeat = null;
  let removeWorkspaceAfter = false;
  // The fenced part of an apply: the tombstone, the deletes and the release. Run under the app's build lease when there is a workspace
  // (below), and answers the teardown's result.
  const fencedTeardown = async () => {
    if (opts.apply && opts.workspaceDir) {
      const tomb = snapStore.tombstoneSnapshot(opts.workspaceDir);
      if (!tomb.ok) {
        const msg = `could not fence the changed-only snapshot before teardown (${tomb.reason}) — nothing was deleted. Let any running build of this app finish, then re-run the teardown.`;
        log(`\n✗ ${msg}`);
        return { ok: false, errors: [msg] };
      }
      createdWorkspaceDir = tomb.createdDir || createdWorkspaceDir;
      teardownId = tomb.teardownId || null;
      // While it runs, the teardown keeps its entry fresh (apply-snapshot-store.js liveTeardowns): an entry
      // counts as running only while it keeps being seen, so one a killed teardown left behind stops counting
      // within minutes. unref'd, so it never keeps the process alive; cleared the moment the teardown ends.
      if (teardownId) {
        heartbeat = setInterval(() => snapStore.beatTeardown(opts.workspaceDir, teardownId), snapStore.TEARDOWN_BEAT_MS);
        if (typeof heartbeat.unref === 'function') heartbeat.unref();
      }
    }
    let r;
    try {
      r = await runTeardown(spec, { apply: opts.apply, workspaceDir: opts.workspaceDir, env: opts.env, ...(opts.publicationBarrier ? { publicationBarrier: opts.publicationBarrier } : {}), ...(opts.managedFenceError ? { managedFenceError: opts.managedFenceError } : {}) }, { sdk: deps.sdk, emit, warn });
    } finally {
      if (heartbeat) clearInterval(heartbeat);
      // Every teardown that FINISHES drops its entry from the tombstone's list of teardowns in flight — a
      // clean one, one that finished with errors, and one that threw. An entry left behind read as a
      // teardown still running whenever its pid was alive (reused, slow to exit, or this very process), and
      // a later clean teardown then kept the fence for up to a day.
      //
      // Only a CLEAN teardown may also delete the snapshot — the app is gone, so a fresh rebuild must start a
      // new baseline — and then only as the last one to finish: an overlapping teardown still deleting keeps
      // its fence (releaseTombstone). One that failed or threw keeps the tombstone (`keep`: a surviving
      // artifact must not be rebaselined), in a folder it created too, since that tombstone is what keeps it.
      if (teardownId) {
        const clean = !!(r && r.ok && !r.dryRun);
        const rel = snapStore.releaseTombstone(opts.workspaceDir, teardownId, clean ? {} : { keep: true });
        if (clean && rel.ok && !rel.left) {
          // The folders this teardown made are removed once the build lease is let go too: its lock lives in them.
          if (createdWorkspaceDir) removeWorkspaceAfter = true;
        } else if (clean) {
          // On the result, so main() leaves the workspace alone: --clear-workspace would delete the fence.
          r.snapshotKept = rel.reason;
          log(`\n▸ the changed-only snapshot stays tombstoned: ${rel.reason}.${rel.left ? ' The last of them to finish removes it.' : ' A --changed-only build full-builds until a clean teardown removes it.'}`);
        } else if (!rel.ok) {
          log(`\n▸ could not drop this teardown from the changed-only fence (${rel.reason}); the snapshot stays tombstoned, and a later teardown may keep it until this process has exited.`);
        }
      }
    }
    return r;
  };
  let r;
  if (opts.apply && opts.workspaceDir) {
    // #807: an apply runs under the app's build lease (lib/app-operation-lease.js), the one a build of the app holds, so a teardown and a
    // build of the same app in this workspace never run at once, and the configuration create receipt it checks cannot change under it.
    // A held lease is refused (`build-locked`) before anything is fenced or deleted. The lease makes the workspace folder when it is
    // missing, so the folders above it that did not exist are noted first, to be removed again after a clean teardown as before.
    createdWorkspaceDir = topmostMissingDir(opts.workspaceDir);
    r = await withAppBuildLease({ workspaceDir: opts.workspaceDir, appUniqueName: appUniqueName(spec), warn }, async () => {
      // A workspace holding configuration create evidence — an open or deferred unit, an unreadable or unknown receipt file, a
      // quarantine marker or archive — is refused before the fence and before any delete: the receipt says the environment may hold
      // configuration rows nobody has accounted for, and only configuration-recovery.js may settle that. A build's quarantine
      // acknowledgment is never permission here; teardown accepts none.
      const refused = configurationRefusal(opts.workspaceDir, log);
      if (refused) return refused;
      const result = await fencedTeardown();
      // The caller's work that must still exclude a build of this app runs here, before the lease is let go: main()'s --clear-workspace.
      // Run after the lease, a build could take the lock between the deletes and the clear, and the clear then moved and deleted the
      // workspace that build had just started in, its lock with it (so a second build could start too). `workspaceCreated` says this
      // teardown made the workspace folder itself: that folder is removed below, once the lock in it is let go, not cleared.
      if (typeof deps.underLease === 'function') await deps.underLease(result, { workspaceCreated: removeWorkspaceAfter });
      return result;
    }).finally(() => {
      if (removeWorkspaceAfter) snapStore.removeCreatedDir(opts.workspaceDir, createdWorkspaceDir);
    });
  } else {
    r = await fencedTeardown();
  }
  if (opts.apply && r && !r.dryRun) {
    // A skip is one of three different facts, and the summary used to call all of them "not found" —
    // after an app-delete abort that read "0 deleted, 8 not found, 1 failed" for eight steps nobody
    // queried. `kept` (left in place on purpose: existing:true, system tables, …) and `not attempted`
    // are shown only when non-zero, so an ordinary run reads exactly as it always did.
    const notFound = counts['not-found'] || 0;
    const kept = counts.kept || 0;
    const notAttempted = counts['not-attempted'] || 0;
    const extra = `${kept ? `, ${kept} kept` : ''}${notAttempted ? `, ${notAttempted} not attempted` : ''}`;
    log(`\n${r.ok ? '✓' : '✗'} teardown ${r.ok ? 'complete' : 'finished with errors'} — ${counts.ok} deleted, ${notFound} not found, ${counts.error} failed${extra} (${counts.ok + counts.skip + counts.error} steps)`);
    // A publisher is never deleted, and no step plans one: the build reuses any publisher with the spec's prefix
    // (lib/entity-provision.js provisionSolution), and other solutions may share the one it made, so nothing here can
    // tell that this app alone uses it. Said once, after the count, so the row a maker finds left behind is expected.
    // The structural profile requires solution.publisherPrefix; the guard only keeps a log line from ever throwing.
    const publisherPrefix = spec.solution && spec.solution.publisherPrefix;
    if (publisherPrefix) log(`▸ the publisher with prefix '${publisherPrefix}' is kept: teardown never deletes a publisher, which other solutions may share — delete it in Power Apps (Solutions → Publishers) once nothing uses it`);
  }
  return r;
}

async function main() {
  const argv = process.argv.slice(2);
  const { positional, flags } = parseArgs(argv);
  const USAGE =
    'Usage: node scripts/teardown-model-app.js --env <url> --spec @<app-folder>/app-spec.json [--apply] [--allow-destructive] [--clear-workspace] [--workspace <dir>]\n' +
    '  Note: --workspace names the build\'s workspace (default: .maker-workspace next to the spec). Teardown fences its --changed-only snapshot there before deleting anything, and --clear-workspace removes it after a clean run; the SDK itself uses a throwaway workspace.';
  // Strictness matters more here than anywhere else: this tool deletes. A mistyped
  // `--allow-destructiv` was previously dropped in silence, and the safety flag the operator
  // believed they had passed simply did not exist.
  const flagError = validateFlags(argv, {
    known: ['env', 'spec', 'apply', 'allow-destructive', 'clear-workspace', 'workspace'],
    needValue: ['env', 'spec', 'workspace'],
  });
  if (flagError) {
    makeWritesBlocking(process.stdout, process.stderr);
    process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
    process.exit(1);
  }
  const env = flags.env;
  const specArg = flags.spec || positional[0];
  const workspaceArg = flags.workspace;
  if (!env || !specArg) {
    process.stderr.write(USAGE + '\n');
    process.exit(1);
  }
  const specPath = path.resolve(typeof specArg === 'string' && specArg.startsWith('@') ? specArg.slice(1) : specArg);
  const spec = migrateAppSpec(readJsonArg('@' + specPath));
  const apply = flags.apply === true;
  const allowDestructive = flags['allow-destructive'] === true;
  const workspaceDir = workspaceArg || path.join(path.dirname(specPath), '.maker-workspace');
  // The managed debt a build of this app left in its workspace, read before the client exists so the client's transport is gated by it
  // (lib/managed-standalone-fence.js); runTeardown withholds the resets' table publish it names. A store that cannot be read withholds every one.
  let managed = {};
  if (apply) {
    try {
      managed = { publicationBarrier: openStandaloneManagedFence({ environment: env, workspaceDir, spec }).barrier };
    } catch (error) {
      managed = { managedFenceError: error };
    }
  }
  // #807: a workspace holding configuration create evidence is refused before the destructive client exists. teardownModelApp checks it
  // again under the app's build lease, which is the check that counts; this one only spares the client and its throwaway workspace.
  if (apply) {
    const refused = configurationRefusal(workspaceDir, (m) => process.stderr.write(m + '\n'));
    if (refused) {
      makeWritesBlocking(process.stdout, process.stderr);
      emitResult(false, refused);
      return;
    }
  }
  const { sdk, cleanup } = await makeSdk(env, managed.publicationBarrier);
  let r;
  let thrown = null;
  try {
    // Clear the local workspace only after a clean apply — stale metadata there would make a
    // subsequent rebuild skip tables that no longer exist. Filesystem-local, opt-in.
    //
    // #807: the clear runs while the teardown still holds the app's build lease (teardownModelApp `deps.underLease`), so no build of the
    // app can start in the workspace between the deletes and the clear and then have its folder, lock and all, moved and deleted under it.
    // Its outcome is only written after the teardown returns: those are the run's last writes (below).
    let clearOutcome = null;
    const clearUnderLease = async (result, { workspaceCreated }) => {
      if (!(apply && flags['clear-workspace'] && result && result.ok && !result.dryRun)) return;
      // A workspace folder this teardown made itself (none was there) holds nothing but the lease's lock: the teardown removes it once the
      // lock is let go, as it always did, and the clear then finds nothing to clear (said below).
      if (workspaceCreated) { clearOutcome = { deferred: true }; return; }
      // VALIDATE BEFORE DELETING. `--workspace` is caller-supplied and this runs immediately
      // after a SUCCESSFUL teardown — the moment an operator is least expecting data loss — so an
      // unguarded `rmSync(dir, { recursive: true, force: true })` on a mistyped path, or on a
      // shell variable that expanded to a repo root, destroyed real work. Refusal is a WARNING,
      // not a failure: the teardown itself already succeeded, and the cost of refusing is only a
      // stale cache directory the operator can remove by hand.
      //
      // A workspace whose changed-only snapshot is still tombstoned — another teardown of it is running,
      // or the release failed — is left whole: deleting it deletes the fence that teardown depends on.
      const clearable = result.snapshotKept
        ? { ok: false, reason: `the workspace still holds the changed-only fence (${result.snapshotKept}); clear it once that is done` }
        : checkWorkspaceClearable(workspaceDir);
      //
      // The clear itself runs under the workspace's lease, and only while no snapshot has appeared since this
      // teardown's release — another teardown's tombstone, say, which removing the folder in place after the
      // release deleted (apply-snapshot-store.js clearWorkspace).
      // The path guard proves this is a cache directory; it cannot decide whether its ownership
      // records are disposable. Retain all unconsumed records, including foreign scopes.
      // Check under the clear lease and again after atomic isolation, before recursive removal:
      // another app can finish a receipt between the first check and the directory rename.
      // #807: the configuration create receipt is checked the same way, against the target and then the isolated folder: a workspace
      // holding an open or deferred unit, an unreadable receipt, a quarantine or its archive is never disposable.
      const requireDisposable = (dir) => {
        const ownership = checkPageOwnershipClearable(dir);
        if (!ownership.ok) throw new Error(ownership.reason);
        assertTeardownClear(dir);
      };
      const cleared = clearable.ok ? snapStore.clearWorkspace(clearable.target, {
        beforeRename: () => requireDisposable(clearable.target),
        beforeRemove: requireDisposable,
      }) : clearable;
      clearOutcome = { clearable, cleared };
    };
    const deps = { log: (m) => process.stderr.write(m + '\n'), sdk, underLease: clearUnderLease };
    r = await teardownModelApp(spec, { apply, allowDestructive, workspaceDir, env, ...managed }, deps);

    if (clearOutcome) {
      // The folder the teardown made is removed by now, so this reports what it reported before: nothing to clear. One still there was
      // written into after the lease was let go — a build that started in it — and is that build's to keep.
      let { clearable, cleared } = clearOutcome;
      if (clearOutcome.deferred) {
        clearable = checkWorkspaceClearable(workspaceDir);
        cleared = clearable.ok ? { ok: false, reason: 'a build of the app started in the workspace after this teardown made it; it is that build\'s to keep' } : clearable;
      }
      // The run's last writes: these lines, then the result and the exit, with no turn of the event loop between them — made blocking (lib/output-redaction.js).
      makeWritesBlocking(process.stdout, process.stderr);
      if (cleared.ok) {
        process.stderr.write(`\ncleared workspace ${clearable.target}${cleared.leftover ? ` (${cleared.reason})` : ''}\n`);
      } else {
        process.stderr.write(`\nskipped --clear-workspace: ${cleared.reason}\n`);
      }
    }
  } catch (err) {
    thrown = err;
  } finally {
    cleanup();
  }
  // emitResult() calls process.exit(), so emit AFTER cleanup() has run.
  if (thrown) {
    emitResult(false, thrown);
  }
  emitResult(r.ok, r);
}

if (require.main === module) {
  main().catch((err) => emitResult(false, err));
}
module.exports = { teardownModelApp, cliEmit };