geo-figure-mcp 0.2.2 → 0.2.4

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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # geo-figure-mcp — 지리 시험용 지도·그래프 만들기 (0.2.2)
1
+ # geo-figure-mcp — 지리 시험용 지도·그래프 만들기 (0.2.4)
2
2
 
3
3
  만든 사람: 김한솔 (한백고등학교 지리 교사)
4
4
 
@@ -29,6 +29,7 @@ AI에게 "서울 자치구 주간 인구 지수 지도랑 산점도, 구 이름
29
29
  - 정답표는 파일 마지막 장
30
30
  - 만들기 전에 AI가 계획(지표·연도·지역·가공·기호 순서·출력)을 요약해 보여 주고 확인을 받습니다(확인 없이는 파일을 만들지 않음).
31
31
  - **시안 먼저**: 파일을 만들기 전에 대화창에 미리보기 그림을 보여 줍니다. 지도 기호 모양은 4가지(① 흰 테두리 ② 바탕 없음 ③ 네모 흰 바탕 ④ 작은 원 흰 바탕)를 나란히 보여 주고 고르게 합니다.
32
+ - **필요한 정보만 조회**: 내장 통계는 list_bundled_data의 query로 검색하고 summary:true로 키와 주제만 볼 수 있습니다. 로컬 시안의 previewId가 있으면, 교사가 확인한 뒤 같은 그림 명세 대신 ID를 보내 파일을 만들 수 있습니다(최대 30분).
32
33
  - **만든 뒤 고치기**: 그림과 함께 설계도(`<이름>.geo-figure.json`)를 저장합니다. "범례 바꿔 줘", "화성시 빼 줘", "기호 순서 바꿔 줘"라고 하면 통계를 다시 찾지 않고 그 부분만 고쳐 다시 만듭니다.
33
34
  - **자동 업데이트**: 설정에 `geo-figure-mcp@latest` 를 쓰면 앱을 켤 때마다 최신 버전을 받습니다. 예전 버전이 돌고 있으면 AI가 "새 버전이 있다"고 알려 줍니다.
34
35
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "geo-figure-mcp",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "지리 시험용 지도·그래프를 도형 하나하나 고칠 수 있는 PPTX·HWPX로 만드는 MCP 서버",
5
5
  "author": "김한솔 (한백고등학교)",
6
6
  "mcpName": "io.github.skyblue3925-svg/geo-figure-mcp",
package/server.json CHANGED
@@ -4,12 +4,12 @@
4
4
  "title": "Geo Figure (지리 시험 지도·그래프)",
5
5
  "description": "지리 시험용 지도·그래프를 실제 통계로, 도형 하나하나 고칠 수 있는 PPTX·HWPX로 만든다.",
6
6
  "repository": { "url": "https://github.com/skyblue3925-svg/geo-figure-mcp", "source": "github" },
7
- "version": "0.2.2",
7
+ "version": "0.2.4",
8
8
  "packages": [
9
9
  {
10
10
  "registryType": "npm",
11
11
  "identifier": "geo-figure-mcp",
12
- "version": "0.2.2",
12
+ "version": "0.2.4",
13
13
  "transport": { "type": "stdio" },
14
14
  "environmentVariables": [
15
15
  { "name": "GEO_FIGURE_OUT", "description": "만든 파일을 저장할 폴더 (기본: 문서/지리시험자료)", "isRequired": false, "isSecret": false }
package/src/maps.js CHANGED
@@ -136,10 +136,22 @@ export function makeMap(spec, st = DEFAULT_STYLE) {
136
136
  areas.push(S.poly(rs, { fill, stroke: inFocus.has(f) ? 0.2 : 0.12, name: f.full }));
137
137
  }
138
138
  items.push(S.group(isKorea ? '행정 구역' : '국가', areas));
139
- // 경계 굵게: 시·군 지도일 때 시·도 경계를 한 번 더
140
- if (isKorea && spec.level === 'sigungu') {
141
- const sidos = koreaFeatures('sido', detail, spec.edition);
142
- items.push(S.group('시·도 경계', sidos.flatMap((f) => rings(path, f.geo).map((r) => S.line([...r, r[0]], { stroke: 0.4, name: `${f.name} 경계` })))));
139
+ const isSigungu = spec.level === 'sigungu';
140
+ if (isKorea && (isSigungu || spec.within?.length)) {
141
+ const sidos = isSigungu ? koreaFeatures('sido', detail, spec.edition) : feats;
142
+ const selected = new Set(spec.within);
143
+ const context = isSigungu ? sidos.filter((f) => !selected.has(f.name)).flatMap((f) =>
144
+ rings(path, f.geo).map((r) => S.line([...r, r[0]], { stroke: 0.4, name: `${f.name} 경계` }))) : [];
145
+ // 같은 시·도의 시·군·구를 합친 경계를 위에 그려 내부 경계와 구분한다.
146
+ const outlines = sidos.filter((f) => selected.has(f.name)).flatMap((f) => {
147
+ const style = { stroke: 0.7, name: `${f.name} 경계` };
148
+ if (!spec.bbox) return rings(path, f.geo).map((r) => S.poly([r], style));
149
+ // 잘린 면을 닫으면 지도 틀이 경계처럼 보일 수 있으므로 원래 경계선만 자른다.
150
+ const { type, coordinates } = f.geo.geometry;
151
+ const boundary = { type: 'MultiLineString', coordinates: type === 'Polygon' ? coordinates : coordinates.flat() };
152
+ return lines(path, boundary).filter((pts) => pts.some(([x, y]) => x !== pts[0][0] || y !== pts[0][1])).map((pts) => S.line(pts, style));
153
+ });
154
+ items.push(S.group('시·도 경계', [...context, ...outlines]));
143
155
  }
144
156
  for (const [n, lab] of Object.entries(spec.labels || {})) {
145
157
  const f = find(n);
package/src/tools.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
+ import { randomBytes } from 'node:crypto';
5
6
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6
7
  import { z } from 'zod';
7
8
  import { SOURCES, findData, transform, round, assignLabels, suggestRegions, examSpots, kosisSearch, kosisItems, setKosisKey, bundleList, withKosisKey } from './data.js';
@@ -25,15 +26,15 @@ export const OUT = process.env.GEO_FIGURE_OUT || path.join(os.homedir(), 'Docume
25
26
  const GUIDE = `
26
27
  [작업 순서 — 반드시 지킨다]
27
28
  1. 교사의 말에서 지도·그래프 종류, 지표, 지역, 연도를 읽는다. 모르면 기본값을 채운다.
28
- 2. find_data 로 실제 통계를 찾는다. 한국 시·도·시·군·구 통계는 먼저 list_bundled_data(키 필요 없음)를 보고, 없을 때만 KOSIS(키 필요)를 쓴다. 숫자를 지어내지 않는다. 못 찾으면 [확인 필요]로 알리고 교사에게 숫자를 받는다.
29
+ 2. find_data 로 실제 통계를 찾는다. 한국 시·도·시·군·구 통계는 먼저 list_bundled_data에 query와 summary:true를 보내 후보를 찾고, 없을 때만 KOSIS(키 필요)를 쓴다. 숫자를 지어내지 않는다. 못 찾으면 [확인 필요]로 알리고 교사에게 숫자를 받는다.
29
30
  3. 만들기 전에 반드시 '계획 요약'을 보여 주고 교사의 "예"를 받는다:
30
31
  지표·단위 / 기준 연도 / 지역과 기호(A~E 또는 (가)~(마)) / 가공(지수·비율·편차·반올림) / 기호 순서(무작위·북→남·서→동·지정) / 출력(PPTX·HWPX) / 출처 문구
31
- 4. 계획 요약과 함께 preview_figures 로 시안 그림을 보여 준다. 지도 기호 스타일을 교사가 정하지 않았으면 compareLabelStyles:true 로 4가지를 보여 주고 고르게 한다. 교사가 ‘예’라고 하면 make_figures 로 만들고, 파일 위치(원격이면 내려받기 주소)와 정답표를 알려 준다.
32
+ 4. 계획 요약과 함께 preview_figures 로 시안 그림을 보여 준다. 그림마다 기본 시안을 보여 주고, 기호를 비교할 때만 compareLabelStyles:true를 쓴다. 교사가 ‘예’라고 하면 make_figures로 만든다. 로컬에서 명세가 같으면 figures 대신 previewId를 쓴다. 파일 위치와 정답표를 알려 준다.
32
33
  5. 만든 뒤 고치기(범례·단계·지역·기호·순서): open_figure_spec 으로 설계도를 읽어 그 부분만 바꾸고 make_figures 를 다시 부른다. 통계를 다시 찾지 않는다. 손으로 고칠 땐 그룹 해제(개체 풀기) 한 번이면 모든 도형이 따로 움직인다고 알려 준다.
33
34
 
34
35
  [품질 규칙 — 교사 기준 + 경기도교육청 지리 문항 제작 자료]
35
36
  - 흑백 인쇄로 구분돼야 한다: 색 대신 빗금·회색 농도(자동).
36
- - 정답 단서를 드러내지 않는다: 지명·국가명은 기호로 바꾸고, 정답표는 파일 마지막 장에 둔다.
37
+ - 정답 단서를 드러내지 않는다: 지명·국가명은 기호로 바꾸고, 정답표는 로컬 파일 마지막 장 또는 원격 응답에 둔다.
37
38
  - 경계는 자료 연도에 맞춘다: 2026년 7월 이후 자료는 2026년 판(16개 시·도, '전남광주'), 그 전 자료는 map.edition:'2025'(17개 시·도). 내장 자료는 mapEdition 과 mapName 을 알려 준다.
38
39
  - 출처와 기준 연도를 꼭 적는다: 출처는 그림 오른쪽 아래(자동). 지도 출처도 함께.
39
40
  - 전도(세계·대륙·우리나라 전체)가 아닌 지도에는 축척을 넣는다(자동).
@@ -42,15 +43,40 @@ const GUIDE = `
42
43
  - 판별용 지역은 suggest_regions 로 서로 잘 갈리는 곳을 고른다.
43
44
  `;
44
45
 
46
+ const INSTRUCTIONS = [
47
+ '지리 시험 자료는 실제 통계와 출처를 쓴다. 한국 자료는 list_bundled_data에 query와 summary:true를 보내 먼저 찾는다.',
48
+ '지표·연도·지역·가공·기호·출력·출처와 시안을 제시하고 교사 확인 후 make_figures를 부른다.',
49
+ '기호를 비교할 때만 4종 시안을 요청한다. 로컬에서 명세가 같으면 previewId를 재사용한다.',
50
+ '행정구역 판은 자료 연도에 맞춘다. 정답표는 로컬 파일 마지막 장 또는 원격 응답에 둔다.',
51
+ '필요할 때 guide의 topic으로 workflow 또는 spec을 선택한다.',
52
+ ].join('\n');
53
+ const PREVIEW_TTL_MS = 30 * 60 * 1000;
54
+ const MAX_PREVIEWS = 8;
55
+ const MAX_PREVIEW_SPEC_BYTES = 64 * 1024;
56
+ const figureSpecs = z.array(z.object({ title: z.string().optional() }).passthrough());
57
+ const figureStyle = z.object({ font: z.string().optional(), fontPptx: z.string().optional(), size: z.number().optional(), small: z.number().optional(), width: z.number().optional() });
58
+ const LABEL_NAMES = { halo: '① 흰 테두리(기본)', plain: '② 바탕 없음', box: '③ 네모 흰 바탕', circle: '④ 작은 원 흰 바탕' };
59
+ const hasMap = (f) => f.map || f.parts?.some((p) => p.map);
60
+ const withLabelStyle = (f, labelStyle) => {
61
+ const apply = (p) => p.map ? { ...p, map: { ...p.map, labelStyle } } : p;
62
+ return f.parts ? { ...f, parts: f.parts.map(apply) } : apply(f);
63
+ };
64
+
45
65
  export function createServer({ remote = false, publish = null } = {}) {
46
- const server = new McpServer({ name: 'geo-figure-mcp', version: PKG_VERSION }, { instructions: `지리 시험용 지도·그래프 제작 도구.\n${GUIDE}` });
47
- const ok = (obj) => ({ content: [{ type: 'text', text: typeof obj === 'string' ? obj : JSON.stringify(obj, null, 1) }] });
48
- const fail = (e) => ({ isError: true, content: [{ type: 'text', text: `오류: ${e.message || e}` }] });
66
+ const server = new McpServer({ name: 'geo-figure-mcp', version: PKG_VERSION }, { instructions: INSTRUCTIONS });
67
+ const previews = new Map();
68
+ const ok = (obj) => ({ content: [{ type: 'text', text: typeof obj === 'string' ? obj : JSON.stringify(obj) }] });
69
+ const fail = (e) => ({ isError: true, content: [{ type: 'text', text: '오류: ' + (e.message || e) }] });
49
70
  const wrap = (fn) => async (a) => { try { return ok(await fn(a)); } catch (e) { return fail(e); } };
50
71
 
51
- server.tool('guide', '이 도구의 작업 순서와 시험 자료 품질 규칙, 그림 명세(spec) 작성법을 돌려준다. 처음 쓸 때 먼저 부른다.', {}, wrap(() => (updateNotice() ? `[알림] ${updateNotice()}
52
- ` : '') + `geo-figure-mcp ${PKG_VERSION}
53
- ` + GUIDE + SPEC_HELP));
72
+ server.tool('guide', '필요할 때 제작 순서(workflow) 또는 그림 명세(spec)를 조회한다. 인자 없이 호출하면 둘 다 반환한다.', {
73
+ topic: z.enum(['workflow', 'spec']).optional(),
74
+ }, wrap(({ topic }) => [
75
+ updateNotice(),
76
+ 'geo-figure-mcp ' + PKG_VERSION,
77
+ topic !== 'spec' && GUIDE,
78
+ topic !== 'workflow' && SPEC_HELP,
79
+ ].filter(Boolean).join('\n')));
54
80
 
55
81
  server.tool('list_sources', '쓸 수 있는 통계 자료원과 지표 예시를 보여 준다.', {}, wrap(() => SOURCES));
56
82
 
@@ -68,7 +94,17 @@ server.tool('list_exam_climate_spots', '평가원 기후 기출 지점(2022~2026
68
94
  code: z.string().optional().describe("기후 기호로 거르기. 예: 'Cs', 'BW', 'Df'"),
69
95
  }, wrap((a) => examSpots().filter((s) => !a.code || (s.code || '').startsWith(a.code)).map((s) => ({ name: s.name, code: s.code, exams: s.exams, lat: s.lat, lon: s.lon, data: s.climate ? s.climate.source : (s.lat == null ? '좌표 없음' : 'WMO') }))));
70
96
 
71
- server.tool('list_bundled_data', '키 없이 쓰는 내장 KOSIS 통계 목록(주제·기간·항목·분류). KOSIS 를 직접 부르기 전에 먼저 여기서 찾는다.', {}, wrap(() => bundleList()));
97
+ server.tool('list_bundled_data', '내장 KOSIS 통계 목록. query로 찾고 summary:true로 키와 주제만 본다. 선택한 키로 다시 조회하면 항목과 기간을 볼 수 있다.', {
98
+ query: z.string().optional().describe('표 키 또는 검색어'),
99
+ summary: z.boolean().optional().describe('키와 주제만 반환'),
100
+ }, wrap(({ query, summary }) => {
101
+ const terms = query?.toLowerCase().trim().split(/\s+/).filter(Boolean) || [];
102
+ const tables = bundleList().filter(({ key, topic, title, items }) => {
103
+ const text = [key, topic, title, ...items].join(' ').toLowerCase();
104
+ return terms.every((term) => text.includes(term));
105
+ });
106
+ return summary ? tables.map(({ key, topic }) => ({ key, topic })) : tables;
107
+ }));
72
108
 
73
109
  if (!remote) {
74
110
  server.tool('kosis_search', 'KOSIS 국가통계포털에서 통계표를 찾는다(시·도·시·군·구 통계). 인증키 필요 — 먼저 list_bundled_data 를 본다.', {
@@ -110,48 +146,77 @@ server.tool('assign_labels', '지역 이름을 A~E 또는 (가)~(마) 기호로
110
146
  }, wrap((a) => assignLabels(a.names, a)));
111
147
 
112
148
  server.tool('make_figures', '그림 명세로 PPTX·HWPX 파일을 만든다. 만들기 전에 교사에게 계획 요약을 보여 주고 확인을 받았는지 먼저 확인한다. 명세 작성법은 guide.', {
113
- figures: z.array(z.object({ title: z.string().optional() }).passthrough()).describe('그림 명세 목록 — guide 의 [그림 명세] 참고'),
149
+ figures: (remote ? figureSpecs : figureSpecs.optional()).describe('그림 명세 목록. guide의 spec 참고'),
150
+ ...(remote ? {} : {
151
+ previewId: z.string().optional().describe('명세가 같으면 figures 대신 로컬 시안 ID'),
152
+ labelStyle: z.enum(['halo', 'plain', 'box', 'circle']).optional().describe('기호 비교 시안에서 교사가 선택한 스타일'),
153
+ }),
114
154
  name: z.string().default('지리자료').describe('파일 이름(확장자 제외)'),
115
155
  formats: z.array(z.enum(['pptx', 'hwpx'])).default(['pptx', 'hwpx']),
116
156
  answerKey: z.string().optional().describe(remote ? '정답표 — 원격 서버에서는 파일에 넣지 않고 대화창에만 돌려준다(시험 보안)' : '정답표 — 파일 마지막 장에 들어간다. 첫 줄은 제목'),
117
157
  ...(remote ? {} : { outDir: z.string().optional().describe(`저장 폴더(기본 ${OUT})`) }),
118
- style: z.object({ font: z.string().optional(), fontPptx: z.string().optional(), size: z.number().optional(), small: z.number().optional(), width: z.number().optional() }).optional().describe('이번 파일에만 쓸 글꼴·크기(학교 양식)'),
158
+ style: figureStyle.optional().describe('이번 파일에만 쓸 글꼴·크기(학교 양식)'),
119
159
  confirmed: z.boolean().describe('교사가 계획 요약을 보고 "예"라고 했으면 true'),
120
160
  }, wrap(async (a) => {
121
161
  if (!a.confirmed) throw new Error('먼저 계획 요약(지표·연도·지역·가공·기호 순서·출력·출처)을 교사에게 보여 주고 확인을 받으세요.');
122
- if (remote && a.figures.length > 12) throw new Error('한 번에 그림은 12장까지 만들 수 있습니다.');
123
- const st = { ...loadStyle(), ...(a.style || {}) };
162
+ let { figures, style } = a;
163
+ let st;
164
+ if (a.previewId !== undefined) {
165
+ if (figures !== undefined || style !== undefined) throw new Error('previewId는 figures 또는 style과 함께 쓸 수 없습니다. 명세를 바꾸려면 새 시안을 만드세요.');
166
+ const preview = previews.get(a.previewId);
167
+ if (!preview || preview.expires <= Date.now()) {
168
+ previews.delete(a.previewId);
169
+ throw new Error('시안 ID가 만료되었거나 없습니다. 다시 시안을 만들거나 원래 figures를 보내세요.');
170
+ }
171
+ if (a.labelStyle && preview.compareIndex < 0) throw new Error('labelStyle은 기호 비교 시안 ID와 함께 쓸 수 있습니다.');
172
+ if (preview.compareIndex >= 0 && !a.labelStyle) throw new Error('기호 비교 시안에서는 교사가 선택한 labelStyle을 지정하세요.');
173
+ ({ figures, style, st } = preview);
174
+ if (a.labelStyle) figures = figures.map((f, i) => i === preview.compareIndex ? withLabelStyle(f, a.labelStyle) : f);
175
+ } else if (!figures || a.labelStyle !== undefined) {
176
+ throw new Error('figures 또는 로컬 previewId를 보내세요. labelStyle은 지도 명세 안에 지정할 수 있습니다.');
177
+ }
178
+ if (remote && figures.length > 12) throw new Error('한 번에 그림은 12장까지 만들 수 있습니다.');
179
+ st ??= { ...loadStyle(), ...style };
124
180
  const figs = [];
125
- for (const f of a.figures) figs.push(await makeFigure(f, st));
181
+ for (const f of figures) figs.push(await makeFigure(f, st));
126
182
  const safe = String(a.name || '지리자료').replace(/[\/:*?"<>|]/g, '_').slice(0, 60);
127
183
  const dir = remote ? publish.newDir() : (a.outDir || OUT);
128
184
  const paths = exportFigures(figs, { outDir: dir, name: safe, formats: a.formats, answerKey: remote ? undefined : a.answerKey, style: st });
129
185
  const files = remote ? paths.map((p) => publish.url(p)) : paths;
130
186
  // 고치기용 설계도: 같은 폴더에 <이름>.geo-figure.json — 나중에 open_figure_spec 으로 읽어 일부만 바꿔 다시 만든다
131
187
  let specFile = null;
132
- if (!remote) { specFile = path.join(dir, `${safe}.geo-figure.json`); fs.writeFileSync(specFile, JSON.stringify({ name: safe, formats: a.formats, style: a.style, answerKey: a.answerKey, figures: a.figures }, null, 1)); }
188
+ if (!remote) { specFile = path.join(dir, `${safe}.geo-figure.json`); fs.writeFileSync(specFile, JSON.stringify({ name: safe, formats: a.formats, style, answerKey: a.answerKey, figures }, null, 1)); }
133
189
  return { files, ...(updateNotice() ? { update: updateNotice() } : {}), ...(remote ? { expires: `내려받기 주소는 ${publish.keepText} 동안, 한 번만 열립니다(받으면 서버에서 바로 지움). 꼭 내려받아 저장하세요.`, ...(a.answerKey ? { answerKey: a.answerKey, answerKeyNote: '시험 보안을 위해 정답표는 파일에 넣지 않았습니다. 이 내용을 교사에게 그대로 보여 주세요.' } : {}) } : {}), sizes_mm: figs.map((f) => ({ title: f.title, w: round(f.w), h: round(f.h) })), ...(specFile ? { specFile } : {}), note: '그림마다 묶음 하나 — PPTX는 그룹 해제, HWPX는 개체 풀기를 한 번만 하면 시군구·기호·선·범례가 모두 따로 움직인다(도형 이름이 지역 이름). 범례 칸과 지역은 같은 무늬라 서식 복사로 단계를 바꿀 수 있다. 범례·지역·기호를 크게 바꾸려면 open_figure_spec 으로 설계도를 읽어 고친 뒤 make_figures 를 다시 부른다.' };
134
190
  }));
135
191
 
136
- server.tool('preview_figures', '시안(미리보기 그림)을 대화창에 바로 보여 준다 — 파일을 만들기 전에 쓴다. 기호 스타일이 정해지지 않았으면 compareLabelStyles:true 로 4가지(흰 테두리·바탕 없음·네모 바탕·원 바탕)를 나란히 보여 주고 교사가 고르게 한다. 고른 뒤 make_figures 로 파일을 만든다.', {
137
- figures: z.array(z.object({ title: z.string().optional() }).passthrough()).describe('make_figures 와 같은 그림 명세'),
138
- compareLabelStyles: z.boolean().optional().describe('true 면 첫 지도 그림을 기호 스타일 4가지로 그려 비교'),
139
- style: z.object({ font: z.string().optional(), fontPptx: z.string().optional(), size: z.number().optional(), small: z.number().optional(), width: z.number().optional() }).optional(),
192
+ server.tool('preview_figures', '파일을 만들기 전 PNG 시안을 보여 준다. 기호 비교가 필요하면 compareLabelStyles:true를 쓴다. 로컬 previewId는 make_figures에서 재사용할 수 있다.', {
193
+ figures: figureSpecs.describe('make_figures와 같은 그림 명세'),
194
+ compareLabelStyles: z.boolean().optional().describe('true면 첫 지도에 기호 스타일 4개를 비교'),
195
+ style: figureStyle.optional(),
140
196
  }, async (a) => {
141
197
  try {
142
198
  const st = { ...loadStyle(), ...(a.style || {}) };
143
199
  const content = [];
144
- const NAMES = { halo: '① 흰 테두리(기본)', plain: '② 바탕 없음', box: '③ 네모 흰 바탕', circle: '④ 작은 원 흰 바탕' };
145
- const withStyle = (f, k) => JSON.parse(JSON.stringify(f, (key, v) => (key === 'map' && v && typeof v === 'object' ? { ...v, labelStyle: k } : v)));
146
- const base = a.figures.find((x) => x.map || x.parts?.some((p) => p.map)) || a.figures[0];
147
- const list = a.compareLabelStyles
148
- ? Object.keys(NAMES).map((k) => ({ cap: NAMES[k], spec: withStyle(base, k) }))
149
- : a.figures.slice(0, 6).map((f, i) => ({ cap: `시안 ${i + 1}: ${f.title || ''}`, spec: f }));
200
+ const compareIndex = a.compareLabelStyles && a.figures.length ? Math.max(0, a.figures.findIndex(hasMap)) : -1;
201
+ const list = compareIndex >= 0
202
+ ? Object.entries(LABEL_NAMES).map(([label, cap]) => ({ cap, spec: withLabelStyle(a.figures[compareIndex], label) }))
203
+ : a.figures.slice(0, 6).map((f, i) => ({ cap: '시안 ' + (i + 1) + ': ' + (f.title || ''), spec: f }));
150
204
  for (const { cap, spec } of list) {
151
205
  const fig = await makeFigure(spec, st);
152
206
  content.push({ type: 'text', text: cap }, { type: 'image', mimeType: 'image/png', data: Buffer.from(renderPng(fig, { width: 800 })).toString('base64') });
153
207
  }
154
- content.push({ type: 'text', text: a.compareLabelStyles ? '교사에게 ①~④ 중 하나를 고르게 하고, 그 값(halo·plain·box·circle)을 map.labelStyle 에 넣어 make_figures 를 부른다.' : '교사가 괜찮다고 하면 같은 명세로 make_figures(confirmed:true)를 부른다. 고칠 점이 있으면 고쳐서 다시 미리 본다.' });
208
+ let how = compareIndex >= 0 ? '기호 ①~④ 중 하나를 고르세요(halo·plain·box·circle).' : '교사 확인 후 파일을 만드세요.';
209
+ const allFiguresShown = compareIndex >= 0 ? a.figures.length === 1 : list.length === a.figures.length;
210
+ if (!remote && list.length && allFiguresShown && Buffer.byteLength(JSON.stringify(a)) <= MAX_PREVIEW_SPEC_BYTES) {
211
+ const id = randomBytes(8).toString('hex');
212
+ if (previews.size >= MAX_PREVIEWS) previews.delete(previews.keys().next().value);
213
+ previews.set(id, { figures: a.figures, style: a.style, st, compareIndex, expires: Date.now() + PREVIEW_TTL_MS });
214
+ how += '\npreviewId: ' + id + '\nmake_figures에 figures 대신 이 ID를 보내세요.';
215
+ if (compareIndex >= 0) how += ' 선택한 labelStyle도 보내세요.';
216
+ } else {
217
+ how += ' make_figures에 figures를 보내세요.';
218
+ }
219
+ content.push({ type: 'text', text: how });
155
220
  return { content };
156
221
  } catch (e) { return { isError: true, content: [{ type: 'text', text: `오류: ${e.message || e}` }] }; }
157
222
  });