poad 2.11.0 → 2.13.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.
package/global/run.js CHANGED
@@ -22,9 +22,13 @@ module.exports = async (args = {}) => {
22
22
  const { SERVICES, containerState, wantedServices, wantsAll } = require('../utils/services');
23
23
 
24
24
  const all = wantsAll(args);
25
- const wanted = wantedServices(args);
25
+ // Appel interne de poad start : { services: ['keycloak', …], quiet: true }
26
+ const listed = Array.isArray(args.services) ? args.services : null;
27
+ const quiet = Boolean(args.quiet);
28
+ const wanted = listed ? SERVICES.filter((s) => listed.includes(s.id)) : wantedServices(args);
26
29
 
27
- console.log(' ');
30
+ if (!quiet) console.log(' ');
31
+ if (listed && !wanted.length) return;
28
32
  if (!all && !wanted.length) {
29
33
  console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad run <service>')}`);
30
34
  console.log(' ');
@@ -37,16 +41,13 @@ module.exports = async (args = {}) => {
37
41
 
38
42
  const root = findPoadDir(process.cwd());
39
43
  if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
40
- const readConfig = () => toml.parse(fs.readFileSync(root, 'utf-8'));
41
- let config = readConfig();
44
+ const readConfig = () => require('../utils/config').loadConfig(root);
45
+ let config = require('../utils/config').readConfig(root);
42
46
 
43
47
  if (!(await isDockerExist(config.project_uuid))) {
44
48
  if (!all) return console.log(chalk.redBright('The project is not started: run "poad start" first (or "poad run --all").'));
45
- // --all : le projet d'abord, puis ses services
46
- await require('./start')({});
47
- if (!(await isDockerExist(config.project_uuid))) return;
48
- console.log(' ');
49
- config = readConfig();
49
+ // --all : poad start --all démarre le projet puis tous ses services
50
+ return require('./start')({ all: true });
50
51
  }
51
52
 
52
53
  // Juste après un démarrage, la base et le service auth ne sont pas encore
@@ -74,9 +75,10 @@ module.exports = async (args = {}) => {
74
75
  }
75
76
  }
76
77
  for (const service of targets) {
77
- // --all complète ce qui manque : un service déjà lancé n'est pas redémarré
78
- if (all && (await containerState(docker, service.container(config))) === 'running') {
79
- console.log(`${chalk.greenBright('✔')} ${service.label} already running.`);
78
+ // --all (ou poad start) complète ce qui manque : un service déjà lancé
79
+ // n'est pas redémarré
80
+ if ((all || listed) && (await containerState(docker, service.container(config))) === 'running') {
81
+ if (!quiet) console.log(`${chalk.greenBright('✔')} ${service.label} already running.`);
80
82
  continue;
81
83
  }
82
84
  await runners[service.id]();
@@ -161,6 +163,7 @@ module.exports = async (args = {}) => {
161
163
  progress.fail(chalk.redBright(`Keycloak failed to start: ${err.message}`));
162
164
  return;
163
165
  }
166
+ if (quiet) return;
164
167
 
165
168
  console.log(' ');
166
169
  const base = `http://localhost:${port}`;
@@ -219,6 +222,7 @@ module.exports = async (args = {}) => {
219
222
  progress.fail(chalk.redBright(`Valkey failed to start: ${err.message}`));
220
223
  return;
221
224
  }
225
+ if (quiet) return;
222
226
 
223
227
  console.log(' ');
224
228
  console.log(
package/global/start.js CHANGED
@@ -1,5 +1,8 @@
1
- // poad start démarre le projet (engine + Mailpit)
2
- // poad start --all puis tous les services optionnels configurés (Keycloak, Valkey…)
1
+ // poad start démarre le projet (engine + Mailpit), applique les
2
+ // migrations, lance les services en autostart (poad setup),
3
+ // puis affiche l'état complet (comme poad info)
4
+ // poad start --all tous les services configurés, autostart ou non
5
+ // poad start --bare l'engine et Mailpit seulement, cette fois-ci
3
6
  module.exports = async (args = {}) => {
4
7
  const chalk = require('chalk-v2');
5
8
  const Docker = require('dockerode');
@@ -16,15 +19,25 @@ module.exports = async (args = {}) => {
16
19
  const mail = require('../utils/mail');
17
20
  const valkey = require('../utils/valkey');
18
21
  const root = findPoadDir(process.cwd());
19
- const config = toml.parse(await fs.readFile(root, 'utf-8'));
22
+ if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
23
+ const config = require('../utils/config').readConfig(root);
20
24
  const containerName = config.project_uuid;
21
25
  console.log(' ');
22
- const { wantsAll } = require('../utils/services');
26
+ const { wantsAll, SERVICES, autostartServices } = require('../utils/services');
23
27
  const all = wantsAll(args);
28
+ const bare = Boolean(args.bare || args['--bare']);
29
+
30
+ // Services optionnels à lancer, puis l'état complet du projet
31
+ const finish = async () => {
32
+ const targets = bare ? [] : all ? SERVICES.filter((s) => s.optional && s.configured(config)) : autostartServices(config);
33
+ if (targets.length) await require('./run')({ services: targets.map((s) => s.id), quiet: true });
34
+ console.log(' ');
35
+ await require('../utils/report').printReport(root, require('../utils/config').loadConfig(root));
36
+ };
37
+
24
38
  if (await isDockerExist(containerName)) {
25
39
  console.log(chalk.bold('Container already started'));
26
- if (all) await require('./run')({ all: true });
27
- return;
40
+ return finish();
28
41
  }
29
42
  config.engine = await offerEngineUpgrade(root, config, args);
30
43
  const image = 'poadio/engine:' + config.engine;
@@ -82,21 +95,23 @@ module.exports = async (args = {}) => {
82
95
  return;
83
96
  }
84
97
  progress.succeed(chalk.bold('containers started.'));
85
- if (!all && valkey.enabled(config) && !(await isDockerExist(valkey.containerName(config)))) {
86
- console.log(chalk.grey(' Valkey is configured: start it with "poad run valkey".'));
98
+ // Migrations en attente de poad/migrations ([db] auto_migrate = false pour
99
+ // les appliquer à la main avec poad migrate)
100
+ const migrations = require('../utils/migrations');
101
+ if (migrations.files(root).list.length) {
102
+ if (!migrations.autoMigrate(config)) {
103
+ console.log(chalk.grey(' auto_migrate is off: run "poad migrate" to apply pending migrations.'));
104
+ } else {
105
+ const waiting = ora('Waiting for the database to apply migrations').start();
106
+ const ready = (await migrations.waitForDb(config)) && (await migrations.waitForServices(config));
107
+ if (!ready) {
108
+ waiting.fail(chalk.redBright('Migrations not applied: the engine does not answer (poad migrate later).'));
109
+ } else {
110
+ waiting.stop();
111
+ await require('../utils/migrate-run')(root, config, { quietWhenNone: false });
112
+ }
113
+ }
87
114
  }
88
- console.log(' ');
89
- console.log(chalk.bold(' 🚀 Container started successfully'));
90
- console.log(' ');
91
- const info = {
92
- 'API URL': `http://localhost:${config.web.port}`,
93
- 'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
94
- ...storageInfo(config),
95
- ...(mailpit ? { 'Mail URL': `http://localhost:${mail.mailPort(config)}` } : { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }),
96
- 'JWT secret': `${config.auth.secret}`,
97
- 'anon key': config.auth.anon,
98
- 'service_role key': config.auth.service,
99
- };
100
- console.log(prettyoutput(info));
101
- if (all) await require('./run')({ all: true });
115
+
116
+ await finish();
102
117
  };
package/global/stop.js CHANGED
@@ -12,7 +12,8 @@ module.exports = async (args) => {
12
12
  const mail = require('../utils/mail');
13
13
  const valkey = require('../utils/valkey');
14
14
  const root = findPoadDir(process.cwd());
15
- const config = toml.parse(await fs.readFile(root, 'utf-8'));
15
+ if (!root) return console.log(require('chalk-v2').redBright('You are not in a poad project directory.'));
16
+ const config = require('../utils/config').readConfig(root);
16
17
  const containerName = config.project_uuid;
17
18
  const ora = require('ora');
18
19
  const chalk = require('chalk-v2');
package/package.json CHANGED
@@ -1,16 +1,17 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.11.0",
4
- "engine": "0.7.0",
3
+ "version": "2.13.0",
4
+ "engine": "0.7.1",
5
5
  "main": "index.js",
6
6
  "license": "MIT",
7
7
  "bin": {
8
8
  "poad": "./poad.js"
9
9
  },
10
10
  "scripts": {
11
- "build": "yarn clean && yarn"
11
+ "build": "bun install"
12
12
  },
13
13
  "dependencies": {
14
+ "@inquirer/prompts": "^8.8.0",
14
15
  "axios": "^1.7.7",
15
16
  "boxen": "^5.1.2",
16
17
  "chalk-v2": "^1.0.2",
@@ -23,7 +24,9 @@
23
24
  "listr": "^0.14.3",
24
25
  "log-beautify": "^1.2.0",
25
26
  "ora": "^5.4.1",
27
+ "pg": "8.16.3",
26
28
  "prettyoutput": "^1.2.0",
27
29
  "toml": "^3.0.0"
28
- }
30
+ },
31
+ "packageManager": "bun@1.4.4"
29
32
  }
package/project/cli.js CHANGED
@@ -9,6 +9,9 @@
9
9
  module.exports = {
10
10
  info: `Information about your project`,
11
11
  kc: 'Keycloak test set of the project (poad/keycloak.json; kc export saves the running realm)',
12
+ setup: 'Choose what "poad start" starts: e-mails (Mailpit/SMTP), Keycloak, Valkey, migrations (interactive, or kc=on valkey=off, --all, --none, --list)',
13
+ migrate: 'Apply pending migrations of poad/migrations (poad start does it too)',
14
+ migration: 'Database migrations: migration new <name>, migration list',
12
15
  /* status: `[AI] Vérification du statut de l'environnement`,
13
16
  gen: {
14
17
  description: 'Génération automatique des éléments clés pour votre projet',
package/project/info.js CHANGED
@@ -1,68 +1,16 @@
1
- // poad info : le projet (URL, base, clés), puis un panneau à part pour les
2
- // services qui tournent à côté de l'engine (Mailpit, Keycloak, Valkey).
1
+ // poad info : le projet (URL, base, clés, migrations), puis un panneau à part
2
+ // pour les services qui tournent à côté de l'engine (Mailpit, Keycloak, Valkey).
3
+ // poad start affiche la même chose à la fin du démarrage.
3
4
  module.exports = async () => {
4
5
  const chalk = require('chalk-v2');
5
- const toml = require('toml');
6
- const fs = require('fs').promises;
7
- const Docker = require('dockerode');
8
- const docker = new Docker();
9
- const prettyoutput = require('prettyoutput');
10
6
  const { findPoadDir } = require('../utils/findpoad');
11
7
  const { isDockerExist } = require('../utils/docker');
12
- const { storageInfo } = require('../utils/engine');
13
- const { SERVICES, containerState } = require('../utils/services');
14
8
  const root = findPoadDir(process.cwd());
15
- const config = toml.parse(await fs.readFile(root, 'utf-8'));
9
+ if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
10
+ const config = require('../utils/config').readConfig(root);
16
11
  console.log(' ');
17
12
  if (!(await isDockerExist(config.project_uuid))) {
18
- return console.log(chalk.redBright('Container not found'));
13
+ return console.log(chalk.redBright('The project is not started: "poad start".'));
19
14
  }
20
- console.log(chalk.bold('POAD project info'));
21
- console.log(' ');
22
- const info = {
23
- Engine: config.engine,
24
- 'API URL': `http://localhost:${config.web.port}`,
25
- 'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
26
- ...storageInfo(config),
27
- ...(config.smtp && config.smtp.host ? { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` } : {}),
28
- 'JWT secret': `${config.auth.secret}`,
29
- 'anon key': config.auth.anon,
30
- 'service_role key': config.auth.service,
31
- };
32
- console.log(prettyoutput(info));
33
-
34
- // Panneau des services : en cours, arrêtés (configurés), ou disponibles
35
- const rows = [];
36
- for (const s of SERVICES) {
37
- const configured = s.configured(config);
38
- if (!configured && !s.optional) continue; // Mailpit remplacé par un vrai SMTP
39
- const state = configured ? await containerState(docker, s.container(config)) : null;
40
- rows.push({ s, configured, running: state === 'running' });
41
- }
42
- if (!rows.length) return;
43
-
44
- const width = Math.max(...rows.map((r) => r.s.label.length));
45
- const line = chalk.grey('─'.repeat(48));
46
- console.log(chalk.bold('Services'));
47
- console.log(line);
48
- for (const { s, configured, running } of rows) {
49
- const label = chalk.bold(s.label.padEnd(width));
50
- if (running) {
51
- console.log(`${chalk.greenBright('●')} ${label} ${chalk.greenBright('running')}`);
52
- for (const [k, v] of Object.entries(s.info(config, root))) {
53
- // Une liste (comptes de test) : une ligne par entrée, alignées
54
- const lines = Array.isArray(v) ? v : [v];
55
- lines.forEach((l, i) => console.log(` ${chalk.grey((i ? '' : k).padEnd(16))} ${l}`));
56
- }
57
- } else if (configured) {
58
- const how = s.optional ? `poad run ${s.cmd}` : 'poad stop && poad start';
59
- console.log(`${chalk.yellowBright('○')} ${label} ${chalk.yellowBright('stopped')} ${chalk.grey(`(${how})`)}`);
60
- } else {
61
- console.log(`${chalk.grey('·')} ${chalk.grey(s.label.padEnd(width))} ${chalk.grey(`available: poad run ${s.cmd}`)}`);
62
- }
63
- }
64
- console.log(line);
65
- const stopped = rows.filter((r) => r.s.optional && r.configured && !r.running).length;
66
- if (stopped) console.log(chalk.grey(` "poad run --all" starts every configured service.`));
67
- console.log(' ');
15
+ await require('../utils/report').printReport(root, config);
68
16
  };
package/project/kc.js CHANGED
@@ -13,7 +13,7 @@ module.exports = async (args = {}) => {
13
13
 
14
14
  const root = findPoadDir(process.cwd());
15
15
  if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
16
- const config = toml.parse(fs.readFileSync(root, 'utf-8'));
16
+ const config = require('../utils/config').readConfig(root);
17
17
  console.log(' ');
18
18
 
19
19
  if (args.export) {
@@ -0,0 +1,16 @@
1
+ // poad migrate : applique les migrations en attente de poad/migrations
2
+ module.exports = async () => {
3
+ const chalk = require('chalk-v2');
4
+ const { findPoadDir } = require('../utils/findpoad');
5
+ const { isDockerExist } = require('../utils/docker');
6
+ const { readConfig } = require('../utils/config');
7
+
8
+ const root = findPoadDir(process.cwd());
9
+ if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
10
+ const config = readConfig(root);
11
+ if (!(await isDockerExist(config.project_uuid))) {
12
+ return console.log(chalk.redBright('The project is not started: run "poad start" (it applies pending migrations too).'));
13
+ }
14
+ const ok = await require('../utils/migrate-run')(root, config);
15
+ if (!ok) process.exitCode = 1;
16
+ };
@@ -0,0 +1,62 @@
1
+ // poad migration new <nom> crée poad/migrations/<horodatage>_<nom>.sql
2
+ // poad migration list migrations appliquées et en attente
3
+ // (poad migrate applique celles en attente)
4
+ module.exports = async (args = {}) => {
5
+ const chalk = require('chalk-v2');
6
+ const path = require('path');
7
+ const { findPoadDir } = require('../utils/findpoad');
8
+ const { isDockerExist } = require('../utils/docker');
9
+ const { readConfig } = require('../utils/config');
10
+ const migrations = require('../utils/migrations');
11
+
12
+ const root = findPoadDir(process.cwd());
13
+ if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
14
+ const words = Object.keys(args);
15
+ const rel = (p) => path.relative(process.cwd(), p);
16
+
17
+ if (words[0] === 'new') {
18
+ try {
19
+ const file = migrations.create(root, words.slice(1).join('_'));
20
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(rel(file))}`);
21
+ console.log(chalk.grey(' Write your SQL in it, then "poad migrate".'));
22
+ } catch (err) {
23
+ console.log(chalk.redBright(err.message));
24
+ }
25
+ return;
26
+ }
27
+
28
+ if (words[0] === 'list' || !words.length) {
29
+ const config = readConfig(root);
30
+ const { list, ignored } = migrations.files(root);
31
+ console.log(`${chalk.bold('Migrations')} ${chalk.grey(rel(migrations.dir(root)))}`);
32
+ console.log(' ');
33
+ if (!(await isDockerExist(config.project_uuid))) {
34
+ for (const m of list) console.log(` ${chalk.grey('?')} ${m.file}`);
35
+ if (!list.length) console.log(chalk.grey(' None yet: "poad migration new <name>".'));
36
+ console.log(' ');
37
+ return console.log(chalk.grey(' The project is not started: applied state unknown.'));
38
+ }
39
+ let client;
40
+ try {
41
+ client = await migrations.connect(config);
42
+ const state = await migrations.status(root, client);
43
+ for (const m of state.list) {
44
+ const mark = m.changed ? chalk.yellowBright('!') : m.applied ? chalk.greenBright('✔') : chalk.cyanBright('○');
45
+ const note = m.changed ? chalk.yellowBright(' changed after it was applied') : m.applied ? chalk.grey(` ${new Date(m.applied).toISOString().slice(0, 16).replace('T', ' ')}`) : chalk.cyanBright(' pending');
46
+ console.log(` ${mark} ${m.file}${note}`);
47
+ }
48
+ for (const r of state.missing) console.log(` ${chalk.yellowBright('!')} ${r.version}_${r.name}.sql${chalk.yellowBright(' applied, file missing')}`);
49
+ if (!state.list.length && !state.missing.length) console.log(chalk.grey(' None yet: "poad migration new <name>".'));
50
+ for (const f of ignored) console.log(chalk.grey(` ${f} ignored (expected <YYYYMMDDHHMMSS>_<name>.sql)`));
51
+ console.log(' ');
52
+ if (state.pending.length) console.log(chalk.cyanBright(` ${state.pending.length} pending: "poad migrate".`));
53
+ } catch (err) {
54
+ console.log(chalk.redBright(`Cannot read the migration state: ${err.message}`));
55
+ } finally {
56
+ if (client) await client.end().catch(() => {});
57
+ }
58
+ return;
59
+ }
60
+
61
+ console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad migration new <name>')} | ${chalk.cyanBright('poad migration list')} | ${chalk.cyanBright('poad migrate')}`);
62
+ };
@@ -0,0 +1,241 @@
1
+ // poad setup : ce que "poad start" lance avec le projet
2
+ //
3
+ // poad setup interactif (terminal) : e-mails, services, migrations
4
+ // poad setup kc=on valkey=off non interactif : ne change que ce qui est cité
5
+ // poad setup --all | --none tous les services optionnels en autostart, ou aucun
6
+ // poad setup mail=smtp smtp.host=smtp.example.com smtp.port=587 smtp.user=apikey smtp.pass=…
7
+ // poad setup mail=mailpit revient à Mailpit (e-mails capturés en local)
8
+ // poad setup migrate=off migrations appliquées à la main (poad migrate)
9
+ // poad setup --list affiche les réglages sans rien changer
10
+ //
11
+ // Tout va dans poad/config.toml, sauf le mot de passe SMTP (poad/secrets.toml).
12
+ // Désactiver un service ne retire que son autostart : port, données et jeu de
13
+ // test restent, le réactiver ne coûte rien.
14
+ module.exports = async (args = {}) => {
15
+ const chalk = require('chalk-v2');
16
+ const Docker = require('dockerode');
17
+ const docker = new Docker();
18
+ const { findPoadDir } = require('../utils/findpoad');
19
+ const { isDockerExist } = require('../utils/docker');
20
+ const { findFreePorts } = require('../utils/ports');
21
+ const { setKeys, removeSection } = require('../utils/tomlfile');
22
+ const { loadConfig, readConfig, writeSmtpPass } = require('../utils/config');
23
+ const { SERVICES, containerState } = require('../utils/services');
24
+ const mail = require('../utils/mail');
25
+ const migrations = require('../utils/migrations');
26
+
27
+ const root = findPoadDir(process.cwd());
28
+ if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
29
+ let config = readConfig(root);
30
+ const optional = SERVICES.filter((s) => s.optional);
31
+ console.log(' ');
32
+
33
+ // ------------------------------------------------------------ lecture
34
+ const ALIASES = { kc: 'keycloak', keycloak: 'keycloak', valkey: 'valkey', redis: 'valkey' };
35
+ const ON = new Set(['on', 'true', 'yes', 'oui', '1', 'auto']);
36
+ const OFF = new Set(['off', 'false', 'no', 'non', '0', 'manual']);
37
+ const flag = (v) => {
38
+ const t = String(v).toLowerCase();
39
+ if (ON.has(t)) return true;
40
+ if (OFF.has(t)) return false;
41
+ return null;
42
+ };
43
+ const has = (k) => args[k] || args[`--${k}`];
44
+
45
+ const current = () => ({
46
+ mail: mail.usesMailpit(config) ? 'mailpit' : 'smtp',
47
+ smtp: { ...(config.smtp || {}) },
48
+ services: Object.fromEntries(optional.map((s) => [s.id, s.configured(config) && s.autostart(config)])),
49
+ migrate: migrations.autoMigrate(config),
50
+ });
51
+
52
+ const summary = () => {
53
+ const c = current();
54
+ const pad = (s) => chalk.bold(s.padEnd(11));
55
+ console.log(chalk.bold('Started with "poad start"'));
56
+ console.log(chalk.grey('─'.repeat(48)));
57
+ console.log(` ${pad('E-mails')} ${c.mail === 'mailpit' ? `Mailpit ${chalk.grey(`(local, http://localhost:${mail.mailPort(config)})`)}` : `SMTP ${c.smtp.host}:${c.smtp.port || 587}${c.smtp.user ? chalk.grey(` (${c.smtp.user})`) : ''}`}`);
58
+ for (const s of optional) {
59
+ const state = c.services[s.id]
60
+ ? chalk.greenBright('auto')
61
+ : s.configured(config)
62
+ ? `${chalk.yellowBright('manual')} ${chalk.grey(`(poad run ${s.cmd})`)}`
63
+ : chalk.grey('off');
64
+ console.log(` ${pad(s.label)} ${state}`);
65
+ }
66
+ console.log(` ${pad('Migrations')} ${c.migrate ? chalk.greenBright('applied at start') : `${chalk.yellowBright('manual')} ${chalk.grey('(poad migrate)')}`}`);
67
+ console.log(chalk.grey('─'.repeat(48)));
68
+ };
69
+
70
+ if (has('list')) {
71
+ summary();
72
+ return console.log(' ');
73
+ }
74
+
75
+ // ------------------------------------------------------------ souhaits
76
+ const before = current();
77
+ const wasConfigured = Object.fromEntries(optional.map((s) => [s.id, s.configured(config)]));
78
+ const wish = { services: {} };
79
+ const keys = Object.keys(args).filter((k) => !/^-/.test(k));
80
+
81
+ if (has('all')) for (const s of optional) wish.services[s.id] = true;
82
+ if (has('none')) for (const s of optional) wish.services[s.id] = false;
83
+ for (const k of keys) {
84
+ const v = args[k];
85
+ if (ALIASES[k]) {
86
+ const f = flag(v);
87
+ if (f === null) return console.log(chalk.redBright(`${k}=${v}: expected on or off.`));
88
+ wish.services[ALIASES[k]] = f;
89
+ } else if (k === 'mail') {
90
+ if (!['mailpit', 'smtp'].includes(String(v))) return console.log(chalk.redBright('mail=mailpit or mail=smtp.'));
91
+ wish.mail = String(v);
92
+ } else if (k.startsWith('smtp.')) {
93
+ (wish.smtp ??= {})[k.slice(5)] = v;
94
+ } else if (k === 'migrate' || k === 'migrations') {
95
+ const f = flag(v);
96
+ if (f === null) return console.log(chalk.redBright(`${k}=${v}: expected on or off.`));
97
+ wish.migrate = f;
98
+ } else if (!['all', 'none', 'list'].includes(k)) {
99
+ return console.log(chalk.redBright(`Unknown setting "${k}". See: poad setup --help`));
100
+ }
101
+ }
102
+ if (wish.smtp && !wish.mail) wish.mail = 'smtp';
103
+
104
+ const interactive = !keys.length && !has('all') && !has('none');
105
+ if (interactive) {
106
+ if (!process.stdin.isTTY) {
107
+ summary();
108
+ console.log(chalk.grey(' Not a terminal: pass settings, e.g. "poad setup kc=on valkey=off", "--all", "--none", "mail=smtp smtp.host=…".'));
109
+ return console.log(' ');
110
+ }
111
+ const { select, checkbox, input, password, confirm } = require('@inquirer/prompts');
112
+ try {
113
+ console.log(chalk.bold('Services started with "poad start"'));
114
+ console.log(' ');
115
+ wish.mail = await select({
116
+ message: 'E-mails (sign up, magic links, password reset)',
117
+ default: before.mail,
118
+ choices: [
119
+ { name: 'Mailpit: captured locally, read them in the browser', value: 'mailpit' },
120
+ { name: 'SMTP server: real delivery', value: 'smtp' },
121
+ ],
122
+ });
123
+ if (wish.mail === 'smtp') {
124
+ const s = before.smtp;
125
+ wish.smtp = {};
126
+ wish.smtp.host = await input({ message: 'SMTP host', default: s.host, required: true });
127
+ wish.smtp.port = Number(await input({ message: 'SMTP port', default: String(s.port || 587), validate: (v) => /^\d+$/.test(v) || 'a port number' }));
128
+ wish.smtp.user = await input({ message: 'SMTP user (empty: none)', default: s.user || '' });
129
+ const pass = await password({ message: s.pass ? 'SMTP password (empty: keep the current one)' : 'SMTP password (empty: none)', mask: '*' });
130
+ if (pass) wish.smtp.pass = pass;
131
+ wish.smtp.sender = await input({ message: 'Sender address', default: s.sender || 'no-reply@poad.local' });
132
+ wish.smtp.secure = await confirm({ message: 'TLS from the start (port 465)?', default: Boolean(s.secure) || wish.smtp.port === 465 });
133
+ }
134
+ const picked = await checkbox({
135
+ message: 'Started with the project (space to toggle, enter to confirm)',
136
+ choices: [
137
+ ...optional.map((s) => ({
138
+ name: s.id === 'keycloak' ? 'Keycloak: OIDC provider with test users (poad/keycloak.json)' : 'Valkey: Redis compatible cache (REDIS_URL of the engine)',
139
+ value: s.id,
140
+ checked: before.services[s.id],
141
+ })),
142
+ { name: 'Migrations: apply poad/migrations at start', value: '_migrate', checked: before.migrate },
143
+ ],
144
+ });
145
+ for (const s of optional) wish.services[s.id] = picked.includes(s.id);
146
+ wish.migrate = picked.includes('_migrate');
147
+ console.log(' ');
148
+ } catch (err) {
149
+ // Ctrl+C dans un prompt
150
+ if (err && err.name === 'ExitPromptError') return console.log(chalk.grey(' Nothing changed.'));
151
+ throw err;
152
+ }
153
+ }
154
+
155
+ // ------------------------------------------------------------ écriture
156
+ const changes = [];
157
+ for (const [id, on] of Object.entries(wish.services)) {
158
+ const s = optional.find((x) => x.id === id);
159
+ if (on === before.services[id]) continue;
160
+ if (on && !s.configured(config)) {
161
+ const [port] = await findFreePorts(1);
162
+ s.savePort(root, port);
163
+ }
164
+ if (on || s.configured(config)) setKeys(root, s.section, { autostart: on });
165
+ changes.push(`${s.label}: ${on ? 'started with the project' : 'manual (poad run ' + s.cmd + ')'}`);
166
+ config = loadConfig(root);
167
+ }
168
+
169
+ let mailChanged = false;
170
+ if (wish.mail === 'smtp') {
171
+ const next = { ...before.smtp, ...(wish.smtp || {}) };
172
+ if (!next.host) return console.log(chalk.redBright('mail=smtp needs smtp.host=…'));
173
+ const { pass, ...visible } = next;
174
+ const fields = {
175
+ host: String(visible.host),
176
+ port: Number(visible.port || 587),
177
+ user: visible.user ? String(visible.user) : null,
178
+ sender: visible.sender ? String(visible.sender) : null,
179
+ secure: visible.secure === true || visible.secure === 'true' ? true : null,
180
+ };
181
+ setKeys(root, 'smtp', fields);
182
+ if (wish.smtp && wish.smtp.pass !== undefined) writeSmtpPass(root, String(wish.smtp.pass));
183
+ const was = before.mail === 'smtp' ? JSON.stringify({ ...before.smtp, pass: undefined }) : '';
184
+ mailChanged = before.mail !== 'smtp' || was !== JSON.stringify({ ...next, pass: undefined }) || (wish.smtp && wish.smtp.pass !== undefined);
185
+ if (mailChanged) changes.push(`E-mails: SMTP ${fields.host}:${fields.port}`);
186
+ } else if (wish.mail === 'mailpit' && before.mail === 'smtp') {
187
+ removeSection(root, 'smtp');
188
+ writeSmtpPass(root, null);
189
+ if (!mail.mailPort(loadConfig(root))) {
190
+ const [port] = await findFreePorts(1);
191
+ setKeys(root, 'mail', { port });
192
+ }
193
+ mailChanged = true;
194
+ changes.push('E-mails: Mailpit');
195
+ }
196
+
197
+ if (wish.migrate !== undefined && wish.migrate !== before.migrate) {
198
+ setKeys(root, 'db', { auto_migrate: wish.migrate ? null : false });
199
+ changes.push(`Migrations: ${wish.migrate ? 'applied at start' : 'manual (poad migrate)'}`);
200
+ }
201
+
202
+ config = loadConfig(root);
203
+ if (!changes.length) {
204
+ summary();
205
+ console.log(chalk.grey(' Nothing changed.'));
206
+ return console.log(' ');
207
+ }
208
+ for (const c of changes) console.log(`${chalk.greenBright('✔')} ${c}`);
209
+ console.log(' ');
210
+ summary();
211
+
212
+ // ------------------------------------------------------------ projet lancé
213
+ if (await isDockerExist(config.project_uuid)) {
214
+ // REDIS_URL n'est donné à l'engine que si Valkey était configuré à son démarrage
215
+ const valkeyNew = wish.services.valkey === true && !wasConfigured.valkey;
216
+ if (mailChanged || valkeyNew) {
217
+ console.log(chalk.yellowBright(' The engine reads its mail and Valkey settings at start: "poad stop" then "poad start" to apply them.'));
218
+ }
219
+ const missing = [];
220
+ for (const s of optional) {
221
+ if (wish.services[s.id] && (await containerState(docker, s.container(config))) !== 'running') missing.push(s);
222
+ }
223
+ if (missing.length) {
224
+ let go = !interactive;
225
+ if (interactive) {
226
+ const { confirm } = require('@inquirer/prompts');
227
+ go = await confirm({ message: `Start ${missing.map((s) => s.label).join(' and ')} now?`, default: true }).catch(() => false);
228
+ }
229
+ if (go) {
230
+ await require('../global/run')({ services: missing.map((s) => s.id), quiet: true });
231
+ console.log(' ');
232
+ await require('../utils/report').printServices(root, loadConfig(root));
233
+ return;
234
+ }
235
+ console.log(chalk.grey(' Applied at the next "poad start" (or "poad run --all").'));
236
+ }
237
+ } else {
238
+ console.log(chalk.grey(' Applied at the next "poad start".'));
239
+ }
240
+ console.log(' ');
241
+ };