@promptctl/rich-js 0.18.0 → 0.18.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 (221) hide show
  1. package/dist/core/anchor.d.ts +45 -0
  2. package/dist/core/anchor.js +39 -0
  3. package/dist/core/ansi.d.ts +65 -0
  4. package/dist/core/ansi.js +231 -0
  5. package/dist/core/box.d.ts +143 -0
  6. package/dist/core/box.js +379 -0
  7. package/dist/core/cells.d.ts +159 -0
  8. package/dist/core/cells.js +287 -0
  9. package/dist/core/color.d.ts +246 -0
  10. package/dist/core/color.js +1038 -0
  11. package/dist/core/console.d.ts +165 -0
  12. package/dist/core/console.js +527 -0
  13. package/dist/core/emoji.d.ts +24 -0
  14. package/dist/core/emoji.js +391 -0
  15. package/dist/core/export-html.d.ts +59 -0
  16. package/dist/core/export-html.js +200 -0
  17. package/dist/core/export-lines.d.ts +121 -0
  18. package/dist/core/export-lines.js +141 -0
  19. package/dist/core/highlighter.d.ts +33 -0
  20. package/dist/core/highlighter.js +124 -0
  21. package/dist/core/json.d.ts +27 -0
  22. package/dist/core/json.js +53 -0
  23. package/dist/core/markup.d.ts +119 -0
  24. package/dist/core/markup.js +731 -0
  25. package/dist/core/measure.d.ts +27 -0
  26. package/dist/core/measure.js +62 -0
  27. package/dist/core/oklch.d.ts +161 -0
  28. package/dist/core/oklch.js +312 -0
  29. package/dist/core/osc8.d.ts +68 -0
  30. package/dist/core/osc8.js +90 -0
  31. package/dist/core/place.d.ts +30 -0
  32. package/dist/core/place.js +51 -0
  33. package/dist/core/pretty.d.ts +144 -0
  34. package/dist/core/pretty.js +476 -0
  35. package/dist/core/protocol.d.ts +267 -0
  36. package/dist/core/protocol.js +163 -0
  37. package/dist/core/render.d.ts +84 -0
  38. package/dist/core/render.js +145 -0
  39. package/dist/core/segment.d.ts +161 -0
  40. package/dist/core/segment.js +492 -0
  41. package/dist/core/spinnerData.d.ts +12 -0
  42. package/dist/core/spinnerData.js +117 -0
  43. package/dist/core/strip.d.ts +141 -0
  44. package/dist/core/strip.js +305 -0
  45. package/dist/core/style.d.ts +169 -0
  46. package/dist/core/style.js +695 -0
  47. package/dist/core/subscription.d.ts +12 -0
  48. package/dist/core/subscription.js +12 -0
  49. package/dist/core/text.d.ts +256 -0
  50. package/dist/core/text.js +976 -0
  51. package/dist/core/wrap.d.ts +41 -0
  52. package/dist/core/wrap.js +127 -0
  53. package/dist/host/app.d.ts +121 -0
  54. package/dist/host/app.js +255 -0
  55. package/dist/host/host-environment.d.ts +26 -0
  56. package/dist/host/host-environment.js +44 -0
  57. package/dist/host/index.d.ts +5 -0
  58. package/dist/host/index.js +3 -0
  59. package/dist/host/terminal-host.d.ts +179 -0
  60. package/dist/host/terminal-host.js +186 -0
  61. package/dist/index.d.ts +91 -0
  62. package/dist/index.js +107 -0
  63. package/dist/node/prompt.d.ts +21 -0
  64. package/dist/node/prompt.js +30 -0
  65. package/dist/node/save.d.ts +17 -0
  66. package/dist/node/save.js +21 -0
  67. package/dist/node/terminal-host.d.ts +113 -0
  68. package/dist/node/terminal-host.js +227 -0
  69. package/dist/node/traceback.d.ts +37 -0
  70. package/dist/node/traceback.js +134 -0
  71. package/dist/renderables/align.d.ts +16 -0
  72. package/dist/renderables/align.js +33 -0
  73. package/dist/renderables/columns.d.ts +61 -0
  74. package/dist/renderables/columns.js +152 -0
  75. package/dist/renderables/constrain.d.ts +15 -0
  76. package/dist/renderables/constrain.js +37 -0
  77. package/dist/renderables/embed.d.ts +50 -0
  78. package/dist/renderables/embed.js +71 -0
  79. package/dist/renderables/flexStrip.d.ts +41 -0
  80. package/dist/renderables/flexStrip.js +200 -0
  81. package/dist/renderables/group.d.ts +11 -0
  82. package/dist/renderables/group.js +17 -0
  83. package/dist/renderables/layout.d.ts +92 -0
  84. package/dist/renderables/layout.js +312 -0
  85. package/dist/renderables/live.d.ts +50 -0
  86. package/dist/renderables/live.js +175 -0
  87. package/dist/renderables/markdown.d.ts +24 -0
  88. package/dist/renderables/markdown.js +184 -0
  89. package/dist/renderables/padding.d.ts +38 -0
  90. package/dist/renderables/padding.js +141 -0
  91. package/dist/renderables/panel.d.ts +116 -0
  92. package/dist/renderables/panel.js +307 -0
  93. package/dist/renderables/progress.d.ts +90 -0
  94. package/dist/renderables/progress.js +238 -0
  95. package/dist/renderables/progressBar.d.ts +31 -0
  96. package/dist/renderables/progressBar.js +53 -0
  97. package/dist/renderables/prompt.d.ts +49 -0
  98. package/dist/renderables/prompt.js +125 -0
  99. package/dist/renderables/rule.d.ts +25 -0
  100. package/dist/renderables/rule.js +90 -0
  101. package/dist/renderables/spinner.d.ts +31 -0
  102. package/dist/renderables/spinner.js +70 -0
  103. package/dist/renderables/status.d.ts +23 -0
  104. package/dist/renderables/status.js +60 -0
  105. package/dist/renderables/syntax.d.ts +35 -0
  106. package/dist/renderables/syntax.js +115 -0
  107. package/dist/renderables/table.d.ts +194 -0
  108. package/dist/renderables/table.js +795 -0
  109. package/dist/renderables/traceback.d.ts +31 -0
  110. package/dist/renderables/traceback.js +108 -0
  111. package/dist/renderables/tree.d.ts +68 -0
  112. package/dist/renderables/tree.js +150 -0
  113. package/dist/renderables/viewport.d.ts +114 -0
  114. package/dist/renderables/viewport.js +198 -0
  115. package/dist/template-bindings/color-funcs.d.ts +87 -0
  116. package/dist/template-bindings/color-funcs.js +217 -0
  117. package/dist/template-bindings/helpers.d.ts +24 -0
  118. package/dist/template-bindings/helpers.js +48 -0
  119. package/dist/template-bindings/index.d.ts +107 -0
  120. package/dist/template-bindings/index.js +146 -0
  121. package/dist/template-bindings/palette-funcs.d.ts +94 -0
  122. package/dist/template-bindings/palette-funcs.js +141 -0
  123. package/dist/template-bindings/style-funcs.d.ts +28 -0
  124. package/dist/template-bindings/style-funcs.js +155 -0
  125. package/dist/themes/buildPalette.d.ts +36 -0
  126. package/dist/themes/buildPalette.js +56 -0
  127. package/dist/themes/colorMath.d.ts +82 -0
  128. package/dist/themes/colorMath.js +254 -0
  129. package/dist/themes/colorRef.d.ts +51 -0
  130. package/dist/themes/colorRef.js +96 -0
  131. package/dist/themes/data/ansi-tables.d.ts +14 -0
  132. package/dist/themes/data/ansi-tables.js +49 -0
  133. package/dist/themes/data/atom-one-dark.d.ts +3 -0
  134. package/dist/themes/data/atom-one-dark.js +177 -0
  135. package/dist/themes/data/atom-one-light.d.ts +3 -0
  136. package/dist/themes/data/atom-one-light.js +177 -0
  137. package/dist/themes/data/catppuccin-frappe.d.ts +3 -0
  138. package/dist/themes/data/catppuccin-frappe.js +177 -0
  139. package/dist/themes/data/catppuccin-latte.d.ts +3 -0
  140. package/dist/themes/data/catppuccin-latte.js +177 -0
  141. package/dist/themes/data/catppuccin-macchiato.d.ts +3 -0
  142. package/dist/themes/data/catppuccin-macchiato.js +177 -0
  143. package/dist/themes/data/catppuccin-mocha.d.ts +3 -0
  144. package/dist/themes/data/catppuccin-mocha.js +177 -0
  145. package/dist/themes/data/cyberpunk.d.ts +17 -0
  146. package/dist/themes/data/cyberpunk.js +193 -0
  147. package/dist/themes/data/default.d.ts +3 -0
  148. package/dist/themes/data/default.js +160 -0
  149. package/dist/themes/data/dracula.d.ts +3 -0
  150. package/dist/themes/data/dracula.js +177 -0
  151. package/dist/themes/data/flexoki.d.ts +3 -0
  152. package/dist/themes/data/flexoki.js +177 -0
  153. package/dist/themes/data/gruvbox.d.ts +3 -0
  154. package/dist/themes/data/gruvbox.js +177 -0
  155. package/dist/themes/data/index.d.ts +35 -0
  156. package/dist/themes/data/index.js +64 -0
  157. package/dist/themes/data/monokai.d.ts +3 -0
  158. package/dist/themes/data/monokai.js +177 -0
  159. package/dist/themes/data/nord.d.ts +3 -0
  160. package/dist/themes/data/nord.js +177 -0
  161. package/dist/themes/data/rose-pine-dawn.d.ts +3 -0
  162. package/dist/themes/data/rose-pine-dawn.js +177 -0
  163. package/dist/themes/data/rose-pine-moon.d.ts +3 -0
  164. package/dist/themes/data/rose-pine-moon.js +177 -0
  165. package/dist/themes/data/rose-pine.d.ts +3 -0
  166. package/dist/themes/data/rose-pine.js +177 -0
  167. package/dist/themes/data/solarized-dark.d.ts +3 -0
  168. package/dist/themes/data/solarized-dark.js +177 -0
  169. package/dist/themes/data/solarized-light.d.ts +3 -0
  170. package/dist/themes/data/solarized-light.js +177 -0
  171. package/dist/themes/data/svg-export.d.ts +3 -0
  172. package/dist/themes/data/svg-export.js +177 -0
  173. package/dist/themes/data/textual-ansi.d.ts +3 -0
  174. package/dist/themes/data/textual-ansi.js +160 -0
  175. package/dist/themes/data/textual-dark.d.ts +3 -0
  176. package/dist/themes/data/textual-dark.js +160 -0
  177. package/dist/themes/data/textual-light.d.ts +3 -0
  178. package/dist/themes/data/textual-light.js +160 -0
  179. package/dist/themes/data/tokyo-night.d.ts +3 -0
  180. package/dist/themes/data/tokyo-night.js +177 -0
  181. package/dist/themes/data/types.d.ts +31 -0
  182. package/dist/themes/data/types.js +10 -0
  183. package/dist/themes/palette.d.ts +21 -0
  184. package/dist/themes/palette.js +28 -0
  185. package/dist/themes/ramp.d.ts +83 -0
  186. package/dist/themes/ramp.js +122 -0
  187. package/dist/themes/registry.d.ts +44 -0
  188. package/dist/themes/registry.js +94 -0
  189. package/dist/themes/terminalThemes.d.ts +49 -0
  190. package/dist/themes/terminalThemes.js +63 -0
  191. package/dist/themes/transpose.d.ts +87 -0
  192. package/dist/themes/transpose.js +138 -0
  193. package/dist/widgets/button.d.ts +49 -0
  194. package/dist/widgets/button.js +208 -0
  195. package/dist/widgets/checkbox.d.ts +41 -0
  196. package/dist/widgets/checkbox.js +157 -0
  197. package/dist/widgets/dropdown.d.ts +67 -0
  198. package/dist/widgets/dropdown.js +450 -0
  199. package/dist/widgets/event-router.d.ts +71 -0
  200. package/dist/widgets/event-router.js +629 -0
  201. package/dist/widgets/focus-manager.d.ts +45 -0
  202. package/dist/widgets/focus-manager.js +191 -0
  203. package/dist/widgets/hit.d.ts +64 -0
  204. package/dist/widgets/hit.js +113 -0
  205. package/dist/widgets/index.d.ts +20 -0
  206. package/dist/widgets/index.js +14 -0
  207. package/dist/widgets/slider.d.ts +57 -0
  208. package/dist/widgets/slider.js +270 -0
  209. package/dist/widgets/static-item.d.ts +34 -0
  210. package/dist/widgets/static-item.js +54 -0
  211. package/dist/widgets/text-input.d.ts +274 -0
  212. package/dist/widgets/text-input.js +1165 -0
  213. package/dist/widgets/toggle.d.ts +44 -0
  214. package/dist/widgets/toggle.js +180 -0
  215. package/dist/widgets/types.d.ts +87 -0
  216. package/dist/widgets/types.js +30 -0
  217. package/dist/widgets/widget-app.d.ts +63 -0
  218. package/dist/widgets/widget-app.js +199 -0
  219. package/dist/widgets/widget-base.d.ts +40 -0
  220. package/dist/widgets/widget-base.js +165 -0
  221. package/package.json +6 -2
@@ -0,0 +1,476 @@
1
+ /**
2
+ * Pretty — formats JavaScript data structures with highlighting.
3
+ *
4
+ * Lives in `core/` beside `markup` and `emoji` because it does their job: turn
5
+ * foreign input into `RichText`. It composes no other renderable — the trait
6
+ * every file in `renderables/` shares and this one does not — and its imports
7
+ * are core primitives only. `Console.print` accepts `unknown` and must turn any
8
+ * of it into something renderable, so the formatter has to sit where `console`
9
+ * can reach it without an upward edge. [LAW:one-way-deps]
10
+ *
11
+ * Two traversals share this file, and the split is the whole design. `_format`
12
+ * lays a value out across lines; `_oneLine` answers only "does this fit on one
13
+ * line, and if so what is it?". They meet at `_shape`, which describes a
14
+ * container without committing to either layout. One traversal answering both
15
+ * questions is what made this formatter exponential: every child was rendered
16
+ * once to probe it and again to place it, so a node at depth d was visited 2^d
17
+ * times.
18
+ */
19
+ import { cellLen } from "./cells.js";
20
+ import { RichText } from "./text.js";
21
+ import { ReprHighlighter } from "./highlighter.js";
22
+ const reprHighlighter = new ReprHighlighter();
23
+ const rootFrame = (maxWidth) => ({
24
+ inset: 0,
25
+ level: 0,
26
+ maxWidth,
27
+ column: 0,
28
+ reserve: 0,
29
+ open: new WeakSet(),
30
+ });
31
+ /**
32
+ * The column reached after `text` is appended to a line currently at `column`.
33
+ *
34
+ * A hole's formatted value can itself span multiple lines — a nested
35
+ * container that failed its own compact try. What comes after it (a Map
36
+ * entry's tail, the next hole) sits after `text`'s *last* line, not at
37
+ * `column + cellLen(text)`, so a multi-line insert resets the column to that
38
+ * last line's width instead of accumulating across lines that were never on
39
+ * the same row.
40
+ */
41
+ function lineColumn(column, text) {
42
+ const lastNewline = text.lastIndexOf("\n");
43
+ return lastNewline === -1 ? column + cellLen(text) : cellLen(text.slice(lastNewline + 1));
44
+ }
45
+ /**
46
+ * The text, when it is a single line no wider than `budget` — otherwise `null`.
47
+ *
48
+ * The one definition of "fits on one line" in this file, and it has to name
49
+ * both halves: `cellLen` scores a newline as zero cells, so a width check alone
50
+ * accepted multi-line text as compact. That is how a `Map` nested in an object
51
+ * used to render as `{ m: Map {` — a one-line object with an expansion wedged
52
+ * inside it and the closing brace back at column 0.
53
+ */
54
+ function fitOneLine(text, budget) {
55
+ return text.includes("\n") || cellLen(text) > budget ? null : text;
56
+ }
57
+ /**
58
+ * The elements of an indexed sequence, or `null` for anything that isn't one.
59
+ *
60
+ * A typed array is an array with a fixed element type, and neither of the two
61
+ * questions asked elsewhere in this file recognises it: `Array.isArray` says
62
+ * false, and its own `toString` answers the bare `1,2,3` — no brackets, nothing
63
+ * for the highlighter to colour per element. Both spellings reach the one arm
64
+ * that knows what a sequence looks like. `DataView` is excluded because it is a
65
+ * window onto bytes, not a sequence of values.
66
+ *
67
+ * Returned as `ArrayLike` rather than a materialised array because both
68
+ * spellings already are one. Converting here would box every element of a
69
+ * multi-megabyte `Buffer` to keep the first `maxLength` of them — bounding the
70
+ * output while leaving the cost of producing it unbounded.
71
+ */
72
+ function indexedElements(value) {
73
+ if (Array.isArray(value))
74
+ return value;
75
+ if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
76
+ return value;
77
+ }
78
+ return null;
79
+ }
80
+ /**
81
+ * The first `limit` items of a sequence, pulled and no more.
82
+ *
83
+ * A `Map` or `Set` reaches its size through `.size`, which iterates nothing, so
84
+ * spreading one only ever served to throw the tail away — `print` of a
85
+ * half-million-entry cache walked all of it to show a hundred. `Infinity` is
86
+ * the unbounded case and never breaks.
87
+ */
88
+ function take(source, limit) {
89
+ const taken = [];
90
+ if (limit <= 0)
91
+ return taken;
92
+ for (const item of source) {
93
+ taken.push(item);
94
+ if (taken.length >= limit)
95
+ break;
96
+ }
97
+ return taken;
98
+ }
99
+ /**
100
+ * What a value renders as when reading it threw instead of producing it.
101
+ *
102
+ * `Pretty` reflects on data it did not create, and every reflection it performs
103
+ * — a property getter, `Object.keys`, an iterator, `toString` — can throw. The
104
+ * message travels into the output, so the failure stays visible and attributed
105
+ * to the position that produced it. [LAW:no-silent-failure] the error is
106
+ * carried rather than swallowed; a marker naming its cause is not an
107
+ * answer-shaped void, and a diagnostic that takes the program down over one
108
+ * lazily-computed field is unusable on the objects it is most wanted for.
109
+ */
110
+ function threw(error) {
111
+ return `[Threw: ${error instanceof Error ? error.message : String(error)}]`;
112
+ }
113
+ /**
114
+ * Does this value carry its own string form, or must we reflect on its keys?
115
+ *
116
+ * A `Date`, an `Error`, a `RegExp`, or any object that defines `toString`
117
+ * answers the display question itself, and reflecting on such a value throws
118
+ * that answer away — `Object.keys(new Date())` is empty, so key-reflection
119
+ * renders it `{}`. Inheriting `Object.prototype.toString` is the opposite
120
+ * signal: it yields `[object Object]`, a non-answer, so the keys are all the
121
+ * information there is.
122
+ *
123
+ * Both clauses are load-bearing. The identity check separates the two
124
+ * populations; the `typeof` check is what makes `Object.create(null)` — which
125
+ * has no `toString` at all — reflect rather than throw.
126
+ */
127
+ function describesItself(value) {
128
+ const asRecord = value;
129
+ return (typeof asRecord[Symbol.toPrimitive] === "function" ||
130
+ (typeof asRecord.toString === "function" &&
131
+ asRecord.toString !== Object.prototype.toString));
132
+ }
133
+ /** What joins a container's positions on one line. Its width is charged for, so it is named once. */
134
+ const SEPARATOR = ", ";
135
+ /**
136
+ * What joins a container's positions across lines, once it has expanded —
137
+ * `SEPARATOR` without the trailing space a newline already provides.
138
+ * rich-pretty-xms: named, and derived rather than a second hand-typed
139
+ * literal, so the width it costs a non-last slot's own compact try —
140
+ * reserved via `Frame.reserve` — cannot drift from what `_formatObject`
141
+ * actually joins with.
142
+ */
143
+ const EXPAND_SEPARATOR = SEPARATOR.trimEnd();
144
+ /** The marker for positions the bound dropped, or nothing when it dropped none. */
145
+ const elided = (dropped) => dropped > 0 ? [{ head: `... +${dropped}`, holes: [] }] : [];
146
+ export class Pretty {
147
+ data;
148
+ indent;
149
+ expandAll;
150
+ maxLength;
151
+ maxString;
152
+ maxDepth;
153
+ indentGuides;
154
+ highlighter;
155
+ constructor(data, options) {
156
+ this.data = data;
157
+ this.indent = options?.indent ?? 4;
158
+ this.expandAll = options?.expandAll ?? false;
159
+ this.maxLength = options?.maxLength;
160
+ this.maxString = options?.maxString;
161
+ this.maxDepth = options?.maxDepth ?? Infinity;
162
+ this.indentGuides = options?.indentGuides !== false;
163
+ this.highlighter = options?.highlighter ?? reprHighlighter;
164
+ }
165
+ *render(options) {
166
+ yield* this.toText(options).render(options);
167
+ }
168
+ /** The value laid out for `options.maxWidth` and highlighted: the text this renders. */
169
+ toText(options) {
170
+ const formatted = this._format(this.data, rootFrame(options.maxWidth));
171
+ const text = new RichText(formatted, { end: "" });
172
+ this.highlighter.highlight(text);
173
+ if (this.indentGuides) {
174
+ this._addIndentGuides(text);
175
+ }
176
+ return text;
177
+ }
178
+ measure(_options) {
179
+ const formatted = this._format(this.data, rootFrame(_options.maxWidth));
180
+ const lines = formatted.split("\n");
181
+ let max = 0;
182
+ for (const line of lines) {
183
+ max = Math.max(max, cellLen(line));
184
+ }
185
+ return { minimum: 1, maximum: Math.min(max, _options.maxWidth) };
186
+ }
187
+ /**
188
+ * The text a value shows without being reflected on, or `null` when it is an
189
+ * object and the shape arms own it.
190
+ *
191
+ * Every kind answered here renders the same wherever it sits — no
192
+ * indentation, no width to fit — which is why one method serves both
193
+ * traversals.
194
+ */
195
+ _scalar(value) {
196
+ if (value === null)
197
+ return "null";
198
+ if (value === undefined)
199
+ return "undefined";
200
+ switch (typeof value) {
201
+ case "string": {
202
+ // The dropped count is an annotation about the value, not part of it,
203
+ // so it goes after the closing quote — the way `maxLength`'s `... +N`
204
+ // sits beside the kept entries rather than inside the last one. Inside
205
+ // the quotes it reads as content, and copying it out yields a string
206
+ // the program never held.
207
+ if (this.maxString === undefined || value.length <= this.maxString) {
208
+ return JSON.stringify(value);
209
+ }
210
+ return JSON.stringify(value.slice(0, this.maxString)) + `+${value.length - this.maxString}`;
211
+ }
212
+ case "number":
213
+ case "bigint":
214
+ case "boolean":
215
+ return String(value);
216
+ case "symbol":
217
+ return value.toString();
218
+ case "function":
219
+ return `[Function: ${value.name || "anonymous"}]`;
220
+ }
221
+ return null;
222
+ }
223
+ /**
224
+ * A container, or the text standing in for one that is empty or past the
225
+ * depth cap.
226
+ *
227
+ * `positions` is a thunk because both of those answers are reachable from
228
+ * `size` alone, and reaching a position is not free: a `Map` or `Set` reaches
229
+ * its own through an iterator, so enumerating one only to elide it drains a
230
+ * container to print `Set {...}`. `size` also says how many positions were
231
+ * dropped, which is where the elision marker comes from — one derivation, so
232
+ * the count and the bound cannot disagree.
233
+ */
234
+ _container(open, close, pad, size, level, positions) {
235
+ if (size === 0)
236
+ return { kind: "text", text: open + close };
237
+ if (level >= this.maxDepth)
238
+ return { kind: "text", text: open + "..." + close };
239
+ const slots = positions();
240
+ return { kind: "container", open, close, pad, slots: [...slots, ...elided(size - slots.length)] };
241
+ }
242
+ /**
243
+ * The brackets and positions of an object, layout-free. See `Shape`.
244
+ *
245
+ * `bound` is the most positions the caller could ever use. Laying out passes
246
+ * `Infinity`, because it prints every position it is handed. A probe passes
247
+ * what is left of its line, which is already more positions than a fitting
248
+ * one could hold — `SEPARATOR` charges two cells apiece, so a container with
249
+ * more positions than `budget` overruns however narrow its contents are.
250
+ * Reaching past it only ever feeds a join that returns `null`, and reaching a
251
+ * position is what drains a `Map` or `Set`.
252
+ */
253
+ _shape(value, level, bound) {
254
+ // Clamped because a probe's budget goes negative once a line is overrun,
255
+ // and `slice` reads a negative end as counting from the far end — it would
256
+ // keep all but the last few keys where the other arms take none.
257
+ const cap = Math.max(0, Math.min(this.maxLength ?? Infinity, bound));
258
+ const elements = indexedElements(value);
259
+ if (elements !== null) {
260
+ return this._container("[", "]", "", elements.length, level, () => {
261
+ // Positions rather than values: each index is read in its own slot, so
262
+ // one throwing accessor costs its own slot, not the whole sequence.
263
+ const shown = Math.min(elements.length, cap);
264
+ return Array.from({ length: shown }, (_, i) => ({
265
+ head: "",
266
+ holes: [{ read: () => elements[i], tail: "" }],
267
+ }));
268
+ });
269
+ }
270
+ if (value instanceof Map) {
271
+ return this._container("Map {", "}", " ", value.size, level, () => take(value.entries(), cap).map(([k, v]) => ({
272
+ head: "",
273
+ holes: [{ read: () => k, tail: " => " }, { read: () => v, tail: "" }],
274
+ })));
275
+ }
276
+ if (value instanceof Set) {
277
+ return this._container("Set {", "}", " ", value.size, level, () => take(value, cap).map((v) => ({
278
+ head: "",
279
+ holes: [{ read: () => v, tail: "" }],
280
+ })));
281
+ }
282
+ // Objects that answer the display question themselves. Sits below the
283
+ // Array/Map/Set arms deliberately: an array also overrides `toString`, but
284
+ // "1,2,3" is a poorer answer than the structural form above.
285
+ if (describesItself(value))
286
+ return { kind: "text", text: String(value) };
287
+ // Plain objects — no self-description, so the keys are the whole story.
288
+ const obj = value;
289
+ const keys = Object.keys(obj);
290
+ return this._container("{", "}", " ", keys.length, level, () => keys.slice(0, cap).map((k) => ({
291
+ head: `${k}: `,
292
+ holes: [{ read: () => obj[k], tail: "" }],
293
+ })));
294
+ }
295
+ /** The laid-out form of a value, expanded across lines wherever one line will not do. */
296
+ _format(value, at) {
297
+ const scalar = this._scalar(value);
298
+ if (scalar !== null)
299
+ return scalar;
300
+ const object = value;
301
+ if (at.open.has(object))
302
+ return "[Circular]";
303
+ at.open.add(object);
304
+ try {
305
+ return this._formatObject(object, at);
306
+ }
307
+ catch (error) {
308
+ // The container's *shape* would not be read — `Object.keys`, an iterator,
309
+ // `toString`. Nothing can be enumerated, so the whole container degrades;
310
+ // a value that merely would not be read degrades alone, in its own slot.
311
+ return threw(error);
312
+ }
313
+ finally {
314
+ at.open.delete(object);
315
+ }
316
+ }
317
+ /** The arms for a non-null object, with `value` already on the open path. */
318
+ _formatObject(value, at) {
319
+ const shape = this._shape(value, at.level, Infinity);
320
+ if (shape.kind === "text")
321
+ return shape.text;
322
+ if (!this.expandAll) {
323
+ // rich-pretty-xms: budget from `at.column` and `at.reserve`, not from
324
+ // `at.inset` alone. `at.column` is where *this* value's text actually
325
+ // starts on its line, which already includes whatever `_expandSlot`
326
+ // prepended for us (a key and its separator, a Map entry's `" => "`,
327
+ // ...); `at.reserve` is what a fixed piece of literal text — the rest
328
+ // of this hole's own tail, or the trailing `,` a non-last slot gets
329
+ // joined with — is known to cost right after, before this value's own
330
+ // text even starts. Deriving the budget from the indent alone assumed
331
+ // nothing precedes *or follows* the value on its line, which is only
332
+ // true at the root and for the last hole of an array's last element.
333
+ const compact = this._joinOneLine(shape, {
334
+ level: at.level + 1,
335
+ budget: at.maxWidth - at.column - at.reserve,
336
+ open: at.open,
337
+ });
338
+ if (compact !== null)
339
+ return compact;
340
+ }
341
+ const indentStr = " ".repeat(this.indent * at.inset);
342
+ const innerIndent = " ".repeat(this.indent * (at.inset + 1));
343
+ // Every non-last slot gets `EXPAND_SEPARATOR` appended right after it
344
+ // below, on the same line as whatever its own last character was — the
345
+ // last slot doesn't. Two frames, not one per slot: `reserve` is the only
346
+ // field that varies, and it only ever takes these two values.
347
+ const base = { inset: at.inset + 1, level: at.level + 1, maxWidth: at.maxWidth, column: cellLen(innerIndent), open: at.open };
348
+ const midFrame = { ...base, reserve: cellLen(EXPAND_SEPARATOR) };
349
+ const lastFrame = { ...base, reserve: 0 };
350
+ const lastSlot = shape.slots.length - 1;
351
+ const parts = shape.slots.map((slot, i) => innerIndent + this._expandSlot(slot, i === lastSlot ? lastFrame : midFrame));
352
+ return shape.open + "\n" + parts.join(EXPAND_SEPARATOR + "\n") + "\n" + indentStr + shape.close;
353
+ }
354
+ /**
355
+ * One position, with every value in it laid out.
356
+ *
357
+ * `at.column` is where `slot.head` begins. Rather than hand-tracking a
358
+ * second, parallel "column so far" alongside `out` — two values a future
359
+ * edit could update out of step, silently reintroducing a stale-budget bug
360
+ * of the same shape this file just fixed — each hole derives its own
361
+ * column fresh from `out` via `lineColumn`, the one place "text just
362
+ * emitted" becomes "column now". [LAW:one-source-of-truth] `out` is
363
+ * already the complete record; `column` is a read of it, not a second copy
364
+ * of the same fact. `_joinOneLine`'s probe sibling tracks the analogous
365
+ * thing via `budget` shrinking instead, because a probe already discards
366
+ * anything that overruns and so never needs to know where a multi-line
367
+ * insert's last line ends.
368
+ *
369
+ * Each hole's `reserve` is its own `tail` plus, only for the slot's last
370
+ * hole, whatever `at.reserve` already asked this whole slot to leave room
371
+ * for (`_formatObject`'s trailing `,`). An earlier hole's tail is never
372
+ * folded into a later hole's reserve — it is spent, not carried, the moment
373
+ * `out` grows past it.
374
+ */
375
+ _expandSlot(slot, at) {
376
+ let out = slot.head;
377
+ const lastHole = slot.holes.length - 1;
378
+ for (let i = 0; i < slot.holes.length; i++) {
379
+ const hole = slot.holes[i];
380
+ // This is the read that costs the least when it fails: neighbours are
381
+ // unaffected, so `{ a: 1, b: [Threw: …], c: 3 }` still shows everything
382
+ // that could be read.
383
+ let text;
384
+ try {
385
+ const reserve = cellLen(hole.tail) + (i === lastHole ? at.reserve : 0);
386
+ text = this._format(hole.read(), { ...at, column: lineColumn(at.column, out), reserve });
387
+ }
388
+ catch (error) {
389
+ text = threw(error);
390
+ }
391
+ out += text + hole.tail;
392
+ }
393
+ return out;
394
+ }
395
+ /** The one-line form of a value, or `null` when it will not fit `at.budget`. */
396
+ _oneLine(value, at) {
397
+ const scalar = this._scalar(value);
398
+ if (scalar !== null)
399
+ return fitOneLine(scalar, at.budget);
400
+ const object = value;
401
+ if (at.open.has(object))
402
+ return fitOneLine("[Circular]", at.budget);
403
+ at.open.add(object);
404
+ try {
405
+ const shape = this._shape(object, at.level, at.budget);
406
+ if (shape.kind === "text")
407
+ return fitOneLine(shape.text, at.budget);
408
+ return this._joinOneLine(shape, { level: at.level + 1, budget: at.budget, open: at.open });
409
+ }
410
+ catch (error) {
411
+ return fitOneLine(threw(error), at.budget);
412
+ }
413
+ finally {
414
+ at.open.delete(object);
415
+ }
416
+ }
417
+ /**
418
+ * A container's positions on one line, or `null` as soon as they overrun.
419
+ *
420
+ * The budget is spent as it goes and each position is asked for only what is
421
+ * left, so a subtree that has already outgrown the line is abandoned where it
422
+ * outgrew it rather than formatted in full and then measured.
423
+ *
424
+ * The brackets are charged before anything is read, and that ordering is what
425
+ * bounds the traversal: a budget checked only against the finished text still
426
+ * reads the whole subtree to produce text it then throws away. Charged first,
427
+ * every level costs at least the two cells of its own brackets, so a probe
428
+ * descends at most `budget / 2` levels however deep the data goes.
429
+ */
430
+ _joinOneLine(shape, at) {
431
+ let used = cellLen(shape.open) + cellLen(shape.close) + 2 * cellLen(shape.pad);
432
+ if (used > at.budget)
433
+ return null;
434
+ const pieces = [];
435
+ for (const slot of shape.slots) {
436
+ used += pieces.length > 0 ? cellLen(SEPARATOR) : 0;
437
+ const piece = this._slotOneLine(slot, { ...at, budget: at.budget - used });
438
+ if (piece === null)
439
+ return null;
440
+ used += cellLen(piece);
441
+ pieces.push(piece);
442
+ }
443
+ return shape.open + shape.pad + pieces.join(SEPARATOR) + shape.pad + shape.close;
444
+ }
445
+ /** One position on one line, or `null` when any value in it will not fit. */
446
+ _slotOneLine(slot, at) {
447
+ let out = slot.head;
448
+ for (const hole of slot.holes) {
449
+ const left = at.budget - cellLen(out);
450
+ let text;
451
+ try {
452
+ text = this._oneLine(hole.read(), { ...at, budget: left });
453
+ }
454
+ catch (error) {
455
+ text = fitOneLine(threw(error), left);
456
+ }
457
+ if (text === null)
458
+ return null;
459
+ out += text + hole.tail;
460
+ }
461
+ return fitOneLine(out, at.budget);
462
+ }
463
+ _addIndentGuides(text) {
464
+ const lines = text.plain.split("\n");
465
+ let offset = 0;
466
+ for (const line of lines) {
467
+ const leadingSpaces = line.length - line.trimStart().length;
468
+ for (let i = 0; i < leadingSpaces; i += this.indent) {
469
+ if (i + offset < text.length) {
470
+ text.stylize("repr.indent", offset + i, offset + i + 1);
471
+ }
472
+ }
473
+ offset += line.length + 1; // +1 for newline
474
+ }
475
+ }
476
+ }