@eliceio/cdk-cli 0.1.0-alpha.7 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +64 -57
  2. package/es/commands/build/index.d.ts +3 -23
  3. package/es/commands/build/index.js +16 -148
  4. package/es/commands/doctor/index.d.ts +3 -2
  5. package/es/commands/doctor/index.js +10 -9
  6. package/es/commands/validate/index.js +3 -1
  7. package/es/core/collect.d.ts +1 -1
  8. package/es/core/collect.js +3 -1
  9. package/es/core/config.d.ts +2 -2
  10. package/es/core/config.js +1 -1
  11. package/es/core/manifest.d.ts +3 -3
  12. package/es/core/manifest.js +4 -8
  13. package/es/core/mcp.d.ts +1 -1
  14. package/es/core/prepare.d.ts +15 -10
  15. package/es/core/prepare.js +35 -35
  16. package/es/core/project-check.d.ts +6 -5
  17. package/es/core/project-check.js +9 -9
  18. package/es/core/sandbox.d.ts +6 -30
  19. package/es/core/sandbox.js +32 -109
  20. package/es/core/sdk.d.ts +7 -18
  21. package/es/core/sdk.js +8 -38
  22. package/es/dev/server.d.ts +6 -4
  23. package/es/dev/server.js +47 -77
  24. package/es/engines/vite/index.d.ts +2 -2
  25. package/es/engines/vite/index.js +2 -4
  26. package/es/engines/vite/plugin.d.ts +58 -0
  27. package/es/engines/vite/plugin.js +286 -0
  28. package/es/engines/vite/run.d.ts +15 -0
  29. package/es/engines/vite/run.js +92 -0
  30. package/es/rules/check.js +9 -11
  31. package/es/rules/index.d.ts +1 -1
  32. package/es/rules/index.js +1 -1
  33. package/es/rules/types.d.ts +8 -3
  34. package/es/rules/unused.d.ts +0 -2
  35. package/es/rules/unused.js +3 -4
  36. package/es/rules.json.js +1 -1
  37. package/es/test-packages.d.ts +3 -1
  38. package/package.json +8 -3
  39. package/rules.json +9 -3
  40. package/skills/_shared/always.md +1 -1
  41. package/skills/elice-content-guide/topics/03-create-the-project.md +1 -1
  42. package/skills/elice-content-guide/topics/04-rules.md +1 -1
  43. package/skills/elice-content-guide/topics/07-move-existing-html.md +2 -2
  44. package/skills/elice-content-guide/topics/08-fix-check-errors.md +21 -21
  45. package/skills/elice-content-guide/topics/10-build.md +1 -1
  46. package/templates/_shared/lib/elice-content.js +8 -12
  47. package/templates/blank/README.md +2 -3
  48. package/templates/quiz/README.md +2 -3
  49. package/es/core/minify.d.ts +0 -18
  50. package/es/core/minify.js +0 -122
  51. package/es/engines/static/index.d.ts +0 -3
  52. package/es/engines/static/index.js +0 -11
  53. package/es/engines/types.d.ts +0 -12
@@ -51,9 +51,9 @@ export interface ContentConfig {
51
51
  outDir: string;
52
52
  /** 추가로 뺄 파일·폴더 (basename glob `*` 또는 프로젝트 기준 경로 접두사) */
53
53
  exclude: string[];
54
- /** build가 JS · CSS · JSON을 줄여(주석 빼고) zip에 넣는다. 기본 true, false면 끈다 */
54
+ /** build(Vite)가 묶은 JS · CSS를 줄여(주석 빼고) zip에 넣는다. 기본 true, false면 끈다 */
55
55
  minify?: boolean;
56
- /** minify와 함께: 줄인 JS · CSS마다 .map을 zip에 넣어 운영에서도 원본 위치로 오류를 본다 (용량이 늘어남) */
56
+ /** minify와 함께: 묶은 스크립트에 inline map을 붙여 운영에서도 원본 위치로 오류를 본다 (용량이 늘어남) */
57
57
  sourcemap?: boolean;
58
58
  /** ecdk create가 적는 템플릿과 버전 (예: "quiz@1.0.0"). metadata.json build.template으로 */
59
59
  template?: string;
package/es/core/config.js CHANGED
@@ -2,7 +2,7 @@ import { readFile, writeFile, unlink } from 'node:fs/promises';
2
2
  import { join, resolve, basename } from 'node:path';
3
3
  import 'fflate';
4
4
  import { rules } from '../rules/spec.js';
5
- import { COMPLETION_POLICIES_IGNORED, LEGACY_COMPLETION_SCREENS, LEGACY_COMPLETION_FIELDS, parseManifest, serializeManifest, graderTypeError } from '../rules/manifest.js';
5
+ import { LEGACY_COMPLETION_SCREENS, LEGACY_COMPLETION_FIELDS, parseManifest, serializeManifest, COMPLETION_POLICIES_IGNORED, graderTypeError } from '../rules/manifest.js';
6
6
 
7
7
  /**
8
8
  * 채점 방식 = `settings.grading.type`. 원본은 rules.json `manifest.graderTypes`.
@@ -2,12 +2,12 @@ import { type BuildInfo } from '../rules/index.js';
2
2
  import type { SourceFile } from './collect.js';
3
3
  /**
4
4
  * metadata.json의 build. 같은 입력이면 같은 결과가 나오도록 시각 등 바뀌는 값은 넣지 않는다.
5
- * template은 ecdk create가 package.json "ecdk"에 적은 값. sdk는 zip lib/cdk.js 머리말에서 읽는다
6
- * (build가 node_modules/@eliceio/cdk에서 넣으며 붙인 것, 옛 프로젝트는 복사본 머리말).
5
+ * template은 ecdk create가 package.json "ecdk"에 적은 값. sdk는 번들로 묶은 @eliceio/cdk의 설치 버전
6
+ * (node_modules/@eliceio/cdk/package.json).
7
7
  */
8
8
  export declare function createBuildInfo(engine: string, extra?: {
9
9
  template?: string | undefined;
10
- files?: SourceFile[];
10
+ sdk?: string | undefined;
11
11
  }): BuildInfo;
12
12
  /**
13
13
  * zip 내용의 지문. metadata.json을 뺀 파일을 이름순으로 `경로 \0 길이 \0 내용`을 이어 SHA-256.
@@ -4,16 +4,12 @@ import { RULES_VERSION } from '../rules/spec.js';
4
4
  import { VERSION } from '../version.js';
5
5
  import { PROTOCOL_VERSION } from './protocol.js';
6
6
 
7
- /** lib/cdk.js 머리말: `/* @eliceio/cdk 1.0.0 — UMD. …` 또는 `/* @eliceio/cdk 1.0.0 (브랜치@커밋) · …` */
8
- const SDK_HEADER = /^\/\* @eliceio\/cdk (\S+)(?: \(([^)]+)\))?/;
9
7
  /**
10
8
  * metadata.json의 build. 같은 입력이면 같은 결과가 나오도록 시각 등 바뀌는 값은 넣지 않는다.
11
- * template은 ecdk create가 package.json "ecdk"에 적은 값. sdk는 zip lib/cdk.js 머리말에서 읽는다
12
- * (build가 node_modules/@eliceio/cdk에서 넣으며 붙인 것, 옛 프로젝트는 복사본 머리말).
9
+ * template은 ecdk create가 package.json "ecdk"에 적은 값. sdk는 번들로 묶은 @eliceio/cdk의 설치 버전
10
+ * (node_modules/@eliceio/cdk/package.json).
13
11
  */
14
12
  function createBuildInfo(engine, extra = {}) {
15
- const sdkFile = extra.files?.find(f => f.path === 'lib/cdk.js');
16
- const header = sdkFile ? SDK_HEADER.exec(new TextDecoder().decode(sdkFile.data.subarray(0, 300))) : null;
17
13
  return {
18
14
  cli: VERSION,
19
15
  rules: RULES_VERSION,
@@ -22,8 +18,8 @@ function createBuildInfo(engine, extra = {}) {
22
18
  ...(extra.template ? {
23
19
  template: extra.template
24
20
  } : {}),
25
- ...(header ? {
26
- sdk: header[2] ? `${header[1]} (${header[2]})` : header[1]
21
+ ...(extra.sdk ? {
22
+ sdk: extra.sdk
27
23
  } : {})
28
24
  };
29
25
  }
package/es/core/mcp.d.ts CHANGED
@@ -35,7 +35,7 @@ export declare function defaultMcpEnv(): McpEnv;
35
35
  export declare const helpyConfigPath: (env: McpEnv) => string;
36
36
  export declare function detectTargets(env: McpEnv): McpTarget[];
37
37
  /** 주소로 환경 이름: 운영 주소면 prod, 아니면 custom (--url로 준 주소) */
38
- export declare const envOfUrl: (url: string) => "prod" | "custom";
38
+ export declare const envOfUrl: (url: string) => "custom" | "prod";
39
39
  export type ClaudeRegistration = {
40
40
  state: 'user';
41
41
  url: string;
@@ -1,28 +1,33 @@
1
1
  import { type Excluded, type SourceFile } from './collect.js';
2
2
  import { type ContentConfig } from './config.js';
3
+ /** 빌드 엔진 (metadata.json build.engine). ecdk build · dev는 Vite 위에서 돈다 (engines/vite) */
4
+ export declare const ENGINE = "vite";
5
+ /** Vite 기본 public 폴더 (원본 폴더 기준). 안의 파일은 묶지 않고 그대로 zip 최상위 경로에 들어간다 */
6
+ export declare const PUBLIC_DIR = "public/";
3
7
  export interface PreparedContent {
4
8
  srcDir: string;
5
9
  outDir: string;
6
10
  engine: string;
7
- /** zip에 들어갈 파일 전부 (metadata.json 포함) */
11
+ /** 원본 중 zip 대상 파일 전부 (metadata.json 포함, 번들 전, public/ 파일은 zip 경로로). 검사는 이 원본으로 한다 */
8
12
  files: SourceFile[];
13
+ /** public/ 폴더의 파일 (zip 경로, public/ 뺀 것). build가 원본 그대로 zip에 넣는다 */
14
+ publicFiles: Set<string>;
9
15
  excluded: Excluded[];
10
16
  sdk: PreparedSdk;
11
17
  }
12
- /** SDK(@eliceio/cdk)를 어디서 넣었는지 (ADR 0010 최종 결정) */
18
+ /** SDK(@eliceio/cdk) 의존성 상태 (ADR 0010). SDK는 build가 번들로 묶고 파일로 넣지 않는다 */
13
19
  export interface PreparedSdk {
14
20
  /** package.json에 @eliceio/cdk가 있는지 */
15
21
  declared: boolean;
16
22
  /** 적은 범위 */
17
23
  range?: string | undefined;
18
- /** zip에 넣은 설치 버전 */
24
+ /** 설치된 버전 (metadata.json build.sdk) */
19
25
  version?: string | undefined;
20
- /** 적었는데 node_modules에 없음 (requireSdk: false일 때만, 아니면 오류) */
26
+ /** 적었는데 node_modules에 없음 (build는 오류, dev · doctor는 알림) */
21
27
  missing: boolean;
22
- /** package.json에 없고 원본에 lib/cdk.js 복사본이 있는 옛 프로젝트 (sdk.lib-copy 경고) */
23
- legacyCopy: boolean;
24
28
  }
25
- /** build와 doctor가 같은 결과를 보도록: 수집 → 엔진 → metadata.json(화면 + 빌드 정보). 디스크에는 쓰지 않는다. */
26
- export declare function prepareContent(projectDir: string, config: ContentConfig, options?: {
27
- requireSdk?: boolean;
28
- }): Promise<PreparedContent>;
29
+ /**
30
+ * build · dev · doctor가 같은 결과를 보도록: 수집 → metadata.json(화면 + 빌드 정보). 디스크에는 쓰지 않는다.
31
+ * 번들은 하지 않는다 (Vite 플러그인 engines/vite가 이 결과로 입력 HTML · 그대로 넣을 파일 · 검사를 정한다)
32
+ */
33
+ export declare function prepareContent(projectDir: string, config: ContentConfig): Promise<PreparedContent>;
@@ -1,19 +1,25 @@
1
1
  import { resolve, relative, sep, isAbsolute } from 'node:path';
2
- import { staticEngine } from '../engines/static/index.js';
3
2
  import 'fflate';
4
3
  import { rules } from '../rules/spec.js';
5
4
  import { serializeManifest } from '../rules/manifest.js';
6
5
  import { collectSources } from './collect.js';
7
6
  import { CONFIG_FILE, PLATFORM_KEYS } from './config.js';
8
7
  import { createBuildInfo } from './manifest.js';
9
- import { readProjectSdk, SDK_ZIP_PATH, sdkZipFile, missingSdkMessage } from './sdk.js';
8
+ import { LEGACY_SDK_COPY, readProjectSdk } from './sdk.js';
10
9
 
10
+ /** 빌드 엔진 (metadata.json build.engine). ecdk build · dev는 Vite 위에서 돈다 (engines/vite) */
11
+ const ENGINE = 'vite';
12
+ /** Vite 기본 public 폴더 (원본 폴더 기준). 안의 파일은 묶지 않고 그대로 zip 최상위 경로에 들어간다 */
13
+ const PUBLIC_DIR = 'public/';
11
14
  const isInside = (parent, child) => {
12
15
  const rel = relative(parent, child);
13
16
  return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
14
17
  };
15
- /** build와 doctor가 같은 결과를 보도록: 수집 → 엔진 → metadata.json(화면 + 빌드 정보). 디스크에는 쓰지 않는다. */
16
- async function prepareContent(projectDir, config, options = {}) {
18
+ /**
19
+ * build · dev · doctor가 같은 결과를 보도록: 수집 → metadata.json(화면 + 빌드 정보). 디스크에는 쓰지 않는다.
20
+ * 번들은 하지 않는다 (Vite 플러그인 engines/vite가 이 결과로 입력 HTML · 그대로 넣을 파일 · 검사를 정한다)
21
+ */
22
+ async function prepareContent(projectDir, config) {
17
23
  const srcDir = resolve(projectDir, config.root);
18
24
  const outDir = resolve(projectDir, config.outDir);
19
25
  // build는 <outDir>/content/를 지우고 다시 만든다: 프로젝트 밖이나 프로젝트 폴더 자체를 가리키면 다른 데이터를 지울 수 있다
@@ -28,42 +34,35 @@ async function prepareContent(projectDir, config, options = {}) {
28
34
  const {
29
35
  excluded
30
36
  } = collected;
31
- let sources = collected.files;
32
- // SDK: package.json에 @eliceio/cdk가 있으면 설치된 UMD 빌드를 zip lib/cdk.js로 넣는다 (원본에 옛 복사본이 있으면 대신함).
33
- // 없으면(옛 프로젝트) 원본 lib/cdk.js 복사본을 그대로 쓰고 sdk.lib-copy로 옮기는 법을 알린다.
34
- // dev는 설치 전에도 mock으로 열리게 requireSdk: false (실제 SDK 모드만 lib/cdk.js가 없어 실패)
37
+ // SDK 복사본(옛 lib/cdk.js)은 zip에 넣지 않는다: SDK는 package.json 의존성을 번들로 묶는다 (검사 sdk.lib-copy가 오류로 알림)
38
+ const kept = collected.files.filter(f => f.path !== LEGACY_SDK_COPY);
39
+ if (kept.length !== collected.files.length) excluded.push({
40
+ path: LEGACY_SDK_COPY,
41
+ reason: 'sdk'
42
+ });
43
+ // public/ 파일은 Vite처럼 zip 최상위 경로로 (실행 중 문자열 경로로 받는 파일 · 일반 <script src>)
44
+ const publicFiles = new Set();
45
+ const files = kept.map(f => {
46
+ if (!f.path.startsWith(PUBLIC_DIR)) return f;
47
+ const path = f.path.slice(PUBLIC_DIR.length);
48
+ publicFiles.add(path);
49
+ return {
50
+ ...f,
51
+ path
52
+ };
53
+ });
35
54
  const projectSdk = await readProjectSdk(projectDir);
36
55
  const sdk = {
37
56
  declared: projectSdk !== null,
38
57
  range: projectSdk?.range,
39
- missing: false,
40
- legacyCopy: projectSdk === null && sources.some(f => f.path === SDK_ZIP_PATH)
58
+ version: projectSdk?.installed?.version,
59
+ missing: projectSdk !== null && !projectSdk.installed
41
60
  };
42
- if (projectSdk) {
43
- const replaced = sources.some(f => f.path === SDK_ZIP_PATH);
44
- if (replaced) {
45
- excluded.push({
46
- path: SDK_ZIP_PATH,
47
- reason: 'sdk'
48
- });
49
- sources = sources.filter(f => f.path !== SDK_ZIP_PATH);
50
- }
51
- if (projectSdk.installed) {
52
- sources = [...sources, await sdkZipFile(projectSdk.installed)];
53
- sdk.version = projectSdk.installed.version;
54
- } else if (options.requireSdk === false) sdk.missing = true;else throw new Error(missingSdkMessage());
55
- }
56
- const engine = staticEngine;
57
- const files = await engine.build({
58
- srcDir,
59
- files: sources
60
- });
61
61
  // metadata.json (zip 최상위, ADR 0011): 원본에 작성자가 쓴 것을 그대로 두고 build만 채운다.
62
- // 원본에 없으면 옛 elice.config.json의 kind · screens로 만들고, 그것도 없으면 학생 화면만.
63
- // build.sdk는 zip lib/cdk.js 머리말에서 (설치된 SDK를 넣었으면 그 버전)
64
- const build = createBuildInfo(engine.name, {
62
+ // 원본에 없으면 옛 elice.config.json의 kind · screens로 만들고, 그것도 없으면 학생 화면만
63
+ const build = createBuildInfo(ENGINE, {
65
64
  template: config.template,
66
- files
65
+ sdk: sdk.version
67
66
  });
68
67
  // 학습 참고 내용 (만들 때만): 원본 최상위 .txt 파일을 zip에 그대로 두고, metadata.json commentary에 이름만 적는다
69
68
  const legacy = config.legacy ?? {};
@@ -106,11 +105,12 @@ async function prepareContent(projectDir, config, options = {}) {
106
105
  return {
107
106
  srcDir,
108
107
  outDir,
109
- engine: engine.name,
108
+ engine: ENGINE,
110
109
  files,
110
+ publicFiles,
111
111
  excluded,
112
112
  sdk
113
113
  };
114
114
  }
115
115
 
116
- export { prepareContent };
116
+ export { ENGINE, PUBLIC_DIR, prepareContent };
@@ -6,21 +6,22 @@ import type { CheckOptions } from '../rules/index.js';
6
6
  */
7
7
  export declare function findLegacyFiles(projectDir: string, config: ContentConfig): Promise<string[]>;
8
8
  /**
9
- * 옛 lib/cdk.js 복사본 (ADR 0010 최종 결정): package.json에 @eliceio/cdk가 없는데 원본에 lib/cdk.js가 있으면 그 경로
10
- * (프로젝트 기준). build는 복사본을 그대로 넣고 sdk.lib-copy로 옮기는 법을 알린다
9
+ * 옛 SDK 복사본 (ADR 0010): 원본에 lib/cdk.js가 있으면 그 경로 (프로젝트 기준). SDK는 package.json 의존성을
10
+ * build가 번들로 묶으므로 복사본은 zip에 넣지 않고 sdk.lib-copy 오류로 옮기는 법을 알린다
11
11
  */
12
12
  export declare function findLegacySdkCopy(projectDir: string, config: ContentConfig): Promise<string | undefined>;
13
13
  /**
14
14
  * 프로젝트(ecdk 프로젝트 폴더)를 검사할 때 build · dev · doctor · check가 함께 쓰는 검사 옵션.
15
- * 파일은 prepareContent가 만든 zip 내용(원본)이고, 모듈 묶기는 build가 하므로 module-src는 보지 않는다.
15
+ * 파일은 prepareContent가 모은 원본(번들 전)이고, 모듈 묶기는 build(Vite)가 하므로 module-src는 보지 않는다.
16
16
  * 프로젝트에만 있는 정보(예: 남은 옛 파일, 템플릿 목록)를 검사에 더할 때는 이 함수에만 더한다.
17
17
  * 그래야 `ecdk validate <프로젝트>`와 `ecdk build` 결과가 어긋나지 않는다.
18
18
  *
19
19
  * `ecdk dev`가 쓰는 상태(.ecdk/settings.json)는 보지 않는다: build · check 결과가 dev에서 무엇을
20
20
  * 저장했는지에 따라 달라지지 않게. templates: 이 CLI가 가진 템플릿 · 버전 (build.template-unknown).
21
21
  * legacyFiles: 남은 옛 파일 (project.legacy-file, elice.config.json · content.json · grading.json).
22
- * legacySdkCopy: 옛 lib/cdk.js 복사본 (sdk.lib-copy)
22
+ * legacySdkCopy: 옛 lib/cdk.js 복사본 (sdk.lib-copy). publicFiles: prepareContent의 public/ 파일 (ref.script-not-public)
23
23
  */
24
- export declare function projectCheckOptions(projectDir: string, config: ContentConfig, extra?: {
24
+ export declare function projectCheckOptions(projectDir: string, config: ContentConfig, extra: {
25
+ publicFiles: Set<string>;
25
26
  zipBytes?: number | undefined;
26
27
  }): Promise<CheckOptions>;
@@ -1,7 +1,7 @@
1
1
  import { access } from 'node:fs/promises';
2
2
  import { posix, join } from 'node:path';
3
3
  import { LEGACY_FILES } from './config.js';
4
- import { SDK_ZIP_PATH, readProjectSdk } from './sdk.js';
4
+ import { LEGACY_SDK_COPY } from './sdk.js';
5
5
  import { knownTemplates } from './templates.js';
6
6
 
7
7
  const exists = p => access(p).then(() => true, () => false);
@@ -18,32 +18,32 @@ async function findLegacyFiles(projectDir, config) {
18
18
  return found;
19
19
  }
20
20
  /**
21
- * 옛 lib/cdk.js 복사본 (ADR 0010 최종 결정): package.json에 @eliceio/cdk가 없는데 원본에 lib/cdk.js가 있으면 그 경로
22
- * (프로젝트 기준). build는 복사본을 그대로 넣고 sdk.lib-copy로 옮기는 법을 알린다
21
+ * 옛 SDK 복사본 (ADR 0010): 원본에 lib/cdk.js가 있으면 그 경로 (프로젝트 기준). SDK는 package.json 의존성을
22
+ * build가 번들로 묶으므로 복사본은 zip에 넣지 않고 sdk.lib-copy 오류로 옮기는 법을 알린다
23
23
  */
24
24
  async function findLegacySdkCopy(projectDir, config) {
25
- const path = posix.join(config.root.replace(/\\/g, '/'), SDK_ZIP_PATH);
26
- if (!(await exists(join(projectDir, path)))) return undefined;
27
- return (await readProjectSdk(projectDir)) === null ? path : undefined;
25
+ const path = posix.join(config.root.replace(/\\/g, '/'), LEGACY_SDK_COPY);
26
+ return (await exists(join(projectDir, path))) ? path : undefined;
28
27
  }
29
28
  /**
30
29
  * 프로젝트(ecdk 프로젝트 폴더)를 검사할 때 build · dev · doctor · check가 함께 쓰는 검사 옵션.
31
- * 파일은 prepareContent가 만든 zip 내용(원본)이고, 모듈 묶기는 build가 하므로 module-src는 보지 않는다.
30
+ * 파일은 prepareContent가 모은 원본(번들 전)이고, 모듈 묶기는 build(Vite)가 하므로 module-src는 보지 않는다.
32
31
  * 프로젝트에만 있는 정보(예: 남은 옛 파일, 템플릿 목록)를 검사에 더할 때는 이 함수에만 더한다.
33
32
  * 그래야 `ecdk validate <프로젝트>`와 `ecdk build` 결과가 어긋나지 않는다.
34
33
  *
35
34
  * `ecdk dev`가 쓰는 상태(.ecdk/settings.json)는 보지 않는다: build · check 결과가 dev에서 무엇을
36
35
  * 저장했는지에 따라 달라지지 않게. templates: 이 CLI가 가진 템플릿 · 버전 (build.template-unknown).
37
36
  * legacyFiles: 남은 옛 파일 (project.legacy-file, elice.config.json · content.json · grading.json).
38
- * legacySdkCopy: 옛 lib/cdk.js 복사본 (sdk.lib-copy)
37
+ * legacySdkCopy: 옛 lib/cdk.js 복사본 (sdk.lib-copy). publicFiles: prepareContent의 public/ 파일 (ref.script-not-public)
39
38
  */
40
- async function projectCheckOptions(projectDir, config, extra = {}) {
39
+ async function projectCheckOptions(projectDir, config, extra) {
41
40
  return {
42
41
  input: 'zip',
43
42
  bundlesModules: true,
44
43
  templates: knownTemplates(),
45
44
  legacyFiles: await findLegacyFiles(projectDir, config),
46
45
  legacySdkCopy: await findLegacySdkCopy(projectDir, config),
46
+ publicFiles: [...extra.publicFiles],
47
47
  ...(extra.zipBytes !== undefined ? {
48
48
  zipBytes: extra.zipBytes
49
49
  } : {})
@@ -5,38 +5,14 @@ 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
- }
15
- /** HTML의 모듈 스크립트(src)를 묶어 본문으로 넣는다. 바뀐 파일만 새로 만들어 돌려준다 */
16
- export declare function inlineModuleScripts(files: SourceFile[],
17
- /** esbuild 작업 폴더 (기본: 실행 폴더). 테스트에서 프로젝트 폴더 안 실행을 흉내 낼 때 */
18
- opts?: {
8
+ export interface InlineOptions {
9
+ /** esbuild 작업 폴더 (기본: 실행 폴더). 테스트에서 프로젝트 폴더 안 실행을 흉내 낼 때 */
19
10
  workingDir?: string | undefined;
20
11
  minify?: boolean | undefined;
21
- }): Promise<{
22
- files: SourceFile[];
23
- report: SandboxReport;
24
- bundled: BundledSources;
25
- }>;
26
- export interface DropReport {
27
- /** 묶어 넣었고 다른 데서 쓰지 않아 zip에서 뺀 원본 JS */
28
- dropped: string[];
29
- /** 빼지 않은 까닭 (모두 둔 경우만) */
30
- keptAll?: string | undefined;
12
+ sourcemap?: boolean | undefined;
31
13
  }
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<{
14
+ /** HTML의 모듈 스크립트(src)를 묶어 본문으로 넣는다. 바뀐 파일만 새로 만들어 돌려준다 */
15
+ export declare function inlineModuleScripts(files: SourceFile[], opts?: InlineOptions): Promise<{
40
16
  files: SourceFile[];
41
- report: DropReport;
17
+ report: SandboxReport;
42
18
  }>;
@@ -1,9 +1,8 @@
1
- import { build, transform } from 'esbuild';
1
+ import { build } from 'esbuild';
2
2
  import 'fflate';
3
3
  import { rules } from '../rules/spec.js';
4
4
  import { resolveRef } from '../rules/path.js';
5
5
  import { classifyRef } from '../rules/refs.js';
6
- import { TEXT_FILE } from '../rules/unused.js';
7
6
 
8
7
  /**
9
8
  * LXP는 자료를 콘텐츠마다 다른 출처의 sandbox iframe(`allow-scripts allow-same-origin`)에서 연다.
@@ -14,11 +13,11 @@ import { TEXT_FILE } from '../rules/unused.js';
14
13
  * (일반 `<script src>` · `<link rel="stylesheet">` · `<img>`는 CORS를 쓰지 않아 그대로 된다.)
15
14
  * 헤더가 `allow-same-origin`을 주면 같은 출처 요청이라 막히지 않지만, 어느 쪽이든 화면이 뜨도록 묶는다.
16
15
  *
17
- * build는 zip에 넣기 전에 HTML마다:
18
- * - `<script type="module" src="상대경로">`를 esbuild로 하나로 묶어 `<script type="module">` 본문으로 넣는다
19
- * (zip 안 파일만 묶음. `import.meta.url`은 원래 파일 주소로 바꿔 상대경로 계산이 그대로 맞게).
16
+ * build(Vite 플러그인 engines/vite)는 Vite가 만든 결과물에서 zip에 넣기 전에 HTML마다:
17
+ * - `<script type="module" src="상대경로">`(Vite가 나눈 chunk)를 esbuild로 하나로 묶어 `<script type="module">` 본문으로 넣는다
18
+ * (결과물 안 파일만 묶음. `import.meta.url`은 원래 파일 주소로 바꿔 상대경로 계산이 그대로 맞게).
20
19
  * - zip 안 JSON(metadata.json 제외, 작성자가 넣은 데이터 파일)을 페이지에 넣고 `fetch`가 그 주소를 받으면 넣어 둔 내용을 돌려준다.
21
- * build는 묶어 넣은 원본 JS 중 다른 데서 쓰지 않는 파일을 zip에서 뺀다 (`dropBundledSources`). JSON은 그대로 둔다.
20
+ * 묶어 넣은 chunk 파일은 플러그인이 결과물에서 뺀다.
22
21
  */
23
22
  const encoder = new TextEncoder();
24
23
  const decoder = new TextDecoder();
@@ -54,6 +53,12 @@ function zipFiles(byPath, page) {
54
53
  namespace: 'zip'
55
54
  };
56
55
  }
56
+ // Bare specifiers left here were not resolved by Vite (package not installed)
57
+ if (/^(?:@[\w.-]+\/)?[\w.-]+(?:\/|$)/.test(args.path) && !/^\.\.?\//.test(args.path)) return {
58
+ errors: [{
59
+ text: `패키지를 찾지 못했습니다: ${args.path}. package.json dependencies에 넣고 npm install을 실행해 주세요`
60
+ }]
61
+ };
57
62
  if (classifyRef(args.path) !== 'local') return {
58
63
  errors: [{
59
64
  text: `zip 안 파일만 묶을 수 있습니다: ${args.path}`
@@ -101,10 +106,12 @@ async function bundle(entry, page, byPath, opts) {
101
106
  } : {}),
102
107
  // minify를 켜면 실제로 실행되는 묶음 코드를 줄인다 (원본 JS는 이제 실행되지 않음)
103
108
  minify: opts.minify === true,
109
+ // sourcemap: 묶은 본문 끝에 inline map (chunk의 inline map을 이어 받아 원본 파일을 가리킴)
110
+ ...(opts.sourcemap ? {
111
+ sourcemap: 'inline'
112
+ } : {}),
104
113
  // 라이선스 주석(/*! · @license · @preserve)은 줄여도 묶음 끝에 모아 남긴다 (넣은 라이브러리의 고지 의무)
105
114
  legalComments: 'eof',
106
- // 어느 파일을 묶었는지 (dropBundledSources)
107
- metafile: true,
108
115
  bundle: true,
109
116
  format: 'esm',
110
117
  target: 'es2022',
@@ -114,40 +121,7 @@ async function bundle(entry, page, byPath, opts) {
114
121
  }).catch(e => {
115
122
  throw new Error(`${entry}를 묶지 못했습니다: ${e.errors?.[0]?.text ?? e.message ?? 'esbuild 오류'}. LXP에서는 모듈 스크립트를 따로 받을 수 없어 build가 HTML 안에 묶어 넣습니다.`);
116
123
  });
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);
124
+ return r.outputFiles[0]?.text ?? '';
151
125
  }
152
126
  /** zip 안 JSON을 넣어 두고, 그 주소를 fetch하면 넣어 둔 내용을 돌려준다 */
153
127
  function jsonPrelude(files, page) {
@@ -167,20 +141,25 @@ function jsonPrelude(files, page) {
167
141
  const json = escapeInline(JSON.stringify(data));
168
142
  return `<script>(()=>{const d=${json},b=document.baseURI,m=new Map(Object.entries(d).map(([k,v])=>[new URL(k,location.href).href,v])),f=window.fetch.bind(window);window.fetch=(i,o)=>{try{const u=new URL(typeof i==='string'||i instanceof URL?i:i.url,b).href.replace(/[?#].*$/,'');if(m.has(u)&&(!o||!o.method||o.method.toUpperCase()==='GET'))return Promise.resolve(new Response(JSON.stringify(m.get(u)),{headers:{'Content-Type':'application/json'}}))}catch{}return f(i,o)}})();</script>`;
169
143
  }
144
+ /**
145
+ * `crossorigin` 속성을 뗀다: Vite가 `<script type="module">` · `<link rel="stylesheet">`에 붙이는데,
146
+ * 콘텐츠 출처가 null인 LXP에서는 CORS 모드 요청이 되어 스타일시트까지 막힌다
147
+ */
148
+ function stripCrossorigin(html) {
149
+ return html.replace(/<(?:link|script)\b[^>]*>/gi, tag => tag.replace(/\s+crossorigin(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?(?=[\s/>])/gi, ''));
150
+ }
170
151
  /** HTML의 모듈 스크립트(src)를 묶어 본문으로 넣는다. 바뀐 파일만 새로 만들어 돌려준다 */
171
- async function inlineModuleScripts(files, /** esbuild 작업 폴더 (기본: 실행 폴더). 테스트에서 프로젝트 폴더 안 실행을 흉내 낼 때 */
172
- opts = {}) {
152
+ async function inlineModuleScripts(files, opts = {}) {
173
153
  const byPath = new Map(files.map(f => [f.path, f]));
174
154
  const pages = [];
175
155
  const out = [];
176
- const inputs = new Set();
177
- const pageTexts = new Map();
178
156
  for (const f of files) {
179
157
  if (!/\.html?$/i.test(f.path)) {
180
158
  out.push(f);
181
159
  continue;
182
160
  }
183
- const html = decoder.decode(f.data);
161
+ const original = decoder.decode(f.data);
162
+ const html = stripCrossorigin(original);
184
163
  // 주석 안의 스크립트(<!-- <script type="module" src="old.js"> -->)는 실행되지 않으므로 묶지 않는다
185
164
  const comments = [...html.matchAll(/<!--[\s\S]*?-->/g)].map(c => [c.index, c.index + c[0].length]);
186
165
  const inComment = at => comments.some(([from, to]) => at > from && at < to);
@@ -191,22 +170,19 @@ opts = {}) {
191
170
  return attr(a, 'type')?.toLowerCase() === 'module' && src && classifyRef(src) === 'local';
192
171
  });
193
172
  if (scripts.length === 0) {
194
- out.push(f);
173
+ out.push(html === original ? f : {
174
+ ...f,
175
+ data: encoder.encode(html)
176
+ });
195
177
  continue;
196
178
  }
197
179
  let next = '';
198
180
  let last = 0;
199
- let scan = '';
200
181
  for (const [i, m] of scripts.entries()) {
201
182
  const src = attr(m[1] ?? '', 'src') ?? '';
202
183
  const entry = resolveRef(f.path, src.replace(/[?#].*$/, ''));
203
184
  if (entry === null || !byPath.has(entry)) throw new Error(`${f.path}의 모듈 스크립트 파일이 없습니다: ${src}`);
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`;
185
+ const code = await bundle(entry, f.path, byPath, opts);
210
186
  next += html.slice(last, m.index);
211
187
  if (i === 0) next += jsonPrelude(files, f.path);
212
188
  // data-ecdk-bundle: 원본(ecdk-ignore 주석 포함)을 이미 검사했으니 zip 검사에서 이 본문은 다시 보지 않는다
@@ -214,9 +190,7 @@ opts = {}) {
214
190
  last = (m.index ?? 0) + m[0].length;
215
191
  }
216
192
  next += html.slice(last);
217
- scan += await withoutComments(f.path, html.slice(last));
218
193
  pages.push(f.path);
219
- pageTexts.set(f.path, scan);
220
194
  out.push({
221
195
  ...f,
222
196
  data: encoder.encode(next)
@@ -226,59 +200,8 @@ opts = {}) {
226
200
  files: out,
227
201
  report: {
228
202
  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
280
203
  }
281
204
  };
282
205
  }
283
206
 
284
- export { BUNDLE_ATTR, dropBundledSources, inlineModuleScripts };
207
+ export { BUNDLE_ATTR, inlineModuleScripts };
package/es/core/sdk.d.ts CHANGED
@@ -1,12 +1,12 @@
1
- import type { SourceFile } from './collect.js';
2
1
  /**
3
- * SDK(@eliceio/cdk)는 프로젝트 package.json 의존성이다 (ADR 0010 최종 결정). LXP sandbox에는 node_modules가 없으므로
4
- * build · dev가 설치된 SDK의 UMD 빌드를 zip의 lib/cdk.js로 넣는다 (화면 키트 lib/elice-content.js가 같은 폴더에서 부름).
5
- * 키트(lib/elice-content.js · .css · cdk-mock.js)는 ecdk create가 복사한 프로젝트 lib/ 그대로다.
2
+ * SDK(@eliceio/cdk)는 프로젝트 package.json 의존성이다 (ADR 0010). 화면 키트(lib/elice-content.js)가
3
+ * `import('@eliceio/cdk')`로 부르고, ecdk build(Vite)가 node_modules에서 찾아 화면 코드와 함께 번들로 묶는다.
4
+ * SDK 파일을 zip에 따로 넣거나 복사하지 않는다. metadata.json build.sdk는 설치된 패키지 버전
5
+ * (node_modules/@eliceio/cdk/package.json).
6
6
  */
7
7
  export declare const SDK_PACKAGE = "@eliceio/cdk";
8
- /** zip 안 SDK 파일 */
9
- export declare const SDK_ZIP_PATH = "lib/cdk.js";
8
+ /** 옛 방식의 SDK 복사본 (원본에 있으면 sdk.lib-copy 오류, zip에는 넣지 않는다) */
9
+ export declare const LEGACY_SDK_COPY = "lib/cdk.js";
10
10
  export declare const INSTALL_COMMAND = "npm install";
11
11
  export declare const UPDATE_COMMAND = "npm update @eliceio/cdk";
12
12
  export interface InstalledSdk {
@@ -22,18 +22,7 @@ export interface ProjectSdk {
22
22
  }
23
23
  /** package.json에 적은 SDK 범위 (dependencies → devDependencies). 없으면 undefined */
24
24
  export declare function declaredSdkRange(pkg: Record<string, unknown> | null): string | undefined;
25
- /**
26
- * 프로젝트가 SDK를 패키지로 쓰는지와 설치 상태. package.json에 @eliceio/cdk가 없으면 null
27
- * (옛 lib/cdk.js 복사본 프로젝트이거나 SDK를 쓰지 않는 자료: build는 원본 그대로)
28
- */
25
+ /** 프로젝트가 SDK를 패키지로 쓰는지와 설치 상태. package.json에 @eliceio/cdk가 없으면 null (SDK를 쓰지 않는 자료이거나 옛 프로젝트) */
29
26
  export declare function readProjectSdk(projectDir: string): Promise<ProjectSdk | null>;
30
27
  /** SDK가 설치되지 않았을 때 문구 */
31
28
  export declare function missingSdkMessage(): string;
32
- /**
33
- * zip lib/cdk.js 머리말. build.sdk는 이 머리말에서 읽는다 (core/manifest.ts).
34
- * SDK는 LXP 화면과 postMessage(설정 저장 결과 · 페이지 이동)로 이야기하므로 두 규칙을 이 파일에서만 끈다.
35
- * 두 규칙은 client 검사라 서버 업로드 검사와는 상관없다
36
- */
37
- export declare function sdkHeader(version: string): string;
38
- /** 설치된 SDK의 UMD 빌드에 머리말을 붙인 zip 파일 lib/cdk.js */
39
- export declare function sdkZipFile(sdk: InstalledSdk): Promise<SourceFile>;