@eliceio/cdk-cli 1.2.1 → 1.3.0-contenttypes.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.
Files changed (169) hide show
  1. package/README.md +63 -53
  2. package/es/cli.js +11 -2
  3. package/es/commands/build/index.js +12 -0
  4. package/es/commands/create/index.js +2 -0
  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/commands/doctor/index.js +6 -2
  10. package/es/core/config.d.ts +42 -9
  11. package/es/core/config.js +217 -12
  12. package/es/core/project-check.d.ts +3 -2
  13. package/es/core/project-check.js +14 -3
  14. package/es/core/regex.d.ts +11 -0
  15. package/es/core/regex.js +41 -0
  16. package/es/core/sandbox.d.ts +26 -0
  17. package/es/core/sandbox.js +240 -30
  18. package/es/dev/assets.d.ts +80 -0
  19. package/es/dev/assets.js +240 -0
  20. package/es/dev/check.d.ts +30 -0
  21. package/es/dev/check.js +224 -34
  22. package/es/dev/grading.d.ts +49 -14
  23. package/es/dev/grading.js +109 -29
  24. package/es/dev/host-page.js +27 -3
  25. package/es/dev/inject.d.ts +2 -1
  26. package/es/dev/inject.js +10 -2
  27. package/es/dev/mock-api.d.ts +26 -3
  28. package/es/dev/mock-api.js +219 -40
  29. package/es/dev/server.d.ts +12 -1
  30. package/es/dev/server.js +115 -9
  31. package/es/engines/vite/index.js +1 -1
  32. package/es/engines/vite/plugin.d.ts +2 -0
  33. package/es/engines/vite/plugin.js +33 -5
  34. package/es/rules/answers.d.ts +13 -0
  35. package/es/rules/answers.js +94 -0
  36. package/es/rules/check.js +70 -1
  37. package/es/rules/index.d.ts +1 -0
  38. package/es/rules/index.js +1 -0
  39. package/es/rules/size.d.ts +31 -0
  40. package/es/rules/size.js +58 -0
  41. package/es/rules/types.d.ts +12 -0
  42. package/es/rules.json.js +2 -2
  43. package/package.json +2 -2
  44. package/rules.json +34 -5
  45. package/skills/_shared/always.md +3 -3
  46. package/skills/_shared/references/00-what-the-person-decides.md +1 -1
  47. package/skills/_shared/references/02-design-the-material.md +10 -7
  48. package/skills/_shared/references/03-create-the-project.md +10 -8
  49. package/skills/_shared/references/04-rules.md +1 -1
  50. package/skills/_shared/references/05-screen-code.md +52 -23
  51. package/skills/_shared/references/06-using-the-quiz-template.md +7 -6
  52. package/skills/_shared/references/08-fix-check-errors.md +23 -22
  53. package/skills/_shared/references/09-check.md +8 -6
  54. package/skills/_shared/references/12-upload-with-the-material-mcp.md +13 -13
  55. package/skills/_shared/references/13-edit-screen-design.md +122 -0
  56. package/skills/_shared/references/14-layouts.md +96 -0
  57. package/skills/elice-content-check/SKILL.md +2 -2
  58. package/skills/elice-content-create/SKILL.md +1 -1
  59. package/skills/elice-content-migrate/SKILL.md +1 -1
  60. package/skills/elice-content-publish/SKILL.md +1 -1
  61. package/templates/_shared/lib/cdk-mock.d.ts +47 -3
  62. package/templates/_shared/lib/cdk-mock.js +293 -15
  63. package/templates/_shared/lib/elice-content-editor.js +89 -58
  64. package/templates/_shared/lib/elice-content.css +1313 -126
  65. package/templates/_shared/lib/elice-content.d.ts +222 -23
  66. package/templates/_shared/lib/elice-content.js +1176 -88
  67. package/templates/_shared/lib/icons/empty-content.d.ts +2 -0
  68. package/templates/_shared/lib/icons/empty-content.js +11 -0
  69. package/templates/_shared/lib/icons/file-video.d.ts +2 -0
  70. package/templates/_shared/lib/icons/file-video.js +11 -0
  71. package/templates/_shared/lib/icons/file.d.ts +2 -0
  72. package/templates/_shared/lib/icons/file.js +11 -0
  73. package/templates/blank/README.md +6 -4
  74. package/templates/blank/edit.html +8 -2
  75. package/templates/blank/index.html +6 -1
  76. package/templates/blank/instructor.html +6 -1
  77. package/templates/blank/screens/instructor.js +8 -2
  78. package/templates/blank/screens/learn.js +1 -1
  79. package/templates/blank/template.json +1 -1
  80. package/templates/document/README.md +92 -0
  81. package/templates/document/commentary.txt +2 -0
  82. package/templates/document/core/dom.d.ts +13 -0
  83. package/templates/document/core/dom.js +83 -0
  84. package/templates/document/core/file-type.d.ts +21 -0
  85. package/templates/document/core/file-type.js +85 -0
  86. package/templates/document/core/group-3d.d.ts +20 -0
  87. package/templates/document/core/group-3d.js +256 -0
  88. package/templates/document/core/inline-edit.d.ts +15 -0
  89. package/templates/document/core/inline-edit.js +377 -0
  90. package/templates/document/core/load.d.ts +13 -0
  91. package/templates/document/core/load.js +40 -0
  92. package/templates/document/core/pdf-options.d.ts +9 -0
  93. package/templates/document/core/pdf-options.js +36 -0
  94. package/templates/document/core/pdf-worker.d.ts +24 -0
  95. package/templates/document/core/pdf-worker.js +122 -0
  96. package/templates/document/core/pdf.d.ts +12 -0
  97. package/templates/document/core/pdf.js +190 -0
  98. package/templates/document/core/pptx-edit.d.ts +14 -0
  99. package/templates/document/core/pptx-edit.js +137 -0
  100. package/templates/document/core/pptx-fonts.d.ts +5 -0
  101. package/templates/document/core/pptx-fonts.js +115 -0
  102. package/templates/document/core/pptx-media.d.ts +18 -0
  103. package/templates/document/core/pptx-media.js +83 -0
  104. package/templates/document/core/pptx-view.d.ts +5 -0
  105. package/templates/document/core/pptx-view.js +185 -0
  106. package/templates/document/core/settings.d.ts +25 -0
  107. package/templates/document/core/settings.js +86 -0
  108. package/templates/document/core/slide-edges.d.ts +3 -0
  109. package/templates/document/core/slide-edges.js +82 -0
  110. package/templates/document/core/viewer.d.ts +28 -0
  111. package/templates/document/core/viewer.js +159 -0
  112. package/templates/document/edit.html +17 -0
  113. package/templates/document/gitignore +4 -0
  114. package/templates/document/index.html +18 -0
  115. package/templates/document/metadata.json +9 -0
  116. package/templates/document/package.json +17 -0
  117. package/templates/document/public/fonts/OFL-Caladea.txt +93 -0
  118. package/templates/document/public/fonts/OFL-Carlito.txt +93 -0
  119. package/templates/document/public/fonts/caladea-latin-400-normal.woff2 +0 -0
  120. package/templates/document/public/fonts/caladea-latin-700-normal.woff2 +0 -0
  121. package/templates/document/public/fonts/carlito-latin-400-normal.woff2 +0 -0
  122. package/templates/document/public/fonts/carlito-latin-700-normal.woff2 +0 -0
  123. package/templates/document/screens/edit.js +574 -0
  124. package/templates/document/screens/learn.js +61 -0
  125. package/templates/document/styles.css +644 -0
  126. package/templates/document/template.json +6 -0
  127. package/templates/document/ui/templates/edit.js +82 -0
  128. package/templates/document/ui/templates/page.js +11 -0
  129. package/templates/document/ui/templates/viewer.js +41 -0
  130. package/templates/document/ui/texts.d.ts +3 -0
  131. package/templates/document/ui/texts.js +62 -0
  132. package/templates/document/ui/theme.css +69 -0
  133. package/templates/quiz/README.md +32 -14
  134. package/templates/quiz/core/behaviors.d.ts +17 -7
  135. package/templates/quiz/core/behaviors.js +40 -53
  136. package/templates/quiz/core/editor.d.ts +27 -2
  137. package/templates/quiz/core/editor.js +412 -11
  138. package/templates/quiz/core/markdown.d.ts +19 -0
  139. package/templates/quiz/core/markdown.js +225 -11
  140. package/templates/quiz/core/model.d.ts +40 -3
  141. package/templates/quiz/core/model.js +112 -5
  142. package/templates/quiz/core/rich-text.d.ts +18 -0
  143. package/templates/quiz/core/rich-text.js +469 -0
  144. package/templates/quiz/edit.html +12 -3
  145. package/templates/quiz/index.html +12 -3
  146. package/templates/quiz/public/img/mascot-half.webp +0 -0
  147. package/templates/quiz/screens/edit.js +331 -49
  148. package/templates/quiz/screens/learn.js +147 -15
  149. package/templates/quiz/styles.css +1244 -622
  150. package/templates/quiz/template.json +9 -2
  151. package/templates/quiz/ui/templates/edit.d.ts +19 -5
  152. package/templates/quiz/ui/templates/edit.js +371 -77
  153. package/templates/quiz/ui/templates/group.js +19 -8
  154. package/templates/quiz/ui/templates/order.js +25 -24
  155. package/templates/quiz/ui/templates/page.js +33 -8
  156. package/templates/quiz/ui/templates/question.js +6 -4
  157. package/templates/quiz/ui/texts.js +91 -26
  158. package/templates/quiz/ui/theme.css +8 -9
  159. package/templates/steps/README.md +77 -0
  160. package/templates/steps/commentary.txt +7 -0
  161. package/templates/steps/edit.html +21 -0
  162. package/templates/steps/gitignore +4 -0
  163. package/templates/steps/index.html +69 -0
  164. package/templates/steps/metadata.json +9 -0
  165. package/templates/steps/package.json +13 -0
  166. package/templates/steps/screens/edit.js +32 -0
  167. package/templates/steps/screens/learn.js +108 -0
  168. package/templates/steps/styles.css +54 -0
  169. package/templates/steps/template.json +6 -0
@@ -2,8 +2,8 @@
2
2
  * @eliceio/cdk 1.x(EliceCDK)와 같은 공개 인터페이스를 가진 mock · 템플릿이 제공 (고치지 마세요)
3
3
  *
4
4
  * 서버 없이 화면을 시험할 때 키트가 대신 씁니다. 실제 SDK와 다른 점:
5
- * - 채점: 편집 화면이 저장한 채점 설정(settings.grading { type: pattern | rubric })이 있으면 로컬 채점, 없으면 제출만 받음.
6
- * pattern 답은 정규식 하나, 답 문자열 전체 일치. 프로젝트 폴더를 그대로 열면 ecdk dev가 저장한 .ecdk/settings.json으로 시작
5
+ * - 채점: 편집 화면이 저장한 채점 설정(settings.grading { type: pattern | partial_pattern | rubric })이 있으면 로컬 채점, 없으면 제출만 받음.
6
+ * pattern 답은 정규식 하나, 답 문자열 전체 일치. partial_pattern은 문항별 정규식 · 점수, 답은 문자열 배열. 프로젝트 폴더를 그대로 열면 ecdk dev가 저장한 .ecdk/settings.json으로 시작
7
7
  * - 완료 정책: 흉내 내지 않는다 (LXP에 올린 뒤 자료 편집 화면의 '설정'에서 교육자가 고름, ADR 0012). material.completionPolicy는 null
8
8
  * - 저장: 설정 화면이 저장한 내용과 제출 기록을 브라우저에 남겨 다른 화면에서도 보임
9
9
  * (sandbox라 저장소가 막히면 이 페이지 안에서만)
@@ -14,6 +14,15 @@
14
14
  * 실제 SDK처럼 account · result는 null (edit 토큰은 /me를 부르지 않음)
15
15
  * 편집 화면이 넣은 settings.grading은 학생 화면의 material.settings에서 서버처럼 빼고 준다
16
16
  * - 수업 페이지 이동: 아무 데도 가지 않고, 이전·다음 페이지는 없음(false)
17
+ * - 자료 파일 (assets.post · get, 실제 SDK와 같은 모양 · 검사 · 오류 코드):
18
+ * ecdk dev 콘텐츠 주소를 직접 열었으면(window.__ECDK_DEV__.assets) 실제 SDK처럼 흉내 서버에 올리고(upload-url → PUT)
19
+ * 서버 모양 키 `assets/{자료 id}/{이름}`을 주며, get은 흉내 API asset_base_url + 키라 다른 화면에서도 열린다.
20
+ * 그 밖(서버 없음)은 이 페이지 메모리에만 둔다 (blob: 주소, 새로고침 · 다른 화면에서는 없음)
21
+ * - 동영상 플레이어: videoPlayerUrl · accessToken은 null (ecdk dev나 LXP에서 시험)
22
+ * - kvstore: settings처럼 이 브라우저에 보는 사람의 값을 최상위 key별로 둔다.
23
+ * 튜터는 쓸 수 없다(read_only_mode). 크기 · 쓰기 횟수 제한은 없음
24
+ * - mlapi (mlapi.fetch): mlapi를 부르지 않고, ecdk dev처럼 서버 오류 모양의 503 SERVICE_UNAVAILABLE
25
+ * (reason ai_not_configured)로 답한다 (AI 호출은 LXP에서 시험)
17
26
  * - 시나리오: 주소에 ?mock=session_expired | rate_limited | request_failed | external_service_error
18
27
  * | slow | content_not_ready | unauthorized | draft_not_ready
19
28
  *
@@ -37,6 +46,11 @@ export const ErrorCode = Object.freeze({
37
46
  NavigationTimeout: 'navigation_timeout',
38
47
  RequestFailed: 'request_failed',
39
48
  DraftNotSaved: 'draft_not_saved',
49
+ FileInvalidType: 'file_invalid_type',
50
+ FileInvalidSize: 'file_invalid_size',
51
+ ScriptLoadFailed: 'script_load_failed',
52
+ ScriptNamespaceNotFound: 'script_namespace_not_found',
53
+ StorageLimitExceeded: 'storage_limit_exceeded',
40
54
  });
41
55
 
42
56
  export class EliceCDKError extends Error {
@@ -48,6 +62,75 @@ export class EliceCDKError extends Error {
48
62
  }
49
63
 
50
64
  const VIEWERS = Object.freeze(['student', 'instructor', 'tutor']);
65
+ /** 자료 파일 한도 (실제 SDK와 같음): 문서 1바이트~95MB, 이미지 1바이트~10MB */
66
+ const MB = 1024 * 1024;
67
+ /** 실제 SDK처럼 파일 형식(MIME), 없으면 확장자로 종류를 정한다. SVG는 받지 않는다 */
68
+ const ASSET_KINDS = Object.freeze([
69
+ { extension: 'pdf', aliases: [], contentType: 'application/pdf', maxBytes: 95 * MB },
70
+ {
71
+ extension: 'pptx',
72
+ aliases: [],
73
+ contentType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
74
+ maxBytes: 95 * MB,
75
+ },
76
+ { extension: 'png', aliases: [], contentType: 'image/png', maxBytes: 10 * MB },
77
+ { extension: 'jpg', aliases: ['jpeg'], contentType: 'image/jpeg', maxBytes: 10 * MB },
78
+ { extension: 'webp', aliases: [], contentType: 'image/webp', maxBytes: 10 * MB },
79
+ { extension: 'gif', aliases: [], contentType: 'image/gif', maxBytes: 10 * MB },
80
+ ]);
81
+ /** mock이 올린 파일: 키 → blob: 주소 (이 페이지 메모리에만) */
82
+ const MOCK_ASSETS = new Map();
83
+ /** 서버 파일 키 모양: `assets/{자료 id}/{이름}.{확장자}` */
84
+ const FILE_KEY = /^assets\/[\w-]+\/[\w-]+\.(pdf|pptx|png|jpe?g|webp|gif)$/i;
85
+
86
+ /**
87
+ * ecdk dev가 알려 준 자료 파일 흉내 주소 (콘텐츠 주소를 직접 열어 mock으로 돌 때). 없으면 null.
88
+ * uploadUrl: 토큰 없이 쓰는 dev 전용 upload-url, baseUrl: 흉내 API의 asset_base_url (서명 경로까지)
89
+ * @returns {{ uploadUrl: string, baseUrl: string } | null}
90
+ */
91
+ function devAssets() {
92
+ const d = globalThis.__ECDK_DEV__?.assets;
93
+ return d && typeof d.uploadUrl === 'string' && typeof d.baseUrl === 'string' ? d : null;
94
+ }
95
+
96
+ /** ecdk dev 흉내 서버에 실제 SDK와 같은 흐름으로 올린다 (upload-url → PUT). 서버 파일 키를 돌려줌 */
97
+ async function uploadToDev(dev, file, kind, onProgress, signal) {
98
+ let target;
99
+ try {
100
+ const res = await fetch(dev.uploadUrl, {
101
+ method: 'POST',
102
+ headers: { 'Content-Type': 'application/json' },
103
+ body: JSON.stringify({
104
+ key: `asset.${kind.extension}`,
105
+ content_length: file.size,
106
+ content_type: kind.contentType,
107
+ }),
108
+ signal,
109
+ });
110
+ if (!res.ok) throw new Error(`upload-url ${res.status}`);
111
+ target = (await res.json())?.data;
112
+ const put = await fetch(target.upload_url, {
113
+ method: 'PUT',
114
+ headers: { 'Content-Type': kind.contentType, 'x-ms-blob-type': 'BlockBlob' },
115
+ body: file,
116
+ signal,
117
+ });
118
+ if (!put.ok) throw new Error(`PUT ${put.status}`);
119
+ } catch (e) {
120
+ if (signal?.aborted) throw signal.reason;
121
+ throw new EliceCDKError(ErrorCode.RequestFailed, 'Failed to upload the file (mock · ecdk dev).', e);
122
+ }
123
+ onProgress?.({ loaded: file.size, total: file.size });
124
+ return target.key;
125
+ }
126
+
127
+ /** 키의 주소: 이 페이지에서 올린 것(blob:), 아니면 ecdk dev 흉내 API asset_base_url + 키. 모르면 null */
128
+ function mockAssetUrl(id) {
129
+ const local = MOCK_ASSETS.get(id);
130
+ if (local) return local;
131
+ const dev = devAssets();
132
+ return dev && typeof id === 'string' && FILE_KEY.test(id) ? `${dev.baseUrl}${id}` : null;
133
+ }
51
134
  const MAX_ANSWER_BYTES = 64 * 1024;
52
135
  const STORE_PREFIX = 'elice-content-mock:';
53
136
  const MESSAGE_SOURCE = 'eliceio-content-sdk';
@@ -58,6 +141,9 @@ const DEFAULT_ENTRIES = Object.freeze({
58
141
  instructor: 'instructor.html',
59
142
  edit: 'edit.html',
60
143
  });
144
+ /** kvstore key: dot path of letters, digits, `_` or Korean, at most 256 characters (get also takes '' for every top-level key) */
145
+ const KV_KEY_PATTERN = /^[0-9A-Za-z_가-힣]+(?:\.[0-9A-Za-z_가-힣]+)*$/;
146
+ const KV_KEY_MAX_LENGTH = 256;
61
147
  /** rubric(AI) 채점 흉내 점수 */
62
148
  const RUBRIC_MOCK_SCORE = 80;
63
149
 
@@ -107,48 +193,115 @@ const answerText = answer =>
107
193
  typeof answer === 'string' ? answer.trim() : JSON.stringify(answer ?? null);
108
194
 
109
195
  /**
110
- * 채점 설정을 서버 모양(2026-11-11 결정)으로: `{ type: 'pattern', answer_key }` · `{ type: 'rubric', rubric }`.
196
+ * 채점 설정을 서버 모양(2026-11-11 결정)으로: `{ type: 'pattern', answer_key }` ·
197
+ * `{ type: 'partial_pattern', answer_key: string[], scores: number[] }` · `{ type: 'rubric', rubric }`.
111
198
  * camelCase(answerKey)도 받는다. 채점 방식이 아니면 null
112
199
  */
113
200
  export function normalizeGradingSettings(grading) {
114
201
  if (!grading || typeof grading !== 'object') return null;
115
- if (grading.type === 'pattern') {
116
- const answerKey = grading.answer_key ?? grading.answerKey;
202
+ const answerKey = grading.answer_key ?? grading.answerKey;
203
+ if (grading.type === 'pattern')
117
204
  return { type: 'pattern', ...(typeof answerKey === 'string' ? { answer_key: answerKey } : {}) };
118
- }
205
+ if (grading.type === 'partial_pattern')
206
+ return {
207
+ type: 'partial_pattern',
208
+ answer_key: Array.isArray(answerKey) ? [...answerKey] : [],
209
+ scores: Array.isArray(grading.scores) ? [...grading.scores] : [],
210
+ };
119
211
  if (grading.type === 'rubric')
120
212
  return { type: 'rubric', ...(typeof grading.rubric === 'string' ? { rubric: grading.rubric } : {}) };
121
213
  return null;
122
214
  }
123
215
 
216
+ /** 서버(Python re) 맨 앞 전체 플래그 (?i) · (?s) · (?m): JS는 받지 않아 떼고 같은 JS 플래그로 (키트 toJsRegex와 같음) */
217
+ const LEADING_FLAGS = /^\(\?([ims]+)\)/;
218
+
219
+ /** 정답 정규식이 답 문자열(앞뒤 공백을 자름) 전체와 맞는지 (서버 re.fullmatch와 같은 판정). 정규식이 틀리면 false */
220
+ function fullMatch(regex, text) {
221
+ if (typeof regex !== 'string') return false;
222
+ try {
223
+ const m = LEADING_FLAGS.exec(regex);
224
+ const source = m ? regex.slice(m[0].length) : regex;
225
+ const flags = m ? [...new Set(m[1])].join('') : '';
226
+ return new RegExp(`^(?:${source})$`, flags).test(text.trim());
227
+ } catch {
228
+ return false;
229
+ }
230
+ }
231
+
232
+ /**
233
+ * 채점 전에 서버가 거절하는 답 (422): partial_pattern은 답이 문자열 배열이어야 한다. 문제가 없으면 null
234
+ * @param {object | null} grading settings.grading
235
+ * @param {unknown} answer
236
+ */
237
+ export function answerShapeError(grading, answer) {
238
+ if (normalizeGradingSettings(grading)?.type !== 'partial_pattern') return null;
239
+ if (!Array.isArray(answer)) return 'partial_pattern: answer must be an array of strings';
240
+ const bad = answer.findIndex(item => typeof item !== 'string');
241
+ return bad < 0 ? null : `partial_pattern: answer[${bad}] must be a string`;
242
+ }
243
+
124
244
  /**
125
245
  * elice-material 채점 흉내 (채점 방식 → 점수). 실제 서버처럼 요청 안에서 바로 채점한 `{ isCorrect, score }`만
126
246
  * 돌려준다. 완료 정책은 LXP 설정이라 보지 않는다 (ADR 0012): 채점 설정이 있으면 채점하고, 없으면 제출만 받는다.
127
247
  * - pattern: 정답 정규식(문자열 하나)이 답 문자열 전체와 맞으면 100, 아니면 0
248
+ * - partial_pattern: answer[i]를 answer_key[i]에 맞춰 맞은 문항의 scores[i]를 더함 (최대 100, 100점만 정답).
249
+ * 없는 문항은 0점, 남는 답은 무시. 문항별 맞음 answerCorrectness도 (submit · 제출 기록에는 그 밖의 방식이면 [])
128
250
  * - rubric: 바로 80점으로 흉내, 통과로 봄 (통과 기준 pass_threshold는 정해지지 않음)
129
251
  * - 채점 설정 없음: 점수 없음 `{ isCorrect: null, score: null }`
252
+ * 맨 앞 (?i)는 서버(Python re)처럼 대소문자 무시
130
253
  * @param {object | null} grading settings.grading
131
254
  * @param {unknown} answer
132
255
  */
133
256
  export function gradeLocally(grading, answer) {
134
257
  const g = normalizeGradingSettings(grading);
135
258
  if (g?.type === 'pattern') {
136
- let ok = false;
137
- try {
138
- ok =
139
- typeof g.answer_key === 'string' &&
140
- new RegExp(`^(?:${g.answer_key})$`).test(answerText(answer));
141
- } catch {
142
- ok = false;
143
- }
259
+ const ok = fullMatch(g.answer_key, answerText(answer));
144
260
  return { isCorrect: ok, score: ok ? 100 : 0 };
145
261
  }
262
+ if (g?.type === 'partial_pattern') {
263
+ const items = Array.isArray(answer) ? answer : [];
264
+ const answerCorrectness = g.answer_key.map((key, i) => typeof items[i] === 'string' && fullMatch(key, items[i]));
265
+ const total = answerCorrectness.reduce((sum, ok, i) => sum + (ok ? (g.scores[i] ?? 0) : 0), 0);
266
+ const score = Math.min(100, total);
267
+ return { isCorrect: score === 100, score, answerCorrectness };
268
+ }
146
269
  if (g?.type === 'rubric') return { isCorrect: true, score: RUBRIC_MOCK_SCORE };
147
270
  return { isCorrect: null, score: null };
148
271
  }
149
272
 
150
273
  const sleep = ms => new Promise(r => setTimeout(r, ms));
151
274
 
275
+ function assertKvKey(key) {
276
+ if (typeof key !== 'string' || key.length > KV_KEY_MAX_LENGTH || !KV_KEY_PATTERN.test(key))
277
+ throw new EliceCDKError(ErrorCode.InvalidParam, `Invalid key "${key}".`);
278
+ }
279
+
280
+ /** Value at the dot path ('' = every top-level key as { key: value }), null when missing */
281
+ function kvRead(doc, key) {
282
+ let value = doc;
283
+ for (const part of key ? key.split('.') : [])
284
+ value = value && typeof value === 'object' && !Array.isArray(value) ? value[part] : undefined;
285
+ return value ?? null;
286
+ }
287
+
288
+ /** New document with the value at the dot path. Like the server, a value on the path that is not an object (null included) is invalid_input */
289
+ function kvWrite(doc, key, value) {
290
+ const stored = JSON.parse(JSON.stringify(value ?? null));
291
+ const next = structuredClone(doc ?? {});
292
+ const parts = key.split('.');
293
+ const last = parts.pop();
294
+ let parent = next;
295
+ for (const part of parts) {
296
+ parent[part] ??= {};
297
+ if (!parent[part] || typeof parent[part] !== 'object' || Array.isArray(parent[part]))
298
+ throw new EliceCDKError(ErrorCode.InvalidInput, `"${part}" on the key path is not an object (mock).`);
299
+ parent = parent[part];
300
+ }
301
+ parent[last] = stored;
302
+ return next;
303
+ }
304
+
152
305
  /**
153
306
  * @typedef {object} MockOptions
154
307
  * @property {() => void} [onSessionExpired]
@@ -178,6 +331,9 @@ export class MockEliceCDK {
178
331
  /** draft의 제출은 실제 SDK처럼 메모리에만 */
179
332
  #draftSubmissions = [];
180
333
  #navigation;
334
+ #assets;
335
+ #kvstore;
336
+ #mlapi;
181
337
 
182
338
  /** @param {MockOptions} [options] */
183
339
  constructor(options = {}) {
@@ -206,6 +362,99 @@ export class MockEliceCDK {
206
362
  return false;
207
363
  },
208
364
  });
365
+ this.#assets = Object.freeze({
366
+ post: async (file, { onProgress, signal } = {}) => {
367
+ this.#assertReady();
368
+ this.#assertScreen('edit');
369
+ if (this.#isDraft)
370
+ throw new EliceCDKError(
371
+ ErrorCode.DraftNotSaved,
372
+ 'Files cannot be uploaded to an unsaved upload (mock).'
373
+ );
374
+ const extension = String(file?.name ?? '').split('.').pop()?.toLowerCase();
375
+ const kind =
376
+ ASSET_KINDS.find((k) => k.contentType === file?.type) ??
377
+ ASSET_KINDS.find((k) => k.extension === extension || k.aliases.includes(extension));
378
+ if (!kind)
379
+ throw new EliceCDKError(
380
+ ErrorCode.FileInvalidType,
381
+ 'Only PDF, PPTX, PNG, JPEG, WebP and GIF files can be uploaded (mock).'
382
+ );
383
+ if (!(file.size >= 1) || file.size > kind.maxBytes)
384
+ throw new EliceCDKError(
385
+ ErrorCode.FileInvalidSize,
386
+ `The file must be between 1 byte and ${kind.maxBytes / MB}MB (mock).`
387
+ );
388
+ if (signal?.aborted) throw signal.reason;
389
+ await this.#delay();
390
+ if (signal?.aborted) throw signal.reason;
391
+ const dev = devAssets();
392
+ let id;
393
+ if (dev) id = await uploadToDev(dev, file, kind, onProgress, signal);
394
+ else {
395
+ // 실제 서버처럼 파일 키 `assets/{자료 id}/{이름}`
396
+ id = `assets/mock/mock-${(MOCK_ASSETS.size + 1).toString(36)}-${Date.now().toString(36)}.${kind.extension}`;
397
+ MOCK_ASSETS.set(id, URL.createObjectURL(file));
398
+ onProgress?.({ loaded: file.size, total: file.size });
399
+ }
400
+ return { id, name: file.name, size: file.size, mime: kind.contentType, url: mockAssetUrl(id) ?? '' };
401
+ },
402
+ get: async (id) => {
403
+ const url = this.initialized ? mockAssetUrl(id) : null;
404
+ return url == null ? null : { id, url };
405
+ },
406
+ });
407
+ // The viewer's values in this material, kept in the browser store ('kv': { key: value })
408
+ this.#kvstore = Object.freeze({
409
+ get: async ({ key }) => {
410
+ this.#assertReady();
411
+ if (key !== '') assertKvKey(key);
412
+ await this.#delay();
413
+ return kvRead(this.#store.get('kv', null) ?? {}, key);
414
+ },
415
+ post: async ({ key, value }) => {
416
+ this.#assertReady();
417
+ assertKvKey(key);
418
+ if (this.#viewer === 'tutor')
419
+ throw new EliceCDKError(ErrorCode.ReadOnlyMode, 'A tutor cannot save values (mock).');
420
+ await this.#delay();
421
+ this.#store.set('kv', kvWrite(this.#store.get('kv', null), key, value));
422
+ },
423
+ delete: async key => {
424
+ this.#assertReady();
425
+ assertKvKey(key);
426
+ if (this.#viewer === 'tutor')
427
+ throw new EliceCDKError(ErrorCode.ReadOnlyMode, 'A tutor cannot delete values (mock).');
428
+ await this.#delay();
429
+ const parts = key.split('.');
430
+ const last = parts.pop();
431
+ const next = structuredClone(this.#store.get('kv', null) ?? {});
432
+ const parent = kvRead(next, parts.join('.'));
433
+ if (parent && typeof parent === 'object' && !Array.isArray(parent)) delete parent[last];
434
+ this.#store.set('kv', next);
435
+ },
436
+ });
437
+
438
+ this.#mlapi = Object.freeze({
439
+ // There is no mlapi locally: answer like a server without AI (503 ai_not_configured).
440
+ fetch: async (_input, _init) => {
441
+ this.#assertReady();
442
+ const message = 'AI calls are not available in the mock. Try them in LXP.';
443
+ return new Response(
444
+ JSON.stringify({
445
+ data: null,
446
+ meta: {
447
+ error: {
448
+ code: 'SERVICE_UNAVAILABLE',
449
+ message,
450
+ details: [{ type: 'app_exception_detail', msg: message, ctx: { reason: 'ai_not_configured' } }],
451
+ },
452
+ },
453
+ }),
454
+ { status: 503, headers: { 'Content-Type': 'application/json' } }
455
+ );
456
+ },
457
+ });
209
458
  }
210
459
 
211
460
  get account() {
@@ -236,6 +485,28 @@ export class MockEliceCDK {
236
485
  get navigation() {
237
486
  return this.#navigation;
238
487
  }
488
+ /** 자료 파일 올리기 · 읽기 (위 머리말: ecdk dev 흉내 서버, 아니면 이 페이지 메모리) */
489
+ get assets() {
490
+ return this.#assets;
491
+ }
492
+ /** The viewer's values in this material (get · post · delete), kept in this browser */
493
+ get kvstore() {
494
+ return this.#kvstore;
495
+ }
496
+ /** Calls mlapi. The mock calls nothing and answers 503 ai_not_configured. */
497
+ get mlapi() {
498
+ return this.#mlapi;
499
+ }
500
+ get accessToken() {
501
+ return null;
502
+ }
503
+ get videoPlayerUrl() {
504
+ return null;
505
+ }
506
+ /** No new token ever arrives in the mock. */
507
+ onAccessTokenChange(_listener) {
508
+ return () => {};
509
+ }
239
510
  get material() {
240
511
  if (!this.initialized) return null;
241
512
  // 서버처럼 학생 · 튜터 · 교육자(learn scope)에게는 settings.grading(정답)을 빼고 준다
@@ -344,7 +615,12 @@ export class MockEliceCDK {
344
615
  throw new EliceCDKError(ErrorCode.InvalidInput, 'Answer is over 64KB.');
345
616
  await this.#delay();
346
617
 
347
- const res = gradeLocally(this.#effectiveGrading(), answer);
618
+ const shapeError = answerShapeError(this.#effectiveGrading(), answer);
619
+ // 실제 SDK는 서버 422(VALIDATION_ERROR)를 RequestFailed로 던진다
620
+ if (shapeError) throw new EliceCDKError(ErrorCode.RequestFailed, `${shapeError} (mock 422).`);
621
+ // 서버처럼 문항별 맞음은 늘 준다: partial_pattern이 아니면 []
622
+ const graded = gradeLocally(this.#effectiveGrading(), answer);
623
+ const res = { ...graded, answerCorrectness: graded.answerCorrectness ?? [] };
348
624
  if (this.#isDraft) this.#draftSubmissions.unshift(this.#submission(answer, res, 'preview'));
349
625
  else if (this.#viewer === 'student') this.#record(res, answer);
350
626
  return res;
@@ -413,6 +689,7 @@ export class MockEliceCDK {
413
689
  this.#store.set('settings', {});
414
690
  this.#store.set('submissions', []);
415
691
  this.#store.set('result', null);
692
+ this.#store.set('kv', null);
416
693
  this.#draftSubmissions = [];
417
694
  }
418
695
 
@@ -444,6 +721,7 @@ export class MockEliceCDK {
444
721
  answer,
445
722
  isCorrect: res.isCorrect,
446
723
  score: res.score,
724
+ answerCorrectness: res.answerCorrectness ?? [],
447
725
  };
448
726
  }
449
727