@taliesinb/mash 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +275 -2
  3. package/bin/mash.ts +253 -0
  4. package/dist/bin/mash.d.ts +39 -0
  5. package/dist/bin/mash.d.ts.map +1 -0
  6. package/dist/bin/mash.js +281 -0
  7. package/dist/bin/mash.js.map +1 -0
  8. package/dist/src/analysis/analyze.d.ts +97 -0
  9. package/dist/src/analysis/analyze.d.ts.map +1 -0
  10. package/dist/src/analysis/analyze.js +1406 -0
  11. package/dist/src/analysis/analyze.js.map +1 -0
  12. package/dist/src/analysis/fs.d.ts +39 -0
  13. package/dist/src/analysis/fs.d.ts.map +1 -0
  14. package/dist/src/analysis/fs.js +117 -0
  15. package/dist/src/analysis/fs.js.map +1 -0
  16. package/dist/src/analysis/outputs.d.ts +16 -0
  17. package/dist/src/analysis/outputs.d.ts.map +1 -0
  18. package/dist/src/analysis/outputs.js +277 -0
  19. package/dist/src/analysis/outputs.js.map +1 -0
  20. package/dist/src/analysis/value.d.ts +76 -0
  21. package/dist/src/analysis/value.d.ts.map +1 -0
  22. package/dist/src/analysis/value.js +248 -0
  23. package/dist/src/analysis/value.js.map +1 -0
  24. package/dist/src/behaviors/defs/core.d.ts +15 -0
  25. package/dist/src/behaviors/defs/core.d.ts.map +1 -0
  26. package/dist/src/behaviors/defs/core.js +1084 -0
  27. package/dist/src/behaviors/defs/core.js.map +1 -0
  28. package/dist/src/behaviors/defs/devtools.d.ts +9 -0
  29. package/dist/src/behaviors/defs/devtools.d.ts.map +1 -0
  30. package/dist/src/behaviors/defs/devtools.js +432 -0
  31. package/dist/src/behaviors/defs/devtools.js.map +1 -0
  32. package/dist/src/behaviors/defs/macos.d.ts +12 -0
  33. package/dist/src/behaviors/defs/macos.d.ts.map +1 -0
  34. package/dist/src/behaviors/defs/macos.js +454 -0
  35. package/dist/src/behaviors/defs/macos.js.map +1 -0
  36. package/dist/src/behaviors/defs/tools.d.ts +9 -0
  37. package/dist/src/behaviors/defs/tools.d.ts.map +1 -0
  38. package/dist/src/behaviors/defs/tools.js +639 -0
  39. package/dist/src/behaviors/defs/tools.js.map +1 -0
  40. package/dist/src/behaviors/dsl.d.ts +95 -0
  41. package/dist/src/behaviors/dsl.d.ts.map +1 -0
  42. package/dist/src/behaviors/dsl.js +267 -0
  43. package/dist/src/behaviors/dsl.js.map +1 -0
  44. package/dist/src/behaviors/index.d.ts +12 -0
  45. package/dist/src/behaviors/index.d.ts.map +1 -0
  46. package/dist/src/behaviors/index.js +18 -0
  47. package/dist/src/behaviors/index.js.map +1 -0
  48. package/dist/src/behaviors/registry.d.ts +45 -0
  49. package/dist/src/behaviors/registry.d.ts.map +1 -0
  50. package/dist/src/behaviors/registry.js +266 -0
  51. package/dist/src/behaviors/registry.js.map +1 -0
  52. package/dist/src/behaviors/roles.d.ts +29 -0
  53. package/dist/src/behaviors/roles.d.ts.map +1 -0
  54. package/dist/src/behaviors/roles.js +198 -0
  55. package/dist/src/behaviors/roles.js.map +1 -0
  56. package/dist/src/behaviors/types.d.ts +120 -0
  57. package/dist/src/behaviors/types.d.ts.map +1 -0
  58. package/dist/src/behaviors/types.js +12 -0
  59. package/dist/src/behaviors/types.js.map +1 -0
  60. package/dist/src/index.d.ts +27 -0
  61. package/dist/src/index.d.ts.map +1 -0
  62. package/dist/src/index.js +24 -0
  63. package/dist/src/index.js.map +1 -0
  64. package/dist/src/integrations/deepsea.d.ts +121 -0
  65. package/dist/src/integrations/deepsea.d.ts.map +1 -0
  66. package/dist/src/integrations/deepsea.js +199 -0
  67. package/dist/src/integrations/deepsea.js.map +1 -0
  68. package/dist/src/machine.d.ts +139 -0
  69. package/dist/src/machine.d.ts.map +1 -0
  70. package/dist/src/machine.js +400 -0
  71. package/dist/src/machine.js.map +1 -0
  72. package/dist/src/parser/ast.d.ts +369 -0
  73. package/dist/src/parser/ast.d.ts.map +1 -0
  74. package/dist/src/parser/ast.js +17 -0
  75. package/dist/src/parser/ast.js.map +1 -0
  76. package/dist/src/parser/parser.d.ts +48 -0
  77. package/dist/src/parser/parser.d.ts.map +1 -0
  78. package/dist/src/parser/parser.js +1950 -0
  79. package/dist/src/parser/parser.js.map +1 -0
  80. package/dist/src/policy/effects.d.ts +86 -0
  81. package/dist/src/policy/effects.d.ts.map +1 -0
  82. package/dist/src/policy/effects.js +53 -0
  83. package/dist/src/policy/effects.js.map +1 -0
  84. package/dist/src/policy/policy.d.ts +130 -0
  85. package/dist/src/policy/policy.d.ts.map +1 -0
  86. package/dist/src/policy/policy.js +532 -0
  87. package/dist/src/policy/policy.js.map +1 -0
  88. package/dist/src/printer/doc.d.ts +151 -0
  89. package/dist/src/printer/doc.d.ts.map +1 -0
  90. package/dist/src/printer/doc.js +409 -0
  91. package/dist/src/printer/doc.js.map +1 -0
  92. package/dist/src/printer/highlight.d.ts +53 -0
  93. package/dist/src/printer/highlight.d.ts.map +1 -0
  94. package/dist/src/printer/highlight.js +339 -0
  95. package/dist/src/printer/highlight.js.map +1 -0
  96. package/dist/src/printer/html.d.ts +78 -0
  97. package/dist/src/printer/html.d.ts.map +1 -0
  98. package/dist/src/printer/html.js +426 -0
  99. package/dist/src/printer/html.js.map +1 -0
  100. package/dist/src/printer/index.d.ts +11 -0
  101. package/dist/src/printer/index.d.ts.map +1 -0
  102. package/dist/src/printer/index.js +11 -0
  103. package/dist/src/printer/index.js.map +1 -0
  104. package/dist/src/printer/print.d.ts +63 -0
  105. package/dist/src/printer/print.d.ts.map +1 -0
  106. package/dist/src/printer/print.js +484 -0
  107. package/dist/src/printer/print.js.map +1 -0
  108. package/dist/src/printer/summary.d.ts +57 -0
  109. package/dist/src/printer/summary.d.ts.map +1 -0
  110. package/dist/src/printer/summary.js +633 -0
  111. package/dist/src/printer/summary.js.map +1 -0
  112. package/dist/src/trace/events.d.ts +183 -0
  113. package/dist/src/trace/events.d.ts.map +1 -0
  114. package/dist/src/trace/events.js +9 -0
  115. package/dist/src/trace/events.js.map +1 -0
  116. package/dist/src/trace/progress.d.ts +58 -0
  117. package/dist/src/trace/progress.d.ts.map +1 -0
  118. package/dist/src/trace/progress.js +83 -0
  119. package/dist/src/trace/progress.js.map +1 -0
  120. package/dist/src/vm/arith.d.ts +29 -0
  121. package/dist/src/vm/arith.d.ts.map +1 -0
  122. package/dist/src/vm/arith.js +258 -0
  123. package/dist/src/vm/arith.js.map +1 -0
  124. package/dist/src/vm/builtins.d.ts +31 -0
  125. package/dist/src/vm/builtins.d.ts.map +1 -0
  126. package/dist/src/vm/builtins.js +1773 -0
  127. package/dist/src/vm/builtins.js.map +1 -0
  128. package/dist/src/vm/emulate.d.ts +75 -0
  129. package/dist/src/vm/emulate.d.ts.map +1 -0
  130. package/dist/src/vm/emulate.js +380 -0
  131. package/dist/src/vm/emulate.js.map +1 -0
  132. package/dist/src/vm/expand.d.ts +68 -0
  133. package/dist/src/vm/expand.d.ts.map +1 -0
  134. package/dist/src/vm/expand.js +744 -0
  135. package/dist/src/vm/expand.js.map +1 -0
  136. package/dist/src/vm/external.d.ts +34 -0
  137. package/dist/src/vm/external.d.ts.map +1 -0
  138. package/dist/src/vm/external.js +228 -0
  139. package/dist/src/vm/external.js.map +1 -0
  140. package/dist/src/vm/fifo.d.ts +66 -0
  141. package/dist/src/vm/fifo.d.ts.map +1 -0
  142. package/dist/src/vm/fifo.js +232 -0
  143. package/dist/src/vm/fifo.js.map +1 -0
  144. package/dist/src/vm/interp.d.ts +209 -0
  145. package/dist/src/vm/interp.d.ts.map +1 -0
  146. package/dist/src/vm/interp.js +1641 -0
  147. package/dist/src/vm/interp.js.map +1 -0
  148. package/dist/src/vm/io.d.ts +180 -0
  149. package/dist/src/vm/io.d.ts.map +1 -0
  150. package/dist/src/vm/io.js +502 -0
  151. package/dist/src/vm/io.js.map +1 -0
  152. package/dist/src/vm/pattern.d.ts +46 -0
  153. package/dist/src/vm/pattern.d.ts.map +1 -0
  154. package/dist/src/vm/pattern.js +498 -0
  155. package/dist/src/vm/pattern.js.map +1 -0
  156. package/dist/src/vm/proc.d.ts +94 -0
  157. package/dist/src/vm/proc.d.ts.map +1 -0
  158. package/dist/src/vm/proc.js +130 -0
  159. package/dist/src/vm/proc.js.map +1 -0
  160. package/dist/src/vm/state.d.ts +104 -0
  161. package/dist/src/vm/state.d.ts.map +1 -0
  162. package/dist/src/vm/state.js +233 -0
  163. package/dist/src/vm/state.js.map +1 -0
  164. package/dist/src/vm/test.d.ts +11 -0
  165. package/dist/src/vm/test.d.ts.map +1 -0
  166. package/dist/src/vm/test.js +277 -0
  167. package/dist/src/vm/test.js.map +1 -0
  168. package/package.json +67 -4
  169. package/src/analysis/analyze.ts +1395 -0
  170. package/src/analysis/fs.ts +121 -0
  171. package/src/analysis/outputs.ts +242 -0
  172. package/src/analysis/value.ts +264 -0
  173. package/src/behaviors/defs/core.ts +970 -0
  174. package/src/behaviors/defs/devtools.ts +400 -0
  175. package/src/behaviors/defs/macos.ts +426 -0
  176. package/src/behaviors/defs/tools.ts +596 -0
  177. package/src/behaviors/dsl.ts +293 -0
  178. package/src/behaviors/index.ts +19 -0
  179. package/src/behaviors/registry.ts +261 -0
  180. package/src/behaviors/roles.ts +187 -0
  181. package/src/behaviors/types.ts +127 -0
  182. package/src/index.ts +27 -0
  183. package/src/integrations/deepsea.ts +259 -0
  184. package/src/machine.ts +483 -0
  185. package/src/parser/ast.ts +472 -0
  186. package/src/parser/parser.ts +1826 -0
  187. package/src/policy/effects.ts +102 -0
  188. package/src/policy/policy.ts +578 -0
  189. package/src/printer/doc.ts +454 -0
  190. package/src/printer/highlight.ts +283 -0
  191. package/src/printer/html.ts +451 -0
  192. package/src/printer/index.ts +11 -0
  193. package/src/printer/print.ts +528 -0
  194. package/src/printer/summary.ts +621 -0
  195. package/src/trace/events.ts +102 -0
  196. package/src/trace/progress.ts +119 -0
  197. package/src/vm/arith.ts +236 -0
  198. package/src/vm/builtins.ts +1590 -0
  199. package/src/vm/emulate.ts +337 -0
  200. package/src/vm/expand.ts +721 -0
  201. package/src/vm/external.ts +265 -0
  202. package/src/vm/fifo.ts +226 -0
  203. package/src/vm/interp.ts +1623 -0
  204. package/src/vm/io.ts +570 -0
  205. package/src/vm/pattern.ts +477 -0
  206. package/src/vm/proc.ts +147 -0
  207. package/src/vm/state.ts +267 -0
  208. package/src/vm/test.ts +253 -0
@@ -0,0 +1,621 @@
1
+ /**
2
+ * One-line summaries: a snippet squeezed into a target width while keeping its
3
+ * *shape* (which commands run, how they are combined), e.g.
4
+ *
5
+ * cd …/harness-port && pnpm run build … > …/build.log 2>&1 && echo done
6
+ *
7
+ * The summary is a tree of structure tokens (command names, operators,
8
+ * keywords) and reducible parts. Starting from everything shown (with
9
+ * multi-line strings cut to their first line, here-doc bodies and comments
10
+ * omitted), it repeatedly applies the reduction with the lowest cost per
11
+ * column it saves (counting at most the columns still needed) until the line
12
+ * fits. Costs encode the priorities, cheapest first:
13
+ *
14
+ * shorten long strings, substitutions, words (head and closing quote kept) 1
15
+ * paths and redirection targets → their tail (`…/file.txt`) 1.2
16
+ * collapse assignment values (`FOO=…`; short ones cost double) 4
17
+ * hide plain arguments (strings, words) ┐ hidden runs merge into 3
18
+ * hide long flags (`--frozen-lockfile`) │ one `…` whose tooltip 3.5
19
+ * shorten path tails further │ lists them 4
20
+ * hide paths │ 6
21
+ * hide short flags (`-rn`) ┘ 8
22
+ * hide subcommands (`git status`) 80
23
+ * collapse compound bodies (`for …; do …; done`) 60
24
+ * drop trailing statements of a list (`a; b; …`) 100
25
+ * command names that are paths → their tail 150
26
+ * (and finally a hard cut at the width)
27
+ *
28
+ * Hiding an item of 6 columns or fewer costs double. Command names,
29
+ * operators, keywords and `]`/`]]` are never reduced.
30
+ *
31
+ * Every `…` keeps what it hides: truncated atoms carry the full text as a
32
+ * tooltip, hidden arguments and collapsed bodies carry their source.
33
+ */
34
+
35
+ import type * as A from '../parser/ast.ts'
36
+ import { parse } from '../parser/parser.ts'
37
+ import { Highlight, simpleCommandRoles } from './highlight.ts'
38
+
39
+ export interface SummaryOptions {
40
+ /** Target width in columns (default 80). */
41
+ width?: number
42
+ /**
43
+ * Tag the HTML with source ranges (default false): every piece that shows
44
+ * source text, and every `…` that hides some, carries `data-src="start-end"`
45
+ * (offsets into the source), so a UI can highlight the summary of a running
46
+ * command from its span.
47
+ */
48
+ ranges?: boolean
49
+ }
50
+
51
+ export interface SummaryResult {
52
+ /** The summary as plain text (`…` marks truncation). At most `width` columns, never a newline. */
53
+ text: string
54
+ /** `<span class="mash sum">…</span>`: highlighted, with `el` ellipsis spans and `title` tooltips. */
55
+ html: string
56
+ /** Number of reductions applied. */
57
+ reductions: number
58
+ }
59
+
60
+ type Kind = 'cmd' | 'sc' | 'flag' | 'lflag' | 'path' | 'str' | 'word' | 'val' | 'target'
61
+
62
+ interface Atom { k: 'atom'; start: number; end: number; kind: Kind; limit?: number; tail?: boolean; pos: number }
63
+ interface Tok { k: 'tok'; text: string; cls?: string }
64
+ interface ArgItem { node: Atom; hidden: boolean; fixed?: boolean }
65
+ interface Args { k: 'args'; items: ArgItem[] }
66
+ interface Elide { k: 'elide'; inner: S; start: number; end: number; collapsed: boolean; size: number }
67
+ interface List { k: 'list'; items: S[]; seps: string[]; spans: [number, number][]; keep: number; pos: number }
68
+ interface Fold { k: 'fold'; start: number; end: number }
69
+ type S = Tok | Atom | Args | Elide | List | Fold | S[]
70
+
71
+ interface Piece {
72
+ text: string
73
+ src?: [number, number]
74
+ cls?: string
75
+ el?: boolean
76
+ title?: string
77
+ /** The source range an `el` piece hides. */
78
+ hides?: [number, number]
79
+ /** Pieces of one truncated atom share a wrapper (its full text as tooltip). */
80
+ wrap?: { title: string }
81
+ }
82
+
83
+ const ELLIPSIS = '…'
84
+ const tok = (text: string, cls?: string): Tok => ({ k: 'tok', text, cls })
85
+ const SP = tok(' ')
86
+
87
+ /** Parse and summarize. Unparsable input falls back to a whitespace-collapsed, cut source. */
88
+ export function summarize(source: string, options: SummaryOptions = {}): SummaryResult {
89
+ let script: A.Script
90
+ try {
91
+ script = parse(source)
92
+ } catch {
93
+ const width = options.width ?? 80
94
+ const flat = source.replace(/\s+/g, ' ').trim()
95
+ const text = flat.length <= width ? flat : flat.slice(0, Math.max(0, width - 1)) + ELLIPSIS
96
+ const all = options.ranges ? ` data-src="0-${source.length}"` : ''
97
+ const html = flat.length <= width
98
+ ? `<span class="mash sum"${all}>${esc(flat)}</span>`
99
+ : `<span class="mash sum"${all}>${esc(flat.slice(0, Math.max(0, width - 1)))}<span class="el" title="${esc(source)}">${ELLIPSIS}</span></span>`
100
+ return { text, html, reductions: 0 }
101
+ }
102
+ return summarizeScript(script, source, options)
103
+ }
104
+
105
+ export function summarizeScript(script: A.Script, source: string, options: SummaryOptions = {}): SummaryResult {
106
+ const width = Math.max(4, options.width ?? 80)
107
+ const b = new Builder(source)
108
+ const root = b.list(script.body)
109
+ const atomWidth = (a: Atom): number => atomPieces(a, source).reduce((n, p) => n + p.text.length, 0)
110
+
111
+ const lineWidth = (): number => render(root, source).reduce((n, p) => n + p.text.length, 0)
112
+ const undos: (() => void)[] = []
113
+ for (let iter = 0; iter < 5000; iter++) {
114
+ const overflow = lineWidth() - width
115
+ if (overflow <= 0) break
116
+ const cands: Cand[] = []
117
+ collect(root, cands, { atomWidth, src: source, width: (n) => render(n, source).reduce((m, p) => m + p.text.length, 0) })
118
+ let best: Cand | null = null
119
+ let bestScore = Infinity
120
+ for (const c of cands) {
121
+ if (c.saving <= 0) continue
122
+ const score = c.cost / Math.min(c.saving, overflow + 1)
123
+ if (score < bestScore || (score === bestScore && best && c.key > best.key)) {
124
+ best = c
125
+ bestScore = score
126
+ }
127
+ }
128
+ if (!best) break
129
+ undos.push(best.apply())
130
+ }
131
+ // Relax: greedy steps can overshoot. Newest first, undo each reduction the
132
+ // line no longer needs (restoring the exact state when it is still needed:
133
+ // reductions of one atom do not commute).
134
+ let reductions = undos.length
135
+ if (lineWidth() <= width) {
136
+ for (let i = undos.length - 1; i >= 0; i--) {
137
+ const snap = snapshot(root)
138
+ undos[i]()
139
+ if (lineWidth() > width) restore(root, snap)
140
+ else reductions--
141
+ }
142
+ }
143
+ let pieces = render(root, source)
144
+ if (pieces.reduce((n, p) => n + p.text.length, 0) > width) {
145
+ pieces = hardCut(pieces, width, source)
146
+ reductions++
147
+ }
148
+ const hl = new Highlight(script, source)
149
+ return { text: pieces.map((p) => p.text).join(''), html: toHtml(pieces, hl, options.ranges ?? false), reductions }
150
+ }
151
+
152
+ // ---------------------------------------------------------------------------
153
+ // AST → summary tree
154
+ // ---------------------------------------------------------------------------
155
+
156
+ class Builder {
157
+ readonly src: string
158
+ private pos = 0
159
+
160
+ constructor(src: string) {
161
+ this.src = src
162
+ }
163
+
164
+ private atom(span: A.Span, kind: Kind): Atom {
165
+ return { k: 'atom', start: span.start, end: span.end, kind, pos: this.pos++ }
166
+ }
167
+
168
+ private classify(w: A.Word): Kind {
169
+ const text = this.src.slice(w.span.start, w.span.end)
170
+ if (/^--./.test(text)) return 'lflag'
171
+ if (/^-[^-\s]/.test(text)) return 'flag'
172
+ const bare = text.replace(/^["']|["']$/g, '')
173
+ // paths: start like one (`/`, `~`, `./`, `$HOME/`, `dir/`), no blanks, no regex/substitution syntax
174
+ if (/^(~|\.{0,2}\/|\$\{?\w+\}?\/|[\w.@+-]+\/)/.test(bare) && !/[\s^\\|()`]/.test(bare) && !/^\w\/.*\/.*\/\w*$/.test(bare)) return 'path'
175
+ if (w.parts.every((p) => p.type === 'Lit' || p.type === 'Escaped')) return 'word'
176
+ return 'str'
177
+ }
178
+
179
+ list(stmts: A.Stmt[]): S {
180
+ const items = stmts.map((s) => this.stmt(s))
181
+ const seps = stmts.slice(0, -1).map((s) => (s.background ? ' ' : '; '))
182
+ return { k: 'list', items, seps, spans: stmts.map((s) => [s.span.start, s.span.end]), keep: stmts.length, pos: this.pos++ }
183
+ }
184
+
185
+ private stmt(s: A.Stmt): S {
186
+ return s.background ? [this.command(s.command), SP, tok('&', 'op')] : this.command(s.command)
187
+ }
188
+
189
+ private body(stmts: A.Stmt[]): S {
190
+ if (stmts.length === 0) return []
191
+ const start = stmts[0].span.start
192
+ const end = stmts[stmts.length - 1].span.end
193
+ return { k: 'elide', inner: this.list(stmts), start, end, collapsed: false, size: end - start }
194
+ }
195
+
196
+ private redirs(rs: A.Redirect[]): S {
197
+ return rs.map((r) => {
198
+ if (r.heredoc) return [SP, tok(this.src.slice(r.span.start, r.span.end), 'rd'), { k: 'fold', start: r.heredoc.body.span.start, end: r.heredoc.body.span.end } as Fold]
199
+ const opText = this.src.slice(r.span.start, r.target.span.start)
200
+ if (/^\d*[<>]&$/.test(opText.trim()) || r.target.span.end <= r.target.span.start) return [SP, tok(this.src.slice(r.span.start, r.span.end), 'rd')]
201
+ return [SP, tok(opText, 'rd'), this.atom(r.target.span, this.classify(r.target) === 'path' ? 'target' : 'val')]
202
+ })
203
+ }
204
+
205
+ private assign(a: A.Assign): S {
206
+ const valueStart = a.value ? a.value.span.start : a.span.end
207
+ const name = tok(this.src.slice(a.span.start, valueStart), 'asg')
208
+ if (!a.value || a.value.span.end <= a.value.span.start) return name
209
+ return [name, this.atom(a.value.span, 'val')]
210
+ }
211
+
212
+ private command(c: A.Command): S {
213
+ switch (c.type) {
214
+ case 'SimpleCommand': {
215
+ const out: S[] = []
216
+ for (const a of c.assigns) out.push(this.assign(a), SP)
217
+ const items: ArgItem[] = []
218
+ let name: S | null = null
219
+ let roles: ReturnType<typeof simpleCommandRoles> = []
220
+ try {
221
+ roles = simpleCommandRoles(c)
222
+ } catch {
223
+ // display only
224
+ }
225
+ c.words.forEach((w, i) => {
226
+ if (w.type === 'Assign') {
227
+ items.push({ node: { ...this.atom(w.span, 'str') }, hidden: false })
228
+ return
229
+ }
230
+ if (!name) {
231
+ name = this.atom(w.span, 'cmd')
232
+ return
233
+ }
234
+ const text = this.src.slice(w.span.start, w.span.end)
235
+ // known roles refine the guess: files and directories shorten to their tail, patterns and code to their head
236
+ const role = roles[i]
237
+ let kind = this.classify(w)
238
+ if ((role === 'dir' || role === 'file') && kind !== 'flag' && kind !== 'lflag') kind = 'path'
239
+ else if ((role === 'pattern' || role === 'code') && kind === 'path') kind = 'str'
240
+ else if (role === 'subcommand') kind = 'sc'
241
+ items.push({ node: this.atom(w.span, kind), hidden: false, fixed: text === ']' || text === ']]' })
242
+ })
243
+ if (name) out.push(name)
244
+ else if (out.length) out.pop()
245
+ if (items.length) out.push(SP, { k: 'args', items })
246
+ out.push(this.redirs(c.redirs))
247
+ return out
248
+ }
249
+ case 'Pipeline': {
250
+ const prefix = this.src.slice(c.span.start, c.stages[0].span.start).trim().replace(/\s+/g, ' ')
251
+ const out: S[] = prefix ? [tok(prefix, 'kw'), SP] : []
252
+ c.stages.forEach((st, i) => {
253
+ if (i > 0) out.push(SP, tok(c.pipeStderr[i - 1] ? '|&' : '|', 'op'), SP)
254
+ out.push(this.command(st))
255
+ })
256
+ return out
257
+ }
258
+ case 'AndOr': {
259
+ const out: S[] = []
260
+ c.items.forEach((it, i) => {
261
+ if (i > 0) out.push(SP, tok(c.ops[i - 1], 'op'), SP)
262
+ out.push(this.command(it))
263
+ })
264
+ return out
265
+ }
266
+ case 'FunctionDef':
267
+ return [tok(`${c.name}()`, 'fn'), SP, this.command(c.body)]
268
+ case 'Group':
269
+ return [tok('{', 'kw'), SP, this.body(c.body), tok(';', 'op'), SP, tok('}', 'kw'), this.redirs(c.redirs)]
270
+ case 'Subshell':
271
+ return [tok('(', 'kw'), SP, this.body(c.body), SP, tok(')', 'kw'), this.redirs(c.redirs)]
272
+ case 'If': {
273
+ const out: S[] = []
274
+ c.clauses.forEach((cl, i) => {
275
+ out.push(i === 0 ? tok('if', 'kw') : [tok(';', 'op'), SP, tok('elif', 'kw')], SP, this.list(cl.cond), tok(';', 'op'), SP, tok('then', 'kw'), SP, this.body(cl.body))
276
+ })
277
+ if (c.elseBody) out.push(tok(';', 'op'), SP, tok('else', 'kw'), SP, this.body(c.elseBody))
278
+ out.push(tok(';', 'op'), SP, tok('fi', 'kw'), this.redirs(c.redirs))
279
+ return out
280
+ }
281
+ case 'Loop':
282
+ return [tok(c.kind, 'kw'), SP, this.list(c.cond), tok(';', 'op'), SP, tok('do', 'kw'), SP, this.body(c.body), tok(';', 'op'), SP, tok('done', 'kw'), this.redirs(c.redirs)]
283
+ case 'For':
284
+ case 'Select': {
285
+ const head: S[] = [tok(c.type === 'For' ? 'for' : 'select', 'kw'), SP, tok(c.variable, 'var')]
286
+ if (c.items !== null) {
287
+ head.push(SP, tok('in', 'kw'))
288
+ if (c.items.length) head.push(SP, { k: 'args', items: c.items.map((w) => ({ node: this.atom(w.span, this.classify(w)), hidden: false })) })
289
+ }
290
+ return [head, tok(';', 'op'), SP, tok('do', 'kw'), SP, this.body(c.body), tok(';', 'op'), SP, tok('done', 'kw'), this.redirs(c.redirs)]
291
+ }
292
+ case 'ArithFor': {
293
+ const exprs = [c.init, c.cond, c.step].filter((e): e is A.ArithExpr => e !== null)
294
+ const from = exprs.length ? exprs[exprs.length - 1].span.end : c.span.start
295
+ const close = this.src.indexOf('))', from)
296
+ return [this.atom({ start: c.span.start, end: close + 2 }, 'str'), tok(';', 'op'), SP, tok('do', 'kw'), SP, this.body(c.body), tok(';', 'op'), SP, tok('done', 'kw'), this.redirs(c.redirs)]
297
+ }
298
+ case 'Case': {
299
+ const items: S[] = []
300
+ c.items.forEach((it, i) => {
301
+ if (i > 0) items.push(SP)
302
+ it.patterns.forEach((p, j) => {
303
+ if (j > 0) items.push(tok('|', 'op'))
304
+ items.push(this.atom(p.span, 'word'))
305
+ })
306
+ items.push(tok(')', 'op'))
307
+ if (it.body.length) items.push(SP, this.list(it.body))
308
+ items.push(SP, tok(it.terminator, 'op'))
309
+ })
310
+ const start = c.items[0]?.span.start ?? c.span.start
311
+ const end = c.items[c.items.length - 1]?.span.end ?? c.span.start
312
+ const region: S = c.items.length ? { k: 'elide', inner: items, start, end, collapsed: false, size: end - start } : []
313
+ return [tok('case', 'kw'), SP, this.atom(c.word.span, 'word'), SP, tok('in', 'kw'), SP, region, SP, tok('esac', 'kw'), this.redirs(c.redirs)]
314
+ }
315
+ case 'ArithCommand':
316
+ case 'CondCommand': {
317
+ let end = c.redirs.length > 0 ? c.redirs[0].span.start : c.span.end
318
+ while (end > c.span.start && /\s/.test(this.src[end - 1])) end--
319
+ return [this.atom({ start: c.span.start, end }, 'str'), this.redirs(c.redirs)]
320
+ }
321
+ }
322
+ }
323
+ }
324
+
325
+ // ---------------------------------------------------------------------------
326
+ // Rendering
327
+ // ---------------------------------------------------------------------------
328
+
329
+ function closeLen(src: string, a: Atom): number {
330
+ if (a.end - a.start <= 2 || a.kind === 'path' || a.kind === 'target') return 0
331
+ return `'")}\``.includes(src[a.end - 1]) ? 1 : 0
332
+ }
333
+
334
+ /** The pieces showing an atom under its current limit. */
335
+ function atomPieces(a: Atom, src: string): Piece[] {
336
+ const { start: s, end: e } = a
337
+ const full = src.slice(s, e)
338
+ const nlAt = full.indexOf('\n')
339
+ const lineEnd = nlAt >= 0 ? s + nlAt : e
340
+ const forced = nlAt >= 0
341
+ const wrap = { title: full }
342
+ // paths keep their tail whenever they are shortened
343
+ const tailMode = a.tail || (a.limit !== undefined && (a.kind === 'path' || a.kind === 'target'))
344
+ if (tailMode && !forced) {
345
+ // path tail: `…/file.txt`, or the last limit-1 characters
346
+ let slash = -1
347
+ for (let i = e - 2; i > s; i--) {
348
+ if (src[i] === '/') {
349
+ slash = i
350
+ break
351
+ }
352
+ }
353
+ let from = slash > s ? slash : s
354
+ if (a.limit !== undefined && e - from + 1 > a.limit) from = Math.max(s, e - Math.max(1, a.limit - 1))
355
+ if (from <= s) return [{ text: full, src: [s, e] }]
356
+ return [{ text: ELLIPSIS, el: true, hides: [s, from], wrap }, { text: src.slice(from, e), src: [from, e], wrap }]
357
+ }
358
+ if (!forced && (a.limit === undefined || a.limit >= e - s)) return [{ text: full, src: [s, e] }]
359
+ const close = closeLen(src, a)
360
+ const visibleEnd = forced ? lineEnd : e
361
+ let headEnd = visibleEnd
362
+ if (a.limit !== undefined) headEnd = Math.min(visibleEnd, s + Math.max(0, a.limit - 1 - close))
363
+ // never end the head inside a line with trailing blanks
364
+ while (headEnd > s && /\s/.test(src[headEnd - 1])) headEnd--
365
+ const out: Piece[] = []
366
+ if (headEnd > s) out.push({ text: src.slice(s, headEnd), src: [s, headEnd], wrap })
367
+ const keepClose = close && (a.limit === undefined || a.limit > 1)
368
+ out.push({ text: ELLIPSIS, el: true, hides: [headEnd, keepClose ? e - close : e], wrap })
369
+ if (keepClose) out.push({ text: src.slice(e - close, e), src: [e - close, e], wrap })
370
+ return out
371
+ }
372
+
373
+ function render(node: S, src: string, out: Piece[] = []): Piece[] {
374
+ if (Array.isArray(node)) {
375
+ for (const n of node) render(n, src, out)
376
+ return out
377
+ }
378
+ switch (node.k) {
379
+ case 'tok':
380
+ out.push({ text: node.text, cls: node.cls })
381
+ break
382
+ case 'atom':
383
+ out.push(...atomPieces(node, src))
384
+ break
385
+ case 'fold':
386
+ out.push({ text: ELLIPSIS, el: true, title: src.slice(node.start, node.end), hides: [node.start, node.end] })
387
+ break
388
+ case 'elide':
389
+ if (node.collapsed) out.push({ text: ELLIPSIS, el: true, title: src.slice(node.start, node.end), hides: [node.start, node.end] })
390
+ else render(node.inner, src, out)
391
+ break
392
+ case 'list': {
393
+ const n = node.items.length
394
+ for (let i = 0; i < Math.min(node.keep, n); i++) {
395
+ if (i > 0) out.push({ text: node.seps[i - 1], cls: node.seps[i - 1].trim() ? 'op' : undefined })
396
+ render(node.items[i], src, out)
397
+ }
398
+ if (node.keep < n) {
399
+ if (node.keep > 0) out.push({ text: node.seps[node.keep - 1], cls: 'op' })
400
+ out.push({ text: ELLIPSIS, el: true, title: src.slice(node.spans[node.keep][0], node.spans[n - 1][1]), hides: [node.spans[node.keep][0], node.spans[n - 1][1]] })
401
+ }
402
+ break
403
+ }
404
+ case 'args': {
405
+ let i = 0
406
+ let first = true
407
+ while (i < node.items.length) {
408
+ if (!first) out.push({ text: ' ' })
409
+ first = false
410
+ const it = node.items[i]
411
+ if (!it.hidden) {
412
+ render(it.node, src, out)
413
+ i++
414
+ continue
415
+ }
416
+ let j = i
417
+ while (j < node.items.length && node.items[j].hidden) j++
418
+ out.push({ text: ELLIPSIS, el: true, title: src.slice(node.items[i].node.start, node.items[j - 1].node.end), hides: [node.items[i].node.start, node.items[j - 1].node.end] })
419
+ i = j
420
+ }
421
+ break
422
+ }
423
+ }
424
+ return out
425
+ }
426
+
427
+ // ---------------------------------------------------------------------------
428
+ // Reductions
429
+ // ---------------------------------------------------------------------------
430
+
431
+ /** A possible reduction: `cost` (information lost) and the columns it saves. `apply` returns its undo. */
432
+ type Cand = { cost: number; saving: number; key: number; apply: () => () => void }
433
+ interface Ctx {
434
+ atomWidth: (a: Atom) => number
435
+ width: (n: S) => number
436
+ src: string
437
+ }
438
+
439
+ function collect(node: S, cands: Cand[], ctx: Ctx, inArgs = false): void {
440
+ if (Array.isArray(node)) {
441
+ for (const n of node) collect(n, cands, ctx)
442
+ return
443
+ }
444
+ switch (node.k) {
445
+ case 'atom':
446
+ atomCands(node, cands, ctx, inArgs)
447
+ return
448
+ case 'elide': {
449
+ if (node.collapsed) return
450
+ collect(node.inner, cands, ctx)
451
+ cands.push({ cost: 60, saving: ctx.width(node.inner) - 1, key: node.size, apply: () => { node.collapsed = true; return () => { node.collapsed = false } } })
452
+ return
453
+ }
454
+ case 'list': {
455
+ const shown = Math.min(node.keep, node.items.length)
456
+ for (let i = 0; i < shown; i++) collect(node.items[i], cands, ctx)
457
+ if (node.keep > 1) {
458
+ const last = node.keep - 1
459
+ // dropping the last shown statement: when others are already dropped, it merges into their `…`
460
+ const saving = ctx.width(node.items[last]) + (node.keep < node.items.length ? node.seps[last - 1].length : -1)
461
+ cands.push({ cost: 100, saving, key: node.pos, apply: () => { node.keep--; return () => { node.keep++ } } })
462
+ }
463
+ return
464
+ }
465
+ case 'args':
466
+ node.items.forEach((it, i) => {
467
+ if (it.hidden) return
468
+ collect(it.node, cands, ctx, true)
469
+ if (it.fixed) return
470
+ const w = ctx.atomWidth(it.node)
471
+ // short items say a lot per column: hiding them costs double
472
+ // subcommands are nearly structure (`git status`): hidden only after compound bodies collapse
473
+ const cost = { str: 3, word: 3, val: 3, cmd: 3, sc: 80, lflag: 3.5, target: 6, path: 6, flag: 8 }[it.node.kind] * (w <= 6 ? 2 : 1)
474
+ const merges = (node.items[i - 1]?.hidden ? 1 : 0) + (node.items[i + 1]?.hidden ? 1 : 0)
475
+ // alone it becomes `…`; next to a hidden run it disappears with its space
476
+ const saving = merges === 0 ? w - 1 : merges === 1 ? w + 1 : w + 3
477
+ cands.push({ cost, saving, key: it.node.pos, apply: () => { it.hidden = true; return () => { it.hidden = false } } })
478
+ })
479
+ return
480
+ default:
481
+ return
482
+ }
483
+ }
484
+
485
+ function atomCands(a: Atom, cands: Cand[], ctx: Ctx, inArgs: boolean): void {
486
+ const w = ctx.atomWidth(a)
487
+ const shorten = (cost: number, minKeep: number): void => {
488
+ // shorten by half at a time (at least to minKeep); re-scored every round
489
+ const limit = Math.max(minKeep, Math.ceil(w / 2))
490
+ if (limit < w) cands.push({ cost, saving: w - limit, key: a.pos, apply: () => { const old = a.limit; a.limit = limit; return () => { a.limit = old } } })
491
+ }
492
+ const toTail = (cost: number): void => {
493
+ a.tail = true
494
+ const tw = ctx.atomWidth(a)
495
+ a.tail = false
496
+ if (tw < w) cands.push({ cost, saving: w - tw, key: a.pos, apply: () => { a.tail = true; return () => { a.tail = false } } })
497
+ }
498
+ switch (a.kind) {
499
+ case 'str':
500
+ case 'word':
501
+ if (w > 12) shorten(1, 12)
502
+ return
503
+ case 'path':
504
+ case 'target':
505
+ if (w <= 12) return // short paths (`/dev/null`) are clearer whole; they can still be hidden as arguments
506
+ if (!a.tail) toTail(1.2)
507
+ else shorten(4, a.kind === 'target' ? 6 : 8)
508
+ return
509
+ case 'val':
510
+ if (w > 12) shorten(1, 12)
511
+ else if (w > 1) cands.push({ cost: w <= 6 ? 8 : 4, saving: w - 1, key: a.pos, apply: () => { const old = a.limit; a.limit = 1; return () => { a.limit = old } } })
512
+ return
513
+ case 'cmd':
514
+ if (inArgs) return
515
+ // only command names that are paths (`/usr/local/bin/x`, `./scripts/build.sh`) shrink
516
+ if (!ctx.src.slice(a.start, a.end).includes('/')) return
517
+ if (!a.tail) toTail(150)
518
+ else shorten(150, 6)
519
+ return
520
+ default:
521
+ return
522
+ }
523
+ }
524
+
525
+ /** The reduction state of a tree (limits, tails, hidden args, collapsed bodies, list lengths). */
526
+ function snapshot(node: S, out: unknown[] = []): unknown[] {
527
+ if (Array.isArray(node)) {
528
+ for (const n of node) snapshot(n, out)
529
+ return out
530
+ }
531
+ switch (node.k) {
532
+ case 'atom': out.push(node.limit, node.tail); break
533
+ case 'elide': out.push(node.collapsed); snapshot(node.inner, out); break
534
+ case 'list': out.push(node.keep); for (const it of node.items) snapshot(it, out); break
535
+ case 'args': for (const it of node.items) { out.push(it.hidden); snapshot(it.node, out) } break
536
+ default: break
537
+ }
538
+ return out
539
+ }
540
+
541
+ function restore(node: S, snap: unknown[], at = { i: 0 }): void {
542
+ if (Array.isArray(node)) {
543
+ for (const n of node) restore(n, snap, at)
544
+ return
545
+ }
546
+ switch (node.k) {
547
+ case 'atom': node.limit = snap[at.i++] as number | undefined; node.tail = snap[at.i++] as boolean | undefined; break
548
+ case 'elide': node.collapsed = snap[at.i++] as boolean; restore(node.inner, snap, at); break
549
+ case 'list': node.keep = snap[at.i++] as number; for (const it of node.items) restore(it, snap, at); break
550
+ case 'args': for (const it of node.items) { it.hidden = snap[at.i++] as boolean; restore(it.node, snap, at) } break
551
+ default: break
552
+ }
553
+ }
554
+
555
+ /** Cut the rendered line at `width` columns, ending in an ellipsis that holds the rest. */
556
+ function hardCut(pieces: Piece[], width: number, src: string): Piece[] {
557
+ const out: Piece[] = []
558
+ let used = 0
559
+ const budget = width - 1
560
+ let restStart: number | null = null
561
+ // where the source shown so far ends: the cut hides only what comes after it
562
+ let shownEnd = 0
563
+ for (const p of pieces) {
564
+ if (used + p.text.length <= budget) {
565
+ out.push(p)
566
+ used += p.text.length
567
+ shownEnd = Math.max(shownEnd, p.src?.[1] ?? p.hides?.[1] ?? 0)
568
+ continue
569
+ }
570
+ const room = budget - used
571
+ if (room > 0) {
572
+ const text = p.text.slice(0, room)
573
+ out.push({ ...p, text, src: p.src ? [p.src[0], p.src[0] + room] : undefined, el: false, hides: undefined })
574
+ used += room
575
+ }
576
+ if (p.src) restStart = p.src[0] + Math.max(0, room)
577
+ else if (p.hides) restStart = p.hides[0]
578
+ else restStart = shownEnd
579
+ break
580
+ }
581
+ out.push({ text: ELLIPSIS, el: true, title: restStart !== null ? src.slice(restStart) : src, hides: [restStart ?? 0, src.length] })
582
+ return out
583
+ }
584
+
585
+ // ---------------------------------------------------------------------------
586
+ // HTML
587
+ // ---------------------------------------------------------------------------
588
+
589
+ const esc = (s: string): string => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!)
590
+
591
+ function pieceHtml(p: Piece, hl: Highlight, ranges: boolean): string {
592
+ if (p.el) {
593
+ const range = ranges && p.hides ? ` data-src="${p.hides[0]}-${p.hides[1]}"` : ''
594
+ return `<span class="el"${p.title !== undefined ? ` title="${esc(p.title)}"` : ''}${range}>${esc(p.text)}</span>`
595
+ }
596
+ if (p.src) {
597
+ const runs = hl.runs(p.src[0], p.src[1]).map((r) => {
598
+ const cls = r.cls || p.cls
599
+ return cls ? `<span class="${cls}">${esc(r.text)}</span>` : esc(r.text)
600
+ }).join('')
601
+ return ranges ? `<span data-src="${p.src[0]}-${p.src[1]}">${runs}</span>` : runs
602
+ }
603
+ return p.cls ? `<span class="${p.cls}">${esc(p.text)}</span>` : esc(p.text)
604
+ }
605
+
606
+ function toHtml(pieces: Piece[], hl: Highlight, ranges: boolean): string {
607
+ let html = ''
608
+ for (let i = 0; i < pieces.length; i++) {
609
+ const p = pieces[i]
610
+ if (p.wrap) {
611
+ let inner = ''
612
+ let j = i
613
+ while (j < pieces.length && pieces[j].wrap === p.wrap) inner += pieceHtml(pieces[j++], hl, ranges)
614
+ html += `<span class="tr" title="${esc(p.wrap.title)}">${inner}</span>`
615
+ i = j - 1
616
+ continue
617
+ }
618
+ html += pieceHtml(p, hl, ranges)
619
+ }
620
+ return `<span class="mash sum">${html}</span>`
621
+ }