@poadio/starter-angular 0.0.0-stage → 0.2.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.
Files changed (53) hide show
  1. package/.dockerignore +9 -0
  2. package/.env.example +7 -0
  3. package/Dockerfile +20 -0
  4. package/README.md +91 -2
  5. package/angular.json +119 -0
  6. package/bun.lock +1057 -0
  7. package/docker/40-env-json.sh +39 -0
  8. package/docker/nginx.conf +24 -0
  9. package/package.json +86 -4
  10. package/public/logo.svg +1 -0
  11. package/public/providers/google.svg +1 -0
  12. package/public/providers/keycloak.svg +1 -0
  13. package/scripts/dev.mjs +30 -0
  14. package/scripts/env.mjs +96 -0
  15. package/scripts/routes.mjs +155 -0
  16. package/src/app/app.config.ts +16 -0
  17. package/src/app/app.meta.ts +43 -0
  18. package/src/app/app.routes.gen.ts +7 -0
  19. package/src/app/app.routes.ts +32 -0
  20. package/src/app/app.ts +17 -0
  21. package/src/app/core/auth.service.ts +117 -0
  22. package/src/app/core/captcha.ts +94 -0
  23. package/src/app/core/config.ts +17 -0
  24. package/src/app/core/env.ts +27 -0
  25. package/src/app/core/guards.ts +33 -0
  26. package/src/app/core/messages.ts +38 -0
  27. package/src/app/core/poad.ts +46 -0
  28. package/src/app/core/providers.ts +32 -0
  29. package/src/app/core/theme.service.ts +37 -0
  30. package/src/app/layout/_layout.scss +799 -0
  31. package/src/app/layout/app-layout.ts +263 -0
  32. package/src/app/layout/app-menu.ts +68 -0
  33. package/src/app/layout/app-menuitem.ts +105 -0
  34. package/src/app/layout/brand.ts +50 -0
  35. package/src/app/layout/canvas-head.ts +78 -0
  36. package/src/app/layout/layout.service.ts +159 -0
  37. package/src/app/pages/(auth)/login.html +128 -0
  38. package/src/app/pages/(auth)/login.ts +194 -0
  39. package/src/app/pages/(auth)/mfa.ts +61 -0
  40. package/src/app/pages/(auth)/reset.ts +53 -0
  41. package/src/app/pages/app/_layout.ts +5 -0
  42. package/src/app/pages/app/account.html +233 -0
  43. package/src/app/pages/app/account.ts +262 -0
  44. package/src/app/pages/app/hello/[name].ts +35 -0
  45. package/src/app/pages/app/index.ts +82 -0
  46. package/src/app/pages/app/public.ts +33 -0
  47. package/src/app/pages/index.ts +280 -0
  48. package/src/app/pages/setup.ts +51 -0
  49. package/src/index.html +13 -0
  50. package/src/main.ts +9 -0
  51. package/src/styles.scss +151 -0
  52. package/tsconfig.app.json +15 -0
  53. package/tsconfig.json +31 -0
@@ -0,0 +1,39 @@
1
+ #!/bin/sh
2
+ # Lancé par l'entrypoint de l'image nginx avant le démarrage du serveur :
3
+ # écrit env.json à partir des variables du conteneur. Seules passent les
4
+ # variables PUBLIC_* et POAD_URL, POAD_ANON_KEY, POAD_MAIL_URL (même règle que
5
+ # scripts/env.mjs) ; les autres ne sont jamais servies au navigateur.
6
+ set -eu
7
+ out="${ENV_JSON_PATH:-/usr/share/nginx/html/env.json}"
8
+
9
+ awk '
10
+ # Échappement JSON caractère par caractère : gsub traite les « \\ » de
11
+ # remplacement différemment selon les awk (busybox, gawk, mawk)
12
+ function esc(v, i, c, o) {
13
+ o = ""
14
+ for (i = 1; i <= length(v); i++) {
15
+ c = substr(v, i, 1)
16
+ if (c == "\\") o = o "\\\\"
17
+ else if (c == "\"") o = o "\\\""
18
+ else if (c == "\n") o = o "\\n"
19
+ else if (c == "\r") o = o "\\r"
20
+ else if (c == "\t") o = o "\\t"
21
+ else o = o c
22
+ }
23
+ return o
24
+ }
25
+ BEGIN {
26
+ n = 0
27
+ printf "{"
28
+ for (k in ENVIRON) {
29
+ if (k ~ /^PUBLIC_[A-Za-z0-9_]+$/ || k == "POAD_URL" || k == "POAD_ANON_KEY" || k == "POAD_MAIL_URL") {
30
+ printf "%s\n \"%s\": \"%s\"", (n++ ? "," : ""), k, esc(ENVIRON[k])
31
+ }
32
+ }
33
+ printf "%s}\n", (n ? "\n" : "")
34
+ }' > "$out"
35
+
36
+ echo "env.json : $(grep -o '"[A-Z0-9_]*":' "$out" | tr -d '":' | tr '\n' ' ')"
37
+ if ! grep -q '"POAD_URL"' "$out" || ! grep -q '"POAD_ANON_KEY"' "$out"; then
38
+ echo "attention : POAD_URL ou POAD_ANON_KEY manquant, l'application affichera sa page de configuration" >&2
39
+ fi
@@ -0,0 +1,24 @@
1
+ server {
2
+ listen 80;
3
+ server_name _;
4
+ root /usr/share/nginx/html;
5
+
6
+ # Application monopage : toute route inconnue sert index.html
7
+ location / {
8
+ try_files $uri $uri/ /index.html;
9
+ }
10
+
11
+ # Relus à chaque chargement : la config du conteneur et le point d'entrée
12
+ location = /env.json {
13
+ add_header Cache-Control "no-store";
14
+ }
15
+ location = /index.html {
16
+ add_header Cache-Control "no-cache";
17
+ }
18
+
19
+ # Fichiers compilés, nommés par leur empreinte : cache long
20
+ location ~* \.(?:js|css|woff2?|png|jpe?g|svg|ico)$ {
21
+ add_header Cache-Control "public, max-age=31536000, immutable";
22
+ try_files $uri =404;
23
+ }
24
+ }
package/package.json CHANGED
@@ -1,6 +1,88 @@
1
1
  {
2
2
  "name": "@poadio/starter-angular",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "title": "Mon application",
4
+ "description": "Application Angular branchée sur poad : connexion, compte, cadre d’application (poad client init)",
5
+ "version": "0.2.0",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/poadio/starter-angular.git"
10
+ },
11
+ "scripts": {
12
+ "ng": "ng",
13
+ "start": "node scripts/dev.mjs",
14
+ "build": "node scripts/routes.mjs && ng build",
15
+ "watch": "node scripts/routes.mjs && ng build --watch --configuration development",
16
+ "env": "node scripts/env.mjs",
17
+ "routes": "node scripts/routes.mjs",
18
+ "prepare": "node scripts/routes.mjs"
19
+ },
20
+ "files": [
21
+ "src",
22
+ "public",
23
+ "!public/env.json",
24
+ "scripts",
25
+ "docker",
26
+ "Dockerfile",
27
+ ".dockerignore",
28
+ ".env.example",
29
+ "angular.json",
30
+ "tsconfig.json",
31
+ "tsconfig.app.json",
32
+ "bun.lock",
33
+ "README.md"
34
+ ],
35
+ "dependencies": {
36
+ "@angular/cdk": "^21.2.14",
37
+ "@angular/common": "^21.1.0",
38
+ "@angular/compiler": "^21.1.0",
39
+ "@angular/core": "^21.1.0",
40
+ "@angular/forms": "^21.1.0",
41
+ "@angular/platform-browser": "^21.1.0",
42
+ "@angular/router": "^21.1.0",
43
+ "@cadriciel/ui": "^0.10.0",
44
+ "@poadio/client-js": "^0.3.1",
45
+ "rxjs": "~7.8.0",
46
+ "tslib": "^2.3.0"
47
+ },
48
+ "devDependencies": {
49
+ "@angular/build": "^21.1.1",
50
+ "@angular/cli": "^21.1.1",
51
+ "@angular/compiler-cli": "^21.1.0",
52
+ "typescript": "~5.9.2"
53
+ },
54
+ "prettier": {
55
+ "printWidth": 120,
56
+ "singleQuote": true,
57
+ "overrides": [
58
+ {
59
+ "files": "*.html",
60
+ "options": {
61
+ "parser": "angular"
62
+ }
63
+ }
64
+ ]
65
+ },
66
+ "poad": {
67
+ "routing": "classic",
68
+ "template": {
69
+ "framework": "angular",
70
+ "label": "Angular + @cadriciel/ui",
71
+ "port": 4300,
72
+ "gitignore": [
73
+ "/dist",
74
+ "/.angular/cache",
75
+ "/out-tsc",
76
+ "/coverage",
77
+ "/public/env.json",
78
+ "/src/app/app.routes.gen.ts",
79
+ "/public/poad.json",
80
+ "/dev/keycloak",
81
+ ".sass-cache/",
82
+ "__screenshots__/"
83
+ ],
84
+ "description": "Application Angular branchée sur poad"
85
+ }
86
+ },
87
+ "packageManager": "bun@1.4.4"
88
+ }
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#4f46e5"/><rect x="9.4" y="7" width="3.2" height="19" rx="1.6" fill="#fff"/><circle cx="17" cy="13" r="4.9" fill="none" stroke="#fff" stroke-width="3.2"/><circle cx="17" cy="13" r="1.5" fill="#fff"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"><path fill="#FFC107" d="M43.6 20.1H42V20H24v8h11.3C33.7 32.7 29.2 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 13 4 4 13 4 24s9 20 20 20 20-9 20-20c0-1.3-.1-2.6-.4-3.9z"/><path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z"/><path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.2 0-9.6-3.3-11.3-7.9l-6.5 5C9.5 39.6 16.2 44 24 44z"/><path fill="#1976D2" d="M43.6 20.1H42V20H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.2 5.2C37 39.2 44 34 44 24c0-1.3-.1-2.6-.4-3.9z"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"><path fill="#4D4D4D" d="M13 5h22l11 19-11 19H13L2 24z"/><path fill="#00B8E3" d="M17 13h3l-6 11 6 11h-3l-6-11zm14 0h-3l6 11-6 11h3l6-11z"/><circle cx="24" cy="21" r="4" fill="#fff"/><path fill="#fff" d="M22.5 23h3l1 8h-5z"/></svg>
@@ -0,0 +1,30 @@
1
+ // bun start : variables d'environnement (public/env.json), routes générées,
2
+ // puis ng serve, avec le générateur de routes en surveillance à côté.
3
+ // Les arguments sont passés à ng serve : bun start --port 4300
4
+ import { spawn } from 'node:child_process';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
9
+ const node = process.execPath;
10
+ const run = (cmd, args, opts = {}) => spawn(cmd, args, { cwd: root, stdio: 'inherit', ...opts });
11
+
12
+ const once = (script, args = []) =>
13
+ new Promise((ok, ko) => run(node, [join(root, 'scripts', script), ...args]).on('exit', (c) => (c ? ko(new Error(script)) : ok())));
14
+
15
+ await once('env.mjs', ['development']);
16
+ const routes = run(node, [join(root, 'scripts', 'routes.mjs'), '--watch']);
17
+ const ng = run(join(root, 'node_modules', '.bin', process.platform === 'win32' ? 'ng.cmd' : 'ng'), ['serve', ...process.argv.slice(2)], {
18
+ shell: process.platform === 'win32',
19
+ });
20
+
21
+ const stop = () => {
22
+ routes.kill();
23
+ ng.kill();
24
+ };
25
+ process.on('SIGINT', stop);
26
+ process.on('SIGTERM', stop);
27
+ ng.on('exit', (code) => {
28
+ routes.kill();
29
+ process.exit(code ?? 0);
30
+ });
@@ -0,0 +1,96 @@
1
+ // Variables d'environnement du front, à la Next.js : écrit public/env.json,
2
+ // lu par l'application AU DÉMARRAGE (pas compilé dedans).
3
+ //
4
+ // Fichiers lus, du moins au plus prioritaire, puis l'environnement du processus :
5
+ // .env .env.<mode> .env.local .env.<mode>.local (mode : development par défaut)
6
+ //
7
+ // Seules passent au navigateur les variables PUBLIC_* et celles du projet
8
+ // poad (POAD_URL, POAD_ANON_KEY, POAD_MAIL_URL) : le reste ne quitte pas la machine.
9
+ // Sans POAD_URL ni POAD_ANON_KEY, elles sont lues dans poad/config.toml
10
+ // (ce dossier ou un parent) : un projet poad local se branche tout seul.
11
+ //
12
+ // En production, docker/40-env-json.sh fait la même chose au démarrage du conteneur.
13
+ //
14
+ // node scripts/env.mjs [mode]
15
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
16
+ import { dirname, join, resolve } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+
19
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
20
+ const mode = process.argv[2] || process.env.NODE_ENV || 'development';
21
+ const target = join(root, 'public', 'env.json');
22
+
23
+ export const isPublic = (key) => key.startsWith('PUBLIC_') || ['POAD_URL', 'POAD_ANON_KEY', 'POAD_MAIL_URL'].includes(key);
24
+
25
+ /** Lecture d'un fichier .env : KEY=valeur, guillemets, commentaires, « export » */
26
+ function parseDotenv(text) {
27
+ const out = {};
28
+ for (const raw of text.split(/\r?\n/)) {
29
+ const line = raw.trim();
30
+ if (!line || line.startsWith('#')) continue;
31
+ const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
32
+ if (!m) continue;
33
+ let v = m[2];
34
+ const quoted = /^(['"])([\s\S]*)\1$/.exec(v);
35
+ if (quoted) v = quoted[1] === '"' ? quoted[2].replace(/\\n/g, '\n').replace(/\\"/g, '"') : quoted[2];
36
+ else v = v.replace(/\s+#.*$/, '').trim();
37
+ out[m[1]] = v;
38
+ }
39
+ return out;
40
+ }
41
+
42
+ /** Sections et clés d'un fichier TOML simple (pas de tableaux ni de multilignes) */
43
+ function parseToml(file, conf = {}) {
44
+ if (!existsSync(file)) return conf;
45
+ let section = '';
46
+ for (const raw of readFileSync(file, 'utf8').split(/\r?\n/)) {
47
+ const line = raw.replace(/#.*$/, '').trim();
48
+ const s = /^\[([^\]]+)\]$/.exec(line);
49
+ if (s) {
50
+ section = s[1].trim();
51
+ continue;
52
+ }
53
+ const kv = /^([A-Za-z0-9_.-]+)\s*=\s*"?([^"]*)"?$/.exec(line);
54
+ if (kv) (conf[section] ??= {})[kv[1]] = kv[2];
55
+ }
56
+ return conf;
57
+ }
58
+
59
+ /**
60
+ * URL, clé anon et boîte e-mail du projet poad local : poad/config.toml, et
61
+ * poad/secrets.toml pour la clé (CLI 2.12 et plus ; avant, dans config.toml)
62
+ */
63
+ function fromPoadProject() {
64
+ let dir = root;
65
+ while (!existsSync(join(dir, 'poad', 'config.toml'))) {
66
+ if (dirname(dir) === dir) return {};
67
+ dir = dirname(dir);
68
+ }
69
+ const conf = parseToml(join(dir, 'poad', 'config.toml'));
70
+ parseToml(join(dir, 'poad', 'secrets.toml'), conf);
71
+ const out = {};
72
+ if (conf.web?.port) out.POAD_URL = `http://localhost:${conf.web.port}`;
73
+ if (conf.auth?.anon) out.POAD_ANON_KEY = conf.auth.anon;
74
+ // [mail] depuis l'engine 0.7.0 (Mailpit), [inbucket] avant
75
+ const mail = conf.mail?.port ?? conf.inbucket?.port;
76
+ if (mail) out.POAD_MAIL_URL = `http://localhost:${mail}`;
77
+ return out;
78
+ }
79
+
80
+ let vars = {};
81
+ for (const name of ['.env', `.env.${mode}`, '.env.local', `.env.${mode}.local`]) {
82
+ const file = join(root, name);
83
+ if (existsSync(file)) vars = { ...vars, ...parseDotenv(readFileSync(file, 'utf8')) };
84
+ }
85
+ vars = { ...fromPoadProject(), ...vars, ...process.env };
86
+
87
+ const env = Object.fromEntries(
88
+ Object.entries(vars)
89
+ .filter(([k, v]) => isPublic(k) && v !== undefined && v !== '')
90
+ .sort(([a], [b]) => a.localeCompare(b))
91
+ );
92
+ writeFileSync(target, JSON.stringify(env, null, 2) + '\n');
93
+ console.log(`[env] public/env.json (${mode}) : ${Object.keys(env).join(', ') || 'aucune variable'}`);
94
+ if (!env.POAD_URL || !env.POAD_ANON_KEY) {
95
+ console.warn('[env] POAD_URL ou POAD_ANON_KEY manquant : `poad init` ici, ou renseignez-les dans .env.local');
96
+ }
@@ -0,0 +1,155 @@
1
+ // Routes par fichiers (mode « files », à la Next.js) : parcourt src/app/pages
2
+ // et écrit src/app/app.routes.gen.ts. Le mode se règle dans package.json :
3
+ // "poad": { "routing": "files" } ; sinon (« classic »), app.routes.ts écrit à
4
+ // la main fait foi et le fichier généré reste vide.
5
+ //
6
+ // pages/index.ts /
7
+ // pages/about.ts /about
8
+ // pages/users/[id].ts /users/:id (le paramètre arrive en input())
9
+ // pages/docs/[...slug].ts /docs/**
10
+ // pages/(auth)/login.ts /login (dossier entre parenthèses : groupe, sans segment d'URL)
11
+ // pages/app/_layout.ts cadre de toutes les pages de app/
12
+ //
13
+ // Une page exporte son composant par défaut, et ses options en littéral :
14
+ // export const route = { title: 'Mon compte', auth: true };
15
+ // Options : title ; auth (true ou { roles: [...], mfa: false }) ; guest (pages
16
+ // de connexion) ; configured (exige le projet poad configuré).
17
+ //
18
+ // node scripts/routes.mjs [--watch]
19
+ import { existsSync, readFileSync, readdirSync, statSync, watch, writeFileSync } from 'node:fs';
20
+ import { dirname, join, relative, resolve } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+
23
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
24
+ const pagesDir = join(root, 'src', 'app', 'pages');
25
+ const target = join(root, 'src', 'app', 'app.routes.gen.ts');
26
+
27
+ const routingMode = () => JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).poad?.routing ?? 'classic';
28
+
29
+ /** Littéral `export const route = {...}` d'une page, évalué (code du projet) */
30
+ function readOptions(file) {
31
+ const src = readFileSync(file, 'utf8');
32
+ const m = /export\s+const\s+route\s*(?::[^=]+)?=\s*\{/.exec(src);
33
+ if (!m) return {};
34
+ let depth = 0;
35
+ let i = m.index + m[0].length - 1;
36
+ const start = i;
37
+ for (; i < src.length; i++) {
38
+ if (src[i] === '{') depth++;
39
+ else if (src[i] === '}' && --depth === 0) break;
40
+ }
41
+ try {
42
+ return new Function(`return (${src.slice(start, i + 1)});`)() ?? {};
43
+ } catch (e) {
44
+ throw new Error(`${relative(root, file)} : options de route illisibles (${e.message})`);
45
+ }
46
+ }
47
+
48
+ /** Segment d'URL d'un nom de fichier ou de dossier */
49
+ function segment(name) {
50
+ if (name === 'index') return { path: '', rank: 0 };
51
+ if (/^\(.+\)$/.test(name)) return { path: '', rank: 1, group: true };
52
+ if (/^\[\.\.\..+\]$/.test(name)) return { path: '**', rank: 4 };
53
+ const dyn = /^\[(.+)\]$/.exec(name);
54
+ if (dyn) return { path: `:${dyn[1]}`, rank: 3 };
55
+ return { path: name, rank: 2 };
56
+ }
57
+
58
+ const q = (s) => `'${String(s).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
59
+ const importPath = (file) => './' + relative(join(root, 'src', 'app'), file).replace(/\\/g, '/').replace(/\.ts$/, '');
60
+
61
+ /** canActivate et data d'une route, d'après ses options */
62
+ function decorate(opts, guards) {
63
+ const parts = [];
64
+ const can = [];
65
+ if (opts.guest) can.push('configured', 'signedOut');
66
+ else if (opts.auth) {
67
+ const o = opts.auth === true ? {} : opts.auth;
68
+ can.push(Object.keys(o).length ? `signedIn(${JSON.stringify(o)})` : 'signedIn()');
69
+ } else if (opts.configured) can.push('configured');
70
+ can.forEach((g) => guards.add(g.replace(/\(.*$/, '')));
71
+ if (can.length) parts.push(`canActivate: [${can.join(', ')}]`);
72
+ if (opts.title) parts.push(`data: { title: ${q(opts.title)} }`);
73
+ return parts;
74
+ }
75
+
76
+ /** Routes d'un dossier, triées : statiques, groupes, dynamiques, attrape-tout */
77
+ function scan(dir, guards, indent) {
78
+ const entries = [];
79
+ for (const name of readdirSync(dir)) {
80
+ const full = join(dir, name);
81
+ if (statSync(full).isDirectory()) {
82
+ entries.push({ ...segment(name), dir: full });
83
+ } else if (name.endsWith('.ts') && !name.endsWith('.spec.ts') && !name.startsWith('_')) {
84
+ entries.push({ ...segment(name.replace(/\.ts$/, '')), file: full });
85
+ }
86
+ }
87
+ entries.sort((a, b) => a.rank - b.rank || a.path.localeCompare(b.path));
88
+
89
+ const pad = ' '.repeat(indent);
90
+ return entries.map((e) => {
91
+ if (e.file) {
92
+ const parts = [`path: ${q(e.path)}`];
93
+ if (e.path === '') parts.push(`pathMatch: 'full'`);
94
+ parts.push(...decorate(readOptions(e.file), guards));
95
+ parts.push(`loadComponent: () => import(${q(importPath(e.file))})`);
96
+ return `${pad}{ ${parts.join(', ')} }`;
97
+ }
98
+ const layout = join(e.dir, '_layout.ts');
99
+ const parts = [`path: ${q(e.path)}`];
100
+ if (existsSync(layout)) {
101
+ parts.push(...decorate(readOptions(layout), guards));
102
+ parts.push(`loadComponent: () => import(${q(importPath(layout))})`);
103
+ }
104
+ const children = scan(e.dir, guards, indent + 4);
105
+ return `${pad}{\n${pad} ${parts.join(',\n' + pad + ' ')},\n${pad} children: [\n${children.join(',\n')}\n${pad} ],\n${pad}}`;
106
+ });
107
+ }
108
+
109
+ function generate() {
110
+ // bun install avant la copie des sources (Dockerfile) : rien à générer encore
111
+ if (!existsSync(pagesDir)) return;
112
+ const mode = routingMode();
113
+ const guards = new Set();
114
+ let body = '';
115
+ if (mode === 'files') {
116
+ const routes = scan(pagesDir, guards, 2);
117
+ // Sans page attrape-tout à la racine, une URL inconnue ramène à l'accueil
118
+ if (!routes.some((r) => r.includes("path: '**'"))) routes.push(` { path: '**', redirectTo: '' }`);
119
+ body = `\n${routes.join(',\n')},\n`;
120
+ }
121
+ const imports = guards.size ? `import { ${[...guards].sort().join(', ')} } from './core/guards';\n` : '';
122
+ const out = `// Généré par scripts/routes.mjs à partir de src/app/pages : ne pas modifier.
123
+ // Mode de routage : ${mode} (package.json, "poad": { "routing": "files" | "classic" }).
124
+ import { Routes } from '@angular/router';
125
+ ${imports}
126
+ export const routing: 'files' | 'classic' = ${q(mode)};
127
+
128
+ export const fileRoutes: Routes = [${body}];
129
+ `;
130
+ const before = existsSync(target) ? readFileSync(target, 'utf8') : '';
131
+ // Réécrire à l'identique relancerait la compilation de ng serve pour rien
132
+ if (out !== before) {
133
+ writeFileSync(target, out);
134
+ console.log(`[routes] ${relative(root, target)} (${mode})`);
135
+ }
136
+ }
137
+
138
+ generate();
139
+
140
+ if (process.argv.includes('--watch')) {
141
+ let timer = null;
142
+ const again = () => {
143
+ clearTimeout(timer);
144
+ timer = setTimeout(() => {
145
+ try {
146
+ generate();
147
+ } catch (e) {
148
+ console.error(`[routes] ${e.message}`);
149
+ }
150
+ }, 120);
151
+ };
152
+ watch(pagesDir, { recursive: true }, again);
153
+ watch(join(root, 'package.json'), again);
154
+ console.log('[routes] surveille src/app/pages');
155
+ }
@@ -0,0 +1,16 @@
1
+ import { ApplicationConfig, inject, provideAppInitializer, provideBrowserGlobalErrorListeners } from '@angular/core';
2
+ import { provideRouter, withComponentInputBinding } from '@angular/router';
3
+ import { routes } from './app.routes';
4
+ import { fileRoutes, routing } from './app.routes.gen';
5
+ import { AuthService } from './core/auth.service';
6
+
7
+ export const appConfig: ApplicationConfig = {
8
+ providers: [
9
+ provideBrowserGlobalErrorListeners(),
10
+ // Routes écrites à la main, ou générées depuis src/app/pages (scripts/routes.mjs)
11
+ provideRouter(routing === 'files' ? fileRoutes : routes, withComponentInputBinding()),
12
+ // La session (et un éventuel retour de lien e-mail ou d'OAuth) est
13
+ // traitée avant la première navigation, pour que les gardes la voient
14
+ provideAppInitializer(() => inject(AuthService).init()),
15
+ ],
16
+ };
@@ -0,0 +1,43 @@
1
+ import pkg from '../../package.json';
2
+
3
+ /** Identité de l'application, tirée de package.json (title, description, version) */
4
+ export const APP = {
5
+ name: (pkg as { title?: string }).title || pkg.name,
6
+ description: (pkg as { description?: string }).description ?? '',
7
+ version: pkg.version,
8
+ };
9
+
10
+ /**
11
+ * Entrée du menu du rail. Une entrée de premier niveau sans lien et avec des
12
+ * enfants est un intitulé de groupe ; une entrée avec lien et enfants est un
13
+ * parent dépliable.
14
+ */
15
+ export interface AppMenuItem {
16
+ label: string;
17
+ icon?: string;
18
+ routerLink?: string | unknown[];
19
+ queryParams?: Record<string, unknown>;
20
+ url?: string;
21
+ target?: string;
22
+ title?: string;
23
+ badge?: string | number;
24
+ disabled?: boolean;
25
+ visible?: boolean;
26
+ items?: AppMenuItem[];
27
+ command?: (event: { item: AppMenuItem; originalEvent?: Event }) => void;
28
+ }
29
+
30
+ /** Menu de l'application */
31
+ export const MENU: AppMenuItem[] = [
32
+ {
33
+ label: 'Général',
34
+ items: [
35
+ { label: 'Tableau de bord', icon: 'layout-dashboard', routerLink: '/app' },
36
+ { label: 'Page publique', icon: 'globe', routerLink: '/app/public' },
37
+ ],
38
+ },
39
+ {
40
+ label: 'Compte',
41
+ items: [{ label: 'Mon compte', icon: 'user', routerLink: '/app/account' }],
42
+ },
43
+ ];
@@ -0,0 +1,7 @@
1
+ // Généré par scripts/routes.mjs à partir de src/app/pages : ne pas modifier.
2
+ // Mode de routage : classic (package.json, "poad": { "routing": "files" | "classic" }).
3
+ import { Routes } from '@angular/router';
4
+
5
+ export const routing: 'files' | 'classic' = 'classic';
6
+
7
+ export const fileRoutes: Routes = [];
@@ -0,0 +1,32 @@
1
+ import { Routes } from '@angular/router';
2
+ import { configured, signedIn, signedOut } from './core/guards';
3
+
4
+ /**
5
+ * Routes du mode « classic » (défaut), écrites à la main. En mode « files »
6
+ * (package.json, "poad": { "routing": "files" }), elles sont générées depuis
7
+ * l'arborescence de src/app/pages et ce fichier n'est plus lu.
8
+ * data.title donne le titre affiché en tête du canevas.
9
+ */
10
+ export const routes: Routes = [
11
+ // Hors du cadre : démarrage, connexion, étapes d'authentification
12
+ { path: '', pathMatch: 'full', loadComponent: () => import('./pages/index') },
13
+ { path: 'setup', loadComponent: () => import('./pages/setup') },
14
+ { path: 'login', canActivate: [configured, signedOut], loadComponent: () => import('./pages/(auth)/login') },
15
+ { path: 'reset', canActivate: [signedIn({ mfa: false })], loadComponent: () => import('./pages/(auth)/reset') },
16
+ { path: 'mfa', canActivate: [signedIn({ mfa: false })], loadComponent: () => import('./pages/(auth)/mfa') },
17
+
18
+ // Dans le cadre de l'application (rail + barre du haut + canevas)
19
+ {
20
+ path: 'app',
21
+ canActivate: [configured],
22
+ loadComponent: () => import('./pages/app/_layout'),
23
+ children: [
24
+ { path: '', pathMatch: 'full', data: { title: 'Tableau de bord' }, canActivate: [signedIn()], loadComponent: () => import('./pages/app/index') },
25
+ { path: 'public', data: { title: 'Page publique' }, loadComponent: () => import('./pages/app/public') },
26
+ { path: 'account', data: { title: 'Mon compte' }, canActivate: [signedIn()], loadComponent: () => import('./pages/app/account') },
27
+ { path: 'hello/:name', data: { title: 'Route dynamique' }, loadComponent: () => import('./pages/app/hello/[name]') },
28
+ // Page réservée à un rôle : canActivate: [signedIn({ roles: ['admin'] })]
29
+ ],
30
+ },
31
+ { path: '**', redirectTo: '' },
32
+ ];
package/src/app/app.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { Component, inject } from '@angular/core';
2
+ import { RouterOutlet } from '@angular/router';
3
+ import { CadToastComponent } from '@cadriciel/ui';
4
+ import { ThemeService } from './core/theme.service';
5
+
6
+ @Component({
7
+ selector: 'app-root',
8
+ imports: [RouterOutlet, CadToastComponent],
9
+ template: `
10
+ <router-outlet />
11
+ <cad-toast position="bottom-right" />
12
+ `,
13
+ })
14
+ export class App {
15
+ // Applique le thème choisi dès le démarrage
16
+ private readonly theme = inject(ThemeService);
17
+ }