@djodjonx/x32-simulator 0.0.6 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -1,10 +1,188 @@
1
1
  #!/usr/bin/env node
2
- import { a as ConsoleLogger, i as UdpNetworkGateway, n as SchemaFactory, o as LogLevel, r as OscCodec, s as InMemoryStateRepository, t as SchemaRegistry, u as SimulationService } from "./SchemaRegistry-D4eIJord.mjs";
2
+ import { _ as oscToText, a as ConsoleLogger, b as DEFAULT_FIRMWARE, c as InMemoryStateRepository, i as UdpNetworkGateway, m as parseMeterMode, n as SchemaFactory, o as LogLevel, r as OscCodec, s as parseLogLevel, t as SchemaRegistry, u as SimulationService, v as textToOsc, y as DEFAULT_CONFIG } from "./SchemaRegistry-ffv4HZRa.mjs";
3
3
  import * as readline from "node:readline";
4
4
  import * as fs from "node:fs";
5
+ import { constants } from "node:fs";
5
6
  import * as path from "node:path";
7
+ import { randomBytes } from "node:crypto";
8
+ import { access, readFile, rename, rm, writeFile } from "node:fs/promises";
6
9
 
10
+ //#region src/infrastructure/repositories/JsonFileStateRepository.ts
11
+ /**
12
+ * JSON file-based state repository.
13
+ * Persists state to a JSON file on disk.
14
+ * Supports auto-save and manual flush.
15
+ */
16
+ var JsonFileStateRepository = class {
17
+ state = /* @__PURE__ */ new Map();
18
+ dirty = false;
19
+ autoSaveTimer = null;
20
+ saving = false;
21
+ /**
22
+ * Creates a new JSON file repository.
23
+ * @param filePath - Path to the JSON file.
24
+ * @param autoSaveInterval - Auto-save interval in ms (0 = disabled).
25
+ */
26
+ constructor(filePath, autoSaveInterval = 5e3) {
27
+ this.filePath = filePath;
28
+ this.autoSaveInterval = autoSaveInterval;
29
+ if (this.autoSaveInterval > 0) this.startAutoSave();
30
+ }
31
+ /**
32
+ * Starts the auto-save timer.
33
+ */
34
+ startAutoSave() {
35
+ this.autoSaveTimer = setInterval(async () => {
36
+ if (this.dirty && !this.saving) await this.flush();
37
+ }, this.autoSaveInterval);
38
+ this.autoSaveTimer.unref();
39
+ }
40
+ /**
41
+ * Stops the auto-save timer.
42
+ */
43
+ stopAutoSave() {
44
+ if (this.autoSaveTimer) {
45
+ clearInterval(this.autoSaveTimer);
46
+ this.autoSaveTimer = null;
47
+ }
48
+ }
49
+ /**
50
+ * Checks if the file exists.
51
+ */
52
+ async fileExists() {
53
+ try {
54
+ await access(this.filePath, constants.F_OK);
55
+ return true;
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+ /**
61
+ * Loads state from JSON file.
62
+ */
63
+ async load() {
64
+ if (await this.fileExists()) try {
65
+ const content = await readFile(this.filePath, "utf-8");
66
+ const data = JSON.parse(content);
67
+ this.state.clear();
68
+ for (const [key, value] of Object.entries(data)) this.state.set(key, value);
69
+ this.dirty = false;
70
+ return data;
71
+ } catch (error) {
72
+ console.error(`[JsonFileStateRepository] Failed to load state from ${this.filePath}:`, error);
73
+ return {};
74
+ }
75
+ return {};
76
+ }
77
+ /**
78
+ * Saves complete state to JSON file.
79
+ */
80
+ async save(state) {
81
+ this.state.clear();
82
+ for (const [key, value] of Object.entries(state)) this.state.set(key, value);
83
+ this.dirty = true;
84
+ await this.flush();
85
+ }
86
+ /**
87
+ * Gets a single value.
88
+ */
89
+ get(address) {
90
+ return this.state.get(address);
91
+ }
92
+ /**
93
+ * Sets a single value and marks as dirty.
94
+ */
95
+ set(address, value) {
96
+ this.state.set(address, value);
97
+ this.dirty = true;
98
+ }
99
+ /**
100
+ * Gets all entries.
101
+ */
102
+ getAll() {
103
+ const result = {};
104
+ this.state.forEach((value, key) => {
105
+ result[key] = value;
106
+ });
107
+ return result;
108
+ }
109
+ /**
110
+ * Resets state to defaults and marks as dirty.
111
+ */
112
+ reset(defaults) {
113
+ this.state.clear();
114
+ for (const [key, value] of Object.entries(defaults)) this.state.set(key, value);
115
+ this.dirty = true;
116
+ }
117
+ /**
118
+ * Writes state to JSON file if dirty.
119
+ */
120
+ async flush() {
121
+ if (!this.dirty || this.saving) return;
122
+ this.saving = true;
123
+ const tmpPath = `${this.filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
124
+ try {
125
+ const data = this.getAll();
126
+ await writeFile(tmpPath, JSON.stringify(data, null, 2), "utf-8");
127
+ await rename(tmpPath, this.filePath);
128
+ this.dirty = false;
129
+ } catch (error) {
130
+ await rm(tmpPath, { force: true });
131
+ console.error(`[JsonFileStateRepository] Failed to save state to ${this.filePath}:`, error);
132
+ } finally {
133
+ this.saving = false;
134
+ }
135
+ }
136
+ /**
137
+ * Cleanup: stop auto-save and flush pending changes.
138
+ */
139
+ async dispose() {
140
+ this.stopAutoSave();
141
+ await this.flush();
142
+ }
143
+ };
144
+
145
+ //#endregion
146
+ //#region src/infrastructure/repositories/StateRepositoryFactory.ts
147
+ /**
148
+ * Creates a state repository based on configuration.
149
+ * @param config - Repository configuration.
150
+ * @returns The configured state repository.
151
+ */
152
+ function createStateRepository(config) {
153
+ switch (config.type) {
154
+ case "json":
155
+ if (!config.filePath) throw new Error("JSON repository requires a filePath");
156
+ return new JsonFileStateRepository(config.filePath, config.autoSaveInterval ?? 5e3);
157
+ case "memory":
158
+ default: return new InMemoryStateRepository();
159
+ }
160
+ }
161
+
162
+ //#endregion
7
163
  //#region src/presentation/cli/server.ts
164
+ const CONSOLE_MODELS = new Set([
165
+ "X32",
166
+ "X32RACK",
167
+ "X32C",
168
+ "X32P",
169
+ "X32CORE",
170
+ "M32",
171
+ "M32C",
172
+ "M32R"
173
+ ]);
174
+ const MODEL_LIST = "X32, X32RACK, X32C, X32P, X32CORE, M32, M32C, or M32R";
175
+ const FIRMWARE_PATTERN = /^\d+\.\d+$/;
176
+ const IPV4_OCTET = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)";
177
+ const IPV4_PATTERN = /* @__PURE__ */ new RegExp(`^${IPV4_OCTET}(?:\\.${IPV4_OCTET}){3}$`);
178
+ const fail = (message) => {
179
+ throw new Error(message);
180
+ };
181
+ const readOption = (args, index, flag) => {
182
+ const next = args[index + 1];
183
+ if (next === void 0 || next.startsWith("-")) fail(`Missing value for ${flag}.`);
184
+ return next;
185
+ };
8
186
  const loadEnv = () => {
9
187
  try {
10
188
  const envPath = path.resolve(process.cwd(), ".env");
@@ -25,6 +203,15 @@ const parseArgs = (argv) => {
25
203
  const args = argv.slice(2);
26
204
  let cliPort;
27
205
  let cliHost;
206
+ let storageType = "memory";
207
+ let stateFilePath;
208
+ let cliName;
209
+ let cliModel;
210
+ let cliFirmware;
211
+ let cliAdvertiseIp;
212
+ let cliLogLevel;
213
+ let cliPermissive = false;
214
+ let cliMeterMode;
28
215
  for (let i = 0; i < args.length; i++) {
29
216
  const arg = args[i];
30
217
  if (arg === "--port" || arg === "-p") {
@@ -43,29 +230,199 @@ const parseArgs = (argv) => {
43
230
  continue;
44
231
  }
45
232
  }
46
- if (!cliHost && /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(arg)) {
47
- cliHost = arg;
233
+ if (arg === "--name") {
234
+ cliName = readOption(args, i, arg);
235
+ i++;
236
+ continue;
237
+ }
238
+ if (arg === "--model") {
239
+ const model$1 = readOption(args, i, arg);
240
+ if (!CONSOLE_MODELS.has(model$1)) fail(`Unknown model "${model$1}". Expected ${MODEL_LIST}.`);
241
+ cliModel = model$1;
242
+ i++;
243
+ continue;
244
+ }
245
+ if (arg === "--firmware") {
246
+ const firmware$1 = readOption(args, i, arg);
247
+ if (!FIRMWARE_PATTERN.test(firmware$1)) fail(`Invalid firmware "${firmware$1}". Expected <digits>.<digits>, for example 4.06.`);
248
+ cliFirmware = firmware$1;
249
+ i++;
250
+ continue;
251
+ }
252
+ if (arg === "--log-level") {
253
+ cliLogLevel = parseLogLevel(readOption(args, i, arg));
254
+ i++;
255
+ continue;
256
+ }
257
+ if (arg === "--meters") {
258
+ cliMeterMode = parseMeterMode(readOption(args, i, arg));
259
+ i++;
260
+ continue;
261
+ }
262
+ if (arg === "--advertise-ip") {
263
+ const advertiseIp = readOption(args, i, arg);
264
+ if (!IPV4_PATTERN.test(advertiseIp)) fail(`Invalid advertise IP "${advertiseIp}". Expected an IPv4 address.`);
265
+ cliAdvertiseIp = advertiseIp;
266
+ i++;
48
267
  continue;
49
268
  }
50
- if (!cliPort && /^\d+$/.test(arg)) {
51
- cliPort = parseInt(arg, 10);
269
+ if (arg === "--storage" || arg === "-s") {
270
+ const next = args[i + 1];
271
+ if (next && (next === "memory" || next === "json")) {
272
+ storageType = next;
273
+ i++;
274
+ }
275
+ }
276
+ if (arg === "--state-file" || arg === "-f") {
277
+ const next = args[i + 1];
278
+ if (next) {
279
+ stateFilePath = next;
280
+ storageType = "json";
281
+ i++;
282
+ }
283
+ }
284
+ if (arg === "--permissive") {
285
+ cliPermissive = true;
52
286
  continue;
53
287
  }
288
+ if (arg === "--help") {
289
+ console.log(`
290
+ X32 Simulator - Usage:
291
+ x32-simulator [options]
292
+
293
+ Options:
294
+ -p, --port <port> UDP port to listen on (default: 10023)
295
+ -h, --host <ip> IP address to bind to (default: 0.0.0.0)
296
+ --name <string> Console name reported by /xinfo (default: osc-server)
297
+ --model <model> ${MODEL_LIST} (default: X32)
298
+ --firmware <d.d> Firmware digits.digits (default: 4.06)
299
+ --advertise-ip <ipv4> IP announced when bound to 0.0.0.0
300
+ --log-level <level> debug, info, warn or error (default: info)
301
+ --meters <mode> silent, fixed, or noise (default: silent)
302
+ --permissive Store a Set sent to an unknown address
303
+ -s, --storage <type> Storage type: 'memory' or 'json' (default: memory)
304
+ -f, --state-file <file> Path to JSON state file (implies --storage json)
305
+ --help Show this help message
306
+
307
+ Terminal:
308
+ reset Reset every parameter to its default and notify clients
309
+ set <address> <text> Set a parameter from scene text, for example set /ch/01/mix/fader -10
310
+ get <address> Print a parameter in scene text
311
+ save Flush the state file
312
+ exit Stop the server
313
+
314
+ Examples:
315
+ x32-simulator --port 10023 --host 192.168.1.100
316
+ x32-simulator --model X32RACK --name TestRack --firmware 4.06
317
+ x32-simulator --storage json --state-file ./x32-state.json
318
+ x32-simulator -p 10023 -f ./my-mixer-state.json
319
+ `);
320
+ process.exit(0);
321
+ }
322
+ if (!cliHost && /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(arg)) cliHost = arg;
323
+ if (!cliPort && /^\d+$/.test(arg)) cliPort = parseInt(arg, 10);
54
324
  }
325
+ const PORT = cliPort || parseInt(process.env.X32_PORT || "10023", 10);
326
+ const HOST = cliHost || process.env.X32_IP || "0.0.0.0";
327
+ const name = cliName ?? DEFAULT_CONFIG.DEFAULT_NAME;
328
+ const model = cliModel ?? DEFAULT_CONFIG.DEFAULT_MODEL;
329
+ const firmware = cliFirmware ?? DEFAULT_FIRMWARE;
330
+ const logLevel = cliLogLevel ?? LogLevel.INFO;
55
331
  return {
56
- PORT: cliPort || parseInt(process.env.X32_PORT || "10023", 10),
57
- HOST: cliHost || process.env.X32_IP || "0.0.0.0"
332
+ PORT,
333
+ HOST,
334
+ storageType,
335
+ stateFilePath,
336
+ name,
337
+ model,
338
+ firmware,
339
+ advertiseIp: cliAdvertiseIp,
340
+ logLevel,
341
+ permissive: cliPermissive,
342
+ meterMode: cliMeterMode
58
343
  };
59
344
  };
345
+ /** Keeps `{ PERMISSIVE }` alone when `--meters` is omitted, so the default stays `silent`. */
346
+ const meterConfig = (permissive, meterMode) => {
347
+ const config = { PERMISSIVE: permissive };
348
+ if (meterMode !== void 0) config.METER_MODE = meterMode;
349
+ return config;
350
+ };
351
+ /**
352
+ * `set` converts scene text with {@link textToOsc}. `get` prints scene text.
353
+ * Unknown addresses and bad tokens are reported. They do not change the state.
354
+ */
355
+ const runParamCommand = (word, line, schemaRegistry, service) => {
356
+ const match = /^(?:set|get)\s+(\S+)(?:\s+([\s\S]+))?$/i.exec(line);
357
+ const address = match?.[1];
358
+ if (!address) {
359
+ console.log(`Unknown address ${line}`);
360
+ return;
361
+ }
362
+ const node = schemaRegistry.getNode(address);
363
+ if (!node) {
364
+ console.log(`Unknown address ${address}`);
365
+ return;
366
+ }
367
+ if (word === "get") {
368
+ try {
369
+ const value = service.getParameter(address);
370
+ if (value === void 0) {
371
+ console.log(address);
372
+ return;
373
+ }
374
+ const shown = node.param ? oscToText(node.param, value) : String(value);
375
+ console.log(`${address} ${shown}`);
376
+ } catch (err) {
377
+ console.log(err instanceof Error ? err.message : String(err));
378
+ }
379
+ return;
380
+ }
381
+ const text = match?.[2]?.trim();
382
+ if (!text) {
383
+ console.log(`Invalid value for ${address}`);
384
+ return;
385
+ }
386
+ let osc;
387
+ if (node.param) osc = textToOsc(node.param, text);
388
+ else if (node.type === "s") osc = text;
389
+ else {
390
+ const numeric = Number(text);
391
+ osc = Number.isFinite(numeric) ? numeric : null;
392
+ }
393
+ if (osc === null) {
394
+ console.log(`Invalid value for ${address}`);
395
+ return;
396
+ }
397
+ try {
398
+ service.setParameter(address, osc);
399
+ } catch (err) {
400
+ console.log(err instanceof Error ? err.message : String(err));
401
+ }
402
+ };
60
403
  const bootstrap = async () => {
61
404
  loadEnv();
62
- const { PORT, HOST } = parseArgs(process.argv);
405
+ let parsed;
406
+ try {
407
+ parsed = parseArgs(process.argv);
408
+ } catch (err) {
409
+ const message = err instanceof Error ? err.message : String(err);
410
+ console.error(message);
411
+ process.exit(1);
412
+ return;
413
+ }
414
+ const { PORT, HOST, storageType, stateFilePath, name, model, firmware, advertiseIp, logLevel, permissive, meterMode } = parsed;
63
415
  const logger = ConsoleLogger.getInstance();
64
- logger.setLevel(LogLevel.DEBUG);
416
+ logger.setLevel(logLevel);
65
417
  const schemaRegistry = new SchemaRegistry(new SchemaFactory());
66
- const service = new SimulationService(new UdpNetworkGateway(logger, new OscCodec(schemaRegistry)), logger, new InMemoryStateRepository(logger, schemaRegistry), schemaRegistry, PORT, HOST);
418
+ const service = new SimulationService(new UdpNetworkGateway(logger, new OscCodec(schemaRegistry)), logger, createStateRepository({
419
+ type: storageType,
420
+ filePath: stateFilePath,
421
+ autoSaveInterval: 5e3
422
+ }), schemaRegistry, PORT, HOST, name, model, meterConfig(permissive, meterMode), firmware, advertiseIp);
67
423
  try {
68
424
  await service.start();
425
+ const storageInfo = storageType === "json" ? `JSON (${stateFilePath})` : "In-Memory";
69
426
  console.log(`
70
427
  ╔════════════════════════════════════════╗
71
428
  ║ 🚀 X32 SIMULATION SERVER ACTIVE ║
@@ -73,10 +430,20 @@ const bootstrap = async () => {
73
430
  • IP: ${HOST}
74
431
  • Port: ${PORT}
75
432
  • Protocol: UDP (Strict X32 Schema)
76
- • Logging: ENHANCED (DEBUG)
433
+ • Storage: ${storageInfo}
434
+ • Logging: ${[
435
+ "debug",
436
+ "info",
437
+ "warn",
438
+ "error",
439
+ "none"
440
+ ][logLevel]}
77
441
 
78
442
  👉 Type "exit" or "stop" to shut down.
79
443
  👉 Type "reset" to reset faders to default.
444
+ 👉 Type "set <address> <text>" to move a control, for example set /ch/01/mix/fader -10.
445
+ 👉 Type "get <address>" to print a control.
446
+ 👉 Type "save" to force save state (JSON mode).
80
447
  `);
81
448
  } catch (err) {
82
449
  if (err.code === "EADDRNOTAVAIL") {
@@ -105,23 +472,29 @@ const bootstrap = async () => {
105
472
  input: process.stdin,
106
473
  output: process.stdout
107
474
  }).on("line", async (input) => {
108
- const command = input.trim().toLowerCase();
109
- switch (command) {
110
- case "exit":
111
- case "stop":
112
- case "quit":
113
- console.log("Shutting down...");
114
- await service.stop();
115
- process.exit(0);
116
- break;
117
- case "reset":
118
- service.resetState();
119
- console.log("✨ Console state reset to defaults.");
120
- break;
121
- default:
122
- if (command) console.log(`Unknown command: "${command}"`);
123
- break;
475
+ const line = input.trim();
476
+ const word = (line.split(/\s+/, 1)[0] ?? "").toLowerCase();
477
+ if (word === "exit" || word === "stop" || word === "quit") {
478
+ console.log("Shutting down...");
479
+ await service.stop();
480
+ process.exit(0);
481
+ return;
482
+ }
483
+ if (word === "reset") {
484
+ service.resetState();
485
+ console.log("✨ Console state reset to defaults.");
486
+ return;
487
+ }
488
+ if (word === "save") {
489
+ await service.saveState();
490
+ console.log("💾 State saved to storage.");
491
+ return;
492
+ }
493
+ if (word === "set" || word === "get") {
494
+ runParamCommand(word, line, schemaRegistry, service);
495
+ return;
124
496
  }
497
+ if (line) console.log(`Unknown command: "${line}"`);
125
498
  });
126
499
  process.on("SIGINT", async () => {
127
500
  console.log("\n(SIGINT received)");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djodjonx/x32-simulator",
3
- "version": "0.0.6",
3
+ "version": "0.0.8",
4
4
  "description": "X32 Simulator",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -28,7 +28,9 @@
28
28
  "scripts": {
29
29
  "dev": "tsdown --watch",
30
30
  "build": "tsdown",
31
+ "scn:convert": "node --experimental-strip-types scripts/scn-to-json.ts",
31
32
  "test": "vitest run",
33
+ "test:conformance": "vitest run --config vitest.conformance.config.ts",
32
34
  "test:coverage": "vitest run --coverage",
33
35
  "test:watch": "vitest",
34
36
  "lint": "oxlint -c .oxlintrc.json",