@ui5/logger 5.0.0-alpha.5 → 5.0.0-alpha.7

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.
@@ -0,0 +1,639 @@
1
+ import process from "node:process";
2
+ import {createLogUpdate} from "log-update";
3
+ import sliceAnsi from "slice-ansi";
4
+ import Logger from "../loggers/Logger.js";
5
+ import {formatLogLine, prefixModuleName} from "./internal/format.js";
6
+ import {createHeaderState, setTool} from "./interactiveConsole/state/header.js";
7
+ import {
8
+ createProjectState,
9
+ setProject,
10
+ setFramework,
11
+ enableProjectPlaceholders,
12
+ setVersionResolving,
13
+ clearVersionResolving,
14
+ } from "./interactiveConsole/state/project.js";
15
+ import {createServerState, setListening, enableServerPlaceholders} from "./interactiveConsole/state/server.js";
16
+ import {
17
+ createBuildState, beginBuild, advanceToProject, setTask, transitionTo, setError, setStale, STATES,
18
+ SPINNING_STATES, enableBuildPlaceholders, setDegraded, clearDegraded,
19
+ } from "./interactiveConsole/state/build.js";
20
+ import {
21
+ renderHeaderRegion, renderProjectRegion, renderServerRegion, renderBuildRegion,
22
+ } from "./interactiveConsole/render.js";
23
+
24
+ // Spinner tick interval while in `building` or `validating` state.
25
+ const BUILDING_TICK_MS = 120;
26
+
27
+ // Module names whose info-level logs duplicate state the banner already renders
28
+ // via named build events (ui5.build-metadata / ui5.build-status). Their info
29
+ // lines are suppressed so they don't scroll above the live region. Warnings and
30
+ // errors from these modules, and all other levels, still pass through.
31
+ const BANNER_REDUNDANT_INFO_MODULES = new Set(["ProjectBuilder"]);
32
+
33
+ // DECTCEM "show cursor". log-update hides the cursor on each render; disable()
34
+ // emits this to restore it.
35
+ const CURSOR_SHOW = "[?25h";
36
+
37
+ // Signals that terminate the process while the live region is on-screen.
38
+ // SIGBREAK exists only on Windows; on other platforms the listener is inert.
39
+ const TERMINATION_SIGNALS = ["SIGHUP", "SIGINT", "SIGTERM", "SIGBREAK"];
40
+
41
+ // Decode the tail of `stream.write(chunk[, encoding][, callback])`. `encoding`
42
+ // falls back to "utf8" (Node's default) when not supplied.
43
+ function parseWriteArgs(encodingOrCallback, maybeCallback) {
44
+ if (typeof encodingOrCallback === "function") {
45
+ return {encoding: "utf8", callback: encodingOrCallback};
46
+ }
47
+ return {
48
+ encoding: typeof encodingOrCallback === "string" ? encodingOrCallback : "utf8",
49
+ callback: typeof maybeCallback === "function" ? maybeCallback : undefined,
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Interactive console writer for `ui5 serve` — a live, region-based status
55
+ * display rendered in a persistent bottom region. Owns process.stderr while
56
+ * active. Sibling of {@link module:@ui5/logger/writers/Console|writers/Console};
57
+ * exactly one console-writing writer may be active at a time.
58
+ * <br><br>
59
+ * The writer is universal: it renders whichever regions have received data.
60
+ * No command knowledge. Regions render top-to-bottom in a fixed order —
61
+ * header, root project, server, build status — and hidden regions collapse.
62
+ * <br><br>
63
+ * All state is event-driven. It reacts to process events emitted across
64
+ * <code>@ui5/logger</code> and related packages, including CLI, project,
65
+ * server, build, serve, and log events. These event shapes are internal
66
+ * cross-package contracts within the UI5 CLI codebase and should be kept
67
+ * stable for their in-repo consumers.
68
+ *
69
+ * @public
70
+ * @class
71
+ * @alias @ui5/logger/writers/InteractiveConsole
72
+ */
73
+ class InteractiveConsole {
74
+ #stderr;
75
+ #stopped = false;
76
+
77
+ #headerState;
78
+ #projectState;
79
+ #serverState;
80
+ #buildState;
81
+
82
+ #tickTimer = null;
83
+ #columns;
84
+ // `log-update` instance bound to `#stderr`. Owns the live region: every
85
+ // `#render()` call hands it the full multi-line frame and it diffs against
86
+ // the previous one, erasing wrap-correctly.
87
+ #logUpdate;
88
+
89
+ // True while a live-region render (or explicit persist/done) is in flight,
90
+ // so #interceptWrite lets log-update's own bytes through to the real
91
+ // stream. Any *other* write hits the interception path.
92
+ #renderingLiveRegion = false;
93
+ // Per-stream interception bookkeeping. Keyed by "stdout"/"stderr", each
94
+ // entry holds the saved original write method (or `null` when this stream
95
+ // is not being intercepted) and any partial (non-newline-terminated) bytes
96
+ // that arrived without a newline yet.
97
+ #streams = {
98
+ stdout: {orig: null, partial: ""},
99
+ stderr: {orig: null, partial: ""},
100
+ };
101
+
102
+ // Bound listeners so we can `process.off` them on stop().
103
+ #onLog;
104
+ #onBuildMetadata;
105
+ #onBuildStatus;
106
+ #onProjectBuildStatus;
107
+ #onServeStatus;
108
+ #onToolInfo;
109
+ #onToolMode;
110
+ #onProjectResolved;
111
+ #onProjectFrameworkResolved;
112
+ #onProjectResolving;
113
+ #onProjectResolveFailed;
114
+ #onServerListening;
115
+ #onStopConsole;
116
+ #onResize;
117
+
118
+ // Termination-signal handlers (plus an `exit` catch-all), keyed by event
119
+ // name, so disable() detaches exactly what enable() registered.
120
+ #signalHandlers = new Map();
121
+
122
+ constructor({stderr = process.stderr} = {}) {
123
+ this.#stderr = stderr;
124
+ this.#headerState = createHeaderState();
125
+ this.#projectState = createProjectState();
126
+ this.#serverState = createServerState();
127
+ this.#buildState = createBuildState();
128
+ this.#columns = stderr.columns;
129
+ }
130
+
131
+ /**
132
+ * Attaches all event listeners and starts writing to the output stream.
133
+ * Emits `ui5.log.stop-console` first so any currently-active console-
134
+ * writing writer detaches before this one takes over.
135
+ *
136
+ * @public
137
+ */
138
+ enable() {
139
+ process.emit("ui5.log.stop-console");
140
+ this.#stopped = false;
141
+ this.#attachListeners();
142
+ this.#registerSignalHandlers();
143
+ if (!this.#logUpdate) {
144
+ this.#logUpdate = createLogUpdate(this.#stderr);
145
+ }
146
+ const wantsIntercept = this.#stderr === process.stderr;
147
+ if (wantsIntercept) {
148
+ this.#installWriteInterceptors();
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Detaches all event listeners and stops writing to the output stream.
154
+ *
155
+ * @public
156
+ */
157
+ disable() {
158
+ if (this.#stopped) {
159
+ return;
160
+ }
161
+ this.#stopped = true;
162
+ this.#clearTick();
163
+ this.#detachListeners();
164
+ // Detach before the terminal teardown so a re-raised signal (see
165
+ // #handleTerminationSignal) doesn't re-enter our handler.
166
+ this.#deregisterSignalHandlers();
167
+ // Flush any partial (non-newline-terminated) buffered writes before
168
+ // we tear down the live region, then restore the process.* originals.
169
+ // Flushing first while the live region is still on-screen keeps the
170
+ // trailing fragment above the final frame instead of after it.
171
+ this.#flushPartialBuffers();
172
+ this.#uninstallWriteInterceptors();
173
+ // `done` restores the cursor (which log-update hid on first render)
174
+ // and resets state. End on a clean newline so the prompt lands
175
+ // below the final frame.
176
+ this.#withRenderingGuard(() => this.#logUpdate?.done());
177
+ // done() is a no-op on a non-TTY stderr, so restore the cursor
178
+ // explicitly. This runs after #uninstallWriteInterceptors so the escape
179
+ // reaches the stream instead of being buffered as a partial write.
180
+ this.#stderr.write(CURSOR_SHOW);
181
+ this.#stderr.write("\n");
182
+ }
183
+
184
+ // ---- Termination-signal teardown -----------------------------------------
185
+ // On CTRL+C the process dies without disable() ever running, leaving the
186
+ // cursor hidden. Tear the live region down on the terminating signals, then
187
+ // re-raise so cooperating handlers (profile.js, ProjectBuilder) still run.
188
+
189
+ #registerSignalHandlers() {
190
+ // Re-registering would strand the previous handlers on `process`:
191
+ // #deregisterSignalHandlers() can only detach what the map tracks.
192
+ if (this.#signalHandlers.size > 0) {
193
+ return;
194
+ }
195
+ for (const signal of TERMINATION_SIGNALS) {
196
+ const handler = () => this.#handleTerminationSignal(signal);
197
+ this.#signalHandlers.set(signal, handler);
198
+ process.on(signal, handler);
199
+ }
200
+ // `exit` covers cooperating handlers that call process.exit(); it never
201
+ // fires on a bare signal kill, hence the signal handlers above.
202
+ const onExit = () => this.disable();
203
+ this.#signalHandlers.set("exit", onExit);
204
+ process.on("exit", onExit);
205
+ }
206
+
207
+ #deregisterSignalHandlers() {
208
+ for (const [event, handler] of this.#signalHandlers) {
209
+ process.off(event, handler);
210
+ }
211
+ this.#signalHandlers.clear();
212
+ }
213
+
214
+ #handleTerminationSignal(signal) {
215
+ // Re-raise only if this call did the teardown, so a stale handler
216
+ // invoked after disable() can't kill an already-stopped process.
217
+ const wasStopped = this.#stopped;
218
+ this.disable();
219
+ if (!wasStopped) {
220
+ process.kill(process.pid, signal);
221
+ }
222
+ }
223
+
224
+ // Compose the full live region as a single string. One block per region,
225
+ // separated by their own leading blank line. `log-update` handles wrapping
226
+ // and erase of the previous frame, so we just hand it the full text.
227
+ #composeLiveRegion() {
228
+ const lines = [
229
+ ...renderHeaderRegion(this.#headerState),
230
+ ...renderProjectRegion(this.#projectState),
231
+ ...renderServerRegion(this.#serverState),
232
+ ...renderBuildRegion(this.#buildState),
233
+ ];
234
+ if (lines.length === 0) {
235
+ return "";
236
+ }
237
+ // `log-update` wraps long lines onto additional rows; the last line is
238
+ // designed to fit on a single row when it's a status line, so clip it
239
+ // to the terminal width. `this.#columns` is undefined when stderr isn't
240
+ // a TTY — sliceAnsi treats that as "no limit" and returns unchanged.
241
+ if (this.#buildState.state !== STATES.INITIAL) {
242
+ lines[lines.length - 1] = sliceAnsi(lines[lines.length - 1], 0, this.#columns);
243
+ }
244
+ return lines.join("\n");
245
+ }
246
+
247
+ #render() {
248
+ /* istanbul ignore if — defensive: #render is only called from event
249
+ handlers (detached on disable) and the tick timer (cleared on
250
+ disable), so this branch is unreachable in practice. */
251
+ if (this.#stopped) {
252
+ return;
253
+ }
254
+ this.#withRenderingGuard(() => {
255
+ this.#logUpdate(this.#composeLiveRegion());
256
+ });
257
+ }
258
+
259
+ /**
260
+ * Write a log line ABOVE the live region so it persists in scrollback.
261
+ *
262
+ * Delegates to `log-update`'s `persist()` (which erases the live region,
263
+ * writes the line in its place, and accounts for wrapped lines correctly)
264
+ * followed by a fresh render of the live region below it. Pass a string
265
+ * with embedded newlines to persist multiple lines in a single frame.
266
+ *
267
+ * @param {string} line The log line to write above the live region.
268
+ */
269
+ logAbove(line) {
270
+ if (this.#stopped) {
271
+ this.#stderr.write(line + "\n");
272
+ return;
273
+ }
274
+ this.#withRenderingGuard(() => {
275
+ this.#logUpdate.persist(line);
276
+ this.#logUpdate(this.#composeLiveRegion());
277
+ });
278
+ }
279
+
280
+ // Run `fn` with the re-render flag set so log-update's own writes to
281
+ // the intercepted process streams pass through untouched. Any nested
282
+ // stdout/stderr write inside `fn` will bypass the line-buffering path.
283
+ #withRenderingGuard(fn) {
284
+ this.#renderingLiveRegion = true;
285
+ try {
286
+ return fn();
287
+ } finally {
288
+ this.#renderingLiveRegion = false;
289
+ }
290
+ }
291
+
292
+ // ---- Event subscriptions --------------------------------------------------
293
+
294
+ #attachListeners() {
295
+ this.#onLog = (evt) => this.#handleLog(evt);
296
+ this.#onBuildMetadata = (evt) => this.#handleBuildMetadata(evt);
297
+ this.#onBuildStatus = (evt) => this.#handleBuildStatus(evt);
298
+ this.#onProjectBuildStatus = (evt) => this.#handleProjectBuildStatus(evt);
299
+ this.#onServeStatus = (evt) => this.#handleServeStatus(evt);
300
+ this.#onToolInfo = (evt) => this.#handleToolInfo(evt);
301
+ this.#onToolMode = (evt) => this.#handleToolMode(evt);
302
+ this.#onProjectResolved = (evt) => this.#handleProjectResolved(evt);
303
+ this.#onProjectFrameworkResolved = (evt) => this.#handleProjectFrameworkResolved(evt);
304
+ this.#onProjectResolving = () => this.#handleProjectResolving();
305
+ this.#onProjectResolveFailed = (evt) => this.#handleProjectResolveFailed(evt);
306
+ this.#onServerListening = (evt) => this.#handleServerListening(evt);
307
+ this.#onStopConsole = () => this.disable();
308
+ this.#onResize = () => this.#handleResize();
309
+
310
+ process.on("ui5.log", this.#onLog);
311
+ process.on("ui5.build-metadata", this.#onBuildMetadata);
312
+ process.on("ui5.build-status", this.#onBuildStatus);
313
+ process.on("ui5.project-build-status", this.#onProjectBuildStatus);
314
+ process.on("ui5.serve-status", this.#onServeStatus);
315
+ process.on("ui5.tool-info", this.#onToolInfo);
316
+ process.on("ui5.tool-mode", this.#onToolMode);
317
+ process.on("ui5.project-resolve-succeeded", this.#onProjectResolved);
318
+ process.on("ui5.project-framework-resolved", this.#onProjectFrameworkResolved);
319
+ process.on("ui5.project-resolve-started", this.#onProjectResolving);
320
+ process.on("ui5.project-resolve-failed", this.#onProjectResolveFailed);
321
+ process.on("ui5.server-listening", this.#onServerListening);
322
+ process.on("ui5.log.stop-console", this.#onStopConsole);
323
+ if (typeof this.#stderr.on === "function") {
324
+ this.#stderr.on("resize", this.#onResize);
325
+ }
326
+ }
327
+
328
+ #detachListeners() {
329
+ process.off("ui5.log", this.#onLog);
330
+ process.off("ui5.build-metadata", this.#onBuildMetadata);
331
+ process.off("ui5.build-status", this.#onBuildStatus);
332
+ process.off("ui5.project-build-status", this.#onProjectBuildStatus);
333
+ process.off("ui5.serve-status", this.#onServeStatus);
334
+ process.off("ui5.tool-info", this.#onToolInfo);
335
+ process.off("ui5.tool-mode", this.#onToolMode);
336
+ process.off("ui5.project-resolve-succeeded", this.#onProjectResolved);
337
+ process.off("ui5.project-framework-resolved", this.#onProjectFrameworkResolved);
338
+ process.off("ui5.project-resolve-started", this.#onProjectResolving);
339
+ process.off("ui5.project-resolve-failed", this.#onProjectResolveFailed);
340
+ process.off("ui5.server-listening", this.#onServerListening);
341
+ process.off("ui5.log.stop-console", this.#onStopConsole);
342
+ if (typeof this.#stderr.off === "function") {
343
+ this.#stderr.off("resize", this.#onResize);
344
+ }
345
+ }
346
+
347
+ #handleLog({level, message, moduleName}) {
348
+ if (!Logger.isLevelEnabled(level)) {
349
+ return;
350
+ }
351
+ if (level === "info" && BANNER_REDUNDANT_INFO_MODULES.has(moduleName)) {
352
+ return;
353
+ }
354
+ this.logAbove(formatLogLine(level, prefixModuleName(message, moduleName)));
355
+ }
356
+
357
+ #handleToolInfo(evt) {
358
+ setTool(this.#headerState, evt);
359
+ this.#render();
360
+ }
361
+
362
+ // Optional up-front hint from the CLI: "I'm about to run <mode>". The writer
363
+ // pre-populates placeholders for the sections that <mode> is expected to
364
+ // fill in, so the full frame is visible from the first paint and subsequent
365
+ // events replace placeholders in place rather than growing the layout.
366
+ // Currently only `mode: "serve"` is understood; unknown modes are ignored,
367
+ // keeping the writer forgiving as new modes are added.
368
+ #handleToolMode(evt) {
369
+ if (evt?.mode === "serve") {
370
+ enableProjectPlaceholders(this.#projectState);
371
+ enableServerPlaceholders(this.#serverState, {
372
+ acceptRemoteConnections: evt.acceptRemoteConnections,
373
+ });
374
+ enableBuildPlaceholders(this.#buildState);
375
+ this.#render();
376
+ }
377
+ }
378
+
379
+ #handleProjectResolved(evt) {
380
+ // The writer's model is single-root-project, but the root can be resolved more
381
+ // than once in a process: `Supervisor.reinitialize()` re-resolves the graph
382
+ // on a project-definition change (a `git checkout`, a hand-edit of ui5.yaml), and
383
+ // re-emits this event for the same root. A repeat updates the project region in
384
+ // place; framework data is updated through `ui5.project-framework-resolved`.
385
+ setProject(this.#projectState, evt);
386
+ // A completed re-resolve lifts any degraded state a prior failed re-resolve left sticky, so
387
+ // the next `serve-ready` from the fresh stack renders "ready" normally again.
388
+ clearDegraded(this.#buildState);
389
+ this.#render();
390
+ }
391
+
392
+ #handleProjectFrameworkResolved({framework}) {
393
+ setFramework(this.#projectState, framework);
394
+ this.#render();
395
+ }
396
+
397
+ // A definition change is coming: blank the version slot(s) to a "resolving" placeholder. A
398
+ // completed resolve arrives as `ui5.project-resolve-succeeded` and repopulates them via
399
+ // #handleProjectResolved; an abandoned or failed resolve arrives as `ui5.project-resolve-failed`.
400
+ #handleProjectResolving() {
401
+ setVersionResolving(this.#projectState);
402
+ this.#render();
403
+ }
404
+
405
+ // A re-resolve was abandoned or failed with no `ui5.project-resolve-succeeded`: release the
406
+ // placeholder back to the last-known version rather than leave it on "resolving". A failed
407
+ // re-resolve also means the server is now serving a last-good graph that no longer matches disk;
408
+ // mark it degraded and surface the reason on the (sticky) ERROR status line.
409
+ #handleProjectResolveFailed(evt) {
410
+ clearVersionResolving(this.#projectState);
411
+ setDegraded(this.#buildState);
412
+ setError(this.#buildState, evt?.message);
413
+ this.#render();
414
+ }
415
+
416
+ #handleServerListening(evt) {
417
+ setListening(this.#serverState, evt);
418
+ this.#render();
419
+ }
420
+
421
+ #handleBuildMetadata({projectsToBuild}) {
422
+ beginBuild(this.#buildState, projectsToBuild);
423
+ this.#render();
424
+ }
425
+
426
+ #handleBuildStatus({projectName, status}) {
427
+ if (status === "project-build-start" || status === "project-build-skip") {
428
+ advanceToProject(this.#buildState, projectName);
429
+ this.#render();
430
+ }
431
+ }
432
+
433
+ #handleProjectBuildStatus({taskName, status}) {
434
+ if (status === "task-start") {
435
+ setTask(this.#buildState, taskName);
436
+ this.#render();
437
+ }
438
+ }
439
+
440
+ #handleServeStatus(evt) {
441
+ // validatingProjects is a VALIDATING-only payload; clear it on any other
442
+ // transition so a stale list doesn't linger in the banner state.
443
+ if (evt.status !== "serve-validating") {
444
+ this.#buildState.validatingProjects = [];
445
+ }
446
+ // While degraded (a re-resolve failed and the last-good stack keeps serving), the surviving
447
+ // BuildServer still resettles to IDLE/stale on the branch switch's source churn and would
448
+ // otherwise repaint "ready" over the degraded ERROR line. Suppress those transitions until a
449
+ // successful re-resolve clears the flag (via `ui5.project-resolve-succeeded`). A genuine
450
+ // `serve-error` still passes through: it keeps the line on ERROR either way.
451
+ if (this.#buildState.degraded && evt.status !== "serve-error") {
452
+ return;
453
+ }
454
+ switch (evt.status) {
455
+ case "serve-ready":
456
+ this.#transitionTo(STATES.READY);
457
+ break;
458
+ case "serve-stale":
459
+ // Record the stale set and re-render without a state transition, so the count updates
460
+ // in place beneath the current status (typically `ready`).
461
+ setStale(this.#buildState, evt.staleProjects);
462
+ this.#render();
463
+ break;
464
+ case "serve-settling":
465
+ this.#buildState.pendingProjects = evt.pendingProjects || [];
466
+ this.#transitionTo(STATES.SETTLING);
467
+ break;
468
+ case "serve-building":
469
+ beginBuild(this.#buildState, this.#buildState.projectOrder);
470
+ this.#transitionTo(STATES.BUILDING);
471
+ break;
472
+ case "serve-validating":
473
+ this.#buildState.validatingProjects = evt.validatingProjects || [];
474
+ this.#transitionTo(STATES.VALIDATING);
475
+ break;
476
+ case "serve-build-done":
477
+ this.#buildState.lastBuildHrtime = Array.isArray(evt.hrtime) ? evt.hrtime : null;
478
+ this.#transitionTo(STATES.READY);
479
+ break;
480
+ case "serve-error":
481
+ setError(this.#buildState, evt.error?.message || String(evt.error));
482
+ this.#clearTick();
483
+ this.#render();
484
+ // Don't echo the error via logAbove — BuildServer already logs
485
+ // the same message at `error` level (which #handleLog scrolls
486
+ // above the banner), and the yargs fail-handler renders the full
487
+ // stack trace once the handler promise rejects. A third copy here
488
+ // would just be noise.
489
+ break;
490
+ }
491
+ }
492
+
493
+ #handleResize() {
494
+ this.#columns = this.#stderr.columns;
495
+ this.#render();
496
+ }
497
+
498
+ #transitionTo(newState) {
499
+ if (this.#buildState.state === newState) {
500
+ this.#render();
501
+ return;
502
+ }
503
+ transitionTo(this.#buildState, newState);
504
+ this.#clearTick();
505
+ this.#scheduleTick();
506
+ this.#render();
507
+ }
508
+
509
+ #scheduleTick() {
510
+ /* istanbul ignore if — defensive: #scheduleTick is only reached from
511
+ event handlers (detached on disable), so #stopped is always false
512
+ here in practice. */
513
+ if (this.#stopped) {
514
+ return;
515
+ }
516
+ if (!SPINNING_STATES.has(this.#buildState.state)) {
517
+ return;
518
+ }
519
+ this.#tickTimer = setInterval(() => {
520
+ this.#buildState.spinFrame++;
521
+ this.#render();
522
+ }, BUILDING_TICK_MS);
523
+ // Don't keep the event loop alive purely for the banner spinner.
524
+ if (typeof this.#tickTimer.unref === "function") {
525
+ this.#tickTimer.unref();
526
+ }
527
+ }
528
+
529
+ #clearTick() {
530
+ if (this.#tickTimer) {
531
+ clearInterval(this.#tickTimer);
532
+ this.#tickTimer = null;
533
+ }
534
+ }
535
+
536
+ // ---- process.stdout / process.stderr interception -------------------------
537
+ // Custom tasks and third-party libraries sometimes bypass @ui5/logger and
538
+ // write straight to the process streams. Any such write between frames
539
+ // throws off log-update's line-count accounting (it counts only the bytes
540
+ // it emitted itself) and the next render corrupts — typically by
541
+ // duplicating the header. To keep the live region intact we replace
542
+ // process.stdout.write / process.stderr.write while the writer is active
543
+ // and route incoming bytes through logAbove() line by line. log-update's
544
+ // own writes bypass the interception via the #renderingLiveRegion flag.
545
+
546
+ #installWriteInterceptors() {
547
+ for (const which of ["stdout", "stderr"]) {
548
+ const entry = this.#streams[which];
549
+ entry.orig = process[which].write;
550
+ process[which].write = this.#makeInterceptor(process[which], entry.orig, which);
551
+ }
552
+ }
553
+
554
+ #uninstallWriteInterceptors() {
555
+ for (const which of ["stdout", "stderr"]) {
556
+ const entry = this.#streams[which];
557
+ if (entry.orig) {
558
+ process[which].write = entry.orig;
559
+ entry.orig = null;
560
+ }
561
+ }
562
+ }
563
+
564
+ #makeInterceptor(stream, original, which) {
565
+ // The returned function mirrors WriteStream#write's overloads:
566
+ // write(chunk[, encoding][, callback]) -> boolean
567
+ return (chunk, encodingOrCallback, maybeCallback) => {
568
+ if (this.#renderingLiveRegion || this.#stopped) {
569
+ return original.call(stream, chunk, encodingOrCallback, maybeCallback);
570
+ }
571
+ const {encoding, callback} = parseWriteArgs(encodingOrCallback, maybeCallback);
572
+ const text = typeof chunk === "string" ?
573
+ chunk :
574
+ (Buffer.isBuffer(chunk) ? chunk.toString(encoding) : Buffer.from(chunk).toString(encoding));
575
+ this.#absorbInterceptedText(text, which);
576
+ if (callback) {
577
+ process.nextTick(callback);
578
+ }
579
+ return true;
580
+ };
581
+ }
582
+
583
+ #absorbInterceptedText(text, which) {
584
+ const entry = this.#streams[which];
585
+ const combined = entry.partial + text;
586
+ const lastNewline = combined.lastIndexOf("\n");
587
+ if (lastNewline === -1) {
588
+ entry.partial = combined;
589
+ return;
590
+ }
591
+ entry.partial = combined.slice(lastNewline + 1);
592
+ this.logAbove(combined.slice(0, lastNewline));
593
+ }
594
+
595
+ #flushPartialBuffers() {
596
+ for (const which of ["stdout", "stderr"]) {
597
+ const entry = this.#streams[which];
598
+ if (entry.partial) {
599
+ const line = entry.partial;
600
+ entry.partial = "";
601
+ this.logAbove(line);
602
+ }
603
+ }
604
+ }
605
+
606
+ /**
607
+ * Creates a new instance and subscribes it to all events. Any currently-
608
+ * active console-writing writer is displaced by the `ui5.log.stop-console`
609
+ * event that `enable()` emits.
610
+ *
611
+ * @public
612
+ */
613
+ static init() {
614
+ const w = new InteractiveConsole();
615
+ w.enable();
616
+ return w;
617
+ }
618
+
619
+ static stop() {
620
+ process.emit("ui5.log.stop-console");
621
+ }
622
+
623
+ // ---- Test helpers ---------------------------------------------------------
624
+
625
+ /* istanbul ignore next */
626
+ _getStateForTest() {
627
+ return {
628
+ header: this.#headerState,
629
+ project: this.#projectState,
630
+ server: this.#serverState,
631
+ build: this.#buildState,
632
+ };
633
+ }
634
+ }
635
+
636
+ // Split from the constructor so the `log-update` factory is imported lazily
637
+ // and can be swapped out by tests that pass a stubbed stderr. `createLogUpdate`
638
+ // is a synchronous factory; the async import is not warranted.
639
+ export default InteractiveConsole;
@@ -0,0 +1,31 @@
1
+ import chalk from "chalk";
2
+ import figures from "figures";
3
+
4
+ // Low-level formatting primitives — the theme (brand and accent colors, the
5
+ // pointer arrow, placeholder styling) shared by all region renderers.
6
+
7
+ // COLORFGBG is set by many terminals (xterm, konsole, rxvt, iTerm2, …) as
8
+ // "<fg>;<bg>" with ANSI color indices. Indices 0-6 and 8 are conventionally
9
+ // dark backgrounds. Apple Terminal, VS Code, and Windows Terminal don't set
10
+ // this — we fall back to the light-background palette in that case.
11
+ function isDarkTerminalBackground() {
12
+ const v = process.env.COLORFGBG;
13
+ if (!v) {
14
+ return false;
15
+ }
16
+ const bg = parseInt(v.split(";").pop(), 10);
17
+ if (Number.isNaN(bg)) {
18
+ return false;
19
+ }
20
+ return bg < 7 || bg === 8;
21
+ }
22
+
23
+ const DARK_MODE = isDarkTerminalBackground();
24
+ const BRAND_HEX = DARK_MODE ? "#FF5A37" : "#1873B4";
25
+ const ACCENT_HEX = DARK_MODE ? "#FFA42C" : "#53B8DE";
26
+
27
+ export const brand = (text) => chalk.bold.hex(BRAND_HEX)(text);
28
+ export const accent = (text) => chalk.hex(ACCENT_HEX)(text);
29
+ export const accentBold = (text) => chalk.bold.hex(ACCENT_HEX)(text);
30
+ export const arrow = accent(figures.pointer);
31
+ export const placeholder = (text) => chalk.dim.italic(text);
@@ -0,0 +1,19 @@
1
+ import chalk from "chalk";
2
+ import figures from "figures";
3
+
4
+ // Shared content for the "accepting remote connections" warning, rendered
5
+ // both by the interactive writer's server region and by Console.js's non-TTY
6
+ // fallback. Each entry is a fully chalk-formatted string; consumers just
7
+ // print them line by line.
8
+ export const REMOTE_CONNECTIONS_WARNING_LINES = Object.freeze([
9
+ chalk.bold.yellow(
10
+ `${figures.warning} This server is accepting connections from all hosts on your network`),
11
+ chalk.dim.underline("Warning:"),
12
+ chalk.dim(`${figures.pointerSmall} `) +
13
+ chalk.dim.bold("This server is intended for development purposes only. Do not use it in production."),
14
+ chalk.dim(`${figures.pointerSmall} ` +
15
+ "Vulnerable (custom-)middleware can pose a threat to your system when exposed to the network."),
16
+ chalk.dim(`${figures.pointerSmall} ` +
17
+ "The use of proxy-middleware with preconfigured credentials might enable unauthorized access"),
18
+ chalk.dim(" to a target system for third parties on your network."),
19
+ ]);