poad 2.38.0 → 2.40.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/cli.js CHANGED
@@ -9,7 +9,8 @@
9
9
  module.exports = {
10
10
  install: `Install poad environment`,
11
11
  init: `Init poad project`,
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, --quiet: nothing if it already runs). A port of poad/config.toml already used on this machine is replaced by a free one',
12
+ create: 'Create a poad project and its front-ends. Outside a project: create <project> --template angular|next|nuxt|vanilla [--app web] makes poad/ (backend) and apps/<app> (first front-end), a workspace package.json (bun start: poad, then every front-end), dependencies, first git commit. Inside a project: create <app> --template t adds apps/<app> on its own port. --flat: the former layout (poad/ inside the app). Template from npm, integrity checked (create --help)',
13
+ start: 'Start the project, apply migrations, start the services chosen with poad setup, then show its state, secrets hidden: poad info --secrets (--all: every configured service, --bare: engine and mail only, --quiet: nothing if it already runs). A port of poad/config.toml already used on this machine is replaced by a free one',
13
14
  stop: 'Stop container for poad local development (stop kc|valkey|runner: that service only)',
14
15
  run: 'Run an optional service next to the project (keycloak|kc, valkey|redis, runner, --all)',
15
16
  clean: 'Remove what stopped poad projects left on this machine: orphan Mailpit/Keycloak/Valkey/flows runner, networks, unused engine images (--dry-run to list, --yes without question)',
@@ -0,0 +1,513 @@
1
+ // poad create : un projet poad et ses fronts.
2
+ //
3
+ // Hors d'un projet poad : un projet neuf, un backend et un premier front
4
+ // poad create <projet> [--template t] [--app web]
5
+ // <projet>/poad/ poad init (config.toml, secrets, migrations)
6
+ // <projet>/apps/<app>/ le front, modèle @poadio/starter-<template>
7
+ // <projet>/package.json espace de travail (workspaces apps/*), bun start
8
+ // <projet>/scripts/start.mjs démarre poad puis tous les fronts
9
+ // puis dépendances (bun workspaces), git init et premier commit à la racine.
10
+ //
11
+ // Dans un projet poad (poad/config.toml ici ou dans un parent) : un front de plus
12
+ // poad create <app> --template t [--dir <dossier>]
13
+ // apps/<app>/ (ou --dir), port de développement distinct des autres fronts,
14
+ // inscrit dans les workspaces du package.json racine ; poad/ n'est jamais
15
+ // touché, pas de nouveau dépôt git ni de commit.
16
+ //
17
+ // --flat : l'ancienne disposition, un seul front avec poad/ dedans
18
+ // poad create <dossier> --flat -> <dossier>/package.json, <dossier>/poad/
19
+ //
20
+ // Modèle : dernière version du registre npm (archive en HTTPS, intégrité
21
+ // sha512 vérifiée, extraction sans dépendance : utils/tar refuse chemins
22
+ // absolus, « .. » et liens), ou --from <archive.tgz | dossier> (npm pack d'un
23
+ // modèle en cours d'écriture).
24
+ //
25
+ // Options aussi au format du CLI : template=next pm=npm app=admin.
26
+ const fs = require('fs');
27
+ const os = require('os');
28
+ const path = require('path');
29
+ const { spawn, spawnSync } = require('child_process');
30
+
31
+ const PMS = ['bun', 'npm', 'pnpm'];
32
+ const VALUED = ['template', 'pm', 'from', 'app', 'dir'];
33
+ const FLAGS = { yes: 'yes', y: 'yes', 'no-install': 'noInstall', 'no-git': 'noGit', flat: 'flat', help: 'help', h: 'help' };
34
+
35
+ class UsageError extends Error {}
36
+
37
+ /** Arguments tels que tapés -> { name, template, pm, from, app, dir, yes, noInstall, noGit, flat, help } */
38
+ function parseCreateArgs(raw = []) {
39
+ const opts = { name: null, template: null, pm: null, from: null, app: null, dir: null, yes: false, noInstall: false, noGit: false, flat: false, help: false };
40
+ for (let i = 0; i < raw.length; i++) {
41
+ const arg = String(raw[i]);
42
+ const m = /^--?([a-z][a-z-]*)(?:=(.*))?$/.exec(arg) || /^([a-z]+)=(.*)$/.exec(arg);
43
+ if (!m) {
44
+ if (opts.name) throw new UsageError(`unexpected argument "${arg}" (the name is already "${opts.name}")`);
45
+ opts.name = arg;
46
+ continue;
47
+ }
48
+ const [, key, inline] = m;
49
+ if (VALUED.includes(key)) {
50
+ const value = inline !== undefined ? inline : raw[++i];
51
+ if (value === undefined || value === '' || /^--?[a-z]/.test(value)) throw new UsageError(`--${key} needs a value`);
52
+ opts[key] = value;
53
+ } else if (FLAGS[key] && inline === undefined) {
54
+ opts[FLAGS[key]] = true;
55
+ } else {
56
+ throw new UsageError(`unknown option "${arg}"`);
57
+ }
58
+ }
59
+ if (opts.template) opts.template = opts.template.toLowerCase();
60
+ if (opts.pm && !PMS.includes(opts.pm)) throw new UsageError(`--pm must be one of ${PMS.join(', ')}`);
61
+ return opts;
62
+ }
63
+
64
+ const has = (cmd) => {
65
+ const r = spawnSync(cmd, ['--version'], { encoding: 'utf8', shell: process.platform === 'win32' });
66
+ return !r.error && r.status === 0;
67
+ };
68
+
69
+ /** Dossier cible : neuf, ou vide (un .DS_Store ne compte pas) */
70
+ function checkTarget(target) {
71
+ if (!fs.existsSync(target)) return 'new';
72
+ if (!fs.statSync(target).isDirectory()) throw new UsageError(`${target} exists and is not a folder`);
73
+ const content = fs.readdirSync(target).filter((n) => n !== '.DS_Store');
74
+ if (content.length) throw new UsageError(`${target} is not empty: choose a new folder`);
75
+ return 'empty';
76
+ }
77
+
78
+ /** Disponibilité de chaque modèle sur npm (en parallèle, délai court) */
79
+ async function availability(templates, registry) {
80
+ const { packageMetadata, cachedVersion } = registry;
81
+ return Promise.all(
82
+ templates.map(async (t) => {
83
+ const metadata = await packageMetadata(t.package, { timeout: 3000 });
84
+ const cached = cachedVersion(t.package);
85
+ const state = metadata.status === 'ok' ? 'available' : metadata.status === 'missing' ? 'soon' : cached ? 'cached' : 'offline';
86
+ return { ...t, metadata, cached, state };
87
+ })
88
+ );
89
+ }
90
+
91
+ /** Commande lancée de façon asynchrone (le spinner tourne) ; { ok, output } */
92
+ const run = (cmd, args, cwd) =>
93
+ new Promise((resolve) => {
94
+ let output = '';
95
+ const child = spawn(cmd, args, { cwd, shell: process.platform === 'win32' });
96
+ child.stdout.on('data', (d) => (output += d));
97
+ child.stderr.on('data', (d) => (output += d));
98
+ child.on('error', (err) => resolve({ ok: false, output: err.message }));
99
+ child.on('close', (code) => resolve({ ok: code === 0, output }));
100
+ });
101
+
102
+ const tail = (text, n = 8) => text.trim().split(/\r?\n/).slice(-n).map((l) => ` ${l}`).join('\n');
103
+
104
+ /** « Next.js application created » ; framework inconnu (--from) : « Application created » */
105
+ function createdTitle(template, dev = {}) {
106
+ const label = dev.label || (template && template.label.split(' (')[0]);
107
+ return label ? `${label} application created` : 'Application created';
108
+ }
109
+
110
+ /**
111
+ * Ce que fera poad create, d'après les options et le dossier courant :
112
+ * 'add' : dans un projet poad, un front de plus ;
113
+ * 'flat' : --flat, un seul front avec poad/ dedans (ancienne disposition) ;
114
+ * 'new' : un projet neuf, poad/ et apps/<app>.
115
+ */
116
+ function modeOf(opts, project) {
117
+ if (opts.flat) {
118
+ if (project) throw new UsageError(`Already inside the poad project ${project.root}: --flat makes a separate project, run it from another folder (or drop --flat to add a front-end here).`);
119
+ if (opts.dir) throw new UsageError('--dir is for a front-end added inside a poad project');
120
+ return 'flat';
121
+ }
122
+ if (project) {
123
+ if (opts.app && opts.name && opts.app !== opts.name) throw new UsageError(`Two names for the front-end: "${opts.name}" and --app ${opts.app}`);
124
+ return 'add';
125
+ }
126
+ if (opts.dir) throw new UsageError('--dir is for a front-end added inside a poad project (poad/config.toml here or in a parent folder)');
127
+ return 'new';
128
+ }
129
+
130
+ function usage(chalk) {
131
+ const c = chalk.cyanBright;
132
+ console.log(`${chalk.bold(' Usage :')}`);
133
+ console.log(` ${c('poad create <project>')} ${chalk.cyan('[--template t] [--app web]')} a new project: poad/ (backend) and apps/<app> (first front-end)`);
134
+ console.log(` ${c('poad create <app>')} ${chalk.cyan('--template t [--dir <folder>]')} inside a poad project: one more front-end, apps/<app>`);
135
+ console.log(` ${c('poad create <folder> --flat')} ${chalk.cyan('[--template t]')} one front-end with poad/ inside it (the former layout)`);
136
+ console.log(' ');
137
+ console.log(' One poad backend, several front-ends:');
138
+ console.log(chalk.grey(' my-project/'));
139
+ console.log(chalk.grey(' poad/ backend (config, migrations, functions, flows)'));
140
+ console.log(chalk.grey(' apps/web/ Next.js poad create web --template next'));
141
+ console.log(chalk.grey(' apps/admin/ Angular poad create admin --template angular'));
142
+ console.log(chalk.grey(' package.json workspaces apps/*; bun start: poad, then every front-end on its own port'));
143
+ console.log(' ');
144
+ console.log(` ${c('--template')} angular, next, nuxt or vanilla (asked when omitted in a terminal; angular otherwise)`);
145
+ console.log(` ${c('--app')} name of the first front-end of a new project (default: web): its folder apps/<app>, and the`);
146
+ console.log(' application name of its public variables (PUBLIC_* with app=<name>, /env/v1?app=<name>)');
147
+ console.log(` ${c('--dir')} inside a project: folder of the new front-end (default: apps/<app>)`);
148
+ console.log(` ${c('--flat')} the former layout: package.json and poad/ in the same folder`);
149
+ console.log(` ${c('--yes')} no question`);
150
+ console.log(` ${c('--no-install')} do not install the dependencies (bun start does it later)`);
151
+ console.log(` ${c('--no-git')} no git repository, no commit (a front-end added to a project never commits)`);
152
+ console.log(` ${c('--pm')} bun, npm or pnpm (default: bun if installed, else npm)`);
153
+ console.log(` ${c('--from')} a local template (npm pack archive, or folder), to develop a template`);
154
+ console.log(' ');
155
+ console.log(' Each front-end gets a development port of its own: poad.port in its package.json (from the template,');
156
+ console.log(' else its framework default), moved past the ports of the other front-ends and of the poad services.');
157
+ console.log(' A front-end reads the public variables of its application name (package.json poad.app).');
158
+ console.log(' ');
159
+ }
160
+
161
+ /** Modèle choisi (question dans un terminal) : { template, metadata } ; null si abandon */
162
+ async function chooseTemplate(opts, { prompts, chalk, ora, registry, starter }) {
163
+ let template = opts.template ? starter.templateByValue(opts.template) : null;
164
+ if (opts.template && !template) throw new UsageError(`Unknown template "${opts.template}": ${starter.TEMPLATES.map((t) => t.value).join(', ')}.`);
165
+ if (opts.from) return { template, metadata: null };
166
+ let metadata;
167
+ if (!template && prompts) {
168
+ const spin = ora('Checking the templates on npm').start();
169
+ const states = await availability(starter.TEMPLATES, registry);
170
+ spin.stop();
171
+ const note = { soon: 'coming soon', offline: 'offline', cached: 'offline, cached' };
172
+ const choices = states.map((t) => ({
173
+ value: t.value,
174
+ short: t.label,
175
+ name: `${t.label.padEnd(26)}${chalk.grey(t.package)}${t.state === 'cached' ? chalk.grey(` (${note.cached} ${t.cached})`) : ''}`,
176
+ disabled: t.state === 'soon' || t.state === 'offline' ? note[t.state] : false,
177
+ }));
178
+ if (choices.every((c) => c.disabled)) throw new Error('No template can be fetched: the npm registry cannot be reached and nothing is cached.');
179
+ const value = await prompts.select({ message: 'Template', choices }).catch(() => null);
180
+ if (!value) return null;
181
+ template = starter.templateByValue(value);
182
+ metadata = states.find((s) => s.value === value).metadata;
183
+ }
184
+ if (!template) {
185
+ template = starter.templateByValue('angular');
186
+ console.log(chalk.grey(` Template: angular (--template to choose another one).`));
187
+ }
188
+ if (!metadata) metadata = await registry.packageMetadata(template.package, { timeout: 5000 });
189
+ if (metadata.status === 'missing') throw new Error(`${template.value}: coming soon (${template.package} is not published yet).`);
190
+ return { template, metadata };
191
+ }
192
+
193
+ // Jamais copiés depuis un dossier modèle local (--from <dossier>)
194
+ const SKIP = new Set(['node_modules', 'dist', '.angular', '.next', '.git', '.github', '.env.local', 'env.json', '.DS_Store', 'poad']);
195
+
196
+ function copyTree(from, to, skip = new Set()) {
197
+ fs.mkdirSync(to, { recursive: true });
198
+ for (const name of fs.readdirSync(from)) {
199
+ if (skip.has(name)) continue;
200
+ const a = path.join(from, name);
201
+ const b = path.join(to, name);
202
+ const st = fs.lstatSync(a);
203
+ if (st.isSymbolicLink()) continue;
204
+ if (st.isDirectory()) copyTree(a, b, skip);
205
+ else if (!fs.existsSync(b)) fs.copyFileSync(a, b);
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Modèle extrait dans un dossier temporaire (rien n'est écrit dans le projet
211
+ * tant qu'il n'est pas lu et vérifié) : { dir, pkg, from, source }.
212
+ */
213
+ async function fetchTemplate(opts, template, metadata, { registry }) {
214
+ const { extractTgz } = require('../utils/tar');
215
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-create-'));
216
+ const dir = path.join(work, 'package');
217
+ try {
218
+ let source;
219
+ if (opts.from) {
220
+ const file = path.resolve(process.cwd(), opts.from.replace(/^~(?=\/)/, os.homedir()));
221
+ if (fs.statSync(file).isDirectory()) {
222
+ copyTree(file, dir, SKIP);
223
+ source = { name: null, version: null, source: 'folder' };
224
+ } else {
225
+ extractTgz(fs.readFileSync(file), dir);
226
+ source = { name: null, version: null, source: 'local' };
227
+ }
228
+ } else {
229
+ const got = await registry.fetchLatestTarball(template.package, { metadata, timeout: 5000 });
230
+ extractTgz(got.buf, dir);
231
+ source = { name: template.package, version: got.version, source: got.source };
232
+ }
233
+ const pkg = require('../utils/starter').readPackage(dir);
234
+ if (!pkg) throw new Error('no package.json in it');
235
+ return { work, dir, pkg, source, from: `${source.name || pkg.name}@${source.version || pkg.version}` };
236
+ } catch (err) {
237
+ fs.rmSync(work, { recursive: true, force: true });
238
+ throw err;
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Le modèle devient une application dans appDir : fichiers de publication
244
+ * retirés, .gitignore, package.json réécrit (nom, poad.app, poad.port),
245
+ * titre de la page, fichiers de verrouillage. Renvoie dev ({ framework, label, port, url }).
246
+ * workspace : membre d'un espace de travail (verrouillage et packageManager à la racine)
247
+ * keepPoad : le front porte son backend (--flat) ; sinon un poad/ du modèle est retiré
248
+ */
249
+ async function makeApp(appDir, tpl, { name, title, app, pm, workspace, exclude, keepPoad = false }) {
250
+ const starter = require('../utils/starter');
251
+ copyTree(tpl.dir, appDir);
252
+ starter.prepareStarter(appDir);
253
+ // Le backend est celui du projet : un dossier poad/ du modèle n'a rien à faire dans un front
254
+ const tplPoad = path.join(appDir, 'poad');
255
+ if (!keepPoad && fs.existsSync(tplPoad) && !fs.existsSync(path.join(tplPoad, 'config.toml'))) {
256
+ if (!fs.readdirSync(tplPoad).length) fs.rmSync(tplPoad, { recursive: true });
257
+ else console.log(require('chalk-v2').yellowBright(` The template brought poad/ files (${fs.readdirSync(tplPoad).join(', ')}): the backend is the project's poad/, move what you need there.`));
258
+ }
259
+ // Port et URL du front selon le framework (poad.port / poad.template.port du modèle)
260
+ const dev = await starter.devServer(appDir, tpl.pkg, { exclude });
261
+ // Modèle publié avant les variables par application (poad.template.appEnv) :
262
+ // poad.app est écrit quand même, il servira après la mise à jour du front
263
+ const tplMeta = (tpl.pkg.poad && tpl.pkg.poad.template) || {};
264
+ if (app && tplMeta.framework && !tplMeta.appEnv) {
265
+ console.log(require('chalk-v2').yellowBright(` ${tpl.from} does not read the public variables of its application yet: this front-end gets the common PUBLIC_* only (a newer template does, poad.app "${app}" is already set).`));
266
+ }
267
+ const pkg = starter.rewritePackageJson(tpl.pkg, { name, title, from: tpl.from });
268
+ pkg.poad = { ...(app ? { app } : {}), ...pkg.poad, ...(dev.port ? { port: dev.port } : {}) };
269
+ if (workspace) delete pkg.packageManager;
270
+ fs.writeFileSync(path.join(appDir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');
271
+ for (const html of ['src/index.html', 'index.html']) {
272
+ const file = path.join(appDir, html);
273
+ if (fs.existsSync(file)) fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(/<title>[^<]*<\/title>/, `<title>${String(title).replace(/[<&]/g, '')}</title>`));
274
+ }
275
+ dev.appEnv = Boolean(tplMeta.appEnv);
276
+ if (workspace) {
277
+ // Un seul fichier de verrouillage, celui de la racine
278
+ for (const f of Object.values(starter.LOCKFILES).flat()) fs.rmSync(path.join(appDir, f), { force: true });
279
+ } else starter.adaptToPackageManager(appDir, pm);
280
+ return dev;
281
+ }
282
+
283
+ /** poad init dans dir (le dépôt git est fait plus tard, sans question sur les services) */
284
+ async function poadInit(dir) {
285
+ const cwd = process.cwd();
286
+ try {
287
+ process.chdir(dir);
288
+ return await require('./init')({}, [], { git: false, setup: false });
289
+ } finally {
290
+ process.chdir(cwd);
291
+ }
292
+ }
293
+
294
+ async function install(pm, dir, { chalk, ora }) {
295
+ console.log(' ');
296
+ const progress = ora(`Installing the dependencies (${pm} install)`).start();
297
+ const r = await run(pm, ['install'], dir);
298
+ if (r.ok) {
299
+ progress.succeed('Dependencies installed');
300
+ return true;
301
+ }
302
+ progress.fail(chalk.yellowBright(`${pm} install failed (bun start installs them too):`));
303
+ console.log(chalk.grey(tail(r.output)));
304
+ return false;
305
+ }
306
+
307
+ function gitCommit(dir, message, chalk) {
308
+ const git = require('../utils/git');
309
+ const repo = git.setupRepo(dir);
310
+ if (repo.repo === 'created') {
311
+ const add = spawnSync('git', ['add', '-A'], { cwd: dir, encoding: 'utf8' });
312
+ const commit = add.status === 0 ? spawnSync('git', ['commit', '-q', '-m', message], { cwd: dir, encoding: 'utf8' }) : add;
313
+ if (commit.status === 0) console.log(chalk.grey(' git repository created, first commit done (branch main).'));
314
+ else console.log(chalk.yellowBright(` git repository created, but the first commit failed: ${(commit.stderr || commit.stdout).trim().split('\n').pop()}`));
315
+ } else if (repo.repo === 'existing') console.log(chalk.grey(` Inside the git repository ${repo.root}: no new repository, nothing committed.`));
316
+ else if (repo.repo === 'no-git') console.log(chalk.yellowBright(' git is not installed: no repository created.'));
317
+ else if (repo.repo === 'failed') console.log(chalk.yellowBright(` git init failed: ${repo.error}`));
318
+ }
319
+
320
+ /**
321
+ * poad create, options déjà lues (parseCreateArgs). Aussi appelé par
322
+ * poad client init (même chemin : un front ajouté au projet).
323
+ */
324
+ async function create(opts, { intro } = {}) {
325
+ const chalk = require('chalk-v2');
326
+ const ora = require('ora');
327
+ const registry = require('../utils/registry');
328
+ const starter = require('../utils/starter');
329
+ const ws = require('../utils/workspace');
330
+ const fail = (msg) => {
331
+ process.exitCode = 1;
332
+ console.log(chalk.redBright(` ${msg}`));
333
+ };
334
+ const tty = Boolean(process.stdin.isTTY && process.stdout.isTTY && !opts.yes);
335
+ const prompts = tty ? require('@inquirer/prompts') : null;
336
+ const cwd = process.cwd();
337
+
338
+ // 1. Ce qu'on fait : projet neuf, front ajouté, ou ancienne disposition
339
+ const project = ws.findProject(cwd);
340
+ let mode;
341
+ try {
342
+ mode = modeOf(opts, project);
343
+ } catch (err) {
344
+ return fail(err.message);
345
+ }
346
+ if (intro) intro(mode);
347
+
348
+ // 2. Noms et dossiers, tous vérifiés avant de télécharger quoi que ce soit
349
+ let root; // racine du projet
350
+ let appDir; // dossier du front
351
+ let app; // nom d'application (variables publiques)
352
+ let existed = false;
353
+ const apps = project ? ws.listApps(project.root) : [];
354
+ try {
355
+ if (mode === 'add') {
356
+ root = project.root;
357
+ app = opts.name || opts.app;
358
+ if (!app && prompts) {
359
+ const free = ['web', 'admin', 'site', 'app'].find((n) => !apps.some((a) => a.name === n)) || '';
360
+ app = await prompts.input({ message: 'Name of the new front-end (apps/<name>)', default: free }).catch(() => null);
361
+ if (!app) return;
362
+ }
363
+ if (!app) throw new UsageError('Missing name: poad create <app> --template next|angular (inside a poad project, adds apps/<app>)');
364
+ ws.checkAppName(app);
365
+ const same = apps.find((a) => a.name === app);
366
+ if (same) throw new UsageError(`The project already has a front-end "${app}" (${same.rel}): choose another name.`);
367
+ appDir = opts.dir ? path.resolve(cwd, opts.dir) : path.join(root, ws.APPS_DIR, app);
368
+ const rel = path.relative(root, appDir);
369
+ if (rel.startsWith('..') || path.isAbsolute(rel)) throw new UsageError(`${appDir} is outside the poad project ${root}: the front-end would not find poad/config.toml.`);
370
+ if (rel === 'poad' || rel.startsWith(`poad${path.sep}`)) throw new UsageError('poad/ is the backend: choose another folder.');
371
+ if (fs.existsSync(path.join(appDir, 'package.json'))) throw new UsageError(`${path.relative(cwd, path.join(appDir, 'package.json')) || 'package.json'} already exists: choose another folder (--dir <folder>).`);
372
+ if (appDir !== root) existed = checkTarget(appDir) === 'empty';
373
+ } else {
374
+ if (!opts.name && prompts) opts.name = await prompts.input({ message: mode === 'new' ? 'Folder of the new project' : 'Folder of the new application', default: mode === 'new' ? 'my-project' : 'my-app' }).catch(() => null);
375
+ if (!opts.name) throw new UsageError(`Missing folder: poad create <${mode === 'new' ? 'project' : 'dir'}>`);
376
+ root = path.resolve(cwd, opts.name);
377
+ existed = checkTarget(root) === 'empty';
378
+ if (mode === 'new') {
379
+ app = ws.checkAppName(opts.app || ws.DEFAULT_APP);
380
+ appDir = path.join(root, ws.APPS_DIR, app);
381
+ } else {
382
+ app = opts.app ? ws.checkAppName(opts.app) : ws.appNameOf({ name: path.basename(root) }) || null;
383
+ appDir = root;
384
+ }
385
+ }
386
+ } catch (err) {
387
+ fail(err.message);
388
+ if (err instanceof UsageError && /Missing/.test(err.message)) usage(chalk);
389
+ return;
390
+ }
391
+
392
+ // Gestionnaire de paquets : vérifié avant de télécharger quoi que ce soit
393
+ const pm = opts.pm || (has('bun') ? 'bun' : 'npm');
394
+ if (opts.pm && !opts.noInstall && !has(opts.pm)) return fail(`${opts.pm} is not installed: choose another --pm, or --no-install.`);
395
+
396
+ // 3. Modèle : choisi, téléchargé, intégrité vérifiée, extrait à part
397
+ let template;
398
+ let tpl;
399
+ try {
400
+ const chosen = await chooseTemplate(opts, { prompts, chalk, ora, registry, starter });
401
+ if (!chosen) return;
402
+ template = chosen.template;
403
+ const progress = ora(opts.from ? `Reading ${opts.from}` : `Fetching ${template.package}`).start();
404
+ try {
405
+ tpl = await fetchTemplate(opts, template, chosen.metadata, { registry });
406
+ } catch (err) {
407
+ progress.fail(chalk.redBright(`Template unavailable: ${err.message}`));
408
+ process.exitCode = 1;
409
+ return;
410
+ }
411
+ const note = { registry: ' (integrity verified)', cache: ' (cache, integrity verified)', local: ' (local archive)', folder: ' (local folder)' }[tpl.source.source] || '';
412
+ progress.succeed(`Template ${chalk.bold(tpl.from)}${chalk.grey(note)}`);
413
+ } catch (err) {
414
+ return fail(err.message);
415
+ }
416
+
417
+ // 4. Le projet et le front
418
+ const relOf = (p) => path.relative(cwd, p) || '.';
419
+ const createdRoot = mode !== 'add' && !existed;
420
+ let dev;
421
+ let workspace = false;
422
+ try {
423
+ if (mode === 'new') {
424
+ fs.mkdirSync(root, { recursive: true });
425
+ await poadInit(root);
426
+ const tplPm = typeof tpl.pkg.packageManager === 'string' && tpl.pkg.packageManager.startsWith(`${pm}@`) ? tpl.pkg.packageManager : undefined;
427
+ ws.writeJson(path.join(root, 'package.json'), ws.rootPackageJson(starter.packageName(path.basename(root)), [app], tplPm));
428
+ ws.writeStartScript(root);
429
+ if (pm === 'pnpm') ws.writePnpmWorkspace(root);
430
+ workspace = true;
431
+ dev = await makeApp(appDir, tpl, { name: app, title: path.basename(root), app, pm, workspace, exclude: ws.usedPorts(root) });
432
+ } else if (mode === 'flat') {
433
+ dev = await makeApp(appDir, tpl, { name: starter.packageName(path.basename(root)), title: path.basename(root), app, pm, workspace: false, exclude: new Set(), keepPoad: true });
434
+ await poadInit(root);
435
+ } else {
436
+ const rootPkg = ws.readJson(path.join(root, 'package.json'));
437
+ workspace = Boolean(ws.workspacesOf(rootPkg)) && appDir !== root;
438
+ const config = require('../utils/config').readConfig(project.config) || {};
439
+ const title = appDir === root ? config.project_id || path.basename(root) : `${config.project_id || path.basename(root)} · ${app}`;
440
+ const name = appDir === root ? starter.packageName(config.project_id || path.basename(root)) : app;
441
+ dev = await makeApp(appDir, tpl, { name, title, app, pm, workspace, exclude: ws.usedPorts(root) });
442
+ // .gitignore du projet : celui de poad init, complété si besoin
443
+ require('../utils/git').ensureRootGitignore(root);
444
+ if (workspace) {
445
+ const reg = ws.registerApp(root, appDir, app);
446
+ if (reg.added.includes('start')) ws.writeStartScript(root);
447
+ if (reg.added.length) console.log(chalk.grey(` package.json (root): ${reg.added.join(', ')}`));
448
+ }
449
+ }
450
+ } catch (err) {
451
+ fail(`poad create failed: ${err.message}`);
452
+ // Rien ne reste d'un projet neuf raté ; un front ajouté : son dossier seulement
453
+ if (createdRoot) fs.rmSync(root, { recursive: true, force: true });
454
+ else if (mode === 'add' && appDir !== root && !existed) fs.rmSync(appDir, { recursive: true, force: true });
455
+ return;
456
+ } finally {
457
+ fs.rmSync(tpl.work, { recursive: true, force: true });
458
+ }
459
+
460
+ // 5. Dépendances : à la racine d'un espace de travail (bun workspaces), sinon dans le front
461
+ let installed = false;
462
+ if (!opts.noInstall) installed = await install(pm, workspace ? root : appDir, { chalk, ora });
463
+
464
+ // 6. git : un dépôt à la racine pour un projet neuf ; rien pour un front ajouté
465
+ if (!opts.noGit && mode !== 'add') gitCommit(root, `Initial commit from ${tpl.from} (poad create)`, chalk);
466
+
467
+ // 7. La suite
468
+ const start = pm === 'npm' ? 'npm start' : `${pm} start`;
469
+ const runScript = (s) => (pm === 'npm' ? `npm run ${s}` : `${pm} run ${s}`);
470
+ const url = dev.url ? ` on ${dev.url}` : '';
471
+ console.log(' ');
472
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(createdTitle(template, dev))} in ${chalk.cyanBright(relOf(appDir))}${app ? chalk.grey(` (application "${app}")`) : ''}`);
473
+ console.log(' ');
474
+ if (mode === 'new') {
475
+ console.log(` ${chalk.bold(`cd ${relOf(root)} && ${start}`)}${chalk.grey(` starts the poad project, then the front-end${url}${installed ? '' : ' (installs the dependencies first)'}`)}`);
476
+ console.log(chalk.grey(` Another front-end: cd ${relOf(root)} && poad create admin --template angular (apps/admin, its own port)`));
477
+ } else if (mode === 'flat') {
478
+ console.log(` ${chalk.bold(`cd ${relOf(root)} && ${start}`)}${chalk.grey(` starts the poad project, then the front-end${url}${installed ? '' : ' (installs the dependencies first)'}`)}`);
479
+ } else {
480
+ const fromRoot = relOf(root);
481
+ if (workspace) console.log(` ${chalk.bold(`${fromRoot === '.' ? '' : `cd ${fromRoot} && `}${start}`)}${chalk.grey(' poad, then every front-end')} ${chalk.bold(runScript(`start:${app}`))}${chalk.grey(` this one only${dev.url ? `, ${dev.url}` : ''}`)}`);
482
+ else console.log(` ${chalk.bold(`${relOf(appDir) === '.' ? '' : `cd ${relOf(appDir)} && `}${start}`)}${chalk.grey(` starts the poad project, then the front-end${url}`)}`);
483
+ const locks = workspace ? Object.values(starter.LOCKFILES).flat().filter((f) => fs.existsSync(path.join(root, f))) : [];
484
+ const files = [path.relative(root, appDir) || '.', ...(workspace ? ['package.json', ...locks] : [])].join(' ');
485
+ console.log(chalk.grey(` Nothing committed: git add ${files} && git commit -m "Front-end ${app}"`));
486
+ if (!workspace && apps.some((a) => a.dir === root)) console.log(chalk.yellowBright(` The project root is itself a front-end (former layout): its tsconfig may need "exclude": ["${path.relative(root, appDir).split(path.sep)[0]}"].`));
487
+ }
488
+ if (app && dev.appEnv) console.log(chalk.grey(` Public variables of this front-end only: PUBLIC_* with application "${app}" (console, Variables).`));
489
+ if (mode !== 'add') console.log(chalk.grey(' poad setup: choose the services started with the project (Keycloak, Valkey, e-mails).'));
490
+ console.log(' ');
491
+ }
492
+
493
+ module.exports = async (_parsed, raw = []) => {
494
+ const chalk = require('chalk-v2');
495
+ let opts;
496
+ try {
497
+ opts = parseCreateArgs(raw);
498
+ } catch (err) {
499
+ process.exitCode = 1;
500
+ console.log(chalk.redBright(` ${err.message}`));
501
+ return usage(chalk);
502
+ }
503
+ if (opts.help) return usage(chalk);
504
+ return create(opts);
505
+ };
506
+
507
+ module.exports.help = () => usage(require('chalk-v2'));
508
+ module.exports.create = create;
509
+ module.exports.parseCreateArgs = parseCreateArgs;
510
+ module.exports.createdTitle = createdTitle;
511
+ module.exports.checkTarget = checkTarget;
512
+ module.exports.modeOf = modeOf;
513
+ module.exports.UsageError = UsageError;
package/global/init.js CHANGED
@@ -7,7 +7,11 @@
7
7
  // .gitignore à la racine (fichiers des systèmes, éditeurs, dépendances,
8
8
  // secrets), puis git init si git est installé et que le
9
9
  // dossier n'est pas déjà dans un dépôt (aucun commit)
10
- module.exports = async () => {
10
+ //
11
+ // Appelé par poad create avec options : { git: false } (le .gitignore seulement,
12
+ // poad create s'occupe du dépôt), { setup: false } (pas de question sur les
13
+ // services). Renvoie { initialized, repo } (repo : résultat de setupRepo).
14
+ module.exports = async (args = {}, raw, options = {}) => {
11
15
  const path = require('path');
12
16
  const fs = require('fs');
13
17
  const { findFreePorts } = require('../utils/ports');
@@ -19,7 +23,10 @@ module.exports = async () => {
19
23
 
20
24
  const dir = path.join(process.cwd(), 'poad');
21
25
  const root = path.join(dir, 'config.toml');
22
- if (fs.existsSync(root)) return console.log(chalk.bold('\n ✅ Your project has already been initialized'));
26
+ if (fs.existsSync(root)) {
27
+ console.log(chalk.bold('\n ✅ Your project has already been initialized'));
28
+ return { initialized: false };
29
+ }
23
30
 
24
31
  fs.mkdirSync(path.join(dir, 'data'), { recursive: true });
25
32
  const ports = await findFreePorts(3);
@@ -48,7 +55,8 @@ module.exports = async () => {
48
55
  console.log(chalk.grey(' poad/config.toml and poad/migrations/ are versioned; poad/secrets.toml and poad/data/ stay on this machine.'));
49
56
 
50
57
  // Dépôt git : les migrations suivent les branches
51
- const repo = require('../utils/git').setupRepo(process.cwd());
58
+ const git = require('../utils/git');
59
+ const repo = options.git === false ? { gitignore: git.ensureRootGitignore(process.cwd()), repo: 'skipped' } : git.setupRepo(process.cwd());
52
60
  if (repo.gitignore) console.log(chalk.grey(` .gitignore: ${repo.gitignore} entries (macOS, Windows, Linux, editors, dependencies, poad secrets).`));
53
61
  if (repo.repo === 'created') console.log(chalk.grey(' git repository created (branch main, nothing committed yet).'));
54
62
  else if (repo.repo === 'existing') console.log(chalk.grey(` Already in the git repository ${path.relative(process.cwd(), repo.root) || '.'}: left as is.`));
@@ -56,11 +64,15 @@ module.exports = async () => {
56
64
  else if (repo.repo === 'failed') console.log(chalk.yellowBright(` git init failed: ${repo.error}`));
57
65
 
58
66
  // Dans un terminal : on enchaîne sur le choix des services (poad setup)
59
- if (process.stdin.isTTY && process.stdout.isTTY) {
67
+ if (options.setup !== false && process.stdin.isTTY && process.stdout.isTTY) {
60
68
  const { confirm } = require('@inquirer/prompts');
61
69
  console.log(' ');
62
70
  const go = await confirm({ message: 'Choose the services started with the project now (Keycloak, Valkey, e-mails)?', default: true }).catch(() => false);
63
- if (go) return require('../project/setup')({});
71
+ if (go) {
72
+ await require('../project/setup')({});
73
+ return { initialized: true, repo };
74
+ }
64
75
  console.log(chalk.grey(' Later: "poad setup".'));
65
76
  }
77
+ return { initialized: true, repo };
66
78
  };
package/global/run.js CHANGED
@@ -33,14 +33,7 @@ module.exports = async (args = {}) => {
33
33
  if (!quiet) console.log(' ');
34
34
  if (listed && !wanted.length) return;
35
35
  if (!all && !wanted.length) {
36
- console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad run <service>')}`);
37
- console.log(' ');
38
- console.log(` ${chalk.cyanBright('keycloak')} ${chalk.grey('(or kc)')} Local Keycloak, registered as the "keycloak" OIDC provider`);
39
- console.log(` ${chalk.cyanBright('valkey')} ${chalk.grey('(or redis)')} Local Valkey (Redis compatible), REDIS_URL of the engine`);
40
- console.log(` ${chalk.cyanBright('runner')} Flows runner (engine 0.18.0+, needs Valkey): starts the container steps of the flows, gets the Docker socket`);
41
- console.log(` ${chalk.cyanBright('--all')} ${chalk.grey('(or all)')} The project if stopped, then every service configured in config.toml`);
42
- console.log(' ');
43
- return;
36
+ return help();
44
37
  }
45
38
 
46
39
  const root = findPoadDir(process.cwd());
@@ -190,7 +183,7 @@ module.exports = async (args = {}) => {
190
183
  const info = {
191
184
  'Keycloak URL': base,
192
185
  Issuer: `${base}/realms/${project.realm}`,
193
- 'Admin console': `${base}/admin (admin ${secrets.admin_password})`,
186
+ 'Admin console': `${base}/admin (admin ${require('../utils/report').secretValue(secrets.admin_password)})`,
194
187
  Provider: `"${kc.PROVIDER}" (signInWithOAuth({ provider: '${kc.PROVIDER}' }))`,
195
188
  'Test users': project.users.map(
196
189
  (u) => `${u.username.padEnd(6)} ${u.password} ${u.email}${u.roles.length ? ` [${u.roles.join(', ')}]` : ''}${u.emailVerified ? '' : ' (email not verified)'}`
@@ -229,7 +222,7 @@ module.exports = async (args = {}) => {
229
222
  prettyoutput({
230
223
  'Keycloak URL': `${base} (shared by the local projects)`,
231
224
  Issuer: `${base}/realms/${realm}`,
232
- 'Admin console': `${base}/admin (admin ${state.admin_password})`,
225
+ 'Admin console': `${base}/admin (admin ${require('../utils/report').secretValue(state.admin_password)})`,
233
226
  Provider: `"${kc.PROVIDER}" (signInWithOAuth({ provider: '${kc.PROVIDER}' }))`,
234
227
  'Test users': project.users.map(
235
228
  (u) => `${u.username.padEnd(6)} ${u.password} ${u.email}${u.roles.length ? ` [${u.roles.join(', ')}]` : ''}${u.emailVerified ? '' : ' (email not verified)'}`
@@ -398,3 +391,17 @@ module.exports = async (args = {}) => {
398
391
  }
399
392
  }
400
393
  };
394
+
395
+ /** poad run sans service, ou poad run --help */
396
+ function help() {
397
+ const chalk = require('chalk-v2');
398
+ console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad run <service>')}`);
399
+ console.log(' ');
400
+ console.log(` ${chalk.cyanBright('keycloak')} ${chalk.grey('(or kc)')} Local Keycloak, registered as the "keycloak" OIDC provider`);
401
+ console.log(` ${chalk.cyanBright('valkey')} ${chalk.grey('(or redis)')} Local Valkey (Redis compatible), REDIS_URL of the engine`);
402
+ console.log(` ${chalk.cyanBright('runner')} Flows runner (engine 0.18.0+, needs Valkey): starts the container steps of the flows, gets the Docker socket`);
403
+ console.log(` ${chalk.cyanBright('--all')} ${chalk.grey('(or all)')} The project if stopped, then every service configured in config.toml`);
404
+ console.log(' ');
405
+ }
406
+
407
+ module.exports.help = help;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.38.0",
3
+ "version": "2.40.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.2.0",
6
6
  "main": "index.js",
@@ -9,7 +9,9 @@
9
9
  "poad": "poad.js"
10
10
  },
11
11
  "scripts": {
12
- "build": "bun install"
12
+ "build": "bun install",
13
+ "test": "node --test test/*.test.js",
14
+ "test:e2e": "POAD_E2E=1 node --test test/create.e2e.test.js"
13
15
  },
14
16
  "dependencies": {
15
17
  "@inquirer/prompts": "^7.10.1",