@eliceio/cdk-cli 0.0.0-stage → 0.1.0-alpha.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.
- package/README.md +526 -2
- package/es/bin/index.d.ts +2 -0
- package/es/bin/index.js +10 -0
- package/es/cli.d.ts +5 -0
- package/es/cli.js +209 -0
- package/es/commands/build/index.d.ts +30 -0
- package/es/commands/build/index.js +163 -0
- package/es/commands/check/index.d.ts +9 -0
- package/es/commands/check/index.js +31 -0
- package/es/commands/create/index.d.ts +8 -0
- package/es/commands/create/index.js +22 -0
- package/es/commands/create/scaffold.d.ts +24 -0
- package/es/commands/create/scaffold.js +82 -0
- package/es/commands/dev/index.d.ts +6 -0
- package/es/commands/dev/index.js +40 -0
- package/es/commands/doctor/index.d.ts +34 -0
- package/es/commands/doctor/index.js +311 -0
- package/es/commands/guide/index.d.ts +29 -0
- package/es/commands/guide/index.js +120 -0
- package/es/commands/skill/index.d.ts +48 -0
- package/es/commands/skill/index.js +173 -0
- package/es/core/collect.d.ts +21 -0
- package/es/core/collect.js +89 -0
- package/es/core/config.d.ts +55 -0
- package/es/core/config.js +109 -0
- package/es/core/manifest.d.ts +15 -0
- package/es/core/manifest.js +43 -0
- package/es/core/minify.d.ts +18 -0
- package/es/core/minify.js +93 -0
- package/es/core/prepare.d.ts +12 -0
- package/es/core/prepare.js +86 -0
- package/es/core/protocol.d.ts +2 -0
- package/es/core/protocol.js +4 -0
- package/es/core/sandbox.d.ts +17 -0
- package/es/core/sandbox.js +182 -0
- package/es/core/zip.d.ts +4 -0
- package/es/core/zip.js +17 -0
- package/es/dev/grading.d.ts +15 -0
- package/es/dev/grading.js +37 -0
- package/es/dev/host-page.d.ts +7 -0
- package/es/dev/host-page.js +240 -0
- package/es/dev/inject.d.ts +8 -0
- package/es/dev/inject.js +38 -0
- package/es/dev/mock-api.d.ts +65 -0
- package/es/dev/mock-api.js +269 -0
- package/es/dev/server.d.ts +25 -0
- package/es/dev/server.js +309 -0
- package/es/engines/static/index.d.ts +3 -0
- package/es/engines/static/index.js +11 -0
- package/es/engines/types.d.ts +12 -0
- package/es/engines/vite/index.d.ts +2 -0
- package/es/engines/vite/index.js +4 -0
- package/es/index.d.ts +2 -0
- package/es/index.js +2 -0
- package/es/rules/check.d.ts +2 -0
- package/es/rules/check.js +282 -0
- package/es/rules/index.d.ts +8 -0
- package/es/rules/index.js +7 -0
- package/es/rules/manifest.d.ts +39 -0
- package/es/rules/manifest.js +168 -0
- package/es/rules/node.d.ts +11 -0
- package/es/rules/node.js +87 -0
- package/es/rules/path.d.ts +7 -0
- package/es/rules/path.js +35 -0
- package/es/rules/refs.d.ts +19 -0
- package/es/rules/refs.js +111 -0
- package/es/rules/skip.d.ts +12 -0
- package/es/rules/skip.js +55 -0
- package/es/rules/spec.d.ts +3 -0
- package/es/rules/spec.js +6 -0
- package/es/rules/types.d.ts +140 -0
- package/es/rules/unused.d.ts +7 -0
- package/es/rules/unused.js +21 -0
- package/es/rules/zip.d.ts +13 -0
- package/es/rules/zip.js +45 -0
- package/es/rules.json.js +3 -0
- package/es/types.d.ts +4 -0
- package/es/version.d.ts +2 -0
- package/es/version.js +7 -0
- package/guides/content-development.md +207 -0
- package/package.json +50 -3
- package/rules.json +608 -0
- package/skills/_shared/always.md +7 -0
- package/skills/elice-content-check/SKILL.md +22 -0
- package/skills/elice-content-create/SKILL.md +21 -0
- package/skills/elice-content-migrate/SKILL.md +21 -0
- package/templates/_shared/lib/cdk-mock.d.ts +94 -0
- package/templates/_shared/lib/cdk-mock.js +429 -0
- package/templates/_shared/lib/cdk.js +3 -0
- package/templates/_shared/lib/elice-content.css +262 -0
- package/templates/_shared/lib/elice-content.d.ts +123 -0
- package/templates/_shared/lib/elice-content.js +534 -0
- package/templates/_shared/lib/elice-tokens.css +446 -0
- package/templates/blank/README.md +64 -0
- package/templates/blank/commentary.txt +2 -0
- package/templates/blank/content.json +4 -0
- package/templates/blank/edit.html +15 -0
- package/templates/blank/elice.config.json +12 -0
- package/templates/blank/gitignore +3 -0
- package/templates/blank/index.html +15 -0
- package/templates/blank/instructor.html +15 -0
- package/templates/blank/screens/edit.js +21 -0
- package/templates/blank/screens/instructor.js +9 -0
- package/templates/blank/screens/learn.js +19 -0
- package/templates/blank/styles.css +1 -0
- package/templates/quiz/README.md +108 -0
- package/templates/quiz/commentary.txt +2 -0
- package/templates/quiz/content.json +81 -0
- package/templates/quiz/core/behaviors.d.ts +59 -0
- package/templates/quiz/core/behaviors.js +310 -0
- package/templates/quiz/core/dom.d.ts +13 -0
- package/templates/quiz/core/dom.js +83 -0
- package/templates/quiz/core/editor.d.ts +48 -0
- package/templates/quiz/core/editor.js +206 -0
- package/templates/quiz/core/markdown.d.ts +2 -0
- package/templates/quiz/core/markdown.js +84 -0
- package/templates/quiz/core/model.d.ts +20 -0
- package/templates/quiz/core/model.js +203 -0
- package/templates/quiz/edit.html +17 -0
- package/templates/quiz/elice.config.json +14 -0
- package/templates/quiz/gitignore +3 -0
- package/templates/quiz/grading.json +13 -0
- package/templates/quiz/index.html +17 -0
- package/templates/quiz/instructor.html +17 -0
- package/templates/quiz/screens/edit.js +139 -0
- package/templates/quiz/screens/instructor.js +27 -0
- package/templates/quiz/screens/learn.js +55 -0
- package/templates/quiz/styles.css +570 -0
- package/templates/quiz/ui/templates/choice.js +22 -0
- package/templates/quiz/ui/templates/edit.d.ts +13 -0
- package/templates/quiz/ui/templates/edit.js +183 -0
- package/templates/quiz/ui/templates/group.js +68 -0
- package/templates/quiz/ui/templates/index.d.ts +5 -0
- package/templates/quiz/ui/templates/index.js +17 -0
- package/templates/quiz/ui/templates/order.js +35 -0
- package/templates/quiz/ui/templates/page.js +29 -0
- package/templates/quiz/ui/templates/question.js +28 -0
- package/templates/quiz/ui/templates/text.js +16 -0
- package/templates/quiz/ui/texts.d.ts +3 -0
- package/templates/quiz/ui/texts.js +127 -0
- package/templates/quiz/ui/theme.css +50 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { zipSync } from 'fflate';
|
|
2
|
+
import { parseManifest } from './manifest.js';
|
|
3
|
+
import { isUnsafePath, extname, globToRegExp, resolveRef } from './path.js';
|
|
4
|
+
import { lineAt, parseTags, extractRefs, classifyRef } from './refs.js';
|
|
5
|
+
import { lineSkipper } from './skip.js';
|
|
6
|
+
import { rules } from './spec.js';
|
|
7
|
+
|
|
8
|
+
const MB = 1024 * 1024;
|
|
9
|
+
const fmtMB = n => `${(n / MB).toFixed(1)}MB`;
|
|
10
|
+
function matchExclude(path, group) {
|
|
11
|
+
const segs = path.split('/');
|
|
12
|
+
const name = segs[segs.length - 1] ?? '';
|
|
13
|
+
if (group.files.some(g => globToRegExp(g).test(name))) return true;
|
|
14
|
+
return segs.slice(0, -1).some(seg => group.dirs.some(d => d.toLowerCase() === seg.toLowerCase()));
|
|
15
|
+
}
|
|
16
|
+
/** 비밀 값을 찾아볼 텍스트 파일 (이미지 · 글꼴 등 바이너리 제외) */
|
|
17
|
+
const SECRET_SCAN_EXTENSIONS = new Set(['html', 'htm', 'css', 'js', 'mjs', 'json', 'map', 'txt', 'md', 'csv', 'xml', 'vtt', 'svg']);
|
|
18
|
+
/** `<base href>`가 페이지 자기 폴더가 아니면 이유 (문제없으면 null) */
|
|
19
|
+
function baseHrefError(page, href) {
|
|
20
|
+
const kind = classifyRef(href);
|
|
21
|
+
if (kind === 'root' || kind === 'external') return '는 이 페이지의 상대경로를 모두 배포 주소 밖으로 보냅니다. 지워 주세요.';
|
|
22
|
+
if (kind !== 'local') return null;
|
|
23
|
+
// 기준은 폴더: 끝이 /가 아니면 마지막 조각은 파일 이름이라 뺀다
|
|
24
|
+
const clean = href.replace(/[?#].*$/, '');
|
|
25
|
+
const dir = clean.endsWith('/') ? clean : clean.slice(0, clean.lastIndexOf('/') + 1);
|
|
26
|
+
const resolved = resolveRef(page, dir || './');
|
|
27
|
+
if (resolved === null) return '는 zip 밖(배포 주소 밖)을 가리켜 이 페이지의 상대경로가 모두 깨집니다. 지워 주세요.';
|
|
28
|
+
const pageDir = page.split('/').slice(0, -1).join('/');
|
|
29
|
+
if (resolved !== pageDir) return `는 상대경로 기준을 ${resolved || 'zip 최상위'}로 바꿉니다. 검사는 파일 위치 기준이라 ./만 허용합니다. 지우고 경로를 파일 위치 기준으로 써 주세요.`;
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
const UTF8_BOM = [0xef, 0xbb, 0xbf];
|
|
33
|
+
const startsWithBom = data => UTF8_BOM.every((b, i) => data[i] === b);
|
|
34
|
+
/** 글자로 읽는 파일: UTF-8이 아니면 한글이 깨진다 */
|
|
35
|
+
const UTF8_EXTENSIONS = new Set(['html', 'htm', 'js', 'mjs', 'css', 'json', 'svg', 'csv', 'md']);
|
|
36
|
+
/** 학생 브라우저로 내려가는 JSON에 정답처럼 보이는 키 */
|
|
37
|
+
const ANSWER_KEYS = /^(?:answers?|correct(?:_?answers?)?|answer_?key|is_?correct|solutions?|정답)$/i;
|
|
38
|
+
function answerKeyPath(value, path = []) {
|
|
39
|
+
if (Array.isArray(value)) {
|
|
40
|
+
for (const [i, v] of value.entries()) {
|
|
41
|
+
const found = answerKeyPath(v, [...path, String(i)]);
|
|
42
|
+
if (found) return found;
|
|
43
|
+
}
|
|
44
|
+
} else if (value && typeof value === 'object') {
|
|
45
|
+
for (const [k, v] of Object.entries(value)) {
|
|
46
|
+
if (ANSWER_KEYS.test(k)) return [...path, k].join('.');
|
|
47
|
+
const found = answerKeyPath(v, [...path, k]);
|
|
48
|
+
if (found) return found;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* 화면 코드가 지원 채점 유형 · 편집 화면과 맞는지 (키트 lib/는 빼고 콘텐츠 코드에서 함수 이름을 찾는 방식이라 경고만).
|
|
55
|
+
* 제출형 유형인데 제출이 없으면 교육자가 그 유형을 골랐을 때 학생이 완료할 수 없고,
|
|
56
|
+
* 편집 화면인데 저장이 없으면 편집 내용이 LXP로 넘어가지 않는다.
|
|
57
|
+
*/
|
|
58
|
+
function checkScreenCode(files, manifest, add) {
|
|
59
|
+
const decoder = new TextDecoder();
|
|
60
|
+
const texts = files.filter(f => /\.(?:m?js|html?)$/i.test(f.path) && !f.path.startsWith('lib/')).map(f => decoder.decode(f.data));
|
|
61
|
+
// ecdk build가 묶은 HTML에는 키트(useSubmit · useSave 정의)가 화면 코드와 함께 들어가 나눌 수 없다.
|
|
62
|
+
// 이런 zip은 판단하지 않는다: build가 묶기 전 원본으로 이미 검사했다
|
|
63
|
+
if (texts.some(t => /<script\b[^>]*\sdata-ecdk-bundle\b/i.test(t))) return;
|
|
64
|
+
const code = texts.join('\n');
|
|
65
|
+
const submitTypes = (manifest.gradingTypes ?? []).filter(t => t !== 'on_access');
|
|
66
|
+
if (submitTypes.length > 0 && !/\buseSubmit\b|\.submit\s*\(/.test(code)) add('grading.no-submit', `지원 채점 유형에 ${submitTypes.join(' · ')}가 있는데 화면 코드에 제출(app.useSubmit · sdk.submit)이 없습니다. 교육자가 이 유형을 고르면 학생이 완료할 수 없습니다. 제출을 넣거나 gradingTypes를 ["on_access"]로 줄여 주세요.`);
|
|
67
|
+
if (manifest.entries.edit && !/\buseSave\b|\bsaveSettings\s*\(|\bsaveContent\s*\(/.test(code)) add('edit.no-save', `편집 화면(${manifest.entries.edit})을 켰는데 저장(app.useSave · sdk.saveSettings)이 없습니다. 편집한 내용이 LXP로 넘어가지 않습니다.`);
|
|
68
|
+
}
|
|
69
|
+
/** `<script type="module" data-ecdk-bundle>` 본문을 줄 수만 남기고 비운다 (줄 번호 유지) */
|
|
70
|
+
function blankBundles(html) {
|
|
71
|
+
return html.replace(/(<script\b[^>]*\sdata-ecdk-bundle\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi, (_, open, body, close) => open + body.replace(/[^\n]/g, '') + close);
|
|
72
|
+
}
|
|
73
|
+
function textKind(path) {
|
|
74
|
+
const ext = extname(path);
|
|
75
|
+
if (ext === 'html' || ext === 'htm') return 'html';
|
|
76
|
+
if (ext === 'css') return 'css';
|
|
77
|
+
if (ext === 'js' || ext === 'mjs') return 'js';
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
/** 최상위에 파일이 없고 폴더가 하나뿐인 zip (폴더째 묶음). 벗겨 내지 않고 거절한다 (ADR 0004). */
|
|
81
|
+
function singleRootFolder(files) {
|
|
82
|
+
const tops = new Set(files.map(f => f.path.split('/')[0]));
|
|
83
|
+
const [only] = tops;
|
|
84
|
+
if (tops.size !== 1 || only === undefined || files.some(f => !f.path.includes('/'))) return null;
|
|
85
|
+
return only;
|
|
86
|
+
}
|
|
87
|
+
function estimateZipBytes(files) {
|
|
88
|
+
return zipSync(Object.fromEntries(files.map(f => [f.path, f.data])), {
|
|
89
|
+
level: 9
|
|
90
|
+
}).byteLength;
|
|
91
|
+
}
|
|
92
|
+
function checkFiles(input, opts = {}) {
|
|
93
|
+
const spec = opts.spec ?? rules;
|
|
94
|
+
const kind = opts.input ?? 'zip';
|
|
95
|
+
const levelOf = new Map(spec.rules.map(r => [r.id, r.level]));
|
|
96
|
+
const issues = [];
|
|
97
|
+
const add = (id, message, path, line) => issues.push({
|
|
98
|
+
id,
|
|
99
|
+
level: levelOf.get(id) ?? 'error',
|
|
100
|
+
message,
|
|
101
|
+
path,
|
|
102
|
+
line
|
|
103
|
+
});
|
|
104
|
+
for (const f of input) {
|
|
105
|
+
if (isUnsafePath(f.path)) add('path.unsafe', `안전하지 않은 경로입니다: ${f.path}`, f.path);
|
|
106
|
+
}
|
|
107
|
+
const files = input.filter(f => !f.dir && !isUnsafePath(f.path));
|
|
108
|
+
if (kind === 'html') add('input.not-zip', 'HTML 파일 하나는 올릴 수 없습니다. metadata.json과 함께 zip으로 묶어 주세요 (ecdk build가 만들어 줍니다).');
|
|
109
|
+
const nestedRoot = singleRootFolder(files);
|
|
110
|
+
if (nestedRoot) add('entry.nested', `모든 파일이 ${nestedRoot}/ 폴더 안에 있습니다. 폴더가 아니라 폴더 안의 파일들을 묶어 주세요 (metadata.json이 zip 최상위에 있어야 합니다).`, `${nestedRoot}/`);
|
|
111
|
+
const exact = new Set(files.map(f => f.path));
|
|
112
|
+
const decoder = new TextDecoder();
|
|
113
|
+
// metadata.json (최상위, 필수)
|
|
114
|
+
let manifest = null;
|
|
115
|
+
const mfile = files.find(f => f.path === spec.manifest.file);
|
|
116
|
+
if (mfile) {
|
|
117
|
+
const parsed = parseManifest(decoder.decode(mfile.data), spec);
|
|
118
|
+
if (parsed.ok) manifest = parsed.manifest;else add('manifest.invalid', `${spec.manifest.file}: ${parsed.error}`, spec.manifest.file);
|
|
119
|
+
} else if (kind !== 'html' && !nestedRoot) {
|
|
120
|
+
add('manifest.missing', `최상위에 ${spec.manifest.file}이 없습니다. 학생 화면·교육자 화면 등 어떤 화면이 있는지 적어 주세요 (ecdk build가 만들어 줍니다).`);
|
|
121
|
+
}
|
|
122
|
+
if (manifest) {
|
|
123
|
+
for (const [mode, file] of Object.entries(manifest.entries)) {
|
|
124
|
+
if (!exact.has(file)) add('manifest.entry-missing', `${spec.manifest.file}에 적은 ${mode} 화면 파일이 없습니다: ${file}`, spec.manifest.file);
|
|
125
|
+
}
|
|
126
|
+
const commentaryFile = manifest.commentary === undefined ? undefined : files.find(f => f.path === manifest.commentary);
|
|
127
|
+
// LXP 업로드는 학습 참고 내용이 없는 자료 본문을 거절한다 (qa5에서 확인. 스펙은 선택이었음)
|
|
128
|
+
if ((manifest.kind ?? spec.manifest.defaultKind) !== 'description' && manifest.commentary === undefined) add('manifest.commentary-missing', `학습 참고 내용 파일이 없어 LXP 업로드가 거절됩니다. 프로젝트 맨 위에 ${spec.manifest.commentaryFile}(이 자료의 핵심 개념 · 활동 · 문제 의도, 정답 제외)을 만들어 주세요.`, spec.manifest.file);
|
|
129
|
+
if (manifest.commentary !== undefined && !commentaryFile) add('manifest.entry-missing', `${spec.manifest.file}에 적은 학습 참고 내용 파일이 없습니다: ${manifest.commentary}`, spec.manifest.file);
|
|
130
|
+
// LXP 학습 참고 내용 칸으로 옮길 텍스트라 UTF-8이어야 한다 (메모장 ANSI · EUC-KR 저장이면 깨짐)
|
|
131
|
+
if (commentaryFile) {
|
|
132
|
+
try {
|
|
133
|
+
new TextDecoder('utf-8', {
|
|
134
|
+
fatal: true
|
|
135
|
+
}).decode(commentaryFile.data);
|
|
136
|
+
} catch {
|
|
137
|
+
add('manifest.invalid', `학습 참고 내용 파일이 UTF-8이 아닙니다: ${commentaryFile.path}. UTF-8로 다시 저장해 주세요.`, commentaryFile.path);
|
|
138
|
+
}
|
|
139
|
+
// 메모장 등이 붙이는 BOM은 학습 참고 내용 칸에 보이지 않는 글자로 들어간다
|
|
140
|
+
if (startsWithBom(commentaryFile.data)) add('file.bom', `학습 참고 내용 파일 맨 앞에 BOM(보이지 않는 글자)이 있습니다: ${commentaryFile.path}. "UTF-8(BOM 없음)"으로 다시 저장해 주세요.`, commentaryFile.path);
|
|
141
|
+
}
|
|
142
|
+
checkScreenCode(files, manifest, (id, message) => add(id, message, spec.manifest.file));
|
|
143
|
+
}
|
|
144
|
+
const entry = manifest?.entries.learn ?? spec.manifest.defaultEntry;
|
|
145
|
+
if (!manifest && !exact.has(entry)) add('entry.missing', `최상위에 ${entry} 파일이 없습니다.`);
|
|
146
|
+
// 한도
|
|
147
|
+
const {
|
|
148
|
+
maxFiles,
|
|
149
|
+
maxZipBytes,
|
|
150
|
+
warnRatio,
|
|
151
|
+
maxImageBytes
|
|
152
|
+
} = spec.limits;
|
|
153
|
+
const totalBytes = files.reduce((n, f) => n + f.data.byteLength, 0);
|
|
154
|
+
const zipBytes = opts.zipBytes ?? estimateZipBytes(files);
|
|
155
|
+
if (files.length > maxFiles) add('limit.file-count', `파일이 ${files.length}개입니다 (한도 ${maxFiles}개).`);else if (files.length >= maxFiles * warnRatio) add('limit.near', `파일 ${files.length}개 · 한도 ${maxFiles}개에 가깝습니다.`);
|
|
156
|
+
if (zipBytes > maxZipBytes) add('limit.zip-size', `zip 크기가 ${fmtMB(zipBytes)}입니다 (한도 ${fmtMB(maxZipBytes)}). 영상은 비디오 자료로 따로 올리고 이미지는 줄여 주세요.`);else if (zipBytes >= maxZipBytes * warnRatio) add('limit.near', `zip ${fmtMB(zipBytes)} · 한도 ${fmtMB(maxZipBytes)}에 가깝습니다.`);
|
|
157
|
+
// 경로 · 파일 종류
|
|
158
|
+
const byLower = new Map();
|
|
159
|
+
for (const f of files) {
|
|
160
|
+
const key = f.path.toLowerCase();
|
|
161
|
+
byLower.set(key, [...(byLower.get(key) ?? []), f.path]);
|
|
162
|
+
if (/[^\x21-\x7e]/.test(f.path)) add('path.non-ascii', `공백이나 ASCII 밖 문자가 든 경로입니다: ${f.path}`, f.path);
|
|
163
|
+
if (matchExclude(f.path, spec.excluded.secret)) add('file.secret', `정답·비밀 파일은 올리면 안 됩니다: ${f.path}`, f.path);else if (matchExclude(f.path, spec.excluded.dev)) add('file.dev', `개발용 폴더의 파일입니다: ${f.path}`, f.path);else if (matchExclude(f.path, spec.excluded.junk)) add('file.junk', `불필요한 파일입니다: ${f.path}`, f.path);else if (!spec.allowedExtensions.includes(extname(f.path))) add('file.extension', `허용하지 않는 파일 종류입니다: ${f.path}`, f.path);else if (spec.imageExtensions.includes(extname(f.path)) && f.data.byteLength > maxImageBytes) add('file.large-image', `${fmtMB(maxImageBytes)}가 넘는 이미지입니다 (${fmtMB(f.data.byteLength)}). 줄이면 학생 화면이 빨리 열립니다: ${f.path}`, f.path);
|
|
164
|
+
const ext = extname(f.path);
|
|
165
|
+
if (!UTF8_EXTENSIONS.has(ext) || matchExclude(f.path, spec.excluded.dev)) continue;
|
|
166
|
+
let text;
|
|
167
|
+
try {
|
|
168
|
+
text = new TextDecoder('utf-8', {
|
|
169
|
+
fatal: true
|
|
170
|
+
}).decode(f.data);
|
|
171
|
+
} catch {
|
|
172
|
+
add('file.encoding', `UTF-8이 아닌 파일입니다 (EUC-KR · ANSI로 저장하면 한글이 깨집니다): ${f.path}. UTF-8로 다시 저장해 주세요.`, f.path);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
// content.json 등은 학생 브라우저로 그대로 내려간다. 파일 이름(answers.*)만 막아서는 파일 안의 정답을 못 잡는다
|
|
176
|
+
if (ext === 'json' && f.path !== spec.manifest.file) {
|
|
177
|
+
let data = null;
|
|
178
|
+
try {
|
|
179
|
+
data = JSON.parse(text);
|
|
180
|
+
} catch {
|
|
181
|
+
data = null;
|
|
182
|
+
}
|
|
183
|
+
const key = answerKeyPath(data);
|
|
184
|
+
if (key) add('content.answer-key', `학생에게 내려가는 JSON에 정답처럼 보이는 키가 있습니다: ${key}. 정답은 grading.json · LXP 채점 설정에 두고 zip에서 빼 주세요.`, f.path);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
for (const paths of byLower.values()) {
|
|
188
|
+
if (paths.length > 1) add('path.case-collision', `대소문자만 다른 경로가 있습니다: ${paths.join(', ')}`, paths[0]);
|
|
189
|
+
}
|
|
190
|
+
// 참조 · 태그 · API (텍스트 파일)
|
|
191
|
+
const apis = spec.forbiddenApis.map(a => ({
|
|
192
|
+
...a,
|
|
193
|
+
re: new RegExp(a.pattern, 'g')
|
|
194
|
+
}));
|
|
195
|
+
const checkRef = (from, ref) => {
|
|
196
|
+
const type = classifyRef(ref.value);
|
|
197
|
+
if (type === 'skip') return;
|
|
198
|
+
if (type === 'external') {
|
|
199
|
+
if (ref.role === 'script') add('ref.external-script', `외부 스크립트를 불러옵니다: ${ref.value}. 스크립트 파일을 zip 안에 넣고 상대경로로 불러와 주세요.`, from, ref.line);else if (ref.role === 'resource' && /^http:/i.test(ref.value)) add('ref.insecure', `http:// 리소스는 https 페이지에서 막힙니다: ${ref.value}`, from, ref.line);else if (ref.role === 'resource') add('ref.external-request', `zip 밖 리소스를 불러옵니다: ${ref.value}. 막히면 글꼴·이미지가 보이지 않으니 zip 안에 넣어 주세요.`, from, ref.line);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
if (type === 'root') add('ref.root-absolute', `/로 시작하는 경로는 배포 주소에서 깨집니다. 상대경로로 바꿔 주세요: ${ref.value}`, from, ref.line);
|
|
203
|
+
let clean = ref.value.replace(/[?#].*$/, '');
|
|
204
|
+
try {
|
|
205
|
+
clean = decodeURI(clean);
|
|
206
|
+
} catch {
|
|
207
|
+
// 잘못된 % 인코딩은 그대로 비교
|
|
208
|
+
}
|
|
209
|
+
const target = resolveRef(from, clean);
|
|
210
|
+
const candidates = target === null ? [] : clean.endsWith('/') || target === '' ? [`${target}${target ? '/' : ''}index.html`] : [target];
|
|
211
|
+
if (candidates.some(c => exact.has(c))) return;
|
|
212
|
+
const ci = candidates.flatMap(c => byLower.get(c.toLowerCase()) ?? []);
|
|
213
|
+
if (ci.length > 0) add('ref.case-mismatch', `${ref.value}를 참조했지만 실제 파일은 ${ci[0]}입니다 (서버는 대소문자를 구분합니다).`, from, ref.line);else if (type !== 'root') add('ref.missing', `참조한 파일이 없습니다: ${ref.value}`, from, ref.line);
|
|
214
|
+
};
|
|
215
|
+
// 비밀 값: 주석 안에 있어도 유출이라 주석 줄도 본다. 값은 메시지에 싣지 않는다
|
|
216
|
+
const secrets = spec.secretPatterns.map(s => ({
|
|
217
|
+
...s,
|
|
218
|
+
re: new RegExp(s.pattern, `${s.flags ?? ''}g`),
|
|
219
|
+
notRe: s.not ? new RegExp(s.not, 'i') : null
|
|
220
|
+
}));
|
|
221
|
+
for (const f of files) {
|
|
222
|
+
if (!SECRET_SCAN_EXTENSIONS.has(extname(f.path)) || matchExclude(f.path, spec.excluded.dev)) continue;
|
|
223
|
+
const text = decoder.decode(f.data);
|
|
224
|
+
const skip = lineSkipper(text, {
|
|
225
|
+
skipComments: false
|
|
226
|
+
});
|
|
227
|
+
for (const s of secrets) {
|
|
228
|
+
for (const m of text.matchAll(s.re)) {
|
|
229
|
+
if (s.notRe?.test(m[0])) continue;
|
|
230
|
+
const line = lineAt(text, m.index);
|
|
231
|
+
if (skip.isSkipped(line, 'sec.secret')) continue;
|
|
232
|
+
add('sec.secret', `${s.title}로 보이는 값이 있습니다 (semgrep ${s.source}). 이미 올렸다면 키를 폐기하고, zip에서 빼 주세요.`, f.path, line);
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
for (const f of files) {
|
|
238
|
+
const kindOf = textKind(f.path);
|
|
239
|
+
if (!kindOf || matchExclude(f.path, spec.excluded.dev)) continue;
|
|
240
|
+
const text = decoder.decode(f.data);
|
|
241
|
+
const tags = kindOf === 'html' ? parseTags(text) : [];
|
|
242
|
+
for (const ref of extractRefs(kindOf, text, tags)) checkRef(f.path, ref);
|
|
243
|
+
for (const t of tags) {
|
|
244
|
+
// <base href>는 그 페이지 모든 상대경로의 기준을 바꾼다. 페이지 자기 폴더(./)만 허용한다:
|
|
245
|
+
// /·외부 주소·zip 밖(../)은 배포 주소(/s/{서명}/) 밖으로 나가고, 하위 폴더는 참조 검사(파일 위치 기준)와 어긋난다
|
|
246
|
+
const baseHref = t.name === 'base' ? t.attrs.get('href')?.trim() : undefined;
|
|
247
|
+
const baseError = baseHref === undefined ? null : baseHrefError(f.path, baseHref);
|
|
248
|
+
if (baseHref !== undefined && baseError) add('ref.root-absolute', `<base href="${baseHref}">${baseError}`, f.path, t.line);
|
|
249
|
+
// LXP는 origin null sandbox에서 열고 파일 서버가 CORS 헤더를 주지 않아, 모듈 스크립트 파일은 받지 못한다
|
|
250
|
+
const src = t.name === 'script' ? t.attrs.get('src')?.trim() : undefined;
|
|
251
|
+
if (src !== undefined && t.attrs.get('type')?.trim().toLowerCase() === 'module' && classifyRef(src) === 'local' && kind !== 'dir' && !opts.bundlesModules) add('sandbox.module-src', `<script type="module" src="${src}">는 LXP에서 막혀(CORS) 화면이 "불러오는 중"에서 멈춥니다. ecdk build로 만들면 HTML 안에 묶어 넣습니다. 직접 묶으려면 본문을 넣은 <script type="module">이나 일반 <script src>로 바꿔 주세요.`, f.path, t.line);
|
|
252
|
+
if (t.name === 'img' && !t.attrs.has('alt')) add('html.img-alt', `대체 텍스트(alt)가 없는 이미지입니다.`, f.path, t.line);
|
|
253
|
+
if (t.name === 'form') add('html.form', 'form 제출은 sandbox에서 막힙니다. 버튼 click 처리와 SDK 제출을 써 주세요.', f.path, t.line);
|
|
254
|
+
}
|
|
255
|
+
if (kindOf === 'css') continue;
|
|
256
|
+
const skip = lineSkipper(text);
|
|
257
|
+
// ecdk build가 묶어 넣은 모듈 본문은 건너뛴다: 원본을 ecdk-ignore 주석과 함께 이미 검사했고, 묶으면 주석이 사라진다
|
|
258
|
+
const scanned = kindOf === 'html' ? blankBundles(text) : text;
|
|
259
|
+
for (const api of apis) {
|
|
260
|
+
// 파일마다 처음 걸린 곳 하나만. 주석뿐인 줄과 ecdk-ignore 주석으로 끈 줄은 건너뛴다 (skip.ts)
|
|
261
|
+
for (const m of scanned.matchAll(api.re)) {
|
|
262
|
+
const line = lineAt(scanned, m.index);
|
|
263
|
+
if (skip.isSkipped(line, api.id)) continue;
|
|
264
|
+
add(api.id, `${api.title}: ${m[0]}`, f.path, line);
|
|
265
|
+
break;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return {
|
|
270
|
+
ok: !issues.some(i => i.level === 'error'),
|
|
271
|
+
rulesVersion: spec.version,
|
|
272
|
+
stats: {
|
|
273
|
+
files: files.length,
|
|
274
|
+
totalBytes,
|
|
275
|
+
zipBytes
|
|
276
|
+
},
|
|
277
|
+
manifest,
|
|
278
|
+
issues
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export { checkFiles };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { checkFiles } from './check.js';
|
|
2
|
+
export { gradingTypesError, parseManifest, serializeManifest } from './manifest.js';
|
|
3
|
+
export { globToRegExp } from './path.js';
|
|
4
|
+
export { commentOnlyLines, lineSkipper } from './skip.js';
|
|
5
|
+
export { rules, RULES_VERSION } from './spec.js';
|
|
6
|
+
export { findUnreferenced } from './unused.js';
|
|
7
|
+
export { filesFromHtml, filesFromZip, ZipLimitError } from './zip.js';
|
|
8
|
+
export type * from './types.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { checkFiles } from './check.js';
|
|
2
|
+
export { gradingTypesError, parseManifest, serializeManifest } from './manifest.js';
|
|
3
|
+
export { globToRegExp } from './path.js';
|
|
4
|
+
export { commentOnlyLines, lineSkipper } from './skip.js';
|
|
5
|
+
export { RULES_VERSION, rules } from './spec.js';
|
|
6
|
+
export { findUnreferenced } from './unused.js';
|
|
7
|
+
export { ZipLimitError, filesFromHtml, filesFromZip } from './zip.js';
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Manifest, RulesSpec } from './types.js';
|
|
2
|
+
export type ParsedManifest = {
|
|
3
|
+
ok: true;
|
|
4
|
+
manifest: Manifest;
|
|
5
|
+
} | {
|
|
6
|
+
ok: false;
|
|
7
|
+
error: string;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* 지원 채점 유형 목록 검사 (metadata.json · elice.config.json 공통). 문제가 없으면 null.
|
|
11
|
+
* 수동 채점(manual) · 채점 없음(none)은 Custom HTML에서 쓰지 않는다.
|
|
12
|
+
*/
|
|
13
|
+
export declare function gradingTypesError(value: unknown, allowed: readonly string[]): string | null;
|
|
14
|
+
/**
|
|
15
|
+
* metadata.json (zip 최상위): 용도, 화면(모드)별 사용 여부와 진입 파일, 빌드 정보. 정답은 넣지 않는다.
|
|
16
|
+
*
|
|
17
|
+
* {
|
|
18
|
+
* "kind": "material", // 선택. material: 자료 본문(기본) · description: 문제 설명
|
|
19
|
+
* "screens": { // 화면 3개 모두 적는다
|
|
20
|
+
* "learn": { "enabled": true, "entry": "index.html" },
|
|
21
|
+
* "instructor": { "enabled": true, "entry": "instructor.html" },
|
|
22
|
+
* "edit": { "enabled": false }
|
|
23
|
+
* },
|
|
24
|
+
* // 이 자료가 지원하는 채점 유형 모두 (교육자가 LXP 채점 설정에서 하나를 고름). 자료 본문은 필수, 문제 설명에는 없음
|
|
25
|
+
* // on_access · on_submit · pattern · rubric (rules.json manifest.gradingTypes). manual · none은 없음
|
|
26
|
+
* "gradingTypes": ["on_access", "on_submit", "pattern", "rubric"],
|
|
27
|
+
* "commentary": "commentary.txt", // 선택. 학습 참고 내용 파일 (zip 최상위, 일반 텍스트)
|
|
28
|
+
* "build": { "cli": "0.1.0", "rules": "0.2.0", "protocol": 1, "engine": "static" } // 선택
|
|
29
|
+
* }
|
|
30
|
+
*
|
|
31
|
+
* 파싱 결과의 `entries`는 켠 화면만 담는다. 서버 `material_draft.manifest`(JSONB) · SDK `MaterialManifest`의
|
|
32
|
+
* `{ entries }`가 이 모양이라 서버는 그대로 저장할 수 있다. 형식은 서버·디자인과 확정 전 제안안 (ADR 0004).
|
|
33
|
+
*/
|
|
34
|
+
export declare function parseManifest(text: string, spec: RulesSpec): ParsedManifest;
|
|
35
|
+
/**
|
|
36
|
+
* 화면 3개의 사용 여부(enabled)를 모두 적는다. 필드 순서(kind · screens · gradingTypes · commentary · build)와 화면 순서(learn · instructor · edit)를
|
|
37
|
+
* 고정해 같은 입력이면 같은 파일이 나오게 한다. kind가 없으면 기본값을 적는다.
|
|
38
|
+
*/
|
|
39
|
+
export declare function serializeManifest(manifest: Manifest, spec: RulesSpec): string;
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
const isRecord = v => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
2
|
+
/**
|
|
3
|
+
* metadata.json에 적는 파일 이름(진입 파일 · 학습 참고 내용): zip 최상위, 영문 · 숫자 · `.` · `_` · `-`만.
|
|
4
|
+
* LXP가 배포 주소 뒤에 그대로 붙여 열므로 공백 · 한글 · `?` · `#` · `%`처럼 URL 인코딩이 필요한 글자는 받지 않는다.
|
|
5
|
+
*/
|
|
6
|
+
const SAFE_FILE_NAME = /^[A-Za-z0-9._-]+$/;
|
|
7
|
+
const HTML_FILE = /\.html?$/i;
|
|
8
|
+
function fileNameError(name, label) {
|
|
9
|
+
if (name.includes('/') || name.includes('\\')) return `${label}은 zip 최상위에 있어야 합니다: ${name}`;
|
|
10
|
+
if (!SAFE_FILE_NAME.test(name) || name.startsWith('.')) return `${label} 이름은 영문 · 숫자 · . · _ · -만 씁니다 (LXP가 주소에 그대로 붙임): ${name}`;
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* 지원 채점 유형 목록 검사 (metadata.json · elice.config.json 공통). 문제가 없으면 null.
|
|
15
|
+
* 수동 채점(manual) · 채점 없음(none)은 Custom HTML에서 쓰지 않는다.
|
|
16
|
+
*/
|
|
17
|
+
function gradingTypesError(value, allowed) {
|
|
18
|
+
if (!Array.isArray(value) || value.length === 0 || !value.every(t => typeof t === 'string')) return `gradingTypes는 지원하는 채점 유형을 하나 이상 적은 배열입니다. 예: ["on_submit", "pattern"] (가능: ${allowed.join(', ')})`;
|
|
19
|
+
const types = value;
|
|
20
|
+
if (types.includes('manual')) return `수동 채점(manual)은 Custom HTML 자료에서 쓰지 않습니다. ${allowed.join(' · ')} 중에서 고르세요.`;
|
|
21
|
+
if (types.includes('none')) return '채점 없음(none)은 Custom HTML 자료에서 쓰지 않습니다. 보기만 하는 자료는 on_access, 제출만 받는 자료는 on_submit.';
|
|
22
|
+
const unknown = types.find(t => !allowed.includes(t));
|
|
23
|
+
if (unknown) return `알 수 없는 채점 유형입니다: ${unknown} (가능: ${allowed.join(', ')})`;
|
|
24
|
+
const dup = types.find((t, i) => types.indexOf(t) !== i);
|
|
25
|
+
if (dup) return `gradingTypes에 같은 유형이 두 번 있습니다: ${dup}`;
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* metadata.json (zip 최상위): 용도, 화면(모드)별 사용 여부와 진입 파일, 빌드 정보. 정답은 넣지 않는다.
|
|
30
|
+
*
|
|
31
|
+
* {
|
|
32
|
+
* "kind": "material", // 선택. material: 자료 본문(기본) · description: 문제 설명
|
|
33
|
+
* "screens": { // 화면 3개 모두 적는다
|
|
34
|
+
* "learn": { "enabled": true, "entry": "index.html" },
|
|
35
|
+
* "instructor": { "enabled": true, "entry": "instructor.html" },
|
|
36
|
+
* "edit": { "enabled": false }
|
|
37
|
+
* },
|
|
38
|
+
* // 이 자료가 지원하는 채점 유형 모두 (교육자가 LXP 채점 설정에서 하나를 고름). 자료 본문은 필수, 문제 설명에는 없음
|
|
39
|
+
* // on_access · on_submit · pattern · rubric (rules.json manifest.gradingTypes). manual · none은 없음
|
|
40
|
+
* "gradingTypes": ["on_access", "on_submit", "pattern", "rubric"],
|
|
41
|
+
* "commentary": "commentary.txt", // 선택. 학습 참고 내용 파일 (zip 최상위, 일반 텍스트)
|
|
42
|
+
* "build": { "cli": "0.1.0", "rules": "0.2.0", "protocol": 1, "engine": "static" } // 선택
|
|
43
|
+
* }
|
|
44
|
+
*
|
|
45
|
+
* 파싱 결과의 `entries`는 켠 화면만 담는다. 서버 `material_draft.manifest`(JSONB) · SDK `MaterialManifest`의
|
|
46
|
+
* `{ entries }`가 이 모양이라 서버는 그대로 저장할 수 있다. 형식은 서버·디자인과 확정 전 제안안 (ADR 0004).
|
|
47
|
+
*/
|
|
48
|
+
function parseManifest(text, spec) {
|
|
49
|
+
const fail = error => ({
|
|
50
|
+
ok: false,
|
|
51
|
+
error
|
|
52
|
+
});
|
|
53
|
+
let json;
|
|
54
|
+
try {
|
|
55
|
+
json = JSON.parse(text);
|
|
56
|
+
} catch (e) {
|
|
57
|
+
return fail(`JSON 형식이 아닙니다 (${e.message}).`);
|
|
58
|
+
}
|
|
59
|
+
if (isRecord(json) && json.entries !== undefined && json.screens === undefined) return fail('"entries" 대신 "screens"에 화면마다 사용 여부(enabled)를 적어 주세요. 예: { "screens": { "learn": { "enabled": true, "entry": "index.html" }, "instructor": { "enabled": false }, "edit": { "enabled": false } } }');
|
|
60
|
+
if (!isRecord(json) || !isRecord(json.screens)) return fail('"screens" 객체가 없습니다. 예: { "screens": { "learn": { "enabled": true, "entry": "index.html" }, "instructor": { "enabled": false }, "edit": { "enabled": false } } }');
|
|
61
|
+
if (json.kind !== undefined && !spec.manifest.kinds.includes(json.kind)) return fail(`"kind"는 ${spec.manifest.kinds.join(' · ')} 중 하나여야 합니다 (material: 자료 본문, description: 문제 설명). 없으면 ${spec.manifest.defaultKind}.`);
|
|
62
|
+
const kind = json.kind;
|
|
63
|
+
const unknown = Object.keys(json.screens).find(m => !spec.manifest.modes.includes(m));
|
|
64
|
+
if (unknown) return fail(`알 수 없는 화면입니다: ${unknown} (가능: ${spec.manifest.modes.join(', ')})`);
|
|
65
|
+
const entries = {};
|
|
66
|
+
for (const mode of spec.manifest.modes) {
|
|
67
|
+
const s = json.screens[mode];
|
|
68
|
+
if (s === undefined) return fail(`${mode} 화면의 사용 여부가 없습니다. 쓰지 않으면 { "enabled": false }`);
|
|
69
|
+
if (!isRecord(s) || typeof s.enabled !== 'boolean') return fail(`${mode} 화면은 { "enabled": true|false, "entry": "파일" } 모양이어야 합니다.`);
|
|
70
|
+
if (!s.enabled) {
|
|
71
|
+
if (s.entry !== undefined) return fail(`${mode} 화면은 꺼져 있는데(enabled: false) entry가 있습니다. 둘 중 하나를 고쳐 주세요.`);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const file = s.entry;
|
|
75
|
+
if (typeof file !== 'string' || file.trim() === '') return fail(`${mode} 화면의 entry(진입 파일)가 비어 있거나 문자열이 아닙니다.`);
|
|
76
|
+
const nameError = fileNameError(file.trim(), `${mode} 화면의 진입 파일`);
|
|
77
|
+
if (nameError) return fail(nameError);
|
|
78
|
+
if (!HTML_FILE.test(file.trim())) return fail(`진입 파일은 HTML(.html)이어야 합니다: ${mode} → ${file}`);
|
|
79
|
+
entries[mode] = file.trim();
|
|
80
|
+
}
|
|
81
|
+
const missing = spec.manifest.required.filter(m => !entries[m]);
|
|
82
|
+
if (missing.length > 0) return fail(`반드시 켜야 하는 화면입니다 (enabled: true): ${missing.join(', ')}`);
|
|
83
|
+
const allowed = spec.manifest.kindModes[kind ?? spec.manifest.defaultKind] ?? spec.manifest.modes;
|
|
84
|
+
const extra = Object.keys(entries).filter(m => !allowed.includes(m));
|
|
85
|
+
if (extra.length > 0) return fail(`${kind === 'description' ? '문제 설명' : kind} 용도는 ${allowed.join(' · ')} 화면만 지원합니다: ${extra.join(', ')}를 { "enabled": false }로 바꿔 주세요.`);
|
|
86
|
+
// 채점 방식: 이 자료가 지원하는 채점 유형 목록 (교육자가 LXP 채점 설정에서 이 중 하나를 고름)
|
|
87
|
+
if (json.grading !== undefined) return fail('"grading" 대신 "gradingTypes"에 이 자료가 지원하는 채점 유형을 모두 적어 주세요. 예: "gradingTypes": ["on_submit", "pattern"]');
|
|
88
|
+
const isDescription = (kind ?? spec.manifest.defaultKind) === 'description';
|
|
89
|
+
let gradingTypes;
|
|
90
|
+
if (json.gradingTypes !== undefined) {
|
|
91
|
+
if (isDescription) return fail('문제 설명(kind: description)은 채점하지 않습니다. gradingTypes를 지워 주세요.');
|
|
92
|
+
const error = gradingTypesError(json.gradingTypes, spec.manifest.gradingTypes);
|
|
93
|
+
if (error) return fail(error);
|
|
94
|
+
gradingTypes = json.gradingTypes;
|
|
95
|
+
} else if (!isDescription) {
|
|
96
|
+
return fail(`자료 본문에는 지원하는 채점 유형이 있어야 합니다: "gradingTypes": [${spec.manifest.gradingTypes.map(t => `"${t}"`).join(', ')}] 중 하나 이상. 보기만 하는 자료는 ["on_access"].`);
|
|
97
|
+
}
|
|
98
|
+
const commentary = json.commentary;
|
|
99
|
+
if (commentary !== undefined) {
|
|
100
|
+
if (typeof commentary !== 'string' || commentary.trim() === '') return fail('"commentary"(학습 참고 내용)는 파일 이름이어야 합니다. 예: "commentary.txt"');
|
|
101
|
+
const nameError = fileNameError(commentary.trim(), '학습 참고 내용 파일');
|
|
102
|
+
if (nameError) return fail(nameError);
|
|
103
|
+
if (!/\.txt$/i.test(commentary)) return fail(`학습 참고 내용은 일반 텍스트(.txt) 파일입니다: ${commentary}. LXP의 학습 참고 내용 칸이 서식 없는 텍스트라서입니다.`);
|
|
104
|
+
}
|
|
105
|
+
let build;
|
|
106
|
+
if (json.build !== undefined) {
|
|
107
|
+
const b = json.build;
|
|
108
|
+
if (!isRecord(b) || typeof b.cli !== 'string' || typeof b.rules !== 'string' || typeof b.protocol !== 'number' || typeof b.engine !== 'string') return fail('"build"는 { cli, rules, protocol, engine } 모양이어야 합니다 (없어도 됩니다).');
|
|
109
|
+
build = {
|
|
110
|
+
cli: b.cli,
|
|
111
|
+
rules: b.rules,
|
|
112
|
+
protocol: b.protocol,
|
|
113
|
+
engine: b.engine
|
|
114
|
+
};
|
|
115
|
+
// 선택 필드는 모양이 맞을 때만 남긴다 (없거나 틀려도 오류는 아님)
|
|
116
|
+
for (const key of ['template', 'sdk', 'digest']) if (typeof b[key] === 'string') build[key] = b[key];
|
|
117
|
+
if (typeof b.minify === 'boolean') build.minify = b.minify;
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
ok: true,
|
|
121
|
+
manifest: {
|
|
122
|
+
...(kind ? {
|
|
123
|
+
kind
|
|
124
|
+
} : {}),
|
|
125
|
+
entries,
|
|
126
|
+
...(gradingTypes ? {
|
|
127
|
+
gradingTypes
|
|
128
|
+
} : {}),
|
|
129
|
+
...(typeof commentary === 'string' ? {
|
|
130
|
+
commentary: commentary.trim()
|
|
131
|
+
} : {}),
|
|
132
|
+
...(build ? {
|
|
133
|
+
build
|
|
134
|
+
} : {})
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* 화면 3개의 사용 여부(enabled)를 모두 적는다. 필드 순서(kind · screens · gradingTypes · commentary · build)와 화면 순서(learn · instructor · edit)를
|
|
140
|
+
* 고정해 같은 입력이면 같은 파일이 나오게 한다. kind가 없으면 기본값을 적는다.
|
|
141
|
+
*/
|
|
142
|
+
function serializeManifest(manifest, spec) {
|
|
143
|
+
const screens = Object.fromEntries(spec.manifest.modes.map(m => {
|
|
144
|
+
const entry = manifest.entries[m];
|
|
145
|
+
return [m, entry ? {
|
|
146
|
+
enabled: true,
|
|
147
|
+
entry
|
|
148
|
+
} : {
|
|
149
|
+
enabled: false
|
|
150
|
+
}];
|
|
151
|
+
}));
|
|
152
|
+
const out = {
|
|
153
|
+
kind: manifest.kind ?? spec.manifest.defaultKind,
|
|
154
|
+
screens,
|
|
155
|
+
...(manifest.gradingTypes ? {
|
|
156
|
+
gradingTypes: [...manifest.gradingTypes]
|
|
157
|
+
} : {}),
|
|
158
|
+
...(manifest.commentary !== undefined ? {
|
|
159
|
+
commentary: manifest.commentary
|
|
160
|
+
} : {}),
|
|
161
|
+
...(manifest.build ? {
|
|
162
|
+
build: manifest.build
|
|
163
|
+
} : {})
|
|
164
|
+
};
|
|
165
|
+
return `${JSON.stringify(out, null, 2)}\n`;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export { gradingTypesError, parseManifest, serializeManifest };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { CheckResult, ContentFile, InputKind } from './types.js';
|
|
2
|
+
/** 개발용 폴더는 안으로 들어가지 않고 폴더 안 첫 항목 하나로만 표시한다 (node_modules 전체를 읽지 않도록). */
|
|
3
|
+
export declare function filesFromDir(root: string): Promise<ContentFile[]>;
|
|
4
|
+
/** 폴더, .zip, .html 중 무엇이든 받아 ContentFile 목록과 입력 종류로. */
|
|
5
|
+
export declare function filesFromPath(p: string): Promise<{
|
|
6
|
+
files: ContentFile[];
|
|
7
|
+
input: InputKind;
|
|
8
|
+
zipBytes?: number;
|
|
9
|
+
}>;
|
|
10
|
+
export declare function checkPath(p: string): Promise<CheckResult>;
|
|
11
|
+
export * from './index.js';
|
package/es/rules/node.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { stat, readFile, readdir } from 'node:fs/promises';
|
|
2
|
+
import { extname, join, relative, sep } from 'node:path';
|
|
3
|
+
import { checkFiles } from './check.js';
|
|
4
|
+
import { rules } from './spec.js';
|
|
5
|
+
export { RULES_VERSION } from './spec.js';
|
|
6
|
+
import { ZipLimitError, filesFromZip, filesFromHtml } from './zip.js';
|
|
7
|
+
|
|
8
|
+
/** 개발용 폴더는 안으로 들어가지 않고 폴더 안 첫 항목 하나로만 표시한다 (node_modules 전체를 읽지 않도록). */
|
|
9
|
+
async function filesFromDir(root) {
|
|
10
|
+
const out = [];
|
|
11
|
+
const devDirs = new Set(rules.excluded.dev.dirs.map(d => d.toLowerCase()));
|
|
12
|
+
async function walk(dir) {
|
|
13
|
+
const entries = await readdir(dir, {
|
|
14
|
+
withFileTypes: true
|
|
15
|
+
});
|
|
16
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
17
|
+
for (const e of entries) {
|
|
18
|
+
const abs = join(dir, e.name);
|
|
19
|
+
const rel = relative(root, abs).split(sep).join('/');
|
|
20
|
+
if (e.isDirectory()) {
|
|
21
|
+
if (devDirs.has(e.name.toLowerCase())) out.push({
|
|
22
|
+
path: `${rel}/...`,
|
|
23
|
+
data: new Uint8Array()
|
|
24
|
+
});else await walk(abs);
|
|
25
|
+
} else if (e.isFile()) {
|
|
26
|
+
out.push({
|
|
27
|
+
path: rel,
|
|
28
|
+
data: new Uint8Array(await readFile(abs))
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
await walk(root);
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
/** 폴더, .zip, .html 중 무엇이든 받아 ContentFile 목록과 입력 종류로. */
|
|
37
|
+
async function filesFromPath(p) {
|
|
38
|
+
if ((await stat(p)).isDirectory()) return {
|
|
39
|
+
files: await filesFromDir(p),
|
|
40
|
+
input: 'dir'
|
|
41
|
+
};
|
|
42
|
+
const data = new Uint8Array(await readFile(p));
|
|
43
|
+
const ext = extname(p).toLowerCase();
|
|
44
|
+
if (ext === '.zip') return {
|
|
45
|
+
files: filesFromZip(data),
|
|
46
|
+
input: 'zip',
|
|
47
|
+
zipBytes: data.byteLength
|
|
48
|
+
};
|
|
49
|
+
if (ext === '.html' || ext === '.htm') return {
|
|
50
|
+
files: filesFromHtml(data),
|
|
51
|
+
input: 'html'
|
|
52
|
+
};
|
|
53
|
+
throw new Error(`폴더, .zip, .html만 검사할 수 있습니다: ${p}`);
|
|
54
|
+
}
|
|
55
|
+
async function checkPath(p) {
|
|
56
|
+
try {
|
|
57
|
+
const {
|
|
58
|
+
files,
|
|
59
|
+
input,
|
|
60
|
+
zipBytes
|
|
61
|
+
} = await filesFromPath(p);
|
|
62
|
+
return checkFiles(files, {
|
|
63
|
+
input,
|
|
64
|
+
zipBytes
|
|
65
|
+
});
|
|
66
|
+
} catch (e) {
|
|
67
|
+
if (!(e instanceof ZipLimitError)) throw e;
|
|
68
|
+
// 풀다가 멈춘 zip: 파일을 읽지 않았으므로 이 오류 하나만
|
|
69
|
+
return {
|
|
70
|
+
ok: false,
|
|
71
|
+
rulesVersion: rules.version,
|
|
72
|
+
stats: {
|
|
73
|
+
files: 0,
|
|
74
|
+
totalBytes: 0,
|
|
75
|
+
zipBytes: (await stat(p)).size
|
|
76
|
+
},
|
|
77
|
+
manifest: null,
|
|
78
|
+
issues: [{
|
|
79
|
+
id: e.id,
|
|
80
|
+
level: 'error',
|
|
81
|
+
message: e.message
|
|
82
|
+
}]
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export { ZipLimitError, checkFiles, checkPath, filesFromDir, filesFromHtml, filesFromPath, filesFromZip, rules };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** 서버 `check_zipfile()`(elice-api api/func/remote_file/func.py)과 같은 기준: 정규화 결과가 원래 이름과 같아야 한다. */
|
|
2
|
+
export declare function isUnsafePath(name: string): boolean;
|
|
3
|
+
/** `from` 파일 기준으로 상대 참조를 풀어 루트 기준 경로로. 루트 밖으로 나가면 null. */
|
|
4
|
+
export declare function resolveRef(from: string, ref: string): string | null;
|
|
5
|
+
export declare function basename(p: string): string;
|
|
6
|
+
export declare function extname(p: string): string;
|
|
7
|
+
export declare function globToRegExp(glob: string): RegExp;
|
package/es/rules/path.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** 서버 `check_zipfile()`(elice-api api/func/remote_file/func.py)과 같은 기준: 정규화 결과가 원래 이름과 같아야 한다. */
|
|
2
|
+
function isUnsafePath(name) {
|
|
3
|
+
const p = name.endsWith('/') ? name.slice(0, -1) : name;
|
|
4
|
+
if (p === '' || p.startsWith('/') || p.includes('\\') || /^[a-zA-Z]:/.test(p)) return true;
|
|
5
|
+
return p.split('/').some(seg => seg === '' || seg === '.' || seg === '..');
|
|
6
|
+
}
|
|
7
|
+
/** `from` 파일 기준으로 상대 참조를 풀어 루트 기준 경로로. 루트 밖으로 나가면 null. */
|
|
8
|
+
function resolveRef(from, ref) {
|
|
9
|
+
const base = from.split('/').slice(0, -1);
|
|
10
|
+
const out = ref.startsWith('/') ? [] : base;
|
|
11
|
+
for (const seg of ref.split('/')) {
|
|
12
|
+
if (seg === '' || seg === '.') continue;
|
|
13
|
+
if (seg === '..') {
|
|
14
|
+
if (out.length === 0) return null;
|
|
15
|
+
out.pop();
|
|
16
|
+
} else {
|
|
17
|
+
out.push(seg);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return out.join('/');
|
|
21
|
+
}
|
|
22
|
+
function basename(p) {
|
|
23
|
+
return p.slice(p.lastIndexOf('/') + 1);
|
|
24
|
+
}
|
|
25
|
+
function extname(p) {
|
|
26
|
+
const b = basename(p);
|
|
27
|
+
const i = b.lastIndexOf('.');
|
|
28
|
+
return i <= 0 ? '' : b.slice(i + 1).toLowerCase();
|
|
29
|
+
}
|
|
30
|
+
function globToRegExp(glob) {
|
|
31
|
+
const src = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
|
|
32
|
+
return new RegExp(`^${src}$`, 'i');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export { basename, extname, globToRegExp, isUnsafePath, resolveRef };
|