lifecycleion 0.0.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.
Files changed (177) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +125 -0
  3. package/dist/index.cjs +7 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +2 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/index.js +5 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/lib/arrays.cjs +95 -0
  10. package/dist/lib/arrays.cjs.map +1 -0
  11. package/dist/lib/arrays.d.cts +15 -0
  12. package/dist/lib/arrays.d.ts +15 -0
  13. package/dist/lib/arrays.js +63 -0
  14. package/dist/lib/arrays.js.map +1 -0
  15. package/dist/lib/ascii-tables/index.cjs +642 -0
  16. package/dist/lib/ascii-tables/index.cjs.map +1 -0
  17. package/dist/lib/ascii-tables/index.d.cts +66 -0
  18. package/dist/lib/ascii-tables/index.d.ts +66 -0
  19. package/dist/lib/ascii-tables/index.js +603 -0
  20. package/dist/lib/ascii-tables/index.js.map +1 -0
  21. package/dist/lib/clamp.cjs +41 -0
  22. package/dist/lib/clamp.cjs.map +1 -0
  23. package/dist/lib/clamp.d.cts +26 -0
  24. package/dist/lib/clamp.d.ts +26 -0
  25. package/dist/lib/clamp.js +15 -0
  26. package/dist/lib/clamp.js.map +1 -0
  27. package/dist/lib/constants.cjs +73 -0
  28. package/dist/lib/constants.cjs.map +1 -0
  29. package/dist/lib/constants.d.cts +17 -0
  30. package/dist/lib/constants.d.ts +17 -0
  31. package/dist/lib/constants.js +34 -0
  32. package/dist/lib/constants.js.map +1 -0
  33. package/dist/lib/curly-brackets.cjs +77 -0
  34. package/dist/lib/curly-brackets.cjs.map +1 -0
  35. package/dist/lib/curly-brackets.d.cts +17 -0
  36. package/dist/lib/curly-brackets.d.ts +17 -0
  37. package/dist/lib/curly-brackets.js +52 -0
  38. package/dist/lib/curly-brackets.js.map +1 -0
  39. package/dist/lib/deep-clone.cjs +87 -0
  40. package/dist/lib/deep-clone.cjs.map +1 -0
  41. package/dist/lib/deep-clone.d.cts +19 -0
  42. package/dist/lib/deep-clone.d.ts +19 -0
  43. package/dist/lib/deep-clone.js +62 -0
  44. package/dist/lib/deep-clone.js.map +1 -0
  45. package/dist/lib/error-to-string.cjs +743 -0
  46. package/dist/lib/error-to-string.cjs.map +1 -0
  47. package/dist/lib/error-to-string.d.cts +3 -0
  48. package/dist/lib/error-to-string.d.ts +3 -0
  49. package/dist/lib/error-to-string.js +706 -0
  50. package/dist/lib/error-to-string.js.map +1 -0
  51. package/dist/lib/event-emitter.cjs +899 -0
  52. package/dist/lib/event-emitter.cjs.map +1 -0
  53. package/dist/lib/event-emitter.d.cts +78 -0
  54. package/dist/lib/event-emitter.d.ts +78 -0
  55. package/dist/lib/event-emitter.js +861 -0
  56. package/dist/lib/event-emitter.js.map +1 -0
  57. package/dist/lib/id-helpers.cjs +205 -0
  58. package/dist/lib/id-helpers.cjs.map +1 -0
  59. package/dist/lib/id-helpers.d.cts +198 -0
  60. package/dist/lib/id-helpers.d.ts +198 -0
  61. package/dist/lib/id-helpers.js +170 -0
  62. package/dist/lib/id-helpers.js.map +1 -0
  63. package/dist/lib/is-boolean.cjs +33 -0
  64. package/dist/lib/is-boolean.cjs.map +1 -0
  65. package/dist/lib/is-boolean.d.cts +19 -0
  66. package/dist/lib/is-boolean.d.ts +19 -0
  67. package/dist/lib/is-boolean.js +8 -0
  68. package/dist/lib/is-boolean.js.map +1 -0
  69. package/dist/lib/is-function.cjs +33 -0
  70. package/dist/lib/is-function.cjs.map +1 -0
  71. package/dist/lib/is-function.d.cts +3 -0
  72. package/dist/lib/is-function.d.ts +3 -0
  73. package/dist/lib/is-function.js +8 -0
  74. package/dist/lib/is-function.js.map +1 -0
  75. package/dist/lib/is-number.cjs +38 -0
  76. package/dist/lib/is-number.cjs.map +1 -0
  77. package/dist/lib/is-number.d.cts +38 -0
  78. package/dist/lib/is-number.d.ts +38 -0
  79. package/dist/lib/is-number.js +12 -0
  80. package/dist/lib/is-number.js.map +1 -0
  81. package/dist/lib/is-plain-object.cjs +33 -0
  82. package/dist/lib/is-plain-object.cjs.map +1 -0
  83. package/dist/lib/is-plain-object.d.cts +20 -0
  84. package/dist/lib/is-plain-object.d.ts +20 -0
  85. package/dist/lib/is-plain-object.js +8 -0
  86. package/dist/lib/is-plain-object.js.map +1 -0
  87. package/dist/lib/is-promise.cjs +34 -0
  88. package/dist/lib/is-promise.cjs.map +1 -0
  89. package/dist/lib/is-promise.d.cts +3 -0
  90. package/dist/lib/is-promise.d.ts +3 -0
  91. package/dist/lib/is-promise.js +9 -0
  92. package/dist/lib/is-promise.js.map +1 -0
  93. package/dist/lib/json-helpers.cjs +49 -0
  94. package/dist/lib/json-helpers.cjs.map +1 -0
  95. package/dist/lib/json-helpers.d.cts +10 -0
  96. package/dist/lib/json-helpers.d.ts +10 -0
  97. package/dist/lib/json-helpers.js +22 -0
  98. package/dist/lib/json-helpers.js.map +1 -0
  99. package/dist/lib/lifecycle-manager/index.cjs +5594 -0
  100. package/dist/lib/lifecycle-manager/index.cjs.map +1 -0
  101. package/dist/lib/lifecycle-manager/index.d.cts +2044 -0
  102. package/dist/lib/lifecycle-manager/index.d.ts +2044 -0
  103. package/dist/lib/lifecycle-manager/index.js +5543 -0
  104. package/dist/lib/lifecycle-manager/index.js.map +1 -0
  105. package/dist/lib/logger/index.cjs +2514 -0
  106. package/dist/lib/logger/index.cjs.map +1 -0
  107. package/dist/lib/logger/index.d.cts +630 -0
  108. package/dist/lib/logger/index.d.ts +630 -0
  109. package/dist/lib/logger/index.js +2470 -0
  110. package/dist/lib/logger/index.js.map +1 -0
  111. package/dist/lib/padding-utils.cjs +77 -0
  112. package/dist/lib/padding-utils.cjs.map +1 -0
  113. package/dist/lib/padding-utils.d.cts +44 -0
  114. package/dist/lib/padding-utils.d.ts +44 -0
  115. package/dist/lib/padding-utils.js +46 -0
  116. package/dist/lib/padding-utils.js.map +1 -0
  117. package/dist/lib/process-signal-manager.cjs +1306 -0
  118. package/dist/lib/process-signal-manager.cjs.map +1 -0
  119. package/dist/lib/process-signal-manager.d.cts +305 -0
  120. package/dist/lib/process-signal-manager.d.ts +305 -0
  121. package/dist/lib/process-signal-manager.js +1269 -0
  122. package/dist/lib/process-signal-manager.js.map +1 -0
  123. package/dist/lib/promise-protected-resolver.cjs +828 -0
  124. package/dist/lib/promise-protected-resolver.cjs.map +1 -0
  125. package/dist/lib/promise-protected-resolver.d.cts +17 -0
  126. package/dist/lib/promise-protected-resolver.d.ts +17 -0
  127. package/dist/lib/promise-protected-resolver.js +791 -0
  128. package/dist/lib/promise-protected-resolver.js.map +1 -0
  129. package/dist/lib/retry-utils/index.cjs +2183 -0
  130. package/dist/lib/retry-utils/index.cjs.map +1 -0
  131. package/dist/lib/retry-utils/index.d.cts +321 -0
  132. package/dist/lib/retry-utils/index.d.ts +321 -0
  133. package/dist/lib/retry-utils/index.js +2133 -0
  134. package/dist/lib/retry-utils/index.js.map +1 -0
  135. package/dist/lib/safe-handle-callback.cjs +818 -0
  136. package/dist/lib/safe-handle-callback.cjs.map +1 -0
  137. package/dist/lib/safe-handle-callback.d.cts +43 -0
  138. package/dist/lib/safe-handle-callback.d.ts +43 -0
  139. package/dist/lib/safe-handle-callback.js +780 -0
  140. package/dist/lib/safe-handle-callback.js.map +1 -0
  141. package/dist/lib/serialize-error/index.cjs +93 -0
  142. package/dist/lib/serialize-error/index.cjs.map +1 -0
  143. package/dist/lib/serialize-error/index.d.cts +26 -0
  144. package/dist/lib/serialize-error/index.d.ts +26 -0
  145. package/dist/lib/serialize-error/index.js +64 -0
  146. package/dist/lib/serialize-error/index.js.map +1 -0
  147. package/dist/lib/single-event-observer.cjs +841 -0
  148. package/dist/lib/single-event-observer.cjs.map +1 -0
  149. package/dist/lib/single-event-observer.d.cts +54 -0
  150. package/dist/lib/single-event-observer.d.ts +54 -0
  151. package/dist/lib/single-event-observer.js +803 -0
  152. package/dist/lib/single-event-observer.js.map +1 -0
  153. package/dist/lib/sleep.cjs +37 -0
  154. package/dist/lib/sleep.cjs.map +1 -0
  155. package/dist/lib/sleep.d.cts +11 -0
  156. package/dist/lib/sleep.d.ts +11 -0
  157. package/dist/lib/sleep.js +12 -0
  158. package/dist/lib/sleep.js.map +1 -0
  159. package/dist/lib/strings.cjs +186 -0
  160. package/dist/lib/strings.cjs.map +1 -0
  161. package/dist/lib/strings.d.cts +107 -0
  162. package/dist/lib/strings.d.ts +107 -0
  163. package/dist/lib/strings.js +149 -0
  164. package/dist/lib/strings.js.map +1 -0
  165. package/dist/lib/tmp-dir.cjs +254 -0
  166. package/dist/lib/tmp-dir.cjs.map +1 -0
  167. package/dist/lib/tmp-dir.d.cts +63 -0
  168. package/dist/lib/tmp-dir.d.ts +63 -0
  169. package/dist/lib/tmp-dir.js +211 -0
  170. package/dist/lib/tmp-dir.js.map +1 -0
  171. package/dist/lib/unix-time-helpers.cjs +53 -0
  172. package/dist/lib/unix-time-helpers.cjs.map +1 -0
  173. package/dist/lib/unix-time-helpers.d.cts +56 -0
  174. package/dist/lib/unix-time-helpers.d.ts +56 -0
  175. package/dist/lib/unix-time-helpers.js +24 -0
  176. package/dist/lib/unix-time-helpers.js.map +1 -0
  177. package/package.json +220 -0
@@ -0,0 +1,1306 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/lib/process-signal-manager.ts
31
+ var process_signal_manager_exports = {};
32
+ __export(process_signal_manager_exports, {
33
+ ProcessSignalManager: () => ProcessSignalManager
34
+ });
35
+ module.exports = __toCommonJS(process_signal_manager_exports);
36
+
37
+ // src/lib/strings.ts
38
+ function isString(value) {
39
+ return typeof value === "string";
40
+ }
41
+ function splitGraphemes(text) {
42
+ const graphemes = [];
43
+ let grapheme = "";
44
+ let zwjSequence = "";
45
+ for (let i = 0; i < text.length; i++) {
46
+ const char = text[i];
47
+ const nextChar = text[i + 1] || "";
48
+ const code = char.charCodeAt(0);
49
+ if (code >= 768 && code <= 879 || // Combining Diacritical Marks
50
+ code >= 6832 && code <= 6911 || // Combining Diacritical Marks Extended
51
+ code >= 7616 && code <= 7679 || // Combining Diacritical Marks Supplement
52
+ code >= 65056 && code <= 65071 || // Combining Half Marks
53
+ code >= 3633 && code <= 3642 || // Thai combining marks
54
+ code >= 3655 && code <= 3662) {
55
+ grapheme += char;
56
+ } else if (char === "\u200D") {
57
+ zwjSequence += grapheme + char;
58
+ grapheme = "";
59
+ } else {
60
+ if (grapheme) {
61
+ if (zwjSequence) {
62
+ graphemes.push(zwjSequence + grapheme);
63
+ zwjSequence = "";
64
+ } else {
65
+ graphemes.push(grapheme);
66
+ }
67
+ }
68
+ grapheme = char;
69
+ if (char >= "\uD800" && char <= "\uDBFF" && nextChar >= "\uDC00" && nextChar <= "\uDFFF") {
70
+ grapheme += nextChar;
71
+ i++;
72
+ }
73
+ }
74
+ }
75
+ if (grapheme) {
76
+ if (zwjSequence) {
77
+ graphemes.push(zwjSequence + grapheme);
78
+ } else {
79
+ graphemes.push(grapheme);
80
+ }
81
+ }
82
+ return graphemes;
83
+ }
84
+
85
+ // src/lib/constants.ts
86
+ var BLANK_SPACE = " ";
87
+ var EOL = "\n";
88
+ var DOUBLE_EOL = EOL + EOL;
89
+ var INDENT = " ".repeat(4);
90
+ var DOUBLE_INDENT = INDENT + INDENT;
91
+ var ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
92
+ var ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
93
+ var ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE;
94
+ var DIGITS = "0123456789";
95
+ var HEX_DIGITS = DIGITS + "abcdefABCDEF";
96
+ var PUNCTUATION = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
97
+ var WHITESPACE = " \n\r\v\f";
98
+ var PRINTABLE = DIGITS + ASCII_LETTERS + PUNCTUATION + WHITESPACE;
99
+
100
+ // src/lib/padding-utils.ts
101
+ function padLeft(str, length, padStr = BLANK_SPACE) {
102
+ return str.padStart(length, padStr);
103
+ }
104
+ function padRight(str, length, padStr = BLANK_SPACE) {
105
+ return str.padEnd(length, padStr);
106
+ }
107
+ function padCenter(str, length, prefer = "left", padStr = BLANK_SPACE) {
108
+ const midStrLength = length - str.length;
109
+ if (midStrLength > 0) {
110
+ const padLeftAmount = prefer === "left" ? Math.ceil(midStrLength / 2) : Math.floor(midStrLength / 2);
111
+ const padRightAmount = prefer === "left" ? Math.floor(midStrLength / 2) : Math.ceil(midStrLength / 2);
112
+ return padLeft("", padLeftAmount, padStr) + str + padRight("", padRightAmount, padStr);
113
+ } else {
114
+ return str;
115
+ }
116
+ }
117
+ function padCenterPreferRight(str, length, padStr = BLANK_SPACE) {
118
+ return padCenter(str, length, "right", padStr);
119
+ }
120
+
121
+ // src/lib/ascii-tables/ascii-table-utils.ts
122
+ var import_string_width = __toESM(require("string-width"), 1);
123
+ var ASCIITableUtils = class _ASCIITableUtils {
124
+ static centerText(text, width) {
125
+ return padCenterPreferRight(text, width, " ");
126
+ }
127
+ static createSeparator(columnWidths, character = "=") {
128
+ const totalWidth = columnWidths.reduce((sum, width) => sum + width + 3, 0) - 1;
129
+ return `+${padRight("", totalWidth, character)}+`;
130
+ }
131
+ static wrapText(text, maxLength) {
132
+ const words = text.split(" ");
133
+ const lines = [];
134
+ let currentLine = "";
135
+ for (const word of words) {
136
+ if ((0, import_string_width.default)(currentLine) + (0, import_string_width.default)(word) + 1 <= maxLength) {
137
+ currentLine += (currentLine ? " " : "") + word;
138
+ } else {
139
+ if (currentLine) {
140
+ lines.push(currentLine);
141
+ }
142
+ if ((0, import_string_width.default)(word) <= maxLength) {
143
+ currentLine = word;
144
+ } else {
145
+ const subWords = _ASCIITableUtils.splitWord(word, maxLength);
146
+ lines.push(...subWords.slice(0, -1));
147
+ currentLine = subWords[subWords.length - 1];
148
+ }
149
+ }
150
+ }
151
+ if (currentLine) {
152
+ lines.push(currentLine);
153
+ }
154
+ return lines;
155
+ }
156
+ static splitWord(word, maxLength) {
157
+ const graphemes = splitGraphemes(word);
158
+ const subWords = [];
159
+ let currentSubWord = "";
160
+ for (const grapheme of graphemes) {
161
+ if ((0, import_string_width.default)(currentSubWord + grapheme) <= maxLength) {
162
+ currentSubWord += grapheme;
163
+ } else {
164
+ subWords.push(currentSubWord);
165
+ currentSubWord = grapheme;
166
+ }
167
+ }
168
+ if (currentSubWord) {
169
+ subWords.push(currentSubWord);
170
+ }
171
+ return subWords;
172
+ }
173
+ };
174
+
175
+ // src/lib/ascii-tables/multi-column-ascii-table.ts
176
+ var import_string_width2 = __toESM(require("string-width"), 1);
177
+ var MultiColumnASCIITable = class {
178
+ headers;
179
+ rows;
180
+ tableWidth;
181
+ emptyMessage;
182
+ widthMode;
183
+ constructor(headers, options = {}) {
184
+ this.headers = headers;
185
+ this.rows = [];
186
+ this.tableWidth = options.tableWidth || 80;
187
+ this.emptyMessage = options.emptyMessage || "";
188
+ this.widthMode = options.widthMode || "flex";
189
+ const minTableWidth = this.getMinimumWidth();
190
+ if (this.tableWidth < minTableWidth) {
191
+ throw new Error(
192
+ `Table width must be at least ${minTableWidth} to accommodate the headers.`
193
+ );
194
+ }
195
+ }
196
+ getMinimumWidth() {
197
+ return this.headers.length * 4 + 1;
198
+ }
199
+ addRow(row) {
200
+ if (row.length !== this.headers.length) {
201
+ throw new Error(
202
+ `Number of values in the row (${row.length}) must match the number of headers (${this.headers.length}).`
203
+ );
204
+ }
205
+ this.rows.push(row);
206
+ }
207
+ toString(options = {}) {
208
+ const tableWidth = options.tableWidth || this.tableWidth;
209
+ const emptyMessage = options.emptyMessage || this.emptyMessage;
210
+ if (this.rows.length === 0) {
211
+ const emptyTableWidth = Math.min(tableWidth, 40);
212
+ const separator = "+" + "-".repeat(emptyTableWidth - 2) + "+";
213
+ const emptyMessageLines = ASCIITableUtils.wrapText(
214
+ emptyMessage,
215
+ emptyTableWidth - 4
216
+ );
217
+ const emptyRows = emptyMessageLines.map((line) => {
218
+ const paddingLeft = " ".repeat(
219
+ Math.floor((emptyTableWidth - (0, import_string_width2.default)(line) - 4) / 2)
220
+ );
221
+ const paddingRight = " ".repeat(
222
+ Math.ceil((emptyTableWidth - (0, import_string_width2.default)(line) - 4) / 2)
223
+ );
224
+ return `| ${paddingLeft}${line}${paddingRight} |`;
225
+ });
226
+ if (emptyRows.length === 0) {
227
+ emptyRows.push(`| ${" ".repeat(emptyTableWidth - 4)} |`);
228
+ }
229
+ return [separator, ...emptyRows, separator].join("\n");
230
+ }
231
+ const columnWidths = this.calculateColumnWidths(options);
232
+ const headerSeparator = ASCIITableUtils.createSeparator(columnWidths);
233
+ const rowSeparator = ASCIITableUtils.createSeparator(columnWidths, "-");
234
+ let tableString = headerSeparator + "\n";
235
+ const header = this.renderRow(this.headers, columnWidths);
236
+ tableString += header + "\n" + rowSeparator + "\n";
237
+ const rows = this.rows.map((row) => {
238
+ return this.renderRow(row, columnWidths);
239
+ });
240
+ tableString += rows.join("\n" + rowSeparator + "\n");
241
+ tableString += "\n" + headerSeparator;
242
+ return tableString;
243
+ }
244
+ calculateColumnWidths(options = {}) {
245
+ const tableWidth = options.tableWidth || this.tableWidth;
246
+ const widthMode = options.widthMode || this.widthMode;
247
+ const numColumns = this.headers.length;
248
+ if (widthMode === "fixed") {
249
+ const availableWidth2 = tableWidth - (numColumns + 1) * 3 + 1;
250
+ const columnWidth = Math.floor(availableWidth2 / numColumns);
251
+ const extraWidth = availableWidth2 % numColumns;
252
+ const columnWidths = new Array(numColumns).fill(columnWidth);
253
+ for (let i = 0; i < extraWidth; i++) {
254
+ columnWidths[i] += 1;
255
+ }
256
+ return columnWidths;
257
+ }
258
+ const availableWidth = tableWidth - (numColumns + 1) * 3 + 1;
259
+ const maxColumnWidth = Math.floor(availableWidth / numColumns);
260
+ const totalContentWidth = this.headers.reduce(
261
+ (sum, header) => sum + (0, import_string_width2.default)(header),
262
+ 0
263
+ );
264
+ if (availableWidth >= totalContentWidth) {
265
+ const remainingWidth = availableWidth - totalContentWidth;
266
+ const extraCharWidth = Math.floor(remainingWidth / numColumns);
267
+ const extraCharRemainder = remainingWidth % numColumns;
268
+ const columnWidths = this.headers.map((header, index) => {
269
+ const extraWidth = index < extraCharRemainder ? 1 : 0;
270
+ return (0, import_string_width2.default)(header) + extraCharWidth + extraWidth;
271
+ });
272
+ return columnWidths;
273
+ } else {
274
+ const columnWidths = this.headers.map(() => maxColumnWidth);
275
+ return columnWidths;
276
+ }
277
+ }
278
+ renderRow(row, columnWidths) {
279
+ const wrappedCells = row.map((value, index) => {
280
+ const wrappedLines = ASCIITableUtils.wrapText(value, columnWidths[index]);
281
+ return wrappedLines.map((line) => line.padEnd(columnWidths[index])).join("\n");
282
+ });
283
+ const maxLines = Math.max(
284
+ ...wrappedCells.map((cell) => cell.split("\n").length)
285
+ );
286
+ const paddedRows = [];
287
+ for (let i = 0; i < maxLines; i++) {
288
+ const rowLine = wrappedCells.map((cell, index) => {
289
+ const cellLines = cell.split("\n");
290
+ const cellLine = cellLines[i] || "";
291
+ const padding = " ".repeat(columnWidths[index] - (0, import_string_width2.default)(cellLine));
292
+ return " " + cellLine + padding + " ";
293
+ });
294
+ paddedRows.push("|" + rowLine.join("|") + "|");
295
+ }
296
+ return paddedRows.join("\n");
297
+ }
298
+ };
299
+
300
+ // src/lib/ascii-tables/key-value-ascii-table.ts
301
+ var import_string_width3 = __toESM(require("string-width"), 1);
302
+
303
+ // src/lib/clamp.ts
304
+ function clamp(value, min, max) {
305
+ return Math.max(min, Math.min(value, max));
306
+ }
307
+
308
+ // src/lib/ascii-tables/key-value-ascii-table.ts
309
+ var KeyValueASCIITable = class _KeyValueASCIITable {
310
+ tableWidth;
311
+ emptyMessage;
312
+ autoAdjustWidthWhenPossible = true;
313
+ rows = [];
314
+ constructor(options = {}) {
315
+ const minTableWidth = this.getMinimumWidth();
316
+ if (options.tableWidth && options.tableWidth < minTableWidth) {
317
+ throw new Error(
318
+ `Table width must be at least ${minTableWidth} to accommodate the table structure.`
319
+ );
320
+ }
321
+ this.tableWidth = options.tableWidth || 80;
322
+ this.autoAdjustWidthWhenPossible = options.autoAdjustWidthWhenPossible ?? true;
323
+ this.emptyMessage = options.emptyMessage || "";
324
+ }
325
+ getMinimumWidth() {
326
+ return 9;
327
+ }
328
+ /**
329
+ * Adds key and value to the table but placing the value on its own row.
330
+ *
331
+ * @param key
332
+ * @param value
333
+ */
334
+ addValueOnSeparateRow(key, value) {
335
+ const row = { kind: "own", key, value };
336
+ this.rows.push(row);
337
+ }
338
+ /**
339
+ * Adds key and value to the table.
340
+ *
341
+ * If provided value is an instance of ASCIITable or MultiColumnASCIITable, it will be rendered as a nested table on its own row for readability.
342
+ *
343
+ * @param key
344
+ * @param value
345
+ */
346
+ addRow(key, value) {
347
+ const row = { kind: "regular", key, value };
348
+ this.rows.push(row);
349
+ }
350
+ toString(options = {}) {
351
+ const tableWidth = options.tableWidth || this.tableWidth;
352
+ const canAutoAdjustWidthWhenPossible = options.autoAdjustWidthWhenPossible ?? this.autoAdjustWidthWhenPossible;
353
+ const emptyMessage = options.emptyMessage || this.emptyMessage;
354
+ if (this.rows.length === 0) {
355
+ const emptyTableWidth = Math.min(tableWidth, 40);
356
+ const separator = "+" + "-".repeat(emptyTableWidth - 2) + "+";
357
+ const emptyMessageLines = ASCIITableUtils.wrapText(
358
+ emptyMessage,
359
+ emptyTableWidth - 4
360
+ );
361
+ const emptyRows = emptyMessageLines.map((line) => {
362
+ const paddingLeft = padRight(
363
+ "",
364
+ Math.floor((emptyTableWidth - (0, import_string_width3.default)(line) - 4) / 2),
365
+ " "
366
+ );
367
+ const paddingRight = padRight(
368
+ "",
369
+ Math.ceil((emptyTableWidth - (0, import_string_width3.default)(line) - 4) / 2),
370
+ " "
371
+ );
372
+ return `| ${paddingLeft}${line}${paddingRight} |`;
373
+ });
374
+ if (emptyRows.length === 0) {
375
+ emptyRows.push(`| ${" ".repeat(emptyTableWidth - 4)} |`);
376
+ }
377
+ return [separator, ...emptyRows, separator].join("\n");
378
+ }
379
+ const columnWidths = this.calculateColumnWidths(options);
380
+ const headerSeparator = ASCIITableUtils.createSeparator(columnWidths);
381
+ const rowSeparator = ASCIITableUtils.createSeparator(columnWidths, "-");
382
+ let tableString = headerSeparator + "\n";
383
+ for (const [rowIndex, row] of this.rows.entries()) {
384
+ const { kind, key, value } = row;
385
+ if (kind === "own" || value instanceof _KeyValueASCIITable || value instanceof MultiColumnASCIITable || Array.isArray(value)) {
386
+ const keyString = ASCIITableUtils.centerText(
387
+ key,
388
+ columnWidths[0] + columnWidths[1] + 3
389
+ );
390
+ tableString += `| ${keyString} |
391
+ `;
392
+ tableString += rowSeparator + "\n";
393
+ let valueString = "";
394
+ if (value instanceof _KeyValueASCIITable) {
395
+ valueString = this.formatValue(
396
+ value,
397
+ tableWidth - 4,
398
+ canAutoAdjustWidthWhenPossible,
399
+ ""
400
+ );
401
+ } else if (value instanceof MultiColumnASCIITable) {
402
+ valueString = this.formatValue(
403
+ value,
404
+ tableWidth - 4,
405
+ canAutoAdjustWidthWhenPossible,
406
+ ""
407
+ );
408
+ } else if (Array.isArray(value)) {
409
+ valueString = this.formatValue(
410
+ value,
411
+ tableWidth - 4,
412
+ canAutoAdjustWidthWhenPossible,
413
+ ""
414
+ );
415
+ } else if (row.kind === "own") {
416
+ valueString = this.formatTableRowOnOwnRow(
417
+ value,
418
+ tableWidth - 4,
419
+ tableWidth
420
+ );
421
+ }
422
+ const valueLines = valueString.split("\n");
423
+ const paddedValueLines = valueLines.map((line) => {
424
+ const padding = padRight("", tableWidth - (0, import_string_width3.default)(line) - 4, " ");
425
+ return `| ${line}${padding} |`;
426
+ });
427
+ tableString += paddedValueLines.join("\n") + "\n";
428
+ tableString += headerSeparator + "\n";
429
+ } else {
430
+ const keyLines = ASCIITableUtils.wrapText(key, columnWidths[0]);
431
+ const valueLines = ASCIITableUtils.wrapText(
432
+ this.formatValue(
433
+ value,
434
+ columnWidths[1],
435
+ canAutoAdjustWidthWhenPossible,
436
+ ""
437
+ ),
438
+ columnWidths[1]
439
+ );
440
+ const maxLines = Math.max(keyLines.length, valueLines.length);
441
+ for (let i = 0; i < maxLines; i++) {
442
+ const keyLine = keyLines[i] || "";
443
+ const valueLine = valueLines[i] || "";
444
+ const keyPadding = " ".repeat(columnWidths[0] - (0, import_string_width3.default)(keyLine));
445
+ const valuePadding = " ".repeat(
446
+ columnWidths[1] - (0, import_string_width3.default)(valueLine)
447
+ );
448
+ tableString += `| ${keyLine}${keyPadding} | ${valueLine}${valuePadding} |
449
+ `;
450
+ if (i === maxLines - 1) {
451
+ if (rowIndex === this.rows.length - 1) {
452
+ tableString += headerSeparator + "\n";
453
+ } else {
454
+ tableString += rowSeparator + "\n";
455
+ }
456
+ }
457
+ }
458
+ }
459
+ }
460
+ return tableString.trim();
461
+ }
462
+ calculateColumnWidths(options = {}) {
463
+ const tableWidth = options.tableWidth || this.tableWidth;
464
+ const canAutoAdjustWidthWhenPossible = options.autoAdjustWidthWhenPossible ?? this.autoAdjustWidthWhenPossible;
465
+ const columnWidths = [0, 0];
466
+ for (const row of this.rows) {
467
+ const { key, value } = row;
468
+ const keyWidth = (0, import_string_width3.default)(key);
469
+ const maxKeyWidth = Math.floor((tableWidth - 7) / 2);
470
+ if (keyWidth > columnWidths[0]) {
471
+ columnWidths[0] = Math.min(keyWidth, maxKeyWidth);
472
+ columnWidths[1] = Math.max(0, tableWidth - columnWidths[0] - 7);
473
+ }
474
+ if (typeof value === "string") {
475
+ const valueWidth = Math.max(
476
+ ...value.split("\n").map((line) => (0, import_string_width3.default)(line))
477
+ );
478
+ if (valueWidth > columnWidths[1]) {
479
+ columnWidths[1] = Math.min(
480
+ valueWidth,
481
+ tableWidth - columnWidths[0] - 7
482
+ );
483
+ columnWidths[0] = Math.max(0, tableWidth - columnWidths[1] - 7);
484
+ }
485
+ } else if (row.kind === "own") {
486
+ let valueWidth = 0;
487
+ if (isString(value)) {
488
+ valueWidth = Math.max(
489
+ ...value.split("\n").map((line) => (0, import_string_width3.default)(line))
490
+ );
491
+ }
492
+ if (valueWidth > columnWidths[1]) {
493
+ columnWidths[1] = Math.min(
494
+ valueWidth,
495
+ tableWidth - columnWidths[0] - 7
496
+ );
497
+ columnWidths[0] = Math.max(0, tableWidth - columnWidths[1] - 7);
498
+ }
499
+ } else if (value instanceof _KeyValueASCIITable) {
500
+ let nestedTableColumnWidths = [];
501
+ if (canAutoAdjustWidthWhenPossible) {
502
+ const minWidth = value.getMinimumWidth();
503
+ const availableWidth2 = tableWidth - columnWidths[0] - 7;
504
+ const adjustedWidth = clamp(availableWidth2, minWidth, availableWidth2);
505
+ nestedTableColumnWidths = value.calculateColumnWidths({
506
+ tableWidth: adjustedWidth
507
+ });
508
+ } else {
509
+ nestedTableColumnWidths = value.calculateColumnWidths();
510
+ }
511
+ const nestedTableWidth = nestedTableColumnWidths.reduce((sum, width) => sum + width, 0) + nestedTableColumnWidths.length * 3 - 1;
512
+ const availableWidth = tableWidth - columnWidths[0] - 7;
513
+ if (nestedTableWidth > availableWidth) {
514
+ columnWidths[1] = availableWidth;
515
+ } else {
516
+ columnWidths[1] = Math.max(columnWidths[1], nestedTableWidth);
517
+ }
518
+ } else if (value instanceof MultiColumnASCIITable) {
519
+ let nestedTableColumnWidths = [];
520
+ if (canAutoAdjustWidthWhenPossible) {
521
+ const minWidth = value.getMinimumWidth();
522
+ const availableWidth2 = tableWidth - columnWidths[0] - 7;
523
+ const adjustedWidth = clamp(availableWidth2, minWidth, availableWidth2);
524
+ nestedTableColumnWidths = value.calculateColumnWidths({
525
+ tableWidth: adjustedWidth
526
+ });
527
+ } else {
528
+ nestedTableColumnWidths = value.calculateColumnWidths();
529
+ }
530
+ const nestedTableWidth = nestedTableColumnWidths.reduce((sum, width) => sum + width, 0) + nestedTableColumnWidths.length * 3 - 1;
531
+ const availableWidth = tableWidth - columnWidths[0] - 7;
532
+ if (nestedTableWidth > availableWidth) {
533
+ columnWidths[1] = availableWidth;
534
+ } else {
535
+ columnWidths[1] = Math.max(columnWidths[1], nestedTableWidth);
536
+ }
537
+ } else if (Array.isArray(value)) {
538
+ for (const nestedCell of value) {
539
+ const nestedKeyWidth = (0, import_string_width3.default)(nestedCell.key);
540
+ const maxNestedKeyWidth = Math.floor((tableWidth - 7) / 2);
541
+ if (nestedKeyWidth > columnWidths[0]) {
542
+ columnWidths[0] = Math.min(nestedKeyWidth, maxNestedKeyWidth);
543
+ columnWidths[1] = Math.max(0, tableWidth - columnWidths[0] - 7);
544
+ }
545
+ if (typeof nestedCell.value === "string") {
546
+ const nestedValueWidth = Math.max(
547
+ ...nestedCell.value.split("\n").map((line) => (0, import_string_width3.default)(line))
548
+ );
549
+ if (nestedValueWidth > columnWidths[1]) {
550
+ columnWidths[1] = Math.min(
551
+ nestedValueWidth,
552
+ tableWidth - columnWidths[0] - 7
553
+ );
554
+ columnWidths[0] = Math.max(0, tableWidth - columnWidths[1] - 7);
555
+ }
556
+ }
557
+ }
558
+ }
559
+ }
560
+ return columnWidths;
561
+ }
562
+ formatValue(value, cellWidth, canAutoAdjustWidthWhenPossible, indent = "") {
563
+ if (typeof value === "string") {
564
+ return value;
565
+ } else if (typeof value === "number") {
566
+ return String(value);
567
+ } else if (typeof value === "boolean") {
568
+ return String(value);
569
+ } else if (value === null) {
570
+ return "null";
571
+ } else if (value === void 0) {
572
+ return "undefined";
573
+ } else if (value instanceof _KeyValueASCIITable) {
574
+ let nestedTableLines;
575
+ if (canAutoAdjustWidthWhenPossible) {
576
+ const minWidth = value.getMinimumWidth();
577
+ const adjustedWidth = clamp(cellWidth, minWidth, cellWidth);
578
+ nestedTableLines = value.toString({ tableWidth: adjustedWidth }).split("\n");
579
+ } else {
580
+ nestedTableLines = value.toString().split("\n");
581
+ }
582
+ const indentedLines = nestedTableLines.map((line) => `${indent}${line}`);
583
+ return indentedLines.join("\n");
584
+ } else if (value instanceof MultiColumnASCIITable) {
585
+ let nestedTableLines;
586
+ if (canAutoAdjustWidthWhenPossible) {
587
+ const minWidth = value.getMinimumWidth();
588
+ const adjustedWidth = clamp(cellWidth, minWidth, cellWidth);
589
+ nestedTableLines = value.toString({ tableWidth: adjustedWidth }).split("\n");
590
+ } else {
591
+ nestedTableLines = value.toString().split("\n");
592
+ }
593
+ const indentedLines = nestedTableLines.map((line) => `${indent}${line}`);
594
+ return indentedLines.join("\n");
595
+ } else if (Array.isArray(value)) {
596
+ const nestedValueLines = [];
597
+ for (const { key, value: nestedValue } of value) {
598
+ const formattedKey = `${indent}${key}:`;
599
+ const formattedValue = this.formatValue(
600
+ nestedValue,
601
+ cellWidth - indent.length - (0, import_string_width3.default)(key) - 2,
602
+ canAutoAdjustWidthWhenPossible,
603
+ `${indent}`
604
+ );
605
+ const wrappedSpacer = padRight("", 4, " ");
606
+ const wrappedValue = formattedValue.split("\n").map((line) => `${indent}${wrappedSpacer}${line}`);
607
+ nestedValueLines.push(formattedKey);
608
+ nestedValueLines.push(...wrappedValue);
609
+ nestedValueLines.push("");
610
+ }
611
+ return nestedValueLines.slice(0, -1).join("\n");
612
+ } else {
613
+ throw new TypeError("Invalid value type provided");
614
+ }
615
+ }
616
+ formatTableRowOnOwnRow(value, width, maxRowLength) {
617
+ const lines = value.split("\n");
618
+ const paddedLines = lines.map((line) => {
619
+ const wrappedLines = ASCIITableUtils.wrapText(line, maxRowLength - 4);
620
+ return wrappedLines.map((wrappedLine) => {
621
+ const padding = padRight(
622
+ "",
623
+ width - (0, import_string_width3.default)(wrappedLine) - 2,
624
+ " "
625
+ );
626
+ return `${wrappedLine}${padding}`;
627
+ }).join("\n");
628
+ });
629
+ return paddedLines.join("\n");
630
+ }
631
+ };
632
+
633
+ // src/lib/error-to-string.ts
634
+ function safeStringify(value) {
635
+ if (value === null || value === void 0) {
636
+ return String(value);
637
+ }
638
+ switch (typeof value) {
639
+ case "string":
640
+ return value;
641
+ case "number":
642
+ case "boolean":
643
+ case "bigint":
644
+ return String(value);
645
+ case "object":
646
+ return JSON.stringify(value);
647
+ case "function":
648
+ return "[Function]";
649
+ case "symbol":
650
+ return value.toString();
651
+ default:
652
+ return String(value);
653
+ }
654
+ }
655
+ function errorToString(error, maxRowLength = 80) {
656
+ const table = errorToASCIITable(error, maxRowLength);
657
+ return table.toString();
658
+ }
659
+ function errorToASCIITable(error, maxRowLength) {
660
+ const table = new KeyValueASCIITable({
661
+ tableWidth: maxRowLength,
662
+ autoAdjustWidthWhenPossible: true
663
+ });
664
+ if (error && typeof error === "object") {
665
+ const err = error;
666
+ table.addRow("Key", "Value");
667
+ if (err["message"]) {
668
+ table.addRow("Message", safeStringify(err["message"]));
669
+ }
670
+ if (err["name"]) {
671
+ table.addRow("Name", safeStringify(err["name"]));
672
+ }
673
+ if (err["code"]) {
674
+ table.addRow("Code", safeStringify(err["code"]));
675
+ }
676
+ if (err["errno"]) {
677
+ table.addRow("Errno", safeStringify(err["errno"]));
678
+ }
679
+ if (err["errPrefix"]) {
680
+ table.addRow("Prefix", safeStringify(err["errPrefix"]));
681
+ }
682
+ if (err["errType"]) {
683
+ table.addRow("errType", safeStringify(err["errType"]));
684
+ }
685
+ if (err["errCode"]) {
686
+ table.addRow("errCode", safeStringify(err["errCode"]));
687
+ }
688
+ if (err["additionalInfo"]) {
689
+ const additionalInfo = err["additionalInfo"];
690
+ const sensitiveFieldNames = err["sensitiveFieldNames"] || [];
691
+ for (const key in additionalInfo) {
692
+ if (sensitiveFieldNames.includes(key)) {
693
+ table.addRow(`AdditionalInfo.${key}`, "***");
694
+ } else {
695
+ const value = additionalInfo[key];
696
+ table.addRow(
697
+ `AdditionalInfo.${key}`,
698
+ stringifyValue(value, table, maxRowLength)
699
+ );
700
+ }
701
+ }
702
+ }
703
+ if (err["stack"]) {
704
+ table.addValueOnSeparateRow("Stack", safeStringify(err["stack"]));
705
+ }
706
+ }
707
+ return table;
708
+ }
709
+ function stringifyValue(value, table, maxRowLength) {
710
+ if (typeof value === "string") {
711
+ return value;
712
+ } else if (Array.isArray(value)) {
713
+ return value.map((item) => {
714
+ const result = stringifyValue(item, table, maxRowLength);
715
+ if (typeof result === "string") {
716
+ return result;
717
+ } else if (result instanceof KeyValueASCIITable) {
718
+ return result.toString();
719
+ } else {
720
+ return JSON.stringify(result);
721
+ }
722
+ }).join(", ");
723
+ } else if (typeof value === "object" && value !== null) {
724
+ if (value instanceof Error) {
725
+ return errorToASCIITable(value, maxRowLength - 4);
726
+ } else {
727
+ const entries = Object.entries(value).map(
728
+ ([key, val]) => ({
729
+ key,
730
+ value: stringifyValue(val, table, maxRowLength - 4)
731
+ })
732
+ );
733
+ return entries;
734
+ }
735
+ } else {
736
+ return String(value);
737
+ }
738
+ }
739
+
740
+ // src/lib/is-promise.ts
741
+ function isPromise(obj) {
742
+ return !!obj && (typeof obj === "object" || typeof obj === "function") && // @ts-expect-error - obj is checked to be object/function, then property access works at runtime
743
+ typeof obj["then"] === "function";
744
+ }
745
+
746
+ // src/lib/is-function.ts
747
+ function isFunction(value) {
748
+ return typeof value === "function" || value instanceof Function;
749
+ }
750
+
751
+ // src/lib/safe-handle-callback.ts
752
+ function safeHandleCallback(callbackName, callback, ...args) {
753
+ const handleError = (error) => {
754
+ if (typeof globalThis.dispatchEvent === "function") {
755
+ globalThis.dispatchEvent(
756
+ new ErrorEvent("reportError", {
757
+ error: new Error(
758
+ `Error in a callback ${callbackName}: ${DOUBLE_EOL}${errorToString(error)}`
759
+ )
760
+ })
761
+ );
762
+ }
763
+ };
764
+ if (isFunction(callback)) {
765
+ try {
766
+ const result = callback(...args);
767
+ if (isPromise(result)) {
768
+ result.catch((error) => {
769
+ handleError(error);
770
+ });
771
+ }
772
+ } catch (error) {
773
+ handleError(error);
774
+ }
775
+ } else {
776
+ handleError(
777
+ new Error(`Callback provided for ${callbackName} is not a function`)
778
+ );
779
+ }
780
+ }
781
+
782
+ // src/lib/process-signal-manager.ts
783
+ var import_ulid = require("ulid");
784
+ var import_readline = __toESM(require("readline"), 1);
785
+ var SHARED_STATE_KEY = /* @__PURE__ */ Symbol.for("lifecycleion.ProcessSignalManager.v1");
786
+ function getSharedState() {
787
+ const g = globalThis;
788
+ if (!g[SHARED_STATE_KEY]) {
789
+ g[SHARED_STATE_KEY] = {
790
+ keypressEventsEmittedOnStdin: false,
791
+ attachedInstances: /* @__PURE__ */ new Set(),
792
+ rawModeOwner: null,
793
+ rawModeEnabledByManager: false
794
+ };
795
+ }
796
+ return g[SHARED_STATE_KEY];
797
+ }
798
+ function transferRawModeOwnership(shared, currentOwner) {
799
+ if (shared.rawModeOwner !== currentOwner) {
800
+ return shared.rawModeOwner;
801
+ }
802
+ if (shared.attachedInstances.size === 0) {
803
+ shared.rawModeOwner = null;
804
+ return null;
805
+ }
806
+ for (const candidateID of shared.attachedInstances) {
807
+ if (shared.attachedInstances.has(candidateID)) {
808
+ shared.rawModeOwner = candidateID;
809
+ return candidateID;
810
+ }
811
+ }
812
+ shared.rawModeOwner = null;
813
+ return null;
814
+ }
815
+ var ProcessSignalManager = class {
816
+ // Unique identifier for this instance, used for tracking in shared state
817
+ instanceID;
818
+ onShutdownRequested;
819
+ onReloadRequested;
820
+ onInfoRequested;
821
+ onDebugRequested;
822
+ shutdownCallbackName;
823
+ reloadCallbackName;
824
+ infoCallbackName;
825
+ debugCallbackName;
826
+ shutdownSignalListeners;
827
+ reloadSignalListener;
828
+ infoSignalListener;
829
+ debugSignalListener;
830
+ keypressHandler;
831
+ _isAttached = false;
832
+ // Throttle state for keyboard events (default 200ms, 0 disables)
833
+ // Track throttle separately per action type so different keys don't interfere with each other
834
+ // Use -Infinity to ensure first press is never throttled (always fires immediately)
835
+ keypressThrottleMS;
836
+ lastActionTimes = {
837
+ shutdown: -Infinity,
838
+ reload: -Infinity,
839
+ info: -Infinity,
840
+ debug: -Infinity
841
+ };
842
+ constructor(options) {
843
+ this.instanceID = (0, import_ulid.ulid)();
844
+ this.onShutdownRequested = options.onShutdownRequested;
845
+ this.onReloadRequested = options.onReloadRequested;
846
+ this.onInfoRequested = options.onInfoRequested;
847
+ this.onDebugRequested = options.onDebugRequested;
848
+ this.shutdownCallbackName = options.shutdownCallbackName ?? "onShutdownRequested";
849
+ this.reloadCallbackName = options.reloadCallbackName ?? "onReloadRequested";
850
+ this.infoCallbackName = options.infoCallbackName ?? "onInfoRequested";
851
+ this.debugCallbackName = options.debugCallbackName ?? "onDebugRequested";
852
+ this.keypressThrottleMS = options.keypressThrottleMS ?? 200;
853
+ if (this.onShutdownRequested) {
854
+ const shutdownCallback = this.onShutdownRequested;
855
+ this.shutdownSignalListeners = {
856
+ SIGINT: () => safeHandleCallback(
857
+ this.shutdownCallbackName,
858
+ shutdownCallback,
859
+ "SIGINT"
860
+ ),
861
+ SIGTERM: () => safeHandleCallback(
862
+ this.shutdownCallbackName,
863
+ shutdownCallback,
864
+ "SIGTERM"
865
+ ),
866
+ SIGTRAP: () => safeHandleCallback(
867
+ this.shutdownCallbackName,
868
+ shutdownCallback,
869
+ "SIGTRAP"
870
+ )
871
+ };
872
+ }
873
+ if (this.onReloadRequested) {
874
+ const reloadCallback = this.onReloadRequested;
875
+ this.reloadSignalListener = () => safeHandleCallback(this.reloadCallbackName, reloadCallback);
876
+ }
877
+ if (this.onInfoRequested) {
878
+ const infoCallback = this.onInfoRequested;
879
+ this.infoSignalListener = () => safeHandleCallback(this.infoCallbackName, infoCallback);
880
+ }
881
+ if (this.onDebugRequested) {
882
+ const debugCallback = this.onDebugRequested;
883
+ this.debugSignalListener = () => safeHandleCallback(this.debugCallbackName, debugCallback);
884
+ }
885
+ }
886
+ /**
887
+ * Check if the manager is currently attached to signals and keypresses.
888
+ */
889
+ get isAttached() {
890
+ return this._isAttached;
891
+ }
892
+ /**
893
+ * Get detailed status information about what the manager is attached to.
894
+ *
895
+ * @returns Status object with handler registration and attachment state
896
+ */
897
+ getStatus() {
898
+ return {
899
+ isAttached: this._isAttached,
900
+ handlers: {
901
+ shutdown: !!this.onShutdownRequested,
902
+ reload: !!this.onReloadRequested,
903
+ info: !!this.onInfoRequested,
904
+ debug: !!this.onDebugRequested
905
+ },
906
+ listeningFor: {
907
+ shutdownSignals: this._isAttached && !!this.shutdownSignalListeners,
908
+ reloadSignal: this._isAttached && !!this.reloadSignalListener,
909
+ infoSignal: this._isAttached && !!this.infoSignalListener,
910
+ debugSignal: this._isAttached && !!this.debugSignalListener,
911
+ // Keypresses are only available if stdin is a TTY
912
+ keypresses: this._isAttached && process.stdin.isTTY && !!this.keypressHandler
913
+ }
914
+ };
915
+ }
916
+ /**
917
+ * Attach signal handlers and start listening for process signals and keyboard events.
918
+ * Idempotent - calling multiple times has no effect.
919
+ */
920
+ attach() {
921
+ if (this._isAttached) {
922
+ return;
923
+ }
924
+ try {
925
+ this.listenForShutdownSignals();
926
+ this.listenForReloadSignal();
927
+ this.listenForInfoSignal();
928
+ this.listenForDebugSignal();
929
+ this.listenForKeyPresses();
930
+ this._isAttached = true;
931
+ } catch (error) {
932
+ this.stopListeningForShutdownSignals();
933
+ this.stopListeningForReloadSignal();
934
+ this.stopListeningForInfoSignal();
935
+ this.stopListeningForDebugSignal();
936
+ this.restoreStdin();
937
+ throw error;
938
+ }
939
+ }
940
+ /**
941
+ * Detach signal handlers and stop listening for process signals and keyboard events.
942
+ * Cleans up all event listeners and restores stdin to normal mode.
943
+ *
944
+ * Idempotent - calling multiple times has no effect.
945
+ */
946
+ detach() {
947
+ if (!this._isAttached) {
948
+ return;
949
+ }
950
+ try {
951
+ this.stopListeningForShutdownSignals();
952
+ this.stopListeningForReloadSignal();
953
+ this.stopListeningForInfoSignal();
954
+ this.stopListeningForDebugSignal();
955
+ this.restoreStdin();
956
+ } finally {
957
+ this._isAttached = false;
958
+ }
959
+ }
960
+ /**
961
+ * Manually trigger a shutdown event
962
+ * if the manager is attached and a shutdown handler is registered
963
+ *
964
+ * @param method - The shutdown method (SIGINT, SIGTERM, or SIGTRAP) that will be passed to the shutdown callback
965
+ * @param shouldBypassAttachCheck - If true, triggers the callback even when not attached (useful for testing)
966
+ */
967
+ triggerShutdown(method, shouldBypassAttachCheck = false) {
968
+ if ((this._isAttached || shouldBypassAttachCheck) && this.onShutdownRequested) {
969
+ safeHandleCallback(
970
+ this.shutdownCallbackName,
971
+ this.onShutdownRequested,
972
+ method
973
+ );
974
+ }
975
+ }
976
+ /**
977
+ * Manually trigger a reload event
978
+ * if the manager is attached and a reload handler is registered
979
+ *
980
+ * @param shouldBypassAttachCheck - If true, triggers the callback even when not attached (useful for testing)
981
+ */
982
+ triggerReload(shouldBypassAttachCheck = false) {
983
+ if ((this._isAttached || shouldBypassAttachCheck) && this.onReloadRequested) {
984
+ safeHandleCallback(this.reloadCallbackName, this.onReloadRequested);
985
+ }
986
+ }
987
+ /**
988
+ * Manually trigger an info event
989
+ * if the manager is attached and an info handler is registered
990
+ *
991
+ * @param shouldBypassAttachCheck - If true, triggers the callback even when not attached (useful for testing)
992
+ */
993
+ triggerInfo(shouldBypassAttachCheck = false) {
994
+ if ((this._isAttached || shouldBypassAttachCheck) && this.onInfoRequested) {
995
+ safeHandleCallback(this.infoCallbackName, this.onInfoRequested);
996
+ }
997
+ }
998
+ /**
999
+ * Manually trigger a debug event
1000
+ * if the manager is attached and a debug handler is registered
1001
+ *
1002
+ * @param shouldBypassAttachCheck - If true, triggers the callback even when not attached (useful for testing)
1003
+ */
1004
+ triggerDebug(shouldBypassAttachCheck = false) {
1005
+ if ((this._isAttached || shouldBypassAttachCheck) && this.onDebugRequested) {
1006
+ safeHandleCallback(this.debugCallbackName, this.onDebugRequested);
1007
+ }
1008
+ }
1009
+ /**
1010
+ * Check if an action should be throttled based on the last time it was successfully triggered.
1011
+ * Uses leading-edge throttle: first press fires immediately, subsequent presses within the
1012
+ * throttle window are ignored. Only updates timestamp when action is allowed (not throttled).
1013
+ *
1014
+ * This is the standard pattern for keyboard shortcuts and prevents accidental double-triggers
1015
+ * while allowing predictable repeated actions at a maximum rate.
1016
+ *
1017
+ * @param action - The action type to check throttling for
1018
+ * @returns true if the action should be throttled (ignored), false otherwise
1019
+ */
1020
+ shouldThrottle(action) {
1021
+ if (this.keypressThrottleMS <= 0) {
1022
+ return false;
1023
+ }
1024
+ const now = Date.now();
1025
+ const timeSinceLastTrigger = now - this.lastActionTimes[action];
1026
+ if (timeSinceLastTrigger < this.keypressThrottleMS) {
1027
+ return true;
1028
+ }
1029
+ this.lastActionTimes[action] = now;
1030
+ return false;
1031
+ }
1032
+ /**
1033
+ * Register handlers for all shutdown signals (SIGINT, SIGTERM, SIGTRAP) if callback is provided.
1034
+ * Each signal will trigger the shutdown callback with the appropriate method.
1035
+ */
1036
+ listenForShutdownSignals() {
1037
+ if (this.shutdownSignalListeners) {
1038
+ for (const signal of Object.keys(
1039
+ this.shutdownSignalListeners
1040
+ )) {
1041
+ process.on(signal, this.shutdownSignalListeners[signal]);
1042
+ }
1043
+ }
1044
+ }
1045
+ /**
1046
+ * Remove handlers for all shutdown signals if they were registered.
1047
+ * Uses the same function references to ensure proper cleanup.
1048
+ */
1049
+ stopListeningForShutdownSignals() {
1050
+ if (this.shutdownSignalListeners) {
1051
+ for (const signal of Object.keys(
1052
+ this.shutdownSignalListeners
1053
+ )) {
1054
+ process.off(signal, this.shutdownSignalListeners[signal]);
1055
+ }
1056
+ }
1057
+ }
1058
+ /**
1059
+ * Register handler for SIGHUP signal if reload callback is provided.
1060
+ * SIGHUP is commonly used to trigger configuration reloads.
1061
+ */
1062
+ listenForReloadSignal() {
1063
+ if (this.reloadSignalListener) {
1064
+ process.on("SIGHUP", this.reloadSignalListener);
1065
+ }
1066
+ }
1067
+ /**
1068
+ * Remove handler for SIGHUP signal.
1069
+ * Uses the same function reference to ensure proper cleanup.
1070
+ */
1071
+ stopListeningForReloadSignal() {
1072
+ if (this.reloadSignalListener) {
1073
+ process.off("SIGHUP", this.reloadSignalListener);
1074
+ }
1075
+ }
1076
+ /**
1077
+ * Register handler for SIGUSR1 signal if info callback is provided.
1078
+ * SIGUSR1 is commonly used for printing stats, health checks, etc.
1079
+ */
1080
+ listenForInfoSignal() {
1081
+ if (this.infoSignalListener) {
1082
+ process.on("SIGUSR1", this.infoSignalListener);
1083
+ }
1084
+ }
1085
+ /**
1086
+ * Remove handler for SIGUSR1 signal.
1087
+ * Uses the same function reference to ensure proper cleanup.
1088
+ */
1089
+ stopListeningForInfoSignal() {
1090
+ if (this.infoSignalListener) {
1091
+ process.off("SIGUSR1", this.infoSignalListener);
1092
+ }
1093
+ }
1094
+ /**
1095
+ * Register handler for SIGUSR2 signal if debug callback is provided.
1096
+ * SIGUSR2 is commonly used for toggling debug mode, dumping state, etc.
1097
+ */
1098
+ listenForDebugSignal() {
1099
+ if (this.debugSignalListener) {
1100
+ process.on("SIGUSR2", this.debugSignalListener);
1101
+ }
1102
+ }
1103
+ /**
1104
+ * Remove handler for SIGUSR2 signal.
1105
+ * Uses the same function reference to ensure proper cleanup.
1106
+ */
1107
+ stopListeningForDebugSignal() {
1108
+ if (this.debugSignalListener) {
1109
+ process.off("SIGUSR2", this.debugSignalListener);
1110
+ }
1111
+ }
1112
+ /**
1113
+ * Enable keyboard event listening if stdin is a TTY.
1114
+ * Sets stdin to raw mode and listens for Ctrl+C, Escape, R, I, and D keypresses.
1115
+ *
1116
+ * Note: Letter keys are case-insensitive (R/r, I/i, D/d all work).
1117
+ *
1118
+ * Uses add-then-check pattern to prevent race conditions:
1119
+ * 1. Add ourselves to attachedInstances first
1120
+ * 2. Check if we're the first (size === 1) to enable raw mode
1121
+ * This ensures no gap where another instance could read stale state.
1122
+ */
1123
+ listenForKeyPresses() {
1124
+ if (!process.stdin.isTTY || this.keypressHandler) {
1125
+ return;
1126
+ }
1127
+ const shared = getSharedState();
1128
+ if (!shared.keypressEventsEmittedOnStdin) {
1129
+ shared.keypressEventsEmittedOnStdin = true;
1130
+ import_readline.default.emitKeypressEvents(process.stdin);
1131
+ }
1132
+ this.keypressHandler = (str, key) => {
1133
+ const keyObj = key;
1134
+ const keyName = keyObj.name;
1135
+ if (keyObj.ctrl && keyName === "c" && this.onShutdownRequested) {
1136
+ if (this.shouldThrottle("shutdown")) {
1137
+ return;
1138
+ }
1139
+ safeHandleCallback(
1140
+ this.shutdownCallbackName,
1141
+ this.onShutdownRequested,
1142
+ "SIGINT"
1143
+ );
1144
+ } else if (keyName === "escape" && this.onShutdownRequested) {
1145
+ if (this.shouldThrottle("shutdown")) {
1146
+ return;
1147
+ }
1148
+ safeHandleCallback(
1149
+ this.shutdownCallbackName,
1150
+ this.onShutdownRequested,
1151
+ "SIGINT"
1152
+ );
1153
+ } else if (keyName === "r" && this.onReloadRequested) {
1154
+ if (this.shouldThrottle("reload")) {
1155
+ return;
1156
+ }
1157
+ safeHandleCallback(this.reloadCallbackName, this.onReloadRequested);
1158
+ } else if (keyName === "i" && this.onInfoRequested) {
1159
+ if (this.shouldThrottle("info")) {
1160
+ return;
1161
+ }
1162
+ safeHandleCallback(this.infoCallbackName, this.onInfoRequested);
1163
+ } else if (keyName === "d" && this.onDebugRequested) {
1164
+ if (this.shouldThrottle("debug")) {
1165
+ return;
1166
+ }
1167
+ safeHandleCallback(this.debugCallbackName, this.onDebugRequested);
1168
+ }
1169
+ };
1170
+ shared.attachedInstances.add(this.instanceID);
1171
+ const isFirstInstance = shared.attachedInstances.size === 1;
1172
+ try {
1173
+ process.stdin.on("keypress", this.keypressHandler);
1174
+ } catch (error) {
1175
+ shared.attachedInstances.delete(this.instanceID);
1176
+ this.keypressHandler = void 0;
1177
+ throw error;
1178
+ }
1179
+ if (isFirstInstance) {
1180
+ if (!process.stdin.isRaw) {
1181
+ try {
1182
+ process.stdin.setRawMode(true);
1183
+ shared.rawModeOwner = this.instanceID;
1184
+ shared.rawModeEnabledByManager = true;
1185
+ } catch (error) {
1186
+ this.cleanupKeypressHandler(shared, true);
1187
+ throw error;
1188
+ }
1189
+ } else if (shared.rawModeEnabledByManager && (shared.rawModeOwner === null || !shared.attachedInstances.has(shared.rawModeOwner))) {
1190
+ shared.rawModeOwner = this.instanceID;
1191
+ } else if (!shared.rawModeEnabledByManager) {
1192
+ shared.rawModeOwner = null;
1193
+ }
1194
+ }
1195
+ if (isFirstInstance) {
1196
+ try {
1197
+ process.stdin.resume();
1198
+ } catch (error) {
1199
+ this.cleanupKeypressHandler(shared);
1200
+ throw error;
1201
+ }
1202
+ }
1203
+ }
1204
+ /**
1205
+ * Helper to clean up keypress handler registration on error.
1206
+ * Removes handler, clears instance from shared state, and restores raw mode if needed.
1207
+ *
1208
+ * @param shared - The shared state object
1209
+ * @param didAttemptRawModeEnable - If true, we attempted to enable raw mode (even if ownership wasn't recorded).
1210
+ * This handles the edge case where setRawMode(true) throws after actually enabling raw mode.
1211
+ */
1212
+ cleanupKeypressHandler(shared, didAttemptRawModeEnable = false) {
1213
+ if (this.keypressHandler) {
1214
+ try {
1215
+ process.stdin.off("keypress", this.keypressHandler);
1216
+ } catch {
1217
+ }
1218
+ this.keypressHandler = void 0;
1219
+ }
1220
+ shared.attachedInstances.delete(this.instanceID);
1221
+ if (didAttemptRawModeEnable && process.stdin.isTTY && process.stdin.isRaw) {
1222
+ shared.rawModeEnabledByManager = true;
1223
+ if (shared.rawModeOwner === null) {
1224
+ shared.rawModeOwner = this.instanceID;
1225
+ }
1226
+ }
1227
+ if (shared.rawModeEnabledByManager && shared.rawModeOwner === this.instanceID && shared.attachedInstances.size > 0) {
1228
+ transferRawModeOwnership(shared, this.instanceID);
1229
+ } else if (shared.rawModeOwner !== null && shared.attachedInstances.size > 0 && shared.rawModeEnabledByManager && !shared.attachedInstances.has(shared.rawModeOwner)) {
1230
+ for (const candidateID of shared.attachedInstances) {
1231
+ if (shared.attachedInstances.has(candidateID)) {
1232
+ shared.rawModeOwner = candidateID;
1233
+ break;
1234
+ }
1235
+ }
1236
+ }
1237
+ const shouldRestoreRawMode = shared.attachedInstances.size === 0 && shared.rawModeEnabledByManager && (shared.rawModeOwner === this.instanceID || didAttemptRawModeEnable && shared.rawModeOwner === null);
1238
+ if (shouldRestoreRawMode) {
1239
+ try {
1240
+ if (process.stdin.isTTY && process.stdin.isRaw) {
1241
+ process.stdin.setRawMode(false);
1242
+ }
1243
+ shared.rawModeOwner = null;
1244
+ shared.rawModeEnabledByManager = false;
1245
+ } catch {
1246
+ if (didAttemptRawModeEnable && shared.rawModeOwner === null) {
1247
+ shared.rawModeOwner = this.instanceID;
1248
+ }
1249
+ }
1250
+ }
1251
+ }
1252
+ /**
1253
+ * Restore stdin to normal mode and clean up keypress listener.
1254
+ * Uses remove-then-check pattern (mirror of add-then-check in attach):
1255
+ * 1. Remove ourselves from attachedInstances first
1256
+ * 2. Check if we're the last (size === 0) to disable raw mode and pause stdin
1257
+ *
1258
+ * Note: Can be called even if keypressHandler is undefined (e.g., during error recovery).
1259
+ * In that case, we still update shared state and attempt terminal restoration if we
1260
+ * were the recorded raw mode owner.
1261
+ */
1262
+ restoreStdin() {
1263
+ const shared = getSharedState();
1264
+ if (this.keypressHandler) {
1265
+ try {
1266
+ process.stdin.off("keypress", this.keypressHandler);
1267
+ } catch {
1268
+ }
1269
+ this.keypressHandler = void 0;
1270
+ }
1271
+ shared.attachedInstances.delete(this.instanceID);
1272
+ const isLastInstance = shared.attachedInstances.size === 0;
1273
+ const isCurrentOwner = shared.rawModeOwner === this.instanceID;
1274
+ if (!isLastInstance && isCurrentOwner && shared.rawModeEnabledByManager) {
1275
+ transferRawModeOwnership(shared, this.instanceID);
1276
+ } else if (!isLastInstance && shared.rawModeOwner !== null && shared.rawModeEnabledByManager && !shared.attachedInstances.has(shared.rawModeOwner)) {
1277
+ for (const candidateID of shared.attachedInstances) {
1278
+ if (shared.attachedInstances.has(candidateID)) {
1279
+ shared.rawModeOwner = candidateID;
1280
+ break;
1281
+ }
1282
+ }
1283
+ }
1284
+ if (isLastInstance && shared.rawModeOwner === this.instanceID && shared.rawModeEnabledByManager) {
1285
+ try {
1286
+ if (process.stdin.isTTY && process.stdin.isRaw) {
1287
+ process.stdin.setRawMode(false);
1288
+ }
1289
+ shared.rawModeOwner = null;
1290
+ shared.rawModeEnabledByManager = false;
1291
+ } catch {
1292
+ }
1293
+ }
1294
+ if (isLastInstance) {
1295
+ try {
1296
+ process.stdin.pause();
1297
+ } catch {
1298
+ }
1299
+ }
1300
+ }
1301
+ };
1302
+ // Annotate the CommonJS export names for ESM import in node:
1303
+ 0 && (module.exports = {
1304
+ ProcessSignalManager
1305
+ });
1306
+ //# sourceMappingURL=process-signal-manager.cjs.map