poad 2.19.1 → 2.21.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.
@@ -0,0 +1,113 @@
1
+ // poad clean restes des projets poad sur cette machine, à purger :
2
+ // - services annexes (Mailpit, Keycloak, Valkey) dont l'engine
3
+ // ne tourne plus (engine arrêté hors de poad stop : Docker
4
+ // Desktop, redémarrage, ancienne version du CLI) ;
5
+ // - conteneurs poad arrêtés, réseaux des projets arrêtés ;
6
+ // - Keycloak partagé qui ne sert plus aucun projet en marche ;
7
+ // - anciennes images d'engine (environ 3 Go chacune) qu'aucun
8
+ // conteneur n'utilise.
9
+ // Rien de ce qui appartient à un projet en marche n'est touché.
10
+ // poad clean --dry-run liste seulement
11
+ // poad clean --yes sans question (hors terminal)
12
+ //
13
+ // Un projet arrêté ne perd rien : ses données sont dans son dossier poad/data,
14
+ // et une image d'engine supprimée est retéléchargée par poad start au besoin.
15
+ module.exports = async (args = {}) => {
16
+ const chalk = require('chalk-v2');
17
+ const Docker = require('dockerode');
18
+ const docker = new Docker();
19
+ const flag = (f) => Boolean(args[f] || args[`--${f}`]);
20
+ const dry = flag('dry-run') || flag('dry');
21
+ const yes = flag('yes') || Boolean(args['-y']);
22
+ const shared = require('../utils/keycloak-shared');
23
+
24
+ const UUID = '[a-z0-9]{20}';
25
+ const containers = await docker.listContainers({ all: true });
26
+ const nameOf = (c) => (c.Names[0] || '').replace(/^\//, '');
27
+ const engines = containers.filter((c) => new RegExp(`^${UUID}$`).test(nameOf(c)) && String(c.Image).startsWith('poadio/engine'));
28
+ const running = new Set(engines.filter((c) => c.State === 'running').map(nameOf));
29
+
30
+ // Conteneurs à retirer : annexes orphelines, poad arrêtés
31
+ const doomed = [];
32
+ for (const c of containers) {
33
+ const name = nameOf(c);
34
+ const side = new RegExp(`^(${UUID})-(mail|keycloak|valkey)$`).exec(name);
35
+ if (side && !running.has(side[1])) doomed.push({ c, why: `${side[2]} of a stopped project` });
36
+ else if (engines.includes(c) && c.State !== 'running') doomed.push({ c, why: 'stopped engine' });
37
+ }
38
+ // Keycloak partagé : utile tant qu'un projet en marche y est rattaché
39
+ const kcShared = containers.find((c) => nameOf(c) === shared.NAME);
40
+ if (kcShared) {
41
+ const nets = Object.keys((kcShared.NetworkSettings && kcShared.NetworkSettings.Networks) || {}).filter((n) => n.startsWith('poad-'));
42
+ const used = nets.some((n) => running.has(n.slice(5)));
43
+ if (!used) doomed.push({ c: kcShared, why: 'shared Keycloak, no running project uses it' });
44
+ }
45
+
46
+ // Réseaux des projets arrêtés
47
+ const networks = (await docker.listNetworks()).filter((n) => {
48
+ const m = new RegExp(`^poad-(${UUID})$`).exec(n.Name);
49
+ return m && !running.has(m[1]);
50
+ });
51
+
52
+ // Images d'engine qu'aucun conteneur n'utilise (sauf celle du CLI)
53
+ const usedImages = new Set(containers.map((c) => c.Image));
54
+ const keep = `poadio/engine:${global.package.engine}`;
55
+ const images = (await docker.listImages())
56
+ .flatMap((i) => (i.RepoTags || []).map((tag) => ({ tag, size: i.Size })))
57
+ .filter((i) => i.tag.startsWith('poadio/engine:') && i.tag !== keep && !usedImages.has(i.tag));
58
+ const gb = (n) => `${(n / 1e9).toFixed(1)} GB`;
59
+
60
+ console.log(' ');
61
+ if (!doomed.length && !networks.length && !images.length) return console.log(`${chalk.greenBright('✔')} Nothing to clean.`);
62
+ if (doomed.length || networks.length) {
63
+ console.log(chalk.bold('Leftovers of stopped projects'));
64
+ for (const d of doomed) console.log(` ${chalk.yellowBright('•')} ${nameOf(d.c)} ${chalk.grey(`(${d.why})`)}`);
65
+ for (const n of networks) console.log(` ${chalk.yellowBright('•')} network ${n.Name}`);
66
+ console.log(' ');
67
+ }
68
+ if (images.length) {
69
+ console.log(chalk.bold(`Engine images no container uses ${chalk.grey(`(${gb(images.reduce((s, i) => s + i.size, 0))}; kept: ${keep})`)}`));
70
+ for (const i of images) console.log(` ${chalk.yellowBright('•')} ${i.tag} ${chalk.grey(gb(i.size))}`);
71
+ console.log(' ');
72
+ }
73
+ if (dry) return console.log(chalk.grey(' --dry-run: nothing removed. "poad clean" removes them.'));
74
+
75
+ const ask = async (message) => {
76
+ if (yes) return true;
77
+ if (!(process.stdin.isTTY && process.stdout.isTTY)) {
78
+ console.log(chalk.redBright('Not a terminal: confirm with --yes.'));
79
+ return false;
80
+ }
81
+ const { confirm } = require('@inquirer/prompts');
82
+ return confirm({ message, default: true }).catch(() => false);
83
+ };
84
+
85
+ if ((doomed.length || networks.length) && (await ask('Remove these containers and networks?'))) {
86
+ for (const d of doomed) {
87
+ try {
88
+ await docker.getContainer(d.c.Id).remove({ force: true });
89
+ console.log(`${chalk.greenBright('✔')} ${nameOf(d.c)}`);
90
+ } catch (err) {
91
+ console.log(`${chalk.redBright('✖')} ${nameOf(d.c)}: ${err.message}`);
92
+ }
93
+ }
94
+ for (const n of networks) {
95
+ try {
96
+ await docker.getNetwork(n.Id).remove();
97
+ console.log(`${chalk.greenBright('✔')} network ${n.Name}`);
98
+ } catch (err) {
99
+ console.log(`${chalk.redBright('✖')} network ${n.Name}: ${err.message.split('\n')[0]}`);
100
+ }
101
+ }
102
+ }
103
+ if (images.length && (await ask(`Remove ${images.length} engine image(s) (${gb(images.reduce((s, i) => s + i.size, 0))})? A project that needs one downloads it again on "poad start".`))) {
104
+ for (const i of images) {
105
+ try {
106
+ await docker.getImage(i.tag).remove();
107
+ console.log(`${chalk.greenBright('✔')} ${i.tag}`);
108
+ } catch (err) {
109
+ console.log(`${chalk.redBright('✖')} ${i.tag}: ${err.message.split('\n')[0]}`);
110
+ }
111
+ }
112
+ }
113
+ };
package/global/cli.js CHANGED
@@ -12,4 +12,5 @@ module.exports = {
12
12
  start: 'Start the project, apply migrations, start the services chosen with poad setup, then show its state (--all: every configured service, --bare: engine and mail only)',
13
13
  stop: 'Stop container for poad local development (stop kc|valkey: that service only)',
14
14
  run: 'Run an optional service next to the project (keycloak|kc, valkey|redis, --all)',
15
+ clean: 'Remove what stopped poad projects left on this machine: orphan Mailpit/Keycloak/Valkey, networks, unused engine images (--dry-run to list, --yes without question)',
15
16
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.19.1",
4
- "engine": "0.11.1",
3
+ "version": "2.21.0",
4
+ "engine": "0.11.2",
5
5
  "main": "index.js",
6
6
  "license": "MIT",
7
7
  "bin": {
package/project/cli.js CHANGED
@@ -8,6 +8,10 @@
8
8
  */
9
9
  module.exports = {
10
10
  info: `Information about your project`,
11
+ client: {
12
+ description: 'Front-end of the project: client init creates it from a template (Angular; Vue and React soon), wired to poad with sign-in',
13
+ init: 'Create the front-end (angular | vue | react, dir=<folder>, from=<local template>, --yes)',
14
+ },
11
15
  console: 'Open the administration console of the running project in the browser (engine 0.11.0+, no password, this machine only)',
12
16
  kc: 'Keycloak test set of the project (poad/keycloak.json; kc export saves the running realm)',
13
17
  setup: 'Choose what "poad start" starts: e-mails (Mailpit/SMTP), Keycloak, Valkey, migrations (interactive, or kc=on valkey=off, kc=shared|own, --all, --none, --list)',
@@ -0,0 +1,9 @@
1
+ // poad client : aide des commandes du front
2
+ module.exports = async () => {
3
+ const chalk = require('chalk-v2');
4
+ console.log(`${chalk.bold(' Usage :')}`);
5
+ console.log(' ');
6
+ console.log(` ${chalk.cyanBright('poad client init')} Create the front-end of the project (Angular; Vue and React soon), wired to poad with sign-in`);
7
+ console.log(` ${chalk.grey(' options: angular | vue | react, dir=<folder>, from=<local template>, --yes')}`);
8
+ console.log(' ');
9
+ };
@@ -0,0 +1,179 @@
1
+ // poad client init [angular|vue|react] [dir=web] [from=<dossier ou .tgz>] [--yes]
2
+ //
3
+ // Crée le front du projet à partir d'un modèle (@poadio/starter-<framework>
4
+ // sur npm) : connexion, compte, cadre d'application, branché sur le projet
5
+ // poad (URL et clé lues dans poad/config.toml au démarrage, rien à écrire).
6
+ // - à la racine du projet, ou dans dir= (proposé si la racine a déjà un
7
+ // package.json) ;
8
+ // - port de développement libre à partir de 4300 ;
9
+ // - .gitignore complété, dépendances installées (bun, sinon npm).
10
+ // from= : un modèle local (dossier ou archive), pour le développer.
11
+ const FRAMEWORKS = [
12
+ { value: 'angular', name: 'Angular (@cadriciel/ui)', package: '@poadio/starter-angular' },
13
+ { value: 'vue', name: 'Vue.js (bientôt)', disabled: 'bientôt' },
14
+ { value: 'react', name: 'React (bientôt)', disabled: 'bientôt' },
15
+ ];
16
+
17
+ // Jamais copiés depuis un dossier modèle local
18
+ const SKIP = new Set(['node_modules', 'dist', '.angular', '.git', '.github', '.env.local', 'env.json', '.DS_Store', 'poad']);
19
+
20
+ module.exports = async (args = {}) => {
21
+ const chalk = require('chalk-v2');
22
+ const fs = require('fs');
23
+ const os = require('os');
24
+ const path = require('path');
25
+ const { spawnSync } = require('child_process');
26
+ const { findPoadDir } = require('../../utils/findpoad');
27
+ const { readConfig } = require('../../utils/config');
28
+
29
+ const root = findPoadDir(process.cwd());
30
+ if (!root) {
31
+ process.exitCode = 1;
32
+ return console.log(chalk.redBright('No poad project here: "poad init" first (the backend), then "poad client init".'));
33
+ }
34
+ const config = readConfig(root);
35
+ const projectDir = path.dirname(path.dirname(root)); // dossier qui contient poad/
36
+ const flag = (f) => Boolean(args[f] || args[`--${f}`]);
37
+ const tty = process.stdin.isTTY && process.stdout.isTTY && !flag('yes');
38
+ const prompts = tty ? require('@inquirer/prompts') : null;
39
+
40
+ // 1. Framework
41
+ let fw = FRAMEWORKS.find((f) => args[f.value]);
42
+ if (!fw && prompts) {
43
+ const v = await prompts.select({ message: 'Front-end framework', choices: FRAMEWORKS }).catch(() => null);
44
+ fw = FRAMEWORKS.find((f) => f.value === v);
45
+ }
46
+ if (!fw) fw = FRAMEWORKS[0];
47
+ if (fw.disabled) {
48
+ process.exitCode = 1;
49
+ return console.log(chalk.yellowBright(`${fw.value}: coming soon. Angular is available now.`));
50
+ }
51
+
52
+ // 2. Dossier : la racine si elle est libre, sinon un sous-dossier
53
+ let dir = typeof args.dir === 'string' ? args.dir : null;
54
+ if (!dir) {
55
+ const rootTaken = fs.existsSync(path.join(projectDir, 'package.json'));
56
+ if (!rootTaken) dir = '.';
57
+ else if (prompts) dir = await prompts.input({ message: 'The project root already has a package.json. Folder for the front-end', default: 'web' }).catch(() => null);
58
+ else dir = 'web';
59
+ }
60
+ if (!dir) return;
61
+ const target = path.resolve(projectDir, dir);
62
+ if (fs.existsSync(path.join(target, 'package.json'))) {
63
+ process.exitCode = 1;
64
+ return console.log(chalk.redBright(`${path.relative(process.cwd(), path.join(target, 'package.json')) || 'package.json'} already exists: choose another folder (dir=<folder>).`));
65
+ }
66
+
67
+ // 3. Modèle : dossier local, archive, ou npm
68
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-client-'));
69
+ const ora = require('ora');
70
+ let progress = ora(`Fetching the ${fw.value} template`).start();
71
+ let source;
72
+ try {
73
+ const from = typeof args.from === 'string' ? path.resolve(process.cwd(), args.from.replace(/^~(?=\/)/, os.homedir())) : null;
74
+ let tgz = null;
75
+ if (from && fs.statSync(from).isDirectory()) source = from;
76
+ else if (from) tgz = from;
77
+ else {
78
+ const r = spawnSync('npm', ['pack', `${fw.package}@latest`, '--pack-destination', work, '--json', '--silent'], { encoding: 'utf8', shell: process.platform === 'win32' });
79
+ if (r.status !== 0) throw new Error((r.stderr || r.stdout || 'npm pack failed').trim().split('\n').slice(-3).join(' '));
80
+ tgz = path.join(work, JSON.parse(r.stdout)[0].filename);
81
+ }
82
+ if (tgz) {
83
+ const x = spawnSync('tar', ['-xzf', tgz, '-C', work], { encoding: 'utf8' });
84
+ if (x.status !== 0) throw new Error(`tar: ${x.stderr.trim()}`);
85
+ source = path.join(work, 'package');
86
+ }
87
+ progress.succeed(`Template: ${chalk.bold(require(path.join(source, 'package.json')).name)} ${chalk.grey(require(path.join(source, 'package.json')).version)}`);
88
+ } catch (err) {
89
+ progress.fail(chalk.redBright(`Template unavailable: ${err.message}`));
90
+ process.exitCode = 1;
91
+ return;
92
+ }
93
+
94
+ // 4. Copie (sans écraser un fichier existant)
95
+ const copy = (from, to) => {
96
+ for (const name of fs.readdirSync(from)) {
97
+ if (SKIP.has(name)) continue;
98
+ const a = path.join(from, name);
99
+ const b = path.join(to, name);
100
+ if (fs.statSync(a).isDirectory()) {
101
+ fs.mkdirSync(b, { recursive: true });
102
+ copy(a, b);
103
+ } else if (!fs.existsSync(b)) fs.copyFileSync(a, b);
104
+ }
105
+ };
106
+ fs.mkdirSync(target, { recursive: true });
107
+ copy(source, target);
108
+
109
+ // 5. package.json de l'application : nom du projet, rien de la publication
110
+ const pkgFile = path.join(target, 'package.json');
111
+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
112
+ const tpl = (pkg.poad && pkg.poad.template) || {};
113
+ const name = String(config.project_id || path.basename(projectDir))
114
+ .toLowerCase()
115
+ .replace(/[^a-z0-9._-]+/g, '-')
116
+ .replace(/^[-._]+|[-._]+$/g, '') || 'app';
117
+ pkg.name = dir === '.' ? name : `${name}-${path.basename(target)}`;
118
+ pkg.title = config.project_id || pkg.title;
119
+ // La description du paquet npm parle du modèle : l'application reprend la sienne
120
+ if (tpl.description) pkg.description = tpl.description;
121
+ pkg.version = '0.1.0';
122
+ pkg.private = true;
123
+ for (const k of ['files', 'repository', 'publishConfig', 'license']) delete pkg[k];
124
+ const origin = require(path.join(source, 'package.json'));
125
+ pkg.poad = { ...(pkg.poad || {}), from: `${origin.name}@${origin.version}` };
126
+ delete pkg.poad.template;
127
+ fs.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
128
+
129
+ // 6. Port de développement libre (4200 est souvent pris)
130
+ const net = require('net');
131
+ const free = (port) =>
132
+ new Promise((ok) => {
133
+ const s = net.createServer().once('error', () => ok(false)).once('listening', () => s.close(() => ok(true)));
134
+ s.listen(port, '127.0.0.1');
135
+ });
136
+ let port = Number(tpl.port) || 4300;
137
+ while (!(await free(port)) && port < 4400) port++;
138
+ const ngFile = path.join(target, 'angular.json');
139
+ if (fw.value === 'angular' && fs.existsSync(ngFile)) {
140
+ const ng = JSON.parse(fs.readFileSync(ngFile, 'utf8'));
141
+ for (const p of Object.values(ng.projects || {})) {
142
+ const serve = p.architect && p.architect.serve;
143
+ if (serve) serve.options = { ...(serve.options || {}), port };
144
+ }
145
+ fs.writeFileSync(ngFile, JSON.stringify(ng, null, 2) + '\n');
146
+ }
147
+
148
+ // Titre de la page : le nom du projet
149
+ const html = path.join(target, 'src', 'index.html');
150
+ if (fs.existsSync(html)) fs.writeFileSync(html, fs.readFileSync(html, 'utf8').replace(/<title>[^<]*<\/title>/, `<title>${String(pkg.title).replace(/[<&]/g, '')}</title>`));
151
+
152
+ // 7. .gitignore : celui de poad init (racine), complété des fichiers du front
153
+ const git = require('../../utils/git');
154
+ git.ensureRootGitignore(projectDir);
155
+ if (Array.isArray(tpl.gitignore) && tpl.gitignore.length) {
156
+ const prefix = dir === '.' ? '' : `/${path.relative(projectDir, target).split(path.sep).join('/')}`;
157
+ const lines = tpl.gitignore.map((l) => (l.startsWith('/') ? `${prefix}${l}` : l));
158
+ git.ensureLines(projectDir, `Front-end (${fw.value})`, lines);
159
+ }
160
+
161
+ // 8. Dépendances
162
+ const hasBun = spawnSync('bun', ['--version'], { encoding: 'utf8' }).status === 0;
163
+ const pm = hasBun ? 'bun' : 'npm';
164
+ progress = ora(`Installing the dependencies (${pm} install)`).start();
165
+ const inst = spawnSync(pm, ['install'], { cwd: target, encoding: 'utf8', shell: process.platform === 'win32' });
166
+ if (inst.status !== 0) progress.fail(chalk.yellowBright(`${pm} install failed: run it in ${path.relative(process.cwd(), target) || '.'}`));
167
+ else progress.succeed('Dependencies installed');
168
+ fs.rmSync(work, { recursive: true, force: true });
169
+
170
+ const rel = path.relative(process.cwd(), target) || '.';
171
+ const run = hasBun ? 'bun start' : 'npm start';
172
+ console.log(' ');
173
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(`${fw.value} front-end created`)} in ${chalk.cyanBright(rel)}`);
174
+ console.log(chalk.grey(' Sign-in (e-mail, magic link, providers), account and app layout, wired to this poad project.'));
175
+ console.log(' ');
176
+ console.log(` ${chalk.bold('poad start')}${chalk.grey(' the backend (if not running)')}`);
177
+ console.log(` ${chalk.bold(`${rel === '.' ? '' : `cd ${rel} && `}${run}`)}${chalk.grey(` http://localhost:${port}`)}`);
178
+ console.log(' ');
179
+ };
package/utils/git.js CHANGED
@@ -70,4 +70,15 @@ function setupRepo(dir) {
70
70
  return { gitignore, repo: 'created', root: dir };
71
71
  }
72
72
 
73
- module.exports = { version, repoRoot, ensureRootGitignore, setupRepo, BLOCKS };
73
+ /** Ajoute au .gitignore du dossier les lignes qui lui manquent, sous un titre */
74
+ function ensureLines(dir, title, lines) {
75
+ const file = path.join(dir, '.gitignore');
76
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
77
+ const have = new Set(existing.split(/\r?\n/).map((l) => l.trim()));
78
+ const missing = lines.filter((l) => !have.has(l));
79
+ if (!missing.length) return 0;
80
+ fs.writeFileSync(file, (existing ? existing.replace(/\s*$/, '\n') : '') + `\n# ${title}\n${missing.join('\n')}\n`);
81
+ return missing.length;
82
+ }
83
+
84
+ module.exports = { version, repoRoot, ensureRootGitignore, ensureLines, setupRepo, BLOCKS };