diff --git a/lib/services/bundler/bundler-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts index 96847f3c25..5d3d071ecc 100644 --- a/lib/services/bundler/bundler-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -39,6 +39,7 @@ import { resolvePackagePath, resolvePackageJSONPath, } from "../../helpers/package-path-helper"; +import { commandShortcutsOwnTerminal } from "../key-shortcuts"; // todo: move out of here interface IBundlerMessage { @@ -736,10 +737,17 @@ export class BundlerCompilerService const options: { [key: string]: any } = { cwd: projectData.projectDir, - // Inherit so the dev server's URLs/logs stream to the user as - // before. No IPC needed here — the build watcher provides the + // Output is inherited so the dev server's URLs/logs stream to the + // user. No IPC needed here — the build watcher provides the // bundle-complete IPC; the dev server is fetched over HTTP/ws. - stdio: "inherit", + // Vite reads a terminal stdin for shortcuts of its own, which would + // take the keys meant for the CLI's; otherwise its shortcuts are the + // only ones the terminal has. + stdio: [ + commandShortcutsOwnTerminal() ? "ignore" : "inherit", + "inherit", + "inherit", + ], env: { ...process.env, NATIVESCRIPT_BUNDLER_ENV: JSON.stringify(envData), diff --git a/lib/services/key-shortcuts.ts b/lib/services/key-shortcuts.ts index fb756331e6..b826a2e2ed 100644 --- a/lib/services/key-shortcuts.ts +++ b/lib/services/key-shortcuts.ts @@ -5,6 +5,7 @@ import { RunOnDeviceEvents } from "../constants"; import { IChildProcess } from "../common/declarations"; import { Injector } from "../common/di/injector"; import { + commandShortcutsEnabled, envSwitchIsOn, IKeyShortcutService, KeyContextBase, @@ -98,6 +99,16 @@ export function findShortcut( return shortcut; } +/** + * Node skips `setRawMode(true)` while it believes the terminal is already + * raw, so the mode is cleared first to make the call reach the terminal even + * when something else has changed it since. + */ +function enterRawMode(stdin: NodeJS.ReadStream): void { + stdin.setRawMode(false); + stdin.setRawMode(true); +} + /** * Raw mode outlives the process that set it, so a CI runner or a redirected * stdin must never get it; `NS_KEY_SHORTCUTS=false` is the manual opt-out. @@ -115,6 +126,23 @@ export function keyShortcutsEnabled(): boolean { return !!process.stdin.isTTY; } +function isRawModeTerminal(stdin: NodeJS.ReadStream): boolean { + return !!stdin.isTTY && typeof stdin.setRawMode === "function"; +} + +/** + * Whether a command's shortcuts, once attached, read the keys straight off + * the terminal. Answerable before the attach, so a child spawned earlier can + * be kept off a terminal the CLI is about to read. + */ +export function commandShortcutsOwnTerminal(): boolean { + return ( + commandShortcutsEnabled() && + isRawModeTerminal(process.stdin) && + keyShortcutsEnabled() + ); +} + /** * The names `devicePlatformsConstants` hands out, read off the constants * rather than spelled again here. @@ -410,7 +438,7 @@ export class KeyShortcutService implements IKeyShortcutService { ); const stdin = process.stdin; - if (!stdin.isTTY || typeof stdin.setRawMode !== "function") { + if (!isRawModeTerminal(stdin)) { if (typeof process.send !== "function") { this.releaseShortcuts(); return false; @@ -428,8 +456,7 @@ export class KeyShortcutService implements IKeyShortcutService { return false; } - stdin.setRawMode(false); - stdin.setRawMode(true); + enterRawMode(stdin); stdin.resume(); stdin.on("data", this.onData); process.once("exit", this.onExit); @@ -592,6 +619,12 @@ export class KeyShortcutService implements IKeyShortcutService { } finally { this.running = false; if (process.stdin.setRawMode) { + // A Node child writing to the terminal, such as the Vite dev server + // an action stops, restores the terminal mode it started with when + // it exits; that can be cooked mode, where keys wait for Enter. + if (this.attached && process.stdin.isTTY) { + enterRawMode(process.stdin); + } process.stdin.resume(); } } diff --git a/test/services/bundler/bundler-compiler-service.ts b/test/services/bundler/bundler-compiler-service.ts index 0e3b1dfce9..ba885a6ae0 100644 --- a/test/services/bundler/bundler-compiler-service.ts +++ b/test/services/bundler/bundler-compiler-service.ts @@ -373,6 +373,92 @@ describe("BundlerCompilerService", () => { }); }); + describe("startViteDevServer", () => { + const env = ["NS_COMMAND_SHORTCUTS", "NS_KEY_SHORTCUTS"]; + let savedEnv: { [key: string]: string }; + let originalStdin: PropertyDescriptor; + let spawned: { [key: string]: any }[]; + + const useStdin = (isTTY: boolean): void => { + Object.defineProperty(process, "stdin", { + value: { isTTY, setRawMode: (): void => undefined }, + configurable: true, + }); + }; + + const devServerStdin = async (): Promise => { + await (bundlerCompilerService).startViteDevServer( + { platformNameLowerCase: "ios" }, + { + projectDir: "/project", + bundlerConfigPath: "/project/vite.config.ts", + }, + { watch: true, hmr: true }, + ); + assert.lengthOf(spawned, 1); + + return spawned[0].stdio[0]; + }; + + beforeEach(() => { + savedEnv = {}; + for (const name of env) { + savedEnv[name] = process.env[name]; + delete process.env[name]; + } + originalStdin = Object.getOwnPropertyDescriptor(process, "stdin"); + + spawned = []; + testInjector.resolve("childProcess").spawn = ( + _command: string, + _args: string[], + options: { [key: string]: any }, + ) => { + spawned.push(options); + return fakeChildProcess(321); + }; + const service = bundlerCompilerService; + service.getBundler = () => "vite"; + service.buildEnvData = () => ({}); + service.buildEnvCommandLineParams = async (): Promise => []; + service.getBundlerExecutablePath = () => "/project/vite.js"; + service.waitForPort = async () => true; + }); + + afterEach(() => { + Object.defineProperty(process, "stdin", originalStdin); + for (const name of env) { + if (savedEnv[name] === undefined) { + delete process.env[name]; + } else { + process.env[name] = savedEnv[name]; + } + } + }); + + it("keeps the dev server off the terminal the CLI's shortcuts read", async () => { + process.env.NS_COMMAND_SHORTCUTS = "1"; + process.env.NS_KEY_SHORTCUTS = "true"; + useStdin(true); + + assert.equal(await devServerStdin(), "ignore"); + }); + + it("hands the dev server the terminal while the CLI's shortcuts are off", async () => { + useStdin(true); + + assert.equal(await devServerStdin(), "inherit"); + }); + + it("hands the dev server its stdin when the CLI has no terminal to read", async () => { + process.env.NS_COMMAND_SHORTCUTS = "1"; + process.env.NS_KEY_SHORTCUTS = "true"; + useStdin(false); + + assert.equal(await devServerStdin(), "inherit"); + }); + }); + describe("compileWithWatch", () => { it("fails when the value set for bundlerConfigPath is not existant file", async () => { const bundlerConfigPath = "some path.js"; diff --git a/test/services/key-shortcuts.ts b/test/services/key-shortcuts.ts index a87a462dff..decfe5667c 100644 --- a/test/services/key-shortcuts.ts +++ b/test/services/key-shortcuts.ts @@ -5,6 +5,7 @@ import { getContractName } from "../../lib/common/di/contract"; import { Injector } from "../../lib/common/di/injector"; import { KeyShortcutRegistryService } from "../../lib/services/key-shortcut-registry"; import { + commandShortcutsOwnTerminal, findShortcut, KeyContextBase, KeyShortcut, @@ -19,10 +20,16 @@ import { class FakeStdin extends EventEmitter { public isTTY: boolean = true; public rawMode: boolean = null; + /** The mode the terminal is really in, which another process can change. */ + public terminalRaw: boolean = false; public resumeCount: number = 0; public pauseCount: number = 0; public setRawMode(value: boolean): any { + // Like Node, only a change from the mode it last set reaches the terminal. + if (value !== this.rawMode) { + this.terminalRaw = value; + } this.rawMode = value; return this; } @@ -467,6 +474,61 @@ describe("key shortcuts", () => { }); }); + describe("commandShortcutsOwnTerminal", () => { + const env = [ + "NS_COMMAND_SHORTCUTS", + "NS_KEY_SHORTCUTS", + "CI", + "JENKINS_HOME", + ]; + let saved: { [key: string]: string }; + let stdin: FakeStdin; + let restoreStdin: () => void; + + beforeEach(() => { + saved = {}; + for (const name of env) { + saved[name] = process.env[name]; + delete process.env[name]; + } + process.env.NS_COMMAND_SHORTCUTS = "1"; + stdin = new FakeStdin(); + restoreStdin = swapStdin(stdin); + }); + + afterEach(() => { + restoreStdin(); + for (const name of env) { + if (saved[name] === undefined) { + delete process.env[name]; + } else { + process.env[name] = saved[name]; + } + } + }); + + it("holds for a command's shortcuts on a terminal", () => { + assert.isTrue(commandShortcutsOwnTerminal()); + }); + + it("does not hold while command shortcuts are off", () => { + delete process.env.NS_COMMAND_SHORTCUTS; + assert.isFalse(commandShortcutsOwnTerminal()); + }); + + it("does not hold when key shortcuts are switched off", () => { + process.env.NS_KEY_SHORTCUTS = "false"; + assert.isFalse(commandShortcutsOwnTerminal()); + }); + + it("does not hold for a stdin that is not a terminal, even when forced on", () => { + // A `ns run` spawned by `ns start`: its keys come over IPC. + process.env.NS_KEY_SHORTCUTS = "true"; + stdin.isTTY = false; + assert.isFalse(commandShortcutsOwnTerminal()); + }); + }); + describe("KeyShortcutService", () => { let stdin: FakeStdin; let restoreStdin: () => void; @@ -697,6 +759,43 @@ describe("key shortcuts", () => { assert.equal(stdin.pauseCount, 1); }); + it("takes the terminal back into raw mode after an action", async () => { + service.attach({ + shortcuts: [ + { + key: "R", + description: "Restart", + action: () => { + // A child that shared the terminal exits and restores the + // cooked mode it started with. + stdin.terminalRaw = false; + }, + }, + ], + }); + assert.isTrue(stdin.terminalRaw); + + await press("R"); + + assert.isTrue(stdin.terminalRaw); + }); + + it("leaves the terminal alone after an action that detached", async () => { + service.attach({ + shortcuts: [ + { + key: "x", + description: "Detach", + action: () => service.detach(), + }, + ], + }); + + await press("x"); + + assert.isFalse(stdin.terminalRaw); + }); + it("tears down when the process exits", () => { const before = new Set(process.listeners("exit")); service.attach({ shortcuts: [] });