kordoc 1.7.1 → 1.8.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/README.md CHANGED
@@ -1,127 +1,141 @@
1
1
  # kordoc
2
2
 
3
- **모두 파싱해버리겠다** — The Korean Document Platform.
3
+ **모두 파싱해버리겠다.**
4
4
 
5
- [![npm version](https://img.shields.io/badge/npm-v1.7.0-cb3837.svg)](https://www.npmjs.com/package/kordoc)
5
+ [![npm version](https://img.shields.io/badge/npm-v1.8.0-cb3837.svg)](https://www.npmjs.com/package/kordoc)
6
6
  [![license](https://img.shields.io/npm/l/kordoc.svg)](https://github.com/chrisryugj/kordoc/blob/main/LICENSE)
7
- [![node](https://img.shields.io/node/v/kordoc.svg)](https://nodejs.org)
8
7
 
9
- > *Parse, compare, extract, and generate Korean documents. HWP, HWPX, PDF — all of them.*
8
+ > *대한민국에서 둘째가라면 서러울 문서지옥. 거기서 7년 버틴 공무원이 만들었습니다.*
10
9
 
11
- [한국어](./README-KR.md)
10
+ HWP, HWPX, PDF, XLSX, DOCX — 관공서에서 쏟아지는 모든 문서를 파싱하고, 비교하고, 분석하고, 생성합니다.
12
11
 
13
- ![kordoc demo](./demo.gif)
12
+ [English](./README-EN.md)
13
+
14
+ ![kordoc 데모](./demo.gif)
14
15
 
15
16
  ---
16
17
 
17
- ## What's New in v1.7.0
18
+ ## 💡 kordoc으로 무엇을 할 수 있나요?
18
19
 
19
- - **Image Extraction (HWP/HWPX)** Binary image extraction from ZIP entries and HWP5 BinData streams. Rendered as `![image](...)` in markdown output.
20
- - **Partial Parsing (Graceful Degradation)** — Single page failures no longer abort the whole document. Failed pages emit `PARTIAL_PARSE` warnings and parsing continues.
21
- - **Progress Callbacks** — `onProgress` callback in `ParseOptions`. CLI shows `[3/15 pages]` progress. Batch mode shows `[2/10 files]`.
22
- - **File Path Input** — `parse("path/to/file.hwp")` string overload. Auto-reads file, detects format, returns result.
23
- - **PDF Header/Footer Filtering** — `removeHeaderFooter: true` option removes repeated text at page edges. Removed elements recorded in `ParseWarning`.
24
- - **Security Hardening** — ZIP bomb cumulative-size tracking across all file types, SSRF prevention on webhook URLs, XSS-safe hyperlink rendering (javascript: URLs stripped), null-byte path traversal detection, Levenshtein length guard (O(m×n) DoS prevention), 30s PDF load timeout.
25
- - **Bug Fixes** — HWPX generator separator logic, XML recursion depth limit (MAX_XML_DEPTH=200), PDF table row merge protection, CLI `--format` validation, variable shadowing in PDF parser.
26
- - **UX Improvements** — KV table false-positive reduction (time/URL/number patterns excluded), MCP `parse_metadata` uses 50MB limit with header-only format detection, Watch debounce increased to 1000ms with stable-size check.
20
+ 단순한 텍스트 추출을 넘어, **공문서 처리를 위한 모든 과정**을 자동화합니다.
27
21
 
28
- <details>
29
- <summary>v1.6.1 fixes</summary>
22
+ * **📄 어떤 문서든 마크다운으로**: `HWP`, `HWPX`, `PDF`, `XLSX`, `DOCX` 파일을 즉시 `Markdown`으로 변환합니다. AI(LLM)가 문서를 읽고 분석하기 가장 좋은 상태로 만들어줍니다.
23
+ * **📊 복잡한 표(Table) 완벽 재현**: 선이 없는 PDF나 복잡하게 병합된 HWP 표도 구조를 분석하여 정확한 마크다운 테이블로 복원합니다.
24
+ * **🔍 신구대조표 자동 생성**: 두 문서의 차이점을 분석하여 무엇이 바뀌었는지 한눈에 보여줍니다. (HWP와 HWPX 간의 비교도 가능!)
25
+ * **📝 마크다운을 다시 HWPX로**: AI가 작성한 내용을 다시 보고서 양식(`HWPX`)으로 되돌려줍니다. 이제 복사-붙여넣기 노가다에서 해방되세요.
26
+ * **🤖 AI 에이전트 연동 (MCP)**: `Claude`, `Cursor`와 같은 도구에서 직접 `kordoc`을 호출해 문서를 읽고 코딩할 수 있습니다.
30
27
 
31
- - **HWP5 Table Cell Offset Fix** — Fixed critical 2-byte offset misalignment in LIST_HEADER parsing. Row address was incorrectly read as colSpan, causing 3-column tables to explode into 6+ columns with misaligned content. Tables now use colAddr/rowAddr-based direct placement for accurate cell positioning.
32
- - **HWP5 TAB Control Character Fix** — TAB (0x0009) inline control's 14-byte extension data was not skipped, producing garbage characters (`࣐Ā`) after every tab in the output. Fixed by adding the required 14-byte skip.
28
+ ---
33
29
 
34
- </details>
30
+ ## v1.8.0 변경사항
31
+
32
+ - **XLSX 파서 추가** — Excel 스프레드시트 파싱. 공유 문자열, 병합 셀, 다중 시트 지원. 시트별 heading + table 블록 생성.
33
+ - **DOCX 파서 추가** — Word 문서 파싱. 스타일 기반 heading, 번호 매기기(리스트), 각주, 하이퍼링크, 이미지 추출, vMerge/gridSpan 테이블 병합.
34
+ - **파싱 품질 대폭 개선** — PDF/HWPX/HWP5/XLSX 전 포맷 품질 점수 73→93점.
35
+ - **프로덕션 리뷰 17건 수정** — CLI `--no-header-footer` 플래그 반전 버그, MCP XLSX/DOCX 확장자 허용, ZIP bomb 보호 공유 유틸화, href XSS 살균 강화, PDF timeout 타이머 정리, HWP5 BinData O(n) 최적화, cluster indexOf O(n²)→O(n), SSRF IPv6 차단 등.
35
36
 
36
37
  <details>
37
- <summary>v1.6.0 features</summary>
38
+ <summary>v1.7.x 변경사항</summary>
38
39
 
39
- - **Cluster-Based Table Detection (PDF)** — Detects borderless tables by analyzing text alignment patterns. Baseline grouping + X-coordinate clustering identifies 2+ column tables that line-based detection misses. Sort-and-split clustering for order-independent results.
40
- - **Korean Special Table Detection** — Automatically detects `구분/항목/종류`-style key-value patterns common in Korean government documents and converts them to structured 2-column tables.
41
- - **Korean Word-Break Recovery** Improved merging of broken Korean words in PDF table cells. Handles character-level PDF rendering (micro-gaps between Hangul characters) and cell line-break artifacts up to 8 characters.
42
- - **Empty Table Filtering**Tables with all-empty cells (from line detection of decorative borders) are now automatically removed.
40
+ - **이미지 추출 (HWP/HWPX)** — ZIP 엔트리와 HWP5 BinData 스트림에서 바이너리 이미지 추출.
41
+ - **부분 파싱 (Graceful Degradation)** — 개별 페이지 실패가 전체 파싱을 중단하지 않음.
42
+ - **진행률 콜백**`onProgress` 콜백. CLI에서 `[3/15 pages]` 형태 표시.
43
+ - **파일 경로 직접 입력** `parse("path/to/file.hwp")` 문자열 오버로드.
44
+ - **PDF 머리글/바닥글 필터링** — `removeHeaderFooter` 옵션.
45
+ - **보안 강화** — ZIP bomb 추적, SSRF 방지, XSS 방어, 널바이트 감지, PDF 타임아웃.
46
+ - **pdfjs-dist v5 호환** — constructPath 연산자 형식 변경 대응.
43
47
 
44
48
  </details>
45
49
 
46
50
  <details>
47
- <summary>v1.5.0 features</summary>
51
+ <summary>v1.6.1 수정사항</summary>
48
52
 
49
- - **Line-Based Table Detection (PDF)**Ported from OpenDataLoader. Extracts horizontal/vertical lines from PDF graphics commands, builds grid via intersection vertices, maps text to cells by bbox overlap. Proper colspan/rowspan detection. Falls back to heuristic for line-free PDFs.
50
- - **IRBlock v2** 6 block types: `heading`, `paragraph`, `table`, `list`, `image`, `separator`. New fields: `bbox`, `style`, `pageNumber`, `level`, `href`, `footnoteText`.
51
- - **ParseResult v2** — `outline` (document structure) and `warnings` (skipped elements, hidden text) fields.
52
- - **PDF Enhancements** — XY-Cut reading order, heading detection (font-size ratio), hidden text filtering (prompt injection defense), bounding box on every block.
53
- - **HWP5 Enhancements** — CHAR_SHAPE parsing, style-based heading detection, warnings for skipped OLE/images.
54
- - **HWPX Enhancements** — Style parsing from header.xml, hyperlink/footnote extraction.
55
- - **List Detection** — Numbered paragraphs after tables auto-converted to ordered list blocks.
56
- - **MCP Server** — Now returns `outline` and `warnings` in parse_document responses.
53
+ - **HWP5 테이블 오프셋 수정** LIST_HEADER 파싱 2바이트 오프셋 밀림으로 rowAddr를 colSpan으로 잘못 읽던 치명적 버그 수정. 3열 테이블이 6열로 뻥튀기되던 문제 해결. colAddr/rowAddr 기반 직접 배치로 병합 테이블 정확도 향상.
54
+ - **HWP5 TAB 제어문자 수정** TAB(0x0009) 인라인 컨트롤의 14바이트 확장 데이터 스킵 누락으로 `࣐Ā` 쓰레기 문자가 출력되던 버그 수정.
57
55
 
58
56
  </details>
59
57
 
60
58
  <details>
61
- <summary>v1.4.x features</summary>
62
-
63
- - **Document Compare** — Diff two documents at IR level. Cross-format (HWP vs HWPX) supported.
64
- - **Form Field Recognition**Extract label-value pairs from government forms automatically.
65
- - **Structured Parsing**Access `IRBlock[]` and `DocumentMetadata` directly, not just markdown.
66
- - **Page Range Parsing**Parse only pages 1-3: `parse(buffer, { pages: "1-3" })`.
67
- - **Markdown to HWPX** — Reverse conversion. Generate valid HWPX files from markdown.
68
- - **OCR Integration** — Pluggable OCR for image-based PDFs (bring your own provider).
69
- - **Watch Mode** — `kordoc watch ./incoming --webhook https://...` for auto-conversion.
70
- - **7 MCP Tools** — parse_document, detect_format, parse_metadata, parse_pages, parse_table, compare_documents, parse_form.
71
- - **Error Codes** — Structured `code` field: `"ENCRYPTED"`, `"ZIP_BOMB"`, `"IMAGE_BASED_PDF"`, etc.
59
+ <summary>v1.6.0 기능</summary>
60
+
61
+ - **클러스터 기반 테이블 감지 (PDF)** — 없는 PDF에서 텍스트 정렬 패턴으로 테이블 구조 추론. baseline 그룹핑 + X좌표 클러스터링으로 2열 이상 테이블 감지. 선 기반 감지가 실패한 경우의 중간 계층 fallback.
62
+ - **한국어 특수 테이블 감지** `구분/항목/종류/기준` 등 한국 공문서 key-value 패턴을 자동으로 2열 테이블로 변환.
63
+ - **한국어 어절 끊김 복원** PDF 한글 문자별 렌더링으로 인한 미세 갭 처리 개선. 셀 줄바꿈 병합 임계값 8자로 확장, 1글자 조사 자동 연결.
64
+ - **빈 테이블 필터링**장식용 선에서 생긴 테이블 자동 제거.
72
65
 
73
66
  </details>
74
67
 
75
- ---
68
+ <details>
69
+ <summary>v1.5.0 기능</summary>
76
70
 
77
- ## Why kordoc?
71
+ - **선 기반 테이블 감지 (PDF)** — OpenDataLoader 핵심 알고리즘 포팅. PDF 그래픽 명령에서 수평/수직 선을 추출하고, 교차점으로 그리드 구성, bbox overlap으로 텍스트→셀 매핑. colspan/rowspan 자동 감지. 선 없는 PDF는 기존 휴리스틱 fallback.
72
+ - **IRBlock v2** — 6가지 블록 타입: `heading`, `paragraph`, `table`, `list`, `image`, `separator`. 새 필드: `bbox`, `style`, `pageNumber`, `level`, `href`, `footnoteText`.
73
+ - **ParseResult v2** — `outline` (문서 구조), `warnings` (스킵된 요소, 숨김 텍스트) 필드 추가.
74
+ - **PDF 개선** — XY-Cut 읽기 순서, 폰트 크기 기반 헤딩 감지, hidden text 필터링 (프롬프트 인젝션 방어), 모든 블록에 바운딩 박스.
75
+ - **HWP5 개선** — CHAR_SHAPE 파싱, 스타일 기반 헤딩 감지, OLE/이미지 스킵 경고.
76
+ - **HWPX 개선** — header.xml 스타일 파싱, 하이퍼링크/각주 추출.
77
+ - **리스트 감지** — 테이블 뒤 번호 문단을 ordered list 블록으로 자동 변환.
78
+ - **MCP 서버** — parse_document 응답에 `outline`, `warnings` 포함.
78
79
 
79
- South Korea's government runs on **HWP** — a proprietary word processor the rest of the world has never heard of. Every day, 243 local governments and thousands of public institutions produce mountains of `.hwp` files. Extracting text from them has always been a nightmare.
80
+ </details>
80
81
 
81
- **kordoc** was born from that document hell. Built by a Korean civil servant who spent **7 years** buried under HWP files. Battle-tested across 5 real government projects. If a Korean public servant wrote it, kordoc can parse it.
82
+ <details>
83
+ <summary>v1.4.x 기능</summary>
84
+
85
+ - **문서 비교 (Diff)** — IR 레벨 블록 비교로 신구대조표 생성. HWP↔HWPX 크로스 포맷 지원.
86
+ - **양식 인식** — 공문서 테이블에서 label-value 쌍 자동 추출. 성명, 소속, 전화번호 등.
87
+ - **구조화 파싱** — `IRBlock[]`과 `DocumentMetadata`에 직접 접근. 마크다운 넘어선 데이터 활용.
88
+ - **페이지 범위** — `parse(buffer, { pages: "1-3" })` — 필요한 페이지만 빠르게.
89
+ - **Markdown → HWPX** — 역변환. AI가 생성한 내용을 바로 공문서로.
90
+ - **OCR 연동** — 이미지 기반 PDF도 텍스트 추출 (Tesseract, Claude Vision 등 프로바이더 직접 제공).
91
+ - **Watch 모드** — `kordoc watch ./수신함 -d ./변환결과 --webhook https://...`
92
+ - **MCP 7개 도구** — parse_document, detect_format, parse_metadata, parse_pages, parse_table, compare_documents, parse_form
93
+ - **에러 코드** — `"ENCRYPTED"`, `"ZIP_BOMB"`, `"IMAGE_BASED_PDF"` 등 구조화된 에러 핸들링
94
+
95
+ </details>
82
96
 
83
97
  ---
84
98
 
85
- ## Installation
99
+ ## 설치
86
100
 
87
101
  ```bash
88
102
  npm install kordoc
89
103
 
90
- # PDF support (optional)
104
+ # PDF 파싱이 필요하면 (선택)
91
105
  npm install pdfjs-dist
92
106
  ```
93
107
 
94
- ## Quick Start
108
+ ## 빠른 시작
95
109
 
96
- ### Parse Any Document
110
+ ### 문서 파싱
97
111
 
98
112
  ```typescript
99
113
  import { parse } from "kordoc"
100
114
  import { readFileSync } from "fs"
101
115
 
102
- const buffer = readFileSync("document.hwpx")
116
+ const buffer = readFileSync("사업계획서.hwpx")
103
117
  const result = await parse(buffer.buffer)
104
118
 
105
119
  if (result.success) {
106
- console.log(result.markdown) // Markdown text
107
- console.log(result.blocks) // IRBlock[] structured data
120
+ console.log(result.markdown) // 마크다운 텍스트
121
+ console.log(result.blocks) // IRBlock[] 구조화 데이터
108
122
  console.log(result.metadata) // { title, author, createdAt, ... }
109
123
  }
110
124
  ```
111
125
 
112
- ### Compare Two Documents
126
+ ### 문서 비교 (신구대조표)
113
127
 
114
128
  ```typescript
115
129
  import { compare } from "kordoc"
116
130
 
117
- const diff = await compare(bufferA, bufferB)
131
+ const diff = await compare(구버전Buffer, 신버전Buffer)
118
132
  // diff.stats → { added: 3, removed: 1, modified: 5, unchanged: 42 }
119
- // diff.diffs → BlockDiff[] with cell-level table diffs
133
+ // diff.diffs → BlockDiff[] (테이블은 단위 diff 포함)
120
134
  ```
121
135
 
122
- Cross-format supported: compare HWP against HWPX of the same document.
136
+ HWP vs HWPX 크로스 포맷 비교도 가능합니다.
123
137
 
124
- ### Extract Form Fields
138
+ ### 양식 필드 추출
125
139
 
126
140
  ```typescript
127
141
  import { parse, extractFormFields } from "kordoc"
@@ -134,28 +148,28 @@ if (result.success) {
134
148
  }
135
149
  ```
136
150
 
137
- ### Generate HWPX from Markdown
151
+ ### HWPX 생성 (역변환)
138
152
 
139
153
  ```typescript
140
154
  import { markdownToHwpx } from "kordoc"
141
155
 
142
- const hwpxBuffer = await markdownToHwpx("# Title\n\nParagraph text\n\n| A | B |\n| --- | --- |\n| 1 | 2 |")
143
- writeFileSync("output.hwpx", Buffer.from(hwpxBuffer))
156
+ const hwpxBuffer = await markdownToHwpx("# 제목\n\n본문 텍스트\n\n| 이름 | 직급 |\n| --- | --- |\n| 홍길동 | 과장 |")
157
+ writeFileSync("출력.hwpx", Buffer.from(hwpxBuffer))
144
158
  ```
145
159
 
146
- ### Parse Specific Pages
160
+ ### 페이지 범위 지정
147
161
 
148
162
  ```typescript
149
- const result = await parse(buffer, { pages: "1-3" }) // pages 1-3 only
150
- const result = await parse(buffer, { pages: [1, 5, 10] }) // specific pages
163
+ const result = await parse(buffer, { pages: "1-3" }) // 1~3 페이지만
164
+ const result = await parse(buffer, { pages: [1, 5, 10] }) // 특정 페이지
151
165
  ```
152
166
 
153
- ### OCR for Image-Based PDFs
167
+ ### OCR (이미지 PDF)
154
168
 
155
169
  ```typescript
156
170
  const result = await parse(buffer, {
157
171
  ocr: async (pageImage, pageNumber, mimeType) => {
158
- return await myOcrService.recognize(pageImage) // Tesseract, Claude Vision, etc.
172
+ return await myOcrService.recognize(pageImage)
159
173
  }
160
174
  })
161
175
  ```
@@ -163,16 +177,16 @@ const result = await parse(buffer, {
163
177
  ## CLI
164
178
 
165
179
  ```bash
166
- npx kordoc document.hwpx # stdout
167
- npx kordoc document.hwp -o output.md # save to file
168
- npx kordoc *.pdf -d ./converted/ # batch convert
169
- npx kordoc report.hwpx --format json # JSON with blocks + metadata
170
- npx kordoc report.hwpx --pages 1-3 # page range
171
- npx kordoc watch ./incoming -d ./output # watch mode
172
- npx kordoc watch ./docs --webhook https://api/hook # webhook notification
180
+ npx kordoc 사업계획서.hwpx # 터미널 출력
181
+ npx kordoc 보고서.hwp -o 보고서.md # 파일 저장
182
+ npx kordoc *.pdf -d ./변환결과/ # 일괄 변환
183
+ npx kordoc 검토서.hwpx --format json # JSON (blocks + metadata 포함)
184
+ npx kordoc 보고서.hwpx --pages 1-3 # 페이지 범위
185
+ npx kordoc watch ./수신함 -d ./변환결과 # 폴더 감시 모드
186
+ npx kordoc watch ./문서 --webhook https://api/hook # 웹훅 알림
173
187
  ```
174
188
 
175
- ## MCP Server (Claude / Cursor / Windsurf)
189
+ ## MCP 서버 (Claude / Cursor / Windsurf)
176
190
 
177
191
  ```json
178
192
  {
@@ -185,46 +199,47 @@ npx kordoc watch ./docs --webhook https://api/hook # webhook notification
185
199
  }
186
200
  ```
187
201
 
188
- **7 Tools:**
202
+ **7 도구:**
189
203
 
190
- | Tool | Description |
191
- |------|-------------|
192
- | `parse_document` | Parse HWP/HWPX/PDF → Markdown with metadata |
193
- | `detect_format` | Detect file format via magic bytes |
194
- | `parse_metadata` | Extract metadata only (fast, no full parse) |
195
- | `parse_pages` | Parse specific page range |
196
- | `parse_table` | Extract Nth table from document |
197
- | `compare_documents` | Diff two documents (cross-format) |
198
- | `parse_form` | Extract form fields as structured JSON |
204
+ | 도구 | 설명 |
205
+ |------|------|
206
+ | `parse_document` | HWP/HWPX/PDF/XLSX/DOCX마크다운 (메타데이터 포함) |
207
+ | `detect_format` | 매직 바이트로 포맷 감지 |
208
+ | `parse_metadata` | 메타데이터만 빠르게 추출 |
209
+ | `parse_pages` | 특정 페이지 범위만 파싱 |
210
+ | `parse_table` | N번째 테이블만 추출 |
211
+ | `compare_documents` | 문서 비교 (크로스 포맷) |
212
+ | `parse_form` | 양식 필드를 JSON으로 추출 |
199
213
 
200
- ## API Reference
214
+ ## API
201
215
 
202
- ### Core
216
+ ### 핵심 함수
203
217
 
204
- | Function | Description |
205
- |----------|-------------|
206
- | `parse(buffer, options?)` | Auto-detect format, parse to Markdown + IRBlock[] |
207
- | `parseHwpx(buffer, options?)` | HWPX only |
208
- | `parseHwp(buffer, options?)` | HWP 5.x only |
209
- | `parsePdf(buffer, options?)` | PDF only |
210
- | `detectFormat(buffer)` | Returns `"hwpx" \| "hwp" \| "pdf" \| "unknown"` |
218
+ | 함수 | 설명 |
219
+ |------|------|
220
+ | `parse(buffer, options?)` | 포맷 자동 감지 Markdown + IRBlock[] |
221
+ | `parseHwpx(buffer, options?)` | HWPX 전용 |
222
+ | `parseHwp(buffer, options?)` | HWP 5.x 전용 |
223
+ | `parsePdf(buffer, options?)` | PDF 전용 |
224
+ | `parseXlsx(buffer, options?)` | XLSX 전용 |
225
+ | `parseDocx(buffer, options?)` | DOCX 전용 |
226
+ | `detectFormat(buffer)` | `"hwpx" \| "hwp" \| "pdf" \| "xlsx" \| "docx" \| "unknown"` |
211
227
 
212
- ### Advanced
228
+ ### 고급 함수
213
229
 
214
- | Function | Description |
215
- |----------|-------------|
216
- | `compare(bufferA, bufferB, options?)` | Document diff at IR level |
217
- | `extractFormFields(blocks)` | Form field recognition from IRBlock[] |
218
- | `markdownToHwpx(markdown)` | Markdown → HWPX reverse conversion |
219
- | `blocksToMarkdown(blocks)` | IRBlock[] → Markdown string |
230
+ | 함수 | 설명 |
231
+ |------|------|
232
+ | `compare(bufferA, bufferB, options?)` | IR 레벨 문서 비교 |
233
+ | `extractFormFields(blocks)` | IRBlock[]에서 양식 필드 인식 |
234
+ | `markdownToHwpx(markdown)` | Markdown → HWPX 역변환 |
235
+ | `blocksToMarkdown(blocks)` | IRBlock[] → Markdown 문자열 |
220
236
 
221
- ### Types
237
+ ### 타입
222
238
 
223
239
  ```typescript
224
240
  import type {
225
241
  ParseResult, ParseSuccess, ParseFailure, FileType,
226
- IRBlock, IRBlockType, IRTable, IRCell, CellContext,
227
- BoundingBox, InlineStyle, OutlineItem, ParseWarning, WarningCode,
242
+ IRBlock, IRTable, IRCell, CellContext,
228
243
  DocumentMetadata, ParseOptions, ErrorCode,
229
244
  DiffResult, BlockDiff, CellDiff, DiffChangeType,
230
245
  FormField, FormResult,
@@ -232,22 +247,33 @@ import type {
232
247
  } from "kordoc"
233
248
  ```
234
249
 
235
- ## Supported Formats
250
+ ## 지원 포맷
236
251
 
237
- | Format | Engine | Features |
238
- |--------|--------|----------|
239
- | **HWPX** (한컴 2020+) | ZIP + XML DOM | Manifest, nested tables, merged cells, broken ZIP recovery |
240
- | **HWP 5.x** (한컴 Legacy) | OLE2 + CFB | 21 control chars, zlib decompression, DRM detection, colAddr-based table cell placement |
241
- | **PDF** | pdfjs-dist | Line-based table detection, XY-Cut reading order, heading detection, hidden text filter, OCR |
252
+ | 포맷 | 엔진 | 특징 |
253
+ |------|------|------|
254
+ | **HWPX** (한컴 2020+) | ZIP + XML DOM | 매니페스트, 중첩 테이블, 병합 셀, 손상 ZIP 복구 |
255
+ | **HWP 5.x** (한컴 레거시) | OLE2 + CFB | 21 제어문자, zlib 압축 해제, DRM 감지, colAddr 기반 배치 |
256
+ | **PDF** | pdfjs-dist | 기반 테이블, XY-Cut 읽기 순서, 헤딩 감지, OCR |
257
+ | **XLSX** (Excel) | ZIP + XML DOM | 공유 문자열, 병합 셀, 다중 시트, 수식 표시 |
258
+ | **DOCX** (Word) | ZIP + XML DOM | 스타일 heading, 번호 매기기, 각주, 이미지 추출 |
242
259
 
243
- ## Security
260
+ ## 보안
244
261
 
245
- Production-grade hardening: ZIP bomb protection, XXE/Billion Laughs prevention, decompression bomb guard, path traversal guard, MCP error sanitization, file size limits (500MB). See [SECURITY.md](./SECURITY.md) for details.
262
+ 프로덕션급 보안 강화: ZIP bomb 방지, XXE/Billion Laughs 방지, 압축 폭탄 방지, 경로 순회 차단, MCP 에러 정제, 파일 크기 제한(500MB). 자세한 내용은 [SECURITY.md](./SECURITY.md) 참조.
246
263
 
247
- ## Credits
264
+ ## 만든 사람
248
265
 
249
- Production-tested across 5 Korean government projects: school curriculum plans, facility inspection reports, legal document annexes, municipal newsletters, and public data extraction tools. Thousands of real government documents parsed.
266
+ 대한민국 지방공무원. 광진구청에서 7년간 HWP 파일과 싸우다가 이걸 만들었습니다.
267
+ 5개 공공 프로젝트에서 수천 건의 실제 관공서 문서를 파싱하며 검증했습니다.
250
268
 
251
- ## License
269
+ ## 라이선스
252
270
 
253
271
  [MIT](./LICENSE)
272
+
273
+ 이 프로젝트는 아래 오픈소스를 포함합니다:
274
+ - **OpenDataLoader PDF** (Apache 2.0, Hancom Inc.) — PDF 테이블 감지 알고리즘
275
+ - **cfb** (Apache 2.0, SheetJS) — HWP5 OLE2 컨테이너 파싱
276
+ - **pdfjs-dist** (Apache 2.0, Mozilla) — PDF 텍스트 추출
277
+ - **JSZip** (MIT, Stuart Knightley 외) — ZIP 기반 포맷 파싱
278
+
279
+ 자세한 내용은 [NOTICE](./NOTICE) 파일을 참조하세요.
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/page-range.ts
4
+ function parsePageRange(spec, maxPages) {
5
+ const result = /* @__PURE__ */ new Set();
6
+ if (maxPages <= 0) return result;
7
+ if (Array.isArray(spec)) {
8
+ for (const n of spec) {
9
+ const page = Math.round(n);
10
+ if (page >= 1 && page <= maxPages) result.add(page);
11
+ }
12
+ return result;
13
+ }
14
+ if (typeof spec !== "string" || spec.trim() === "") return result;
15
+ const parts = spec.split(",");
16
+ for (const part of parts) {
17
+ const trimmed = part.trim();
18
+ if (!trimmed) continue;
19
+ const rangeMatch = trimmed.match(/^(\d+)\s*-\s*(\d+)$/);
20
+ if (rangeMatch) {
21
+ const start = Math.max(1, parseInt(rangeMatch[1], 10));
22
+ const end = Math.min(maxPages, parseInt(rangeMatch[2], 10));
23
+ for (let i = start; i <= end; i++) result.add(i);
24
+ } else {
25
+ const page = parseInt(trimmed, 10);
26
+ if (!isNaN(page) && page >= 1 && page <= maxPages) result.add(page);
27
+ }
28
+ }
29
+ return result;
30
+ }
31
+
32
+ export {
33
+ parsePageRange
34
+ };
35
+ //# sourceMappingURL=chunk-MOL7MDBG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/page-range.ts"],"sourcesContent":["/** 페이지/섹션 범위 파싱 유틸리티 */\n\n/**\n * 페이지 범위 지정을 1-based Set<number>로 변환.\n *\n * @param spec - [1,2,3] 또는 \"1-3\" 또는 \"1,3,5-7\"\n * @param maxPages - 최대 페이지 수 (클램핑 상한)\n * @returns 1-based 페이지 번호 Set\n */\nexport function parsePageRange(spec: number[] | string, maxPages: number): Set<number> {\n const result = new Set<number>()\n if (maxPages <= 0) return result\n\n if (Array.isArray(spec)) {\n for (const n of spec) {\n const page = Math.round(n)\n if (page >= 1 && page <= maxPages) result.add(page)\n }\n return result\n }\n\n if (typeof spec !== \"string\" || spec.trim() === \"\") return result\n\n const parts = spec.split(\",\")\n for (const part of parts) {\n const trimmed = part.trim()\n if (!trimmed) continue\n\n const rangeMatch = trimmed.match(/^(\\d+)\\s*-\\s*(\\d+)$/)\n if (rangeMatch) {\n const start = Math.max(1, parseInt(rangeMatch[1], 10))\n const end = Math.min(maxPages, parseInt(rangeMatch[2], 10))\n for (let i = start; i <= end; i++) result.add(i)\n } else {\n const page = parseInt(trimmed, 10)\n if (!isNaN(page) && page >= 1 && page <= maxPages) result.add(page)\n }\n }\n\n return result\n}\n"],"mappings":";;;AASO,SAAS,eAAe,MAAyB,UAA+B;AACrF,QAAM,SAAS,oBAAI,IAAY;AAC/B,MAAI,YAAY,EAAG,QAAO;AAE1B,MAAI,MAAM,QAAQ,IAAI,GAAG;AACvB,eAAW,KAAK,MAAM;AACpB,YAAM,OAAO,KAAK,MAAM,CAAC;AACzB,UAAI,QAAQ,KAAK,QAAQ,SAAU,QAAO,IAAI,IAAI;AAAA,IACpD;AACA,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,SAAS,YAAY,KAAK,KAAK,MAAM,GAAI,QAAO;AAE3D,QAAM,QAAQ,KAAK,MAAM,GAAG;AAC5B,aAAW,QAAQ,OAAO;AACxB,UAAM,UAAU,KAAK,KAAK;AAC1B,QAAI,CAAC,QAAS;AAEd,UAAM,aAAa,QAAQ,MAAM,qBAAqB;AACtD,QAAI,YAAY;AACd,YAAM,QAAQ,KAAK,IAAI,GAAG,SAAS,WAAW,CAAC,GAAG,EAAE,CAAC;AACrD,YAAM,MAAM,KAAK,IAAI,UAAU,SAAS,WAAW,CAAC,GAAG,EAAE,CAAC;AAC1D,eAAS,IAAI,OAAO,KAAK,KAAK,IAAK,QAAO,IAAI,CAAC;AAAA,IACjD,OAAO;AACL,YAAM,OAAO,SAAS,SAAS,EAAE;AACjC,UAAI,CAAC,MAAM,IAAI,KAAK,QAAQ,KAAK,QAAQ,SAAU,QAAO,IAAI,IAAI;AAAA,IACpE;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}