poad 2.20.0 → 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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.20.0",
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 };