Open History to see the last commit
1// @effect-diagnostics preferSchemaOverJson:off - JSON string literals embed paths safely into generated JavaScript.
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import { resolveNodeExecutable } from "@t3tools/shared/nodeRuntime";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7
8const SHIM_DIR = "device/bin";
9
10export const ensureAgentDeviceShim = Effect.fn("AgentDeviceShim.ensure")(function* (input: {
11 readonly entryPath: string;
12 readonly stateDir: string;
13}) {
14 const { entryPath } = input;
15 const fs = yield* FileSystem.FileSystem;
16 const path = yield* Path.Path;
17 const platform = yield* HostProcess.Platform;
18 const node = yield* resolveNodeExecutable("Device automation");
19 const shimDir = path.join(input.stateDir, SHIM_DIR);
20 yield* fs.makeDirectory(shimDir, { recursive: true });
21 const launcherPath = path.join(shimDir, "agent-device-launcher.mjs");
22 yield* fs.writeFileString(
23 launcherPath,
24 `import { spawn } from "node:child_process";
25const args = process.argv.slice(2);
26const informational = args.length === 1 && ["help", "--help", "-h", "--version", "version"].includes(args[0]);
27const hasValue = flag => { const index = args.indexOf(flag); return index >= 0 && !!args[index + 1] && !args[index + 1].startsWith("--"); };
28if (!informational && !(hasValue("--config") && hasValue("--session"))) {
29 console.error("Call device_open first and include its --config and --session flags.");
30 process.exit(1);
31}
32const env = { ...process.env, ELECTRON_RUN_AS_NODE: "1" };
33delete env.AGENT_DEVICE_DAEMON_BASE_URL;
34delete env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
35delete env.AGENT_DEVICE_CONFIG;
36const child = spawn(${JSON.stringify(node)}, [${JSON.stringify(entryPath)}, ...args], { stdio: "inherit", env });
37child.on("error", error => { console.error(error.message); process.exitCode = 1; });
38child.on("exit", code => { process.exitCode = code ?? 1; });
39`,
40 );
41 if (platform === "win32") {
42 const script = `@echo off\r\nsetlocal EnableExtensions DisableDelayedExpansion\r\nset "ELECTRON_RUN_AS_NODE=1"\r\n"${node}" "${launcherPath}" %*\r\n`;
43 yield* fs.writeFileString(path.join(shimDir, "agent-device.cmd"), script);
44 } else {
45 const command = [node, launcherPath]
46 .map((value) => "'" + value.replaceAll("'", "'\"'\"'") + "'")
47 .join(" ");
48 const script = `#!/bin/sh\nexport ELECTRON_RUN_AS_NODE=1\nexec ${command} "$@"\n`;
49 const shimPath = path.join(shimDir, "agent-device");
50 yield* fs.writeFileString(shimPath, script);
51 yield* fs.chmod(shimPath, 0o755);
52 }
53 return shimDir;
54});