poad 2.39.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,7 @@
9
9
  module.exports = {
10
10
  install: `Install poad environment`,
11
11
  init: `Init poad project`,
12
- create: 'Create an application wired to poad in a new folder: create <dir> --template angular|next|nuxt|vanilla (asked if omitted), --yes, --no-install, --no-git, --pm bun|npm|pnpm. Template from npm (integrity checked), then poad init, dependencies, first git commit (create --help)',
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
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',
14
14
  stop: 'Stop container for poad local development (stop kc|valkey|runner: that service only)',
15
15
  run: 'Run an optional service next to the project (keycloak|kc, valkey|redis, runner, --all)',
package/global/create.js CHANGED
@@ -1,37 +1,48 @@
1
- // poad create [dir] [--template angular|next|nuxt|vanilla] [--yes] [--no-install] [--no-git] [--pm bun|npm|pnpm]
1
+ // poad create : un projet poad et ses fronts.
2
2
  //
3
- // Crée une application branchée sur poad dans un dossier neuf (ou vide) :
4
- // 1. modèle @poadio/starter-<template>, dernière version du registre npm :
5
- // archive téléchargée en HTTPS, intégrité sha512 vérifiée, extraite sans
6
- // dépendance (utils/tar : ni chemin absolu, ni « .. », ni lien) ;
7
- // 2. .gitignore rétabli, fichiers de publication retirés, package.json
8
- // réécrit (nom du dossier, 0.1.0, private) ;
9
- // 3. poad init dans le dossier (poad/config.toml, secrets, migrations) ;
10
- // 4. dépendances installées (bun s'il est là, sinon npm), sauf --no-install ;
11
- // 5. git init et premier commit, sauf --no-git.
12
- // Ensuite : cd <dir> && bun start (démarre poad puis le front).
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.
13
10
  //
14
- // Options aussi au format du CLI : template=next pm=npm. --from=<archive.tgz> :
15
- // un modèle local (npm pack), pour mettre au point un nouveau modèle.
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.
16
26
  const fs = require('fs');
27
+ const os = require('os');
17
28
  const path = require('path');
18
29
  const { spawn, spawnSync } = require('child_process');
19
30
 
20
31
  const PMS = ['bun', 'npm', 'pnpm'];
21
- const VALUED = ['template', 'pm', 'from'];
22
- const FLAGS = { yes: 'yes', y: 'yes', 'no-install': 'noInstall', 'no-git': 'noGit', help: 'help', h: 'help' };
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' };
23
34
 
24
35
  class UsageError extends Error {}
25
36
 
26
- /** Arguments tels que tapés -> { dir, template, pm, from, yes, noInstall, noGit, help } */
37
+ /** Arguments tels que tapés -> { name, template, pm, from, app, dir, yes, noInstall, noGit, flat, help } */
27
38
  function parseCreateArgs(raw = []) {
28
- const opts = { dir: null, template: null, pm: null, from: null, yes: false, noInstall: false, noGit: false, help: false };
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 };
29
40
  for (let i = 0; i < raw.length; i++) {
30
41
  const arg = String(raw[i]);
31
42
  const m = /^--?([a-z][a-z-]*)(?:=(.*))?$/.exec(arg) || /^([a-z]+)=(.*)$/.exec(arg);
32
43
  if (!m) {
33
- if (opts.dir) throw new UsageError(`unexpected argument "${arg}" (the folder is already "${opts.dir}")`);
34
- opts.dir = arg;
44
+ if (opts.name) throw new UsageError(`unexpected argument "${arg}" (the name is already "${opts.name}")`);
45
+ opts.name = arg;
35
46
  continue;
36
47
  }
37
48
  const [, key, inline] = m;
@@ -96,191 +107,407 @@ function createdTitle(template, dev = {}) {
96
107
  return label ? `${label} application created` : 'Application created';
97
108
  }
98
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
+
99
130
  function usage(chalk) {
100
- console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad create <dir>')} ${chalk.cyan('[--template angular|next|nuxt|vanilla] [--yes] [--no-install] [--no-git] [--pm bun|npm|pnpm]')}`);
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)`);
101
136
  console.log(' ');
102
- console.log(' Creates an application wired to poad in a new folder, from the template @poadio/starter-<template> on npm,');
103
- console.log(' initialises its poad project (poad/config.toml), installs the dependencies and makes the first git commit.');
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'));
104
143
  console.log(' ');
105
- console.log(` ${chalk.cyanBright('--template')} angular, next, nuxt or vanilla (asked when omitted in a terminal; angular otherwise)`);
106
- console.log(` ${chalk.cyanBright('--yes')} no question`);
107
- console.log(` ${chalk.cyanBright('--no-install')} do not install the dependencies (bun start does it later)`);
108
- console.log(` ${chalk.cyanBright('--no-git')} no git repository, no commit`);
109
- console.log(` ${chalk.cyanBright('--pm')} bun, npm or pnpm (default: bun if installed, else npm)`);
110
- console.log(` ${chalk.cyanBright('--from')} a local template archive (npm pack), to develop a template`);
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`);
111
154
  console.log(' ');
112
- console.log(' The front-end URL shown at the end comes from the template: poad.port in its package.json (or poad.template.port),');
113
- console.log(' else the default port of its framework; Angular gets the first free port from there, written to angular.json.');
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).');
114
158
  console.log(' ');
115
159
  }
116
160
 
117
- module.exports = async (_parsed, raw = []) => {
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 } = {}) {
118
325
  const chalk = require('chalk-v2');
119
326
  const ora = require('ora');
120
327
  const registry = require('../utils/registry');
121
328
  const starter = require('../utils/starter');
122
- const { extractTgz } = require('../utils/tar');
329
+ const ws = require('../utils/workspace');
123
330
  const fail = (msg) => {
124
331
  process.exitCode = 1;
125
332
  console.log(chalk.redBright(` ${msg}`));
126
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();
127
337
 
128
- let opts;
338
+ // 1. Ce qu'on fait : projet neuf, front ajouté, ou ancienne disposition
339
+ const project = ws.findProject(cwd);
340
+ let mode;
129
341
  try {
130
- opts = parseCreateArgs(raw);
342
+ mode = modeOf(opts, project);
131
343
  } catch (err) {
132
- fail(err.message);
133
- return usage(chalk);
344
+ return fail(err.message);
134
345
  }
135
- if (opts.help) return usage(chalk);
136
- const tty = Boolean(process.stdin.isTTY && process.stdout.isTTY && !opts.yes);
137
- const prompts = tty ? require('@inquirer/prompts') : null;
346
+ if (intro) intro(mode);
138
347
 
139
- // 1. Dossier
140
- if (!opts.dir && prompts) opts.dir = await prompts.input({ message: 'Folder of the new application', default: 'my-app' }).catch(() => null);
141
- if (!opts.dir) {
142
- fail('Missing folder: poad create <dir>');
143
- return usage(chalk);
144
- }
145
- const target = path.resolve(process.cwd(), opts.dir);
146
- const rel = path.relative(process.cwd(), target) || '.';
147
- let existed;
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) : [];
148
354
  try {
149
- existed = checkTarget(target) === 'empty';
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
+ }
150
386
  } catch (err) {
151
- return fail(err.message);
387
+ fail(err.message);
388
+ if (err instanceof UsageError && /Missing/.test(err.message)) usage(chalk);
389
+ return;
152
390
  }
153
391
 
154
392
  // Gestionnaire de paquets : vérifié avant de télécharger quoi que ce soit
155
- const bun = has('bun');
156
- const pm = opts.pm || (bun ? 'bun' : 'npm');
393
+ const pm = opts.pm || (has('bun') ? 'bun' : 'npm');
157
394
  if (opts.pm && !opts.noInstall && !has(opts.pm)) return fail(`${opts.pm} is not installed: choose another --pm, or --no-install.`);
158
395
 
159
- // 2. Modèle
160
- let template = opts.template ? starter.templateByValue(opts.template) : null;
161
- if (opts.template && !template) return fail(`Unknown template "${opts.template}": ${starter.TEMPLATES.map((t) => t.value).join(', ')}.`);
162
- let metadata;
163
- if (!opts.from) {
164
- if (!template && prompts) {
165
- const spin = ora('Checking the templates on npm').start();
166
- const states = await availability(starter.TEMPLATES, registry);
167
- spin.stop();
168
- const note = { soon: 'coming soon', offline: 'offline', cached: 'offline, cached' };
169
- const choices = states.map((t) => ({
170
- value: t.value,
171
- short: t.label,
172
- name: `${t.label.padEnd(26)}${chalk.grey(t.package)}${t.state === 'cached' ? chalk.grey(` (${note.cached} ${t.cached})`) : ''}`,
173
- disabled: t.state === 'soon' || t.state === 'offline' ? note[t.state] : false,
174
- }));
175
- if (choices.every((c) => c.disabled)) return fail('No template can be fetched: the npm registry cannot be reached and nothing is cached.');
176
- const value = await prompts.select({ message: 'Template', choices }).catch(() => null);
177
- if (!value) return;
178
- template = starter.templateByValue(value);
179
- metadata = states.find((s) => s.value === value).metadata;
180
- }
181
- if (!template) {
182
- template = starter.templateByValue('angular');
183
- console.log(chalk.grey(` Template: angular (--template to choose another one).`));
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;
184
410
  }
185
- if (!metadata) metadata = await registry.packageMetadata(template.package, { timeout: 5000 });
186
- if (metadata.status === 'missing') return fail(`${template.value}: coming soon (${template.package} is not published yet).`);
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);
187
415
  }
188
416
 
189
- // 3. Téléchargement, intégrité, extraction
190
- let source;
191
- let progress = ora(opts.from ? `Reading ${opts.from}` : `Fetching ${template.package}`).start();
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;
192
422
  try {
193
- if (opts.from) {
194
- const file = path.resolve(process.cwd(), opts.from);
195
- source = { name: null, version: null, buf: fs.readFileSync(file), source: 'local' };
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);
196
435
  } else {
197
- const got = await registry.fetchLatestTarball(template.package, { metadata, timeout: 5000 });
198
- source = { name: template.package, ...got };
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
+ }
199
449
  }
200
- extractTgz(source.buf, target);
201
450
  } catch (err) {
202
- progress.fail(chalk.redBright(`Template unavailable: ${err.message}`));
203
- process.exitCode = 1;
204
- // Rien ne reste d'une extraction ratée
205
- if (!existed) fs.rmSync(target, { recursive: true, force: true });
206
- else if (fs.existsSync(target)) for (const n of fs.readdirSync(target)) if (n !== '.DS_Store') fs.rmSync(path.join(target, n), { recursive: true, force: true });
207
- return;
208
- }
209
- const tplPkg = starter.readPackage(target);
210
- if (!tplPkg) {
211
- progress.fail(chalk.redBright('Template unusable: no package.json in it.'));
212
- process.exitCode = 1;
213
- if (!existed) fs.rmSync(target, { recursive: true, force: true });
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 });
214
455
  return;
215
- }
216
- const from = `${source.name || tplPkg.name}@${source.version || tplPkg.version}`;
217
- progress.succeed(`Template ${chalk.bold(from)}${source.source === 'registry' ? chalk.grey(' (integrity verified)') : source.source === 'cache' ? chalk.grey(' (cache, integrity verified)') : chalk.grey(' (local archive)')}`);
218
-
219
- // 4. Fichiers de publication, .gitignore, package.json
220
- starter.prepareStarter(target);
221
- const name = starter.packageName(path.basename(target));
222
- const pkg = starter.rewritePackageJson(tplPkg, { name, title: path.basename(target), from });
223
- fs.writeFileSync(path.join(target, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');
224
- for (const html of ['src/index.html', 'index.html']) {
225
- const file = path.join(target, html);
226
- if (fs.existsSync(file)) fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(/<title>[^<]*<\/title>/, `<title>${path.basename(target).replace(/[<&]/g, '')}</title>`));
227
- }
228
- starter.adaptToPackageManager(target, pm);
229
- // Port et URL du front selon le framework (poad.port / poad.template.port du modèle)
230
- const dev = await starter.devServer(target, tplPkg);
231
-
232
- // 5. poad init dans le dossier (le dépôt git est fait plus bas)
233
- const cwd = process.cwd();
234
- try {
235
- process.chdir(target);
236
- await require('./init')({}, [], { git: false, setup: false });
237
- } catch (err) {
238
- return fail(`poad init failed in ${rel}: ${err.message}`);
239
456
  } finally {
240
- process.chdir(cwd);
457
+ fs.rmSync(tpl.work, { recursive: true, force: true });
241
458
  }
242
459
 
243
- // 6. Dépendances
460
+ // 5. Dépendances : à la racine d'un espace de travail (bun workspaces), sinon dans le front
244
461
  let installed = false;
245
- if (!opts.noInstall) {
246
- console.log(' ');
247
- progress = ora(`Installing the dependencies (${pm} install)`).start();
248
- const r = await run(pm, ['install'], target);
249
- if (r.ok) {
250
- installed = true;
251
- progress.succeed('Dependencies installed');
252
- } else {
253
- progress.fail(chalk.yellowBright(`${pm} install failed (bun start installs them too):`));
254
- console.log(chalk.grey(tail(r.output)));
255
- }
256
- }
462
+ if (!opts.noInstall) installed = await install(pm, workspace ? root : appDir, { chalk, ora });
257
463
 
258
- // 7. Dépôt git et premier commit
259
- if (!opts.noGit) {
260
- const git = require('../utils/git');
261
- const repo = git.setupRepo(target);
262
- if (repo.repo === 'created') {
263
- const add = spawnSync('git', ['add', '-A'], { cwd: target, encoding: 'utf8' });
264
- const commit = add.status === 0 ? spawnSync('git', ['commit', '-q', '-m', `Initial commit from ${from} (poad create)`], { cwd: target, encoding: 'utf8' }) : add;
265
- if (commit.status === 0) console.log(chalk.grey(' git repository created, first commit done (branch main).'));
266
- else console.log(chalk.yellowBright(` git repository created, but the first commit failed: ${(commit.stderr || commit.stdout).trim().split('\n').pop()}`));
267
- } else if (repo.repo === 'existing') console.log(chalk.grey(` Inside the git repository ${repo.root}: no new repository, nothing committed.`));
268
- else if (repo.repo === 'no-git') console.log(chalk.yellowBright(' git is not installed: no repository created.'));
269
- else if (repo.repo === 'failed') console.log(chalk.yellowBright(` git init failed: ${repo.error}`));
270
- }
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);
271
466
 
272
- // 8. La suite
467
+ // 7. La suite
273
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}` : '';
274
471
  console.log(' ');
275
- console.log(`${chalk.greenBright('✔')} ${chalk.bold(createdTitle(template, dev))} in ${chalk.cyanBright(rel)}`);
472
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(createdTitle(template, dev))} in ${chalk.cyanBright(relOf(appDir))}${app ? chalk.grey(` (application "${app}")`) : ''}`);
276
473
  console.log(' ');
277
- console.log(` ${chalk.bold(`cd ${rel} && ${start}`)}${chalk.grey(` starts the poad project, then the front-end${dev.url ? ` on ${dev.url}` : ''}${installed ? '' : ' (installs the dependencies first)'}`)}`);
278
- console.log(chalk.grey(' poad setup: choose the services started with the project (Keycloak, Valkey, e-mails).'));
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).'));
279
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);
280
505
  };
281
506
 
282
507
  module.exports.help = () => usage(require('chalk-v2'));
508
+ module.exports.create = create;
283
509
  module.exports.parseCreateArgs = parseCreateArgs;
284
510
  module.exports.createdTitle = createdTitle;
285
511
  module.exports.checkTarget = checkTarget;
512
+ module.exports.modeOf = modeOf;
286
513
  module.exports.UsageError = UsageError;