@noldova/terminal 0.0.0-stage → 0.0.2

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 (189) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +10 -2
  3. package/menus.json +53 -0
  4. package/module.json +28 -0
  5. package/package.json +50 -4
  6. package/settings.json +83 -0
  7. package/src/api/index.d.ts +131 -0
  8. package/src/api/index.js +11 -0
  9. package/src/api/window.d.ts +467 -0
  10. package/src/api/window.js +8 -0
  11. package/src/enums/escape-state.js +15 -0
  12. package/src/enums/escape-stripper-state.js +15 -0
  13. package/src/enums/mark-kind.js +18 -0
  14. package/src/enums/shell-family.js +14 -0
  15. package/src/enums/system-requirement.js +11 -0
  16. package/src/exceptions/agent-terminal-restart.exception.js +16 -0
  17. package/src/exceptions/command-exited.exception.js +23 -0
  18. package/src/exceptions/command-failed.exception.js +13 -0
  19. package/src/exceptions/command-not-started.exception.js +17 -0
  20. package/src/exceptions/command-output-too-long.exception.js +18 -0
  21. package/src/exceptions/command-timed-out.exception.js +18 -0
  22. package/src/exceptions/command-variable-not-set.exception.js +18 -0
  23. package/src/exceptions/default-shell-not-found.exception.js +14 -0
  24. package/src/exceptions/environment-export-invalid.exception.js +14 -0
  25. package/src/exceptions/environment-key-unreadable.exception.js +17 -0
  26. package/src/exceptions/environment-unreadable.exception.js +13 -0
  27. package/src/exceptions/folder-not-found.exception.js +16 -0
  28. package/src/exceptions/host-ended.exception.js +14 -0
  29. package/src/exceptions/session-not-found.exception.js +18 -0
  30. package/src/exceptions/shell-kind-not-found.exception.js +16 -0
  31. package/src/exceptions/shell-not-found.exception.js +18 -0
  32. package/src/exceptions/shells-unreadable.exception.js +13 -0
  33. package/src/exceptions/stored-lines-damaged.exception.js +15 -0
  34. package/src/exceptions/stored-lines-unwritable.exception.js +15 -0
  35. package/src/exceptions/system-root-missing.exception.js +14 -0
  36. package/src/exceptions/terminal.exception.js +13 -0
  37. package/src/exceptions/unknown-method.exception.js +16 -0
  38. package/src/exceptions/unsupported-system.exception.js +18 -0
  39. package/src/exceptions/visual-studio-unreadable.exception.js +15 -0
  40. package/src/exceptions/wsl-distributions-unreadable.exception.js +15 -0
  41. package/src/interfaces/i-command-runner.js +8 -0
  42. package/src/interfaces/i-disposable.js +8 -0
  43. package/src/interfaces/i-environment-source.js +8 -0
  44. package/src/interfaces/i-file-system-reader.js +8 -0
  45. package/src/interfaces/i-file-system-writer.js +8 -0
  46. package/src/interfaces/i-flow-controller-listener.js +8 -0
  47. package/src/interfaces/i-folder-access.js +8 -0
  48. package/src/interfaces/i-line-process-listener.js +8 -0
  49. package/src/interfaces/i-line-process-starter.js +8 -0
  50. package/src/interfaces/i-line-process.js +8 -0
  51. package/src/interfaces/i-output-batcher-listener.js +8 -0
  52. package/src/interfaces/i-process-signaller.js +8 -0
  53. package/src/interfaces/i-pseudo-terminal-listener.js +8 -0
  54. package/src/interfaces/i-pty-exit-event.js +8 -0
  55. package/src/interfaces/i-pty-process.js +8 -0
  56. package/src/interfaces/i-pty-spawner.js +8 -0
  57. package/src/interfaces/i-terminal-mirror-listener.js +8 -0
  58. package/src/interfaces/i-terminal-session-listener.js +8 -0
  59. package/src/interfaces/i-waiting-options-request.js +8 -0
  60. package/src/models/command-listing.js +17 -0
  61. package/src/models/completion-candidate.js +19 -0
  62. package/src/models/environment-tools.js +23 -0
  63. package/src/models/environment-variable.js +15 -0
  64. package/src/models/folder-entry.js +15 -0
  65. package/src/models/hosted-terminal.js +116 -0
  66. package/src/models/mirror-line.js +27 -0
  67. package/src/models/mirror-snapshot.js +19 -0
  68. package/src/models/one-shot-launch.js +42 -0
  69. package/src/models/pane-progress.js +15 -0
  70. package/src/models/powershell-cmdlet.js +21 -0
  71. package/src/models/powershell-lookup.js +17 -0
  72. package/src/models/powershell-parameter.js +19 -0
  73. package/src/models/registry-value.js +15 -0
  74. package/src/models/request-client.js +23 -0
  75. package/src/models/saved-terminal.js +25 -0
  76. package/src/models/shell-launch.js +23 -0
  77. package/src/models/shell-line.js +21 -0
  78. package/src/models/shell-mark.js +19 -0
  79. package/src/models/shell-options-reply.js +17 -0
  80. package/src/models/shell.js +29 -0
  81. package/src/models/started-shell.js +21 -0
  82. package/src/models/system-shortfall.js +15 -0
  83. package/src/models/terminal-events.js +37 -0
  84. package/src/models/terminal-history-paths.js +15 -0
  85. package/src/models/terminal-prompt.js +28 -0
  86. package/src/models/tracked-command.js +26 -0
  87. package/src/models/typed-line.js +40 -0
  88. package/src/models/visual-studio-installation.js +22 -0
  89. package/src/models/waiting-run.js +25 -0
  90. package/src/resources.js +1725 -0
  91. package/src/runtime-part.js +84 -0
  92. package/src/services/agent-terminal.js +137 -0
  93. package/src/services/agent-terminals.js +55 -0
  94. package/src/services/bounded-reads.js +57 -0
  95. package/src/services/change-signal.js +33 -0
  96. package/src/services/command-history.js +20 -0
  97. package/src/services/command-runner.js +67 -0
  98. package/src/services/command-tracker.js +161 -0
  99. package/src/services/completion-source.js +316 -0
  100. package/src/services/context-pty-process.js +79 -0
  101. package/src/services/context-pty-spawner.js +26 -0
  102. package/src/services/deferred-pty-process.js +94 -0
  103. package/src/services/escape-sequence-tracker.js +126 -0
  104. package/src/services/escape-stripper.js +91 -0
  105. package/src/services/failure-text.js +15 -0
  106. package/src/services/file-system-writer.js +35 -0
  107. package/src/services/file-system.reader.js +54 -0
  108. package/src/services/flow-controller.js +102 -0
  109. package/src/services/folder-access.js +19 -0
  110. package/src/services/inherited-environment.js +20 -0
  111. package/src/services/line-process-starter.js +17 -0
  112. package/src/services/line-process.js +72 -0
  113. package/src/services/log-file.js +57 -0
  114. package/src/services/mac-environment.js +81 -0
  115. package/src/services/mac-folder-access.js +17 -0
  116. package/src/services/mark-scanner.js +94 -0
  117. package/src/services/one-shot-command.js +119 -0
  118. package/src/services/output-batcher.js +62 -0
  119. package/src/services/output-log.js +50 -0
  120. package/src/services/powershell-binding.js +61 -0
  121. package/src/services/process-signaller.js +19 -0
  122. package/src/services/pseudo-terminal.js +54 -0
  123. package/src/services/registry-export.js +108 -0
  124. package/src/services/resize-wakeup.js +39 -0
  125. package/src/services/saved-terminals.js +52 -0
  126. package/src/services/shared-reads.js +41 -0
  127. package/src/services/shell-command.js +90 -0
  128. package/src/services/shell-environment.js +20 -0
  129. package/src/services/shell-integration.js +207 -0
  130. package/src/services/shell-locator.js +177 -0
  131. package/src/services/shell-options-queue.js +34 -0
  132. package/src/services/shell-words.js +80 -0
  133. package/src/services/system-requirements.js +46 -0
  134. package/src/services/terminal-audience.js +83 -0
  135. package/src/services/terminal-history-folder.js +97 -0
  136. package/src/services/terminal-history-segment.js +109 -0
  137. package/src/services/terminal-history.js +130 -0
  138. package/src/services/terminal-host.js +931 -0
  139. package/src/services/terminal-line-reader.js +101 -0
  140. package/src/services/terminal-mirror.js +221 -0
  141. package/src/services/terminal-owner.service.js +27 -0
  142. package/src/services/terminal-session.js +398 -0
  143. package/src/services/visual-studio.reader.js +76 -0
  144. package/src/services/windows-environment.js +218 -0
  145. package/src/services/windows-folder-access.js +23 -0
  146. package/src/services/wsl-distribution.reader.js +49 -0
  147. package/src/services/xterm-headless-loader.js +14 -0
  148. package/src/tools/enums/command-status.js +13 -0
  149. package/src/tools/enums/run-method.js +11 -0
  150. package/src/tools/exceptions/abort-reason-unknown.exception.js +17 -0
  151. package/src/tools/exceptions/stale-terminal.exception.js +16 -0
  152. package/src/tools/interfaces/i-agent-command.js +8 -0
  153. package/src/tools/interfaces/i-agent-terminal.js +8 -0
  154. package/src/tools/interfaces/i-agent-terminals.js +8 -0
  155. package/src/tools/interfaces/i-output-source.js +8 -0
  156. package/src/tools/interfaces/i-terminal-prompt.js +8 -0
  157. package/src/tools/models/agent-terminal-access.js +25 -0
  158. package/src/tools/models/agent-terminal-opening.js +29 -0
  159. package/src/tools/models/command-line.js +28 -0
  160. package/src/tools/models/key-sequence.js +27 -0
  161. package/src/tools/models/output-chunk.js +18 -0
  162. package/src/tools/models/output-excerpt.js +31 -0
  163. package/src/tools/models/permission-ask.js +34 -0
  164. package/src/tools/models/read-cursor.js +26 -0
  165. package/src/tools/models/read-cursors.js +25 -0
  166. package/src/tools/models/terminal-open-input.js +34 -0
  167. package/src/tools/models/terminal-output-report.js +61 -0
  168. package/src/tools/models/terminal-read-input.js +39 -0
  169. package/src/tools/models/terminal-run-input.js +52 -0
  170. package/src/tools/models/terminal-target-input.js +34 -0
  171. package/src/tools/models/terminal-write-input.js +38 -0
  172. package/src/tools/models/tool-call-context.js +61 -0
  173. package/src/tools/services/abort-reason-reader.js +25 -0
  174. package/src/tools/services/permission-details.js +42 -0
  175. package/src/tools/services/permission-gate.js +35 -0
  176. package/src/tools/services/signal-race.js +24 -0
  177. package/src/tools/services/terminal-access-policy.js +57 -0
  178. package/src/tools/services/terminal-close-tool.js +57 -0
  179. package/src/tools/services/terminal-interrupt-tool.js +57 -0
  180. package/src/tools/services/terminal-list-tool.js +69 -0
  181. package/src/tools/services/terminal-open-tool.js +71 -0
  182. package/src/tools/services/terminal-read-tool.js +58 -0
  183. package/src/tools/services/terminal-run-tool.js +78 -0
  184. package/src/tools/services/terminal-text-escaper.js +40 -0
  185. package/src/tools/services/terminal-tool.js +47 -0
  186. package/src/tools/services/terminal-tools.js +60 -0
  187. package/src/tools/services/terminal-write-tool.js +75 -0
  188. package/src/tools/services/tool-failures.js +28 -0
  189. package/src/tools/services/tool-results.js +13 -0
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { Resources } from "../resources.js";
9
+ import { CommandStatus } from "../tools/enums/command-status.js";
10
+ import { RunMethod } from "../tools/enums/run-method.js";
11
+ import { OutputChunk } from "../tools/models/output-chunk.js";
12
+ export class ShellCommand {
13
+ session;
14
+ line;
15
+ isKilled = false;
16
+ givenUp = null;
17
+ method = RunMethod.InShell;
18
+ logFile;
19
+ constructor(session, command, timeoutMilliseconds, logFile) {
20
+ this.session = session;
21
+ this.logFile = logFile;
22
+ this.line = session.typeLine(command);
23
+ if (timeoutMilliseconds > 0) {
24
+ const limit = new AbortController();
25
+ const timer = setTimeout(() => limit.abort(), timeoutMilliseconds).unref();
26
+ void session.changes.waitUntilAsync(() => this.hasEnded, null, limit.signal).then(() => {
27
+ clearTimeout(timer);
28
+ if (limit.signal.aborted)
29
+ this.interrupt();
30
+ });
31
+ }
32
+ }
33
+ get status() {
34
+ if (this.givenUp !== null)
35
+ return CommandStatus.Killed;
36
+ if (this.tracked?.hasEnded === true || this.unmarkedEnd !== null)
37
+ return this.isKilled ? CommandStatus.Killed : CommandStatus.Exited;
38
+ if (this.session.hasExited)
39
+ return CommandStatus.Killed;
40
+ return this.session.text.isAwaitingSecret ? CommandStatus.AwaitingInput : CommandStatus.Running;
41
+ }
42
+ get exitCode() {
43
+ return this.givenUp === null ? this.tracked?.exitCode ?? null : null;
44
+ }
45
+ get cwd() {
46
+ return this.givenUp === null ? this.tracked?.cwd ?? null : null;
47
+ }
48
+ get hasEnded() {
49
+ return this.givenUp !== null || this.tracked?.hasEnded === true || this.unmarkedEnd !== null || this.session.hasExited;
50
+ }
51
+ get outputStart() {
52
+ if (this.givenUp !== null)
53
+ return this.givenUp[0];
54
+ const tracked = this.tracked;
55
+ return tracked?.hasOutputStart === true ? tracked.outputStart : this.line.startOffset;
56
+ }
57
+ get outputEnd() {
58
+ return this.givenUp?.[1] ?? this.tracked?.outputEnd ?? this.unmarkedEnd ?? this.session.text.endOffset;
59
+ }
60
+ get unmarkedEnd() {
61
+ return this.line.endOffset;
62
+ }
63
+ get tracked() {
64
+ return this.line.command;
65
+ }
66
+ readSince(offset) {
67
+ const start = this.outputStart;
68
+ const end = this.outputEnd;
69
+ return new OutputChunk(this.session.text.readRange(start + offset, end), end - start);
70
+ }
71
+ waitForOutputAsync(offset, timeoutMilliseconds, signal) {
72
+ return this.session.changes.waitUntilAsync(() => this.hasEnded || this.outputEnd > this.outputStart + offset, timeoutMilliseconds, signal);
73
+ }
74
+ waitForEndAsync(timeoutMilliseconds, signal) {
75
+ return this.session.changes.waitUntilAsync(() => this.hasEnded, timeoutMilliseconds, signal);
76
+ }
77
+ interrupt() {
78
+ if (this.hasEnded || this.isKilled)
79
+ return false;
80
+ this.isKilled = true;
81
+ this.session.write(Resources.interruptKey);
82
+ setTimeout(() => {
83
+ if (this.hasEnded)
84
+ return;
85
+ this.givenUp = [this.outputStart, this.outputEnd];
86
+ this.session.changes.notify();
87
+ }, Resources.graceMilliseconds).unref();
88
+ return true;
89
+ }
90
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { Resources } from "../resources.js";
9
+ import { InheritedEnvironment } from "./inherited-environment.js";
10
+ import { MacEnvironment } from "./mac-environment.js";
11
+ import { WindowsEnvironment } from "./windows-environment.js";
12
+ export class ShellEnvironment {
13
+ static create(platform, environment, tools, log, locale, hasLocaleAsync) {
14
+ if (platform === Resources.windowsPlatform)
15
+ return new WindowsEnvironment(environment, tools, log);
16
+ if (platform === Resources.macPlatform)
17
+ return new MacEnvironment(environment, tools.starter, locale, hasLocaleAsync);
18
+ return new InheritedEnvironment(environment);
19
+ }
20
+ }
@@ -0,0 +1,207 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { randomBytes } from "node:crypto";
9
+ import path from "node:path";
10
+ import { Resources as ProtocolResources } from "@noldova/terminal.protocol";
11
+ import { ShellFamily } from "../enums/shell-family.js";
12
+ import { ShellLaunch } from "../models/shell-launch.js";
13
+ import { Resources } from "../resources.js";
14
+ import { FailureText } from "./failure-text.js";
15
+ export class ShellIntegration {
16
+ writer;
17
+ temporaryFolder;
18
+ log;
19
+ access;
20
+ settings;
21
+ platform;
22
+ sharedMemoryFolders = new Map();
23
+ folder = null;
24
+ constructor(writer, temporaryFolder, log, access, settings, platform) {
25
+ this.writer = writer;
26
+ this.temporaryFolder = temporaryFolder;
27
+ this.log = log;
28
+ this.access = access;
29
+ this.settings = settings;
30
+ this.platform = platform;
31
+ }
32
+ async prepareAsync(shell, nonce, environment, note = null) {
33
+ const family = ShellIntegration.toFamily(shell.file);
34
+ if (family === ShellFamily.CommandPrompt)
35
+ return ShellIntegration.toCommandPromptLaunch(shell, note);
36
+ if (family === ShellFamily.Other)
37
+ return new ShellLaunch(shell.file, shell.args, {}, null);
38
+ if (family === ShellFamily.PowerShell)
39
+ await this.makeSharedMemoryFolderAsync(environment);
40
+ const folder = await this.writeScriptsOrNullAsync();
41
+ const nonceFile = folder === null ? null : await this.writeNonceOrNullAsync(folder, nonce);
42
+ if (folder === null || nonceFile === null)
43
+ return ShellIntegration.toPlainLaunch(shell, family);
44
+ const noteVariables = note === null ? {} : { [Resources.noteVariable]: note };
45
+ if (family === ShellFamily.PowerShell)
46
+ return new ShellLaunch(shell.file, [...shell.args, ...Resources.powerShellIntegrationArguments, ShellIntegration.encode([Resources.shellIntegrationPowerShellNonce, Resources.shellIntegrationPowerShellNote, Resources.shellIntegrationPowerShellProfiles, shell.startCommand,
47
+ Resources.shellIntegrationPowerShellScript].filter(t => t !== null).join(Resources.lineFeed))], {
48
+ [Resources.nonceFileVariable]: nonceFile,
49
+ ...noteVariables
50
+ }, nonce, nonceFile, note !== null);
51
+ if (family === ShellFamily.Bash) {
52
+ const bashScript = path.join(folder, Resources.bashScriptFile).replaceAll(Resources.windowsSeparator, Resources.posixSeparator);
53
+ const isLogin = shell.args.some(t => Resources.loginArguments.includes(t));
54
+ return new ShellLaunch(shell.file, [Resources.initFileArgument, bashScript, Resources.interactiveArgument], {
55
+ [Resources.nonceFileVariable]: nonceFile.replaceAll(Resources.windowsSeparator, Resources.posixSeparator),
56
+ ...(isLogin ? { [Resources.loginVariable]: Resources.shellIntegrationLoginValue } : {}),
57
+ ...noteVariables
58
+ }, nonce, nonceFile, note !== null);
59
+ }
60
+ const userFolder = environment[Resources.zdotdirVariable];
61
+ return new ShellLaunch(shell.file, shell.args, {
62
+ [Resources.nonceFileVariable]: nonceFile,
63
+ [Resources.zdotdirVariable]: folder,
64
+ ...(userFolder === undefined ? {} : { [Resources.userZdotdirVariable]: userFolder }),
65
+ ...noteVariables
66
+ }, nonce, nonceFile, note !== null);
67
+ }
68
+ watch(process, launch) {
69
+ const { nonce, nonceFile } = launch;
70
+ if (nonce === null || nonceFile === null)
71
+ return;
72
+ const remove = () => {
73
+ data.dispose();
74
+ exit.dispose();
75
+ void this.removeNonceFileAsync(nonceFile);
76
+ };
77
+ const data = process.onData(t => {
78
+ if (t.includes(nonce))
79
+ remove();
80
+ });
81
+ const exit = process.onExit(() => remove());
82
+ }
83
+ async removeNonceFileAsync(nonceFile) {
84
+ if (nonceFile === null)
85
+ return;
86
+ try {
87
+ await this.writer.removeFileAsync(nonceFile);
88
+ }
89
+ catch (error) {
90
+ this.log.write(Resources.formatNonceFileRemovalFailed(FailureText.read(error)));
91
+ }
92
+ }
93
+ async disposeAsync() {
94
+ const folder = this.folder;
95
+ this.folder = null;
96
+ if (folder !== null)
97
+ await this.writer.removeFolderAsync(await folder);
98
+ }
99
+ isSuggesting() {
100
+ try {
101
+ return this.settings.read(ProtocolResources.suggestionsSetting) !== false;
102
+ }
103
+ catch (error) {
104
+ this.log.write(Resources.formatSuggestionsUnread(FailureText.read(error)));
105
+ return true;
106
+ }
107
+ }
108
+ onSuggestingChanged(listener) {
109
+ try {
110
+ this.settings.onChanged(ProtocolResources.suggestionsSetting, t => listener(t.value !== false));
111
+ }
112
+ catch (error) {
113
+ this.log.write(Resources.formatSuggestionsUnwatched(FailureText.read(error)));
114
+ }
115
+ }
116
+ makeSharedMemoryFolderAsync(environment) {
117
+ const runtimeFolder = environment[Resources.runtimeFolderVariable];
118
+ if (this.platform !== Resources.linuxPlatform || runtimeFolder === undefined || !path.posix.isAbsolute(runtimeFolder))
119
+ return Promise.resolve();
120
+ const dotnetFolder = path.posix.join(runtimeFolder, Resources.dotnetFolder);
121
+ const folder = path.posix.join(dotnetFolder, Resources.dotnetSharedMemoryFolder);
122
+ const made = this.sharedMemoryFolders.get(folder) ?? this.createSharedMemoryFolderAsync(dotnetFolder, folder);
123
+ this.sharedMemoryFolders.set(folder, made);
124
+ return made;
125
+ }
126
+ async createSharedMemoryFolderAsync(dotnetFolder, folder) {
127
+ try {
128
+ await this.writer.createMissingFolderAsync(dotnetFolder, Resources.dotnetSharedMemoryFolderMode);
129
+ await this.writer.createMissingFolderAsync(folder, Resources.dotnetSharedMemoryFolderMode);
130
+ }
131
+ catch (error) {
132
+ this.log.write(Resources.formatDotnetSharedMemoryFolderFailed(folder, FailureText.read(error)));
133
+ }
134
+ }
135
+ async writeScriptsOrNullAsync() {
136
+ this.folder ??= this.writeScriptsAsync();
137
+ try {
138
+ return await this.folder;
139
+ }
140
+ catch (error) {
141
+ this.folder = null;
142
+ this.log.write(Resources.formatIntegrationFailed(FailureText.read(error)));
143
+ return null;
144
+ }
145
+ }
146
+ async writeNonceOrNullAsync(folder, nonce) {
147
+ const nonceFile = path.join(folder, `${Resources.nonceFilePrefix}${randomBytes(Resources.nonceFileNameBytes).toString(Resources.hexEncoding)}`);
148
+ try {
149
+ await this.writer.writeTextAsync(nonceFile, `${nonce}${Resources.lineFeed}`);
150
+ return nonceFile;
151
+ }
152
+ catch (error) {
153
+ this.log.write(Resources.formatNonceFileFailed(FailureText.read(error)));
154
+ return null;
155
+ }
156
+ }
157
+ async writeScriptsAsync() {
158
+ const folder = await this.writer.createPrivateFolderAsync(path.join(this.temporaryFolder, Resources.integrationFolderPrefix));
159
+ try {
160
+ await this.access?.restrictAsync(folder);
161
+ for (const [name, text] of [
162
+ [Resources.bashScriptFile, Resources.shellIntegrationBashScript],
163
+ [Resources.zshEnvironmentFile, Resources.shellIntegrationZshEnvironment],
164
+ [Resources.zshProfileFile, Resources.shellIntegrationZshProfile],
165
+ [Resources.zshInteractiveFile, Resources.shellIntegrationZshInteractive],
166
+ [Resources.zshLoginFile, Resources.shellIntegrationZshLogin]
167
+ ])
168
+ await this.writer.writeTextAsync(path.join(folder, name), text);
169
+ }
170
+ catch (error) {
171
+ await this.writer.removeFolderAsync(folder)
172
+ .catch((removalError) => this.log.write(Resources.formatIntegrationRemovalFailed(FailureText.read(removalError))));
173
+ throw error;
174
+ }
175
+ return folder;
176
+ }
177
+ static toCommandPromptLaunch(shell, note) {
178
+ const [first, ...start] = shell.args;
179
+ if (note === null || (first !== undefined && first.toLowerCase() !== Resources.keepOpenArgument))
180
+ return new ShellLaunch(shell.file, shell.args, {}, null);
181
+ return new ShellLaunch(shell.file, Resources.formatCmdNoteLine(shell.file, Resources.noteVariable, Resources.formatCmdStart(start)), { [Resources.noteVariable]: note.slice(0, note.length - Resources.noteLineBreak.length) }, null, null, true);
182
+ }
183
+ static toPlainLaunch(shell, family) {
184
+ if (family !== ShellFamily.PowerShell || shell.startCommand === null)
185
+ return new ShellLaunch(shell.file, shell.args, {}, null);
186
+ return new ShellLaunch(shell.file, [...shell.args, ...Resources.powerShellArguments, ShellIntegration.encode(shell.startCommand)], {}, null);
187
+ }
188
+ static toFamily(file) {
189
+ const name = path.win32.parse(file).name.toLowerCase();
190
+ switch (name) {
191
+ case Resources.bashExecutable:
192
+ return ShellFamily.Bash;
193
+ case Resources.zshExecutable:
194
+ return ShellFamily.Zsh;
195
+ case Resources.cmdExecutable:
196
+ return ShellFamily.CommandPrompt;
197
+ case Resources.pwshExecutable:
198
+ case Resources.windowsPowerShellExecutable:
199
+ return ShellFamily.PowerShell;
200
+ default:
201
+ return ShellFamily.Other;
202
+ }
203
+ }
204
+ static encode(script) {
205
+ return Buffer.from(script, Resources.utf16Encoding).toString(Resources.base64Encoding);
206
+ }
207
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { userInfo } from "node:os";
9
+ import path from "node:path";
10
+ import { TerminalShellKind } from "@noldova/terminal.protocol";
11
+ import { Shell } from "../models/shell.js";
12
+ import { Resources } from "../resources.js";
13
+ import { FailureText } from "./failure-text.js";
14
+ import { VisualStudioReader } from "./visual-studio.reader.js";
15
+ import { WslDistributionReader } from "./wsl-distribution.reader.js";
16
+ export class ShellLocator {
17
+ platform;
18
+ architecture;
19
+ environment;
20
+ userShell;
21
+ fileSystem;
22
+ log;
23
+ wsl;
24
+ visualStudioReader;
25
+ distributions = null;
26
+ installations = null;
27
+ constructor(platform, architecture, environment, userShell, fileSystem, runner, log) {
28
+ const systemRoot = environment[Resources.systemRootVariable];
29
+ this.platform = platform;
30
+ this.architecture = architecture;
31
+ this.environment = environment;
32
+ this.userShell = userShell;
33
+ this.fileSystem = fileSystem;
34
+ this.log = log;
35
+ this.wsl = systemRoot === undefined || systemRoot.length === 0
36
+ ? null
37
+ : { file: path.win32.join(systemRoot, ...Resources.wslPath), reader: new WslDistributionReader(runner, systemRoot) };
38
+ this.visualStudioReader = new VisualStudioReader(runner, fileSystem, environment[Resources.programFilesX86Variable]);
39
+ }
40
+ static readUserShell() {
41
+ try {
42
+ const shell = userInfo().shell;
43
+ return shell === null || shell.trim().length === 0 ? null : shell;
44
+ }
45
+ catch (error) {
46
+ if (error instanceof Error && "code" in error && error.code === Resources.systemErrorCode)
47
+ return null;
48
+ throw error;
49
+ }
50
+ }
51
+ async locateAsync() {
52
+ if (this.platform !== Resources.windowsPlatform)
53
+ return this.locateOnUnixAsync();
54
+ const installed = await this.locateOnWindowsAsync();
55
+ return [...installed, ...await this.locateListedAsync(installed)];
56
+ }
57
+ async findAsync(shellId) {
58
+ const isMatch = (shell) => shellId === null ? shell.isDefault : shell.id === shellId;
59
+ if (this.platform !== Resources.windowsPlatform)
60
+ return (await this.locateOnUnixAsync()).find(isMatch);
61
+ const installed = await this.locateOnWindowsAsync();
62
+ return installed.find(isMatch) ?? (shellId === null ? undefined : (await this.locateListedAsync(installed)).find(isMatch));
63
+ }
64
+ async findKindAsync(kinds) {
65
+ const isMatch = (shell) => kinds.includes(shell.kind);
66
+ if (this.platform !== Resources.windowsPlatform)
67
+ return (await this.locateOnUnixAsync()).find(isMatch);
68
+ const installed = await this.locateOnWindowsAsync();
69
+ return installed.find(isMatch) ?? (await this.locateListedAsync(installed)).find(isMatch);
70
+ }
71
+ async locateOnWindowsAsync() {
72
+ const programFiles = this.environment[Resources.programFilesVariable];
73
+ const localAppData = this.environment[Resources.localAppDataVariable];
74
+ const systemRoot = this.environment[Resources.systemRootVariable];
75
+ const searchPath = (this.environment[Resources.pathVariable] ?? "").split(path.win32.delimiter).filter(t => path.win32.isAbsolute(t));
76
+ const gitFolders = [
77
+ ...ShellLocator.joinIfSet(programFiles, Resources.gitFolder),
78
+ ...ShellLocator.joinIfSet(this.environment[Resources.programFilesX86Variable], Resources.gitFolder),
79
+ ...ShellLocator.joinIfSet(localAppData, Resources.gitUserFolder),
80
+ ...await this.findGitOnSearchPathAsync(searchPath)
81
+ ];
82
+ const candidates = [
83
+ [Resources.pwshId, Resources.pwshName, TerminalShellKind.PowerShell, [
84
+ ...ShellLocator.joinIfSet(programFiles, [...Resources.pwshFolder, Resources.pwshFile]),
85
+ ...searchPath.map(t => path.win32.join(t, Resources.pwshFile)),
86
+ ...ShellLocator.joinIfSet(localAppData, [...Resources.appAliasFolder, Resources.pwshFile])
87
+ ], []],
88
+ [Resources.windowsPowerShellId, Resources.windowsPowerShellName, TerminalShellKind.PowerShell, ShellLocator.joinIfSet(systemRoot, Resources.windowsPowerShellPath), []],
89
+ [Resources.cmdId, Resources.cmdName, TerminalShellKind.CommandPrompt, ShellLocator.joinIfSet(systemRoot, Resources.cmdPath), []],
90
+ [Resources.gitBashId, Resources.gitBashName, TerminalShellKind.Bash, gitFolders.map(t => path.win32.join(t, ...Resources.gitBashFile)), Resources.gitBashArguments]
91
+ ];
92
+ const shells = [];
93
+ for (const [id, name, kind, files, args] of candidates) {
94
+ const file = await this.findFileAsync(files);
95
+ if (file !== null)
96
+ shells.push(new Shell(id, name, kind, file, args, shells.length === 0));
97
+ }
98
+ return shells;
99
+ }
100
+ async locateOnUnixAsync() {
101
+ const listed = (await this.fileSystem.readTextOrNullAsync(Resources.shellsFile) ?? "")
102
+ .split(Resources.lineFeed)
103
+ .map(t => t.trim())
104
+ .filter(t => t.startsWith(Resources.posixRoot) && !Resources.nonShellNames.includes(path.posix.basename(t)));
105
+ const preferred = this.userShell ?? this.environment[Resources.shellVariable];
106
+ const files = preferred === undefined ? listed : [preferred, ...listed];
107
+ const args = [Resources.loginArgument];
108
+ const shells = [];
109
+ for (const file of files) {
110
+ const id = path.posix.basename(file);
111
+ if (id.length > 0 && !shells.some(t => t.id === id) && await this.fileSystem.isFileAsync(file))
112
+ shells.push(new Shell(id, id, Resources.unixShellKinds.get(id) ?? TerminalShellKind.Other, file, args, shells.length === 0));
113
+ }
114
+ return shells;
115
+ }
116
+ async locateListedAsync(installed) {
117
+ const [wslShells, installations] = await Promise.all([this.locateWslShellsAsync(), this.readInstallationsAsync()]);
118
+ const commandPrompt = installed.find(t => t.id === Resources.cmdId);
119
+ const powerShell = installed.find(t => t.id === Resources.pwshId) ?? installed.find(t => t.id === Resources.windowsPowerShellId);
120
+ const shells = [...wslShells];
121
+ for (const installation of installations)
122
+ shells.push(...await this.locateDeveloperShellsAsync(installation, commandPrompt, powerShell));
123
+ return shells;
124
+ }
125
+ async locateDeveloperShellsAsync(installation, commandPrompt, powerShell) {
126
+ const tools = path.win32.join(installation.path, ...Resources.developerToolsPath);
127
+ const script = path.win32.join(tools, Resources.developerCommandScript);
128
+ const module = path.win32.join(tools, Resources.developerShellModule);
129
+ const architecture = Resources.developerArchitectures.get(this.architecture) ?? this.architecture;
130
+ const id = Resources.developerIdPrefix + installation.instanceId;
131
+ const shells = [];
132
+ if (commandPrompt !== undefined && await this.fileSystem.isFileAsync(script))
133
+ shells.push(new Shell(id + Resources.developerCommandSuffix, Resources.formatDeveloperCommandPromptName(installation.name), TerminalShellKind.CommandPrompt, commandPrompt.file, [Resources.keepOpenArgument, script, Resources.noStartFolderArgument, ...Resources.formatDeveloperArchitectureArguments(architecture)], false));
134
+ if (powerShell !== undefined && await this.fileSystem.isFileAsync(module))
135
+ shells.push(new Shell(id + Resources.developerPowerShellSuffix, Resources.formatDeveloperPowerShellName(installation.name), TerminalShellKind.PowerShell, powerShell.file, [], false, Resources.formatDeveloperPowerShellCommand(module, installation.path, architecture)));
136
+ return shells;
137
+ }
138
+ async locateWslShellsAsync() {
139
+ const wsl = this.wsl;
140
+ if (wsl === null)
141
+ return [];
142
+ this.distributions ??= wsl.reader.readAsync().catch((error) => {
143
+ this.distributions = null;
144
+ this.log.write(FailureText.read(error));
145
+ return [];
146
+ });
147
+ return (await this.distributions)
148
+ .filter(t => !t.toLowerCase().startsWith(Resources.wslDockerPrefix))
149
+ .map(t => new Shell(Resources.wslIdPrefix + t, t, TerminalShellKind.Wsl, wsl.file, [Resources.wslDistributionArgument, t], false));
150
+ }
151
+ readInstallationsAsync() {
152
+ this.installations ??= this.visualStudioReader.readAsync().catch((error) => {
153
+ this.installations = null;
154
+ this.log.write(FailureText.read(error));
155
+ return [];
156
+ });
157
+ return this.installations;
158
+ }
159
+ async findFileAsync(files) {
160
+ for (const file of files) {
161
+ if (await this.fileSystem.isProgramAsync(file))
162
+ return file;
163
+ }
164
+ return null;
165
+ }
166
+ async findGitOnSearchPathAsync(searchPath) {
167
+ const folders = [];
168
+ for (const folder of searchPath) {
169
+ if (path.win32.basename(folder).toLowerCase() === Resources.gitCommandFolder && await this.fileSystem.isProgramAsync(path.win32.join(folder, Resources.gitExecutableFile)))
170
+ folders.push(path.win32.dirname(folder));
171
+ }
172
+ return folders;
173
+ }
174
+ static joinIfSet(folder, names) {
175
+ return folder === undefined || folder.length === 0 ? [] : [path.win32.join(folder, ...names)];
176
+ }
177
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { ShellOptionsReply } from "../models/shell-options-reply.js";
9
+ export class ShellOptionsQueue {
10
+ waiting = [];
11
+ askAsync(milliseconds) {
12
+ return new Promise(resolve => {
13
+ const request = { settle: null };
14
+ const timer = setTimeout(() => request.settle?.(ShellOptionsReply.timedOut), milliseconds);
15
+ request.settle = t => {
16
+ clearTimeout(timer);
17
+ request.settle = null;
18
+ resolve(t);
19
+ };
20
+ this.waiting.push(request);
21
+ });
22
+ }
23
+ answer(options) {
24
+ this.waiting.shift()?.settle?.(new ShellOptionsReply(options, false));
25
+ }
26
+ cancel() {
27
+ for (const request of this.waiting)
28
+ request.settle?.(ShellOptionsReply.none);
29
+ }
30
+ reset() {
31
+ this.cancel();
32
+ this.waiting.length = 0;
33
+ }
34
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { ShellLine } from "../models/shell-line.js";
9
+ import { Resources } from "../resources.js";
10
+ export class ShellWords {
11
+ static read(text, isPowerShell) {
12
+ const escape = isPowerShell ? Resources.powerShellEscape : Resources.posixEscape;
13
+ let words = [];
14
+ let value = "";
15
+ let start = text.length;
16
+ let isInWord = false;
17
+ let quote = null;
18
+ let startsQuoted = false;
19
+ for (let index = 0; index < text.length; index++) {
20
+ const character = text.charAt(index);
21
+ if (quote === Resources.singleQuote) {
22
+ if (character !== Resources.singleQuote)
23
+ value += character;
24
+ else if (isPowerShell && text.charAt(index + 1) === Resources.singleQuote) {
25
+ value += character;
26
+ index++;
27
+ }
28
+ else
29
+ quote = null;
30
+ continue;
31
+ }
32
+ if (!isInWord && !Resources.wordBreaks.includes(character) && !Resources.commandBreaks.includes(character)) {
33
+ isInWord = true;
34
+ start = index;
35
+ startsQuoted = character === escape || character === Resources.singleQuote || character === Resources.doubleQuote;
36
+ }
37
+ if (character === escape && index + 1 < text.length) {
38
+ const next = text.charAt(index + 1);
39
+ if (quote === null || isPowerShell || Resources.posixQuotedEscapes.includes(next)) {
40
+ value += next;
41
+ index++;
42
+ }
43
+ else
44
+ value += character;
45
+ }
46
+ else if (quote === Resources.doubleQuote) {
47
+ if (character === Resources.doubleQuote)
48
+ quote = null;
49
+ else
50
+ value += character;
51
+ }
52
+ else if (character === Resources.singleQuote || character === Resources.doubleQuote)
53
+ quote = character;
54
+ else if (Resources.wordBreaks.includes(character)) {
55
+ if (isInWord)
56
+ words.push(value);
57
+ value = "";
58
+ isInWord = false;
59
+ }
60
+ else if (Resources.commandBreaks.includes(character)) {
61
+ words = [];
62
+ value = "";
63
+ isInWord = false;
64
+ }
65
+ else
66
+ value += character;
67
+ }
68
+ return new ShellLine(words, isInWord ? start : text.length, value, quote, isInWord && startsQuoted);
69
+ }
70
+ static write(value, quote, isPowerShell, closesQuote, escapesWildcards, keepsHome) {
71
+ const literal = isPowerShell && escapesWildcards ? value.replace(Resources.powerShellWildcards, Resources.shellWordsPowerShellEscapeReplacement) : value;
72
+ const quoted = quote ?? (isPowerShell && (literal !== value || Resources.powerShellSpecial.test(value)) ? Resources.singleQuote : null);
73
+ if (quoted === null)
74
+ return isPowerShell ? literal : `${!keepsHome && value.startsWith(Resources.homeWord) ? Resources.posixEscape : ""}${value.replace(Resources.posixSpecial, Resources.shellWordsPosixEscapeReplacement)}`;
75
+ const body = quoted === Resources.singleQuote
76
+ ? literal.replaceAll(Resources.singleQuote, isPowerShell ? Resources.shellWordsPowerShellQuotedSingleQuote : Resources.shellWordsPosixQuotedSingleQuote)
77
+ : literal.replace(isPowerShell ? Resources.powerShellQuotedSpecial : Resources.posixQuotedSpecial, isPowerShell ? Resources.shellWordsPowerShellEscapeReplacement : Resources.shellWordsPosixEscapeReplacement);
78
+ return `${quoted}${body}${closesQuote ? quoted : ""}`;
79
+ }
80
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { SystemRequirement } from "../enums/system-requirement.js";
9
+ import { SystemShortfall } from "../models/system-shortfall.js";
10
+ import { Resources } from "../resources.js";
11
+ export class SystemRequirements {
12
+ static findShortfall(platform, osRelease, report) {
13
+ if (platform === Resources.windowsPlatform) {
14
+ const build = SystemRequirements.readWindowsBuild(osRelease);
15
+ if (build === null)
16
+ return new SystemShortfall(SystemRequirement.WindowsBuild, osRelease);
17
+ return build < Resources.minimumWindowsBuild ? new SystemShortfall(SystemRequirement.WindowsBuild, String(build)) : null;
18
+ }
19
+ if (platform === Resources.linuxPlatform) {
20
+ const version = SystemRequirements.readGlibcVersion(report);
21
+ return version !== null && SystemRequirements.isBelowGlibcMinimum(version) ? new SystemShortfall(SystemRequirement.Glibc, version) : null;
22
+ }
23
+ return null;
24
+ }
25
+ static readWindowsBuild(osRelease) {
26
+ const match = Resources.systemRequirementsWindowsBuild.exec(osRelease);
27
+ return match === null ? null : Number(match[1]);
28
+ }
29
+ static readGlibcVersion(report) {
30
+ if (typeof report !== "object" || report === null || !(Resources.reportHeaderField in report))
31
+ return null;
32
+ const header = report[Resources.reportHeaderField];
33
+ if (typeof header !== "object" || header === null || !(Resources.reportGlibcVersionField in header))
34
+ return null;
35
+ const version = header[Resources.reportGlibcVersionField];
36
+ return typeof version === "string" ? version : null;
37
+ }
38
+ static isBelowGlibcMinimum(version) {
39
+ const match = Resources.systemRequirementsGlibcVersion.exec(version);
40
+ if (match === null)
41
+ return false;
42
+ const [minimumMajor, minimumMinor] = Resources.minimumGlibcVersion;
43
+ const major = Number(match[1]);
44
+ return major < minimumMajor || (major === minimumMajor && Number(match[2]) < minimumMinor);
45
+ }
46
+ }