@open330/kiwimu 0.7.1 → 1.1.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.
@@ -1,17 +1,44 @@
1
- import { mkdirSync, rmSync, cpSync, existsSync } from "fs";
1
+ import { mkdirSync, rmSync, cpSync, existsSync, readFileSync, writeFileSync } from "fs";
2
2
  import { join, dirname } from "path";
3
3
  import { marked } from "marked";
4
4
  import sanitizeHtml from "sanitize-html";
5
- import type { KiwiConfig } from "../config";
5
+ import { loadConfig, type KiwiConfig } from "../config";
6
6
  import type { Store } from "../store";
7
7
  import { buildGraphData } from "../pipeline/graph";
8
- import { renderPage, renderIndex, renderGraph, renderQuizPage } from "./templates";
8
+ import { renderCitationFootnotes } from "../pipeline/citations";
9
+ import { renderPage, renderIndex, renderGraph, renderQuizPage, renderDashboardPage, renderCatalogPage } from "./templates";
10
+
11
+ function escapeHtmlChars(s: string): string {
12
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
13
+ }
14
+
15
+ // Fallback: catches any ```mermaid block that slipped past the placeholder pre-pass.
16
+ // Keeps marked's existing escaping intact — the browser decodes via textContent
17
+ // when mermaid.js reads the diagram source.
18
+ function convertMermaidBlocks(html: string): string {
19
+ if (!html.includes('language-mermaid')) return html;
20
+ return html.replace(
21
+ /<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,
22
+ (_match, code: string) => {
23
+ if (!code.trim()) return '';
24
+ return `<pre class="mermaid">${code}</pre>`;
25
+ }
26
+ );
27
+ }
9
28
 
10
29
  // Fix internal wiki links: /wiki/slug → /wiki/slug.html
11
- function fixWikiLinks(html: string): string {
30
+ // Mark non-existent pages as "red links" (wiki convention for missing pages)
31
+ function fixWikiLinks(html: string, existingSlugs?: Set<string>): string {
12
32
  return html.replace(/href="\/wiki\/([^"]+?)"/g, (match, slug) => {
13
- if (slug.endsWith(".html")) return match;
14
- return `href="/wiki/${slug}.html"`;
33
+ const cleanSlug = slug.endsWith(".html") ? slug.replace(".html", "") : slug;
34
+ const decodedSlug = decodeURIComponent(cleanSlug);
35
+ const href = slug.endsWith(".html") ? match : `href="/wiki/${slug}.html"`;
36
+
37
+ // If we have slug list and this page doesn't exist, mark as red link
38
+ if (existingSlugs && !existingSlugs.has(decodedSlug) && !existingSlugs.has(cleanSlug)) {
39
+ return `${href} class="redlink" title="문서 없음: ${decodedSlug}"`;
40
+ }
41
+ return href;
15
42
  });
16
43
  }
17
44
 
@@ -43,6 +70,79 @@ function generateToc(markdown: string): string {
43
70
  .join("")}</ul></div>`;
44
71
  }
45
72
 
73
+ // Shared markdown rendering + sanitization logic
74
+ export async function renderPageContent(page: { content: string }, existingSlugs?: Set<string>): Promise<string> {
75
+ // Convert [[wiki links]] to markdown links before rendering
76
+ // [[slug]] → [slug](/wiki/slug.html)
77
+ // [[slug|display text]] → [display text](/wiki/slug.html)
78
+ let markdown = page.content.replace(/\[\[([^\]|]+?)(?:\|([^\]]+?))?\]\]/g, (_match, slug, display) => {
79
+ const text = display || slug.replace(/-/g, ' ');
80
+ return `[${text}](/wiki/${encodeURIComponent(slug)}.html)`;
81
+ });
82
+
83
+ // Protect LaTeX math from marked() processing
84
+ // Replace $...$ and $$...$$ with placeholders to prevent _ and * from being parsed as markdown
85
+ const mathPlaceholders: string[] = [];
86
+ markdown = markdown.replace(/\$\$[\s\S]+?\$\$/g, (match) => {
87
+ mathPlaceholders.push(match);
88
+ return `%%MATH_BLOCK_${mathPlaceholders.length - 1}%%`;
89
+ });
90
+ markdown = markdown.replace(/\$(?!\$)(.+?)\$/g, (match) => {
91
+ mathPlaceholders.push(match);
92
+ return `%%MATH_INLINE_${mathPlaceholders.length - 1}%%`;
93
+ });
94
+
95
+ // Protect mermaid fenced blocks: extract verbatim before marked sees them, so
96
+ // node labels containing markdown chars (*, _, |) or HTML chars (<, >, ")
97
+ // never get mangled by marked or stripped by sanitize-html.
98
+ const mermaidBlocks: string[] = [];
99
+ markdown = markdown.replace(/```mermaid\r?\n([\s\S]*?)```/g, (_match, body: string) => {
100
+ mermaidBlocks.push(body);
101
+ return `\n\n%%MERMAID_BLOCK_${mermaidBlocks.length - 1}%%\n\n`;
102
+ });
103
+
104
+ let htmlContent = await marked(markdown);
105
+
106
+ // Restore LaTeX math from placeholders
107
+ htmlContent = htmlContent.replace(/%%MATH_(BLOCK|INLINE)_(\d+)%%/g, (_match, _type, idx) => {
108
+ return mathPlaceholders[parseInt(idx)] || '';
109
+ });
110
+ // Fallback: convert any leftover marked-emitted mermaid code blocks
111
+ htmlContent = convertMermaidBlocks(htmlContent);
112
+ htmlContent = sanitizeHtml(htmlContent, {
113
+ allowedTags: sanitizeHtml.defaults.allowedTags.concat([
114
+ 'img', 'details', 'summary', 'kbd', 'del', 's', 'sup', 'sub',
115
+ 'span', 'div', 'section', 'figure', 'figcaption', 'mark',
116
+ 'pre', 'code'
117
+ ]),
118
+ allowedAttributes: {
119
+ ...sanitizeHtml.defaults.allowedAttributes,
120
+ '*': ['id', 'class'],
121
+ 'img': ['src', 'alt', 'title', 'width', 'height'],
122
+ 'a': ['href', 'title', 'target', 'rel'],
123
+ 'span': ['class'], // For KaTeX
124
+ 'pre': ['class'], // For Mermaid
125
+ 'code': ['class'],
126
+ },
127
+ allowedSchemes: ['http', 'https', 'mailto'],
128
+ });
129
+
130
+ // Restore mermaid blocks AFTER sanitize so the diagram source is preserved
131
+ // verbatim. Escape only the HTML structural chars so the browser's textContent
132
+ // (which mermaid.js uses) yields the original characters.
133
+ htmlContent = htmlContent.replace(
134
+ /(?:<p>\s*)?%%MERMAID_BLOCK_(\d+)%%(?:\s*<\/p>)?/g,
135
+ (_match, idx) => {
136
+ const body = mermaidBlocks[parseInt(idx, 10)] || '';
137
+ if (!body.trim()) return '';
138
+ return `<pre class="mermaid">${escapeHtmlChars(body)}</pre>`;
139
+ }
140
+ );
141
+
142
+ htmlContent = fixWikiLinks(htmlContent, existingSlugs);
143
+ return htmlContent;
144
+ }
145
+
46
146
  export async function buildSite(store: Store, config: KiwiConfig, projectRoot: string): Promise<number> {
47
147
  const outputDir = join(projectRoot, config.build.output_dir);
48
148
  const wikiDir = join(outputDir, "wiki");
@@ -57,36 +157,53 @@ export async function buildSite(store: Store, config: KiwiConfig, projectRoot: s
57
157
  cpSync(assetsDir, staticDir, { recursive: true });
58
158
  }
59
159
 
60
- // Copy logo
61
- const logoSrc = join(projectRoot, "..", "assets", "logos", "logo_2_minimalist_icon_transparent.png");
62
- const logoSrc2 = join(projectRoot, "assets", "logos", "logo_2_minimalist_icon_transparent.png");
63
- const logoFile = existsSync(logoSrc) ? logoSrc : existsSync(logoSrc2) ? logoSrc2 : null;
64
- if (logoFile) {
160
+ // Copy logo (check multiple possible locations).
161
+ // Order: shipped-with-kiwimu (works for both git clone and npm install), then
162
+ // wiki-project-local overrides, then Docker path, then the assetsDir copy
163
+ // already produced above (so Bun.file lookups stay consistent).
164
+ const kiwimuAssets = join(dirname(import.meta.path), "..", "..", "assets", "logos", "logo_2_minimalist_icon_transparent.png");
165
+ const logoCandidates = [
166
+ kiwimuAssets,
167
+ join(projectRoot, "..", "assets", "logos", "logo_2_minimalist_icon_transparent.png"),
168
+ join(projectRoot, "assets", "logos", "logo_2_minimalist_icon_transparent.png"),
169
+ "/app/assets/logos/logo_2_minimalist_icon_transparent.png", // Docker path
170
+ join(staticDir, "logo.png"), // already copied via assetsDir → use it as the source
171
+ ];
172
+ const logoFile = logoCandidates.find(p => existsSync(p)) || null;
173
+ if (logoFile && logoFile !== join(staticDir, "logo.png")) {
65
174
  cpSync(logoFile, join(staticDir, "logo.png"));
66
175
  }
67
176
 
177
+ // Browsers fetch /favicon.ico from the site root regardless of HTML markup,
178
+ // so we mirror it from the bundled static assets if present.
179
+ const faviconSrc = join(staticDir, "favicon.ico");
180
+ if (existsSync(faviconSrc)) {
181
+ cpSync(faviconSrc, join(outputDir, "favicon.ico"));
182
+ } else if (logoFile) {
183
+ // Fall back to the logo as a favicon so /favicon.ico never 404s.
184
+ cpSync(logoFile, join(outputDir, "favicon.ico"));
185
+ }
186
+
68
187
  const pages = store.listPages();
69
188
  const sourcePages = store.listSourcePages();
70
189
  const conceptPages = store.listConceptPages();
71
190
  const wikiName = config.project.name;
72
191
  const backlinksMap = store.getAllBacklinksGrouped();
192
+ const allSlugs = new Set(pages.map(p => p.slug));
193
+ const categories = config.categories;
194
+
195
+ // Build source_id → uri map so PageLink rows can carry sourceUri (used by templates for category grouping)
196
+ const sourceUriMap = new Map<number, string>();
197
+ for (const s of store.listSources()) sourceUriMap.set(s.id, s.uri);
198
+ const sourceLink = (p: { slug: string; title: string; source_id: number; origin?: string }) => ({
199
+ slug: p.slug,
200
+ title: p.title,
201
+ sourceUri: sourceUriMap.get(p.source_id),
202
+ ...(p.origin ? { origin: p.origin } : {}),
203
+ });
73
204
 
74
205
  for (const page of pages) {
75
- let htmlContent = await marked(page.content);
76
- htmlContent = sanitizeHtml(htmlContent, {
77
- allowedTags: sanitizeHtml.defaults.allowedTags.concat([
78
- 'img', 'details', 'summary', 'kbd', 'del', 's', 'sup', 'sub',
79
- 'span', 'div', 'section', 'figure', 'figcaption', 'mark'
80
- ]),
81
- allowedAttributes: {
82
- ...sanitizeHtml.defaults.allowedAttributes,
83
- '*': ['id', 'class', 'style'],
84
- 'img': ['src', 'alt', 'title', 'width', 'height'],
85
- 'a': ['href', 'title', 'target', 'rel'],
86
- },
87
- allowedSchemes: ['http', 'https', 'mailto'],
88
- });
89
- htmlContent = fixWikiLinks(htmlContent);
206
+ const htmlContent = await renderPageContent(page, allSlugs);
90
207
 
91
208
  const { body, externalRefs } = extractExternalRefs(htmlContent);
92
209
  const toc = generateToc(page.content);
@@ -96,17 +213,25 @@ export async function buildSite(store: Store, config: KiwiConfig, projectRoot: s
96
213
  pageType: bl.page_type,
97
214
  }));
98
215
 
216
+ // Citations footer
217
+ const citations = store.getCitationsForPage(page.id);
218
+ const citationsHtml = renderCitationFootnotes(citations);
219
+
99
220
  const html = renderPage({
100
221
  wikiName,
101
222
  pageTitle: page.title,
102
223
  pageSlug: page.slug,
103
224
  pageType: page.page_type,
225
+ pageId: page.id,
226
+ origin: page.origin,
104
227
  content: body,
105
228
  externalRefs,
106
229
  toc,
107
230
  backlinks,
108
- sourcePages: sourcePages.map((p) => ({ slug: p.slug, title: p.title })),
109
- conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
231
+ citationsHtml,
232
+ sourcePages: sourcePages.map(sourceLink),
233
+ conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title, origin: p.origin })),
234
+ categories,
110
235
  });
111
236
 
112
237
  await Bun.write(join(wikiDir, `${page.slug}.html`), html);
@@ -114,9 +239,10 @@ export async function buildSite(store: Store, config: KiwiConfig, projectRoot: s
114
239
 
115
240
  const indexHtml = renderIndex({
116
241
  wikiName,
117
- sourcePages: sourcePages.map((p) => ({ slug: p.slug, title: p.title })),
242
+ sourcePages: sourcePages.map(sourceLink),
118
243
  conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
119
- sourceCount: store.listSources().length,
244
+ sourceCount: store.countSources(),
245
+ categories,
120
246
  });
121
247
  await Bun.write(join(outputDir, "index.html"), indexHtml);
122
248
 
@@ -126,8 +252,9 @@ export async function buildSite(store: Store, config: KiwiConfig, projectRoot: s
126
252
  join(outputDir, "graph.html"),
127
253
  renderGraph({
128
254
  wikiName,
129
- sourcePages: sourcePages.map((p) => ({ slug: p.slug, title: p.title })),
255
+ sourcePages: sourcePages.map(sourceLink),
130
256
  conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
257
+ categories,
131
258
  })
132
259
  );
133
260
 
@@ -141,11 +268,46 @@ export async function buildSite(store: Store, config: KiwiConfig, projectRoot: s
141
268
  id: q.id,
142
269
  question: q.question,
143
270
  answer: q.answer,
271
+ explanation: q.explanation || "",
144
272
  quiz_type: q.quiz_type,
145
273
  page_title: q.page_title,
146
274
  page_slug: q.page_slug,
147
275
  })),
148
- sourcePages: sourcePages.map((p) => ({ slug: p.slug, title: p.title })),
276
+ sourcePages: sourcePages.map(sourceLink),
277
+ conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
278
+ categories,
279
+ })
280
+ );
281
+
282
+ // Dashboard page
283
+ const stats = store.getLearningStats();
284
+ const weakConcepts = store.getWeakConcepts(10);
285
+ const recentAttempts = store.getQuizHistory(20);
286
+ await Bun.write(
287
+ join(outputDir, "dashboard.html"),
288
+ renderDashboardPage({
289
+ wikiName,
290
+ stats,
291
+ weakConcepts,
292
+ recentAttempts,
293
+ sourcePages: sourcePages.map(sourceLink),
294
+ conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
295
+ categories,
296
+ })
297
+ );
298
+
299
+ // Catalog (index) page
300
+ const { generateContentIndex } = await import("../services/index-generator");
301
+ const contentIndex = await generateContentIndex(store);
302
+ await Bun.write(
303
+ join(outputDir, "catalog.html"),
304
+ renderCatalogPage({
305
+ wikiName,
306
+ categories: contentIndex.categories,
307
+ totalPages: contentIndex.totalPages,
308
+ totalLinks: contentIndex.totalLinks,
309
+ generatedAt: contentIndex.generatedAt,
310
+ sourcePages: sourcePages.map(sourceLink),
149
311
  conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
150
312
  })
151
313
  );
@@ -173,3 +335,82 @@ fetch('/search-index.json').then(r=>r.json()).then(pages=>{
173
335
 
174
336
  return pages.length;
175
337
  }
338
+
339
+ export async function buildSinglePage(root: string, store: Store, slug: string): Promise<void> {
340
+ const page = store.getPage(slug);
341
+ if (!page) return;
342
+
343
+ const config = loadConfig(root);
344
+ const siteDir = join(root, config.build?.output_dir || "_site");
345
+ const wikiDir = join(siteDir, "wiki");
346
+ mkdirSync(wikiDir, { recursive: true });
347
+
348
+ const sourcePages = store.listSourcePages();
349
+ const conceptPages = store.listConceptPages();
350
+ const wikiName = config.project.name;
351
+ const backlinksMap = store.getAllBacklinksGrouped();
352
+
353
+ const sourceUriMap = new Map<number, string>();
354
+ for (const s of store.listSources()) sourceUriMap.set(s.id, s.uri);
355
+ const sourceLink = (p: { slug: string; title: string; source_id: number; origin?: string }) => ({
356
+ slug: p.slug,
357
+ title: p.title,
358
+ sourceUri: sourceUriMap.get(p.source_id),
359
+ ...(p.origin ? { origin: p.origin } : {}),
360
+ });
361
+
362
+ // Render the single page
363
+ const htmlContent = await renderPageContent(page);
364
+
365
+ const { body, externalRefs } = extractExternalRefs(htmlContent);
366
+ const toc = generateToc(page.content);
367
+ const backlinks = (backlinksMap.get(page.id) || []).map((bl) => ({
368
+ slug: bl.slug,
369
+ title: bl.title,
370
+ pageType: bl.page_type,
371
+ }));
372
+
373
+ // Citations footer
374
+ const citations = store.getCitationsForPage(page.id);
375
+ const citationsHtml = renderCitationFootnotes(citations);
376
+
377
+ const html = renderPage({
378
+ wikiName,
379
+ pageTitle: page.title,
380
+ pageSlug: page.slug,
381
+ pageType: page.page_type,
382
+ pageId: page.id,
383
+ origin: page.origin,
384
+ content: body,
385
+ externalRefs,
386
+ toc,
387
+ backlinks,
388
+ citationsHtml,
389
+ sourcePages: sourcePages.map(sourceLink),
390
+ conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title, origin: p.origin })),
391
+ categories: config.categories,
392
+ });
393
+
394
+ await Bun.write(join(wikiDir, `${page.slug}.html`), html);
395
+
396
+ // Update search-index.json
397
+ const searchIndexPath = join(siteDir, "search-index.json");
398
+ let searchData: Array<{ slug: string; title: string; preview: string; type: string }> = [];
399
+ if (existsSync(searchIndexPath)) {
400
+ try {
401
+ searchData = JSON.parse(readFileSync(searchIndexPath, "utf-8"));
402
+ } catch {
403
+ searchData = [];
404
+ }
405
+ }
406
+ // Remove existing entry for this slug if any
407
+ searchData = searchData.filter((p) => p.slug !== page.slug);
408
+ // Append new entry
409
+ searchData.push({
410
+ slug: page.slug,
411
+ title: page.title,
412
+ preview: page.content.slice(0, 200),
413
+ type: page.page_type,
414
+ });
415
+ await Bun.write(searchIndexPath, JSON.stringify(searchData));
416
+ }