@eliceio/cdk-cli 1.2.0 → 1.3.0-contenttypes.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +69 -60
  2. package/es/cli.js +11 -2
  3. package/es/commands/build/index.js +12 -0
  4. package/es/commands/create/index.js +2 -1
  5. package/es/commands/create/scaffold.d.ts +2 -2
  6. package/es/commands/create/scaffold.js +3 -3
  7. package/es/commands/dev/index.d.ts +10 -1
  8. package/es/commands/dev/index.js +47 -7
  9. package/es/core/config.d.ts +20 -9
  10. package/es/core/config.js +53 -12
  11. package/es/core/project-check.d.ts +3 -2
  12. package/es/core/project-check.js +14 -3
  13. package/es/core/regex.d.ts +11 -0
  14. package/es/core/regex.js +41 -0
  15. package/es/core/sandbox.d.ts +26 -0
  16. package/es/core/sandbox.js +240 -30
  17. package/es/dev/check.d.ts +30 -0
  18. package/es/dev/check.js +224 -34
  19. package/es/dev/grading.d.ts +20 -1
  20. package/es/dev/grading.js +38 -7
  21. package/es/dev/host-page.js +1 -1
  22. package/es/dev/mock-api.d.ts +3 -1
  23. package/es/dev/mock-api.js +20 -11
  24. package/es/engines/vite/index.js +1 -1
  25. package/es/engines/vite/plugin.d.ts +2 -0
  26. package/es/engines/vite/plugin.js +33 -5
  27. package/es/rules/answers.d.ts +13 -0
  28. package/es/rules/answers.js +94 -0
  29. package/es/rules/check.js +70 -1
  30. package/es/rules/index.d.ts +1 -0
  31. package/es/rules/index.js +1 -0
  32. package/es/rules/size.d.ts +31 -0
  33. package/es/rules/size.js +58 -0
  34. package/es/rules/types.d.ts +12 -0
  35. package/es/rules.json.js +2 -2
  36. package/package.json +2 -2
  37. package/rules.json +32 -3
  38. package/skills/_shared/always.md +3 -3
  39. package/skills/_shared/references/00-what-the-person-decides.md +1 -1
  40. package/skills/_shared/references/02-design-the-material.md +10 -7
  41. package/skills/_shared/references/03-create-the-project.md +2 -1
  42. package/skills/_shared/references/05-screen-code.md +49 -22
  43. package/skills/_shared/references/06-using-the-quiz-template.md +7 -6
  44. package/skills/_shared/references/08-fix-check-errors.md +23 -22
  45. package/skills/_shared/references/09-check.md +7 -6
  46. package/skills/_shared/references/12-upload-with-the-material-mcp.md +13 -13
  47. package/skills/_shared/references/13-edit-screen-design.md +122 -0
  48. package/skills/_shared/references/14-layouts.md +96 -0
  49. package/skills/elice-content-check/SKILL.md +2 -2
  50. package/skills/elice-content-create/SKILL.md +1 -1
  51. package/skills/elice-content-migrate/SKILL.md +1 -1
  52. package/templates/_shared/lib/cdk-mock.d.ts +30 -3
  53. package/templates/_shared/lib/cdk-mock.js +88 -15
  54. package/templates/_shared/lib/elice-content-editor.js +89 -58
  55. package/templates/_shared/lib/elice-content.css +1313 -126
  56. package/templates/_shared/lib/elice-content.d.ts +162 -23
  57. package/templates/_shared/lib/elice-content.js +865 -84
  58. package/templates/_shared/lib/icons/empty-content.d.ts +2 -0
  59. package/templates/_shared/lib/icons/empty-content.js +11 -0
  60. package/templates/_shared/lib/icons/file-video.d.ts +2 -0
  61. package/templates/_shared/lib/icons/file-video.js +11 -0
  62. package/templates/_shared/lib/icons/file.d.ts +2 -0
  63. package/templates/_shared/lib/icons/file.js +11 -0
  64. package/templates/blank/README.md +5 -3
  65. package/templates/blank/edit.html +8 -2
  66. package/templates/blank/index.html +6 -1
  67. package/templates/blank/instructor.html +6 -1
  68. package/templates/blank/template.json +1 -1
  69. package/templates/quiz/README.md +28 -12
  70. package/templates/quiz/core/behaviors.d.ts +13 -7
  71. package/templates/quiz/core/behaviors.js +36 -51
  72. package/templates/quiz/core/editor.d.ts +10 -0
  73. package/templates/quiz/core/editor.js +471 -8
  74. package/templates/quiz/core/markdown.d.ts +4 -0
  75. package/templates/quiz/core/markdown.js +65 -11
  76. package/templates/quiz/core/model.d.ts +34 -1
  77. package/templates/quiz/core/model.js +89 -7
  78. package/templates/quiz/core/rich-text.d.ts +19 -0
  79. package/templates/quiz/core/rich-text.js +521 -0
  80. package/templates/quiz/edit.html +12 -3
  81. package/templates/quiz/index.html +12 -3
  82. package/templates/quiz/screens/edit.js +848 -168
  83. package/templates/quiz/screens/learn.js +90 -14
  84. package/templates/quiz/styles.css +889 -213
  85. package/templates/quiz/template.json +9 -2
  86. package/templates/quiz/ui/templates/edit.d.ts +19 -6
  87. package/templates/quiz/ui/templates/edit.js +666 -87
  88. package/templates/quiz/ui/templates/group.js +19 -8
  89. package/templates/quiz/ui/templates/order.js +25 -24
  90. package/templates/quiz/ui/templates/page.js +19 -8
  91. package/templates/quiz/ui/templates/question.js +2 -2
  92. package/templates/quiz/ui/texts.js +104 -35
  93. package/templates/quiz/ui/theme.css +8 -9
  94. package/templates/steps/README.md +77 -0
  95. package/templates/steps/commentary.txt +7 -0
  96. package/templates/steps/edit.html +21 -0
  97. package/templates/steps/gitignore +4 -0
  98. package/templates/steps/index.html +69 -0
  99. package/templates/steps/metadata.json +9 -0
  100. package/templates/steps/package.json +13 -0
  101. package/templates/steps/screens/edit.js +32 -0
  102. package/templates/steps/screens/learn.js +108 -0
  103. package/templates/steps/styles.css +54 -0
  104. package/templates/steps/template.json +6 -0
package/es/dev/check.js CHANGED
@@ -17,6 +17,8 @@ const CHECK_VIEWPORTS = {
17
17
  desktop: '100%',
18
18
  mobile: '360px'
19
19
  };
20
+ /** --theme: 콘텐츠 문서에 EDS 테마(data-eds-theme)를 붙여 찍는다. 없으면 프로젝트 그대로 */
21
+ const CHECK_THEMES = ['light', 'dark'];
20
22
  const WINDOW = {
21
23
  width: 1280,
22
24
  height: 860
@@ -77,6 +79,16 @@ function findingsOf(r) {
77
79
  level: 'warn',
78
80
  message: '가로로 넘침 (가로 스크롤 생김)'
79
81
  });
82
+ if (r.missingStep) out.push({
83
+ level: 'warn',
84
+ message: r.missingStep
85
+ });
86
+ const byId = new Map();
87
+ for (const l of r.layout ?? []) byId.set(l.id, [...(byId.get(l.id) ?? []), l]);
88
+ for (const [id, list] of byId) out.push({
89
+ level: list.some(l => l.level === 'fail') ? 'fail' : 'warn',
90
+ message: list.length > 1 ? `${id} ${list.length}개` : id
91
+ });
80
92
  return out;
81
93
  }
82
94
  function statusOf(r) {
@@ -97,7 +109,7 @@ function formatText(report) {
97
109
  for (const r of report.screens) {
98
110
  const findings = findingsOf(r).map(f => f.message);
99
111
  const shot = r.screenshot ? `화면 그림 ${r.screenshot}` : '화면 그림 없음';
100
- lines.push(`[${statusOf(r)}] ${r.screen} · ${r.viewport} ${r.width}px ${[...findings, shot].join(' · ')}`);
112
+ lines.push(`[${statusOf(r)}] ${[r.screen, r.viewport, r.theme, r.step === undefined ? undefined : `단계 ${r.step}`].filter(Boolean).join(' · ')} ${r.width}px ${[...findings, shot].join(' · ')}`);
101
113
  const detail = (label, items) => {
102
114
  for (const item of items.slice(0, DETAIL_LIMIT)) lines.push(` ${label}: ${item.split('\n')[0]}`);
103
115
  if (items.length > DETAIL_LIMIT) lines.push(` … ${label} 외 ${items.length - DETAIL_LIMIT}개`);
@@ -106,6 +118,7 @@ function formatText(report) {
106
118
  detail('콘솔 오류', r.consoleErrors);
107
119
  detail('막힌 외부 요청', r.blocked);
108
120
  detail('실패한 요청', r.failedRequests);
121
+ detail('배치', (r.layout ?? []).map(l => `${l.id} ${l.message}`));
109
122
  }
110
123
  const bad = report.screens.filter(r => statusOf(r) !== 'ok').length;
111
124
  lines.push('', `${report.ok ? '[ok]' : '[fail]'} 화면 ${report.screens.length}개 중 문제 ${bad}개${v.errors ? ` · 검사 오류 ${v.errors}` : ''} (${(report.durationMs / 1000).toFixed(1)}초)`, `화면 그림: ${report.screenshotsDir}`);
@@ -139,6 +152,115 @@ function probe() {
139
152
  width: window.innerWidth
140
153
  };
141
154
  }
155
+ /**
156
+ * 키트 스테퍼 · 레이아웃 배치 (브라우저 안에서 돈다). 첫 화면(스크롤 0) 그대로 본다.
157
+ * 스테퍼 버튼은 <ec-stepper-nav> Shadow DOM 안(옛 키트는 문서의 .ec-step-nav)이라 그 루트의 elementFromPoint로 맞힌다
158
+ */
159
+ function layoutProbe() {
160
+ const out = [];
161
+ const vw = window.innerWidth;
162
+ const vh = window.innerHeight;
163
+ const shown = el => el.getClientRects().length > 0;
164
+ const name = el => !el ? '없음' : `<${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : ''}${typeof el.className === 'string' && el.className.trim() ? `.${el.className.trim().split(/\s+/).join('.')}` : ''}>`;
165
+ const buttons = [];
166
+ for (const host of document.querySelectorAll('ec-stepper-nav')) if (host.shadowRoot) for (const b of host.shadowRoot.querySelectorAll('button')) buttons.push([b, host.shadowRoot]);
167
+ for (const b of document.querySelectorAll('.ec-step-nav')) buttons.push([b, document]);
168
+ for (const [b, root] of buttons) {
169
+ const r = b.getBoundingClientRect();
170
+ if (!shown(b) || r.width === 0 || r.height === 0) continue;
171
+ const x = r.left + r.width / 2;
172
+ const y = r.top + r.height / 2;
173
+ // 틀 안에 겹친 옛 방식은 내용이 길면 첫 화면 밖에 있을 수 있다 (가려진 것과 다름)
174
+ if (x < 0 || y < 0 || x >= vw || y >= vh) continue;
175
+ const hit = root.elementFromPoint(x, y);
176
+ if (hit && (hit === b || b.contains(hit))) continue;
177
+ out.push({
178
+ id: 'render.covered-control',
179
+ level: 'fail',
180
+ message: `스테퍼 버튼 "${b.getAttribute('aria-label') ?? b.textContent ?? ''}"을 ${name(hit)}이 덮음 (${Math.round(x)}, ${Math.round(y)})`
181
+ });
182
+ }
183
+ // 작성자 조작(칸 안 버튼 · 입력 · 슬라이더)이 키트 스테퍼 버튼 · n / N 밑에 깔림 (모바일 화면 아래 줄 등).
184
+ // 둥근 버튼은 모서리가 비어 한 점 맞히기로는 놓치므로 상자끼리 겹침(2px 넘게)으로 본다
185
+ const navBoxes = [...document.querySelectorAll('ec-stepper-nav')].flatMap(host => [...(host.shadowRoot?.querySelectorAll('button, .count') ?? [])].filter(el => shown(el)).map(el => el.getBoundingClientRect()).filter(r => r.width > 0 && r.height > 0));
186
+ const CONTROLS = 'button, input:not([type="hidden"]), select, textarea, a[href], [role="button"], [role="slider"]';
187
+ const overlapsNav = r => navBoxes.find(n => Math.min(n.right, r.right) - Math.max(n.left, r.left) > 2 && Math.min(n.bottom, r.bottom) - Math.max(n.top, r.top) > 2);
188
+ // 키트 제출 · 저장 바의 버튼(.ec-submitbar)이 스테퍼 버튼 줄 밑에 깔림: 바는 화면 아래에 붙어(sticky) 스크롤해도
189
+ // 빠져나오지 못하므로 fail. 키트는 스테퍼가 있으면 모바일에서 바를 줄 위로 올린다 (작성자 CSS가 되돌렸을 때 등)
190
+ if (navBoxes.length) for (const button of document.querySelectorAll('.ec-submitbar button')) {
191
+ if (!shown(button)) continue;
192
+ const r = button.getBoundingClientRect();
193
+ if (r.width === 0 || r.height === 0 || r.bottom <= 0 || r.top >= vh) continue;
194
+ const nav = overlapsNav(r);
195
+ if (!nav) continue;
196
+ out.push({
197
+ id: 'render.covered-control',
198
+ level: 'fail',
199
+ message: `제출 바 버튼 "${button.textContent?.trim().slice(0, 20) ?? ''}"이 키트 스테퍼 버튼 줄에 깔림 (${Math.round(nav.left)}, ${Math.round(nav.top)}): .ec-submitbar의 bottom · padding을 바꾸지 마세요`
200
+ });
201
+ }
202
+ if (navBoxes.length) for (const control of document.querySelectorAll(`[data-ec-region] :is(${CONTROLS})`)) {
203
+ if (!shown(control)) continue;
204
+ const r = control.getBoundingClientRect();
205
+ if (r.width === 0 || r.height === 0 || r.bottom <= 0 || r.top >= vh) continue;
206
+ const nav = overlapsNav(r);
207
+ if (!nav) continue;
208
+ const label = control.textContent?.trim().slice(0, 20);
209
+ out.push({
210
+ id: 'render.covered-control',
211
+ level: 'warn',
212
+ message: `${name(control)}${label ? ` "${label}"` : ''}이 키트 스테퍼 버튼 줄과 겹침 (${Math.round(nav.left)}, ${Math.round(nav.top)}): 첫 화면 아래쪽 조작은 무대를 줄이거나 --ec-nav-reserve-mobile만큼 띄워 주세요`
213
+ });
214
+ }
215
+ for (const layout of document.querySelectorAll('[data-ec-layout]')) {
216
+ if (!shown(layout)) continue;
217
+ const kind = layout.getAttribute('data-ec-layout');
218
+ if (kind === 'stage') for (const [region, id, label] of [['readout', 'render.readout-below', '실시간 값(readout)'], ['controls', 'render.controls-below', '조작(controls)']]) {
219
+ const el = layout.querySelector(`:scope > [data-ec-region="${region}"]`);
220
+ if (!el || !shown(el)) continue;
221
+ const r = el.getBoundingClientRect();
222
+ if (r.top >= 0 && r.bottom <= vh + 1) continue;
223
+ out.push({
224
+ id,
225
+ level: 'warn',
226
+ message: `stage 레이아웃의 ${label}이 첫 화면 밖 (아래 끝 ${Math.round(r.bottom)}px, 화면 높이 ${vh}px)`
227
+ });
228
+ }
229
+ // 실시간 값이 무대 그림을 덮는지: 무대 안 그림 요소(canvas · img · video · svg와 그 도형 · 글이 있는 끝 요소)와 겹치면
230
+ if (kind === 'stage') {
231
+ const readout = layout.querySelector(':scope > [data-ec-region="readout"]');
232
+ const stage = layout.querySelector(':scope > [data-ec-region="stage"]');
233
+ if (readout && stage && shown(readout)) {
234
+ const ro = readout.getBoundingClientRect();
235
+ const DRAWN = 'canvas, img, video, svg, circle, ellipse, line, path, polygon, polyline, rect, text, image, use';
236
+ const hit = [...stage.querySelectorAll(DRAWN), ...stage.querySelectorAll('*')].find(el => {
237
+ if (!shown(el)) return false;
238
+ const isDrawn = el.matches(DRAWN);
239
+ const isTextLeaf = !isDrawn && el.children.length === 0 && (el.textContent ?? '').trim() !== '';
240
+ if (!isDrawn && !isTextLeaf) return false;
241
+ const r = el.getBoundingClientRect();
242
+ if (r.width === 0 || r.height === 0) return false;
243
+ const w = Math.min(r.right, ro.right) - Math.max(r.left, ro.left);
244
+ const hgt = Math.min(r.bottom, ro.bottom) - Math.max(r.top, ro.top);
245
+ return w > 1 && hgt > 1;
246
+ });
247
+ if (hit) out.push({
248
+ id: 'render.readout-covers',
249
+ level: 'warn',
250
+ message: `stage 레이아웃의 실시간 값(readout)이 무대 그림 ${name(hit)}을 덮음: 무대 바로 아래 그림은 키트가 위쪽 띠(--ec-readout-safe)를 비워 두니 그림을 직접 position: absolute로 칸 전체에 붙이지 마세요`
251
+ });
252
+ }
253
+ }
254
+ if (kind === 'single') continue;
255
+ const loose = [...layout.children].filter(c => !c.hasAttribute('data-ec-region') && !/^(H[1-3]|SCRIPT|STYLE|TEMPLATE)$/.test(c.tagName) && shown(c));
256
+ if (loose.length) out.push({
257
+ id: 'render.outside-region',
258
+ level: 'warn',
259
+ message: `${kind} 레이아웃 바로 아래에 영역 밖 내용 ${loose.length}개 (${name(loose[0] ?? null)}): data-ec-region 칸 안에 넣어 주세요`
260
+ });
261
+ }
262
+ return out;
263
+ }
142
264
  const wait = ms => new Promise(r => setTimeout(r, ms));
143
265
  async function checkScreen(page, o) {
144
266
  const started = Date.now();
@@ -186,37 +308,102 @@ async function checkScreen(page, o) {
186
308
  }
187
309
  await wait(SETTLE_MS);
188
310
  state = (await read()) ?? state;
189
- let screenshot = null;
190
- const file = join(o.shotDir, `${o.screen}-${o.viewport}.png`);
191
- try {
192
- await page.locator('#content').screenshot({
193
- path: file,
194
- timeout: 5000
195
- });
196
- screenshot = relative(o.dir, file).split(sep).join('/');
197
- } catch {
198
- // 그림 없이 결과만
311
+ const frameEval = async (fn, arg) => {
312
+ const frame = contentFrame();
313
+ if (!frame) return null;
314
+ try {
315
+ return (await frame.evaluate(fn, arg)) ?? null;
316
+ } catch {
317
+ return null; // 다시 띄우는 중
318
+ }
319
+ };
320
+ // --theme: 키트 · EDS 색은 <html data-eds-theme="dark">로 바뀐다 (light는 속성을 뗀다)
321
+ if (o.theme) {
322
+ await frameEval(theme => {
323
+ if (theme === 'dark') document.documentElement.setAttribute('data-eds-theme', 'dark');else document.documentElement.removeAttribute('data-eds-theme');
324
+ }, o.theme);
325
+ await wait(150);
326
+ state = (await read()) ?? state;
199
327
  }
200
328
  let blocked = [];
201
- try {
202
- blocked = await page.evaluate(() => (window.__ECDK_HOST__?.blocked ?? []).map(b => `${b.blockedURI} (${b.violatedDirective})`));
203
- } catch {
204
- // 화면이 닫혔으면 빈 목록
205
- }
206
- return {
207
- screen: o.screen,
208
- viewport: o.viewport,
209
- width: state?.width ?? 0,
210
- rendered: !!state && (state.text > 0 || state.media) && !state.loading,
211
- loading: state?.loading ?? null,
212
- consoleErrors: [...new Set(consoleErrors)],
213
- pageErrors: [...new Set(pageErrors)],
214
- blocked,
215
- failedRequests: [...new Set(failedRequests)],
216
- overflowX: state?.overflowX ?? false,
217
- screenshot,
218
- ms: Date.now() - started
329
+ const readBlocked = async () => {
330
+ try {
331
+ blocked = await page.evaluate(() => (window.__ECDK_HOST__?.blocked ?? []).map(b => `${b.blockedURI} (${b.violatedDirective})`));
332
+ } catch {
333
+ // 화면이 닫혔으면 빈 목록
334
+ }
335
+ };
336
+ // 단계마다 그때까지 새로 난 오류만 그 단계 결과에
337
+ const seen = {
338
+ console: 0,
339
+ page: 0,
340
+ failed: 0
341
+ };
342
+ const capture = async (step, missingStep) => {
343
+ const layout = (await frameEval(layoutProbe)) ?? [];
344
+ const name = [o.screen, o.viewport, o.theme, step === undefined ? undefined : `step${step}`].filter(Boolean).join('-');
345
+ let screenshot = null;
346
+ const file = join(o.shotDir, `${name}.png`);
347
+ try {
348
+ await page.locator('#content').screenshot({
349
+ path: file,
350
+ timeout: 5000
351
+ });
352
+ screenshot = relative(o.dir, file).split(sep).join('/');
353
+ } catch {
354
+ // 그림 없이 결과만
355
+ }
356
+ await readBlocked();
357
+ const fresh = (list, key) => {
358
+ const out = [...new Set(list.slice(seen[key]))];
359
+ seen[key] = list.length;
360
+ return out;
361
+ };
362
+ return {
363
+ screen: o.screen,
364
+ viewport: o.viewport,
365
+ ...(o.theme ? {
366
+ theme: o.theme
367
+ } : {}),
368
+ ...(step === undefined ? {} : {
369
+ step
370
+ }),
371
+ ...(missingStep ? {
372
+ missingStep
373
+ } : {}),
374
+ width: state?.width ?? 0,
375
+ rendered: !!state && (state.text > 0 || state.media) && !state.loading,
376
+ loading: state?.loading ?? null,
377
+ consoleErrors: fresh(consoleErrors, 'console'),
378
+ pageErrors: fresh(pageErrors, 'page'),
379
+ blocked,
380
+ failedRequests: fresh(failedRequests, 'failed'),
381
+ overflowX: state?.overflowX ?? false,
382
+ layout,
383
+ screenshot,
384
+ ms: Date.now() - started
385
+ };
219
386
  };
387
+ if (!o.steps) return [await capture()];
388
+ // --step: 키트 스테퍼(<ec-stepper-nav>의 ecStepper 손잡이)로 단계를 바꿔 찍는다. canNext와 상관없이 그 단계로 간다
389
+ const count = (await frameEval(() => document.querySelector('ec-stepper-nav')?.ecStepper?.count ?? 0)) ?? 0;
390
+ // 스테퍼가 없는 화면(편집 화면 등): all이면 그대로 한 번, 단계 번호를 적었으면 알린다
391
+ if (count === 0) return [await capture(undefined, o.steps === 'all' ? undefined : '스테퍼가 없는 화면이라 단계별로 찍지 않음 (--step)')];
392
+ const wanted = o.steps === 'all' ? Array.from({
393
+ length: count
394
+ }, (_, i) => i + 1) : o.steps;
395
+ const results = [];
396
+ for (const step of wanted) {
397
+ if (step > count) {
398
+ results.push(await capture(undefined, `단계 ${step}이 없음 (이 화면은 ${count}단계)`));
399
+ continue;
400
+ }
401
+ await frameEval(i => document.querySelector('ec-stepper-nav').ecStepper.go(i), step - 1);
402
+ await wait(SETTLE_MS);
403
+ state = (await read()) ?? state;
404
+ results.push(await capture(step));
405
+ }
406
+ return results;
220
407
  }
221
408
  /** 프로젝트에 없는 화면을 고른 경우 (사용법 오류) */
222
409
  class ScreenNotFoundError extends Error {}
@@ -265,10 +452,12 @@ async function runCheck(opts) {
265
452
  recursive: true
266
453
  });
267
454
  const contentOrigin = new URL(server.contentUrl).origin;
268
- const jobs = screens.flatMap(screen => viewports.map(viewport => ({
455
+ const themes = opts.themes ?? [undefined];
456
+ const jobs = screens.flatMap(screen => viewports.flatMap(viewport => themes.map(theme => ({
269
457
  screen,
270
- viewport
271
- })));
458
+ viewport,
459
+ theme
460
+ }))));
272
461
  const results = new Array(jobs.length);
273
462
  let next = 0;
274
463
  await Promise.all(Array.from({
@@ -282,6 +471,7 @@ async function runCheck(opts) {
282
471
  hostUrl: server.hostUrl,
283
472
  contentOrigin,
284
473
  ...jobs[i],
474
+ steps: opts.steps,
285
475
  dir,
286
476
  shotDir
287
477
  });
@@ -309,7 +499,7 @@ async function runCheck(opts) {
309
499
  browser: launched.name,
310
500
  durationMs: 0,
311
501
  screenshotsDir: shotDir,
312
- screens: results,
502
+ screens: results.flat(),
313
503
  validate,
314
504
  notes
315
505
  };
@@ -323,4 +513,4 @@ async function runCheck(opts) {
323
513
  }
324
514
  }
325
515
 
326
- export { CHECK_SCREENS, CHECK_VIEWPORTS, SCREEN_WAIT_MS, ScreenNotFoundError, defaultScreens, exitCodeOf, findingsOf, formatText, parseList, runCheck, statusOf };
516
+ export { CHECK_SCREENS, CHECK_THEMES, CHECK_VIEWPORTS, SCREEN_WAIT_MS, ScreenNotFoundError, defaultScreens, exitCodeOf, findingsOf, formatText, parseList, runCheck, statusOf };
@@ -3,18 +3,37 @@ import type { LocalGrading } from '../core/config.js';
3
3
  export interface GradeResult {
4
4
  isCorrect: boolean | null;
5
5
  score: number | null;
6
+ /**
7
+ * partial_pattern 문항별 맞음 (응답 `answer_correctness`, answer_key 순서, 없는 답은 false).
8
+ * 서버는 pattern · rubric · 채점 없음이면 `[]`를 준다 (흉내 서버가 응답에서 채움)
9
+ */
10
+ answerCorrectness?: boolean[];
6
11
  }
7
12
  /** dev가 rubric(AI) 채점을 흉내 낼 때 돌려주는 점수. 서버는 요청 안에서 채점한다 */
8
13
  export declare const RUBRIC_DEV_SCORE = 80;
9
14
  /** 정답 비교에 쓰는 답 문자열: 문자열은 앞뒤 공백을 자르고, 그 밖은 JSON으로 */
10
15
  export declare const answerText: (answer: unknown) => string;
11
- /** pattern: 정답 정규식(문자열 하나)이 답 문자열 전체와 맞는지. 정규식이 틀리거나 없으면 오답 */
16
+ /**
17
+ * pattern: 정답 정규식(문자열 하나)이 답 문자열 전체와 맞는지. 정규식이 틀리거나 없으면 오답.
18
+ * 맨 앞 `(?i)`는 서버(Python re)처럼 대소문자 무시
19
+ */
12
20
  export declare function matchesPattern(answerKey: unknown, answer: unknown): boolean;
21
+ /**
22
+ * 채점 전에 서버가 거절하는 답 (422). partial_pattern은 답이 문자열 배열이어야 한다.
23
+ * 문제가 없으면 null, 있으면 이유
24
+ */
25
+ export declare function answerError(local: LocalGrading | undefined, answer: unknown): string | null;
26
+ /**
27
+ * partial_pattern: `answer[i]`를 `answer_key[i]`에 맞춰 보고, 맞은 문항의 `scores[i]`를 더해 100에서 자른다.
28
+ * 없는 문항은 0점(answerCorrectness false), 남는 답은 무시. 100점일 때만 정답. 답 모양은 answerError가 먼저 본다
29
+ */
30
+ export declare function gradePartial(answerKey: string[], scores: number[], answer: unknown): GradeResult;
13
31
  /**
14
32
  * elice-material 채점 흉내 (채점 방식 → 점수). 채점은 모두 요청 안에서 끝난다.
15
33
  * 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이다. 완료 정책은 LXP 설정이라 보지 않는다 (ADR 0012):
16
34
  * 채점 설정이 있으면 채점하고, 없으면 제출만 받는다.
17
35
  * - pattern: 답 문자열 전체를 정규식 하나로 비교 0 / 100
36
+ * - partial_pattern: 문항별 정규식, 맞은 문항 점수의 합(최대 100). 100점일 때만 정답
18
37
  * - rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지 않음)
19
38
  * - 채점 설정(편집 화면이 저장하는 settings.grading)이 없으면 제출만 받고 `{ null, null }`
20
39
  */
package/es/dev/grading.js CHANGED
@@ -1,21 +1,51 @@
1
+ import { fullMatch } from '../core/regex.js';
2
+
1
3
  /** dev가 rubric(AI) 채점을 흉내 낼 때 돌려주는 점수. 서버는 요청 안에서 채점한다 */
2
4
  const RUBRIC_DEV_SCORE = 80;
3
5
  /** 정답 비교에 쓰는 답 문자열: 문자열은 앞뒤 공백을 자르고, 그 밖은 JSON으로 */
4
6
  const answerText = answer => typeof answer === 'string' ? answer.trim() : JSON.stringify(answer ?? null);
5
- /** pattern: 정답 정규식(문자열 하나)이 답 문자열 전체와 맞는지. 정규식이 틀리거나 없으면 오답 */
7
+ /**
8
+ * pattern: 정답 정규식(문자열 하나)이 답 문자열 전체와 맞는지. 정규식이 틀리거나 없으면 오답.
9
+ * 맨 앞 `(?i)`는 서버(Python re)처럼 대소문자 무시
10
+ */
6
11
  function matchesPattern(answerKey, answer) {
7
12
  if (typeof answerKey !== 'string') return false;
8
- try {
9
- return new RegExp(`^(?:${answerKey})$`).test(answerText(answer));
10
- } catch {
11
- return false;
12
- }
13
+ return fullMatch(answerKey, answerText(answer));
14
+ }
15
+ /**
16
+ * 채점 전에 서버가 거절하는 답 (422). partial_pattern은 답이 문자열 배열이어야 한다.
17
+ * 문제가 없으면 null, 있으면 이유
18
+ */
19
+ function answerError(local, answer) {
20
+ if (local?.grading?.type !== 'partial_pattern') return null;
21
+ if (!Array.isArray(answer)) return 'partial_pattern: answer must be an array of strings';
22
+ const bad = answer.findIndex(item => typeof item !== 'string');
23
+ return bad < 0 ? null : `partial_pattern: answer[${bad}] must be a string`;
24
+ }
25
+ /**
26
+ * partial_pattern: `answer[i]`를 `answer_key[i]`에 맞춰 보고, 맞은 문항의 `scores[i]`를 더해 100에서 자른다.
27
+ * 없는 문항은 0점(answerCorrectness false), 남는 답은 무시. 100점일 때만 정답. 답 모양은 answerError가 먼저 본다
28
+ */
29
+ function gradePartial(answerKey, scores, answer) {
30
+ const items = Array.isArray(answer) ? answer : [];
31
+ const answerCorrectness = answerKey.map((key, i) => {
32
+ const item = items[i];
33
+ return typeof item === 'string' && fullMatch(key, item);
34
+ });
35
+ const total = answerCorrectness.reduce((sum, ok, i) => sum + (ok ? scores[i] ?? 0 : 0), 0);
36
+ const score = Math.min(100, total);
37
+ return {
38
+ isCorrect: score === 100,
39
+ score,
40
+ answerCorrectness
41
+ };
13
42
  }
14
43
  /**
15
44
  * elice-material 채점 흉내 (채점 방식 → 점수). 채점은 모두 요청 안에서 끝난다.
16
45
  * 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이다. 완료 정책은 LXP 설정이라 보지 않는다 (ADR 0012):
17
46
  * 채점 설정이 있으면 채점하고, 없으면 제출만 받는다.
18
47
  * - pattern: 답 문자열 전체를 정규식 하나로 비교 0 / 100
48
+ * - partial_pattern: 문항별 정규식, 맞은 문항 점수의 합(최대 100). 100점일 때만 정답
19
49
  * - rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지 않음)
20
50
  * - 채점 설정(편집 화면이 저장하는 settings.grading)이 없으면 제출만 받고 `{ null, null }`
21
51
  */
@@ -28,6 +58,7 @@ function grade(local, answer) {
28
58
  score: ok ? 100 : 0
29
59
  };
30
60
  }
61
+ if (grading?.type === 'partial_pattern') return gradePartial(grading.answer_key, grading.scores, answer);
31
62
  if (grading?.type === 'rubric') return {
32
63
  isCorrect: true,
33
64
  score: RUBRIC_DEV_SCORE
@@ -38,4 +69,4 @@ function grade(local, answer) {
38
69
  };
39
70
  }
40
71
 
41
- export { RUBRIC_DEV_SCORE, answerText, grade, matchesPattern };
72
+ export { RUBRIC_DEV_SCORE, answerError, answerText, grade, gradePartial, matchesPattern };
@@ -66,7 +66,7 @@ function hostPage(opts) {
66
66
  <b>저장 전 편집 화면</b> <code>#edit=1</code>
67
67
  <button type="button" id="open-edit-draft">열기</button>
68
68
  </div>
69
- <div class="tool" role="group" aria-label="저장 전 미리보기" title="LXP 편집 페이지의 미리보기처럼 토큰 없이 학생 화면을 엽니다. settings가 비어 '아직 내용이 없습니다' 안내가 뜨고(기본 내용 없음), 제출은 기록되지 않습니다(늘 100점)">
69
+ <div class="tool" role="group" aria-label="저장 전 미리보기" title="LXP 편집 페이지의 미리보기처럼 토큰 없이 학생 화면을 엽니다. settings가 비어 '학습 자료를 준비하고 있어요' 안내가 뜨고(기본 내용 없음), 제출은 기록되지 않습니다(늘 100점)">
70
70
  <b>저장 전 미리보기</b> <code>#preview=1</code>
71
71
  <button type="button" id="open-preview">열기</button>
72
72
  </div>
@@ -24,7 +24,7 @@ export type MaterialViewer = 'student' | 'instructor' | 'tutor';
24
24
  * 콘텐츠의 `saveSettings`가 이 토큰으로 `PATCH /materials/{id}/draft`를 부른다 (토큰 없는 `#edit=1` draft는 저장할 수 없음).
25
25
  * dev에는 draft 발행 단계가 없어 draft에 저장한 settings가 바로 지금 버전 settings가 된다
26
26
  * 완료 정책은 LXP 설정이라 (ADR 0012) 흉내 내지 않는다: 채점 설정이 있으면 채점하고, 없으면 제출만 받는다.
27
- * 편집 화면의 `saveSettings`가 보낸 settings(내용 + `grading` { type: pattern | rubric })는 통째로 `.ecdk/settings.json`에 쓰고,
27
+ * 편집 화면의 `saveSettings`가 보낸 settings(내용 + `grading` { type: pattern | partial_pattern | rubric })는 통째로 `.ecdk/settings.json`에 쓰고,
28
28
  * edit 범위 응답에는 `grading`까지, 학생 · 튜터 · 교육자(learn scope) 응답에는 서버처럼 `grading`을 빼고 준다
29
29
  */
30
30
  export type DevScenario = 'student' | 'instructor' | 'tutor' | 'edit';
@@ -44,6 +44,8 @@ interface Submission {
44
44
  answer: unknown;
45
45
  is_correct: boolean | null;
46
46
  score: number | null;
47
+ /** partial_pattern 문항별 맞음, 그 밖은 [] */
48
+ answer_correctness: boolean[];
47
49
  }
48
50
  interface Result {
49
51
  score: number | null;
@@ -1,5 +1,5 @@
1
1
  import { parseGrading } from '../core/config.js';
2
- import { grade } from './grading.js';
2
+ import { answerError, grade } from './grading.js';
3
3
 
4
4
  /**
5
5
  * elice-material API 흉내 (서버 설계 v25, @eliceio/cdk 1.x가 부르는 것만).
@@ -267,16 +267,27 @@ async function handleMockApi(req, res, path, opts) {
267
267
  state.recent.set(subject, [...recent, now]);
268
268
  // 채점은 요청 안에서 끝난다 (rubric 포함). 학생만 기록, instructor는 채점만
269
269
  const answer = json?.answer ?? null;
270
+ // 서버처럼 채점 방식이 받지 않는 답 모양은 422 (partial_pattern: 문자열 배열이 아님). 기록에 넣지 않는다
271
+ const shapeError = answerError(opts.getGrading(), answer);
272
+ if (shapeError) return fail(res, 422, 'VALIDATION_ERROR', shapeError, [{
273
+ type: 'value_error',
274
+ loc: ['body', 'answer']
275
+ }]);
270
276
  const {
271
277
  isCorrect,
272
- score
278
+ score,
279
+ answerCorrectness
273
280
  } = grade(opts.getGrading(), answer);
281
+ // answer_correctness: partial_pattern 문항별 맞음, 그 밖의 채점 방식은 서버처럼 []. 제출 응답 · 제출 기록에 같이 (/me에는 없음)
282
+ const correctness = answerCorrectness ?? [];
283
+ const response = {
284
+ is_correct: isCorrect,
285
+ score,
286
+ answer_correctness: correctness
287
+ };
274
288
  if (claims.viewer !== 'student') {
275
289
  log(`${claims.viewer} 제출: 채점만 (${score ?? '-'}점, 기록 안 함)`);
276
- return send(res, 200, {
277
- is_correct: isCorrect,
278
- score
279
- });
290
+ return send(res, 200, response);
280
291
  }
281
292
  state.submissions.unshift({
282
293
  id: `dev-${state.submissions.length + 1}`,
@@ -285,7 +296,8 @@ async function handleMockApi(req, res, path, opts) {
285
296
  created_at: new Date().toISOString(),
286
297
  answer,
287
298
  is_correct: isCorrect,
288
- score
299
+ score,
300
+ answer_correctness: correctness
289
301
  });
290
302
  // 채점 설정이 있으면 통과해야, 없으면 제출만으로 기록에 완료 시각을 남긴다 (운영 완료 여부는 LXP 완료 정책이 정함)
291
303
  record(state, subject, {
@@ -293,10 +305,7 @@ async function handleMockApi(req, res, path, opts) {
293
305
  submit_count: 1
294
306
  }, isCorrect === true || !opts.getGrading()?.grading);
295
307
  log(`학생 제출: ${score ?? '-'}점 (${isCorrect === null ? '채점 없음' : isCorrect ? '정답' : '오답'})`);
296
- return send(res, 200, {
297
- is_correct: isCorrect,
298
- score
299
- });
308
+ return send(res, 200, response);
300
309
  }
301
310
  return fail(res, 405, 'RESOURCE_NOT_FOUND', `${method} ${path}`);
302
311
  }
@@ -1,2 +1,2 @@
1
- export { ECDK_PLUGIN_NAME, ecdk, flattenPlugins } from './plugin.js';
1
+ export { ECDK_PLUGIN_NAME, MOCK_SDK_FLAG, ecdk, flattenPlugins } from './plugin.js';
2
2
  export { viteBuild, viteDevServer } from './run.js';
@@ -4,6 +4,8 @@ import type { Plugin } from 'vite';
4
4
  import type { Excluded } from '../../core/collect.js';
5
5
  /** Plugin name. `ecdk build` / `ecdk dev` add the plugin only when the Vite config has none with this name */
6
6
  export declare const ECDK_PLUGIN_NAME = "ecdk";
7
+ /** 키트가 흉내 SDK를 넣을지 보는 전역 이름. build만 false로 바꾼다 (정의하지 않으면 넣음: ecdk dev · 테스트) */
8
+ export declare const MOCK_SDK_FLAG = "__ECDK_MOCK_SDK__";
7
9
  export interface EcdkOptions {
8
10
  /** ecdk project folder (where package.json "ecdk" lives). Default: Vite root or the working directory */
9
11
  projectDir?: string | undefined;
@@ -12,11 +12,14 @@ import { injectDevScript } from '../../dev/inject.js';
12
12
  import { checkFiles } from '../../rules/check.js';
13
13
  import { rules } from '../../rules/spec.js';
14
14
  import { stripCompletionPolicy } from '../../rules/manifest.js';
15
+ import { screenSizeIssues, screenSizes } from '../../rules/size.js';
15
16
  import { findUnreferenced } from '../../rules/unused.js';
16
17
  import 'fflate';
17
18
 
18
19
  /** Plugin name. `ecdk build` / `ecdk dev` add the plugin only when the Vite config has none with this name */
19
20
  const ECDK_PLUGIN_NAME = 'ecdk';
21
+ /** 키트가 흉내 SDK를 넣을지 보는 전역 이름. build만 false로 바꾼다 (정의하지 않으면 넣음: ecdk dev · 테스트) */
22
+ const MOCK_SDK_FLAG = '__ECDK_MOCK_SDK__';
20
23
  const encoder = new TextEncoder();
21
24
  const decoder = new TextDecoder();
22
25
  /**
@@ -127,6 +130,13 @@ function ecdk(options = {}) {
127
130
  ...(isBuild ? {
128
131
  base: './'
129
132
  } : {}),
133
+ // 키트(lib/elice-content.js)의 흉내 SDK 분기를 build에서 지운다 (운영 zip에 cdk-mock.js가 들어가지 않게).
134
+ // ecdk dev는 바꾸지 않아 흉내 SDK를 그대로 쓴다
135
+ ...(isBuild ? {
136
+ define: {
137
+ [MOCK_SDK_FLAG]: 'false'
138
+ }
139
+ } : {}),
130
140
  appType: 'mpa',
131
141
  cacheDir: join(projectDir, 'node_modules', '.vite'),
132
142
  build: {
@@ -147,7 +157,11 @@ function ecdk(options = {}) {
147
157
  // chunk hashes depend on the absolute project path, so chunks get stable names for reproducible zips
148
158
  output: {
149
159
  entryFileNames: 'assets/[name].js',
150
- chunkFileNames: 'assets/[name].js'
160
+ chunkFileNames: 'assets/[name].js',
161
+ // minify해도 라이선스 주석(/*! · @license)은 남긴다 (넣은 아이콘 · 라이브러리의 고지 의무, Vite 8 기본은 지움)
162
+ comments: {
163
+ legal: true
164
+ }
151
165
  }
152
166
  }
153
167
  }
@@ -180,12 +194,20 @@ function ecdk(options = {}) {
180
194
  const emitted = new Set(output.map(f => f.path));
181
195
  for (const f of prepared.files) if (!emitted.has(f.path) && (prepared.publicFiles.has(f.path) || f.path === commentary)) output.push(f);
182
196
  // Inline each page's module scripts (chunks) so pages load even when the LXP content origin is null
197
+ // Chunks reached only through import() can stay as separate files loaded on demand (core/sandbox.ts)
198
+ const graph = new Map();
199
+ for (const item of Object.values(bundle)) if (item.type === 'chunk') graph.set(item.fileName, {
200
+ imports: item.imports,
201
+ dynamicImports: item.dynamicImports
202
+ });
183
203
  const sandboxed = await inlineModuleScripts(output, {
184
204
  minify: config.minify !== false,
185
- sourcemap: config.sourcemap === true
205
+ sourcemap: config.sourcemap === true,
206
+ chunks: graph
186
207
  });
187
- const chunks = new Set(Object.values(bundle).filter(item => item.type === 'chunk').map(item => item.fileName));
188
- const content = sandboxed.files.filter(f => !chunks.has(f.path));
208
+ // Inlined chunks are dropped; chunks emitted as lazy files stay (rewritten as classic scripts)
209
+ const lazy = new Set(sandboxed.report.lazyFiles);
210
+ const content = sandboxed.files.filter(f => !graph.has(f.path) || lazy.has(f.path));
189
211
  if (manifest) content.push(manifest);
190
212
  // metadata.json build gets the minify flag and the digest of the final files (metadata.json excluded)
191
213
  const digest = contentDigest(content);
@@ -209,6 +231,12 @@ function ecdk(options = {}) {
209
231
  }
210
232
  const zip = createZip(files);
211
233
  const check = await checkBuild(projectDir, config, prepared, files, zip.byteLength);
234
+ // Screen sizes are known only after bundling: checks read the sources, so add limit.screen-size from the output
235
+ const flagged = new Set(check.issues.filter(i => i.id === 'limit.screen-size').map(i => i.path));
236
+ for (const issue of screenSizeIssues(screenSizes(files), rules)) if (!flagged.has(issue.path)) check.issues.push({
237
+ ...issue,
238
+ level: rules.rules.find(r => r.id === issue.id)?.level ?? 'warn'
239
+ });
212
240
  pendingZip = zip;
213
241
  api.result = {
214
242
  ok: check.ok,
@@ -283,4 +311,4 @@ async function flattenPlugins(plugins) {
283
311
  return value && typeof value === 'object' && 'name' in value ? [value] : [];
284
312
  }
285
313
 
286
- export { ECDK_PLUGIN_NAME, ecdk, flattenPlugins };
314
+ export { ECDK_PLUGIN_NAME, MOCK_SDK_FLAG, ecdk, flattenPlugins };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * 정답 노출 검사(sec.answer-in-bundle)에 쓸 글: 편집 화면이 저장한 채점 설정(settings.grading)에서 그대로 찾을 수 있는 정답 글.
3
+ * 정답은 zip에 넣지 않는다 (ADR 0009). 화면 코드 · 학습 참고 내용에 같은 글이 있으면 학생이 zip에서 읽을 수 있다.
4
+ *
5
+ * - pattern: 정답 정규식 `^…$`에서 앞뒤 ^ · $와 바깥 묶음을 떼고, 맨 위 `|`로 나눈 갈래 중 정규식 기호가 없는 글만
6
+ * (`\.` 같은 이스케이프는 풀어서). `^(서울|Seoul)$` → 서울 · Seoul. `^\d+$`처럼 글이 아닌 갈래는 건너뜀
7
+ * - partial_pattern: 문항마다 정답 정규식 배열이라 원소마다 위와 같이
8
+ * - rubric: 평가 기준 글 전체
9
+ * 흔한 글과 겹치는 짧은 글은 뺀다: 한글이 든 글은 2자 미만, 그 밖(영문 · 숫자 등)은 3자 미만, 숫자만 3자 이하(100 · 0.5)
10
+ */
11
+ export declare function answerNeedles(grading: unknown): string[];
12
+ /** 정규식에서 그대로 찾을 수 있는 글 갈래 */
13
+ export declare function regexLiterals(regex: string): string[];