@eliceio/cdk-cli 1.3.0-contenttypes.1 → 1.3.0-contenttypes.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,8 +5,11 @@
5
5
  // shuffle?, placeholder?, explanation: { enabled, text } }] }
6
6
  // 퀴즈 제목 · 안내(title · description)는 지금 화면이 쓰지 않는다. 예전에 저장한 값은 지우지 않고 그대로 둔다
7
7
  // 문항 description은 편집 화면에서 적을 때만 생긴다 (새 문항에는 키가 없음)
8
- // 제출하는 답: 문자열 하나 (ADR 0008). 문항 순서대로 `문항id=답`을 `;`로 잇고, 주관식 답은 encodeURIComponent
9
- // "q1=b;q2=a,d;q3=c,a,b;q4=%EA%B0%80%EC%A4%91%EC%B9%98;q5=g1:a|g2:b,c"
8
+ // 제출하는 답: 문자열 하나 (ADR 0008 · 0013). 문항 순서대로 `문항id=답`을 `;`로 잇는다. 주관식 답은 답 형식(공개 값 answerFormat)에 따라
9
+ // - 2 (1.10.0부터 편집 화면이 저장): 원문, `%` → `%25` · `;` → `%3B`만 바꿈 "q1=b;q2=a,d;q4=가중치"
10
+ // - 없음 (1.9.x 이하가 저장한 자료): encodeURIComponent "q4=%EA%B0%80%EC%A4%91%EC%B9%98"
11
+ // 어느 쪽이든 decodeURIComponent 하나로 원래 답이 된다. 정답 정규식(grading)도 같은 형식으로 만들어 둘이 늘 짝이 맞는다
12
+ // 주관식 문항의 공개 값 answerMode: 'list'(허용 답 목록, 기본) · 'regex'(작성자 정규식). 다시 열 때 정답 입력 방식을 되살린다
10
13
  // 채점 방식은 둘 중 하나 (작성자가 고름, 완료 정책은 LXP 설정, ADR 0012). 정답(settings.grading)은 편집 화면이 문항마다 고른 답으로 만든다.
11
14
  // - pattern (기본, 모두 맞혀야 100점): 정규식 하나 { type: 'pattern', answer_key: '^q1=b;…$' }, 답은 위 문자열 하나
12
15
  // - partial_pattern (문항별 부분 점수): 문항마다 정규식 { type: 'partial_pattern', answer_key: ['^q1=b$', …], scores: [50, …] },
@@ -90,8 +93,14 @@ export function convertType(q, type, names) {
90
93
  { id: 'g2', name: names.group('B') },
91
94
  ];
92
95
  else delete next.groups;
93
- if (type === 'text') next.placeholder = q.placeholder ?? '';
94
- else delete next.placeholder;
96
+ if (type === 'text') {
97
+ next.placeholder = q.placeholder ?? '';
98
+ // 정답 입력 방식 (공개 값, ADR 0013): 직접 입력이 기본
99
+ next.answerMode = q.answerMode === 'regex' ? 'regex' : 'list';
100
+ } else {
101
+ delete next.placeholder;
102
+ delete next.answerMode;
103
+ }
95
104
  return next;
96
105
  }
97
106
 
@@ -200,21 +209,44 @@ export function decodeAnswer(q, text) {
200
209
  }
201
210
  }
202
211
 
212
+ // ---------- 답 형식 (ADR 0013) ----------
213
+
214
+ /** 1.10.0 편집 화면이 저장하는 답 형식. 공개 settings answerFormat에 둔다 (학생 화면이 주관식 답을 어떻게 보낼지 안다) */
215
+ export const ANSWER_FORMAT = 2;
216
+ /**
217
+ * 이 settings를 읽으려면 필요한 템플릿 버전 (공개 settings requires). 앞으로 형식을 바꾸는 판이 올리고, 옛 판 화면에 안내할 때 쓴다.
218
+ * 템플릿 이름을 키로 두어 한 settings를 여러 템플릿이 읽게 돼도 섞이지 않게 한다
219
+ */
220
+ export const REQUIRES = { quiz: '1.10.0' };
221
+
222
+ /** settings → 학생 화면이 쓸 답 형식 (1 = encodeURIComponent, 2 = 원문). 모르는 미래 형식(3 이상)은 2로 보낸다 */
223
+ export const answerFormatOf = (content) => (Number(content?.answerFormat) >= 2 ? 2 : 1);
224
+
225
+ /** 원문 형식 주관식 답: `%` · `;`만 바꾼다 (`;`는 문항 경계, `%`는 decodeURIComponent로 되돌릴 수 있게) */
226
+ export const encodeRaw = (text) => String(text).replace(/%/g, '%25').replace(/;/g, '%3B');
227
+
228
+ /** 주관식 답(앞뒤 공백을 자른 것) → 제출 문자열 조각 */
229
+ export const encodeText = (text, format = 1) =>
230
+ format >= 2 ? encodeRaw(text) : encodeURIComponent(text);
231
+
203
232
  // ---------- 제출 답 하나로 잇기 · 풀기 (ADR 0008) ----------
204
233
 
205
- /** 문항별 답 문자열 → 제출할 답 문자열 하나. 주관식 답은 encodeURIComponent (`;` · `=` · `|`가 들어가도 경계가 그대로) */
206
- export function joinAnswers(questions, values) {
234
+ /**
235
+ * 문항별 답 문자열 → 제출할 답 문자열 하나. 주관식 답은 encodeText (`;`가 들어가도 경계가 그대로).
236
+ * format: answerFormatOf(settings) (없으면 1 = 옛 형식)
237
+ */
238
+ export function joinAnswers(questions, values, format = 1) {
207
239
  return questions
208
240
  .map((q, i) => {
209
241
  const a = encodeAnswer(q, values[i]);
210
- return `${q.id}=${q.type === 'text' ? encodeURIComponent(a) : a}`;
242
+ return `${q.id}=${q.type === 'text' ? encodeText(a, format) : a}`;
211
243
  })
212
244
  .join(';');
213
245
  }
214
246
 
215
247
  /**
216
248
  * 제출한 답 → 문항 id별 답 문자열 (다시 열기 · 튜터링). 옛 답 `{ answers: { q1: "b" } }`도 받는다.
217
- * `;`로 나누고 첫 `=`에서 문항 id와 답을 나눈 뒤, 주관식은 decodeURIComponent
249
+ * `;`로 나누고 첫 `=`에서 문항 id와 답을 나눈 뒤, 주관식은 decodeURIComponent (답 형식 1 · 2 모두 이것 하나로 풀림)
218
250
  */
219
251
  export function splitAnswers(questions, answer) {
220
252
  // partial_pattern 답: 문항별 문자열 배열 → 한 문자열로 이어 같은 방식으로 푼다
@@ -241,60 +273,322 @@ export function splitAnswers(questions, answer) {
241
273
  return out;
242
274
  }
243
275
 
244
- // ---------- 정답 정규식 (편집 화면, ADR 0009) ----------
276
+ // ---------- 정답 정규식 (편집 화면, ADR 0009 · 0013) ----------
245
277
 
246
278
  const escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
247
279
  const unescapeRegex = (text) => text.replace(/\\(.)/g, '$1');
248
280
 
249
- /** 정답 하나(화면 값) → 문항 정규식 조각. 주관식은 허용 답 여러 개를 (?:…|…)로 */
250
- function keyPart(q, value) {
281
+ /** 주관식 정답 입력 방식: 'list'(허용 답 목록, 기본) · 'regex'(작성자 정규식) */
282
+ export const isRegexMode = (q) => q?.type === 'text' && q.answerMode === 'regex';
283
+
284
+ /** 정답 하나(화면 값) → 문항 정규식 조각. 주관식 목록은 허용 답 여러 개를 (?:…|…)로, 정규식은 바꾼 식을 (?:…)로 */
285
+ function keyPart(q, value, format) {
251
286
  if (q.type === 'text') {
252
- const alts = (value ?? []).map((t) => String(t).trim()).filter(Boolean);
253
- return `(?:${alts.map((t) => escapeRegex(encodeURIComponent(t))).join('|')})`;
287
+ if (isRegexMode(q)) {
288
+ const result = compileTextRegex(typeof value === 'string' ? value : '');
289
+ return `(?:${result.body ?? ''})`;
290
+ }
291
+ const alts = (Array.isArray(value) ? value : []).map((t) => String(t).trim()).filter(Boolean);
292
+ return `(?:${alts.map((t) => escapeRegex(encodeText(t, format))).join('|')})`;
254
293
  }
255
294
  return escapeRegex(encodeAnswer(q, value));
256
295
  }
257
296
 
258
297
  /**
259
- * 문항별 정답(화면 값: 주관식은 허용 답 배열) → regex 정답 정규식 하나.
260
- * 인코딩 → 정규식 이스케이프 → `|`로 묶기 → 전체를 `^…$` (ADR 0008 §4)
298
+ * 문항별 정답(화면 값: 주관식 목록은 허용 답 배열, 정규식은 작성자가 쓴 식) → regex 정답 정규식 하나.
299
+ * 인코딩 → 정규식 이스케이프 → `|`로 묶기 → 전체를 `^…$` (ADR 0008 §4). format: 답 형식 (편집 화면은 ANSWER_FORMAT)
261
300
  */
262
- export function buildAnswerKey(questions, key) {
263
- return `^${questions.map((q) => `${escapeRegex(q.id)}=${keyPart(q, key[q.id])}`).join(';')}$`;
301
+ export function buildAnswerKey(questions, key, format = 1) {
302
+ return `^${questions.map((q) => `${escapeRegex(q.id)}=${keyPart(q, key[q.id], format)}`).join(';')}$`;
303
+ }
304
+
305
+ /**
306
+ * 정답 정규식 `^…$` → 문항 조각 목록 (`문항id=…`). 경계는 `;문항id=` (정답 조각 안의 `;`는 주관식 인코딩 %3B이고,
307
+ * 작성자 정규식에는 `;`를 쓰지 못한다). 모양이 다르면 null
308
+ */
309
+ function keyParts(questions, regex) {
310
+ if (typeof regex !== 'string' || !regex.startsWith('^') || !regex.endsWith('$')) return null;
311
+ const body = regex.slice(1, -1);
312
+ const ids = questions.map((q) => escapeRegex(escapeRegex(q.id)));
313
+ return ids.length ? body.split(new RegExp(`;(?=(?:${ids.join('|')})=)`)) : body.split(';');
314
+ }
315
+
316
+ /** 정답 정규식 → 문항 id별 조각(`문항id=…`) Map. 모양이 다르면 null */
317
+ function splitKeyParts(questions, regex) {
318
+ const parts = keyParts(questions, regex);
319
+ if (!parts) return null;
320
+ const out = new Map();
321
+ for (const part of parts) {
322
+ const at = part.indexOf('=');
323
+ if (at < 0) return null;
324
+ out.set(unescapeRegex(part.slice(0, at)), part);
325
+ }
326
+ return out;
264
327
  }
265
328
 
266
329
  /**
267
330
  * buildAnswerKey가 만든 정규식 → 문항별 정답(화면 값). 다른 모양(손으로 쓴 정규식)이면 null.
268
- * 문항이 바뀌었으면 있는 문항만 돌려준다 (없는 문항은 validateAnswerKey가 알려 줌)
331
+ * 주관식 정규식 문항(answerMode 'regex')은 저장한 식을 작성자가 쓴 모양으로 되돌린다 (`%25` → `%`).
332
+ * 목록은 답 형식 1 · 2 모두 decodeURIComponent로 푼다. 문항이 바뀌었으면 있는 문항만 돌려준다 (없는 문항은 validateAnswerKey가 알려 줌)
269
333
  */
270
334
  export function parseAnswerKey(questions, regex) {
271
- if (typeof regex !== 'string' || !regex.startsWith('^') || !regex.endsWith('$')) return null;
335
+ const parts = keyParts(questions, regex);
336
+ if (!parts) return null;
272
337
  const byId = Object.fromEntries(questions.map((q) => [q.id, q]));
273
338
  const out = {};
274
- // 정답 조각 안의 `;`는 주관식 인코딩(%3B)이라 나오지 않는다
275
- for (const part of regex.slice(1, -1).split(';')) {
339
+ for (const part of parts) {
276
340
  const at = part.indexOf('=');
277
341
  if (at < 0) return null;
278
342
  const id = unescapeRegex(part.slice(0, at));
279
- const body = part.slice(at + 1);
343
+ const piece = part.slice(at + 1);
280
344
  const q = byId[id];
281
345
  if (!q) continue;
282
346
  if (q.type === 'text') {
283
- if (!body.startsWith('(?:') || !body.endsWith(')')) return null;
347
+ if (!piece.startsWith('(?:') || !piece.endsWith(')')) return null;
348
+ const inner = piece.slice(3, -1);
349
+ if (isRegexMode(q)) {
350
+ out[id] = inner.replace(/%25/g, '%');
351
+ continue;
352
+ }
284
353
  try {
285
- out[id] = body
286
- .slice(3, -1)
354
+ out[id] = inner
287
355
  .split(/(?<!\\)\|/)
288
356
  .map((t) => decodeURIComponent(unescapeRegex(t)))
289
357
  .filter(Boolean);
290
358
  } catch {
291
359
  return null;
292
360
  }
293
- } else out[id] = decodeAnswer(q, unescapeRegex(body));
361
+ } else out[id] = decodeAnswer(q, unescapeRegex(piece));
294
362
  }
295
363
  return out;
296
364
  }
297
365
 
366
+ /**
367
+ * 정규식 조각이 이스케이프한 글자만으로 된 `a|b|…`이면 허용 답 목록, 아니면 null (정규식 → 직접 입력으로 바꿀 때)
368
+ * @param {string} source 작성자가 쓴 정규식
369
+ */
370
+ export function regexToList(source) {
371
+ const out = [];
372
+ for (const alt of String(source ?? '').trim().split(/(?<!\\)\|/)) {
373
+ if (!alt) continue;
374
+ if (/[.*+?^${}()|[\]\\]/.test(alt.replace(/\\[\\.*+?^${}()|[\]]/g, ''))) return null;
375
+ out.push(unescapeRegex(alt));
376
+ }
377
+ return out;
378
+ }
379
+
380
+ /** 허용 답 목록 → 같은 뜻의 정규식 (직접 입력 → 정규식으로 바꿀 때) */
381
+ export const listToRegex = (list) =>
382
+ (list ?? [])
383
+ .map((t) => String(t).trim())
384
+ .filter(Boolean)
385
+ .map(escapeRegex)
386
+ .join('|');
387
+
388
+ // Python regex(서버)와 브라우저 RegExp가 같은 뜻으로 읽는 글자만 받는다
389
+ const ALLOWED_LETTER_ESCAPES = new Set(['d', 'D', 'w', 'W', 's', 'S', 'n', 'r', 't', 'f', 'v']);
390
+ // 서버 \w (Python regex, 유니코드): 글자 · 결합 문자 · 숫자 · 연결 문장 부호
391
+ const UNICODE_WORD = '\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}\\u200C\\u200D';
392
+ // u 플래그에서 \로 써도 되는 글자 (그 밖의 기호는 \ 없이 글자 그대로)
393
+ const U_SYNTAX = new Set([...'^$\\.*+?()[]{}|/']);
394
+
395
+ /**
396
+ * 작성자 주관식 정규식 → 서버 정답 조각(body, `(?:…)` 안에 들어감)과 채점 테스트용 JS 정규식(test, u 플래그).
397
+ * - 맨 앞 `^` · 맨 뒤 `$`는 뗀다 (답 전체와 맞춰 봄, notes에 'anchors')
398
+ * - 맨 앞 `(?i)`(대소문자 무시)는 `(?i:…)`로 감싼다 (가운데 전역 플래그는 서버 오류, notes에 'flag')
399
+ * - 답 형식 2에서 학생 답의 `%`는 `%25`로 가므로 식의 `%`(`\%`)도 `%25`로
400
+ * - 서버(Python regex)와 브라우저가 다르게 읽거나 한쪽만 아는 문법은 막는다 (error 코드)
401
+ * 채점 테스트(test)는 서버처럼: `\d` → `\p{Nd}`, `\w` → 유니코드 글자, `.`은 줄바꿈만 빼고
402
+ * @param {string} source
403
+ * @returns {{ body?: string, test?: string, notes: string[], error?: string, detail?: string }}
404
+ */
405
+ export function compileTextRegex(source) {
406
+ const notes = [];
407
+ let s = String(source ?? '').trim();
408
+ const fail = (error, detail) => ({ error, detail, notes });
409
+ if (!s) return fail('empty');
410
+ let ignoreCase = false;
411
+ // 맨 앞 `^` · `(?i)`는 어느 순서로 와도 뗀다
412
+ for (;;) {
413
+ const lead = /^\(\?([a-zA-Z]+)\)/.exec(s);
414
+ if (lead) {
415
+ if (lead[1] !== 'i') return fail('flag');
416
+ ignoreCase = true;
417
+ s = s.slice(lead[0].length);
418
+ if (!notes.includes('flag')) notes.push('flag');
419
+ } else if (s.startsWith('^')) {
420
+ s = s.slice(1);
421
+ if (!notes.includes('anchors')) notes.push('anchors');
422
+ } else break;
423
+ }
424
+ if (/(^|[^\\])(\\\\)*\$$/.test(s)) {
425
+ s = s.slice(0, -1);
426
+ if (!notes.includes('anchors')) notes.push('anchors');
427
+ }
428
+ if (!s) return fail('empty');
429
+ let body = '';
430
+ let test = '';
431
+ let inClass = false;
432
+ for (let i = 0; i < s.length; i++) {
433
+ const c = s[i];
434
+ if (c === ';') return fail('semicolon');
435
+ if (c === '\\') {
436
+ const n = s[i + 1];
437
+ if (n === undefined) return fail('invalid');
438
+ i++;
439
+ if (n === ';') return fail('semicolon');
440
+ if (n === '%') {
441
+ if (inClass) return fail('percentInClass');
442
+ body += '%25';
443
+ test += '%25';
444
+ continue;
445
+ }
446
+ if (/[1-9]/.test(n) || n === 'k' || n === 'g') return fail('backref');
447
+ if (n === 'p' || n === 'P') return fail('unicodeProperty');
448
+ if (n === 'b' || n === 'B') {
449
+ if (inClass && n === 'b') {
450
+ body += '\\b';
451
+ test += '\\x08';
452
+ continue;
453
+ }
454
+ return fail('wordBoundary');
455
+ }
456
+ if (n === '0') {
457
+ if (/[0-9]/.test(s[i + 1] ?? '')) return fail('escape', `\\0${s[i + 1]}`);
458
+ body += '\\0';
459
+ test += '\\0';
460
+ continue;
461
+ }
462
+ if (n === 'x') {
463
+ const hex = s.slice(i + 1, i + 3);
464
+ if (!/^[0-9A-Fa-f]{2}$/.test(hex)) return fail('escape', '\\x');
465
+ body += `\\x${hex}`;
466
+ test += `\\x${hex}`;
467
+ i += 2;
468
+ continue;
469
+ }
470
+ if (n === 'u') {
471
+ const hex = s.slice(i + 1, i + 5);
472
+ if (!/^[0-9A-Fa-f]{4}$/.test(hex)) return fail('escape', '\\u');
473
+ body += `\\u${hex}`;
474
+ test += `\\u${hex}`;
475
+ i += 4;
476
+ continue;
477
+ }
478
+ if (/[A-Za-z0-9]/.test(n)) {
479
+ if (!ALLOWED_LETTER_ESCAPES.has(n)) return fail('escape', `\\${n}`);
480
+ body += `\\${n}`;
481
+ if (n === 'd') test += '\\p{Nd}';
482
+ else if (n === 'w') test += inClass ? UNICODE_WORD : `[${UNICODE_WORD}]`;
483
+ else if (n === 'D' || n === 'W') {
484
+ if (inClass) return fail('negatedInClass', `\\${n}`);
485
+ test += n === 'D' ? '\\P{Nd}' : `[^${UNICODE_WORD}]`;
486
+ } else test += `\\${n}`;
487
+ continue;
488
+ }
489
+ // 기호: 서버는 글자 그대로. u 플래그는 문법 기호(와 [ ] 안의 -)만 \를 받는다
490
+ body += `\\${n}`;
491
+ test += U_SYNTAX.has(n) || (inClass && n === '-') ? `\\${n}` : n;
492
+ continue;
493
+ }
494
+ if (inClass) {
495
+ if (c === ']') inClass = false;
496
+ else if (c === '[') return fail('nestedClass');
497
+ else if (c === '%') return fail('percentInClass');
498
+ body += c;
499
+ test += c;
500
+ continue;
501
+ }
502
+ if (c === '[') {
503
+ const neg = s[i + 1] === '^';
504
+ const first = s[i + (neg ? 2 : 1)];
505
+ // [] · [^] · []a]: 브라우저와 서버가 다르게 읽는다
506
+ if (first === ']' || first === undefined) return fail('emptyClass');
507
+ inClass = true;
508
+ body += neg ? '[^' : '[';
509
+ test += neg ? '[^' : '[';
510
+ if (neg) i++;
511
+ continue;
512
+ }
513
+ if (c === '%') {
514
+ body += '%25';
515
+ test += '%25';
516
+ continue;
517
+ }
518
+ if (c === '^' || c === '$') return fail('anchorMiddle');
519
+ if (c === '.') {
520
+ body += '.';
521
+ // 서버 `.`은 줄바꿈(\n)만 빼고 모두 (브라우저는 \r · \u2028 · \u2029도 뺌)
522
+ test += '[^\\n]';
523
+ continue;
524
+ }
525
+ if (c === '(') {
526
+ if (s[i + 1] === '?') {
527
+ const rest = s.slice(i + 2);
528
+ const ok = ['<=', '<!', ':', '=', '!', 'i:'].find((p) => rest.startsWith(p));
529
+ if (!ok) {
530
+ if (/^(P?<[A-Za-z_]|P=|P>)/.test(rest)) return fail('namedGroup');
531
+ if (/^[a-zA-Z-]+\)/.test(rest)) return fail('flag');
532
+ return fail('group', `(?${rest.slice(0, 2)}`);
533
+ }
534
+ body += `(?${ok}`;
535
+ test += `(?${ok}`;
536
+ i += 1 + ok.length;
537
+ continue;
538
+ }
539
+ body += c;
540
+ test += c;
541
+ continue;
542
+ }
543
+ if (c === '{') {
544
+ const m = /^\{(\d*)(,?)(\d*)\}/.exec(s.slice(i));
545
+ if (m && m[1] === '' && m[2] === ',') return fail('quantifier', m[0]);
546
+ if (m && (m[1] !== '' || m[3] === '')) {
547
+ body += m[0];
548
+ test += m[0];
549
+ i += m[0].length - 1;
550
+ continue;
551
+ }
552
+ // 반복이 아닌 `{`는 서버에서 글자 그대로 (u 플래그는 \{여야 함)
553
+ body += '{';
554
+ test += '\\{';
555
+ continue;
556
+ }
557
+ if (c === '}' || c === ']') {
558
+ body += c;
559
+ test += `\\${c}`;
560
+ continue;
561
+ }
562
+ body += c;
563
+ test += c;
564
+ }
565
+ if (inClass) return fail('invalid');
566
+ if (ignoreCase) {
567
+ body = `(?i:${body})`;
568
+ test = `(?i:${test})`;
569
+ }
570
+ try {
571
+ new RegExp(`^(?:${test})$`, 'u');
572
+ } catch (e) {
573
+ return fail('invalid', e instanceof Error ? e.message : String(e));
574
+ }
575
+ return { body, test, notes };
576
+ }
577
+
578
+ /**
579
+ * 채점 테스트: 학생이 이 답을 내면 정답인지 (서버처럼 앞뒤 공백을 자르고 답 형식 2로 바꾼 뒤 전체 일치).
580
+ * 정규식이 틀리면 null
581
+ */
582
+ export function testTextRegex(source, answer) {
583
+ const { test } = compileTextRegex(source);
584
+ if (test === undefined) return null;
585
+ try {
586
+ return new RegExp(`^(?:${test})$`, 'u').test(encodeRaw(String(answer ?? '').trim()));
587
+ } catch {
588
+ return null;
589
+ }
590
+ }
591
+
298
592
  // ---------- 문항별 부분 점수 (partial_pattern) ----------
299
593
 
300
594
  export const PARTIAL = 'partial_pattern';
@@ -306,13 +600,13 @@ export function gradingTypeOf(content, grading) {
306
600
  }
307
601
 
308
602
  /** 문항별 답 → 제출할 문자열 배열 (문항 순서). 한 항목은 pattern 답의 한 조각과 같은 `문항id=답` */
309
- export function joinAnswerList(questions, values) {
310
- return questions.map((q, i) => joinAnswers([q], [values[i]]));
603
+ export function joinAnswerList(questions, values, format = 1) {
604
+ return questions.map((q, i) => joinAnswers([q], [values[i]], format));
311
605
  }
312
606
 
313
607
  /** 문항별 정답 → 문항마다 정답 정규식 `^문항id=…$` (buildAnswerKey를 문항 하나씩) */
314
- export function buildAnswerKeys(questions, key) {
315
- return questions.map((q) => buildAnswerKey([q], key));
608
+ export function buildAnswerKeys(questions, key, format = 1) {
609
+ return questions.map((q) => buildAnswerKey([q], key, format));
316
610
  }
317
611
 
318
612
  /** buildAnswerKeys가 만든 정규식 배열 → 문항별 정답(화면 값). 다른 모양이면 null */
@@ -326,10 +620,11 @@ export function parseAnswerKeys(questions, keys) {
326
620
  * 정답 검증 2 (문항별): 문항마다 checkAnswerKey (정답으로 낸 답은 맞고, 하나 바꾼 답은 맞지 않음).
327
621
  * 문제가 없으면 null, 있으면 { questionIndex, message }
328
622
  */
329
- export function checkAnswerKeys(questions, key, keys, v) {
623
+ export function checkAnswerKeys(questions, key, keys, v, format = 1) {
330
624
  for (const [i, q] of questions.entries()) {
625
+ if (isRegexMode(q)) continue;
331
626
  const at = (_no, message) => v.at(i + 1, message);
332
- const problem = checkAnswerKey([q], key, keys[i], { ...v, at });
627
+ const problem = checkAnswerKey([q], key, keys[i], { ...v, at }, format);
333
628
  if (!problem) continue;
334
629
  if (problem.message === v.badRegex) return { questionIndex: i, message: at(0, v.badRegex) };
335
630
  return {
@@ -377,7 +672,13 @@ export function validateAnswerKey(questions, key, v) {
377
672
  const at = (message) => ({ questionIndex: i, message: v.at(i + 1, message) });
378
673
  const value = key[q.id];
379
674
  if (q.type === 'text') {
380
- if (!(value ?? []).some((t) => String(t).trim())) return at(v.noAnswer);
675
+ if (isRegexMode(q)) {
676
+ const { error, detail } = compileTextRegex(typeof value === 'string' ? value : '');
677
+ if (error === 'empty') return at(v.noAnswer);
678
+ if (error) return at(v.regex[error]?.(detail) ?? v.regex.invalid(detail));
679
+ continue;
680
+ }
681
+ if (!(Array.isArray(value) ? value : []).some((t) => String(t).trim())) return at(v.noAnswer);
381
682
  continue;
382
683
  }
383
684
  if (!isAnswered(q, value)) return at(v.noAnswer);
@@ -508,7 +809,23 @@ export function wrongValue(q, value) {
508
809
  * 문제가 없으면 null, 있으면 { questionIndex, message }
509
810
  * @param {object} v 검증 문구 (ui/texts.js의 answers.validation)
510
811
  */
511
- export function checkAnswerKey(questions, key, regex, v) {
812
+ export function checkAnswerKey(questions, key, regex, v, format = 1) {
813
+ // 주관식 정규식 문항은 작성자가 일부러 넓게 쓸 수 있어 왕복 · 오답 검사에서 뺀다 (채점 테스트 · 빈 답 경고로 대신, ADR 0013).
814
+ // 나머지 문항만으로 만든 정규식으로 검사하고 문항 번호는 원래 자리로
815
+ if (questions.some(isRegexMode)) {
816
+ const kept = questions.map((q, i) => (isRegexMode(q) ? -1 : i)).filter((i) => i >= 0);
817
+ if (kept.length === 0) return null;
818
+ const sub = kept.map((i) => questions[i]);
819
+ // 받은 정규식에서 남길 문항 조각만 골라 잇는다 (모양이 다르면 다시 만들지 않고 그대로 검사해 왕복에서 걸리게)
820
+ const parts = splitKeyParts(questions, regex);
821
+ const subKey = parts
822
+ ? `^${sub.map((q) => parts.get(q.id) ?? '').join(';')}$`
823
+ : regex;
824
+ const problem = checkAnswerKey(sub, key, subKey, v, format);
825
+ return problem && problem.questionIndex >= 0
826
+ ? { ...problem, questionIndex: kept[problem.questionIndex] }
827
+ : problem;
828
+ }
512
829
  let re;
513
830
  try {
514
831
  re = new RegExp(regex);
@@ -517,20 +834,20 @@ export function checkAnswerKey(questions, key, regex, v) {
517
834
  }
518
835
  // 화면 값으로: 주관식은 허용 답 중 하나
519
836
  const base = questions.map((q) => (q.type === 'text' ? (key[q.id] ?? [])[0] : key[q.id]));
520
- if (!re.test(joinAnswers(questions, base))) return { questionIndex: -1, message: v.roundTrip };
837
+ if (!re.test(joinAnswers(questions, base, format))) return { questionIndex: -1, message: v.roundTrip };
521
838
  for (const [i, q] of questions.entries()) {
522
839
  const at = (message) => ({ questionIndex: i, message: v.at(i + 1, message) });
523
840
  if (q.type === 'text')
524
841
  for (const alt of key[q.id] ?? []) {
525
842
  const values = [...base];
526
843
  values[i] = alt;
527
- if (!re.test(joinAnswers(questions, values))) return at(v.roundTrip);
844
+ if (!re.test(joinAnswers(questions, values, format))) return at(v.roundTrip);
528
845
  }
529
846
  const wrong = wrongValue(q, key[q.id]);
530
847
  if (wrong === undefined) continue;
531
848
  const values = [...base];
532
849
  values[i] = q.type === 'text' ? wrong[0] : wrong;
533
- if (re.test(joinAnswers(questions, values))) return at(v.tooWide);
850
+ if (re.test(joinAnswers(questions, values, format))) return at(v.tooWide);
534
851
  }
535
852
  return null;
536
853
  }