kasaframe 0.0.0-stage → 0.1.1

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 (338) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +146 -0
  3. package/README.md +77 -2
  4. package/app/package.json +12 -0
  5. package/app/server/engine.ts +415 -0
  6. package/app/server/main.ts +205 -0
  7. package/app/web/env.d.ts +2 -0
  8. package/app/web/icons.ts +31 -0
  9. package/app/web/index.html +21 -0
  10. package/app/web/main.ts +1013 -0
  11. package/app/web/style.css +430 -0
  12. package/bin/hooks.mjs +51 -0
  13. package/bin/kf.mjs +14 -0
  14. package/docs/AGENTS.md +238 -0
  15. package/music/README.md +13 -0
  16. package/package.json +44 -4
  17. package/packages/adapters/package.json +36 -0
  18. package/packages/adapters/src/css.ts +11 -0
  19. package/packages/adapters/src/gsap.ts +26 -0
  20. package/packages/adapters/src/index.ts +9 -0
  21. package/packages/adapters/src/lottie.ts +22 -0
  22. package/packages/adapters/src/media.ts +59 -0
  23. package/packages/adapters/src/page.ts +229 -0
  24. package/packages/adapters/src/project.ts +214 -0
  25. package/packages/adapters/src/react.ts +36 -0
  26. package/packages/adapters/src/svelte.ts +22 -0
  27. package/packages/adapters/src/three.ts +18 -0
  28. package/packages/adapters/src/vue.ts +27 -0
  29. package/packages/check/package.json +19 -0
  30. package/packages/check/src/check.ts +273 -0
  31. package/packages/check/src/cli.ts +70 -0
  32. package/packages/check/src/image.ts +146 -0
  33. package/packages/check/src/index.ts +9 -0
  34. package/packages/check/src/ocr.swift +37 -0
  35. package/packages/check/src/probe.ts +328 -0
  36. package/packages/check/src/report.ts +44 -0
  37. package/packages/check/src/rules/assets.ts +42 -0
  38. package/packages/check/src/rules/beats.ts +212 -0
  39. package/packages/check/src/rules/camera.ts +217 -0
  40. package/packages/check/src/rules/captions.ts +49 -0
  41. package/packages/check/src/rules/flash.ts +235 -0
  42. package/packages/check/src/rules/frames.ts +135 -0
  43. package/packages/check/src/rules/layout.ts +257 -0
  44. package/packages/check/src/rules/page.ts +87 -0
  45. package/packages/check/src/rules/runs.ts +20 -0
  46. package/packages/check/src/rules/text.ts +326 -0
  47. package/packages/check/src/scan.ts +240 -0
  48. package/packages/check/src/serve.ts +67 -0
  49. package/packages/check/src/types.ts +80 -0
  50. package/packages/check/src/video.ts +137 -0
  51. package/packages/cli/package.json +29 -0
  52. package/packages/cli/src/blur.ts +68 -0
  53. package/packages/cli/src/browser.ts +203 -0
  54. package/packages/cli/src/command.ts +44 -0
  55. package/packages/cli/src/commands/app.ts +25 -0
  56. package/packages/cli/src/commands/beats.ts +36 -0
  57. package/packages/cli/src/commands/blender.ts +270 -0
  58. package/packages/cli/src/commands/check.ts +25 -0
  59. package/packages/cli/src/commands/doctor.ts +22 -0
  60. package/packages/cli/src/commands/gen.ts +173 -0
  61. package/packages/cli/src/commands/look.ts +39 -0
  62. package/packages/cli/src/commands/lyrics.ts +111 -0
  63. package/packages/cli/src/commands/make.ts +542 -0
  64. package/packages/cli/src/commands/new.ts +176 -0
  65. package/packages/cli/src/commands/preview.ts +43 -0
  66. package/packages/cli/src/commands/render.ts +216 -0
  67. package/packages/cli/src/commands/setup.ts +63 -0
  68. package/packages/cli/src/commands/sheet.ts +114 -0
  69. package/packages/cli/src/commands/skill.ts +43 -0
  70. package/packages/cli/src/commands/still.ts +40 -0
  71. package/packages/cli/src/commands/theme.ts +85 -0
  72. package/packages/cli/src/commands/transitions.ts +40 -0
  73. package/packages/cli/src/deps.ts +122 -0
  74. package/packages/cli/src/ffmpeg.ts +81 -0
  75. package/packages/cli/src/index.ts +8 -0
  76. package/packages/cli/src/kf.ts +53 -0
  77. package/packages/cli/src/lock.ts +72 -0
  78. package/packages/cli/src/out.ts +13 -0
  79. package/packages/cli/src/serve.ts +124 -0
  80. package/packages/clock/package.json +14 -0
  81. package/packages/clock/src/index.ts +25 -0
  82. package/packages/clock/src/install.ts +351 -0
  83. package/packages/clock/src/types.ts +45 -0
  84. package/packages/core/package.json +9 -0
  85. package/packages/core/src/beats.ts +283 -0
  86. package/packages/core/src/ease.ts +87 -0
  87. package/packages/core/src/frame.ts +99 -0
  88. package/packages/core/src/index.ts +27 -0
  89. package/packages/core/src/project.ts +146 -0
  90. package/packages/core/src/rand.ts +56 -0
  91. package/packages/core/src/spring.ts +52 -0
  92. package/packages/core/src/style.ts +100 -0
  93. package/packages/core/src/time.ts +88 -0
  94. package/packages/gen/PROVIDERS.md +55 -0
  95. package/packages/gen/package.json +9 -0
  96. package/packages/gen/src/generate.ts +204 -0
  97. package/packages/gen/src/image/og.ts +133 -0
  98. package/packages/gen/src/index.ts +18 -0
  99. package/packages/gen/src/keys.ts +60 -0
  100. package/packages/gen/src/media.ts +150 -0
  101. package/packages/gen/src/plan.ts +106 -0
  102. package/packages/gen/src/registry.ts +51 -0
  103. package/packages/gen/src/seam.ts +103 -0
  104. package/packages/gen/src/types.ts +86 -0
  105. package/packages/gen/src/video/fal.ts +140 -0
  106. package/packages/gen/src/video/h3.ts +107 -0
  107. package/packages/gen/src/video/http.ts +44 -0
  108. package/packages/gen/src/video/ltx.ts +60 -0
  109. package/packages/gen/src/video/minimax.ts +55 -0
  110. package/packages/gen/src/video/veo.ts +71 -0
  111. package/packages/jizura/package.json +16 -0
  112. package/packages/jizura/src/deny.ts +73 -0
  113. package/packages/jizura/src/index.ts +7 -0
  114. package/packages/jizura/src/install.ts +226 -0
  115. package/packages/jizura/src/layer.ts +282 -0
  116. package/packages/jizura/src/lyrics.ts +81 -0
  117. package/packages/jizura/src/pin.ts +5 -0
  118. package/packages/jizura/src/vite.ts +36 -0
  119. package/packages/motion/README.md +142 -0
  120. package/packages/motion/package.json +29 -0
  121. package/packages/motion/src/camera.ts +97 -0
  122. package/packages/motion/src/captions.ts +479 -0
  123. package/packages/motion/src/enter.ts +128 -0
  124. package/packages/motion/src/hangul.ts +129 -0
  125. package/packages/motion/src/impact.ts +100 -0
  126. package/packages/motion/src/index.ts +17 -0
  127. package/packages/motion/src/moves/brushWipe.ts +90 -0
  128. package/packages/motion/src/moves/cloneArray.ts +111 -0
  129. package/packages/motion/src/moves/curtains.ts +81 -0
  130. package/packages/motion/src/moves/echoStack.ts +70 -0
  131. package/packages/motion/src/moves/fit.ts +34 -0
  132. package/packages/motion/src/moves/flood.ts +61 -0
  133. package/packages/motion/src/moves/ghostStack.ts +79 -0
  134. package/packages/motion/src/moves/gridFloor.ts +100 -0
  135. package/packages/motion/src/moves/imageSwarm.ts +109 -0
  136. package/packages/motion/src/moves/index.ts +19 -0
  137. package/packages/motion/src/moves/irisBlades.ts +113 -0
  138. package/packages/motion/src/moves/karaokeLine.ts +94 -0
  139. package/packages/motion/src/moves/ledBoard.ts +94 -0
  140. package/packages/motion/src/moves/liquidTab.ts +72 -0
  141. package/packages/motion/src/moves/markerWrite.ts +63 -0
  142. package/packages/motion/src/moves/morphBox.ts +96 -0
  143. package/packages/motion/src/moves/neonSign.ts +77 -0
  144. package/packages/motion/src/moves/panelPop.ts +78 -0
  145. package/packages/motion/src/moves/paperTear.ts +75 -0
  146. package/packages/motion/src/moves/path.ts +64 -0
  147. package/packages/motion/src/moves/pathText.ts +107 -0
  148. package/packages/motion/src/moves/pointSphere.ts +109 -0
  149. package/packages/motion/src/moves/ransomLetters.ts +73 -0
  150. package/packages/motion/src/moves/shapeMorph.ts +143 -0
  151. package/packages/motion/src/moves/slamWords.ts +89 -0
  152. package/packages/motion/src/moves/sparkTrail.ts +114 -0
  153. package/packages/motion/src/moves/speedLines.ts +91 -0
  154. package/packages/motion/src/moves/splitFlap.ts +147 -0
  155. package/packages/motion/src/moves/stepWords.ts +117 -0
  156. package/packages/motion/src/moves/strikeOut.ts +98 -0
  157. package/packages/motion/src/moves/sunburst.ts +58 -0
  158. package/packages/motion/src/moves/tickerRows.ts +87 -0
  159. package/packages/motion/src/moves/tokenPicker.ts +114 -0
  160. package/packages/motion/src/moves/truchet.ts +85 -0
  161. package/packages/motion/src/moves/wordWall.ts +76 -0
  162. package/packages/motion/src/moves/worldRoll.ts +31 -0
  163. package/packages/motion/src/particles.ts +102 -0
  164. package/packages/motion/src/react/index.tsx +21 -0
  165. package/packages/motion/src/react/parts.tsx +431 -0
  166. package/packages/motion/src/react/time.tsx +97 -0
  167. package/packages/motion/src/text.ts +103 -0
  168. package/packages/motion/src/transition.ts +82 -0
  169. package/packages/motion/src/transition3d/cards.ts +65 -0
  170. package/packages/motion/src/transition3d/chain.ts +84 -0
  171. package/packages/motion/src/transition3d/dive.ts +181 -0
  172. package/packages/motion/src/transition3d/fold.ts +110 -0
  173. package/packages/motion/src/transition3d/gl.ts +219 -0
  174. package/packages/motion/src/transition3d/index.ts +228 -0
  175. package/packages/motion/src/transition3d/live.ts +70 -0
  176. package/packages/motion/src/transition3d/portal.ts +115 -0
  177. package/packages/motion/src/transition3d/react.tsx +29 -0
  178. package/packages/motion/src/transition3d/rig.ts +502 -0
  179. package/packages/motion/src/transition3d/shatter.ts +101 -0
  180. package/packages/motion/src/transition3d/whip.ts +65 -0
  181. package/packages/motion/src/transition3d/world.ts +683 -0
  182. package/packages/motion/src/transition3d/zoomOut.ts +114 -0
  183. package/packages/motion/src/transitions2d/catalog.ts +127 -0
  184. package/packages/motion/src/transitions2d/css.d.ts +2 -0
  185. package/packages/motion/src/transitions2d/cult-ui/LICENSE.md +9 -0
  186. package/packages/motion/src/transitions2d/cult-ui/RollingNumber.tsx +43 -0
  187. package/packages/motion/src/transitions2d/gl-transitions/LICENSE +25 -0
  188. package/packages/motion/src/transitions2d/gl-transitions/shaders.ts +1931 -0
  189. package/packages/motion/src/transitions2d/index.ts +2 -0
  190. package/packages/motion/src/transitions2d/kokonutui/LICENSE +21 -0
  191. package/packages/motion/src/transitions2d/kokonutui/MatrixText.css +16 -0
  192. package/packages/motion/src/transitions2d/kokonutui/MatrixText.tsx +94 -0
  193. package/packages/motion/src/transitions2d/magicui/HyperText.css +15 -0
  194. package/packages/motion/src/transitions2d/magicui/HyperText.tsx +115 -0
  195. package/packages/motion/src/transitions2d/magicui/LICENSE.md +21 -0
  196. package/packages/motion/src/transitions2d/magicui/MorphingText.css +25 -0
  197. package/packages/motion/src/transitions2d/magicui/MorphingText.tsx +130 -0
  198. package/packages/motion/src/transitions2d/magicui/WordRotate.tsx +42 -0
  199. package/packages/motion/src/transitions2d/react.ts +13 -0
  200. package/packages/motion/src/transitions2d/skiper-ui/ClipDiv.css +39 -0
  201. package/packages/motion/src/transitions2d/skiper-ui/ClipDiv.tsx +32 -0
  202. package/packages/motion/src/transitions2d/smoothui/LICENSE +21 -0
  203. package/packages/motion/src/transitions2d/smoothui/SharedAxisY.tsx +50 -0
  204. package/packages/motion/src/transitions2d/smoothui/TextMorph.tsx +90 -0
  205. package/packages/motion/src/transitions2d/smoothui/shaders.ts +223 -0
  206. package/packages/motion/src/transitions2d/unlumen/LICENSE +21 -0
  207. package/packages/motion/src/transitions2d/unlumen/ScrambleText.tsx +114 -0
  208. package/packages/motion/src/transitions2d/vengeance-ui/LICENSE +21 -0
  209. package/packages/motion/src/transitions2d/vengeance-ui/MorphText.css +69 -0
  210. package/packages/motion/src/transitions2d/vengeance-ui/MorphText.tsx +45 -0
  211. package/packages/motion/src/type.ts +131 -0
  212. package/packages/motion/src/ui.ts +172 -0
  213. package/packages/plan/package.json +15 -0
  214. package/packages/plan/src/brief.ts +254 -0
  215. package/packages/plan/src/captions.ts +75 -0
  216. package/packages/plan/src/detect.ts +93 -0
  217. package/packages/plan/src/index.ts +23 -0
  218. package/packages/plan/src/layout.ts +176 -0
  219. package/packages/plan/src/llm.ts +110 -0
  220. package/packages/plan/src/look.ts +220 -0
  221. package/packages/plan/src/plan.ts +125 -0
  222. package/packages/plan/src/request.ts +55 -0
  223. package/packages/plan/src/studio.ts +53 -0
  224. package/packages/plan/src/templates.ts +42 -0
  225. package/packages/plan/src/themes.ts +48 -0
  226. package/packages/plan/src/types.ts +106 -0
  227. package/packages/studio/package.json +12 -0
  228. package/packages/studio/src/index.ts +1 -0
  229. package/packages/studio/src/plugin.ts +236 -0
  230. package/packages/studio/src/ui/main.ts +503 -0
  231. package/packages/studio/src/ui/studio.css +165 -0
  232. package/packages/studio/src/ui/timeline.ts +317 -0
  233. package/packages/themes/kit/THEME-MAKE.md +68 -0
  234. package/packages/themes/kit/THEME.md +30 -0
  235. package/packages/themes/kit/briefs/og-intro-15s/brief.json +16 -0
  236. package/packages/themes/kit/briefs/og-intro-15s/facts.ts +29 -0
  237. package/packages/themes/kit/briefs/og-intro-15s/logo.svg +12 -0
  238. package/packages/themes/kit/effects.ts +5 -0
  239. package/packages/themes/kit/sample/index.html +11 -0
  240. package/packages/themes/kit/sample/main.ts +9 -0
  241. package/packages/themes/kit/sample/scenes/scene.ts +15 -0
  242. package/packages/themes/package.json +16 -0
  243. package/packages/themes/src/factory.ts +296 -0
  244. package/packages/themes/src/fx.ts +14 -0
  245. package/packages/themes/src/index.ts +105 -0
  246. package/packages/themes/src/stage3d.ts +177 -0
  247. package/packages/themes/src/types.ts +58 -0
  248. package/presets/kawaii-pastel.json +94 -0
  249. package/presets/neutral-dark.json +82 -0
  250. package/presets/og.json +98 -0
  251. package/skills/kasaframe/SKILL.md +32 -0
  252. package/templates/_shared/project/index.html +11 -0
  253. package/templates/_shared/project/lib/react.ts +22 -0
  254. package/templates/_shared/project/lib/stage.ts +272 -0
  255. package/templates/_shared/project/main.ts +9 -0
  256. package/templates/_shared/scenes/default.ts +18 -0
  257. package/templates/_shared/scenes/drop.ts +30 -0
  258. package/templates/_shared/scenes/end.ts +23 -0
  259. package/templates/_shared/scenes/hook.ts +16 -0
  260. package/templates/_shared/scenes/seam.ts +41 -0
  261. package/templates/_shared/scenes/step.ts +40 -0
  262. package/templates/ad/preview.png +0 -0
  263. package/templates/ad/template.json +132 -0
  264. package/templates/demo/preview.png +0 -0
  265. package/templates/demo/template.json +130 -0
  266. package/templates/explainer/preview.png +0 -0
  267. package/templates/explainer/template.json +142 -0
  268. package/templates/launch/preview.png +0 -0
  269. package/templates/launch/template.json +130 -0
  270. package/templates/mv/preview.png +0 -0
  271. package/templates/mv/scenes/default.ts +95 -0
  272. package/templates/mv/template.json +176 -0
  273. package/templates/promo/preview.png +0 -0
  274. package/templates/promo/template.json +144 -0
  275. package/templates/shorts/preview.png +0 -0
  276. package/templates/shorts/scenes/hook.ts +34 -0
  277. package/templates/shorts/template.json +127 -0
  278. package/templates/square/preview.png +0 -0
  279. package/templates/square/template.json +113 -0
  280. package/themes/debug-hud/THEME.md +39 -0
  281. package/themes/debug-hud/effects.ts +389 -0
  282. package/themes/debug-hud/sample/assets/og/logo.svg +12 -0
  283. package/themes/debug-hud/sample/beats.json +1 -0
  284. package/themes/debug-hud/sample/index.html +11 -0
  285. package/themes/debug-hud/sample/kf.json +59 -0
  286. package/themes/debug-hud/sample/lib/hudkit.ts +49 -0
  287. package/themes/debug-hud/sample/lib/og.ts +29 -0
  288. package/themes/debug-hud/sample/main.ts +9 -0
  289. package/themes/debug-hud/sample/scenes/end.ts +62 -0
  290. package/themes/debug-hud/sample/scenes/gather.ts +67 -0
  291. package/themes/debug-hud/sample/scenes/models.ts +70 -0
  292. package/themes/debug-hud/sample/scenes/price.ts +79 -0
  293. package/themes/debug-hud/sample/style.json +91 -0
  294. package/themes/debug-hud/still.png +0 -0
  295. package/themes/debug-hud/style.json +91 -0
  296. package/themes/debug-hud/theme.json +68 -0
  297. package/themes/og-measure/THEME.md +47 -0
  298. package/themes/og-measure/effects.ts +432 -0
  299. package/themes/og-measure/sample/assets/brand/og-logo-full.svg +12 -0
  300. package/themes/og-measure/sample/assets/brand/og-logo.svg +12 -0
  301. package/themes/og-measure/sample/assets/data/measure.json +353 -0
  302. package/themes/og-measure/sample/beats.json +1 -0
  303. package/themes/og-measure/sample/index.html +11 -0
  304. package/themes/og-measure/sample/kf.json +66 -0
  305. package/themes/og-measure/sample/lib/data.ts +62 -0
  306. package/themes/og-measure/sample/main.ts +9 -0
  307. package/themes/og-measure/sample/measure.ts +78 -0
  308. package/themes/og-measure/sample/scenes/end.ts +47 -0
  309. package/themes/og-measure/sample/scenes/gather.ts +51 -0
  310. package/themes/og-measure/sample/scenes/models.ts +34 -0
  311. package/themes/og-measure/sample/scenes/one.ts +39 -0
  312. package/themes/og-measure/sample/scenes/price.ts +56 -0
  313. package/themes/og-measure/sample/style.json +97 -0
  314. package/themes/og-measure/still.png +0 -0
  315. package/themes/og-measure/style.json +97 -0
  316. package/themes/og-measure/theme.json +79 -0
  317. package/themes/riso-zine/THEME.md +43 -0
  318. package/themes/riso-zine/effects.ts +321 -0
  319. package/themes/riso-zine/sample/assets/og/logo.svg +12 -0
  320. package/themes/riso-zine/sample/beats.json +1 -0
  321. package/themes/riso-zine/sample/index.html +11 -0
  322. package/themes/riso-zine/sample/kf.json +59 -0
  323. package/themes/riso-zine/sample/lib/og.ts +29 -0
  324. package/themes/riso-zine/sample/lib/shot.ts +86 -0
  325. package/themes/riso-zine/sample/lib/zine.ts +42 -0
  326. package/themes/riso-zine/sample/main.ts +9 -0
  327. package/themes/riso-zine/sample/scenes/end.ts +61 -0
  328. package/themes/riso-zine/sample/scenes/gather.ts +62 -0
  329. package/themes/riso-zine/sample/scenes/models.ts +52 -0
  330. package/themes/riso-zine/sample/scenes/price.ts +82 -0
  331. package/themes/riso-zine/sample/style.json +99 -0
  332. package/themes/riso-zine/still.png +0 -0
  333. package/themes/riso-zine/style.json +99 -0
  334. package/themes/riso-zine/theme.json +75 -0
  335. package/tools/beats/beats.py +372 -0
  336. package/tools/beats/requirements.txt +3 -0
  337. package/tools/lyrics/align.py +164 -0
  338. package/tools/lyrics/requirements.txt +9 -0
@@ -0,0 +1,296 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, extname, isAbsolute, join, resolve } from "node:path";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { checkTheme, themesDir } from "./index.ts";
7
+ import type { ThemeManifest, ThemeStatus } from "./types.ts";
8
+
9
+ // 테마 공장 — 참고 자료에서 테마 팩 뼈대와 지시서(THEME-MAKE.md)를 짓고, 계약을 검사하고, 견본을 review 로 올린다.
10
+ // 테마를 만드는 건 지시서를 받은 모델 세션이다. 공장은 그 세션이 매번 같은 틀·같은 브리프·같은 검사로 끝나게 하는 몫.
11
+
12
+ export const kitDir = fileURLToPath(new URL("../kit/", import.meta.url));
13
+ const repoRoot = resolve(themesDir, "..");
14
+ const kfBin = join(repoRoot, "packages/cli/src/kf.ts");
15
+
16
+ const IMAGE = new Set([".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg", ".avif"]);
17
+ const VIDEO = new Set([".mp4", ".mov", ".webm", ".mkv", ".m4v"]);
18
+ const KOREAN = /Pretendard|Noto Sans KR|Apple SD Gothic Neo|Jua|Galmuri|DungGeunMo|NeoDunggeunmo/;
19
+ // 장면 뼈대에 남겨 둔 표시 — 이게 남아 있으면 장면을 아직 안 썼다
20
+ const SKELETON = "THEME-MAKE.md 5단계에서 이 파일을 통째로 다시 쓴다";
21
+
22
+ export interface BriefKit {
23
+ id: string;
24
+ doc: string;
25
+ label: string;
26
+ share: string;
27
+ music: string;
28
+ from: number;
29
+ to: number;
30
+ assets: Record<string, string>;
31
+ scenes: { id: string; role: string; until: string; idea: string }[];
32
+ }
33
+
34
+ export const briefs = (): string[] => readdirSync(join(kitDir, "briefs")).filter((d) => existsSync(join(kitDir, "briefs", d, "brief.json")));
35
+
36
+ export function loadBrief(id: string): BriefKit {
37
+ const file = join(kitDir, "briefs", id, "brief.json");
38
+ if (!existsSync(file)) throw new Error(`브리프 "${id}" 가 없다. 있는 브리프: ${briefs().join(" ")}`);
39
+ return JSON.parse(readFileSync(file, "utf8")) as BriefKit;
40
+ }
41
+
42
+ const tilde = (p: string) => (p.startsWith("~/") ? join(homedir(), p.slice(2)) : p);
43
+ const fill = (s: string, v: Record<string, string>) => s.replace(/\{\{(\w+)\}\}/g, (_, k: string) => v[k] ?? `{{${k}}}`);
44
+ const writeJson = (file: string, v: unknown) => writeFileSync(file, `${JSON.stringify(v, null, 2)}\n`);
45
+ const readJson = <T>(file: string): T => JSON.parse(readFileSync(file, "utf8")) as T;
46
+
47
+ function run(cmd: string, args: string[], quiet = false): number {
48
+ const r = spawnSync(cmd, args, { cwd: repoRoot, stdio: quiet ? ["ignore", "ignore", "inherit"] : "inherit" });
49
+ return r.status ?? 1;
50
+ }
51
+ const kf = (args: string[], quiet = false) => run(process.execPath, [kfBin, ...args], quiet);
52
+
53
+ const THREE_NOTE = `
54
+ ## 입체(three.js) 테마 — 평면이 아니라 깊이·원근·빛으로 선다
55
+
56
+ - 바탕은 \`@kasaframe/themes/stage3d\`: \`stage3d(root, { ctx, camera: "perspective" | "ortho", fog, env, shot(t, camera) })\` 가 무대(씬·카메라·\`add(rig)\`·\`paint(t)\`)를 주고, 렌더러는 페이지에 하나를 돌려 쓴다(크롬은 한 페이지에 WebGL 문맥을 16 개쯤만 살린다). \`textPlane({ text, family, color, height })\` 은 한글이 서는 글꼴로 그린 글자판, \`roomEnvironment(renderer)\` 는 금속·유리가 비칠 환경광, \`roundRectShape\` 는 OG 로고의 둥근 사각 칸 꼴. \`THREE\` 도 거기서 다시 내보낸다.
57
+ - 테마 효과 중 3D 부품은 kind \`rig\` = \`(stage, opts) => (t) => void\` — 무대에 물체를 얹고 t 로 움직인다. 카메라·빛·재질 값을 **전부 t 로** 정한다 — \`THREE.Clock\`·\`requestAnimationFrame\`·누적 회전 금지.
58
+ - 카메라 경로는 \`flyPath\`(@kasaframe/motion) 나 닫힌 식. 마디마다 컷(카메라를 새 자리로 끊어 옮기거나 다른 세트로), 박마다 큰 사건(물체가 날아들고·켜지고·갈라지고).
59
+ - 화면 글은 3D 공간 안의 글자판으로. 검사의 화면 글 훑기는 WebGL 안 글을 못 읽으니, 끝 카드처럼 꼭 읽혀야 하는 글은 DOM 으로 겹쳐 둬도 된다.
60
+ - 헤드리스 크롬은 GPU 없이 SwiftShader 로 그린다 — 한 프레임 50ms 안을 넘지 않게 정점 수·그림자 맵·후처리를 아낀다. 큰 원통·구는 분할 수를 낮게, 그림자는 하나. 투과 유리(\`MeshPhysicalMaterial.transmission\`)는 그리기를 한 번 더 하니 한 화면에 몇 개만.
61
+ - 컷은 씬 안 오브젝트의 \`visible\` 로(CSS 가 아니다).
62
+ `;
63
+
64
+ export interface ScaffoldOpts {
65
+ refs: string[];
66
+ name?: string;
67
+ brief?: string;
68
+ like?: string;
69
+ kind?: "flat" | "3d";
70
+ force?: boolean;
71
+ }
72
+
73
+ /** themes/<id>/ 를 짓는다 — 계약 파일 뼈대 · refs/ · 브리프대로 자른 곡과 박 · 장면 넷 뼈대 · THEME-MAKE.md */
74
+ export function scaffold(id: string, o: ScaffoldOpts): { dir: string; make: string; refs: string[]; urls: string[] } {
75
+ if (!/^[a-z][a-z0-9-]{1,40}$/.test(id)) throw new Error(`테마 id 는 소문자·숫자·하이픈(첫 글자는 영문): "${id}"`);
76
+ const dir = join(themesDir, id);
77
+ if (existsSync(dir) && readdirSync(dir).length && !o.force) throw new Error(`${dir} 가 이미 있다 — 덮어쓰려면 --force`);
78
+ const brief = loadBrief(o.brief ?? "og-intro-15s");
79
+ const like = o.like && existsSync(join(themesDir, o.like, "style.json")) ? o.like : null;
80
+ mkdirSync(join(dir, "refs", "frames"), { recursive: true });
81
+
82
+ // 참고 자료 — 파일·폴더는 복사, 영상은 장면 여섯 장을 뽑고, 주소는 목록으로
83
+ const files: string[] = [];
84
+ const urls: string[] = [];
85
+ const take = (src: string) => {
86
+ const ext = extname(src).toLowerCase();
87
+ if (!IMAGE.has(ext) && !VIDEO.has(ext)) return;
88
+ const name = basename(src).replace(/[^\w.가-힣-]/g, "_");
89
+ copyFileSync(src, join(dir, "refs", name));
90
+ files.push(`refs/${name}`);
91
+ if (VIDEO.has(ext)) {
92
+ const probe = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", src], { encoding: "utf8" });
93
+ const dur = Number(probe.stdout) || 6;
94
+ for (let k = 1; k <= 6; k++) {
95
+ const out = join(dir, "refs", "frames", `${name.replace(/\.\w+$/, "")}-${k}.jpg`);
96
+ spawnSync("ffmpeg", ["-v", "error", "-y", "-ss", String((dur * k) / 7), "-i", src, "-frames:v", "1", "-vf", "scale=960:-2", out]);
97
+ if (existsSync(out)) files.push(`refs/frames/${basename(out)}`);
98
+ }
99
+ }
100
+ };
101
+ for (const r of o.refs) {
102
+ if (/^https?:\/\//.test(r)) {
103
+ urls.push(r);
104
+ continue;
105
+ }
106
+ const p = resolve(tilde(r));
107
+ if (!existsSync(p)) throw new Error(`참고 자료가 없다: ${r}`);
108
+ if (statSync(p).isDirectory()) for (const f of readdirSync(p)) take(join(p, f));
109
+ else take(p);
110
+ }
111
+ writeJson(join(dir, "refs", "refs.json"), { files, urls });
112
+
113
+ const name = o.name ?? id;
114
+ writeJson(join(dir, "theme.json"), {
115
+ id,
116
+ name,
117
+ metaphor: "",
118
+ status: "draft",
119
+ approvedAt: null,
120
+ purposes: [],
121
+ aspect: ["16:9"],
122
+ effects: [],
123
+ } satisfies ThemeManifest);
124
+ const base = like ? readJson<Record<string, unknown>>(join(themesDir, like, "style.json")) : readJson<Record<string, unknown>>(join(repoRoot, "presets", "neutral-dark.json"));
125
+ writeJson(join(dir, "style.json"), { ...base, name: id, label: name, notes: [`뼈대: ${like ? `테마 ${like}` : "presets/neutral-dark"} 에서 — 3단계에서 통째로 바꾼다`] });
126
+ const vars = { id, name, brief: `${brief.label}(${brief.doc}), 곡 ${basename(brief.music)} ${brief.from}–${brief.to}초`, share: brief.share };
127
+ writeFileSync(join(dir, "THEME.md"), fill(readFileSync(join(kitDir, "THEME.md"), "utf8"), vars));
128
+ writeFileSync(join(dir, "effects.ts"), fill(readFileSync(join(kitDir, "effects.ts"), "utf8"), vars));
129
+
130
+ // 견본 뼈대 — 곡을 브리프 구간으로 자르고 박을 재서 장면 경계를 마디·드롭에 붙인다
131
+ const sample = join(dir, "sample");
132
+ mkdirSync(join(sample, "scenes"), { recursive: true });
133
+ mkdirSync(join(sample, "lib"), { recursive: true });
134
+ mkdirSync(join(sample, "assets", "music"), { recursive: true });
135
+ // 브리프의 곡은 곡 모음(music/·KF_MUSIC_DIR) 안 이름 — 절대 경로·~/ 도 받는다
136
+ const song = isAbsolute(tilde(brief.music)) ? tilde(brief.music) : join(process.env.KF_MUSIC_DIR ?? join(repoRoot, "music"), brief.music);
137
+ const dur = +(brief.to - brief.from).toFixed(4);
138
+ const cut = `${basename(song).replace(/\.\w+$/, "")}-${String(Math.round(brief.from * 100)).padStart(4, "0")}.mp3`;
139
+ spawnSync("ffmpeg", ["-v", "error", "-y", "-ss", String(brief.from), "-t", String(dur), "-i", song, "-af", `afade=t=in:d=0.03,afade=t=out:st=${dur - 0.3}:d=0.3`, "-c:a", "libmp3lame", "-b:a", "192k", join(sample, "assets", "music", cut)]);
140
+ if (kf(["beats", song, "--from", String(brief.from), "--duration", String(dur), "--out", join(sample, "beats.json")], true) !== 0) throw new Error("kf beats 가 실패했다");
141
+ const beats = readJson<{ bars: number[]; drops: number[]; source: string; from: number }>(join(sample, "beats.json"));
142
+ writeJson(join(sample, "beats.json"), { ...beats, source: `assets/music/${cut}`, from: 0 });
143
+ const edge = (until: string): number => {
144
+ if (until === "end") return dur;
145
+ const [kind, v] = until.split(":");
146
+ if (kind === "drop") return beats.drops[Number(v)] ?? dur / 2;
147
+ const want = Number(v);
148
+ return beats.bars.reduce((a, b) => (Math.abs(b - want) < Math.abs(a - want) ? b : a), beats.bars[0] ?? want);
149
+ };
150
+ let from = 0;
151
+ const scenes = brief.scenes.map((s) => {
152
+ const to = +edge(s.until).toFixed(4);
153
+ const e = { id: s.id, from, dur: +(to - from).toFixed(4), file: `scenes/${s.id}.ts`, role: s.role, idea: s.idea };
154
+ from = to;
155
+ return e;
156
+ });
157
+ writeJson(join(sample, "kf.json"), {
158
+ template: "promo",
159
+ title: `${id} · ${brief.label}`,
160
+ theme: id,
161
+ fps: 60,
162
+ width: 1920,
163
+ height: 1080,
164
+ duration: dur,
165
+ mode: "seek",
166
+ style: "style.json",
167
+ music: `assets/music/${cut}`,
168
+ beats: "beats.json",
169
+ captions: "none",
170
+ safeArea: { top: 60, bottom: 60, left: 80, right: 80 },
171
+ text: { policy: "terms-only", maxOnScreen: 0, minPx: 0 },
172
+ scenes,
173
+ });
174
+ copyFileSync(join(dir, "style.json"), join(sample, "style.json"));
175
+ writeFileSync(join(sample, "index.html"), fill(readFileSync(join(kitDir, "sample", "index.html"), "utf8"), vars));
176
+ copyFileSync(join(kitDir, "sample", "main.ts"), join(sample, "main.ts"));
177
+ const sceneKit = readFileSync(join(kitDir, "sample", "scenes", "scene.ts"), "utf8");
178
+ for (const s of scenes) writeFileSync(join(sample, s.file), fill(sceneKit, { ...vars, scene: s.id, idea: s.idea }));
179
+ copyFileSync(join(kitDir, "briefs", brief.id, "facts.ts"), join(sample, "lib", "facts.ts"));
180
+ for (const [to, src] of Object.entries(brief.assets)) {
181
+ mkdirSync(join(sample, "assets", to, ".."), { recursive: true });
182
+ copyFileSync(join(kitDir, "briefs", brief.id, src), join(sample, "assets", to));
183
+ }
184
+
185
+ const make = join(dir, "THEME-MAKE.md");
186
+ const refsLine = [...files.map((f) => `\`${f}\``), ...urls.map((u) => `<${u}>`)].join(" · ") || "(없음 — 브리프와 approved 테마만 보고 정한다)";
187
+ writeFileSync(
188
+ make,
189
+ fill(readFileSync(join(kitDir, "THEME-MAKE.md"), "utf8"), {
190
+ ...vars,
191
+ refs: refsLine,
192
+ like: like ?? "(없음)",
193
+ briefDoc: brief.doc,
194
+ kindNote: o.kind === "3d" ? THREE_NOTE : "",
195
+ }),
196
+ );
197
+ return { dir, make, refs: files, urls };
198
+ }
199
+
200
+ /** 계약 + 지시서가 남긴 빈칸까지 — 견본 페이지 검사(kf check)는 따로 */
201
+ export async function staticCheck(id: string): Promise<string[]> {
202
+ const dir = join(themesDir, id);
203
+ if (!existsSync(join(dir, "theme.json"))) return [`themes/${id} 가 없다`];
204
+ const bad = checkTheme(dir);
205
+ const m = readJson<ThemeManifest>(join(dir, "theme.json"));
206
+ const guide = existsSync(join(dir, "THEME.md")) ? readFileSync(join(dir, "THEME.md"), "utf8") : "";
207
+ if (/TODO/.test(guide)) bad.push("THEME.md 에 TODO 가 남았다");
208
+ // 머리말 꼴은 공장이 지은 테마(지시서가 있는 것)에만 — 공장 전에 손으로 만든 테마는 꼴이 다를 수 있다
209
+ if (existsSync(join(dir, "THEME-MAKE.md"))) for (const h of ["**비유:", "## 맞는 내용·용도", "## 금지", "## 움직임", "## 효과"]) if (!guide.includes(h)) bad.push(`THEME.md 에 「${h.replace(/\*/g, "")}」 가 없다`);
210
+ if (existsSync(join(dir, "refs")) && !existsSync(join(dir, "refs", "NOTES.md"))) bad.push("refs/NOTES.md 가 없다 — 참고 자료에서 본 것을 적는다(2단계)");
211
+ try {
212
+ const style = readJson<{ fonts?: Record<string, string> }>(join(dir, "style.json"));
213
+ for (const k of ["sans", "display", "mono"]) if (!KOREAN.test(style.fonts?.[k] ?? "")) bad.push(`style.json fonts.${k} 가 한글이 서는 글꼴로 끝나지 않는다`);
214
+ } catch {
215
+ bad.push("style.json 을 못 읽는다");
216
+ }
217
+ if (existsSync(join(dir, "effects.ts"))) {
218
+ try {
219
+ const mod = (await import(pathToFileURL(join(dir, "effects.ts")).href)) as Record<string, unknown>;
220
+ const exported = Object.keys(mod).filter((k) => typeof mod[k] === "function").sort();
221
+ const listed = (m.effects ?? []).map((e) => e.name).sort();
222
+ const missing = listed.filter((n) => !exported.includes(n));
223
+ const extra = exported.filter((n) => !listed.includes(n));
224
+ if (missing.length) bad.push(`theme.json 에 있는데 effects.ts 에 없는 효과: ${missing.join(" ")}`);
225
+ if (extra.length) bad.push(`effects.ts 가 내보내는데 theme.json 에 없는 효과: ${extra.join(" ")}`);
226
+ } catch (e) {
227
+ bad.push(`effects.ts 를 불러오지 못했다 — ${(e as Error).message.split("\n")[0]}`);
228
+ }
229
+ }
230
+ const sample = join(dir, "sample");
231
+ if (existsSync(join(sample, "scenes"))) {
232
+ for (const f of readdirSync(join(sample, "scenes"))) if (readFileSync(join(sample, "scenes", f), "utf8").includes(SKELETON)) bad.push(`sample/scenes/${f} 가 아직 뼈대다`);
233
+ }
234
+ return bad;
235
+ }
236
+
237
+ export function setStatus(id: string, status: ThemeStatus): ThemeManifest {
238
+ const file = join(themesDir, id, "theme.json");
239
+ const m = readJson<ThemeManifest>(file);
240
+ const d = new Date();
241
+ const today = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
242
+ const next = { ...m, status, approvedAt: status === "approved" ? today : null };
243
+ writeJson(file, next);
244
+ return next;
245
+ }
246
+
247
+ /** 견본을 굽고 검사하고 장면 모음·대표 장면·작은 sample.mp4 를 만들어 공유 폴더에 넣고 status 를 review 로 */
248
+ export function review(id: string, o: { brief?: string; tabs?: number; share?: boolean } = {}): { ok: boolean; share: string | null; notes: string[] } {
249
+ const dir = join(themesDir, id);
250
+ const sample = join(dir, "sample");
251
+ const out = join(sample, "out");
252
+ const notes: string[] = [];
253
+ const brief = loadBrief(o.brief ?? "og-intro-15s");
254
+ const tabs = String(o.tabs ?? 2);
255
+ if (kf(["render", sample, "--tabs", tabs]) !== 0) return { ok: false, share: null, notes: ["kf render 가 실패했다"] };
256
+ if (kf(["check", join(out, "render.mp4")]) !== 0) return { ok: false, share: null, notes: ["mp4 검사가 실패했다 — 보고서를 보고 고친다"] };
257
+ kf(["sheet", sample, "--count", "16", "--cols", "4", "--width", "640", "--out", join(out, "scenes.png")], true);
258
+ const beats = readJson<{ drops: number[] }>(join(sample, "beats.json"));
259
+ const stillAt = Math.min((beats.drops[0] ?? 5) + 0.7, brief.to - brief.from - 0.5);
260
+ kf(["still", sample, "--t", stillAt.toFixed(2)], true);
261
+ const still = readdirSync(out).find((f) => f.startsWith("still-") && f.endsWith(".png"));
262
+ if (still) {
263
+ // 종이결·잡음이 많은 테마는 대표 장면이 몇 MB — 레포에는 1280 폭으로
264
+ spawnSync("ffmpeg", ["-v", "error", "-y", "-i", join(out, still), "-vf", "scale='min(1920,iw)':-2", join(dir, "still.png")]);
265
+ if (statSync(join(dir, "still.png")).size > 2_000_000) spawnSync("ffmpeg", ["-v", "error", "-y", "-i", join(out, still), "-vf", "scale=1280:-2", join(dir, "still.png")]);
266
+ }
267
+ const enc = (args: string[], to: string) =>
268
+ spawnSync("ffmpeg", ["-v", "error", "-y", "-i", join(out, "render.mp4"), ...args, "-pix_fmt", "yuv420p", "-color_range", "tv", "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-c:a", "copy", "-movflags", "+faststart", to]);
269
+ const shareMp4 = join(out, "share.mp4");
270
+ enc(["-c:v", "libx264", "-preset", "slow", "-crf", "24"], shareMp4);
271
+ enc(["-c:v", "libx264", "-preset", "slow", "-crf", "26"], join(dir, "sample.mp4"));
272
+ if (statSync(join(dir, "sample.mp4")).size > 8_000_000) enc(["-vf", "scale=1280:720:flags=lanczos", "-c:v", "libx264", "-preset", "slow", "-crf", "30"], join(dir, "sample.mp4"));
273
+ notes.push(`sample.mp4 ${(statSync(join(dir, "sample.mp4")).size / 1e6).toFixed(1)}MB`);
274
+ let share: string | null = null;
275
+ if (o.share !== false) {
276
+ const r = spawnSync("kasaterm-cli", ["share", "new", `kasaframe-테마-${id}`], { encoding: "utf8" });
277
+ share = r.status === 0 ? (r.stdout.trim().split("\n").pop() ?? null) : null;
278
+ if (!share || !existsSync(share)) {
279
+ share = join(homedir(), "Desktop", `kasaframe-테마-${id}`);
280
+ mkdirSync(share, { recursive: true });
281
+ notes.push("kasaterm-cli share 가 없어 바탕화면에 폴더를 만들었다");
282
+ }
283
+ copyFileSync(shareMp4, join(share, `${id}-${brief.share}.mp4`));
284
+ if (existsSync(join(out, "scenes.png"))) copyFileSync(join(out, "scenes.png"), join(share, `장면모음-${brief.share}.png`));
285
+ if (still) copyFileSync(join(out, still), join(share, `대표장면-${brief.share}.png`));
286
+ copyFileSync(join(dir, "THEME.md"), join(share, "THEME.md"));
287
+ }
288
+ setStatus(id, "review");
289
+ return { ok: true, share, notes };
290
+ }
291
+
292
+ /** 지시서 원문 — 새 세션에 그대로 넘기는 첫 메시지 */
293
+ export function sessionPrompt(id: string): string {
294
+ return `themes/${id}/THEME-MAKE.md 를 처음부터 끝까지 읽고 그대로 따라 테마 ${id} 를 만든다. 끝나면 npx kf theme review ${id} 까지.`;
295
+ }
296
+
@@ -0,0 +1,14 @@
1
+ /// <reference types="vite/client" />
2
+ // 페이지(Vite) 쪽. 테마 폴더를 늘려도 이 파일은 그대로 — themes/*/effects.ts 를 모아 id 로 꺼낸다.
3
+ const mods = import.meta.glob("../../../themes/*/effects.ts", { eager: true }) as Record<string, Record<string, unknown>>;
4
+
5
+ const byId = new Map(Object.entries(mods).map(([path, mod]) => [path.split("/").at(-2)!, mod]));
6
+
7
+ export const themeIds = (): string[] => [...byId.keys()].sort();
8
+
9
+ /** 장면에서: `const { plateStamp, misregister } = fx("riso-zine")` */
10
+ export function fx<T = Record<string, (...args: any[]) => any>>(id: string): T {
11
+ const mod = byId.get(id);
12
+ if (!mod) throw new Error(`테마 효과 "${id}" 가 없다. 있는 테마: ${themeIds().join(" ") || "(없음)"}`);
13
+ return mod as T;
14
+ }
@@ -0,0 +1,105 @@
1
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import type { KfStyle } from "@kasaframe/core";
5
+ import { THEME_STATUSES, type Theme, type ThemeCard, type ThemeManifest, type ThemeStatus } from "./types.ts";
6
+
7
+ export type * from "./types.ts";
8
+ export { THEME_STATUSES } from "./types.ts";
9
+
10
+ export const themesDir = fileURLToPath(new URL("../../../themes/", import.meta.url));
11
+
12
+ export interface ThemeFilter {
13
+ /** 하나나 여럿. 안 주면 전부 */
14
+ status?: ThemeStatus | ThemeStatus[];
15
+ purpose?: string;
16
+ aspect?: string;
17
+ }
18
+
19
+ const readJson = <T>(path: string): T => JSON.parse(readFileSync(path, "utf8")) as T;
20
+ const fileOrNull = (path: string): string | null => (existsSync(path) ? path : null);
21
+
22
+ /** 틀이 깨진 곳을 사람이 읽을 줄로. 빈 배열이면 통과 */
23
+ export function checkTheme(dir: string): string[] {
24
+ const bad: string[] = [];
25
+ for (const f of ["theme.json", "style.json", "THEME.md", "effects.ts"]) if (!existsSync(join(dir, f))) bad.push(`${f} 가 없다`);
26
+ if (bad.length) return bad;
27
+ const m = readJson<Partial<ThemeManifest>>(join(dir, "theme.json"));
28
+ const id = dir.replace(/\/+$/, "").split("/").pop();
29
+ if (m.id !== id) bad.push(`theme.json id "${m.id}" 가 폴더 이름 "${id}" 와 다르다`);
30
+ for (const k of ["name", "metaphor"] as const) if (typeof m[k] !== "string" || !m[k]) bad.push(`theme.json ${k} 가 비었다`);
31
+ if (!THEME_STATUSES.includes(m.status as ThemeStatus)) bad.push(`theme.json status 는 ${THEME_STATUSES.join("|")} 중 하나`);
32
+ if (m.status === "approved" && !m.approvedAt) bad.push("approved 인데 approvedAt 이 없다");
33
+ if (!Array.isArray(m.purposes) || !m.purposes.length) bad.push("theme.json purposes 가 비었다");
34
+ if (!Array.isArray(m.aspect) || !m.aspect.length) bad.push("theme.json aspect 가 비었다");
35
+ const n = m.effects?.length ?? 0;
36
+ if (n < 5 || n > 10) bad.push(`효과는 5–10개 — 지금 ${n}개`);
37
+ for (const e of m.effects ?? []) if (!["value", "layer", "rig"].includes(e.kind)) bad.push(`효과 ${e.name} kind 는 value|layer|rig`);
38
+ const s = readJson<Partial<KfStyle>>(join(dir, "style.json"));
39
+ if (s.name !== m.id) bad.push(`style.json name 이 테마 id 와 다르다`);
40
+ if (!s.fonts?.sans || !s.colors?.bg || !s.motion) bad.push("style.json 이 KfStyle 꼴이 아니다(fonts·colors·motion)");
41
+ if (m.status !== "draft") {
42
+ if (!existsSync(join(dir, m.still ?? "still.png"))) bad.push(`${m.status} 인데 대표 장면 ${m.still ?? "still.png"} 가 없다`);
43
+ if (!existsSync(join(dir, "sample", "kf.json"))) bad.push(`${m.status} 인데 견본 프로젝트 sample/ 이 없다`);
44
+ }
45
+ return bad;
46
+ }
47
+
48
+ export function loadTheme(id: string): Theme {
49
+ const dir = join(themesDir, id);
50
+ const bad = checkTheme(dir);
51
+ if (bad.length) throw new Error(`테마 ${id}: ${bad.join(" · ")}`);
52
+ const m = readJson<ThemeManifest>(join(dir, "theme.json"));
53
+ return {
54
+ ...m,
55
+ dir,
56
+ style: readJson<KfStyle>(join(dir, "style.json")),
57
+ guide: readFileSync(join(dir, "THEME.md"), "utf8"),
58
+ files: {
59
+ still: fileOrNull(join(dir, m.still ?? "still.png")),
60
+ sample: fileOrNull(join(dir, m.sample ?? "sample.mp4")),
61
+ sampleProject: fileOrNull(join(dir, "sample")),
62
+ effects: join(dir, "effects.ts"),
63
+ },
64
+ };
65
+ }
66
+
67
+ /** 틀이 깨진 테마는 건너뛴다 — 하나가 깨져도 목록은 선다 */
68
+ export function listThemes(filter: ThemeFilter = {}): Theme[] {
69
+ if (!existsSync(themesDir)) return [];
70
+ const want = filter.status === undefined ? null : [filter.status].flat();
71
+ const out: Theme[] = [];
72
+ for (const id of readdirSync(themesDir).sort()) {
73
+ if (!existsSync(join(themesDir, id, "theme.json")) || checkTheme(join(themesDir, id)).length) continue;
74
+ const t = loadTheme(id);
75
+ if (want && !want.includes(t.status)) continue;
76
+ if (filter.purpose && !t.purposes.includes(filter.purpose)) continue;
77
+ if (filter.aspect && !t.aspect.includes(filter.aspect)) continue;
78
+ out.push(t);
79
+ }
80
+ return out;
81
+ }
82
+
83
+ export function themeCards(filter: ThemeFilter = {}): ThemeCard[] {
84
+ return listThemes(filter).map((t) => ({
85
+ id: t.id,
86
+ name: t.name,
87
+ metaphor: t.metaphor,
88
+ status: t.status,
89
+ approvedAt: t.approvedAt,
90
+ still: t.files.still,
91
+ sample: t.files.sample,
92
+ purposes: t.purposes,
93
+ aspect: t.aspect,
94
+ }));
95
+ }
96
+
97
+ /**
98
+ * 프로젝트 style.json 으로 쓸 것 — 프리셋과 같은 꼴 통째. 틀의 motion 은 프리셋 때처럼 위에 덮는다.
99
+ * 고른 id 가 draft 면 던진다(견본을 만드는 테마 폴더 안에서만 쓴다)
100
+ */
101
+ export function themeStyle(id: string, opts: { allowDraft?: boolean } = {}): KfStyle {
102
+ const t = loadTheme(id);
103
+ if (t.status === "draft" && !opts.allowDraft) throw new Error(`테마 ${id} 는 아직 draft — 견본이 review 로 올라온 뒤에 쓴다`);
104
+ return structuredClone(t.style);
105
+ }
@@ -0,0 +1,177 @@
1
+ import type { SceneCtx } from "@kasaframe/core";
2
+ import * as THREE from "three";
3
+ import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
4
+
5
+ // 입체 테마가 같이 쓰는 바탕 — 렌더러 하나·한글 글자판·환경광. 테마의 효과(rig)는 이 위에 물체를 얹고 t 로 움직인다.
6
+
7
+ let shared: THREE.WebGLRenderer | null = null;
8
+
9
+ // 크롬은 한 페이지에 WebGL 문맥을 16 개쯤만 살려 둔다 — 장면이 여럿이어도 렌더러 하나를 돌려 쓰고, 그리는 장면으로 캔버스를 옮긴다
10
+ export function renderer3d(w: number, h: number): THREE.WebGLRenderer {
11
+ if (!shared) {
12
+ shared = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true, alpha: false, powerPreference: "high-performance" });
13
+ shared.setPixelRatio(1);
14
+ shared.outputColorSpace = THREE.SRGBColorSpace;
15
+ shared.toneMapping = THREE.ACESFilmicToneMapping;
16
+ shared.shadowMap.enabled = true;
17
+ shared.shadowMap.type = THREE.PCFSoftShadowMap;
18
+ shared.domElement.style.cssText = "position:absolute;inset:0;width:100%;height:100%;display:block";
19
+ }
20
+ const size = shared.getSize(new THREE.Vector2());
21
+ if (size.x !== w || size.y !== h) shared.setSize(w, h, false);
22
+ return shared;
23
+ }
24
+
25
+ let envTex: THREE.Texture | null = null;
26
+ /** 방 하나의 빛을 환경 맵으로 — 금속·유리가 비칠 것이 생긴다. 한 번만 굽는다 */
27
+ export function roomEnvironment(renderer: THREE.WebGLRenderer): THREE.Texture {
28
+ if (!envTex) {
29
+ const pmrem = new THREE.PMREMGenerator(renderer);
30
+ envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
31
+ pmrem.dispose();
32
+ }
33
+ return envTex;
34
+ }
35
+
36
+ /** 3D 부품(rig) — 무대 위에 물체를 얹고 t 마다 움직인다. 같은 t 면 같은 자리 */
37
+ export type Rig = (t: number) => void;
38
+
39
+ export interface Stage3D {
40
+ scene: THREE.Scene;
41
+ camera: THREE.PerspectiveCamera | THREE.OrthographicCamera;
42
+ renderer: THREE.WebGLRenderer;
43
+ /** 무대가 박힌 DOM 자리(장면 루트 안) — 겹칠 DOM 은 여기 형제로 */
44
+ el: HTMLElement;
45
+ /** rig 를 등록 — paint(t) 가 카메라를 놓은 뒤 차례로 부른다 */
46
+ add(rig: Rig): void;
47
+ /** rig 를 다 부르고 그린다 */
48
+ paint(t: number): void;
49
+ }
50
+
51
+ export interface StageOpts {
52
+ ctx: SceneCtx;
53
+ camera?: "perspective" | "ortho";
54
+ fov?: number;
55
+ /** 정사영일 때 화면 세로에 담길 세계 단위 */
56
+ frustum?: number;
57
+ background?: string;
58
+ fog?: [near: number, far: number];
59
+ env?: boolean;
60
+ exposure?: number;
61
+ /** 카메라를 t 로 — 자리와 보는 곳 */
62
+ shot?(t: number, camera: THREE.Camera): void;
63
+ }
64
+
65
+ export function stage3d(root: HTMLElement, o: StageOpts): Stage3D {
66
+ const { ctx } = o;
67
+ const W = ctx.meta.width;
68
+ const H = ctx.meta.height;
69
+ const el = document.createElement("div");
70
+ el.style.cssText = "position:absolute;inset:0;";
71
+ root.append(el);
72
+ const renderer = renderer3d(W, H);
73
+ const scene = new THREE.Scene();
74
+ const bg = new THREE.Color(o.background ?? ctx.style.colors.bg);
75
+ scene.background = bg;
76
+ if (o.fog) scene.fog = new THREE.Fog(bg, o.fog[0], o.fog[1]);
77
+ if (o.env) scene.environment = roomEnvironment(renderer);
78
+ let camera: THREE.PerspectiveCamera | THREE.OrthographicCamera;
79
+ if (o.camera === "ortho") {
80
+ const f = o.frustum ?? 10;
81
+ const a = W / H;
82
+ camera = new THREE.OrthographicCamera((-f * a) / 2, (f * a) / 2, f / 2, -f / 2, 0.1, 400);
83
+ } else {
84
+ camera = new THREE.PerspectiveCamera(o.fov ?? 50, W / H, 0.1, 400);
85
+ }
86
+ const rigs: Rig[] = [];
87
+ return {
88
+ scene,
89
+ camera,
90
+ renderer,
91
+ el,
92
+ add: (rig) => rigs.push(rig),
93
+ paint(t) {
94
+ if (renderer.domElement.parentElement !== el) el.prepend(renderer.domElement);
95
+ renderer.toneMappingExposure = o.exposure ?? 1;
96
+ o.shot?.(t, camera);
97
+ for (const r of rigs) r(t);
98
+ renderer.render(scene, camera);
99
+ },
100
+ };
101
+ }
102
+
103
+ export interface TextPlaneOpts {
104
+ text: string;
105
+ /** CSS font 단축 꼴의 앞부분 없이 글꼴 스택만 — 굵기·크기는 따로 */
106
+ family: string;
107
+ weight?: number;
108
+ color: string;
109
+ /** 세계 단위 높이(글 한 줄) */
110
+ height: number;
111
+ /** 캔버스에 그릴 글 크기 px — 클수록 가까이서도 또렷하다 */
112
+ px?: number;
113
+ align?: "left" | "center" | "right";
114
+ /** 바탕을 칠하면 판, 없으면 투명 */
115
+ plate?: string;
116
+ pad?: number;
117
+ emissive?: boolean;
118
+ }
119
+
120
+ /** 한글이 서는 글꼴로 캔버스에 그린 글을 판(평면 메시)으로. 장면 build 에서 만든다(글꼴을 다 받은 뒤라 치수가 맞다) */
121
+ export function textPlane(o: TextPlaneOpts): THREE.Mesh<THREE.PlaneGeometry, THREE.MeshBasicMaterial> {
122
+ const px = o.px ?? 160;
123
+ const pad = o.pad ?? px * 0.25;
124
+ const font = `${o.weight ?? 700} ${px}px ${o.family}`;
125
+ const probe = document.createElement("canvas").getContext("2d")!;
126
+ probe.font = font;
127
+ const w = Math.ceil(probe.measureText(o.text).width + pad * 2);
128
+ const h = Math.ceil(px * 1.3 + pad * 2);
129
+ const c = document.createElement("canvas");
130
+ c.width = w;
131
+ c.height = h;
132
+ const g = c.getContext("2d")!;
133
+ if (o.plate) {
134
+ g.fillStyle = o.plate;
135
+ g.fillRect(0, 0, w, h);
136
+ }
137
+ g.font = font;
138
+ g.fillStyle = o.color;
139
+ g.textBaseline = "middle";
140
+ g.textAlign = "left";
141
+ g.fillText(o.text, pad, h / 2);
142
+ const tex = new THREE.CanvasTexture(c);
143
+ tex.colorSpace = THREE.SRGBColorSpace;
144
+ tex.anisotropy = 4;
145
+ const worldH = (o.height * h) / (px * 1.3);
146
+ const worldW = (worldH * w) / h;
147
+ const geo = new THREE.PlaneGeometry(worldW, worldH);
148
+ if (o.align === "left") geo.translate(worldW / 2, 0, 0);
149
+ if (o.align === "right") geo.translate(-worldW / 2, 0, 0);
150
+ const mat = new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false, toneMapped: !o.emissive, side: THREE.DoubleSide });
151
+ return new THREE.Mesh(geo, mat);
152
+ }
153
+
154
+ /** 둥근 사각 테(관문) 모양 — OG 로고의 두 칸이 이 꼴이다 */
155
+ export function roundRectShape(w: number, h: number, r: number, hole = 0): THREE.Shape {
156
+ const s = new THREE.Shape();
157
+ const rr = (p: THREE.Path | THREE.Shape, x: number, y: number, ww: number, hh: number, rad: number) => {
158
+ p.moveTo(x + rad, y);
159
+ p.lineTo(x + ww - rad, y);
160
+ p.quadraticCurveTo(x + ww, y, x + ww, y + rad);
161
+ p.lineTo(x + ww, y + hh - rad);
162
+ p.quadraticCurveTo(x + ww, y + hh, x + ww - rad, y + hh);
163
+ p.lineTo(x + rad, y + hh);
164
+ p.quadraticCurveTo(x, y + hh, x, y + hh - rad);
165
+ p.lineTo(x, y + rad);
166
+ p.quadraticCurveTo(x, y, x + rad, y);
167
+ };
168
+ rr(s, -w / 2, -h / 2, w, h, r);
169
+ if (hole > 0) {
170
+ const p = new THREE.Path();
171
+ rr(p, -w / 2 + hole, -h / 2 + hole, w - hole * 2, h - hole * 2, Math.max(0.01, r - hole * 0.6));
172
+ s.holes.push(p);
173
+ }
174
+ return s;
175
+ }
176
+
177
+ export { THREE };
@@ -0,0 +1,58 @@
1
+ import type { KfStyle } from "@kasaframe/core";
2
+
3
+ /** draft 만드는 중 · review 견본이 나와 사람이 볼 차례 · approved 사람이 OK 해서 라이브러리에 정식으로 들어감 */
4
+ export type ThemeStatus = "draft" | "review" | "approved";
5
+
6
+ export const THEME_STATUSES: readonly ThemeStatus[] = ["draft", "review", "approved"];
7
+
8
+ export interface ThemeEffectInfo {
9
+ /** effects.ts 의 이름 있는 내보내기와 같다 */
10
+ name: string;
11
+ /** value: (t, opts) => Style·수·글 · layer: (el, opts) => (t) => void · rig: (stage, opts) => (t) => void(3D 무대에 물체를 얹는다) — 모두 같은 t 면 같은 화면 */
12
+ kind: "value" | "layer" | "rig";
13
+ /** 무엇을 하나 — 한 줄 */
14
+ does: string;
15
+ /** 부르는 꼴 한 줄(모델이 그대로 베낀다) */
16
+ use: string;
17
+ }
18
+
19
+ /** themes/<id>/theme.json */
20
+ export interface ThemeManifest {
21
+ id: string;
22
+ name: string;
23
+ /** 내용에서 나온 비유 한 줄 — 「무엇이 무엇처럼 되며 화면이 찍힌다」 */
24
+ metaphor: string;
25
+ status: ThemeStatus;
26
+ /** approved 로 바꾼 날(ISO). 그 전엔 null */
27
+ approvedAt: string | null;
28
+ /** 어울리는 용도 — templates/<id> */
29
+ purposes: string[];
30
+ /** 견본이 서는 화면비. 앞이 견본의 화면비 */
31
+ aspect: string[];
32
+ effects: ThemeEffectInfo[];
33
+ /** 테마 폴더 기준 파일 이름. 기본 still.png · sample.mp4 */
34
+ still?: string;
35
+ sample?: string;
36
+ }
37
+
38
+ export interface Theme extends ThemeManifest {
39
+ dir: string;
40
+ style: KfStyle;
41
+ /** THEME.md 원문 — 비유·맞는 내용·금지 */
42
+ guide: string;
43
+ /** 절대 경로. 파일이 아직 없으면 null */
44
+ files: { still: string | null; sample: string | null; sampleProject: string | null; effects: string };
45
+ }
46
+
47
+ /** 작업실·plan 이 목록에 쓰는 꼴. still·sample 은 절대 경로(없으면 null) */
48
+ export interface ThemeCard {
49
+ id: string;
50
+ name: string;
51
+ metaphor: string;
52
+ status: ThemeStatus;
53
+ approvedAt: string | null;
54
+ still: string | null;
55
+ sample: string | null;
56
+ purposes: string[];
57
+ aspect: string[];
58
+ }