@eliceio/cdk-cli 0.1.0-alpha.5 → 0.1.0-alpha.7
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 +110 -84
- package/es/cli.js +7 -22
- package/es/commands/build/index.d.ts +5 -3
- package/es/commands/build/index.js +20 -11
- package/es/commands/create/scaffold.d.ts +2 -0
- package/es/commands/create/scaffold.js +15 -1
- package/es/commands/dev/index.d.ts +1 -1
- package/es/commands/dev/index.js +1 -1
- package/es/commands/doctor/index.d.ts +1 -1
- package/es/commands/doctor/index.js +5 -6
- package/es/commands/setup/index.d.ts +4 -7
- package/es/commands/setup/index.js +41 -70
- package/es/commands/uninstall/index.d.ts +9 -8
- package/es/commands/uninstall/index.js +41 -47
- package/es/commands/update/index.d.ts +4 -2
- package/es/commands/update/index.js +27 -18
- package/es/core/collect.js +1 -1
- package/es/core/config.d.ts +1 -1
- package/es/core/config.js +3 -3
- package/es/{commands/mcp/index.d.ts → core/mcp.d.ts} +11 -18
- package/es/{commands/mcp/index.js → core/mcp.js} +29 -51
- package/es/core/minify.js +31 -2
- package/es/core/prepare.js +1 -1
- package/es/core/sandbox.d.ts +25 -0
- package/es/core/sandbox.js +110 -8
- package/es/{commands/skill/index.d.ts → core/skills.d.ts} +1 -17
- package/es/{commands/skill/index.js → core/skills.js} +6 -22
- package/es/dev/grading.d.ts +1 -1
- package/es/dev/grading.js +1 -1
- package/es/dev/host-page.js +20 -5
- package/es/dev/inject.d.ts +6 -0
- package/es/dev/inject.js +16 -1
- package/es/dev/mock-api.js +0 -16
- package/es/dev/server.d.ts +4 -2
- package/es/dev/server.js +11 -3
- package/es/rules/check.js +71 -8
- package/es/rules/csp.d.ts +26 -0
- package/es/rules/csp.js +42 -0
- package/es/rules/index.d.ts +2 -1
- package/es/rules/index.js +2 -1
- package/es/rules/refs.d.ts +12 -2
- package/es/rules/refs.js +50 -18
- package/es/rules/types.d.ts +5 -0
- package/es/rules/unused.d.ts +2 -0
- package/es/rules/unused.js +4 -3
- package/es/rules.json.js +2 -2
- package/package.json +2 -2
- package/rules.json +37 -15
- package/skills/_shared/always.md +2 -1
- package/skills/elice-content-create/SKILL.md +2 -1
- package/skills/elice-content-guide/SKILL.md +1 -1
- package/skills/elice-content-guide/topics/01-check-the-environment.md +2 -2
- package/skills/elice-content-guide/topics/02-design-the-material.md +2 -0
- package/skills/elice-content-guide/topics/03-create-the-project.md +2 -2
- package/skills/elice-content-guide/topics/04-rules.md +3 -1
- package/skills/elice-content-guide/topics/05-screen-code.md +44 -13
- package/skills/elice-content-guide/topics/07-move-existing-html.md +1 -1
- package/skills/elice-content-guide/topics/08-fix-check-errors.md +21 -18
- package/skills/elice-content-guide/topics/09-check.md +1 -0
- package/skills/elice-content-guide/topics/10-build.md +1 -1
- package/skills/elice-content-guide/topics/12-upload-with-the-material-mcp.md +2 -2
- package/skills/elice-content-migrate/SKILL.md +4 -3
- package/skills/elice-content-publish/SKILL.md +1 -1
- package/templates/_shared/lib/cdk-mock.js +3 -3
- package/templates/_shared/lib/elice-content-editor.d.ts +80 -0
- package/templates/_shared/lib/elice-content-editor.js +1062 -0
- package/templates/_shared/lib/elice-content.css +354 -1
- package/templates/_shared/lib/elice-content.js +10 -3
- package/templates/blank/README.md +27 -2
- package/templates/blank/commentary.txt +5 -0
- package/templates/blank/screens/edit.js +38 -17
- package/templates/blank/screens/instructor.js +20 -8
- package/templates/blank/screens/learn.js +151 -13
- package/templates/blank/styles.css +171 -0
- package/templates/blank/template.json +2 -2
- package/templates/quiz/README.md +2 -2
- package/templates/quiz/core/editor.d.ts +2 -0
- package/templates/quiz/core/editor.js +16 -6
- package/templates/quiz/core/model.js +1 -1
- package/templates/quiz/screens/edit.js +117 -24
- package/templates/quiz/styles.css +86 -12
- package/templates/quiz/template.json +1 -1
- package/templates/quiz/ui/templates/edit.d.ts +4 -0
- package/templates/quiz/ui/templates/edit.js +46 -10
- package/templates/quiz/ui/templates/page.js +1 -2
- package/templates/quiz/ui/templates/text.js +10 -7
- package/templates/quiz/ui/texts.js +13 -9
|
@@ -4,20 +4,16 @@ import { homedir } from 'node:os';
|
|
|
4
4
|
import { delimiter, join, dirname } from 'node:path';
|
|
5
5
|
|
|
6
6
|
/*
|
|
7
|
-
* Elice 학습자료 서버 MCP(elice-material)를 AI 도구에
|
|
7
|
+
* Elice 학습자료 서버 MCP(elice-material)를 AI 도구에 등록 · 확인한다 (ecdk setup · uninstall · doctor가 쓴다).
|
|
8
8
|
* 등록 전에 서버에 MCP가 있는지 확인하고, 로그인은 등록 뒤 각 도구에서 한다.
|
|
9
9
|
*/
|
|
10
10
|
const MCP_NAME = 'elice-material';
|
|
11
11
|
/**
|
|
12
|
-
* 서버
|
|
13
|
-
*
|
|
14
|
-
* (GET 405), 백엔드가 주소를 확정해 주기로
|
|
12
|
+
* 운영 서버 MCP 주소. 그 밖의 서버는 --url로 준다 (사내 서버 주소는 패키지에 두지 않음).
|
|
13
|
+
* material API 주소(api-material.elice.io)에 /mcp를 붙인 **가정**이다: 2026-11-10 운영에는 아직 MCP가 없고
|
|
14
|
+
* (GET 405), 백엔드가 주소를 확정해 주기로 함. 그래서 등록 전에 probe로 확인한다.
|
|
15
15
|
*/
|
|
16
|
-
const
|
|
17
|
-
prod: 'https://api-material.elice.io/mcp',
|
|
18
|
-
qa5: 'https://dev-v5-material-api.dev.elicer.io/mcp'
|
|
19
|
-
};
|
|
20
|
-
const DEFAULT_ENV = 'prod';
|
|
16
|
+
const MCP_URL = 'https://api-material.elice.io/mcp';
|
|
21
17
|
const PROBE_TIMEOUT_MS = 5000;
|
|
22
18
|
/** MCP initialize를 POST해 본다. 로그인 전이면 401과 www-authenticate(resource_metadata)가 와야 한다 */
|
|
23
19
|
async function probeMcp(url) {
|
|
@@ -85,8 +81,7 @@ function defaultMcpEnv() {
|
|
|
85
81
|
};
|
|
86
82
|
},
|
|
87
83
|
exists: existsSync,
|
|
88
|
-
probe: probeMcp
|
|
89
|
-
envVar: process.env.ECDK_ENV
|
|
84
|
+
probe: probeMcp
|
|
90
85
|
};
|
|
91
86
|
}
|
|
92
87
|
const helpyConfigPath = env => join(env.home, '.config', 'helpycode', 'helpycode.jsonc');
|
|
@@ -96,8 +91,8 @@ function detectTargets(env) {
|
|
|
96
91
|
if (env.exists(join(env.home, '.config', 'helpycode')) || env.which('helpycode') || env.platform === 'darwin' && env.exists('/Applications/HelpyCode.app')) found.push('helpycode');
|
|
97
92
|
return found;
|
|
98
93
|
}
|
|
99
|
-
/** 주소로 환경
|
|
100
|
-
const envOfUrl = url =>
|
|
94
|
+
/** 주소로 환경 이름: 운영 주소면 prod, 아니면 custom (--url로 준 주소) */
|
|
95
|
+
const envOfUrl = url => url === MCP_URL ? 'prod' : 'custom';
|
|
101
96
|
const CLAUDE_TIMEOUT_MS = 5000;
|
|
102
97
|
/**
|
|
103
98
|
* Claude Code 등록 상태. `claude mcp get`은 서버 연결 상태까지 확인해 느릴 수 있으므로
|
|
@@ -129,11 +124,6 @@ function claudeRegistration(env) {
|
|
|
129
124
|
url
|
|
130
125
|
};
|
|
131
126
|
}
|
|
132
|
-
/** Claude Code 사용자 범위에 등록된 주소 (없거나 확인 못 하면 null) */
|
|
133
|
-
function claudeRegisteredUrl(env) {
|
|
134
|
-
const reg = claudeRegistration(env);
|
|
135
|
-
return reg.state === 'user' ? reg.url : null;
|
|
136
|
-
}
|
|
137
127
|
/** 주석 · 끝 쉼표가 있으면 다시 쓰지 않는다 (지우면 사람이 적은 설명이 사라짐) */
|
|
138
128
|
function readHelpyConfig(path) {
|
|
139
129
|
if (!existsSync(path)) return {
|
|
@@ -174,7 +164,7 @@ function helpyRegisteredUrl(env) {
|
|
|
174
164
|
const mcp = config.data.mcp;
|
|
175
165
|
return mcp?.[MCP_NAME]?.url ?? null;
|
|
176
166
|
}
|
|
177
|
-
function setupClaude(env, url,
|
|
167
|
+
function setupClaude(env, url, force) {
|
|
178
168
|
const reg = claudeRegistration(env);
|
|
179
169
|
if (reg.state === 'unknown') return {
|
|
180
170
|
target: 'claude',
|
|
@@ -194,11 +184,6 @@ function setupClaude(env, url, dryRun, force) {
|
|
|
194
184
|
message: `다른 주소로 등록돼 있습니다 (${current}). 바꾸려면 --force`
|
|
195
185
|
};
|
|
196
186
|
const add = ['mcp', 'add', '--transport', 'http', '--scope', 'user', MCP_NAME, url];
|
|
197
|
-
if (dryRun) return {
|
|
198
|
-
target: 'claude',
|
|
199
|
-
action: current ? 'would-replace' : 'would-add',
|
|
200
|
-
message: `${current ? `claude mcp remove ${MCP_NAME} --scope user 뒤 ` : ''}claude ${add.join(' ')}${localNote}`
|
|
201
|
-
};
|
|
202
187
|
if (current) {
|
|
203
188
|
const rm = env.exec('claude', ['mcp', 'remove', MCP_NAME, '--scope', 'user'], 30000);
|
|
204
189
|
if (rm.code !== 0 || rm.timedOut) return {
|
|
@@ -219,7 +204,7 @@ function setupClaude(env, url, dryRun, force) {
|
|
|
219
204
|
message: `Claude Code 사용자 설정에 ${current ? '바꿈' : '등록'} (${url})${localNote}`
|
|
220
205
|
};
|
|
221
206
|
}
|
|
222
|
-
function setupHelpy(env, url,
|
|
207
|
+
function setupHelpy(env, url, force) {
|
|
223
208
|
const path = helpyConfigPath(env);
|
|
224
209
|
const config = readHelpyConfig(path);
|
|
225
210
|
const block = JSON.stringify({
|
|
@@ -260,11 +245,6 @@ function setupHelpy(env, url, dryRun, force) {
|
|
|
260
245
|
action: 'conflict',
|
|
261
246
|
message: `다른 주소로 등록돼 있습니다 (${current}). 바꾸려면 --force`
|
|
262
247
|
};
|
|
263
|
-
if (dryRun) return {
|
|
264
|
-
target: 'helpycode',
|
|
265
|
-
action: current ? 'would-replace' : 'would-add',
|
|
266
|
-
message: `${path}의 mcp.${MCP_NAME}를 ${url}로${config.kind === 'json' ? env.exists(`${path}.bak`) ? ' (.bak은 이미 있어 그대로 둠)' : ' (원본은 .bak)' : ' (새 파일)'}`
|
|
267
|
-
};
|
|
268
248
|
mcp[MCP_NAME] = helpyEntry(url);
|
|
269
249
|
data.mcp = mcp;
|
|
270
250
|
mkdirSync(dirname(path), {
|
|
@@ -294,9 +274,9 @@ async function setup(opts) {
|
|
|
294
274
|
url
|
|
295
275
|
} = opts;
|
|
296
276
|
const targets = opts.target === 'all' ? detectTargets(opts.env) : [opts.target];
|
|
297
|
-
const login =
|
|
298
|
-
const probe =
|
|
299
|
-
if (
|
|
277
|
+
const login = targets.flatMap(t => LOGIN[t]);
|
|
278
|
+
const probe = await opts.env.probe(url);
|
|
279
|
+
if (!probe.ok && !opts.force) return {
|
|
300
280
|
env: opts.envName,
|
|
301
281
|
probe,
|
|
302
282
|
url,
|
|
@@ -308,7 +288,7 @@ async function setup(opts) {
|
|
|
308
288
|
})),
|
|
309
289
|
login
|
|
310
290
|
};
|
|
311
|
-
const steps = targets.map(t => t === 'claude' ? setupClaude(opts.env, url, opts.
|
|
291
|
+
const steps = targets.map(t => t === 'claude' ? setupClaude(opts.env, url, opts.force) : setupHelpy(opts.env, url, opts.force));
|
|
312
292
|
return {
|
|
313
293
|
env: opts.envName,
|
|
314
294
|
probe,
|
|
@@ -319,30 +299,28 @@ async function setup(opts) {
|
|
|
319
299
|
};
|
|
320
300
|
}
|
|
321
301
|
const NEEDS_PERSON = ['conflict', 'manual', 'unreachable', 'failed'];
|
|
322
|
-
/** 주소: --url
|
|
323
|
-
function resolveUrl(args
|
|
324
|
-
if (args.url
|
|
325
|
-
ok:
|
|
326
|
-
|
|
302
|
+
/** 주소: --url, 없으면 운영 */
|
|
303
|
+
function resolveUrl(args) {
|
|
304
|
+
if (args.url === undefined) return {
|
|
305
|
+
ok: true,
|
|
306
|
+
envName: envOfUrl(MCP_URL),
|
|
307
|
+
source: '기본값',
|
|
308
|
+
url: MCP_URL
|
|
327
309
|
};
|
|
328
|
-
|
|
329
|
-
const source = args.url ? '--url' : args.envName ? '--env' : env.envVar ? 'ECDK_ENV' : '기본값';
|
|
330
|
-
const url = args.url ?? MCP_ENVS[envName];
|
|
331
|
-
if (!url) return {
|
|
310
|
+
if (!/^https:\/\/\S+$/.test(args.url)) return {
|
|
332
311
|
ok: false,
|
|
333
|
-
error:
|
|
312
|
+
error: `--url은 https 주소여야 합니다: ${args.url}`
|
|
334
313
|
};
|
|
335
314
|
return {
|
|
336
315
|
ok: true,
|
|
337
|
-
envName,
|
|
338
|
-
source,
|
|
339
|
-
url
|
|
316
|
+
envName: envOfUrl(args.url),
|
|
317
|
+
source: '--url',
|
|
318
|
+
url: args.url
|
|
340
319
|
};
|
|
341
320
|
}
|
|
342
321
|
/** 사람용 출력의 MCP 부분 (환경 · 서버 확인 · 도구별 결과) */
|
|
343
|
-
function formatSetupLines(result, source
|
|
344
|
-
|
|
345
|
-
return [`MCP ${MCP_NAME} · 환경 ${result.env} (${source}) · ${result.url}${dryRun ? ' · 미리보기(--dry-run)' : ''}`, probeLine, ...(result.env === 'prod' ? [] : [`※ 운영이 아닌 환경(${result.env})입니다. 운영 자료를 올리지 마세요.`]), ...result.steps.flatMap(s => [` ${s.target}: ${s.message}`, ...(s.paste ? s.paste.split('\n').map(l => ` ${l}`) : [])])];
|
|
322
|
+
function formatSetupLines(result, source) {
|
|
323
|
+
return [`MCP ${MCP_NAME} · 환경 ${result.env} (${source}) · ${result.url}`, `서버 확인: ${result.probe.ok ? 'MCP 있음' : 'MCP 없음'} (${result.probe.detail})`, ...(result.env === 'prod' ? [] : [`※ 운영이 아닌 서버(--url)입니다. 운영 자료를 올리지 마세요.`]), ...result.steps.flatMap(s => [` ${s.target}: ${s.message}`, ...(s.paste ? s.paste.split('\n').map(l => ` ${l}`) : [])])];
|
|
346
324
|
}
|
|
347
325
|
|
|
348
|
-
export {
|
|
326
|
+
export { MCP_NAME, MCP_URL, NEEDS_PERSON, claudeRegistration, defaultMcpEnv, detectTargets, envOfUrl, formatSetupLines, helpyConfigPath, helpyRegisteredUrl, probeMcp, readHelpyConfig, resolveUrl, setup };
|
package/es/core/minify.js
CHANGED
|
@@ -1,21 +1,34 @@
|
|
|
1
1
|
import { transform } from 'esbuild';
|
|
2
|
+
import { SDK_ZIP_PATH } from './sdk.js';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
|
-
* package.json `"ecdk"`의 `"minify":
|
|
5
|
+
* zip에 넣기 전에 줄인다 (기본, package.json `"ecdk"`의 `"minify": false`면 끔). zip은 학생 브라우저가 받으므로
|
|
6
|
+
* 주석(작업 메모 · 티켓 번호)을 빼고 용량도 줄인다.
|
|
5
7
|
* 파일 단위 변환(번들 아님)이라 경로 · import · 파일 구성은 그대로다.
|
|
6
8
|
*
|
|
7
9
|
* - JS(.js · .mjs): 공백 · 주석 제거, 이름 줄이기. ES 모듈의 import/export와 top-level await는 그대로.
|
|
10
|
+
* 라이선스 주석(/*! · @license · @preserve)은 그 자리에 남긴다 (넣은 라이브러리의 고지 의무).
|
|
8
11
|
* - CSS: 공백 · 주석 제거.
|
|
9
12
|
* - JSON: 공백 제거 (형식이 틀리면 그대로 둠, 검사가 알려 줌). metadata.json은 사람이 보도록 그대로.
|
|
10
13
|
* - HTML · 이미지 등은 그대로.
|
|
11
14
|
* - sourcemap: 줄인 JS · CSS 옆에 `<파일>.map`을 두고 끝에 sourceMappingURL을 단다 (원본 내용 포함).
|
|
12
15
|
* 이미 줄여 둔 파일(minify로 10%도 안 줄어듦, 예: lib/cdk.js)은 .map을 만들지 않는다.
|
|
13
16
|
*
|
|
17
|
+
* - `ecdk-ignore` 주석이 있던 JS · CSS는 줄인 결과가 한 줄이면 그 규칙들을 `ecdk-ignore-next-line`으로 맨 앞에 다시 단다
|
|
18
|
+
* (zip 검사 · 서버 업로드 검사가 같은 규칙을 다시 보므로). 여러 줄이면 줄 위치를 맞출 수 없어 그 파일은 줄이지 않는다.
|
|
19
|
+
* - lib/cdk.js(build가 넣는 SDK)는 이미 줄인 코드이고 머리말(버전 · ecdk-ignore)을 검사가 읽으므로 그대로 둔다.
|
|
20
|
+
*
|
|
14
21
|
* 검사는 minify 전 원본으로 한다 (`ecdk-ignore` 주석 · 원본 줄 번호). build 참고.
|
|
15
22
|
*/
|
|
16
23
|
const encoder = new TextEncoder();
|
|
17
24
|
const decoder = new TextDecoder();
|
|
18
|
-
const KEEP = new Set(['metadata.json']);
|
|
25
|
+
const KEEP = new Set(['metadata.json', SDK_ZIP_PATH]);
|
|
26
|
+
/** 원본의 ecdk-ignore · ecdk-ignore-next-line이 끈 규칙 id (줄여도 zip 검사에서 같은 규칙을 끄도록) */
|
|
27
|
+
function ignoredRules(text) {
|
|
28
|
+
const ids = new Set();
|
|
29
|
+
for (const m of text.matchAll(/ecdk-ignore(?:-next-line)?((?:[ \t]+[\w.,-]+)+)/g)) for (const id of (m[1] ?? '').split(/[\s,]+/)) if (id === 'all' || /^[a-z][\w-]*\.[\w.-]+$/.test(id)) ids.add(id);
|
|
30
|
+
return [...ids];
|
|
31
|
+
}
|
|
19
32
|
async function minifyFiles(files, {
|
|
20
33
|
sourcemap = false
|
|
21
34
|
} = {}) {
|
|
@@ -42,6 +55,7 @@ async function minifyFiles(files, {
|
|
|
42
55
|
const r = await transform(text, {
|
|
43
56
|
loader,
|
|
44
57
|
minify: true,
|
|
58
|
+
legalComments: 'inline',
|
|
45
59
|
target: 'es2022',
|
|
46
60
|
...(sourcemap ? {
|
|
47
61
|
sourcemap: 'external',
|
|
@@ -49,6 +63,21 @@ async function minifyFiles(files, {
|
|
|
49
63
|
} : {})
|
|
50
64
|
});
|
|
51
65
|
next = r.code;
|
|
66
|
+
const ignored = ignoredRules(text);
|
|
67
|
+
if (ignored.length > 0) {
|
|
68
|
+
// 여러 줄(템플릿 문자열 등)이면 끈 줄을 맞출 수 없다: 줄이지 않고 원본 그대로
|
|
69
|
+
if (next.trimEnd().includes('\n')) return f;
|
|
70
|
+
const line = `ecdk-ignore-next-line ${ignored.join(' ')}`;
|
|
71
|
+
next = `${loader === 'css' ? `/* ${line} */` : `// ${line}`}\n${next}`;
|
|
72
|
+
// 한 줄 밀렸으니 .map도 한 줄 민다
|
|
73
|
+
if (r.map) {
|
|
74
|
+
const map = JSON.parse(r.map);
|
|
75
|
+
r.map = JSON.stringify({
|
|
76
|
+
...map,
|
|
77
|
+
mappings: `;${map.mappings}`
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
52
81
|
// 이미 줄여 둔 파일(묶어 넣은 SDK 등)은 .map이 줄인 코드를 다시 가리킬 뿐이라 용량만 늘린다
|
|
53
82
|
const alreadyMin = encoder.encode(next).byteLength > f.data.byteLength * 0.9;
|
|
54
83
|
if (sourcemap && r.map && !alreadyMin) {
|
package/es/core/prepare.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { resolve, relative, sep, isAbsolute } from 'node:path';
|
|
2
2
|
import { staticEngine } from '../engines/static/index.js';
|
|
3
3
|
import 'fflate';
|
|
4
|
-
import { serializeManifest } from '../rules/manifest.js';
|
|
5
4
|
import { rules } from '../rules/spec.js';
|
|
5
|
+
import { serializeManifest } from '../rules/manifest.js';
|
|
6
6
|
import { collectSources } from './collect.js';
|
|
7
7
|
import { CONFIG_FILE, PLATFORM_KEYS } from './config.js';
|
|
8
8
|
import { createBuildInfo } from './manifest.js';
|
package/es/core/sandbox.d.ts
CHANGED
|
@@ -5,6 +5,13 @@ export interface SandboxReport {
|
|
|
5
5
|
/** 모듈 스크립트를 묶어 넣은 HTML */
|
|
6
6
|
pages: string[];
|
|
7
7
|
}
|
|
8
|
+
/** 묶은 결과: 원본 빼기(dropBundledSources)에 쓴다 */
|
|
9
|
+
export interface BundledSources {
|
|
10
|
+
/** 어느 페이지에든 묶여 들어간 zip 안 파일 */
|
|
11
|
+
inputs: Set<string>;
|
|
12
|
+
/** 묶은 페이지마다 다른 파일 이름을 찾을 글: 묶은 <script> 태그를 뺀 HTML + 주석을 뺀 묶음 코드 */
|
|
13
|
+
pageTexts: Map<string, string>;
|
|
14
|
+
}
|
|
8
15
|
/** HTML의 모듈 스크립트(src)를 묶어 본문으로 넣는다. 바뀐 파일만 새로 만들어 돌려준다 */
|
|
9
16
|
export declare function inlineModuleScripts(files: SourceFile[],
|
|
10
17
|
/** esbuild 작업 폴더 (기본: 실행 폴더). 테스트에서 프로젝트 폴더 안 실행을 흉내 낼 때 */
|
|
@@ -14,4 +21,22 @@ opts?: {
|
|
|
14
21
|
}): Promise<{
|
|
15
22
|
files: SourceFile[];
|
|
16
23
|
report: SandboxReport;
|
|
24
|
+
bundled: BundledSources;
|
|
25
|
+
}>;
|
|
26
|
+
export interface DropReport {
|
|
27
|
+
/** 묶어 넣었고 다른 데서 쓰지 않아 zip에서 뺀 원본 JS */
|
|
28
|
+
dropped: string[];
|
|
29
|
+
/** 빼지 않은 까닭 (모두 둔 경우만) */
|
|
30
|
+
keptAll?: string | undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* 묶어 넣은 원본 JS 중 다른 데서 이름이 나오지 않는 파일을 뺀다 (zip 크기 · 같은 코드 두 벌).
|
|
34
|
+
* 묶은 파일(.js · .mjs)마다, 남는 텍스트 파일(묶은 페이지는 BundledSources.pageTexts)에 경로나 파일 이름이 나오면 둔다:
|
|
35
|
+
* 일반 <script src> · new Worker('…') · fetch · HTML · CSS · 문자열로 조합한 주소. 둔 파일은 따로 받히므로 그 안의
|
|
36
|
+
* import도 찾아 계속 둔다. 묶음에 import()가 남았으면(변수 주소) 무엇을 받는지 몰라 하나도 빼지 않는다.
|
|
37
|
+
* metadata.json · 화면 진입 파일(HTML) · JSON · CSS는 JS가 아니라 대상이 아니다.
|
|
38
|
+
*/
|
|
39
|
+
export declare function dropBundledSources(files: SourceFile[], bundled: BundledSources): Promise<{
|
|
40
|
+
files: SourceFile[];
|
|
41
|
+
report: DropReport;
|
|
17
42
|
}>;
|
package/es/core/sandbox.js
CHANGED
|
@@ -1,20 +1,24 @@
|
|
|
1
|
-
import { build } from 'esbuild';
|
|
1
|
+
import { build, transform } from 'esbuild';
|
|
2
2
|
import 'fflate';
|
|
3
|
+
import { rules } from '../rules/spec.js';
|
|
3
4
|
import { resolveRef } from '../rules/path.js';
|
|
4
5
|
import { classifyRef } from '../rules/refs.js';
|
|
5
|
-
import {
|
|
6
|
+
import { TEXT_FILE } from '../rules/unused.js';
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
|
-
* LXP는 자료를
|
|
9
|
-
*
|
|
9
|
+
* LXP는 자료를 콘텐츠마다 다른 출처의 sandbox iframe(`allow-scripts allow-same-origin`)에서 연다.
|
|
10
|
+
* iframe 속성과 콘텐츠 서버의 `Content-Security-Policy: sandbox` 헤더가 함께 적용되므로, 헤더에
|
|
11
|
+
* `allow-same-origin`이 없으면 콘텐츠 출처는 `null`이 된다. 자료 파일 서버는 `Access-Control-Allow-Origin`을
|
|
12
|
+
* 주지 않아, 그때는 CORS 모드로 받는 요청이 모두 막힌다:
|
|
10
13
|
* `<script type="module" src>` · 그 안의 `import` · `import()` · `fetch('data.json')`.
|
|
11
14
|
* (일반 `<script src>` · `<link rel="stylesheet">` · `<img>`는 CORS를 쓰지 않아 그대로 된다.)
|
|
15
|
+
* 헤더가 `allow-same-origin`을 주면 같은 출처 요청이라 막히지 않지만, 어느 쪽이든 화면이 뜨도록 묶는다.
|
|
12
16
|
*
|
|
13
17
|
* build는 zip에 넣기 전에 HTML마다:
|
|
14
18
|
* - `<script type="module" src="상대경로">`를 esbuild로 하나로 묶어 `<script type="module">` 본문으로 넣는다
|
|
15
19
|
* (zip 안 파일만 묶음. `import.meta.url`은 원래 파일 주소로 바꿔 상대경로 계산이 그대로 맞게).
|
|
16
20
|
* - zip 안 JSON(metadata.json 제외, 작성자가 넣은 데이터 파일)을 페이지에 넣고 `fetch`가 그 주소를 받으면 넣어 둔 내용을 돌려준다.
|
|
17
|
-
* 원본 JS
|
|
21
|
+
* build는 묶어 넣은 원본 JS 중 다른 데서 쓰지 않는 파일을 zip에서 뺀다 (`dropBundledSources`). JSON은 그대로 둔다.
|
|
18
22
|
*/
|
|
19
23
|
const encoder = new TextEncoder();
|
|
20
24
|
const decoder = new TextDecoder();
|
|
@@ -97,6 +101,10 @@ async function bundle(entry, page, byPath, opts) {
|
|
|
97
101
|
} : {}),
|
|
98
102
|
// minify를 켜면 실제로 실행되는 묶음 코드를 줄인다 (원본 JS는 이제 실행되지 않음)
|
|
99
103
|
minify: opts.minify === true,
|
|
104
|
+
// 라이선스 주석(/*! · @license · @preserve)은 줄여도 묶음 끝에 모아 남긴다 (넣은 라이브러리의 고지 의무)
|
|
105
|
+
legalComments: 'eof',
|
|
106
|
+
// 어느 파일을 묶었는지 (dropBundledSources)
|
|
107
|
+
metafile: true,
|
|
100
108
|
bundle: true,
|
|
101
109
|
format: 'esm',
|
|
102
110
|
target: 'es2022',
|
|
@@ -106,7 +114,40 @@ async function bundle(entry, page, byPath, opts) {
|
|
|
106
114
|
}).catch(e => {
|
|
107
115
|
throw new Error(`${entry}를 묶지 못했습니다: ${e.errors?.[0]?.text ?? e.message ?? 'esbuild 오류'}. LXP에서는 모듈 스크립트를 따로 받을 수 없어 build가 HTML 안에 묶어 넣습니다.`);
|
|
108
116
|
});
|
|
109
|
-
return
|
|
117
|
+
return {
|
|
118
|
+
code: r.outputFiles[0]?.text ?? '',
|
|
119
|
+
inputs: Object.keys(r.metafile.inputs).map(k => k.replace(/^zip:/, ''))
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* 묶음 코드에서 다른 파일 이름을 찾을 글. 그 파일을 받는 코드가 아닌 것은 뺀다: 주석(줄이지 않을 때 esbuild가 다는
|
|
124
|
+
* `// zip:파일` 포함), 줄이지 않을 때 esbuild가 모듈을 감싸며 쓰는 이름(`"zip:파일"()`), import.meta.url 대신 넣은 원래 파일 주소
|
|
125
|
+
*/
|
|
126
|
+
async function scanText(code, inputs) {
|
|
127
|
+
const bare = await withoutComments('x.js', code);
|
|
128
|
+
const own = new Set(inputs);
|
|
129
|
+
return bare.replace(/"zip:([^"]+)"/g, (m, p) => own.has(p) ? '""' : m).replace(/new URL\("(?:\.\.\/)*([^"]+)",\s*location\.href\)\.href/g, (m, p) => own.has(p) ? '""' : m);
|
|
130
|
+
}
|
|
131
|
+
/** 주석을 뺀 글 (주석 속 파일 이름은 받는 것이 아니다). JS는 esbuild로, 문법이 틀리면 그대로 */
|
|
132
|
+
async function withoutComments(path, text) {
|
|
133
|
+
if (/\.html?$/i.test(path)) return text.replace(/<!--[\s\S]*?-->/g, '');
|
|
134
|
+
if (/\.css$/i.test(path)) return text.replace(/\/\*[\s\S]*?\*\//g, '');
|
|
135
|
+
if (!/\.m?js$/i.test(path)) return text;
|
|
136
|
+
try {
|
|
137
|
+
return (await transform(text, {
|
|
138
|
+
loader: 'js',
|
|
139
|
+
minifyWhitespace: true,
|
|
140
|
+
legalComments: 'none'
|
|
141
|
+
})).code;
|
|
142
|
+
} catch {
|
|
143
|
+
return text;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** 경로나 파일 이름이 나오는지. 앞에 이름 글자가 붙어 있으면 다른 파일이다 (editor.js ≠ elice-content-editor.js) */
|
|
147
|
+
function mentions(path, text) {
|
|
148
|
+
const name = path.split('/').pop() ?? path;
|
|
149
|
+
const escape = x => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
150
|
+
return new RegExp(`(?<![\\w.-])(?:${escape(path)}|${escape(name)})`).test(text);
|
|
110
151
|
}
|
|
111
152
|
/** zip 안 JSON을 넣어 두고, 그 주소를 fetch하면 넣어 둔 내용을 돌려준다 */
|
|
112
153
|
function jsonPrelude(files, page) {
|
|
@@ -132,6 +173,8 @@ opts = {}) {
|
|
|
132
173
|
const byPath = new Map(files.map(f => [f.path, f]));
|
|
133
174
|
const pages = [];
|
|
134
175
|
const out = [];
|
|
176
|
+
const inputs = new Set();
|
|
177
|
+
const pageTexts = new Map();
|
|
135
178
|
for (const f of files) {
|
|
136
179
|
if (!/\.html?$/i.test(f.path)) {
|
|
137
180
|
out.push(f);
|
|
@@ -153,11 +196,17 @@ opts = {}) {
|
|
|
153
196
|
}
|
|
154
197
|
let next = '';
|
|
155
198
|
let last = 0;
|
|
199
|
+
let scan = '';
|
|
156
200
|
for (const [i, m] of scripts.entries()) {
|
|
157
201
|
const src = attr(m[1] ?? '', 'src') ?? '';
|
|
158
202
|
const entry = resolveRef(f.path, src.replace(/[?#].*$/, ''));
|
|
159
203
|
if (entry === null || !byPath.has(entry)) throw new Error(`${f.path}의 모듈 스크립트 파일이 없습니다: ${src}`);
|
|
160
|
-
const
|
|
204
|
+
const {
|
|
205
|
+
code,
|
|
206
|
+
inputs: used
|
|
207
|
+
} = await bundle(entry, f.path, byPath, opts);
|
|
208
|
+
for (const p of used) inputs.add(p);
|
|
209
|
+
scan += `${await withoutComments(f.path, html.slice(last, m.index))}\n${await scanText(code, used)}\n`;
|
|
161
210
|
next += html.slice(last, m.index);
|
|
162
211
|
if (i === 0) next += jsonPrelude(files, f.path);
|
|
163
212
|
// data-ecdk-bundle: 원본(ecdk-ignore 주석 포함)을 이미 검사했으니 zip 검사에서 이 본문은 다시 보지 않는다
|
|
@@ -165,7 +214,9 @@ opts = {}) {
|
|
|
165
214
|
last = (m.index ?? 0) + m[0].length;
|
|
166
215
|
}
|
|
167
216
|
next += html.slice(last);
|
|
217
|
+
scan += await withoutComments(f.path, html.slice(last));
|
|
168
218
|
pages.push(f.path);
|
|
219
|
+
pageTexts.set(f.path, scan);
|
|
169
220
|
out.push({
|
|
170
221
|
...f,
|
|
171
222
|
data: encoder.encode(next)
|
|
@@ -175,8 +226,59 @@ opts = {}) {
|
|
|
175
226
|
files: out,
|
|
176
227
|
report: {
|
|
177
228
|
pages
|
|
229
|
+
},
|
|
230
|
+
bundled: {
|
|
231
|
+
inputs,
|
|
232
|
+
pageTexts
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
/** 묶음에 남은 import(): 묶을 때 풀지 못한 것(변수 · 조합 주소)이라 어느 파일을 받는지 모른다 */
|
|
237
|
+
const DYNAMIC_IMPORT = /\bimport\s*\(/;
|
|
238
|
+
/**
|
|
239
|
+
* 묶어 넣은 원본 JS 중 다른 데서 이름이 나오지 않는 파일을 뺀다 (zip 크기 · 같은 코드 두 벌).
|
|
240
|
+
* 묶은 파일(.js · .mjs)마다, 남는 텍스트 파일(묶은 페이지는 BundledSources.pageTexts)에 경로나 파일 이름이 나오면 둔다:
|
|
241
|
+
* 일반 <script src> · new Worker('…') · fetch · HTML · CSS · 문자열로 조합한 주소. 둔 파일은 따로 받히므로 그 안의
|
|
242
|
+
* import도 찾아 계속 둔다. 묶음에 import()가 남았으면(변수 주소) 무엇을 받는지 몰라 하나도 빼지 않는다.
|
|
243
|
+
* metadata.json · 화면 진입 파일(HTML) · JSON · CSS는 JS가 아니라 대상이 아니다.
|
|
244
|
+
*/
|
|
245
|
+
async function dropBundledSources(files, bundled) {
|
|
246
|
+
const byPath = new Map(files.map(f => [f.path, f]));
|
|
247
|
+
const candidates = [...bundled.inputs].filter(p => /\.m?js$/i.test(p) && byPath.has(p));
|
|
248
|
+
if (candidates.length === 0) return {
|
|
249
|
+
files,
|
|
250
|
+
report: {
|
|
251
|
+
dropped: []
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
if ([...bundled.pageTexts.values()].some(t => DYNAMIC_IMPORT.test(t))) return {
|
|
255
|
+
files,
|
|
256
|
+
report: {
|
|
257
|
+
dropped: [],
|
|
258
|
+
keptAll: '묶은 코드에 주소를 조합하는 import()가 있어 어느 파일을 받는지 몰라 원본 JS를 모두 둡니다'
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
const isCandidate = new Set(candidates);
|
|
262
|
+
const texts = await Promise.all(files.filter(f => !isCandidate.has(f.path) && TEXT_FILE.test(f.path)).map(async f => bundled.pageTexts.get(f.path) ?? withoutComments(f.path, decoder.decode(f.data))));
|
|
263
|
+
const kept = new Set();
|
|
264
|
+
// 둔 파일의 글에서 다시 찾는다 (둔 파일은 따로 받히므로 그 안의 import도 받힌다)
|
|
265
|
+
for (let grew = true; grew;) {
|
|
266
|
+
grew = false;
|
|
267
|
+
for (const p of candidates) {
|
|
268
|
+
if (kept.has(p) || !texts.some(t => mentions(p, t))) continue;
|
|
269
|
+
kept.add(p);
|
|
270
|
+
texts.push(await withoutComments(p, decoder.decode(byPath.get(p)?.data)));
|
|
271
|
+
grew = true;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const dropped = candidates.filter(p => !kept.has(p)).sort();
|
|
275
|
+
const gone = new Set(dropped);
|
|
276
|
+
return {
|
|
277
|
+
files: files.filter(f => !gone.has(f.path)),
|
|
278
|
+
report: {
|
|
279
|
+
dropped
|
|
178
280
|
}
|
|
179
281
|
};
|
|
180
282
|
}
|
|
181
283
|
|
|
182
|
-
export { BUNDLE_ATTR, inlineModuleScripts };
|
|
284
|
+
export { BUNDLE_ATTR, dropBundledSources, inlineModuleScripts };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { compareVersions } from '
|
|
1
|
+
import { compareVersions } from '../rules/semver.js';
|
|
2
2
|
export { compareVersions };
|
|
3
3
|
/** 다른 스킬이 ../elice-content-guide/topics/로 읽는 공유 개발 가이드 스킬 */
|
|
4
4
|
export declare const GUIDE_SKILL = "elice-content-guide";
|
|
@@ -65,19 +65,3 @@ export declare function install(opts: {
|
|
|
65
65
|
* Helpy Code 데스크톱은 바로 다시 읽는지 확인하지 못해 다시 시작하라고 한다
|
|
66
66
|
*/
|
|
67
67
|
export declare function reloadNotes(skillsDirCreated: boolean): string[];
|
|
68
|
-
export type PlannedAction = InstallResult['skills'][number]['action'] | 'would-install' | 'would-update';
|
|
69
|
-
/** --dry-run: 스킬 폴더를 쓰지 않고 install이 무엇을 할지만 */
|
|
70
|
-
export declare function planInstall(opts: {
|
|
71
|
-
project: boolean;
|
|
72
|
-
force: boolean;
|
|
73
|
-
cwd?: string | undefined;
|
|
74
|
-
home?: string | undefined;
|
|
75
|
-
root?: string | undefined;
|
|
76
|
-
version?: string | undefined;
|
|
77
|
-
}): {
|
|
78
|
-
dir: string;
|
|
79
|
-
skills: {
|
|
80
|
-
name: string;
|
|
81
|
-
action: PlannedAction;
|
|
82
|
-
}[];
|
|
83
|
-
};
|
|
@@ -4,17 +4,17 @@ import { mkdir, copyFile, writeFile } from 'node:fs/promises';
|
|
|
4
4
|
import { homedir } from 'node:os';
|
|
5
5
|
import { join, resolve, dirname, relative, sep } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
|
-
import { compareVersions } from '
|
|
7
|
+
import { compareVersions } from '../rules/semver.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
* 스킬 설치 · 상태 검사 (
|
|
10
|
+
* 스킬 설치 · 상태 검사 (ecdk setup · update · uninstall · doctor가 쓴다).
|
|
11
11
|
* 설치 위치는 ~/.claude/skills/ (모든 프로젝트) 또는 --project면 현재 폴더의 .claude/skills/.
|
|
12
12
|
*/
|
|
13
|
-
/** CLI 패키지의 skills/ (es/
|
|
14
|
-
const SKILLS_ROOT = fileURLToPath(new URL('
|
|
13
|
+
/** CLI 패키지의 skills/ (es/core/와 src/core/ 모두 두 단계 위) */
|
|
14
|
+
const SKILLS_ROOT = fileURLToPath(new URL('../../skills', import.meta.url));
|
|
15
15
|
/** 모든 스킬에 끼워 넣는 공통 규칙 */
|
|
16
16
|
const SHARED_DIR = '_shared';
|
|
17
|
-
const PACKAGE_VERSION = JSON.parse(readFileSync(fileURLToPath(new URL('
|
|
17
|
+
const PACKAGE_VERSION = JSON.parse(readFileSync(fileURLToPath(new URL('../../package.json', import.meta.url)), 'utf8')).version;
|
|
18
18
|
/** 설치한 스킬 맨 끝 줄. 버전 · 내용 지문으로 오래됨 · 손으로 고침을 알아본다 */
|
|
19
19
|
const STAMP = /<!-- ecdk-skill: (\S+) (\S+) (sha256-[A-Za-z0-9+/=]+) -->\s*$/;
|
|
20
20
|
/**
|
|
@@ -241,21 +241,5 @@ async function install(opts) {
|
|
|
241
241
|
function reloadNotes(skillsDirCreated) {
|
|
242
242
|
return [skillsDirCreated ? 'Claude Code: 이미 열려 있던 Claude Code 세션에서는 /reload-skills를 한 번 입력하세요 (새로 여는 세션은 필요 없음).' : 'Claude Code: 열려 있는 세션에도 바뀐 스킬이 자동으로 적용됩니다.', 'Helpy Code 데스크톱은 다시 시작하세요.'];
|
|
243
243
|
}
|
|
244
|
-
/** --dry-run: 스킬 폴더를 쓰지 않고 install이 무엇을 할지만 */
|
|
245
|
-
function planInstall(opts) {
|
|
246
|
-
const dir = skillsDir(opts);
|
|
247
|
-
const skills = skillNames(opts.root).map(name => {
|
|
248
|
-
const state = inspectSkill(dir, name, opts.version).state;
|
|
249
|
-
const action = state === 'missing' ? 'would-install' : state === 'current' ? 'skipped' : state === 'outdated' || opts.force ? 'would-update' : state === 'newer' ? 'newer' : 'kept';
|
|
250
|
-
return {
|
|
251
|
-
name,
|
|
252
|
-
action
|
|
253
|
-
};
|
|
254
|
-
});
|
|
255
|
-
return {
|
|
256
|
-
dir,
|
|
257
|
-
skills
|
|
258
|
-
};
|
|
259
|
-
}
|
|
260
244
|
|
|
261
|
-
export { GUIDE_SKILL, compareVersions, inspectSkill, install, isDotPath, markedSkillNames,
|
|
245
|
+
export { GUIDE_SKILL, compareVersions, inspectSkill, install, isDotPath, markedSkillNames, reloadNotes, removeSkillFiles, renderSkill, skillFiles, skillNames, skillsDir };
|
package/es/dev/grading.d.ts
CHANGED
|
@@ -15,7 +15,7 @@ export declare function matchesPattern(answerKey: unknown, answer: unknown): boo
|
|
|
15
15
|
* 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이다. 완료 정책은 LXP 설정이라 보지 않는다 (ADR 0012):
|
|
16
16
|
* 채점 설정이 있으면 채점하고, 없으면 제출만 받는다.
|
|
17
17
|
* - pattern: 답 문자열 전체를 정규식 하나로 비교 0 / 100
|
|
18
|
-
* - rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지
|
|
18
|
+
* - rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지 않음)
|
|
19
19
|
* - 채점 설정(편집 화면이 저장하는 settings.grading)이 없으면 제출만 받고 `{ null, null }`
|
|
20
20
|
*/
|
|
21
21
|
export declare function grade(local: LocalGrading | undefined, answer: unknown): GradeResult;
|
package/es/dev/grading.js
CHANGED
|
@@ -16,7 +16,7 @@ function matchesPattern(answerKey, answer) {
|
|
|
16
16
|
* 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이다. 완료 정책은 LXP 설정이라 보지 않는다 (ADR 0012):
|
|
17
17
|
* 채점 설정이 있으면 채점하고, 없으면 제출만 받는다.
|
|
18
18
|
* - pattern: 답 문자열 전체를 정규식 하나로 비교 0 / 100
|
|
19
|
-
* - rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지
|
|
19
|
+
* - rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지 않음)
|
|
20
20
|
* - 채점 설정(편집 화면이 저장하는 settings.grading)이 없으면 제출만 받고 `{ null, null }`
|
|
21
21
|
*/
|
|
22
22
|
function grade(local, answer) {
|
package/es/dev/host-page.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DEV_MESSAGE_SOURCE } from './inject.js';
|
|
1
2
|
import { DEV_MATERIAL_ID } from './mock-api.js';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -75,10 +76,12 @@ function hostPage(opts) {
|
|
|
75
76
|
</header>
|
|
76
77
|
<div id="check">검사 중…</div>
|
|
77
78
|
<pre id="messages" aria-live="polite"></pre>
|
|
78
|
-
<main><iframe id="content" sandbox="allow-scripts" title="콘텐츠"></iframe></main>
|
|
79
|
+
<main><iframe id="content" sandbox="allow-scripts allow-same-origin" title="콘텐츠"></iframe></main>
|
|
79
80
|
<script type="module">
|
|
80
81
|
const MATERIAL_ID = ${JSON.stringify(DEV_MATERIAL_ID)};
|
|
81
82
|
const SDK_SOURCE = 'eliceio-content-sdk';
|
|
83
|
+
// ecdk dev가 콘텐츠 HTML에 넣는 스크립트(inject.ts)의 메시지: 콘텐츠 CSP가 막은 요청
|
|
84
|
+
const DEV_SOURCE = ${JSON.stringify(DEV_MESSAGE_SOURCE)};
|
|
82
85
|
// [보기, 이름, 화면, 주소 조각]. token은 흉내 서버가 발급. 내용 편집은 LXP처럼 저장된 버전을 edit 토큰으로 연다
|
|
83
86
|
const SCENARIOS = [
|
|
84
87
|
['student', '학생', 'learn', 'token'],
|
|
@@ -115,8 +118,11 @@ function hostPage(opts) {
|
|
|
115
118
|
// 교육자 화면은 instructor 진입 파일이 없으면 학생 화면을 연다 (@eliceio/cdk resolveScreen과 같음)
|
|
116
119
|
const entryOf = (screen) => state.entries[screen] || (screen === 'instructor' ? state.entries.learn : undefined);
|
|
117
120
|
|
|
121
|
+
// 막힌 외부 요청은 콘텐츠를 열 때마다 한 번씩만 적는다
|
|
122
|
+
let blocked = new Set();
|
|
118
123
|
async function open(scenario) {
|
|
119
124
|
current = scenario;
|
|
125
|
+
blocked = new Set();
|
|
120
126
|
try { sessionStorage.setItem('ecdk-scenario', scenario); } catch {}
|
|
121
127
|
for (const b of scenariosEl.children) b.setAttribute('aria-pressed', String(b.dataset.scenario === scenario));
|
|
122
128
|
previewEl.setAttribute('aria-pressed', String(scenario === PREVIEW[0]));
|
|
@@ -136,7 +142,7 @@ function hostPage(opts) {
|
|
|
136
142
|
}
|
|
137
143
|
|
|
138
144
|
// 화면(learn · instructor · edit)은 검사기가 kindModes로 이미 걸러 state.entries에 켠 것만 온다.
|
|
139
|
-
// 문제 설명에는 학생 보기만 둔다: 다른 보기가 있는지는 서버 · LXP와 아직 정하지 않았다
|
|
145
|
+
// 문제 설명에는 학생 보기만 둔다: 다른 보기가 있는지는 서버 · LXP와 아직 정하지 않았다
|
|
140
146
|
const available = (s) => entryOf(s[2]) && (state.kind !== 'description' || s[0] === 'student');
|
|
141
147
|
function renderScenarios() {
|
|
142
148
|
scenariosEl.replaceChildren(...SCENARIOS.filter(available).map(([scenario, label]) => {
|
|
@@ -161,6 +167,15 @@ function hostPage(opts) {
|
|
|
161
167
|
window.addEventListener('message', (event) => {
|
|
162
168
|
if (event.source !== frame.contentWindow) return;
|
|
163
169
|
const data = event.data;
|
|
170
|
+
if (data && typeof data === 'object' && data.source === DEV_SOURCE && data.type === 'csp-violation') {
|
|
171
|
+
const p = data.payload || {};
|
|
172
|
+
const key = p.blockedURI + ' ' + p.violatedDirective;
|
|
173
|
+
if (!blocked.has(key)) {
|
|
174
|
+
blocked.add(key);
|
|
175
|
+
note('막힌 외부 요청: ' + p.blockedURI + ' (' + p.violatedDirective + ') — LXP 콘텐츠 CSP도 막습니다. zip 안에 넣어 주세요');
|
|
176
|
+
}
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
164
179
|
if (!data || typeof data !== 'object' || data.source !== SDK_SOURCE) return;
|
|
165
180
|
const payload = data.payload || {};
|
|
166
181
|
switch (data.type) {
|
|
@@ -170,7 +185,7 @@ function hostPage(opts) {
|
|
|
170
185
|
? 'settings-saved: 저장했습니다. 다른 보기에서 material.settings로 받습니다 (내용 · 채점 방식 · 답은 .ecdk/settings.json)'
|
|
171
186
|
: 'settings-saved: 저장 실패 (' + payload.code + ')');
|
|
172
187
|
return;
|
|
173
|
-
// init의 불러오기
|
|
188
|
+
// init의 불러오기 상태. loading · ready는 매번 오므로 적지 않고, 실패만 적는다
|
|
174
189
|
// (LXP는 failed를 받으면 자기 실패 화면을 띄움: reason network · auth · config)
|
|
175
190
|
case 'status':
|
|
176
191
|
if (payload.state === 'failed')
|
|
@@ -196,8 +211,8 @@ function hostPage(opts) {
|
|
|
196
211
|
hasNextLecturePage: document.getElementById('has-next').checked,
|
|
197
212
|
},
|
|
198
213
|
};
|
|
199
|
-
//
|
|
200
|
-
event.source.postMessage(reply,
|
|
214
|
+
// 콘텐츠는 콘텐츠 서버 출처로 돈다 (allow-same-origin): 그 출처로만 보낸다
|
|
215
|
+
event.source.postMessage(reply, new URL(state.contentBase).origin);
|
|
201
216
|
note('navigate-state-sync → ' + JSON.stringify(reply.payload));
|
|
202
217
|
return;
|
|
203
218
|
}
|
package/es/dev/inject.d.ts
CHANGED
|
@@ -2,7 +2,13 @@
|
|
|
2
2
|
* dev에서만 콘텐츠 HTML의 <head> 맨 앞에 넣는 스크립트 (zip에는 들어가지 않음).
|
|
3
3
|
* - 키트가 흉내 서버를 쓰도록 API 주소를, 콘텐츠 주소를 직접 열어 mock으로 돌 때 쓸 로컬 채점 설정 주소를 알려 줌 (window.__ECDK_DEV__)
|
|
4
4
|
* - 콘솔 오류 · 처리 안 된 예외 · 불러오지 못한 파일을 터미널로 보냄
|
|
5
|
+
* - 콘텐츠 CSP(rules/csp.ts)가 막은 요청(securitypolicyviolation)을 dev 화면(부모 창, 호스트 출처로만)과 터미널에 알림.
|
|
6
|
+
* 키트가 아니라 여기서 듣는 이유: 이 스크립트는 ecdk dev 응답에만 들어가 운영 LXP에서는 돌지 않고, 다른 스크립트보다
|
|
7
|
+
* 먼저 돌아 HTML의 <img> · CSS 글꼴처럼 키트(모듈 스크립트)가 뜨기 전에 막힌 요청도 놓치지 않으며, 키트를 쓰지 않는
|
|
8
|
+
* 옮겨 온 HTML에서도 동작한다
|
|
5
9
|
*/
|
|
10
|
+
/** dev 스크립트 → dev 화면 메시지 (SDK 메시지 source와 다름) */
|
|
11
|
+
export declare const DEV_MESSAGE_SOURCE = "ecdk-dev";
|
|
6
12
|
export declare function devScript(hostOrigin: string): string;
|
|
7
13
|
/** <head> 바로 뒤(없으면 맨 앞)에 넣는다. 다른 스크립트보다 먼저 돌아야 오류를 놓치지 않는다 */
|
|
8
14
|
export declare function injectDevScript(html: string, hostOrigin: string): string;
|