@eliceio/cdk-cli 0.0.0-stage → 0.1.0-alpha.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 (128) hide show
  1. package/README.md +511 -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 +171 -0
  6. package/es/commands/build/index.d.ts +27 -0
  7. package/es/commands/build/index.js +154 -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 +33 -0
  17. package/es/commands/doctor/index.js +230 -0
  18. package/es/core/collect.d.ts +21 -0
  19. package/es/core/collect.js +89 -0
  20. package/es/core/config.d.ts +55 -0
  21. package/es/core/config.js +109 -0
  22. package/es/core/manifest.d.ts +15 -0
  23. package/es/core/manifest.js +43 -0
  24. package/es/core/minify.d.ts +18 -0
  25. package/es/core/minify.js +93 -0
  26. package/es/core/prepare.d.ts +12 -0
  27. package/es/core/prepare.js +86 -0
  28. package/es/core/protocol.d.ts +2 -0
  29. package/es/core/protocol.js +4 -0
  30. package/es/core/zip.d.ts +4 -0
  31. package/es/core/zip.js +17 -0
  32. package/es/dev/grading.d.ts +15 -0
  33. package/es/dev/grading.js +37 -0
  34. package/es/dev/host-page.d.ts +7 -0
  35. package/es/dev/host-page.js +240 -0
  36. package/es/dev/inject.d.ts +8 -0
  37. package/es/dev/inject.js +38 -0
  38. package/es/dev/mock-api.d.ts +65 -0
  39. package/es/dev/mock-api.js +269 -0
  40. package/es/dev/server.d.ts +24 -0
  41. package/es/dev/server.js +294 -0
  42. package/es/engines/static/index.d.ts +3 -0
  43. package/es/engines/static/index.js +11 -0
  44. package/es/engines/types.d.ts +12 -0
  45. package/es/engines/vite/index.d.ts +2 -0
  46. package/es/engines/vite/index.js +4 -0
  47. package/es/index.d.ts +2 -0
  48. package/es/index.js +2 -0
  49. package/es/rules/check.d.ts +2 -0
  50. package/es/rules/check.js +209 -0
  51. package/es/rules/index.d.ts +8 -0
  52. package/es/rules/index.js +7 -0
  53. package/es/rules/manifest.d.ts +39 -0
  54. package/es/rules/manifest.js +168 -0
  55. package/es/rules/node.d.ts +11 -0
  56. package/es/rules/node.js +87 -0
  57. package/es/rules/path.d.ts +7 -0
  58. package/es/rules/path.js +35 -0
  59. package/es/rules/refs.d.ts +19 -0
  60. package/es/rules/refs.js +111 -0
  61. package/es/rules/skip.d.ts +12 -0
  62. package/es/rules/skip.js +55 -0
  63. package/es/rules/spec.d.ts +3 -0
  64. package/es/rules/spec.js +6 -0
  65. package/es/rules/types.d.ts +138 -0
  66. package/es/rules/unused.d.ts +7 -0
  67. package/es/rules/unused.js +21 -0
  68. package/es/rules/zip.d.ts +13 -0
  69. package/es/rules/zip.js +45 -0
  70. package/es/rules.json.js +3 -0
  71. package/es/types.d.ts +4 -0
  72. package/es/version.d.ts +1 -0
  73. package/es/version.js +3 -0
  74. package/package.json +48 -3
  75. package/rules.json +555 -0
  76. package/templates/_shared/lib/cdk-mock.d.ts +94 -0
  77. package/templates/_shared/lib/cdk-mock.js +429 -0
  78. package/templates/_shared/lib/cdk.js +3 -0
  79. package/templates/_shared/lib/elice-content.css +252 -0
  80. package/templates/_shared/lib/elice-content.d.ts +121 -0
  81. package/templates/_shared/lib/elice-content.js +541 -0
  82. package/templates/_shared/lib/elice-tokens.css +446 -0
  83. package/templates/blank/README.md +64 -0
  84. package/templates/blank/content.json +4 -0
  85. package/templates/blank/edit.html +15 -0
  86. package/templates/blank/elice.config.json +12 -0
  87. package/templates/blank/gitignore +3 -0
  88. package/templates/blank/index.html +15 -0
  89. package/templates/blank/instructor.html +15 -0
  90. package/templates/blank/screens/edit.js +21 -0
  91. package/templates/blank/screens/instructor.js +9 -0
  92. package/templates/blank/screens/learn.js +19 -0
  93. package/templates/blank/styles.css +1 -0
  94. package/templates/quiz/README.md +108 -0
  95. package/templates/quiz/content.json +81 -0
  96. package/templates/quiz/core/behaviors.d.ts +59 -0
  97. package/templates/quiz/core/behaviors.js +309 -0
  98. package/templates/quiz/core/dom.d.ts +13 -0
  99. package/templates/quiz/core/dom.js +83 -0
  100. package/templates/quiz/core/editor.d.ts +48 -0
  101. package/templates/quiz/core/editor.js +206 -0
  102. package/templates/quiz/core/markdown.d.ts +2 -0
  103. package/templates/quiz/core/markdown.js +84 -0
  104. package/templates/quiz/core/model.d.ts +20 -0
  105. package/templates/quiz/core/model.js +203 -0
  106. package/templates/quiz/edit.html +17 -0
  107. package/templates/quiz/elice.config.json +14 -0
  108. package/templates/quiz/gitignore +3 -0
  109. package/templates/quiz/grading.json +13 -0
  110. package/templates/quiz/index.html +17 -0
  111. package/templates/quiz/instructor.html +17 -0
  112. package/templates/quiz/screens/edit.js +139 -0
  113. package/templates/quiz/screens/instructor.js +27 -0
  114. package/templates/quiz/screens/learn.js +50 -0
  115. package/templates/quiz/styles.css +510 -0
  116. package/templates/quiz/ui/templates/choice.js +22 -0
  117. package/templates/quiz/ui/templates/edit.d.ts +14 -0
  118. package/templates/quiz/ui/templates/edit.js +187 -0
  119. package/templates/quiz/ui/templates/group.js +47 -0
  120. package/templates/quiz/ui/templates/index.d.ts +5 -0
  121. package/templates/quiz/ui/templates/index.js +17 -0
  122. package/templates/quiz/ui/templates/order.js +35 -0
  123. package/templates/quiz/ui/templates/page.js +29 -0
  124. package/templates/quiz/ui/templates/question.js +28 -0
  125. package/templates/quiz/ui/templates/text.js +16 -0
  126. package/templates/quiz/ui/texts.d.ts +3 -0
  127. package/templates/quiz/ui/texts.js +128 -0
  128. package/templates/quiz/ui/theme.css +50 -0
@@ -0,0 +1,541 @@
1
+ /**
2
+ * Elice Content 화면 키트 · 템플릿이 제공하는 로직 (이 파일은 고치지 마세요)
3
+ *
4
+ * 화면은 누가 보는지(학생 · 교육자 · 튜터)나 미리보기인지 몰라도 됩니다.
5
+ * 학생 화면: app.useSubmit({ getAnswer, setAnswer, validate })
6
+ * 편집 화면: app.useSave({ getContent, validate })
7
+ * 상태 표시, 읽기 전용 잠금, 답 복원, 결과·오류 안내, 저장 문구는 키트가 합니다.
8
+ *
9
+ * 화면(screens/*.js)은 이 키트만 부릅니다. 키트가 SDK로 인증 · 화면 확인 · 내용 불러오기 ·
10
+ * 제출 · 저장 · 오류 안내를 처리합니다. SDK는 둘 중 하나를 자동으로 고릅니다.
11
+ *
12
+ * real lib/cdk.js (@eliceio/cdk 1.x) 플랫폼에서 열 때 (#token=, 편집기 #preview=1 · #edit=1)
13
+ * mock lib/cdk-mock.js (같은 인터페이스) 그 밖 (로컬): 로컬 채점, 화면 사이 저장 공유
14
+ *
15
+ * 바꾸기: 주소에 ?sdk=mock 또는 ?sdk=real, 또는 start({ screen, sdk: 'mock' })
16
+ * 로컬에서 보는 사람 바꾸기 (mock): #viewer=tutor (student · instructor · tutor), 미리보기: #preview=1
17
+ *
18
+ * import { start } from '../lib/elice-content.js';
19
+ * const app = await start({ screen: 'learn' });
20
+ * app.content // 편집 화면(CMS)이 저장한 내용, 없으면 content.json
21
+ * await app.submit(answer)
22
+ *
23
+ * 정답은 콘텐츠에 넣지 않습니다. 채점은 서버가 편집 화면의 채점 설정으로 합니다.
24
+ */
25
+
26
+ /**
27
+ * 이 HTML(metadata.json의 learn · instructor · edit)을 SDK가 알려 준 화면 · 보는 사람으로 열어도 되는지.
28
+ * 학생 · 교육자 화면은 learn · instructor 어느 쪽이든 된다: draft 미리보기(#preview=1)는 늘 learn이고,
29
+ * 파일 하나로 두 화면을 같이 쓸 수도 있다. 교육자 화면은 교육자만 본다.
30
+ */
31
+ const SCREEN_ALLOWED = {
32
+ learn: (sdk) => sdk.screen === 'learn' || sdk.screen === 'instructor',
33
+ instructor: (sdk) =>
34
+ (sdk.screen === 'learn' || sdk.screen === 'instructor') && sdk.viewer === 'instructor',
35
+ edit: (sdk) => sdk.screen === 'edit',
36
+ };
37
+
38
+ const MESSAGES = {
39
+ session_expired: '접속 시간이 지났습니다. 페이지를 새로고침해 주세요.',
40
+ unauthorized: '접속 정보가 올바르지 않습니다. 페이지를 새로고침해 주세요.',
41
+ read_only_mode: '보기 전용 화면이라 제출할 수 없습니다.',
42
+ rate_limited: '제출이 너무 잦습니다. 잠시 뒤 다시 시도해 주세요.',
43
+ invalid_input: '답이 너무 크거나 형식이 올바르지 않습니다.',
44
+ content_not_ready: '아직 저장된 자료가 없습니다.',
45
+ external_service_error: '채점하지 못했어요. 제출이 저장되지 않았으니 다시 제출해 주세요.',
46
+ screen_not_supported: '이 화면에서는 할 수 없는 일입니다.',
47
+ navigation_timeout: '수업 페이지 정보를 받지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
48
+ permission_denied: '권한이 없습니다.',
49
+ not_initialized: '아직 준비되지 않았습니다.',
50
+ request_failed: '서버와 연결하지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
51
+ // 키트만의 코드: 자료 주소인데 접속 토큰이 없음 (새로고침 · 다른 HTML로 이동하면 SDK가 지운 토큰이 남지 않는다)
52
+ reopen_required:
53
+ '자료를 다시 열어 주세요. 새로고침하거나 다른 페이지로 옮기면 다시 열어야 합니다.',
54
+ };
55
+
56
+ export class ContentError extends Error {
57
+ /**
58
+ * @param {string} code
59
+ * @param {string} message
60
+ * @param {unknown} [cause]
61
+ */
62
+ constructor(code, message, cause) {
63
+ super(message, { cause });
64
+ this.name = 'ContentError';
65
+ this.code = code;
66
+ }
67
+ }
68
+
69
+ /** SDK 오류를 화면이 그대로 보여 줄 수 있는 한국어 메시지로 */
70
+ function toContentError(err) {
71
+ if (err instanceof ContentError) return err;
72
+ const code = typeof err?.code === 'string' ? err.code : 'request_failed';
73
+ return new ContentError(code, MESSAGES[code] ?? MESSAGES.request_failed, err);
74
+ }
75
+
76
+ const MATERIAL_PATH = /\/materials\/[0-9a-f-]{36}\//i;
77
+
78
+ /** 로컬 mock에서 화면별 기본 fragment (보는 사람 · 설정 화면) */
79
+ const LOCAL_MOCK_HASH = { learn: '', instructor: 'viewer=instructor', edit: 'edit=1' };
80
+
81
+ /** 토큰 없는 draft: 편집기 미리보기 · 설정 화면 */
82
+ const DRAFT_HASH = /(?:^#|&)(?:preview|edit)=1/;
83
+ const LAUNCH_HASH = /(?:^#|&)(?:token|preview|edit)=/;
84
+
85
+ const isLoopback = (h) => h === 'localhost' || h === '127.0.0.1' || h === '[::1]';
86
+
87
+ /**
88
+ * 어떤 SDK를 쓸지. ?sdk=가 있으면 그대로, 플랫폼 주소(토큰 · 편집기 미리보기)면 real, 그 밖은 mock.
89
+ * 자료 주소(/materials/{uuid}/)면 토큰이 없어도 real: SDK가 init 때 주소의 토큰을 지우므로 새로고침하거나
90
+ * 다른 HTML로 옮기면 토큰이 없다. 이때 mock으로 바꾸면 제출이 저장되지 않으므로, real로 두고 start가
91
+ * "다시 열어 주세요"를 보여 준다. 로컬(localhost · 127.0.0.1)은 개발 편의로 mock (운영 주소는 로컬이 아님).
92
+ * @param {{ hash: string, pathname: string, search: string, hostname?: string }} where
93
+ * @returns {'real' | 'mock'}
94
+ */
95
+ export function pickSdk({ hash, pathname, search, hostname = '' }) {
96
+ const forced = new URLSearchParams(search).get('sdk');
97
+ if (forced === 'mock' || forced === 'real') return forced;
98
+ if (/(?:^#|&)token=/.test(hash)) return 'real';
99
+ if (DRAFT_HASH.test(hash) && MATERIAL_PATH.test(pathname)) return 'real';
100
+ if (MATERIAL_PATH.test(pathname) && !isLoopback(hostname)) return 'real';
101
+ return 'mock';
102
+ }
103
+
104
+ /** mock: 주소에 보는 사람 · 미리보기 · 설정 화면이 없으면 화면에 맞게 */
105
+ function mockLaunch(hash, screen) {
106
+ if (/(?:^#|&)(?:viewer|preview|edit)=/.test(hash)) return { hash, pathname: '/', local: true };
107
+ const parts = [LOCAL_MOCK_HASH[screen], hash.replace(/^#/, '')].filter(Boolean);
108
+ return { hash: parts.length ? `#${parts.join('&')}` : '', pathname: '/', local: true };
109
+ }
110
+
111
+ /**
112
+ * ecdk dev가 넣어 준 흉내 서버 주소. 로컬(localhost · 127.0.0.1)에서 열었을 때만 따른다:
113
+ * 운영 콘텐츠에서 누군가 이 값을 바꿔도 토큰이 다른 서버로 가지 않게
114
+ */
115
+ function devApi() {
116
+ const api = globalThis.__ECDK_DEV__?.api;
117
+ const host = typeof location === 'undefined' ? '' : location.hostname;
118
+ if (typeof api !== 'string' || !isLoopback(host)) return {};
119
+ try {
120
+ return isLoopback(new URL(api).hostname) ? { baseUrl: api } : {};
121
+ } catch {
122
+ return {};
123
+ }
124
+ }
125
+
126
+ /** 실제 SDK 파일은 필요할 때만 불러온다 (mock이면 받지 않음) */
127
+ async function loadRealSdk() {
128
+ if (globalThis.elice?.EliceCDK) return globalThis.elice.EliceCDK;
129
+ await new Promise((resolve, reject) => {
130
+ const script = document.createElement('script');
131
+ script.src = new URL('./cdk.js', import.meta.url).href;
132
+ script.onload = resolve;
133
+ script.onerror = () =>
134
+ reject(
135
+ new ContentError('request_failed', 'SDK 파일(lib/cdk.js)을 불러오지 못했습니다.'),
136
+ );
137
+ document.head.append(script);
138
+ });
139
+ return globalThis.elice.EliceCDK;
140
+ }
141
+
142
+ /** 로컬에서 열 때 SDK에 넘기는 자료 경로. SDK는 주소의 /materials/{uuid}/에서 자료 id를 읽는다 */
143
+ export const LOCAL_MATERIAL_PATH = '/materials/00000000-0000-0000-0000-000000000000/local/';
144
+
145
+ /**
146
+ * 토큰 없이 열면(파일을 직접 열거나 로컬 서버) draft로 연다: 설정 화면은 #edit=1, 그 밖은 #preview=1.
147
+ * 제출은 SDK가 흉내 내고 아무것도 저장하지 않는다.
148
+ * @param {string} hash
149
+ * @param {string} pathname
150
+ * @param {string} screen
151
+ * @returns {{ hash: string, pathname: string, local: boolean }}
152
+ */
153
+ export function resolveLaunch(hash, pathname, screen) {
154
+ if (LAUNCH_HASH.test(hash)) {
155
+ // 편집기의 draft(#preview=1 · #edit=1)는 경로에 자료 id가 있다. 없으면 로컬
156
+ const local = !MATERIAL_PATH.test(pathname);
157
+ return { hash, pathname: local ? LOCAL_MATERIAL_PATH : pathname, local };
158
+ }
159
+ return {
160
+ hash: screen === 'edit' ? '#edit=1' : '#preview=1',
161
+ pathname: LOCAL_MATERIAL_PATH,
162
+ local: true,
163
+ };
164
+ }
165
+
166
+ /**
167
+ * @typedef {object} StartOptions
168
+ * @property {'learn' | 'instructor' | 'edit'} screen 이 HTML이 어떤 화면인지
169
+ * @property {string} [defaults] 저장된 내용이 없을 때 쓸 내용 파일 (기본 'content.json')
170
+ * @property {(error: ContentError) => void} [onError] 화면 밖 오류(세션 만료 등)를 받을 함수. 기본은 상단 알림
171
+ * @property {'real' | 'mock' | object} [sdk] SDK 고르기 (기본: pickSdk). 객체면 그대로 씀 (테스트)
172
+ * @property {object} [mock] mock 옵션 (scenario, grading, settings, delayMs)
173
+ * @property {(url: string) => Promise<unknown>} [loadJson] 테스트용
174
+ * @property {string} [hash] 테스트용: location.hash 대신
175
+ * @property {string} [pathname] 테스트용: location.pathname 대신
176
+ * @property {string} [search] 테스트용: location.search 대신
177
+ * @property {string} [hostname] 테스트용: location.hostname 대신
178
+ * @property {boolean} [status] 화면 맨 위 상태 표시 (기본 true)
179
+ */
180
+
181
+ /**
182
+ * @param {StartOptions} options
183
+ */
184
+ export async function start(options) {
185
+ const { screen, defaults = 'content.json' } = options;
186
+ if (!SCREEN_ALLOWED[screen]) throw new Error(`알 수 없는 화면: ${screen}`);
187
+ const notify = options.onError ?? showBanner;
188
+
189
+ const hash = options.hash ?? (typeof location === 'undefined' ? '' : location.hash);
190
+ const pathname = options.pathname ?? (typeof location === 'undefined' ? '/' : location.pathname);
191
+ const search = options.search ?? (typeof location === 'undefined' ? '' : location.search);
192
+ const hostname = options.hostname ?? (typeof location === 'undefined' ? '' : location.hostname);
193
+ const kind =
194
+ typeof options.sdk === 'object' && options.sdk !== null
195
+ ? 'custom'
196
+ : (options.sdk ?? pickSdk({ hash, pathname, search, hostname }));
197
+ // 자료 주소인데 토큰 · 미리보기가 없으면 실제 SDK는 열 수 없다: mock으로 속이지 않고 다시 열라고 안내
198
+ if (kind === 'real' && !LAUNCH_HASH.test(hash) && MATERIAL_PATH.test(pathname)) {
199
+ const e = new ContentError('reopen_required', MESSAGES.reopen_required);
200
+ notify(e);
201
+ throw e;
202
+ }
203
+ const launch = kind === 'mock' ? mockLaunch(hash, screen) : resolveLaunch(hash, pathname, screen);
204
+ const onSessionExpired = () =>
205
+ notify(new ContentError('session_expired', MESSAGES.session_expired));
206
+
207
+ let sdk;
208
+ try {
209
+ if (kind === 'custom') sdk = options.sdk;
210
+ else if (kind === 'mock') {
211
+ const { MockEliceCDK } = await import('./cdk-mock.js');
212
+ sdk = new MockEliceCDK({ onSessionExpired, loadJson: options.loadJson, ...options.mock });
213
+ } else sdk = new (await loadRealSdk())({ onSessionExpired, ...devApi() });
214
+ if (kind === 'mock' && typeof console !== 'undefined')
215
+ console.info(
216
+ '[elice-content] mock SDK 사용 중 (실제 서버에 저장되지 않음). 실제 SDK: ?sdk=real',
217
+ );
218
+ } catch (err) {
219
+ const e = toContentError(err);
220
+ notify(e);
221
+ throw e;
222
+ }
223
+
224
+ try {
225
+ await sdk.init({ hash: launch.hash, pathname: launch.pathname });
226
+ if (options.hash === undefined && typeof history !== 'undefined' && /token=/.test(hash)) {
227
+ history.replaceState(null, '', location.pathname + location.search);
228
+ }
229
+ } catch (err) {
230
+ const e = toContentError(err);
231
+ notify(e);
232
+ throw e;
233
+ }
234
+
235
+ const { scope, viewer } = sdk;
236
+ if (!SCREEN_ALLOWED[screen](sdk)) {
237
+ const e = new ContentError(
238
+ 'screen_not_supported',
239
+ `이 파일은 ${screen} 화면인데 ${sdk.screen} 화면(보는 사람 ${viewer})으로 열렸습니다. metadata.json의 진입 파일을 확인해 주세요.`,
240
+ );
241
+ notify(e);
242
+ throw e;
243
+ }
244
+
245
+ const saved = sdk.material?.settings;
246
+ const loadJson = options.loadJson ?? ((url) => fetch(url).then((r) => (r.ok ? r.json() : {})));
247
+ let content =
248
+ saved && Object.keys(saved).length > 0 ? saved : await loadJson(defaults).catch(() => ({}));
249
+
250
+ const readOnly = viewer === 'tutor';
251
+ const app = {
252
+ /** 이 HTML이 어떤 화면인지 (start에 넘긴 값) */
253
+ screen,
254
+ /** 어느 페이지가 열었나: learn · edit (화면 코드는 보통 몰라도 됨: useSubmit · useSave가 처리) */
255
+ scope,
256
+ /** 누가 보나: student · instructor · tutor */
257
+ viewer,
258
+ /** 튜터가 학생 화면을 보는 중 */
259
+ readOnly,
260
+ /** 편집기가 토큰 없이 연 draft (#preview=1 · #edit=1). 서버에 아무것도 저장하지 않음 */
261
+ isDraft: Boolean(sdk.isDraft),
262
+ /** 수업 페이지 이동 (previous · next · navigate · getHasPrevious · getHasNext) */
263
+ navigation: sdk.navigation ?? null,
264
+ /** 플랫폼 밖(로컬 파일·로컬 서버)에서 연 미리보기 */
265
+ isLocal: launch.local,
266
+ /** 쓰고 있는 SDK: 'real' | 'mock' | 'custom' */
267
+ sdkKind: kind,
268
+ /** 보는 사람 { anonymousId, fullname } */
269
+ account: sdk.account,
270
+ /** 내 결과 { score(가장 최근 채점), submitCount, completedAt } 또는 null */
271
+ result: sdk.result,
272
+ /** 제출이 기록되는지 (학생만, draft · mock 제외) */
273
+ get records() {
274
+ return viewer === 'student' && !app.isDraft && kind !== 'mock';
275
+ },
276
+ /** 편집 화면(CMS)이 저장한 내용. 학생에게도 공개되므로 정답을 넣지 않는다 */
277
+ get content() {
278
+ return content;
279
+ },
280
+
281
+ /** 답 제출 → 서버 채점 결과 { isCorrect, score } (점수 없는 채점이면 둘 다 null). 보통은 useSubmit을 쓴다 */
282
+ async submit(answer) {
283
+ if (readOnly) throw new ContentError('read_only_mode', MESSAGES.read_only_mode);
284
+ try {
285
+ const res = await sdk.submit(answer);
286
+ app.result = sdk.result ?? app.result;
287
+ return res;
288
+ } catch (err) {
289
+ throw toContentError(err);
290
+ }
291
+ },
292
+
293
+ /** 마지막으로 제출한 답 (튜터링이면 그 학생의 답). 없으면 null */
294
+ async lastAnswer() {
295
+ return (await app.lastSubmission())?.answer ?? null;
296
+ },
297
+
298
+ /** 마지막 제출 전체 { id, answer, isCorrect, score, createdAt } 또는 null */
299
+ async lastSubmission() {
300
+ try {
301
+ const [last] = await sdk.history({ limit: 1 });
302
+ return last ?? null;
303
+ } catch (err) {
304
+ throw toContentError(err);
305
+ }
306
+ },
307
+
308
+ /** 내용 저장 (편집 화면): SDK saveSettings로 편집 페이지에 넘긴다. 보통은 useSave를 쓴다 */
309
+ async saveContent(next) {
310
+ if (screen !== 'edit')
311
+ throw new ContentError('screen_not_supported', '내용은 편집 화면에서만 저장합니다.');
312
+ try {
313
+ await sdk.saveSettings(next);
314
+ content = next;
315
+ } catch (err) {
316
+ throw toContentError(err);
317
+ }
318
+ },
319
+
320
+ /**
321
+ * 학생 화면의 제출 영역. 화면은 답을 모으고 채우는 방법만 알려 주면, 보는 사람별 처리는 키트가 한다.
322
+ * - 튜터링: 화면을 읽기 전용으로 잠그고 학생 답을 채움, 제출 버튼 없음
323
+ * - 미리보기 · 교육자 · mock: 채점은 하되 "기록되지 않음" 안내
324
+ * - 다시 열면 마지막 답 복원, 지난 점수 표시, 오류 안내, 중복 클릭 방지
325
+ * @param {SubmitOptions} opts
326
+ */
327
+ useSubmit(opts) {
328
+ return mountSubmit(app, opts);
329
+ },
330
+
331
+ /**
332
+ * 편집 화면의 저장 영역. 저장하지 않은 변경 표시, 검증, 저장 문구, 나가기 경고를 키트가 한다.
333
+ * @param {SaveOptions} opts
334
+ */
335
+ useSave(opts) {
336
+ return mountSave(app, opts);
337
+ },
338
+ };
339
+ if (options.status !== false) showStatus(app);
340
+ return app;
341
+ }
342
+
343
+ /**
344
+ * @typedef {object} SubmitOptions
345
+ * @property {() => unknown} getAnswer 화면에서 답 모으기
346
+ * @property {(answer: unknown) => void} [setAnswer] 저장된 답을 화면에 채우기 (복원 · 튜터링)
347
+ * @property {(answer: unknown) => true | string} [validate] 통과면 true, 아니면 보여 줄 문장
348
+ * @property {(result: object, info: { restored: boolean }) => void} [onResult] 채점 결과 { isCorrect, score } (제출 직후 · 다시 열었을 때). 정답 표시 등에
349
+ * @property {Element} [root] 잠글 화면 영역 (기본 #app)
350
+ * @property {string} [label] 버튼 글자 (기본 '제출')
351
+ */
352
+
353
+ /**
354
+ * @typedef {object} SaveOptions
355
+ * @property {() => Record<string, unknown>} getContent 저장할 내용 (학생에게 공개, 정답 넣지 않음)
356
+ * @property {(content: Record<string, unknown>) => true | string} [validate]
357
+ * @property {Element} [root] 변경을 지켜볼 화면 영역 (기본 #app)
358
+ * @property {string} [label] 버튼 글자 (기본 '저장')
359
+ */
360
+
361
+ const h = (tag, props = {}) => Object.assign(document.createElement(tag), props);
362
+ const appRoot = (root) => root ?? document.getElementById('app') ?? document.body;
363
+
364
+ /** 지금 상태 한 줄 (화면 맨 위). 화면 코드가 보는 사람을 몰라도 사용자가 알 수 있게 */
365
+ export function statusText(app) {
366
+ if (app.viewer === 'tutor')
367
+ return `튜터링 · ${app.account?.fullname ?? '학생'}의 화면 (읽기 전용)`;
368
+ // 설정 화면은 늘 편집기 안(draft)이라 따로 알릴 것이 없다
369
+ if (app.screen === 'edit')
370
+ return app.sdkKind === 'mock' ? 'mock SDK · 저장 내용은 이 브라우저에만' : '';
371
+ const parts = [];
372
+ if (app.sdkKind === 'mock') parts.push('mock SDK · 로컬 채점, 서버에 저장되지 않음');
373
+ else if (app.isDraft) parts.push('저장 전 미리보기 · 기록되지 않음');
374
+ else if (app.viewer === 'instructor' && app.screen === 'instructor')
375
+ parts.push('교육자 화면 · 학생에게 보이지 않음');
376
+ else if (app.viewer === 'instructor') parts.push('교육자 미리보기 · 기록되지 않음');
377
+ if (app.sdkKind === 'mock' && app.viewer === 'instructor' && app.screen === 'learn')
378
+ parts.push('교육자로 보는 중');
379
+ return parts.join(' · ');
380
+ }
381
+
382
+ function showStatus(app) {
383
+ if (typeof document === 'undefined') return;
384
+ const text = statusText(app);
385
+ if (!text) return;
386
+ const el =
387
+ document.getElementById('elice-status') ?? h('div', { id: 'elice-status', role: 'note' });
388
+ el.textContent = text;
389
+ if (!el.isConnected) document.body.prepend(el);
390
+ }
391
+
392
+ function resultText(app, r, past = false) {
393
+ // 지난 점수는 이미 기록된 것이라 "기록되지 않음"을 붙이지 않는다
394
+ const unsaved = app.records || past ? '' : ' (기록되지 않음)';
395
+ // 점수 없는 채점(manual · none): 교육자가 매긴 점수는 나중에 결과로 보인다
396
+ if (r.score === null || r.score === undefined) return `제출했어요.${unsaved}`;
397
+ return (
398
+ (r.isCorrect ? `모두 맞았어요. ${r.score}점` : `${r.score}점이에요. 다시 풀어 볼 수 있어요.`) +
399
+ unsaved
400
+ );
401
+ }
402
+
403
+ function mountSubmit(app, { getAnswer, setAnswer, validate, onResult, root, label = '제출' }) {
404
+ const area = appRoot(root);
405
+ const result = h('p', { className: 'ec-result', role: 'status', hidden: true });
406
+ const error = h('p', { className: 'ec-error', role: 'alert' });
407
+ const button = h('button', { className: 'ec-primary', type: 'button', textContent: label });
408
+ const bar = h('div', { className: 'ec-submitbar' });
409
+ bar.append(error, button);
410
+ area.after(result, bar);
411
+
412
+ const show = (r, prefix = '') => {
413
+ result.textContent = prefix + resultText(app, r, prefix !== '');
414
+ result.className = `ec-result ${r.isCorrect ? 'ok' : r.isCorrect === false ? 'no' : ''}`;
415
+ result.hidden = false;
416
+ };
417
+
418
+ if (app.readOnly) {
419
+ area.inert = true;
420
+ area.setAttribute('aria-readonly', 'true');
421
+ button.hidden = true;
422
+ error.textContent = '보기 전용이라 제출할 수 없습니다.';
423
+ }
424
+ if (app.result && app.result.score !== null && app.result.score !== undefined) {
425
+ show({ score: app.result.score, isCorrect: app.result.score === 100 }, '지난 점수: ');
426
+ if (!app.readOnly) button.textContent = `다시 ${label}`;
427
+ }
428
+ // 다시 열면 마지막 제출의 답을 채우고, 채점 결과({ isCorrect, score })도 화면에 알려 준다
429
+ const restored =
430
+ setAnswer || onResult
431
+ ? app
432
+ .lastSubmission()
433
+ .then((last) => {
434
+ if (!last) return;
435
+ if (setAnswer && last.answer !== null && last.answer !== undefined)
436
+ setAnswer(last.answer);
437
+ onResult?.(last, { restored: true });
438
+ })
439
+ .catch(() => undefined)
440
+ : Promise.resolve();
441
+
442
+ button.addEventListener('click', async () => {
443
+ const answer = getAnswer();
444
+ const ok = validate ? validate(answer) : true;
445
+ if (ok !== true) {
446
+ error.textContent = typeof ok === 'string' ? ok : '답을 확인해 주세요.';
447
+ return;
448
+ }
449
+ error.textContent = '';
450
+ button.disabled = true;
451
+ button.setAttribute('aria-busy', 'true');
452
+ try {
453
+ const res = await app.submit(answer);
454
+ show(res);
455
+ onResult?.(res, { restored: false });
456
+ button.textContent = `다시 ${label}`;
457
+ } catch (e) {
458
+ error.textContent = e.message;
459
+ } finally {
460
+ button.disabled = false;
461
+ button.removeAttribute('aria-busy');
462
+ }
463
+ });
464
+ return { element: bar, result, restored };
465
+ }
466
+
467
+ function mountSave(app, { getContent, validate, root, label = '저장' }) {
468
+ if (app.screen !== 'edit') throw new Error('useSave는 편집 화면(screen: edit)에서만 씁니다.');
469
+ const area = appRoot(root);
470
+ const status = h('p', { className: 'ec-muted', role: 'status' });
471
+ const button = h('button', { className: 'ec-primary', type: 'button', textContent: label });
472
+ const bar = h('div', { className: 'ec-submitbar' });
473
+ bar.append(status, button);
474
+ area.after(bar);
475
+
476
+ let dirty = false;
477
+ const markDirty = () => {
478
+ dirty = true;
479
+ status.textContent = '저장하지 않은 변경이 있어요.';
480
+ };
481
+ area.addEventListener('input', markDirty);
482
+ area.addEventListener('change', markDirty);
483
+ // 문항 추가 · 삭제처럼 입력 없이 화면이 바뀌는 경우
484
+ if (typeof MutationObserver !== 'undefined') {
485
+ let ready = false;
486
+ queueMicrotask(() => (ready = true));
487
+ new MutationObserver(() => ready && markDirty()).observe(area, {
488
+ childList: true,
489
+ subtree: true,
490
+ });
491
+ }
492
+ globalThis.addEventListener?.('beforeunload', (e) => {
493
+ if (dirty) e.preventDefault();
494
+ });
495
+
496
+ // 실제 SDK의 saveSettings는 편집 페이지에 넘기기만 한다. 자료를 저장해야 학생 화면에 반영된다
497
+ const savedText = () =>
498
+ app.sdkKind === 'mock'
499
+ ? '저장했어요 (mock · 이 브라우저에만).'
500
+ : app.isLocal
501
+ ? '로컬 미리보기라 저장되지 않았어요.'
502
+ : '편집 페이지에 넘겼어요. 자료를 저장하면 학생 화면에 반영됩니다.';
503
+
504
+ button.addEventListener('click', async () => {
505
+ const next = getContent();
506
+ const ok = validate ? validate(next) : true;
507
+ if (ok !== true) {
508
+ status.textContent = typeof ok === 'string' ? ok : '내용을 확인해 주세요.';
509
+ return;
510
+ }
511
+ button.disabled = true;
512
+ try {
513
+ await app.saveContent(next);
514
+ dirty = false;
515
+ status.textContent = savedText();
516
+ } catch (e) {
517
+ status.textContent = `저장하지 못했어요: ${e.message}`;
518
+ } finally {
519
+ button.disabled = false;
520
+ }
521
+ });
522
+ return {
523
+ element: bar,
524
+ markDirty,
525
+ get dirty() {
526
+ return dirty;
527
+ },
528
+ };
529
+ }
530
+
531
+ function showBanner(error) {
532
+ if (typeof document === 'undefined') return;
533
+ let el = document.getElementById('elice-banner');
534
+ if (!el) {
535
+ el = document.createElement('div');
536
+ el.id = 'elice-banner';
537
+ el.setAttribute('role', 'alert');
538
+ document.body.prepend(el);
539
+ }
540
+ el.textContent = error.message;
541
+ }