trace-codebook 0.0.0-stage → 0.1.5
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/LICENSE +21 -0
- package/README.ko.md +214 -0
- package/README.md +213 -2
- package/bin/messages.mjs +96 -0
- package/bin/trace-codebook.mjs +234 -0
- package/dist/assets/index-BQpDGt-F.js +20 -0
- package/dist/assets/index-CPfzDIhf.css +1 -0
- package/dist/favicon.svg +1 -0
- package/dist/index.html +15 -0
- package/dist/samples/anthropic.jsonl +2 -0
- package/dist/samples/langfuse-trace.json +46 -0
- package/dist/samples/otlp.json +92 -0
- package/dist/samples/phoenix.jsonl +2 -0
- package/dist/samples/support-agent.annotations.jsonl +40 -0
- package/dist/samples/support-agent.jsonl +40 -0
- package/dist/samples/support-agent.taxonomy.csv +6 -0
- package/package.json +65 -4
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// trace-codebook CLI — 의존성 없는 작은 정적 서버.
|
|
3
|
+
// 빌드된 앱(dist/)을 127.0.0.1 에서만 제공하고, 파일을 주면 같은 출처 경로 /__trace/<이름> 로 제공해
|
|
4
|
+
// 앱이 주소의 ?trace= 를 보고 자동으로 연다. 파일은 읽기만 한다.
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs';
|
|
7
|
+
import { createServer } from 'node:http';
|
|
8
|
+
import { basename, extname, join, resolve, sep } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { helpText, langFromEnv, msg } from './messages.mjs';
|
|
11
|
+
|
|
12
|
+
const HERE = fileURLToPath(new URL('.', import.meta.url));
|
|
13
|
+
const PKG = JSON.parse(readFileSync(join(HERE, '..', 'package.json'), 'utf8'));
|
|
14
|
+
const DEFAULT_PORT = 4178;
|
|
15
|
+
const HOST = '127.0.0.1'; // 같은 컴퓨터에서만 접속 가능
|
|
16
|
+
|
|
17
|
+
const TYPES = {
|
|
18
|
+
'.html': 'text/html; charset=utf-8',
|
|
19
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
20
|
+
'.css': 'text/css; charset=utf-8',
|
|
21
|
+
'.svg': 'image/svg+xml',
|
|
22
|
+
'.png': 'image/png',
|
|
23
|
+
'.json': 'application/json; charset=utf-8',
|
|
24
|
+
'.jsonl': 'application/x-ndjson; charset=utf-8',
|
|
25
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
26
|
+
'.ico': 'image/x-icon',
|
|
27
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** 인자 해석. 잘못되면 { error } */
|
|
31
|
+
export function parseArgs(argv, env = process.env) {
|
|
32
|
+
const opts = { file: null, port: DEFAULT_PORT, open: true, help: false, version: false, lang: null };
|
|
33
|
+
const files = [];
|
|
34
|
+
let badOption = null;
|
|
35
|
+
for (let i = 0; i < argv.length; i++) {
|
|
36
|
+
const a = argv[i];
|
|
37
|
+
const value = () => (a.includes('=') ? a.slice(a.indexOf('=') + 1) : argv[++i]);
|
|
38
|
+
if (a === '-h' || a === '--help') opts.help = true;
|
|
39
|
+
else if (a === '-v' || a === '--version') opts.version = true;
|
|
40
|
+
else if (a === '--no-open') opts.open = false;
|
|
41
|
+
else if (a === '--port' || a.startsWith('--port=')) opts.port = value();
|
|
42
|
+
else if (a === '--lang' || a.startsWith('--lang=')) opts.lang = value();
|
|
43
|
+
else if (a.startsWith('-')) badOption ??= a; // 첫 번째만 기억하고 끝까지 훑는다
|
|
44
|
+
else files.push(a);
|
|
45
|
+
}
|
|
46
|
+
// 언어부터 정해야 오류 메시지도 그 언어로 낼 수 있다
|
|
47
|
+
if (opts.lang != null) {
|
|
48
|
+
const l = String(opts.lang).toLowerCase();
|
|
49
|
+
if (l !== 'en' && l !== 'ko') {
|
|
50
|
+
opts.lang = langFromEnv(env);
|
|
51
|
+
if (badOption) return { opts, error: ['badOption', { option: badOption }] };
|
|
52
|
+
return { opts, error: ['badLang', { lang: l }] };
|
|
53
|
+
}
|
|
54
|
+
opts.lang = l;
|
|
55
|
+
} else opts.lang = langFromEnv(env);
|
|
56
|
+
if (badOption) return { opts, error: ['badOption', { option: badOption }] };
|
|
57
|
+
if (files.length > 1) return { opts, error: ['tooMany', {}] };
|
|
58
|
+
opts.file = files[0] ?? null;
|
|
59
|
+
const port = Number(opts.port);
|
|
60
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) return { opts, error: ['badPort', { port: opts.port }] };
|
|
61
|
+
opts.port = port;
|
|
62
|
+
return { opts };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 정적 서버를 만든다. root 밖의 경로는 404, /__trace/<이름> 은 주어진 파일 하나만.
|
|
67
|
+
* 반환한 server 는 호출한 쪽이 close() 한다.
|
|
68
|
+
*/
|
|
69
|
+
export function makeServer({ root, file }) {
|
|
70
|
+
const rootDir = resolve(root);
|
|
71
|
+
const traceName = file ? basename(file) : null;
|
|
72
|
+
const csp = "default-src 'self'; connect-src 'self'; img-src 'self' data:; style-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'";
|
|
73
|
+
|
|
74
|
+
return createServer((req, res) => {
|
|
75
|
+
const notFound = () => {
|
|
76
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
|
|
77
|
+
res.end('not found');
|
|
78
|
+
};
|
|
79
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
80
|
+
res.writeHead(405, { allow: 'GET, HEAD' });
|
|
81
|
+
return res.end();
|
|
82
|
+
}
|
|
83
|
+
let path;
|
|
84
|
+
try {
|
|
85
|
+
// 원문 경로(정규화 전)를 그대로 디코딩해 쓴다. /../package.json·%2e%2e 같은 요청은
|
|
86
|
+
// 아래에서 resolve 한 결과가 root 밖이라 404 가 된다.
|
|
87
|
+
path = decodeURIComponent((req.url ?? '/').split('?')[0].split('#')[0]);
|
|
88
|
+
} catch {
|
|
89
|
+
return notFound();
|
|
90
|
+
}
|
|
91
|
+
if (path.includes('\0')) return notFound();
|
|
92
|
+
const headers = { 'x-content-type-options': 'nosniff', 'cache-control': 'no-store', 'content-security-policy': csp };
|
|
93
|
+
|
|
94
|
+
// 1) 사용자가 준 트레이스 파일(읽기 전용)
|
|
95
|
+
if (traceName && path === `/__trace/${traceName}`) {
|
|
96
|
+
const type = TYPES[extname(traceName).toLowerCase()] ?? 'application/octet-stream';
|
|
97
|
+
// 파일이 사라졌거나 일반 파일이 아니면 이 요청만 404 — 서버는 계속 돈다
|
|
98
|
+
let traceStat;
|
|
99
|
+
try {
|
|
100
|
+
traceStat = statSync(file);
|
|
101
|
+
} catch {
|
|
102
|
+
return notFound();
|
|
103
|
+
}
|
|
104
|
+
if (!traceStat.isFile()) return notFound();
|
|
105
|
+
const okHeaders = { ...headers, 'content-type': type, 'content-length': traceStat.size };
|
|
106
|
+
if (req.method === 'HEAD') {
|
|
107
|
+
res.writeHead(200, okHeaders);
|
|
108
|
+
return res.end();
|
|
109
|
+
}
|
|
110
|
+
const stream = createReadStream(file);
|
|
111
|
+
// stat 뒤 읽기 직전에 지워지는 경우 등: 헤더 전이면 404, 이미 보냈으면 연결만 끊는다
|
|
112
|
+
stream.on('error', () => {
|
|
113
|
+
if (!res.headersSent) notFound();
|
|
114
|
+
else res.destroy();
|
|
115
|
+
});
|
|
116
|
+
// 파일이 실제로 열린 뒤에만 200 헤더를 쓴다
|
|
117
|
+
stream.on('open', () => {
|
|
118
|
+
res.writeHead(200, okHeaders);
|
|
119
|
+
stream.pipe(res);
|
|
120
|
+
});
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// 2) dist/ 안의 정적 파일
|
|
125
|
+
const rel = path === '/' ? 'index.html' : path.replace(/^\/+/, '');
|
|
126
|
+
const full = resolve(rootDir, rel);
|
|
127
|
+
if (full !== rootDir && !full.startsWith(rootDir + sep)) return notFound();
|
|
128
|
+
let st;
|
|
129
|
+
try {
|
|
130
|
+
st = statSync(full);
|
|
131
|
+
} catch {
|
|
132
|
+
return notFound();
|
|
133
|
+
}
|
|
134
|
+
if (!st.isFile()) return notFound();
|
|
135
|
+
res.writeHead(200, { ...headers, 'content-type': TYPES[extname(full).toLowerCase()] ?? 'application/octet-stream', 'content-length': st.size });
|
|
136
|
+
if (req.method === 'HEAD') return res.end();
|
|
137
|
+
createReadStream(full).pipe(res);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 운영체제 기본 브라우저로 주소를 연다. 실패해도 주소는 이미 출력했으니 안내만 한다. */
|
|
142
|
+
function openBrowser(url, lang) {
|
|
143
|
+
const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
|
|
144
|
+
const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
|
|
145
|
+
try {
|
|
146
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
147
|
+
child.on('error', () => console.error(msg(lang, 'openFailed', { url })));
|
|
148
|
+
child.unref(); // CLI 가 브라우저 프로세스를 기다리지 않게
|
|
149
|
+
} catch {
|
|
150
|
+
console.error(msg(lang, 'openFailed', { url }));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function main(argv = process.argv.slice(2), env = process.env) {
|
|
155
|
+
const { opts, error } = parseArgs(argv, env);
|
|
156
|
+
const lang = opts.lang;
|
|
157
|
+
if (error) {
|
|
158
|
+
console.error(msg(lang, error[0], error[1]));
|
|
159
|
+
return 2;
|
|
160
|
+
}
|
|
161
|
+
if (opts.help) {
|
|
162
|
+
console.log(helpText(lang));
|
|
163
|
+
return 0;
|
|
164
|
+
}
|
|
165
|
+
if (opts.version) {
|
|
166
|
+
console.log(PKG.version);
|
|
167
|
+
return 0;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const root = join(HERE, '..', 'dist');
|
|
171
|
+
if (!existsSync(join(root, 'index.html'))) {
|
|
172
|
+
console.error(msg(lang, 'noDist', { dir: root }));
|
|
173
|
+
return 1;
|
|
174
|
+
}
|
|
175
|
+
let file = null;
|
|
176
|
+
if (opts.file) {
|
|
177
|
+
file = resolve(opts.file);
|
|
178
|
+
if (!existsSync(file)) {
|
|
179
|
+
console.error(msg(lang, 'noFile', { file: opts.file }));
|
|
180
|
+
return 1;
|
|
181
|
+
}
|
|
182
|
+
if (!statSync(file).isFile()) {
|
|
183
|
+
console.error(msg(lang, 'notFile', { file: opts.file }));
|
|
184
|
+
return 1;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const server = makeServer({ root, file });
|
|
189
|
+
server.on('error', (e) => {
|
|
190
|
+
console.error(e && e.code === 'EADDRINUSE' ? msg(lang, 'portInUse', { port: opts.port }) : String(e));
|
|
191
|
+
process.exit(1);
|
|
192
|
+
});
|
|
193
|
+
server.listen(opts.port, HOST, () => {
|
|
194
|
+
const { port } = server.address();
|
|
195
|
+
let url = `http://${HOST}:${port}/`;
|
|
196
|
+
const q = new URLSearchParams();
|
|
197
|
+
if (file) q.set('trace', `__trace/${encodeURIComponent(basename(file))}`);
|
|
198
|
+
if (env.TRACE_CODEBOOK_LANG || argv.some((a) => a.startsWith('--lang'))) q.set('lang', lang);
|
|
199
|
+
if ([...q].length) url += `?${q.toString()}`;
|
|
200
|
+
console.log(msg(lang, 'running', { url }));
|
|
201
|
+
if (file) console.log(msg(lang, 'serving', { file }));
|
|
202
|
+
console.log(msg(lang, 'stop'));
|
|
203
|
+
if (opts.open) openBrowser(url, lang);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
// Ctrl+C·종료 신호: 서버를 닫고 끝낸다(열린 연결도 끊는다)
|
|
207
|
+
const stop = () => {
|
|
208
|
+
console.log(msg(lang, 'stopped'));
|
|
209
|
+
server.close(() => process.exit(0));
|
|
210
|
+
server.closeAllConnections?.();
|
|
211
|
+
setTimeout(() => process.exit(0), 1000).unref();
|
|
212
|
+
};
|
|
213
|
+
process.once('SIGINT', stop);
|
|
214
|
+
process.once('SIGTERM', stop);
|
|
215
|
+
return null; // 서버가 계속 돈다
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// 직접 실행했을 때만 main (테스트에서 import 해도 서버가 뜨지 않게)
|
|
219
|
+
const invoked = process.argv[1] && resolve(process.argv[1]);
|
|
220
|
+
const self = fileURLToPath(import.meta.url);
|
|
221
|
+
let isMain = invoked === self;
|
|
222
|
+
if (!isMain && invoked) {
|
|
223
|
+
// npm 이 만든 bin 링크(심볼릭 링크)로 실행된 경우
|
|
224
|
+
try {
|
|
225
|
+
const { realpathSync } = await import('node:fs');
|
|
226
|
+
isMain = realpathSync(invoked) === realpathSync(self);
|
|
227
|
+
} catch {
|
|
228
|
+
isMain = false;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
if (isMain) {
|
|
232
|
+
const code = main();
|
|
233
|
+
if (code != null) process.exitCode = code;
|
|
234
|
+
}
|