Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

command.ts

120 lines4.0 KB

1/**
2 * The variables of this process that a command gets. The others, like
3 * provider keys and `DATABASE_URL`, stay in the server.
4 */
5const KEPT_ENV = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'TMPDIR', 'TEMP', 'TMP']
6/** On Windows, a command also gets these, so programs can start. */
7const KEPT_WINDOWS_ENV = [
8 'SystemRoot',
9 'ComSpec',
10 'PATHEXT',
11 'WINDIR',
12 'USERPROFILE',
14​
15/**
16 * The environment of a command that this process starts: the variables of
17 * this process in a short list (`PATH`, `HOME`, `LANG`, `LC_ALL`, `TMPDIR`,
18 * `TEMP`, `TMP`, and on Windows `SystemRoot`, `ComSpec`, `PATHEXT`, `WINDIR`,
19 * `USERPROFILE`), plus the variables named in `passEnv`, plus `env`. No
20 * other variable of this process goes to the command. On Windows it sets
21 * `NoDefaultCurrentDirectoryInExePath`, so `cmd.exe` takes a program name
22 * from the PATH only, and not from the current folder, where a cloned repo
23 * can put an `rg.cmd`. Without `process` (a browser), only `env`.
24 *
25 * @example
26 * ```ts
27 * spawn(command, {
28 * shell: true,
29 * env: commandEnv({ AGENT: '1' }, process.platform, ['HTTPS_PROXY']),
30 * })
31 * ```
32 */
33export function commandEnv(
34 env: Record<string, string> | undefined,
35 platform: string,
36 passEnv: ReadonlyArray<string> = [],
37) {
38 const isWindows = platform === 'win32'
39 const names = isWindows
40 ? [...KEPT_ENV, ...KEPT_WINDOWS_ENV, ...passEnv]
41 : [...KEPT_ENV, ...passEnv]
42 const own: Record<string, string | undefined> =
43 typeof process !== 'undefined' ? process.env : {}
44 const kept: Record<string, string> = {}
45 for (const name of names) {
46 // On Windows, `process.env` finds a name in any letter case.
47 const value = own[name]
48 if (value !== undefined) kept[name] = value
49 }
50 if (!isWindows) return { ...kept, ...env }
51 return { ...kept, ...env, NoDefaultCurrentDirectoryInExePath: '1' }
53​
54const encoder = new TextEncoder()
55const decoder = new TextDecoder()
56​
57/** True for a byte in the middle of a UTF-8 character (`10xxxxxx`). */
58const isContinuation = (byte: number) => (byte & 0xc0) === 0x80
59​
60/**
61 * The newest output of a command, at most `maxBytes` bytes. When more comes,
62 * the oldest bytes are dropped. `text()` gives the output as UTF-8 text, and
63 * starts with a line that tells how many bytes were dropped.
64 *
65 * @example
66 * ```ts
67 * const output = createOutputTail(1024 * 1024)
68 * child.stdout.on('data', output.push)
69 * output.text() // '[12 earlier bytes were dropped.]\n...'
70 * ```
71 */
72export function createOutputTail(maxBytes: number) {
73 // The chunks from `start` on are the output. The ones before are dropped.
74 const chunks: Array<Uint8Array> = []
75 let start = 0
76 let size = 0
77 let dropped = 0
78​
79 const push = (chunk: Uint8Array | string) => {
80 const bytes = typeof chunk === 'string' ? encoder.encode(chunk) : chunk
81 // A copy of the end only, so a big chunk is not kept whole.
82 const kept = bytes.byteLength > maxBytes ? bytes.slice(-maxBytes) : bytes
83 dropped += bytes.byteLength - kept.byteLength
84 chunks.push(kept)
85 size += kept.byteLength
86 while (size > maxBytes) {
87 const first = chunks[start]
88 if (first === undefined) break
89 const over = size - maxBytes
90 const cut = Math.min(over, first.byteLength)
91 if (cut === first.byteLength) start += 1
92 else chunks[start] = first.subarray(cut)
93 size -= cut
94 dropped += cut
95 }
96 // Remove the dropped chunks from the array now and then, not each time.
97 if (start > 1024 && start * 2 > chunks.length) {
98 chunks.splice(0, start)
99 start = 0
100 }
101 }
102​
103 const text = () => {
104 let bytes = new Uint8Array(size)
105 let at = 0
106 for (const chunk of chunks.slice(start)) {
107 bytes.set(chunk, at)
108 at += chunk.byteLength
109 }
110 if (dropped === 0) return decoder.decode(bytes)
111 // The cut can be in a character. Start at the next whole one.
112 let from = 0
113 while (from < 3 && from < bytes.length && isContinuation(bytes[from] ?? 0))
114 from += 1
115 bytes = bytes.subarray(from)
116 return `[${dropped + from} earlier bytes were dropped.]\n${decoder.decode(bytes)}`
117 }
118​
119 return { push, text }