skillService.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
  2. import { basename, dirname, join, relative, resolve, sep } from 'node:path';
  3. import { randomUUID } from 'node:crypto';
  4. import { fromBuffer, type Entry, type ZipFile } from 'yauzl';
  5. import { getSkillsDir, isInsideDir, MAX_SKILL_NAME_LENGTH, SKILL_NAME_PATTERN } from './codexHome';
  6. import type { CodexRuntime, CodexSkillSummary, JsonValue } from './codexRuntime';
  7. /**
  8. * Skill 的文件层管理。Codex app-server 只给了 skills/list 与 skills/config/write(启停),
  9. * 没有安装/卸载接口,所以目录的增删由本模块负责,启停仍走原生 RPC。
  10. *
  11. * 目录布局:<CODEX_HOME>/skills/<kebab-name>/SKILL.md(+ 可选 agents/ scripts/ references/ assets/)。
  12. * Codex 会把内置 skill 实体化到同级的 .system/.curated/.experimental,这些一律不可删改。
  13. */
  14. const MAX_ENTRY_COUNT = 300;
  15. const MAX_FILE_BYTES = 2 * 1024 * 1024;
  16. const MAX_TOTAL_BYTES = 25 * 1024 * 1024;
  17. const MAX_SKILL_MD_BYTES = 64 * 1024;
  18. const SKILL_FILE_NAME = 'SKILL.md';
  19. const STAGING_PREFIX = '.staging-';
  20. const ALLOWED_EXTENSIONS = new Set([
  21. 'md', 'txt', 'json', 'yaml', 'yml', 'toml',
  22. 'py', 'js', 'mjs', 'cjs', 'ts', 'sh', 'ps1', 'bat',
  23. 'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'csv',
  24. ]);
  25. export interface SkillListItem extends CodexSkillSummary {
  26. /** 是否落在本模块可管理的用户目录里(内置 skill 为 false,不允许删除) */
  27. managed: boolean;
  28. }
  29. export interface SkillFileEntry {
  30. path: string;
  31. size: number;
  32. }
  33. export interface SkillReadResult {
  34. dir: string;
  35. content: string;
  36. files: SkillFileEntry[];
  37. }
  38. export interface SkillInstallOptions {
  39. /** 覆盖 frontmatter 里的 name;不传则用 frontmatter 的 name */
  40. name?: string | null;
  41. overwrite?: boolean;
  42. }
  43. export interface SkillTarget {
  44. path?: string | null;
  45. name?: string | null;
  46. }
  47. type SkillRuntime = Pick<CodexRuntime, 'listSkills' | 'setSkillEnabled'> &
  48. Partial<Pick<CodexRuntime, 'readConfig' | 'writeConfigValue'>>;
  49. export interface SkillServiceOptions {
  50. /** 默认取 <CODEX_HOME>/skills;单测注入临时目录 */
  51. skillsDir?: string;
  52. /** 非致命问题的上报口(诊断日志),避免异常被静默吞掉 */
  53. onDiagnostic?: (line: string) => void;
  54. }
  55. export class SkillService {
  56. readonly #runtime: SkillRuntime;
  57. readonly #skillsDir: string;
  58. readonly #options: SkillServiceOptions;
  59. constructor(runtime: SkillRuntime, options: SkillServiceOptions = {}) {
  60. this.#runtime = runtime;
  61. this.#options = options;
  62. this.#skillsDir = options.skillsDir ?? getSkillsDir();
  63. }
  64. get skillsDir(): string {
  65. return this.#skillsDir;
  66. }
  67. async list(options: { forceReload?: boolean } = {}): Promise<SkillListItem[]> {
  68. const skills = await this.#runtime.listSkills({ forceReload: options.forceReload ?? false });
  69. return skills.map((skill) => ({
  70. ...skill,
  71. managed: isManagedSkillPath(this.#skillsDir, skill.path),
  72. }));
  73. }
  74. async setEnabled(target: SkillTarget, enabled: boolean): Promise<boolean> {
  75. const selector = await this.#resolveSelector(target);
  76. return this.#runtime.setSkillEnabled(selector, enabled);
  77. }
  78. async read(target: SkillTarget): Promise<SkillReadResult> {
  79. const dir = await this.#resolveManagedDir(target);
  80. const content = await readFile(join(dir, SKILL_FILE_NAME), 'utf8');
  81. const files = await collectFiles(dir);
  82. return { dir, content, files };
  83. }
  84. /** 从一个已存在的目录安装(配合 osCtl.selectDirectory 选目录) */
  85. async installFromFolder(srcPath: string, options: SkillInstallOptions = {}): Promise<SkillListItem[]> {
  86. const source = resolve(srcPath);
  87. const sourceStat = await stat(source).catch(() => null);
  88. if (!sourceStat?.isDirectory()) throw new Error('源路径不是一个目录');
  89. const staging = await this.#createStagingDir();
  90. try {
  91. const manifest = await copyFolderChecked(source, staging);
  92. const name = await finalizeStagedSkill(staging, manifest, options);
  93. await this.#promoteStaging(staging, name, options.overwrite === true);
  94. } catch (error) {
  95. await rm(staging, { recursive: true, force: true }).catch(() => undefined);
  96. throw error;
  97. }
  98. return this.list({ forceReload: true });
  99. }
  100. /** 从 zip 字节安装(渲染进程读文件后把字节传过来,主进程不需要拿到本机路径) */
  101. async installFromZip(data: Uint8Array, options: SkillInstallOptions = {}): Promise<SkillListItem[]> {
  102. if (!data || data.byteLength === 0) throw new Error('zip 内容为空');
  103. if (data.byteLength > MAX_TOTAL_BYTES) throw new Error(`zip 超过 ${MAX_TOTAL_BYTES / 1024 / 1024} MiB 上限`);
  104. const staging = await this.#createStagingDir();
  105. try {
  106. const manifest = await extractZipChecked(data, staging);
  107. const root = await resolveZipRoot(staging, manifest);
  108. const name = await finalizeStagedSkill(root, manifest, options);
  109. await this.#promoteStaging(staging, name, options.overwrite === true, root);
  110. } catch (error) {
  111. await rm(staging, { recursive: true, force: true }).catch(() => undefined);
  112. throw error;
  113. }
  114. return this.list({ forceReload: true });
  115. }
  116. async remove(target: SkillTarget): Promise<SkillListItem[]> {
  117. const dir = await this.#resolveManagedDir(target);
  118. await rm(dir, { recursive: true, force: true });
  119. await this.#clearStaleConfig(dir, basename(dir));
  120. return this.list({ forceReload: true });
  121. }
  122. /**
  123. * 删掉目录后清掉 config.toml 里的 [[skills.config]] 残留条目。
  124. * 不清的话,将来装回同名 skill 会直接继承旧的 enabled=false,表现为「装了但不生效」。
  125. */
  126. async #clearStaleConfig(dir: string, name: string): Promise<void> {
  127. const runtime = this.#runtime;
  128. if (typeof runtime.readConfig !== 'function' || typeof runtime.writeConfigValue !== 'function') return;
  129. try {
  130. // 必须按方法调用,解构出来会丢 this 绑定
  131. const config = await runtime.readConfig();
  132. const skills = asRecord(config.skills);
  133. const entries = Array.isArray(skills?.config) ? (skills.config as unknown[]) : null;
  134. if (!entries) return;
  135. const kept = entries.filter((item) => !isStaleEntry(item, dir, name));
  136. if (kept.length === entries.length) return;
  137. await runtime.writeConfigValue('skills.config', kept as JsonValue[]);
  138. } catch (error) {
  139. // 目录已经删掉了,清理失败不该让删除整体失败,但一定要上报,否则表现为配置里有幽灵条目
  140. this.#options.onDiagnostic?.(
  141. `清理 skill 配置残留失败:${error instanceof Error ? error.message : String(error)}`,
  142. );
  143. }
  144. }
  145. /** 把 UI 传来的 path/name 收敛成一个「确实在用户 skills 目录内」的绝对路径 */
  146. async #resolveManagedDir(target: SkillTarget): Promise<string> {
  147. const skillsDir = this.#skillsDir;
  148. if (target.path) {
  149. const dir = resolve(target.path);
  150. assertManagedSkillDir(skillsDir, dir);
  151. const manifest = await stat(join(dir, SKILL_FILE_NAME)).catch(() => null);
  152. if (!manifest?.isFile()) throw new Error('该目录下没有 SKILL.md');
  153. return dir;
  154. }
  155. if (target.name) {
  156. const name = normalizeSkillName(target.name);
  157. const dir = join(skillsDir, name);
  158. assertManagedSkillDir(skillsDir, dir);
  159. const manifest = await stat(join(dir, SKILL_FILE_NAME)).catch(() => null);
  160. if (!manifest?.isFile()) throw new Error(`未找到名为 ${name} 的 skill`);
  161. return dir;
  162. }
  163. throw new Error('必须提供 skill 的 path 或 name');
  164. }
  165. async #resolveSelector(target: SkillTarget): Promise<{ path?: string; name?: string }> {
  166. if (target.path) return { path: target.path };
  167. if (target.name) return { name: normalizeSkillName(target.name) };
  168. throw new Error('必须提供 skill 的 path 或 name');
  169. }
  170. async #createStagingDir(): Promise<string> {
  171. const staging = join(this.#skillsDir, `${STAGING_PREFIX}${randomUUID()}`);
  172. await mkdir(staging, { recursive: true });
  173. return staging;
  174. }
  175. /** staging → skills/<name>,用 rename 保证原子性 */
  176. async #promoteStaging(
  177. staging: string,
  178. name: string,
  179. overwrite: boolean,
  180. stagedRoot = staging,
  181. ): Promise<void> {
  182. const target = join(this.#skillsDir, name);
  183. const existing = await stat(target).catch(() => null);
  184. if (existing) {
  185. if (!overwrite) throw new Error(`skill「${name}」已存在,需显式覆盖`);
  186. await rm(target, { recursive: true, force: true });
  187. }
  188. await mkdir(this.#skillsDir, { recursive: true });
  189. await rename(stagedRoot, target);
  190. if (resolve(stagedRoot) !== resolve(staging)) {
  191. // zip 里带了一层外壳目录:搬完内层后清掉外壳
  192. await rm(staging, { recursive: true, force: true }).catch(() => undefined);
  193. }
  194. }
  195. }
  196. /** 内置目录(.system/.curated/.experimental)与暂存目录一律不可管理 */
  197. function isManagedSkillPath(skillsDir: string, skillPath: string): boolean {
  198. if (!isInsideDir(skillsDir, skillPath)) return false;
  199. const rel = relative(skillsDir, skillPath);
  200. const first = rel.split(sep)[0] ?? '';
  201. return Boolean(first) && !first.startsWith('.') && !rel.includes(`..${sep}`);
  202. }
  203. function assertManagedSkillDir(skillsDir: string, dir: string): void {
  204. if (!isInsideDir(skillsDir, dir)) throw new Error('只能管理用户 skills 目录内的 skill');
  205. const rel = relative(skillsDir, dir);
  206. const segments = rel.split(sep);
  207. // 先判内置/暂存目录,否则 .system/imagegen 会先撞上「一级子目录」的报错,信息不准
  208. if (segments[0]?.startsWith('.')) throw new Error('内置或暂存目录不可删改');
  209. if (segments.length !== 1 || !segments[0]) throw new Error('skill 必须是 skills 目录下的一级子目录');
  210. if (!SKILL_NAME_PATTERN.test(segments[0])) throw new Error('skill 目录名不合法');
  211. }
  212. export function normalizeSkillName(raw: string): string {
  213. const name = raw
  214. .trim()
  215. .toLowerCase()
  216. .replace(/[\s_]+/gu, '-')
  217. .replace(/[^a-z0-9-]/gu, '')
  218. .replace(/-{2,}/gu, '-')
  219. .replace(/^-|-$/gu, '');
  220. if (!name || name.length > MAX_SKILL_NAME_LENGTH) {
  221. throw new Error(`skill 名称非法(需为小写连字符命名,长度 ≤ ${MAX_SKILL_NAME_LENGTH})`);
  222. }
  223. if (!SKILL_NAME_PATTERN.test(name)) throw new Error('skill 名称只能是字母数字与连字符的组合');
  224. return name;
  225. }
  226. /** 校验并落定 staged skill:必须有合法 frontmatter,返回最终 skill 名 */
  227. async function finalizeStagedSkill(
  228. root: string,
  229. manifest: FileManifest,
  230. options: SkillInstallOptions,
  231. ): Promise<string> {
  232. if (manifest.totalBytes > MAX_TOTAL_BYTES) {
  233. throw new Error(`skill 内容超过 ${MAX_TOTAL_BYTES / 1024 / 1024} MiB 上限`);
  234. }
  235. const skillMd = join(root, SKILL_FILE_NAME);
  236. const skillStat = await stat(skillMd).catch(() => null);
  237. if (!skillStat?.isFile()) throw new Error('缺少 SKILL.md');
  238. if (skillStat.size > MAX_SKILL_MD_BYTES) throw new Error(`SKILL.md 超过 ${MAX_SKILL_MD_BYTES / 1024} KiB 上限`);
  239. const frontmatter = parseFrontmatter(await readFile(skillMd, 'utf8'));
  240. const rawName = options.name?.trim() || frontmatter.name;
  241. if (!rawName) throw new Error('SKILL.md 的 frontmatter 缺少 name');
  242. if (!frontmatter.description) throw new Error('SKILL.md 的 frontmatter 缺少 description');
  243. return normalizeSkillName(rawName);
  244. }
  245. interface FileManifest {
  246. entries: number;
  247. totalBytes: number;
  248. paths: string[];
  249. }
  250. function assertAllowedExtension(relPath: string): void {
  251. const ext = basename(relPath).split('.').pop()?.toLowerCase() ?? '';
  252. if (!basename(relPath).includes('.')) return;
  253. if (!ALLOWED_EXTENSIONS.has(ext)) throw new Error(`不允许的文件类型:${relPath}`);
  254. }
  255. /** 相对路径安全校验:拒绝绝对路径、`..`、盘符、UNC 与 macOS 垃圾目录。yauzl 也会拦一层,这里是第二道防线 */
  256. export function assertSafeRelativePath(relPath: string): string {
  257. if (!relPath || relPath.length > 512) throw new Error('条目路径非法');
  258. if (relPath.startsWith('__MACOSX/') || relPath.includes('/__MACOSX/')) {
  259. throw new Error('zip 含 __MACOSX 元数据目录');
  260. }
  261. const normalized = relPath.replace(/\\/gu, '/');
  262. if (/^[a-zA-Z]:/u.test(normalized) || normalized.startsWith('/') || normalized.startsWith('//')) {
  263. throw new Error('zip 含绝对路径条目');
  264. }
  265. const segments = normalized.split('/').filter(Boolean);
  266. if (!segments.length) throw new Error('zip 条目路径为空');
  267. for (const segment of segments) {
  268. if (segment === '..') throw new Error('zip 含路径穿越条目');
  269. if (segment === '.' || segment.startsWith(STAGING_PREFIX)) throw new Error('zip 条目路径非法');
  270. if (segment.length > 128) throw new Error('zip 条目路径过长');
  271. }
  272. return segments.join('/');
  273. }
  274. async function copyFolderChecked(source: string, staging: string): Promise<FileManifest> {
  275. const manifest: FileManifest = { entries: 0, totalBytes: 0, paths: [] };
  276. const walk = async (dir: string): Promise<void> => {
  277. for (const entry of await readdir(dir, { withFileTypes: true })) {
  278. const abs = join(dir, entry.name);
  279. const rel = relative(source, abs).split(sep).join('/');
  280. if (entry.isSymbolicLink()) throw new Error('源目录含符号链接,拒绝安装');
  281. if (entry.name.startsWith('.')) continue;
  282. if (entry.isDirectory()) {
  283. await mkdir(join(staging, rel), { recursive: true });
  284. await walk(abs);
  285. continue;
  286. }
  287. if (!entry.isFile()) throw new Error(`不支持的条目类型:${rel}`);
  288. assertSafeRelativePath(rel);
  289. assertAllowedExtension(rel);
  290. const info = await stat(abs);
  291. if (info.size > MAX_FILE_BYTES) throw new Error(`文件超过单文件 2 MiB 上限:${rel}`);
  292. manifest.entries += 1;
  293. manifest.totalBytes += info.size;
  294. manifest.paths.push(rel);
  295. if (manifest.entries > MAX_ENTRY_COUNT) throw new Error(`条目数超过 ${MAX_ENTRY_COUNT} 上限`);
  296. if (manifest.totalBytes > MAX_TOTAL_BYTES) throw new Error('内容总量超过上限');
  297. await mkdir(dirname(join(staging, rel)), { recursive: true });
  298. await writeFile(join(staging, rel), await readFile(abs));
  299. }
  300. };
  301. await walk(source);
  302. if (!manifest.entries) throw new Error('源目录是空的');
  303. return manifest;
  304. }
  305. function isSymlinkEntry(entry: Entry): boolean {
  306. // zip 的 Unix mode 存在 externalFileAttributes 高 16 位
  307. const mode = (entry.externalFileAttributes ?? 0) >>> 16;
  308. return (mode & 0o170000) === 0o120000;
  309. }
  310. async function extractZipChecked(data: Uint8Array, staging: string): Promise<FileManifest> {
  311. const manifest: FileManifest = { entries: 0, totalBytes: 0, paths: [] };
  312. const zip: ZipFile = await new Promise((resolvePromise, rejectPromise) => {
  313. fromBuffer(Buffer.from(data), { lazyEntries: true, autoClose: false }, (error, zipFile) => {
  314. // yauzl 的原文是英文且面向 zip 格式细节,页面会直接展示 message,这里包一层可读提示
  315. if (zipFile && !error) {
  316. resolvePromise(zipFile);
  317. return;
  318. }
  319. rejectPromise(new Error(`无法解析 zip 文件:${error?.message ?? '格式不正确'}`));
  320. });
  321. });
  322. try {
  323. await new Promise<void>((resolvePromise, reject) => {
  324. zip.once('error', reject);
  325. zip.once('end', () => resolvePromise());
  326. zip.on('entry', (entry: Entry) => {
  327. void handleEntry(entry).then(
  328. () => zip.readEntry(),
  329. (error: unknown) => reject(error instanceof Error ? error : new Error(String(error))),
  330. );
  331. });
  332. async function handleEntry(entry: Entry): Promise<void> {
  333. const rawName = entry.fileName.replace(/\\/gu, '/');
  334. if (isSymlinkEntry(entry)) throw new Error(`zip 含符号链接条目:${rawName}`);
  335. const isDir = rawName.endsWith('/');
  336. const rel = assertSafeRelativePath(isDir ? rawName.slice(0, -1) : rawName);
  337. if (isDir) {
  338. await mkdir(join(staging, rel), { recursive: true });
  339. return;
  340. }
  341. if (entry.uncompressedSize > MAX_FILE_BYTES) {
  342. throw new Error(`文件超过单文件 2 MiB 上限:${rel}`);
  343. }
  344. assertAllowedExtension(rel);
  345. manifest.entries += 1;
  346. if (manifest.entries > MAX_ENTRY_COUNT) throw new Error(`条目数超过 ${MAX_ENTRY_COUNT} 上限`);
  347. manifest.totalBytes += entry.uncompressedSize;
  348. if (manifest.totalBytes > MAX_TOTAL_BYTES) throw new Error('解压总量超过 25 MiB 上限');
  349. manifest.paths.push(rel);
  350. const buffer = await new Promise<Buffer>((resolveBuffer, rejectBuffer) => {
  351. zip.openReadStream(entry, (error, stream) => {
  352. if (error || !stream) {
  353. rejectBuffer(error ?? new Error(`无法读取 zip 条目:${rel}`));
  354. return;
  355. }
  356. const chunks: Buffer[] = [];
  357. let received = 0;
  358. stream.on('data', (chunk: Buffer) => {
  359. received += chunk.length;
  360. // 防 zip bomb:实际解压量超过声明值或超过单文件上限就立即中止
  361. if (received > MAX_FILE_BYTES || received > entry.uncompressedSize) {
  362. stream.destroy();
  363. rejectBuffer(new Error(`zip 条目解压量异常:${rel}`));
  364. return;
  365. }
  366. chunks.push(chunk);
  367. });
  368. stream.once('error', rejectBuffer);
  369. stream.once('end', () => resolveBuffer(Buffer.concat(chunks)));
  370. });
  371. });
  372. const destination = join(staging, rel);
  373. await mkdir(join(destination, '..'), { recursive: true });
  374. await writeFile(destination, buffer);
  375. }
  376. zip.readEntry();
  377. });
  378. } finally {
  379. zip.close();
  380. }
  381. if (!manifest.entries) throw new Error('zip 内没有可用文件');
  382. return manifest;
  383. }
  384. /** zip 常见形态是「一层外壳目录 + SKILL.md」,此时把内层当作 skill 根 */
  385. async function resolveZipRoot(staging: string, manifest: FileManifest): Promise<string> {
  386. if (manifest.paths.includes(SKILL_FILE_NAME)) return staging;
  387. const tops = new Set(manifest.paths.map((item) => item.split('/')[0]!));
  388. if (tops.size === 1) {
  389. const candidate = join(staging, [...tops][0]!);
  390. const inner = await stat(join(candidate, SKILL_FILE_NAME)).catch(() => null);
  391. if (inner?.isFile()) return candidate;
  392. }
  393. throw new Error('zip 根目录(或唯一的外壳目录)下没有 SKILL.md');
  394. }
  395. async function collectFiles(dir: string): Promise<SkillFileEntry[]> {
  396. const files: SkillFileEntry[] = [];
  397. const walk = async (current: string): Promise<void> => {
  398. for (const entry of await readdir(current, { withFileTypes: true })) {
  399. const abs = join(current, entry.name);
  400. if (entry.isDirectory()) {
  401. await walk(abs);
  402. continue;
  403. }
  404. if (!entry.isFile()) continue;
  405. const info = await stat(abs);
  406. files.push({ path: relative(dir, abs).split(sep).join('/'), size: info.size });
  407. }
  408. };
  409. await walk(dir);
  410. return files.sort((left, right) => left.path.localeCompare(right.path));
  411. }
  412. /** 只取 YAML frontmatter 里的 name / description 单行标量,够用且不引 YAML 依赖 */
  413. export function parseFrontmatter(content: string): { name: string | null; description: string | null } {
  414. const match = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/u.exec(content);
  415. if (!match) return { name: null, description: null };
  416. const fields: Record<string, string> = {};
  417. for (const line of match[1]!.split(/\r?\n/u)) {
  418. const pair = /^([A-Za-z0-9_-]+)\s*:\s*(.*)$/u.exec(line.trim());
  419. if (!pair) continue;
  420. fields[pair[1]!.toLowerCase()] = stripQuotes(pair[2]!.trim());
  421. }
  422. return { name: fields.name || null, description: fields.description || null };
  423. }
  424. function stripQuotes(value: string): string {
  425. if (value.length >= 2 && ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))) {
  426. return value.slice(1, -1);
  427. }
  428. return value.replace(/^>\s*|^\|\s*/u, '').trim();
  429. }
  430. /** 配置条目可能按 path(指向 SKILL.md)记录,也可能只按 name 记录 */
  431. function isStaleEntry(item: unknown, removedDir: string, removedName: string): boolean {
  432. const record = asRecord(item);
  433. if (!record) return false;
  434. const entryPath = readString(record.path);
  435. if (entryPath) {
  436. const target = resolve(entryPath);
  437. const dir = resolve(removedDir);
  438. return target === dir || target.startsWith(dir + sep) || dirname(target) === dir;
  439. }
  440. const entryName = readString(record.name);
  441. return Boolean(entryName) && entryName === removedName;
  442. }
  443. function asRecord(value: unknown): Record<string, unknown> | null {
  444. return value && typeof value === 'object' && !Array.isArray(value)
  445. ? (value as Record<string, unknown>)
  446. : null;
  447. }
  448. function readString(value: unknown): string | null {
  449. return typeof value === 'string' ? value : null;
  450. }