@egen-civitas/egen 2.0.5 → 2.1.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @egen-civitas/egen
2
2
 
3
+ ## 2.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - e8ccb0f: Hub de logs : niveaux plus justes (pluriels « errors/warnings », succès resserré, stderr sans indice = info), lignes de suite d'un bloc d'erreur/avertissement héritant du niveau, retours chariot (barres de progression) réduits à leur dernier état, couleurs ANSI conservées chez les processus fils, ids croissants entre redémarrages (reprise SSE fiable).
8
+ - @egen-civitas/esm-app-shell@2.6.2
9
+
10
+ ## 2.1.0
11
+
12
+ ### Minor Changes
13
+
14
+ - ac88343: `egen develop` : hub de logs du terminal. Toute la sortie (processus principal, serveur de dev de chaque app, processus `develop`) est structurée (source, niveau, horodatage, ANSI conservé) et diffusée en temps réel (SSE) sur `<spaPath>/__egen_logs__/stream` (+ `/history`, `/health`), exposée au navigateur via `window.egenLogsUrl`. Écoute locale uniquement (127.0.0.1), absente en production.
15
+
16
+ ### Patch Changes
17
+
18
+ - Updated dependencies [0978f93]
19
+ - @egen-civitas/esm-app-shell@2.6.1
20
+
3
21
  ## 2.0.5
4
22
 
5
23
  ### Patch Changes
package/dist/cli.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,OAAc,EAAE,KAAK,IAAI,EAAE,MAAM,OAAO,CAAC;AAiDzC,wBAAgB,QAAQ,CAAC,CAAC,EAAE,IAAI,YAoW/B"}
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,OAAc,EAAE,KAAK,IAAI,EAAE,MAAM,OAAO,CAAC;AAsDzC,wBAAgB,QAAQ,CAAC,CAAC,EAAE,IAAI,YA6W/B"}
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import yargs from "yargs";
3
3
  import { fork } from "child_process";
4
4
  import { resolve } from "node:path";
5
- import { getAvailablePort, getImportmapAndRoutes, isPortAvailable, logFail, mergeImportmapAndRoutes, proxyImportmapAndRoutes, resolvePackages, runProject, trimEnd } from "./utils/index.js";
5
+ import { getAvailablePort, getImportmapAndRoutes, isPortAvailable, startLogHub, childColorEnv, getLogHub, logFail, mergeImportmapAndRoutes, proxyImportmapAndRoutes, resolvePackages, runProject, trimEnd } from "./utils/index.js";
6
6
  /**
7
7
  * Port explicite de l'URL du backend (ex. 8082 pour http://localhost:8082), à réserver : les serveurs de
8
8
  * dev des apps sont alloués à partir de `port + 1` et ne doivent JAMAIS prendre le port du backend, même
@@ -21,9 +21,13 @@ import { getAvailablePort, getImportmapAndRoutes, isPortAvailable, logFail, merg
21
21
  const runner = resolve(import.meta.dirname, `runner.js`);
22
22
  const root = resolve(import.meta.dirname, '..');
23
23
  function runCommand(type, args) {
24
+ const hub = type === 'runDevelop' ? getLogHub() : undefined;
24
25
  const ps = fork(runner, [], {
25
- cwd: type === 'runBuild' ? root : process.cwd()
26
+ cwd: type === 'runBuild' ? root : process.cwd(),
27
+ silent: !!hub,
28
+ env: hub ? childColorEnv() : process.env
26
29
  });
30
+ hub?.attachChild(ps, 'egen-develop');
27
31
  ps.send({
28
32
  type,
29
33
  args
@@ -135,6 +139,13 @@ export function buildCli(y) {
135
139
  const sources = deduplicated.length > 0 ? deduplicated : [
136
140
  '.'
137
141
  ];
142
+ // Hub de logs : doit démarrer avant les serveurs de dev pour capter toute leur sortie.
143
+ let logsPort;
144
+ try {
145
+ logsPort = (await startLogHub()).port;
146
+ } catch {
147
+ // pas de hub : le terminal fonctionne normalement, sans diffusion des logs
148
+ }
138
149
  const importmapAndRoutes = await getImportmapAndRoutes(args.importmap, args.routes, port);
139
150
  // Les ports du backend sont réservés : un serveur de dev d'app ne doit jamais s'y voir allouer.
140
151
  const locallyRun = await runProject(port, sources, args['use-rspack'], backendPorts(args.backend));
@@ -143,6 +154,7 @@ export function buildCli(y) {
143
154
  configFiles: args['config-file'],
144
155
  ...args,
145
156
  port,
157
+ logsPort,
146
158
  ...proxyImportmapAndRoutes(await mergeImportmapAndRoutes(importmapAndRoutes, locallyRun, args.backend, args.spaPath), args.backend, args.spaPath, // Apps started locally must never be rewritten as if they were served by the backend.
147
159
  Object.keys(locallyRun.importMap))
148
160
  });
@@ -13,6 +13,8 @@ export interface DevelopArgs {
13
13
  configFiles: Array<string>;
14
14
  addCookie: string;
15
15
  supportOffline: boolean;
16
+ /** Port local du hub de logs du terminal (voir utils/log-hub). */
17
+ logsPort?: number;
16
18
  }
17
19
  export declare function runDevelop(args: DevelopArgs, signal?: AbortSignal): Promise<void>;
18
20
  //# sourceMappingURL=develop.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"develop.d.ts","sourceRoot":"","sources":["../../src/commands/develop.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,oBAAoB,EAAE,KAAK,iBAAiB,EAAyC,MAAM,UAAU,CAAC;AAyCpH,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,OAAO,CAAC;IACd,SAAS,EAAE,oBAAoB,CAAC;IAChC,MAAM,EAAE,iBAAiB,CAAC;IAC1B,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC3C,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC1B,WAAW,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;CACzB;AAED,wBAAsB,UAAU,CAAC,IAAI,EAAE,WAAW,EAAE,MAAM,CAAC,EAAE,WAAW,iBA8MvE"}
1
+ {"version":3,"file":"develop.d.ts","sourceRoot":"","sources":["../../src/commands/develop.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,oBAAoB,EAAE,KAAK,iBAAiB,EAAyC,MAAM,UAAU,CAAC;AAyCpH,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,OAAO,CAAC;IACd,SAAS,EAAE,oBAAoB,CAAC;IAChC,MAAM,EAAE,iBAAiB,CAAC;IAC1B,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC3C,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC1B,WAAW,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;IACxB,kEAAkE;IAClE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,wBAAsB,UAAU,CAAC,IAAI,EAAE,WAAW,EAAE,MAAM,CAAC,EAAE,WAAW,iBA+NvE"}
@@ -76,7 +76,7 @@ import { logInfo, logWarn, removeTrailingSlash } from "../utils/index.js";
76
76
  }
77
77
  ];
78
78
  export async function runDevelop(args, signal) {
79
- const { backend, host, port, open, importmap, routes, watchedRoutesPaths, configUrls, configFiles, addCookie, supportOffline } = args;
79
+ const { backend, host, port, open, importmap, routes, watchedRoutesPaths, configUrls, configFiles, addCookie, supportOffline, logsPort } = args;
80
80
  const apiUrl = removeTrailingSlash(args.apiUrl);
81
81
  const spaPath = removeTrailingSlash(args.spaPath);
82
82
  const app = express();
@@ -116,6 +116,9 @@ export async function runDevelop(args, signal) {
116
116
  if (runtimeWindowOverrides.egenTenantMode && runtimeWindowOverrides.egenTenantMode !== 'off') {
117
117
  logInfo(`EGEN_TENANT_MODE=${runtimeWindowOverrides.egenTenantMode} — système multi-tenant actif.`);
118
118
  }
119
+ // URL same-origin du flux de logs du terminal, lue par l'app de logs du shell.
120
+ const logsPath = `${spaPath}/__egen_logs__`;
121
+ if (logsPort) runtimeWindowOverrides.egenLogsUrl = logsPath;
119
122
  const indexContent = readFileSync(index, 'utf8').replace(/<script>initializeSpa\([\s\S\n]*<\/script>/m, `<script>
120
123
  Object.assign(window, ${JSON.stringify(runtimeWindowOverrides)});
121
124
  initializeSpa({
@@ -139,6 +142,16 @@ export async function runDevelop(args, signal) {
139
142
  // explicitly exclude routes that we want to use other handlers for.
140
143
  //
141
144
  // express.static respects normal route declaration order.
145
+ // Flux de logs du terminal (SSE + historique) : proxy vers le hub local, avant le catch-all index.html
146
+ if (logsPort) {
147
+ app.use(logsPath, createProxyMiddleware({
148
+ target: `http://127.0.0.1:${logsPort}`,
149
+ changeOrigin: true,
150
+ pathRewrite: {
151
+ [`^${logsPath}`]: ''
152
+ }
153
+ }));
154
+ }
142
155
  // Route for custom `importmap.json` goes above static assets
143
156
  if (importmap.type === 'inline') {
144
157
  app.get(`${spaPath}/importmap.json`, (_, res)=>{
@@ -1 +1 @@
1
- {"version":3,"file":"devserver.d.ts","sourceRoot":"","sources":["../../src/utils/devserver.ts"],"names":[],"mappings":"AAGA,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,SAAgB,EAAE,SAAS,GAAE,OAAe;;;EAqB3G"}
1
+ {"version":3,"file":"devserver.d.ts","sourceRoot":"","sources":["../../src/utils/devserver.ts"],"names":[],"mappings":"AAKA,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,SAAgB,EAAE,SAAS,GAAE,OAAe;;;EAwB3G"}
@@ -1,10 +1,17 @@
1
1
  import { resolve } from "path";
2
+ import { basename } from "path";
2
3
  import { fork } from "child_process";
4
+ import { childColorEnv, getLogHub } from "./log-hub.js";
3
5
  export function startDevServer(source, port, cwd = process.cwd(), useRspack = false) {
4
6
  const runner = resolve(import.meta.dirname, 'debugger.js');
7
+ const hub = getLogHub();
8
+ // Avec le hub, la sortie du serveur de dev transite par lui (puis est réémise dans le terminal).
5
9
  const ps = fork(runner, [], {
6
- cwd
10
+ cwd,
11
+ silent: !!hub,
12
+ env: hub ? childColorEnv() : process.env
7
13
  });
14
+ hub?.attachChild(ps, basename(cwd));
8
15
  ps.send({
9
16
  source,
10
17
  port,
@@ -1,6 +1,7 @@
1
1
  export * from './config';
2
2
  export * from './helpers';
3
3
  export * from './importmap';
4
+ export * from './log-hub';
4
5
  export * from './logger';
5
6
  export * from './packages';
6
7
  export * from './port';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC;AAC3B,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC;AAC3B,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC"}
@@ -1,6 +1,7 @@
1
1
  export * from "./config.js";
2
2
  export * from "./helpers.js";
3
3
  export * from "./importmap.js";
4
+ export * from "./log-hub.js";
4
5
  export * from "./logger.js";
5
6
  export * from "./packages.js";
6
7
  export * from "./port.js";
@@ -0,0 +1,47 @@
1
+ import type { ChildProcess } from 'node:child_process';
2
+ /**
3
+ * Hub de logs du terminal `egen develop`.
4
+ *
5
+ * Il capte tout ce qui sort dans le terminal (processus principal + serveurs de dev de chaque
6
+ * app + processus `develop`), le structure (source, niveau, horodatage) et le diffuse en temps
7
+ * réel (SSE) à l'app de logs du shell. Le texte brut, couleurs ANSI comprises, est conservé.
8
+ * Le serveur n'écoute que sur 127.0.0.1 ; `egen develop` l'expose en same-origin via un proxy.
9
+ */
10
+ export type LogLevel = 'error' | 'warn' | 'success' | 'info' | 'debug';
11
+ export interface LogEntry {
12
+ id: number;
13
+ ts: number;
14
+ source: string;
15
+ level: LogLevel;
16
+ /** Ligne brute (séquences ANSI conservées). */
17
+ message: string;
18
+ }
19
+ export declare function stripAnsi(text: string): string;
20
+ /** Niveau explicite d'une ligne, ou `undefined` si rien ne l'indique (le niveau vient alors du contexte). */
21
+ export declare function detectLevel(line: string): LogLevel | undefined;
22
+ export declare class LogHub {
23
+ private entries;
24
+ private nextId;
25
+ private lastLevel;
26
+ private clients;
27
+ private partial;
28
+ private server?;
29
+ private readonly write;
30
+ push(source: string, line: string, _stream?: 'out' | 'err'): void;
31
+ /** Découpe un flux en lignes complètes (le reste attend le prochain bloc). */
32
+ ingest(source: string, chunk: string | Buffer, stream?: 'out' | 'err'): void;
33
+ /** Duplique stdout/stderr du processus courant dans le hub (le terminal reste inchangé). */
34
+ teeProcess(source: string): void;
35
+ /** Capte la sortie d'un processus fils (créé avec `silent: true`) et la réémet dans le terminal. */
36
+ attachChild(child: ChildProcess, source: string): void;
37
+ start(): Promise<number>;
38
+ }
39
+ /** Env des processus fils capturés : sortie piped = non-TTY, donc on force les couleurs si le terminal en a. */
40
+ export declare function childColorEnv(): NodeJS.ProcessEnv;
41
+ export declare function getLogHub(): LogHub | undefined;
42
+ /** Démarre (une seule fois) le hub : capte le processus courant et retourne son port local. */
43
+ export declare function startLogHub(): Promise<{
44
+ hub: LogHub;
45
+ port: number;
46
+ }>;
47
+ //# sourceMappingURL=log-hub.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-hub.d.ts","sourceRoot":"","sources":["../../src/utils/log-hub.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAEvD;;;;;;;GAOG;AACH,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,CAAC;AAEvE,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,QAAQ,CAAC;IAChB,+CAA+C;IAC/C,OAAO,EAAE,MAAM,CAAC;CACjB;AAMD,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9C;AAED,6GAA6G;AAC7G,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAQ9D;AAKD,qBAAa,MAAM;IACjB,OAAO,CAAC,OAAO,CAAkB;IAEjC,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,SAAS,CAA+B;IAChD,OAAO,CAAC,OAAO,CAA6B;IAC5C,OAAO,CAAC,OAAO,CAA6B;IAC5C,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAGpB;IAEF,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,KAAK,GAAG,KAAa;IAgBjE,8EAA8E;IAC9E,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,MAAM,GAAE,KAAK,GAAG,KAAa;IAQ5E,4FAA4F;IAC5F,UAAU,CAAC,MAAM,EAAE,MAAM;IAczB,oGAAoG;IACpG,WAAW,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM;IAW/C,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;CAyCzB;AAED,gHAAgH;AAChH,wBAAgB,aAAa,IAAI,MAAM,CAAC,UAAU,CAGjD;AAID,wBAAgB,SAAS,IAAI,MAAM,GAAG,SAAS,CAE9C;AAED,+FAA+F;AAC/F,wBAAsB,WAAW,IAAI,OAAO,CAAC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAK1E"}
@@ -0,0 +1,175 @@
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value: value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
14
+ import { createServer } from "node:http";
15
+ const MAX_ENTRIES = 5000;
16
+ // eslint-disable-next-line no-control-regex
17
+ const ANSI = /\u001b\[[0-9;]*[A-Za-z]/g;
18
+ export function stripAnsi(text) {
19
+ return text.replace(ANSI, '');
20
+ }
21
+ /** Niveau explicite d'une ligne, ou `undefined` si rien ne l'indique (le niveau vient alors du contexte). */ export function detectLevel(line) {
22
+ const text = stripAnsi(line);
23
+ if (/\b(errors?|erreurs?|fatal|failed|failure|exception|ELIFECYCLE|ERR_[A-Z_]+|TS\d{4})\b|✖|✘|^\s*at\s.+\(.+\)/i.test(text)) return 'error';
24
+ if (/\b(warn(ing)?s?|avertissements?|deprecated|deprecation)\b|⚠/i.test(text)) return 'warn';
25
+ if (/\b(success(ful(ly)?)?|succeeded|ready|done|listening at)\b|✔|✓/i.test(text)) return 'success';
26
+ if (/\b(debug|trace|verbose)\b/i.test(text)) return 'debug';
27
+ if (/^\s*<i>|\binfo\b/i.test(text)) return 'info';
28
+ return undefined;
29
+ }
30
+ /** Ligne de suite d'un bloc (indentée ou encadrée) : hérite du niveau de la ligne qui l'ouvre. */ const CONTINUATION = /^\s+\S|^\s*[│╭╰├└┌┐┘╵╷×›>|]/;
31
+ export class LogHub {
32
+ push(source, line, _stream = 'out') {
33
+ // Comme le terminal : un retour chariot réécrit la ligne (barres de progression) — seul le dernier état compte.
34
+ const message = line.replace(/\r+$/, '').split('\r').pop() ?? '';
35
+ if (stripAnsi(message).trim().length === 0) return;
36
+ const explicit = detectLevel(message);
37
+ const previous = this.lastLevel.get(source);
38
+ const inherited = !explicit && CONTINUATION.test(stripAnsi(message)) && (previous === 'error' || previous === 'warn') ? previous : undefined;
39
+ const level = explicit ?? inherited ?? 'info';
40
+ this.lastLevel.set(source, level);
41
+ const entry = {
42
+ id: this.nextId++,
43
+ ts: Date.now(),
44
+ source,
45
+ level,
46
+ message
47
+ };
48
+ this.entries.push(entry);
49
+ if (this.entries.length > MAX_ENTRIES) this.entries.splice(0, this.entries.length - MAX_ENTRIES);
50
+ const frame = `id: ${entry.id}\ndata: ${JSON.stringify(entry)}\n\n`;
51
+ for (const client of this.clients)client.write(frame);
52
+ }
53
+ /** Découpe un flux en lignes complètes (le reste attend le prochain bloc). */ ingest(source, chunk, stream = 'out') {
54
+ const key = `${source}:${stream}`;
55
+ const text = (this.partial.get(key) ?? '') + chunk.toString();
56
+ const lines = text.split('\n');
57
+ this.partial.set(key, lines.pop() ?? '');
58
+ for (const line of lines)this.push(source, line, stream);
59
+ }
60
+ /** Duplique stdout/stderr du processus courant dans le hub (le terminal reste inchangé). */ teeProcess(source) {
61
+ for (const [name, stream] of [
62
+ [
63
+ 'out',
64
+ process.stdout
65
+ ],
66
+ [
67
+ 'err',
68
+ process.stderr
69
+ ]
70
+ ]){
71
+ const original = this.write[name];
72
+ stream.write = (chunk, ...rest)=>{
73
+ try {
74
+ this.ingest(source, typeof chunk === 'string' ? chunk : Buffer.from(chunk), name);
75
+ } catch {
76
+ // le hub ne doit jamais casser la sortie du terminal
77
+ }
78
+ return original(chunk, ...rest);
79
+ };
80
+ }
81
+ }
82
+ /** Capte la sortie d'un processus fils (créé avec `silent: true`) et la réémet dans le terminal. */ attachChild(child, source) {
83
+ child.stdout?.on('data', (data)=>{
84
+ this.write.out(data);
85
+ this.ingest(source, data, 'out');
86
+ });
87
+ child.stderr?.on('data', (data)=>{
88
+ this.write.err(data);
89
+ this.ingest(source, data, 'err');
90
+ });
91
+ }
92
+ start() {
93
+ if (this.server?.listening) return Promise.resolve(this.server.address().port);
94
+ this.server = createServer((req, res)=>{
95
+ const path = (req.url ?? '/').split('?')[0].replace(/\/+$/, '');
96
+ if (path === '/health') {
97
+ res.writeHead(200, {
98
+ 'Content-Type': 'application/json',
99
+ 'Cache-Control': 'no-store'
100
+ });
101
+ res.end(JSON.stringify({
102
+ ok: true,
103
+ entries: this.entries.length
104
+ }));
105
+ } else if (path === '/history') {
106
+ res.writeHead(200, {
107
+ 'Content-Type': 'application/json',
108
+ 'Cache-Control': 'no-store'
109
+ });
110
+ res.end(JSON.stringify(this.entries));
111
+ } else if (path === '/stream') {
112
+ res.writeHead(200, {
113
+ 'Content-Type': 'text/event-stream',
114
+ 'Cache-Control': 'no-store',
115
+ Connection: 'keep-alive',
116
+ 'X-Accel-Buffering': 'no'
117
+ });
118
+ res.write(': connected\n\n'); // envoie les en-têtes tout de suite (onopen côté navigateur)
119
+ // Reprise après coupure : seules les entrées manquantes sont renvoyées.
120
+ const last = Number(req.headers['last-event-id'] ?? 0) || 0;
121
+ for (const entry of this.entries){
122
+ if (entry.id > last) res.write(`id: ${entry.id}\ndata: ${JSON.stringify(entry)}\n\n`);
123
+ }
124
+ this.clients.add(res);
125
+ const ping = setInterval(()=>res.write(': ping\n\n'), 15000);
126
+ req.on('close', ()=>{
127
+ clearInterval(ping);
128
+ this.clients.delete(res);
129
+ });
130
+ } else {
131
+ res.writeHead(404).end();
132
+ }
133
+ });
134
+ return new Promise((resolve, reject)=>{
135
+ this.server.once('error', reject);
136
+ this.server.listen(0, '127.0.0.1', ()=>{
137
+ this.server.unref();
138
+ resolve(this.server.address().port);
139
+ });
140
+ });
141
+ }
142
+ constructor(){
143
+ _define_property(this, "entries", []);
144
+ // Base horaire : les ids restent croissants d'un redémarrage à l'autre (reprise SSE par Last-Event-ID sans trou ni doublon).
145
+ _define_property(this, "nextId", Date.now() * 1000);
146
+ _define_property(this, "lastLevel", new Map());
147
+ _define_property(this, "clients", new Set());
148
+ _define_property(this, "partial", new Map());
149
+ _define_property(this, "server", void 0);
150
+ _define_property(this, "write", {
151
+ out: process.stdout.write.bind(process.stdout),
152
+ err: process.stderr.write.bind(process.stderr)
153
+ });
154
+ }
155
+ }
156
+ /** Env des processus fils capturés : sortie piped = non-TTY, donc on force les couleurs si le terminal en a. */ export function childColorEnv() {
157
+ const color = process.stdout.isTTY && !process.env.NO_COLOR;
158
+ return color ? {
159
+ ...process.env,
160
+ FORCE_COLOR: process.env.FORCE_COLOR ?? '1'
161
+ } : process.env;
162
+ }
163
+ let hub;
164
+ export function getLogHub() {
165
+ return hub;
166
+ }
167
+ /** Démarre (une seule fois) le hub : capte le processus courant et retourne son port local. */ export async function startLogHub() {
168
+ hub ?? (hub = new LogHub());
169
+ const port = await hub.start();
170
+ hub.teeProcess('egen');
171
+ return {
172
+ hub,
173
+ port
174
+ };
175
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egen-civitas/egen",
3
- "version": "2.0.5",
3
+ "version": "2.1.1",
4
4
  "license": "MPL-2.0",
5
5
  "main": "dist/index.js",
6
6
  "files": [
@@ -60,7 +60,7 @@
60
60
  ],
61
61
  "homepage": "https://github.com/amourgit/Frontend-esm-framework/tree/main/packages/tooling/egen#readme",
62
62
  "dependencies": {
63
- "@egen-civitas/esm-app-shell": "^2.0.1",
63
+ "@egen-civitas/esm-app-shell": "^2.6.2",
64
64
  "@egen-civitas/rspack-config": "^1.1.0",
65
65
  "@egen-civitas/webpack-config": "^1.0.0",
66
66
  "@inquirer/prompts": "8.3.2",