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
package/main/index.js ADDED
@@ -0,0 +1,2003 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { mkdir, appendFile, readdir, rm, stat, readFile, copyFile, writeFile } from "node:fs/promises";
3
+ import { createRequire } from "node:module";
4
+ import { join, dirname, extname, relative, sep, normalize } from "node:path";
5
+ import { Readable } from "node:stream";
6
+ import { fileURLToPath } from "node:url";
7
+ import { app, protocol, ipcMain, shell, BrowserWindow, screen } from "electron";
8
+ import Store from "electron-store";
9
+ import { validateArduinoBoardConfig, defaultArduinoBoardConfig } from "../shared/arduino-board.js";
10
+ import { createScreenCatalog } from "../shared/screen-catalog.js";
11
+ import { RESET_SCREEN_TARGET, buildDefaultGlobalShortcuts, mergeGlobalShortcuts, normalizeShortcutAccelerator } from "../shared/screen-shortcuts.js";
12
+ import { EventEmitter } from "node:events";
13
+ import { spawn } from "node:child_process";
14
+ import { acceleratorToArduinoKeyboardShortcut } from "../shared/arduino-keyboard-shortcut.js";
15
+ import { SerialPort } from "serialport";
16
+ import { Buffer as Buffer$1 } from "node:buffer";
17
+ const now$4 = () => (/* @__PURE__ */ new Date()).toISOString();
18
+ function resolveArduinoCliPaths(app2, options = {}) {
19
+ const platform = options.platform ?? process.platform;
20
+ const arch = options.arch ?? process.arch;
21
+ const resourcesRoot = app2.isPackaged ? join(options.resourcesPath ?? process.resourcesPath, "arduino") : join(app2.getAppPath(), "resources", "arduino", `${platform}-${arch}`);
22
+ return {
23
+ cliPath: join(resourcesRoot, "bin", platform === "win32" ? "arduino-cli.exe" : "arduino-cli"),
24
+ dataDir: join(resourcesRoot, "data"),
25
+ userDir: join(app2.getPath("userData"), "arduino-cli-user"),
26
+ libraryPaths: [
27
+ join(resourcesRoot, "libraries", "KeyescapeSerialProtocolBridge"),
28
+ join(resourcesRoot, "libraries", "Keyboard")
29
+ ]
30
+ };
31
+ }
32
+ function buildArduinoCompileArgs(options) {
33
+ return [
34
+ "compile",
35
+ "--fqbn",
36
+ options.fqbn,
37
+ ...options.libraryPaths.flatMap((libraryPath) => ["--library", libraryPath]),
38
+ options.sketchDir
39
+ ];
40
+ }
41
+ function buildArduinoUploadArgs(options) {
42
+ return [
43
+ "compile",
44
+ "--upload",
45
+ "-p",
46
+ options.portPath,
47
+ "--fqbn",
48
+ options.fqbn,
49
+ ...options.libraryPaths.flatMap((libraryPath) => ["--library", libraryPath]),
50
+ options.sketchDir
51
+ ];
52
+ }
53
+ class ArduinoCliRunner extends EventEmitter {
54
+ constructor(paths, spawnProcess = spawn) {
55
+ super();
56
+ this.paths = paths;
57
+ this.spawnProcess = spawnProcess;
58
+ }
59
+ paths;
60
+ spawnProcess;
61
+ currentProcess = null;
62
+ cancelled = false;
63
+ compileSketch(sketchDir, fqbn) {
64
+ return this.run(buildArduinoCompileArgs({ fqbn, libraryPaths: this.paths.libraryPaths, sketchDir }));
65
+ }
66
+ uploadSketch(sketchDir, fqbn, portPath) {
67
+ return this.run(buildArduinoUploadArgs({ fqbn, libraryPaths: this.paths.libraryPaths, sketchDir, portPath }));
68
+ }
69
+ cancel() {
70
+ this.cancelled = true;
71
+ this.currentProcess?.kill("SIGTERM");
72
+ }
73
+ run(args) {
74
+ if (this.currentProcess) {
75
+ return Promise.reject(new Error("Arduino CLI is already running."));
76
+ }
77
+ this.cancelled = false;
78
+ return new Promise((resolve, reject) => {
79
+ const child = this.spawnProcess(this.paths.cliPath, args, {
80
+ env: {
81
+ ...process.env,
82
+ ARDUINO_DIRECTORIES_DATA: this.paths.dataDir,
83
+ ARDUINO_DIRECTORIES_USER: this.paths.userDir
84
+ }
85
+ });
86
+ this.currentProcess = child;
87
+ child.once("error", (error) => {
88
+ this.currentProcess = null;
89
+ reject(error);
90
+ });
91
+ this.attachLineLogger(child.stdout, "stdout");
92
+ this.attachLineLogger(child.stderr, "stderr");
93
+ child.once("close", (exitCode, signal) => {
94
+ const cancelled = this.cancelled;
95
+ this.currentProcess = null;
96
+ this.cancelled = false;
97
+ resolve({ exitCode, signal, cancelled });
98
+ });
99
+ });
100
+ }
101
+ attachLineLogger(stream, streamName) {
102
+ let buffer = "";
103
+ stream.on("data", (chunk) => {
104
+ buffer += chunk.toString("utf-8").replaceAll("\r", "");
105
+ const lines = buffer.split("\n");
106
+ buffer = lines.pop() ?? "";
107
+ for (const line of lines) {
108
+ this.emit("log", {
109
+ stream: streamName,
110
+ line,
111
+ createdAt: now$4()
112
+ });
113
+ }
114
+ });
115
+ stream.on("end", () => {
116
+ if (!buffer) {
117
+ return;
118
+ }
119
+ this.emit("log", {
120
+ stream: streamName,
121
+ line: buffer,
122
+ createdAt: now$4()
123
+ });
124
+ buffer = "";
125
+ });
126
+ }
127
+ }
128
+ const BOARD_PRESET_ENUM = {
129
+ Generic: "Generic",
130
+ Leonardo: "Leonardo",
131
+ Micro: "Micro",
132
+ ProMicro: "ProMicro",
133
+ Uno: "Uno"
134
+ };
135
+ function generateArduinoSketch(options) {
136
+ const boardConfig = validateArduinoBoardConfig(options.boardConfig);
137
+ const warnings = [];
138
+ const shortcutByTarget = new Map(options.globalShortcuts.map((shortcut) => [shortcut.target, shortcut]));
139
+ const inputPlans = boardConfig.inputs.map((input, index) => {
140
+ if (!boardConfig.keyboardFallbackEnabled) {
141
+ return { input };
142
+ }
143
+ const shortcut = shortcutByTarget.get(input.target);
144
+ if (!shortcut) {
145
+ warnings.push(`No global shortcut found for Arduino input target: ${input.target}`);
146
+ return { input };
147
+ }
148
+ const result = acceleratorToArduinoKeyboardShortcut(shortcut.accelerator);
149
+ if (!result.ok) {
150
+ warnings.push(`${input.target}: ${result.warning}`);
151
+ return { input };
152
+ }
153
+ return {
154
+ input,
155
+ helperName: `shortcut${index}`
156
+ };
157
+ });
158
+ const source = [
159
+ "#include <KeyescapeSerialProtocolBridge.h>",
160
+ "",
161
+ "#if defined(USBCON)",
162
+ "#include <Keyboard.h>",
163
+ "#endif",
164
+ "",
165
+ "using namespace keyescape;",
166
+ "",
167
+ ...buildShortcutHelpers(inputPlans, shortcutByTarget),
168
+ buildInputs(inputPlans),
169
+ "",
170
+ buildOutputs(boardConfig),
171
+ "",
172
+ "KeyescapeSerialProtocolBridge bridge(Serial);",
173
+ "",
174
+ "void setup() {",
175
+ " BridgeConfig config;",
176
+ ` config.boardPreset = BoardPreset::${BOARD_PRESET_ENUM[boardConfig.boardPreset]};`,
177
+ ` config.serialHealthyTimeoutMs = ${boardConfig.serialHealthyTimeoutMs};`,
178
+ ` config.keyboardFallbackEnabled = ${boardConfig.keyboardFallbackEnabled ? "true" : "false"};`,
179
+ " bridge.begin(INPUTS,",
180
+ " sizeof(INPUTS) / sizeof(INPUTS[0]),",
181
+ " OUTPUTS,",
182
+ " sizeof(OUTPUTS) / sizeof(OUTPUTS[0]),",
183
+ " config);",
184
+ "}",
185
+ "",
186
+ "void loop() {",
187
+ " bridge.update();",
188
+ "}",
189
+ ""
190
+ ].join("\n");
191
+ return { source, warnings };
192
+ }
193
+ function buildShortcutHelpers(inputPlans, shortcutByTarget) {
194
+ const helpers = [];
195
+ for (const plan of inputPlans) {
196
+ if (!plan.helperName) {
197
+ continue;
198
+ }
199
+ const shortcut = shortcutByTarget.get(plan.input.target);
200
+ const converted = shortcut ? acceleratorToArduinoKeyboardShortcut(shortcut.accelerator) : void 0;
201
+ if (!converted?.ok) {
202
+ continue;
203
+ }
204
+ helpers.push(
205
+ `static KeyboardShortcut ${plan.helperName}() {`,
206
+ " KeyboardShortcut shortcut;",
207
+ "#if defined(USBCON)",
208
+ ` shortcut.key = ${converted.shortcut.keyLiteral};`,
209
+ ` shortcut.modifierCount = ${converted.shortcut.modifiers.length};`,
210
+ ...converted.shortcut.modifiers.map((modifier, index) => ` shortcut.modifiers[${index}] = ${modifier};`),
211
+ " shortcut.holdMs = 80;",
212
+ "#endif",
213
+ " return shortcut;",
214
+ "}",
215
+ ""
216
+ );
217
+ }
218
+ return helpers;
219
+ }
220
+ function buildInputs(inputPlans) {
221
+ const rows = orderInputPlansForPinMode(inputPlans).map(({ input, helperName }) => {
222
+ const shortcut = helperName ? `${helperName}()` : "KeyboardShortcut()";
223
+ return ` {${input.pin}, ${input.activeLow ? "true" : "false"}, ${input.debounceMs}, "${escapeCString(
224
+ input.target
225
+ )}", ${shortcut}},`;
226
+ });
227
+ return ["static const InputMapping INPUTS[] = {", ...rows, "};"].join("\n");
228
+ }
229
+ function orderInputPlansForPinMode(inputPlans) {
230
+ const ordered = [];
231
+ for (const plan of inputPlans) {
232
+ if (!plan.input.activeLow) {
233
+ const firstActiveLowOnSamePin = ordered.findIndex(
234
+ (orderedPlan) => orderedPlan.input.pin === plan.input.pin && orderedPlan.input.activeLow
235
+ );
236
+ if (firstActiveLowOnSamePin >= 0) {
237
+ ordered.splice(firstActiveLowOnSamePin, 0, plan);
238
+ continue;
239
+ }
240
+ }
241
+ ordered.push(plan);
242
+ }
243
+ return ordered;
244
+ }
245
+ function buildOutputs(boardConfig) {
246
+ const rows = boardConfig.outputs.map(
247
+ (output) => ` {"${escapeCString(output.target)}", "${escapeCString(output.action)}", ${output.pin}, ${output.activeHigh ? "true" : "false"}, ${output.pulseMs}},`
248
+ );
249
+ return ["static const OutputMapping OUTPUTS[] = {", ...rows, "};"].join("\n");
250
+ }
251
+ function escapeCString(value) {
252
+ return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
253
+ }
254
+ function isKey$1(input, key) {
255
+ return input.key?.toLowerCase() === key.toLowerCase() || input.code?.toLowerCase() === `key${key}`.toLowerCase();
256
+ }
257
+ function hasPrimaryModifier$1(input, platform) {
258
+ return platform === "darwin" ? input.meta : input.control;
259
+ }
260
+ function isReloadShortcut(input, platform = process.platform) {
261
+ if (input.type !== "keyDown") {
262
+ return false;
263
+ }
264
+ return Boolean(input.key?.toLowerCase() === "f5" || hasPrimaryModifier$1(input, platform) && isKey$1(input, "r"));
265
+ }
266
+ const SERIAL_BAUD_RATE = 115200;
267
+ const REQUEST_TIMEOUT_MS = 500;
268
+ const REQUEST_RETRY_LIMIT = 3;
269
+ const HEARTBEAT_INTERVAL_MS = 1e4;
270
+ const HEARTBEAT_TIMEOUT_MS = 22e3;
271
+ const knownErrorCodes = /* @__PURE__ */ new Set([
272
+ "UNKNOWN_COMMAND",
273
+ "INVALID_TARGET",
274
+ "INVALID_ACTION",
275
+ "ALREADY_IN_TARGET",
276
+ "BUSY",
277
+ "INTERNAL_ERROR"
278
+ ]);
279
+ function buildOutgoingLine(command) {
280
+ switch (command.type) {
281
+ case "ping":
282
+ return "PING";
283
+ case "atod":
284
+ return `ATOD ${command.target} ${command.action}`;
285
+ }
286
+ }
287
+ function buildResponseLine(response) {
288
+ if (response.ok) {
289
+ return `ACK ${response.target ?? ""}`.trim();
290
+ }
291
+ return `ERR ${response.code ?? "INTERNAL_ERROR"}${response.target ? ` ${response.target}` : ""}`;
292
+ }
293
+ function parseIncomingLine(rawLine) {
294
+ const raw = rawLine.trim();
295
+ if (!raw) {
296
+ return null;
297
+ }
298
+ const [command, arg1, arg2] = raw.split(/\s+/);
299
+ switch (command) {
300
+ case "READY":
301
+ return { type: "ready", raw };
302
+ case "PONG":
303
+ return { type: "pong", raw };
304
+ case "DTOA":
305
+ if (!arg1) {
306
+ return { type: "err", code: "INVALID_TARGET", raw };
307
+ }
308
+ return { type: "dtoa", target: arg1, raw };
309
+ case "ACK":
310
+ if (!arg1) {
311
+ return { type: "err", code: "INVALID_TARGET", raw };
312
+ }
313
+ return { type: "ack", target: arg1, raw };
314
+ case "ERR":
315
+ if (!arg1 || !knownErrorCodes.has(arg1)) {
316
+ return { type: "err", code: "UNKNOWN_COMMAND", raw };
317
+ }
318
+ return {
319
+ type: "err",
320
+ code: arg1,
321
+ target: arg2,
322
+ raw
323
+ };
324
+ default:
325
+ return null;
326
+ }
327
+ }
328
+ const now$3 = () => (/* @__PURE__ */ new Date()).toISOString();
329
+ class DeviceController extends EventEmitter {
330
+ port = null;
331
+ options;
332
+ readBuffer = "";
333
+ heartbeatInterval = null;
334
+ heartbeatTimeout = null;
335
+ writeQueue = Promise.resolve();
336
+ pendingRequest = null;
337
+ state = {
338
+ status: "disconnected",
339
+ availablePorts: [],
340
+ messageLog: [],
341
+ updatedAt: now$3()
342
+ };
343
+ constructor(options) {
344
+ super();
345
+ this.options = options;
346
+ }
347
+ async listPorts() {
348
+ const ports = await SerialPort.list();
349
+ this.state = {
350
+ ...this.state,
351
+ availablePorts: ports.map((port) => ({
352
+ path: port.path,
353
+ manufacturer: port.manufacturer ?? void 0,
354
+ serialNumber: port.serialNumber ?? void 0,
355
+ vendorId: port.vendorId ?? void 0,
356
+ productId: port.productId ?? void 0
357
+ })),
358
+ updatedAt: now$3()
359
+ };
360
+ this.emitState();
361
+ return this.state.availablePorts;
362
+ }
363
+ getState() {
364
+ return this.state;
365
+ }
366
+ logSystemEvent(message) {
367
+ this.state = {
368
+ ...this.state,
369
+ updatedAt: now$3()
370
+ };
371
+ this.pushLog("system", message);
372
+ this.emitState();
373
+ }
374
+ async connect(portPath) {
375
+ await this.disconnect(false);
376
+ await this.listPorts();
377
+ const selectedPort = portPath ?? this.state.availablePorts[0]?.path;
378
+ if (!selectedPort) {
379
+ this.state = {
380
+ ...this.state,
381
+ status: "error",
382
+ lastError: "No serial ports detected.",
383
+ updatedAt: now$3()
384
+ };
385
+ this.pushLog("error", this.state.lastError);
386
+ this.emitState();
387
+ return this.state;
388
+ }
389
+ this.state = {
390
+ ...this.state,
391
+ status: "connecting",
392
+ selectedPortPath: selectedPort,
393
+ lastError: void 0,
394
+ updatedAt: now$3()
395
+ };
396
+ this.emitState();
397
+ await new Promise((resolve, reject) => {
398
+ const port = new SerialPort({
399
+ path: selectedPort,
400
+ baudRate: SERIAL_BAUD_RATE,
401
+ autoOpen: false
402
+ });
403
+ port.open((error) => {
404
+ if (error) {
405
+ reject(error);
406
+ return;
407
+ }
408
+ this.port = port;
409
+ this.attachPortListeners(port);
410
+ resolve();
411
+ });
412
+ }).catch((error) => {
413
+ this.state = {
414
+ ...this.state,
415
+ status: "error",
416
+ lastError: error instanceof Error ? error.message : "Failed to open port.",
417
+ updatedAt: now$3()
418
+ };
419
+ this.pushLog("error", this.state.lastError);
420
+ this.emitState();
421
+ return Promise.reject(error);
422
+ });
423
+ this.state = {
424
+ ...this.state,
425
+ status: "connected",
426
+ lastMessage: `Connected to ${selectedPort}. Waiting for READY/PONG.`,
427
+ updatedAt: now$3()
428
+ };
429
+ this.pushLog("system", this.state.lastMessage);
430
+ this.emitState();
431
+ this.startHeartbeat();
432
+ return this.state;
433
+ }
434
+ async disconnect(emit = true) {
435
+ const selectedPortPath = this.state.selectedPortPath;
436
+ this.stopHeartbeat();
437
+ this.pendingRequest = null;
438
+ this.readBuffer = "";
439
+ if (this.port?.isOpen) {
440
+ await new Promise((resolve) => {
441
+ this.port?.close(() => resolve());
442
+ });
443
+ }
444
+ this.port = null;
445
+ this.state = {
446
+ ...this.state,
447
+ status: "disconnected",
448
+ selectedPortPath,
449
+ lastMessage: "Disconnected from device.",
450
+ updatedAt: now$3()
451
+ };
452
+ this.pushLog("system", this.state.lastMessage);
453
+ if (emit) {
454
+ this.emitState();
455
+ }
456
+ return this.state;
457
+ }
458
+ async send(command) {
459
+ if (!this.port?.isOpen) {
460
+ return {
461
+ ok: false,
462
+ message: "Device is not connected.",
463
+ receivedAt: now$3()
464
+ };
465
+ }
466
+ if (command.type === "ping") {
467
+ await this.writeLine(buildOutgoingLine(command));
468
+ return {
469
+ ok: true,
470
+ message: "Ping sent to Arduino.",
471
+ raw: "PING",
472
+ attempts: 1,
473
+ receivedAt: now$3()
474
+ };
475
+ }
476
+ return this.sendWithRetry(command);
477
+ }
478
+ async sendWithRetry(command) {
479
+ this.pendingRequest = {
480
+ command,
481
+ attempts: 0
482
+ };
483
+ while (this.pendingRequest && this.pendingRequest.attempts < REQUEST_RETRY_LIMIT) {
484
+ this.pendingRequest.attempts += 1;
485
+ const raw = buildOutgoingLine(command);
486
+ await this.writeLine(raw);
487
+ const response = await this.waitForMatchingResponse(command, this.pendingRequest.attempts);
488
+ if (response) {
489
+ this.pendingRequest = null;
490
+ return response;
491
+ }
492
+ }
493
+ this.pendingRequest = null;
494
+ return {
495
+ ok: false,
496
+ message: "Timed out waiting for Arduino response.",
497
+ raw: buildOutgoingLine(command),
498
+ target: command.type === "atod" ? command.target : void 0,
499
+ attempts: REQUEST_RETRY_LIMIT,
500
+ receivedAt: now$3()
501
+ };
502
+ }
503
+ attachPortListeners(port) {
504
+ port.on("data", (chunk) => {
505
+ this.readBuffer += chunk.toString("utf-8").replaceAll("\r", "");
506
+ void this.flushReadBuffer();
507
+ });
508
+ port.on("error", (error) => {
509
+ this.state = {
510
+ ...this.state,
511
+ status: "error",
512
+ lastError: error.message,
513
+ updatedAt: now$3()
514
+ };
515
+ this.pushLog("error", error.message);
516
+ this.emitState();
517
+ });
518
+ port.on("close", () => {
519
+ this.stopHeartbeat();
520
+ this.state = {
521
+ ...this.state,
522
+ status: "disconnected",
523
+ updatedAt: now$3()
524
+ };
525
+ this.emitState();
526
+ });
527
+ }
528
+ emitState() {
529
+ this.emit("state", this.state);
530
+ }
531
+ async flushReadBuffer() {
532
+ const lines = this.readBuffer.split("\n");
533
+ this.readBuffer = lines.pop() ?? "";
534
+ for (const line of lines) {
535
+ await this.handleIncomingLine(line);
536
+ }
537
+ }
538
+ async handleIncomingLine(rawLine) {
539
+ const parsed = parseIncomingLine(rawLine);
540
+ const trimmed = rawLine.trim();
541
+ const logDirection = parsed?.type === "err" ? "error" : "in";
542
+ const shouldSkip = this.shouldSkipMessageLog("in", trimmed);
543
+ this.state = {
544
+ ...this.state,
545
+ lastMessage: this.shouldKeepAsLastMessage(trimmed) ? trimmed : this.state.lastMessage,
546
+ updatedAt: now$3()
547
+ };
548
+ if (!shouldSkip) {
549
+ this.pushLog(logDirection, trimmed, "in");
550
+ } else {
551
+ this.pushRawLog(logDirection, trimmed, "in");
552
+ }
553
+ this.emitState();
554
+ if (!parsed) {
555
+ await this.writeLine(buildResponseLine({ ok: false, code: "UNKNOWN_COMMAND" }));
556
+ return;
557
+ }
558
+ switch (parsed.type) {
559
+ case "ready":
560
+ case "pong":
561
+ this.markHandshake(parsed.raw);
562
+ return;
563
+ case "dtoa": {
564
+ const response = await this.options.onDtoa(parsed.target, parsed.raw);
565
+ await this.writeLine(buildResponseLine(response));
566
+ return;
567
+ }
568
+ case "ack":
569
+ case "err":
570
+ this.emit("protocol-response", parsed);
571
+ return;
572
+ }
573
+ }
574
+ markHandshake(message) {
575
+ this.state = {
576
+ ...this.state,
577
+ status: "connected",
578
+ lastMessage: this.shouldKeepAsLastMessage(message) ? message : this.state.lastMessage,
579
+ lastHandshakeAt: now$3(),
580
+ updatedAt: now$3()
581
+ };
582
+ this.emitState();
583
+ this.refreshHeartbeatTimeout();
584
+ if (message === "READY") {
585
+ void this.sendHeartbeatPing();
586
+ }
587
+ }
588
+ startHeartbeat() {
589
+ this.stopHeartbeat();
590
+ void this.sendHeartbeatPing();
591
+ this.heartbeatInterval = setInterval(() => {
592
+ void this.sendHeartbeatPing();
593
+ }, HEARTBEAT_INTERVAL_MS);
594
+ this.refreshHeartbeatTimeout();
595
+ }
596
+ async sendHeartbeatPing() {
597
+ if (!this.port?.isOpen) {
598
+ return;
599
+ }
600
+ try {
601
+ await this.writeLine("PING");
602
+ } catch (error) {
603
+ const message = error instanceof Error ? error.message : "Failed to send heartbeat ping.";
604
+ this.state = {
605
+ ...this.state,
606
+ status: "error",
607
+ lastError: message,
608
+ updatedAt: now$3()
609
+ };
610
+ this.pushLog("error", message, "system");
611
+ this.emitState();
612
+ }
613
+ }
614
+ stopHeartbeat() {
615
+ if (this.heartbeatInterval) {
616
+ clearInterval(this.heartbeatInterval);
617
+ this.heartbeatInterval = null;
618
+ }
619
+ if (this.heartbeatTimeout) {
620
+ clearTimeout(this.heartbeatTimeout);
621
+ this.heartbeatTimeout = null;
622
+ }
623
+ }
624
+ refreshHeartbeatTimeout() {
625
+ if (this.heartbeatTimeout) {
626
+ clearTimeout(this.heartbeatTimeout);
627
+ }
628
+ this.heartbeatTimeout = setTimeout(() => {
629
+ if (!this.port?.isOpen) {
630
+ return;
631
+ }
632
+ this.state = {
633
+ ...this.state,
634
+ status: "error",
635
+ lastError: "Heartbeat timeout: no READY/PONG received.",
636
+ lastHandshakeAt: void 0,
637
+ updatedAt: now$3()
638
+ };
639
+ this.pushLog("error", this.state.lastError, "system");
640
+ this.emitState();
641
+ }, HEARTBEAT_TIMEOUT_MS);
642
+ }
643
+ async waitForMatchingResponse(command, attempts) {
644
+ return new Promise((resolve) => {
645
+ const timeout = setTimeout(() => {
646
+ this.off("protocol-response", onResponse);
647
+ resolve(null);
648
+ }, REQUEST_TIMEOUT_MS);
649
+ const onResponse = (response) => {
650
+ if (response.type === "ack" && command.type === "atod" && response.target === command.target) {
651
+ clearTimeout(timeout);
652
+ this.off("protocol-response", onResponse);
653
+ resolve({
654
+ ok: true,
655
+ message: `Arduino acknowledged target ${response.target}.`,
656
+ raw: response.raw,
657
+ target: response.target,
658
+ attempts,
659
+ receivedAt: now$3()
660
+ });
661
+ return;
662
+ }
663
+ if (response.type === "err" && command.type === "atod" && response.target === command.target) {
664
+ clearTimeout(timeout);
665
+ this.off("protocol-response", onResponse);
666
+ resolve({
667
+ ok: false,
668
+ message: `Arduino rejected target ${command.target} with ${response.code}.`,
669
+ raw: response.raw,
670
+ code: response.code,
671
+ target: response.target,
672
+ attempts,
673
+ receivedAt: now$3()
674
+ });
675
+ }
676
+ };
677
+ this.on("protocol-response", onResponse);
678
+ });
679
+ }
680
+ async writeLine(line) {
681
+ if (!this.port?.isOpen) {
682
+ return;
683
+ }
684
+ const logDirection = line.trim().startsWith("ERR ") ? "error" : "out";
685
+ const shouldSkip = this.shouldSkipMessageLog("out", line);
686
+ this.state = {
687
+ ...this.state,
688
+ lastMessage: this.shouldKeepAsLastMessage(line) ? line : this.state.lastMessage,
689
+ updatedAt: now$3()
690
+ };
691
+ if (!shouldSkip) {
692
+ this.pushLog(logDirection, line, "out");
693
+ } else {
694
+ this.pushRawLog(logDirection, line, "out");
695
+ }
696
+ this.emitState();
697
+ const writePromise = this.writeQueue.then(
698
+ () => new Promise((resolve, reject) => {
699
+ this.port?.write(`${line}
700
+ `, (error) => {
701
+ if (error) {
702
+ reject(error);
703
+ return;
704
+ }
705
+ this.port?.drain((drainError) => {
706
+ if (drainError) {
707
+ reject(drainError);
708
+ return;
709
+ }
710
+ resolve();
711
+ });
712
+ });
713
+ })
714
+ );
715
+ this.writeQueue = writePromise.catch(() => void 0);
716
+ await writePromise;
717
+ }
718
+ pushLog(direction, raw, origin) {
719
+ if (!raw) {
720
+ return;
721
+ }
722
+ const entry = {
723
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
724
+ direction,
725
+ origin: origin ?? (direction === "out" ? "out" : direction === "system" ? "system" : "in"),
726
+ raw,
727
+ createdAt: now$3()
728
+ };
729
+ this.state = {
730
+ ...this.state,
731
+ messageLog: [entry, ...this.state.messageLog].slice(0, 50)
732
+ };
733
+ this.emit("log", entry);
734
+ this.emit("raw-log", entry);
735
+ }
736
+ pushRawLog(direction, raw, origin) {
737
+ if (!raw) {
738
+ return;
739
+ }
740
+ const entry = {
741
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
742
+ direction,
743
+ origin: origin ?? (direction === "out" ? "out" : direction === "system" ? "system" : "in"),
744
+ raw,
745
+ createdAt: now$3()
746
+ };
747
+ this.emit("raw-log", entry);
748
+ }
749
+ shouldSkipMessageLog(direction, raw) {
750
+ const trimmed = raw.trim();
751
+ if (direction === "out" && trimmed === "PING") {
752
+ return true;
753
+ }
754
+ if (direction === "in" && trimmed === "PONG") {
755
+ return true;
756
+ }
757
+ return false;
758
+ }
759
+ shouldKeepAsLastMessage(raw) {
760
+ const trimmed = raw.trim();
761
+ return trimmed !== "PING" && trimmed !== "PONG";
762
+ }
763
+ }
764
+ function getDateKey(createdAt) {
765
+ const date = new Date(createdAt);
766
+ if (Number.isNaN(date.getTime())) {
767
+ return "unknown-date";
768
+ }
769
+ const year = date.getFullYear();
770
+ const month = String(date.getMonth() + 1).padStart(2, "0");
771
+ const day = String(date.getDate()).padStart(2, "0");
772
+ return `${year}-${month}-${day}`;
773
+ }
774
+ const RAW_LOG_DIRECTORY = "device-raw";
775
+ const LEGACY_LOG_DIRECTORY = "device";
776
+ const DEFAULT_RAW_LOG_MAX_BYTES = 10 * 1024 * 1024;
777
+ const DEFAULT_RAW_LOG_RETENTION_DAYS = 30;
778
+ function formatSegment(segment) {
779
+ return String(segment).padStart(3, "0");
780
+ }
781
+ function parseRawLogSegment(fileName, dateKey) {
782
+ const match = new RegExp(`^${dateKey.replaceAll("-", "\\-")}\\.(\\d{3})\\.jsonl$`).exec(fileName);
783
+ if (!match) {
784
+ return null;
785
+ }
786
+ return Number.parseInt(match[1], 10);
787
+ }
788
+ async function readEntriesFromFile(filePath) {
789
+ const raw = await readFile(filePath, "utf8").catch(() => "");
790
+ if (!raw) {
791
+ return [];
792
+ }
793
+ return raw.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => {
794
+ try {
795
+ return JSON.parse(line);
796
+ } catch {
797
+ return null;
798
+ }
799
+ }).filter((entry) => entry !== null);
800
+ }
801
+ class DeviceLogWriter {
802
+ constructor(logsRootDir, options = {}) {
803
+ this.logsRootDir = logsRootDir;
804
+ this.rawLogMaxBytes = options.rawLogMaxBytes ?? DEFAULT_RAW_LOG_MAX_BYTES;
805
+ this.rawLogRetentionDays = options.rawLogRetentionDays ?? DEFAULT_RAW_LOG_RETENTION_DAYS;
806
+ }
807
+ logsRootDir;
808
+ writeQueue = Promise.resolve();
809
+ rawLogMaxBytes;
810
+ rawLogRetentionDays;
811
+ write(entry) {
812
+ this.writeQueue = this.writeQueue.then(async () => {
813
+ await this.pruneExpiredRawLogs(entry.createdAt);
814
+ const dateKey = getDateKey(entry.createdAt);
815
+ const payload = `${JSON.stringify(entry)}
816
+ `;
817
+ const filePath = await this.resolveWritableRawLogPath(dateKey, Buffer.byteLength(payload, "utf8"));
818
+ await mkdir(dirname(filePath), { recursive: true });
819
+ await appendFile(filePath, payload, "utf8");
820
+ }).catch(() => void 0);
821
+ }
822
+ async listArchives() {
823
+ const dateKeys = /* @__PURE__ */ new Set();
824
+ for (const directoryName of [RAW_LOG_DIRECTORY, LEGACY_LOG_DIRECTORY]) {
825
+ const directory = join(this.logsRootDir, directoryName);
826
+ const files = await readdir(directory, { withFileTypes: true }).catch(() => []);
827
+ for (const file of files) {
828
+ if (!file.isFile() || !file.name.endsWith(".jsonl")) continue;
829
+ const baseName = file.name.replace(/\.jsonl$/, "");
830
+ const matchedDateKey = /^(\d{4}-\d{2}-\d{2})(?:\.\d{3})?$/.exec(baseName)?.[1];
831
+ if (matchedDateKey) {
832
+ dateKeys.add(matchedDateKey);
833
+ }
834
+ }
835
+ }
836
+ const archives = await Promise.all(
837
+ Array.from(dateKeys).map(async (dateKey) => ({
838
+ dateKey,
839
+ entryCount: (await this.readArchive(dateKey)).length
840
+ }))
841
+ );
842
+ return archives.sort((a, b) => b.dateKey.localeCompare(a.dateKey));
843
+ }
844
+ async readArchive(dateKey) {
845
+ const rawDirectory = join(this.logsRootDir, RAW_LOG_DIRECTORY);
846
+ const rawFiles = await readdir(rawDirectory, { withFileTypes: true }).catch(() => []);
847
+ const segmentedFiles = rawFiles.filter((file) => file.isFile()).map((file) => ({
848
+ name: file.name,
849
+ segment: parseRawLogSegment(file.name, dateKey)
850
+ })).filter((file) => file.segment !== null).sort((a, b) => a.segment - b.segment);
851
+ const rawEntries = (await Promise.all(
852
+ segmentedFiles.map((file) => readEntriesFromFile(join(rawDirectory, file.name)))
853
+ )).flat();
854
+ if (rawEntries.length > 0) {
855
+ return rawEntries.reverse();
856
+ }
857
+ return readEntriesFromFile(join(this.logsRootDir, LEGACY_LOG_DIRECTORY, `${dateKey}.jsonl`)).then(
858
+ (entries) => entries.reverse()
859
+ );
860
+ }
861
+ async pruneExpiredRawLogs(referenceCreatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
862
+ if (this.rawLogRetentionDays <= 0) {
863
+ return;
864
+ }
865
+ const directory = join(this.logsRootDir, RAW_LOG_DIRECTORY);
866
+ const files = await readdir(directory, { withFileTypes: true }).catch(() => []);
867
+ const referenceDate = new Date(referenceCreatedAt);
868
+ if (Number.isNaN(referenceDate.getTime())) {
869
+ return;
870
+ }
871
+ const cutoff = new Date(referenceDate);
872
+ cutoff.setHours(0, 0, 0, 0);
873
+ cutoff.setDate(cutoff.getDate() - this.rawLogRetentionDays);
874
+ await Promise.all(
875
+ files.filter((file) => file.isFile() && file.name.endsWith(".jsonl")).map(async (file) => {
876
+ const baseName = file.name.replace(/\.jsonl$/, "");
877
+ const dateKey = /^(\d{4}-\d{2}-\d{2})(?:\.\d{3})?$/.exec(baseName)?.[1];
878
+ if (!dateKey) return;
879
+ const fileDate = /* @__PURE__ */ new Date(`${dateKey}T00:00:00.000Z`);
880
+ if (Number.isNaN(fileDate.getTime())) return;
881
+ if (fileDate >= cutoff) return;
882
+ await rm(join(directory, file.name), { force: true });
883
+ })
884
+ );
885
+ }
886
+ async resolveWritableRawLogPath(dateKey, payloadBytes) {
887
+ const directory = join(this.logsRootDir, RAW_LOG_DIRECTORY);
888
+ await mkdir(directory, { recursive: true });
889
+ const files = await readdir(directory, { withFileTypes: true }).catch(() => []);
890
+ const segments = files.filter((file) => file.isFile()).map((file) => parseRawLogSegment(file.name, dateKey)).filter((segment) => segment !== null).sort((a, b) => a - b);
891
+ const currentSegment = segments.at(-1) ?? 1;
892
+ const currentFilePath = join(directory, `${dateKey}.${formatSegment(currentSegment)}.jsonl`);
893
+ const currentSize = await stat(currentFilePath).then((result) => result.size).catch(() => 0);
894
+ if (currentSize > 0 && currentSize + payloadBytes > this.rawLogMaxBytes) {
895
+ const nextSegment = currentSegment + 1;
896
+ return join(directory, `${dateKey}.${formatSegment(nextSegment)}.jsonl`);
897
+ }
898
+ return currentFilePath;
899
+ }
900
+ }
901
+ const now$2 = () => (/* @__PURE__ */ new Date()).toISOString();
902
+ class ScreenTransitionCommand {
903
+ target;
904
+ constructor(screen2) {
905
+ this.target = screen2.id;
906
+ }
907
+ async execute(context) {
908
+ const currentTarget = context.gameSession.getState().currentStepId;
909
+ if (currentTarget === this.target) {
910
+ return {
911
+ ok: false,
912
+ code: "ALREADY_IN_TARGET",
913
+ message: `App is already in target ${this.target}.`,
914
+ target: this.target,
915
+ receivedAt: now$2()
916
+ };
917
+ }
918
+ context.gameSession.moveToTarget(this.target);
919
+ return {
920
+ ok: true,
921
+ message: `App moved to target ${this.target}.`,
922
+ target: this.target,
923
+ receivedAt: now$2()
924
+ };
925
+ }
926
+ }
927
+ class ResetScreenCommand {
928
+ target = RESET_SCREEN_TARGET;
929
+ async execute(context) {
930
+ context.gameSession.reset();
931
+ return {
932
+ ok: true,
933
+ message: "App reset to admin screen.",
934
+ target: this.target,
935
+ receivedAt: now$2()
936
+ };
937
+ }
938
+ }
939
+ class DtoaDispatcher {
940
+ constructor(context) {
941
+ this.context = context;
942
+ this.screenCatalog = context.screenCatalog;
943
+ for (const screen2 of this.screenCatalog.screenDefinitions) {
944
+ this.commands.set(screen2.id, new ScreenTransitionCommand(screen2));
945
+ }
946
+ this.commands.set(RESET_SCREEN_TARGET, new ResetScreenCommand());
947
+ }
948
+ context;
949
+ commands = /* @__PURE__ */ new Map();
950
+ screenCatalog;
951
+ getAvailableScreens() {
952
+ return this.screenCatalog.screenDefinitions.map((screen2) => ({ ...screen2 }));
953
+ }
954
+ hasScreenTarget(target) {
955
+ return this.commands.has(target);
956
+ }
957
+ async dispatch(target) {
958
+ const command = this.commands.get(target);
959
+ if (!command) {
960
+ return {
961
+ ok: false,
962
+ code: "INVALID_TARGET",
963
+ message: `Unknown DTOA target ${target}.`,
964
+ target,
965
+ receivedAt: now$2()
966
+ };
967
+ }
968
+ try {
969
+ return await command.execute(this.context);
970
+ } catch {
971
+ return {
972
+ ok: false,
973
+ code: "INTERNAL_ERROR",
974
+ message: `Failed to execute DTOA target ${target}.`,
975
+ target,
976
+ receivedAt: now$2()
977
+ };
978
+ }
979
+ }
980
+ }
981
+ const now$1 = () => (/* @__PURE__ */ new Date()).toISOString();
982
+ async function handleDtoa(target, raw, options) {
983
+ if (options.dtoaDispatcher.hasScreenTarget(target)) {
984
+ return options.dtoaDispatcher.dispatch(target);
985
+ }
986
+ if (!options.deviceSignalTargets.has(target)) {
987
+ return {
988
+ ok: false,
989
+ code: "INVALID_TARGET",
990
+ message: `Unknown DTOA target ${target}.`,
991
+ raw,
992
+ target,
993
+ receivedAt: now$1()
994
+ };
995
+ }
996
+ const signal = {
997
+ type: "dtoa",
998
+ target,
999
+ raw,
1000
+ receivedAt: now$1()
1001
+ };
1002
+ options.broadcastDeviceSignal(signal);
1003
+ return {
1004
+ ok: true,
1005
+ message: `Device signal ${target} was delivered to renderer.`,
1006
+ raw,
1007
+ target,
1008
+ receivedAt: signal.receivedAt
1009
+ };
1010
+ }
1011
+ const now = () => (/* @__PURE__ */ new Date()).toISOString();
1012
+ class GameSession extends EventEmitter {
1013
+ constructor(screenCatalog) {
1014
+ super();
1015
+ this.screenCatalog = screenCatalog;
1016
+ this.state = {
1017
+ mode: "idle",
1018
+ currentStepId: screenCatalog.getInitialScreenDefinition().id,
1019
+ updatedAt: now()
1020
+ };
1021
+ }
1022
+ screenCatalog;
1023
+ state;
1024
+ getState() {
1025
+ return this.state;
1026
+ }
1027
+ start() {
1028
+ this.state = {
1029
+ mode: "running",
1030
+ startedAt: this.state.startedAt ?? now(),
1031
+ currentStepId: this.screenCatalog.getFirstSceneScreenDefinition().id,
1032
+ updatedAt: now()
1033
+ };
1034
+ this.emit("state", this.state);
1035
+ return this.state;
1036
+ }
1037
+ reset() {
1038
+ this.state = {
1039
+ mode: "idle",
1040
+ currentStepId: this.screenCatalog.getInitialScreenDefinition().id,
1041
+ updatedAt: now()
1042
+ };
1043
+ this.emit("state", this.state);
1044
+ return this.state;
1045
+ }
1046
+ moveToTarget(target) {
1047
+ this.state = {
1048
+ ...this.state,
1049
+ mode: this.state.mode === "idle" ? "running" : this.state.mode,
1050
+ currentStepId: target,
1051
+ updatedAt: now()
1052
+ };
1053
+ this.emit("state", this.state);
1054
+ return this.state;
1055
+ }
1056
+ }
1057
+ function isKey(input, key) {
1058
+ return input.key?.toLowerCase() === key.toLowerCase() || input.code?.toLowerCase() === `key${key}`.toLowerCase();
1059
+ }
1060
+ function hasPrimaryModifier(input, platform) {
1061
+ return platform === "darwin" ? input.meta : input.control;
1062
+ }
1063
+ function isKioskQuitShortcut(input, platform = process.platform) {
1064
+ return Boolean(input.alt && input.shift && hasPrimaryModifier(input, platform) && isKey(input, "x"));
1065
+ }
1066
+ function isBlockedKioskShortcut(input, platform = process.platform) {
1067
+ if (isKioskQuitShortcut(input, platform)) {
1068
+ return false;
1069
+ }
1070
+ if (platform === "win32" && input.meta) {
1071
+ return true;
1072
+ }
1073
+ if (platform === "darwin") {
1074
+ return Boolean(input.meta && ["q", "w", "m"].some((key) => isKey(input, key)));
1075
+ }
1076
+ return Boolean(input.alt && input.key?.toLowerCase() === "f4");
1077
+ }
1078
+ const MEDIA_TYPES = ["image", "video", "audio", "font"];
1079
+ const MEDIA_EXTENSION_BY_TYPE = {
1080
+ image: /* @__PURE__ */ new Set([".apng", ".avif", ".gif", ".jpeg", ".jpg", ".png", ".webp"]),
1081
+ video: /* @__PURE__ */ new Set([".m4v", ".mov", ".mp4", ".ogg", ".ogv", ".webm"]),
1082
+ audio: /* @__PURE__ */ new Set([".aac", ".flac", ".m4a", ".mp3", ".oga", ".ogg", ".wav", ".weba"]),
1083
+ font: /* @__PURE__ */ new Set([".otf", ".ttf", ".woff", ".woff2"])
1084
+ };
1085
+ function assertMediaType(type) {
1086
+ if (!MEDIA_TYPES.includes(type)) {
1087
+ throw new Error(`Unsupported media type: ${type}`);
1088
+ }
1089
+ }
1090
+ function assertSafeAssetName(name) {
1091
+ if (!name || name.includes("/") || name.includes("\\") || name !== normalize(name)) {
1092
+ throw new Error("Media asset name must be a file name without path separators.");
1093
+ }
1094
+ }
1095
+ function isInsideDirectory(rootPath, targetPath) {
1096
+ const pathFromRoot = relative(rootPath, targetPath);
1097
+ return pathFromRoot === "" || !pathFromRoot.startsWith("..") && !pathFromRoot.startsWith(sep);
1098
+ }
1099
+ function toMediaUrl(type, name) {
1100
+ return `media://${type}/${encodeURIComponent(name)}`;
1101
+ }
1102
+ class MediaManager {
1103
+ constructor(rootPath) {
1104
+ this.rootPath = rootPath;
1105
+ }
1106
+ rootPath;
1107
+ getRootPath() {
1108
+ return this.rootPath;
1109
+ }
1110
+ async ensureDirectories() {
1111
+ await Promise.all(MEDIA_TYPES.map((type) => mkdir(join(this.rootPath, type), { recursive: true })));
1112
+ }
1113
+ async seedFrom(sourceRootPath) {
1114
+ await this.ensureDirectories();
1115
+ await Promise.all(
1116
+ MEDIA_TYPES.map(async (type) => {
1117
+ const sourceDirectory = join(sourceRootPath, type);
1118
+ const files = await readdir(sourceDirectory, { withFileTypes: true }).catch(() => []);
1119
+ await Promise.all(
1120
+ files.filter((file) => file.isFile()).filter((file) => MEDIA_EXTENSION_BY_TYPE[type].has(extname(file.name).toLowerCase())).map(async (file) => {
1121
+ const sourcePath = join(sourceDirectory, file.name);
1122
+ const destinationPath = join(this.rootPath, type, file.name);
1123
+ if (!isInsideDirectory(sourceRootPath, sourcePath)) {
1124
+ return;
1125
+ }
1126
+ if (!isInsideDirectory(this.rootPath, destinationPath)) {
1127
+ return;
1128
+ }
1129
+ const existingDestination = await stat(destinationPath).catch(() => null);
1130
+ if (existingDestination) {
1131
+ return;
1132
+ }
1133
+ await mkdir(dirname(destinationPath), { recursive: true });
1134
+ await copyFile(sourcePath, destinationPath);
1135
+ })
1136
+ );
1137
+ })
1138
+ );
1139
+ }
1140
+ async listLibrary() {
1141
+ await this.ensureDirectories();
1142
+ const assets = (await Promise.all(MEDIA_TYPES.map((type) => this.listAssetsForType(type)))).flat();
1143
+ return {
1144
+ rootPath: this.rootPath,
1145
+ assets: assets.sort(
1146
+ (left, right) => left.type === right.type ? left.name.localeCompare(right.name) : MEDIA_TYPES.indexOf(left.type) - MEDIA_TYPES.indexOf(right.type)
1147
+ )
1148
+ };
1149
+ }
1150
+ resolveMediaPath(ref) {
1151
+ assertMediaType(ref.type);
1152
+ assertSafeAssetName(ref.name);
1153
+ const extension = extname(ref.name).toLowerCase();
1154
+ if (!MEDIA_EXTENSION_BY_TYPE[ref.type].has(extension)) {
1155
+ throw new Error(`Unsupported media extension for ${ref.type}: ${extension || "(none)"}`);
1156
+ }
1157
+ const mediaPath = join(this.rootPath, ref.type, ref.name);
1158
+ if (!isInsideDirectory(this.rootPath, mediaPath)) {
1159
+ throw new Error("Media path is outside of the media root.");
1160
+ }
1161
+ return mediaPath;
1162
+ }
1163
+ resolveMediaUrl(ref) {
1164
+ this.resolveMediaPath(ref);
1165
+ return toMediaUrl(ref.type, ref.name);
1166
+ }
1167
+ async listAssetsForType(type) {
1168
+ const directory = join(this.rootPath, type);
1169
+ const files = await readdir(directory, { withFileTypes: true }).catch(() => []);
1170
+ const assets = await Promise.all(
1171
+ files.filter((file) => file.isFile()).filter((file) => MEDIA_EXTENSION_BY_TYPE[type].has(extname(file.name).toLowerCase())).map(async (file) => {
1172
+ const filePath = join(directory, file.name);
1173
+ if (!isInsideDirectory(this.rootPath, filePath)) {
1174
+ return null;
1175
+ }
1176
+ const fileStat = await stat(filePath).catch(() => null);
1177
+ if (!fileStat) {
1178
+ return null;
1179
+ }
1180
+ return {
1181
+ name: file.name,
1182
+ type,
1183
+ relativePath: `${type}/${file.name}`,
1184
+ url: toMediaUrl(type, file.name),
1185
+ sizeBytes: fileStat.size,
1186
+ updatedAt: fileStat.mtime.toISOString()
1187
+ };
1188
+ })
1189
+ );
1190
+ return assets.filter((asset) => asset !== null);
1191
+ }
1192
+ }
1193
+ function parseByteRange(rangeHeader, sizeBytes) {
1194
+ if (!rangeHeader) {
1195
+ return null;
1196
+ }
1197
+ const match = /^bytes=(\d*)-(\d*)$/.exec(rangeHeader.trim());
1198
+ if (!match) {
1199
+ return null;
1200
+ }
1201
+ const [, rawStart, rawEnd] = match;
1202
+ if (!rawStart && !rawEnd) {
1203
+ return null;
1204
+ }
1205
+ if (!rawStart) {
1206
+ const suffixLength = Number.parseInt(rawEnd, 10);
1207
+ if (!Number.isFinite(suffixLength) || suffixLength <= 0) {
1208
+ return null;
1209
+ }
1210
+ return {
1211
+ start: Math.max(sizeBytes - suffixLength, 0),
1212
+ end: sizeBytes - 1
1213
+ };
1214
+ }
1215
+ const start = Number.parseInt(rawStart, 10);
1216
+ const requestedEnd = rawEnd ? Number.parseInt(rawEnd, 10) : sizeBytes - 1;
1217
+ if (!Number.isFinite(start) || !Number.isFinite(requestedEnd) || start < 0 || requestedEnd < start || start >= sizeBytes) {
1218
+ return null;
1219
+ }
1220
+ return {
1221
+ start,
1222
+ end: Math.min(requestedEnd, sizeBytes - 1)
1223
+ };
1224
+ }
1225
+ function getEnvWindowModeOverride(env) {
1226
+ if (env.KEYESCAPE_KIOSK === "1") {
1227
+ return "kiosk";
1228
+ }
1229
+ return void 0;
1230
+ }
1231
+ function resolveInitialWindowMode(options) {
1232
+ const envOverride = getEnvWindowModeOverride(options.env);
1233
+ if (envOverride) {
1234
+ return envOverride;
1235
+ }
1236
+ if (options.savedMode) {
1237
+ return options.savedMode;
1238
+ }
1239
+ return options.isDev ? "windowed" : "fullscreen";
1240
+ }
1241
+ function applyWindowMode(window, mode, options = {}) {
1242
+ const isWindowed = mode === "windowed";
1243
+ const isKiosk = mode === "kiosk";
1244
+ const canRestore = "restore" in window && typeof window.restore === "function";
1245
+ const canUnmaximize = "unmaximize" in window && typeof window.unmaximize === "function";
1246
+ const canMoveTop = "moveTop" in window && typeof window.moveTop === "function";
1247
+ const canFocus = "focus" in window && typeof window.focus === "function";
1248
+ window.setMinimumSize(isWindowed ? 1200 : 0, isWindowed ? 760 : 0);
1249
+ window.setResizable(isWindowed);
1250
+ window.setMinimizable(isWindowed);
1251
+ window.setMaximizable(isWindowed);
1252
+ window.setMovable(isWindowed);
1253
+ window.setFullScreenable(true);
1254
+ if (isKiosk) {
1255
+ if (canUnmaximize) {
1256
+ window.unmaximize();
1257
+ }
1258
+ window.setSkipTaskbar(true);
1259
+ if (options.kioskBounds) {
1260
+ window.setBounds(options.kioskBounds, false);
1261
+ }
1262
+ window.setKiosk(true);
1263
+ window.setFullScreen(true);
1264
+ window.setAlwaysOnTop(true, "screen-saver");
1265
+ if (canMoveTop) {
1266
+ window.moveTop();
1267
+ }
1268
+ if (canFocus) {
1269
+ window.focus();
1270
+ }
1271
+ return;
1272
+ }
1273
+ window.setKiosk(false);
1274
+ window.setSkipTaskbar(false);
1275
+ window.setAlwaysOnTop(false);
1276
+ if (isWindowed) {
1277
+ window.setFullScreen(false);
1278
+ if (canRestore) {
1279
+ window.restore();
1280
+ }
1281
+ if (canUnmaximize) {
1282
+ window.unmaximize();
1283
+ }
1284
+ return;
1285
+ }
1286
+ if (mode === "fullscreen") {
1287
+ window.setFullScreen(true);
1288
+ }
1289
+ }
1290
+ const WINDOWS_KEY_BLOCKER_SCRIPT = String.raw`
1291
+ $signature = @"
1292
+ using System;
1293
+ using System.Diagnostics;
1294
+ using System.Runtime.InteropServices;
1295
+ using System.Windows.Forms;
1296
+
1297
+ public static class KioskWindowsKeyBlocker {
1298
+ private const int WH_KEYBOARD_LL = 13;
1299
+ private const int WM_KEYDOWN = 0x0100;
1300
+ private const int WM_KEYUP = 0x0101;
1301
+ private const int WM_SYSKEYDOWN = 0x0104;
1302
+ private const int WM_SYSKEYUP = 0x0105;
1303
+ private const int VK_LWIN = 0x5B;
1304
+ private const int VK_RWIN = 0x5C;
1305
+
1306
+ private static LowLevelKeyboardProc proc = HookCallback;
1307
+ private static IntPtr hookId = IntPtr.Zero;
1308
+
1309
+ public static void Run() {
1310
+ hookId = SetHook(proc);
1311
+ Application.Run(new ApplicationContext());
1312
+ UnhookWindowsHookEx(hookId);
1313
+ }
1314
+
1315
+ private static IntPtr SetHook(LowLevelKeyboardProc proc) {
1316
+ using (Process currentProcess = Process.GetCurrentProcess())
1317
+ using (ProcessModule currentModule = currentProcess.MainModule) {
1318
+ return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(currentModule.ModuleName), 0);
1319
+ }
1320
+ }
1321
+
1322
+ private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
1323
+
1324
+ private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
1325
+ if (nCode >= 0 && IsKeyboardMessage(wParam)) {
1326
+ int vkCode = Marshal.ReadInt32(lParam);
1327
+ if (vkCode == VK_LWIN || vkCode == VK_RWIN) {
1328
+ return (IntPtr)1;
1329
+ }
1330
+ }
1331
+
1332
+ return CallNextHookEx(hookId, nCode, wParam, lParam);
1333
+ }
1334
+
1335
+ private static bool IsKeyboardMessage(IntPtr wParam) {
1336
+ int message = wParam.ToInt32();
1337
+ return message == WM_KEYDOWN || message == WM_KEYUP || message == WM_SYSKEYDOWN || message == WM_SYSKEYUP;
1338
+ }
1339
+
1340
+ [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
1341
+ private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
1342
+
1343
+ [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
1344
+ [return: MarshalAs(UnmanagedType.Bool)]
1345
+ private static extern bool UnhookWindowsHookEx(IntPtr hhk);
1346
+
1347
+ [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
1348
+ private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
1349
+
1350
+ [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
1351
+ private static extern IntPtr GetModuleHandle(string lpModuleName);
1352
+ }
1353
+ "@
1354
+
1355
+ Add-Type -TypeDefinition $signature -ReferencedAssemblies System.Windows.Forms
1356
+ [KioskWindowsKeyBlocker]::Run()
1357
+ `;
1358
+ let lockProcess = null;
1359
+ function createWindowsKeyBlockerArgs(script = WINDOWS_KEY_BLOCKER_SCRIPT) {
1360
+ const encodedCommand = Buffer$1.from(script, "utf16le").toString("base64");
1361
+ return ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encodedCommand];
1362
+ }
1363
+ function startWindowsKeyLock(platform = process.platform) {
1364
+ if (platform !== "win32") {
1365
+ return false;
1366
+ }
1367
+ if (lockProcess && !lockProcess.killed) {
1368
+ return true;
1369
+ }
1370
+ const child = spawn("powershell.exe", createWindowsKeyBlockerArgs(), {
1371
+ stdio: "ignore",
1372
+ windowsHide: true
1373
+ });
1374
+ lockProcess = child;
1375
+ child.once("exit", () => {
1376
+ lockProcess = null;
1377
+ });
1378
+ child.once("error", () => {
1379
+ lockProcess = null;
1380
+ });
1381
+ return true;
1382
+ }
1383
+ function stopWindowsKeyLock() {
1384
+ if (!lockProcess) {
1385
+ return;
1386
+ }
1387
+ lockProcess.kill();
1388
+ lockProcess = null;
1389
+ }
1390
+ function resolveMainRuntimePaths(overrides, context) {
1391
+ const defaultMediaRoot = context.isPackaged ? join(context.resourcesPath, "default-media") : context.isDev ? join(context.appPath, "media") : join(context.mainDirectory, "../default-media");
1392
+ return {
1393
+ preload: overrides?.preload ?? join(context.mainDirectory, "../preload/index.mjs"),
1394
+ rendererHtml: overrides?.rendererHtml ?? join(context.mainDirectory, "../renderer/index.html"),
1395
+ defaultMediaRoot: overrides?.defaultMediaRoot ?? defaultMediaRoot
1396
+ };
1397
+ }
1398
+ const requireMainDependency = createRequire(import.meta.url);
1399
+ function startKeyScreenMain(options) {
1400
+ const log = requireMainDependency("electron-log/main");
1401
+ const screenCatalog = createScreenCatalog(options.screenDefinitions);
1402
+ const defaultGlobalShortcuts = buildDefaultGlobalShortcuts(screenCatalog.screenDefinitions);
1403
+ const deviceSignalTargets = new Set(options.deviceSignalTargets);
1404
+ const store = new Store();
1405
+ const gameSession = new GameSession(screenCatalog);
1406
+ const dtoaDispatcher = new DtoaDispatcher({ gameSession, screenCatalog });
1407
+ let arduinoCliRunner = null;
1408
+ const deviceController = new DeviceController({
1409
+ onDtoa: async (target, raw) => handleDtoa(target, raw, {
1410
+ dtoaDispatcher,
1411
+ deviceSignalTargets,
1412
+ broadcastDeviceSignal
1413
+ })
1414
+ });
1415
+ let mainWindow = null;
1416
+ let currentWindowMode = "windowed";
1417
+ let allowKioskQuit = false;
1418
+ let activeArduinoBuild = null;
1419
+ let arduinoLogSequence = 0;
1420
+ let arduinoBuildStatus = {
1421
+ phase: "idle",
1422
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1423
+ };
1424
+ const isDev = Boolean(process.env.ELECTRON_RENDERER_URL);
1425
+ const runtimePaths = resolveMainRuntimePaths(options.runtimePaths, {
1426
+ mainDirectory: dirname(fileURLToPath(import.meta.url)),
1427
+ appPath: app.getAppPath(),
1428
+ resourcesPath: process.resourcesPath,
1429
+ isPackaged: app.isPackaged,
1430
+ isDev
1431
+ });
1432
+ log.initialize();
1433
+ app.commandLine.appendSwitch("autoplay-policy", "no-user-gesture-required");
1434
+ protocol.registerSchemesAsPrivileged([
1435
+ {
1436
+ scheme: "media",
1437
+ privileges: {
1438
+ bypassCSP: false,
1439
+ corsEnabled: false,
1440
+ secure: true,
1441
+ standard: true,
1442
+ stream: true,
1443
+ supportFetchAPI: true
1444
+ }
1445
+ }
1446
+ ]);
1447
+ app.on("before-quit", () => {
1448
+ allowKioskQuit = true;
1449
+ stopWindowsKeyLock();
1450
+ });
1451
+ function getPositiveIntegerEnv(name, fallback) {
1452
+ const raw = process.env[name];
1453
+ if (!raw) {
1454
+ return fallback;
1455
+ }
1456
+ const parsed = Number.parseInt(raw, 10);
1457
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
1458
+ }
1459
+ function broadcastDeviceState(state) {
1460
+ if (state.status === "connected" && state.selectedPortPath) {
1461
+ store.set("lastPortPath", state.selectedPortPath);
1462
+ }
1463
+ mainWindow?.webContents.send("device:state", state);
1464
+ }
1465
+ async function tryAutoReconnect() {
1466
+ const lastPortPath = store.get("lastPortPath");
1467
+ if (!lastPortPath) {
1468
+ return;
1469
+ }
1470
+ try {
1471
+ await deviceController.connect(lastPortPath);
1472
+ } catch (error) {
1473
+ log.warn("[device] auto reconnect failed", {
1474
+ portPath: lastPortPath,
1475
+ error: error instanceof Error ? error.message : error
1476
+ });
1477
+ }
1478
+ }
1479
+ function broadcastGameState() {
1480
+ mainWindow?.webContents.send("game:state", gameSession.getState());
1481
+ }
1482
+ function broadcastDeviceSignal(signal) {
1483
+ mainWindow?.webContents.send("device:signal", signal);
1484
+ }
1485
+ function broadcastArduinoLog(entry) {
1486
+ const logEntry = {
1487
+ id: `${Date.now()}-${arduinoLogSequence++}`,
1488
+ ...entry
1489
+ };
1490
+ mainWindow?.webContents.send("arduino:log", logEntry);
1491
+ }
1492
+ function setArduinoBuildStatus(status) {
1493
+ arduinoBuildStatus = {
1494
+ ...arduinoBuildStatus,
1495
+ ...status,
1496
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1497
+ };
1498
+ mainWindow?.webContents.send("arduino:status", arduinoBuildStatus);
1499
+ return arduinoBuildStatus;
1500
+ }
1501
+ function getGlobalShortcuts() {
1502
+ return mergeGlobalShortcuts(store.get("globalShortcuts") ?? [], defaultGlobalShortcuts);
1503
+ }
1504
+ function getArduinoBoardConfig() {
1505
+ return validateArduinoBoardConfig(store.get("arduinoBoardConfig") ?? defaultArduinoBoardConfig());
1506
+ }
1507
+ function getSavedWindowMode() {
1508
+ return store.get("windowMode");
1509
+ }
1510
+ function hasWindowModeEnvOverride() {
1511
+ return getEnvWindowModeOverride(process.env) !== void 0;
1512
+ }
1513
+ function getCurrentWindowMode() {
1514
+ return currentWindowMode;
1515
+ }
1516
+ function normalizeGlobalShortcuts(shortcuts, availableScreenIds) {
1517
+ return shortcuts.map((shortcut) => {
1518
+ const accelerator = normalizeShortcutAccelerator(shortcut.accelerator.trim());
1519
+ const target = shortcut.target.trim();
1520
+ if (!accelerator) {
1521
+ throw new Error("Shortcut accelerator is required.");
1522
+ }
1523
+ if (!availableScreenIds.has(target)) {
1524
+ throw new Error(`Shortcut target does not exist: ${target}`);
1525
+ }
1526
+ return {
1527
+ accelerator,
1528
+ target
1529
+ };
1530
+ });
1531
+ }
1532
+ function persistWindowMode(mode) {
1533
+ store.set("windowMode", mode);
1534
+ }
1535
+ function parseMediaProtocolUrl(rawUrl) {
1536
+ const url = new URL(rawUrl);
1537
+ const type = url.hostname;
1538
+ const name = decodeURIComponent(url.pathname.replace(/^\/+/, ""));
1539
+ return { type, name };
1540
+ }
1541
+ function getMediaContentType(fileName) {
1542
+ const extension = extname(fileName).toLowerCase();
1543
+ if (extension === ".mp4" || extension === ".m4v") return "video/mp4";
1544
+ if (extension === ".mov") return "video/quicktime";
1545
+ if (extension === ".webm") return "video/webm";
1546
+ if (extension === ".ogg" || extension === ".ogv") return "video/ogg";
1547
+ if (extension === ".mp3") return "audio/mpeg";
1548
+ if (extension === ".wav") return "audio/wav";
1549
+ if (extension === ".m4a") return "audio/mp4";
1550
+ if (extension === ".aac") return "audio/aac";
1551
+ if (extension === ".flac") return "audio/flac";
1552
+ if (extension === ".png") return "image/png";
1553
+ if (extension === ".jpg" || extension === ".jpeg") return "image/jpeg";
1554
+ if (extension === ".webp") return "image/webp";
1555
+ if (extension === ".gif") return "image/gif";
1556
+ if (extension === ".avif") return "image/avif";
1557
+ if (extension === ".woff2") return "font/woff2";
1558
+ if (extension === ".woff") return "font/woff";
1559
+ if (extension === ".ttf") return "font/ttf";
1560
+ if (extension === ".otf") return "font/otf";
1561
+ return "application/octet-stream";
1562
+ }
1563
+ async function createMediaProtocolResponse(mediaManager, request) {
1564
+ const ref = parseMediaProtocolUrl(request.url);
1565
+ const filePath = mediaManager.resolveMediaPath(ref);
1566
+ const fileStat = await stat(filePath);
1567
+ if (!fileStat.isFile()) {
1568
+ return new Response("Media asset not found.", { status: 404 });
1569
+ }
1570
+ const headers = new Headers({
1571
+ "Accept-Ranges": "bytes",
1572
+ "Content-Type": getMediaContentType(ref.name)
1573
+ });
1574
+ const range = parseByteRange(request.headers.get("range"), fileStat.size);
1575
+ if (request.headers.has("range") && !range) {
1576
+ headers.set("Content-Range", `bytes */${fileStat.size}`);
1577
+ return new Response(null, { status: 416, headers });
1578
+ }
1579
+ if (range) {
1580
+ headers.set("Content-Length", String(range.end - range.start + 1));
1581
+ headers.set("Content-Range", `bytes ${range.start}-${range.end}/${fileStat.size}`);
1582
+ return new Response(Readable.toWeb(createReadStream(filePath, range)), {
1583
+ status: 206,
1584
+ headers
1585
+ });
1586
+ }
1587
+ headers.set("Content-Length", String(fileStat.size));
1588
+ return new Response(Readable.toWeb(createReadStream(filePath)), {
1589
+ status: 200,
1590
+ headers
1591
+ });
1592
+ }
1593
+ async function writeGeneratedArduinoSketch(source) {
1594
+ const sketchDir = join(app.getPath("userData"), "arduino-generated", "device-bridge");
1595
+ await mkdir(sketchDir, { recursive: true });
1596
+ await writeFile(join(sketchDir, "device-bridge.ino"), source, "utf-8");
1597
+ return sketchDir;
1598
+ }
1599
+ async function sleep(ms) {
1600
+ await new Promise((resolve) => setTimeout(resolve, ms));
1601
+ }
1602
+ async function runArduinoBuild(action, portPath) {
1603
+ if (!arduinoCliRunner) {
1604
+ throw new Error("Arduino CLI runner is not initialized.");
1605
+ }
1606
+ const startedAt = Date.now();
1607
+ const warnings = [];
1608
+ let previousPortPath;
1609
+ let shouldReconnect = false;
1610
+ let exitCode = null;
1611
+ let cancelled = false;
1612
+ let errorMessage;
1613
+ setArduinoBuildStatus({
1614
+ phase: "generating",
1615
+ action,
1616
+ startedAt: new Date(startedAt).toISOString(),
1617
+ lastResult: void 0
1618
+ });
1619
+ try {
1620
+ broadcastArduinoLog({
1621
+ stream: "system",
1622
+ line: "Arduino sketch generation started.",
1623
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1624
+ });
1625
+ const boardConfig = getArduinoBoardConfig();
1626
+ const preview = generateArduinoSketch({
1627
+ boardConfig,
1628
+ globalShortcuts: getGlobalShortcuts()
1629
+ });
1630
+ warnings.push(...preview.warnings);
1631
+ const sketchDir = await writeGeneratedArduinoSketch(preview.source);
1632
+ if (action === "upload") {
1633
+ const deviceState = deviceController.getState();
1634
+ previousPortPath = deviceState.status === "connected" ? deviceState.selectedPortPath : void 0;
1635
+ shouldReconnect = Boolean(previousPortPath);
1636
+ const uploadPortPath = portPath ?? previousPortPath;
1637
+ if (!uploadPortPath) {
1638
+ throw new Error("Arduino upload requires a serial port.");
1639
+ }
1640
+ if (shouldReconnect) {
1641
+ await deviceController.disconnect();
1642
+ }
1643
+ setArduinoBuildStatus({ phase: "uploading" });
1644
+ broadcastArduinoLog({
1645
+ stream: "system",
1646
+ line: `Arduino upload started on ${uploadPortPath}.`,
1647
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1648
+ });
1649
+ const result = await arduinoCliRunner.uploadSketch(sketchDir, boardConfig.fqbn, uploadPortPath);
1650
+ exitCode = result.exitCode;
1651
+ cancelled = result.cancelled;
1652
+ } else {
1653
+ setArduinoBuildStatus({ phase: "compiling" });
1654
+ broadcastArduinoLog({ stream: "system", line: "Arduino compile started.", createdAt: (/* @__PURE__ */ new Date()).toISOString() });
1655
+ const result = await arduinoCliRunner.compileSketch(sketchDir, boardConfig.fqbn);
1656
+ exitCode = result.exitCode;
1657
+ cancelled = result.cancelled;
1658
+ }
1659
+ } catch (error) {
1660
+ errorMessage = error instanceof Error ? error.message : "Arduino build failed.";
1661
+ } finally {
1662
+ if (shouldReconnect && previousPortPath) {
1663
+ setArduinoBuildStatus({ phase: "reconnecting-device" });
1664
+ await sleep(1500);
1665
+ await deviceController.listPorts();
1666
+ const portExists = deviceController.getState().availablePorts.some((port) => port.path === previousPortPath);
1667
+ if (portExists) {
1668
+ try {
1669
+ await deviceController.connect(previousPortPath);
1670
+ } catch (error) {
1671
+ warnings.push(
1672
+ error instanceof Error ? `Arduino upload succeeded but device reconnect failed: ${error.message}` : "Arduino upload succeeded but device reconnect failed."
1673
+ );
1674
+ }
1675
+ } else {
1676
+ warnings.push("Arduino upload finished but the previous port was not found. Manual reconnect may be required.");
1677
+ }
1678
+ }
1679
+ }
1680
+ if (errorMessage) {
1681
+ const result = {
1682
+ ok: false,
1683
+ action,
1684
+ exitCode: null,
1685
+ message: errorMessage,
1686
+ warnings,
1687
+ durationMs: Date.now() - startedAt,
1688
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
1689
+ };
1690
+ setArduinoBuildStatus({ phase: "error", lastResult: result });
1691
+ return result;
1692
+ }
1693
+ return buildArduinoResult(action, exitCode, cancelled, warnings, startedAt);
1694
+ }
1695
+ function buildArduinoResult(action, exitCode, cancelled, warnings, startedAt) {
1696
+ const ok = !cancelled && exitCode === 0;
1697
+ const result = {
1698
+ ok,
1699
+ action,
1700
+ exitCode,
1701
+ message: cancelled ? "Arduino build was cancelled." : ok ? `Arduino ${action} completed successfully.` : `Arduino ${action} failed with exit code ${exitCode ?? "unknown"}.`,
1702
+ warnings,
1703
+ durationMs: Date.now() - startedAt,
1704
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
1705
+ };
1706
+ setArduinoBuildStatus({ phase: cancelled ? "cancelled" : ok ? "success" : "error", lastResult: result });
1707
+ return result;
1708
+ }
1709
+ async function runExclusiveArduinoBuild(action, portPath) {
1710
+ if (activeArduinoBuild) {
1711
+ throw new Error("Arduino build is already running.");
1712
+ }
1713
+ activeArduinoBuild = runArduinoBuild(action, portPath);
1714
+ try {
1715
+ return await activeArduinoBuild;
1716
+ } finally {
1717
+ activeArduinoBuild = null;
1718
+ }
1719
+ }
1720
+ function applyCurrentWindowMode() {
1721
+ if (!mainWindow) {
1722
+ return;
1723
+ }
1724
+ applyWindowMode(mainWindow, currentWindowMode, {
1725
+ kioskBounds: screen.getDisplayMatching(mainWindow.getBounds()).bounds
1726
+ });
1727
+ }
1728
+ function enforceKioskWindowMode() {
1729
+ if (!mainWindow || currentWindowMode !== "kiosk") {
1730
+ return;
1731
+ }
1732
+ applyCurrentWindowMode();
1733
+ mainWindow.show();
1734
+ mainWindow.focus();
1735
+ }
1736
+ function scheduleKioskWindowModeEnforcement() {
1737
+ if (currentWindowMode !== "kiosk") {
1738
+ return;
1739
+ }
1740
+ for (const delayMs of [50, 250, 1e3, 2500]) {
1741
+ setTimeout(enforceKioskWindowMode, delayMs);
1742
+ }
1743
+ }
1744
+ function syncWindowsKeyLockToWindowMode() {
1745
+ if (currentWindowMode === "kiosk") {
1746
+ startWindowsKeyLock();
1747
+ return;
1748
+ }
1749
+ stopWindowsKeyLock();
1750
+ }
1751
+ function setWindowMode(mode) {
1752
+ if (!mainWindow) {
1753
+ currentWindowMode = mode;
1754
+ syncWindowsKeyLockToWindowMode();
1755
+ persistWindowMode(mode);
1756
+ return currentWindowMode;
1757
+ }
1758
+ currentWindowMode = mode;
1759
+ syncWindowsKeyLockToWindowMode();
1760
+ applyCurrentWindowMode();
1761
+ scheduleKioskWindowModeEnforcement();
1762
+ persistWindowMode(mode);
1763
+ return currentWindowMode;
1764
+ }
1765
+ async function getPerformanceSnapshot() {
1766
+ const processMemory = await process.getProcessMemoryInfo();
1767
+ return {
1768
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
1769
+ appVersion: app.getVersion(),
1770
+ platform: process.platform,
1771
+ arch: process.arch,
1772
+ processMemory: {
1773
+ privateKb: processMemory.private,
1774
+ residentSetKb: processMemory.residentSet,
1775
+ sharedKb: processMemory.shared
1776
+ },
1777
+ appMetrics: app.getAppMetrics().map((metric) => ({
1778
+ pid: metric.pid,
1779
+ type: metric.type,
1780
+ name: metric.name,
1781
+ cpuPercent: metric.cpu.percentCPUUsage,
1782
+ memoryWorkingSetKb: metric.memory.workingSetSize
1783
+ }))
1784
+ };
1785
+ }
1786
+ function createWindow() {
1787
+ const initialWindowMode = resolveInitialWindowMode({
1788
+ env: process.env,
1789
+ isDev,
1790
+ savedMode: getSavedWindowMode()
1791
+ });
1792
+ currentWindowMode = initialWindowMode;
1793
+ mainWindow = new BrowserWindow({
1794
+ width: 1440,
1795
+ height: 960,
1796
+ minWidth: 1200,
1797
+ minHeight: 760,
1798
+ show: false,
1799
+ autoHideMenuBar: true,
1800
+ fullscreen: initialWindowMode !== "windowed",
1801
+ kiosk: initialWindowMode === "kiosk",
1802
+ resizable: initialWindowMode === "windowed",
1803
+ minimizable: initialWindowMode === "windowed",
1804
+ maximizable: initialWindowMode === "windowed",
1805
+ movable: initialWindowMode === "windowed",
1806
+ fullscreenable: initialWindowMode !== "windowed",
1807
+ backgroundColor: "#07111f",
1808
+ webPreferences: {
1809
+ preload: runtimePaths.preload,
1810
+ contextIsolation: true,
1811
+ sandbox: false
1812
+ }
1813
+ });
1814
+ if (!isDev && process.platform === "win32") {
1815
+ mainWindow.setMenu(null);
1816
+ mainWindow.setMenuBarVisibility(false);
1817
+ }
1818
+ mainWindow.on("ready-to-show", () => {
1819
+ applyCurrentWindowMode();
1820
+ mainWindow?.show();
1821
+ scheduleKioskWindowModeEnforcement();
1822
+ });
1823
+ mainWindow.on("close", (event) => {
1824
+ if (currentWindowMode === "kiosk" && !allowKioskQuit) {
1825
+ event.preventDefault();
1826
+ }
1827
+ });
1828
+ mainWindow.webContents.on("before-input-event", (event, input) => {
1829
+ if (!isDev && isReloadShortcut(input)) {
1830
+ event.preventDefault();
1831
+ return;
1832
+ }
1833
+ if (currentWindowMode !== "kiosk" || input.type !== "keyDown") {
1834
+ return;
1835
+ }
1836
+ if (isKioskQuitShortcut(input)) {
1837
+ event.preventDefault();
1838
+ allowKioskQuit = true;
1839
+ app.quit();
1840
+ return;
1841
+ }
1842
+ if (isBlockedKioskShortcut(input)) {
1843
+ event.preventDefault();
1844
+ }
1845
+ });
1846
+ if (isDev && process.env.ELECTRON_RENDERER_URL) {
1847
+ mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL);
1848
+ } else {
1849
+ mainWindow.loadFile(runtimePaths.rendererHtml);
1850
+ }
1851
+ }
1852
+ app.whenReady().then(async () => {
1853
+ const mediaManager = new MediaManager(join(app.getPath("userData"), "media"));
1854
+ await mediaManager.ensureDirectories();
1855
+ await mediaManager.seedFrom(runtimePaths.defaultMediaRoot);
1856
+ protocol.handle("media", async (request) => {
1857
+ try {
1858
+ return await createMediaProtocolResponse(mediaManager, request);
1859
+ } catch (error) {
1860
+ log.warn("[media] blocked media request", {
1861
+ url: request.url,
1862
+ error: error instanceof Error ? error.message : error
1863
+ });
1864
+ return new Response("Media asset not found.", { status: 404 });
1865
+ }
1866
+ });
1867
+ createWindow();
1868
+ syncWindowsKeyLockToWindowMode();
1869
+ arduinoCliRunner = new ArduinoCliRunner(resolveArduinoCliPaths(app));
1870
+ arduinoCliRunner.on("log", (entry) => {
1871
+ broadcastArduinoLog(entry);
1872
+ });
1873
+ const deviceLogWriter = new DeviceLogWriter(app.getPath("logs"), {
1874
+ rawLogMaxBytes: getPositiveIntegerEnv("DEVICE_LOG_MAX_BYTES", 10 * 1024 * 1024),
1875
+ rawLogRetentionDays: getPositiveIntegerEnv("DEVICE_LOG_RETENTION_DAYS", 30)
1876
+ });
1877
+ await deviceLogWriter.pruneExpiredRawLogs();
1878
+ deviceController.on("state", (state) => {
1879
+ log.info("[device]", state);
1880
+ broadcastDeviceState(state);
1881
+ });
1882
+ deviceController.on("raw-log", (entry) => {
1883
+ deviceLogWriter.write({
1884
+ ...entry,
1885
+ selectedPortPath: deviceController.getState().selectedPortPath,
1886
+ status: deviceController.getState().status
1887
+ });
1888
+ });
1889
+ gameSession.on("state", () => {
1890
+ log.info("[game]", gameSession.getState());
1891
+ broadcastGameState();
1892
+ });
1893
+ ipcMain.handle("device:listPorts", async () => deviceController.listPorts());
1894
+ ipcMain.handle("device:getState", async () => deviceController.getState());
1895
+ ipcMain.handle("device:listLogArchives", async () => deviceLogWriter.listArchives());
1896
+ ipcMain.handle("device:getLogArchive", async (_event, dateKey) => deviceLogWriter.readArchive(dateKey));
1897
+ ipcMain.handle("device:connect", async (_event, portPath) => {
1898
+ const preferredPort = portPath ?? store.get("lastPortPath");
1899
+ return deviceController.connect(preferredPort);
1900
+ });
1901
+ ipcMain.handle("device:disconnect", async () => deviceController.disconnect());
1902
+ ipcMain.handle("device:send", async (_event, command) => deviceController.send(command));
1903
+ ipcMain.handle("game:getState", async () => gameSession.getState());
1904
+ ipcMain.handle("game:getAvailableScreens", async () => dtoaDispatcher.getAvailableScreens());
1905
+ ipcMain.handle("media:getLibrary", async () => mediaManager.listLibrary());
1906
+ ipcMain.handle("media:resolveUrl", async (_event, ref) => mediaManager.resolveMediaUrl(ref));
1907
+ ipcMain.handle("media:openFolder", async () => {
1908
+ await mediaManager.ensureDirectories();
1909
+ const path = mediaManager.getRootPath();
1910
+ const message = await shell.openPath(path);
1911
+ return {
1912
+ ok: message === "",
1913
+ path,
1914
+ message: message || void 0
1915
+ };
1916
+ });
1917
+ ipcMain.handle("app:getPerformanceSnapshot", async () => getPerformanceSnapshot());
1918
+ ipcMain.on("app:quit", () => {
1919
+ allowKioskQuit = true;
1920
+ app.quit();
1921
+ });
1922
+ ipcMain.handle("game:getGlobalShortcuts", async () => getGlobalShortcuts());
1923
+ ipcMain.handle("game:getDeviceSignalTargets", async () => [...deviceSignalTargets]);
1924
+ ipcMain.handle("game:updateGlobalShortcuts", async (_event, shortcuts) => {
1925
+ const availableScreenIds = new Set(dtoaDispatcher.getAvailableScreens().map((screen2) => screen2.id));
1926
+ const normalizedShortcuts = normalizeGlobalShortcuts(shortcuts, availableScreenIds);
1927
+ store.set(
1928
+ "globalShortcuts",
1929
+ normalizedShortcuts.filter(
1930
+ (shortcut) => !defaultGlobalShortcuts.some(
1931
+ (defaultShortcut) => defaultShortcut.accelerator === shortcut.accelerator && defaultShortcut.target === shortcut.target
1932
+ )
1933
+ )
1934
+ );
1935
+ return getGlobalShortcuts();
1936
+ });
1937
+ ipcMain.handle("arduino:getBoardConfig", async () => getArduinoBoardConfig());
1938
+ ipcMain.handle("arduino:updateBoardConfig", async (_event, config) => {
1939
+ const normalizedConfig = validateArduinoBoardConfig(config);
1940
+ store.set("arduinoBoardConfig", normalizedConfig);
1941
+ return getArduinoBoardConfig();
1942
+ });
1943
+ ipcMain.handle(
1944
+ "arduino:previewSketch",
1945
+ async () => generateArduinoSketch({
1946
+ boardConfig: getArduinoBoardConfig(),
1947
+ globalShortcuts: getGlobalShortcuts()
1948
+ })
1949
+ );
1950
+ ipcMain.handle("arduino:compile", async () => runExclusiveArduinoBuild("compile"));
1951
+ ipcMain.handle("arduino:upload", async (_event, portPath) => runExclusiveArduinoBuild("upload", portPath));
1952
+ ipcMain.handle("arduino:getStatus", async () => arduinoBuildStatus);
1953
+ ipcMain.on("arduino:cancel", () => {
1954
+ arduinoCliRunner?.cancel();
1955
+ });
1956
+ ipcMain.handle("game:getWindowMode", async () => getCurrentWindowMode());
1957
+ ipcMain.handle("game:isWindowModeLocked", async () => hasWindowModeEnvOverride());
1958
+ ipcMain.handle("game:setWindowMode", async (_event, mode) => {
1959
+ if (hasWindowModeEnvOverride()) {
1960
+ return getCurrentWindowMode();
1961
+ }
1962
+ return setWindowMode(mode);
1963
+ });
1964
+ ipcMain.handle("game:moveToScreen", async (_event, target) => {
1965
+ const response = await dtoaDispatcher.dispatch(target);
1966
+ return response.ok ? gameSession.getState() : Promise.reject(new Error(response.message));
1967
+ });
1968
+ ipcMain.on("preload:log", (_event, entry) => {
1969
+ const prefix = `[preload:${entry.phase}]`;
1970
+ const payload = {
1971
+ screenId: entry.screenId,
1972
+ componentKey: entry.componentKey,
1973
+ message: entry.message
1974
+ };
1975
+ if (entry.phase === "error") {
1976
+ console.error(prefix, payload);
1977
+ log.error(prefix, payload);
1978
+ return;
1979
+ }
1980
+ console.info(prefix, payload);
1981
+ log.info(prefix, payload);
1982
+ });
1983
+ ipcMain.on("shortcut:log", (_event, entry) => {
1984
+ deviceController.logSystemEvent(`단축키 ${entry.accelerator} → ${entry.target} 화면 전환`);
1985
+ });
1986
+ await deviceController.listPorts();
1987
+ await tryAutoReconnect();
1988
+ broadcastGameState();
1989
+ app.on("activate", () => {
1990
+ if (BrowserWindow.getAllWindows().length === 0) {
1991
+ createWindow();
1992
+ }
1993
+ });
1994
+ });
1995
+ app.on("window-all-closed", () => {
1996
+ if (process.platform !== "darwin") {
1997
+ app.quit();
1998
+ }
1999
+ });
2000
+ }
2001
+ export {
2002
+ startKeyScreenMain
2003
+ };