@eliceio/cdk-cli 1.4.1 → 1.5.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 (79) hide show
  1. package/README.md +17 -16
  2. package/es/cli.js +1 -1
  3. package/es/commands/create/index.js +1 -0
  4. package/es/commands/create/scaffold.d.ts +1 -1
  5. package/es/commands/create/scaffold.js +1 -1
  6. package/es/core/config.d.ts +36 -0
  7. package/es/core/config.js +234 -6
  8. package/es/core/quiz-check.js +123 -4
  9. package/es/dev/grading.d.ts +26 -4
  10. package/es/dev/grading.js +66 -11
  11. package/es/dev/mock-api.d.ts +6 -1
  12. package/es/dev/mock-api.js +45 -6
  13. package/es/rules/answers.d.ts +1 -0
  14. package/es/rules/answers.js +8 -0
  15. package/es/rules.json.js +1 -1
  16. package/package.json +2 -2
  17. package/rules.json +1 -1
  18. package/skills/_shared/always.md +1 -1
  19. package/skills/_shared/references/02-design-the-material.md +8 -7
  20. package/skills/_shared/references/03-create-the-project.md +10 -9
  21. package/skills/_shared/references/12-upload-with-the-material-mcp.md +5 -5
  22. package/skills/_shared/references/16-using-the-survey-template.md +158 -0
  23. package/skills/elice-content-create/SKILL.md +2 -2
  24. package/skills/elice-content-edit/SKILL.md +2 -2
  25. package/skills/elice-content-publish/SKILL.md +1 -1
  26. package/templates/_shared/lib/cdk-mock.d.ts +22 -3
  27. package/templates/_shared/lib/cdk-mock.js +78 -11
  28. package/templates/_shared/lib/elice-content.d.ts +17 -1
  29. package/templates/_shared/lib/elice-content.js +47 -5
  30. package/templates/blank/template.json +1 -1
  31. package/templates/document/template.json +1 -1
  32. package/templates/quiz/README.md +26 -1
  33. package/templates/quiz/core/behaviors.d.ts +5 -0
  34. package/templates/quiz/core/behaviors.js +16 -1
  35. package/templates/quiz/core/model.d.ts +78 -1
  36. package/templates/quiz/core/model.js +219 -4
  37. package/templates/quiz/screens/edit.js +244 -55
  38. package/templates/quiz/screens/learn.js +137 -27
  39. package/templates/quiz/styles.css +258 -5
  40. package/templates/quiz/template.json +1 -1
  41. package/templates/quiz/ui/templates/edit.d.ts +1 -0
  42. package/templates/quiz/ui/templates/edit.js +67 -8
  43. package/templates/quiz/ui/templates/page.js +34 -0
  44. package/templates/quiz/ui/templates/text.js +15 -2
  45. package/templates/quiz/ui/texts.js +61 -0
  46. package/templates/steps/template.json +1 -1
  47. package/templates/survey/README.md +112 -0
  48. package/templates/survey/commentary.txt +2 -0
  49. package/templates/survey/core/behaviors.d.ts +14 -0
  50. package/templates/survey/core/behaviors.js +115 -0
  51. package/templates/survey/core/dom.d.ts +13 -0
  52. package/templates/survey/core/dom.js +83 -0
  53. package/templates/survey/core/editor.d.ts +80 -0
  54. package/templates/survey/core/editor.js +720 -0
  55. package/templates/survey/core/markdown.d.ts +21 -0
  56. package/templates/survey/core/markdown.js +298 -0
  57. package/templates/survey/core/model.d.ts +83 -0
  58. package/templates/survey/core/model.js +209 -0
  59. package/templates/survey/core/rich-text.d.ts +18 -0
  60. package/templates/survey/core/rich-text.js +469 -0
  61. package/templates/survey/edit.html +26 -0
  62. package/templates/survey/gitignore +4 -0
  63. package/templates/survey/index.html +26 -0
  64. package/templates/survey/metadata.json +9 -0
  65. package/templates/survey/package.json +13 -0
  66. package/templates/survey/screens/edit.js +345 -0
  67. package/templates/survey/screens/learn.js +100 -0
  68. package/templates/survey/styles.css +1264 -0
  69. package/templates/survey/template.json +6 -0
  70. package/templates/survey/ui/templates/edit.d.ts +27 -0
  71. package/templates/survey/ui/templates/edit.js +656 -0
  72. package/templates/survey/ui/templates/index.d.ts +3 -0
  73. package/templates/survey/ui/templates/index.js +3 -0
  74. package/templates/survey/ui/templates/learn.js +147 -0
  75. package/templates/survey/ui/templates/page.js +19 -0
  76. package/templates/survey/ui/texts.d.ts +3 -0
  77. package/templates/survey/ui/texts.js +116 -0
  78. package/templates/survey/ui/theme.css +42 -0
  79. package/templates/video/template.json +1 -1
@@ -0,0 +1,21 @@
1
+ export declare function setImages(next: Record<string, string> | undefined): void;
2
+ export declare const IMAGE_DATA: RegExp;
3
+ export declare function imageSrc(id: string): string | null;
4
+ export declare function lineNumbers(count: number): string;
5
+ export declare function markdownToHtml(source: string): string;
6
+ export declare function markdown(source: string, className?: string): HTMLElement;
7
+ export declare const ASSET_KEY: RegExp;
8
+ export declare function setAssetFailedText(text: string): void;
9
+ export declare const ASSET_TIMEOUT_MS: number;
10
+ export declare function loadAsset(
11
+ key: string,
12
+ urlOf: (key: string) => Promise<string | null>,
13
+ ): Promise<void>;
14
+ export declare function assetBlock(ref: string, alt?: string): HTMLElement | null;
15
+ export declare function assetKeysIn(source: string | undefined): string[];
16
+ export declare function resolveAssets(
17
+ sources: (string | undefined)[],
18
+ urlOf: (key: string) => Promise<string | null>,
19
+ ): Promise<void>;
20
+ export declare function refSrc(ref: string): string | null;
21
+ export declare const ASSET_FILLED_EVENT: string;
@@ -0,0 +1,298 @@
1
+ // 지문 · 해설용 작은 마크다운 (외부 라이브러리 없이). 먼저 HTML을 모두 이스케이프하므로 교육자가 쓴 태그는 그대로 글자로 보인다.
2
+ // 지원: 문단 · 줄바꿈 · # 제목 · **굵게** · *기울임* · ~~취소선~~ · `코드` · ```코드 블록```(3줄부터 줄 번호) · - 목록 · 1. 목록 ·
3
+ // [링크](https://…) · 그림 ![설명](asset:파일키)(편집 화면에서 서버에 올린 그림) · ![설명](img/파일)(zip 안 그림) ·
4
+ // 옛 ![설명](image:아이디)(1.9.0 전 편집 화면이 내용 images에 data: 주소로 둔 그림) ·
5
+ // \* 처럼 앞에 \를 붙이면 서식 기호가 아니라 글자
6
+
7
+ const escape = (s) =>
8
+ s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
9
+
10
+ /** 옛 그림: 내용 images에 둔 그림 (아이디 → data: 주소). 화면이 내용을 받으면 setImages로 넣는다 */
11
+ let images = {};
12
+ /** @param {Record<string, string> | undefined} next */
13
+ export const setImages = (next) => {
14
+ images = next ?? {};
15
+ };
16
+ /** 옛 그림으로 받는 data: 주소 (1.9.0 전 편집 화면이 줄여 만든 webp · jpeg, 옛 png) */
17
+ export const IMAGE_DATA = /^data:image\/(webp|jpeg|png);base64,[A-Za-z0-9+/=]+$/;
18
+ /** 아이디의 옛 그림 주소 (없거나 모양이 다르면 null) */
19
+ export const imageSrc = (id) => (IMAGE_DATA.test(images[id] ?? '') ? images[id] : null);
20
+
21
+ /** 서버에 올린 그림의 파일 키 `assets/{자료 id}/{이름}.{확장자}` (SDK assets.post가 준 id 그대로) */
22
+ export const ASSET_KEY = /^assets\/[\w-]+\/[\w-]+\.(?:png|jpe?g|webp|gif)$/i;
23
+ const ASSET_REF = /asset:(assets\/[\w-]+\/[\w-]+\.(?:png|jpe?g|webp|gif))(?=\))/gi;
24
+ /**
25
+ * 올린 그림 (파일 키 → 받은 결과: 화면에 넣을 blob: 주소, 받지 못했으면 null). settings에는 키만 둔다.
26
+ * 서명 주소를 <img>에 바로 넣지 않고 fetch로 받아 blob:으로 넣는다: 콘텐츠 CSP 초안의 img-src는 콘텐츠 출처 · data: · blob:뿐이고
27
+ * 파일 출처(자료 API)는 connect-src에만 있다. 받아 둔 그림은 서명 주소가 만료돼도 그대로 보인다.
28
+ * 화면은 그림을 기다리지 않고 먼저 그린다: 아직 받지 못한 그림 자리는 설명 글(data-asset-pending)이고, 받으면 그 자리만 <img>로
29
+ * (못 받으면 안내로) 바꾼다. 다시 그려도 받은 그림은 바로 <img>, 받는 중이면 다시 자리를 두었다가 끝나면 바꾼다
30
+ */
31
+ const assetUrls = new Map();
32
+ /** 받는 중인 그림 (파일 키 → Promise). 같은 그림을 두 번 받지 않는다 */
33
+ const assetLoads = new Map();
34
+ /** 그림 하나를 받는 시간 한도 (주소 묻기 + 내려받기 합쳐서). 넘으면 못 받은 것으로 */
35
+ export const ASSET_TIMEOUT_MS = 10_000;
36
+ /** 받지 못했던 자리를 받은 결과로 바꾼 뒤 document에 보내는 이벤트 (detail: { key, element }) */
37
+ export const ASSET_FILLED_EVENT = 'qz-asset-filled';
38
+ /** 처음 보는 키를 그릴 때 받으러 갈 함수 (resolveAssets · loadAsset이 넣음, 키트 app.assets.url) */
39
+ let assetLoader = null;
40
+ /** 받지 못한 그림 자리에 보일 글 (화면이 문구를 넣음, 없으면 설명 글) */
41
+ let assetFailedText = '';
42
+ /** @param {string} text */
43
+ export const setAssetFailedText = (text) => {
44
+ assetFailedText = text ?? '';
45
+ };
46
+ /** 그림을 받을 주소: 서명 주소(https) · 로컬 흉내(http · blob:) */
47
+ const ASSET_URL = /^(https?:\/\/|blob:)[^\s"'<>]+$/;
48
+ const ASSET_TYPES = /^image\/(png|jpeg|webp|gif)$/;
49
+
50
+ /** 주소를 묻고 받아 blob: 주소로 (signal로 멈춤) */
51
+ async function fetchAsset(key, urlOf, signal) {
52
+ const url = await urlOf(key);
53
+ if (typeof url !== 'string' || !ASSET_URL.test(url)) return null;
54
+ if (url.startsWith('blob:')) return url;
55
+ const res = await fetch(url, { signal });
56
+ if (!res.ok) return null;
57
+ const blob = await res.blob();
58
+ return ASSET_TYPES.test(blob.type) || blob.type === '' ? URL.createObjectURL(blob) : null;
59
+ }
60
+
61
+ /** 그림 자리 (아직 받지 못함 · 못 받음) */
62
+ function placeholder(key, alt) {
63
+ const failed = assetUrls.has(key);
64
+ const el = document.createElement('span');
65
+ el.className = 'qz-image-missing';
66
+ if (failed && assetFailedText) {
67
+ el.setAttribute('role', 'alert');
68
+ el.textContent = assetFailedText;
69
+ } else el.textContent = alt;
70
+ if (!failed) el.dataset.assetPending = key;
71
+ el.dataset.alt = alt;
72
+ return el;
73
+ }
74
+ /** 받은 그림 */
75
+ function assetImage(key, src, alt) {
76
+ const img = document.createElement('img');
77
+ img.className = 'qz-image';
78
+ img.src = src;
79
+ img.alt = alt;
80
+ img.dataset.asset = key;
81
+ return img;
82
+ }
83
+ /** 문서에 놓인 그 키의 자리를 받은 결과로 바꾼다 (자리만 바꾸고 나머지는 건드리지 않음) */
84
+ function fillAsset(key) {
85
+ if (typeof document === 'undefined') return;
86
+ for (const el of document.querySelectorAll('[data-asset-pending]')) {
87
+ if (el.dataset.assetPending !== key) continue;
88
+ const alt = el.dataset.alt ?? el.textContent ?? '';
89
+ const src = assetUrls.get(key);
90
+ const next = src ? assetImage(key, src, alt) : placeholder(key, alt);
91
+ el.replaceWith(next);
92
+ // 화면이 늦게 들어온 그림에 맞출 수 있게 (학생 화면: 제출 뒤 맨 아래로 한 번 더)
93
+ document.dispatchEvent(new CustomEvent(ASSET_FILLED_EVENT, { detail: { key, element: next } }));
94
+ }
95
+ }
96
+
97
+ /**
98
+ * 파일 키의 그림을 받는다 (주소 묻기 + 내려받기 합쳐서 ASSET_TIMEOUT_MS까지). 끝나면 화면의 그 자리를 바꾼다.
99
+ * 이미 받았거나 받는 중이면 그것을 기다린다. urlOf는 키트 app.assets.url
100
+ * @param {string} key
101
+ * @param {(key: string) => Promise<string | null>} urlOf
102
+ */
103
+ export function loadAsset(key, urlOf) {
104
+ if (!ASSET_KEY.test(key)) return Promise.resolve();
105
+ assetLoader ??= urlOf;
106
+ if (assetUrls.get(key)) return Promise.resolve();
107
+ const running = assetLoads.get(key);
108
+ if (running) return running;
109
+ const controller = new AbortController();
110
+ let timer;
111
+ const deadline = new Promise((resolve) => {
112
+ timer = setTimeout(() => {
113
+ controller.abort();
114
+ resolve(null);
115
+ }, ASSET_TIMEOUT_MS);
116
+ });
117
+ const load = Promise.race([
118
+ fetchAsset(key, urlOf, controller.signal).catch(() => null),
119
+ deadline,
120
+ ]).then((src) => {
121
+ clearTimeout(timer);
122
+ assetLoads.delete(key);
123
+ assetUrls.set(key, src);
124
+ fillAsset(key);
125
+ });
126
+ assetLoads.set(key, load);
127
+ return load;
128
+ }
129
+ /** 글에 든 올린 그림 파일 키들 */
130
+ export const assetKeysIn = (source) => [...String(source ?? '').matchAll(ASSET_REF)].map((m) => m[1]);
131
+ /**
132
+ * 글들에 든 올린 그림을 받기 시작한다. 화면은 기다리지 않고 먼저 그려도 된다 (받으면 자리를 바꿈).
133
+ * 돌려준 Promise는 모두 끝났을 때 (테스트용)
134
+ * @param {(string | undefined)[]} sources
135
+ * @param {(key: string) => Promise<string | null>} urlOf
136
+ */
137
+ export function resolveAssets(sources, urlOf) {
138
+ assetLoader = urlOf;
139
+ const keys = [...new Set(sources.flatMap(assetKeysIn))];
140
+ return Promise.all(keys.map((key) => loadAsset(key, urlOf))).then(() => undefined);
141
+ }
142
+ /** 그림 칸 참조(image:아이디 · asset:파일키)의 주소 (모르면 null) */
143
+ export const refSrc = (ref) => {
144
+ const [, kind, value] = /^(image|asset):(.+)$/.exec(ref ?? '') ?? [];
145
+ if (kind === 'image') return imageSrc(value);
146
+ if (kind === 'asset') return assetUrls.get(value) ?? null;
147
+ return null;
148
+ };
149
+ /**
150
+ * 그림 칸(편집 화면)에 놓을 asset 그림: 받았으면 <img>, 아직이면 자리(받으면 바뀜), 못 받았으면 안내. asset이 아니면 null
151
+ * @param {string} ref
152
+ * @param {string} [alt]
153
+ */
154
+ export function assetBlock(ref, alt = '') {
155
+ const key = /^asset:(.+)$/.exec(ref ?? '')?.[1];
156
+ if (!key || !ASSET_KEY.test(key)) return null;
157
+ const src = assetUrls.get(key);
158
+ if (src) return assetImage(key, src, alt);
159
+ if (!assetUrls.has(key) && !assetLoads.has(key) && assetLoader) void loadAsset(key, assetLoader);
160
+ return placeholder(key, alt);
161
+ }
162
+
163
+ // \로 막은 서식 기호는 잠시 쓰지 않는 글자로 바꿔 두었다가 마지막에 되돌린다
164
+ const ESCAPED = {
165
+ '\\': '',
166
+ '*': '',
167
+ '`': '',
168
+ '[': '',
169
+ ']': '',
170
+ '#': '',
171
+ '-': '',
172
+ '.': '',
173
+ '~': '',
174
+ };
175
+ const UNESCAPED = Object.fromEntries(Object.entries(ESCAPED).map(([k, v]) => [v, k]));
176
+ const restore = (s) => s.replace(/[-]/g, (c) => UNESCAPED[c]);
177
+
178
+ function inline(s) {
179
+ // 코드 안은 서식을 풀지 않게 먼저 떼어 두었다가 마지막에 넣는다
180
+ const codes = [];
181
+ return restore(
182
+ s
183
+ .replace(/\\([\\*`[\]#\-.~])/g, (_, c) => ESCAPED[c])
184
+ .replace(/`([^`]+)`/g, (_, c) => `${codes.push(c) - 1}`)
185
+ .replace(/!\[([^\]]*)\]\(image:([\w-]+)\)/g, (_, alt, id) => {
186
+ const src = imageSrc(id);
187
+ return src
188
+ ? `<img class="qz-image" src="${src}" alt="${alt}">`
189
+ : `<span class="qz-image-missing">${alt}</span>`;
190
+ })
191
+ .replace(
192
+ /!\[([^\]]*)\]\(asset:(assets\/[\w-]+\/[\w-]+\.(?:png|jpe?g|webp|gif))\)/gi,
193
+ (_, alt, key) => {
194
+ const src = assetUrls.get(key);
195
+ if (src) return `<img class="qz-image" src="${escape(src)}" alt="${alt}" data-asset="${key}">`;
196
+ // 받지 못했으면(주소 만료 · 시간 초과 등) 화면이 준 안내
197
+ if (assetUrls.has(key) && assetFailedText)
198
+ return `<span class="qz-image-missing" role="alert" data-alt="${alt}">${escape(assetFailedText)}</span>`;
199
+ // 아직이면 설명 글 자리를 두고 받으러 간다 (받으면 fillAsset이 이 자리를 바꿈)
200
+ if (!assetUrls.has(key) && !assetLoads.has(key) && assetLoader) {
201
+ const loader = assetLoader;
202
+ queueMicrotask(() => void loadAsset(key, loader));
203
+ }
204
+ const pending = assetUrls.has(key) ? '' : ` data-asset-pending="${key}"`;
205
+ return `<span class="qz-image-missing"${pending} data-alt="${alt}">${alt}</span>`;
206
+ },
207
+ )
208
+ .replace(
209
+ /!\[([^\]]*)\]\((img\/[\w./-]+)\)/g,
210
+ '<img class="qz-image" src="$2" alt="$1" loading="lazy">',
211
+ )
212
+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
213
+ .replace(/\*([^*]+)\*/g, '<em>$1</em>')
214
+ .replace(/~~([^~]+)~~/g, '<del>$1</del>')
215
+ .replace(
216
+ /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,
217
+ '<a href="$2" target="_blank" rel="noopener">$1</a>',
218
+ )
219
+ .replace(/(\d+)/g, (_, i) => `<code>${codes[i]}</code>`),
220
+ );
221
+ }
222
+
223
+ /** 줄 번호 글 "1\n2\n…" (코드 블록 왼쪽, CSS가 data-lines를 보인다) */
224
+ export const lineNumbers = (count) => Array.from({ length: count }, (_, i) => i + 1).join('\n');
225
+
226
+ /** 코드 블록. 3줄부터 줄 번호 */
227
+ const codeBlock = (lines) =>
228
+ lines.length >= 3
229
+ ? `<pre class="qz-lines" data-lines="${lines.map((_, i) => i + 1).join('&#10;')}"><code>${lines.join('\n')}</code></pre>`
230
+ : `<pre><code>${lines.join('\n')}</code></pre>`;
231
+
232
+ export function markdownToHtml(source) {
233
+ const lines = escape(String(source ?? '')).split('\n');
234
+ const out = [];
235
+ let list = null;
236
+ let code = null;
237
+ let para = [];
238
+ const flushPara = () => {
239
+ if (para.length) out.push(`<p>${inline(para.join('<br>'))}</p>`);
240
+ para = [];
241
+ };
242
+ const flushList = () => {
243
+ if (list)
244
+ out.push(
245
+ `<${list.tag}>${list.items.map((i) => `<li>${inline(i)}</li>`).join('')}</${list.tag}>`,
246
+ );
247
+ list = null;
248
+ };
249
+ for (const line of lines) {
250
+ if (code) {
251
+ if (line.startsWith('```')) {
252
+ out.push(codeBlock(code));
253
+ code = null;
254
+ } else code.push(line);
255
+ continue;
256
+ }
257
+ if (line.startsWith('```')) {
258
+ flushPara();
259
+ flushList();
260
+ code = [];
261
+ continue;
262
+ }
263
+ const heading = line.match(/^(#{1,3})\s+(.*)$/);
264
+ const bullet = line.match(/^\s*[-*]\s+(.*)$/);
265
+ const numbered = line.match(/^\s*\d+\.\s+(.*)$/);
266
+ if (heading) {
267
+ flushPara();
268
+ flushList();
269
+ out.push(`<h${heading[1].length + 2}>${inline(heading[2])}</h${heading[1].length + 2}>`);
270
+ } else if (bullet || numbered) {
271
+ flushPara();
272
+ const tag = bullet ? 'ul' : 'ol';
273
+ if (list?.tag !== tag) flushList();
274
+ list ??= { tag, items: [] };
275
+ list.items.push((bullet ?? numbered)[1]);
276
+ } else if (line.trim() === '') {
277
+ flushPara();
278
+ flushList();
279
+ } else {
280
+ flushList();
281
+ para.push(line);
282
+ }
283
+ }
284
+ if (code) out.push(codeBlock(code));
285
+ flushPara();
286
+ flushList();
287
+ return out.join('');
288
+ }
289
+
290
+ /** 마크다운을 안전하게 넣은 요소 */
291
+ export function markdown(source, className = 'qz-markdown') {
292
+ const el = document.createElement('div');
293
+ el.className = className;
294
+ // markdownToHtml은 먼저 전부 이스케이프하고 정해진 태그만 만든다 (quiz.test.ts '마크다운')
295
+ // ecdk-ignore-next-line sec.html-injection
296
+ el.innerHTML = markdownToHtml(source);
297
+ return el;
298
+ }
@@ -0,0 +1,83 @@
1
+ // core/model.js 타입 (편집기 자동완성 · 테스트용)
2
+ export type QuestionType = 'single' | 'multiple' | 'scale' | 'text';
3
+ export interface Option {
4
+ id: string;
5
+ text: string;
6
+ }
7
+ export interface Scale {
8
+ min: number;
9
+ max: number;
10
+ minLabel: string;
11
+ maxLabel: string;
12
+ }
13
+ export interface Question {
14
+ id: string;
15
+ type: QuestionType;
16
+ title: string;
17
+ description?: string;
18
+ required: boolean;
19
+ options?: Option[];
20
+ other?: boolean;
21
+ scale?: Scale;
22
+ /** 편집 화면에서만 (설명 칸을 열어 둠), 저장하지 않음 */
23
+ descOpen?: boolean;
24
+ }
25
+ export interface Survey {
26
+ description?: string;
27
+ questions: Question[];
28
+ }
29
+ export declare const LIMITS: {
30
+ questionsMax: number;
31
+ optionsMin: number;
32
+ optionsMax: number;
33
+ groupsMin: number;
34
+ groupsMax: number;
35
+ title: number;
36
+ otherMax: number;
37
+ textMax: number;
38
+ imagesMax: number;
39
+ };
40
+ export declare const TYPES: QuestionType[];
41
+ export declare const OTHER: 'other';
42
+ export declare const OTHER_SUFFIX: ':other';
43
+ export declare const SCALE_MINS: number[];
44
+ export declare const SCALE_MAXES: number[];
45
+ export declare function isChoice(q: Question): boolean;
46
+ export declare function canAddQuestion(questions: Question[] | undefined): boolean;
47
+ export declare function nextId(used: string[], prefix?: string): string;
48
+ export declare function normalizeScale(q: Partial<Question>): Scale;
49
+ export declare function scaleSteps(scale: { min: number; max: number }): number[];
50
+ export declare function scaleColumns(count: number): { wide: number; narrow: number };
51
+ export declare function newQuestion(type: QuestionType, usedIds: string[]): Question;
52
+ export declare function newOption(options: Option[]): Option;
53
+ export declare function convertType(q: Question, type: QuestionType): Question;
54
+ export declare function validateSurvey(
55
+ content: Partial<Survey>,
56
+ v: {
57
+ noQuestions: string;
58
+ at(no: number, message: string): string;
59
+ title: string;
60
+ optionText: string;
61
+ optionsMin(min: number): string;
62
+ }
63
+ ): true | string;
64
+ export declare function isAnswered(q: Question, value: unknown): boolean;
65
+ export declare function otherMissing(q: Question, value: unknown, otherText: unknown): boolean;
66
+ export declare function checkAnswer(
67
+ questions: Question[],
68
+ answer: Record<string, unknown>,
69
+ t: {
70
+ unanswered(no: number): string;
71
+ otherEmpty(no: number): string;
72
+ invalid(no: number): string;
73
+ }
74
+ ): true | string;
75
+ export declare function cleanQuestions(questions: Question[]): Question[];
76
+ export type Answers = Record<string, unknown>;
77
+ export declare function readSurvey(content: unknown): Survey;
78
+ export declare function makeContent(survey: Survey): { survey: Survey };
79
+ export declare function isValidValue(q: Question, value: unknown): boolean;
80
+ export declare function answerProblem(
81
+ questions: Question[],
82
+ answer: unknown
83
+ ): { question_id: string | null; reason: 'not_object' | 'unknown_key' | 'bad_value' } | null;
@@ -0,0 +1,209 @@
1
+ // 설문 데이터 다루기 (화면 · 문구와 무관한 순수 함수). 설문은 정답 · 채점이 없습니다.
2
+ //
3
+ // 내용(settings, 편집 화면이 저장, 학생에게도 그대로 내려감): 설문이 쓰는 것은 모두 settings.survey 아래
4
+ // { survey: { description?: string, questions: Question[] } }
5
+ // 서버는 settings.survey가 있으면 설문으로 알아보고 문항 모양 · 답 모양을 검사한다
6
+ // Question = { id, type: 'single' | 'multiple' | 'scale' | 'text', title, description?, required }
7
+ // single · multiple: options: [{ id, text }], other?: true ('기타(자유 입력)' 보기)
8
+ // scale: scale: { min: 0 | 1, max: 2~10, minLabel, maxLabel }
9
+ // 그림은 안내 · 설명 글에 asset:파일키로 (settings에는 키만)
10
+ // 답(SDK submit에 그대로, JSON 객체 하나): 문항 id를 키로 한 객체
11
+ // { [문항 id]: 값, [문항 id + ':other']: 기타 글 }
12
+ // single: 보기 id | 'other' | null · multiple: 보기 id 배열('other' 포함 가능) · scale: 정수 | null · text: 문자열
13
+ // 서버는 아는 문항 id(또는 id:other)의 값 종류가 유형과 맞는지 본다 (틀리면 422 not_a_survey_answer). 모르는 키는 무시한다
14
+ // (템플릿 answerProblem은 모르는 키도 막는다)
15
+
16
+ const isObject = v => v !== null && typeof v === 'object' && !Array.isArray(v);
17
+
18
+ /** 저장된 내용(settings)에서 설문: settings.survey. 없으면 빈 문항 */
19
+ export function readSurvey(content) {
20
+ const { description, questions } = isObject(content?.survey) ? content.survey : {};
21
+ return {
22
+ ...(typeof description === 'string' ? { description } : {}),
23
+ questions: Array.isArray(questions) ? questions : [],
24
+ };
25
+ }
26
+
27
+ /** 저장할 내용: { survey: { description, questions } } (맨 위에 다른 키는 두지 않음) */
28
+ export const makeContent = survey => ({ survey });
29
+
30
+ /** 개수 · 길이 한도 (편집 화면이 지킴). groups*는 공용 편집 도우미(core/editor.js)가 읽는 값이라 둔다 (설문은 그룹 없음) */
31
+ export const LIMITS = {
32
+ questionsMax: 30,
33
+ optionsMin: 2,
34
+ optionsMax: 10,
35
+ groupsMin: 2,
36
+ groupsMax: 10,
37
+ title: 300,
38
+ /** 기타 · 서술형 답 글자 수 (답 전체가 서버 한도 64KB 안에 들게) */
39
+ otherMax: 300,
40
+ textMax: 1000,
41
+ /** 서버에 올리는 그림 (asset:파일키) 설문 전체 개수 */
42
+ imagesMax: 50,
43
+ };
44
+
45
+ /** 문항 유형 (편집 화면 유형 고르기 순서) */
46
+ export const TYPES = ['single', 'multiple', 'scale', 'text'];
47
+ const CHOICE_TYPES = ['single', 'multiple'];
48
+ export const isChoice = q => CHOICE_TYPES.includes(q.type);
49
+
50
+ /** '기타(자유 입력)' 보기의 값과 기타 글을 담는 답 키 꼬리 */
51
+ export const OTHER = 'other';
52
+ export const OTHER_SUFFIX = ':other';
53
+
54
+ /** 척도 시작값 · 끝값으로 고를 수 있는 수 */
55
+ export const SCALE_MINS = [0, 1];
56
+ export const SCALE_MAXES = [2, 3, 4, 5, 6, 7, 8, 9, 10];
57
+
58
+ export const canAddQuestion = questions => (questions?.length ?? 0) < LIMITS.questionsMax;
59
+
60
+ /** 아직 쓰지 않은 아이디 (prefix + 1, 2, …) */
61
+ export function nextId(used, prefix = '') {
62
+ const taken = new Set(used);
63
+ for (let n = 1; ; n++) if (!taken.has(`${prefix}${n}`)) return `${prefix}${n}`;
64
+ }
65
+
66
+ /** 척도 설정을 고를 수 있는 값으로 맞춘다 (없거나 틀리면 1 ~ 5) */
67
+ export function normalizeScale(q) {
68
+ const s = q.scale ?? {};
69
+ return {
70
+ min: SCALE_MINS.includes(s.min) ? s.min : 1,
71
+ max: SCALE_MAXES.includes(s.max) ? s.max : 5,
72
+ minLabel: typeof s.minLabel === 'string' ? s.minLabel : '',
73
+ maxLabel: typeof s.maxLabel === 'string' ? s.maxLabel : '',
74
+ };
75
+ }
76
+
77
+ /** 척도의 수들 (min ~ max) */
78
+ export const scaleSteps = ({ min, max }) =>
79
+ Array.from({ length: max - min + 1 }, (_, i) => min + i);
80
+
81
+ /** 척도 칸 열 수: 넓은 화면은 한 줄, 좁은 화면은 7칸 이상이면 두 줄 */
82
+ export const scaleColumns = count => ({
83
+ wide: count,
84
+ narrow: count > 6 ? Math.ceil(count / 2) : count,
85
+ });
86
+
87
+ /** 새 문항 (필수 응답이 켜진 채). usedIds: 이미 쓰는 문항 id */
88
+ export function newQuestion(type, usedIds) {
89
+ return convertType(
90
+ { id: nextId(usedIds, 'q'), type, title: '', description: '', required: true },
91
+ type
92
+ );
93
+ }
94
+
95
+ /** 빈 보기 */
96
+ export const newOption = options => ({
97
+ id: nextId(
98
+ options.map(o => o.id),
99
+ 'o'
100
+ ),
101
+ text: '',
102
+ });
103
+
104
+ /**
105
+ * 유형을 바꾼 문항. 질문 · 설명 · 필수는 그대로, 단일 ↔ 다중 선택은 보기 · 기타도 그대로.
106
+ * 선택형이 되면 보기가 없을 때 빈 보기 둘, 척도가 되면 1 ~ 5
107
+ */
108
+ export function convertType(q, type) {
109
+ const { id, title, description, required } = q;
110
+ const base = { id, type, title, description, required };
111
+ if (CHOICE_TYPES.includes(type)) {
112
+ const options = Array.isArray(q.options) && q.options.length ? q.options : null;
113
+ const fresh = [
114
+ { id: 'o1', text: '' },
115
+ { id: 'o2', text: '' },
116
+ ];
117
+ return { ...base, ...(q.other ? { other: true } : {}), options: options ?? fresh };
118
+ }
119
+ if (type === 'scale') return { ...base, scale: normalizeScale(q) };
120
+ return base;
121
+ }
122
+
123
+ /**
124
+ * 저장 전 검사. 문제가 없으면 true, 있으면 보여 줄 문장 (v: texts.validation)
125
+ */
126
+ export function validateSurvey(content, v) {
127
+ if (!content.questions?.length) return v.noQuestions;
128
+ for (const [i, q] of content.questions.entries()) {
129
+ if (!q.title?.trim()) return v.at(i + 1, v.title);
130
+ if (isChoice(q)) {
131
+ if (q.options.length < LIMITS.optionsMin) return v.at(i + 1, v.optionsMin(LIMITS.optionsMin));
132
+ if (q.options.some(o => !o.text.trim())) return v.at(i + 1, v.optionText);
133
+ }
134
+ }
135
+ return true;
136
+ }
137
+
138
+ /** 문항에 답했는지 (필수 응답 검사) */
139
+ export function isAnswered(q, value) {
140
+ if (q.type === 'multiple') return Array.isArray(value) && value.length > 0;
141
+ if (q.type === 'text') return typeof value === 'string' && value.trim() !== '';
142
+ return value !== null && value !== undefined && value !== '';
143
+ }
144
+
145
+ /** '기타'를 골랐는데 글이 비었는지 */
146
+ export function otherMissing(q, value, otherText) {
147
+ const picked = Array.isArray(value) ? value.includes(OTHER) : value === OTHER;
148
+ return Boolean(q.other) && picked && !String(otherText ?? '').trim();
149
+ }
150
+
151
+ /**
152
+ * 값이 서버가 받는 모양인지 (설계: 단일 = 보기 id | 'other' | null, 다중 = 보기 id 배열, 척도 = 정수 | null, 서술형 = 문자열).
153
+ * 템플릿은 서버보다 조금 더 좁게 본다: 지금 문항에 있는 보기 id · 척도 수만, '기타'는 그 문항에 기타가 있을 때만
154
+ */
155
+ export function isValidValue(q, value) {
156
+ if (value === undefined) return true;
157
+ const ids = (q.options ?? []).map(o => o.id);
158
+ const isOption = v => typeof v === 'string' && (ids.includes(v) || (q.other && v === OTHER));
159
+ if (q.type === 'single') return value === null || isOption(value);
160
+ if (q.type === 'multiple')
161
+ return Array.isArray(value) && value.every(isOption) && new Set(value).size === value.length;
162
+ if (q.type === 'scale')
163
+ return value === null || (Number.isInteger(value) && scaleSteps(normalizeScale(q)).includes(value));
164
+ return typeof value === 'string';
165
+ }
166
+
167
+ /**
168
+ * 답이 서버 검사(422 not_a_survey_answer)를 지나는 모양인지. 문제가 없으면 null, 있으면 { question_id, reason }
169
+ * (서버 detail과 같은 모양). 키는 지금 문항 id 또는 문항 id + ':other'(기타가 있는 문항, 문자열)만
170
+ * @param {object[]} questions
171
+ * @param {Record<string, unknown>} answer
172
+ */
173
+ export function answerProblem(questions, answer) {
174
+ if (!isObject(answer)) return { question_id: null, reason: 'not_object' };
175
+ const byId = new Map(questions.map(q => [q.id, q]));
176
+ for (const [key, value] of Object.entries(answer)) {
177
+ if (byId.has(key)) {
178
+ if (!isValidValue(byId.get(key), value)) return { question_id: key, reason: 'bad_value' };
179
+ continue;
180
+ }
181
+ const q = key.endsWith(OTHER_SUFFIX) ? byId.get(key.slice(0, -OTHER_SUFFIX.length)) : null;
182
+ if (!q) return { question_id: key, reason: 'unknown_key' };
183
+ if (!q.other || typeof value !== 'string') return { question_id: q.id, reason: 'bad_value' };
184
+ }
185
+ return null;
186
+ }
187
+
188
+ /**
189
+ * 제출 전 검사 (학생 화면). 필수 문항에 답하지 않았거나 '기타' 글이 비었으면 그 문항 번호와 문장,
190
+ * 서버가 거절할 모양이면(보기 · 척도 수가 지금 문항에 없음 등) "다시 골라 주세요", 아니면 true
191
+ * @param {object[]} questions
192
+ * @param {Record<string, unknown>} answer
193
+ * @param {{ unanswered: (no: number) => string, otherEmpty: (no: number) => string, invalid: (no: number) => string }} t
194
+ */
195
+ export function checkAnswer(questions, answer, t) {
196
+ for (const [i, q] of questions.entries()) {
197
+ if (q.required && !isAnswered(q, answer[q.id])) return t.unanswered(i + 1);
198
+ if (otherMissing(q, answer[q.id], answer[q.id + OTHER_SUFFIX])) return t.otherEmpty(i + 1);
199
+ }
200
+ const problem = answerProblem(questions, answer);
201
+ if (problem) {
202
+ const no = questions.findIndex(q => q.id === problem.question_id) + 1;
203
+ return t.invalid(no || 1);
204
+ }
205
+ return true;
206
+ }
207
+
208
+ /** 저장할 문항 (화면에서만 쓰는 값 빼기: descOpen) */
209
+ export const cleanQuestions = questions => questions.map(({ descOpen: _open, ...q }) => q);
@@ -0,0 +1,18 @@
1
+ export interface RichText {
2
+ el: HTMLElement;
3
+ set(markdown: string): void;
4
+ get(): string;
5
+ focus(atEnd?: boolean): void;
6
+ split(): { before: string; after: string };
7
+ state(): { bold: boolean; italic: boolean; strike: boolean; ul: boolean; ol: boolean; code: boolean };
8
+ bold(): void;
9
+ italic(): void;
10
+ strike(): void;
11
+ list(tag?: 'ul' | 'ol'): void;
12
+ code(sample: string): void;
13
+ }
14
+ export type Block = { type: 'text'; text: string } | { type: 'image'; alt: string; ref: string };
15
+ export declare function toMarkdown(root: Node): string;
16
+ export declare function richText(el: HTMLElement, opts: { onChange: (markdown: string) => void }): RichText;
17
+ export declare function splitBlocks(source: string): Block[];
18
+ export declare function joinBlocks(items: Block[]): string;