key-screen-framework 0.1.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 (113) hide show
  1. package/chunks/store-txJwmrlO.js +281 -0
  2. package/chunks/useArduinoBuild-CVr4XAsL.js +152 -0
  3. package/cli/check-arduino-bundle.mjs +157 -0
  4. package/cli/doctor-project.mjs +554 -0
  5. package/cli/generate-screen.mjs +286 -0
  6. package/cli/migrate-project.mjs +679 -0
  7. package/cli/new-project.mjs +344 -0
  8. package/cli/remove-screen.mjs +83 -0
  9. package/cli/screen-generation-contract.mjs +127 -0
  10. package/cli/screen-generation-renderers.mjs +71 -0
  11. package/cli/screen-module-utils.mjs +148 -0
  12. package/cli/screen-script-utils.mjs +92 -0
  13. package/cli/setup-arduino-cli.mjs +515 -0
  14. package/cli/source-module-specifiers.mjs +89 -0
  15. package/cli/sync-screens.mjs +48 -0
  16. package/main/index.js +2003 -0
  17. package/package.json +108 -0
  18. package/preload/index.js +69 -0
  19. package/renderer/components/VideoSceneScreen.js +160 -0
  20. package/renderer/hooks/index.js +6 -0
  21. package/renderer/index.js +3092 -0
  22. package/renderer/store.js +6 -0
  23. package/renderer/styles.css +1395 -0
  24. package/shared/arduino-board.js +136 -0
  25. package/shared/arduino-keyboard-shortcut.js +77 -0
  26. package/shared/index.js +25 -0
  27. package/shared/screen-catalog.js +35 -0
  28. package/shared/screen-shortcuts.js +164 -0
  29. package/shared/types.js +1 -0
  30. package/templates/project/README.md +45 -0
  31. package/templates/project/build/favicon-mac.png +0 -0
  32. package/templates/project/build/favicon.ico +0 -0
  33. package/templates/project/build/favicon.png +0 -0
  34. package/templates/project/e2e/smoke.spec.ts +10 -0
  35. package/templates/project/electron.vite.config.ts +40 -0
  36. package/templates/project/eslint.config.js +23 -0
  37. package/templates/project/gitignore +19 -0
  38. package/templates/project/media/audio/.gitkeep +1 -0
  39. package/templates/project/media/font/.gitkeep +1 -0
  40. package/templates/project/media/image/.gitkeep +1 -0
  41. package/templates/project/media/video/.gitkeep +1 -0
  42. package/templates/project/media/video/external-sample-30s.mp4 +0 -0
  43. package/templates/project/package.json +117 -0
  44. package/templates/project/playwright.config.ts +7 -0
  45. package/templates/project/postcss.config.js +6 -0
  46. package/templates/project/src/arduino-output-signals.ts +19 -0
  47. package/templates/project/src/assets/audio/.gitkeep +1 -0
  48. package/templates/project/src/assets/font/PretendardVariable.woff2 +0 -0
  49. package/templates/project/src/assets/image/.gitkeep +1 -0
  50. package/templates/project/src/assets/image/key-icon.png +0 -0
  51. package/templates/project/src/assets/video/.gitkeep +1 -0
  52. package/templates/project/src/assets/video/sample-30s.mp4 +0 -0
  53. package/templates/project/src/device-signal-handlers.test.ts +9 -0
  54. package/templates/project/src/device-signal-handlers.ts +14 -0
  55. package/templates/project/src/device-signal-targets.ts +3 -0
  56. package/templates/project/src/main/index.ts +17 -0
  57. package/templates/project/src/preload/index.ts +4 -0
  58. package/templates/project/src/project.config.ts +11 -0
  59. package/templates/project/src/renderer/index.html +16 -0
  60. package/templates/project/src/renderer/main.tsx +20 -0
  61. package/templates/project/src/renderer/vite-env.d.ts +1 -0
  62. package/templates/project/src/screen-definitions.ts +75 -0
  63. package/templates/project/src/screens/Screen001Black.test.tsx +21 -0
  64. package/templates/project/src/screens/Screen001Black.tsx +38 -0
  65. package/templates/project/src/screens/Screen002Video.test.tsx +18 -0
  66. package/templates/project/src/screens/Screen002Video.tsx +22 -0
  67. package/templates/project/src/screens/Screen003ExternalVideo.test.tsx +26 -0
  68. package/templates/project/src/screens/Screen003ExternalVideo.tsx +22 -0
  69. package/templates/project/src/store.test.ts +21 -0
  70. package/templates/project/src/store.ts +32 -0
  71. package/templates/project/src/styles.css +60 -0
  72. package/templates/project/tailwind.config.ts +69 -0
  73. package/templates/project/tsconfig.json +4 -0
  74. package/templates/project/tsconfig.node.json +32 -0
  75. package/templates/project/vitest.config.ts +20 -0
  76. package/templates/project/vitest.setup.ts +1 -0
  77. package/types/main/app-keyboard-shortcuts.d.ts +4 -0
  78. package/types/main/arduino-cli.d.ts +55 -0
  79. package/types/main/arduino-sketch-generator.d.ts +10 -0
  80. package/types/main/device-controller.d.ts +39 -0
  81. package/types/main/device-log-writer.d.ts +21 -0
  82. package/types/main/dtoa-dispatcher.d.ts +17 -0
  83. package/types/main/dtoa-handler.d.ts +9 -0
  84. package/types/main/game-session.d.ts +12 -0
  85. package/types/main/kiosk-quit.d.ts +5 -0
  86. package/types/main/media-manager.d.ts +17 -0
  87. package/types/main/runtime-paths.d.ts +10 -0
  88. package/types/main/serial-protocol.d.ts +29 -0
  89. package/types/main/start.d.ts +2 -0
  90. package/types/main/window-mode.d.ts +18 -0
  91. package/types/main/windows-key-lock.d.ts +3 -0
  92. package/types/preload/bridge.d.ts +4 -0
  93. package/types/renderer/src/App.d.ts +3 -0
  94. package/types/renderer/src/KeyScreenApp.d.ts +3 -0
  95. package/types/renderer/src/bridge.d.ts +3 -0
  96. package/types/renderer/src/components/DeviceLogOverlay.d.ts +7 -0
  97. package/types/renderer/src/components/ScreenRenderer.d.ts +7 -0
  98. package/types/renderer/src/components/SplashScreen.d.ts +7 -0
  99. package/types/renderer/src/components/VideoSceneScreen.d.ts +16 -0
  100. package/types/renderer/src/framework/AdminScreen.d.ts +3 -0
  101. package/types/renderer/src/hooks/index.d.ts +4 -0
  102. package/types/renderer/src/hooks/useArduinoBuild.d.ts +14 -0
  103. package/types/renderer/src/hooks/useAtodSignal.d.ts +12 -0
  104. package/types/renderer/src/index.d.ts +9 -0
  105. package/types/renderer/src/project-runtime.d.ts +10 -0
  106. package/types/renderer/src/screen-types.d.ts +24 -0
  107. package/types/renderer/src/store.d.ts +33 -0
  108. package/types/shared/arduino-board.d.ts +11 -0
  109. package/types/shared/arduino-keyboard-shortcut.d.ts +14 -0
  110. package/types/shared/index.d.ts +5 -0
  111. package/types/shared/screen-catalog.d.ts +19 -0
  112. package/types/shared/screen-shortcuts.d.ts +10 -0
  113. package/types/shared/types.d.ts +272 -0
@@ -0,0 +1,679 @@
1
+ #!/usr/bin/env node
2
+ import process from 'node:process'
3
+ import { createHash, randomUUID } from 'node:crypto'
4
+ import {
5
+ cpSync,
6
+ existsSync,
7
+ lstatSync,
8
+ mkdirSync,
9
+ readFileSync,
10
+ readlinkSync,
11
+ realpathSync,
12
+ readdirSync,
13
+ rmSync,
14
+ writeFileSync
15
+ } from 'node:fs'
16
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
17
+ import { fileURLToPath } from 'node:url'
18
+ import { isDirectExecution } from './screen-script-utils.mjs'
19
+ import { collectModuleSpecifiers } from './source-module-specifiers.mjs'
20
+
21
+ const cliDirectory = dirname(fileURLToPath(import.meta.url))
22
+ const packageRoot = resolve(cliDirectory, '..')
23
+ const defaultTemplateDirectory = join(packageRoot, 'templates/project')
24
+
25
+ const THIN_TEMPLATE_PATHS = [
26
+ 'src/main/index.ts',
27
+ 'src/preload/index.ts',
28
+ 'src/renderer/main.tsx',
29
+ 'src/renderer/index.html',
30
+ 'src/renderer/vite-env.d.ts',
31
+ 'src/screen-definitions.ts'
32
+ ]
33
+
34
+ const LEGACY_ELECTRON_VITE_CONFIG = `import { resolve } from 'node:path'
35
+ import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
36
+ import react from '@vitejs/plugin-react'
37
+
38
+ const aliases = {
39
+ '@renderer': resolve(__dirname, 'framework/renderer/src'),
40
+ '@shared': resolve(__dirname, 'framework/shared'),
41
+ '@framework': resolve(__dirname, 'framework'),
42
+ '@project': resolve(__dirname, 'src'),
43
+ '@screens': resolve(__dirname, 'src/screens'),
44
+ '@assets': resolve(__dirname, 'src/assets')
45
+ }
46
+
47
+ export default defineConfig({
48
+ main: {
49
+ plugins: [externalizeDepsPlugin()],
50
+ resolve: {
51
+ alias: aliases
52
+ },
53
+ build: {
54
+ rollupOptions: {
55
+ input: {
56
+ index: resolve(__dirname, 'framework/main/index.ts')
57
+ }
58
+ }
59
+ }
60
+ },
61
+ preload: {
62
+ plugins: [externalizeDepsPlugin()],
63
+ resolve: {
64
+ alias: aliases
65
+ },
66
+ build: {
67
+ rollupOptions: {
68
+ input: {
69
+ index: resolve(__dirname, 'framework/preload/index.ts')
70
+ }
71
+ }
72
+ }
73
+ },
74
+ renderer: {
75
+ root: resolve(__dirname, 'framework/renderer'),
76
+ resolve: {
77
+ alias: aliases
78
+ },
79
+ plugins: [react()],
80
+ build: {
81
+ rollupOptions: {
82
+ input: resolve(__dirname, 'framework/renderer/index.html')
83
+ }
84
+ }
85
+ }
86
+ })
87
+ `
88
+
89
+ const LEGACY_TSCONFIG_NODE = {
90
+ compilerOptions: {
91
+ target: 'ES2022',
92
+ lib: ['ES2023', 'DOM'],
93
+ module: 'ESNext',
94
+ moduleResolution: 'Bundler',
95
+ jsx: 'react-jsx',
96
+ allowSyntheticDefaultImports: true,
97
+ resolveJsonModule: true,
98
+ isolatedModules: true,
99
+ noEmit: true,
100
+ strict: true,
101
+ noUnusedLocals: true,
102
+ noUnusedParameters: true,
103
+ skipLibCheck: true,
104
+ baseUrl: '.',
105
+ paths: {
106
+ '@main/*': ['framework/main/*'],
107
+ '@preload/*': ['framework/preload/*'],
108
+ '@renderer/*': ['framework/renderer/src/*'],
109
+ '@shared/*': ['framework/shared/*'],
110
+ '@framework/*': ['framework/*'],
111
+ '@project/*': ['src/*'],
112
+ '@screens/*': ['src/screens/*'],
113
+ '@assets/*': ['src/assets/*']
114
+ },
115
+ types: ['node', 'vitest/globals', '@testing-library/jest-dom']
116
+ },
117
+ include: [
118
+ 'electron.vite.config.ts',
119
+ 'eslint.config.js',
120
+ 'playwright.config.ts',
121
+ 'framework/**/*.ts',
122
+ 'framework/**/*.tsx',
123
+ 'src/**/*.ts',
124
+ 'src/**/*.tsx',
125
+ 'e2e/**/*.ts'
126
+ ]
127
+ }
128
+
129
+ const SOURCE_IMPORT_REPLACEMENTS = new Map([
130
+ ['@shared/types', 'key-screen-framework/shared/types'],
131
+ ['@shared/screens', '@project/screen-definitions'],
132
+ ['@shared/arduino-board', 'key-screen-framework/shared/arduino-board'],
133
+ [
134
+ '@shared/arduino-keyboard-shortcut',
135
+ 'key-screen-framework/shared/arduino-keyboard-shortcut'
136
+ ],
137
+ ['@shared/screen-catalog', 'key-screen-framework/shared/screen-catalog'],
138
+ ['@shared/screen-shortcuts', 'key-screen-framework/shared/screen-shortcuts'],
139
+ ['@framework/renderer/src/screen-types', 'key-screen-framework/renderer'],
140
+ ['@framework/renderer/src/bridge', 'key-screen-framework/renderer'],
141
+ ['@framework/renderer/src/hooks', 'key-screen-framework/renderer/hooks'],
142
+ ['@framework/renderer/src/store', 'key-screen-framework/renderer/store'],
143
+ ['@renderer/screen-types', 'key-screen-framework/renderer'],
144
+ ['@renderer/bridge', 'key-screen-framework/renderer'],
145
+ ['@renderer/hooks', 'key-screen-framework/renderer/hooks'],
146
+ ['@renderer/store', 'key-screen-framework/renderer/store'],
147
+ [
148
+ '@renderer/components/VideoSceneScreen',
149
+ 'key-screen-framework/renderer/components/VideoSceneScreen'
150
+ ],
151
+ [
152
+ '@framework/renderer/src/components/VideoSceneScreen',
153
+ 'key-screen-framework/renderer/components/VideoSceneScreen'
154
+ ]
155
+ ])
156
+
157
+ const PACKAGE_SCRIPT_MIGRATIONS = new Map([
158
+ ['new-project', ['node scripts/new-project.mjs', 'key-screen-new-project']],
159
+ ['sync:screens', ['node scripts/sync-screens.mjs', 'key-screen-sync']],
160
+ ['generate:screen', ['node scripts/generate-screen.mjs', 'key-screen-generate']],
161
+ ['remove:screen', ['node scripts/remove-screen.mjs', 'key-screen-remove']],
162
+ ['setup:arduino-cli', ['node scripts/setup-arduino-cli.mjs', 'key-screen-setup-arduino']],
163
+ [
164
+ 'check:arduino-bundle',
165
+ ['node scripts/check-arduino-bundle.mjs', 'key-screen-check-arduino-bundle']
166
+ ],
167
+ [
168
+ 'check:arduino-bundle:win',
169
+ [
170
+ 'node scripts/check-arduino-bundle.mjs --target win32-x64',
171
+ 'key-screen-check-arduino-bundle --target win32-x64'
172
+ ]
173
+ ],
174
+ [
175
+ 'check:arduino-bundle:mac',
176
+ [
177
+ 'node scripts/check-arduino-bundle.mjs --target darwin-arm64',
178
+ 'key-screen-check-arduino-bundle --target darwin-arm64'
179
+ ]
180
+ ]
181
+ ])
182
+
183
+ const SOURCE_EXTENSION_PATTERN = /\.[cm]?[jt]sx?$/
184
+ const PRIVATE_IMPORT_PATTERN = /^@(shared|framework|renderer|main|preload)(?:\/.*)?$/
185
+
186
+ function normalizeNewlines(value) {
187
+ return value.replaceAll('\r\n', '\n')
188
+ }
189
+
190
+ function jsonEqual(left, right) {
191
+ return JSON.stringify(left) === JSON.stringify(right)
192
+ }
193
+
194
+ function parseCliArgs(argv) {
195
+ const options = {}
196
+ const booleanOptions = new Set(['apply', 'remove-framework', 'help'])
197
+ const valueOptions = new Set(['project-root', 'framework-dependency', 'backup-dir'])
198
+
199
+ for (let index = 0; index < argv.length; index += 1) {
200
+ const token = argv[index]
201
+ if (!token.startsWith('--')) throw new Error(`Unexpected argument: ${token}`)
202
+ const [name, inlineValue] = token.slice(2).split(/=(.*)/s, 2)
203
+ if (Object.hasOwn(options, name)) throw new Error(`Option may only be provided once: --${name}`)
204
+
205
+ if (booleanOptions.has(name)) {
206
+ if (inlineValue !== undefined) throw new Error(`Option --${name} does not accept a value.`)
207
+ options[name] = true
208
+ continue
209
+ }
210
+ if (!valueOptions.has(name)) throw new Error(`Unknown option: --${name}`)
211
+ const value = inlineValue ?? argv[index + 1]
212
+ if (!value || value.startsWith('--')) throw new Error(`Option --${name} requires a value.`)
213
+ options[name] = value
214
+ if (inlineValue === undefined) index += 1
215
+ }
216
+
217
+ if (options['remove-framework'] && !options.apply) {
218
+ throw new Error('--remove-framework requires --apply.')
219
+ }
220
+ return options
221
+ }
222
+
223
+ function listSourceFiles(directory) {
224
+ if (!existsSync(directory)) return []
225
+ const files = []
226
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
227
+ const path = join(directory, entry.name)
228
+ if (entry.isDirectory()) files.push(...listSourceFiles(path))
229
+ else if (entry.isFile() && SOURCE_EXTENSION_PATTERN.test(entry.name)) files.push(path)
230
+ }
231
+ return files
232
+ }
233
+
234
+ function rewritePublicImports(source, path) {
235
+ let rewritten = source
236
+ const replacements = collectModuleSpecifiers(source, path)
237
+ .map(({ node, value, sourceFile }) => ({
238
+ start: node.getStart(sourceFile) + 1,
239
+ end: node.getEnd() - 1,
240
+ value: SOURCE_IMPORT_REPLACEMENTS.get(value)
241
+ }))
242
+ .filter((replacement) => replacement.value)
243
+ .sort((left, right) => right.start - left.start)
244
+ for (const replacement of replacements) {
245
+ rewritten = `${rewritten.slice(0, replacement.start)}${replacement.value}${rewritten.slice(replacement.end)}`
246
+ }
247
+ return rewritten
248
+ }
249
+
250
+ function findPrivateImports(source, path) {
251
+ return collectModuleSpecifiers(source, path)
252
+ .map(({ value }) => value)
253
+ .filter((value) => PRIVATE_IMPORT_PATTERN.test(value))
254
+ }
255
+
256
+ function addChange(changes, projectRoot, absolutePath, content, reason, conflicts) {
257
+ const projectPath = relative(projectRoot, absolutePath).split(sep).join('/')
258
+ if (projectPath.startsWith('../') || isAbsolute(projectPath)) {
259
+ conflicts.push(`프로젝트 밖의 파일은 변경할 수 없습니다: ${absolutePath}`)
260
+ return
261
+ }
262
+ const realProjectRoot = realpathSync(projectRoot)
263
+ let existingAncestor = existsSync(absolutePath) ? absolutePath : dirname(absolutePath)
264
+ while (!existsSync(existingAncestor)) existingAncestor = dirname(existingAncestor)
265
+ const realAncestor = realpathSync(existingAncestor)
266
+ const realProjectPath = relative(realProjectRoot, realAncestor)
267
+ if (realProjectPath.startsWith(`..${sep}`) || realProjectPath === '..' || isAbsolute(realProjectPath)) {
268
+ conflicts.push(`${projectPath}: symlink를 통해 프로젝트 밖을 가리켜 변경할 수 없습니다.`)
269
+ return
270
+ }
271
+ const before = existsSync(absolutePath) ? readFileSync(absolutePath, 'utf8') : undefined
272
+ if (before === content || normalizeNewlines(before ?? '') === normalizeNewlines(content)) return
273
+ changes.push({ path: projectPath, absolutePath, before, content, reason })
274
+ }
275
+
276
+ function loadThinTemplates(templateDirectory) {
277
+ const templates = new Map()
278
+ for (const path of [...THIN_TEMPLATE_PATHS, 'electron.vite.config.ts', 'tsconfig.node.json']) {
279
+ const absolutePath = join(templateDirectory, path)
280
+ if (!existsSync(absolutePath)) throw new Error(`Migration template is missing: ${absolutePath}`)
281
+ templates.set(path, readFileSync(absolutePath, 'utf8'))
282
+ }
283
+ return templates
284
+ }
285
+
286
+ function planThinFile({ changes, conflicts, projectRoot, path, content }) {
287
+ const absolutePath = join(projectRoot, path)
288
+ if (existsSync(absolutePath)) {
289
+ const current = readFileSync(absolutePath, 'utf8')
290
+ if (normalizeNewlines(current) !== normalizeNewlines(content)) {
291
+ conflicts.push(`${path}: 기존 파일이 Wave 2 thin template과 달라 자동 덮어쓸 수 없습니다.`)
292
+ return
293
+ }
294
+ }
295
+ addChange(changes, projectRoot, absolutePath, content, 'thin consumer entry 생성', conflicts)
296
+ }
297
+
298
+ function planConfigFiles({ changes, conflicts, projectRoot, templates }) {
299
+ const electronPath = join(projectRoot, 'electron.vite.config.ts')
300
+ const desiredElectron = templates.get('electron.vite.config.ts')
301
+ if (!existsSync(electronPath)) {
302
+ addChange(changes, projectRoot, electronPath, desiredElectron, 'thin build config 생성', conflicts)
303
+ } else {
304
+ const current = readFileSync(electronPath, 'utf8')
305
+ if (normalizeNewlines(current) === normalizeNewlines(LEGACY_ELECTRON_VITE_CONFIG)) {
306
+ addChange(changes, projectRoot, electronPath, desiredElectron, '복제형 build config 변환', conflicts)
307
+ } else if (normalizeNewlines(current) !== normalizeNewlines(desiredElectron)) {
308
+ conflicts.push(
309
+ 'electron.vite.config.ts: canonical 복제형 또는 Wave 2 template과 달라 자동 변환할 수 없습니다.'
310
+ )
311
+ }
312
+ }
313
+
314
+ const tsconfigPath = join(projectRoot, 'tsconfig.node.json')
315
+ const desiredTsconfig = templates.get('tsconfig.node.json')
316
+ if (!existsSync(tsconfigPath)) {
317
+ addChange(changes, projectRoot, tsconfigPath, desiredTsconfig, 'thin TypeScript config 생성', conflicts)
318
+ return
319
+ }
320
+
321
+ let currentTsconfig
322
+ try {
323
+ currentTsconfig = JSON.parse(readFileSync(tsconfigPath, 'utf8'))
324
+ } catch (error) {
325
+ conflicts.push(`tsconfig.node.json: JSON을 읽을 수 없습니다 (${error.message}).`)
326
+ return
327
+ }
328
+ const parsedDesired = JSON.parse(desiredTsconfig)
329
+ if (jsonEqual(currentTsconfig, LEGACY_TSCONFIG_NODE)) {
330
+ addChange(changes, projectRoot, tsconfigPath, desiredTsconfig, '복제형 TypeScript config 변환', conflicts)
331
+ } else if (!jsonEqual(currentTsconfig, parsedDesired)) {
332
+ conflicts.push(
333
+ 'tsconfig.node.json: canonical 복제형 또는 Wave 2 template과 달라 자동 변환할 수 없습니다.'
334
+ )
335
+ }
336
+ }
337
+
338
+ function replaceMediaResourcePaths(value) {
339
+ if (Array.isArray(value)) return value.map(replaceMediaResourcePaths)
340
+ if (value && typeof value === 'object') {
341
+ return Object.fromEntries(
342
+ Object.entries(value).map(([key, child]) => [key, replaceMediaResourcePaths(child)])
343
+ )
344
+ }
345
+ return value === 'out/default-media' ? 'media' : value
346
+ }
347
+
348
+ function resolveDefaultFrameworkDependency() {
349
+ const manifest = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8'))
350
+ if (typeof manifest.version !== 'string' || !manifest.version.trim()) {
351
+ throw new Error('key-screen-framework package version is missing.')
352
+ }
353
+ return `^${manifest.version}`
354
+ }
355
+
356
+ function planPackageJson({ changes, conflicts, projectRoot, frameworkDependency }) {
357
+ const path = join(projectRoot, 'package.json')
358
+ if (!existsSync(path)) {
359
+ conflicts.push('package.json이 없습니다.')
360
+ return
361
+ }
362
+ let manifest
363
+ try {
364
+ manifest = JSON.parse(readFileSync(path, 'utf8'))
365
+ } catch (error) {
366
+ conflicts.push(`package.json을 읽을 수 없습니다 (${error.message}).`)
367
+ return
368
+ }
369
+
370
+ const next = structuredClone(manifest)
371
+ next.dependencies ??= {}
372
+ if (frameworkDependency || !next.dependencies['key-screen-framework']) {
373
+ next.dependencies['key-screen-framework'] = frameworkDependency || resolveDefaultFrameworkDependency()
374
+ }
375
+ next.scripts ??= {}
376
+ if (!Object.hasOwn(next.scripts, 'doctor:framework')) {
377
+ next.scripts['doctor:framework'] = 'key-screen-doctor'
378
+ }
379
+ for (const [name, [legacy, migrated]] of PACKAGE_SCRIPT_MIGRATIONS) {
380
+ const current = next.scripts[name]
381
+ if (current === undefined || current === legacy) next.scripts[name] = migrated
382
+ else if (current !== migrated) {
383
+ conflicts.push(`package.json scripts.${name}: 예상한 복제형 명령과 달라 자동 변환할 수 없습니다.`)
384
+ }
385
+ }
386
+
387
+ if (next.scripts.build === 'electron-vite build && npm run sync:media') {
388
+ next.scripts.build = 'electron-vite build'
389
+ } else if (typeof next.scripts.build === 'string' && next.scripts.build.includes('sync:media')) {
390
+ conflicts.push('package.json scripts.build: 사용자 정의 sync:media 호출을 자동 제거할 수 없습니다.')
391
+ }
392
+ if (next.scripts['sync:media'] === 'node scripts/sync-media.mjs') delete next.scripts['sync:media']
393
+ next.build = replaceMediaResourcePaths(next.build)
394
+
395
+ addChange(
396
+ changes,
397
+ projectRoot,
398
+ path,
399
+ `${JSON.stringify(next, null, 2)}\n`,
400
+ 'package dependency/CLI/build 경로 변환',
401
+ conflicts
402
+ )
403
+ }
404
+
405
+ function planProjectSources({ changes, conflicts, projectRoot }) {
406
+ for (const absolutePath of listSourceFiles(join(projectRoot, 'src'))) {
407
+ const source = readFileSync(absolutePath, 'utf8')
408
+ const rewritten = rewritePublicImports(source, absolutePath)
409
+ const unsupported = findPrivateImports(rewritten, absolutePath)
410
+ if (unsupported.length > 0) {
411
+ conflicts.push(
412
+ `${relative(projectRoot, absolutePath)}: 공개 API로 자동 변환할 수 없는 import (${[...new Set(unsupported)].join(', ')})`
413
+ )
414
+ continue
415
+ }
416
+ addChange(changes, projectRoot, absolutePath, rewritten, 'framework import 공개 API 전환', conflicts)
417
+ }
418
+ }
419
+
420
+ function planGeneratedSources({ changes, conflicts, projectRoot }) {
421
+ const legacyDirectory = join(projectRoot, 'framework/generated')
422
+ const targetDirectory = join(projectRoot, 'src/generated')
423
+ if (!existsSync(legacyDirectory)) return
424
+ for (const legacyPath of listSourceFiles(legacyDirectory)) {
425
+ const projectRelative = relative(legacyDirectory, legacyPath)
426
+ const targetPath = join(targetDirectory, projectRelative)
427
+ const content = rewritePublicImports(readFileSync(legacyPath, 'utf8'), legacyPath)
428
+ const unsupported = findPrivateImports(content, legacyPath)
429
+ if (unsupported.length > 0) {
430
+ conflicts.push(
431
+ `framework/generated/${projectRelative}: 공개 API로 자동 변환할 수 없는 import (${[...new Set(unsupported)].join(', ')})`
432
+ )
433
+ continue
434
+ }
435
+ if (existsSync(targetPath)) {
436
+ const current = rewritePublicImports(readFileSync(targetPath, 'utf8'), targetPath)
437
+ if (normalizeNewlines(current) !== normalizeNewlines(content)) {
438
+ conflicts.push(`src/generated/${projectRelative}: 기존 generated 파일과 복제형 출력이 다릅니다.`)
439
+ continue
440
+ }
441
+ }
442
+ addChange(changes, projectRoot, targetPath, content, 'generated registry 이전', conflicts)
443
+ }
444
+ }
445
+
446
+ function planGitignore({ changes, conflicts, projectRoot }) {
447
+ const path = join(projectRoot, '.gitignore')
448
+ const current = existsSync(path) ? readFileSync(path, 'utf8') : ''
449
+ const lines = normalizeNewlines(current).split('\n')
450
+ const missingEntries = ['src/generated', '.key-screen-migration-backup/'].filter(
451
+ (entry) => !lines.includes(entry)
452
+ )
453
+ if (missingEntries.length === 0) return
454
+ const content = `${current}${current && !current.endsWith('\n') ? '\n' : ''}${missingEntries.join('\n')}\n`
455
+ addChange(changes, projectRoot, path, content, 'generated output ignore 추가', conflicts)
456
+ }
457
+
458
+ export function analyzeMigration({
459
+ projectRoot: projectRootInput = process.cwd(),
460
+ templateDirectory = defaultTemplateDirectory,
461
+ frameworkDependency,
462
+ removeFramework = false
463
+ } = {}) {
464
+ const projectRoot = resolve(projectRootInput)
465
+ const templates = loadThinTemplates(templateDirectory)
466
+ const changes = []
467
+ const conflicts = []
468
+
469
+ planPackageJson({ changes, conflicts, projectRoot, frameworkDependency })
470
+ for (const path of THIN_TEMPLATE_PATHS) {
471
+ planThinFile({ changes, conflicts, projectRoot, path, content: templates.get(path) })
472
+ }
473
+ planConfigFiles({ changes, conflicts, projectRoot, templates })
474
+ planProjectSources({ changes, conflicts, projectRoot })
475
+ planGeneratedSources({ changes, conflicts, projectRoot })
476
+ planGitignore({ changes, conflicts, projectRoot })
477
+
478
+ const frameworkPath = join(projectRoot, 'framework')
479
+ const frameworkExists = existsSync(frameworkPath)
480
+ if (!frameworkExists) {
481
+ let manifest
482
+ try {
483
+ manifest = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'))
484
+ } catch {
485
+ manifest = undefined
486
+ }
487
+ if (!manifest?.dependencies?.['key-screen-framework']) {
488
+ conflicts.push('framework/도 key-screen-framework dependency도 없어 복제형 프로젝트인지 확인할 수 없습니다.')
489
+ }
490
+ }
491
+
492
+ return {
493
+ projectRoot,
494
+ changes,
495
+ conflicts,
496
+ frameworkExists,
497
+ removeFramework: removeFramework && frameworkExists
498
+ }
499
+ }
500
+
501
+ function snapshot(path) {
502
+ const result = new Map()
503
+ function visit(current, root) {
504
+ const stats = lstatSync(current)
505
+ const key = relative(root, current).split(sep).join('/') || '.'
506
+ if (stats.isSymbolicLink()) {
507
+ result.set(key, `symlink:${readlinkSync(current)}`)
508
+ return
509
+ }
510
+ if (stats.isDirectory()) {
511
+ result.set(key, 'directory')
512
+ for (const entry of readdirSync(current).sort()) visit(join(current, entry), root)
513
+ return
514
+ }
515
+ if (stats.isFile()) {
516
+ result.set(key, `file:${createHash('sha256').update(readFileSync(current)).digest('hex')}`)
517
+ return
518
+ }
519
+ result.set(key, `other:${stats.mode}:${stats.size}`)
520
+ }
521
+ visit(path, path)
522
+ return result
523
+ }
524
+
525
+ function verifyCopy(source, destination) {
526
+ const sourceSnapshot = snapshot(source)
527
+ const destinationSnapshot = snapshot(destination)
528
+ if (!jsonEqual([...sourceSnapshot], [...destinationSnapshot])) {
529
+ throw new Error(`Backup verification failed: ${destination}`)
530
+ }
531
+ }
532
+
533
+ function defaultBackupDirectory(projectRoot) {
534
+ const stamp = new Date().toISOString().replaceAll(':', '-').replaceAll('.', '-')
535
+ return join(projectRoot, '.key-screen-migration-backup', stamp)
536
+ }
537
+
538
+ function assertSafeBackupDirectory(projectRoot, backupDirectory) {
539
+ const relativePath = relative(projectRoot, backupDirectory)
540
+ if (!relativePath || relativePath === '.') throw new Error('Backup directory cannot be the project root.')
541
+ const frameworkRelative = relative(join(projectRoot, 'framework'), backupDirectory)
542
+ if (!frameworkRelative.startsWith('..') && !isAbsolute(frameworkRelative)) {
543
+ throw new Error('Backup directory cannot be inside framework/.')
544
+ }
545
+ if (existsSync(backupDirectory) && readdirSync(backupDirectory).length > 0) {
546
+ throw new Error(`Backup directory must be empty: ${backupDirectory}`)
547
+ }
548
+ }
549
+
550
+ function backUpExistingChanges(plan, backupDirectory) {
551
+ const filesRoot = join(backupDirectory, 'project-files')
552
+ for (const change of plan.changes.filter((item) => item.before !== undefined)) {
553
+ const destination = join(filesRoot, change.path)
554
+ mkdirSync(dirname(destination), { recursive: true })
555
+ cpSync(change.absolutePath, destination, { dereference: false, verbatimSymlinks: true })
556
+ verifyCopy(change.absolutePath, destination)
557
+ }
558
+ }
559
+
560
+ export function applyMigration(plan, { backupDirectory: backupDirectoryInput } = {}) {
561
+ if (plan.conflicts.length > 0) {
562
+ throw new Error(`Migration preflight failed:\n- ${plan.conflicts.join('\n- ')}`)
563
+ }
564
+ if (plan.changes.length === 0 && !plan.removeFramework) {
565
+ return { applied: false, backupDirectory: undefined, changedPaths: [], frameworkRemoved: false }
566
+ }
567
+
568
+ const backupDirectory = backupDirectoryInput
569
+ ? isAbsolute(backupDirectoryInput)
570
+ ? backupDirectoryInput
571
+ : resolve(plan.projectRoot, backupDirectoryInput)
572
+ : defaultBackupDirectory(plan.projectRoot)
573
+ assertSafeBackupDirectory(plan.projectRoot, backupDirectory)
574
+ mkdirSync(backupDirectory, { recursive: true })
575
+ backUpExistingChanges(plan, backupDirectory)
576
+
577
+ if (plan.removeFramework) {
578
+ const frameworkBackup = join(backupDirectory, 'framework')
579
+ cpSync(join(plan.projectRoot, 'framework'), frameworkBackup, {
580
+ recursive: true,
581
+ dereference: false,
582
+ verbatimSymlinks: true
583
+ })
584
+ verifyCopy(join(plan.projectRoot, 'framework'), frameworkBackup)
585
+ }
586
+
587
+ for (const change of plan.changes) {
588
+ mkdirSync(dirname(change.absolutePath), { recursive: true })
589
+ const temporaryPath = `${change.absolutePath}.key-screen-migration-${randomUUID()}.tmp`
590
+ try {
591
+ writeFileSync(temporaryPath, change.content, { flag: 'wx' })
592
+ rmSync(change.absolutePath, { force: true })
593
+ cpSync(temporaryPath, change.absolutePath)
594
+ } finally {
595
+ rmSync(temporaryPath, { force: true })
596
+ }
597
+ }
598
+
599
+ if (plan.removeFramework) {
600
+ rmSync(join(plan.projectRoot, 'framework'), { recursive: true })
601
+ }
602
+ writeFileSync(
603
+ join(backupDirectory, 'migration-manifest.json'),
604
+ `${JSON.stringify(
605
+ {
606
+ projectRoot: plan.projectRoot,
607
+ changedPaths: plan.changes.map((change) => change.path),
608
+ frameworkRemoved: plan.removeFramework
609
+ },
610
+ null,
611
+ 2
612
+ )}\n`
613
+ )
614
+ return {
615
+ applied: true,
616
+ backupDirectory,
617
+ changedPaths: plan.changes.map((change) => change.path),
618
+ frameworkRemoved: plan.removeFramework
619
+ }
620
+ }
621
+
622
+ function printPlan(plan) {
623
+ process.stdout.write(`프로젝트: ${plan.projectRoot}\n`)
624
+ process.stdout.write(`변경 예정: ${plan.changes.length}개\n`)
625
+ for (const change of plan.changes) process.stdout.write(` - ${change.path}: ${change.reason}\n`)
626
+ process.stdout.write(
627
+ `framework/: ${plan.frameworkExists ? (plan.removeFramework ? '백업 후 삭제 예정' : '보존') : '없음'}\n`
628
+ )
629
+ if (plan.conflicts.length > 0) {
630
+ process.stdout.write(`충돌: ${plan.conflicts.length}개\n`)
631
+ for (const conflict of plan.conflicts) process.stdout.write(` - ${conflict}\n`)
632
+ }
633
+ }
634
+
635
+ function printHelp() {
636
+ process.stdout.write(`Usage: key-screen-migrate [options]\n\n`)
637
+ process.stdout.write(' --project-root <path> migration target (default: cwd)\n')
638
+ process.stdout.write(' --framework-dependency <spec> key-screen-framework version/range\n')
639
+ process.stdout.write(' --apply apply the preflighted plan\n')
640
+ process.stdout.write(' --remove-framework back up and remove framework/ (requires --apply)\n')
641
+ process.stdout.write(' --backup-dir <path> empty backup destination\n')
642
+ process.stdout.write(' --help show this help\n')
643
+ }
644
+
645
+ async function main() {
646
+ const args = parseCliArgs(process.argv.slice(2))
647
+ if (args.help) {
648
+ printHelp()
649
+ return
650
+ }
651
+ const plan = analyzeMigration({
652
+ projectRoot: args['project-root'],
653
+ frameworkDependency: args['framework-dependency'],
654
+ removeFramework: args['remove-framework']
655
+ })
656
+ printPlan(plan)
657
+ if (plan.conflicts.length > 0) {
658
+ process.exitCode = 1
659
+ process.stderr.write('충돌을 해결한 뒤 다시 실행하세요. 파일은 변경하지 않았습니다.\n')
660
+ return
661
+ }
662
+ if (!args.apply) {
663
+ process.stdout.write('Dry-run 완료. 적용하려면 --apply를 추가하세요.\n')
664
+ return
665
+ }
666
+ const result = applyMigration(plan, { backupDirectory: args['backup-dir'] })
667
+ if (!result.applied) {
668
+ process.stdout.write('이미 package consumer 구조입니다. 변경할 내용이 없습니다.\n')
669
+ return
670
+ }
671
+ process.stdout.write(`Migration 완료. Backup: ${result.backupDirectory}\n`)
672
+ }
673
+
674
+ if (isDirectExecution(import.meta.url, process.argv[1])) {
675
+ main().catch((error) => {
676
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)
677
+ process.exitCode = 1
678
+ })
679
+ }