@unana_dev/doxen 0.2.5 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unana_dev/doxen",
3
- "version": "0.2.5",
3
+ "version": "0.3.0",
4
4
  "description": "Config-first Markdown documentation sites with Korean and section search",
5
5
  "type": "module",
6
6
  "bin": {
@@ -42,6 +42,7 @@
42
42
  "markdown-it": "^14.1.0",
43
43
  "markdown-it-container": "^4.0.0",
44
44
  "mermaid": "^12.1.0",
45
+ "read-excel-file": "^9.3.14",
45
46
  "sanitize-html": "^2.17.0",
46
47
  "wrangler": "4.149.0"
47
48
  },
@@ -12,6 +12,7 @@ export function accessWorker(access, keys = createRemoteJWKSet(
12
12
  });
13
13
  const token = request.headers.get("cf-access-jwt-assertion");
14
14
  if (!token) return denied();
15
+ let email;
15
16
  try {
16
17
  const { payload } = await jwtVerify(token, keys, {
17
18
  issuer: access.teamDomain,
@@ -21,9 +22,36 @@ export function accessWorker(access, keys = createRemoteJWKSet(
21
22
  });
22
23
  if (typeof payload.email !== "string" || !emails.has(payload.email.toLowerCase()))
23
24
  return denied();
25
+ email = payload.email.toLowerCase();
24
26
  } catch {
25
27
  return denied();
26
28
  }
29
+ const url = new URL(request.url);
30
+ if (url.pathname === "/__doxen/comments") {
31
+ const headers = { "Cache-Control": "private, no-store" };
32
+ if (!env.COMMENTS_DB) return new Response("댓글 저장소가 설정되지 않았습니다.", { status: 503, headers });
33
+ if (request.method === "GET") {
34
+ const document = url.searchParams.get("document");
35
+ if (!document || document.length > 500) return new Response("잘못된 문서", { status: 400, headers });
36
+ const rows = await env.COMMENTS_DB.prepare("SELECT id, block, quote, body, author, created_at FROM comments WHERE document = ? ORDER BY created_at, id").bind(document).all();
37
+ return Response.json(rows.results, { headers });
38
+ }
39
+ if (request.method === "POST") {
40
+ if (request.headers.get("origin") !== url.origin || !request.headers.get("content-type")?.startsWith("application/json"))
41
+ return new Response("잘못된 요청", { status: 403, headers });
42
+ let data;
43
+ try { data = await request.json(); } catch { return new Response("잘못된 요청", { status: 400, headers }); }
44
+ if (![data?.document, data?.block, data?.quote, data?.body].every((value) => typeof value === "string") ||
45
+ !data.document || data.document.length > 500 || !data.block || data.block.length > 10000 ||
46
+ data.quote.length > 2000 || !data.body.trim() || data.body.length > 5000)
47
+ return new Response("잘못된 댓글", { status: 400, headers });
48
+ const row = { id: crypto.randomUUID(), block: data.block, quote: data.quote, body: data.body.trim(), author: email, created_at: new Date().toISOString() };
49
+ await env.COMMENTS_DB.prepare("INSERT INTO comments (id, document, block, quote, body, author, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
50
+ .bind(row.id, data.document, row.block, row.quote, row.body, row.author, row.created_at).run();
51
+ return Response.json(row, { status: 201, headers });
52
+ }
53
+ return new Response("허용되지 않는 요청", { status: 405, headers });
54
+ }
27
55
  const asset = await env.ASSETS.fetch(request);
28
56
  const response = new Response(asset.body, asset);
29
57
  response.headers.set("Cache-Control", "private, no-store");
package/src/build.js CHANGED
@@ -53,7 +53,7 @@ export async function siteFiles(config, dev = false) {
53
53
  `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="${config.icon.background}"/><text x="16" y="16" dominant-baseline="middle" text-anchor="middle" font-family="Arial, sans-serif" font-size="22" font-weight="700" fill="${config.icon.color}">${initial.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)}</text></svg>`,
54
54
  ),
55
55
  );
56
- for (const name of ["index.html", "app.js", "style.css", "search.js"])
56
+ for (const name of ["index.html", "app.js", "style.css", "search.js", "comments.js"])
57
57
  files.set(`/${name}`, await readFile(path.join(client, name)));
58
58
  for (const output of (await getPresentationAssets()).outputFiles) {
59
59
  const name = path.relative(path.join(client, "generated"), output.path).split(path.sep).join("/");
@@ -0,0 +1,82 @@
1
+ // Copy src/templates/comment-report.yml into the consuming repository to run this report.
2
+ import path from 'node:path';
3
+ import { realpath } from 'node:fs/promises';
4
+ import { loadConfig, inside } from './config.js';
5
+ import { collectSite } from './content.js';
6
+
7
+ const { CLOUDFLARE_ACCOUNT_ID: account, CLOUDFLARE_D1_DATABASE_ID: database,
8
+ CLOUDFLARE_API_TOKEN: cloudflareToken, GITHUB_TOKEN: githubToken,
9
+ GITHUB_REPOSITORY: repository, GITHUB_SHA: commit, DOXEN_SITE_URL: siteUrl, REPORT_DATE } = process.env;
10
+ if (!account || !database || !cloudflareToken || !githubToken || !repository || !commit || !siteUrl)
11
+ throw new Error('댓글 보고서에 필요한 Cloudflare 및 GitHub 환경 변수가 없습니다.');
12
+ if (!/^[a-f0-9]{40}$/i.test(commit)) throw new Error('GITHUB_SHA가 올바르지 않습니다.');
13
+ let site;
14
+ try { site = new URL(siteUrl); } catch { throw new Error('DOXEN_SITE_URL은 사이트의 HTTP(S) 주소여야 합니다.'); }
15
+ if (!['http:', 'https:'].includes(site.protocol) || site.username || site.password || site.search || site.hash)
16
+ throw new Error('DOXEN_SITE_URL은 쿼리나 인증 정보가 없는 사이트 주소여야 합니다.');
17
+ const date = REPORT_DATE || new Date(Date.now() + 9 * 3600000 - 86400000).toISOString().slice(0, 10);
18
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || new Date(`${date}T00:00:00Z`).toISOString().slice(0, 10) !== date)
19
+ throw new Error('REPORT_DATE는 YYYY-MM-DD 형식의 유효한 날짜여야 합니다.');
20
+ const start = new Date(`${date}T00:00:00+09:00`);
21
+ const end = new Date(start.getTime() + 86400000);
22
+ const cloudflare = await fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(account)}/d1/database/${encodeURIComponent(database)}/query`, {
23
+ method: 'POST', headers: { Authorization: `Bearer ${cloudflareToken}`, 'Content-Type': 'application/json' },
24
+ body: JSON.stringify({ sql: 'SELECT id, document, quote, body, author, created_at FROM comments WHERE created_at >= ? AND created_at < ? ORDER BY created_at, id', params: [start.toISOString(), end.toISOString()] }),
25
+ });
26
+ if (!cloudflare.ok) throw new Error(`D1 조회 실패: HTTP ${cloudflare.status}`);
27
+ const result = await cloudflare.json();
28
+ if (!result.success || !result.result?.[0]?.success) throw new Error('D1 조회에 실패했습니다.');
29
+ const comments = result.result[0].results;
30
+ if (!comments.length) { console.log(`${date}: 등록할 댓글이 없습니다.`); process.exit(0); }
31
+ const github = `https://api.github.com/repos/${repository}/issues`;
32
+ const headers = { Authorization: `Bearer ${githubToken}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
33
+ const marker = `<!-- doxen-comment-report:${date} -->`;
34
+ for (let page = 1; ; page++) {
35
+ const response = await fetch(`${github}?state=all&per_page=100&page=${page}`, { headers });
36
+ if (!response.ok) throw new Error(`GitHub 이슈 조회 실패: HTTP ${response.status}`);
37
+ const issues = await response.json();
38
+ if (issues.some((issue) => !issue.pull_request && issue.body?.includes(marker))) {
39
+ console.log(`${date}: 이미 보고서 이슈가 있습니다.`); process.exit(0);
40
+ }
41
+ if (issues.length < 100) break;
42
+ }
43
+ const workspace = await realpath(process.env.GITHUB_WORKSPACE || process.cwd());
44
+ const config = await loadConfig(workspace, process.env.DOXEN_CONFIG || undefined);
45
+ const { data } = await collectSite(config);
46
+ const paths = new Map(data.documents.filter((doc) => !doc.spreadsheet).map((doc) => {
47
+ const tab = config.tabs.find((item) => item.slug === doc.tab);
48
+ const file = path.resolve(tab.dir, doc.path);
49
+ return [doc.id, inside(workspace, file) ? path.relative(workspace, file).split(path.sep).join('/') : null];
50
+ }));
51
+ const encodedPath = (value) => value.split('/').map(encodeURIComponent).join('/');
52
+ const safeLink = (value) => value.replace(/[()<>\s]/g, (char) => encodeURIComponent(char));
53
+ const fileLink = (document) => {
54
+ const file = paths.get(document);
55
+ if (!file) return ['- 문서 링크: 현재 문서 경로를 찾을 수 없습니다.'];
56
+ return [
57
+ `- 원본 파일: [${safe(file).replace(/[\\\[\]]/g, '\\$&')}](<https://github.com/${repository}/blob/${commit}/${encodedPath(file)}>)`,
58
+ ];
59
+ };
60
+ const commentLink = (item) => {
61
+ if (!paths.get(item.document)) return [];
62
+ const documentUrl = new URL(site);
63
+ documentUrl.hash = `/${encodeURIComponent(item.document)}/comment/${encodeURIComponent(item.id)}`;
64
+ return [`- 배포 사이트: [댓글 위치 보기](<${safeLink(documentUrl.href)}>)`];
65
+ };
66
+ const safe = (value) => String(value).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]).replace(/@/g, '&#64;');
67
+ const grouped = new Map();
68
+ for (const item of comments) {
69
+ if (!grouped.has(item.document)) grouped.set(item.document, []);
70
+ grouped.get(item.document).push(item);
71
+ }
72
+ const body = [marker, `## ${date} 문서 댓글`, '', `총 ${comments.length}개 · 한국 시간 기준`, '', ...[...grouped].flatMap(([document, items]) => [
73
+ `### ${safe(document)} · 댓글 ${items.length}개`, ...fileLink(document), '',
74
+ ...items.flatMap((item, index) => [
75
+ `#### 댓글 ${index + 1}`, ...commentLink(item), `- 작성자: ${safe(item.author)}`, `- 작성 시각: ${safe(item.created_at)}`,
76
+ ...(item.quote ? ['', '**선택한 문구**', `<pre>${safe(item.quote)}</pre>`] : []),
77
+ '', '**댓글**', `<pre>${safe(item.body)}</pre>`, '',
78
+ ]), '---', '',
79
+ ]), '## 후속 작업', '- [ ] 댓글 검토 및 처리'].join('\n');
80
+ const created = await fetch(github, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ title: `[문서 댓글] ${date} 일일 보고`, body }) });
81
+ if (!created.ok) throw new Error(`GitHub 이슈 생성 실패: HTTP ${created.status}`);
82
+ console.log(`${date}: 댓글 ${comments.length}개를 이슈로 등록했습니다.`);
@@ -0,0 +1,10 @@
1
+ CREATE TABLE IF NOT EXISTS comments (
2
+ id TEXT PRIMARY KEY,
3
+ document TEXT NOT NULL,
4
+ block TEXT NOT NULL,
5
+ quote TEXT NOT NULL,
6
+ body TEXT NOT NULL,
7
+ author TEXT NOT NULL,
8
+ created_at TEXT NOT NULL
9
+ );
10
+ CREATE INDEX IF NOT EXISTS comments_document ON comments(document, created_at);
package/src/content.js CHANGED
@@ -1,12 +1,28 @@
1
- import { readFile, readdir, realpath } from "node:fs/promises";
1
+ import { readFile, readdir, realpath, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
3
5
  import { createHash } from "node:crypto";
4
6
  import MarkdownIt from "markdown-it";
5
7
  import container from "markdown-it-container";
6
8
  import GithubSlugger from "github-slugger";
7
9
  import sanitizeHtml from "sanitize-html";
10
+ import readXlsxFile from "read-excel-file/node";
8
11
  import { inside } from "./config.js";
9
12
 
13
+ const execFileAsync = promisify(execFile);
14
+
15
+ async function modificationInfo(file, root) {
16
+ try {
17
+ const { stdout } = await execFileAsync("git", ["log", "-1", "--format=%aI%n%an", "--follow", "--", file], { cwd: root });
18
+ const [date, author] = stdout.trim().split("\n");
19
+ if (date) return { date, author };
20
+ } catch {
21
+ // Files outside Git or environments without Git use the filesystem timestamp.
22
+ }
23
+ return { date: (await stat(file)).mtime.toISOString() };
24
+ }
25
+
10
26
  const assetExtensions = new Set([
11
27
  ".png",
12
28
  ".jpg",
@@ -16,6 +32,7 @@ const assetExtensions = new Set([
16
32
  ".avif",
17
33
  ".ico",
18
34
  ".pdf",
35
+ ".xlsx",
19
36
  ]);
20
37
  const escape = (text) =>
21
38
  text.replace(
@@ -47,7 +64,7 @@ async function walk(dir) {
47
64
  continue;
48
65
  const file = path.join(dir, entry.name);
49
66
  if (entry.isDirectory()) files.push(...(await walk(file)));
50
- else if (/\.md$/i.test(entry.name)) files.push(file);
67
+ else if (/\.(?:md|xlsx)$/i.test(entry.name)) files.push(file);
51
68
  }
52
69
  return files.sort((a, b) => a.localeCompare(b, "ko", { numeric: true }));
53
70
  }
@@ -62,13 +79,27 @@ export async function collectSite(config) {
62
79
  tab: tab.slug,
63
80
  path: relative,
64
81
  file,
65
- source: await readFile(file, "utf8"),
82
+ modified: await modificationInfo(file, config.root),
83
+ source: await readFile(file, /\.xlsx$/i.test(file) ? undefined : "utf8"),
66
84
  });
67
85
  }
68
86
  }
69
87
  const byFile = new Map(documents.map((doc) => [doc.file, doc]));
70
88
  const assets = new Map();
71
89
  for (const doc of documents) {
90
+ if (/\.xlsx$/i.test(doc.path)) {
91
+ const hash = createHash("sha256").update(doc.source).digest("hex").slice(0, 20);
92
+ const sheets = await readXlsxFile(doc.source, { trim: false });
93
+ assets.set(`${hash}.xlsx`, doc.source);
94
+ assets.set(`${hash}.json`, Buffer.from(JSON.stringify(sheets)));
95
+ doc.title = path.basename(doc.path);
96
+ doc.spreadsheet = { data: `./assets/${hash}.json`, file: `./assets/${hash}.xlsx` };
97
+ doc.toc = [];
98
+ doc.sections = [];
99
+ delete doc.source;
100
+ delete doc.file;
101
+ continue;
102
+ }
72
103
  const slugger = new GithubSlugger();
73
104
  const md = new MarkdownIt({
74
105
  html: false,
@@ -69,6 +69,7 @@ export function deploymentFromState(state) {
69
69
  if (!state?.ready) return undefined;
70
70
  return {
71
71
  project: state.project,
72
+ ...(state.comments ? { comments: state.comments } : {}),
72
73
  access: { teamDomain: state.teamDomain, audiences: Object.values(state.apps).map((app) => app.aud), emails: state.emails },
73
74
  };
74
75
  }
package/src/deploy.js CHANGED
@@ -22,9 +22,13 @@ export function validateDeployment(deploy) {
22
22
  if (!Array.isArray(access.emails) || !access.emails.length ||
23
23
  access.emails.some((value) => typeof value !== "string" || !/^[^\s@*]+@[^\s@*]+\.[^\s@*]+$/.test(value)))
24
24
  throw new Error("deploy.access.emails에 허용할 이메일 주소를 하나 이상 설정하세요.");
25
+ if (deploy.comments && (typeof deploy.comments.databaseName !== "string" || !/^[a-zA-Z0-9_-]+$/.test(deploy.comments.databaseName) ||
26
+ typeof deploy.comments.databaseId !== "string" || !/^[a-f0-9-]{36}$/i.test(deploy.comments.databaseId)))
27
+ throw new Error("deploy.comments에 올바른 databaseName과 databaseId를 설정하세요.");
25
28
  return {
26
29
  project: deploy.project,
27
30
  access: { teamDomain: access.teamDomain, audiences: access.audiences, emails: access.emails },
31
+ ...(deploy.comments ? { comments: deploy.comments } : {}),
28
32
  };
29
33
  }
30
34
 
@@ -94,6 +98,7 @@ export async function deploy(config, options) {
94
98
  name: settings.project,
95
99
  pages_build_output_dir: out,
96
100
  compatibility_date: "2026-10-08",
101
+ ...(settings.comments ? { d1_databases: [{ binding: "COMMENTS_DB", database_name: settings.comments.databaseName, database_id: settings.comments.databaseId }] } : {}),
97
102
  }));
98
103
  await new Promise((resolve, reject) => {
99
104
  const child = spawn(process.execPath, [wrangler, "pages", "deploy", out,
package/src/dev.js CHANGED
@@ -18,6 +18,7 @@ const types = {
18
18
  ".ico": "image/x-icon",
19
19
  ".svg": "image/svg+xml",
20
20
  ".pdf": "application/pdf",
21
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
21
22
  ".woff2": "font/woff2",
22
23
  };
23
24
 
package/src/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export interface DocsConfig {
5
5
  icon?: string | { background?: string; color?: string; border?: string };
6
6
  deploy?: {
7
7
  project: string;
8
+ comments?: { databaseName: string; databaseId: string };
8
9
  access: {
9
10
  teamDomain: string;
10
11
  audiences: string[];
@@ -0,0 +1,34 @@
1
+ name: Daily Doxen comments
2
+ on:
3
+ schedule:
4
+ - cron: '0 23 * * *' # 매일 오전 8시 (Asia/Seoul)
5
+ workflow_dispatch:
6
+ inputs:
7
+ report_date:
8
+ description: '집계할 날짜 (YYYY-MM-DD, 한국 시간; 비우면 전날)'
9
+ required: false
10
+ permissions:
11
+ contents: read
12
+ issues: write
13
+ concurrency:
14
+ group: doxen-comment-report
15
+ cancel-in-progress: false
16
+ jobs:
17
+ report:
18
+ runs-on: ubuntu-latest
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ - uses: actions/setup-node@v4
22
+ with:
23
+ node-version: '22'
24
+ - run: npm ci
25
+ - name: Create daily comment issue
26
+ run: node node_modules/@unana_dev/doxen/src/comment-report.js
27
+ env:
28
+ CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
29
+ CLOUDFLARE_D1_DATABASE_ID: ${{ secrets.CLOUDFLARE_D1_DATABASE_ID }}
30
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_D1_READ_TOKEN }}
31
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
32
+ DOXEN_SITE_URL: ${{ vars.DOXEN_SITE_URL }}
33
+ DOXEN_CONFIG: ${{ vars.DOXEN_CONFIG }}
34
+ REPORT_DATE: ${{ inputs.report_date }}