fauxnix-cli 1.0.0 → 2.0.0

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.
package/dist/mcp.js CHANGED
@@ -11,8 +11,8 @@ const TOOL_NAME = process.env.FAUXNIX_TOOL_NAME || 'bash';
11
11
  const BATCH_TOOL_NAME = TOOL_NAME + '_batch';
12
12
  // Text and structured output both appear in the JSON response. Leave room for
13
13
  // worst-case JSON escaping below the official stdio client's 10 MiB limit.
14
- const BATCH_STDOUT_LIMIT = 262_144;
15
- const BATCH_STDERR_LIMIT = 65_536;
14
+ const MCP_STDOUT_LIMIT = 262_144;
15
+ const MCP_STDERR_LIMIT = 65_536;
16
16
  const EXEC_ANNOTATIONS = {
17
17
  readOnlyHint: false,
18
18
  destructiveHint: true,
@@ -41,6 +41,7 @@ Unknown commands (git, node, npm, python, cargo...) are passed through and execu
41
41
  Not supported: heredocs, env -i/--ignore-environment, background jobs. if/then/elif/else/fi, for-in loops, while/until, case ... esac, and word-level \$((...)) arithmetic expansion are supported.
42
42
  CWD, environment variables, export/unset, cd, and positional parameters (set -- / $1 / "$@") persist across calls within this session — a resident PowerShell 5.1 host is started when the MCP session begins (and after reset), so the first bash tool call is already warm.
43
43
  Efficiency: when two or more commands or verification steps are already known, prefer ${BATCH_TOOL_NAME} once instead of making several ${TOOL_NAME} calls. Keep separate calls only when the next command requires model interpretation of the previous output. For byte-exact work, measure with wc -c or stat -c %s instead of inferring CRLF byte counts from displayed text.
44
+ MCP capture is bounded to 256 KiB stdout and 64 KiB stderr across the complete command list; larger output is marked truncated. Redirect larger artifacts to files. These transport-safe budgets include room for JSON escaping and duplicate text/structured fields.
44
45
  Exit codes follow bash conventions (0 ok, 1 fail, 2 usage/serious, 127 command not found, 124 timeout, 130 cancelled). The tool also returns structuredContent (schemaVersion 1) with stdout/stderr/exitCode/timedOut/cancelled/truncated/sessionId.
45
46
 
46
47
  Platform requirement: the execution backend is native Windows PowerShell 5.1+. On hosts without PowerShell on PATH (e.g. Linux containers/sandboxes), the bash tool returns exit code 127 with an actionable error instead of running the command.`;
@@ -221,155 +222,175 @@ export async function startMcpServer() {
221
222
  process.env.FAUXNIX_ARG0 = TOOL_NAME;
222
223
  const server = new McpServer({ name: 'fauxnix', version: packageVersion }, { capabilities: { tools: {} } });
223
224
  const session = new FauxnixSession();
224
- await session.prewarm();
225
- server.tool(TOOL_NAME, TOOL_DESCRIPTION, {
226
- command: z.string().describe('The bash-style command line to run'),
227
- timeout_ms: z
228
- .number()
229
- .int()
230
- .min(1000)
231
- .max(600_000)
232
- .optional()
233
- .describe('Timeout in milliseconds (default 120000)'),
234
- }, EXEC_ANNOTATIONS, async ({ command, timeout_ms }, extra) => {
235
- try {
236
- const plans = translateCommandList(parseCommand(command), EXECUTE_TRANSLATION);
237
- const result = await session.run(plans, {
238
- timeoutMs: timeout_ms,
239
- signal: extra.signal,
240
- });
241
- const infra = result.spawnError === 'ENOENT' || result.spawnError === 'START';
242
- return bashToolResult(result, session.id, infra);
243
- }
244
- catch (e) {
245
- const msg = e instanceof Error ? e.message : String(e);
246
- return bashToolResult({
247
- stdout: '',
248
- stderr: msg,
249
- exitCode: 2,
250
- timedOut: false,
251
- cancelled: false,
252
- truncated: false,
253
- }, session.id, true);
254
- }
255
- });
256
- server.tool(BATCH_TOOL_NAME, BATCH_TOOL_DESCRIPTION, {
257
- steps: z
258
- .array(z.object({
259
- id: z.string().min(1).max(64).optional().describe('Optional short step label'),
260
- command: z.string().min(1).max(16384).describe('Bash-style command for this step'),
261
- }))
262
- .min(1)
263
- .max(32)
264
- .describe('Ordered workflow steps; all are compiled before execution begins'),
265
- stop_on_error: z
266
- .boolean()
267
- .optional()
268
- .default(true)
269
- .describe('Stop after the first nonzero exit (default true)'),
270
- timeout_ms: z
271
- .number()
272
- .int()
273
- .min(1000)
274
- .max(600_000)
275
- .optional()
276
- .describe('Total timeout for the complete batch (default 120000)'),
277
- stdout_limit_bytes: z
278
- .number()
279
- .int()
280
- .min(0)
281
- .max(BATCH_STDOUT_LIMIT)
282
- .optional()
283
- .describe('Total stdout budget shared by every step (default 262144)'),
284
- stderr_limit_bytes: z
285
- .number()
286
- .int()
287
- .min(0)
288
- .max(BATCH_STDERR_LIMIT)
289
- .optional()
290
- .describe('Total stderr budget shared by every step (default 65536)'),
291
- }, EXEC_ANNOTATIONS, async ({ steps, stop_on_error, timeout_ms, stdout_limit_bytes, stderr_limit_bytes }, extra) => {
292
- try {
293
- const compiled = compileBatchSteps(steps);
294
- const result = await session.runBatch(compiled, {
295
- stopOnError: stop_on_error,
296
- timeoutMs: timeout_ms,
297
- stdoutLimit: stdout_limit_bytes ?? BATCH_STDOUT_LIMIT,
298
- stderrLimit: stderr_limit_bytes ?? BATCH_STDERR_LIMIT,
299
- signal: extra.signal,
225
+ const input = process.stdin;
226
+ let shutdownPromise;
227
+ const shutdown = () => {
228
+ if (!shutdownPromise) {
229
+ input.removeListener('end', onShutdown);
230
+ input.removeListener('close', onShutdown);
231
+ process.removeListener('SIGINT', onShutdown);
232
+ process.removeListener('SIGTERM', onShutdown);
233
+ // Schedule cleanup after storing the promise so transport.close callbacks
234
+ // can request shutdown again without disposing the session twice.
235
+ shutdownPromise = Promise.resolve().then(async () => {
236
+ try {
237
+ await session.dispose();
238
+ }
239
+ finally {
240
+ try {
241
+ await server.close();
242
+ }
243
+ catch {
244
+ /* best effort, including partially connected transports */
245
+ }
246
+ }
300
247
  });
301
- return batchToolResult(steps, result, session.id);
302
248
  }
303
- catch (e) {
304
- if (e instanceof BatchCompileError) {
305
- return batchCompileErrorResult(steps, e, session.id);
249
+ return shutdownPromise;
250
+ };
251
+ const onShutdown = () => {
252
+ void shutdown().catch(() => undefined);
253
+ };
254
+ try {
255
+ await session.prewarm();
256
+ server.tool(TOOL_NAME, TOOL_DESCRIPTION, {
257
+ command: z.string().describe('The bash-style command line to run'),
258
+ timeout_ms: z
259
+ .number()
260
+ .int()
261
+ .min(1000)
262
+ .max(600_000)
263
+ .optional()
264
+ .describe('Timeout in milliseconds (default 120000)'),
265
+ }, EXEC_ANNOTATIONS, async ({ command, timeout_ms }, extra) => {
266
+ try {
267
+ const plans = translateCommandList(parseCommand(command), EXECUTE_TRANSLATION);
268
+ const result = await session.run(plans, {
269
+ timeoutMs: timeout_ms,
270
+ signal: extra.signal,
271
+ stdoutLimit: MCP_STDOUT_LIMIT,
272
+ stderrLimit: MCP_STDERR_LIMIT,
273
+ });
274
+ const infra = result.infrastructureError === true ||
275
+ result.spawnError === 'ENOENT' || result.spawnError === 'START';
276
+ return bashToolResult(result, session.id, infra);
306
277
  }
307
- const message = e instanceof Error ? e.message : String(e);
308
- return {
309
- content: [{ type: 'text', text: message }],
310
- structuredContent: {
311
- schemaVersion: 1,
312
- sessionId: session.id,
313
- preflightOk: true,
314
- stopReason: 'infrastructure',
315
- stepsRequested: steps.length,
316
- stepsCompleted: 0,
278
+ catch (e) {
279
+ const msg = e instanceof Error ? e.message : String(e);
280
+ return bashToolResult({
281
+ stdout: '',
282
+ stderr: msg,
283
+ exitCode: 2,
317
284
  timedOut: false,
318
285
  cancelled: false,
319
286
  truncated: false,
320
- steps: steps.map((step, index) => ({
321
- index,
322
- ...(step.id ? { id: step.id } : {}),
323
- status: 'skipped',
324
- })),
325
- },
326
- isError: true,
327
- };
328
- }
329
- });
330
- server.tool('fauxnix_translate', 'Translate a bash-style command into the equivalent PowerShell script WITHOUT executing it. Useful for learning/debugging what fauxnix does under the hood.', { command: z.string().describe('The bash-style command line to translate (never executed)') }, TRANSLATE_ANNOTATIONS, async ({ command }) => translateToolResult(command));
331
- server.tool('fauxnix_session', 'Inspect or reset the persistent fauxnix shell session (current directory, environment, positional count, session id). Actions: "status" (default) or "reset".', {
332
- action: z
333
- .enum(['status', 'reset'])
334
- .default('status')
335
- .describe('"status" shows the session state (cwd, tracked env keys, positional count); "reset" clears it back to a fresh shell'),
336
- }, SESSION_ANNOTATIONS, async ({ action }) => {
337
- if (action === 'reset') {
338
- await session.reset();
339
- return { content: [{ type: 'text', text: 'fauxnix: session reset' }] };
340
- }
341
- return { content: [{ type: 'text', text: formatSessionStatus(session) }] };
342
- });
343
- const transport = new StdioServerTransport();
344
- let shuttingDown = false;
345
- const shutdown = async () => {
346
- if (shuttingDown)
347
- return;
348
- shuttingDown = true;
349
- await session.dispose();
287
+ }, session.id, true);
288
+ }
289
+ });
290
+ server.tool(BATCH_TOOL_NAME, BATCH_TOOL_DESCRIPTION, {
291
+ steps: z
292
+ .array(z.object({
293
+ id: z.string().min(1).max(64).optional().describe('Optional short step label'),
294
+ command: z.string().min(1).max(16384).describe('Bash-style command for this step'),
295
+ }))
296
+ .min(1)
297
+ .max(32)
298
+ .describe('Ordered workflow steps; all are compiled before execution begins'),
299
+ stop_on_error: z
300
+ .boolean()
301
+ .optional()
302
+ .default(true)
303
+ .describe('Stop after the first nonzero exit (default true)'),
304
+ timeout_ms: z
305
+ .number()
306
+ .int()
307
+ .min(1000)
308
+ .max(600_000)
309
+ .optional()
310
+ .describe('Total timeout for the complete batch (default 120000)'),
311
+ stdout_limit_bytes: z
312
+ .number()
313
+ .int()
314
+ .min(0)
315
+ .max(MCP_STDOUT_LIMIT)
316
+ .optional()
317
+ .describe('Total stdout budget shared by every step (default 262144)'),
318
+ stderr_limit_bytes: z
319
+ .number()
320
+ .int()
321
+ .min(0)
322
+ .max(MCP_STDERR_LIMIT)
323
+ .optional()
324
+ .describe('Total stderr budget shared by every step (default 65536)'),
325
+ }, EXEC_ANNOTATIONS, async ({ steps, stop_on_error, timeout_ms, stdout_limit_bytes, stderr_limit_bytes }, extra) => {
326
+ try {
327
+ const compiled = compileBatchSteps(steps);
328
+ const result = await session.runBatch(compiled, {
329
+ stopOnError: stop_on_error,
330
+ timeoutMs: timeout_ms,
331
+ stdoutLimit: stdout_limit_bytes ?? MCP_STDOUT_LIMIT,
332
+ stderrLimit: stderr_limit_bytes ?? MCP_STDERR_LIMIT,
333
+ signal: extra.signal,
334
+ });
335
+ return batchToolResult(steps, result, session.id);
336
+ }
337
+ catch (e) {
338
+ if (e instanceof BatchCompileError) {
339
+ return batchCompileErrorResult(steps, e, session.id);
340
+ }
341
+ const message = e instanceof Error ? e.message : String(e);
342
+ return {
343
+ content: [{ type: 'text', text: message }],
344
+ structuredContent: {
345
+ schemaVersion: 1,
346
+ sessionId: session.id,
347
+ preflightOk: true,
348
+ stopReason: 'infrastructure',
349
+ stepsRequested: steps.length,
350
+ stepsCompleted: 0,
351
+ timedOut: false,
352
+ cancelled: false,
353
+ truncated: false,
354
+ steps: steps.map((step, index) => ({
355
+ index,
356
+ ...(step.id ? { id: step.id } : {}),
357
+ status: 'skipped',
358
+ })),
359
+ },
360
+ isError: true,
361
+ };
362
+ }
363
+ });
364
+ server.tool('fauxnix_translate', 'Translate a bash-style command into the equivalent PowerShell script WITHOUT executing it. Useful for learning/debugging what fauxnix does under the hood.', { command: z.string().describe('The bash-style command line to translate (never executed)') }, TRANSLATE_ANNOTATIONS, async ({ command }) => translateToolResult(command));
365
+ server.tool('fauxnix_session', 'Inspect or reset the persistent fauxnix shell session (current directory, environment, positional count, session id). Actions: "status" (default) or "reset".', {
366
+ action: z
367
+ .enum(['status', 'reset'])
368
+ .default('status')
369
+ .describe('"status" shows the session state (cwd, tracked env keys, positional count); "reset" clears it back to a fresh shell'),
370
+ }, SESSION_ANNOTATIONS, async ({ action }) => {
371
+ if (action === 'reset') {
372
+ await session.reset();
373
+ return { content: [{ type: 'text', text: 'fauxnix: session reset' }] };
374
+ }
375
+ return { content: [{ type: 'text', text: formatSessionStatus(session) }] };
376
+ });
377
+ const transport = new StdioServerTransport();
378
+ input.on('end', onShutdown);
379
+ input.on('close', onShutdown);
380
+ process.on('SIGINT', onShutdown);
381
+ process.on('SIGTERM', onShutdown);
382
+ transport.onclose = onShutdown;
383
+ await server.connect(transport);
384
+ }
385
+ catch (error) {
350
386
  try {
351
- await server.close();
387
+ await shutdown();
352
388
  }
353
389
  catch {
354
- /* ignore */
390
+ /* preserve the startup error if session teardown also fails */
355
391
  }
356
- };
357
- process.stdin.on('end', () => {
358
- void shutdown();
359
- });
360
- process.stdin.on('close', () => {
361
- void shutdown();
362
- });
363
- process.on('SIGINT', () => {
364
- void shutdown();
365
- });
366
- process.on('SIGTERM', () => {
367
- void shutdown();
368
- });
369
- transport.onclose = () => {
370
- void shutdown();
371
- };
372
- await server.connect(transport);
392
+ throw error;
393
+ }
373
394
  }
374
395
  // keep referenced for tree-shaking clarity
375
396
  export { translatePipelineBody };
package/dist/parser.js CHANGED
@@ -123,6 +123,12 @@ export function tokenize(input) {
123
123
  let buf = '';
124
124
  while (i < n && input[i] !== '"') {
125
125
  const c = input[i];
126
+ // A quoted continuation joins the physical lines just as it does
127
+ // outside quotes; unlike an ordinary quoted newline it adds no text.
128
+ if (c === '\\' && input[i + 1] === '\n') {
129
+ i += 2;
130
+ continue;
131
+ }
126
132
  if (c === '\\' && i + 1 < n && '"$`\\'.includes(input[i + 1])) {
127
133
  buf += input[i + 1];
128
134
  i += 2;
@@ -441,6 +447,12 @@ function readDollar(input, i) {
441
447
  let depth = 1;
442
448
  let k = j + 1;
443
449
  while (k < n && depth > 0) {
450
+ // Escaped delimiters belong to the command text, not the enclosing
451
+ // substitution. Preserve both characters for its recursive tokenizer.
452
+ if (input[k] === '\\' && k + 1 < n) {
453
+ k += 2;
454
+ continue;
455
+ }
444
456
  if (input[k] === '(')
445
457
  depth++;
446
458
  else if (input[k] === ')')
@@ -449,7 +461,8 @@ function readDollar(input, i) {
449
461
  const q = input[k];
450
462
  k++;
451
463
  while (k < n && input[k] !== q) {
452
- if (input[k] === '\\')
464
+ // Single quotes are fully literal, including a final backslash.
465
+ if (q === '"' && input[k] === '\\')
453
466
  k++;
454
467
  k++;
455
468
  }
@@ -913,6 +926,10 @@ export function parseCommand(input) {
913
926
  const t = peek();
914
927
  if (t.type === 'OP' && t.op === '|') {
915
928
  next();
929
+ // Bash permits physical newlines (and comments on those lines)
930
+ // while waiting for the next pipeline stage, as after && and ||.
931
+ while (peek().type === 'OP' && peek().op === '\n')
932
+ next();
916
933
  continue;
917
934
  }
918
935
  break;
package/dist/ps-host.js CHANGED
@@ -152,7 +152,38 @@ export class PowerShellHost {
152
152
  await this.stop();
153
153
  return this.cancelledResult();
154
154
  }
155
- const started = await this.ensureStarted();
155
+ // Startup is part of the caller's deadline. A cold host must not send a
156
+ // command after its caller has already cancelled or exhausted its budget.
157
+ const deadline = Date.now() + timeoutMs;
158
+ let startupTimer;
159
+ let onStartupAbort;
160
+ const interrupted = new Promise((resolve) => {
161
+ startupTimer = setTimeout(() => resolve('timed_out'), Math.max(0, timeoutMs));
162
+ onStartupAbort = () => resolve('cancelled');
163
+ signal?.addEventListener('abort', onStartupAbort, { once: true });
164
+ if (signal?.aborted)
165
+ resolve('cancelled');
166
+ });
167
+ let started;
168
+ try {
169
+ started = await Promise.race([this.ensureStarted(), interrupted]);
170
+ }
171
+ finally {
172
+ clearTimeout(startupTimer);
173
+ if (onStartupAbort)
174
+ signal?.removeEventListener('abort', onStartupAbort);
175
+ }
176
+ if (started === 'cancelled' || signal?.aborted) {
177
+ await this.stop();
178
+ return this.cancelledResult();
179
+ }
180
+ if (started === 'timed_out' || Date.now() >= deadline) {
181
+ await this.stop();
182
+ return {
183
+ stdout: Buffer.alloc(0), stderr: Buffer.alloc(0), exitCode: 124,
184
+ timedOut: true, cancelled: false, truncated: false,
185
+ };
186
+ }
156
187
  if (started)
157
188
  return { ...started, cancelled: false, truncated: false };
158
189
  const id = 'f' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
@@ -199,9 +230,9 @@ export class PowerShellHost {
199
230
  signal?.addEventListener('abort', onAbort, { once: true });
200
231
  try {
201
232
  if (this.protocol === 2) {
202
- return await this.collectV2(id, timeoutMs, resolvedLimits);
233
+ return await this.collectV2(id, Math.max(0, deadline - Date.now()), resolvedLimits);
203
234
  }
204
- const raw = await this.nextJsonLine(timeoutMs, id);
235
+ const raw = await this.nextJsonLine(Math.max(0, deadline - Date.now()), id);
205
236
  const msg = decodeHostResponse(raw);
206
237
  const native = this.drainNativeStderr();
207
238
  return {
@@ -68,6 +68,11 @@ export interface WordArgs {
68
68
  flags: Set<string>;
69
69
  longs: Set<string>;
70
70
  values: Map<string, string>;
71
+ /** Every option value in argv order, including repeated options/aliases. */
72
+ valueEntries: Array<{
73
+ name: string;
74
+ value: string;
75
+ }>;
71
76
  /** Options that take a value but were not followed by one. */
72
77
  missingValue: string[];
73
78
  operandWords: Word[];
package/dist/registry.js CHANGED
@@ -96,6 +96,11 @@ export function parseWords(args, shortValues = [], longValues = []) {
96
96
  const flags = new Set();
97
97
  const longs = new Set();
98
98
  const values = new Map();
99
+ const valueEntries = [];
100
+ const addValue = (name, value) => {
101
+ values.set(name, value);
102
+ valueEntries.push({ name, value });
103
+ };
99
104
  const missingValue = [];
100
105
  const operandWords = [];
101
106
  let i = 0;
@@ -109,12 +114,12 @@ export function parseWords(args, shortValues = [], longValues = []) {
109
114
  const eq = t.indexOf('=');
110
115
  if (eq >= 0) {
111
116
  longs.add(t.slice(0, eq));
112
- values.set(t.slice(0, eq), t.slice(eq + 1));
117
+ addValue(t.slice(0, eq), t.slice(eq + 1));
113
118
  }
114
119
  else if (longValues.includes(t)) {
115
120
  longs.add(t);
116
121
  if (i + 1 < args.length) {
117
- values.set(t, wordToString(args[i + 1]));
122
+ addValue(t, wordToString(args[i + 1]));
118
123
  i++;
119
124
  }
120
125
  else
@@ -133,10 +138,10 @@ export function parseWords(args, shortValues = [], longValues = []) {
133
138
  // value-taking options report via `values`, not `flags`
134
139
  const rest = body.slice(c + 1);
135
140
  if (rest) {
136
- values.set('-' + ch, rest);
141
+ addValue('-' + ch, rest);
137
142
  }
138
143
  else if (i + 1 < args.length) {
139
- values.set('-' + ch, wordToString(args[i + 1]));
144
+ addValue('-' + ch, wordToString(args[i + 1]));
140
145
  i++;
141
146
  }
142
147
  else
@@ -151,7 +156,7 @@ export function parseWords(args, shortValues = [], longValues = []) {
151
156
  }
152
157
  i++;
153
158
  }
154
- return { flags, longs, values, missingValue, operandWords };
159
+ return { flags, longs, values, valueEntries, missingValue, operandWords };
155
160
  }
156
161
  const specs = new Map();
157
162
  /**
@@ -0,0 +1,3 @@
1
+ export declare const nodeEngineRange: string;
2
+ /** This package uses one inclusive stable-version floor, not general semver ranges. */
3
+ export declare function supportsNode(version: string): boolean;
@@ -0,0 +1,22 @@
1
+ import { readFileSync } from 'node:fs';
2
+ // Keep diagnostics and the entrypoint aligned with the install contract.
3
+ const metadata = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
4
+ export const nodeEngineRange = metadata.engines?.node;
5
+ const minimum = /^>=(\d+)\.(\d+)\.(\d+)$/.exec(nodeEngineRange);
6
+ if (!minimum)
7
+ throw new Error('fauxnix: unsupported package.json Node engine range');
8
+ const required = minimum.slice(1).map(Number);
9
+ /** This package uses one inclusive stable-version floor, not general semver ranges. */
10
+ export function supportsNode(version) {
11
+ const match = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[\w.-]+)?$/.exec(version);
12
+ if (!match)
13
+ return false;
14
+ const actual = match.slice(1, 4).map(Number);
15
+ if (!actual.every(Number.isSafeInteger))
16
+ return false;
17
+ for (let i = 0; i < 3; i++) {
18
+ if (actual[i] !== required[i])
19
+ return actual[i] > required[i];
20
+ }
21
+ return true;
22
+ }
@@ -50,7 +50,8 @@ export declare function pathExpr(s: string): string;
50
50
  /**
51
51
  * Convert a Word to a PowerShell string expression.
52
52
  * Literal words become single-quoted strings; dynamic ones become
53
- * double-quoted strings with $(...) interpolation.
53
+ * double-quoted strings with $(...) interpolation, concatenating command
54
+ * substitutions outside those strings so their scriptblocks parse independently.
54
55
  */
55
56
  export declare function exprOfWord(w: Word, opts?: {
56
57
  preserveCmdSub?: boolean;
@@ -366,7 +366,8 @@ export function pathExpr(s) {
366
366
  /**
367
367
  * Convert a Word to a PowerShell string expression.
368
368
  * Literal words become single-quoted strings; dynamic ones become
369
- * double-quoted strings with $(...) interpolation.
369
+ * double-quoted strings with $(...) interpolation, concatenating command
370
+ * substitutions outside those strings so their scriptblocks parse independently.
370
371
  */
371
372
  export function exprOfWord(w, opts) {
372
373
  // tilde expansion (unquoted leading ~)
@@ -399,35 +400,59 @@ export function exprOfWord(w, opts) {
399
400
  const text = expanded.map((p) => p.text).join('');
400
401
  return pathExpr(normalizeLiteralPath(text));
401
402
  }
402
- // dynamic — build a PS double-quoted string with interpolation
403
- let out = '"';
403
+ return interpolatedWordExpr(expanded, opts?.preserveCmdSub === true);
404
+ }
405
+ function containsCmdSub(parts) {
406
+ return parts.some((part) => part.kind === 'CmdSub' ||
407
+ ((part.kind === 'DoubleQuoted' || part.kind === 'Arith') && containsCmdSub(part.parts)));
408
+ }
409
+ /** Keep generated scriptblocks out of PowerShell's expandable-string lexer. */
410
+ function interpolatedWordExpr(parts, preserveCmdSub) {
411
+ const expressions = [];
412
+ let text = '';
413
+ const flushText = () => {
414
+ if (text)
415
+ expressions.push('"' + text + '"');
416
+ text = '';
417
+ };
404
418
  const emitPart = (p, quoted) => {
405
419
  switch (p.kind) {
406
420
  case 'Text':
407
- out += escapeDq(p.text);
408
- break;
409
421
  case 'SingleQuoted':
410
- out += escapeDq(p.text);
422
+ text += escapeDq(p.text);
411
423
  break;
412
424
  case 'DoubleQuoted':
413
425
  for (const q of p.parts)
414
426
  emitPart(q, true);
415
427
  break;
416
428
  case 'Var':
417
- out += '$(' + varExpr(p.name, p.index, p.param, p.length === true, varExtraOf(p)) + ')';
429
+ text += '$(' + varExpr(p.name, p.index, p.param, p.length === true, varExtraOf(p)) + ')';
418
430
  break;
419
431
  case 'CmdSub':
420
- out += '$(' + translateCmdSub(p.cmd, quoted || opts?.preserveCmdSub === true) + ')';
432
+ flushText();
433
+ // fx-csub returns one string. Preserve an empty result and prevent '+'
434
+ // from acquiring array/numeric semantics when this starts a mixed word.
435
+ expressions.push('[string](' + translateCmdSub(p.cmd, quoted || preserveCmdSub) + ')');
421
436
  break;
422
437
  case 'Arith':
423
- out += arithExpr(p.parts);
438
+ if (containsCmdSub(p.parts)) {
439
+ flushText();
440
+ expressions.push('[string](' + arithExpr(p.parts) + ')');
441
+ }
442
+ else {
443
+ text += arithExpr(p.parts);
444
+ }
424
445
  break;
425
446
  }
426
447
  };
427
- for (const p of expanded)
448
+ for (const p of parts)
428
449
  emitPart(p, false);
429
- out += '"';
430
- return out;
450
+ flushText();
451
+ if (expressions.length === 0)
452
+ return '""';
453
+ if (expressions.length === 1)
454
+ return expressions[0];
455
+ return '(' + expressions.join(' + ') + ')';
431
456
  }
432
457
  let arithHelperPreamble = '';
433
458
  /** Registered by sysinfo so wrapScript can emit fx-arith without a circular import. */
@@ -458,32 +483,7 @@ function arithSourceExpr(parts) {
458
483
  if (parts.every((p) => p.kind === 'Text')) {
459
484
  return psStr(parts.map((p) => p.text).join(''));
460
485
  }
461
- let out = '"';
462
- const emit = (p) => {
463
- switch (p.kind) {
464
- case 'Text':
465
- case 'SingleQuoted':
466
- out += escapeDq(p.text);
467
- break;
468
- case 'DoubleQuoted':
469
- for (const q of p.parts)
470
- emit(q);
471
- break;
472
- case 'Var':
473
- out += '$(' + varExpr(p.name, p.index, p.param, p.length === true, varExtraOf(p)) + ')';
474
- break;
475
- case 'CmdSub':
476
- out += '$(' + translateCmdSub(p.cmd, true) + ')';
477
- break;
478
- case 'Arith':
479
- out += arithExpr(p.parts);
480
- break;
481
- }
482
- };
483
- for (const p of parts)
484
- emit(p);
485
- out += '"';
486
- return out;
486
+ return interpolatedWordExpr(parts, true);
487
487
  }
488
488
  /** Literal text of a word when it contains no interpolation, else null. */
489
489
  export function literalOfWord(w) {