@wonderwhy-er/desktop-commander 0.3.2-alpha.1 → 0.3.2-alpha.3

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 (56) hide show
  1. package/dist/bootstrap.js +7 -7
  2. package/dist/command-manager.d.ts +98 -1
  3. package/dist/command-manager.js +200 -16
  4. package/dist/remote-device/desktop-commander-integration.js +3 -1
  5. package/dist/remote-device/diagnostics/redact.js +30 -8
  6. package/dist/remote-device/diagnostics/report.js +30 -13
  7. package/dist/remote-device/mqtt/mqtt-enrollment.js +1 -1
  8. package/dist/remote-device/mqtt/mqtt-transport.js +2 -2
  9. package/dist/remote-device/remote-channel.d.ts +1 -1
  10. package/dist/remote-device/remote-channel.js +1 -1
  11. package/dist/remote-device/transport-telemetry.js +5 -4
  12. package/dist/server.js +2 -0
  13. package/dist/terminal-manager.js +4 -6
  14. package/dist/tools/improved-process-tools.d.ts +2 -0
  15. package/dist/tools/improved-process-tools.js +68 -40
  16. package/dist/tools/pdf/markdown.js +7 -3
  17. package/dist/tools/process.js +10 -2
  18. package/dist/track-installation.js +2 -2
  19. package/dist/ui/file-preview/preview-runtime.js +145 -138
  20. package/dist/utils/brace-expansion.d.ts +25 -0
  21. package/dist/utils/brace-expansion.js +171 -0
  22. package/dist/utils/capture.d.ts +8 -2
  23. package/dist/utils/capture.js +1 -1
  24. package/dist/utils/cmd-commands.d.ts +3 -0
  25. package/dist/utils/cmd-commands.js +322 -0
  26. package/dist/utils/command-reading.d.ts +78 -0
  27. package/dist/utils/command-reading.js +7 -0
  28. package/dist/utils/command-wrappers.d.ts +45 -0
  29. package/dist/utils/command-wrappers.js +941 -0
  30. package/dist/utils/inline-shells.d.ts +64 -0
  31. package/dist/utils/inline-shells.js +290 -0
  32. package/dist/utils/posix-commands.d.ts +3 -0
  33. package/dist/utils/posix-commands.js +201 -0
  34. package/dist/utils/powershell-commands.d.ts +60 -0
  35. package/dist/utils/powershell-commands.js +420 -0
  36. package/dist/utils/process-tree.js +4 -4
  37. package/dist/utils/shell-script-files.d.ts +4 -0
  38. package/dist/utils/shell-script-files.js +121 -0
  39. package/dist/utils/shell.d.ts +36 -0
  40. package/dist/utils/shell.js +69 -0
  41. package/dist/utils/system-info.d.ts +2 -0
  42. package/dist/utils/system-info.js +5 -1
  43. package/dist/utils/threadpool-size.d.ts +36 -0
  44. package/dist/utils/threadpool-size.js +143 -0
  45. package/dist/version.d.ts +1 -1
  46. package/dist/version.js +1 -1
  47. package/package.json +11 -9
  48. package/node_modules/@desktop-commander/telemetry-contract/README.md +0 -56
  49. package/node_modules/@desktop-commander/telemetry-contract/package.json +0 -32
  50. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +0 -39
  51. package/node_modules/@desktop-commander/telemetry-contract/transport.js +0 -167
  52. package/vendor/telemetry-contract/README.md +0 -56
  53. package/vendor/telemetry-contract/package.json +0 -32
  54. package/vendor/telemetry-contract/transport.d.ts +0 -38
  55. package/vendor/telemetry-contract/transport.js +0 -164
  56. package/vendor/telemetry-contract/transport.test.js +0 -39
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Brace expansion, the way bash does it before it runs a command: x{1,2}y
3
+ * becomes the words x1y and x2y, and {1..3} becomes 1 2 3. So {sudo,ls} runs
4
+ * sudo, and su{d..d}o runs sudo too. zsh expands the same forms. The command
5
+ * check's POSIX reader uses it to find the program such a command name runs.
6
+ */
7
+ /** One character of a word, and whether it is quoted or escaped there: a quoted "{", "," or "}" is only text */
8
+ export interface WordChar {
9
+ char: string;
10
+ quoted: boolean;
11
+ }
12
+ /** The most words of one expansion the check reads; past that it gives up rather than check part of it */
13
+ export declare const MAX_BRACE_WORDS = 1000;
14
+ /** Characters that are all text: a quoted part of a word, or a part with no brace syntax in it */
15
+ export declare function quotedChars(text: string): WordChar[];
16
+ /** Characters as written outside quotes, where a backslash makes the character after it text */
17
+ export declare function unquotedChars(text: string): WordChar[];
18
+ /**
19
+ * The words bash makes from a word by brace expansion, in bash's order, without
20
+ * the unquoted empty ones: bash drops {,sudo}'s empty word, but keeps {"",sudo}'s.
21
+ * A word without an expansion gives itself. Past MAX_BRACE_WORDS words or
22
+ * MAX_BRACE_STEPS steps it gives null, and the reader takes the command as
23
+ * unreadable.
24
+ */
25
+ export declare function braceWords(chars: WordChar[]): string[] | null;
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Brace expansion, the way bash does it before it runs a command: x{1,2}y
3
+ * becomes the words x1y and x2y, and {1..3} becomes 1 2 3. So {sudo,ls} runs
4
+ * sudo, and su{d..d}o runs sudo too. zsh expands the same forms. The command
5
+ * check's POSIX reader uses it to find the program such a command name runs.
6
+ */
7
+ /** The most words of one expansion the check reads; past that it gives up rather than check part of it */
8
+ export const MAX_BRACE_WORDS = 1000;
9
+ /**
10
+ * The most steps one expansion may take, a step being a character looked at
11
+ * to find a brace or one put in a word. The words are bounded by
12
+ * MAX_BRACE_WORDS, but the work to make them isn't: the rest of the word is
13
+ * expanded again for each word of a list, and a nested group's braces take
14
+ * a time that grows with the square of its depth. This keeps the check to a
15
+ * fraction of a second; past it the check gives up, as past MAX_BRACE_WORDS.
16
+ */
17
+ const MAX_BRACE_STEPS = 10000000;
18
+ /** Characters that are all text: a quoted part of a word, or a part with no brace syntax in it */
19
+ export function quotedChars(text) {
20
+ // An empty quoted part still keeps its word after quote removal.
21
+ return Array.from(text || [''], (char) => ({ char, quoted: true }));
22
+ }
23
+ /** Characters as written outside quotes, where a backslash makes the character after it text */
24
+ export function unquotedChars(text) {
25
+ const chars = [];
26
+ const all = Array.from(text);
27
+ for (let i = 0; i < all.length; i++) {
28
+ if (all[i] === '\\' && i + 1 < all.length) {
29
+ chars.push({ char: all[++i], quoted: true });
30
+ }
31
+ else {
32
+ chars.push({ char: all[i], quoted: false });
33
+ }
34
+ }
35
+ return chars;
36
+ }
37
+ /**
38
+ * The words bash makes from a word by brace expansion, in bash's order, without
39
+ * the unquoted empty ones: bash drops {,sudo}'s empty word, but keeps {"",sudo}'s.
40
+ * A word without an expansion gives itself. Past MAX_BRACE_WORDS words or
41
+ * MAX_BRACE_STEPS steps it gives null, and the reader takes the command as
42
+ * unreadable.
43
+ */
44
+ export function braceWords(chars) {
45
+ const words = [];
46
+ const steps = { left: MAX_BRACE_STEPS };
47
+ let read = 0;
48
+ try {
49
+ for (const word of expand(chars, steps)) {
50
+ if (++read > MAX_BRACE_WORDS)
51
+ return null;
52
+ take(steps, word.text.length);
53
+ if (word.text !== '' || word.quoted)
54
+ words.push(word.text);
55
+ }
56
+ }
57
+ catch (error) {
58
+ if (error instanceof TooManySteps)
59
+ return null;
60
+ throw error;
61
+ }
62
+ return words;
63
+ }
64
+ class TooManySteps extends Error {
65
+ }
66
+ /** Takes n steps, or stops the expansion when there aren't that many left */
67
+ function take(steps, n) {
68
+ steps.left -= n;
69
+ if (steps.left < 0)
70
+ throw new TooManySteps();
71
+ }
72
+ const isSyntax = (c, char) => !c.quoted && c.char === char;
73
+ const textOf = (chars) => chars.map((c) => c.char).join('');
74
+ function* expand(chars, steps) {
75
+ const brace = findBrace(chars, steps);
76
+ if (!brace) {
77
+ yield { text: textOf(chars), quoted: chars.some((c) => c.quoted) };
78
+ return;
79
+ }
80
+ const preamble = chars.slice(0, brace.open);
81
+ const postscript = chars.slice(brace.close + 1);
82
+ for (const middle of middles(chars, brace, steps)) {
83
+ for (const end of expand(postscript, steps)) {
84
+ yield {
85
+ text: textOf(preamble) + middle.text + end.text,
86
+ quoted: preamble.some((c) => c.quoted) || middle.quoted || end.quoted,
87
+ };
88
+ }
89
+ }
90
+ }
91
+ /** The words that replace the braces, in order: each piece between the commas, expanded, or the sequence */
92
+ function* middles(chars, brace, steps) {
93
+ if ('text' in brace) {
94
+ for (const text of sequence(brace.text))
95
+ yield { text, quoted: false };
96
+ return;
97
+ }
98
+ const bounds = [brace.open, ...brace.commas, brace.close];
99
+ for (let k = 0; k + 1 < bounds.length; k++) {
100
+ yield* expand(chars.slice(bounds[k] + 1, bounds[k + 1]), steps);
101
+ }
102
+ }
103
+ // bash reads a number here with its sign, - or +: su{d..d..+1}o runs sudo
104
+ const NUMBERS = /^([-+]?\d+)\.\.([-+]?\d+)(?:\.\.([-+]?\d+))?$/;
105
+ const LETTERS = /^([A-Za-z])\.\.([A-Za-z])(?:\.\.([-+]?\d+))?$/;
106
+ /**
107
+ * The first {a,b} or {x..y} in the word. As in bash, a "{" without a matching
108
+ * "}", or whose braces hold neither a comma nor a sequence ({sudo}), is text,
109
+ * and the search goes on after it.
110
+ */
111
+ function findBrace(chars, steps) {
112
+ take(steps, chars.length);
113
+ for (let open = 0; open < chars.length; open++) {
114
+ if (!isSyntax(chars[open], '{'))
115
+ continue;
116
+ let depth = 0;
117
+ let close = -1;
118
+ const commas = [];
119
+ let i = open + 1;
120
+ for (; i < chars.length && close < 0; i++) {
121
+ if (isSyntax(chars[i], '{')) {
122
+ depth++;
123
+ }
124
+ else if (isSyntax(chars[i], '}')) {
125
+ if (depth === 0)
126
+ close = i;
127
+ else
128
+ depth--;
129
+ }
130
+ else if (depth === 0 && isSyntax(chars[i], ',')) {
131
+ commas.push(i);
132
+ }
133
+ }
134
+ take(steps, i - open);
135
+ if (close < 0)
136
+ continue;
137
+ if (commas.length > 0)
138
+ return { open, close, commas };
139
+ const inside = chars.slice(open + 1, close);
140
+ const text = textOf(inside);
141
+ if (inside.every((c) => !c.quoted) && (NUMBERS.test(text) || LETTERS.test(text)))
142
+ return { open, close, text };
143
+ }
144
+ return null;
145
+ }
146
+ /** The words of a {1..10}, {01..10..2} or {a..e} sequence (findBrace has matched its text) */
147
+ function* sequence(text) {
148
+ const numbers = NUMBERS.exec(text);
149
+ if (numbers) {
150
+ const [, first, last, increment] = numbers;
151
+ // Match bash: a leading zero (after -, not +) pads to the longer endpoint's width, including its sign.
152
+ const width = /^-?0\d/.test(first) || /^-?0\d/.test(last) ? Math.max(first.length, last.length) : 0;
153
+ const pad = (n) => (n < 0 ? '-' + String(-n).padStart(width - 1, '0') : String(n).padStart(width, '0'));
154
+ for (const n of range(Number(first), Number(last), increment))
155
+ yield pad(n);
156
+ return;
157
+ }
158
+ const [, first, last, increment] = LETTERS.exec(text);
159
+ for (const n of range(first.charCodeAt(0), last.charCodeAt(0), increment)) {
160
+ // bash leaves out the backslash, which lies between "Z" and "a"
161
+ if (n !== 0x5c)
162
+ yield String.fromCharCode(n);
163
+ }
164
+ }
165
+ /** from, from ± step, … as far as to, in either direction; bash takes a missing or zero step as 1 */
166
+ function* range(from, to, increment) {
167
+ const size = Math.abs(Number(increment ?? 1)) || 1;
168
+ const step = from <= to ? size : -size;
169
+ for (let n = from; Math.abs(n - from) <= Math.abs(to - from); n += step)
170
+ yield n;
171
+ }
@@ -1,4 +1,10 @@
1
- import type { TransportParams } from '@desktop-commander/telemetry-contract/transport';
1
+ /** Core fields required by the collector; producers own their optional diagnostic fields. */
2
+ export interface TransportParams {
3
+ call_id: string;
4
+ stage: string;
5
+ timestamp_utc: string;
6
+ [key: string]: unknown;
7
+ }
2
8
  export declare function runInUiOriginCallContext<T>(fn: () => T): T;
3
9
  export declare function isInsideUiOriginCall(): boolean;
4
10
  /** Runs a tool call with its own set of known paths. */
@@ -36,7 +42,7 @@ export declare const captureBase: (captureURL: string, event: string, properties
36
42
  export declare const buildEventProperties: (properties?: any) => Promise<any>;
37
43
  export declare const capture: (event: string, properties?: any) => Promise<void>;
38
44
  /**
39
- * Send only contract-validated transport fields through the existing proxy sender,
45
+ * Send transport observations through the existing proxy sender,
40
46
  * redacted like every other event (known paths, path properties, error text).
41
47
  */
42
48
  export declare const captureTransport: (event: string, properties: TransportParams, userId: string) => Promise<void>;
@@ -550,7 +550,7 @@ export const capture = async (event, properties) => {
550
550
  })();
551
551
  };
552
552
  /**
553
- * Send only contract-validated transport fields through the existing proxy sender,
553
+ * Send transport observations through the existing proxy sender,
554
554
  * redacted like every other event (known paths, path properties, error text).
555
555
  */
556
556
  export const captureTransport = async (event, properties, userId) => {
@@ -0,0 +1,3 @@
1
+ import type { CommandReading } from './command-reading.js';
2
+ /** Reads a command for cmd */
3
+ export declare function readCmdCommands(command: string): Promise<CommandReading>;
@@ -0,0 +1,322 @@
1
+ function tokenize(text) {
2
+ const tokens = [];
3
+ let i = 0;
4
+ while (i < text.length) {
5
+ const char = text[i];
6
+ if (char === ' ' || char === '\t') {
7
+ i++;
8
+ }
9
+ else if (char === '\r' || char === '\n') {
10
+ tokens.push({ kind: 'op', value: '\n', text: char, start: i, atRunTime: false });
11
+ i++;
12
+ }
13
+ else if (char === '&' || char === '|') {
14
+ const value = text[i + 1] === char ? char + char : char;
15
+ tokens.push({ kind: 'op', value, text: value, start: i, atRunTime: false });
16
+ i += value.length;
17
+ }
18
+ else if (char === '(' || char === ')') {
19
+ tokens.push({ kind: char === '(' ? 'open' : 'close', value: char, text: char, start: i, atRunTime: false });
20
+ i++;
21
+ }
22
+ else if (char === '>' || char === '<' || (/[0-9]/.test(char) && /[<>]/.test(text[i + 1] ?? ''))) {
23
+ // A redirection: an optional handle number, > >> or <, and &N when it points at another handle
24
+ const start = i;
25
+ if (/[0-9]/.test(char))
26
+ i++;
27
+ i += text[i] === '>' && text[i + 1] === '>' ? 2 : 1;
28
+ if (text[i] === '&' && /[0-9]/.test(text[i + 1] ?? ''))
29
+ i += 2;
30
+ tokens.push({ kind: 'redirect', value: text.slice(start, i), text: text.slice(start, i), start, atRunTime: false });
31
+ }
32
+ else {
33
+ const start = i;
34
+ let value = '';
35
+ let inQuotes = false;
36
+ // Where in value a ; , = or / is outside "…": cmd ends a command's name at the first one
37
+ const ends = [];
38
+ while (i < text.length) {
39
+ const c = text[i];
40
+ if (inQuotes) {
41
+ if (c === '"')
42
+ inQuotes = false;
43
+ else if (c === '\r' || c === '\n')
44
+ break;
45
+ else
46
+ value += c;
47
+ i++;
48
+ }
49
+ else if (c === '"') {
50
+ inQuotes = true;
51
+ i++;
52
+ }
53
+ else if (c === '^' && i + 1 < text.length) {
54
+ if (';,=/'.includes(text[i + 1]))
55
+ ends.push({ value: value.length, text: i - start });
56
+ value += text[i + 1];
57
+ i += 2;
58
+ }
59
+ else if (' \t\r\n&|()<>'.includes(c)) {
60
+ break;
61
+ }
62
+ else {
63
+ if (';,=/'.includes(c))
64
+ ends.push({ value: value.length, text: i - start });
65
+ value += c;
66
+ i++;
67
+ }
68
+ }
69
+ const written = text.slice(start, i);
70
+ const lead = /^[;,=@]*/.exec(written)[0].length;
71
+ const drive = /^[A-Za-z]:/.test(value.slice(lead));
72
+ const end = ends.find((at) => at.value >= lead && !(drive && value[at.value] === '/'));
73
+ const atRunTime = /%[^%\s]+%/.test(written);
74
+ const ending = { nameEnd: end?.value, textEnd: end?.text };
75
+ tokens.push({ kind: 'word', value, text: written, start, atRunTime, lead, ...ending });
76
+ }
77
+ }
78
+ return tokens;
79
+ }
80
+ const IF_TESTS = ['exist', 'defined', 'errorlevel', 'cmdextversion'];
81
+ const IF_COMPARISONS = ['equ', 'neq', 'lss', 'leq', 'gtr', 'geq'];
82
+ /**
83
+ * How many words an if condition starting at words[i] takes: "exist x" and
84
+ * the other tests take 2, "a==b" 1, "a== b" and "a ==b" 2, "a == b" and
85
+ * "a equ b" 3. Undefined while the words so far aren't a condition yet.
86
+ */
87
+ function ifConditionLength(words, i) {
88
+ const word = words[i]?.value;
89
+ if (word === undefined)
90
+ return undefined;
91
+ const next = words[i + 1]?.value;
92
+ if (IF_TESTS.includes(word.toLowerCase()))
93
+ return 2;
94
+ if (/^.+==.+$/.test(word))
95
+ return 1;
96
+ if (word.endsWith('=='))
97
+ return 2;
98
+ if (next === '==')
99
+ return 3;
100
+ if (next?.startsWith('=='))
101
+ return 2;
102
+ if (next !== undefined && IF_COMPARISONS.includes(next.toLowerCase()))
103
+ return 3;
104
+ return undefined;
105
+ }
106
+ /** Whether a word is only ; , = and @, which cmd skips where a command starts */
107
+ const isLead = (word) => word.lead !== undefined && word.lead > 0 && word.lead === word.value.length;
108
+ /** The name a command's first word gives, without the ; , = and @ that cmd skips before it (;sc runs sc) */
109
+ const commandName = (word) => word.value.slice(word.lead ?? 0, word.nameEnd);
110
+ /** The rest of a command's first word after its name, cmd's first argument: user for net,user, /query for sc/query */
111
+ const afterName = (word) => word.nameEnd === undefined ? '' : word.value.slice(word.nameEnd).replace(/^[;,=]+/, '');
112
+ /** The same rest as written, without the ; , = (and its ^) the name ends at */
113
+ const writtenAfterName = (word) => word.textEnd === undefined ? '' : word.text.slice(word.textEnd).replace(/^(\^?[;,=])+/, '');
114
+ class CmdReader {
115
+ constructor(tokens, text) {
116
+ this.tokens = tokens;
117
+ this.text = text;
118
+ this.position = 0;
119
+ this.commands = [];
120
+ }
121
+ /** Reads commands and the operators between them, up to the end, or up to the ) that closes a group */
122
+ readList(inGroup) {
123
+ while (this.position < this.tokens.length) {
124
+ const token = this.tokens[this.position];
125
+ if (token.kind === 'op') {
126
+ this.position++;
127
+ }
128
+ else if (token.kind === 'close' && inGroup) {
129
+ return;
130
+ }
131
+ else {
132
+ this.readCommand(inGroup);
133
+ }
134
+ }
135
+ if (inGroup)
136
+ throw new Error('a ( group is not closed with )');
137
+ }
138
+ /** Reads one command: a group, or words up to the next operator */
139
+ readCommand(inGroup) {
140
+ // Words of only ; , = and @ before the command are skipped, as spaces are (@ sc runs sc)
141
+ while (this.tokens[this.position]?.kind === 'word' && isLead(this.tokens[this.position]))
142
+ this.position++;
143
+ const first = this.tokens[this.position];
144
+ if (first === undefined || first.kind === 'op' || (first.kind === 'close' && inGroup))
145
+ return;
146
+ if (first.kind === 'open') {
147
+ this.position++;
148
+ this.readList(true);
149
+ this.position++; // the closing )
150
+ this.skipRedirects();
151
+ return;
152
+ }
153
+ const words = [];
154
+ let parens = 0;
155
+ while (this.position < this.tokens.length) {
156
+ const token = this.tokens[this.position];
157
+ if (token.kind === 'open' && parens === 0 && this.readForSet(words))
158
+ continue;
159
+ if (token.kind === 'op')
160
+ break;
161
+ if (token.kind === 'close' && parens === 0 && inGroup)
162
+ break;
163
+ if (token.kind === 'redirect') {
164
+ this.skipRedirects();
165
+ continue;
166
+ }
167
+ // An if or for condition: the command after it starts here, and a ( there opens a group
168
+ if (words.length > 0 && token.kind !== 'close' && this.startsCommandAfter(words, parens)) {
169
+ this.readCommand(inGroup);
170
+ return;
171
+ }
172
+ if (token.kind === 'open')
173
+ parens++;
174
+ if (token.kind === 'close')
175
+ parens--;
176
+ words.push(token);
177
+ this.position++;
178
+ }
179
+ if (words.length > 0 && !this.startsCommandAfter(words, parens))
180
+ this.addCommand(words);
181
+ }
182
+ /** A FOR /F quoted set is a command or literal, not part of the outer list. */
183
+ readForSet(words) {
184
+ if (words.length === 0 || commandName(words[0]).toLowerCase() !== 'for'
185
+ || words[words.length - 1].value.toLowerCase() !== 'in')
186
+ return false;
187
+ const rest = afterName(words[0]);
188
+ // Comma/equal/semicolon may separate FOR from /F; an attached slash cannot.
189
+ if (rest && !';,='.includes(words[0].value[words[0].nameEnd]))
190
+ return false;
191
+ const args = [...(rest ? [rest] : []), ...words.slice(1).map(word => word.value)];
192
+ if (args[0]?.toLowerCase() !== '/f')
193
+ return false;
194
+ const usebackq = /(?:^|\s)usebackq(?:\s|$)/i.test(args[1] ?? '');
195
+ const open = this.tokens[this.position];
196
+ let start = open.start + 1;
197
+ while (/[ \t]/.test(this.text[start] ?? '') && start < this.text.length)
198
+ start++;
199
+ const quote = this.text[start];
200
+ const isCommand = quote === (usebackq ? '`' : "'");
201
+ const isLiteral = quote === (usebackq ? "'" : '"') || (usebackq && quote === '"');
202
+ if (!isCommand && !isLiteral)
203
+ return false;
204
+ // Keep the raw span: tokenization removes quotes and splits the inner operators.
205
+ let end = start + 1;
206
+ let depth = 0;
207
+ let inQuotes = false;
208
+ let close = -1;
209
+ for (; end < this.text.length; end++) {
210
+ const char = this.text[end];
211
+ if (isCommand && char === '^' && !inQuotes) {
212
+ end++;
213
+ continue;
214
+ }
215
+ if (isCommand && char === '"')
216
+ inQuotes = !inQuotes;
217
+ if (!inQuotes && depth === 0 && char === quote) {
218
+ let next = end + 1;
219
+ while (/[ \t]/.test(this.text[next] ?? '') && next < this.text.length)
220
+ next++;
221
+ if (this.text[next] === ')') {
222
+ close = next;
223
+ break;
224
+ }
225
+ }
226
+ if (isCommand && !inQuotes) {
227
+ if (char === '(')
228
+ depth++;
229
+ if (char === ')')
230
+ depth--;
231
+ }
232
+ }
233
+ if (close < 0)
234
+ throw new Error('a for /f quoted set is not closed');
235
+ if (isCommand) {
236
+ // cmd consumes one caret-escape layer before passing the command to its child.
237
+ let command = '';
238
+ const offsets = [];
239
+ inQuotes = false;
240
+ for (let i = start + 1; i < end; i++) {
241
+ const char = this.text[i];
242
+ if (char === '"')
243
+ inQuotes = !inQuotes;
244
+ if (char === '^' && !inQuotes && i + 1 < end)
245
+ i++;
246
+ offsets.push(i);
247
+ command += this.text[i];
248
+ }
249
+ const reader = new CmdReader(tokenize(command), command);
250
+ reader.readList(false);
251
+ this.commands.push(...reader.commands.map(found => ({ ...found, start: offsets[found.start] })));
252
+ }
253
+ // Retain a balanced placeholder so the existing DO/body/group logic still applies.
254
+ words.push(open, { kind: 'close', value: ')', text: ')', start: close, atRunTime: false });
255
+ while (this.position < this.tokens.length && this.tokens[this.position].start <= close)
256
+ this.position++;
257
+ return true;
258
+ }
259
+ /**
260
+ * Whether the words so far are a whole if condition, a for clause up to its
261
+ * "do", an "else" or a "call", so the next token starts the command that runs.
262
+ * parens: how many of the words' ( are not closed yet.
263
+ */
264
+ startsCommandAfter(words, parens) {
265
+ const first = commandName(words[0]).toLowerCase();
266
+ if (first === 'else')
267
+ return words.length === 1;
268
+ // CALL can carry its program in the same token: call,net user must keep net.
269
+ if (first === 'call')
270
+ return words.length === 1 && afterName(words[0]) === '';
271
+ if (first === 'for') {
272
+ return words.length > 1 && parens === 0 && words[words.length - 1].value.toLowerCase() === 'do';
273
+ }
274
+ if (first !== 'if')
275
+ return false;
276
+ let i = 1;
277
+ while (i < words.length && ['/i', 'not'].includes(words[i].value.toLowerCase()))
278
+ i++;
279
+ const length = ifConditionLength(words, i);
280
+ return length !== undefined && words.length === i + length;
281
+ }
282
+ skipRedirects() {
283
+ while (this.tokens[this.position]?.kind === 'redirect') {
284
+ const redirect = this.tokens[this.position++];
285
+ if (!/&[0-9]$/.test(redirect.value) && this.tokens[this.position]?.kind === 'word')
286
+ this.position++;
287
+ }
288
+ }
289
+ addCommand(words) {
290
+ const first = words[0];
291
+ const name = commandName(first);
292
+ if (!name && words.length === 1)
293
+ return; // "" alone runs nothing
294
+ const rest = afterName(first);
295
+ const firstWords = rest ? [name, rest] : [name];
296
+ this.commands.push({
297
+ name,
298
+ words: [
299
+ ...firstWords.map((word) => (first.atRunTime ? null : word)),
300
+ ...words.slice(1).map((word) => (word.atRunTime ? null : word.value)),
301
+ ],
302
+ written: [
303
+ ...(rest ? [first.text.slice(0, first.textEnd), writtenAfterName(first)] : [first.text]),
304
+ ...words.slice(1).map((word) => word.text),
305
+ ],
306
+ wordTexts: [...firstWords, ...words.slice(1).map((word) => word.value)],
307
+ start: first.start,
308
+ nameAtRunTime: first.atRunTime,
309
+ });
310
+ }
311
+ }
312
+ /** Reads a command for cmd */
313
+ export async function readCmdCommands(command) {
314
+ const reader = new CmdReader(tokenize(command), command);
315
+ try {
316
+ reader.readList(false);
317
+ }
318
+ catch (error) {
319
+ return { commands: [], functions: [], parseError: error instanceof Error ? error.message : String(error) };
320
+ }
321
+ return { commands: reader.commands.sort((a, b) => a.start - b.start), functions: [] };
322
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * What the command check finds in a command's text. The check reads each
3
+ * command with a reader for the shell that will run it (POSIX shells,
4
+ * PowerShell, cmd). Every reader returns a CommandReading, and checkCommand()
5
+ * in command-manager.ts turns it into a CommandCheck.
6
+ */
7
+ /** One command the shell would run */
8
+ export interface FoundCommand {
9
+ /**
10
+ * The command's name as the shell reads it, with quotes and escapes removed.
11
+ * In PowerShell it is what the name means there: an alias gives its target
12
+ * (in Windows PowerShell 5.1 "sc" gives "Set-Content"), and a program gives
13
+ * the program's file name. When the name is known only at run time ("$tool"),
14
+ * this is the name as it is written in the text.
15
+ */
16
+ name: string;
17
+ /**
18
+ * The command's words as the shell reads them, starting with the name as
19
+ * written (before PowerShell gives its meaning). A word known only at run
20
+ * time, such as "$CMD" or "$(date)", is null.
21
+ */
22
+ words: (string | null)[];
23
+ /**
24
+ * The same words as they are written in the text, quotes included. The
25
+ * wrapper rules use them: cmd's start takes a first word in quotes as the
26
+ * window title, and a program known only at run time is named as written.
27
+ */
28
+ written: string[];
29
+ /**
30
+ * The same words as the shell reads them, but with each part known only at
31
+ * run time kept as it is written: "sudo $X" gives sudo $X, where `words`
32
+ * has null and `written` keeps the quotes. A shell started with a command
33
+ * text (bash -c "sudo $X") gets such a word as its command, so the check
34
+ * reads it to see the programs it names.
35
+ */
36
+ wordTexts: string[];
37
+ /**
38
+ * PowerShell's Start-Process only: the programs it may start, as this
39
+ * PowerShell binds its FilePath, each with its value (null when known only
40
+ * at run time) and its text as written. A splatted @params may hold
41
+ * FilePath, so it counts as a program known only at run time.
42
+ */
43
+ filePaths?: {
44
+ word: string | null;
45
+ written: string;
46
+ }[];
47
+ /** Where the command starts: an index into the command's text */
48
+ start: number;
49
+ /** True when the name is known only at run time: a variable, or the output of another command */
50
+ nameAtRunTime: boolean;
51
+ }
52
+ /** A function the command's text defines */
53
+ export interface DefinedFunction {
54
+ /** The function's name as written */
55
+ name: string;
56
+ /** Where the definition ends: the index just past its last character */
57
+ end: number;
58
+ }
59
+ /** What a reader found in a command's text */
60
+ export interface CommandReading {
61
+ /** Every command the shell would run, including those nested in others, in the order they start */
62
+ commands: FoundCommand[];
63
+ /**
64
+ * The functions defined by the text's own statements, which stay defined
65
+ * for the rest of the text. A definition inside a subshell, a { } group,
66
+ * another function's body, a pipeline, an if or loop body, after && or ||,
67
+ * or in a PowerShell script block is not listed: it may not exist when a
68
+ * later command runs. Nor is a function the text may remove or hide behind
69
+ * an alias (unset -f halt, Remove-Item function:net, Set-Alias net net.exe),
70
+ * wherever that is written, or one the PowerShell session has an alias of
71
+ * (the user's profile can set one). There are none when the text runs code
72
+ * the reader doesn't read (eval, a file run with ., Invoke-Expression, a
73
+ * method call), which may remove any of them.
74
+ */
75
+ functions: DefinedFunction[];
76
+ /** The parser's message when the text can't be parsed. The two lists are then empty. */
77
+ parseError?: string;
78
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * What the command check finds in a command's text. The check reads each
3
+ * command with a reader for the shell that will run it (POSIX shells,
4
+ * PowerShell, cmd). Every reader returns a CommandReading, and checkCommand()
5
+ * in command-manager.ts turns it into a CommandCheck.
6
+ */
7
+ export {};