@unana_dev/doxen 0.3.1 → 0.3.3
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 +26 -1
- package/bin/docs.js +6 -2
- package/client/api-reference/index.html +12 -0
- package/client/api-reference/model.js +64 -0
- package/client/api-reference/page.css +12 -0
- package/client/api-reference/page.js +12 -0
- package/client/api-reference/standalone.js +3 -0
- package/client/api-reference/viewer.css +127 -0
- package/client/api-reference/viewer.js +256 -0
- package/client/app.js +8 -0
- package/client/comments.js +18 -0
- package/client/diagram-viewer.js +137 -0
- package/client/diagrams.js +35 -1
- package/client/style.css +19 -2
- package/package.json +1 -1
- package/src/api.js +78 -0
- package/src/build.js +4 -0
- package/src/config.js +18 -0
- package/src/index.d.ts +1 -0
- package/src/openapi.js +79 -0
- package/src/templates/comment-report.yml +2 -1
package/README.md
CHANGED
|
@@ -585,6 +585,31 @@ npx wrangler d1 execute 데이터베이스이름 --remote --file=node_modules/@u
|
|
|
585
585
|
|
|
586
586
|
저장소의 Actions variables에 배포된 문서 사이트 주소를 `DOXEN_SITE_URL`로 등록하세요. 설정 파일이 저장소 루트의 기본 이름이 아니라면 `DOXEN_CONFIG`에 저장소 기준 경로도 등록합니다. 보고서의 각 댓글에는 보고서 실행 시점 커밋의 GitHub 원본 파일 링크와 배포 사이트의 해당 댓글 링크가 표시됩니다. 현재 설정에서 문서를 찾지 못하면 링크 대신 안내 문구가 표시됩니다.
|
|
587
587
|
|
|
588
|
-
매일 한국 시간
|
|
588
|
+
매일 한국 시간 00시에 전날 00:00~24:00의 댓글을 하나의 이슈로 작성합니다. 실행 시각은 복사한 `.github/workflows/comment-report.yml`의 `schedule`에서 설정합니다. 예를 들어 한국 시간 오전 8시에 실행하려면 `cron: '0 8 * * *'`로 바꾸세요. `timezone: 'Asia/Seoul'`을 유지하면 한국 시간으로 적용됩니다. 설정한 시각에 하루 한 번 실행되며, 기존 워크플로를 사용 중이라면 변경된 템플릿의 `schedule`을 반영해야 합니다.
|
|
589
|
+
|
|
590
|
+
댓글은 문서별로 묶이며, 같은 문서 안에서는 작성 순서대로 표시됩니다. 댓글이 없으면 이슈를 만들지 않으며, 같은 날짜의 보고서 이슈가 이미 있으면 중복 생성하지 않습니다. Actions 화면의 수동 실행에서 날짜를 입력해 누락된 날을 다시 집계할 수 있습니다. 이슈 본문 양식은 패키지의 `src/comment-report.js`에서 확인할 수 있으며 필요에 맞게 복사해 수정하세요. 댓글 내용과 작성자 이메일이 이슈 저장소의 열람자에게 공개되므로 접근 권한을 확인하세요. GitHub 예약 실행은 지연되거나 누락될 수 있습니다.
|
|
589
591
|
|
|
590
592
|
문서별 최종 수정자와 수정일을 표시하려면 빌드 환경에 전체 Git 이력이 필요합니다. GitHub Actions에서는 `actions/checkout`에 `fetch-depth: 0`을 설정하세요. 얕은 복제의 경계 커밋은 파일의 실제 마지막 수정인지 확인할 수 없어 해당 정보가 표시되지 않습니다.
|
|
593
|
+
|
|
594
|
+
## OpenAPI 문서
|
|
595
|
+
|
|
596
|
+
API 탭의 Markdown 문서 하나를 API 화면으로 지정할 수 있습니다. 기존 API 화면의 기능별 탐색, 요청·응답 모델과 예시, 전체 검색을 함께 제공합니다.
|
|
597
|
+
|
|
598
|
+
```ts
|
|
599
|
+
api: {
|
|
600
|
+
document: 'api/README', // 탭 slug + 확장자 없는 문서 경로
|
|
601
|
+
spec: './api/openapi.json',
|
|
602
|
+
metadata: './api/spec-metadata.json',
|
|
603
|
+
},
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
```bash
|
|
607
|
+
npx doxen api:sync --file /path/to/openapi.json
|
|
608
|
+
npx doxen api:sync --url https://example.com/v3/api-docs
|
|
609
|
+
```
|
|
610
|
+
|
|
611
|
+
주소는 `OPENAPI_URL`로도 지정할 수 있습니다. Basic 인증은 `OPENAPI_BASIC_USER`, `OPENAPI_BASIC_PASSWORD` 환경 변수를 사용합니다. 명세는 OpenAPI 3 JSON이며, 가져오기 실패 시 명령이 실패하고 기존 명세를 유지합니다. 주소를 사용하는 경우 일시적인 실패를 최대 3회 재시도합니다. `--config`도 지원합니다. 생성 파일은 Git에서 제외하고 CI에서는 명세 가져오기 성공 후 배포하세요. 인증 정보를 포함한 URL과 리디렉션은 허용하지 않습니다.
|
|
612
|
+
|
|
613
|
+
명세가 없으면 API 화면에 미생성 안내를 표시합니다. `spec`과 `metadata` 경로는 설정 파일 하위에 두고, 상위 폴더는 미리 만들어 두세요. API 설정을 생략하면 일반 문서 사이트로 동작합니다.
|
|
614
|
+
|
|
615
|
+
Markdown의 Mermaid 다이어그램은 바로 렌더링되며 우상단 확대 아이콘으로 모달을 엽니다. API 설명의 Mermaid 코드 블록과 `<div class="mermaid">`는 버튼을 누르면 렌더링됩니다. `<details><summary>흐름 보기</summary>…</details>` 안에 넣으면 summary를 버튼 제목으로 사용합니다. 모달에서 확대·축소, 100%, 화면 맞춤, 전체화면을 사용할 수 있습니다. Esc 또는 닫기로 돌아옵니다. 전체화면 API 지원 여부는 브라우저에 따릅니다.
|
package/bin/docs.js
CHANGED
|
@@ -12,6 +12,7 @@ try {
|
|
|
12
12
|
options: {
|
|
13
13
|
config: { type: "string" },
|
|
14
14
|
port: { type: "string", default: "4173" },
|
|
15
|
+
url: { type: "string" },
|
|
15
16
|
file: { type: "string" },
|
|
16
17
|
instruction: { type: "string" },
|
|
17
18
|
help: { type: "boolean", short: "h" },
|
|
@@ -19,10 +20,10 @@ try {
|
|
|
19
20
|
},
|
|
20
21
|
});
|
|
21
22
|
const [command, ...extra] = positionals;
|
|
22
|
-
if (values.version) console.log("0.
|
|
23
|
+
if (values.version) console.log("0.3.3");
|
|
23
24
|
else if (values.help || !command)
|
|
24
25
|
console.log(
|
|
25
|
-
`Doxen — 저장소 기반 문서 사이트\n\n docs init 설정과 스크립트 생성\n docs dev [--port 4173] 로컬 미리보기 및 자동 갱신\n docs build .docs-dist 정적 사이트 생성\n docs deploy 최초 설정 안내 및 비공개 Cloudflare Pages 배포\n docs ai --file <문서.md> --instruction "변경 요청"\n 표준 양식과 AI 작업 지침을 stdout으로 출력\n\n옵션: --config <파일> (dev/build/deploy/ai), --help, --version\n동일 명령: doxen <명령>`,
|
|
26
|
+
`Doxen — 저장소 기반 문서 사이트\n\n docs init 설정과 스크립트 생성\n docs dev [--port 4173] 로컬 미리보기 및 자동 갱신\n docs build .docs-dist 정적 사이트 생성\n docs deploy 최초 설정 안내 및 비공개 Cloudflare Pages 배포\n docs api:sync [--file <명세.json> | --url <주소>] OpenAPI 명세 가져오기\n docs ai --file <문서.md> --instruction "변경 요청"\n 표준 양식과 AI 작업 지침을 stdout으로 출력\n\n옵션: --config <파일> (dev/build/deploy/ai), --help, --version\n동일 명령: doxen <명령>`,
|
|
26
27
|
);
|
|
27
28
|
else {
|
|
28
29
|
if (extra.length) throw new Error(`알 수 없는 인자: ${extra.join(" ")}`);
|
|
@@ -30,6 +31,9 @@ try {
|
|
|
30
31
|
if (values.config)
|
|
31
32
|
throw new Error("init은 --config 옵션을 지원하지 않습니다.");
|
|
32
33
|
await init(process.cwd());
|
|
34
|
+
} else if (command === "api:sync") {
|
|
35
|
+
const { syncOpenApi } = await import("../src/openapi.js");
|
|
36
|
+
await syncOpenApi(await loadConfig(process.cwd(), values.config), values);
|
|
33
37
|
} else if (command === "build")
|
|
34
38
|
console.log(
|
|
35
39
|
`빌드 완료: ${await build(await loadConfig(process.cwd(), values.config))}`,
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="ko">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
6
|
+
<title>파마리서치 API</title>
|
|
7
|
+
<link rel="stylesheet" href="./viewer.css" />
|
|
8
|
+
</head>
|
|
9
|
+
<body>
|
|
10
|
+
<script type="module" src="./standalone.js"></script>
|
|
11
|
+
</body>
|
|
12
|
+
</html>
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export const METHODS = ["get", "post", "put", "patch", "delete", "options", "head", "trace"];
|
|
2
|
+
|
|
3
|
+
export function resolve(spec, value, seen = new Set()) {
|
|
4
|
+
if (!value?.$ref || !value.$ref.startsWith("#/")) return value || {};
|
|
5
|
+
if (seen.has(value.$ref)) return { type: "object", title: "순환 참조" };
|
|
6
|
+
const ref = value.$ref;
|
|
7
|
+
const target = ref.slice(2).split("/").reduce((item, key) => item?.[key.replace(/~1/g, "/").replace(/~0/g, "~")], spec);
|
|
8
|
+
if (!target) return { ...value, title: `참조를 찾을 수 없음: ${ref}` };
|
|
9
|
+
return { ...resolve(spec, target, new Set([...seen, ref])), ...Object.fromEntries(Object.entries(value).filter(([key]) => key !== "$ref")) };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function operations(spec) {
|
|
13
|
+
return Object.entries(spec.paths).flatMap(([path, rawItem]) => {
|
|
14
|
+
const item = resolve(spec, rawItem);
|
|
15
|
+
return METHODS.filter((method) => item[method]).map((method) => {
|
|
16
|
+
const operation = resolve(spec, item[method]);
|
|
17
|
+
return { ...operation, path, method, key: `${method.toUpperCase()} ${path}`, group: operation.tags?.[0] || "기타 API", item };
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function parameters(spec, op) {
|
|
23
|
+
const merged = new Map();
|
|
24
|
+
for (const raw of [...(op.item.parameters || []), ...(op.parameters || [])]) {
|
|
25
|
+
const parameter = resolve(spec, raw);
|
|
26
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
27
|
+
}
|
|
28
|
+
return [...merged.values()];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function schema(spec, raw, depth = 0) {
|
|
32
|
+
const value = resolve(spec, raw);
|
|
33
|
+
if (!value.allOf || depth > 8) return value;
|
|
34
|
+
const parts = value.allOf.map((part) => schema(spec, part, depth + 1));
|
|
35
|
+
return { ...value, properties: Object.assign({}, ...parts.map((part) => part.properties), value.properties), required: [...new Set([...parts.flatMap((part) => part.required || []), ...(value.required || [])])] };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function example(spec, raw, seen = new Set(), depth = 0, mode = "response") {
|
|
39
|
+
if (!raw || depth > 8 || (raw.$ref && seen.has(raw.$ref))) return null;
|
|
40
|
+
const next = new Set(seen);
|
|
41
|
+
if (raw.$ref) next.add(raw.$ref);
|
|
42
|
+
const value = schema(spec, raw);
|
|
43
|
+
for (const key of ["example", "default", "const"]) if (value[key] !== undefined) return value[key];
|
|
44
|
+
if (value.examples?.length) return value.examples[0];
|
|
45
|
+
if (value.enum?.length) return value.enum[0];
|
|
46
|
+
if (value.oneOf || value.anyOf) return example(spec, (value.oneOf || value.anyOf)[0], next, depth + 1, mode);
|
|
47
|
+
if (value.type === "array" || value.items) return [example(spec, value.items, next, depth + 1, mode)];
|
|
48
|
+
if (value.type === "object" || value.properties) {
|
|
49
|
+
return Object.fromEntries(Object.entries(value.properties || {}).filter(([, prop]) => !resolve(spec, prop)[mode === "request" ? "readOnly" : "writeOnly"]).map(([name, prop]) => [name, example(spec, prop, next, depth + 1, mode)]));
|
|
50
|
+
}
|
|
51
|
+
if (value.type === "boolean") return true;
|
|
52
|
+
if (value.type === "integer" || value.type === "number") return value.minimum ?? 0;
|
|
53
|
+
return ({ "date-time": "2026-01-01T00:00:00.000Z", date: "2026-01-01", uuid: "123e4567-e89b-12d3-a456-426614174000", email: "user@example.com", binary: "<파일>" })[value.format] || "text";
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function mediaExample(spec, media, mode = "response") {
|
|
57
|
+
if (media.example !== undefined) return media.example;
|
|
58
|
+
const first = Object.values(media.examples || {})[0];
|
|
59
|
+
if (first) {
|
|
60
|
+
const value = resolve(spec, first);
|
|
61
|
+
if (value.value !== undefined) return value.value;
|
|
62
|
+
}
|
|
63
|
+
return example(spec, media.schema, new Set(), 0, mode);
|
|
64
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
body.api-page .layout {
|
|
2
|
+
grid-template-columns: minmax(0, 1fr);
|
|
3
|
+
}
|
|
4
|
+
body.api-page :is(.sidebar, .toc, #pagination, #breadcrumb) { display: none; }
|
|
5
|
+
body.api-page main { padding: 0; }
|
|
6
|
+
.api-reference-view {
|
|
7
|
+
display: block;
|
|
8
|
+
width: 100%;
|
|
9
|
+
border: 0;
|
|
10
|
+
margin: 0;
|
|
11
|
+
background: #fff;
|
|
12
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { mountApiReference } from "./viewer.js";
|
|
2
|
+
|
|
3
|
+
export function renderApiReference(doc, anchor) {
|
|
4
|
+
if (!doc.apiReference) return false;
|
|
5
|
+
const host = document.createElement("div");
|
|
6
|
+
host.className = "api-reference-view";
|
|
7
|
+
const root = host.attachShadow({ mode: "open" });
|
|
8
|
+
document.querySelector("#article").replaceChildren(host);
|
|
9
|
+
mountApiReference(root, anchor, doc.id);
|
|
10
|
+
window.scrollTo(0, 0);
|
|
11
|
+
return true;
|
|
12
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
:root, :host { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans KR", sans-serif; color: #242a31; background: #fff; font-size: 14px; line-height: 1.65; --line: #e3e8ee; --muted: #707986; --accent: #008bd2; }
|
|
2
|
+
* { box-sizing: border-box; }
|
|
3
|
+
body { margin: 0; }
|
|
4
|
+
html, .navigation, .page-toc, pre, #groups {
|
|
5
|
+
scrollbar-width: thin;
|
|
6
|
+
scrollbar-color: transparent transparent;
|
|
7
|
+
}
|
|
8
|
+
html:hover, html:focus-within,
|
|
9
|
+
.navigation:hover, .navigation:focus-within,
|
|
10
|
+
.page-toc:hover, .page-toc:focus-within,
|
|
11
|
+
pre:hover, pre:focus-visible,
|
|
12
|
+
#groups:hover, #groups:focus-within {
|
|
13
|
+
scrollbar-color: #cbd3dc transparent;
|
|
14
|
+
}
|
|
15
|
+
:is(html, .navigation, .page-toc, pre, #groups)::-webkit-scrollbar { width: 5px; height: 5px; }
|
|
16
|
+
:is(html, .navigation, .page-toc, pre, #groups)::-webkit-scrollbar-track { background: transparent; }
|
|
17
|
+
:is(html, .navigation, .page-toc, pre, #groups)::-webkit-scrollbar-thumb { background: transparent; border-radius: 999px; }
|
|
18
|
+
:is(html, .navigation, .page-toc, pre, #groups):is(:hover, :focus-within)::-webkit-scrollbar-thumb { background: #cbd3dc; }
|
|
19
|
+
:is(html, .navigation, .page-toc, pre, #groups)::-webkit-scrollbar-corner { background: transparent; }
|
|
20
|
+
[hidden] { display: none !important; }
|
|
21
|
+
a { color: var(--accent); text-decoration: none; }
|
|
22
|
+
a:hover { text-decoration: underline; }
|
|
23
|
+
button, input, select { font: inherit; }
|
|
24
|
+
button, select { cursor: pointer; }
|
|
25
|
+
button { background: #fff; border: 1px solid var(--line); border-radius: 6px; padding: 4px 10px; color: inherit; }
|
|
26
|
+
button:hover { background: #edf5fb; }
|
|
27
|
+
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible, summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
|
28
|
+
pre:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
|
29
|
+
.spec-status { padding: 8px 24px; border-bottom: 1px solid var(--line); background: #fafbfc; color: var(--muted); font-size: 12px; }
|
|
30
|
+
.spec-status-failed { background: #fff3f0; color: #9a3412; padding: 24px; }
|
|
31
|
+
.docs-layout { display: grid; grid-template-columns: 288px minmax(0, 1fr) 224px; align-items: start; max-width: 1800px; margin: auto; }
|
|
32
|
+
.navigation, .page-toc { position: sticky; top: 0; max-height: 100vh; overflow-y: auto; padding: 28px 20px; scrollbar-width: thin; }
|
|
33
|
+
.navigation { padding: 34px 14px 30px 0; }
|
|
34
|
+
.brand { color: #242a31; font-size: 17px; font-weight: 700; display: block; margin-bottom: 18px; }
|
|
35
|
+
.group-link { display: flex; align-items: start; gap: 8px; justify-content: space-between; padding: 9px 10px; color: #65707b; border-radius: 5px; font-size: 13px; overflow-wrap: anywhere; }
|
|
36
|
+
.group-link:focus-visible { outline-offset: -2px; }
|
|
37
|
+
.group-link:hover { background: #f5f7f9; text-decoration: none; }
|
|
38
|
+
.group-link.active { background: #edf8ff; color: var(--accent); font-weight: 600; }
|
|
39
|
+
.count { font-size: 11px; color: #8a94a0; font-weight: 400; }
|
|
40
|
+
.download { display: block; font-size: 12px; padding: 24px 10px 8px; }
|
|
41
|
+
#content { min-width: 0; padding: 28px 48px 80px; }
|
|
42
|
+
.group-header { padding-bottom: 30px; border-bottom: 1px solid var(--line); }
|
|
43
|
+
.eyebrow { color: var(--accent); font-size: 12px; font-weight: 500; }
|
|
44
|
+
h1 { font-size: 32px; line-height: 1.25; letter-spacing: -1px; margin: 12px 0 18px; overflow-wrap: anywhere; }
|
|
45
|
+
h2 { font-size: 22px; line-height: 1.5; letter-spacing: -.5px; margin: 0; }
|
|
46
|
+
h3 { font-size: 15px; margin: 26px 0 10px; }
|
|
47
|
+
h4 { font-size: 13px; margin: 16px 0 8px; }
|
|
48
|
+
p { margin: 8px 0 14px; }
|
|
49
|
+
.operation { padding: 38px 0 42px; border-bottom: 1px solid var(--line); scroll-margin-top: 24px; }
|
|
50
|
+
.operation-title { display: flex; flex-wrap: wrap; gap: 10px; align-items: baseline; }
|
|
51
|
+
.permalink { color: #a3adb7; font-size: 16px; }
|
|
52
|
+
.endpoint { display: flex; align-items: center; gap: 10px; margin: 14px 0 22px; overflow-wrap: anywhere; }
|
|
53
|
+
.endpoint > code { background: none; border: none; color: #65707b; padding: 0; }
|
|
54
|
+
.method { display: inline-block; flex-shrink: 0; padding: 1px 6px; border-radius: 4px; font: 600 11px/1.7 ui-monospace, SFMono-Regular, Menlo, monospace; background: #eef2f6; color: #52606d; }
|
|
55
|
+
.method.get { background: #ddfbe8; color: #08783b; }
|
|
56
|
+
.method.post { background: #fff3c4; color: #9c5700; }
|
|
57
|
+
.method.patch { background: #f0e6ff; color: #7b1ac5; }
|
|
58
|
+
.method.put { background: #deedff; color: #1659b7; }
|
|
59
|
+
.method.delete { background: #ffe6e8; color: #b82b3c; }
|
|
60
|
+
.operation-columns { display: grid; grid-template-columns: minmax(0, 1fr) minmax(280px, .9fr); gap: 28px; align-items: start; }
|
|
61
|
+
.operation-document { min-width: 0; overflow-wrap: anywhere; }
|
|
62
|
+
.operation-document > :first-child { margin-top: 0; }
|
|
63
|
+
.samples { position: sticky; top: 24px; min-width: 0; }
|
|
64
|
+
.sample-card { border: 1px solid var(--line); border-radius: 8px; overflow: hidden; background: #f7f9fb; margin: 0 0 16px; box-shadow: 0 2px 0 #e5e9ed; }
|
|
65
|
+
.sample-heading { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; padding: 10px 12px; border-bottom: 1px solid var(--line); font-size: 12px; }
|
|
66
|
+
.sample-heading button { margin-left: auto; font-size: 11px; padding: 2px 8px; }
|
|
67
|
+
.sample-type { color: var(--muted); font-size: 11px; overflow-wrap: anywhere; }
|
|
68
|
+
pre { margin: 0; padding: 16px; overflow: auto; max-height: 480px; font: 12px/1.8 ui-monospace, SFMono-Regular, Menlo, monospace; tab-size: 2; }
|
|
69
|
+
code { font: .9em/1.6 ui-monospace, SFMono-Regular, Menlo, monospace; background: #f4f6f8; border: 1px solid #e5e8eb; border-radius: 3px; padding: 1px 4px; overflow-wrap: anywhere; }
|
|
70
|
+
pre code { border: none; padding: 0; background: none; font: inherit; overflow-wrap: normal; }
|
|
71
|
+
.syntax-method { color: #df1239; }
|
|
72
|
+
.syntax-protocol { color: #df1239; }
|
|
73
|
+
.syntax-key { color: #b85500; }
|
|
74
|
+
.syntax-string { color: #00802b; }
|
|
75
|
+
.syntax-number { color: #155cc2; }
|
|
76
|
+
.syntax-literal { color: #7a28b8; }
|
|
77
|
+
.syntax-punctuation { color: #727b87; }
|
|
78
|
+
.operation-document pre { border: 1px solid var(--line); border-radius: 6px; background: #f7f9fb; margin: 14px 0; }
|
|
79
|
+
.operation-document ul, .operation-document ol { padding-left: 22px; }
|
|
80
|
+
.operation-document li { margin: 6px 0; }
|
|
81
|
+
.operation-document details { border: 1px solid var(--line); border-radius: 6px; padding: 10px 12px; margin: 12px 0; }
|
|
82
|
+
summary { cursor: pointer; color: #65707b; font-weight: 600; }
|
|
83
|
+
details[open] > summary { margin-bottom: 12px; }
|
|
84
|
+
.operation-document table { width: 100%; border-collapse: collapse; margin: 12px 0; font-size: 12px; }
|
|
85
|
+
.operation-document th, .operation-document td { border: 1px solid var(--line); text-align: left; padding: 7px; }
|
|
86
|
+
.group-header > details { border: 1px solid var(--line); border-radius: 8px; margin: 24px 0 0; padding: 0 20px; overflow-wrap: anywhere; }
|
|
87
|
+
.group-header > details:has(+ details) { border-bottom-left-radius: 0; border-bottom-right-radius: 0; }
|
|
88
|
+
.group-header > details + details { margin-top: -1px; border-top-left-radius: 0; border-top-right-radius: 0; }
|
|
89
|
+
.group-header > details > summary { display: flex; align-items: baseline; gap: 14px; list-style: none; padding: 18px 0; font-size: 14px; }
|
|
90
|
+
.group-header > details > summary::-webkit-details-marker { display: none; }
|
|
91
|
+
.group-header > details > summary::before { content: ""; width: 6px; height: 6px; border-top: 1.5px solid currentColor; border-right: 1.5px solid currentColor; transform: rotate(45deg); flex-shrink: 0; align-self: center; transition: transform .15s ease; }
|
|
92
|
+
.group-header > details[open] > summary { color: #242a31; margin-bottom: 0; }
|
|
93
|
+
.group-header > details[open] > summary::before { transform: rotate(135deg); }
|
|
94
|
+
.group-header > details[open] { padding-bottom: 20px; }
|
|
95
|
+
.group-header > details > :not(summary) { margin-left: 20px; margin-right: 0; }
|
|
96
|
+
.group-header > details p { margin-top: 0; margin-bottom: 16px; }
|
|
97
|
+
.group-header table { width: calc(100% - 20px); border-collapse: separate; border-spacing: 0; font-size: 13px; margin-top: 16px; }
|
|
98
|
+
.group-header :is(th, td) { text-align: left; padding: 10px 12px; vertical-align: top; border-bottom: 1px solid var(--line); }
|
|
99
|
+
.group-header th { background: #f5f7f9; font-weight: 500; border-top: 1px solid var(--line); }
|
|
100
|
+
.group-header th:first-child { border-radius: 6px 0 0 6px; border-left: 1px solid var(--line); }
|
|
101
|
+
.group-header th:last-child { border-radius: 0 6px 6px 0; border-right: 1px solid var(--line); }
|
|
102
|
+
.group-header td + td { border-left: 1px solid var(--line); }
|
|
103
|
+
.group-header tbody tr:last-child td { border-bottom: 0; }
|
|
104
|
+
.field { padding: 13px 0; border-top: 1px solid var(--line); }
|
|
105
|
+
.field-heading { display: flex; flex-wrap: wrap; gap: 8px; align-items: baseline; font-size: 12px; }
|
|
106
|
+
.field-heading > code { color: #27323b; font-size: 13px; }
|
|
107
|
+
.field p { margin: 6px 0; font-size: 13px; }
|
|
108
|
+
.field-type, .muted, .constraint { color: var(--muted); }
|
|
109
|
+
.constraint { font-size: 12px; margin-top: 4px; }
|
|
110
|
+
.required { color: #bd6000; font-size: 11px; font-weight: 500; }
|
|
111
|
+
.deprecated { color: #a64640; background: #fff0ee; border-radius: 4px; padding: 2px 5px; font-size: 11px; }
|
|
112
|
+
.response-tabs { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 12px; }
|
|
113
|
+
.response-tabs button { color: var(--muted); font-size: 12px; }
|
|
114
|
+
.response-tabs .selected { background: #edf8ff; border-color: #88cbed; color: #0085c9; }
|
|
115
|
+
.response-code { color: #07824d; font-weight: 600; }
|
|
116
|
+
.media-label { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; color: var(--muted); font-size: 12px; }
|
|
117
|
+
select { max-width: 100%; border: 1px solid var(--line); border-radius: 5px; padding: 5px; background: #fff; }
|
|
118
|
+
.sample-note { font-size: 11px; color: var(--muted); margin: 8px 0 20px; }
|
|
119
|
+
.page-toc { padding: 34px 0 30px; font-size: 12px; }
|
|
120
|
+
.page-toc > span { display: block; color: #8a949e; font-size: 11px; font-weight: 600; margin-bottom: 15px; }
|
|
121
|
+
.page-toc a { display: flex; align-items: baseline; gap: 7px; color: #77808b; margin: 0 0 15px; line-height: 1.6; }
|
|
122
|
+
.page-toc a:hover { color: var(--accent); }
|
|
123
|
+
.empty { padding: 24px 0; color: var(--muted); }
|
|
124
|
+
.route-warning { border-left: 3px solid #dba54e; padding: 8px 12px; background: #fff9eb; font-size: 13px; }
|
|
125
|
+
@media (max-width: 1200px) { .docs-layout { grid-template-columns: 230px minmax(0, 1fr); } .page-toc { display: none; } #content { padding: 28px; } }
|
|
126
|
+
@media (max-width: 1000px) { .operation-columns { grid-template-columns: minmax(0, 1fr); } .samples { position: static; margin-top: 15px; } }
|
|
127
|
+
@media (max-width: 640px) { .docs-layout { display: block; } .navigation { position: static; max-height: none; padding: 16px; border-right: 0; border-bottom: 1px solid var(--line); } .brand { margin-bottom: 12px; } #groups { max-height: 190px; overflow-y: auto; } .download { padding: 12px 10px 0; } #content { padding: 24px 18px 60px; } h1 { font-size: 26px; } h2 { font-size: 20px; } .operation { padding-top: 28px; } .spec-status { padding: 8px 16px; } }
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { resolve, operations, parameters, schema, mediaExample } from "./model.js";
|
|
2
|
+
|
|
3
|
+
export async function mountApiReference(root, anchor = "", documentId = "api/README") {
|
|
4
|
+
const document = root;
|
|
5
|
+
const base = new URL("./", import.meta.url);
|
|
6
|
+
root.innerHTML = `<link rel="stylesheet" href="${new URL("viewer.css", base).href}">
|
|
7
|
+
<div class="spec-status" id="spec-status" role="status">API 명세를 불러오는 중입니다.</div>
|
|
8
|
+
<div class="docs-layout" id="docs-layout" hidden>
|
|
9
|
+
<aside class="navigation" aria-label="API 기능 목록"><nav id="groups"></nav><a class="download" href="${new URL("openapi.json", base).href}" download>OpenAPI 명세 다운로드 ↗</a></aside>
|
|
10
|
+
<main id="content" tabindex="-1"></main>
|
|
11
|
+
<aside class="page-toc" aria-label="현재 페이지 API 목차"><span>이 페이지의 API</span><nav id="toc"></nav></aside></div>`;
|
|
12
|
+
let selection = anchor.startsWith("group:") ? { group: anchor.slice(6) } : { operation: anchor };
|
|
13
|
+
function reveal(element) {
|
|
14
|
+
if (element) element.scrollIntoView({ block: "start" });
|
|
15
|
+
else window.scrollTo(0, 0);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const status = document.querySelector("#spec-status");
|
|
19
|
+
const content = document.querySelector("#content");
|
|
20
|
+
const groupNav = document.querySelector("#groups");
|
|
21
|
+
const toc = document.querySelector("#toc");
|
|
22
|
+
const escape = (value = "") => String(value).replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]);
|
|
23
|
+
const description = (value) => value?.["x-doc-description"] || (value?.description ? `<p>${escape(value.description)}</p>` : "");
|
|
24
|
+
const badge = (method) => `<span class="method ${method}">${method.toUpperCase()}</span>`;
|
|
25
|
+
const json = (value) => JSON.stringify(value, null, 2) ?? "null";
|
|
26
|
+
const token = (kind, value) => `<span class="syntax-${kind}">${escape(value)}</span>`;
|
|
27
|
+
|
|
28
|
+
function highlightJson(value) {
|
|
29
|
+
const pattern = /"(?:\\.|[^"\\])*"|-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b(?:true|false|null)\b|[{}\[\],:]/g;
|
|
30
|
+
let html = "";
|
|
31
|
+
let end = 0;
|
|
32
|
+
for (const match of value.matchAll(pattern)) {
|
|
33
|
+
html += escape(value.slice(end, match.index));
|
|
34
|
+
const text = match[0];
|
|
35
|
+
const kind = text.startsWith('"')
|
|
36
|
+
? /^\s*:/.test(value.slice(match.index + text.length)) ? "key" : "string"
|
|
37
|
+
: /^[{}\[\],:]$/.test(text) ? "punctuation"
|
|
38
|
+
: /^(true|false|null)$/.test(text) ? "literal" : "number";
|
|
39
|
+
html += token(kind, text);
|
|
40
|
+
end = match.index + text.length;
|
|
41
|
+
}
|
|
42
|
+
return html + escape(value.slice(end));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function highlightSample(raw) {
|
|
46
|
+
const value = String(raw);
|
|
47
|
+
const first = value.match(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD|TRACE) (.+) (HTTP\/\d(?:\.\d)?)$/m);
|
|
48
|
+
if (!first || first.index !== 0) return /^[\s]*[\[{"\d-]|^(true|false|null)$/.test(value) ? highlightJson(value) : escape(value);
|
|
49
|
+
const [header, ...body] = value.split("\n\n");
|
|
50
|
+
const lines = header.split("\n");
|
|
51
|
+
lines[0] = `${token("method", first[1])} ${escape(first[2])} ${token("protocol", first[3])}`;
|
|
52
|
+
for (let i = 1; i < lines.length; i++) {
|
|
53
|
+
const colon = lines[i].indexOf(":");
|
|
54
|
+
lines[i] = colon < 0 ? escape(lines[i]) : `${token("key", lines[i].slice(0, colon))}${token("punctuation", ":")}${token("string", lines[i].slice(colon + 1))}`;
|
|
55
|
+
}
|
|
56
|
+
const payload = body.join("\n\n");
|
|
57
|
+
return lines.join("\n") + (body.length ? `\n\n${/^\s*[\[{]/.test(payload) ? highlightJson(payload) : escape(payload)}` : "");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const code = (value) => `<pre tabindex="0"><code>${highlightSample(value)}</code></pre>`;
|
|
61
|
+
const time = (value) => value && !Number.isNaN(Date.parse(value)) ? new Intl.DateTimeFormat("ko-KR", { timeZone: "Asia/Seoul", dateStyle: "medium", timeStyle: "short" }).format(new Date(value)) : "미확인";
|
|
62
|
+
let spec, all, groups;
|
|
63
|
+
|
|
64
|
+
function typeLabel(raw, depth = 0) {
|
|
65
|
+
if (depth > 6) return "object";
|
|
66
|
+
const value = schema(spec, raw);
|
|
67
|
+
if (value.oneOf || value.anyOf) return (value.oneOf || value.anyOf).map((variant) => typeLabel(variant, depth + 1)).join(" | ");
|
|
68
|
+
if (value.type === "array" || value.items) return `${typeLabel(value.items, depth + 1)}[]`;
|
|
69
|
+
return `${Array.isArray(value.type) ? value.type.join(" | ") : value.type || (value.properties ? "object" : "미지정")}${value.format ? ` · ${value.format}` : ""}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function fields(raw, depth = 0, seen = new Set(), mode = "response") {
|
|
73
|
+
if (!raw) return "";
|
|
74
|
+
if (depth > 6 || (raw.$ref && seen.has(raw.$ref))) return '<p class="muted">참조 모델이 반복됩니다. 전체 정의는 OpenAPI 명세에서 확인하세요.</p>';
|
|
75
|
+
const next = new Set(seen);
|
|
76
|
+
if (raw.$ref) next.add(raw.$ref);
|
|
77
|
+
const value = schema(spec, raw);
|
|
78
|
+
const variants = value.oneOf || value.anyOf;
|
|
79
|
+
if (variants) return variants.map((variant, i) => `<details class="model"><summary>${value.oneOf ? "oneOf" : "anyOf"} · ${i + 1}번째 모델</summary>${fields(variant, depth + 1, next, mode)}</details>`).join("");
|
|
80
|
+
if (value.items) return fields(value.items, depth + 1, next, mode);
|
|
81
|
+
if (!value.properties) return `<div class="field"><code>${escape(typeLabel(raw))}</code>${description(value)}${value.enum ? `<p>허용 값: ${value.enum.map((v) => `<code>${escape(json(v))}</code>`).join(" ")}</p>` : ""}${value.additionalProperties ? '<p class="muted">추가 키를 허용하는 객체입니다.</p>' : ""}</div>`;
|
|
82
|
+
return Object.entries(value.properties).filter(([, prop]) => !resolve(spec, prop)[mode === "request" ? "readOnly" : "writeOnly"]).map(([name, prop]) => {
|
|
83
|
+
const item = schema(spec, prop);
|
|
84
|
+
const nested = item.properties || item.items || item.oneOf || item.anyOf;
|
|
85
|
+
const constraints = [item.enum && `허용 값: ${item.enum.map((v) => json(v)).join(", ")}`, item.default !== undefined && `기본값: ${json(item.default)}`, item.nullable && "null 허용", item.minLength !== undefined && `최소 길이: ${item.minLength}`, item.maxLength !== undefined && `최대 길이: ${item.maxLength}`, item.minimum !== undefined && `최솟값: ${item.minimum}`, item.maximum !== undefined && `최댓값: ${item.maximum}`, item.pattern && `패턴: ${item.pattern}`].filter(Boolean);
|
|
86
|
+
return `<div class="field"><div class="field-heading"><code>${escape(name)}</code><span class="field-type">${escape(typeLabel(prop))}</span><span class="${value.required?.includes(name) ? "required" : "muted"}">${value.required?.includes(name) ? "필수" : "선택"}</span>${item.deprecated ? '<span class="deprecated">사용 중단 예정</span>' : ""}</div>${description(item)}${constraints.map((c) => `<div class="constraint">${escape(c)}</div>`).join("")}${nested ? `<details class="model"><summary>모델 펼치기</summary>${fields(prop, depth + 1, next, mode)}</details>` : ""}</div>`;
|
|
87
|
+
}).join("");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function security(op) {
|
|
91
|
+
const requirements = op.security ?? spec.security ?? [];
|
|
92
|
+
if (!requirements.length) return '<p class="muted">명세에 인증 요구사항이 없습니다.</p>';
|
|
93
|
+
return requirements.map((requirement) => {
|
|
94
|
+
if (!Object.keys(requirement).length) return '<p class="muted">인증 없이 접근할 수 있는 대안이 있습니다.</p>';
|
|
95
|
+
return `<div class="security-option">${Object.entries(requirement).map(([name, scopes]) => {
|
|
96
|
+
const value = resolve(spec, spec.components?.securitySchemes?.[name]);
|
|
97
|
+
return `<div><code>${escape(name)}</code> <span class="muted">${escape(value.type || "")}${value.scheme ? ` · ${escape(value.scheme)}` : ""}${value.in ? ` · ${escape(value.in)}: ${escape(value.name)}` : ""}</span>${description(value)}${scopes.length ? `<p>필요 scope: ${scopes.map(escape).join(", ")}</p>` : ""}</div>`;
|
|
98
|
+
}).join('<span class="muted">그리고</span>')}</div>`;
|
|
99
|
+
}).join('<p class="muted">또는</p>');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function parameterFields(op) {
|
|
103
|
+
const params = parameters(spec, op);
|
|
104
|
+
return ["path", "query", "header", "cookie"].map((location) => {
|
|
105
|
+
const selected = params.filter((p) => p.in === location);
|
|
106
|
+
if (!selected.length) return "";
|
|
107
|
+
return `<h3>${({ path: "경로", query: "쿼리", header: "헤더", cookie: "쿠키" })[location]} 파라미터</h3>${selected.map((p) => `<div class="field"><div class="field-heading"><code>${escape(p.name)}</code><span class="field-type">${escape(typeLabel(p.schema))}</span><span class="${p.required || p.in === "path" ? "required" : "muted"}">${p.required || p.in === "path" ? "필수" : "선택"}</span></div>${description(p)}${p.schema?.enum ? `<p>허용 값: ${p.schema.enum.map((v) => `<code>${escape(json(v))}</code>`).join(" ")}</p>` : ""}</div>`).join("")}`;
|
|
108
|
+
}).join("");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function mediaSelector(entries, kind) {
|
|
112
|
+
return entries.length > 1 ? `<label class="media-label">형식 <select data-media="${kind}">${entries.map(([type]) => `<option>${escape(type)}</option>`).join("")}</select></label>` : `<span class="muted">${escape(entries[0]?.[0] || "")}</span>`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function requestPanel(op, body) {
|
|
116
|
+
const entries = Object.entries(body.content || {});
|
|
117
|
+
return `<div class="request-content">${entries.map(([type, media], i) => `<div data-media-panel="request" data-type="${escape(type)}" ${i ? "hidden" : ""}><h3>요청 본문 ${body.required ? '<span class="required">필수</span>' : '<span class="muted">선택</span>'}</h3>${description(body)}${fields(media.schema, 0, new Set(), "request")}</div>`).join("")}</div>`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function requestSample(op, type, media) {
|
|
121
|
+
const server = op.servers?.[0] || op.item.servers?.[0] || spec.servers?.[0];
|
|
122
|
+
let base = server?.url || "";
|
|
123
|
+
base = base.replace(/\{([^}]+)\}/g, (whole, key) => server.variables?.[key]?.default ?? whole).replace(/\/$/, "");
|
|
124
|
+
let path = op.path;
|
|
125
|
+
const query = [];
|
|
126
|
+
const headers = [];
|
|
127
|
+
const cookies = [];
|
|
128
|
+
for (const parameter of parameters(spec, op)) {
|
|
129
|
+
const value = parameter.example ?? parameter.schema?.example ?? parameter.schema?.default ?? `<${parameter.name}>`;
|
|
130
|
+
if (parameter.in === "path") path = path.replace(`{${parameter.name}}`, String(value));
|
|
131
|
+
if (parameter.in === "query") query.push(`${encodeURIComponent(parameter.name)}=${encodeURIComponent(String(value))}`);
|
|
132
|
+
if (parameter.in === "header") headers.push(`${parameter.name}: ${value}`);
|
|
133
|
+
if (parameter.in === "cookie") cookies.push(`${parameter.name}=${value}`);
|
|
134
|
+
}
|
|
135
|
+
const requirement = (op.security ?? spec.security ?? [])[0] || {};
|
|
136
|
+
for (const name of Object.keys(requirement)) {
|
|
137
|
+
const auth = resolve(spec, spec.components?.securitySchemes?.[name]);
|
|
138
|
+
if (auth.type === "http") headers.push(`Authorization: ${auth.scheme === "basic" ? "Basic <BASE64_CREDENTIALS>" : "Bearer <TOKEN>"}`);
|
|
139
|
+
if (auth.type === "oauth2" || auth.type === "openIdConnect") headers.push("Authorization: Bearer <TOKEN>");
|
|
140
|
+
if (auth.type === "apiKey") {
|
|
141
|
+
if (auth.in === "header") headers.push(`${auth.name}: <API_KEY>`);
|
|
142
|
+
if (auth.in === "query") query.push(`${encodeURIComponent(auth.name)}=<API_KEY>`);
|
|
143
|
+
if (auth.in === "cookie") cookies.push(`${auth.name}=<API_KEY>`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (cookies.length) headers.push(`Cookie: ${cookies.join("; ")}`);
|
|
147
|
+
if (type) headers.push(`Content-Type: ${type}`);
|
|
148
|
+
const target = `${base}${path}${query.length ? `?${query.join("&")}` : ""}`;
|
|
149
|
+
let first;
|
|
150
|
+
try { const url = new URL(target); first = `${op.method.toUpperCase()} ${url.pathname}${url.search} HTTP/1.1\nHost: ${url.host}`; }
|
|
151
|
+
catch { first = `${op.method.toUpperCase()} ${target} HTTP/1.1`; }
|
|
152
|
+
const body = media ? mediaExample(spec, media, "request") : undefined;
|
|
153
|
+
return `${first}${headers.length ? `\n${headers.join("\n")}` : ""}${media ? `\n\n${type.includes("json") ? json(body) : typeof body === "string" ? body : json(body)}` : ""}`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function responses(op) {
|
|
157
|
+
const entries = Object.entries(op.responses || {}).map(([code, value]) => [code, resolve(spec, value)]);
|
|
158
|
+
if (!entries.length) return '<p class="muted">응답이 정의되지 않았습니다.</p>';
|
|
159
|
+
return `<h3>응답</h3><div class="response-tabs" role="group" aria-label="응답 코드">${entries.map(([code], i) => `<button type="button" class="${i ? "" : "selected"}" data-response="${escape(code)}" aria-pressed="${!i}">${escape(code)}</button>`).join("")}</div>${entries.map(([code, response], i) => `<div data-response-panel="${escape(code)}" ${i ? "hidden" : ""}>${description(response)}${Object.entries(response.headers || {}).length ? `<h4>응답 헤더</h4>${Object.entries(response.headers).map(([name, raw]) => { const header = resolve(spec, raw); return `<div class="field"><code>${escape(name)}</code> <span class="muted">${escape(typeLabel(header.schema))}</span>${description(header)}</div>`; }).join("")}` : ""}${Object.entries(response.content || {}).map(([type, media]) => `<h4>${escape(type)}</h4>${fields(media.schema)}`).join("") || '<p class="muted">응답 본문이 없습니다.</p>'}</div>`).join("")}`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function sampleCard(title, sample, extra = "") {
|
|
163
|
+
return `<div class="sample-card"><div class="sample-heading"><span>${title}</span>${extra}<button type="button" data-copy aria-label="예시 복사">복사</button></div>${code(sample)}</div>`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function operationPage(op, index) {
|
|
167
|
+
const body = resolve(spec, op.requestBody);
|
|
168
|
+
const requestEntries = Object.entries(body.content || {});
|
|
169
|
+
const responseEntries = Object.entries(op.responses || {});
|
|
170
|
+
return `<section class="operation" id="operation-${index}" data-operation="${escape(op.key)}"><div class="operation-title"><h2>${escape(op.summary || op.key)}</h2>${op.deprecated ? '<span class="deprecated">사용 중단 예정</span>' : ""}<a class="permalink" href="#/${encodeURIComponent(documentId)}/${encodeURIComponent(op.key)}" data-api-anchor="${escape(op.key)}" aria-label="이 API 링크">#</a></div><div class="endpoint">${badge(op.method)}<code>${escape(op.path)}</code></div><div class="operation-columns"><div class="operation-document">${description(op)}<h3>인증</h3>${security(op)}${parameterFields(op)}${requestPanel(op, body)}${responses(op)}</div><aside class="samples" aria-label="요청 및 응답 예시">${requestEntries.length ? mediaSelector(requestEntries, "request") : ""}${(requestEntries.length ? requestEntries : [["", null]]).map(([type, media], i) => `<div data-request-sample="${escape(type)}" ${i ? "hidden" : ""}>${sampleCard(`${badge(op.method)} 요청 예시`, requestSample(op, type, media))}</div>`).join("")}${responseEntries.map(([code, raw], i) => {
|
|
171
|
+
const response = resolve(spec, raw);
|
|
172
|
+
const media = Object.entries(response.content || {});
|
|
173
|
+
return `<div data-response-sample="${escape(code)}" ${i ? "hidden" : ""}>${media.length ? media.map(([type, value]) => sampleCard(`<span class="response-code">${escape(code)}</span> 응답 예시`, type.includes("json") ? json(mediaExample(spec, value)) : typeof mediaExample(spec, value) === "string" ? mediaExample(spec, value) : json(mediaExample(spec, value)), `<span class="sample-type">${escape(type)}</span>`)).join("") : sampleCard(`${escape(code)} 응답`, "응답 본문 없음")}</div>`;
|
|
174
|
+
}).join("")}</aside></div></section>`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function route() {
|
|
178
|
+
const requested = selection.operation;
|
|
179
|
+
const op = all.find((item) => item.key === requested || item.operationId === requested);
|
|
180
|
+
return { group: selection.group || op?.group || groups[0], requested, op };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function render() {
|
|
184
|
+
const current = route();
|
|
185
|
+
const matches = all;
|
|
186
|
+
const visibleGroups = groups.filter((group) => matches.some((op) => op.group === group));
|
|
187
|
+
const selected = visibleGroups.includes(current.group) ? current.group : visibleGroups[0];
|
|
188
|
+
groupNav.innerHTML = visibleGroups.map((group) => `<a href="#/${encodeURIComponent(documentId)}/${encodeURIComponent(`group:${group}`)}" data-api-anchor="${escape(`group:${group}`)}" class="group-link ${group === selected ? "active" : ""}" ${group === selected ? 'aria-current="page"' : ""}><span>${escape(group)}</span><span class="count">${matches.filter((op) => op.group === group).length}</span></a>`).join("") || '<p class="empty">검색 결과가 없습니다.</p>';
|
|
189
|
+
const visible = matches.filter((op) => op.group === selected);
|
|
190
|
+
const tag = (spec.tags || []).find((tag) => tag.name === selected);
|
|
191
|
+
content.innerHTML = `<header class="group-header"><div class="eyebrow">API Reference${spec.info?.version ? ` · ${escape(spec.info.version)}` : ""}</div><h1>${escape(selected || "검색 결과 없음")}</h1>${description(tag)}<p class="muted">${visible.length}개 API</p>${current.requested && !current.op ? `<p class="route-warning">현재 명세에 ${escape(current.requested)} 경로가 없습니다.</p>` : ""}</header>${visible.map(operationPage).join("") || '<p class="empty">다른 기능명이나 경로로 검색해보세요.</p>'}`;
|
|
192
|
+
const blocks = [...content.querySelectorAll("pre > code, div.mermaid")].filter((code) => code.classList.contains("mermaid") || code.classList.contains("language-mermaid") || code.textContent.trimStart().startsWith("sequenceDiagram"));
|
|
193
|
+
if (blocks.length) import("../diagrams.js").then(({ renderDiagrams }) => renderDiagrams(blocks, { buttonOnly: true })).catch(() => {});
|
|
194
|
+
toc.innerHTML = visible.map((op, index) => `<a href="#/${encodeURIComponent(documentId)}/${encodeURIComponent(op.key)}" data-api-anchor="${escape(op.key)}" data-scroll="operation-${index}">${badge(op.method)}<span>${escape(op.summary || op.path)}</span></a>`).join("");
|
|
195
|
+
const index = visible.findIndex((op) => op === current.op);
|
|
196
|
+
reveal(index >= 0 ? document.querySelector(`#operation-${index}`) : null);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
content.addEventListener("click", async (event) => {
|
|
200
|
+
const button = event.target.closest("button");
|
|
201
|
+
if (!button) return;
|
|
202
|
+
if (button.hasAttribute("data-copy")) {
|
|
203
|
+
try {
|
|
204
|
+
await navigator.clipboard.writeText(button.closest(".sample-card").querySelector("code").textContent);
|
|
205
|
+
button.textContent = "복사됨";
|
|
206
|
+
setTimeout(() => { button.textContent = "복사"; }, 1600);
|
|
207
|
+
} catch { button.textContent = "텍스트를 선택해 복사하세요"; }
|
|
208
|
+
}
|
|
209
|
+
if (button.dataset.response) {
|
|
210
|
+
const section = button.closest(".operation");
|
|
211
|
+
const selected = button.dataset.response;
|
|
212
|
+
for (const tab of section.querySelectorAll("[data-response]")) {
|
|
213
|
+
tab.classList.toggle("selected", tab.dataset.response === selected);
|
|
214
|
+
tab.setAttribute("aria-pressed", String(tab.dataset.response === selected));
|
|
215
|
+
}
|
|
216
|
+
for (const panel of section.querySelectorAll("[data-response-panel]")) panel.hidden = panel.dataset.responsePanel !== selected;
|
|
217
|
+
for (const panel of section.querySelectorAll("[data-response-sample]")) panel.hidden = panel.dataset.responseSample !== selected;
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
content.addEventListener("change", (event) => {
|
|
221
|
+
if (!event.target.dataset.media) return;
|
|
222
|
+
const section = event.target.closest(".operation");
|
|
223
|
+
for (const panel of section.querySelectorAll('[data-media-panel="request"]')) panel.hidden = panel.dataset.type !== event.target.value;
|
|
224
|
+
for (const sample of section.querySelectorAll("[data-request-sample]")) sample.hidden = sample.dataset.requestSample !== event.target.value;
|
|
225
|
+
});
|
|
226
|
+
root.addEventListener("click", (event) => {
|
|
227
|
+
const link = event.target.closest("a[data-api-anchor]");
|
|
228
|
+
if (!link) return;
|
|
229
|
+
event.preventDefault();
|
|
230
|
+
const anchor = link.dataset.apiAnchor;
|
|
231
|
+
selection = anchor.startsWith("group:") ? { group: anchor.slice(6) } : { operation: anchor };
|
|
232
|
+
history.replaceState(null, "", `#/${encodeURIComponent(documentId)}/${encodeURIComponent(anchor)}`);
|
|
233
|
+
render();
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
try {
|
|
237
|
+
const metadataResponse = await fetch(new URL("spec-metadata.json", base));
|
|
238
|
+
if (!metadataResponse.ok) throw new Error("API 명세 상태를 불러오지 못했습니다.");
|
|
239
|
+
const metadata = await metadataResponse.json();
|
|
240
|
+
if (metadata.available === false) throw new Error(metadata.status === "not-generated" ? "아직 가져온 API 명세가 없습니다." : `명세 다운로드 실패 · ${time(metadata.failedAt)} KST. 다음 배포에서 다시 가져옵니다.`);
|
|
241
|
+
const response = await fetch(new URL("documentation.json", base));
|
|
242
|
+
if (!response.ok) throw new Error("API 명세 파일을 불러오지 못했습니다.");
|
|
243
|
+
spec = await response.json();
|
|
244
|
+
all = operations(spec);
|
|
245
|
+
if (!all.length) throw new Error("표시할 API 경로가 없습니다.");
|
|
246
|
+
groups = [...new Set([...(spec.tags || []).map((tag) => tag.name), ...all.map((op) => op.group)])].filter((group) => all.some((op) => op.group === group));
|
|
247
|
+
status.hidden = true;
|
|
248
|
+
document.querySelector("#docs-layout").hidden = false;
|
|
249
|
+
render();
|
|
250
|
+
} catch (error) {
|
|
251
|
+
status.classList.add("spec-status-failed");
|
|
252
|
+
status.setAttribute("role", "alert");
|
|
253
|
+
status.textContent = `API 명세를 표시하지 못했습니다. ${error.message}`;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
}
|
package/client/app.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { renderApiReference } from "./api-reference/page.js";
|
|
1
2
|
import { searchDocuments, matchRanges, matchesRow } from "./search.js";
|
|
2
3
|
import { attachComments } from "./comments.js";
|
|
3
4
|
|
|
@@ -621,6 +622,7 @@ function render() {
|
|
|
621
622
|
$("#article").dataset.commentDocument = "";
|
|
622
623
|
document.body.classList.toggle("is-spreadsheet", Boolean(current?.spreadsheet));
|
|
623
624
|
document.body.classList.remove("sheet-fullscreen");
|
|
625
|
+
document.body.classList.toggle("api-page", Boolean(current?.apiReference));
|
|
624
626
|
renderNavigation(isFolder ? folderPath : null);
|
|
625
627
|
$("#toc").replaceChildren();
|
|
626
628
|
$("#pagination").replaceChildren();
|
|
@@ -658,6 +660,12 @@ function render() {
|
|
|
658
660
|
window.scrollTo(0, 0);
|
|
659
661
|
return;
|
|
660
662
|
}
|
|
663
|
+
if (current.apiReference) {
|
|
664
|
+
$(".toc").hidden = true;
|
|
665
|
+
$("#pagination").hidden = true;
|
|
666
|
+
renderApiReference(current, anchor);
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
661
669
|
$("#article").dataset.commentDocument = current.id;
|
|
662
670
|
$("#article").innerHTML = current.html;
|
|
663
671
|
if (!$("#article h1")) $("#article").prepend(el("h1", current.title));
|
package/client/comments.js
CHANGED
|
@@ -23,6 +23,7 @@ export async function attachComments(article, documentId, commentId) {
|
|
|
23
23
|
const occurrences = new Map();
|
|
24
24
|
const matched = new Set();
|
|
25
25
|
const anchors = new Map();
|
|
26
|
+
const anchorBlocks = new Map();
|
|
26
27
|
const popover = document.createElement('button');
|
|
27
28
|
popover.type = 'button';
|
|
28
29
|
popover.className = 'comment-selection-trigger';
|
|
@@ -106,6 +107,7 @@ export async function attachComments(article, documentId, commentId) {
|
|
|
106
107
|
matched.add(key);
|
|
107
108
|
const wrapper = document.createElement('div');
|
|
108
109
|
wrapper.className = 'comment-anchor';
|
|
110
|
+
anchorBlocks.set(wrapper, block);
|
|
109
111
|
if (['LI', 'TD', 'TH'].includes(block.tagName)) {
|
|
110
112
|
if (ownNodes) {
|
|
111
113
|
block.insertBefore(wrapper, ownNodes[0]);
|
|
@@ -298,6 +300,13 @@ export async function attachComments(article, documentId, commentId) {
|
|
|
298
300
|
for (const other of article.querySelectorAll('.comment-anchor > .comment-panel')) other.hidden = true;
|
|
299
301
|
for (const other of article.querySelectorAll('.comment-trigger.is-open')) other.classList.remove('is-open');
|
|
300
302
|
draftQuote = quote;
|
|
303
|
+
if (!range) {
|
|
304
|
+
range = document.createRange();
|
|
305
|
+
if (['LI', 'TD', 'TH'].includes(block.tagName)) {
|
|
306
|
+
range.setStart(wrapper, 0);
|
|
307
|
+
range.setEndBefore(button);
|
|
308
|
+
} else range.selectNodeContents(block);
|
|
309
|
+
}
|
|
301
310
|
showDraftHighlight(block, range);
|
|
302
311
|
panel.hidden = false;
|
|
303
312
|
button.classList.add('is-open');
|
|
@@ -323,6 +332,15 @@ export async function attachComments(article, documentId, commentId) {
|
|
|
323
332
|
const alignButtons = () => {
|
|
324
333
|
const right = article.getBoundingClientRect().right;
|
|
325
334
|
for (const wrapper of anchors.keys()) {
|
|
335
|
+
const range = document.createRange();
|
|
336
|
+
const block = anchorBlocks.get(wrapper);
|
|
337
|
+
if (['LI', 'TD', 'TH'].includes(block.tagName)) {
|
|
338
|
+
range.setStart(wrapper, 0);
|
|
339
|
+
range.setEndBefore(wrapper.querySelector('.comment-trigger'));
|
|
340
|
+
} else range.selectNodeContents(block);
|
|
341
|
+
const content = range.getBoundingClientRect();
|
|
342
|
+
const bounds = wrapper.getBoundingClientRect();
|
|
343
|
+
wrapper.style.setProperty('--comment-center', `${(content.top + content.bottom) / 2 - bounds.top}px`);
|
|
326
344
|
wrapper.style.setProperty('--comment-offset', `${Math.max(0, right - wrapper.getBoundingClientRect().right)}px`);
|
|
327
345
|
wrapper.style.setProperty('--comment-panel-right', `${wrapper.getBoundingClientRect().right - window.innerWidth + 16}px`);
|
|
328
346
|
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
export function clampZoom(value) {
|
|
2
|
+
return Math.min(8, Math.max(0.05, value));
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function fitZoom(width, height, viewportWidth, viewportHeight) {
|
|
6
|
+
return clampZoom(Math.min((viewportWidth - 32) / width, (viewportHeight - 32) / height, 1));
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function openDiagram(source, trigger) {
|
|
10
|
+
const dialog = document.createElement("dialog");
|
|
11
|
+
dialog.className = "diagram-dialog";
|
|
12
|
+
dialog.setAttribute("aria-label", "다이어그램 크게 보기");
|
|
13
|
+
dialog.innerHTML = `<div class="diagram-toolbar"><strong>다이어그램</strong><button type="button" data-action="out" aria-label="축소">−</button><output aria-live="polite"></output><button type="button" data-action="in" aria-label="확대">+</button><button type="button" data-action="reset">100%</button><button type="button" data-action="fit">화면 맞춤</button><button type="button" data-action="fullscreen">전체화면</button><button type="button" data-action="close" aria-label="다이어그램 닫기">닫기</button></div><div class="diagram-viewport" tabindex="0" aria-label="다이어그램 이동 영역"><div class="diagram-canvas"></div></div><p class="diagram-viewer-status" role="status"></p>`;
|
|
14
|
+
const svg = source.cloneNode(true);
|
|
15
|
+
// Avoid duplicate SVG IDs while retaining markers, CSS selectors and accessibility refs.
|
|
16
|
+
const suffix = `-viewer-${Date.now()}`;
|
|
17
|
+
const ids = [...svg.querySelectorAll("[id]")].map((node) => node.id);
|
|
18
|
+
if (svg.id) ids.push(svg.id);
|
|
19
|
+
let markup = svg.outerHTML;
|
|
20
|
+
for (const id of ids.sort((a, b) => b.length - a.length)) {
|
|
21
|
+
markup = markup.replaceAll(`id="${id}"`, `id="${id}${suffix}"`).replaceAll(`#${id}`, `#${id}${suffix}`);
|
|
22
|
+
}
|
|
23
|
+
const canvas = dialog.querySelector(".diagram-canvas");
|
|
24
|
+
canvas.innerHTML = markup;
|
|
25
|
+
const image = canvas.querySelector("svg");
|
|
26
|
+
const box = source.viewBox.baseVal;
|
|
27
|
+
const width = box.width || source.getBoundingClientRect().width || 1200;
|
|
28
|
+
const height = box.height || source.getBoundingClientRect().height || 800;
|
|
29
|
+
const viewport = dialog.querySelector(".diagram-viewport");
|
|
30
|
+
let ownsFullscreen = false;
|
|
31
|
+
let zoom = 1;
|
|
32
|
+
let fitting = true;
|
|
33
|
+
let x = 0, y = 0;
|
|
34
|
+
function paint() {
|
|
35
|
+
image.style.width = `${width * zoom}px`;
|
|
36
|
+
image.style.height = `${height * zoom}px`;
|
|
37
|
+
image.style.maxWidth = "none";
|
|
38
|
+
image.style.display = "block";
|
|
39
|
+
canvas.style.transform = `translate(${x}px, ${y}px)`;
|
|
40
|
+
dialog.querySelector("output").textContent = `${Math.round(zoom * 100)}%`;
|
|
41
|
+
}
|
|
42
|
+
function apply(value, px = viewport.clientWidth / 2, py = viewport.clientHeight / 2) {
|
|
43
|
+
const next = clampZoom(value);
|
|
44
|
+
const ratio = next / zoom;
|
|
45
|
+
x = px - (px - x) * ratio;
|
|
46
|
+
y = py - (py - y) * ratio;
|
|
47
|
+
zoom = next;
|
|
48
|
+
paint();
|
|
49
|
+
}
|
|
50
|
+
const fit = () => {
|
|
51
|
+
zoom = fitZoom(width, height, viewport.clientWidth, viewport.clientHeight);
|
|
52
|
+
x = (viewport.clientWidth - width * zoom) / 2;
|
|
53
|
+
y = (viewport.clientHeight - height * zoom) / 2;
|
|
54
|
+
paint();
|
|
55
|
+
};
|
|
56
|
+
const observer = new ResizeObserver(() => { if (fitting) fit(); });
|
|
57
|
+
viewport.addEventListener("wheel", (event) => {
|
|
58
|
+
event.preventDefault();
|
|
59
|
+
fitting = false;
|
|
60
|
+
const rect = viewport.getBoundingClientRect();
|
|
61
|
+
const delta = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? viewport.clientHeight : 1);
|
|
62
|
+
apply(zoom * Math.exp(-delta * 0.002), event.clientX - rect.left, event.clientY - rect.top);
|
|
63
|
+
}, { passive: false });
|
|
64
|
+
let drag;
|
|
65
|
+
viewport.addEventListener("pointerdown", (event) => {
|
|
66
|
+
if (event.button !== 0 || drag) return;
|
|
67
|
+
event.preventDefault();
|
|
68
|
+
fitting = false;
|
|
69
|
+
drag = { id: event.pointerId, x: event.clientX, y: event.clientY };
|
|
70
|
+
viewport.setPointerCapture(event.pointerId);
|
|
71
|
+
viewport.classList.add("is-dragging");
|
|
72
|
+
});
|
|
73
|
+
viewport.addEventListener("pointermove", (event) => {
|
|
74
|
+
if (!drag || drag.id !== event.pointerId) return;
|
|
75
|
+
x += event.clientX - drag.x;
|
|
76
|
+
y += event.clientY - drag.y;
|
|
77
|
+
drag.x = event.clientX;
|
|
78
|
+
drag.y = event.clientY;
|
|
79
|
+
paint();
|
|
80
|
+
});
|
|
81
|
+
const release = (event) => {
|
|
82
|
+
if (drag?.id !== event.pointerId) return;
|
|
83
|
+
drag = null;
|
|
84
|
+
viewport.classList.remove("is-dragging");
|
|
85
|
+
if (viewport.hasPointerCapture(event.pointerId)) viewport.releasePointerCapture(event.pointerId);
|
|
86
|
+
};
|
|
87
|
+
for (const name of ["pointerup", "pointercancel", "lostpointercapture"]) viewport.addEventListener(name, release);
|
|
88
|
+
viewport.addEventListener("keydown", (event) => {
|
|
89
|
+
const offset = { ArrowLeft: [40, 0], ArrowRight: [-40, 0], ArrowUp: [0, 40], ArrowDown: [0, -40] }[event.key];
|
|
90
|
+
if (!offset) return;
|
|
91
|
+
event.preventDefault();
|
|
92
|
+
fitting = false;
|
|
93
|
+
x += offset[0]; y += offset[1]; paint();
|
|
94
|
+
});
|
|
95
|
+
document.body.append(dialog);
|
|
96
|
+
const previousOverflow = document.body.style.overflow;
|
|
97
|
+
document.body.style.overflow = "hidden";
|
|
98
|
+
dialog.showModal();
|
|
99
|
+
fit();
|
|
100
|
+
observer.observe(viewport);
|
|
101
|
+
dialog.addEventListener("click", async (event) => {
|
|
102
|
+
const action = event.target.closest("button")?.dataset.action;
|
|
103
|
+
if (action === "close" || event.target === dialog) dialog.close();
|
|
104
|
+
if (["in", "out", "reset"].includes(action)) {
|
|
105
|
+
fitting = false;
|
|
106
|
+
apply(action === "reset" ? 1 : zoom * (action === "in" ? 1.25 : 0.8));
|
|
107
|
+
}
|
|
108
|
+
if (action === "fit") { fitting = true; fit(); }
|
|
109
|
+
if (action === "fullscreen") {
|
|
110
|
+
try {
|
|
111
|
+
if (ownsFullscreen && document.fullscreenElement) await document.exitFullscreen();
|
|
112
|
+
else {
|
|
113
|
+
await document.documentElement.requestFullscreen();
|
|
114
|
+
ownsFullscreen = true;
|
|
115
|
+
fullscreenChanged();
|
|
116
|
+
}
|
|
117
|
+
} catch { dialog.querySelector(".diagram-viewer-status").textContent = "이 브라우저에서는 전체화면 전환을 사용할 수 없습니다."; }
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
const fullscreenChanged = () => {
|
|
121
|
+
if (!document.fullscreenElement) ownsFullscreen = false;
|
|
122
|
+
dialog.classList.toggle("is-fullscreen", ownsFullscreen);
|
|
123
|
+
dialog.querySelector('[data-action="fullscreen"]').textContent = ownsFullscreen ? "전체화면 종료" : "전체화면";
|
|
124
|
+
};
|
|
125
|
+
document.addEventListener("fullscreenchange", fullscreenChanged);
|
|
126
|
+
const navigate = () => dialog.close();
|
|
127
|
+
window.addEventListener("hashchange", navigate);
|
|
128
|
+
dialog.addEventListener("close", () => {
|
|
129
|
+
if (ownsFullscreen && document.fullscreenElement) document.exitFullscreen().catch(() => {});
|
|
130
|
+
observer.disconnect();
|
|
131
|
+
window.removeEventListener("hashchange", navigate);
|
|
132
|
+
document.removeEventListener("fullscreenchange", fullscreenChanged);
|
|
133
|
+
document.body.style.overflow = previousOverflow;
|
|
134
|
+
dialog.remove();
|
|
135
|
+
if (trigger?.isConnected) trigger.focus();
|
|
136
|
+
}, { once: true });
|
|
137
|
+
}
|
package/client/diagrams.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { openDiagram } from "./diagram-viewer.js";
|
|
1
2
|
import mermaid from "mermaid";
|
|
2
3
|
|
|
3
4
|
mermaid.initialize({
|
|
@@ -10,11 +11,36 @@ mermaid.initialize({
|
|
|
10
11
|
|
|
11
12
|
let diagramId = 0;
|
|
12
13
|
|
|
13
|
-
export async function renderDiagrams(blocks) {
|
|
14
|
+
export async function renderDiagrams(blocks, { buttonOnly = false } = {}) {
|
|
14
15
|
await document.fonts.ready;
|
|
15
16
|
for (const code of blocks) {
|
|
16
17
|
if (!code.isConnected) continue;
|
|
17
18
|
const source = code.textContent;
|
|
19
|
+
if (buttonOnly) {
|
|
20
|
+
const details = code.closest("details");
|
|
21
|
+
const title = details?.querySelector("summary")?.textContent.trim() || "다이어그램 보기";
|
|
22
|
+
const button = document.createElement("button");
|
|
23
|
+
button.type = "button";
|
|
24
|
+
button.textContent = `⛶ ${title}`;
|
|
25
|
+
button.style.cssText = "padding:10px 14px;margin:12px 0;cursor:pointer;border:1px solid #cbd5e1;border-radius:8px;background:white;color:#172033";
|
|
26
|
+
let cached;
|
|
27
|
+
button.addEventListener("click", async () => {
|
|
28
|
+
button.disabled = true;
|
|
29
|
+
try {
|
|
30
|
+
if (!cached) {
|
|
31
|
+
const { svg } = await mermaid.render(`diagram-${++diagramId}`, source);
|
|
32
|
+
const template = document.createElement("template");
|
|
33
|
+
template.innerHTML = svg;
|
|
34
|
+
cached = template.content.querySelector("svg");
|
|
35
|
+
}
|
|
36
|
+
openDiagram(cached, button);
|
|
37
|
+
} catch { button.textContent = "다이어그램 문법을 확인해주세요."; }
|
|
38
|
+
finally { button.disabled = false; }
|
|
39
|
+
});
|
|
40
|
+
if (details) details.replaceWith(button);
|
|
41
|
+
else code.parentElement.replaceWith(button);
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
18
44
|
const pre = code.parentElement;
|
|
19
45
|
const figure = document.createElement("figure");
|
|
20
46
|
figure.className = "diagram";
|
|
@@ -23,6 +49,14 @@ export async function renderDiagrams(blocks) {
|
|
|
23
49
|
const { svg } = await mermaid.render(`diagram-${++diagramId}`, source);
|
|
24
50
|
if (!pre.isConnected) continue;
|
|
25
51
|
figure.innerHTML = svg;
|
|
52
|
+
const button = document.createElement("button");
|
|
53
|
+
button.type = "button";
|
|
54
|
+
button.className = "diagram-expand";
|
|
55
|
+
button.innerHTML = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path d="M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5M3 3l6 6m12-6-6 6M3 21l6-6m12 6-6-6"/></svg>';
|
|
56
|
+
button.setAttribute("aria-label", "다이어그램 크게 보기");
|
|
57
|
+
button.title = "다이어그램 크게 보기";
|
|
58
|
+
button.addEventListener("click", () => openDiagram(figure.querySelector(":scope > svg"), button));
|
|
59
|
+
figure.prepend(button);
|
|
26
60
|
pre.replaceWith(figure);
|
|
27
61
|
} catch {
|
|
28
62
|
if (!pre.isConnected) continue;
|
package/client/style.css
CHANGED
|
@@ -1152,8 +1152,8 @@ dialog::backdrop {
|
|
|
1152
1152
|
}
|
|
1153
1153
|
|
|
1154
1154
|
.comment-anchor { position: relative; }
|
|
1155
|
-
.comment-trigger { position: absolute; left: calc(100% + 20px); top:
|
|
1156
|
-
.comment-trigger:not(:has(.comment-avatar)) { width: 32px; height: 32px;
|
|
1155
|
+
.comment-trigger { position: absolute; left: calc(100% + 20px); top: var(--comment-center, 0px); transform: translateY(-50%); z-index: 2; display: flex; align-items: center; gap: 6px; height: 28px; padding: 0 8px 0 3px; border: 0; border-radius: 14px; background: transparent; color: #374151; font-size: 13px; font-weight: 600; cursor: pointer; opacity: 0; white-space: nowrap; }
|
|
1156
|
+
.comment-trigger:not(:has(.comment-avatar)) { width: 32px; height: 32px; padding: 0; justify-content: center; color: #9ca3af; }
|
|
1157
1157
|
.comment-anchor:hover > .comment-trigger, .comment-trigger:focus-visible, .comment-trigger:has(.comment-avatar) { opacity: 1; }
|
|
1158
1158
|
.comment-trigger:hover:has(.comment-avatar), .comment-trigger:focus-visible:has(.comment-avatar) { background: #f3f4f6; }
|
|
1159
1159
|
.comment-trigger.is-open:has(.comment-avatar) { background: #fef3c7; }
|
|
@@ -1296,3 +1296,20 @@ body.has-comments .comment-panel { left: auto; right: var(--comment-panel-right)
|
|
|
1296
1296
|
.document-download { display: grid; flex: none; place-items: center; width: 36px; height: 36px; border-radius: 6px; color: #6b7280; }
|
|
1297
1297
|
.document-download:hover { background: #f3f4f6; color: #191919; }
|
|
1298
1298
|
.document-title > .comment-anchor { flex: 1; min-width: 0; }
|
|
1299
|
+
|
|
1300
|
+
.diagram-expand { display:block; margin:0 0 8px auto; padding:6px 12px; cursor:pointer; }
|
|
1301
|
+
.diagram-dialog { position:fixed; inset:16px; margin:0; box-sizing:border-box; width:calc(100vw - 32px); max-width:none; height:calc(100dvh - 32px); max-height:none; padding:0; border:1px solid #cbd5e1; border-radius:12px; background:white; color:#172033; overflow:hidden; }
|
|
1302
|
+
.diagram-dialog[open] { display:flex; flex-direction:column; }
|
|
1303
|
+
.diagram-dialog::backdrop { background:#0f172aaa; }
|
|
1304
|
+
.diagram-dialog.is-fullscreen { inset:0; width:100vw; height:100dvh; border:0; border-radius:0; }
|
|
1305
|
+
.diagram-toolbar { flex-shrink:0; display:flex; align-items:center; gap:8px; flex-wrap:wrap; padding:12px; border-bottom:1px solid #e2e8f0; }
|
|
1306
|
+
.diagram-toolbar strong { margin-right:auto; }
|
|
1307
|
+
.diagram-toolbar button { padding:6px 10px; cursor:pointer; }
|
|
1308
|
+
.diagram-toolbar output { min-width:4ch; text-align:center; }
|
|
1309
|
+
.diagram-viewport { position:relative; flex:1; min-height:0; overflow:hidden; touch-action:none; user-select:none; cursor:grab; background:#f8fafc; }
|
|
1310
|
+
.diagram-viewport.is-dragging { cursor:grabbing; }
|
|
1311
|
+
.diagram-canvas { position:absolute; left:0; top:0; width:max-content; transform-origin:0 0; }
|
|
1312
|
+
.diagram-viewer-status { margin:0; padding:0 12px; }
|
|
1313
|
+
body.api-page .layout { grid-template-columns:minmax(0,1fr); }
|
|
1314
|
+
body.api-page :is(.sidebar,.toc,#pagination,#breadcrumb,.compact-toc) { display:none; }
|
|
1315
|
+
body.api-page main { padding:0; }
|
package/package.json
CHANGED
package/src/api.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import MarkdownIt from "markdown-it";
|
|
5
|
+
import sanitizeHtml from "sanitize-html";
|
|
6
|
+
import { operations, resolve } from "../client/api-reference/model.js";
|
|
7
|
+
|
|
8
|
+
const markdown = new MarkdownIt({ html: true, linkify: true });
|
|
9
|
+
|
|
10
|
+
function searchText(spec, value, seen = new Set()) {
|
|
11
|
+
if (value === null || value === undefined) return "";
|
|
12
|
+
if (typeof value !== "object") return String(value);
|
|
13
|
+
if (value.$ref && seen.has(value.$ref)) return "";
|
|
14
|
+
const next = new Set(seen);
|
|
15
|
+
if (value.$ref) next.add(value.$ref);
|
|
16
|
+
const resolved = resolve(spec, value);
|
|
17
|
+
return Object.entries(resolved).filter(([key]) => !["example", "examples", "default", "x-doc-description"].includes(key)).map(([key, child]) => `${key} ${searchText(spec, child, next)}`).join(" ");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function includeApiSearch(files, spec, documentId) {
|
|
21
|
+
const site = JSON.parse(files.get("/site.json").toString());
|
|
22
|
+
const doc = site.documents.find((item) => item.id === documentId);
|
|
23
|
+
if (!doc) return;
|
|
24
|
+
doc.sections.push(...operations(spec).map((op) => ({
|
|
25
|
+
anchor: op.key,
|
|
26
|
+
title: `${op.group} · ${op.summary || op.key}`,
|
|
27
|
+
text: `${op.key} ${op.operationId || ""} ${op.tags?.join(" ") || ""} ${sanitizeHtml(markdown.render(op.description || ""), { allowedTags: [], allowedAttributes: {} })} ${searchText(spec, { parameters: [...(op.item.parameters || []), ...(op.parameters || [])], requestBody: op.requestBody, responses: op.responses })}`,
|
|
28
|
+
})));
|
|
29
|
+
files.set("/site.json", Buffer.from(JSON.stringify(site)));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function presentDescriptions(value) {
|
|
33
|
+
if (!value || typeof value !== "object") return;
|
|
34
|
+
for (const child of Object.values(value)) presentDescriptions(child);
|
|
35
|
+
if (typeof value.description === "string") {
|
|
36
|
+
value["x-doc-description"] = sanitizeHtml(markdown.render(value.description), {
|
|
37
|
+
allowedTags: [...sanitizeHtml.defaults.allowedTags, "details", "summary"],
|
|
38
|
+
allowedAttributes: { a: ["href", "title"], code: ["class"], div: ["class"] },
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function extendSiteFiles(files, config) {
|
|
44
|
+
if (!config.api) return;
|
|
45
|
+
const client = fileURLToPath(new URL("../client/api-reference/", import.meta.url));
|
|
46
|
+
const site = JSON.parse(files.get("/site.json").toString());
|
|
47
|
+
const doc = site.documents.find((item) => item.id === config.api.document);
|
|
48
|
+
if (!doc) throw new Error(`API 문서를 찾을 수 없습니다: ${config.api.document}`);
|
|
49
|
+
doc.apiReference = true;
|
|
50
|
+
files.set("/site.json", Buffer.from(JSON.stringify(site)));
|
|
51
|
+
for (const name of ["index.html", "viewer.js", "standalone.js", "model.js", "viewer.css", "page.js", "page.css"]) {
|
|
52
|
+
files.set(`/api-reference/${name}`, await readFile(path.join(client, name)));
|
|
53
|
+
}
|
|
54
|
+
files.set("/index.html", Buffer.from(files.get("/index.html").toString().replace("</head>", '<link rel="stylesheet" href="./api-reference/page.css" /></head>')));
|
|
55
|
+
const metadata = await readFile(config.api.metadata).catch((error) => {
|
|
56
|
+
if (error.code !== "ENOENT") throw error;
|
|
57
|
+
return Buffer.from(JSON.stringify({ available: true, status: "ready" }));
|
|
58
|
+
});
|
|
59
|
+
if (JSON.parse(metadata).available !== false) {
|
|
60
|
+
const spec = await readFile(config.api.spec).catch((error) => {
|
|
61
|
+
if (error.code !== "ENOENT") throw error;
|
|
62
|
+
return null;
|
|
63
|
+
});
|
|
64
|
+
if (!spec) {
|
|
65
|
+
files.set("/api-reference/spec-metadata.json", Buffer.from(JSON.stringify({ available: false, status: "not-generated" })));
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const parsed = JSON.parse(spec);
|
|
69
|
+
if (!/^3\./.test(parsed.openapi) || !parsed.paths || !parsed.info) {
|
|
70
|
+
throw new Error("api/openapi.json에 유효한 OpenAPI 3 명세가 필요합니다.");
|
|
71
|
+
}
|
|
72
|
+
files.set("/api-reference/openapi.json", spec);
|
|
73
|
+
includeApiSearch(files, parsed, config.api.document);
|
|
74
|
+
presentDescriptions(parsed);
|
|
75
|
+
files.set("/api-reference/documentation.json", Buffer.from(JSON.stringify(parsed)));
|
|
76
|
+
}
|
|
77
|
+
files.set("/api-reference/spec-metadata.json", metadata);
|
|
78
|
+
}
|
package/src/build.js
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
} from "node:fs/promises";
|
|
11
11
|
import path from "node:path";
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { extendSiteFiles } from "./api.js";
|
|
13
14
|
import { collectSite } from "./content.js";
|
|
14
15
|
import { inside } from "./config.js";
|
|
15
16
|
import { build as bundle } from "esbuild";
|
|
@@ -59,6 +60,8 @@ export async function siteFiles(config, dev = false) {
|
|
|
59
60
|
const name = path.relative(path.join(client, "generated"), output.path).split(path.sep).join("/");
|
|
60
61
|
files.set(`/${name}`, Buffer.from(output.contents));
|
|
61
62
|
}
|
|
63
|
+
for (const name of ["page.js", "viewer.js", "model.js", "viewer.css"])
|
|
64
|
+
files.set(`/api-reference/${name}`, await readFile(path.join(client, "api-reference", name)));
|
|
62
65
|
let html = files.get("/index.html").toString();
|
|
63
66
|
html = html.replace(
|
|
64
67
|
'<span class="brand-icon">D</span',
|
|
@@ -88,6 +91,7 @@ export async function siteFiles(config, dev = false) {
|
|
|
88
91
|
files.set("/index.html", Buffer.from(html));
|
|
89
92
|
files.set("/site.json", Buffer.from(JSON.stringify(data)));
|
|
90
93
|
for (const [name, buffer] of assets) files.set(`/assets/${name}`, buffer);
|
|
94
|
+
await extendSiteFiles(files, config);
|
|
91
95
|
return files;
|
|
92
96
|
}
|
|
93
97
|
|
package/src/config.js
CHANGED
|
@@ -102,10 +102,28 @@ export async function loadConfig(cwd, configPath) {
|
|
|
102
102
|
slugs.add(tab.slug);
|
|
103
103
|
tabs.push({ title: tab.title, slug: tab.slug, dir });
|
|
104
104
|
}
|
|
105
|
+
let api;
|
|
106
|
+
if (config.api !== undefined) {
|
|
107
|
+
const value = config.api;
|
|
108
|
+
if (!value || typeof value !== "object" || typeof value.document !== "string" || !value.document.trim())
|
|
109
|
+
throw new Error("api.document에 API 화면으로 사용할 문서 ID를 지정하세요.");
|
|
110
|
+
api = { document: value.document };
|
|
111
|
+
for (const [key, fallback] of [["spec", "api/openapi.json"], ["metadata", "api/spec-metadata.json"]]) {
|
|
112
|
+
const input = value[key] ?? fallback;
|
|
113
|
+
if (typeof input !== "string" || !input.trim()) throw new Error(`api.${key}에 파일 경로를 지정하세요.`);
|
|
114
|
+
const target = path.resolve(root, input);
|
|
115
|
+
const parent = await realpath(path.dirname(target));
|
|
116
|
+
const actual = await realpath(target).catch((error) => { if (error.code !== "ENOENT") throw error; return target; });
|
|
117
|
+
if (!inside(root, parent) || !inside(root, actual)) throw new Error(`api.${key}는 설정 파일 하위 경로여야 합니다.`);
|
|
118
|
+
api[key] = target;
|
|
119
|
+
}
|
|
120
|
+
if (api.spec === api.metadata) throw new Error("API 명세와 메타데이터 경로는 달라야 합니다.");
|
|
121
|
+
}
|
|
105
122
|
const deploymentState = await readDeploymentState(root, file);
|
|
106
123
|
if (deploymentState && config.deploy !== undefined)
|
|
107
124
|
throw new Error("docs.config의 deploy와 .doxen-deploy.json이 함께 있습니다. 사용할 배포 설정 하나만 유지하세요.");
|
|
108
125
|
return {
|
|
126
|
+
api,
|
|
109
127
|
deploymentState,
|
|
110
128
|
deploy: config.deploy ?? deploymentFromState(deploymentState),
|
|
111
129
|
title: config.title,
|
package/src/index.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ export interface DocsConfig {
|
|
|
3
3
|
description?: string;
|
|
4
4
|
color?: string;
|
|
5
5
|
icon?: string | { background?: string; color?: string; border?: string };
|
|
6
|
+
api?: { document: string; spec?: string; metadata?: string };
|
|
6
7
|
deploy?: {
|
|
7
8
|
project: string;
|
|
8
9
|
comments?: { databaseName: string; databaseId: string };
|
package/src/openapi.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { readFile, writeFile, rename, rm } from "node:fs/promises";
|
|
2
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3
|
+
|
|
4
|
+
export async function syncOpenApi(config, values = {}) {
|
|
5
|
+
if (!config.api) throw new Error("docs.config에 api 설정을 추가하세요.");
|
|
6
|
+
const sourceUrl = (values.url || process.env.OPENAPI_URL || "").trim();
|
|
7
|
+
let raw;
|
|
8
|
+
if (values.file) {
|
|
9
|
+
raw = await readFile(values.file, "utf8");
|
|
10
|
+
} else {
|
|
11
|
+
if (!sourceUrl) throw new Error("OPENAPI_URL 환경 변수를 설정하거나 --url 옵션으로 명세 주소를 지정하세요.");
|
|
12
|
+
const url = new URL(sourceUrl);
|
|
13
|
+
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password) {
|
|
14
|
+
throw new Error("인증 정보가 포함되지 않은 HTTP(S) 명세 주소를 지정하세요.");
|
|
15
|
+
}
|
|
16
|
+
const headers = { Accept: "application/json" };
|
|
17
|
+
const user = process.env.OPENAPI_BASIC_USER;
|
|
18
|
+
const password = process.env.OPENAPI_BASIC_PASSWORD;
|
|
19
|
+
if (user || password) {
|
|
20
|
+
if (!user || !password) throw new Error("문서 인증 계정과 비밀번호를 모두 설정하세요.");
|
|
21
|
+
headers.Authorization = `Basic ${Buffer.from(`${user}:${password}`).toString("base64")}`;
|
|
22
|
+
}
|
|
23
|
+
const maxAttempts = 3;
|
|
24
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
25
|
+
let response;
|
|
26
|
+
let failure;
|
|
27
|
+
try {
|
|
28
|
+
response = await fetch(url, { headers, redirect: "error", signal: AbortSignal.timeout(30000) });
|
|
29
|
+
if (response.ok) {
|
|
30
|
+
raw = await response.text();
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
} catch {
|
|
34
|
+
failure = "네트워크 오류 또는 응답 시간 초과";
|
|
35
|
+
}
|
|
36
|
+
if (!failure) {
|
|
37
|
+
failure = `HTTP ${response.status}`;
|
|
38
|
+
await response.body?.cancel();
|
|
39
|
+
if (![408, 429].includes(response.status) && response.status < 500) {
|
|
40
|
+
throw new Error(`OpenAPI 다운로드 실패: ${failure}. 명세 주소와 인증 설정을 확인하세요.`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (attempt === maxAttempts) {
|
|
44
|
+
throw new Error(`OpenAPI 다운로드 실패: ${failure}. ${maxAttempts}회 시도 후 중단합니다. 기존 명세를 유지합니다.`);
|
|
45
|
+
}
|
|
46
|
+
const waitMs = attempt * 5000;
|
|
47
|
+
console.warn(`OpenAPI 다운로드 실패: ${failure}. ${waitMs / 1000}초 후 재시도합니다 (${attempt + 1}/${maxAttempts}).`);
|
|
48
|
+
await delay(waitMs);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const spec = JSON.parse(raw);
|
|
52
|
+
if (!/^3\./.test(spec.openapi) || !spec.info || !spec.paths || !Object.keys(spec.paths).length) {
|
|
53
|
+
throw new Error("HTTP 경로가 포함된 OpenAPI 3 JSON 파일이 필요합니다. 기존 명세를 유지합니다.");
|
|
54
|
+
}
|
|
55
|
+
const metadata = {
|
|
56
|
+
available: true,
|
|
57
|
+
status: "ready",
|
|
58
|
+
source: values.file ? "file" : "server",
|
|
59
|
+
sourceUrl: values.file ? null : new URL(sourceUrl).origin + new URL(sourceUrl).pathname,
|
|
60
|
+
importedAt: new Date().toISOString(),
|
|
61
|
+
revision: process.env.OPENAPI_REVISION || null,
|
|
62
|
+
note: values.file ? "파일에서 가져온 명세. 생성 환경과 코드 버전은 제공자가 확인한다." : "개발 서버에서 가져온 명세. 로컬 브랜치와 배포 버전은 다를 수 있다.",
|
|
63
|
+
};
|
|
64
|
+
const specPath = config.api.spec;
|
|
65
|
+
const metaPath = config.api.metadata;
|
|
66
|
+
const specTmp = specPath + ".tmp";
|
|
67
|
+
const metaTmp = metaPath + ".tmp";
|
|
68
|
+
try {
|
|
69
|
+
await writeFile(specTmp, JSON.stringify(spec, null, 2) + "\n");
|
|
70
|
+
await writeFile(metaTmp, JSON.stringify(metadata, null, 2) + "\n");
|
|
71
|
+
await rename(specTmp, specPath);
|
|
72
|
+
await rename(metaTmp, metaPath);
|
|
73
|
+
} finally {
|
|
74
|
+
await rm(specTmp, { force: true });
|
|
75
|
+
await rm(metaTmp, { force: true });
|
|
76
|
+
}
|
|
77
|
+
console.log(`OpenAPI 갱신: ${Object.keys(spec.paths).length}개 경로`);
|
|
78
|
+
|
|
79
|
+
}
|