poad 2.47.0 → 2.49.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 (45) hide show
  1. package/global/cli.js +14 -0
  2. package/global/cloud/action.js +37 -0
  3. package/global/cloud/create.js +42 -0
  4. package/global/cloud/index.js +19 -0
  5. package/global/cloud/info.js +37 -0
  6. package/global/cloud/pause.js +2 -0
  7. package/global/cloud/projects.js +32 -0
  8. package/global/cloud/resume.js +2 -0
  9. package/global/cloud/upgrade.js +2 -0
  10. package/global/create.js +4 -4
  11. package/global/init.js +2 -0
  12. package/global/login.js +32 -0
  13. package/global/logout.js +14 -0
  14. package/global/ls.js +2 -0
  15. package/global/projects.js +124 -0
  16. package/global/start.js +2 -0
  17. package/global/whoami.js +13 -0
  18. package/package.json +1 -1
  19. package/poad.js +5 -2
  20. package/project/cli.js +11 -0
  21. package/project/db/index.js +2 -0
  22. package/project/db/pull.js +92 -0
  23. package/project/db/url.js +33 -0
  24. package/project/deploy.js +136 -0
  25. package/project/env/create.js +19 -0
  26. package/project/env/index.js +2 -0
  27. package/project/env/ls.js +24 -0
  28. package/project/env/rm.js +21 -0
  29. package/project/link.js +38 -0
  30. package/project/unlink.js +12 -0
  31. package/project/upgrade.js +1 -0
  32. package/test/cloud.test.js +589 -0
  33. package/test/projects.test.js +167 -0
  34. package/utils/banner.js +3 -0
  35. package/utils/cloud/api.js +120 -0
  36. package/utils/cloud/branches.js +63 -0
  37. package/utils/cloud/bundle.js +226 -0
  38. package/utils/cloud/cli.js +166 -0
  39. package/utils/cloud/credentials.js +92 -0
  40. package/utils/cloud/db.js +34 -0
  41. package/utils/cloud/device.js +66 -0
  42. package/utils/cloud/system.js +45 -0
  43. package/utils/engine.js +1 -0
  44. package/utils/help-details.js +135 -0
  45. package/utils/projects.js +338 -0
package/global/cli.js CHANGED
@@ -22,4 +22,18 @@ module.exports = {
22
22
  models: 'Model catalog (poadio/permalink, cached): default model, prices and status per provider: ai models [provider] [--refresh]',
23
23
  },
24
24
  clean: 'Remove what stopped poad projects left on this machine: orphan services, networks, unused engine images',
25
+ projects: 'The poad projects of this machine (folder, state, engine, console URL), from ~/.poad/projects.json and Docker',
26
+ ls: 'Same as poad projects',
27
+ login: 'Log this machine in to poad.io (code confirmed in the browser); the session stays in ~/.poad/credentials.json, never shown',
28
+ logout: 'Forget the poad.io session of this machine (the token is revoked on poad.io)',
29
+ whoami: 'The poad.io account of the session (POAD_ACCESS_TOKEN first)',
30
+ cloud: {
31
+ description: 'Projects hosted on poad.io: list, create (and link this folder), info, pause, resume, engine upgrade',
32
+ projects: 'The poad.io projects of your account',
33
+ create: 'Create a poad.io project, then link this folder to it: cloud create [--name <name>] [--region paris]',
34
+ info: 'URL, anon key, state and engine of the linked poad.io project (never the service_role key)',
35
+ pause: 'Pause the linked poad.io project (confirmation, --yes)',
36
+ resume: 'Resume the linked poad.io project',
37
+ upgrade: 'Upgrade the engine of the linked poad.io project (confirmation, --yes; --to <version>)',
38
+ },
25
39
  };
@@ -0,0 +1,37 @@
1
+ // poad cloud pause | resume | upgrade : actions sur le projet poad.io lié.
2
+ // pause POST v1/projects/:id/pause (confirmation, --yes)
3
+ // resume POST v1/projects/:id/resume
4
+ // upgrade GET v1/projects/:id/engine, puis POST v1/projects/:id/upgrade { to }
5
+ // (confirmation, --yes ; --to <version> pour une version donnée)
6
+ module.exports = (action) => (args, raw) =>
7
+ require('../../utils/cloud/cli').run(raw, { values: ['project', 'to'] }, async ({ opts, out }) => {
8
+ const api = require('../../utils/cloud/api');
9
+ const cli = require('../../utils/cloud/cli');
10
+ const { chalk } = out;
11
+ const { id } = cli.targetProject(opts);
12
+ const base = `v1/projects/${api.enc(id)}`;
13
+
14
+ if (action === 'pause') {
15
+ await cli.confirm(`Pause ${id}? Its API stops answering until "poad cloud resume".`, { yes: opts.yes, json: out.json });
16
+ const r = await api.call('POST', `${base}/pause`, { what: 'pause' });
17
+ out.log(`${chalk.greenBright('✔')} Pause of ${id} requested.`);
18
+ return out.result({ id, action, status: r.status || null });
19
+ }
20
+ if (action === 'resume') {
21
+ const r = await api.call('POST', `${base}/resume`, { what: 'resume' });
22
+ out.log(`${chalk.greenBright('✔')} Resume of ${id} requested: "poad cloud info" to follow.`);
23
+ return out.result({ id, action, status: r.status || null });
24
+ }
25
+ // upgrade
26
+ const engine = await api.call('GET', `${base}/engine`, { what: 'engine' });
27
+ const to = opts.to || engine.offered;
28
+ if (!opts.to && !engine.available) {
29
+ out.log(`${chalk.greenBright('✔')} Engine ${engine.current || '?'}: nothing to upgrade${engine.reason ? chalk.grey(` (${engine.reason})`) : ''}.`);
30
+ return out.result({ id, action, upgraded: false, current: engine.current || null, offered: engine.offered || null, reason: engine.reason || null });
31
+ }
32
+ if (!to) throw new api.CloudError('poad.io offers no engine version to upgrade to.', { code: 'no_offer' });
33
+ await cli.confirm(`Upgrade the engine of ${id} from ${engine.current || '?'} to ${to}? The project restarts (about a minute).`, { yes: opts.yes, json: out.json });
34
+ const r = await api.call('POST', `${base}/upgrade`, { body: { to }, what: 'upgrade', timeout: 60000 });
35
+ out.log(`${chalk.greenBright('✔')} Engine upgrade of ${id} to ${to} started: "poad cloud info" to follow.`);
36
+ out.result({ id, action, upgraded: true, from: engine.current || null, to, upgrade: r && typeof r === 'object' ? { state: r.state || null } : null });
37
+ });
@@ -0,0 +1,42 @@
1
+ // poad cloud create [--name <nom>] [--region paris] [--no-link] [--json]
2
+ // Crée un projet sur poad.io (POST v1/projects), puis, dans un dossier poad
3
+ // pas encore lié, le lie ([cloud] project de poad/config.toml).
4
+ module.exports = (args, raw) =>
5
+ require('../../utils/cloud/cli').run(raw, { values: ['name', 'region'], flags: ['no-link'] }, async ({ opts, out }) => {
6
+ const path = require('path');
7
+ const api = require('../../utils/cloud/api');
8
+ const cli = require('../../utils/cloud/cli');
9
+ const { view, statusText } = require('./index');
10
+ const { chalk } = out;
11
+
12
+ const root = cli.projectRoot();
13
+ let name = opts.name;
14
+ if (!name && root) {
15
+ try {
16
+ name = cli.readToml(root).project_id;
17
+ } catch {}
18
+ if (!name) name = path.basename(path.dirname(path.dirname(root)));
19
+ }
20
+ if (!name) throw api.usageError('A name is needed outside a poad project folder: poad cloud create --name <name>');
21
+ name = String(name).trim().slice(0, 64);
22
+ const region = opts.region || 'paris';
23
+
24
+ const created = view(await api.call('POST', 'v1/projects', { body: { name, region }, what: 'project creation', timeout: 60000 }));
25
+ if (!created.id) throw new api.CloudError('poad.io created the project but sent back no id: see "poad cloud projects".', { code: 'bad_response' });
26
+
27
+ let link = 'none';
28
+ if (root && !opts['no-link']) {
29
+ const current = cli.linkedId(root);
30
+ if (current && current !== created.id) link = 'kept';
31
+ else {
32
+ cli.writeLink(root, created.id);
33
+ link = 'linked';
34
+ }
35
+ }
36
+ out.log(`${chalk.greenBright('✔')} Project ${chalk.bold(created.name || name)} created on poad.io: ${chalk.white(created.id)} ${statusText(chalk, created.status)}`);
37
+ if (link === 'linked') out.log(chalk.grey(` Linked to this folder: [cloud] project = "${created.id}" in ${cli.rel(root)} (commit it).`));
38
+ if (link === 'kept') out.log(chalk.yellowBright(` This folder stays linked to ${cli.linkedId(root)}: "poad link ${created.id}" to switch.`));
39
+ if (created.status === 'creating') out.log(chalk.grey(' It is being created (about a minute): "poad cloud info" to follow, then "poad deploy".'));
40
+ else out.log(chalk.grey(' Next: "poad deploy" sends poad/ (migrations, functions, flows…) to it.'));
41
+ out.result({ project: created, link });
42
+ });
@@ -0,0 +1,19 @@
1
+ // poad cloud : les projets hébergés sur poad.io (aide des sous-commandes)
2
+ module.exports = () => require('../../utils/help').printHelp(['cloud']);
3
+
4
+ /** Projet tel que l'API le rend, ramené aux champs affichables (jamais de clé) */
5
+ module.exports.view = (p = {}) => ({
6
+ id: p.id || null,
7
+ name: p.name || null,
8
+ region: p.region || null,
9
+ status: p.status || null,
10
+ status_detail: p.status_detail || null,
11
+ engine_version: p.engine_version || null,
12
+ created_at: p.created_at || null,
13
+ last_request_at: p.last_request_at || null,
14
+ });
15
+
16
+ module.exports.statusText = (chalk, s) => {
17
+ const styles = { active: chalk.green('● active'), paused: chalk.yellow('◐ paused'), creating: chalk.cyan('◌ creating'), deleting: chalk.grey('✕ deleting'), error: chalk.red('✕ error') };
18
+ return styles[s] || chalk.grey(s || '?');
19
+ };
@@ -0,0 +1,37 @@
1
+ // poad cloud info [--project <id>] [--json]
2
+ // Le projet poad.io lié : adresse, clé anon, état, version d'engine
3
+ // (GET v1/projects/:id et GET v1/projects/:id/keys). La clé service_role
4
+ // n'est jamais demandée ni affichée.
5
+ module.exports = (args, raw) =>
6
+ require('../../utils/cloud/cli').run(raw, { values: ['project'] }, async ({ opts, out }) => {
7
+ const api = require('../../utils/cloud/api');
8
+ const cli = require('../../utils/cloud/cli');
9
+ const { view, statusText } = require('./index');
10
+ const { chalk } = out;
11
+ const { id } = cli.targetProject(opts);
12
+ const p = view(await api.call('GET', `v1/projects/${api.enc(id)}`, { what: `project ${id}` }));
13
+ let keys = { url: null, anon_key: null };
14
+ if (p.status === 'active' || p.status === 'paused') {
15
+ try {
16
+ const k = await api.call('GET', `v1/projects/${api.enc(id)}/keys`, { what: 'keys' });
17
+ // Seuls ces deux champs : jamais service_role, même si l'API en rendait une
18
+ keys = { url: typeof k.url === 'string' ? k.url : null, anon_key: typeof k.anon_key === 'string' ? k.anon_key : null };
19
+ } catch (err) {
20
+ if (err.exit === api.EXIT.auth) throw err;
21
+ }
22
+ }
23
+ const info = { ...p, url: keys.url, anon_key: keys.anon_key };
24
+ if (out.json) return out.result(info);
25
+ out.log(' ');
26
+ out.log(` ${chalk.bold(p.name || id)} ${chalk.grey(id)} ${statusText(chalk, p.status)}${p.status_detail ? chalk.grey(` ${p.status_detail}`) : ''}`);
27
+ out.log(' ');
28
+ const row = (k, v) => out.log(` ${chalk.grey(k.padEnd(10))} ${v}`);
29
+ row('URL', info.url ? chalk.cyanBright(info.url) : chalk.grey('– (not ready yet)'));
30
+ row('anon key', info.anon_key ? chalk.white(info.anon_key) : chalk.grey('–'));
31
+ row('engine', p.engine_version || chalk.grey('–'));
32
+ row('region', p.region || chalk.grey('–'));
33
+ if (p.last_request_at) row('last use', chalk.grey(p.last_request_at));
34
+ out.log(' ');
35
+ out.log(chalk.grey(' The service_role key is never shown by the CLI: poad.io, project page. Database: "poad db url".'));
36
+ out.log(' ');
37
+ });
@@ -0,0 +1,2 @@
1
+ // poad cloud pause : voir action.js
2
+ module.exports = require('./action')('pause');
@@ -0,0 +1,32 @@
1
+ // poad cloud projects [--json] : les projets poad.io du compte (GET v1/projects)
2
+ module.exports = (args, raw) =>
3
+ require('../../utils/cloud/cli').run(raw, {}, async ({ out }) => {
4
+ const api = require('../../utils/cloud/api');
5
+ const cli = require('../../utils/cloud/cli');
6
+ const { view, statusText } = require('./index');
7
+ const { chalk } = out;
8
+ const data = await api.call('GET', 'v1/projects', { what: 'projects' });
9
+ const list = (Array.isArray(data) ? data : Array.isArray(data.projects) ? data.projects : []).map(view);
10
+ const root = cli.projectRoot();
11
+ const linked = root ? cli.linkedId(root) : null;
12
+ if (out.json) return out.result(list.map((p) => ({ ...p, linked: p.id === linked })));
13
+ out.log(' ');
14
+ out.log(chalk.bold(' POAD projects on poad.io') + chalk.grey(` (${list.length})`));
15
+ out.log(' ');
16
+ if (!list.length) return out.log(chalk.grey(' None yet: "poad cloud create" creates one (and links this project).'));
17
+ const { visible } = require('../../utils/layout');
18
+ const cols = [
19
+ { h: 'ID', v: (p) => p.id, s: chalk.white },
20
+ { h: 'NAME', v: (p) => p.name || '–', s: chalk.bold.white },
21
+ { h: 'STATE', v: (p) => statusText(chalk, p.status) },
22
+ { h: 'ENGINE', v: (p) => p.engine_version || '–', s: chalk.white },
23
+ { h: 'REGION', v: (p) => p.region || '–', s: chalk.grey },
24
+ { h: '', v: (p) => (p.id === linked ? 'linked to this folder' : ''), s: chalk.cyan },
25
+ ];
26
+ const cells = list.map((p) => cols.map((c) => String(c.v(p))));
27
+ const width = cols.map((c, i) => Math.max(visible(c.h), ...cells.map((r) => visible(r[i]))));
28
+ const pad = (t, w) => t + ' '.repeat(Math.max(0, w - visible(t)));
29
+ out.log(' ' + cols.map((c, i) => chalk.grey(pad(c.h, width[i]))).join(' '));
30
+ cells.forEach((r) => out.log(' ' + r.map((t, i) => pad(cols[i].s ? cols[i].s(t) : t, width[i])).join(' ').trimEnd()));
31
+ out.log(' ');
32
+ });
@@ -0,0 +1,2 @@
1
+ // poad cloud resume : voir action.js
2
+ module.exports = require('./action')('resume');
@@ -0,0 +1,2 @@
1
+ // poad cloud upgrade : voir action.js
2
+ module.exports = require('./action')('upgrade');
package/global/create.js CHANGED
@@ -281,11 +281,11 @@ async function makeApp(appDir, tpl, { name, title, app, pm, workspace, exclude,
281
281
  }
282
282
 
283
283
  /** poad init dans dir (le dépôt git est fait plus tard, sans question sur les services) */
284
- async function poadInit(dir) {
284
+ async function poadInit(dir, template) {
285
285
  const cwd = process.cwd();
286
286
  try {
287
287
  process.chdir(dir);
288
- return await require('./init')({}, [], { git: false, setup: false });
288
+ return await require('./init')({}, [], { git: false, setup: false, template });
289
289
  } finally {
290
290
  process.chdir(cwd);
291
291
  }
@@ -422,7 +422,7 @@ async function create(opts, { intro } = {}) {
422
422
  try {
423
423
  if (mode === 'new') {
424
424
  fs.mkdirSync(root, { recursive: true });
425
- await poadInit(root);
425
+ await poadInit(root, template && template.value);
426
426
  const tplPm = typeof tpl.pkg.packageManager === 'string' && tpl.pkg.packageManager.startsWith(`${pm}@`) ? tpl.pkg.packageManager : undefined;
427
427
  ws.writeJson(path.join(root, 'package.json'), ws.rootPackageJson(starter.packageName(path.basename(root)), [app], tplPm));
428
428
  ws.writeStartScript(root);
@@ -431,7 +431,7 @@ async function create(opts, { intro } = {}) {
431
431
  dev = await makeApp(appDir, tpl, { name: app, title: path.basename(root), app, pm, workspace, exclude: ws.usedPorts(root) });
432
432
  } else if (mode === 'flat') {
433
433
  dev = await makeApp(appDir, tpl, { name: starter.packageName(path.basename(root)), title: path.basename(root), app, pm, workspace: false, exclude: new Set(), keepPoad: true });
434
- await poadInit(root);
434
+ await poadInit(root, template && template.value);
435
435
  } else {
436
436
  const rootPkg = ws.readJson(path.join(root, 'package.json'));
437
437
  workspace = Boolean(ws.workspacesOf(rootPkg)) && appDir !== root;
package/global/init.js CHANGED
@@ -47,6 +47,8 @@ module.exports = async (args = {}, raw, options = {}) => {
47
47
  };
48
48
  fs.writeFileSync(root, json2toml(config));
49
49
  writeSecrets(root, generateSecrets());
50
+ // Registre des projets de la machine (~/.poad/projects.json, sans secret)
51
+ require('../utils/projects').record(root, { template: options.template });
50
52
  ensureGitignore(root);
51
53
  fs.mkdirSync(migrations.dir(root), { recursive: true });
52
54
  fs.writeFileSync(path.join(migrations.dir(root), '.gitkeep'), '');
@@ -0,0 +1,32 @@
1
+ // poad login [--no-browser] [--json]
2
+ // Connexion de cette machine à poad.io par appareil (RFC 8628) : un code à
3
+ // valider dans le navigateur, puis un jeton rangé dans ~/.poad/credentials.json
4
+ // (0600). Le jeton n'est jamais affiché. POAD_ACCESS_TOKEN (CI) passe avant.
5
+ module.exports = (args, raw) =>
6
+ require('../utils/cloud/cli').run(raw, { flags: ['no-browser'] }, async ({ opts, out }) => {
7
+ const api = require('../utils/cloud/api');
8
+ const device = require('../utils/cloud/device');
9
+ const creds = require('../utils/cloud/credentials');
10
+ const { chalk } = out;
11
+ const base = api.apiBase();
12
+
13
+ if (process.env.POAD_ACCESS_TOKEN) out.tell(chalk.yellowBright(' POAD_ACCESS_TOKEN is set: it is used before the session saved by poad login.'));
14
+
15
+ const d = await device.start();
16
+ const link = d.verification_uri_complete || d.verification_uri;
17
+ out.tell('');
18
+ out.tell(` ${chalk.bold('Code:')} ${chalk.cyanBright.bold(d.user_code)}`);
19
+ if (link) out.tell(` Confirm it on ${chalk.cyanBright(link)}`);
20
+ const tty = Boolean(process.stdout.isTTY && process.stdin.isTTY);
21
+ if (link && !opts['no-browser'] && tty && !out.json) {
22
+ if (require('../utils/cloud/system').openBrowser(link)) out.tell(chalk.grey(' (opened in your browser)'));
23
+ }
24
+ out.tell(chalk.grey(` Waiting for the confirmation (the code expires in ${Math.round(d.expires_in / 60)} min)…`));
25
+
26
+ const got = await device.poll(d.device_code, { interval: d.interval, expiresIn: d.expires_in });
27
+ creds.set(base, got);
28
+ const email = got.account && got.account.email;
29
+ out.log(`${chalk.greenBright('✔')} Logged in to poad.io${email ? ` as ${chalk.bold(email)}` : ''}.`);
30
+ out.log(chalk.grey(` Session saved in ${creds.file()} (readable by you only)${got.expires_at ? `, valid until ${got.expires_at}` : ''}.`));
31
+ out.result({ logged_in: true, account: got.account ? { id: got.account.id || null, email: got.account.email || null } : null, expires_at: got.expires_at, api: base });
32
+ });
@@ -0,0 +1,14 @@
1
+ // poad logout [--json]
2
+ // Oublie la session poad.io de cette machine (~/.poad/credentials.json). Le
3
+ // jeton n'est pas révoqué par le CLI : cela se fait sur poad.io.
4
+ module.exports = (args, raw) =>
5
+ require('../utils/cloud/cli').run(raw, {}, async ({ out }) => {
6
+ const api = require('../utils/cloud/api');
7
+ const creds = require('../utils/cloud/credentials');
8
+ const { chalk } = out;
9
+ const removed = creds.remove(api.apiBase());
10
+ out.log(removed ? `${chalk.greenBright('✔')} poad.io session removed from this machine.` : chalk.grey(' No poad.io session saved on this machine.'));
11
+ out.log(chalk.grey(' The token itself is not revoked: revoke it on poad.io (account, CLI sessions) if it may have leaked.'));
12
+ if (process.env.POAD_ACCESS_TOKEN) out.log(chalk.yellowBright(' POAD_ACCESS_TOKEN is still set in this shell: it is still used.'));
13
+ out.result({ logged_out: removed, revoked: false, env_token: Boolean(process.env.POAD_ACCESS_TOKEN) });
14
+ });
package/global/ls.js ADDED
@@ -0,0 +1,2 @@
1
+ // poad ls : alias de poad projects
2
+ module.exports = (...a) => require('./projects')(...a);
@@ -0,0 +1,124 @@
1
+ // poad projects (ou poad ls) les projets poad de cette machine, d'après le
2
+ // registre ~/.poad/projects.json (tenu par poad
3
+ // init, create, start, upgrade) et l'état Docker
4
+ // (un seul « docker ps -a »)
5
+ // --json sortie JSON (pour un script)
6
+ // --all avec les projets dont le dossier n'existe plus
7
+ // --prune retire du registre les projets dont le dossier n'existe plus
8
+ // (liste d'abord ; question, sauf --yes)
9
+ // --scan retrouve les projets d'après les conteneurs Docker (lecture
10
+ // seule) et le dossier courant ; fait d'office au premier appel
11
+ //
12
+ // Rien n'est démarré, arrêté ni supprimé : seul le registre change (--scan,
13
+ // --prune). Aucun secret n'est lu ni affiché.
14
+ module.exports = async (args = {}) => {
15
+ const chalk = require('chalk-v2');
16
+ const os = require('os');
17
+ const reg = require('../utils/projects');
18
+ const { findPoadDir } = require('../utils/findpoad');
19
+ const flag = (f) => Boolean(args[f] || args[`--${f}`]);
20
+ const json = flag('json');
21
+ const yes = flag('yes') || Boolean(args['-y']);
22
+
23
+ const cwdRoot = findPoadDir(process.cwd());
24
+ // Le projet du dossier courant est toujours inscrit
25
+ if (cwdRoot) reg.record(cwdRoot);
26
+
27
+ let scanned = null;
28
+ const { exists, corrupt } = reg.read();
29
+ if (flag('scan') || !exists || corrupt) {
30
+ try {
31
+ scanned = await reg.scan({ cwdRoot });
32
+ } catch (e) {
33
+ if (!json) console.log(chalk.yellowBright(` Scan failed: ${e.message}`));
34
+ }
35
+ }
36
+ if (corrupt && !json) console.log(chalk.yellowBright(` The registry could not be read: kept aside as ${corrupt}, rebuilt from Docker.`));
37
+
38
+ const ps = await reg.docker(['ps', '-a', '--format', '{{json .}}']);
39
+ const containers = ps === null ? null : reg.parsePs(ps);
40
+ const { data } = reg.read();
41
+
42
+ if (flag('prune')) {
43
+ const gone = reg.rows(data, containers, { all: true }).filter((r) => r.missing);
44
+ if (!gone.length) return json ? console.log(JSON.stringify({ removed: [] })) : console.log(chalk.grey('\n No project with a missing folder: nothing to prune.'));
45
+ if (!json) {
46
+ console.log(chalk.bold('\n Projects whose folder no longer exists'));
47
+ for (const r of gone) console.log(` ${chalk.white(r.name)} ${chalk.grey(r.id)} ${chalk.grey(tilde(r.path))}`);
48
+ console.log(chalk.grey(' Only their line in ~/.poad/projects.json is removed (containers and images: poad clean).'));
49
+ }
50
+ let go = yes;
51
+ if (!go && process.stdin.isTTY && process.stdout.isTTY && !json) {
52
+ const { confirm } = require('@inquirer/prompts');
53
+ go = await confirm({ message: `Remove ${gone.length} entr${gone.length > 1 ? 'ies' : 'y'} from the registry?`, default: true }).catch(() => false);
54
+ }
55
+ if (!go) {
56
+ if (!json) console.log(chalk.grey(' Nothing removed (add --yes outside a terminal).'));
57
+ else console.log(JSON.stringify({ removed: [], reason: 'confirmation required (--yes)' }));
58
+ return;
59
+ }
60
+ const n = reg.remove(gone.map((r) => r.id));
61
+ return json ? console.log(JSON.stringify({ removed: gone.map((r) => r.id) })) : console.log(chalk.green(` ${n} entr${n > 1 ? 'ies' : 'y'} removed.`));
62
+ }
63
+
64
+ const list = reg.rows(data, containers, { all: flag('all') });
65
+ const hidden = reg.rows(data, containers, { all: true }).length - list.length;
66
+
67
+ if (json) {
68
+ console.log(JSON.stringify(list.map(({ id, name, path, state, engine, port, template, cloud, created_at, last_used_at }) => ({ id, name, path, state, engine, api: port ? `http://localhost:${port}` : null, console: port ? `http://localhost:${port}/console` : null, template, cloud: cloud || null, created_at, last_used_at })), null, 2));
69
+ return;
70
+ }
71
+
72
+ console.log(' ');
73
+ console.log(chalk.bold(` POAD projects on this machine`) + chalk.grey(` (${list.length}${hidden ? `, ${hidden} with a missing folder: --all` : ''})`));
74
+ if (scanned && scanned.added) console.log(chalk.grey(` ${scanned.added} found from Docker and added to the registry.`));
75
+ if (containers === null) console.log(chalk.yellowBright(' Docker is not reachable: state unknown.'));
76
+ console.log(' ');
77
+ if (!list.length) {
78
+ console.log(chalk.grey(' None yet. poad init or poad create records a project here; poad projects --scan looks for existing ones in Docker.'));
79
+ console.log(' ');
80
+ return;
81
+ }
82
+
83
+ const STATE = {
84
+ running: chalk.green('● running'),
85
+ stopped: chalk.grey('○ stopped'),
86
+ none: chalk.grey('○ not started'),
87
+ unknown: chalk.grey('? unknown'),
88
+ missing: chalk.red('✕ folder gone'),
89
+ };
90
+ const cols = [
91
+ { h: 'NAME', v: (r) => r.name, s: chalk.bold.white },
92
+ { h: 'STATE', v: (r) => STATE[r.state] || r.state },
93
+ { h: 'ENGINE', v: (r) => r.engine || '–', s: chalk.white },
94
+ { h: 'CONSOLE', v: (r) => (r.port ? `http://localhost:${r.port}/console` : '–'), s: (t) => (t === '–' ? chalk.grey(t) : chalk.cyanBright(t)) },
95
+ // Colonne de la liaison poad.io, seulement si un projet est lié
96
+ ...(list.some((r) => r.cloud) ? [{ h: 'POAD.IO', v: (r) => r.cloud || '–', s: (t) => (t === '–' ? chalk.grey(t) : chalk.magenta(t)) }] : []),
97
+ { h: 'LAST USED', v: (r) => ago(r.last_used_at || r.created_at), s: chalk.grey },
98
+ { h: 'PATH', v: (r) => tilde(r.path), s: chalk.grey },
99
+ ];
100
+ const { visible } = require('../utils/layout');
101
+ const cells = list.map((r) => cols.map((c) => String(c.v(r))));
102
+ const width = cols.map((c, i) => Math.max(visible(c.h), ...cells.map((row) => visible(row[i]))));
103
+ const pad = (t, w) => t + ' '.repeat(Math.max(0, w - visible(t)));
104
+ console.log(' ' + cols.map((c, i) => chalk.grey(pad(c.h, width[i]))).join(' '));
105
+ cells.forEach((row) => console.log(' ' + row.map((t, i) => pad(cols[i].s ? cols[i].s(t) : t, width[i])).join(' ')));
106
+ console.log(' ');
107
+ console.log(chalk.grey(' cd <path> && poad start · poad projects --json · --scan to find older projects · --prune to forget deleted ones'));
108
+ console.log(' ');
109
+
110
+ function tilde(p) {
111
+ const home = os.homedir();
112
+ return p === home || p.startsWith(home + '/') ? '~' + p.slice(home.length) : p;
113
+ }
114
+ function ago(iso) {
115
+ const t = Date.parse(iso || '');
116
+ if (!t) return '–';
117
+ const s = Math.max(0, (Date.now() - t) / 1000);
118
+ if (s < 90) return 'just now';
119
+ if (s < 5400) return `${Math.round(s / 60)} min ago`;
120
+ if (s < 129600) return `${Math.round(s / 3600)} h ago`;
121
+ if (s < 60 * 86400) return `${Math.round(s / 86400)} d ago`;
122
+ return new Date(t).toISOString().slice(0, 10);
123
+ }
124
+ };
package/global/start.js CHANGED
@@ -30,6 +30,8 @@ module.exports = async (args = {}) => {
30
30
  if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
31
31
  const config = require('../utils/config').readConfig(root);
32
32
  const containerName = config.project_uuid;
33
+ // Registre des projets de la machine : dernière utilisation (inscrit s'il n'y était pas)
34
+ require('../utils/projects').record(root, { used: true });
33
35
  console.log(' ');
34
36
  const { wantsAll, SERVICES, autostartServices } = require('../utils/services');
35
37
  const all = wantsAll(args);
@@ -0,0 +1,13 @@
1
+ // poad whoami [--json] : le compte poad.io de la session (GET v1/me)
2
+ module.exports = (args, raw) =>
3
+ require('../utils/cloud/cli').run(raw, {}, async ({ out }) => {
4
+ const api = require('../utils/cloud/api');
5
+ const { chalk } = out;
6
+ const t = api.requireToken();
7
+ const me = await api.call('GET', 'v1/me', { what: 'account' });
8
+ const account = me.account && typeof me.account === 'object' ? me.account : me;
9
+ const view = { id: account.id || null, email: account.email || null, source: t.source === 'env' ? 'POAD_ACCESS_TOKEN' : 'poad login', expires_at: t.expires_at, api: api.apiBase() };
10
+ out.log(`${chalk.bold(view.email || view.id || '?')}${view.id && view.email ? chalk.grey(` ${view.id}`) : ''}`);
11
+ out.log(chalk.grey(` session: ${view.source}${view.expires_at ? `, valid until ${view.expires_at}` : ''}${view.api !== api.DEFAULT_API ? `, API ${view.api}` : ''}`));
12
+ out.result(view);
13
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.47.0",
3
+ "version": "2.49.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.2.0",
6
6
  "main": "index.js",
package/poad.js CHANGED
@@ -252,7 +252,8 @@ const processCommands = (args) => {
252
252
  unit(parseArgs(px.args), px.args);
253
253
  } else {
254
254
  if (POAD_COMMANDS[command]) {
255
- console.log(' ');
255
+ // --json : rien d'autre que le JSON sur la sortie standard
256
+ if (!args.includes('--json')) console.log(' ');
256
257
 
257
258
  const dir = args.join('/');
258
259
  const px = parseCommandArgs(require(__dirname + '/project/cli'), args);
@@ -331,7 +332,9 @@ const main = async () => {
331
332
  // Création de l'encadré avec Boxen
332
333
  const framedMessage = boxen(styledMessage, boxenOptions);
333
334
 
334
- console.log(framedMessage);
335
+ // --json : l'avis de nouvelle version part sur stderr, la sortie reste du JSON
336
+ if (process.argv.includes('--json')) console.error(framedMessage);
337
+ else console.log(framedMessage);
335
338
 
336
339
  POAD_GLOBAL_COMMANDS = loadPoadCommands(__dirname + '/global/cli.js');
337
340
  process.argv.shift();
package/project/cli.js CHANGED
@@ -20,7 +20,18 @@ module.exports = {
20
20
  reset: 'Erase the database and storage files, restart, apply migrations then poad/seed.sql (--yes outside a terminal)',
21
21
  seed: 'Apply poad/seed.sql (development data)',
22
22
  diff: 'Structure changes made outside the migrations (console SQL, psql…): diff to list them, diff <name> to write them as a migration, diff --discard to forget them',
23
+ url: 'Connection string of the poad.io database (password masked, copied to the clipboard; --show-password to print it)',
24
+ pull: 'Schema of the poad.io database into a new local migration (pg_dump --schema-only, never overwrites)',
23
25
  },
26
+ link: 'Link this project to a poad.io project: [cloud] project = "<id>" in poad/config.toml (no secret): link [<id>]',
27
+ unlink: 'Remove the link to poad.io from poad/config.toml (nothing changes on poad.io)',
28
+ env: {
29
+ description: 'Environments (branches) of the linked poad.io project: main is production',
30
+ ls: 'Environments of the project; the default of poad deploy is the current git branch if it exists there, else main',
31
+ create: 'Create an environment: env create <name> [--kind persistent|preview]',
32
+ rm: 'Remove an environment, its database and files (confirmation, --yes); never main',
33
+ },
34
+ deploy: 'Send poad/ (migrations, functions, flows, api, auth, storage…, never a secret) to poad.io: deploy [--env <name>] [--dry-run] [--yes]',
24
35
  upgrade: 'Upgrade the engine of the project (backup first), or roll back to a backup',
25
36
  logs: 'Unified logs of the project, every service, with filters (level, since, request, flow, function, AI…) and -f',
26
37
  gen: {
@@ -6,6 +6,8 @@ module.exports = async () => {
6
6
  console.log(` ${chalk.cyanBright('poad db reset')} Erase the database and storage files, restart, apply migrations then poad/seed.sql`);
7
7
  console.log(` ${chalk.cyanBright('poad db seed')} Apply poad/seed.sql (development data)`);
8
8
  console.log(` ${chalk.cyanBright('poad db diff')} Structure changes made outside the migrations; "db diff <name>" writes them as a migration`);
9
+ console.log(` ${chalk.cyanBright('poad db url')} Connection string of the poad.io database (password masked unless --show-password)`);
10
+ console.log(` ${chalk.cyanBright('poad db pull')} Schema of the poad.io database into a new local migration`);
9
11
  console.log(` ${chalk.cyanBright('poad migrate')} Apply pending migrations`);
10
12
  console.log(' ');
11
13
  };
@@ -0,0 +1,92 @@
1
+ // poad db pull [--env <branche>] [--name <nom>] [--json]
2
+ // Schéma de la base du projet poad.io lié -> nouvelle migration locale
3
+ // (poad/migrations/<horodatage>_<nom>.sql), par pg_dump --schema-only via
4
+ // db.poad.io. Jamais d'écrasement : le fichier est toujours nouveau.
5
+ //
6
+ // pg_dump : celui de la machine, sinon celui du conteneur de l'engine local
7
+ // (docker exec, projet démarré), sinon ce qu'il faut installer. Le mot de
8
+ // passe passe par PGPASSWORD (environnement), jamais en argument.
9
+ //
10
+ // Les schémas de l'engine (auth, storage, _poad, _logs, poad_migrations,
11
+ // vault…) ne sont pas tirés : ils viennent de l'engine lui-même.
12
+ const INTERNAL = ['auth', 'storage', '_poad', '_logs', 'poad_migrations', 'extensions', 'pgsodium', 'pgsodium_masks', 'vault', 'cron', 'net', 'graphql', 'graphql_public', 'realtime', '_timescaledb_*', 'timescaledb_*', 'supabase_functions', 'pgbouncer', 'tiger', 'tiger_data', 'topology'];
13
+
14
+ /** Sortie de pg_dump rendue jouable par poad migrate : ni commandes psql, ni réglages de session */
15
+ function cleanDump(sql) {
16
+ return String(sql)
17
+ .split('\n')
18
+ .filter((l) => !/^\\/.test(l))
19
+ .filter((l) => !/^SET\s+[a-z_]+\s*=.*;\s*$/i.test(l))
20
+ .filter((l) => !/^SELECT pg_catalog\.set_config\('search_path', '', false\);\s*$/.test(l))
21
+ .join('\n')
22
+ .replace(/\n{3,}/g, '\n\n')
23
+ .trim();
24
+ }
25
+
26
+ function run(cmd, argv, env) {
27
+ const { spawn } = require('child_process');
28
+ return new Promise((resolve) => {
29
+ const child = spawn(cmd, argv, { env, stdio: ['ignore', 'pipe', 'pipe'] });
30
+ const out = [];
31
+ const err = [];
32
+ child.stdout.on('data', (d) => out.push(d));
33
+ child.stderr.on('data', (d) => err.push(d));
34
+ child.on('error', (e) => resolve({ status: -1, stdout: '', stderr: e.message }));
35
+ child.on('close', (status) => resolve({ status, stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8') }));
36
+ });
37
+ }
38
+
39
+ module.exports = (args, raw) =>
40
+ require('../../utils/cloud/cli').run(raw, { values: ['env', 'name', 'project'] }, async ({ opts, out }) => {
41
+ const fs = require('fs');
42
+ const api = require('../../utils/cloud/api');
43
+ const cli = require('../../utils/cloud/cli');
44
+ const branches = require('../../utils/cloud/branches');
45
+ const db = require('../../utils/cloud/db');
46
+ const { has } = require('../../utils/cloud/system');
47
+ const migrations = require('../../utils/migrations');
48
+ const { chalk } = out;
49
+
50
+ const root = cli.projectRoot();
51
+ if (!root) throw api.usageError('Not in a poad project folder: cd into one.');
52
+ const { id } = cli.targetProject(opts);
53
+ const env = await branches.resolve(id, { wanted: opts.env, root });
54
+
55
+ // Où lancer pg_dump
56
+ let runner = null;
57
+ if (process.env.POAD_PG_DUMP || has('pg_dump')) runner = { cmd: process.env.POAD_PG_DUMP || 'pg_dump', pre: [], where: 'this machine' };
58
+ else {
59
+ let uuid = null;
60
+ try {
61
+ uuid = cli.readToml(root).project_uuid;
62
+ } catch {}
63
+ const ps = uuid && has('docker') ? await run('docker', ['ps', '--filter', `name=^/${uuid}$`, '--format', '{{.Names}}'], process.env) : null;
64
+ if (ps && ps.status === 0 && ps.stdout.trim() === uuid) runner = { cmd: 'docker', pre: ['exec', '-e', 'PGPASSWORD', '-e', 'PGSSLMODE', uuid, 'pg_dump'], where: 'the local engine container' };
65
+ }
66
+ if (!runner) {
67
+ throw new api.CloudError('pg_dump is needed: install the PostgreSQL client tools (macOS: brew install libpq, then add its bin to PATH; Debian/Ubuntu: apt install postgresql-client), or start the local project ("poad start") to use the pg_dump of its engine.', { code: 'pg_dump_missing' });
68
+ }
69
+
70
+ const c = await db.credentials(id, { env, purpose: 'copy' });
71
+ const argv = [...runner.pre, '--schema-only', '--no-owner', '--no-privileges', '-h', c.host, '-p', String(c.port('session')), '-U', c.user, '-d', 'postgres', ...INTERNAL.flatMap((s) => ['-N', s])];
72
+ out.log(chalk.grey(` pg_dump of ${id} (${env.branch}) through ${c.host}, from ${runner.where}…`));
73
+ const r = await run(runner.cmd, argv, { ...process.env, PGPASSWORD: c.password, PGSSLMODE: 'require', PGCONNECT_TIMEOUT: '15' });
74
+ if (r.status !== 0) {
75
+ const why = r.stderr.split(c.password).join(db.MASK).trim().split('\n').slice(-3).join(' ');
76
+ const hint = /server version/.test(why) ? ' Your pg_dump is older than the server: install a newer PostgreSQL client.' : '';
77
+ throw new api.CloudError(`pg_dump failed: ${why || `exit ${r.status}`}.${hint}`, { code: 'pg_dump_failed' });
78
+ }
79
+ const sql = cleanDump(r.stdout);
80
+ if (!/^\s*CREATE\s/im.test(sql)) {
81
+ out.log(chalk.grey(' The cloud database has no structure of its own yet: no migration written.'));
82
+ return out.result({ project: id, env: env.branch, written: null });
83
+ }
84
+ const name = opts.name || `cloud_${env.branch.replace(/[^A-Za-z0-9]+/g, '_')}_schema`;
85
+ const file = migrations.create(root, name);
86
+ fs.appendFileSync(file, `-- Schéma tiré de poad.io par "poad db pull" : projet ${id}, environnement ${env.branch}, ${new Date().toISOString()}.\n-- Relisez-le avant "poad migrate" : une table qui existe déjà dans la base locale le ferait échouer.\n\n${sql}\n`);
87
+ out.log(`${chalk.greenBright('✔')} ${chalk.bold(cli.rel(file))}`);
88
+ out.log(chalk.grey(' A new migration (nothing overwritten). Review it, then "poad migrate" locally.'));
89
+ out.result({ project: id, env: env.branch, written: cli.rel(file) });
90
+ });
91
+
92
+ module.exports.cleanDump = cleanDump;