@narumitw/pi-starship 0.55.0 → 0.55.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 (101) hide show
  1. package/README.md +21 -36
  2. package/dist/chunks/{chunk-UX6PBXVK.js → chunk-JO5PH6FN.js} +28 -110
  3. package/dist/chunks/chunk-JO5PH6FN.js.map +7 -0
  4. package/dist/chunks/{chunk-P4XMFSQW.js → chunk-YWY5RIDQ.js} +3 -7
  5. package/dist/chunks/chunk-YWY5RIDQ.js.map +7 -0
  6. package/dist/chunks/{chunk-EOGXAMTA.js → chunk-ZQZSXXPI.js} +1 -1
  7. package/dist/chunks/chunk-ZQZSXXPI.js.map +7 -0
  8. package/dist/chunks/{cloud-BKHYWCTA.js → cloud-C4VU3TX3.js} +7 -14
  9. package/dist/chunks/cloud-C4VU3TX3.js.map +7 -0
  10. package/dist/chunks/{commands-53ZO2JUK.js → commands-ATILSUVK.js} +13 -42
  11. package/dist/chunks/commands-ATILSUVK.js.map +7 -0
  12. package/dist/chunks/{deployment-RKKOEQQ2.js → deployment-FMNTYRBW.js} +6 -21
  13. package/dist/chunks/deployment-FMNTYRBW.js.map +7 -0
  14. package/dist/chunks/{development-BERD42HW.js → development-OUYXDPBS.js} +4 -8
  15. package/dist/chunks/development-OUYXDPBS.js.map +7 -0
  16. package/dist/chunks/{execution-42JTEY3N.js → execution-HJOGLMWD.js} +3 -3
  17. package/dist/chunks/execution-HJOGLMWD.js.map +7 -0
  18. package/dist/chunks/{languages-RMP6DW7H.js → languages-WXMF4GOF.js} +6 -22
  19. package/dist/chunks/languages-WXMF4GOF.js.map +7 -0
  20. package/dist/chunks/{package-LG5H7BBM.js → package-YXRZQAOV.js} +5 -14
  21. package/dist/chunks/package-YXRZQAOV.js.map +7 -0
  22. package/dist/index.ts +38 -53
  23. package/dist/index.ts.map +2 -2
  24. package/package.json +60 -61
  25. package/skills/configuring-pi-starship/references/runtime-and-security.md +5 -1
  26. package/skills/configuring-pi-starship/scripts/apply.mjs +43 -47
  27. package/skills/configuring-pi-starship/scripts/config-path.mjs +3 -3
  28. package/skills/configuring-pi-starship/scripts/script-support.mjs +6 -6
  29. package/skills/configuring-pi-starship/scripts/validate.mjs +18 -18
  30. package/src/command-configuration.ts +267 -286
  31. package/src/command-contract.ts +6 -6
  32. package/src/command-inspector.ts +27 -27
  33. package/src/command-preset-picker.ts +45 -50
  34. package/src/command-preview.ts +153 -166
  35. package/src/commands.ts +588 -618
  36. package/src/config.ts +580 -660
  37. package/src/effective-config.ts +46 -48
  38. package/src/format/formatter.ts +211 -227
  39. package/src/format/style.ts +205 -216
  40. package/src/modules/activity.ts +74 -74
  41. package/src/modules/brand.ts +9 -9
  42. package/src/modules/cache.ts +18 -18
  43. package/src/modules/catalog.ts +79 -83
  44. package/src/modules/cloud.ts +54 -54
  45. package/src/modules/context.ts +27 -27
  46. package/src/modules/cost.ts +23 -23
  47. package/src/modules/deployment.ts +45 -45
  48. package/src/modules/development.ts +80 -81
  49. package/src/modules/directory.ts +89 -113
  50. package/src/modules/display.ts +9 -9
  51. package/src/modules/execution.ts +62 -69
  52. package/src/modules/extension-status.ts +59 -64
  53. package/src/modules/fill.ts +10 -10
  54. package/src/modules/git/branch.ts +26 -26
  55. package/src/modules/git/commit.ts +21 -23
  56. package/src/modules/git/metrics.ts +22 -22
  57. package/src/modules/git/runtime.ts +299 -334
  58. package/src/modules/git/state.ts +17 -17
  59. package/src/modules/git/status.ts +77 -79
  60. package/src/modules/git/worktree.ts +10 -12
  61. package/src/modules/github-pr.ts +20 -20
  62. package/src/modules/helpers.ts +3 -3
  63. package/src/modules/index.ts +21 -21
  64. package/src/modules/inspection.ts +101 -108
  65. package/src/modules/languages.ts +52 -59
  66. package/src/modules/model.ts +57 -67
  67. package/src/modules/package.ts +12 -12
  68. package/src/modules/provider.ts +22 -24
  69. package/src/modules/render.ts +124 -140
  70. package/src/modules/thinking.ts +27 -26
  71. package/src/modules/time.ts +10 -13
  72. package/src/modules/tokens.ts +13 -13
  73. package/src/modules/truncation.ts +14 -17
  74. package/src/modules/turn.ts +9 -9
  75. package/src/modules/types.ts +125 -132
  76. package/src/modules/workspace-helpers.ts +4 -7
  77. package/src/pi-starship.ts +567 -571
  78. package/src/presets/catalog.ts +113 -113
  79. package/src/runtime/cloud.ts +122 -150
  80. package/src/runtime/command.ts +106 -108
  81. package/src/runtime/deployment.ts +150 -179
  82. package/src/runtime/development.ts +107 -124
  83. package/src/runtime/execution.ts +110 -124
  84. package/src/runtime/github-pr.ts +223 -252
  85. package/src/runtime/helpers.ts +186 -199
  86. package/src/runtime/languages.ts +149 -180
  87. package/src/runtime/package.ts +74 -87
  88. package/src/runtime/refresh-controller.ts +82 -86
  89. package/src/runtime/types.ts +38 -38
  90. package/src/runtime/workspace.ts +108 -116
  91. package/src/usage.ts +40 -40
  92. package/dist/chunks/chunk-EOGXAMTA.js.map +0 -7
  93. package/dist/chunks/chunk-P4XMFSQW.js.map +0 -7
  94. package/dist/chunks/chunk-UX6PBXVK.js.map +0 -7
  95. package/dist/chunks/cloud-BKHYWCTA.js.map +0 -7
  96. package/dist/chunks/commands-53ZO2JUK.js.map +0 -7
  97. package/dist/chunks/deployment-RKKOEQQ2.js.map +0 -7
  98. package/dist/chunks/development-BERD42HW.js.map +0 -7
  99. package/dist/chunks/execution-42JTEY3N.js.map +0 -7
  100. package/dist/chunks/languages-RMP6DW7H.js.map +0 -7
  101. package/dist/chunks/package-LG5H7BBM.js.map +0 -7
package/src/config.ts CHANGED
@@ -1,76 +1,59 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import {
3
- existsSync,
4
- lstatSync,
5
- mkdirSync,
6
- readFileSync,
7
- renameSync,
8
- rmSync,
9
- writeFileSync,
10
- } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
11
3
  import { createRequire } from "node:module";
12
4
  import { dirname, join } from "node:path";
13
5
  import type { TomlTable } from "smol-toml";
14
- import {
15
- type FormatNode,
16
- formatVariables,
17
- parseFormat,
18
- styleVariables,
19
- } from "./format/formatter.js";
6
+ import { type FormatNode, formatVariables, parseFormat, styleVariables } from "./format/formatter.js";
20
7
  import { type ColorPalette, isValidStyle, parseColor } from "./format/style.js";
21
8
  import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
22
- import type {
23
- ModuleDisplayConfig,
24
- ModuleOptionSchema,
25
- ModuleOptionValue,
26
- } from "./modules/types.js";
9
+ import type { ModuleDisplayConfig, ModuleOptionSchema, ModuleOptionValue } from "./modules/types.js";
27
10
 
28
11
  export const CONFIG_FILE_NAME = "pi-starship.toml";
29
12
  export { MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
30
13
 
31
14
  const MODULE_CONTENT_VARIABLES = Object.fromEntries(
32
- MODULE_DEFINITIONS.map((definition) => [definition.name, definition.variables]),
15
+ MODULE_DEFINITIONS.map((definition) => [definition.name, definition.variables]),
33
16
  ) as Record<ModuleName, readonly string[]>;
34
17
 
35
18
  export interface ModuleConfig {
36
- format: string;
37
- formatAst: FormatNode[];
38
- symbol: string;
39
- style: string;
40
- styles: Record<string, string>;
41
- display: ModuleDisplayConfig[];
42
- disabled: boolean;
43
- options: Record<string, ModuleOptionValue>;
19
+ format: string;
20
+ formatAst: FormatNode[];
21
+ symbol: string;
22
+ style: string;
23
+ styles: Record<string, string>;
24
+ display: ModuleDisplayConfig[];
25
+ disabled: boolean;
26
+ options: Record<string, ModuleOptionValue>;
44
27
  }
45
28
 
46
29
  export interface ExtensionStatusConfig {
47
- separator: string;
48
- maxStatuses: number;
49
- icons: Record<string, string>;
30
+ separator: string;
31
+ maxStatuses: number;
32
+ icons: Record<string, string>;
50
33
  }
51
34
 
52
35
  export interface StarshipConfig {
53
- format: string;
54
- formatAst: FormatNode[];
55
- palette?: string;
56
- palettes: Record<string, Record<string, string>>;
57
- modules: Record<ModuleName, ModuleConfig>;
58
- extensionStatus: ExtensionStatusConfig;
36
+ format: string;
37
+ formatAst: FormatNode[];
38
+ palette?: string;
39
+ palettes: Record<string, Record<string, string>>;
40
+ modules: Record<ModuleName, ModuleConfig>;
41
+ extensionStatus: ExtensionStatusConfig;
59
42
  }
60
43
 
61
44
  export interface ConfigDiagnostic {
62
- severity: "warning" | "error";
63
- path: string;
64
- message: string;
45
+ severity: "warning" | "error";
46
+ path: string;
47
+ message: string;
65
48
  }
66
49
 
67
50
  export interface LoadedStarshipConfig {
68
- config: StarshipConfig;
69
- source: "built-in" | "user";
70
- settingsPath: string;
71
- rawDocument?: string;
72
- fileIdentity?: { dev: number; ino: number };
73
- diagnostics: ConfigDiagnostic[];
51
+ config: StarshipConfig;
52
+ source: "built-in" | "user";
53
+ settingsPath: string;
54
+ rawDocument?: string;
55
+ fileIdentity?: { dev: number; ino: number };
56
+ diagnostics: ConfigDiagnostic[];
74
57
  }
75
58
 
76
59
  const BUILT_IN_FORMAT_DOCUMENT = String.raw`format = """
@@ -84,34 +67,30 @@ $activity\
84
67
  $context\
85
68
  $time"""`;
86
69
 
87
- const BUILT_IN_FORMAT =
88
- "$brand$model$thinking$directory$git_branch$git_status$activity$context$time";
70
+ const BUILT_IN_FORMAT = "$brand$model$thinking$directory$git_branch$git_status$activity$context$time";
89
71
 
90
72
  const BUILT_IN_MODULES = Object.fromEntries(
91
- MODULE_DEFINITIONS.map(({ name, defaults, styleDefaults, displayDefaults, options }) => [
92
- name,
93
- {
94
- ...defaults,
95
- formatAst: parseFormat(defaults.format),
96
- styles: { ...styleDefaults },
97
- display: structuredClone(displayDefaults ?? []),
98
- options: Object.fromEntries(
99
- Object.entries(options ?? {}).map(([key, schema]) => [
100
- key,
101
- cloneOptionValue(schema.default),
102
- ]),
103
- ),
104
- },
105
- ]),
73
+ MODULE_DEFINITIONS.map(({ name, defaults, styleDefaults, displayDefaults, options }) => [
74
+ name,
75
+ {
76
+ ...defaults,
77
+ formatAst: parseFormat(defaults.format),
78
+ styles: { ...styleDefaults },
79
+ display: structuredClone(displayDefaults ?? []),
80
+ options: Object.fromEntries(
81
+ Object.entries(options ?? {}).map(([key, schema]) => [key, cloneOptionValue(schema.default)]),
82
+ ),
83
+ },
84
+ ]),
106
85
  ) as Record<ModuleName, ModuleConfig>;
107
86
 
108
87
  export const BUILT_IN_CONFIG: StarshipConfig = {
109
- format: BUILT_IN_FORMAT,
110
- formatAst: parseFormat(BUILT_IN_FORMAT),
111
- palette: undefined,
112
- palettes: {},
113
- modules: BUILT_IN_MODULES,
114
- extensionStatus: { separator: " • ", maxStatuses: 5, icons: {} },
88
+ format: BUILT_IN_FORMAT,
89
+ formatAst: parseFormat(BUILT_IN_FORMAT),
90
+ palette: undefined,
91
+ palettes: {},
92
+ modules: BUILT_IN_MODULES,
93
+ extensionStatus: { separator: " • ", maxStatuses: 5, icons: {} },
115
94
  };
116
95
 
117
96
  export const BUILT_IN_EXAMPLE = `# Native Pi modules with Starship-compatible format and style syntax.\n${BUILT_IN_FORMAT_DOCUMENT}\n`;
@@ -120,684 +99,625 @@ const require = createRequire(import.meta.url);
120
99
  let parseTomlImplementation: typeof import("smol-toml")["parse"] | undefined;
121
100
 
122
101
  function parseToml(document: string): TomlTable {
123
- parseTomlImplementation ??= (require("smol-toml") as typeof import("smol-toml")).parse;
124
- return parseTomlImplementation(document);
102
+ parseTomlImplementation ??= (require("smol-toml") as typeof import("smol-toml")).parse;
103
+ return parseTomlImplementation(document);
125
104
  }
126
105
 
127
106
  export function settingsFilePath(agentDir: string): string {
128
- return join(agentDir, CONFIG_FILE_NAME);
107
+ return join(agentDir, CONFIG_FILE_NAME);
129
108
  }
130
109
 
131
110
  export function loadStarshipConfig(settingsPath: string): LoadedStarshipConfig {
132
- let rawDocument: string;
133
- try {
134
- rawDocument = readFileSync(settingsPath, "utf8");
135
- } catch (error) {
136
- if ((error as NodeJS.ErrnoException).code === "ENOENT" && !existsSync(settingsPath)) {
137
- return {
138
- config: cloneBuiltInConfig(),
139
- source: "built-in",
140
- settingsPath,
141
- diagnostics: [],
142
- };
143
- }
144
- return {
145
- config: cloneBuiltInConfig(),
146
- source: "built-in",
147
- settingsPath,
148
- diagnostics: [diagnostic("error", "", `Unable to read settings: ${formatError(error)}`)],
149
- };
150
- }
151
-
152
- let parsed: TomlTable;
153
- try {
154
- parsed = parseToml(rawDocument);
155
- } catch (error) {
156
- return {
157
- config: cloneBuiltInConfig(),
158
- source: "built-in",
159
- settingsPath,
160
- rawDocument,
161
- diagnostics: [diagnostic("error", "", `Unable to parse TOML: ${formatError(error)}`)],
162
- };
163
- }
164
- const normalized = normalizeConfig(parsed);
165
- return {
166
- ...normalized,
167
- source: "user",
168
- settingsPath,
169
- rawDocument,
170
- };
111
+ let rawDocument: string;
112
+ try {
113
+ rawDocument = readFileSync(settingsPath, "utf8");
114
+ } catch (error) {
115
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" && !existsSync(settingsPath)) {
116
+ return {
117
+ config: cloneBuiltInConfig(),
118
+ source: "built-in",
119
+ settingsPath,
120
+ diagnostics: [],
121
+ };
122
+ }
123
+ return {
124
+ config: cloneBuiltInConfig(),
125
+ source: "built-in",
126
+ settingsPath,
127
+ diagnostics: [diagnostic("error", "", `Unable to read settings: ${formatError(error)}`)],
128
+ };
129
+ }
130
+
131
+ let parsed: TomlTable;
132
+ try {
133
+ parsed = parseToml(rawDocument);
134
+ } catch (error) {
135
+ return {
136
+ config: cloneBuiltInConfig(),
137
+ source: "built-in",
138
+ settingsPath,
139
+ rawDocument,
140
+ diagnostics: [diagnostic("error", "", `Unable to parse TOML: ${formatError(error)}`)],
141
+ };
142
+ }
143
+ const normalized = normalizeConfig(parsed);
144
+ return {
145
+ ...normalized,
146
+ source: "user",
147
+ settingsPath,
148
+ rawDocument,
149
+ };
171
150
  }
172
151
 
173
152
  export function normalizeConfig(value: unknown): {
174
- config: StarshipConfig;
175
- diagnostics: ConfigDiagnostic[];
153
+ config: StarshipConfig;
154
+ diagnostics: ConfigDiagnostic[];
176
155
  } {
177
- const config = cloneBuiltInConfig();
178
- const diagnostics: ConfigDiagnostic[] = [];
179
- if (!isRecord(value)) {
180
- return {
181
- config,
182
- diagnostics: [diagnostic("error", "", "Settings must contain a TOML table")],
183
- };
184
- }
185
-
186
- const knownRoot = new Set(["format", "palette", "palettes", ...MODULE_NAMES]);
187
- for (const key of Object.keys(value)) {
188
- if (!knownRoot.has(key)) diagnostics.push(unknownDiagnostic(key));
189
- }
190
-
191
- if (value.format !== undefined) {
192
- if (typeof value.format !== "string") {
193
- diagnostics.push(typeDiagnostic("format", "string"));
194
- } else {
195
- try {
196
- config.formatAst = parseFormat(value.format);
197
- config.format = value.format;
198
- } catch (error) {
199
- diagnostics.push(
200
- diagnostic("warning", "format", `Invalid format; using built-in: ${formatError(error)}`),
201
- );
202
- }
203
- }
204
- }
205
-
206
- if (value.palettes !== undefined) {
207
- if (!isRecord(value.palettes)) {
208
- diagnostics.push(typeDiagnostic("palettes", "table"));
209
- } else {
210
- for (const [paletteName, paletteValue] of Object.entries(value.palettes)) {
211
- if (!isRecord(paletteValue)) {
212
- diagnostics.push(typeDiagnostic(`palettes.${paletteName}`, "table"));
213
- continue;
214
- }
215
- const palette: Record<string, string> = {};
216
- for (const [name, color] of Object.entries(paletteValue)) {
217
- if (typeof color !== "string" || !parseColor(color.toLowerCase())) {
218
- diagnostics.push(
219
- diagnostic(
220
- "warning",
221
- `palettes.${paletteName}.${name}`,
222
- "Palette colors must be named, ANSI 0-255, or #RRGGBB",
223
- ),
224
- );
225
- continue;
226
- }
227
- setOwn(palette, name, color);
228
- }
229
- setOwn(config.palettes, paletteName, palette);
230
- }
231
- }
232
- }
233
-
234
- if (value.palette !== undefined) {
235
- if (typeof value.palette !== "string") diagnostics.push(typeDiagnostic("palette", "string"));
236
- else {
237
- config.palette = value.palette;
238
- if (!Object.hasOwn(config.palettes, value.palette)) {
239
- diagnostics.push(
240
- diagnostic("warning", "palette", `Unknown palette ${JSON.stringify(value.palette)}`),
241
- );
242
- }
243
- }
244
- }
245
-
246
- for (const name of MODULE_NAMES) {
247
- const moduleValue = value[name];
248
- if (moduleValue === undefined) continue;
249
- if (!isRecord(moduleValue)) {
250
- diagnostics.push(typeDiagnostic(name, "table"));
251
- continue;
252
- }
253
- normalizeModule(name, moduleValue, config, diagnostics);
254
- }
255
-
256
- validateFormatVariables(
257
- config.formatAst,
258
- new Set([...MODULE_NAMES, "all"]),
259
- "format",
260
- diagnostics,
261
- );
262
- validateStyleVariables(config.formatAst, new Set(), "format", diagnostics);
263
- const palette = activePalette(config);
264
- validateLiteralStyles(config.formatAst, palette, "format", diagnostics);
265
- for (const definition of MODULE_DEFINITIONS) {
266
- const name = definition.name;
267
- const module = config.modules[name];
268
- validateFormatVariables(
269
- module.formatAst,
270
- new Set(MODULE_CONTENT_VARIABLES[name]),
271
- `${name}.format`,
272
- diagnostics,
273
- );
274
- validateStyleVariables(
275
- module.formatAst,
276
- new Set(definition.styleVariables ?? ["style"]),
277
- `${name}.format`,
278
- diagnostics,
279
- );
280
- validateLiteralStyles(module.formatAst, palette, `${name}.format`, diagnostics);
281
- if (definition.styleDefaults) {
282
- if (definition.fallbackStyle) {
283
- validateModuleStyleField(name, "style", module, palette, diagnostics);
284
- }
285
- for (const field of Object.keys(definition.styleDefaults)) {
286
- validateModuleStyleField(name, field, module, palette, diagnostics);
287
- }
288
- } else if (!definition.displayDefaults) {
289
- validateModuleStyleField(name, "style", module, palette, diagnostics);
290
- }
291
- }
292
-
293
- return { config, diagnostics };
156
+ const config = cloneBuiltInConfig();
157
+ const diagnostics: ConfigDiagnostic[] = [];
158
+ if (!isRecord(value)) {
159
+ return {
160
+ config,
161
+ diagnostics: [diagnostic("error", "", "Settings must contain a TOML table")],
162
+ };
163
+ }
164
+
165
+ const knownRoot = new Set(["format", "palette", "palettes", ...MODULE_NAMES]);
166
+ for (const key of Object.keys(value)) {
167
+ if (!knownRoot.has(key)) diagnostics.push(unknownDiagnostic(key));
168
+ }
169
+
170
+ if (value.format !== undefined) {
171
+ if (typeof value.format !== "string") {
172
+ diagnostics.push(typeDiagnostic("format", "string"));
173
+ } else {
174
+ try {
175
+ config.formatAst = parseFormat(value.format);
176
+ config.format = value.format;
177
+ } catch (error) {
178
+ diagnostics.push(diagnostic("warning", "format", `Invalid format; using built-in: ${formatError(error)}`));
179
+ }
180
+ }
181
+ }
182
+
183
+ if (value.palettes !== undefined) {
184
+ if (!isRecord(value.palettes)) {
185
+ diagnostics.push(typeDiagnostic("palettes", "table"));
186
+ } else {
187
+ for (const [paletteName, paletteValue] of Object.entries(value.palettes)) {
188
+ if (!isRecord(paletteValue)) {
189
+ diagnostics.push(typeDiagnostic(`palettes.${paletteName}`, "table"));
190
+ continue;
191
+ }
192
+ const palette: Record<string, string> = {};
193
+ for (const [name, color] of Object.entries(paletteValue)) {
194
+ if (typeof color !== "string" || !parseColor(color.toLowerCase())) {
195
+ diagnostics.push(
196
+ diagnostic(
197
+ "warning",
198
+ `palettes.${paletteName}.${name}`,
199
+ "Palette colors must be named, ANSI 0-255, or #RRGGBB",
200
+ ),
201
+ );
202
+ continue;
203
+ }
204
+ setOwn(palette, name, color);
205
+ }
206
+ setOwn(config.palettes, paletteName, palette);
207
+ }
208
+ }
209
+ }
210
+
211
+ if (value.palette !== undefined) {
212
+ if (typeof value.palette !== "string") diagnostics.push(typeDiagnostic("palette", "string"));
213
+ else {
214
+ config.palette = value.palette;
215
+ if (!Object.hasOwn(config.palettes, value.palette)) {
216
+ diagnostics.push(diagnostic("warning", "palette", `Unknown palette ${JSON.stringify(value.palette)}`));
217
+ }
218
+ }
219
+ }
220
+
221
+ for (const name of MODULE_NAMES) {
222
+ const moduleValue = value[name];
223
+ if (moduleValue === undefined) continue;
224
+ if (!isRecord(moduleValue)) {
225
+ diagnostics.push(typeDiagnostic(name, "table"));
226
+ continue;
227
+ }
228
+ normalizeModule(name, moduleValue, config, diagnostics);
229
+ }
230
+
231
+ validateFormatVariables(config.formatAst, new Set([...MODULE_NAMES, "all"]), "format", diagnostics);
232
+ validateStyleVariables(config.formatAst, new Set(), "format", diagnostics);
233
+ const palette = activePalette(config);
234
+ validateLiteralStyles(config.formatAst, palette, "format", diagnostics);
235
+ for (const definition of MODULE_DEFINITIONS) {
236
+ const name = definition.name;
237
+ const module = config.modules[name];
238
+ validateFormatVariables(module.formatAst, new Set(MODULE_CONTENT_VARIABLES[name]), `${name}.format`, diagnostics);
239
+ validateStyleVariables(
240
+ module.formatAst,
241
+ new Set(definition.styleVariables ?? ["style"]),
242
+ `${name}.format`,
243
+ diagnostics,
244
+ );
245
+ validateLiteralStyles(module.formatAst, palette, `${name}.format`, diagnostics);
246
+ if (definition.styleDefaults) {
247
+ if (definition.fallbackStyle) {
248
+ validateModuleStyleField(name, "style", module, palette, diagnostics);
249
+ }
250
+ for (const field of Object.keys(definition.styleDefaults)) {
251
+ validateModuleStyleField(name, field, module, palette, diagnostics);
252
+ }
253
+ } else if (!definition.displayDefaults) {
254
+ validateModuleStyleField(name, "style", module, palette, diagnostics);
255
+ }
256
+ }
257
+
258
+ return { config, diagnostics };
294
259
  }
295
260
 
296
261
  function normalizeModule(
297
- name: ModuleName,
298
- value: Record<string, unknown>,
299
- config: StarshipConfig,
300
- diagnostics: ConfigDiagnostic[],
262
+ name: ModuleName,
263
+ value: Record<string, unknown>,
264
+ config: StarshipConfig,
265
+ diagnostics: ConfigDiagnostic[],
301
266
  ) {
302
- const definition = MODULE_DEFINITIONS.find((candidate) => candidate.name === name);
303
- if (!definition) return;
304
- const optionSchemas: Readonly<Record<string, ModuleOptionSchema>> = definition.options ?? {};
305
- const known = new Set(["format", "symbol", "disabled", ...Object.keys(optionSchemas)]);
306
- if (definition.styleDefaults) {
307
- if (definition.fallbackStyle) known.add("style");
308
- for (const field of Object.keys(definition.styleDefaults)) known.add(field);
309
- } else if (!definition.displayDefaults) known.add("style");
310
- if (definition.displayDefaults) known.add("display");
311
- if (name === "extension_status") {
312
- known.add("separator");
313
- known.add("max_statuses");
314
- known.add("icons");
315
- }
316
- for (const key of Object.keys(value)) {
317
- if (!known.has(key)) diagnostics.push(unknownDiagnostic(`${name}.${key}`));
318
- }
319
- const module = config.modules[name];
320
- if (value.format !== undefined) {
321
- if (typeof value.format !== "string")
322
- diagnostics.push(typeDiagnostic(`${name}.format`, "string"));
323
- else {
324
- try {
325
- module.formatAst = parseFormat(value.format);
326
- module.format = value.format;
327
- } catch (error) {
328
- diagnostics.push(
329
- diagnostic(
330
- "warning",
331
- `${name}.format`,
332
- `Invalid format; using module default: ${formatError(error)}`,
333
- ),
334
- );
335
- }
336
- }
337
- }
338
- if (value.symbol !== undefined) {
339
- if (typeof value.symbol !== "string") {
340
- diagnostics.push(typeDiagnostic(`${name}.symbol`, "string"));
341
- } else module.symbol = value.symbol;
342
- }
343
- if (definition.styleDefaults && definition.fallbackStyle && value.style !== undefined) {
344
- if (typeof value.style !== "string") {
345
- diagnostics.push(typeDiagnostic(`${name}.style`, "string"));
346
- } else module.style = value.style;
347
- }
348
- if (definition.styleDefaults) {
349
- for (const field of Object.keys(definition.styleDefaults)) {
350
- if (value[field] === undefined) continue;
351
- if (typeof value[field] !== "string") {
352
- diagnostics.push(typeDiagnostic(`${name}.${field}`, "string"));
353
- } else module.styles[field] = value[field];
354
- }
355
- } else if (!definition.displayDefaults && value.style !== undefined) {
356
- if (typeof value.style !== "string") {
357
- diagnostics.push(typeDiagnostic(`${name}.style`, "string"));
358
- } else module.style = value.style;
359
- }
360
- if (definition.displayDefaults && value.display !== undefined) {
361
- module.display = normalizeDisplay(
362
- name,
363
- value.display,
364
- definition.displayDefaults,
365
- activePalette(config),
366
- diagnostics,
367
- );
368
- }
369
- if (value.disabled !== undefined) {
370
- if (typeof value.disabled !== "boolean") {
371
- diagnostics.push(typeDiagnostic(`${name}.disabled`, "boolean"));
372
- } else module.disabled = value.disabled;
373
- }
374
- for (const [key, schema] of Object.entries(optionSchemas)) {
375
- if (value[key] === undefined) continue;
376
- const normalized = normalizeModuleOption(value[key], schema);
377
- if (normalized.ok) module.options[key] = normalized.value;
378
- else diagnostics.push(diagnostic("warning", `${name}.${key}`, normalized.message));
379
- }
380
- if (name !== "extension_status") return;
381
- if (value.separator !== undefined) {
382
- if (typeof value.separator !== "string") {
383
- diagnostics.push(typeDiagnostic("extension_status.separator", "string"));
384
- } else config.extensionStatus.separator = value.separator;
385
- }
386
- if (value.max_statuses !== undefined) {
387
- if (
388
- typeof value.max_statuses !== "number" ||
389
- !Number.isInteger(value.max_statuses) ||
390
- value.max_statuses < 0 ||
391
- value.max_statuses > 100
392
- ) {
393
- diagnostics.push(
394
- diagnostic(
395
- "warning",
396
- "extension_status.max_statuses",
397
- "Expected an integer from 0 through 100",
398
- ),
399
- );
400
- } else config.extensionStatus.maxStatuses = value.max_statuses;
401
- }
402
- if (value.icons !== undefined) {
403
- if (!isRecord(value.icons)) diagnostics.push(typeDiagnostic("extension_status.icons", "table"));
404
- else {
405
- config.extensionStatus.icons = Object.fromEntries(
406
- Object.entries(value.icons).flatMap(([key, icon]) => {
407
- if (typeof icon === "string") return [[key, icon]];
408
- diagnostics.push(typeDiagnostic(`extension_status.icons.${key}`, "string"));
409
- return [];
410
- }),
411
- );
412
- }
413
- }
267
+ const definition = MODULE_DEFINITIONS.find((candidate) => candidate.name === name);
268
+ if (!definition) return;
269
+ const optionSchemas: Readonly<Record<string, ModuleOptionSchema>> = definition.options ?? {};
270
+ const known = new Set(["format", "symbol", "disabled", ...Object.keys(optionSchemas)]);
271
+ if (definition.styleDefaults) {
272
+ if (definition.fallbackStyle) known.add("style");
273
+ for (const field of Object.keys(definition.styleDefaults)) known.add(field);
274
+ } else if (!definition.displayDefaults) known.add("style");
275
+ if (definition.displayDefaults) known.add("display");
276
+ if (name === "extension_status") {
277
+ known.add("separator");
278
+ known.add("max_statuses");
279
+ known.add("icons");
280
+ }
281
+ for (const key of Object.keys(value)) {
282
+ if (!known.has(key)) diagnostics.push(unknownDiagnostic(`${name}.${key}`));
283
+ }
284
+ const module = config.modules[name];
285
+ if (value.format !== undefined) {
286
+ if (typeof value.format !== "string") diagnostics.push(typeDiagnostic(`${name}.format`, "string"));
287
+ else {
288
+ try {
289
+ module.formatAst = parseFormat(value.format);
290
+ module.format = value.format;
291
+ } catch (error) {
292
+ diagnostics.push(
293
+ diagnostic("warning", `${name}.format`, `Invalid format; using module default: ${formatError(error)}`),
294
+ );
295
+ }
296
+ }
297
+ }
298
+ if (value.symbol !== undefined) {
299
+ if (typeof value.symbol !== "string") {
300
+ diagnostics.push(typeDiagnostic(`${name}.symbol`, "string"));
301
+ } else module.symbol = value.symbol;
302
+ }
303
+ if (definition.styleDefaults && definition.fallbackStyle && value.style !== undefined) {
304
+ if (typeof value.style !== "string") {
305
+ diagnostics.push(typeDiagnostic(`${name}.style`, "string"));
306
+ } else module.style = value.style;
307
+ }
308
+ if (definition.styleDefaults) {
309
+ for (const field of Object.keys(definition.styleDefaults)) {
310
+ if (value[field] === undefined) continue;
311
+ if (typeof value[field] !== "string") {
312
+ diagnostics.push(typeDiagnostic(`${name}.${field}`, "string"));
313
+ } else module.styles[field] = value[field];
314
+ }
315
+ } else if (!definition.displayDefaults && value.style !== undefined) {
316
+ if (typeof value.style !== "string") {
317
+ diagnostics.push(typeDiagnostic(`${name}.style`, "string"));
318
+ } else module.style = value.style;
319
+ }
320
+ if (definition.displayDefaults && value.display !== undefined) {
321
+ module.display = normalizeDisplay(
322
+ name,
323
+ value.display,
324
+ definition.displayDefaults,
325
+ activePalette(config),
326
+ diagnostics,
327
+ );
328
+ }
329
+ if (value.disabled !== undefined) {
330
+ if (typeof value.disabled !== "boolean") {
331
+ diagnostics.push(typeDiagnostic(`${name}.disabled`, "boolean"));
332
+ } else module.disabled = value.disabled;
333
+ }
334
+ for (const [key, schema] of Object.entries(optionSchemas)) {
335
+ if (value[key] === undefined) continue;
336
+ const normalized = normalizeModuleOption(value[key], schema);
337
+ if (normalized.ok) module.options[key] = normalized.value;
338
+ else diagnostics.push(diagnostic("warning", `${name}.${key}`, normalized.message));
339
+ }
340
+ if (name !== "extension_status") return;
341
+ if (value.separator !== undefined) {
342
+ if (typeof value.separator !== "string") {
343
+ diagnostics.push(typeDiagnostic("extension_status.separator", "string"));
344
+ } else config.extensionStatus.separator = value.separator;
345
+ }
346
+ if (value.max_statuses !== undefined) {
347
+ if (
348
+ typeof value.max_statuses !== "number" ||
349
+ !Number.isInteger(value.max_statuses) ||
350
+ value.max_statuses < 0 ||
351
+ value.max_statuses > 100
352
+ ) {
353
+ diagnostics.push(
354
+ diagnostic("warning", "extension_status.max_statuses", "Expected an integer from 0 through 100"),
355
+ );
356
+ } else config.extensionStatus.maxStatuses = value.max_statuses;
357
+ }
358
+ if (value.icons !== undefined) {
359
+ if (!isRecord(value.icons)) diagnostics.push(typeDiagnostic("extension_status.icons", "table"));
360
+ else {
361
+ config.extensionStatus.icons = Object.fromEntries(
362
+ Object.entries(value.icons).flatMap(([key, icon]) => {
363
+ if (typeof icon === "string") return [[key, icon]];
364
+ diagnostics.push(typeDiagnostic(`extension_status.icons.${key}`, "string"));
365
+ return [];
366
+ }),
367
+ );
368
+ }
369
+ }
414
370
  }
415
371
 
416
372
  interface AtomicFileSystem {
417
- mkdirSync: typeof mkdirSync;
418
- writeFileSync: typeof writeFileSync;
419
- renameSync: typeof renameSync;
420
- rmSync: typeof rmSync;
421
- }
422
-
423
- export function validateConfigDocument(
424
- settingsPath: string,
425
- rawDocument: string,
426
- ): LoadedStarshipConfig {
427
- let parsed: TomlTable;
428
- try {
429
- parsed = parseToml(rawDocument);
430
- } catch (error) {
431
- throw new Error(`Unable to parse TOML: ${formatError(error)}`);
432
- }
433
- const normalized = normalizeConfig(parsed);
434
- if (normalized.diagnostics.some((item) => item.severity === "error")) {
435
- throw new Error(normalized.diagnostics.map((item) => item.message).join("\n"));
436
- }
437
- return {
438
- ...normalized,
439
- source: "user",
440
- settingsPath,
441
- rawDocument,
442
- };
373
+ mkdirSync: typeof mkdirSync;
374
+ writeFileSync: typeof writeFileSync;
375
+ renameSync: typeof renameSync;
376
+ rmSync: typeof rmSync;
377
+ }
378
+
379
+ export function validateConfigDocument(settingsPath: string, rawDocument: string): LoadedStarshipConfig {
380
+ let parsed: TomlTable;
381
+ try {
382
+ parsed = parseToml(rawDocument);
383
+ } catch (error) {
384
+ throw new Error(`Unable to parse TOML: ${formatError(error)}`);
385
+ }
386
+ const normalized = normalizeConfig(parsed);
387
+ if (normalized.diagnostics.some((item) => item.severity === "error")) {
388
+ throw new Error(normalized.diagnostics.map((item) => item.message).join("\n"));
389
+ }
390
+ return {
391
+ ...normalized,
392
+ source: "user",
393
+ settingsPath,
394
+ rawDocument,
395
+ };
443
396
  }
444
397
 
445
398
  export function atomicSaveConfigDocument(
446
- settingsPath: string,
447
- rawDocument: string,
448
- overrides: Partial<AtomicFileSystem> = {},
399
+ settingsPath: string,
400
+ rawDocument: string,
401
+ overrides: Partial<AtomicFileSystem> = {},
449
402
  ): LoadedStarshipConfig {
450
- const validated = validateConfigDocument(settingsPath, rawDocument);
451
- return {
452
- ...validated,
453
- fileIdentity: atomicWriteConfigDocument(settingsPath, rawDocument, overrides),
454
- };
403
+ const validated = validateConfigDocument(settingsPath, rawDocument);
404
+ return {
405
+ ...validated,
406
+ fileIdentity: atomicWriteConfigDocument(settingsPath, rawDocument, overrides),
407
+ };
455
408
  }
456
409
 
457
410
  export function atomicRestoreConfigDocument(
458
- settingsPath: string,
459
- rawDocument: string,
460
- overrides: Partial<AtomicFileSystem> = {},
411
+ settingsPath: string,
412
+ rawDocument: string,
413
+ overrides: Partial<AtomicFileSystem> = {},
461
414
  ) {
462
- atomicWriteConfigDocument(settingsPath, rawDocument, overrides);
415
+ atomicWriteConfigDocument(settingsPath, rawDocument, overrides);
463
416
  }
464
417
 
465
418
  export function removeConfigDocumentIfMatches(
466
- settingsPath: string,
467
- expectedRawDocument: string,
468
- expectedIdentity: { dev: number; ino: number },
469
- overrides: Pick<Partial<AtomicFileSystem>, "rmSync"> = {},
419
+ settingsPath: string,
420
+ expectedRawDocument: string,
421
+ expectedIdentity: { dev: number; ino: number },
422
+ overrides: Pick<Partial<AtomicFileSystem>, "rmSync"> = {},
470
423
  ) {
471
- const quarantinePath = join(
472
- dirname(settingsPath),
473
- `.${CONFIG_FILE_NAME}.${randomUUID()}.rollback`,
474
- );
475
- const before = lstatSync(settingsPath);
476
- if (before.dev !== expectedIdentity.dev || before.ino !== expectedIdentity.ino) {
477
- throw new Error("Starship settings changed concurrently; the newer file was preserved");
478
- }
479
- renameSync(settingsPath, quarantinePath);
480
- const quarantined = lstatSync(quarantinePath);
481
- const quarantinedSavedFile =
482
- quarantined.isFile() &&
483
- !quarantined.isSymbolicLink() &&
484
- quarantined.dev === expectedIdentity.dev &&
485
- quarantined.ino === expectedIdentity.ino;
486
- if (quarantinedSavedFile && readFileSync(quarantinePath, "utf8") === expectedRawDocument) {
487
- (overrides.rmSync ?? rmSync)(quarantinePath);
488
- return;
489
- }
490
- if (quarantinedSavedFile && !pathEntryExists(settingsPath)) {
491
- try {
492
- renameSync(quarantinePath, settingsPath);
493
- } catch {
494
- // Keep the quarantine for recovery when its atomic restoration fails.
495
- }
496
- }
497
- throw new Error("Starship settings changed concurrently; the newer file was preserved");
424
+ const quarantinePath = join(dirname(settingsPath), `.${CONFIG_FILE_NAME}.${randomUUID()}.rollback`);
425
+ const before = lstatSync(settingsPath);
426
+ if (before.dev !== expectedIdentity.dev || before.ino !== expectedIdentity.ino) {
427
+ throw new Error("Starship settings changed concurrently; the newer file was preserved");
428
+ }
429
+ renameSync(settingsPath, quarantinePath);
430
+ const quarantined = lstatSync(quarantinePath);
431
+ const quarantinedSavedFile =
432
+ quarantined.isFile() &&
433
+ !quarantined.isSymbolicLink() &&
434
+ quarantined.dev === expectedIdentity.dev &&
435
+ quarantined.ino === expectedIdentity.ino;
436
+ if (quarantinedSavedFile && readFileSync(quarantinePath, "utf8") === expectedRawDocument) {
437
+ (overrides.rmSync ?? rmSync)(quarantinePath);
438
+ return;
439
+ }
440
+ if (quarantinedSavedFile && !pathEntryExists(settingsPath)) {
441
+ try {
442
+ renameSync(quarantinePath, settingsPath);
443
+ } catch {
444
+ // Keep the quarantine for recovery when its atomic restoration fails.
445
+ }
446
+ }
447
+ throw new Error("Starship settings changed concurrently; the newer file was preserved");
498
448
  }
499
449
 
500
450
  function atomicWriteConfigDocument(
501
- settingsPath: string,
502
- rawDocument: string,
503
- overrides: Partial<AtomicFileSystem>,
451
+ settingsPath: string,
452
+ rawDocument: string,
453
+ overrides: Partial<AtomicFileSystem>,
504
454
  ): { dev: number; ino: number } {
505
- const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };
506
- const replaceExisting = pathEntryExists(settingsPath);
507
- fs.mkdirSync(dirname(settingsPath), { recursive: true });
508
- const tempPath = join(dirname(settingsPath), `.${CONFIG_FILE_NAME}.${randomUUID()}.tmp`);
509
- try {
510
- fs.writeFileSync(tempPath, rawDocument, { encoding: "utf8", flag: "wx" });
511
- const info = lstatSync(tempPath);
512
- if (!replaceExisting && pathEntryExists(settingsPath)) {
513
- throw new Error(`${CONFIG_FILE_NAME} was created concurrently; reopen settings and retry.`);
514
- }
515
- fs.renameSync(tempPath, settingsPath);
516
- return { dev: info.dev, ino: info.ino };
517
- } finally {
518
- try {
519
- fs.rmSync(tempPath, { force: true });
520
- } catch {
521
- // Best-effort cleanup must not replace the publication result.
522
- }
523
- }
455
+ const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };
456
+ const replaceExisting = pathEntryExists(settingsPath);
457
+ fs.mkdirSync(dirname(settingsPath), { recursive: true });
458
+ const tempPath = join(dirname(settingsPath), `.${CONFIG_FILE_NAME}.${randomUUID()}.tmp`);
459
+ try {
460
+ fs.writeFileSync(tempPath, rawDocument, { encoding: "utf8", flag: "wx" });
461
+ const info = lstatSync(tempPath);
462
+ if (!replaceExisting && pathEntryExists(settingsPath)) {
463
+ throw new Error(`${CONFIG_FILE_NAME} was created concurrently; reopen settings and retry.`);
464
+ }
465
+ fs.renameSync(tempPath, settingsPath);
466
+ return { dev: info.dev, ino: info.ino };
467
+ } finally {
468
+ try {
469
+ fs.rmSync(tempPath, { force: true });
470
+ } catch {
471
+ // Best-effort cleanup must not replace the publication result.
472
+ }
473
+ }
524
474
  }
525
475
 
526
476
  function cloneBuiltInConfig(): StarshipConfig {
527
- return {
528
- ...BUILT_IN_CONFIG,
529
- formatAst: structuredClone(BUILT_IN_CONFIG.formatAst),
530
- palettes: Object.fromEntries(
531
- Object.entries(BUILT_IN_CONFIG.palettes).map(([name, colors]) => [name, { ...colors }]),
532
- ),
533
- modules: Object.fromEntries(
534
- MODULE_NAMES.map((name) => [
535
- name,
536
- {
537
- ...BUILT_IN_CONFIG.modules[name],
538
- formatAst: structuredClone(BUILT_IN_CONFIG.modules[name].formatAst),
539
- styles: { ...BUILT_IN_CONFIG.modules[name].styles },
540
- display: structuredClone(BUILT_IN_CONFIG.modules[name].display),
541
- options: structuredClone(BUILT_IN_CONFIG.modules[name].options),
542
- },
543
- ]),
544
- ) as Record<ModuleName, ModuleConfig>,
545
- extensionStatus: {
546
- ...BUILT_IN_CONFIG.extensionStatus,
547
- icons: { ...BUILT_IN_CONFIG.extensionStatus.icons },
548
- },
549
- };
477
+ return {
478
+ ...BUILT_IN_CONFIG,
479
+ formatAst: structuredClone(BUILT_IN_CONFIG.formatAst),
480
+ palettes: Object.fromEntries(
481
+ Object.entries(BUILT_IN_CONFIG.palettes).map(([name, colors]) => [name, { ...colors }]),
482
+ ),
483
+ modules: Object.fromEntries(
484
+ MODULE_NAMES.map((name) => [
485
+ name,
486
+ {
487
+ ...BUILT_IN_CONFIG.modules[name],
488
+ formatAst: structuredClone(BUILT_IN_CONFIG.modules[name].formatAst),
489
+ styles: { ...BUILT_IN_CONFIG.modules[name].styles },
490
+ display: structuredClone(BUILT_IN_CONFIG.modules[name].display),
491
+ options: structuredClone(BUILT_IN_CONFIG.modules[name].options),
492
+ },
493
+ ]),
494
+ ) as Record<ModuleName, ModuleConfig>,
495
+ extensionStatus: {
496
+ ...BUILT_IN_CONFIG.extensionStatus,
497
+ icons: { ...BUILT_IN_CONFIG.extensionStatus.icons },
498
+ },
499
+ };
550
500
  }
551
501
 
552
502
  function validateFormatVariables(
553
- ast: readonly FormatNode[],
554
- allowed: ReadonlySet<string>,
555
- path: string,
556
- diagnostics: ConfigDiagnostic[],
503
+ ast: readonly FormatNode[],
504
+ allowed: ReadonlySet<string>,
505
+ path: string,
506
+ diagnostics: ConfigDiagnostic[],
557
507
  ) {
558
- for (const variable of formatVariables(ast)) {
559
- if (allowed.has(variable)) continue;
560
- diagnostics.push(
561
- diagnostic(
562
- "warning",
563
- path,
564
- `Unknown variable ${JSON.stringify(variable)} in ${path} was ignored`,
565
- ),
566
- );
567
- }
508
+ for (const variable of formatVariables(ast)) {
509
+ if (allowed.has(variable)) continue;
510
+ diagnostics.push(
511
+ diagnostic("warning", path, `Unknown variable ${JSON.stringify(variable)} in ${path} was ignored`),
512
+ );
513
+ }
568
514
  }
569
515
 
570
516
  function validateStyleVariables(
571
- ast: readonly FormatNode[],
572
- allowed: ReadonlySet<string>,
573
- path: string,
574
- diagnostics: ConfigDiagnostic[],
517
+ ast: readonly FormatNode[],
518
+ allowed: ReadonlySet<string>,
519
+ path: string,
520
+ diagnostics: ConfigDiagnostic[],
575
521
  ) {
576
- for (const variable of styleVariables(ast)) {
577
- if (allowed.has(variable)) continue;
578
- diagnostics.push(
579
- diagnostic(
580
- "warning",
581
- path,
582
- `Unknown style variable ${JSON.stringify(variable)} in ${path} was ignored`,
583
- ),
584
- );
585
- }
522
+ for (const variable of styleVariables(ast)) {
523
+ if (allowed.has(variable)) continue;
524
+ diagnostics.push(
525
+ diagnostic("warning", path, `Unknown style variable ${JSON.stringify(variable)} in ${path} was ignored`),
526
+ );
527
+ }
586
528
  }
587
529
 
588
530
  function validateModuleStyleField(
589
- name: ModuleName,
590
- field: string,
591
- module: ModuleConfig,
592
- palette: ColorPalette,
593
- diagnostics: ConfigDiagnostic[],
531
+ name: ModuleName,
532
+ field: string,
533
+ module: ModuleConfig,
534
+ palette: ColorPalette,
535
+ diagnostics: ConfigDiagnostic[],
594
536
  ) {
595
- const style = field === "style" ? module.style : module.styles[field];
596
- if (style === undefined || isValidStyle(style, palette)) return;
597
- diagnostics.push(
598
- diagnostic(
599
- "warning",
600
- `${name}.${field}`,
601
- `Invalid style ${JSON.stringify(style)}; using the module default`,
602
- ),
603
- );
604
- if (field === "style") module.style = BUILT_IN_CONFIG.modules[name].style;
605
- else {
606
- const fallback = BUILT_IN_CONFIG.modules[name].styles[field];
607
- if (fallback !== undefined) module.styles[field] = fallback;
608
- }
537
+ const style = field === "style" ? module.style : module.styles[field];
538
+ if (style === undefined || isValidStyle(style, palette)) return;
539
+ diagnostics.push(
540
+ diagnostic("warning", `${name}.${field}`, `Invalid style ${JSON.stringify(style)}; using the module default`),
541
+ );
542
+ if (field === "style") module.style = BUILT_IN_CONFIG.modules[name].style;
543
+ else {
544
+ const fallback = BUILT_IN_CONFIG.modules[name].styles[field];
545
+ if (fallback !== undefined) module.styles[field] = fallback;
546
+ }
609
547
  }
610
548
 
611
549
  function normalizeDisplay(
612
- name: ModuleName,
613
- value: unknown,
614
- defaults: readonly ModuleDisplayConfig[],
615
- palette: ColorPalette,
616
- diagnostics: ConfigDiagnostic[],
550
+ name: ModuleName,
551
+ value: unknown,
552
+ defaults: readonly ModuleDisplayConfig[],
553
+ palette: ColorPalette,
554
+ diagnostics: ConfigDiagnostic[],
617
555
  ): ModuleDisplayConfig[] {
618
- if (!Array.isArray(value)) {
619
- diagnostics.push(typeDiagnostic(`${name}.display`, "array of tables"));
620
- return defaults.map((entry) => ({ ...entry }));
621
- }
622
- const result: ModuleDisplayConfig[] = [];
623
- for (const [index, entry] of value.entries()) {
624
- const path = `${name}.display.${index}`;
625
- if (!isRecord(entry)) {
626
- diagnostics.push(typeDiagnostic(path, "table"));
627
- continue;
628
- }
629
- for (const field of Object.keys(entry)) {
630
- if (!new Set(["threshold", "style", "hidden"]).has(field)) {
631
- diagnostics.push(unknownDiagnostic(`${path}.${field}`));
632
- }
633
- }
634
- let valid = true;
635
- if (typeof entry.threshold !== "number" || !Number.isFinite(entry.threshold)) {
636
- diagnostics.push(diagnostic("warning", `${path}.threshold`, "Expected a finite number"));
637
- valid = false;
638
- }
639
- if (typeof entry.style !== "string" || !isValidStyle(entry.style, palette)) {
640
- diagnostics.push(
641
- diagnostic("warning", `${path}.style`, "Expected a valid Starship style string"),
642
- );
643
- valid = false;
644
- }
645
- if (typeof entry.hidden !== "boolean") {
646
- diagnostics.push(typeDiagnostic(`${path}.hidden`, "boolean"));
647
- valid = false;
648
- }
649
- if (valid) {
650
- result.push({
651
- threshold: entry.threshold as number,
652
- style: entry.style as string,
653
- hidden: entry.hidden as boolean,
654
- });
655
- }
656
- }
657
- if (result.length > 0) return result;
658
- diagnostics.push(
659
- diagnostic("warning", `${name}.display`, "Expected at least one valid entry; using defaults"),
660
- );
661
- return defaults.map((entry) => ({ ...entry }));
556
+ if (!Array.isArray(value)) {
557
+ diagnostics.push(typeDiagnostic(`${name}.display`, "array of tables"));
558
+ return defaults.map((entry) => ({ ...entry }));
559
+ }
560
+ const result: ModuleDisplayConfig[] = [];
561
+ for (const [index, entry] of value.entries()) {
562
+ const path = `${name}.display.${index}`;
563
+ if (!isRecord(entry)) {
564
+ diagnostics.push(typeDiagnostic(path, "table"));
565
+ continue;
566
+ }
567
+ for (const field of Object.keys(entry)) {
568
+ if (!new Set(["threshold", "style", "hidden"]).has(field)) {
569
+ diagnostics.push(unknownDiagnostic(`${path}.${field}`));
570
+ }
571
+ }
572
+ let valid = true;
573
+ if (typeof entry.threshold !== "number" || !Number.isFinite(entry.threshold)) {
574
+ diagnostics.push(diagnostic("warning", `${path}.threshold`, "Expected a finite number"));
575
+ valid = false;
576
+ }
577
+ if (typeof entry.style !== "string" || !isValidStyle(entry.style, palette)) {
578
+ diagnostics.push(diagnostic("warning", `${path}.style`, "Expected a valid Starship style string"));
579
+ valid = false;
580
+ }
581
+ if (typeof entry.hidden !== "boolean") {
582
+ diagnostics.push(typeDiagnostic(`${path}.hidden`, "boolean"));
583
+ valid = false;
584
+ }
585
+ if (valid) {
586
+ result.push({
587
+ threshold: entry.threshold as number,
588
+ style: entry.style as string,
589
+ hidden: entry.hidden as boolean,
590
+ });
591
+ }
592
+ }
593
+ if (result.length > 0) return result;
594
+ diagnostics.push(diagnostic("warning", `${name}.display`, "Expected at least one valid entry; using defaults"));
595
+ return defaults.map((entry) => ({ ...entry }));
662
596
  }
663
597
 
664
598
  function validateLiteralStyles(
665
- ast: readonly FormatNode[],
666
- palette: ColorPalette,
667
- path: string,
668
- diagnostics: ConfigDiagnostic[],
599
+ ast: readonly FormatNode[],
600
+ palette: ColorPalette,
601
+ path: string,
602
+ diagnostics: ConfigDiagnostic[],
669
603
  ) {
670
- for (const node of ast) {
671
- if (node.type === "group" && node.style.every((part) => part.type === "text")) {
672
- const style = node.style.map((part) => (part.type === "text" ? part.value : "")).join("");
673
- if (!isValidStyle(style, palette)) {
674
- diagnostics.push(
675
- diagnostic(
676
- "warning",
677
- path,
678
- `Invalid literal style ${JSON.stringify(style)}; rendered unstyled`,
679
- ),
680
- );
681
- }
682
- }
683
- if (node.type === "group" || node.type === "conditional") {
684
- validateLiteralStyles(node.children, palette, path, diagnostics);
685
- }
686
- }
604
+ for (const node of ast) {
605
+ if (node.type === "group" && node.style.every((part) => part.type === "text")) {
606
+ const style = node.style.map((part) => (part.type === "text" ? part.value : "")).join("");
607
+ if (!isValidStyle(style, palette)) {
608
+ diagnostics.push(
609
+ diagnostic("warning", path, `Invalid literal style ${JSON.stringify(style)}; rendered unstyled`),
610
+ );
611
+ }
612
+ }
613
+ if (node.type === "group" || node.type === "conditional") {
614
+ validateLiteralStyles(node.children, palette, path, diagnostics);
615
+ }
616
+ }
687
617
  }
688
618
 
689
619
  function normalizeModuleOption(
690
- value: unknown,
691
- schema: ModuleOptionSchema,
620
+ value: unknown,
621
+ schema: ModuleOptionSchema,
692
622
  ): { ok: true; value: ModuleOptionValue } | { ok: false; message: string } {
693
- switch (schema.kind) {
694
- case "string":
695
- return typeof value === "string" && (schema.allowEmpty !== false || value.length > 0)
696
- ? { ok: true, value }
697
- : { ok: false, message: "Expected a non-empty string; using the default value" };
698
- case "string-enum":
699
- return typeof value === "string" && schema.values.includes(value)
700
- ? { ok: true, value }
701
- : {
702
- ok: false,
703
- message: `Expected one of: ${schema.values.join(", ")}; using the default value`,
704
- };
705
- case "boolean":
706
- return typeof value === "boolean"
707
- ? { ok: true, value }
708
- : { ok: false, message: "Expected boolean; using the default value" };
709
- case "integer":
710
- return typeof value === "number" &&
711
- Number.isInteger(value) &&
712
- value >= schema.minimum &&
713
- value <= schema.maximum
714
- ? { ok: true, value }
715
- : {
716
- ok: false,
717
- message: `Expected an integer from ${schema.minimum} through ${schema.maximum}; using the default value`,
718
- };
719
- case "string-array": {
720
- if (
721
- !Array.isArray(value) ||
722
- value.some(
723
- (item) =>
724
- typeof item !== "string" ||
725
- item.length === 0 ||
726
- (!schema.allowNegative && item.startsWith("!")),
727
- )
728
- ) {
729
- return {
730
- ok: false,
731
- message: "Expected an array of valid strings; using the default value",
732
- };
733
- }
734
- return { ok: true, value: [...value] as string[] };
735
- }
736
- case "string-map": {
737
- if (!isRecord(value) || Object.values(value).some((item) => typeof item !== "string")) {
738
- return { ok: false, message: "Expected a table of strings; using the default value" };
739
- }
740
- const result: Record<string, string> = {};
741
- for (const [key, item] of Object.entries(value)) setOwn(result, key, item as string);
742
- return { ok: true, value: result };
743
- }
744
- }
623
+ switch (schema.kind) {
624
+ case "string":
625
+ return typeof value === "string" && (schema.allowEmpty !== false || value.length > 0)
626
+ ? { ok: true, value }
627
+ : { ok: false, message: "Expected a non-empty string; using the default value" };
628
+ case "string-enum":
629
+ return typeof value === "string" && schema.values.includes(value)
630
+ ? { ok: true, value }
631
+ : {
632
+ ok: false,
633
+ message: `Expected one of: ${schema.values.join(", ")}; using the default value`,
634
+ };
635
+ case "boolean":
636
+ return typeof value === "boolean"
637
+ ? { ok: true, value }
638
+ : { ok: false, message: "Expected boolean; using the default value" };
639
+ case "integer":
640
+ return typeof value === "number" && Number.isInteger(value) && value >= schema.minimum && value <= schema.maximum
641
+ ? { ok: true, value }
642
+ : {
643
+ ok: false,
644
+ message: `Expected an integer from ${schema.minimum} through ${schema.maximum}; using the default value`,
645
+ };
646
+ case "string-array": {
647
+ if (
648
+ !Array.isArray(value) ||
649
+ value.some(
650
+ (item) => typeof item !== "string" || item.length === 0 || (!schema.allowNegative && item.startsWith("!")),
651
+ )
652
+ ) {
653
+ return {
654
+ ok: false,
655
+ message: "Expected an array of valid strings; using the default value",
656
+ };
657
+ }
658
+ return { ok: true, value: [...value] as string[] };
659
+ }
660
+ case "string-map": {
661
+ if (!isRecord(value) || Object.values(value).some((item) => typeof item !== "string")) {
662
+ return { ok: false, message: "Expected a table of strings; using the default value" };
663
+ }
664
+ const result: Record<string, string> = {};
665
+ for (const [key, item] of Object.entries(value)) setOwn(result, key, item as string);
666
+ return { ok: true, value: result };
667
+ }
668
+ }
745
669
  }
746
670
 
747
671
  function cloneOptionValue(value: ModuleOptionValue): ModuleOptionValue {
748
- return typeof value === "object" ? structuredClone(value) : value;
672
+ return typeof value === "object" ? structuredClone(value) : value;
749
673
  }
750
674
 
751
675
  function setOwn<T>(record: Record<string, T>, key: string, value: T) {
752
- Object.defineProperty(record, key, {
753
- value,
754
- writable: true,
755
- enumerable: true,
756
- configurable: true,
757
- });
676
+ Object.defineProperty(record, key, {
677
+ value,
678
+ writable: true,
679
+ enumerable: true,
680
+ configurable: true,
681
+ });
758
682
  }
759
683
 
760
684
  function isRecord(value: unknown): value is Record<string, unknown> {
761
- return typeof value === "object" && value !== null && !Array.isArray(value);
685
+ return typeof value === "object" && value !== null && !Array.isArray(value);
762
686
  }
763
687
 
764
688
  function typeDiagnostic(path: string, type: string): ConfigDiagnostic {
765
- return diagnostic("warning", path, `Expected ${type}; using the default value`);
689
+ return diagnostic("warning", path, `Expected ${type}; using the default value`);
766
690
  }
767
691
 
768
692
  function unknownDiagnostic(path: string): ConfigDiagnostic {
769
- return diagnostic("warning", path, `Unknown setting ${JSON.stringify(path)} was ignored`);
693
+ return diagnostic("warning", path, `Unknown setting ${JSON.stringify(path)} was ignored`);
770
694
  }
771
695
 
772
- function diagnostic(
773
- severity: ConfigDiagnostic["severity"],
774
- path: string,
775
- message: string,
776
- ): ConfigDiagnostic {
777
- return { severity, path, message };
696
+ function diagnostic(severity: ConfigDiagnostic["severity"], path: string, message: string): ConfigDiagnostic {
697
+ return { severity, path, message };
778
698
  }
779
699
 
780
700
  function pathEntryExists(path: string): boolean {
781
- try {
782
- lstatSync(path);
783
- return true;
784
- } catch (error) {
785
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
786
- throw error;
787
- }
701
+ try {
702
+ lstatSync(path);
703
+ return true;
704
+ } catch (error) {
705
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
706
+ throw error;
707
+ }
788
708
  }
789
709
 
790
710
  function formatError(error: unknown): string {
791
- return error instanceof Error ? error.message : String(error);
711
+ return error instanceof Error ? error.message : String(error);
792
712
  }
793
713
 
794
714
  export function activePalette(config: StarshipConfig): ColorPalette {
795
- return ownPalette(config.palettes, config.palette) ?? {};
715
+ return ownPalette(config.palettes, config.palette) ?? {};
796
716
  }
797
717
 
798
718
  function ownPalette(
799
- palettes: Readonly<Record<string, Record<string, string>>>,
800
- name: string | undefined,
719
+ palettes: Readonly<Record<string, Record<string, string>>>,
720
+ name: string | undefined,
801
721
  ): Record<string, string> | undefined {
802
- return name !== undefined && Object.hasOwn(palettes, name) ? palettes[name] : undefined;
722
+ return name !== undefined && Object.hasOwn(palettes, name) ? palettes[name] : undefined;
803
723
  }