trace-codebook 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,209 @@
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
+ for (let i = 0; i < argv.length; i++) {
35
+ const a = argv[i];
36
+ const value = () => (a.includes('=') ? a.slice(a.indexOf('=') + 1) : argv[++i]);
37
+ if (a === '-h' || a === '--help') opts.help = true;
38
+ else if (a === '-v' || a === '--version') opts.version = true;
39
+ else if (a === '--no-open') opts.open = false;
40
+ else if (a === '--port' || a.startsWith('--port=')) opts.port = value();
41
+ else if (a === '--lang' || a.startsWith('--lang=')) opts.lang = value();
42
+ else if (a.startsWith('-')) return { opts, error: ['badOption', { option: a }] };
43
+ else files.push(a);
44
+ }
45
+ // 언어부터 정해야 오류 메시지도 그 언어로 낼 수 있다
46
+ if (opts.lang != null) {
47
+ const l = String(opts.lang).toLowerCase();
48
+ if (l !== 'en' && l !== 'ko') {
49
+ opts.lang = langFromEnv(env);
50
+ return { opts, error: ['badLang', { lang: l }] };
51
+ }
52
+ opts.lang = l;
53
+ } else opts.lang = langFromEnv(env);
54
+ if (files.length > 1) return { opts, error: ['tooMany', {}] };
55
+ opts.file = files[0] ?? null;
56
+ const port = Number(opts.port);
57
+ if (!Number.isInteger(port) || port < 0 || port > 65535) return { opts, error: ['badPort', { port: opts.port }] };
58
+ opts.port = port;
59
+ return { opts };
60
+ }
61
+
62
+ /**
63
+ * 정적 서버를 만든다. root 밖의 경로는 404, /__trace/<이름> 은 주어진 파일 하나만.
64
+ * 반환한 server 는 호출한 쪽이 close() 한다.
65
+ */
66
+ export function makeServer({ root, file }) {
67
+ const rootDir = resolve(root);
68
+ const traceName = file ? basename(file) : null;
69
+ const csp = "default-src 'self'; connect-src 'self'; img-src 'self' data:; style-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'";
70
+
71
+ return createServer((req, res) => {
72
+ const notFound = () => {
73
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
74
+ res.end('not found');
75
+ };
76
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
77
+ res.writeHead(405, { allow: 'GET, HEAD' });
78
+ return res.end();
79
+ }
80
+ let path;
81
+ try {
82
+ // 원문 경로(정규화 전)를 그대로 디코딩해 쓴다. /../package.json·%2e%2e 같은 요청은
83
+ // 아래에서 resolve 한 결과가 root 밖이라 404 가 된다.
84
+ path = decodeURIComponent((req.url ?? '/').split('?')[0].split('#')[0]);
85
+ } catch {
86
+ return notFound();
87
+ }
88
+ if (path.includes('\0')) return notFound();
89
+ const headers = { 'x-content-type-options': 'nosniff', 'cache-control': 'no-store', 'content-security-policy': csp };
90
+
91
+ // 1) 사용자가 준 트레이스 파일(읽기 전용)
92
+ if (traceName && path === `/__trace/${traceName}`) {
93
+ const type = TYPES[extname(traceName).toLowerCase()] ?? 'application/octet-stream';
94
+ res.writeHead(200, { ...headers, 'content-type': type, 'content-length': statSync(file).size });
95
+ if (req.method === 'HEAD') return res.end();
96
+ return createReadStream(file).pipe(res);
97
+ }
98
+
99
+ // 2) dist/ 안의 정적 파일
100
+ const rel = path === '/' ? 'index.html' : path.replace(/^\/+/, '');
101
+ const full = resolve(rootDir, rel);
102
+ if (full !== rootDir && !full.startsWith(rootDir + sep)) return notFound();
103
+ let st;
104
+ try {
105
+ st = statSync(full);
106
+ } catch {
107
+ return notFound();
108
+ }
109
+ if (!st.isFile()) return notFound();
110
+ res.writeHead(200, { ...headers, 'content-type': TYPES[extname(full).toLowerCase()] ?? 'application/octet-stream', 'content-length': st.size });
111
+ if (req.method === 'HEAD') return res.end();
112
+ createReadStream(full).pipe(res);
113
+ });
114
+ }
115
+
116
+ /** 운영체제 기본 브라우저로 주소를 연다. 실패해도 주소는 이미 출력했으니 안내만 한다. */
117
+ function openBrowser(url, lang) {
118
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
119
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
120
+ try {
121
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
122
+ child.on('error', () => console.error(msg(lang, 'openFailed', { url })));
123
+ child.unref(); // CLI 가 브라우저 프로세스를 기다리지 않게
124
+ } catch {
125
+ console.error(msg(lang, 'openFailed', { url }));
126
+ }
127
+ }
128
+
129
+ export function main(argv = process.argv.slice(2), env = process.env) {
130
+ const { opts, error } = parseArgs(argv, env);
131
+ const lang = opts.lang;
132
+ if (error) {
133
+ console.error(msg(lang, error[0], error[1]));
134
+ return 2;
135
+ }
136
+ if (opts.help) {
137
+ console.log(helpText(lang));
138
+ return 0;
139
+ }
140
+ if (opts.version) {
141
+ console.log(PKG.version);
142
+ return 0;
143
+ }
144
+
145
+ const root = join(HERE, '..', 'dist');
146
+ if (!existsSync(join(root, 'index.html'))) {
147
+ console.error(msg(lang, 'noDist', { dir: root }));
148
+ return 1;
149
+ }
150
+ let file = null;
151
+ if (opts.file) {
152
+ file = resolve(opts.file);
153
+ if (!existsSync(file)) {
154
+ console.error(msg(lang, 'noFile', { file: opts.file }));
155
+ return 1;
156
+ }
157
+ if (!statSync(file).isFile()) {
158
+ console.error(msg(lang, 'notFile', { file: opts.file }));
159
+ return 1;
160
+ }
161
+ }
162
+
163
+ const server = makeServer({ root, file });
164
+ server.on('error', (e) => {
165
+ console.error(e && e.code === 'EADDRINUSE' ? msg(lang, 'portInUse', { port: opts.port }) : String(e));
166
+ process.exit(1);
167
+ });
168
+ server.listen(opts.port, HOST, () => {
169
+ const { port } = server.address();
170
+ let url = `http://${HOST}:${port}/`;
171
+ const q = new URLSearchParams();
172
+ if (file) q.set('trace', `__trace/${encodeURIComponent(basename(file))}`);
173
+ if (env.TRACE_CODEBOOK_LANG || argv.some((a) => a.startsWith('--lang'))) q.set('lang', lang);
174
+ if ([...q].length) url += `?${q.toString()}`;
175
+ console.log(msg(lang, 'running', { url }));
176
+ if (file) console.log(msg(lang, 'serving', { file }));
177
+ console.log(msg(lang, 'stop'));
178
+ if (opts.open) openBrowser(url, lang);
179
+ });
180
+
181
+ // Ctrl+C·종료 신호: 서버를 닫고 끝낸다(열린 연결도 끊는다)
182
+ const stop = () => {
183
+ console.log(msg(lang, 'stopped'));
184
+ server.close(() => process.exit(0));
185
+ server.closeAllConnections?.();
186
+ setTimeout(() => process.exit(0), 1000).unref();
187
+ };
188
+ process.once('SIGINT', stop);
189
+ process.once('SIGTERM', stop);
190
+ return null; // 서버가 계속 돈다
191
+ }
192
+
193
+ // 직접 실행했을 때만 main (테스트에서 import 해도 서버가 뜨지 않게)
194
+ const invoked = process.argv[1] && resolve(process.argv[1]);
195
+ const self = fileURLToPath(import.meta.url);
196
+ let isMain = invoked === self;
197
+ if (!isMain && invoked) {
198
+ // npm 이 만든 bin 링크(심볼릭 링크)로 실행된 경우
199
+ try {
200
+ const { realpathSync } = await import('node:fs');
201
+ isMain = realpathSync(invoked) === realpathSync(self);
202
+ } catch {
203
+ isMain = false;
204
+ }
205
+ }
206
+ if (isMain) {
207
+ const code = main();
208
+ if (code != null) process.exitCode = code;
209
+ }