@eliceio/cdk-cli 0.0.0-stage → 0.1.0-alpha.2

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.
Files changed (141) hide show
  1. package/README.md +526 -2
  2. package/es/bin/index.d.ts +2 -0
  3. package/es/bin/index.js +10 -0
  4. package/es/cli.d.ts +5 -0
  5. package/es/cli.js +209 -0
  6. package/es/commands/build/index.d.ts +30 -0
  7. package/es/commands/build/index.js +163 -0
  8. package/es/commands/check/index.d.ts +9 -0
  9. package/es/commands/check/index.js +31 -0
  10. package/es/commands/create/index.d.ts +8 -0
  11. package/es/commands/create/index.js +22 -0
  12. package/es/commands/create/scaffold.d.ts +24 -0
  13. package/es/commands/create/scaffold.js +82 -0
  14. package/es/commands/dev/index.d.ts +6 -0
  15. package/es/commands/dev/index.js +40 -0
  16. package/es/commands/doctor/index.d.ts +34 -0
  17. package/es/commands/doctor/index.js +311 -0
  18. package/es/commands/guide/index.d.ts +29 -0
  19. package/es/commands/guide/index.js +120 -0
  20. package/es/commands/skill/index.d.ts +48 -0
  21. package/es/commands/skill/index.js +173 -0
  22. package/es/core/collect.d.ts +21 -0
  23. package/es/core/collect.js +89 -0
  24. package/es/core/config.d.ts +55 -0
  25. package/es/core/config.js +109 -0
  26. package/es/core/manifest.d.ts +15 -0
  27. package/es/core/manifest.js +43 -0
  28. package/es/core/minify.d.ts +18 -0
  29. package/es/core/minify.js +93 -0
  30. package/es/core/prepare.d.ts +12 -0
  31. package/es/core/prepare.js +86 -0
  32. package/es/core/protocol.d.ts +2 -0
  33. package/es/core/protocol.js +4 -0
  34. package/es/core/sandbox.d.ts +17 -0
  35. package/es/core/sandbox.js +182 -0
  36. package/es/core/zip.d.ts +4 -0
  37. package/es/core/zip.js +17 -0
  38. package/es/dev/grading.d.ts +15 -0
  39. package/es/dev/grading.js +37 -0
  40. package/es/dev/host-page.d.ts +7 -0
  41. package/es/dev/host-page.js +240 -0
  42. package/es/dev/inject.d.ts +8 -0
  43. package/es/dev/inject.js +38 -0
  44. package/es/dev/mock-api.d.ts +65 -0
  45. package/es/dev/mock-api.js +269 -0
  46. package/es/dev/server.d.ts +25 -0
  47. package/es/dev/server.js +309 -0
  48. package/es/engines/static/index.d.ts +3 -0
  49. package/es/engines/static/index.js +11 -0
  50. package/es/engines/types.d.ts +12 -0
  51. package/es/engines/vite/index.d.ts +2 -0
  52. package/es/engines/vite/index.js +4 -0
  53. package/es/index.d.ts +2 -0
  54. package/es/index.js +2 -0
  55. package/es/rules/check.d.ts +2 -0
  56. package/es/rules/check.js +282 -0
  57. package/es/rules/index.d.ts +8 -0
  58. package/es/rules/index.js +7 -0
  59. package/es/rules/manifest.d.ts +39 -0
  60. package/es/rules/manifest.js +168 -0
  61. package/es/rules/node.d.ts +11 -0
  62. package/es/rules/node.js +87 -0
  63. package/es/rules/path.d.ts +7 -0
  64. package/es/rules/path.js +35 -0
  65. package/es/rules/refs.d.ts +19 -0
  66. package/es/rules/refs.js +111 -0
  67. package/es/rules/skip.d.ts +12 -0
  68. package/es/rules/skip.js +55 -0
  69. package/es/rules/spec.d.ts +3 -0
  70. package/es/rules/spec.js +6 -0
  71. package/es/rules/types.d.ts +140 -0
  72. package/es/rules/unused.d.ts +7 -0
  73. package/es/rules/unused.js +21 -0
  74. package/es/rules/zip.d.ts +13 -0
  75. package/es/rules/zip.js +45 -0
  76. package/es/rules.json.js +3 -0
  77. package/es/types.d.ts +4 -0
  78. package/es/version.d.ts +2 -0
  79. package/es/version.js +7 -0
  80. package/guides/content-development.md +207 -0
  81. package/package.json +50 -3
  82. package/rules.json +608 -0
  83. package/skills/_shared/always.md +7 -0
  84. package/skills/elice-content-check/SKILL.md +22 -0
  85. package/skills/elice-content-create/SKILL.md +21 -0
  86. package/skills/elice-content-migrate/SKILL.md +21 -0
  87. package/templates/_shared/lib/cdk-mock.d.ts +94 -0
  88. package/templates/_shared/lib/cdk-mock.js +429 -0
  89. package/templates/_shared/lib/cdk.js +3 -0
  90. package/templates/_shared/lib/elice-content.css +262 -0
  91. package/templates/_shared/lib/elice-content.d.ts +123 -0
  92. package/templates/_shared/lib/elice-content.js +534 -0
  93. package/templates/_shared/lib/elice-tokens.css +446 -0
  94. package/templates/blank/README.md +64 -0
  95. package/templates/blank/commentary.txt +2 -0
  96. package/templates/blank/content.json +4 -0
  97. package/templates/blank/edit.html +15 -0
  98. package/templates/blank/elice.config.json +12 -0
  99. package/templates/blank/gitignore +3 -0
  100. package/templates/blank/index.html +15 -0
  101. package/templates/blank/instructor.html +15 -0
  102. package/templates/blank/screens/edit.js +21 -0
  103. package/templates/blank/screens/instructor.js +9 -0
  104. package/templates/blank/screens/learn.js +19 -0
  105. package/templates/blank/styles.css +1 -0
  106. package/templates/quiz/README.md +108 -0
  107. package/templates/quiz/commentary.txt +2 -0
  108. package/templates/quiz/content.json +81 -0
  109. package/templates/quiz/core/behaviors.d.ts +59 -0
  110. package/templates/quiz/core/behaviors.js +310 -0
  111. package/templates/quiz/core/dom.d.ts +13 -0
  112. package/templates/quiz/core/dom.js +83 -0
  113. package/templates/quiz/core/editor.d.ts +48 -0
  114. package/templates/quiz/core/editor.js +206 -0
  115. package/templates/quiz/core/markdown.d.ts +2 -0
  116. package/templates/quiz/core/markdown.js +84 -0
  117. package/templates/quiz/core/model.d.ts +20 -0
  118. package/templates/quiz/core/model.js +203 -0
  119. package/templates/quiz/edit.html +17 -0
  120. package/templates/quiz/elice.config.json +14 -0
  121. package/templates/quiz/gitignore +3 -0
  122. package/templates/quiz/grading.json +13 -0
  123. package/templates/quiz/index.html +17 -0
  124. package/templates/quiz/instructor.html +17 -0
  125. package/templates/quiz/screens/edit.js +139 -0
  126. package/templates/quiz/screens/instructor.js +27 -0
  127. package/templates/quiz/screens/learn.js +55 -0
  128. package/templates/quiz/styles.css +570 -0
  129. package/templates/quiz/ui/templates/choice.js +22 -0
  130. package/templates/quiz/ui/templates/edit.d.ts +13 -0
  131. package/templates/quiz/ui/templates/edit.js +183 -0
  132. package/templates/quiz/ui/templates/group.js +68 -0
  133. package/templates/quiz/ui/templates/index.d.ts +5 -0
  134. package/templates/quiz/ui/templates/index.js +17 -0
  135. package/templates/quiz/ui/templates/order.js +35 -0
  136. package/templates/quiz/ui/templates/page.js +29 -0
  137. package/templates/quiz/ui/templates/question.js +28 -0
  138. package/templates/quiz/ui/templates/text.js +16 -0
  139. package/templates/quiz/ui/texts.d.ts +3 -0
  140. package/templates/quiz/ui/texts.js +127 -0
  141. package/templates/quiz/ui/theme.css +50 -0
@@ -0,0 +1,269 @@
1
+ import { grade } from './grading.js';
2
+
3
+ /**
4
+ * elice-material API 흉내 (서버 설계 v25, @eliceio/cdk 1.x가 부르는 것만).
5
+ * 응답은 elib 형식 `{ data, meta }`, 필드는 snake_case. 오류는 `{ data: null, meta: { error } }`.
6
+ */
7
+ const DEV_MATERIAL_ID = '00000000-0000-4000-8000-0000000000e1';
8
+ const STUDENT = {
9
+ account_id: 1,
10
+ anonymous_id: 'dev-student',
11
+ fullname: '김하늘 (dev)'
12
+ };
13
+ const MANAGER = {
14
+ account_id: 100,
15
+ anonymous_id: 'dev-manager',
16
+ fullname: '교육자 (dev)'
17
+ };
18
+ const TOKEN_SCENARIOS = Object.freeze({
19
+ edit: {
20
+ scope: 'edit',
21
+ viewer: 'instructor'
22
+ },
23
+ instructor: {
24
+ scope: 'learn',
25
+ viewer: 'instructor'
26
+ },
27
+ student: {
28
+ scope: 'learn',
29
+ viewer: 'student'
30
+ },
31
+ tutor: {
32
+ scope: 'learn',
33
+ viewer: 'tutor'
34
+ }
35
+ });
36
+ const isTokenScenario = v => typeof v === 'string' && Object.hasOwn(TOKEN_SCENARIOS, v);
37
+ const TOKEN_TTL_SECONDS = 7200;
38
+ const SESSION_SECONDS = 12 * 3600;
39
+ const b64url = s => Buffer.from(s).toString('base64url');
40
+ const nowSeconds = () => Math.floor(Date.now() / 1000);
41
+ /** SDK는 서명을 검사하지 않고 claim만 읽는다. 흉내 서버도 서명은 보지 않는다 */
42
+ const sign = claims => `${b64url(JSON.stringify({
43
+ alg: 'HS256',
44
+ typ: 'JWT'
45
+ }))}.${b64url(JSON.stringify(claims))}.ZGV2`;
46
+ function issueToken(scenario, ttlSeconds = TOKEN_TTL_SECONDS) {
47
+ const {
48
+ scope,
49
+ viewer
50
+ } = TOKEN_SCENARIOS[scenario];
51
+ const subject = viewer === 'instructor' ? MANAGER : STUDENT;
52
+ const now = nowSeconds();
53
+ return sign({
54
+ material_id: DEV_MATERIAL_ID,
55
+ scope,
56
+ viewer,
57
+ account_id: subject.account_id,
58
+ lecture_page_id: 1,
59
+ course_id: 1,
60
+ locale: 'ko',
61
+ session_started_at: now,
62
+ exp: now + ttlSeconds
63
+ });
64
+ }
65
+ function readClaims(req) {
66
+ const auth = req.headers.authorization ?? '';
67
+ const token = auth.replace(/^Bearer\s+/i, '');
68
+ try {
69
+ const claims = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString());
70
+ return claims.exp * 1000 > Date.now() ? claims : null;
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+ const createState = () => ({
76
+ settings: {},
77
+ submissions: [],
78
+ results: new Map(),
79
+ recent: new Map()
80
+ });
81
+ const MAX_ANSWER_BYTES = 64 * 1024;
82
+ const RATE_PER_MINUTE = 30;
83
+ function send(res, status, data) {
84
+ res.writeHead(status, {
85
+ 'Content-Type': 'application/json; charset=utf-8'
86
+ });
87
+ res.end(JSON.stringify({
88
+ data,
89
+ meta: {}
90
+ }));
91
+ }
92
+ function fail(res, status, code, message, details = []) {
93
+ res.writeHead(status, {
94
+ 'Content-Type': 'application/json; charset=utf-8'
95
+ });
96
+ res.end(JSON.stringify({
97
+ data: null,
98
+ meta: {
99
+ error: {
100
+ code,
101
+ message,
102
+ details
103
+ }
104
+ }
105
+ }));
106
+ }
107
+ async function body(req) {
108
+ const chunks = [];
109
+ for await (const c of req) chunks.push(c);
110
+ const raw = Buffer.concat(chunks).toString();
111
+ try {
112
+ return {
113
+ raw,
114
+ json: raw ? JSON.parse(raw) : null
115
+ };
116
+ } catch {
117
+ return {
118
+ raw,
119
+ json: null
120
+ };
121
+ }
122
+ }
123
+ /** 점수는 가장 최근 채점, 완료 시각은 처음 한 번만 */
124
+ function record(state, accountId, change, completed) {
125
+ const prev = state.results.get(accountId) ?? {
126
+ score: null,
127
+ submit_count: 0,
128
+ completed_at: null
129
+ };
130
+ const now = new Date().toISOString();
131
+ state.results.set(accountId, {
132
+ score: change.score ?? prev.score,
133
+ submit_count: prev.submit_count + (change.submit_count ?? 0),
134
+ completed_at: prev.completed_at ?? (completed ? now : null)
135
+ });
136
+ }
137
+ /** `/api` 아래 요청을 처리한다 */
138
+ async function handleMockApi(req, res, path, opts) {
139
+ const {
140
+ state
141
+ } = opts;
142
+ const method = req.method ?? 'GET';
143
+ const log = m => opts.onEvent?.(m);
144
+ if (method === 'POST' && path === '/auth/token/refresh') {
145
+ const claims = readClaims(req);
146
+ if (!claims) return fail(res, 401, 'AUTHENTICATION_INVALID', 'token expired (dev)');
147
+ if (nowSeconds() - claims.session_started_at > SESSION_SECONDS) return fail(res, 401, 'AUTHENTICATION_INVALID', 'session expired (dev)', [{
148
+ reason: 'session_expired'
149
+ }]);
150
+ const exp = nowSeconds() + TOKEN_TTL_SECONDS;
151
+ return send(res, 200, {
152
+ access_token: sign({
153
+ ...claims,
154
+ exp
155
+ }),
156
+ expires_at: new Date(exp * 1000).toISOString()
157
+ });
158
+ }
159
+ const m = path.match(/^\/materials\/([0-9a-f-]{36})(\/me|\/submissions|\/submissions\/me)?$/);
160
+ if (!m) return fail(res, 404, 'RESOURCE_NOT_FOUND', `no route: ${method} ${path}`);
161
+ const claims = readClaims(req);
162
+ if (!claims) return fail(res, 401, 'AUTHENTICATION_INVALID', 'missing or expired token (dev)');
163
+ if (m[1] !== claims.material_id) return fail(res, 403, 'AUTH_PERMISSION_DENIED', 'material mismatch');
164
+ const sub = m[2] ?? '';
165
+ const subject = claims.account_id;
166
+ const material = settings => ({
167
+ id: DEV_MATERIAL_ID,
168
+ lecture_page_id: 1,
169
+ course_id: 1,
170
+ description: {
171
+ type: 'text',
172
+ text: ''
173
+ },
174
+ current_version: {
175
+ id: 'dev',
176
+ content_urls: {},
177
+ metadata: {
178
+ entries: opts.getEntries()
179
+ },
180
+ file_tree: [],
181
+ settings
182
+ }
183
+ });
184
+ if (method === 'GET' && sub === '') return send(res, 200, material(state.settings));
185
+ // 편집 페이지의 자료 저장. dev에서는 호스트의 "저장" 버튼만 edit 토큰으로 부른다
186
+ if (method === 'PATCH' && sub === '') {
187
+ if (claims.scope !== 'edit') return fail(res, 403, 'AUTH_PERMISSION_DENIED', 'settings only with an edit token');
188
+ const {
189
+ json
190
+ } = await body(req);
191
+ const settings = json?.settings;
192
+ if (!settings || typeof settings !== 'object') return fail(res, 400, 'INVALID_INPUT', 'settings required');
193
+ state.settings = settings;
194
+ log('편집 페이지가 자료를 저장했습니다 (settings)');
195
+ return send(res, 200, material(state.settings));
196
+ }
197
+ if (method === 'GET' && sub === '/me') {
198
+ const user = claims.viewer === 'instructor' ? MANAGER : STUDENT;
199
+ if (claims.scope === 'learn' && claims.viewer === 'student' && opts.getGrading()?.type === 'on_access' && !state.results.has(subject)) {
200
+ record(state, subject, {
201
+ score: 100
202
+ }, true);
203
+ log('열람 완료로 100점 (on_access)');
204
+ }
205
+ return send(res, 200, {
206
+ scope: claims.scope,
207
+ viewer: claims.viewer,
208
+ user: {
209
+ anonymous_id: user.anonymous_id,
210
+ fullname: user.fullname
211
+ },
212
+ result: state.results.get(subject) ?? null
213
+ });
214
+ }
215
+ if (method === 'GET' && sub === '/submissions/me') {
216
+ const url = new URL(req.url ?? '', 'http://x');
217
+ const offset = Number(url.searchParams.get('offset') ?? 0);
218
+ const limit = Number(url.searchParams.get('limit') ?? 20);
219
+ const mine = state.submissions.filter(s => s.account_id === subject);
220
+ return send(res, 200, mine.slice(offset, offset + limit));
221
+ }
222
+ if (method === 'POST' && sub === '/submissions') {
223
+ if (claims.scope !== 'learn') return fail(res, 403, 'AUTH_PERMISSION_DENIED', 'no submissions with an edit token');
224
+ if (claims.viewer === 'tutor') return fail(res, 403, 'MATERIAL_READ_ONLY_MODE', 'tutor is read-only');
225
+ const {
226
+ raw,
227
+ json
228
+ } = await body(req);
229
+ if (Buffer.byteLength(raw) > MAX_ANSWER_BYTES) return fail(res, 400, 'INVALID_INPUT', 'answer over 64KB');
230
+ const now = Date.now();
231
+ const recent = (state.recent.get(subject) ?? []).filter(t => now - t < 60_000);
232
+ if (recent.length >= RATE_PER_MINUTE) return fail(res, 429, 'MATERIAL_TOO_MANY_SUBMISSIONS', 'too many submissions (dev)');
233
+ state.recent.set(subject, [...recent, now]);
234
+ // 채점은 요청 안에서 끝난다 (rubric 포함). 학생만 기록, instructor는 채점만
235
+ const answer = json?.answer ?? null;
236
+ const {
237
+ isCorrect,
238
+ score
239
+ } = grade(opts.getGrading(), answer);
240
+ if (claims.viewer !== 'student') {
241
+ log(`${claims.viewer} 제출: 채점만 (${score ?? '-'}점, 기록 안 함)`);
242
+ return send(res, 200, {
243
+ is_correct: isCorrect,
244
+ score
245
+ });
246
+ }
247
+ state.submissions.unshift({
248
+ id: `dev-${state.submissions.length + 1}`,
249
+ material_version_id: 'dev',
250
+ account_id: subject,
251
+ created_at: new Date().toISOString(),
252
+ answer,
253
+ is_correct: isCorrect,
254
+ score
255
+ });
256
+ record(state, subject, {
257
+ score,
258
+ submit_count: 1
259
+ }, isCorrect === true);
260
+ log(`학생 제출: ${score ?? '-'}점 (${isCorrect === null ? '채점 없음' : isCorrect ? '정답' : '오답'})`);
261
+ return send(res, 200, {
262
+ is_correct: isCorrect,
263
+ score
264
+ });
265
+ }
266
+ return fail(res, 405, 'RESOURCE_NOT_FOUND', `${method} ${path}`);
267
+ }
268
+
269
+ export { DEV_MATERIAL_ID, MANAGER, STUDENT, TOKEN_SCENARIOS, createState, handleMockApi, isTokenScenario, issueToken };
@@ -0,0 +1,25 @@
1
+ import { type CheckResult } from '../rules/index.js';
2
+ /** 운영 콘텐츠 경로(/s/{exp}.{sig}/materials/{id}/{draft}/…)와 같은 모양. SDK가 여기서 자료 id를 읽는다 */
3
+ export declare const CONTENT_PREFIX = "/s/dev/materials/00000000-0000-4000-8000-0000000000e1/dev/";
4
+ export interface DevServerOptions {
5
+ dir: string;
6
+ /** 호스트 포트 (콘텐츠는 +1). 0이면 아무 빈 포트 */
7
+ port?: number;
8
+ log?: (line: string) => void;
9
+ }
10
+ export interface DevServer {
11
+ hostUrl: string;
12
+ contentUrl: string;
13
+ /** 지금 보고 있는 콘텐츠 기준 검사 결과 */
14
+ readonly check: CheckResult;
15
+ reload(): Promise<void>;
16
+ close(): Promise<void>;
17
+ }
18
+ /**
19
+ * 로컬에서 운영과 같은 조건으로 콘텐츠를 띄운다.
20
+ * - 호스트(localhost): LXP 흉내 화면 + elice-material 흉내 API(/api) + 콘솔 수집
21
+ * - 콘텐츠(127.0.0.1, 다른 출처): build와 같은 파일(모듈 묶기 포함)을 운영 헤더(CSP sandbox allow-scripts)로.
22
+ * LXP 자료 파일 서버처럼 CORS 헤더를 주지 않아, 묶지 않은 모듈 스크립트 · fetch가 LXP에서처럼 막힌다
23
+ * - 원본이 바뀌면 다시 준비 · 검사 → 호스트가 iframe을 다시 띄움
24
+ */
25
+ export declare function startDevServer(opts: DevServerOptions): Promise<DevServer>;
@@ -0,0 +1,309 @@
1
+ import { watch } from 'node:fs';
2
+ import { createServer } from 'node:http';
3
+ import { resolve, extname, basename, relative, sep } from 'node:path';
4
+ import { loadConfig, loadGrading, GRADING_DATA_FILE } from '../core/config.js';
5
+ import { prepareContent } from '../core/prepare.js';
6
+ import { inlineModuleScripts } from '../core/sandbox.js';
7
+ import { checkFiles } from '../rules/check.js';
8
+ import '../rules/spec.js';
9
+ import 'fflate';
10
+ import { hostPage } from './host-page.js';
11
+ import { injectDevScript } from './inject.js';
12
+ import { DEV_MATERIAL_ID, handleMockApi, isTokenScenario, issueToken, createState } from './mock-api.js';
13
+
14
+ const MIME = {
15
+ html: 'text/html; charset=utf-8',
16
+ htm: 'text/html; charset=utf-8',
17
+ js: 'text/javascript; charset=utf-8',
18
+ mjs: 'text/javascript; charset=utf-8',
19
+ css: 'text/css; charset=utf-8',
20
+ json: 'application/json; charset=utf-8',
21
+ svg: 'image/svg+xml',
22
+ png: 'image/png',
23
+ jpg: 'image/jpeg',
24
+ jpeg: 'image/jpeg',
25
+ gif: 'image/gif',
26
+ webp: 'image/webp',
27
+ avif: 'image/avif',
28
+ ico: 'image/x-icon',
29
+ woff: 'font/woff',
30
+ woff2: 'font/woff2',
31
+ ttf: 'font/ttf',
32
+ otf: 'font/otf',
33
+ mp3: 'audio/mpeg',
34
+ mp4: 'video/mp4',
35
+ webm: 'video/webm',
36
+ wasm: 'application/wasm',
37
+ txt: 'text/plain; charset=utf-8',
38
+ md: 'text/plain; charset=utf-8',
39
+ csv: 'text/csv; charset=utf-8',
40
+ pdf: 'application/pdf'
41
+ };
42
+ /** 운영 콘텐츠 경로(/s/{exp}.{sig}/materials/{id}/{draft}/…)와 같은 모양. SDK가 여기서 자료 id를 읽는다 */
43
+ const CONTENT_PREFIX = `/s/dev/materials/${DEV_MATERIAL_ID}/dev/`;
44
+ function summarize(check) {
45
+ const errors = check.issues.filter(i => i.level === 'error');
46
+ const warns = check.issues.length - errors.length;
47
+ const head = `${check.ok ? '[ok]' : '[fail]'} 검사 오류 ${errors.length} · 경고 ${warns} (규칙 ${check.rulesVersion})`;
48
+ const lines = check.issues.slice(0, 5).map(i => ` [${i.level}] ${i.id}${i.path ? ` ${i.path}${i.line ? `:${i.line}` : ''}` : ''} ${i.message}`);
49
+ if (check.issues.length > 5) lines.push(` … 외 ${check.issues.length - 5}개 (ecdk check로 전체 보기)`);
50
+ return [head, ...lines].join('\n');
51
+ }
52
+ const listen = (server, port) => new Promise((ok, fail) => {
53
+ server.once('error', fail);
54
+ server.listen(port, '127.0.0.1', () => ok(server.address().port));
55
+ });
56
+ /** build와 같이 모듈을 묶은 파일. 묶지 못하면 원본을 그대로 주고 이유를 알린다 (LXP에서는 막힐 것) */
57
+ async function servedFiles(prepared, log) {
58
+ try {
59
+ const {
60
+ files
61
+ } = await inlineModuleScripts(prepared.files);
62
+ return new Map(files.map(f => [f.path, f.data]));
63
+ } catch (e) {
64
+ log(`[dev] ${e.message}`);
65
+ return new Map(prepared.files.map(f => [f.path, f.data]));
66
+ }
67
+ }
68
+ /**
69
+ * 로컬에서 운영과 같은 조건으로 콘텐츠를 띄운다.
70
+ * - 호스트(localhost): LXP 흉내 화면 + elice-material 흉내 API(/api) + 콘솔 수집
71
+ * - 콘텐츠(127.0.0.1, 다른 출처): build와 같은 파일(모듈 묶기 포함)을 운영 헤더(CSP sandbox allow-scripts)로.
72
+ * LXP 자료 파일 서버처럼 CORS 헤더를 주지 않아, 묶지 않은 모듈 스크립트 · fetch가 LXP에서처럼 막힌다
73
+ * - 원본이 바뀌면 다시 준비 · 검사 → 호스트가 iframe을 다시 띄움
74
+ */
75
+ async function startDevServer(opts) {
76
+ const dir = resolve(opts.dir);
77
+ const log = opts.log ?? (l => process.stdout.write(`${l}\n`));
78
+ let config = await loadConfig(dir);
79
+ let grading = await loadGrading(dir, config);
80
+ let prepared = await prepareContent(dir, config);
81
+ let files = await servedFiles(prepared, log);
82
+ let check = checkFiles(prepared.files, {
83
+ input: 'zip',
84
+ bundlesModules: true
85
+ });
86
+ const state = createState();
87
+ const clients = new Set();
88
+ let hostOrigin = '';
89
+ let contentOrigin = '';
90
+ const entries = () => check.manifest?.entries ?? {
91
+ learn: 'index.html'
92
+ };
93
+ const snapshot = () => ({
94
+ kind: check.manifest?.kind ?? 'material',
95
+ entries: entries(),
96
+ contentBase: contentOrigin + CONTENT_PREFIX,
97
+ check: {
98
+ ok: check.ok,
99
+ summary: summarize(check)
100
+ }
101
+ });
102
+ // 콘텐츠 서버
103
+ const content = createServer((req, res) => {
104
+ const url = new URL(req.url ?? '/', 'http://x');
105
+ const headers = {
106
+ 'Content-Security-Policy': `sandbox allow-scripts; frame-ancestors ${hostOrigin}`,
107
+ 'X-Content-Type-Options': 'nosniff',
108
+ 'Referrer-Policy': 'no-referrer',
109
+ 'Cache-Control': 'no-store'
110
+ };
111
+ // 콘텐츠 주소를 직접 열면 브라우저가 찾는 아이콘. zip과 상관없어 빈 응답
112
+ if (url.pathname === '/favicon.ico') {
113
+ res.writeHead(204, headers).end();
114
+ return;
115
+ }
116
+ if (!url.pathname.startsWith(CONTENT_PREFIX)) {
117
+ res.writeHead(404, headers).end('not found');
118
+ return;
119
+ }
120
+ let path = decodeURIComponent(url.pathname.slice(CONTENT_PREFIX.length));
121
+ if (path === '' || path.endsWith('/')) path += 'index.html';
122
+ const data = files.get(path);
123
+ if (!data) {
124
+ log(`[404] ${path} (zip에 없는 파일)`);
125
+ res.writeHead(404, headers).end('not found');
126
+ return;
127
+ }
128
+ const ext = extname(path).slice(1).toLowerCase();
129
+ const type = MIME[ext] ?? 'application/octet-stream';
130
+ const out = ext === 'html' || ext === 'htm' ? injectDevScript(new TextDecoder().decode(data), hostOrigin) : data;
131
+ res.writeHead(200, {
132
+ ...headers,
133
+ 'Content-Type': type
134
+ });
135
+ res.end(out);
136
+ });
137
+ // 호스트 서버
138
+ const cors = {
139
+ 'Access-Control-Allow-Origin': '*',
140
+ 'Access-Control-Allow-Headers': 'Authorization, Content-Type',
141
+ 'Access-Control-Allow-Methods': 'GET, POST, PATCH, OPTIONS'
142
+ };
143
+ const host = createServer(async (req, res) => {
144
+ const url = new URL(req.url ?? '/', 'http://x');
145
+ try {
146
+ if (req.method === 'OPTIONS') {
147
+ res.writeHead(204, cors).end();
148
+ return;
149
+ }
150
+ if (url.pathname.startsWith('/api/')) {
151
+ for (const [k, v] of Object.entries(cors)) res.setHeader(k, v);
152
+ await handleMockApi(req, res, url.pathname.slice(4), {
153
+ state,
154
+ getGrading: () => grading,
155
+ getEntries: entries,
156
+ onEvent: m => log(`[api] ${m}`)
157
+ });
158
+ return;
159
+ }
160
+ // 콘텐츠 주소를 직접 열어 mock으로 돌 때: elice.config.json · grading.json은 zip에 없어 콘텐츠 서버가 주지 않으므로
161
+ // 흉내 서버가 채점에 쓰는 것과 같은 로컬 채점 설정을 여기서 준다 (dev 전용)
162
+ // CORS *로 둔다: ecdk dev는 작성자 PC에서만 돌고 내주는 값도 작성자 본인의 grading.json이라, 막아도 지킬 대상이 없다
163
+ // (실행마다 열쇠를 두는 방식은 콘텐츠 주소가 예측 가능해 열쇠까지 읽혀 효과가 없어서 되돌림, !19 리뷰)
164
+ if (url.pathname === '/__ecdk/grading') {
165
+ res.writeHead(200, {
166
+ ...cors,
167
+ 'Content-Type': 'application/json; charset=utf-8'
168
+ });
169
+ res.end(JSON.stringify(grading ?? null));
170
+ return;
171
+ }
172
+ if (url.pathname === '/favicon.ico') {
173
+ res.writeHead(204).end();
174
+ return;
175
+ }
176
+ if (url.pathname === '/__ecdk/log' && req.method === 'POST') {
177
+ let raw = '';
178
+ for await (const c of req) raw += c;
179
+ const {
180
+ level,
181
+ message,
182
+ page
183
+ } = JSON.parse(raw || '{}');
184
+ log(`[content ${level ?? 'log'}] ${page ?? ''} ${message ?? ''}`.trim());
185
+ res.writeHead(204, cors).end();
186
+ return;
187
+ }
188
+ if (url.pathname === '/__ecdk/token') {
189
+ const scenario = url.searchParams.get('scenario') ?? 'student';
190
+ if (!isTokenScenario(scenario)) {
191
+ res.writeHead(400).end(`no token for scenario: ${scenario}`);
192
+ return;
193
+ }
194
+ res.writeHead(200, {
195
+ 'Content-Type': 'application/json'
196
+ }).end(JSON.stringify({
197
+ token: issueToken(scenario)
198
+ }));
199
+ return;
200
+ }
201
+ if (url.pathname === '/__ecdk/state') {
202
+ res.writeHead(200, {
203
+ 'Content-Type': 'application/json'
204
+ }).end(JSON.stringify(snapshot()));
205
+ return;
206
+ }
207
+ if (url.pathname === '/__ecdk/reset' && req.method === 'POST') {
208
+ Object.assign(state, createState());
209
+ log('[api] 저장 내용과 제출 기록을 지웠습니다');
210
+ res.writeHead(204).end();
211
+ return;
212
+ }
213
+ if (url.pathname === '/__ecdk/events') {
214
+ res.writeHead(200, {
215
+ 'Content-Type': 'text/event-stream',
216
+ 'Cache-Control': 'no-store',
217
+ Connection: 'keep-alive'
218
+ });
219
+ res.write(': connected\n\n');
220
+ clients.add(res);
221
+ req.on('close', () => clients.delete(res));
222
+ return;
223
+ }
224
+ if (url.pathname === '/') {
225
+ res.writeHead(200, {
226
+ 'Content-Type': 'text/html; charset=utf-8',
227
+ 'Cache-Control': 'no-store'
228
+ });
229
+ res.end(hostPage({
230
+ title: basename(dir)
231
+ }));
232
+ return;
233
+ }
234
+ res.writeHead(404).end('not found');
235
+ } catch (e) {
236
+ log(`[dev] 요청 처리 오류: ${e.message}`);
237
+ if (!res.headersSent) res.writeHead(500).end('dev server error');
238
+ }
239
+ });
240
+ const base = opts.port ?? 4170;
241
+ const hostPort = await listen(host, base);
242
+ let contentPort;
243
+ try {
244
+ contentPort = await listen(content, base === 0 ? 0 : hostPort + 1);
245
+ } catch (e) {
246
+ // 콘텐츠 포트가 막히면 열어 둔 호스트도 닫아야 프로세스가 끝난다
247
+ await new Promise(r => host.close(r));
248
+ throw e;
249
+ }
250
+ hostOrigin = `http://localhost:${hostPort}`;
251
+ contentOrigin = `http://127.0.0.1:${contentPort}`;
252
+ async function reload() {
253
+ try {
254
+ config = await loadConfig(dir);
255
+ grading = await loadGrading(dir, config);
256
+ prepared = await prepareContent(dir, config);
257
+ files = await servedFiles(prepared, log);
258
+ check = checkFiles(prepared.files, {
259
+ input: 'zip',
260
+ bundlesModules: true
261
+ });
262
+ log(summarize(check));
263
+ const payload = JSON.stringify(snapshot());
264
+ for (const c of clients) c.write(`event: reload\ndata: ${payload}\n\n`);
265
+ } catch (e) {
266
+ log(`[dev] 다시 읽지 못했습니다: ${e.message}`);
267
+ }
268
+ }
269
+ // 원본 감시: 산출물 폴더 · node_modules · .git 제외, 짧게 모아서 한 번만
270
+ let timer = null;
271
+ const outRel = relative(prepared.srcDir, prepared.outDir).split(sep)[0];
272
+ let watcher = null;
273
+ try {
274
+ watcher = watch(prepared.srcDir, {
275
+ recursive: true
276
+ }, (_e, name) => {
277
+ const first = String(name ?? '').split(/[\\/]/)[0];
278
+ if (!first || first === outRel || first === 'node_modules' || first.startsWith('.')) return;
279
+ if (timer) clearTimeout(timer);
280
+ timer = setTimeout(() => void reload(), 150);
281
+ });
282
+ } catch {
283
+ log('[dev] 이 환경에서는 파일 감시를 못 합니다. 고친 뒤 새로고침하세요.');
284
+ }
285
+ // 프로젝트 루트의 설정 파일(원본 폴더 밖일 수 있음)
286
+ const configWatcher = prepared.srcDir === dir ? null : watch(dir, (_e, name) => {
287
+ if (name === 'elice.config.json' || name === GRADING_DATA_FILE) void reload();
288
+ });
289
+ log(summarize(check));
290
+ return {
291
+ hostUrl: `${hostOrigin}/`,
292
+ contentUrl: contentOrigin + CONTENT_PREFIX,
293
+ get check() {
294
+ return check;
295
+ },
296
+ reload,
297
+ async close() {
298
+ watcher?.close();
299
+ configWatcher?.close();
300
+ for (const c of clients) c.end();
301
+ const closing = Promise.all([new Promise(r => host.close(r)), new Promise(r => content.close(r))]);
302
+ host.closeAllConnections();
303
+ content.closeAllConnections();
304
+ await closing;
305
+ }
306
+ };
307
+ }
308
+
309
+ export { CONTENT_PREFIX, startDevServer };
@@ -0,0 +1,3 @@
1
+ import type { ContentEngine } from '../types.js';
2
+ /** 번들 없이 원본을 그대로 쓴다. 기본 엔진, 의존성 없음. */
3
+ export declare const staticEngine: ContentEngine;
@@ -0,0 +1,11 @@
1
+ /** 번들 없이 원본을 그대로 쓴다. 기본 엔진, 의존성 없음. */
2
+ const staticEngine = {
3
+ name: 'static',
4
+ async build({
5
+ files
6
+ }) {
7
+ return files;
8
+ }
9
+ };
10
+
11
+ export { staticEngine };
@@ -0,0 +1,12 @@
1
+ import type { SourceFile } from '../core/collect.js';
2
+ export interface EngineBuildContext {
3
+ /** 콘텐츠 원본 폴더 (절대경로) */
4
+ srcDir: string;
5
+ /** core가 정답·비밀·프로젝트 파일을 뺀 뒤의 원본 */
6
+ files: SourceFile[];
7
+ }
8
+ /** 2단계에서 dev()를 더한다 (CLI 구조 문서의 ContentEngine). */
9
+ export interface ContentEngine {
10
+ name: string;
11
+ build(ctx: EngineBuildContext): Promise<SourceFile[]>;
12
+ }
@@ -0,0 +1,2 @@
1
+ /** 3단계(3-2)에서 구현. 엔진 인터페이스는 @eliceio/cdk-cli의 ContentEngine을 따른다. */
2
+ export declare const name = "vite";
@@ -0,0 +1,4 @@
1
+ /** 3단계(3-2)에서 구현. 엔진 인터페이스는 @eliceio/cdk-cli의 ContentEngine을 따른다. */
2
+ const name = 'vite';
3
+
4
+ export { name };
package/es/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { main, VERSION } from './cli.js';
2
+ export type { CommandResult } from './types.js';
package/es/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { main } from './cli.js';
2
+ export { VERSION } from './version.js';
@@ -0,0 +1,2 @@
1
+ import type { CheckOptions, CheckResult, ContentFile } from './types.js';
2
+ export declare function checkFiles(input: ContentFile[], opts?: CheckOptions): CheckResult;