@narumitw/pi-starship 0.55.2 → 0.56.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.
@@ -0,0 +1,118 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, open, rename, rm } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { formatDisplayValue, formatError } from "./script-support.mjs";
5
+
6
+ const PRIVATE_DIRECTORY_MODE = 0o700;
7
+ const PRIVATE_FILE_MODE = 0o600;
8
+ const MAX_EMBEDDED_ERROR_LENGTH = 240;
9
+ const MAX_NESTED_DIRECTORY_ERROR_LENGTH = 80;
10
+
11
+ export async function backupExpectedDocument(destinationPath, expected, options = {}) {
12
+ const backupDirectory = join(dirname(destinationPath), "pi-starship");
13
+ const backupPath = join(backupDirectory, `pi-starship-${localTimestamp(options.now ?? new Date())}.toml`);
14
+ const temporaryPath = join(backupDirectory, `.pi-starship-${randomUUID()}.tmp`);
15
+ const inspectPath = options.inspectPath ?? lstat;
16
+ const makeDirectory = options.makeDirectory ?? mkdir;
17
+ const openFile = options.openFile ?? open;
18
+ const removeFile = options.removeFile ?? rm;
19
+ const renameFile = options.renameFile ?? rename;
20
+ const syncDirectory = options.syncDirectory ?? syncDirectoryEntry;
21
+
22
+ await makeDirectory(backupDirectory, { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
23
+
24
+ let handle;
25
+ let ownsTemporaryPath = false;
26
+ let backupPublished = false;
27
+ try {
28
+ handle = await openFile(temporaryPath, "wx", PRIVATE_FILE_MODE);
29
+ ownsTemporaryPath = true;
30
+ await handle.writeFile(expected);
31
+ await handle.sync();
32
+ await handle.close();
33
+ handle = undefined;
34
+ await assertBackupMissing(backupPath, inspectPath);
35
+ await renameFile(temporaryPath, backupPath);
36
+ ownsTemporaryPath = false;
37
+ backupPublished = true;
38
+ await syncDirectory(backupDirectory);
39
+ await syncDirectory(dirname(backupDirectory));
40
+ return backupPath;
41
+ } catch (error) {
42
+ const cleanupErrors = [];
43
+ if (handle) {
44
+ try {
45
+ await handle.close();
46
+ } catch (closeError) {
47
+ cleanupErrors.push({ operation: "closing the temporary backup", error: closeError });
48
+ }
49
+ }
50
+ if (ownsTemporaryPath) {
51
+ try {
52
+ await removeFile(temporaryPath, { force: true });
53
+ } catch (removeError) {
54
+ cleanupErrors.push({ operation: "removing the temporary backup", error: removeError });
55
+ }
56
+ }
57
+ if (cleanupErrors.length > 0) {
58
+ const diagnostics = cleanupErrors
59
+ .map(({ operation, error: cleanupError }) => `${operation}: ${formatEmbeddedError(cleanupError)}`)
60
+ .join("; ");
61
+ throw new Error(
62
+ `Backup creation failed: ${formatEmbeddedError(error)}. Cleanup also failed (${diagnostics}). The active file was preserved.`,
63
+ );
64
+ }
65
+ if (backupPublished) {
66
+ throw new Error(
67
+ `Backup was retained at ${formatDisplayValue(backupPath)}, but its directory durability check failed: ${formatEmbeddedError(error)}. The active file was preserved.`,
68
+ );
69
+ }
70
+ throw error;
71
+ }
72
+ }
73
+
74
+ async function syncDirectoryEntry(directoryPath) {
75
+ if (process.platform === "win32") return;
76
+
77
+ const handle = await open(directoryPath, "r");
78
+ let syncError;
79
+ try {
80
+ await handle.sync();
81
+ } catch (error) {
82
+ syncError = error;
83
+ }
84
+
85
+ try {
86
+ await handle.close();
87
+ } catch (closeError) {
88
+ if (syncError) {
89
+ throw new Error(
90
+ `Directory sync failed: ${formatEmbeddedError(syncError, MAX_NESTED_DIRECTORY_ERROR_LENGTH)}. Closing the directory also failed: ${formatEmbeddedError(closeError, MAX_NESTED_DIRECTORY_ERROR_LENGTH)}.`,
91
+ );
92
+ }
93
+ throw closeError;
94
+ }
95
+
96
+ if (syncError) throw syncError;
97
+ }
98
+
99
+ async function assertBackupMissing(backupPath, inspectPath) {
100
+ try {
101
+ await inspectPath(backupPath);
102
+ } catch (error) {
103
+ if (error && typeof error === "object" && error.code === "ENOENT") return;
104
+ throw error;
105
+ }
106
+ throw new Error(`Backup already exists at ${formatDisplayValue(backupPath)}; the active file was preserved.`);
107
+ }
108
+
109
+ function formatEmbeddedError(error, maximumLength = MAX_EMBEDDED_ERROR_LENGTH) {
110
+ const diagnostic = formatError(error);
111
+ return diagnostic.length > maximumLength ? `${diagnostic.slice(0, maximumLength - 1)}…` : diagnostic;
112
+ }
113
+
114
+ function localTimestamp(date) {
115
+ return [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()]
116
+ .map((value, index) => String(value).padStart(index === 0 ? 4 : 2, "0"))
117
+ .join("");
118
+ }
package/src/commands.ts CHANGED
@@ -197,6 +197,8 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
197
197
  `Reason: ${module.reason}`,
198
198
  `Variables: ${module.variables.join(", ") || "none"}`,
199
199
  `Style fields: ${module.styleFields.join(", ") || "none"}`,
200
+ `Style-rule selectors: ${module.styleRuleSelectors.join(", ") || "none"}`,
201
+ `Style rules: ${module.styleRuleCount} configured`,
200
202
  `Display rules: ${module.displayRules.join(" · ") || "none"}`,
201
203
  ],
202
204
  })),
package/src/config.ts CHANGED
@@ -6,7 +6,7 @@ import type { TomlTable } from "smol-toml";
6
6
  import { type FormatNode, formatVariables, parseFormat, styleVariables } from "./format/formatter.js";
7
7
  import { type ColorPalette, isValidStyle, parseColor } from "./format/style.js";
8
8
  import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
9
- import type { ModuleDisplayConfig, ModuleOptionSchema, ModuleOptionValue } from "./modules/types.js";
9
+ import type { ModuleDisplayConfig, ModuleOptionSchema, ModuleOptionValue, ModuleStyleRule } from "./modules/types.js";
10
10
 
11
11
  export const CONFIG_FILE_NAME = "pi-starship.toml";
12
12
  export { MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
@@ -21,6 +21,7 @@ export interface ModuleConfig {
21
21
  symbol: string;
22
22
  style: string;
23
23
  styles: Record<string, string>;
24
+ styleRules: ModuleStyleRule[];
24
25
  display: ModuleDisplayConfig[];
25
26
  disabled: boolean;
26
27
  options: Record<string, ModuleOptionValue>;
@@ -76,6 +77,7 @@ const BUILT_IN_MODULES = Object.fromEntries(
76
77
  ...defaults,
77
78
  formatAst: parseFormat(defaults.format),
78
79
  styles: { ...styleDefaults },
80
+ styleRules: [] as ModuleStyleRule[],
79
81
  display: structuredClone(displayDefaults ?? []),
80
82
  options: Object.fromEntries(
81
83
  Object.entries(options ?? {}).map(([key, schema]) => [key, cloneOptionValue(schema.default)]),
@@ -273,6 +275,7 @@ function normalizeModule(
273
275
  for (const field of Object.keys(definition.styleDefaults)) known.add(field);
274
276
  } else if (!definition.displayDefaults) known.add("style");
275
277
  if (definition.displayDefaults) known.add("display");
278
+ if (definition.styleRuleSelectors) known.add("style_rules");
276
279
  if (name === "extension_status") {
277
280
  known.add("separator");
278
281
  known.add("max_statuses");
@@ -326,6 +329,15 @@ function normalizeModule(
326
329
  diagnostics,
327
330
  );
328
331
  }
332
+ if (definition.styleRuleSelectors && value.style_rules !== undefined) {
333
+ module.styleRules = normalizeStyleRules(
334
+ name,
335
+ value.style_rules,
336
+ new Set(Object.keys(definition.styleRuleSelectors)),
337
+ activePalette(config),
338
+ diagnostics,
339
+ );
340
+ }
329
341
  if (value.disabled !== undefined) {
330
342
  if (typeof value.disabled !== "boolean") {
331
343
  diagnostics.push(typeDiagnostic(`${name}.disabled`, "boolean"));
@@ -487,6 +499,7 @@ function cloneBuiltInConfig(): StarshipConfig {
487
499
  ...BUILT_IN_CONFIG.modules[name],
488
500
  formatAst: structuredClone(BUILT_IN_CONFIG.modules[name].formatAst),
489
501
  styles: { ...BUILT_IN_CONFIG.modules[name].styles },
502
+ styleRules: structuredClone(BUILT_IN_CONFIG.modules[name].styleRules),
490
503
  display: structuredClone(BUILT_IN_CONFIG.modules[name].display),
491
504
  options: structuredClone(BUILT_IN_CONFIG.modules[name].options),
492
505
  },
@@ -546,6 +559,48 @@ function validateModuleStyleField(
546
559
  }
547
560
  }
548
561
 
562
+ function normalizeStyleRules(
563
+ name: ModuleName,
564
+ value: unknown,
565
+ allowedSelectors: ReadonlySet<string>,
566
+ palette: ColorPalette,
567
+ diagnostics: ConfigDiagnostic[],
568
+ ): ModuleStyleRule[] {
569
+ if (!Array.isArray(value)) {
570
+ diagnostics.push(typeDiagnostic(`${name}.style_rules`, "array of tables"));
571
+ return [];
572
+ }
573
+ const result: ModuleStyleRule[] = [];
574
+ for (const [index, entry] of value.entries()) {
575
+ const path = `${name}.style_rules.${index}`;
576
+ if (!isRecord(entry)) {
577
+ diagnostics.push(diagnostic("warning", path, "Expected a table; rule ignored"));
578
+ continue;
579
+ }
580
+ let valid = true;
581
+ for (const field of Object.keys(entry)) {
582
+ if (field !== "style" && !allowedSelectors.has(field)) {
583
+ diagnostics.push(diagnostic("warning", `${path}.${field}`, "Unknown style-rule field; rule ignored"));
584
+ valid = false;
585
+ }
586
+ }
587
+ if (typeof entry.style !== "string" || !isValidStyle(entry.style, palette)) {
588
+ diagnostics.push(diagnostic("warning", `${path}.style`, "Expected a valid Starship style string; rule ignored"));
589
+ valid = false;
590
+ }
591
+ const selectors: Record<string, string> = {};
592
+ for (const selector of allowedSelectors) {
593
+ if (entry[selector] === undefined) continue;
594
+ if (typeof entry[selector] !== "string") {
595
+ diagnostics.push(diagnostic("warning", `${path}.${selector}`, "Expected string; rule ignored"));
596
+ valid = false;
597
+ } else setOwn(selectors, selector, entry[selector]);
598
+ }
599
+ if (valid) result.push({ style: entry.style as string, selectors });
600
+ }
601
+ return result;
602
+ }
603
+
549
604
  function normalizeDisplay(
550
605
  name: ModuleName,
551
606
  value: unknown,
@@ -28,6 +28,9 @@ export function projectEffectiveConfig(config: StarshipConfig): TomlTable {
28
28
  if (definition.displayDefaults) {
29
29
  table.display = module.display.map((entry) => ({ ...entry }));
30
30
  }
31
+ if (definition.styleRuleSelectors && module.styleRules.length > 0) {
32
+ table.style_rules = module.styleRules.map((rule) => ({ ...rule.selectors, style: rule.style }));
33
+ }
31
34
  table.disabled = module.disabled;
32
35
  for (const key of Object.keys(definition.options ?? {})) {
33
36
  table[key] = cloneOptionValue(module.options[key]);
@@ -14,6 +14,8 @@ export interface ModuleInspection {
14
14
  preview: string;
15
15
  variables: readonly string[];
16
16
  styleFields: readonly string[];
17
+ styleRuleSelectors: readonly string[];
18
+ styleRuleCount: number;
17
19
  displayRules: readonly string[];
18
20
  rootReferenced: boolean;
19
21
  reachable: boolean;
@@ -98,6 +100,8 @@ function moduleInspection(
98
100
  preview,
99
101
  variables: [...definition.variables],
100
102
  styleFields: ["style", ...Object.keys(module.styles)],
103
+ styleRuleSelectors: Object.keys(definition.styleRuleSelectors ?? {}),
104
+ styleRuleCount: module.styleRules.length,
101
105
  displayRules: module.display.map(
102
106
  (rule) => `${rule.threshold}: ${rule.hidden ? "hidden" : rule.style || "unstyled"}`,
103
107
  ),
@@ -14,6 +14,10 @@ export const modelModule = defineModule({
14
14
  style: "bold blue",
15
15
  disabled: false,
16
16
  },
17
+ styleRuleSelectors: {
18
+ provider: ({ runtime }) => runtime.model?.provider,
19
+ model: ({ runtime }) => runtime.model?.id,
20
+ },
17
21
  options: {
18
22
  truncation_length: { kind: "integer", default: 0, minimum: 0, maximum: 1000 },
19
23
  truncation_symbol: { kind: "string", default: "…" },
@@ -12,6 +12,9 @@ export const providerModule = defineModule({
12
12
  style: "bold blue",
13
13
  disabled: false,
14
14
  },
15
+ styleRuleSelectors: {
16
+ provider: ({ runtime }) => runtime.model?.provider,
17
+ },
15
18
  options: {
16
19
  [PROVIDER_ALIASES_KEY]: { kind: "string-map", default: {} },
17
20
  },
@@ -3,7 +3,8 @@ import { activePalette, type ModuleConfig, type StarshipConfig } from "../config
3
3
  import { type FormatValue, formatVariables, renderFormat } from "../format/formatter.js";
4
4
  import { isFillChunk, type LayoutChunk, renderChunksToAnsi, type StyledChunk } from "../format/style.js";
5
5
  import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./catalog.js";
6
- import type { ModuleValueContext, RenderedStatusline, StarshipRuntimeSnapshot } from "./types.js";
6
+ import { resolveStyleRule } from "./style-rules.js";
7
+ import type { ModuleStyleContext, ModuleValueContext, RenderedStatusline, StarshipRuntimeSnapshot } from "./types.js";
7
8
 
8
9
  export function renderStatusline(
9
10
  config: StarshipConfig,
@@ -23,16 +24,21 @@ export function renderStatusline(
23
24
  const module = config.modules[name];
24
25
  const values = definition.values(valueContext(config, name, runtime));
25
26
  if (!values) continue;
26
- const styleVariables = definition.resolveStyleVariables
27
- ? definition.resolveStyleVariables({
28
- runtime,
29
- values,
30
- style: module.style,
31
- styles: module.styles,
32
- display: module.display,
33
- })
27
+ const styleContext: ModuleStyleContext = {
28
+ runtime,
29
+ values,
30
+ style: module.style,
31
+ styles: module.styles,
32
+ display: module.display,
33
+ };
34
+ const baseStyleVariables = definition.resolveStyleVariables
35
+ ? definition.resolveStyleVariables(styleContext)
34
36
  : { style: module.style };
35
- if (!styleVariables) continue;
37
+ if (!baseStyleVariables) continue;
38
+ const ruleStyle = definition.styleRuleSelectors
39
+ ? resolveStyleRule(module.styleRules, definition.styleRuleSelectors, styleContext)
40
+ : undefined;
41
+ const styleVariables = ruleStyle === undefined ? baseStyleVariables : { ...baseStyleVariables, style: ruleStyle };
36
42
  const contentValues = Object.fromEntries(
37
43
  definition.variables.flatMap((variable) =>
38
44
  variable !== "symbol" && Object.hasOwn(values, variable) ? [[variable, values[variable]]] : [],
@@ -0,0 +1,21 @@
1
+ import type { ModuleStyleContext, ModuleStyleRule, ModuleStyleSelector } from "./types.js";
2
+
3
+ export function resolveStyleRule(
4
+ rules: readonly ModuleStyleRule[],
5
+ selectors: Readonly<Record<string, ModuleStyleSelector>>,
6
+ context: ModuleStyleContext,
7
+ ): string | undefined {
8
+ for (const rule of rules) {
9
+ let matches = true;
10
+ for (const name in rule.selectors) {
11
+ if (!Object.hasOwn(rule.selectors, name)) continue;
12
+ const selector = Object.hasOwn(selectors, name) ? selectors[name] : undefined;
13
+ if (!selector || selector(context) !== rule.selectors[name]) {
14
+ matches = false;
15
+ break;
16
+ }
17
+ }
18
+ if (matches) return rule.style;
19
+ }
20
+ return undefined;
21
+ }
@@ -30,6 +30,10 @@ export const thinkingModule = defineModule({
30
30
  >,
31
31
  fallbackStyle: true,
32
32
  styleVariables: ["style"],
33
+ styleRuleSelectors: {
34
+ provider: ({ runtime }) => runtime.model?.provider,
35
+ level: ({ runtime }) => runtime.thinkingLevel,
36
+ },
33
37
  resolveStyleVariables: ({ runtime, styles, style }) => {
34
38
  const level = thinkingLevelOf(runtime.thinkingLevel);
35
39
  return { style: (level && styles[`style_${level}`]) || style };
@@ -145,6 +145,11 @@ export interface ModuleDisplayConfig {
145
145
  hidden: boolean;
146
146
  }
147
147
 
148
+ export interface ModuleStyleRule {
149
+ style: string;
150
+ selectors: Readonly<Record<string, string>>;
151
+ }
152
+
148
153
  export interface ModuleDefaults {
149
154
  format: string;
150
155
  symbol: string;
@@ -160,6 +165,8 @@ export interface ModuleStyleContext {
160
165
  display: readonly ModuleDisplayConfig[];
161
166
  }
162
167
 
168
+ export type ModuleStyleSelector = (context: ModuleStyleContext) => string | undefined;
169
+
163
170
  export interface ModuleDefinition<Name extends string> {
164
171
  name: Name;
165
172
  variables: readonly string[];
@@ -168,6 +175,7 @@ export interface ModuleDefinition<Name extends string> {
168
175
  fallbackStyle?: boolean;
169
176
  displayDefaults?: readonly ModuleDisplayConfig[];
170
177
  styleVariables?: readonly string[];
178
+ styleRuleSelectors?: Readonly<Record<string, ModuleStyleSelector>>;
171
179
  resolveStyleVariables?(context: ModuleStyleContext): Readonly<Record<string, string>> | undefined;
172
180
  options?: Readonly<Record<string, ModuleOptionSchema>>;
173
181
  layout?: "fill";