@narumitw/pi-starship 0.24.0 → 0.29.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.
Files changed (39) hide show
  1. package/NOTICES.md +18 -1
  2. package/README.md +202 -16
  3. package/package.json +4 -3
  4. package/src/commands.ts +405 -22
  5. package/src/config.ts +113 -11
  6. package/src/format/formatter.ts +26 -11
  7. package/src/format/style.ts +13 -1
  8. package/src/index.ts +1 -0
  9. package/src/modules/catalog.ts +20 -0
  10. package/src/modules/cloud.ts +74 -0
  11. package/src/modules/deployment.ts +61 -0
  12. package/src/modules/development.ts +95 -0
  13. package/src/modules/execution.ts +73 -0
  14. package/src/modules/extension-status.ts +33 -1
  15. package/src/modules/fill.ts +14 -0
  16. package/src/modules/git/branch.ts +7 -3
  17. package/src/modules/git/commit.ts +22 -0
  18. package/src/modules/git/metrics.ts +20 -0
  19. package/src/modules/git/runtime.ts +320 -41
  20. package/src/modules/git/state.ts +21 -0
  21. package/src/modules/git/status.ts +62 -11
  22. package/src/modules/index.ts +7 -1
  23. package/src/modules/languages.ts +87 -0
  24. package/src/modules/package.ts +17 -0
  25. package/src/modules/render.ts +97 -9
  26. package/src/modules/types.ts +65 -2
  27. package/src/modules/workspace-helpers.ts +10 -0
  28. package/src/pi-starship.ts +230 -104
  29. package/src/runtime/cloud.ts +166 -0
  30. package/src/runtime/command.ts +85 -0
  31. package/src/runtime/deployment.ts +201 -0
  32. package/src/runtime/development.ts +154 -0
  33. package/src/runtime/execution.ts +141 -0
  34. package/src/runtime/helpers.ts +273 -0
  35. package/src/runtime/languages.ts +205 -0
  36. package/src/runtime/package.ts +112 -0
  37. package/src/runtime/refresh-controller.ts +85 -0
  38. package/src/runtime/types.ts +59 -0
  39. package/src/runtime/workspace.ts +110 -0
@@ -0,0 +1,85 @@
1
+ import { spawn } from "node:child_process";
2
+ import type { WorkspaceExec } from "./types.js";
3
+
4
+ const FORCE_KILL_DELAY_MS = 250;
5
+
6
+ export const execWorkspaceCommand: WorkspaceExec = async (command, args, options) =>
7
+ new Promise((resolve) => {
8
+ let child: ReturnType<typeof spawn>;
9
+ try {
10
+ child = spawn(command, args, {
11
+ cwd: options.cwd,
12
+ env: explicitEnvironment(options.environment),
13
+ shell: false,
14
+ stdio: ["ignore", "pipe", "pipe"],
15
+ windowsHide: true,
16
+ });
17
+ } catch {
18
+ resolve({ stdout: "", stderr: "", code: 1, killed: false });
19
+ return;
20
+ }
21
+
22
+ const stdout: Buffer[] = [];
23
+ const stderr: Buffer[] = [];
24
+ let outputBytes = 0;
25
+ let killed = false;
26
+ let settled = false;
27
+ let forceKillTimer: NodeJS.Timeout | undefined;
28
+
29
+ const finish = (code: number) => {
30
+ if (settled) return;
31
+ settled = true;
32
+ clearTimeout(timeoutTimer);
33
+ if (forceKillTimer) clearTimeout(forceKillTimer);
34
+ resolve({
35
+ stdout: Buffer.concat(stdout).toString("utf8"),
36
+ stderr: Buffer.concat(stderr).toString("utf8"),
37
+ code,
38
+ killed,
39
+ });
40
+ };
41
+
42
+ const terminate = () => {
43
+ if (killed || settled) return;
44
+ killed = true;
45
+ child.kill("SIGTERM");
46
+ forceKillTimer = setTimeout(() => {
47
+ child.kill("SIGKILL");
48
+ child.stdout?.destroy();
49
+ child.stderr?.destroy();
50
+ finish(1);
51
+ }, FORCE_KILL_DELAY_MS);
52
+ };
53
+
54
+ const collect = (target: Buffer[]) => (data: Buffer | string) => {
55
+ const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);
56
+ const remaining = Math.max(0, options.maxOutputBytes - outputBytes);
57
+ if (remaining > 0) target.push(chunk.subarray(0, remaining));
58
+ outputBytes += chunk.byteLength;
59
+ if (outputBytes > options.maxOutputBytes) terminate();
60
+ };
61
+
62
+ child.stdout?.on("data", collect(stdout));
63
+ child.stderr?.on("data", collect(stderr));
64
+ child.once("error", () => finish(1));
65
+ child.once("close", (code) => finish(code ?? 1));
66
+ const timeoutTimer = setTimeout(terminate, options.timeout);
67
+ });
68
+
69
+ function explicitEnvironment(
70
+ source: Readonly<Record<string, string | undefined>>,
71
+ ): NodeJS.ProcessEnv {
72
+ const result: NodeJS.ProcessEnv = Object.create(null);
73
+ for (const [name, value] of Object.entries(source)) {
74
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || value === undefined || value.includes("\0")) {
75
+ continue;
76
+ }
77
+ Object.defineProperty(result, name, {
78
+ value,
79
+ writable: true,
80
+ enumerable: true,
81
+ configurable: true,
82
+ });
83
+ }
84
+ return result;
85
+ }
@@ -0,0 +1,201 @@
1
+ import { extname, isAbsolute, join, resolve } from "node:path";
2
+ import { parse as parseYaml } from "yaml";
3
+ import {
4
+ directMatch,
5
+ exactAlias,
6
+ formatVersion,
7
+ isRecord,
8
+ joinHome,
9
+ MAX_METADATA_FILE_BYTES,
10
+ optionBoolean,
11
+ optionMap,
12
+ optionNumber,
13
+ optionString,
14
+ optionStrings,
15
+ runBounded,
16
+ safeMetadata,
17
+ } from "./helpers.js";
18
+ import type { CollectorContext, MutableModuleSnapshot } from "./types.js";
19
+
20
+ export async function collectDeployment(context: CollectorContext): Promise<MutableModuleSnapshot> {
21
+ const result: MutableModuleSnapshot = {};
22
+ if (context.needs("docker_context")) {
23
+ const docker = await collectDocker(context);
24
+ if (docker) result.docker_context = docker;
25
+ }
26
+ if (context.needs("kubernetes")) {
27
+ const kubernetes = await collectKubernetes(context);
28
+ if (kubernetes) result.kubernetes = kubernetes;
29
+ }
30
+ if (context.needs("terraform")) {
31
+ const terraform = await collectTerraform(context);
32
+ if (terraform) result.terraform = terraform;
33
+ }
34
+ return result;
35
+ }
36
+
37
+ async function collectDocker(
38
+ context: CollectorContext,
39
+ ): Promise<Record<string, string> | undefined> {
40
+ const entries = await context.entries();
41
+ if (optionBoolean(context, "docker_context", "only_with_files")) {
42
+ const configuredFiles = optionStrings(context, "docker_context", "detect_files");
43
+ if (
44
+ !directMatch(
45
+ entries,
46
+ configuredFiles.length > 0
47
+ ? configuredFiles
48
+ : [
49
+ "Dockerfile",
50
+ "docker-compose.yml",
51
+ "docker-compose.yaml",
52
+ "compose.yml",
53
+ "compose.yaml",
54
+ ],
55
+ optionStrings(context, "docker_context", "detect_extensions"),
56
+ optionStrings(context, "docker_context", "detect_folders"),
57
+ )
58
+ ) {
59
+ return undefined;
60
+ }
61
+ }
62
+ let active = safeMetadata(context.input.environment.DOCKER_CONTEXT);
63
+ if (!active) {
64
+ const configDirectory =
65
+ safeMetadata(context.input.environment.DOCKER_CONFIG, 1_024) ??
66
+ joinHome(context.input, ".docker");
67
+ const source = await context.fs.readFile(
68
+ join(configDirectory, "config.json"),
69
+ MAX_METADATA_FILE_BYTES,
70
+ );
71
+ if (source) {
72
+ try {
73
+ const document = JSON.parse(source) as unknown;
74
+ active = isRecord(document) ? safeMetadata(document.currentContext) : undefined;
75
+ } catch {
76
+ // Malformed metadata degrades to an empty module.
77
+ }
78
+ }
79
+ }
80
+ return active && active !== "default" ? { context: active } : undefined;
81
+ }
82
+
83
+ async function collectKubernetes(
84
+ context: CollectorContext,
85
+ ): Promise<Record<string, string> | undefined> {
86
+ const selected = safeMetadata(context.input.environment.KUBECONFIG, 4_096);
87
+ const candidates = selected
88
+ ? selected.split(context.input.platform === "win32" ? ";" : ":").filter(Boolean)
89
+ : [joinHome(context.input, ".kube", "config")];
90
+ const limit = optionNumber(context, "kubernetes", "max_config_files") ?? 8;
91
+ const contexts = new Map<string, Record<string, unknown>>();
92
+ const clusters = new Set<string>();
93
+ const users = new Set<string>();
94
+ let currentContext: string | undefined;
95
+ for (const path of candidates.slice(0, limit)) {
96
+ const source = await context.fs.readFile(path, MAX_METADATA_FILE_BYTES);
97
+ if (!source) continue;
98
+ try {
99
+ const document = parseYaml(source) as unknown;
100
+ if (!isRecord(document)) continue;
101
+ currentContext ??= safeMetadata(document["current-context"]);
102
+ for (const item of arrayRecords(document.contexts)) {
103
+ const name = safeMetadata(item.name);
104
+ if (name && !contexts.has(name) && isRecord(item.context)) contexts.set(name, item.context);
105
+ }
106
+ for (const item of arrayRecords(document.clusters)) {
107
+ const name = safeMetadata(item.name);
108
+ if (name) clusters.add(name);
109
+ }
110
+ for (const item of arrayRecords(document.users)) {
111
+ const name = safeMetadata(item.name);
112
+ if (name) users.add(name);
113
+ }
114
+ } catch {
115
+ // Ignore malformed files independently.
116
+ }
117
+ }
118
+ if (!currentContext) return undefined;
119
+ const selectedContext = contexts.get(currentContext);
120
+ const cluster = safeMetadata(selectedContext?.cluster);
121
+ const user = safeMetadata(selectedContext?.user);
122
+ const namespace = safeMetadata(selectedContext?.namespace) ?? "default";
123
+ const values: Record<string, string> = {
124
+ context:
125
+ exactAlias(currentContext, optionMap(context, "kubernetes", "context_aliases")) ??
126
+ currentContext,
127
+ namespace:
128
+ exactAlias(namespace, optionMap(context, "kubernetes", "namespace_aliases")) ?? namespace,
129
+ };
130
+ if (cluster && clusters.has(cluster)) {
131
+ values.cluster =
132
+ exactAlias(cluster, optionMap(context, "kubernetes", "cluster_aliases")) ?? cluster;
133
+ }
134
+ if (user && users.has(user)) {
135
+ values.user = exactAlias(user, optionMap(context, "kubernetes", "user_aliases")) ?? user;
136
+ }
137
+ return values;
138
+ }
139
+
140
+ async function collectTerraform(
141
+ context: CollectorContext,
142
+ ): Promise<Record<string, string> | undefined> {
143
+ const entries = await context.entries();
144
+ const configuredFiles = optionStrings(context, "terraform", "detect_files");
145
+ const configuredExtensions = optionStrings(context, "terraform", "detect_extensions");
146
+ const configuredFolders = optionStrings(context, "terraform", "detect_folders");
147
+ const detected =
148
+ configuredFiles.length + configuredExtensions.length + configuredFolders.length > 0
149
+ ? directMatch(entries, configuredFiles, configuredExtensions, configuredFolders)
150
+ : entries.some(
151
+ (entry) =>
152
+ (entry.isFile && [".tf", ".tfplan", ".tfstate"].includes(extname(entry.name))) ||
153
+ (entry.isDirectory && entry.name === ".terraform"),
154
+ );
155
+ if (!detected) return undefined;
156
+ const values: Record<string, string> = {};
157
+ const workspace = await terraformWorkspace(context);
158
+ if (workspace) values.workspace = workspace;
159
+ if (context.needs("terraform", "version")) {
160
+ for (const command of ["terraform", "tofu"]) {
161
+ const output = await runBounded(context, command, ["version"]);
162
+ const parsed = output ? parseTerraformVersion(output, command) : undefined;
163
+ if (parsed) {
164
+ values.version = formatVersion(
165
+ parsed,
166
+ optionString(context, "terraform", "version_format"),
167
+ );
168
+ break;
169
+ }
170
+ }
171
+ }
172
+ return values;
173
+ }
174
+
175
+ async function terraformWorkspace(context: CollectorContext): Promise<string | undefined> {
176
+ const direct = safeMetadata(context.input.environment.TF_WORKSPACE);
177
+ if (direct) return direct;
178
+ const dataDirectory = safeMetadata(context.input.environment.TF_DATA_DIR, 1_024);
179
+ const candidate = dataDirectory
180
+ ? join(
181
+ isAbsolute(dataDirectory) ? dataDirectory : resolve(context.input.cwd, dataDirectory),
182
+ "environment",
183
+ )
184
+ : join(context.input.cwd, ".terraform", "environment");
185
+ return safeMetadata(await context.fs.readFile(candidate, 1_024));
186
+ }
187
+
188
+ export function parseTerraformVersion(
189
+ output: string,
190
+ command: "terraform" | "tofu" | string,
191
+ ): string | undefined {
192
+ const escaped = command === "tofu" ? "OpenTofu" : "Terraform";
193
+ const match = new RegExp(`^${escaped} v?(\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.-]+)?)$`, "u").exec(
194
+ output.trim().split(/\r?\n/u)[0] ?? "",
195
+ );
196
+ return match?.[1] ? `v${match[1]}` : undefined;
197
+ }
198
+
199
+ function arrayRecords(value: unknown): Record<string, unknown>[] {
200
+ return Array.isArray(value) ? value.filter(isRecord) : [];
201
+ }
@@ -0,0 +1,154 @@
1
+ import { join } from "node:path";
2
+ import { parse } from "smol-toml";
3
+ import {
4
+ directMatch,
5
+ formatVersion,
6
+ isRecord,
7
+ MAX_METADATA_FILE_BYTES,
8
+ optionBoolean,
9
+ optionString,
10
+ optionStrings,
11
+ pathName,
12
+ runBounded,
13
+ safeMetadata,
14
+ setString,
15
+ } from "./helpers.js";
16
+ import type { CollectorContext, MutableModuleSnapshot } from "./types.js";
17
+
18
+ export async function collectDevelopment(
19
+ context: CollectorContext,
20
+ ): Promise<MutableModuleSnapshot> {
21
+ const result: MutableModuleSnapshot = {};
22
+ const directNames = ["mise", "direnv", "pixi"] as const;
23
+ const needsListing = directNames.some((name) => context.needs(name));
24
+ const entries = needsListing ? await context.entries() : [];
25
+
26
+ if (
27
+ context.needs("mise") &&
28
+ detected(context, entries, "mise", ["mise.toml", ".mise.toml", ".tool-versions"])
29
+ ) {
30
+ const values: Record<string, string> = {};
31
+ if (context.needs("mise", "health")) {
32
+ const output = await runBounded(context, "mise", ["doctor"]);
33
+ const health = output ? parseMiseHealth(output) : undefined;
34
+ if (health) values.health = health;
35
+ }
36
+ result.mise = values;
37
+ }
38
+
39
+ if (context.needs("direnv") && detected(context, entries, "direnv", [".envrc"])) {
40
+ const values: Record<string, string> = {};
41
+ if (["rc_path", "allowed", "loaded"].some((variable) => context.needs("direnv", variable))) {
42
+ const output = await runBounded(context, "direnv", ["status", "--json"]);
43
+ if (output) Object.assign(values, parseDirenvStatus(output));
44
+ }
45
+ result.direnv = values;
46
+ }
47
+
48
+ const conda = safeMetadata(context.input.environment.CONDA_DEFAULT_ENV);
49
+ if (
50
+ context.needs("conda") &&
51
+ conda &&
52
+ !(optionBoolean(context, "conda", "ignore_base") && conda === "base")
53
+ ) {
54
+ result.conda = { environment: pathName(conda) };
55
+ }
56
+
57
+ if (context.needs("pixi") && detected(context, entries, "pixi", ["pixi.toml", "pixi.lock"])) {
58
+ const values: Record<string, string> = {};
59
+ const environment = safeMetadata(context.input.environment.PIXI_ENVIRONMENT_NAME);
60
+ if (
61
+ environment &&
62
+ (environment !== "default" || optionBoolean(context, "pixi", "show_default_environment"))
63
+ ) {
64
+ values.environment = environment;
65
+ }
66
+ const project =
67
+ safeMetadata(context.input.environment.PIXI_PROJECT_NAME) ?? (await readPixiProject(context));
68
+ if (project) values.project_name = project;
69
+ if (context.needs("pixi", "version")) {
70
+ const output = await runBounded(context, "pixi", ["--version"]);
71
+ const version = output ? parsePixiVersion(output) : undefined;
72
+ if (version)
73
+ values.version = formatVersion(version, optionString(context, "pixi", "version_format"));
74
+ }
75
+ result.pixi = values;
76
+ }
77
+
78
+ const nixState = safeMetadata(context.input.environment.IN_NIX_SHELL);
79
+ if (context.needs("nix_shell") && (nixState === "pure" || nixState === "impure")) {
80
+ const values: Record<string, string> = { state: nixState };
81
+ setString(values, "name", context.input.environment.NIX_SHELL_NAME);
82
+ setString(values, "level", context.input.environment.NIX_SHELL_LEVEL);
83
+ result.nix_shell = values;
84
+ }
85
+
86
+ if (context.needs("guix_shell") && safeMetadata(context.input.environment.GUIX_ENVIRONMENT)) {
87
+ result.guix_shell = { state: "active" };
88
+ }
89
+ return result;
90
+ }
91
+
92
+ function detected(
93
+ context: CollectorContext,
94
+ entries: Awaited<ReturnType<CollectorContext["entries"]>>,
95
+ name: "mise" | "direnv" | "pixi",
96
+ defaultFiles: string[],
97
+ ): boolean {
98
+ const files = optionStrings(context, name, "detect_files");
99
+ return directMatch(
100
+ entries,
101
+ files.length > 0 ? files : defaultFiles,
102
+ optionStrings(context, name, "detect_extensions"),
103
+ optionStrings(context, name, "detect_folders"),
104
+ );
105
+ }
106
+
107
+ export function parseMiseHealth(output: string): string | undefined {
108
+ const text = safeMetadata(output, 8_192)?.toLowerCase();
109
+ if (!text) return undefined;
110
+ if (/\b(?:healthy|no problems found|all checks passed)\b/u.test(text)) return "healthy";
111
+ if (/\b(?:error|unhealthy|problem|warning)\b/u.test(text)) return "issues";
112
+ return undefined;
113
+ }
114
+
115
+ export function parseDirenvStatus(output: string): Record<string, string> {
116
+ try {
117
+ const document = JSON.parse(output) as unknown;
118
+ if (!isRecord(document)) return {};
119
+ const values: Record<string, string> = {};
120
+ const found = isRecord(document.foundRC) ? document.foundRC : undefined;
121
+ const loaded = isRecord(document.loadedRC) ? document.loadedRC : undefined;
122
+ setString(values, "rc_path", found?.path ?? loaded?.path);
123
+ if (typeof found?.allowed === "number" || typeof found?.allowed === "boolean") {
124
+ values.allowed = found.allowed ? "allowed" : "denied";
125
+ }
126
+ if (loaded) values.loaded = "loaded";
127
+ else if (found) values.loaded = "not loaded";
128
+ return values;
129
+ } catch {
130
+ const path = /^Found RC path ([^\r\n]+)$/mu.exec(output)?.[1];
131
+ return path ? { rc_path: safeMetadata(path) ?? "" } : {};
132
+ }
133
+ }
134
+
135
+ async function readPixiProject(context: CollectorContext): Promise<string | undefined> {
136
+ const source = await context.fs.readFile(
137
+ join(context.input.cwd, "pixi.toml"),
138
+ MAX_METADATA_FILE_BYTES,
139
+ );
140
+ if (!source) return undefined;
141
+ try {
142
+ const document = parse(source);
143
+ const project = isRecord(document.project) ? document.project : undefined;
144
+ const workspace = isRecord(document.workspace) ? document.workspace : undefined;
145
+ return safeMetadata(project?.name ?? workspace?.name);
146
+ } catch {
147
+ return undefined;
148
+ }
149
+ }
150
+
151
+ function parsePixiVersion(output: string): string | undefined {
152
+ const match = /^(?:pixi\s+)?(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/u.exec(output.trim());
153
+ return match?.[1] ? `v${match[1]}` : undefined;
154
+ }
@@ -0,0 +1,141 @@
1
+ import {
2
+ exactAlias,
3
+ optionBoolean,
4
+ optionMap,
5
+ optionString,
6
+ optionStrings,
7
+ safeMetadata,
8
+ } from "./helpers.js";
9
+ import type { CollectorContext, MutableModuleSnapshot } from "./types.js";
10
+
11
+ export async function collectExecution(context: CollectorContext): Promise<MutableModuleSnapshot> {
12
+ if (context.input.reason === "periodic" && context.input.previous) {
13
+ const retained: MutableModuleSnapshot = {};
14
+ for (const name of ["os", "container", "hostname", "username"] as const) {
15
+ const values = context.input.previous.modules[name];
16
+ if (context.needs(name) && values) retained[name] = { ...values };
17
+ }
18
+ return retained;
19
+ }
20
+ const result: MutableModuleSnapshot = {};
21
+ if (context.needs("os")) result.os = await osValues(context);
22
+ const container = context.needs("container") ? await containerValues(context) : undefined;
23
+ if (container) result.container = container;
24
+ const hostname = context.needs("hostname") ? hostnameValues(context) : undefined;
25
+ if (hostname) result.hostname = hostname;
26
+ const username = context.needs("username") ? usernameValues(context) : undefined;
27
+ if (username) result.username = username;
28
+ return result;
29
+ }
30
+
31
+ async function osValues(context: CollectorContext): Promise<Record<string, string>> {
32
+ const wsl = Boolean(safeMetadata(context.input.environment.WSL_DISTRO_NAME));
33
+ const type = wsl ? "wsl" : platformType(context.input.platform);
34
+ const details = context.input.platform === "linux" ? await linuxRelease(context) : {};
35
+ const symbols = optionMap(context, "os", "symbols");
36
+ return {
37
+ type,
38
+ name: details.name ?? platformName(context.input.platform, wsl),
39
+ ...(details.version ? { version: details.version } : {}),
40
+ ...(details.edition ? { edition: details.edition } : {}),
41
+ ...(details.codename ? { codename: details.codename } : {}),
42
+ ...(Object.hasOwn(symbols, type) && safeMetadata(symbols[type])
43
+ ? { symbol: safeMetadata(symbols[type]) as string }
44
+ : {}),
45
+ };
46
+ }
47
+
48
+ async function linuxRelease(context: CollectorContext): Promise<{
49
+ name?: string;
50
+ version?: string;
51
+ edition?: string;
52
+ codename?: string;
53
+ }> {
54
+ const source = await context.fs.readFile("/etc/os-release", 16 * 1024);
55
+ if (!source) return {};
56
+ const values: Record<string, string> = {};
57
+ for (const line of source.split(/\r?\n/u)) {
58
+ const match = /^([A-Z_]+)=(.*)$/u.exec(line);
59
+ if (!match?.[1] || match[2] === undefined) continue;
60
+ const value = safeMetadata(match[2].replace(/^['"]|['"]$/gu, ""));
61
+ if (value) values[match[1]] = value;
62
+ }
63
+ return {
64
+ name: values.NAME,
65
+ version: values.VERSION_ID,
66
+ edition: values.ID,
67
+ codename: values.VERSION_CODENAME,
68
+ };
69
+ }
70
+
71
+ async function containerValues(
72
+ context: CollectorContext,
73
+ ): Promise<Record<string, string> | undefined> {
74
+ const env = context.input.environment;
75
+ if (safeMetadata(env.REMOTE_CONTAINERS) || safeMetadata(env.CODESPACES)) {
76
+ return { name: "Dev Container", type: "devcontainer" };
77
+ }
78
+ const wsl = safeMetadata(env.WSL_DISTRO_NAME);
79
+ if (wsl) return { name: `WSL ${wsl}`, type: "wsl" };
80
+ if (await context.fs.fileExists("/.dockerenv")) return { name: "Docker", type: "docker" };
81
+ if (await context.fs.fileExists("/run/.containerenv")) return { name: "Podman", type: "podman" };
82
+ const systemd = safeMetadata(await context.fs.readFile("/run/systemd/container", 256));
83
+ return systemd ? { name: systemd, type: "container" } : undefined;
84
+ }
85
+
86
+ function hostnameValues(context: CollectorContext): Record<string, string> | undefined {
87
+ const ssh = isSsh(context);
88
+ if (optionBoolean(context, "hostname", "ssh_only") && !ssh) return undefined;
89
+ const raw = safeMetadata(context.input.hostname);
90
+ if (!raw) return undefined;
91
+ const aliases = optionMap(context, "hostname", "aliases");
92
+ let hostname = exactAlias(raw, aliases) ?? raw;
93
+ if (hostname === raw) {
94
+ const trimAt = optionString(context, "hostname", "trim_at");
95
+ const index = trimAt ? hostname.indexOf(trimAt) : -1;
96
+ if (index > 0) hostname = hostname.slice(0, index);
97
+ }
98
+ return { hostname, ssh_symbol: ssh ? "🌐 " : "" };
99
+ }
100
+
101
+ function usernameValues(context: CollectorContext): Record<string, string> | undefined {
102
+ const user = safeMetadata(context.input.username);
103
+ if (!user) return undefined;
104
+ const env = context.input.environment;
105
+ const login = safeMetadata(env.LOGNAME ?? env.USER ?? env.USERNAME);
106
+ const privileged = /^(?:root|administrator)$/iu.test(user);
107
+ const detected = optionStrings(context, "username", "detect_env_vars").some(
108
+ (name) => safeMetadata(env[name]) !== undefined,
109
+ );
110
+ if (
111
+ !optionBoolean(context, "username", "show_always") &&
112
+ !isSsh(context) &&
113
+ !privileged &&
114
+ !(login && login !== user) &&
115
+ !detected
116
+ ) {
117
+ return undefined;
118
+ }
119
+ return { user: exactAlias(user, optionMap(context, "username", "aliases")) ?? user };
120
+ }
121
+
122
+ function isSsh(context: CollectorContext): boolean {
123
+ return Boolean(
124
+ safeMetadata(context.input.environment.SSH_CONNECTION) ||
125
+ safeMetadata(context.input.environment.SSH_TTY),
126
+ );
127
+ }
128
+
129
+ function platformType(platform: NodeJS.Platform): string {
130
+ if (platform === "darwin") return "macos";
131
+ if (platform === "win32") return "windows";
132
+ return platform;
133
+ }
134
+
135
+ function platformName(platform: NodeJS.Platform, wsl: boolean): string {
136
+ if (wsl) return "WSL";
137
+ if (platform === "darwin") return "macOS";
138
+ if (platform === "win32") return "Windows";
139
+ if (platform === "linux") return "Linux";
140
+ return platform;
141
+ }