designsnitch 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/format.js CHANGED
@@ -1,85 +1,71 @@
1
- const SEVERITY_LABELS = { error: "오류", warning: "경고" };
1
+ import { messages } from "./messages.js";
2
2
 
3
3
  /**
4
4
  * 검사 결과를 사람이 읽는 글로 만든다.
5
5
  * @param {Awaited<ReturnType<typeof import("./check.js").check>>} result
6
+ * @param {"en" | "ko"} [lang]
6
7
  */
7
- export function formatText({ designSystem, problems, summary, violations }) {
8
- const header = [
9
- describe(designSystem),
10
- ...problems.map((problem) => `주의: ${problem}`),
11
- "",
12
- ];
8
+ export function formatText({ designSystem, problems, summary, violations }, lang) {
9
+ const m = messages(lang);
10
+ // 첫 줄은 설정에서 무엇을 읽었는지다. 경로를 잘못 적으면 여기서 0개로 드러난다.
11
+ const header = [m.designSystem(designSystem), ...problems.map(m.notice), ""];
13
12
 
14
13
  if (violations.length === 0) {
15
- return [...header, `위반이 없습니다. (파일 ${summary.files}개 검사)`, ""].join("\n");
14
+ return [...header, m.noViolations(summary), ""].join("\n");
16
15
  }
17
16
 
18
- const byFile = Map.groupBy(violations, (violation) => violation.file);
17
+ const byFile = new Map();
18
+ for (const violation of violations) {
19
+ const { file } = violation;
20
+ if (!byFile.has(file)) byFile.set(file, []);
21
+ byFile.get(file).push(violation);
22
+ }
19
23
  const sections = [...byFile].map(([file, items]) =>
20
24
  [
21
25
  file,
22
26
  ...items.map(
23
27
  ({ line, column, severity, message, rule }) =>
24
- ` ${line}:${column} ${SEVERITY_LABELS[severity]} ${message} (${rule})`,
28
+ ` ${line}:${column} ${m.severity[severity]} ${message} (${rule})`,
25
29
  ),
26
30
  "",
27
31
  ].join("\n"),
28
32
  );
29
33
 
30
34
  const count = (action) => violations.filter((v) => v.action === action).length;
31
- const actions = [
32
- `바로 바꿀 수 있는 것 ${count("replace")}건`,
33
- `사람이 정해야 하는 것 ${count("ask")}건`,
34
- ...(count("repair") > 0 ? [`문법을 고쳐야 하는 것 ${count("repair")}건`] : []),
35
- ].join(", ");
36
-
37
35
  return [
38
36
  ...header,
39
37
  ...sections,
40
- `오류 ${summary.errors}개, 경고 ${summary.warnings}개 (파일 ${summary.files}개 검사)`,
41
- actions,
38
+ m.summary(summary),
39
+ m.actions({ replace: count("replace"), ask: count("ask"), repair: count("repair") }),
42
40
  "",
43
41
  ].join("\n");
44
42
  }
45
43
 
46
- // 설정에서 무엇을 읽었는지 보여준다. 경로를 잘못 적으면 여기서 0개로 드러난다.
47
- function describe({ colorTokens, components }) {
48
- return [
49
- `디자인 시스템: 색 토큰 ${colorTokens}개`,
50
- components > 0 ? `컴포넌트 ${components}개` : "컴포넌트 설정 없음",
51
- ].join(", ");
52
- }
53
-
54
44
  /**
55
45
  * 색 수집 결과를 사람이 읽는 글로 만든다.
56
46
  * @param {Awaited<ReturnType<typeof import("./colors.js").collectColors>>} result
47
+ * @param {"en" | "ko"} [lang]
57
48
  */
58
- export function formatColorsText({ summary, colors, palette }) {
59
- if (colors.length === 0 && palette.length === 0) {
60
- return `코드에서 색을 찾지 못했습니다. (파일 ${summary.files}개 검사)\n`;
61
- }
49
+ export function formatColorsText({ summary, colors, palette }, lang) {
50
+ const m = messages(lang);
51
+ if (colors.length === 0 && palette.length === 0) return `${m.colorsNone(summary)}\n`;
62
52
 
63
53
  const usage = ({ uses, files, utilities, literals, properties = {} }) => {
64
54
  const where = Object.entries(utilities).map(([utility, count]) => `${utility} ${count}`);
65
- if (literals) where.push(`문자열 ${literals}`);
55
+ if (literals) where.push(m.literals(literals));
66
56
  const inCss = Object.values(properties).reduce((sum, count) => sum + count, 0);
67
- if (inCss) where.push(`CSS ${inCss}`);
68
- return `${uses}곳 파일 ${files}개 ${where.join(", ")}`;
57
+ if (inCss) where.push(m.css(inCss));
58
+ return `${m.usage({ uses, files })} ${where.join(", ")}`;
69
59
  };
70
60
  // 설정 파일이 있을 때만 tokens 가 붙는다.
71
- const tokenNote = ({ tokens }) =>
72
- tokens === undefined ? "" : tokens.length > 0 ? ` 토큰: ${tokens.join(", ")}` : " 토큰 없음";
61
+ const tokenNote = ({ tokens }) => (tokens === undefined ? "" : ` ${m.tokenNote(tokens)}`);
73
62
 
74
- const lines = [
75
- `코드에서 쓰는 색: hex ${summary.colors}개, 기본 팔레트 ${summary.paletteColors}개 (사용 ${summary.uses}곳, 파일 ${summary.files}개 검사)`,
76
- "",
77
- ];
63
+ const lines = [m.colorsSummary(summary), ""];
78
64
  if (colors.length > 0) {
79
- lines.push("hex 색", ...colors.map((c) => ` ${c.color} ${usage(c)}${tokenNote(c)}`), "");
65
+ lines.push(m.hexTitle, ...colors.map((c) => ` ${c.color} ${usage(c)}${tokenNote(c)}`), "");
80
66
  }
81
67
  if (palette.length > 0) {
82
- lines.push("Tailwind 기본 팔레트", ...palette.map((p) => ` ${p.name} ${usage(p)}`), "");
68
+ lines.push(m.paletteTitle, ...palette.map((p) => ` ${p.name} ${usage(p)}`), "");
83
69
  }
84
70
  return lines.join("\n");
85
71
  }
package/src/hook.js CHANGED
@@ -1,17 +1,20 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import fs from "node:fs";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { check, nextSteps } from "./check.js";
5
6
  import { CONFIG_FILE, loadConfig } from "./config.js";
7
+ import { messages, resolveLang } from "./messages.js";
6
8
 
7
9
  const CHECKABLE = /\.(?:[cm]?[jt]s|[jt]sx|css)$/;
8
- const STOP_EVENTS = new Set(["Stop", "SubagentStop"]);
10
+ // Claude Code, Codex 는 Stop, Gemini CLI 는 AfterAgent 가 "작업을 끝내려 할 때"다.
11
+ const STOP_EVENTS = new Set(["Stop", "SubagentStop", "AfterAgent"]);
9
12
 
10
13
  /**
11
14
  * 코딩 에이전트의 훅에서 부르는 검사. 에이전트가 방금 고친 파일만 본다.
12
15
  *
13
- * - 파일을 고친 직후: 그 파일에 오류가 있으면 종료 코드 2와 함께 stderr 로 알린다.
14
- * - 작업을 끝내려 할 때(Stop): 에이전트가 스스로 고칠 수 있는 오류가 남아 있으면 2로 막는다.
16
+ * - 파일을 고친 직후: HEAD 대비 새 오류가 있으면 종료 코드 2와 함께 stderr 로 알린다.
17
+ * - 작업을 끝내려 할 때(Stop): 에이전트가 스스로 고칠 수 있는 새 오류가 남아 있으면 2로 막는다.
15
18
  * 사람이 정해야 하는 오류만 남았으면 막지 않는다. 물어보려면 멈춰야 하기 때문이다.
16
19
  * - 경고는 막지 않는다. 설정 파일이 없는 프로젝트에서는 아무것도 하지 않는다.
17
20
  *
@@ -19,47 +22,104 @@ const STOP_EVENTS = new Set(["Stop", "SubagentStop"]);
19
22
  * @param {string} options.cwd 프로젝트 디렉터리
20
23
  * @param {string} [options.input] 훅이 stdin 으로 준 JSON. 비어 있거나 JSON 이 아니어도 된다
21
24
  * @param {string} [options.configPath]
25
+ * @param {"en" | "ko"} [options.lang] 없으면 설정의 lang, 환경 변수, 영어 순으로 정한다
22
26
  * @returns {Promise<{ stderr: string, exitCode: 0 | 2 }>}
23
27
  */
24
- export async function runHook({ cwd, input = "", configPath = CONFIG_FILE }) {
28
+ export async function runHook({ cwd, input = "", configPath = CONFIG_FILE, lang }) {
25
29
  const pass = { stderr: "", exitCode: 0 };
26
30
  const event = parse(input);
27
- const stopping = STOP_EVENTS.has(event.hook_event_name);
31
+ // Claude Code, Codex, Gemini CLI 는 snake_case, Grok Build 는 camelCase 로 보낸다.
32
+ const eventName = event.hook_event_name ?? event.hookEventName;
33
+ const toolInput = event.tool_input ?? event.toolInput;
34
+ const stopping = STOP_EVENTS.has(eventName);
28
35
 
29
36
  // 이미 한 번 막아서 에이전트가 고치는 중이면 다시 막지 않는다.
30
- if (stopping && event.stop_hook_active) return pass;
37
+ if (stopping && (event.stop_hook_active ?? event.stopHookActive)) return pass;
31
38
  if (!fs.existsSync(path.resolve(cwd, configPath))) return pass;
32
39
 
33
- const edited = event.tool_input?.file_path;
40
+ const edited = toolInput?.file_path ?? toolInput?.filePath;
34
41
  const files = (typeof edited === "string" ? [edited] : changedFiles(cwd))
35
42
  .map((file) => path.resolve(cwd, file))
36
43
  .filter((file) => isInside(cwd, file) && CHECKABLE.test(file) && fs.existsSync(file))
37
44
  .map((file) => path.relative(cwd, file));
38
45
  if (files.length === 0) return pass;
39
46
 
47
+ const canBlock = (v) => v.severity === "error" && (!stopping || v.action !== "ask");
40
48
  let result;
49
+ let errors;
41
50
  try {
42
- result = await check({ cwd, config: loadConfig(cwd, configPath), paths: files });
51
+ const config = loadConfig(cwd, configPath, resolveLang(lang));
52
+ lang = resolveLang(lang, config.lang);
53
+ result = await check({ cwd, config, paths: files, lang });
54
+ if (!result.violations.some(canBlock)) return pass;
55
+
56
+ const baseline = countViolations(await checkHead({ cwd, config, files, lang }));
57
+ const current = countViolations(result.violations);
58
+ errors = result.violations.filter((v) => {
59
+ const key = violationKey(v);
60
+ return v.severity === "error" && current.get(key) > (baseline.get(key) ?? 0);
61
+ });
43
62
  } catch (error) {
44
63
  return { stderr: `${error.message}\n`, exitCode: 2 };
45
64
  }
46
65
 
47
- const errors = result.violations.filter((v) => v.severity === "error");
48
- const blocking = stopping ? errors.filter((v) => v.action !== "ask") : errors;
49
- if (blocking.length === 0) return pass;
66
+ if (!errors.some(canBlock)) return pass;
50
67
 
68
+ const m = messages(lang);
51
69
  const lines = [
52
- `designsnitch: 방금 고친 파일에 디자인 시스템 오류가 ${errors.length}건 있습니다.`,
70
+ m.hookHeader(errors.length),
53
71
  "",
54
72
  ...errors.map((v) => `${v.file}:${v.line}:${v.column} ${v.message} [${v.action}]`),
55
73
  "",
56
- "다음에 할 일",
57
- ...nextSteps(result.designSystem, errors).map((step) => `- ${step}`),
74
+ m.nextTitle,
75
+ ...nextSteps(result.designSystem, errors, lang).map((step) => `- ${step}`),
58
76
  "",
59
77
  ];
60
78
  return { stderr: lines.join("\n"), exitCode: 2 };
61
79
  }
62
80
 
81
+ async function checkHead({ cwd, config, files, lang }) {
82
+ let temp;
83
+ const paths = [];
84
+ try {
85
+ for (const file of files) {
86
+ const gitPath = file.split(path.sep).join("/");
87
+ // HEAD 나 파일이 없으면 기준선에 위반이 없다.
88
+ const source = gitOutput(cwd, ["show", `HEAD:./${gitPath}`], { maxBuffer: Infinity });
89
+ if (source === undefined) continue;
90
+
91
+ temp ??= fs.mkdtempSync(path.join(os.tmpdir(), "designsnitch-head-"));
92
+ const target = path.join(temp, file);
93
+ fs.mkdirSync(path.dirname(target), { recursive: true });
94
+ fs.writeFileSync(target, source);
95
+ paths.push(file);
96
+ }
97
+ if (paths.length === 0) return [];
98
+
99
+ const baselineConfig = { ...config, tokens: path.resolve(cwd, config.tokens) };
100
+ if (config.components) {
101
+ baselineConfig.components = { ...config.components, path: path.resolve(cwd, config.components.path) };
102
+ }
103
+ const result = await check({ cwd: temp, config: baselineConfig, paths, lang });
104
+ return result.violations;
105
+ } finally {
106
+ if (temp) fs.rmSync(temp, { recursive: true, force: true });
107
+ }
108
+ }
109
+
110
+ function violationKey({ file, rule, found }) {
111
+ return JSON.stringify([file, rule, found]);
112
+ }
113
+
114
+ function countViolations(violations) {
115
+ const counts = new Map();
116
+ for (const violation of violations) {
117
+ const key = violationKey(violation);
118
+ counts.set(key, (counts.get(key) ?? 0) + 1);
119
+ }
120
+ return counts;
121
+ }
122
+
63
123
  function parse(input) {
64
124
  try {
65
125
  const value = JSON.parse(input);
@@ -74,19 +134,22 @@ function isInside(cwd, file) {
74
134
  return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
75
135
  }
76
136
 
77
- /** git 작업 폴더에서 바뀌었거나 새로 생긴 파일. git 저장소가 아니면 빈 배열. */
78
- function changedFiles(cwd) {
79
- let output;
137
+ function gitOutput(cwd, args, options) {
80
138
  try {
81
- output = execFileSync("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all"], {
139
+ return execFileSync("git", args, {
82
140
  cwd,
83
- encoding: "utf8",
84
141
  stdio: ["ignore", "pipe", "ignore"],
142
+ ...options,
85
143
  });
86
144
  } catch {
87
- return [];
145
+ return undefined;
88
146
  }
147
+ }
89
148
 
149
+ /** git 작업 폴더에서 바뀌었거나 새로 생긴 파일. git 저장소가 아니면 빈 배열. */
150
+ function changedFiles(cwd) {
151
+ const output = gitOutput(cwd, ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { encoding: "utf8" });
152
+ if (!output) return [];
90
153
  const files = [];
91
154
  const entries = output.split("\0").filter(Boolean);
92
155
  for (let i = 0; i < entries.length; i += 1) {
package/src/install.js CHANGED
@@ -2,82 +2,140 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { CONFIG_FILE } from "./config.js";
5
+ import { messages } from "./messages.js";
5
6
 
6
7
  const SKILLS_DIR = fileURLToPath(new URL("../skills", import.meta.url));
7
- const SETTINGS_FILE = ".claude/settings.json";
8
8
  const HOOK_COMMAND = "npx designsnitch hook";
9
- // 파일을 고친 직후와 작업을 끝내려 할 때 훅을 실행한다.
10
- const HOOK_ENTRIES = {
11
- PostToolUse: { matcher: "Edit|Write|MultiEdit", hooks: [{ type: "command", command: HOOK_COMMAND }] },
12
- Stop: { hooks: [{ type: "command", command: HOOK_COMMAND }] },
9
+
10
+ /**
11
+ * 에이전트마다 스킬을 읽는 곳, 훅을 등록하는 파일, 이벤트 이름이 다르다.
12
+ * 훅이 하는 일(표준 입력의 JSON 을 읽고, 막을 때 종료 코드 2와 stderr)은 같다.
13
+ * editEvent 는 파일을 고친 직후, stopEvent 는 작업을 끝내려 할 때다.
14
+ */
15
+ const AGENTS = {
16
+ claude: {
17
+ skillsDir: ".claude/skills",
18
+ hooksFile: ".claude/settings.json",
19
+ editEvent: "PostToolUse",
20
+ stopEvent: "Stop",
21
+ editTools: "Edit|Write|MultiEdit",
22
+ hook: { type: "command", command: HOOK_COMMAND },
23
+ approval: null,
24
+ },
25
+ codex: {
26
+ skillsDir: ".agents/skills",
27
+ hooksFile: ".codex/hooks.json",
28
+ editEvent: "PostToolUse",
29
+ stopEvent: "Stop",
30
+ // Codex 는 셸 명령으로도 파일을 고친다. 그런 수정은 Stop 훅이 git 에서 바뀐 파일을 보고 잡는다.
31
+ editTools: "apply_patch",
32
+ hook: { type: "command", command: HOOK_COMMAND, timeout: 60 },
33
+ // 신뢰한 프로젝트에서, 사용자가 승인한 훅만 실행한다.
34
+ approval: "codexTrust",
35
+ },
36
+ // geminicli.com 의 공식 문서 기준. timeout 은 밀리초다.
37
+ gemini: {
38
+ skillsDir: ".agents/skills",
39
+ hooksFile: ".gemini/settings.json",
40
+ editEvent: "AfterTool",
41
+ stopEvent: "AfterAgent",
42
+ editTools: "write_file|replace",
43
+ hook: { name: "designsnitch", type: "command", command: HOOK_COMMAND, timeout: 60000 },
44
+ // 새 프로젝트 훅은 실행하기 전에 경고하고 허용을 받는다.
45
+ approval: "geminiTrust",
46
+ },
47
+ // docs.x.ai 의 공식 문서 기준. 훅은 .grok/hooks/*.json 어느 파일에 둬도 된다. timeout 은 초다.
48
+ // Claude Code 의 도구 이름(Edit, Write)은 Grok 의 도구로 자동으로 연결된다고 문서에 적혀 있다.
49
+ grok: {
50
+ skillsDir: ".grok/skills",
51
+ hooksFile: ".grok/hooks/designsnitch.json",
52
+ editEvent: "PostToolUse",
53
+ stopEvent: "Stop",
54
+ editTools: "Edit|Write|MultiEdit",
55
+ hook: { type: "command", command: HOOK_COMMAND, timeout: 60 },
56
+ // 신뢰한 프로젝트의 훅만 실행한다(/hooks-trust 또는 --trust).
57
+ approval: "grokTrust",
58
+ },
13
59
  };
14
60
 
61
+ export const AGENT_CHOICES = [...Object.keys(AGENTS), "all"];
62
+
15
63
  /**
16
- * 프로젝트에 스킬과 에이전트 훅을 설치한다. Claude Code 의 위치(.claude)에 맞춘다.
64
+ * 프로젝트에 스킬과 에이전트 훅을 설치한다.
17
65
  * 여러 번 실행해도 된다. 스킬은 최신으로 덮어쓰고, 훅은 없을 때만 더한다.
18
- * @param {{ cwd: string }} options
66
+ * @param {{ cwd: string, lang?: "en" | "ko", agent?: "claude" | "codex" | "gemini" | "grok" | "all" }} options
19
67
  * @returns {{ stdout: string, exitCode: 0 }}
20
- * @throws {Error} .claude/settings.json 을 읽을 수 없을 때. 이때는 아무것도 바꾸지 않는다
68
+ * @throws {Error} 훅을 등록할 파일을 읽을 수 없을 때. 이때는 아무것도 바꾸지 않는다
21
69
  */
22
- export function install({ cwd }) {
23
- const settingsPath = path.join(cwd, SETTINGS_FILE);
24
- // 설정 파일이 깨져 있으면 아무것도 건드리기 전에 멈춘다.
25
- const settings = readSettings(settingsPath);
70
+ export function install({ cwd, lang, agent = "claude" }) {
71
+ const m = messages(lang);
72
+ const targets = (agent === "all" ? Object.keys(AGENTS) : [agent]).map((name) => AGENTS[name]);
73
+
74
+ // 훅 파일이 깨져 있으면 아무것도 건드리기 전에 멈춘다.
75
+ const settings = new Map(
76
+ targets.map((target) => [target, readJson(path.join(cwd, target.hooksFile), m)]),
77
+ );
26
78
 
27
79
  const skills = fs.readdirSync(SKILLS_DIR).filter((name) => !name.startsWith("."));
28
- for (const skill of skills) {
29
- fs.cpSync(path.join(SKILLS_DIR, skill), path.join(cwd, ".claude/skills", skill), { recursive: true });
30
- }
80
+ const lines = [];
81
+ const steps = [];
31
82
 
32
- const added = addHooks(settings);
33
- if (added) {
34
- fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
35
- fs.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
36
- }
83
+ const copiedTo = new Set();
84
+ for (const target of targets) {
85
+ // Codex 와 Gemini CLI 는 같은 .agents/skills 를 읽는다. 한 번만 복사한다.
86
+ if (!copiedTo.has(target.skillsDir)) {
87
+ copiedTo.add(target.skillsDir);
88
+ for (const skill of skills) {
89
+ fs.cpSync(path.join(SKILLS_DIR, skill), path.join(cwd, target.skillsDir, skill), { recursive: true });
90
+ }
91
+ lines.push(m.skillsCopied({ n: skills.length, dir: target.skillsDir }));
92
+ }
37
93
 
38
- const steps = [];
39
- if (!isInstalled(cwd)) {
40
- steps.push("훅이 매번 빠르게 돌도록 프로젝트에 설치하세요: npm install --save-dev designsnitch");
41
- }
42
- if (!fs.existsSync(path.join(cwd, CONFIG_FILE))) {
43
- steps.push(
44
- `코딩 에이전트에게 "이 프로젝트에 designsnitch를 설정해 줘"라고 요청하세요. 토큰 CSS와 공용 컴포넌트를 찾아 ${CONFIG_FILE} 을 만들고 ESLint에 규칙을 넣습니다.`,
45
- );
94
+ const file = path.join(cwd, target.hooksFile);
95
+ const added = addHooks(settings.get(target), target);
96
+ if (added) {
97
+ fs.mkdirSync(path.dirname(file), { recursive: true });
98
+ fs.writeFileSync(file, `${JSON.stringify(settings.get(target), null, 2)}\n`);
99
+ }
100
+
101
+ lines.push(added ? m.hookRegistered({ file: target.hooksFile }) : m.hookAlready({ file: target.hooksFile }));
102
+ if (added && target.approval) steps.push(m[target.approval]());
46
103
  }
47
104
 
48
- const lines = [
49
- `스킬 ${skills.length}개를 .claude/skills 에 복사했습니다.`,
50
- added
51
- ? `훅을 ${SETTINGS_FILE} 에 등록했습니다.`
52
- : `훅은 이미 ${SETTINGS_FILE} 에 등록되어 있습니다.`,
53
- ...(steps.length > 0 ? ["", "다음에 할 일", ...steps.map((step) => `- ${step}`)] : []),
54
- "",
55
- ];
105
+ if (!isInstalled(cwd)) steps.push(m.installPackage());
106
+ if (!fs.existsSync(path.join(cwd, CONFIG_FILE))) steps.push(m.askAgent({ configFile: CONFIG_FILE }));
107
+
108
+ if (steps.length > 0) lines.push("", m.nextTitle, ...steps.map((step) => `- ${step}`));
109
+ lines.push("");
56
110
  return { stdout: lines.join("\n"), exitCode: 0 };
57
111
  }
58
112
 
59
- function readSettings(file) {
113
+ function readJson(file, m) {
60
114
  if (!fs.existsSync(file)) return {};
61
115
  try {
62
- const settings = JSON.parse(fs.readFileSync(file, "utf8"));
63
- if (settings && typeof settings === "object" && !Array.isArray(settings)) return settings;
116
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
117
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
64
118
  } catch {
65
119
  // 아래에서 같은 오류로 알린다.
66
120
  }
67
- throw new Error(`${file} 을 읽을 수 없습니다. JSON 형식을 고친 뒤 다시 실행하세요.`);
121
+ throw new Error(m.settingsUnreadable({ file }));
68
122
  }
69
123
 
70
124
  /** 훅이 없는 이벤트에만 더한다. 하나라도 더했으면 true. */
71
- function addHooks(settings) {
125
+ function addHooks(settings, target) {
126
+ const entries = {
127
+ [target.editEvent]: { matcher: target.editTools, hooks: [target.hook] },
128
+ [target.stopEvent]: { hooks: [target.hook] },
129
+ };
72
130
  settings.hooks ??= {};
73
131
  let added = false;
74
- for (const [event, entry] of Object.entries(HOOK_ENTRIES)) {
75
- const entries = (settings.hooks[event] ??= []);
76
- const registered = entries.some((existing) =>
77
- existing.hooks?.some((hook) => hook.command?.includes("designsnitch hook")),
132
+ for (const [event, entry] of Object.entries(entries)) {
133
+ const existing = (settings.hooks[event] ??= []);
134
+ const registered = existing.some((item) =>
135
+ item.hooks?.some((hook) => hook.command?.includes("designsnitch hook")),
78
136
  );
79
137
  if (!registered) {
80
- entries.push(structuredClone(entry));
138
+ existing.push(structuredClone(entry));
81
139
  added = true;
82
140
  }
83
141
  }