file-config.adapter.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. // File Config Adapter - Load and patch JSON configuration files
  2. import {
  3. existsSync,
  4. readFileSync,
  5. renameSync,
  6. unlinkSync,
  7. writeFileSync,
  8. } from "node:fs";
  9. import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
  10. import { homedir } from "node:os";
  11. import { basename, dirname, join, resolve } from "node:path";
  12. import type { RuntimeConfigPatch, UiLocale } from "@zcode/contracts";
  13. import { z } from "zod";
  14. import {
  15. CANONICAL_CUA_PLUGIN_ID,
  16. canonicalizePluginId,
  17. LEGACY_CUA_PLUGIN_ID,
  18. parseConfigFileToRuntimePatchWithDiagnostics,
  19. pluginIdAliases,
  20. type ConfigDiagnostic,
  21. } from "./schema.js";
  22. interface FileConfigOptions {
  23. baseDir?: string;
  24. configFileName?: string;
  25. scope?: "user" | "project";
  26. }
  27. export interface LoadedConfig {
  28. config: RuntimeConfigPatch;
  29. diagnostics: ConfigDiagnostic[];
  30. path: string;
  31. loaded: boolean;
  32. }
  33. export interface UiLocalePatchResult {
  34. locale: UiLocale;
  35. path: string;
  36. }
  37. export interface PluginEnabledPatchResult {
  38. enabled: boolean;
  39. path: string;
  40. pluginId: string;
  41. }
  42. export interface PluginOptionsPatchResult {
  43. clearedOptionKeys: string[];
  44. options: Record<string, string | number | boolean>;
  45. path: string;
  46. pluginId: string;
  47. }
  48. export interface PluginRemovePatchResult {
  49. path: string;
  50. pluginId: string;
  51. removedEnabled: boolean;
  52. removedOptions: boolean;
  53. }
  54. const DEFAULT_CONFIG_FILE = "config.json";
  55. const DEFAULT_BASE_DIR = "~/.zcode/cli";
  56. /**
  57. * Resolve path with ~ expansion
  58. */
  59. export function resolvePath(path: string): string {
  60. if (path.startsWith("~/")) {
  61. return join(homedir(), path.slice(2));
  62. }
  63. return resolve(path);
  64. }
  65. /**
  66. * Load configuration from a JSON file
  67. */
  68. export function loadFileConfig(filePath?: string, options: FileConfigOptions = {}): LoadedConfig {
  69. const resolvedPath = filePath
  70. ? resolvePath(filePath)
  71. : join(
  72. resolvePath(options.baseDir ?? DEFAULT_BASE_DIR),
  73. options.configFileName ?? DEFAULT_CONFIG_FILE,
  74. );
  75. if (!existsSync(resolvedPath)) {
  76. return {
  77. config: {},
  78. diagnostics: [],
  79. path: resolvedPath,
  80. loaded: false,
  81. };
  82. }
  83. try {
  84. const content = readFileSync(resolvedPath, "utf-8");
  85. const parsed = JSON.parse(content);
  86. const migrated = migratePluginConfigInFile(parsed);
  87. if (migrated) {
  88. // 仅装载态归一化会让旧 key 永久留在磁盘,后续版本无法安全删除迁移逻辑。
  89. persistPluginConfigMigration(resolvedPath, migrated);
  90. }
  91. const result = parseConfigFileToRuntimePatchWithDiagnostics(parsed, options.scope);
  92. return {
  93. config: result.config,
  94. diagnostics: attachDiagnosticFilePath(result.diagnostics, resolvedPath),
  95. path: resolvedPath,
  96. loaded: true,
  97. };
  98. } catch (error) {
  99. return {
  100. config: {},
  101. diagnostics: [createConfigFileInvalidDiagnostic(error, resolvedPath)],
  102. path: resolvedPath,
  103. loaded: false,
  104. };
  105. }
  106. }
  107. function migratePluginConfigInFile(value: unknown): Record<string, unknown> | undefined {
  108. if (!isRecord(value) || !isRecord(value.plugins)) return undefined;
  109. const plugins = value.plugins;
  110. const nextPlugins = { ...plugins };
  111. let changed = false;
  112. if (isRecord(plugins.enabledPlugins)) {
  113. const enabledPlugins = { ...plugins.enabledPlugins };
  114. for (const [id, enabled] of Object.entries(plugins.enabledPlugins)) {
  115. if (id === LEGACY_CUA_PLUGIN_ID) {
  116. const canonicalId = CANONICAL_CUA_PLUGIN_ID;
  117. if (enabledPlugins[canonicalId] === undefined) enabledPlugins[canonicalId] = enabled;
  118. delete enabledPlugins[id];
  119. changed = true;
  120. }
  121. }
  122. if (changed) nextPlugins.enabledPlugins = enabledPlugins;
  123. }
  124. if (Array.isArray(plugins.suppressedBuiltins)) {
  125. const suppressedBuiltins = plugins.suppressedBuiltins.map((id) =>
  126. id === LEGACY_CUA_PLUGIN_ID ? CANONICAL_CUA_PLUGIN_ID : id,
  127. );
  128. if (JSON.stringify(suppressedBuiltins) !== JSON.stringify(plugins.suppressedBuiltins)) {
  129. nextPlugins.suppressedBuiltins = suppressedBuiltins;
  130. changed = true;
  131. }
  132. }
  133. if (isRecord(plugins.options)) {
  134. const options = { ...plugins.options };
  135. for (const [id, pluginOptions] of Object.entries(plugins.options)) {
  136. if (id === LEGACY_CUA_PLUGIN_ID) {
  137. const canonicalId = CANONICAL_CUA_PLUGIN_ID;
  138. if (options[canonicalId] === undefined) options[canonicalId] = pluginOptions;
  139. delete options[id];
  140. changed = true;
  141. }
  142. }
  143. if (changed) nextPlugins.options = options;
  144. }
  145. return changed ? { ...value, plugins: nextPlugins } : undefined;
  146. }
  147. function persistPluginConfigMigration(
  148. filePath: string,
  149. value: Record<string, unknown>,
  150. ): void {
  151. const tempPath = `${filePath}.migrate.${process.pid}.${Date.now()}.tmp`;
  152. try {
  153. writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, {
  154. encoding: "utf-8",
  155. mode: 0o600,
  156. });
  157. renameSync(tempPath, filePath);
  158. } catch {
  159. // 迁移写回是 best-effort 副作用,失败不能改变合法配置的装载语义。
  160. try {
  161. unlinkSync(tempPath);
  162. } catch {
  163. // 临时文件清理失败不影响当前配置装载。
  164. }
  165. }
  166. }
  167. function createConfigFileInvalidDiagnostic(error: unknown, filePath: string): ConfigDiagnostic {
  168. return {
  169. code: "config_file_invalid",
  170. filePath,
  171. message:
  172. error instanceof z.ZodError
  173. ? formatZodError(error)
  174. : error instanceof Error
  175. ? error.message
  176. : "Unable to parse config file.",
  177. severity: "error",
  178. };
  179. }
  180. function attachDiagnosticFilePath(
  181. diagnostics: ConfigDiagnostic[],
  182. filePath: string,
  183. ): ConfigDiagnostic[] {
  184. return diagnostics.map((diagnostic) => ({
  185. ...diagnostic,
  186. filePath: diagnostic.filePath ?? filePath,
  187. }));
  188. }
  189. function formatZodError(error: z.ZodError): string {
  190. return error.issues
  191. .map((issue) => {
  192. const path = issue.path.length > 0 ? issue.path.join(".") : "<config>";
  193. return `${path}: ${issue.message}`;
  194. })
  195. .join("; ");
  196. }
  197. /**
  198. * Patch only the UI locale selection in a JSON config file.
  199. */
  200. export async function updateUiLocaleInFileConfig(
  201. filePath: string,
  202. locale: UiLocale,
  203. ): Promise<UiLocalePatchResult> {
  204. const resolvedPath = resolvePath(filePath);
  205. const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
  206. const next = patchUiLocale(parsed, locale);
  207. await atomicWriteJson(resolvedPath, next);
  208. return {
  209. locale,
  210. path: resolvedPath,
  211. };
  212. }
  213. /**
  214. * Patch the user plugin enabled map without touching plugin installation state.
  215. */
  216. export async function updatePluginEnabledInFileConfig(
  217. filePath: string,
  218. pluginId: string,
  219. enabled: boolean,
  220. ): Promise<PluginEnabledPatchResult> {
  221. const resolvedPath = resolvePath(filePath);
  222. const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
  223. const next = patchPluginEnabled(parsed, pluginId, enabled);
  224. await atomicWriteJson(resolvedPath, next);
  225. return {
  226. enabled,
  227. path: resolvedPath,
  228. pluginId,
  229. };
  230. }
  231. /**
  232. * Mark freshly installed plugins as enabled by default, in a single atomic write.
  233. *
  234. * 设计:安装即默认启用(仅对本次安装的插件 + 其依赖闭包生效)。这里只对**用户配置里尚未显式声明**
  235. * 的 id 写入 `true`——若用户先前显式停用过(例如停用后重装),尊重其选择不覆盖;已是 true 的也跳过。
  236. * 一次性读改写,避免逐个 id 反复读写配置文件。返回真正被新置为启用的 id 列表,便于上层据此决定是否回写。
  237. */
  238. export async function enablePluginsByDefaultInFileConfig(
  239. filePath: string,
  240. pluginIds: readonly string[],
  241. ): Promise<{ enabledIds: string[]; path: string }> {
  242. const resolvedPath = resolvePath(filePath);
  243. if (pluginIds.length === 0) {
  244. return { enabledIds: [], path: resolvedPath };
  245. }
  246. const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
  247. const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
  248. const enabledPlugins = isRecord(plugins.enabledPlugins) ? plugins.enabledPlugins : {};
  249. const enabledIds = pluginIds.filter(
  250. (id) => !Object.prototype.hasOwnProperty.call(enabledPlugins, id),
  251. );
  252. if (enabledIds.length === 0) {
  253. return { enabledIds: [], path: resolvedPath };
  254. }
  255. const next = {
  256. ...parsed,
  257. plugins: {
  258. ...plugins,
  259. enabledPlugins: {
  260. ...enabledPlugins,
  261. ...Object.fromEntries(enabledIds.map((id) => [id, true])),
  262. },
  263. },
  264. };
  265. await atomicWriteJson(resolvedPath, next);
  266. return { enabledIds, path: resolvedPath };
  267. }
  268. /**
  269. * Patch plugin user options without touching plugin installation state.
  270. */
  271. export async function updatePluginOptionsInFileConfig(
  272. filePath: string,
  273. pluginId: string,
  274. options: Record<string, string | number | boolean>,
  275. clearOptionKeys: string[] = [],
  276. ): Promise<PluginOptionsPatchResult> {
  277. const resolvedPath = resolvePath(filePath);
  278. const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
  279. const next = patchPluginOptions(parsed, pluginId, options, clearOptionKeys);
  280. await atomicWriteJson(resolvedPath, next);
  281. return {
  282. clearedOptionKeys: clearOptionKeys,
  283. options,
  284. path: resolvedPath,
  285. pluginId,
  286. };
  287. }
  288. /**
  289. * Remove a plugin's user config footprint when it is uninstalled.
  290. *
  291. * Uninstall is a thorough teardown, so it
  292. * must drop both the `plugins.enabledPlugins[id]` flag and any saved
  293. * `plugins.options[id]`. updatePluginEnabledInFileConfig/...Options can only set
  294. * values; deleting the keys needs its own patch so a reinstall starts clean.
  295. */
  296. export async function removePluginFromFileConfig(
  297. filePath: string,
  298. pluginId: string,
  299. ): Promise<PluginRemovePatchResult> {
  300. const resolvedPath = resolvePath(filePath);
  301. const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
  302. const { next, removedEnabled, removedOptions } = patchPluginRemoved(parsed, pluginId);
  303. if (removedEnabled || removedOptions) {
  304. await atomicWriteJson(resolvedPath, next);
  305. }
  306. return {
  307. path: resolvedPath,
  308. pluginId,
  309. removedEnabled,
  310. removedOptions,
  311. };
  312. }
  313. /**
  314. * 只删除 Plugin 的启用覆盖并保留 options。
  315. *
  316. * Workspace“恢复继承”是配置视图操作,只应删除 Workspace 的启用覆盖,不能误删
  317. * 单独保存的 Workspace options 或 secret。
  318. */
  319. export async function removePluginEnabledFromFileConfig(
  320. filePath: string,
  321. pluginId: string,
  322. ): Promise<{ path: string; pluginId: string; removedEnabled: boolean }> {
  323. const resolvedPath = resolvePath(filePath);
  324. const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
  325. const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
  326. const enabledPlugins = isRecord(plugins.enabledPlugins) ? plugins.enabledPlugins : {};
  327. const aliases = pluginIdAliases(pluginId);
  328. const removedEnabled = aliases.some((id) =>
  329. Object.prototype.hasOwnProperty.call(enabledPlugins, id),
  330. );
  331. if (!removedEnabled) {
  332. return { path: resolvedPath, pluginId, removedEnabled: false };
  333. }
  334. const nextEnabled = { ...enabledPlugins };
  335. for (const id of aliases) delete nextEnabled[id];
  336. await atomicWriteJson(resolvedPath, {
  337. ...parsed,
  338. plugins: {
  339. ...plugins,
  340. enabledPlugins: nextEnabled,
  341. },
  342. });
  343. return { path: resolvedPath, pluginId, removedEnabled: true };
  344. }
  345. export interface SuppressedBuiltinPatchResult {
  346. path: string;
  347. pluginId: string;
  348. suppressed: boolean;
  349. }
  350. /**
  351. * Persist that a built-in (official) plugin is uninstalled, so seeding skips it
  352. * across restarts and app upgrades. Idempotent. Stored in user config beside
  353. * enabledPlugins so it survives bundle re-seeds.
  354. */
  355. export async function addSuppressedBuiltinInFileConfig(
  356. filePath: string,
  357. pluginId: string,
  358. ): Promise<SuppressedBuiltinPatchResult> {
  359. const resolvedPath = resolvePath(filePath);
  360. const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
  361. const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
  362. const canonicalPluginId = canonicalizePluginId(pluginId);
  363. const aliases = pluginIdAliases(canonicalPluginId);
  364. const current = Array.isArray(plugins.suppressedBuiltins)
  365. ? (plugins.suppressedBuiltins as unknown[]).filter((v): v is string => typeof v === "string")
  366. : [];
  367. const retained = current.filter((id) => !aliases.includes(id));
  368. if (retained.length === current.length && current.includes(canonicalPluginId)) {
  369. return { path: resolvedPath, pluginId, suppressed: true };
  370. }
  371. const next = {
  372. ...parsed,
  373. plugins: { ...plugins, suppressedBuiltins: [...retained, canonicalPluginId] },
  374. };
  375. await atomicWriteJson(resolvedPath, next);
  376. return { path: resolvedPath, pluginId, suppressed: true };
  377. }
  378. /**
  379. * Reverse of addSuppressedBuiltinInFileConfig: restore a built-in by dropping its
  380. * suppression marker. The seeder re-materializes it on the next resolve.
  381. */
  382. export async function removeSuppressedBuiltinInFileConfig(
  383. filePath: string,
  384. pluginId: string,
  385. ): Promise<SuppressedBuiltinPatchResult> {
  386. const resolvedPath = resolvePath(filePath);
  387. const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
  388. const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
  389. const aliases = pluginIdAliases(pluginId);
  390. const current = Array.isArray(plugins.suppressedBuiltins)
  391. ? (plugins.suppressedBuiltins as unknown[]).filter((v): v is string => typeof v === "string")
  392. : [];
  393. const nextSuppressedBuiltins = current.filter((id) => !aliases.includes(id));
  394. if (nextSuppressedBuiltins.length === current.length) {
  395. return { path: resolvedPath, pluginId, suppressed: false };
  396. }
  397. const next = {
  398. ...parsed,
  399. plugins: { ...plugins, suppressedBuiltins: nextSuppressedBuiltins },
  400. };
  401. await atomicWriteJson(resolvedPath, next);
  402. return { path: resolvedPath, pluginId, suppressed: false };
  403. }
  404. /**
  405. * Get default config file path
  406. */
  407. export function getDefaultConfigPath(): string {
  408. return join(resolvePath(DEFAULT_BASE_DIR), DEFAULT_CONFIG_FILE);
  409. }
  410. /**
  411. * Check if config file exists at default location
  412. */
  413. export function hasDefaultConfigFile(): boolean {
  414. return existsSync(getDefaultConfigPath());
  415. }
  416. async function readJsonConfigFile(filePath: string): Promise<Record<string, unknown>> {
  417. let content: string;
  418. try {
  419. content = await readFile(filePath, "utf-8");
  420. } catch (error) {
  421. throw new Error(`Unable to read config file: ${filePath}`, { cause: error });
  422. }
  423. let parsed: unknown;
  424. try {
  425. parsed = JSON.parse(content);
  426. } catch (error) {
  427. throw new Error(`Unable to parse config file as JSON: ${filePath}`, { cause: error });
  428. }
  429. if (!isRecord(parsed)) {
  430. throw new Error(`Config file must contain a JSON object: ${filePath}`);
  431. }
  432. return parsed;
  433. }
  434. async function readJsonConfigFileOrEmpty(filePath: string): Promise<Record<string, unknown>> {
  435. try {
  436. return await readJsonConfigFile(filePath);
  437. } catch (error) {
  438. const cause = error instanceof Error ? error.cause : undefined;
  439. if (isNodeError(cause) && cause.code === "ENOENT") {
  440. return {};
  441. }
  442. throw error;
  443. }
  444. }
  445. function patchUiLocale(parsed: Record<string, unknown>, locale: UiLocale): Record<string, unknown> {
  446. const currentUi = isRecord(parsed.ui) ? parsed.ui : {};
  447. return {
  448. ...parsed,
  449. ui: {
  450. ...currentUi,
  451. locale,
  452. },
  453. };
  454. }
  455. function patchPluginEnabled(
  456. parsed: Record<string, unknown>,
  457. pluginId: string,
  458. enabled: boolean,
  459. ): Record<string, unknown> {
  460. const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
  461. const enabledPlugins = isRecord(plugins.enabledPlugins) ? plugins.enabledPlugins : {};
  462. const canonicalPluginId = canonicalizePluginId(pluginId);
  463. const nextEnabledPlugins = { ...enabledPlugins };
  464. for (const id of pluginIdAliases(canonicalPluginId)) delete nextEnabledPlugins[id];
  465. return {
  466. ...parsed,
  467. plugins: {
  468. ...plugins,
  469. enabledPlugins: {
  470. ...nextEnabledPlugins,
  471. [canonicalPluginId]: enabled,
  472. },
  473. },
  474. };
  475. }
  476. function patchPluginOptions(
  477. parsed: Record<string, unknown>,
  478. pluginId: string,
  479. options: Record<string, string | number | boolean>,
  480. clearOptionKeys: string[],
  481. ): Record<string, unknown> {
  482. const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
  483. const currentOptions = isRecord(plugins.options) ? plugins.options : {};
  484. const canonicalPluginId = canonicalizePluginId(pluginId);
  485. const aliases = pluginIdAliases(canonicalPluginId);
  486. const legacyPluginId = aliases.length > 1 ? aliases[1] : undefined;
  487. const currentPluginOptions = isRecord(currentOptions[canonicalPluginId])
  488. ? currentOptions[canonicalPluginId]
  489. : legacyPluginId && isRecord(currentOptions[legacyPluginId])
  490. ? currentOptions[legacyPluginId]
  491. : {};
  492. const nextOptions = { ...currentOptions };
  493. for (const id of aliases) delete nextOptions[id];
  494. const clearedOptionKeySet = new Set(clearOptionKeys);
  495. const retainedPluginOptions = Object.fromEntries(
  496. Object.entries(currentPluginOptions).filter(([key]) => !clearedOptionKeySet.has(key)),
  497. );
  498. return {
  499. ...parsed,
  500. plugins: {
  501. ...plugins,
  502. options: {
  503. ...nextOptions,
  504. // 敏感字段按脱敏合同不会回传 UI,二次保存普通字段时请求中自然缺少
  505. // 已存 secret。这里按 option key 合并,避免整对象替换把同 scope 的密钥静默清空。
  506. // 显式清除走 clearOptionKeys,先删除指定键,再合并本次输入;不会连带删除启用状态
  507. // 或同插件的其他配置。
  508. [canonicalPluginId]: {
  509. ...retainedPluginOptions,
  510. ...options,
  511. },
  512. },
  513. },
  514. };
  515. }
  516. function patchPluginRemoved(
  517. parsed: Record<string, unknown>,
  518. pluginId: string,
  519. ): { next: Record<string, unknown>; removedEnabled: boolean; removedOptions: boolean } {
  520. const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
  521. const enabledPlugins = isRecord(plugins.enabledPlugins) ? plugins.enabledPlugins : {};
  522. const options = isRecord(plugins.options) ? plugins.options : {};
  523. const aliases = pluginIdAliases(pluginId);
  524. const removedEnabled = aliases.some((id) => id in enabledPlugins);
  525. const removedOptions = aliases.some((id) => id in options);
  526. if (!removedEnabled && !removedOptions) {
  527. return { next: parsed, removedEnabled, removedOptions };
  528. }
  529. const nextEnabled = { ...enabledPlugins };
  530. for (const id of aliases) delete nextEnabled[id];
  531. const nextOptions = { ...options };
  532. for (const id of aliases) delete nextOptions[id];
  533. return {
  534. next: {
  535. ...parsed,
  536. plugins: {
  537. ...plugins,
  538. enabledPlugins: nextEnabled,
  539. options: nextOptions,
  540. },
  541. },
  542. removedEnabled,
  543. removedOptions,
  544. };
  545. }
  546. async function atomicWriteJson(filePath: string, value: Record<string, unknown>): Promise<void> {
  547. const directory = dirname(filePath);
  548. await mkdir(directory, { recursive: true });
  549. const tempPath = join(
  550. directory,
  551. `.${basename(filePath)}.${process.pid}.${Date.now()}.${Math.random()
  552. .toString(16)
  553. .slice(2)}.tmp`,
  554. );
  555. const content = `${JSON.stringify(value, null, 2)}\n`;
  556. try {
  557. await writeFile(tempPath, content, { mode: 0o600 });
  558. await rename(tempPath, filePath);
  559. } catch (error) {
  560. await unlink(tempPath).catch(() => undefined);
  561. throw new Error(`Unable to write config file: ${filePath}`, { cause: error });
  562. }
  563. }
  564. function isRecord(value: unknown): value is Record<string, unknown> {
  565. return typeof value === "object" && value !== null && !Array.isArray(value);
  566. }
  567. function isNodeError(value: unknown): value is NodeJS.ErrnoException {
  568. return value instanceof Error && "code" in value;
  569. }