368 lines
20 KiB
JavaScript
368 lines
20 KiB
JavaScript
// The Composer window: the packages of the project's composer.json files (a game, an app, an extension, the root, a web
|
|
// site...), the outdated ones (composer outdated) with Update / Update all, and Packagist: search, a package's versions,
|
|
// Require (a version constraint, --dev) and Remove. Composer itself runs in the Run window (Docker through bin/jumphp, or
|
|
// the IDE's copy of JumPHP for web sites); the list is read again when it ends.
|
|
// The PHP side: ide/src/Composer/ (ComposerCommands, ComposerProject, Packagist). Claude: composer_* tools at the end.
|
|
import { backend } from './backend.js';
|
|
import { el, clear, icon, notify, prefs, t, confirm } from './ui.js';
|
|
|
|
const count = (n) => (n >= 1e6 ? (n / 1e6).toFixed(1) + ' M' : n >= 1e3 ? (n / 1e3).toFixed(1) + ' k' : String(n));
|
|
|
|
export class ComposerPanel {
|
|
constructor(app) {
|
|
this.app = app;
|
|
this.node = el('div.composer-view');
|
|
this.tab = prefs.get('composerTab', 'installed');
|
|
this.mode = 'jumphp';
|
|
this.targets = [];
|
|
this.dir = null;
|
|
this.data = null; // composer.packages of the chosen folder
|
|
this.outdated = null; // {name: {latest, status}} once checked
|
|
this.checking = false;
|
|
this.filter = '';
|
|
this.query = '';
|
|
this.results = null; // composer.search
|
|
this.searching = false;
|
|
this.detail = null; // {name, data, error, version, constraint, dev}
|
|
this.error = null;
|
|
this.running = false;
|
|
this.loaded = false;
|
|
this.render();
|
|
}
|
|
|
|
title() { return 'Composer'; }
|
|
|
|
actions() {
|
|
return [
|
|
el('button', { title: t('Check for updates (composer outdated)'), onclick: () => this.checkOutdated() }, icon('download')),
|
|
el('button', { title: t('Refresh'), onclick: () => this.load() }, icon('refresh')),
|
|
];
|
|
}
|
|
|
|
shown() { if (!this.loaded) this.load(); }
|
|
|
|
async load() {
|
|
this.loaded = true;
|
|
try {
|
|
const r = await backend.invoke('composer.targets', {});
|
|
this.mode = r.mode;
|
|
this.targets = r.targets || [];
|
|
const saved = prefs.get('composerDir:' + (this.app.projectKey || ''), null);
|
|
if (!this.targets.some((x) => x.dir === this.dir)) this.dir = this.targets.some((x) => x.dir === saved) ? saved : this.targets[0]?.dir ?? null;
|
|
await this.loadPackages();
|
|
} catch (e) {
|
|
this.error = e.message || String(e);
|
|
this.render();
|
|
}
|
|
}
|
|
|
|
async loadPackages() {
|
|
this.error = null;
|
|
if (this.dir === null) { this.data = null; this.render(); return; }
|
|
try {
|
|
this.data = await backend.invoke('composer.packages', { dir: this.dir });
|
|
} catch (e) {
|
|
this.data = null;
|
|
this.error = e.message || String(e);
|
|
}
|
|
this.render();
|
|
}
|
|
|
|
setDir(dir) {
|
|
this.dir = dir;
|
|
prefs.set('composerDir:' + (this.app.projectKey || ''), dir);
|
|
this.outdated = null;
|
|
this.detail = null;
|
|
this.loadPackages();
|
|
}
|
|
|
|
setTab(tab) { this.tab = tab; this.detail = null; prefs.set('composerTab', tab); this.render(); }
|
|
|
|
/** Docker first (bin/jumphp runs Composer there), then the command itself */
|
|
async ready() {
|
|
if (this.mode !== 'native') await this.app.docker?.();
|
|
}
|
|
|
|
async checkOutdated() {
|
|
if (this.dir === null || this.checking) return;
|
|
this.checking = true;
|
|
this.render();
|
|
try {
|
|
await this.ready();
|
|
const r = await backend.invoke('composer.outdated', { dir: this.dir });
|
|
this.outdated = Object.fromEntries((r.packages || []).map((p) => [p.name.toLowerCase(), p]));
|
|
return r.packages || [];
|
|
} catch (e) {
|
|
notify(e.message || String(e), 'error', { title: t('Composer') });
|
|
throw e;
|
|
} finally {
|
|
this.checking = false;
|
|
this.render();
|
|
}
|
|
}
|
|
|
|
/** A Composer action in the Run window; resolves with its end ({code}) and reads the packages again. */
|
|
async run(params) {
|
|
if (this.dir === null) throw new Error(t('No composer.json in this project'));
|
|
await this.app.editors?.saveAll?.(true);
|
|
await this.ready();
|
|
this.running = true;
|
|
this.render();
|
|
try {
|
|
const r = await backend.invoke('composer.run', { dir: this.dir, ...params });
|
|
const config = { id: 'composer', kind: r.kind || 'tool', label: r.label, command: r.command };
|
|
const end = new Promise((resolve) => {
|
|
const off = backend.on('run.exit', (p) => { if (p.id === r.id) { off?.(); resolve(p); } });
|
|
});
|
|
this.app.runner?.track(r.id, r.label, config);
|
|
const exit = await end;
|
|
exit.output = ((this.app.runner?.runs || []).find((x) => x.id === r.id)?.output || '').replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').slice(-3000);
|
|
await this.loadPackages();
|
|
if (this.outdated && exit.code === 0) this.checkOutdated().catch(() => null);
|
|
if (exit.code === 0) notify(t('{command} done', { command: r.label }), 'success', { title: t('Composer') });
|
|
return exit;
|
|
} catch (e) {
|
|
notify(e.message || String(e), 'error', { title: t('Composer') });
|
|
throw e;
|
|
} finally {
|
|
this.running = false;
|
|
this.render();
|
|
}
|
|
}
|
|
|
|
async search(page = 1) {
|
|
const q = this.query.trim();
|
|
if (!q) { this.results = null; this.render(); return; }
|
|
this.searching = true;
|
|
this.render();
|
|
try {
|
|
const r = await backend.invoke('composer.search', { q, page });
|
|
this.results = page > 1 && this.results ? { ...r, results: [...this.results.results, ...r.results] } : r;
|
|
} catch (e) {
|
|
this.results = { results: [], total: 0, error: e.message || String(e) };
|
|
}
|
|
this.searching = false;
|
|
this.render();
|
|
}
|
|
|
|
async open(name) {
|
|
const row = this.installed(name);
|
|
this.detail = { name, data: null, error: null, dev: row ? row.dev : false, constraint: '', version: '' };
|
|
this.render();
|
|
try {
|
|
const data = await backend.invoke('composer.package', { name });
|
|
if (this.detail?.name !== name) return;
|
|
this.detail.data = data;
|
|
this.detail.constraint = row?.constraint || data.constraint || '';
|
|
this.detail.version = data.latest || data.versions[0]?.version || '';
|
|
} catch (e) {
|
|
if (this.detail?.name === name) this.detail.error = e.message || String(e);
|
|
}
|
|
this.render();
|
|
}
|
|
|
|
installed(name) {
|
|
return this.data?.packages.find((p) => p.name.toLowerCase() === String(name).toLowerCase()) || null;
|
|
}
|
|
|
|
// rendering -----------------------------------------------------------------------------------------------------
|
|
|
|
render() {
|
|
clear(this.node);
|
|
if (this.targets.length > 1) {
|
|
this.node.append(el('div.composer-target', {},
|
|
el('span', {}, t('composer.json')),
|
|
el('select.input', { onchange: (e) => this.setDir(e.target.value) },
|
|
...this.targets.map((x) => el('option', { value: x.dir, selected: x.dir === this.dir }, x.dir === '' ? `${t(x.label)} (./)` : `${x.label} — ${x.dir}/`)))));
|
|
}
|
|
const tabs = [['installed', 'Installed'], ['search', 'Search Packagist']];
|
|
this.node.append(el('div.cryo-tabs', {}, ...tabs.map(([id, label]) => el('button' + (this.tab === id && !this.detail ? '.on' : ''), { onclick: () => this.setTab(id) }, t(label)))));
|
|
const body = el('div.composer-body');
|
|
this.node.append(body);
|
|
if (this.error) body.append(el('div.composer-error', {}, this.error));
|
|
if (this.dir === null && this.loaded && !this.error) {
|
|
body.append(el('div.prof-empty', {}, el('div.prof-empty-title', {}, t('No composer.json in this project')),
|
|
el('p', {}, t('Composer packages are listed here once the project (or one of its games, apps or extensions) has a composer.json.'))));
|
|
return;
|
|
}
|
|
if (this.detail) this.renderDetail(body);
|
|
else if (this.tab === 'search') this.renderSearch(body);
|
|
else this.renderInstalled(body);
|
|
}
|
|
|
|
renderInstalled(body) {
|
|
const d = this.data;
|
|
if (!d) { if (!this.error) body.append(el('div.composer-muted', {}, t('Loading…'))); return; }
|
|
const outdatedCount = this.outdated ? Object.keys(this.outdated).length : 0;
|
|
body.append(el('div.composer-bar', {},
|
|
el('input.input', { type: 'search', placeholder: t('Filter packages'), value: this.filter, oninput: (e) => { this.filter = e.target.value; this.renderList(list); } }),
|
|
el('button.btn.small', { disabled: this.checking || this.running, title: t('Check for updates (composer outdated)'), onclick: () => this.checkOutdated() },
|
|
icon('download'), this.checking ? t('Checking…') : t('Check for updates')),
|
|
el('button.btn.small' + (outdatedCount ? '.primary' : ''), { disabled: this.running, title: t('composer update: every package to the newest version its constraint allows'),
|
|
onclick: async () => { if (await confirm(t('Update all'), t('Update every package (composer update)?'), { ok: t('Update all') })) this.run({ action: 'update' }).catch(() => null); } }, t('Update all')),
|
|
!d.hasVendor || !d.hasLock ? el('button.btn.small', { disabled: this.running, onclick: () => this.run({ action: 'install' }).catch(() => null) }, t('Install')) : null));
|
|
if (d.name || d.description) body.append(el('div.composer-muted', {}, d.name ? el('b', {}, d.name) : null, d.description ? ' — ' + d.description : ''));
|
|
if (!d.hasLock) body.append(el('div.composer-muted', {}, t('No composer.lock yet: Install resolves and installs the packages.')));
|
|
if (this.outdated) body.append(el('div.composer-muted', {}, outdatedCount ? t('{n} packages can be updated', { n: outdatedCount }) : t('Every package is up to date')));
|
|
const list = el('div.composer-list');
|
|
body.append(list);
|
|
this.renderList(list);
|
|
}
|
|
|
|
renderList(list) {
|
|
clear(list);
|
|
const f = this.filter.trim().toLowerCase();
|
|
const rows = this.data.packages.filter((p) => !f || p.name.toLowerCase().includes(f) || (p.description || '').toLowerCase().includes(f));
|
|
const groups = [['Required', rows.filter((p) => p.direct && !p.dev)], ['Required for development (require-dev)', rows.filter((p) => p.direct && p.dev)],
|
|
['Dependencies', rows.filter((p) => !p.direct)]];
|
|
for (const [label, items] of groups) {
|
|
if (!items.length) continue;
|
|
const open = prefs.get('composerGroup:' + label, label !== 'Dependencies');
|
|
list.append(el('div.composer-group', { onclick: () => { prefs.set('composerGroup:' + label, !open); this.renderList(list); } },
|
|
icon(open ? 'collapse' : 'expand'), `${t(label)} (${items.length})`));
|
|
if (open) for (const p of items) list.append(this.row(p));
|
|
}
|
|
if (!rows.length) list.append(el('div.composer-muted', {}, t('No package')));
|
|
}
|
|
|
|
row(p) {
|
|
const o = this.outdated?.[p.name.toLowerCase()];
|
|
const major = o && o.status === 'update-possible';
|
|
return el('div.composer-row', { onclick: () => (p.platform ? null : this.open(p.name)), title: p.description || p.name },
|
|
el('div.composer-row-main', {},
|
|
el('span.composer-name', {}, p.name),
|
|
p.dev && p.direct ? el('span.composer-tag', {}, 'dev') : null,
|
|
p.constraint ? el('span.composer-constraint', {}, p.constraint) : null,
|
|
el('span.composer-version', {}, p.version || (p.platform ? '' : t('not installed'))),
|
|
o ? el('span.composer-latest' + (major ? '.major' : ''), { title: major ? t('A new major version: its constraint must change (Require it again with the new version)') : t('An update within the constraint') }, '→ ' + o.latest) : null),
|
|
p.description ? el('div.composer-desc', {}, p.description) : null,
|
|
el('div.composer-row-actions', { onclick: (e) => e.stopPropagation() },
|
|
o && !p.platform ? el('button.btn.small' + (major ? '' : '.primary'), { disabled: this.running,
|
|
onclick: () => (major && p.direct ? this.run({ action: 'require', package: p.name, constraint: this.suggest(o.latest), dev: p.dev })
|
|
: this.run({ action: 'update', package: p.name })).catch(() => null) }, t('Update')) : null,
|
|
p.direct && !p.platform ? el('button.btn.small.danger', { disabled: this.running, title: t('composer remove'),
|
|
onclick: async () => { if (await confirm(t('Remove'), t('Remove {name} from composer.json?', { name: p.name }), { ok: t('Remove'), danger: true })) this.run({ action: 'remove', package: p.name, dev: p.dev }).catch(() => null); } }, icon('trash')) : null));
|
|
}
|
|
|
|
renderSearch(body) {
|
|
const input = el('input.input', { type: 'search', placeholder: t('Search packages on Packagist'), value: this.query,
|
|
oninput: (e) => { this.query = e.target.value; }, onkeydown: (e) => { if (e.key === 'Enter') this.search(); } });
|
|
body.append(el('div.composer-bar', {}, input, el('button.btn.small.primary', { disabled: this.searching, onclick: () => this.search() }, icon('search'), t('Search'))));
|
|
setTimeout(() => { if (input.isConnected && !this.query) input.focus(); }, 0);
|
|
const r = this.results;
|
|
if (this.searching && !r) body.append(el('div.composer-muted', {}, t('Searching…')));
|
|
if (!r) return;
|
|
if (r.error) { body.append(el('div.composer-error', {}, r.error)); return; }
|
|
body.append(el('div.composer-muted', {}, t('{n} packages found', { n: r.total })));
|
|
const list = el('div.composer-list');
|
|
for (const p of r.results) {
|
|
const mine = this.installed(p.name);
|
|
list.append(el('div.composer-row', { onclick: () => this.open(p.name), title: p.description },
|
|
el('div.composer-row-main', {},
|
|
el('span.composer-name', {}, p.name),
|
|
p.abandoned ? el('span.composer-tag.warn', {}, t('abandoned')) : null,
|
|
mine?.direct ? el('span.composer-tag.ok', {}, t('required')) : null,
|
|
el('span.composer-stats', { title: t('Downloads · stars') }, `⬇ ${count(p.downloads)} · ★ ${count(p.favers)}`)),
|
|
p.description ? el('div.composer-desc', {}, p.description) : null));
|
|
}
|
|
body.append(list);
|
|
if (r.next) body.append(el('button.btn.small', { disabled: this.searching, onclick: () => this.search((r.page || 1) + 1) }, t('More results')));
|
|
}
|
|
|
|
renderDetail(body) {
|
|
const det = this.detail;
|
|
const d = det.data;
|
|
const mine = this.installed(det.name);
|
|
body.append(el('div.composer-bar', {}, el('button.btn.small', { onclick: () => { this.detail = null; this.render(); } }, '← ' + t('Back')),
|
|
el('span.composer-name.big', {}, det.name)));
|
|
if (det.error) { body.append(el('div.composer-error', {}, det.error)); return; }
|
|
if (!d) { body.append(el('div.composer-muted', {}, t('Loading…'))); return; }
|
|
if (d.abandoned) body.append(el('div.composer-error', {}, t('This package is abandoned.')));
|
|
if (d.description) body.append(el('div', {}, d.description));
|
|
const link = (label, url) => (url ? el('a.composer-link', { href: url, onclick: (e) => { e.preventDefault(); this.app.openUrl(url); } }, t(label)) : null);
|
|
body.append(el('div.composer-links', {},
|
|
d.license ? el('span.composer-tag', {}, d.license) : null,
|
|
d.latest ? el('span.composer-muted', {}, t('Latest: {v}', { v: d.latest })) : null,
|
|
mine?.version ? el('span.composer-muted', {}, t('Installed: {v}', { v: mine.version })) : null,
|
|
link('Home page', d.homepage), link('Repository', d.repository), link('Packagist', d.packagist)));
|
|
// the version to require: its constraint (^x.y suggested, an exact version, or typed)
|
|
const versions = d.versions.filter((v) => v.stable).slice(0, 40);
|
|
const constraintInput = el('input.input', { value: det.constraint, placeholder: '^1.0', oninput: (e) => { det.constraint = e.target.value; } });
|
|
const pick = el('select.input', { onchange: (e) => { det.version = e.target.value; det.constraint = e.target.value.startsWith('dev-') ? e.target.value : this.suggest(e.target.value); constraintInput.value = det.constraint; renderRequires(); } },
|
|
...(versions.length ? versions : d.versions.slice(0, 40)).map((v) => el('option', { value: v.version, selected: v.version === det.version }, v.version + (v.time ? ' (' + v.time.slice(0, 10) + ')' : ''))));
|
|
const exact = el('button.btn.small', { title: t('This exact version'), onclick: () => { det.constraint = det.version.replace(/^v(?=\d)/, ''); constraintInput.value = det.constraint; } }, '=');
|
|
body.append(el('div.composer-require', {},
|
|
el('label', {}, t('Version'), pick),
|
|
el('label', {}, t('Constraint'), el('div.composer-inline', {}, constraintInput, exact)),
|
|
el('label.composer-check', {}, el('input', { type: 'checkbox', checked: det.dev, onchange: (e) => { det.dev = e.target.checked; } }), t('Development only (--dev)'))));
|
|
body.append(el('div.composer-bar', {},
|
|
el('button.btn.small.primary', { disabled: this.running, onclick: () => this.run({ action: 'require', package: det.name, constraint: det.constraint.trim(), dev: det.dev }).catch(() => null) },
|
|
icon('download'), mine?.direct ? t('Change the version') : t('Require')),
|
|
mine?.direct ? el('button.btn.small.danger', { disabled: this.running,
|
|
onclick: async () => { if (await confirm(t('Remove'), t('Remove {name} from composer.json?', { name: det.name }), { ok: t('Remove'), danger: true })) this.run({ action: 'remove', package: det.name, dev: mine.dev }).catch(() => null); } }, icon('trash'), t('Remove')) : null));
|
|
const requires = el('div.composer-requires');
|
|
body.append(requires);
|
|
const renderRequires = () => {
|
|
clear(requires);
|
|
const v = d.versions.find((x) => x.version === det.version) || d.versions[0];
|
|
if (!v) return;
|
|
for (const [label, deps] of [['Requires', v.require], ['Requires (dev)', v.requireDev]]) {
|
|
const entries = Object.entries(deps || {});
|
|
if (!entries.length) continue;
|
|
requires.append(el('div.composer-group', {}, `${t(label)} (${entries.length})`),
|
|
...entries.map(([n, c]) => el('div.composer-dep', {}, n.includes('/') ? el('a.composer-link', { href: '#', onclick: (e) => { e.preventDefault(); this.open(n); } }, n) : el('span', {}, n), el('span.composer-constraint', {}, c))));
|
|
}
|
|
};
|
|
renderRequires();
|
|
}
|
|
|
|
suggest(version) {
|
|
const m = /^v?(\d+)\.(\d+)(?:\.(\d+))?/.exec(version);
|
|
if (!m) return '*';
|
|
return m[1] === '0' ? `^0.${m[2]}.${m[3] || 0}` : `^${m[1]}.${m[2]}`;
|
|
}
|
|
|
|
/** the folder a tool call names (its dir, a game / app id), else the one chosen in the window */
|
|
async useTarget(target) {
|
|
if (!this.loaded || !this.targets.length) await this.load();
|
|
if (target === undefined || target === null || target === '') return;
|
|
const t2 = String(target).replace(/^\.\/?$/, '').replace(/\/+$/, '');
|
|
const found = this.targets.find((x) => x.dir === t2 || x.module === t2);
|
|
if (!found) throw new Error(`no composer.json for ${target}: ${this.targets.map((x) => x.dir || '.').join(', ')}`);
|
|
if (found.dir !== this.dir) { this.dir = found.dir; await this.loadPackages(); }
|
|
}
|
|
}
|
|
|
|
// Claude's tools (AgentTools, MCP server jumphp-ide): the same actions, shown in the Composer and Run windows
|
|
export const composerAgentTools = {
|
|
composer() {
|
|
if (!this.app.composer) throw new Error('no Composer window here: it needs a project on this computer');
|
|
return this.app.composer;
|
|
},
|
|
async tool_composer_search(args) {
|
|
this.composer();
|
|
return backend.invoke('composer.search', { q: String(args.query || ''), page: Number(args.page) || 1 });
|
|
},
|
|
async tool_composer_package(args) {
|
|
this.composer();
|
|
return backend.invoke('composer.package', { name: String(args.name || '') });
|
|
},
|
|
async tool_composer_outdated(args) {
|
|
const c = this.composer();
|
|
await c.useTarget(args.target);
|
|
this.app.showTool('composer', true);
|
|
return { dir: c.dir, packages: await c.checkOutdated() };
|
|
},
|
|
async tool_composer_require(args) {
|
|
const c = this.composer();
|
|
await c.useTarget(args.target);
|
|
const exit = await c.run({ action: 'require', package: String(args.package || ''), constraint: String(args.constraint || ''), dev: !!args.dev });
|
|
return { dir: c.dir, code: exit.code, ok: exit.code === 0, seconds: exit.seconds, output: exit.output };
|
|
},
|
|
async tool_composer_remove(args) {
|
|
const c = this.composer();
|
|
await c.useTarget(args.target);
|
|
const exit = await c.run({ action: 'remove', package: String(args.package || ''), dev: !!args.dev });
|
|
return { dir: c.dir, code: exit.code, ok: exit.code === 0, seconds: exit.seconds, output: exit.output };
|
|
},
|
|
};
|