poad 2.59.0 → 2.61.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/start.js CHANGED
@@ -28,6 +28,12 @@ module.exports = async (args = {}) => {
28
28
  const gateway = require('../utils/gateway');
29
29
  const root = findPoadDir(process.cwd());
30
30
  if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
31
+ // Une seule commande à la fois sur les conteneurs du projet (utils/project-lock.js)
32
+ const lock = require('../utils/project-lock').acquire(root, 'start');
33
+ if (!lock.ok) {
34
+ process.exitCode = 1;
35
+ return console.log(chalk.redBright(require('../utils/project-lock').busyMessage(lock.held)));
36
+ }
31
37
  const config = require('../utils/config').readConfig(root);
32
38
  const containerName = config.project_uuid;
33
39
  // Registre des projets de la machine : dernière utilisation (inscrit s'il n'y était pas)
package/global/stop.js CHANGED
@@ -16,12 +16,34 @@ module.exports = async (args) => {
16
16
  const runner = require('../utils/runner');
17
17
  const root = findPoadDir(process.cwd());
18
18
  if (!root) return console.log(require('chalk-v2').redBright('You are not in a poad project directory.'));
19
+ // Une seule commande à la fois sur les conteneurs du projet (utils/project-lock.js)
20
+ const lock = require('../utils/project-lock').acquire(root, 'stop');
21
+ if (!lock.ok) {
22
+ process.exitCode = 1;
23
+ return console.log(require('chalk-v2').redBright(require('../utils/project-lock').busyMessage(lock.held)));
24
+ }
19
25
  const config = require('../utils/config').readConfig(root);
20
26
  const containerName = config.project_uuid;
21
27
  const ora = require('ora');
22
28
  const chalk = require('chalk-v2');
23
29
  console.log(' ');
24
30
 
31
+ // Docker qui ne répond pas n'est pas un projet arrêté : le dire, code 1
32
+ try {
33
+ await docker.ping();
34
+ } catch (err) {
35
+ process.exitCode = 1;
36
+ return console.log(chalk.redBright(`Docker does not answer (${(err && err.code) || (err && err.message) || err}): start Docker, then run "poad stop" again.`));
37
+ }
38
+
39
+ // Un conteneur déjà arrêté (304) ou déjà retiré (404) entre la vérification et l'arrêt : c'est fait
40
+ const gone = (err) => Boolean(err) && (err.statusCode === 304 || err.statusCode === 404);
41
+ /** Échec réel d'un arrêt : la cause, et un code de sortie non nul */
42
+ const failed = (progress, what, err) => {
43
+ process.exitCode = 1;
44
+ progress.fail(chalk.redBright(`Failed to stop ${what}: ${(err && (err.json && err.json.message)) || (err && err.message) || err}`));
45
+ };
46
+
25
47
  const stopKeycloak = async () => {
26
48
  const shared = require('../utils/keycloak-shared');
27
49
  if (shared.isShared(config)) {
@@ -44,8 +66,9 @@ module.exports = async (args) => {
44
66
  try {
45
67
  await docker.getContainer(name).remove({ force: true });
46
68
  progress.succeed(chalk.bold('Keycloak stopped'));
47
- } catch {
48
- progress.fail('Error: Failed to stop Keycloak');
69
+ } catch (err) {
70
+ if (gone(err)) progress.succeed(chalk.bold('Keycloak stopped'));
71
+ else failed(progress, 'Keycloak', err);
49
72
  }
50
73
  return true;
51
74
  };
@@ -57,8 +80,9 @@ module.exports = async (args) => {
57
80
  try {
58
81
  await docker.getContainer(name).stop();
59
82
  progress.succeed(chalk.bold('Valkey stopped'));
60
- } catch {
61
- progress.fail('Error: Failed to stop Valkey');
83
+ } catch (err) {
84
+ if (gone(err)) progress.succeed(chalk.bold('Valkey stopped'));
85
+ else failed(progress, 'Valkey', err);
62
86
  }
63
87
  return true;
64
88
  };
@@ -73,43 +97,52 @@ module.exports = async (args) => {
73
97
  await docker.getContainer(name).stop();
74
98
  for (let i = 0; i < 20 && (await isDockerExist(name)); i++) await new Promise((r) => setTimeout(r, 500));
75
99
  progress.succeed(chalk.bold('Flows runner stopped'));
76
- } catch {
77
- progress.fail('Error: Failed to stop the flows runner');
100
+ } catch (err) {
101
+ if (gone(err)) progress.succeed(chalk.bold('Flows runner stopped'));
102
+ else failed(progress, 'the flows runner', err);
78
103
  }
79
104
  return true;
80
105
  };
81
106
 
82
107
  if (runner.wanted(args)) {
83
- if (!(await stopRunner())) console.log(chalk.redBright('The flows runner is not running'));
108
+ if (!(await stopRunner())) console.log(chalk.grey('The flows runner is not running: nothing to stop.'));
84
109
  return;
85
110
  }
86
111
  if (kc.wanted(args)) {
87
- if (!(await stopKeycloak())) console.log(chalk.redBright('Keycloak is not running'));
112
+ if (!(await stopKeycloak())) console.log(chalk.grey('Keycloak is not running: nothing to stop.'));
88
113
  return;
89
114
  }
90
115
  if (valkey.wanted(args)) {
91
- if (!(await stopValkey())) console.log(chalk.redBright('Valkey is not running'));
116
+ if (!(await stopValkey())) console.log(chalk.grey('Valkey is not running: nothing to stop.'));
92
117
  return;
93
118
  }
94
119
 
95
120
  // L'exécuteur d'abord : il rend compte à l'engine, par Valkey et par HTTP
96
- await stopRunner();
97
- await stopKeycloak();
98
- await stopValkey();
121
+ const runnerStopped = await stopRunner();
122
+ const kcStopped = await stopKeycloak();
123
+ const valkeyStopped = await stopValkey();
99
124
  const engine = await isDockerExist(containerName);
100
125
  if (engine) {
101
- const progress = ora('Stopping container').start();
102
- try {
103
- await docker.getContainer(containerName).stop();
126
+ const progress = ora('Stopping the engine').start();
127
+ const waitGone = async () => {
104
128
  // AutoRemove : le conteneur disparaît juste après l'arrêt ; le réseau
105
129
  // ne peut être supprimé qu'ensuite
106
130
  for (let i = 0; i < 20 && (await isDockerExist(containerName)); i++) await new Promise((r) => setTimeout(r, 500));
107
- progress.succeed(chalk.bold('Container stopped successfully'));
108
- } catch {
109
- progress.fail('Error: Failed to stop container');
131
+ };
132
+ try {
133
+ await docker.getContainer(containerName).stop();
134
+ await waitGone();
135
+ progress.succeed(chalk.bold('Engine stopped'));
136
+ } catch (err) {
137
+ if (gone(err)) {
138
+ await waitGone();
139
+ progress.succeed(chalk.bold('Engine stopped'));
140
+ } else failed(progress, 'the engine', err);
110
141
  }
111
142
  }
112
143
  const mailpit = await mail.stopMailpit(docker, config);
144
+ if (mailpit) console.log(`${chalk.greenBright('✔')} ${chalk.bold('Mailpit stopped')}`);
113
145
  await mail.removeNetwork(docker, config);
114
- if (!engine && !mailpit) console.log(chalk.redBright('Container not found'));
146
+ // Rien ne tournait : le projet est déjà arrêté, ce n'est pas une erreur
147
+ if (!engine && !mailpit && !runnerStopped && !kcStopped && !valkeyStopped) console.log(chalk.grey('The project is already stopped: nothing to stop.'));
115
148
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.59.0",
3
+ "version": "2.61.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.2.0",
6
6
  "main": "index.js",
package/poad.js CHANGED
@@ -304,8 +304,31 @@ const helpGuard = () => {
304
304
  return true;
305
305
  };
306
306
 
307
+ // Version : `poad --version` ou `poad -v` (premier mot seulement) affiche la
308
+ // version du CLI et s'arrête, sans vérification sur npm ni commande.
309
+ const VERSION_FLAGS = ['--version', '-v'];
310
+ const versionGuard = () => {
311
+ if (!VERSION_FLAGS.includes(process.argv[2])) return false;
312
+ console.log(package.version);
313
+ return true;
314
+ };
315
+
316
+ // Dernier filet : une erreur que la commande n'a pas traitée devient une phrase
317
+ // (la trace complète avec POAD_DEBUG=1), jamais une trace Node brute.
318
+ const fatal = (err) => {
319
+ // Ctrl-C dans une question : pas une erreur
320
+ if (err && err.name === 'ExitPromptError') process.exit(130);
321
+ console.error(chalk.redBright(`poad: unexpected error: ${(err && err.message) || err}`));
322
+ if (process.env.POAD_DEBUG) console.error((err && err.stack) || err);
323
+ else console.error(chalk.grey(' POAD_DEBUG=1 poad … shows the details.'));
324
+ process.exit(1);
325
+ };
326
+ process.on('unhandledRejection', fatal);
327
+ process.on('uncaughtException', fatal);
328
+
307
329
  // Main function.
308
330
  const main = async () => {
331
+ if (versionGuard()) return;
309
332
  if (helpGuard()) return;
310
333
  let version = await checkVersion();
311
334
  const current_version = require(__dirname + '/package.json').version;
package/project/cli.js CHANGED
@@ -39,6 +39,13 @@ module.exports = {
39
39
  load: 'Same as poad ref load',
40
40
  rm: 'Same as poad ref rm',
41
41
  },
42
+ storage: {
43
+ description: 'Files of the project storage, local engine or poad.io (--env <name>): ls, cp (disk ↔ storage, storage → storage), mv, rm; a storage path is bucket/path (poad:bucket/path for cp)',
44
+ ls: 'Buckets, or the files and folders of a folder: ls [bucket[/folder]] [-r] [--json]',
45
+ cp: 'Copy files, -r for a folder: cp ./a.png poad:images/ | cp poad:images/a.png ./ | cp -r poad:images/2024 poad:archives/',
46
+ mv: 'Move or rename inside the storage (copy, then delete the source): mv <bucket/path> <bucket/path> [-r]',
47
+ rm: 'Delete files, or a whole folder with -r (asks first, --yes outside a terminal): rm <bucket/path…> [-r] [--yes]',
48
+ },
42
49
  link: 'Link this project to a poad.io project: [cloud] project = "<id>" in poad/config.toml (no secret): link [<id>]',
43
50
  unlink: 'Remove the link to poad.io from poad/config.toml (nothing changes on poad.io)',
44
51
  env: {
@@ -61,7 +68,7 @@ module.exports = {
61
68
  migration: 'Database migrations: migration new <name>, migration list',
62
69
  functions: 'Functions of the project (JS/TS, served on /functions/v1/<name>): new, list, types',
63
70
  function: 'Alias of poad functions',
64
- flows: 'Flows of the project (automations in poad/flows/<name>.json, engine 0.18.0+, needs Valkey): new, list, run, runs, show, cancel',
71
+ flows: 'Flows of the project (automations in poad/flows/<name>.json, engine 0.18.0+, needs Valkey): new, list, run, runs, show, cancel; --env <name> for poad.io',
65
72
  flow: 'Alias of poad flows',
66
73
  /* status: `[AI] Vérification du statut de l'environnement`,
67
74
  gen: {
@@ -3,6 +3,9 @@
3
3
  // poad db diff <nom> les écrit dans poad/migrations/<horodatage>_<nom>.sql
4
4
  // (déjà appliqués : ils ne sont pas rejoués)
5
5
  // poad db diff --discard les oublie (ils restent dans la base)
6
+ //
7
+ // La liste commence par un résumé, un objet par ligne : + ajouté, ~ modifié,
8
+ // - supprimé, · sans effet (créé puis supprimé…), puis le SQL de chaque changement.
6
9
  module.exports = async (args = {}) => {
7
10
  const chalk = require('chalk-v2');
8
11
  const path = require('path');
@@ -30,7 +33,7 @@ module.exports = async (args = {}) => {
30
33
  process.exitCode = 1;
31
34
  return console.log(chalk.yellowBright(`The change journal needs engine 0.11.0 or later (this project: ${config.engine}): "poad upgrade".`));
32
35
  }
33
- if (flag('json')) return console.log(JSON.stringify(c, null, 2));
36
+ if (flag('json')) return console.log(JSON.stringify({ ...c, summary: summarize(c) }, null, 2));
34
37
  if (!c.entries.length) {
35
38
  if (c.drift) {
36
39
  process.exitCode = 1;
@@ -47,6 +50,10 @@ module.exports = async (args = {}) => {
47
50
  const byId = new Map(c.entries.map((e) => [e.id, e]));
48
51
  console.log(chalk.bold(`${c.units.length} structure change(s) not in a migration`));
49
52
  console.log(' ');
53
+ for (const line of summaryLines(summarize(c), chalk)) console.log(line);
54
+ console.log(' ');
55
+ console.log(chalk.bold('SQL'));
56
+ console.log(' ');
50
57
  for (const u of c.units) {
51
58
  const e = byId.get(u.keep.length ? u.keep[u.keep.length - 1] : u.ids[u.ids.length - 1]);
52
59
  const when = new Date(e.at).toLocaleString();
@@ -65,6 +72,7 @@ module.exports = async (args = {}) => {
65
72
  }
66
73
  const file = await migrations.saveChanges(root, client, name, c.sql, c.upTo);
67
74
  console.log(`${chalk.greenBright('✔')} ${chalk.bold(path.relative(process.cwd(), file))} ${chalk.grey(`(${c.entries.length} change(s), already applied here)`)}`);
75
+ for (const line of summaryLines(summarize(c).filter((i) => i.change !== 'none'), chalk)) console.log(line);
68
76
  console.log(chalk.grey(' Review it, then commit it with your branch.'));
69
77
  } catch (err) {
70
78
  process.exitCode = 1;
@@ -73,3 +81,93 @@ module.exports = async (args = {}) => {
73
81
  await client.end().catch(() => {});
74
82
  }
75
83
  };
84
+
85
+ // ------------------------------------------------------------------ résumé
86
+ // Les entrées du journal (poad_migrations.journal) portent les commandes
87
+ // (« CREATE TABLE », « DROP INDEX », « GRANT »…) et les objets touchés, sans
88
+ // dire quel objet va avec quelle commande : l'objet principal est celui que
89
+ // l'instruction nomme, les autres (séquence, clé primaire…) suivent.
90
+
91
+ // Ordre de préférence pour l'objet principal d'une instruction qui en touche plusieurs
92
+ const KINDS = ['schema', 'extension', 'table', 'view', 'materialized view', 'foreign table', 'type', 'domain', 'function', 'procedure', 'aggregate', 'trigger', 'policy', 'publication', 'index', 'sequence'];
93
+
94
+ /** Type d'objet d'une commande : « CREATE TABLE » → table ; GRANT, COMMENT… → null. Pure. */
95
+ const kindOf = (command) => {
96
+ const m = /^(?:CREATE|ALTER|DROP)\s+(.+)$/i.exec(String(command || '').trim());
97
+ return m ? m[1].toLowerCase() : null;
98
+ };
99
+
100
+ const escapeRe = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
101
+ /** Dernier élément d'une identité (public.todos → todos ; « p on public.t » → p). Pure. */
102
+ const shortName = (identity) => {
103
+ const head = String(identity).split(' on ')[0];
104
+ const parts = head.match(/"(?:[^"]|"")+"|[^.]+/g) || [head];
105
+ return parts[parts.length - 1].replace(/^"|"$/g, '').replace(/\(.*$/, '');
106
+ };
107
+
108
+ /** Détail d'un ALTER TABLE : colonne ajoutée, supprimée, modifiée, renommage, RLS. Pure. */
109
+ const alterDetail = (statement) => {
110
+ const st = String(statement).replace(/\s+/g, ' ');
111
+ const id = '("(?:[^"]|"")+"|[A-Za-z_][\\w$]*)';
112
+ const unq = (t) => t.replace(/^"|"$/g, '');
113
+ let m;
114
+ if ((m = new RegExp(`\\brename\\s+(?:column\\s+)?${id}\\s+to\\s+${id}`, 'i').exec(st))) return `column ${unq(m[1])} renamed to ${unq(m[2])}`;
115
+ if ((m = new RegExp(`\\brename\\s+to\\s+${id}`, 'i').exec(st))) return `renamed to ${unq(m[1])}`;
116
+ if ((m = new RegExp(`\\badd\\s+(?:column\\s+)?(?:if\\s+not\\s+exists\\s+)?${id}`, 'i').exec(st)) && !/^(constraint|primary|unique|foreign|check|exclude)$/i.test(m[1])) return `column ${unq(m[1])} added`;
117
+ if ((m = new RegExp(`\\badd\\s+constraint\\s+${id}`, 'i').exec(st))) return `constraint ${unq(m[1])} added`;
118
+ if ((m = new RegExp(`\\bdrop\\s+constraint\\s+(?:if\\s+exists\\s+)?${id}`, 'i').exec(st))) return `constraint ${unq(m[1])} removed`;
119
+ if ((m = new RegExp(`\\bdrop\\s+(?:column\\s+)?(?:if\\s+exists\\s+)?${id}`, 'i').exec(st))) return `column ${unq(m[1])} removed`;
120
+ if ((m = new RegExp(`\\balter\\s+(?:column\\s+)?${id}\\s+(?:set|drop|type|add)\\b`, 'i').exec(st))) return `column ${unq(m[1])} changed`;
121
+ if ((m = /\b(enable|disable)\s+row\s+level\s+security/i.exec(st))) return `row level security ${m[1].toLowerCase()}d`;
122
+ return null;
123
+ };
124
+
125
+ /**
126
+ * Un changement du journal, lisible : { change: added|changed|removed, kind, object, others, detail }. Pure.
127
+ */
128
+ const describe = (entry) => {
129
+ const commands = (entry.commands || []).map(String);
130
+ const objects = (entry.objects || []).filter(Boolean).map(String);
131
+ const statement = String(entry.statement || '');
132
+ const rank = (k) => (KINDS.includes(k) ? KINDS.indexOf(k) : KINDS.length);
133
+ const main = [...commands].sort((a, b) => rank(kindOf(a)) - rank(kindOf(b)))[0] || '';
134
+ const verb = main.split(/\s+/)[0].toUpperCase();
135
+ const kind = kindOf(main) || (verb === 'GRANT' || verb === 'REVOKE' ? 'privileges' : verb === 'COMMENT' ? 'comment' : main.toLowerCase() || 'object');
136
+ // L'objet que l'instruction nomme ; à défaut, le premier
137
+ const named = objects.find((o) => new RegExp(`(^|[^\\w$])"?${escapeRe(shortName(o))}"?($|[^\\w$])`, 'i').test(statement));
138
+ const object = named || objects[0] || '';
139
+ const change = verb === 'DROP' ? 'removed' : verb === 'CREATE' && !/^\s*create\s+or\s+replace\b/i.test(statement) ? 'added' : 'changed';
140
+ let detail = null;
141
+ if (main.toUpperCase() === 'ALTER TABLE') detail = alterDetail(statement);
142
+ else if (verb === 'GRANT' || verb === 'REVOKE') detail = verb === 'GRANT' ? 'granted' : 'revoked';
143
+ else if (/^\s*create\s+or\s+replace\b/i.test(statement)) detail = 'created or replaced';
144
+ return { change, kind, object, others: objects.filter((o) => o !== object), detail };
145
+ };
146
+
147
+ /** Résumé de changes() : un élément par changement gardé, et les groupes sans effet. Pure. */
148
+ const summarize = (c) => {
149
+ const byId = new Map((c.entries || []).map((e) => [e.id, e]));
150
+ const out = [];
151
+ for (const u of c.units || []) {
152
+ if (u.effect === 'none') {
153
+ out.push({ change: 'none', kind: u.kind, object: u.target, others: [], detail: `${u.ids.length} changes, no net effect` });
154
+ continue;
155
+ }
156
+ for (const id of u.keep) if (byId.has(id)) out.push(describe(byId.get(id)));
157
+ }
158
+ return out;
159
+ };
160
+
161
+ /** Lignes du résumé, alignées. Pure (au style près). */
162
+ const summaryLines = (items, chalk) => {
163
+ const SIGN = { added: ['+', 'greenBright'], changed: ['~', 'yellowBright'], removed: ['-', 'redBright'], none: ['·', 'grey'] };
164
+ const kw = Math.max(0, ...items.map((i) => i.kind.length));
165
+ const ow = Math.min(48, Math.max(0, ...items.map((i) => i.object.length)));
166
+ return items.map((i) => {
167
+ const [sign, color] = SIGN[i.change];
168
+ const extra = [i.detail, i.others.length ? `with ${i.others.slice(0, 3).join(', ')}${i.others.length > 3 ? ` (+${i.others.length - 3})` : ''}` : ''].filter(Boolean).join('; ');
169
+ return ` ${chalk[color](sign)} ${i.kind.padEnd(kw)} ${chalk.bold(extra ? i.object.padEnd(ow) : i.object)}${extra ? ` ${chalk.grey(extra)}` : ''}`;
170
+ });
171
+ };
172
+
173
+ Object.assign(module.exports, { describe, summarize, summaryLines, alterDetail, kindOf, shortName });
package/project/flows.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // poad flows new <nom> crée poad/flows/<nom>.json (flow minimal)
2
2
  // poad flows list flows du projet, vus par l'engine lancé
3
- // poad flows run <nom> [clé=valeur …] [input=<fichier.json>] [--wait|--no-wait]
3
+ // poad flows run <nom> [clé=valeur …] [input=<fichier.json>] [--input '<json>'] [--wait|--no-wait|--detach]
4
4
  // lance un flow et suit ses étapes
5
5
  // poad flows runs [nom] [limit=20] dernières exécutions
6
6
  // poad flows show <run_id> détail d'une exécution
@@ -10,14 +10,21 @@
10
10
  // poad/flows/<nom>.json. L'engine (0.18.0+) le sert sous /flows/v1 ; sa file
11
11
  // est sur le Valkey du projet (poad run valkey). Les étapes « conteneur » sont
12
12
  // lancées par l'exécuteur (poad run runner).
13
+ //
14
+ // --env <environnement> (production : main) et --project <id> : le projet
15
+ // hébergé sur poad.io (session de poad login) au lieu de l'engine local, pour
16
+ // list, run, runs, show et cancel. poad.io remet au propriétaire un jeton
17
+ // service_role de 15 minutes (route storage-token du plan de contrôle,
18
+ // renouvelé pendant un long suivi) et la clé anon : jamais affichés.
13
19
  const NAME_RE = /^[a-z][a-z0-9-]{0,62}$/;
14
20
  const POLL_MS = 700;
15
21
  const TIMEOUT_MS = 10000;
16
22
  const MAX_OUTPUT = 4000;
17
23
  const MAX_STEP_OUTPUT = 300;
18
24
  const FINAL = ['completed', 'failed', 'cancelled'];
25
+ const RUN_USAGE = "Usage: poad flows run <name> [key=value …] [input=<file.json>] [--input '<json>'] [--wait|--no-wait|--detach] [--env <name>] [--project <id>]";
19
26
  const USAGE =
20
- 'Usage: poad flows new <name> | list | run <name> [key=value …] [input=<file.json>] [--wait|--no-wait] | runs [name] [limit=20] | show <run_id> | cancel <run_id>';
27
+ 'Usage: poad flows new <name> | list | run <name> [key=value …] [input=<file.json>] [--input <json>] [--detach] | runs [name] [limit=20] | show <run_id> | cancel <run_id>, and --env <name> | --project <id> for poad.io';
21
28
  const NEEDS_VALKEY = 'Flows need Valkey: "poad run valkey", then restart the project ("poad stop", "poad start").';
22
29
 
23
30
  /** Flow minimal valide : déclencheur manuel → étape set qui rend un message. Pure. */
@@ -51,12 +58,25 @@ const parseValue = (text) => {
51
58
  * fichier JSON (lu par l'appelant) ; les autres clé=valeur forment l'entrée.
52
59
  */
53
60
  const parseRunArgs = (tokens) => {
54
- const out = { name: null, input: {}, file: null, wait: true };
55
- for (const token of tokens) {
56
- const text = String(token);
61
+ const out = { name: null, input: {}, file: null, inline: null, wait: true };
62
+ const list = tokens.map(String);
63
+ for (let i = 0; i < list.length; i++) {
64
+ const text = list[i];
57
65
  if (text === '--wait') out.wait = true;
58
- else if (text === '--no-wait') out.wait = false;
59
- else if (text.startsWith('--')) return { error: `unknown option ${text}` };
66
+ else if (text === '--no-wait' || text === '--detach' || text === '-d') out.wait = false;
67
+ else if (text === '--input' || text.startsWith('--input=')) {
68
+ // --input '<json>' : l'entrée en JSON (un objet), en ligne
69
+ let value = text === '--input' ? list[++i] : text.slice('--input='.length);
70
+ if (value === undefined) return { error: "--input needs a value: --input '{\"key\": \"value\"}'" };
71
+ let parsed;
72
+ try {
73
+ parsed = JSON.parse(value);
74
+ } catch (err) {
75
+ return { error: `--input: not valid JSON (${err.message})` };
76
+ }
77
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return { error: '--input: a JSON object is expected, such as \'{"key": "value"}\'' };
78
+ out.inline = { ...(out.inline || {}), ...parsed };
79
+ } else if (text.startsWith('-')) return { error: `unknown option ${text}` };
60
80
  else if (text.includes('=')) {
61
81
  // Seul le premier « = » sépare : la valeur peut en contenir
62
82
  const at = text.indexOf('=');
@@ -173,6 +193,43 @@ const explain = (status, body) => {
173
193
  return `HTTP ${status}`;
174
194
  };
175
195
 
196
+ /**
197
+ * --env et --project (poad.io), où qu'ils soient : rend { words, env, project } ou { error }. Pure.
198
+ * « --env x » et « --env=x » ; le reste des mots, dans l'ordre.
199
+ */
200
+ const cloudOptions = (words) => {
201
+ const out = { words: [], env: null, project: null };
202
+ for (let i = 0; i < words.length; i++) {
203
+ const m = /^--(env|project)(?:=(.*))?$/s.exec(words[i]);
204
+ if (!m) {
205
+ out.words.push(words[i]);
206
+ continue;
207
+ }
208
+ let v = m[2];
209
+ if (v === undefined) {
210
+ v = words[i + 1];
211
+ if (v === undefined || v.startsWith('-')) return { error: `--${m[1]} needs a value` };
212
+ i++;
213
+ }
214
+ if (!v) return { error: `--${m[1]} needs a value` };
215
+ out[m[1]] = v;
216
+ }
217
+ return out;
218
+ };
219
+
220
+ /**
221
+ * Comme explain, pour poad.io : la passerelle sans service flows derrière elle
222
+ * n'est pas une affaire de Valkey local. Pure.
223
+ */
224
+ const explainCloud = (status, body, label) => {
225
+ if (status >= 200 && status < 300) return null;
226
+ const error = body && typeof body === 'object' && body.error && typeof body.error === 'object' ? body.error : null;
227
+ if (status === 502 || status === 503 || status === 504 || (status === 404 && !(error && error.code))) return `The flows service of ${label} does not answer (HTTP ${status}): is the environment active? ("poad env ls", "poad cloud info")`;
228
+ if (error && error.message) return `${error.message}${error.hint ? ` (${error.hint})` : ''}`;
229
+ if (status === 401 || status === 403) return `${label} refused the access (HTTP ${status}): "poad login" again, or check that you own the project.`;
230
+ return `HTTP ${status}`;
231
+ };
232
+
176
233
  class FlowsError extends Error {}
177
234
 
178
235
  /**
@@ -190,51 +247,82 @@ const main = async (args = {}, raw, deps = {}) => {
190
247
  const doFetch = deps.fetch || fetch;
191
248
  const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
192
249
  const started = deps.started || ((config) => require('../utils/docker').isDockerExist(config.project_uuid));
250
+ const cloudTarget = deps.cloudTarget || ((opts) => require('../utils/storage').cloudTarget(opts));
251
+ const fail = (message, code = 1) => {
252
+ process.exitCode = code;
253
+ console.log(chalk.redBright(message));
254
+ };
193
255
 
194
- const root = findPoadDir(cwd);
195
- if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
196
- const dir = path.join(path.dirname(root), 'flows');
197
- const rel = (p) => path.relative(cwd, p) || p;
198
256
  // Les mots tels que tapés : parseArgs convertit les valeurs et coupe au second « = »
199
- const words = Array.isArray(raw) ? raw.map(String) : Object.keys(args);
257
+ const typed = cloudOptions(Array.isArray(raw) ? raw.map(String) : Object.keys(args));
258
+ if (typed.error) return fail(`poad flows: ${typed.error}.`, 2);
259
+ const words = typed.words;
200
260
  const command = words[0] || 'list';
201
- const fail = (message) => {
202
- process.exitCode = 1;
203
- console.log(chalk.redBright(message));
204
- };
261
+ const cloud = Boolean(typed.env || typed.project);
262
+ const where = cloud ? ` ${[typed.env ? `--env ${typed.env}` : '', typed.project ? `--project ${typed.project}` : ''].filter(Boolean).join(' ')}` : '';
205
263
 
206
- /** Configuration d'un projet prêt à répondre, ou null (message affiché) */
264
+ const root = findPoadDir(cwd);
265
+ // Avec --project, le dossier courant n'a pas besoin d'être un projet
266
+ if (!root && !(cloud && typed.project)) return fail(cloud ? 'Not in a poad project folder: cd into one, or pass --project <id>.' : 'You are not in a poad project directory.');
267
+ const dir = root ? path.join(path.dirname(root), 'flows') : null;
268
+ const rel = (p) => path.relative(cwd, p) || p;
269
+
270
+ /**
271
+ * Engine visé, prêt à répondre, ou null (message affiché) :
272
+ * { base, key, apikey, label, cloud, renew? }
273
+ */
207
274
  const ready = async () => {
275
+ if (cloud) {
276
+ try {
277
+ const t = await cloudTarget({ env: typed.env, project: typed.project });
278
+ return { base: t.base, key: t.key, apikey: t.apikey || t.key, label: t.label, cloud: true, renew: t.renew, expires: t.renew && t.renew.first ? Date.parse(t.renew.first) : null };
279
+ } catch (err) {
280
+ return fail((err && err.message) || String(err), (err && err.exit) || 1) || null;
281
+ }
282
+ }
208
283
  const config = readConfig(root);
209
284
  if (!supportsFlows(config)) return fail(`Flows need engine 0.18.0 or later (this project uses ${config.engine}): "poad upgrade".`) || null;
210
285
  if (!(await started(config))) return fail('The project is not started: run "poad start".') || null;
211
- return config;
286
+ const key = config.auth.service;
287
+ return { base: `http://localhost:${config.web.port}`, key, apikey: key, label: 'local engine', cloud: false };
212
288
  };
213
289
 
214
- /** Appel de /flows/v1 avec la clé service_role ; lève FlowsError avec un message à afficher */
215
- const call = async (config, method, route, body) => {
216
- const key = config.auth.service;
217
- const base = `http://localhost:${config.web.port}`;
290
+ /** Jeton poad.io renouvelé une minute avant son expiration (suivi de plus de 15 minutes) */
291
+ const fresh = async (t) => {
292
+ if (!t.renew || !t.expires || t.expires - Date.now() > 60000) return;
293
+ try {
294
+ const n = await t.renew.next();
295
+ Object.assign(t, { key: n.token, apikey: n.anon_key || t.apikey, expires: Date.parse(n.expires_at) });
296
+ } catch (err) {
297
+ throw new FlowsError(`poad.io gave no new access: ${(err && err.message) || err}`);
298
+ }
299
+ };
300
+
301
+ /** Appel de /flows/v1 avec un jeton service_role ; lève FlowsError avec un message à afficher */
302
+ const call = async (t, method, route, body) => {
303
+ await fresh(t);
218
304
  let res;
219
305
  try {
220
- res = await doFetch(`${base}/flows/v1${route}`, {
306
+ res = await doFetch(`${t.base}/flows/v1${route}`, {
221
307
  method,
222
- headers: { apikey: key, authorization: `Bearer ${key}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
308
+ headers: { apikey: t.apikey, authorization: `Bearer ${t.key}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
223
309
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
224
310
  signal: AbortSignal.timeout(TIMEOUT_MS),
225
311
  });
226
312
  } catch (err) {
227
313
  const timedOut = err && (err.name === 'TimeoutError' || err.name === 'AbortError');
228
- throw new FlowsError(timedOut ? `The engine did not answer within ${TIMEOUT_MS / 1000} s (${base}).` : `The engine does not answer on ${base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
314
+ const who = t.cloud ? t.label : 'The engine';
315
+ throw new FlowsError(timedOut ? `${who} did not answer within ${TIMEOUT_MS / 1000} s (${t.base}).` : `${who} does not answer on ${t.base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
229
316
  }
230
317
  const json = await res.json().catch(() => null);
231
- const problem = explain(res.status, json);
318
+ const problem = t.cloud ? explainCloud(res.status, json, t.label) : explain(res.status, json);
232
319
  if (problem) throw new FlowsError(problem);
233
320
  return json || {};
234
321
  };
235
322
 
236
323
  // ------------------------------------------------------------------ new
237
324
  if (command === 'new' || command === 'create') {
325
+ if (cloud) return fail('poad flows new writes poad/flows/<name>.json here: no --env nor --project (then "poad deploy").', 2);
238
326
  const name = String(words[1] || '');
239
327
  if (!NAME_RE.test(name)) return fail('Flow name: a letter first, then a-z, 0-9 and "-" (poad flows new send-report).');
240
328
  const file = path.join(dir, `${name}.json`);
@@ -260,9 +348,9 @@ const main = async (args = {}, raw, deps = {}) => {
260
348
  if (!(err instanceof FlowsError)) throw err;
261
349
  return fail(err.message);
262
350
  }
263
- console.log(`${chalk.bold('Flows')} ${chalk.grey(rel(dir))}`);
351
+ console.log(`${chalk.bold('Flows')} ${chalk.grey(cloud ? config.label : rel(dir))}`);
264
352
  console.log(' ');
265
- if (!flows.length) return console.log(chalk.grey(' None yet: "poad flows new <name>".'));
353
+ if (!flows.length) return console.log(chalk.grey(cloud ? ' None yet: "poad flows new <name>", then "poad deploy".' : ' None yet: "poad flows new <name>".'));
266
354
  const width = Math.max(...flows.map((f) => String(f.name).length));
267
355
  for (const flow of flows) for (const line of flowLines(flow, width)) console.log(line);
268
356
  return;
@@ -272,11 +360,11 @@ const main = async (args = {}, raw, deps = {}) => {
272
360
  if (command === 'run') {
273
361
  const parsed = parseRunArgs(words.slice(1));
274
362
  if (parsed.error) {
275
- fail(`poad flows run: ${parsed.error}.`);
276
- return console.log(chalk.grey(' Usage: poad flows run <name> [key=value …] [input=<file.json>] [--wait|--no-wait]'));
363
+ fail(`poad flows run: ${parsed.error}.`, 2);
364
+ return console.log(chalk.grey(` ${RUN_USAGE}`));
277
365
  }
278
- // Le fichier d'abord, les clé=valeur par-dessus
279
- let input = parsed.input;
366
+ // Le fichier d'abord, puis --input, les clé=valeur par-dessus
367
+ let input = { ...(parsed.inline || {}), ...parsed.input };
280
368
  if (parsed.file !== null) {
281
369
  let fromFile;
282
370
  try {
@@ -285,7 +373,7 @@ const main = async (args = {}, raw, deps = {}) => {
285
373
  return fail(`input=${parsed.file}: ${err.code === 'ENOENT' ? 'no such file' : `not readable as JSON (${err.message})`}.`);
286
374
  }
287
375
  if (typeof fromFile !== 'object' || fromFile === null || Array.isArray(fromFile)) return fail(`input=${parsed.file}: the file must contain a JSON object.`);
288
- input = { ...fromFile, ...parsed.input };
376
+ input = { ...fromFile, ...(parsed.inline || {}), ...parsed.input };
289
377
  }
290
378
  const config = await ready();
291
379
  if (!config) return;
@@ -296,9 +384,15 @@ const main = async (args = {}, raw, deps = {}) => {
296
384
  if (!(err instanceof FlowsError)) throw err;
297
385
  return fail(`Flow not started: ${err.message}`);
298
386
  }
299
- if (!parsed.wait) return console.log(runId);
387
+ if (!runId) return fail('Flow not started: the engine gave no run id.');
388
+ if (!parsed.wait) {
389
+ // La sortie standard ne porte que l'id (scripts) ; la suite, sur la sortie d'erreur
390
+ console.log(runId);
391
+ if (cloud && process.stderr.isTTY) console.error(chalk.grey(` Follow it: poad flows show ${runId}${where}`));
392
+ return;
393
+ }
300
394
 
301
- console.log(`${chalk.bold(parsed.name)} ${chalk.grey(`run ${runId}`)}`);
395
+ console.log(`${chalk.bold(parsed.name)} ${chalk.grey(`run ${runId}${cloud ? ` ${config.label}` : ''}`)}`);
302
396
  const seen = new Map();
303
397
  let misses = 0;
304
398
  let view = null;
@@ -311,7 +405,7 @@ const main = async (args = {}, raw, deps = {}) => {
311
405
  // Une lecture ratée n'arrête pas le suivi ; cinq de suite, si
312
406
  if (++misses >= 5) {
313
407
  fail(`Lost track of the run: ${err.message}`);
314
- return console.log(chalk.grey(` It may still be running: poad flows show ${runId}`));
408
+ return console.log(chalk.grey(` It may still be running: poad flows show ${runId}${where}`));
315
409
  }
316
410
  await sleep(POLL_MS);
317
411
  continue;
@@ -356,7 +450,7 @@ const main = async (args = {}, raw, deps = {}) => {
356
450
  }
357
451
  console.log(`${chalk.bold('Runs')}${flow ? ` ${chalk.grey(flow)}` : ''}`);
358
452
  console.log(' ');
359
- if (!runs.length) return console.log(chalk.grey(flow ? ` No run of "${flow}" yet: poad flows run ${flow}` : ' No run yet: poad flows run <name>'));
453
+ if (!runs.length) return console.log(chalk.grey(flow ? ` No run of "${flow}" yet: poad flows run ${flow}${where}` : ` No run yet: poad flows run <name>${where}`));
360
454
  const width = Math.max(...runs.map((r) => String(r.flow).length));
361
455
  for (const run of runs) console.log(runLine(run, width));
362
456
  return;
@@ -365,7 +459,7 @@ const main = async (args = {}, raw, deps = {}) => {
365
459
  // ------------------------------------------------------------------ show, cancel
366
460
  if (command === 'show' || command === 'cancel') {
367
461
  const id = String(words[1] || '');
368
- if (!id) return fail(`Usage: poad flows ${command} <run_id> ("poad flows runs" lists them).`);
462
+ if (!id) return fail(`Usage: poad flows ${command} <run_id> ("poad flows runs${where}" lists them).`, 2);
369
463
  const config = await ready();
370
464
  if (!config) return;
371
465
  try {
@@ -408,4 +502,4 @@ const main = async (args = {}, raw, deps = {}) => {
408
502
  };
409
503
 
410
504
  module.exports = (args, raw) => main(args, raw);
411
- Object.assign(module.exports, { main, template, parseValue, parseRunArgs, duration, clip, pretty, stepKey, stepLine, flowLines, runLine, explain, NAME_RE, NEEDS_VALKEY });
505
+ Object.assign(module.exports, { main, template, parseValue, parseRunArgs, cloudOptions, duration, clip, pretty, stepKey, stepLine, flowLines, runLine, explain, explainCloud, NAME_RE, NEEDS_VALKEY });