@loopress/cli 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +335 -58
  2. package/dist/commands/app/list.d.ts +17 -0
  3. package/dist/commands/app/list.js +35 -0
  4. package/dist/commands/app/pull.d.ts +27 -0
  5. package/dist/commands/app/pull.js +94 -0
  6. package/dist/commands/app/push.d.ts +28 -0
  7. package/dist/commands/app/push.js +130 -0
  8. package/dist/commands/app/remove.d.ts +20 -0
  9. package/dist/commands/app/remove.js +42 -0
  10. package/dist/commands/composer/push.d.ts +1 -0
  11. package/dist/commands/composer/push.js +43 -19
  12. package/dist/commands/init.js +1 -0
  13. package/dist/commands/plugin/add.d.ts +1 -0
  14. package/dist/commands/plugin/add.js +18 -8
  15. package/dist/commands/plugin/audit.d.ts +30 -0
  16. package/dist/commands/plugin/audit.js +138 -0
  17. package/dist/commands/plugin/pull.d.ts +1 -2
  18. package/dist/commands/plugin/pull.js +11 -11
  19. package/dist/commands/plugin/push.d.ts +14 -8
  20. package/dist/commands/plugin/push.js +168 -67
  21. package/dist/commands/plugin/status.d.ts +22 -0
  22. package/dist/commands/plugin/status.js +65 -0
  23. package/dist/commands/theme/add.d.ts +13 -0
  24. package/dist/commands/theme/add.js +35 -0
  25. package/dist/commands/theme/pull.d.ts +21 -0
  26. package/dist/commands/theme/pull.js +37 -0
  27. package/dist/commands/theme/push.d.ts +23 -0
  28. package/dist/commands/theme/push.js +130 -0
  29. package/dist/commands/theme/status.d.ts +20 -0
  30. package/dist/commands/theme/status.js +51 -0
  31. package/dist/lib/app-manifest.d.ts +36 -0
  32. package/dist/lib/app-manifest.js +162 -0
  33. package/dist/lib/base.d.ts +1 -0
  34. package/dist/lib/base.js +5 -0
  35. package/dist/types/plugin.d.ts +1 -0
  36. package/dist/types/project-config.generated.d.ts +11 -1
  37. package/dist/utils/plugin-sync.d.ts +26 -0
  38. package/dist/utils/plugin-sync.js +31 -0
  39. package/dist/utils/plugins.d.ts +15 -2
  40. package/dist/utils/plugins.js +57 -12
  41. package/dist/utils/themes.d.ts +30 -0
  42. package/dist/utils/themes.js +29 -0
  43. package/dist/utils/version.d.ts +2 -0
  44. package/dist/utils/version.js +21 -0
  45. package/oclif.manifest.json +714 -68
  46. package/package.json +22 -18
  47. package/schemas/project-config.schema.json +22 -4
@@ -0,0 +1,138 @@
1
+ import got from 'got';
2
+ import { LoopressCommand } from '../../lib/base.js';
3
+ import { compareVersions } from '../../utils/version.js';
4
+ const WPVULN_BASE = 'https://www.wpvulnerability.net/plugin';
5
+ const WPORG_INFO = 'https://api.wordpress.org/plugins/info/1.2/';
6
+ export default class Audit extends LoopressCommand {
7
+ static description = 'Check the plugins in loopress.json for known vulnerabilities and health issues';
8
+ static enableJsonFlag = true;
9
+ static examples = ['$ lps plugin audit'];
10
+ static flags = {};
11
+ async run() {
12
+ const manifest = { ...this.localConfig.plugins };
13
+ const slugs = Object.keys(manifest);
14
+ if (slugs.length === 0) {
15
+ this.log('No plugins in loopress.json to audit.');
16
+ return { advisories: [], health: [], status: 'clean' };
17
+ }
18
+ const advisories = [];
19
+ const health = [];
20
+ for (const slug of slugs) {
21
+ const found = await this.auditOne(slug, manifest[slug]);
22
+ advisories.push(...found.advisories);
23
+ health.push(...found.health);
24
+ }
25
+ return this.report(advisories, health, slugs.length);
26
+ }
27
+ async auditOne(slug, pinned) {
28
+ const [vulns, info] = await Promise.all([this.fetchVulnerabilities(slug), this.fetchHealth(slug)]);
29
+ const advisories = vulns
30
+ .filter((v) => pinned === 'latest' || affects(pinned, v.fixedIn))
31
+ .map((v) => ({ ...v, slug }));
32
+ const health = info ? describeHealth(slug, pinned, info) : [];
33
+ return { advisories, health };
34
+ }
35
+ async fetchHealth(slug) {
36
+ try {
37
+ const body = await got(WPORG_INFO, {
38
+ searchParams: { 'action': 'plugin_information', 'request[slug]': slug },
39
+ timeout: { request: 10_000 },
40
+ }).json();
41
+ return typeof body === 'object' && !('error' in body) ? body : null;
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ async fetchVulnerabilities(slug) {
48
+ let body;
49
+ try {
50
+ body = await got(`${WPVULN_BASE}/${encodeURIComponent(slug)}/`, {
51
+ timeout: { request: 10_000 },
52
+ }).json();
53
+ }
54
+ catch (error) {
55
+ // Never swallow this into an empty list: a clean audit must mean "no advisories found",
56
+ // not "the advisory service was unreachable". Fail the command instead.
57
+ throw new Error(`Could not reach the vulnerability database (wpvulnerability.net) for "${slug}": ${error.message}. ` +
58
+ 'Audit aborted so a service outage is not reported as a clean result.', { cause: error });
59
+ }
60
+ const list = Array.isArray(body?.data?.vulnerability) ? body.data.vulnerability : [];
61
+ return list.map((raw) => normalizeAdvisory(raw));
62
+ }
63
+ report(advisories, health, count) {
64
+ if (advisories.length === 0 && health.length === 0) {
65
+ this.log(`No known vulnerabilities or health issues for ${count} plugin(s).`);
66
+ return { advisories, health, status: 'clean' };
67
+ }
68
+ for (const a of advisories)
69
+ this.log(` ⚠ ${a.slug}: ${a.title}${advisoryMeta(a)}`);
70
+ for (const h of health)
71
+ this.log(` · ${h.slug}: ${h.message}`);
72
+ const noun = advisories.length === 1 ? 'advisory' : 'advisories';
73
+ this.log(`\n${advisories.length} vulnerability ${noun}, ${health.length} health note(s). ` +
74
+ 'Vulnerability data: wpvulnerability.net.');
75
+ if (advisories.length > 0)
76
+ this.exit(1);
77
+ return { advisories, health, status: 'issues' };
78
+ }
79
+ }
80
+ function advisoryMeta(a) {
81
+ const fixed = a.fixedIn ? `fixed in ${a.fixedIn}` : undefined;
82
+ const parts = [a.severity, a.cve, fixed].filter(Boolean);
83
+ return parts.length > 0 ? ` (${parts.join(', ')})` : '';
84
+ }
85
+ function normalizeAdvisory(raw) {
86
+ const cvss = (raw.cvss ?? {});
87
+ const source = Array.isArray(raw.source) ? raw.source : [];
88
+ const cve = typeof raw.cve === 'string' ? raw.cve : source.find((s) => s.id?.startsWith('CVE-'))?.id;
89
+ return {
90
+ cve,
91
+ fixedIn: extractFixedIn(raw),
92
+ score: cvss.score,
93
+ severity: cvss.severity,
94
+ title: typeof raw.name === 'string' ? raw.name : 'Unnamed advisory',
95
+ };
96
+ }
97
+ // wpvulnerability's `impact.software[].versions[]` carries `to_version` / `to_compare`; the
98
+ // first "< X" bound is the version the fix landed in. Best-effort: the shape varies, so a
99
+ // missing bound just means we can't tell and the advisory is reported anyway.
100
+ function extractFixedIn(raw) {
101
+ const impact = raw.impact;
102
+ for (const sw of impact?.software ?? []) {
103
+ for (const v of sw.versions ?? []) {
104
+ if (v.to_compare === '<' && typeof v.to_version === 'string')
105
+ return v.to_version;
106
+ }
107
+ }
108
+ return undefined;
109
+ }
110
+ // If we know the fix version, a pin below it is affected. If we can't compare (odd version
111
+ // strings), report it anyway: a false positive is safer than hiding an advisory.
112
+ function affects(pinned, fixedIn) {
113
+ if (!fixedIn)
114
+ return true;
115
+ const order = compareVersions(pinned, fixedIn);
116
+ return order === null || order < 0;
117
+ }
118
+ function describeHealth(slug, pinned, info) {
119
+ const notes = [];
120
+ if (info.closed === true) {
121
+ notes.push({ message: 'removed from the WordPress.org directory', slug });
122
+ }
123
+ const requiresPhp = typeof info.requires_php === 'string' ? info.requires_php : null;
124
+ if (requiresPhp)
125
+ notes.push({ message: `requires PHP ${requiresPhp}`, slug });
126
+ const latest = typeof info.version === 'string' ? info.version : null;
127
+ const behindLatest = latest ? compareVersions(pinned, latest) : null;
128
+ if (latest && pinned !== 'latest' && behindLatest !== null && behindLatest < 0) {
129
+ notes.push({ message: `pinned to ${pinned}, latest is ${latest}`, slug });
130
+ }
131
+ const lastUpdated = typeof info.last_updated === 'string' ? info.last_updated : null;
132
+ if (lastUpdated) {
133
+ const years = (Date.now() - Date.parse(lastUpdated)) / (365 * 24 * 3600 * 1000);
134
+ if (years > 2)
135
+ notes.push({ message: `last updated ${lastUpdated.slice(0, 10)} (possibly abandoned)`, slug });
136
+ }
137
+ return notes;
138
+ }
@@ -1,7 +1,7 @@
1
1
  import { LoopressCommand } from '../../lib/base.js';
2
2
  import { type MergeResult } from '../../utils/plugins.js';
3
3
  type PullResult = MergeResult & {
4
- status: 'dry-run' | 'success';
4
+ status: 'composer-managed' | 'dry-run' | 'success';
5
5
  };
6
6
  export default class Pull extends LoopressCommand {
7
7
  static description: string;
@@ -11,6 +11,5 @@ export default class Pull extends LoopressCommand {
11
11
  'dry-run': import("@oclif/core/interfaces").BooleanFlag<boolean>;
12
12
  };
13
13
  run(): Promise<PullResult>;
14
- private logSkippedComposerManaged;
15
14
  }
16
15
  export {};
@@ -1,9 +1,10 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
1
3
  import { LoopressCommand } from '../../lib/base.js';
2
- import { getComposerManagedSlugs, readComposerJson } from '../../utils/composer.js';
3
4
  import { writeLocalConfig } from '../../utils/loopress-config.js';
4
5
  import { mergePluginManifest, parseInstalledPlugins } from '../../utils/plugins.js';
5
6
  export default class Pull extends LoopressCommand {
6
- static description = 'Pull installed plugins from WordPress into loopress.json';
7
+ static description = 'Pull installed plugins from WordPress into loopress.json, pinned to their live versions';
7
8
  static enableJsonFlag = true;
8
9
  static examples = ['$ lps plugin pull', '$ lps plugin pull --dry-run'];
9
10
  static flags = {
@@ -11,13 +12,17 @@ export default class Pull extends LoopressCommand {
11
12
  };
12
13
  async run() {
13
14
  const { url } = this.siteConfig;
15
+ if (existsSync(join(process.cwd(), this.rootDir, 'composer.json'))) {
16
+ this.warn('This project has a composer.json, which is authoritative for plugins. Run `lps composer pull` instead.');
17
+ return { added: [], merged: this.localConfig.plugins ?? {}, status: 'composer-managed', updated: [] };
18
+ }
14
19
  this.log(`Pulling plugins from ${url}`);
15
20
  const raw = await this.wp.get('wp/v2/plugins');
16
21
  const installed = parseInstalledPlugins(raw);
17
- const composerJson = await readComposerJson();
18
- const composerSlugs = composerJson ? getComposerManagedSlugs(composerJson) : [];
19
- const incoming = Object.fromEntries(installed.filter((p) => !composerSlugs.includes(p.slug)).map((p) => [p.slug, 'latest']));
20
- this.logSkippedComposerManaged(installed.filter((p) => composerSlugs.includes(p.slug)).map((p) => p.slug));
22
+ // Pin every plugin to the version actually running on the site. A later `plugin push`
23
+ // installs exactly this set via Composer + WPackagist; drift only surfaces when the pinned
24
+ // version and the live version disagree.
25
+ const incoming = Object.fromEntries(installed.map((p) => [p.slug, p.version]));
21
26
  const { added, merged, updated } = mergePluginManifest(this.localConfig.plugins ?? {}, incoming);
22
27
  if (this.dryRun) {
23
28
  this.log(`[dry-run] Would write ${Object.keys(merged).length} plugins to loopress.json`);
@@ -35,9 +40,4 @@ export default class Pull extends LoopressCommand {
35
40
  this.log(` ~ Updated: ${u.slug} ${u.from} → ${u.to}`);
36
41
  return { added, merged, status: 'success', updated };
37
42
  }
38
- logSkippedComposerManaged(found) {
39
- if (found.length > 0) {
40
- this.log(`Skipping ${found.length} Composer-managed ${found.length === 1 ? 'plugin' : 'plugins'}: ${found.join(', ')}`);
41
- }
42
- }
43
43
  }
@@ -2,23 +2,29 @@ import { PushCommand } from '../../lib/push-command.js';
2
2
  type PushResult = {
3
3
  activated: string[];
4
4
  installed: string[];
5
- skippedComposerManaged: string[];
6
- status: 'dry-run' | 'in-sync' | 'success';
5
+ pinned: string[];
6
+ pruned: string[];
7
+ removed: string[];
8
+ status: 'composer-managed' | 'dry-run' | 'in-sync' | 'success';
7
9
  };
8
10
  export default class Push extends PushCommand {
9
11
  static description: string;
10
12
  static enableJsonFlag: boolean;
11
13
  static examples: string[];
12
14
  static flags: {
15
+ force: import("@oclif/core/interfaces").BooleanFlag<boolean>;
16
+ prune: import("@oclif/core/interfaces").BooleanFlag<boolean>;
13
17
  yes: import("@oclif/core/interfaces").BooleanFlag<boolean>;
14
18
  'dry-run': import("@oclif/core/interfaces").BooleanFlag<boolean>;
15
19
  };
16
20
  run(): Promise<PushResult>;
17
- private activatePlugin;
18
- private applyPluginChanges;
19
- private installPlugin;
20
- private logPlannedChanges;
21
- private logSkippedComposerManaged;
22
- private performPluginAction;
21
+ private activate;
22
+ private confirmRemovals;
23
+ private deactivate;
24
+ private deactivateEndangered;
25
+ private fetchInstanceLock;
26
+ private guardForce;
27
+ private result;
28
+ private sync;
23
29
  }
24
30
  export {};
@@ -1,98 +1,199 @@
1
- import { Listr } from 'listr2';
1
+ import { confirm } from '@inquirer/prompts';
2
+ import { Flags } from '@oclif/core';
3
+ import { existsSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { isInteractive } from '../../lib/interactive.js';
2
6
  import { PushCommand } from '../../lib/push-command.js';
3
- import { getComposerManagedSlugs, readComposerJson } from '../../utils/composer.js';
4
- import { diffPlugins, parseInstalledPlugins } from '../../utils/plugins.js';
5
- import { pluralize } from '../../utils/pluralize.js';
7
+ import { isNotFoundError } from '../../lib/wp-client.js';
8
+ import { isDowngrade, parseCollisions, SYNC_TIMEOUT_MS } from '../../utils/plugin-sync.js';
9
+ import { diffPlugins, lockedWpackagistSlugs, parseInstalledPlugins } from '../../utils/plugins.js';
10
+ const IN_SYNC = { activated: [], installed: [], pinned: [], pruned: [], removed: [], status: 'in-sync' };
6
11
  export default class Push extends PushCommand {
7
- static description = 'Push plugins to WordPress to match loopress.json';
12
+ static description = 'Install plugins on WordPress to match loopress.json, pinned via Composer + WPackagist';
8
13
  static enableJsonFlag = true;
9
- static examples = ['$ lps plugin push', '$ lps plugin push --dry-run'];
14
+ static examples = ['$ lps plugin push', '$ lps plugin push --dry-run', '$ lps plugin push --force --prune'];
10
15
  static flags = {
11
16
  ...PushCommand.dryRunFlag,
12
17
  ...PushCommand.yesFlag,
18
+ force: Flags.boolean({
19
+ default: false,
20
+ description: 'Allow downgrades and let Loopress take over plugins installed outside it (replaces their files)',
21
+ }),
22
+ prune: Flags.boolean({
23
+ default: false,
24
+ description: 'Deactivate plugins that are active on the site but absent from loopress.json',
25
+ }),
13
26
  };
14
27
  async run() {
15
- const { url } = this.siteConfig;
16
- const manifest = this.localConfig.plugins;
17
- if (!manifest || Object.keys(manifest).length === 0) {
18
- this.error('No plugins found in loopress.json. Run `lps plugin pull` first.');
28
+ const { flags } = await this.parse(Push);
29
+ const { force, prune } = flags;
30
+ if (existsSync(join(process.cwd(), this.rootDir, 'composer.json'))) {
31
+ this.warn('This project has a composer.json, which is authoritative for plugins. Run `lps composer push` instead.');
32
+ return { ...IN_SYNC, status: 'composer-managed' };
19
33
  }
20
- const composerJson = await readComposerJson();
21
- const composerSlugs = composerJson ? getComposerManagedSlugs(composerJson) : [];
22
- const filteredManifest = Object.fromEntries(Object.entries(manifest).filter(([slug]) => !composerSlugs.includes(slug)));
23
- const skippedComposerManaged = composerSlugs.filter((slug) => Object.hasOwn(manifest, slug));
24
- this.logSkippedComposerManaged(skippedComposerManaged);
25
- this.log(`Pushing plugins to ${url}`);
34
+ const manifest = this.localConfig.plugins ?? {};
35
+ if (Object.keys(manifest).length === 0) {
36
+ this.error('No plugins found in loopress.json. Run `lps plugin pull` or `lps plugin add <slug>` first.');
37
+ }
38
+ this.log(`Pushing plugins to ${this.siteConfig.url}`);
26
39
  const raw = await this.wp.get('wp/v2/plugins');
27
40
  const installed = parseInstalledPlugins(raw);
28
- const { toActivate, toInstall } = diffPlugins(filteredManifest, installed);
29
- if (toInstall.length === 0 && toActivate.length === 0) {
41
+ const managed = lockedWpackagistSlugs(await this.fetchInstanceLock(), 'plugin');
42
+ const diff = diffPlugins(manifest, installed, managed);
43
+ this.guardForce(diff, force);
44
+ const toPrune = prune ? diff.untrackedActive : [];
45
+ // A "latest" pin never shows as drift, but its newest upstream release may have moved
46
+ // since the last push, so a push must still run `composer update` to pick it up.
47
+ const hasLatestPin = Object.values(manifest).includes('latest');
48
+ if (!hasLatestPin && isNoop(diff, toPrune)) {
30
49
  this.log('Everything is already in sync.');
31
- return { activated: [], installed: [], skippedComposerManaged, status: 'in-sync' };
50
+ return { ...IN_SYNC };
51
+ }
52
+ if (isNoop(diff, toPrune))
53
+ this.log('Refreshing plugins pinned to "latest" to their newest releases.');
54
+ logPlan(this, diff, toPrune, force);
55
+ if (this.dryRun) {
56
+ return this.result(diff, { includeCollisions: true, pruned: toPrune, removed: diff.toRemove, status: 'dry-run' });
57
+ }
58
+ await this.confirmRemovals(diff.toRemove);
59
+ const deactivated = await this.deactivateEndangered(installed, diff, force);
60
+ // Plugins that must end up active: the ones we deactivated for the file swap (minus any
61
+ // being uninstalled) plus the ones the manifest wants active but that are inactive today.
62
+ const toReactivate = [...deactivated.filter((p) => !diff.toRemove.includes(p.slug)), ...diff.toActivate];
63
+ let response;
64
+ try {
65
+ response = await this.sync(manifest, force);
66
+ }
67
+ catch (error) {
68
+ // The file swap never happened, so restore the plugins we defensively deactivated
69
+ // instead of leaving the site with them switched off.
70
+ await this.activate(deactivated.filter((p) => !diff.toRemove.includes(p.slug)));
71
+ throw error;
32
72
  }
33
- this.logPlannedChanges(toInstall, toActivate);
34
- const installedSlugs = toInstall.map((a) => a.slug);
35
- const activatedSlugs = toActivate.map((a) => a.slug);
36
- if (this.dryRun)
37
- return { activated: activatedSlugs, installed: installedSlugs, skippedComposerManaged, status: 'dry-run' };
38
- // Installing with `status: active` activates in the same call, so installs never need a
39
- // separate activation step the way the old custom endpoint's two-step flow did.
40
- await this.applyPluginChanges(toInstall, toActivate);
41
- if (this.failedCount > 0) {
42
- this.error(`${pluralize(this.failedCount, 'plugin')} failed to install or activate.`);
73
+ if (toPrune.length > 0) {
74
+ await this.deactivate(installed.filter((p) => toPrune.includes(p.slug)));
43
75
  }
76
+ await this.activate(toReactivate);
77
+ if (response.output.trim())
78
+ this.log(response.output.trim());
79
+ this.log('Plugins synced.');
44
80
  await this.recordSuccess();
45
- return { activated: activatedSlugs, installed: installedSlugs, skippedComposerManaged, status: 'success' };
46
- }
47
- async activatePlugin(file, slug, task) {
48
- await this.performPluginAction('activate', slug, async () => this.wp.put(`wp/v2/plugins/${file}`, { status: 'active' }), task);
81
+ return this.result(diff, {
82
+ activated: toReactivate.map((p) => p.slug),
83
+ includeCollisions: force,
84
+ pruned: toPrune,
85
+ removed: response.removed ?? diff.toRemove,
86
+ status: 'success',
87
+ });
49
88
  }
50
- async applyPluginChanges(toInstall, toActivate) {
51
- if (toInstall.length > 0) {
52
- await new Listr(toInstall.map((action) => ({
53
- task: async (_ctx, task) => this.installPlugin(action.slug, task),
54
- title: `Install ${action.slug}`,
55
- })), { concurrent: false, exitOnError: false, renderer: this.jsonEnabled() ? 'silent' : 'default' }).run();
89
+ async activate(plugins) {
90
+ for (const plugin of plugins) {
91
+ this.log(` ⊙ activating ${plugin.slug}`);
92
+ await this.wp.put(`wp/v2/plugins/${plugin.file}`, { status: 'active' });
56
93
  }
57
- if (toActivate.length > 0) {
58
- await new Listr(toActivate.map((action) => ({
59
- task: async (_ctx, task) => this.activatePlugin(action.file, action.slug, task),
60
- title: `Activate ${action.slug}`,
61
- })), { concurrent: false, exitOnError: false, renderer: this.jsonEnabled() ? 'silent' : 'default' }).run();
94
+ }
95
+ async confirmRemovals(toRemove) {
96
+ if (toRemove.length === 0 || this.yes || !isInteractive())
97
+ return;
98
+ const ok = await confirm({ default: false, message: `Uninstall ${toRemove.join(', ')} from the site?` });
99
+ if (!ok)
100
+ this.error('Aborted.');
101
+ }
102
+ async deactivate(plugins) {
103
+ for (const plugin of plugins) {
104
+ this.log(` ⊘ deactivating ${plugin.slug}`);
105
+ await this.wp.put(`wp/v2/plugins/${plugin.file}`, { status: 'inactive' });
62
106
  }
63
107
  }
64
- async installPlugin(slug, task) {
65
- await this.performPluginAction('install', slug, async () => this.wp.post('wp/v2/plugins', { slug, status: 'active' }), task);
108
+ // Deactivate anything whose folder is about to be deleted or replaced (removed, re-pinned to
109
+ // a new version, or taken over with --force), so the site does not fatal in the window
110
+ // between removal and Composer finishing the install. Returns the plugins it switched off so
111
+ // the caller can switch the still-wanted ones back on.
112
+ async deactivateEndangered(installed, diff, force) {
113
+ const endangered = new Set([
114
+ ...diff.toRemove,
115
+ ...diff.toPin.map((p) => p.slug),
116
+ ...(force ? diff.collisions.map((c) => c.slug) : []),
117
+ ]);
118
+ const victims = installed.filter((p) => p.active && endangered.has(p.slug));
119
+ await this.deactivate(victims);
120
+ return victims;
66
121
  }
67
- logPlannedChanges(toInstall, toActivate) {
68
- if (toInstall.length > 0) {
69
- this.log(`\nTo install (${toInstall.length}):`);
70
- for (const a of toInstall)
71
- this.log(` + ${a.slug}`);
122
+ // The site's live composer.lock tells us which plugins Loopress already manages, so the plan
123
+ // can preview removals and tell an unmanaged folder (collision) apart from a re-pin. 404 =
124
+ // nothing pushed yet.
125
+ async fetchInstanceLock() {
126
+ try {
127
+ const { composerLock } = await this.wp.get('loopress/v1/composer/lock');
128
+ return composerLock;
72
129
  }
73
- if (toActivate.length > 0) {
74
- this.log(`\nTo activate (${toActivate.length}):`);
75
- for (const a of toActivate)
76
- this.log(` ↑ ${a.slug}`);
130
+ catch (error) {
131
+ if (isNotFoundError(error))
132
+ return null;
133
+ throw error;
77
134
  }
78
135
  }
79
- logSkippedComposerManaged(skippedComposerManaged) {
80
- if (skippedComposerManaged.length === 0)
136
+ guardForce(diff, force) {
137
+ if (force)
81
138
  return;
82
- this.log(`Skipping ${skippedComposerManaged.length} Composer-managed ${skippedComposerManaged.length === 1 ? 'plugin' : 'plugins'}: ${skippedComposerManaged.join(', ')}`);
83
- this.log('Run `lps composer push` to deploy them.');
139
+ if (diff.collisions.length > 0) {
140
+ const list = diff.collisions.map((c) => `${c.slug} (${c.installedVersion})`).join(', ');
141
+ this.error(`${diff.collisions.length} plugin(s) are already installed outside Loopress: ${list}. ` +
142
+ 'Re-run with --force to let Loopress manage them (this replaces their files with the WPackagist build, ' +
143
+ 'local modifications are lost), or remove them from loopress.json.');
144
+ }
145
+ const downgrades = diff.toPin.filter((p) => isDowngrade(p.from, p.to));
146
+ if (downgrades.length > 0) {
147
+ const list = downgrades.map((p) => `${p.slug} ${p.from} to ${p.to}`).join(', ');
148
+ this.error(`Refusing to downgrade: ${list}. A downgrade only replaces plugin files, it does not undo database ` +
149
+ 'migrations the newer version ran, which can break the site. Re-run with --force, or bump the version in loopress.json.');
150
+ }
151
+ }
152
+ result(diff, opts) {
153
+ const collisionSlugs = opts.includeCollisions ? diff.collisions.map((c) => c.slug) : [];
154
+ return {
155
+ activated: opts.activated ?? diff.toActivate.map((a) => a.slug),
156
+ installed: [...diff.toInstall.map((a) => a.slug), ...collisionSlugs],
157
+ pinned: diff.toPin.map((p) => p.slug),
158
+ pruned: opts.pruned,
159
+ removed: opts.removed,
160
+ status: opts.status,
161
+ };
84
162
  }
85
- async performPluginAction(verb, slug, request, task) {
163
+ async sync(manifest, force) {
86
164
  try {
87
- await request();
88
- const message = `✓ ${slug} ${verb === 'install' ? 'installed and activated' : 'activated'}`;
89
- if (task)
90
- task.output = message;
91
- else
92
- this.log(` ${message}`);
165
+ return await this.wp.post('loopress/v1/composer/sync', { force, intent: { plugins: manifest }, lock: null }, { timeoutMs: SYNC_TIMEOUT_MS });
93
166
  }
94
167
  catch (error) {
95
- this.reportTaskFailure(`Failed to ${verb} ${slug}: ${error.message}`, error, task);
168
+ const collisions = parseCollisions(error);
169
+ if (collisions) {
170
+ this.error(`The site rejected the push: ${collisions.map((c) => c.slug).join(', ')} installed outside Loopress. Re-run with --force.`);
171
+ }
172
+ throw error;
96
173
  }
97
174
  }
98
175
  }
176
+ function isNoop(diff, toPrune) {
177
+ return (diff.toInstall.length === 0 &&
178
+ diff.toPin.length === 0 &&
179
+ diff.toActivate.length === 0 &&
180
+ diff.toRemove.length === 0 &&
181
+ diff.collisions.length === 0 &&
182
+ toPrune.length === 0);
183
+ }
184
+ function logPlan(cmd, diff, prune, force) {
185
+ const section = (label, lines) => {
186
+ if (lines.length === 0)
187
+ return;
188
+ cmd.log(`\n${label} (${lines.length}):`);
189
+ for (const line of lines)
190
+ cmd.log(` ${line}`);
191
+ };
192
+ section('To install', diff.toInstall.map((a) => `+ ${a.slug} ${a.version}`));
193
+ if (force)
194
+ section('To take over', diff.collisions.map((c) => `! ${c.slug} (installed outside Loopress)`));
195
+ section('To re-pin', diff.toPin.map((p) => `~ ${p.slug} ${p.from} to ${p.to}`));
196
+ section('To activate', diff.toActivate.map((a) => `↑ ${a.slug}`));
197
+ section('To uninstall', diff.toRemove.map((s) => `- ${s}`));
198
+ section('To deactivate (--prune)', prune.map((s) => `⊘ ${s}`));
199
+ }
@@ -0,0 +1,22 @@
1
+ import { LoopressCommand } from '../../lib/base.js';
2
+ type StatusResult = {
3
+ drift: boolean;
4
+ inactive: string[];
5
+ missing: string[];
6
+ status: 'composer-managed' | 'drift' | 'in-sync';
7
+ untrackedActive: string[];
8
+ wrongVersion: Array<{
9
+ live: string;
10
+ pinned: string;
11
+ slug: string;
12
+ }>;
13
+ };
14
+ export default class Status extends LoopressCommand {
15
+ static description: string;
16
+ static enableJsonFlag: boolean;
17
+ static examples: string[];
18
+ static flags: {};
19
+ run(): Promise<StatusResult>;
20
+ private fetchInstanceLock;
21
+ }
22
+ export {};
@@ -0,0 +1,65 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { LoopressCommand } from '../../lib/base.js';
4
+ import { isNotFoundError } from '../../lib/wp-client.js';
5
+ import { diffPlugins, lockedWpackagistSlugs, parseInstalledPlugins } from '../../utils/plugins.js';
6
+ export default class Status extends LoopressCommand {
7
+ static description = 'Compare the plugins on WordPress against loopress.json and report drift';
8
+ static enableJsonFlag = true;
9
+ static examples = ['$ lps plugin status'];
10
+ static flags = {};
11
+ async run() {
12
+ const { url } = this.siteConfig;
13
+ if (existsSync(join(process.cwd(), this.rootDir, 'composer.json'))) {
14
+ this.warn('This project has a composer.json, which is authoritative for plugins. Run `lps composer` commands instead.');
15
+ return { drift: false, inactive: [], missing: [], status: 'composer-managed', untrackedActive: [], wrongVersion: [] };
16
+ }
17
+ const manifest = this.localConfig.plugins ?? {};
18
+ const raw = await this.wp.get('wp/v2/plugins');
19
+ const installed = parseInstalledPlugins(raw);
20
+ const managed = lockedWpackagistSlugs(await this.fetchInstanceLock(), 'plugin');
21
+ const diff = diffPlugins(manifest, installed, managed);
22
+ const missing = diff.toInstall.map((a) => a.slug);
23
+ const wrongVersion = diff.toPin.map((p) => ({ live: p.from, pinned: p.to, slug: p.slug }));
24
+ const inactive = diff.toActivate.map((a) => a.slug);
25
+ const { untrackedActive } = diff;
26
+ // `collisions` are also drift (Loopress doesn't own them yet); surface them under missing's
27
+ // banner so `plugin push --force` is the obvious next step.
28
+ const collisions = diff.collisions.map((c) => c.slug);
29
+ const drift = missing.length > 0 ||
30
+ wrongVersion.length > 0 ||
31
+ inactive.length > 0 ||
32
+ diff.toRemove.length > 0 ||
33
+ collisions.length > 0;
34
+ if (!drift && untrackedActive.length === 0) {
35
+ this.log(`In sync with loopress.json (${url})`);
36
+ return { drift: false, inactive: [], missing: [], status: 'in-sync', untrackedActive: [], wrongVersion: [] };
37
+ }
38
+ if (missing.length > 0)
39
+ this.log(`Not installed: ${missing.join(', ')}`);
40
+ if (collisions.length > 0)
41
+ this.log(`Installed outside Loopress (run \`plugin push --force\`): ${collisions.join(', ')}`);
42
+ for (const w of wrongVersion)
43
+ this.log(`Version drift: ${w.slug} is ${w.live}, loopress.json pins ${w.pinned}`);
44
+ if (inactive.length > 0)
45
+ this.log(`Pinned but inactive: ${inactive.join(', ')}`);
46
+ if (diff.toRemove.length > 0)
47
+ this.log(`Managed by Loopress but dropped from loopress.json: ${diff.toRemove.join(', ')}`);
48
+ if (untrackedActive.length > 0)
49
+ this.log(`Active but untracked: ${untrackedActive.join(', ')}`);
50
+ if (drift)
51
+ this.exit(1);
52
+ return { drift, inactive, missing, status: drift ? 'drift' : 'in-sync', untrackedActive, wrongVersion };
53
+ }
54
+ async fetchInstanceLock() {
55
+ try {
56
+ const { composerLock } = await this.wp.get('loopress/v1/composer/lock');
57
+ return composerLock;
58
+ }
59
+ catch (error) {
60
+ if (isNotFoundError(error))
61
+ return null;
62
+ throw error;
63
+ }
64
+ }
65
+ }
@@ -0,0 +1,13 @@
1
+ import { LoopressCommand } from '../../lib/base.js';
2
+ export default class Add extends LoopressCommand {
3
+ static args: {
4
+ slug: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
5
+ };
6
+ static description: string;
7
+ static examples: string[];
8
+ static flags: {
9
+ version: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
+ 'dry-run': import("@oclif/core/interfaces").BooleanFlag<boolean>;
11
+ };
12
+ run(): Promise<void>;
13
+ }
@@ -0,0 +1,35 @@
1
+ import { Args, Flags } from '@oclif/core';
2
+ import { LoopressCommand } from '../../lib/base.js';
3
+ import { writeLocalConfig } from '../../utils/loopress-config.js';
4
+ import { isExactVersion } from '../../utils/version.js';
5
+ export default class Add extends LoopressCommand {
6
+ static args = {
7
+ slug: Args.string({ description: 'Theme slug on WordPress.org', required: true }),
8
+ };
9
+ static description = 'Add a WordPress.org theme to loopress.json';
10
+ static examples = ['$ lps theme add generatepress', '$ lps theme add generatepress --version 3.4.0'];
11
+ static flags = {
12
+ ...LoopressCommand.dryRunFlag,
13
+ version: Flags.string({ description: 'Exact version to pin (default: "latest")' }),
14
+ };
15
+ async run() {
16
+ const { args, flags } = await this.parse(Add);
17
+ const { slug } = args;
18
+ const version = flags.version ?? 'latest';
19
+ if (version !== 'latest' && !isExactVersion(version)) {
20
+ this.error(`--version must be an exact version like 3.4.0, not a Composer constraint. Got "${version}".`);
21
+ }
22
+ const existing = this.localConfig.themes ?? {};
23
+ if (existing[slug] === version) {
24
+ this.log(`${slug} is already pinned to ${version}, nothing to do.`);
25
+ return;
26
+ }
27
+ const isUpdated = existing[slug] !== undefined;
28
+ if (this.dryRun) {
29
+ this.log(`[dry-run] Would ${isUpdated ? 'update' : 'add'} ${slug} (${version})`);
30
+ return;
31
+ }
32
+ await writeLocalConfig({ ...this.localConfig, themes: { ...existing, [slug]: version } });
33
+ this.log(`${isUpdated ? 'Updated' : 'Added'} ${slug} (${version}). Run \`lps theme push\` to apply.`);
34
+ }
35
+ }