@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.
@@ -1,2180 +0,0 @@
1
- import * as os from "os";
2
- import { EventEmitter } from "node:events";
3
- import * as dgram from "node:dgram";
4
- import { Buffer as Buffer$1 } from "node:buffer";
5
-
6
- //#region src/application/use-cases/ProcessPacketUseCase.ts
7
- var ProcessPacketUseCase = class {
8
- constructor(messageHandler, gateway) {
9
- this.messageHandler = messageHandler;
10
- this.gateway = gateway;
11
- }
12
- execute(packet, rinfo) {
13
- if (packet.oscType === "bundle") packet.elements?.forEach((el) => this.execute(el, rinfo));
14
- else if (packet.oscType === "message") {
15
- const args = packet.args.map((arg) => {
16
- if (typeof arg === "object" && arg !== null && "value" in arg) return arg.value;
17
- return arg;
18
- });
19
- this.messageHandler.handle({
20
- address: packet.address,
21
- args
22
- }, rinfo).forEach((reply) => {
23
- this.gateway.send(rinfo, reply.address, reply.args);
24
- });
25
- }
26
- }
27
- };
28
-
29
- //#endregion
30
- //#region src/domain/ports/ILogger.ts
31
- /**
32
- * Standard log categories for the domain.
33
- */
34
- let LogCategory = /* @__PURE__ */ function(LogCategory$1) {
35
- LogCategory$1["SYSTEM"] = "SYSTEM";
36
- LogCategory$1["OSC_IN"] = "OSC_IN";
37
- LogCategory$1["OSC_OUT"] = "OSC_OUT";
38
- LogCategory$1["DISPATCH"] = "DISPATCH";
39
- LogCategory$1["STATE"] = "STATE";
40
- LogCategory$1["SUB"] = "SUB";
41
- LogCategory$1["METER"] = "METER";
42
- return LogCategory$1;
43
- }({});
44
-
45
- //#endregion
46
- //#region src/application/use-cases/BroadcastUpdatesUseCase.ts
47
- var BroadcastUpdatesUseCase = class {
48
- constructor(subscriptionManager, state, gateway, logger, meterService, schemaRegistry) {
49
- this.subscriptionManager = subscriptionManager;
50
- this.state = state;
51
- this.gateway = gateway;
52
- this.logger = logger;
53
- this.meterService = meterService;
54
- this.schemaRegistry = schemaRegistry;
55
- }
56
- execute() {
57
- this.subscriptionManager.getSubscribers().forEach((sub) => {
58
- if (sub.type === "path" || !sub.alias) {
59
- if (sub.type === "meter" && sub.meterPath) {
60
- const meterData = this.meterService.generateMeterData(sub.meterPath, this.state);
61
- this.gateway.send({
62
- address: sub.address,
63
- port: sub.port
64
- }, sub.meterPath, [meterData.toBlob()]);
65
- }
66
- return;
67
- }
68
- const rinfo = {
69
- address: sub.address,
70
- port: sub.port
71
- };
72
- if (sub.type === "batch" && sub.paths) {
73
- if (sub.paths.length === 1 && sub.paths[0].startsWith("/meters")) {
74
- const meterData = this.meterService.generateMeterData(sub.paths[0], this.state);
75
- this.gateway.send(rinfo, sub.alias, [meterData.toBlob()]);
76
- return;
77
- }
78
- let stride;
79
- const dataSize = sub.paths.length * 4;
80
- const factor = sub.factor || 0;
81
- const count = sub.count || 0;
82
- if (factor > 0) stride = Math.max(factor * 4, dataSize);
83
- else stride = sub.paths.length === 3 ? 16 : dataSize;
84
- const blobSize = count * stride;
85
- if (isNaN(blobSize) || blobSize < 0) {
86
- this.logger.error(LogCategory.SYSTEM, `Invalid blob size`, {
87
- alias: sub.alias,
88
- blobSize,
89
- count,
90
- stride,
91
- factor,
92
- dataSize
93
- });
94
- return;
95
- }
96
- const blob = Buffer.alloc(blobSize);
97
- for (let i = 0; i < count; i++) {
98
- const root = this.schemaRegistry.getRootFromIndex(sub.start + i);
99
- let currentOffset = i * stride;
100
- if (!root) continue;
101
- sub.paths.forEach((s, pIdx) => {
102
- if (pIdx * 4 >= stride) return;
103
- if (s.startsWith("/meters")) blob.writeFloatLE(0, currentOffset);
104
- else {
105
- const target = `${root}${s}`;
106
- const node = this.schemaRegistry.getNode(target);
107
- let val = this.state.get(target);
108
- if (val === void 0) val = node ? node.default : 0;
109
- if (typeof val === "number") if (node && node.type === "f") blob.writeFloatLE(val, currentOffset);
110
- else blob.writeInt32LE(val, currentOffset);
111
- else blob.writeInt32LE(0, currentOffset);
112
- }
113
- currentOffset += 4;
114
- });
115
- }
116
- this.gateway.send(rinfo, sub.alias, [blob]);
117
- } else if (sub.type === "format" && sub.pattern) {
118
- const stride = sub.factor ? sub.factor * 4 : 4;
119
- const start = sub.start || 0;
120
- const count = sub.count || 0;
121
- const totalSize = (start + count) * stride;
122
- if (isNaN(totalSize) || totalSize < 0) return;
123
- const blob = Buffer.alloc(totalSize);
124
- let offset = start * stride;
125
- for (let i = start; i < start + count; i++) {
126
- const id = i.toString().padStart(2, "0");
127
- const target = sub.pattern.replace(/\*\*?/, id);
128
- let val = this.state.get(target);
129
- if (val === void 0) val = 0;
130
- if (typeof val === "number") {
131
- const node = this.schemaRegistry.getNode(target);
132
- if (node && node.type === "f") blob.writeFloatLE(val, offset);
133
- else blob.writeInt32LE(val, offset);
134
- } else blob.writeInt32LE(0, offset);
135
- offset += stride;
136
- }
137
- this.gateway.send(rinfo, sub.alias, [blob]);
138
- }
139
- });
140
- }
141
- broadcastSingleChange(path, value) {
142
- this.subscriptionManager.getSubscribers().forEach((sub) => {
143
- if (path === sub.path || sub.path === "/xremote" || sub.path && sub.path.includes("*") && path.startsWith(sub.path.split("*")[0])) this.gateway.send({
144
- address: sub.address,
145
- port: sub.port
146
- }, path, [value]);
147
- });
148
- }
149
- };
150
-
151
- //#endregion
152
- //#region src/application/use-cases/ManageSessionsUseCase.ts
153
- var ManageSessionsUseCase = class {
154
- constructor(subscriptionManager) {
155
- this.subscriptionManager = subscriptionManager;
156
- }
157
- cleanup() {
158
- this.subscriptionManager.cleanup();
159
- }
160
- };
161
-
162
- //#endregion
163
- //#region src/domain/entities/SubscriptionManager.ts
164
- /**
165
- * Manages OSC client subscriptions and their lifecycle.
166
- */
167
- var SubscriptionManager = class {
168
- logger;
169
- subscribers = [];
170
- constructor(logger) {
171
- this.logger = logger;
172
- }
173
- /**
174
- * Cleans up expired subscriptions.
175
- * Standard X32 subscriptions last 10 seconds.
176
- */
177
- cleanup() {
178
- const now = Date.now();
179
- const initialCount = this.subscribers.length;
180
- this.subscribers = this.subscribers.filter((s) => {
181
- const active = s.expires > now;
182
- if (!active) this.logger.debug(LogCategory.SUB, `Expired subscriber`, {
183
- type: s.type,
184
- ip: s.address,
185
- port: s.port,
186
- path: "path" in s ? s.path : s.alias
187
- });
188
- return active;
189
- });
190
- if (this.subscribers.length !== initialCount) this.logger.info(LogCategory.SUB, `Cleanup finished`, {
191
- removed: initialCount - this.subscribers.length,
192
- remaining: this.subscribers.length
193
- });
194
- }
195
- /**
196
- * Gets all active subscribers.
197
- * @returns Array of subscribers.
198
- */
199
- getSubscribers() {
200
- return this.subscribers;
201
- }
202
- /**
203
- * Adds or renews a path-based subscription (e.g. /subscribe or /xremote).
204
- * @param rinfo - Client remote info.
205
- * @param path - Subscription path.
206
- */
207
- addPathSubscriber(rinfo, path) {
208
- const key = `${rinfo.address}:${rinfo.port}:${path}`;
209
- const expires = Date.now() + 1e4;
210
- const existing = this.subscribers.find((s) => s.type === "path" && `${s.address}:${s.port}:${s.path}` === key);
211
- if (existing) {
212
- existing.expires = expires;
213
- this.logger.debug(LogCategory.SUB, `Renewed subscription`, {
214
- ip: rinfo.address,
215
- path
216
- });
217
- } else {
218
- this.subscribers.push({
219
- type: "path",
220
- address: rinfo.address,
221
- port: rinfo.port,
222
- path,
223
- expires
224
- });
225
- this.logger.info(LogCategory.SUB, `New subscription`, {
226
- ip: rinfo.address,
227
- path
228
- });
229
- }
230
- }
231
- /**
232
- * Adds or renews a batch subscription.
233
- * @param rinfo - Client remote info.
234
- * @param alias - Response alias.
235
- * @param paths - Target paths.
236
- * @param start - Start index.
237
- * @param count - Count.
238
- * @param factor - Frequency factor.
239
- * @param args - Command arguments.
240
- */
241
- addBatchSubscriber(rinfo, alias, paths, start, count, factor, args) {
242
- const expires = Date.now() + 1e4;
243
- this.subscribers = this.subscribers.filter((s) => !(s.type === "batch" && s.alias === alias && s.address === rinfo.address));
244
- this.subscribers.push({
245
- type: "batch",
246
- address: rinfo.address,
247
- port: rinfo.port,
248
- alias,
249
- paths,
250
- start,
251
- count,
252
- factor,
253
- expires,
254
- args
255
- });
256
- this.logger.info(LogCategory.SUB, `Batch subscription`, {
257
- alias,
258
- count: paths.length,
259
- factor,
260
- ip: rinfo.address,
261
- args
262
- });
263
- }
264
- /**
265
- * Adds or renews a format subscription.
266
- * @param rinfo - Client remote info.
267
- * @param alias - Response alias.
268
- * @param pattern - Path pattern.
269
- * @param start - Start index.
270
- * @param count - Count.
271
- * @param factor - Frequency factor.
272
- */
273
- addFormatSubscriber(rinfo, alias, pattern, start, count, factor) {
274
- const expires = Date.now() + 1e4;
275
- this.subscribers = this.subscribers.filter((s) => !(s.type === "format" && s.alias === alias && s.address === rinfo.address));
276
- this.subscribers.push({
277
- type: "format",
278
- address: rinfo.address,
279
- port: rinfo.port,
280
- alias,
281
- pattern,
282
- start,
283
- count,
284
- factor,
285
- expires
286
- });
287
- this.logger.info(LogCategory.SUB, `Format subscription`, {
288
- alias,
289
- pattern,
290
- factor,
291
- ip: rinfo.address
292
- });
293
- }
294
- /**
295
- * Adds or renews a high-frequency meter subscription.
296
- * @param rinfo - Client remote info.
297
- * @param meterPath - Target meter path.
298
- */
299
- addMeterSubscriber(rinfo, meterPath) {
300
- const expires = Date.now() + 1e4;
301
- const existing = this.subscribers.find((s) => s.type === "meter" && s.meterPath === meterPath && s.address === rinfo.address);
302
- this.subscribers = this.subscribers.filter((s) => !(s.type === "meter" && s.meterPath === meterPath && s.address === rinfo.address));
303
- this.subscribers.push({
304
- type: "meter",
305
- address: rinfo.address,
306
- port: rinfo.port,
307
- meterPath,
308
- expires
309
- });
310
- if (!existing) this.logger.info(LogCategory.SUB, `Meter subscription`, {
311
- path: meterPath,
312
- ip: rinfo.address
313
- });
314
- else this.logger.debug(LogCategory.SUB, `Meter renewal`, {
315
- path: meterPath,
316
- ip: rinfo.address
317
- });
318
- }
319
- /**
320
- * Removes a subscription.
321
- * @param rinfo - Client remote info.
322
- * @param path - Subscription path.
323
- */
324
- removeSubscriber(rinfo, path) {
325
- const initial = this.subscribers.length;
326
- this.subscribers = this.subscribers.filter((s) => !(s.address === rinfo.address && s.port === rinfo.port && s.path === path));
327
- if (this.subscribers.length < initial) this.logger.info(LogCategory.SUB, `Unsubscribed`, {
328
- path,
329
- ip: rinfo.address
330
- });
331
- }
332
- };
333
-
334
- //#endregion
335
- //#region src/domain/services/strategies/NodeDiscoveryStrategy.ts
336
- /**
337
- * Handles the /node command for tree traversal/discovery.
338
- * Returns a list of child nodes for a given path.
339
- */
340
- var NodeDiscoveryStrategy = class {
341
- constructor(schemaRegistry) {
342
- this.schemaRegistry = schemaRegistry;
343
- }
344
- canHandle(address) {
345
- return address === "/node";
346
- }
347
- execute(msg, _source) {
348
- const queryPath = msg.args[0] || "/";
349
- const children = /* @__PURE__ */ new Set();
350
- const prefix = queryPath.endsWith("/") ? queryPath : `${queryPath}/`;
351
- for (const key of this.schemaRegistry.getAllPaths()) if (key.startsWith(prefix)) {
352
- const segment = key.slice(prefix.length).split("/")[0];
353
- if (segment) children.add(segment);
354
- }
355
- return [{
356
- address: "/node",
357
- args: [queryPath, ...children]
358
- }];
359
- }
360
- };
361
-
362
- //#endregion
363
- //#region src/domain/services/strategies/StaticResponseStrategy.ts
364
- /**
365
- * Handles discovery and static information queries.
366
- * e.g., /status, /xinfo, /-prefs/...
367
- */
368
- var StaticResponseStrategy = class {
369
- constructor(serverIp, serverName, serverModel, staticResponseService) {
370
- this.serverIp = serverIp;
371
- this.serverName = serverName;
372
- this.serverModel = serverModel;
373
- this.staticResponseService = staticResponseService;
374
- }
375
- canHandle(address) {
376
- return !!this.staticResponseService.getResponse(address);
377
- }
378
- execute(msg, _source) {
379
- const rawResponse = this.staticResponseService.getResponse(msg.address);
380
- if (!rawResponse) return [];
381
- const args = rawResponse.map((arg) => {
382
- if (typeof arg === "string") return arg.replace("{{ip}}", this.serverIp).replace("{{name}}", this.serverName).replace("{{model}}", this.serverModel);
383
- return arg;
384
- });
385
- return [{
386
- address: msg.address,
387
- args
388
- }];
389
- }
390
- };
391
-
392
- //#endregion
393
- //#region src/domain/services/strategies/SubscriptionStrategy.ts
394
- var SubscriptionStrategy = class {
395
- constructor(subscriptionManager, state, logger) {
396
- this.subscriptionManager = subscriptionManager;
397
- this.state = state;
398
- this.logger = logger;
399
- }
400
- canHandle(address) {
401
- return [
402
- "/subscribe",
403
- "/renew",
404
- "/unsubscribe",
405
- "/xremote"
406
- ].includes(address);
407
- }
408
- /**
409
- * Handles Session and Subscription lifecycle.
410
- *
411
- * ROUTES:
412
- * - /xremote: Firehose subscription (requests all console updates for 10s).
413
- * - /subscribe [path]: Requests updates for a specific node path for 10s.
414
- * - /renew [path]: Resets the 10s watchdog timer for a path.
415
- * - /unsubscribe [path]: Stops updates for a path.
416
- * @param msg - Parsed OSC message.
417
- * @param source - Source address and port of the packet.
418
- * @returns Returns the current value of the path upon subscription.
419
- */
420
- execute(msg, source) {
421
- const addr = msg.address;
422
- if (addr === "/xremote") {
423
- this.subscriptionManager.addPathSubscriber(source, "/xremote");
424
- return [{
425
- address: "/xremote",
426
- args: []
427
- }];
428
- }
429
- if (addr === "/unsubscribe") {
430
- this.subscriptionManager.removeSubscriber(source, msg.args[0]);
431
- this.logger.debug(LogCategory.SUB, `[UNSUB] ${msg.args[0]}`);
432
- return [];
433
- }
434
- const target = msg.args[0];
435
- this.subscriptionManager.addPathSubscriber(source, target);
436
- const val = this.state.get(target);
437
- if (val !== void 0) {
438
- this.logger.debug(LogCategory.SUB, `[SUB] ${target} -> ${val}`);
439
- return [{
440
- address: target,
441
- args: [val]
442
- }];
443
- }
444
- return [];
445
- }
446
- };
447
-
448
- //#endregion
449
- //#region src/domain/services/strategies/BatchStrategy.ts
450
- /**
451
- * Handles bulk data subscription requests from advanced clients like X32-Edit or Mixing Station.
452
- *
453
- * SUPPORTED COMMANDS:
454
- * - /formatsubscribe: Requests a range of numbered nodes (e.g. /ch/01-32/mix/fader).
455
- * - /batchsubscribe: Aggregates multiple parameters into a single binary blob response.
456
- */
457
- var BatchStrategy = class {
458
- /**
459
- * Initializes the strategy.
460
- * @param subscriptionManager - Session manager.
461
- * @param logger - Logger instance.
462
- */
463
- constructor(subscriptionManager, logger) {
464
- this.subscriptionManager = subscriptionManager;
465
- this.logger = logger;
466
- }
467
- /** @inheritdoc */
468
- canHandle(address) {
469
- return ["/batchsubscribe", "/formatsubscribe"].includes(address);
470
- }
471
- /** @inheritdoc */
472
- execute(msg, source) {
473
- const addr = msg.address;
474
- if (addr === "/formatsubscribe") {
475
- const alias = msg.args[0];
476
- const pattern = msg.args[1];
477
- const start = msg.args[2];
478
- const end = msg.args[3];
479
- const factor = msg.args[4];
480
- const count = end - start + 1;
481
- this.subscriptionManager.addFormatSubscriber(source, alias, pattern, start, count, factor);
482
- this.logger.debug(LogCategory.SUB, `[FORMAT] ${alias} factor: ${factor}`);
483
- return [];
484
- }
485
- if (addr === "/batchsubscribe") {
486
- const alias = msg.args[0];
487
- const firstIntIndex = msg.args.findIndex((a) => typeof a === "number");
488
- if (firstIntIndex === -1) return [];
489
- const paths = msg.args.slice(1, firstIntIndex);
490
- const intArgs = msg.args.slice(firstIntIndex);
491
- const factor = intArgs.pop();
492
- const cmdArgs = intArgs;
493
- this.subscriptionManager.addBatchSubscriber(source, alias, paths, 0, 1, factor, cmdArgs);
494
- this.logger.debug(LogCategory.SUB, `[BATCH] ${alias} paths: ${JSON.stringify(paths)} args: ${JSON.stringify(cmdArgs)} factor: ${factor}`);
495
- return [];
496
- }
497
- return [];
498
- }
499
- };
500
-
501
- //#endregion
502
- //#region src/domain/services/strategies/MeterStrategy.ts
503
- /**
504
- * Handles high-frequency metering data requests.
505
- * Meters are sent as binary blobs to optimize network bandwidth.
506
- * Supports both direct address requests (/meters/1) and argument-based requests (/meters ,s "/meters/1").
507
- */
508
- var MeterStrategy = class {
509
- /**
510
- * Initializes the strategy.
511
- * @param subscriptionManager - Session manager.
512
- * @param state - Current mixer state.
513
- * @param meterService - Service to generate meter data.
514
- */
515
- constructor(subscriptionManager, state, meterService) {
516
- this.subscriptionManager = subscriptionManager;
517
- this.state = state;
518
- this.meterService = meterService;
519
- }
520
- /** @inheritdoc */
521
- canHandle(address) {
522
- return address.startsWith("/meters");
523
- }
524
- /** @inheritdoc */
525
- execute(msg, source) {
526
- let meterPath = msg.address;
527
- if (msg.address === "/meters" && typeof msg.args[0] === "string" && msg.args[0].startsWith("/meters")) meterPath = msg.args[0];
528
- this.subscriptionManager.addMeterSubscriber(source, meterPath);
529
- const blob = this.meterService.generateMeterData(meterPath, this.state).toBlob();
530
- return [{
531
- address: meterPath,
532
- args: [blob]
533
- }];
534
- }
535
- };
536
-
537
- //#endregion
538
- //#region src/domain/services/strategies/StateAccessStrategy.ts
539
- /**
540
- * General-purpose strategy for reading and writing console parameters.
541
- * acts as the fallback for any command that matches the schema.
542
- *
543
- * LOGIC:
544
- * - If no arguments: Treats as a QUERY (GET) and returns the current value.
545
- * - If arguments provided: Treats as an UPDATE (SET) and stores the new value.
546
- */
547
- var StateAccessStrategy = class {
548
- /**
549
- * Initializes the strategy.
550
- * @param state - Current mixer state.
551
- * @param logger - Logger instance.
552
- * @param schemaRegistry - Registry to validate addresses.
553
- */
554
- constructor(state, logger, schemaRegistry) {
555
- this.state = state;
556
- this.logger = logger;
557
- this.schemaRegistry = schemaRegistry;
558
- }
559
- /** @inheritdoc */
560
- canHandle(address) {
561
- return this.schemaRegistry.has(address);
562
- }
563
- /** @inheritdoc */
564
- execute(msg, _source) {
565
- const addr = msg.address;
566
- const node = this.schemaRegistry.getNode(addr);
567
- if (msg.args.length === 0) {
568
- const val$1 = this.state.get(addr);
569
- if (val$1 !== void 0) return [{
570
- address: addr,
571
- args: [val$1]
572
- }];
573
- return [];
574
- }
575
- const val = msg.args[0];
576
- if (node) {
577
- if (!node.validate(val)) {
578
- this.logger.warn(LogCategory.DISPATCH, `[TYPE ERR] ${addr} expected ${node.type}, got ${typeof val}`);
579
- return [];
580
- }
581
- this.state.set(addr, val);
582
- this.logger.debug(LogCategory.STATE, `[SET] ${addr} -> ${val}`);
583
- if (addr.startsWith("/config/mute/")) {
584
- const groupIdx = parseInt(addr.split("/").pop(), 10);
585
- if (!isNaN(groupIdx)) this.state.handleMuteGroupChange(groupIdx, val);
586
- }
587
- }
588
- return [];
589
- }
590
- };
591
-
592
- //#endregion
593
- //#region src/domain/services/OscMessageHandler.ts
594
- /**
595
- * The central dispatcher for incoming OSC messages.
596
- * Uses a Chain of Responsibility (Strategy pattern) to delegate handling.
597
- * Order of strategies is critical for correct prioritization.
598
- */
599
- var OscMessageHandler = class {
600
- /** List of active command strategies. */
601
- strategies;
602
- /**
603
- * Initializes the handler with all available strategies.
604
- * @param state - Global mixer state.
605
- * @param subscriptionManager - Active client sessions.
606
- * @param logger - Logger instance.
607
- * @param serverIp - Host IP reported in handshakes.
608
- * @param serverName - Console name reported in handshakes.
609
- * @param serverModel - Console model reported in handshakes.
610
- * @param meterService - Service for metering.
611
- * @param schemaRegistry - Service for schema validation.
612
- * @param staticResponseService - Service for static responses.
613
- */
614
- constructor(state, subscriptionManager, logger, serverIp, serverName, serverModel, meterService, schemaRegistry, staticResponseService) {
615
- this.logger = logger;
616
- this.meterService = meterService;
617
- this.schemaRegistry = schemaRegistry;
618
- this.staticResponseService = staticResponseService;
619
- this.strategies = [
620
- new NodeDiscoveryStrategy(this.schemaRegistry),
621
- new SubscriptionStrategy(subscriptionManager, state, logger),
622
- new BatchStrategy(subscriptionManager, logger),
623
- new MeterStrategy(subscriptionManager, state, this.meterService),
624
- new StateAccessStrategy(state, logger, this.schemaRegistry),
625
- new StaticResponseStrategy(serverIp, serverName, serverModel, this.staticResponseService)
626
- ];
627
- }
628
- /**
629
- * Dispatches an incoming message to the first matching strategy.
630
- * @param msg - Parsed OSC message.
631
- * @param source - Source address and port of the packet.
632
- * @returns Array of replies generated by the strategy.
633
- */
634
- handle(msg, source) {
635
- const addr = msg.address;
636
- if (!addr.startsWith("/meters")) this.logger.debug(LogCategory.DISPATCH, `Handling`, {
637
- addr,
638
- args: msg.args
639
- });
640
- for (const strategy of this.strategies) if (strategy.canHandle(addr)) {
641
- const replies = strategy.execute(msg, source);
642
- if (replies.length > 0) this.logger.debug(LogCategory.DISPATCH, `Strategy ${strategy.constructor.name} replied`, { count: replies.length });
643
- return replies;
644
- }
645
- this.logger.warn(LogCategory.DISPATCH, `Unknown Command`, {
646
- addr,
647
- args: msg.args,
648
- ip: source.address
649
- });
650
- return [];
651
- }
652
- };
653
-
654
- //#endregion
655
- //#region src/domain/models/MeterData.ts
656
- /**
657
- * Represents a set of meter values for a specific meter path.
658
- * Handles the storage of float values and serialization to X32-specific binary blobs.
659
- */
660
- var MeterData = class {
661
- _path;
662
- _values;
663
- /**
664
- * Creates a new MeterData instance.
665
- * @param path - The meter OSC path (e.g., "/meters/1").
666
- * @param values - The array of float values (0.0 - 1.0 or similar).
667
- */
668
- constructor(path, values) {
669
- this._path = path;
670
- this._values = values;
671
- }
672
- /**
673
- * Gets the meter path.
674
- */
675
- get path() {
676
- return this._path;
677
- }
678
- /**
679
- * Gets the values.
680
- */
681
- get values() {
682
- return [...this._values];
683
- }
684
- /**
685
- * Generates an optimized binary blob for X32 meters (mixed endianness).
686
- * Structure: [Size (Int32BE)] [Count (Int32LE)] [Float1 (LE)] [Float2 (LE)] ...
687
- * @returns Buffer containing the OSC blob.
688
- */
689
- toBlob() {
690
- const count = this._values.length;
691
- const totalSize = 8 + count * 4;
692
- const blob = Buffer.alloc(totalSize);
693
- blob.writeInt32BE(totalSize, 0);
694
- blob.writeInt32LE(count, 4);
695
- for (let i = 0; i < count; i++) blob.writeFloatLE(this._values[i], 8 + i * 4);
696
- return blob;
697
- }
698
- };
699
-
700
- //#endregion
701
- //#region src/domain/models/MeterConfig.ts
702
- /**
703
- * Configuration for meter counts per path.
704
- */
705
- const METER_COUNTS = {
706
- "/meters/0": 70,
707
- "/meters/1": 96,
708
- "/meters/2": 49,
709
- "/meters/3": 22,
710
- "/meters/4": 82,
711
- "/meters/5": 27,
712
- "/meters/6": 4,
713
- "/meters/7": 16,
714
- "/meters/8": 6,
715
- "/meters/9": 32,
716
- "/meters/10": 32,
717
- "/meters/11": 5,
718
- "/meters/12": 4,
719
- "/meters/13": 48,
720
- "/meters/14": 80,
721
- "/meters/15": 50,
722
- "/meters/16": 48
723
- };
724
-
725
- //#endregion
726
- //#region src/domain/services/MeterService.ts
727
- /**
728
- * Service responsible for generating meter values and data.
729
- * Mimics the physics/audio engine of the X32.
730
- */
731
- var MeterService = class {
732
- /**
733
- * Generates a MeterData object for a given path.
734
- * @param path - The meter OSC path (e.g., "/meters/1").
735
- * @param state - The current X32 state (for correlating faders to meters).
736
- * @returns MeterData object containing the values.
737
- */
738
- generateMeterData(path, state) {
739
- const count = METER_COUNTS[path];
740
- if (count === void 0) return new MeterData(path, []);
741
- const values = [];
742
- for (let i = 0; i < count; i++) {
743
- let val = Math.random() * .05;
744
- if (state && path === "/meters/1") {
745
- if (i < 32) {
746
- const faderPath = `/ch/${(i + 1).toString().padStart(2, "0")}/mix/fader`;
747
- const fader = state.get(faderPath);
748
- if (typeof fader === "number") val = fader > .01 ? fader * (.9 + Math.random() * .1) : 0;
749
- }
750
- }
751
- values.push(val);
752
- }
753
- return new MeterData(path, values);
754
- }
755
- };
756
-
757
- //#endregion
758
- //#region src/domain/services/StaticResponseService.ts
759
- /**
760
- * Static OSC responses for X32 Discovery and System status.
761
- */
762
- const STATIC_RESPONSES_DATA = {
763
- "/xinfo": [
764
- "{{ip}}",
765
- "{{name}}",
766
- "{{model}}",
767
- "4.06"
768
- ],
769
- "/info": [
770
- "V2.05",
771
- "{{name}}",
772
- "{{model}}",
773
- "4.06"
774
- ],
775
- "/status": [
776
- "active",
777
- "{{ip}}",
778
- "{{name}}"
779
- ],
780
- "/-prefs/invertmutes": [0],
781
- "/-prefs/fine": [0],
782
- "/-prefs/bright": [50],
783
- "/-prefs/contrast": [50],
784
- "/-prefs/led_bright": [50],
785
- "/-prefs/lcd_bright": [50],
786
- "/-stat/userpar/1/value": [0],
787
- "/-stat/userpar/2/value": [0],
788
- "/-stat/tape/state": [0],
789
- "/-stat/aes50/A": [0],
790
- "/-stat/aes50/B": [0],
791
- "/-stat/solo": [0],
792
- "/-stat/rtasource": [0],
793
- "/-urec/errorcode": [0],
794
- "/-prefs/rta/gain": [0],
795
- "/-prefs/rta/autogain": [0],
796
- "/-prefs/hardmute": [0],
797
- "/-prefs/dcamute": [0],
798
- "/config/mono/mode": [0],
799
- "/config/amixenable/X": [0],
800
- "/config/amixenable/Y": [0],
801
- "/-show/prepos/current": [0],
802
- "/-show/showfile/current": [""],
803
- "/-action/setrtasrc": [0],
804
- "/-action/playtrack": [0],
805
- "/-action/goscene": [0],
806
- "/-action/setscene": [0]
807
- };
808
- /**
809
- * Service providing static system responses.
810
- * Mimics the fixed firmware responses of the X32.
811
- */
812
- var StaticResponseService = class {
813
- responses = STATIC_RESPONSES_DATA;
814
- /**
815
- * Retrieves a static response for a given path.
816
- * @param path - The OSC path.
817
- * @returns The response arguments or undefined.
818
- */
819
- getResponse(path) {
820
- return this.responses[path];
821
- }
822
- };
823
-
824
- //#endregion
825
- //#region src/application/use-cases/SimulationService.ts
826
- /**
827
- * Gets the first non-internal IPv4 address found on this machine.
828
- * @returns Detected IP or localhost.
829
- */
830
- function getLocalIp() {
831
- const interfaces = os.networkInterfaces();
832
- for (const name of Object.keys(interfaces)) for (const iface of interfaces[name]) if (iface.family === "IPv4" && !iface.internal) return iface.address;
833
- return "127.0.0.1";
834
- }
835
- /**
836
- * The core service that manages the X32 simulation, including networking,
837
- * state management, and OSC message handling.
838
- */
839
- var SimulationService = class {
840
- subscriptionManager;
841
- messageHandler;
842
- processPacket;
843
- broadcastUpdates;
844
- manageSessions;
845
- meterService;
846
- staticResponseService;
847
- updateInterval = null;
848
- cleanupInterval = null;
849
- /**
850
- * Creates a new SimulationService instance.
851
- * @param gateway - The network gateway for OSC communication.
852
- * @param logger - The logger service.
853
- * @param stateRepo - The repository managing the mixer state.
854
- * @param schemaRegistry - The registry for X32 OSC schema.
855
- * @param port - UDP port to listen on (default 10023).
856
- * @param ip - IP address to bind to (default '0.0.0.0').
857
- * @param name - Reported console name.
858
- * @param model - Reported console model.
859
- */
860
- constructor(gateway, logger, stateRepo, schemaRegistry, port = 10023, ip = "0.0.0.0", name = "osc-server", model = "X32") {
861
- this.gateway = gateway;
862
- this.logger = logger;
863
- this.stateRepo = stateRepo;
864
- this.schemaRegistry = schemaRegistry;
865
- this.port = port;
866
- this.ip = ip;
867
- const state = this.stateRepo.getState();
868
- this.subscriptionManager = new SubscriptionManager(logger);
869
- this.meterService = new MeterService();
870
- this.staticResponseService = new StaticResponseService();
871
- const reportedIp = this.ip === "0.0.0.0" ? getLocalIp() : this.ip;
872
- this.messageHandler = new OscMessageHandler(state, this.subscriptionManager, logger, reportedIp, name, model, this.meterService, this.schemaRegistry, this.staticResponseService);
873
- this.processPacket = new ProcessPacketUseCase(this.messageHandler, gateway);
874
- this.broadcastUpdates = new BroadcastUpdatesUseCase(this.subscriptionManager, state, gateway, logger, this.meterService, this.schemaRegistry);
875
- this.manageSessions = new ManageSessionsUseCase(this.subscriptionManager);
876
- state.on("change", (evt) => {
877
- this.logger.info(LogCategory.STATE, `State Changed`, evt);
878
- this.broadcastUpdates.broadcastSingleChange(evt.address, evt.value);
879
- });
880
- this.gateway.onPacket((packet, source) => this.processPacket.execute(packet, source));
881
- }
882
- /**
883
- * Starts the simulator server and internal loops.
884
- */
885
- async start() {
886
- await this.gateway.start(this.port, this.ip);
887
- this.cleanupInterval = setInterval(() => {
888
- this.manageSessions.cleanup();
889
- }, 5e3);
890
- this.updateInterval = setInterval(() => {
891
- this.broadcastUpdates.execute();
892
- }, 100);
893
- }
894
- /**
895
- * Stops the simulator server and stops all internal loops.
896
- */
897
- async stop() {
898
- if (this.updateInterval) clearInterval(this.updateInterval);
899
- if (this.cleanupInterval) clearInterval(this.cleanupInterval);
900
- await this.gateway.stop();
901
- }
902
- /**
903
- * Resets the mixer state to default values.
904
- */
905
- resetState() {
906
- this.stateRepo.reset();
907
- }
908
- };
909
-
910
- //#endregion
911
- //#region src/domain/entities/X32State.ts
912
- /**
913
- * Manages the internal "Digital Twin" state of the X32 console.
914
- * It acts as a single source of truth for all parameters.
915
- * Emits 'change' events whenever a value is updated.
916
- */
917
- var X32State = class extends EventEmitter {
918
- /** Map storing all OSC paths and their current values. */
919
- state = /* @__PURE__ */ new Map();
920
- defaultState = /* @__PURE__ */ new Map();
921
- /**
922
- * Initializes the state with default values from the schema.
923
- * @param schema - The schema definition map.
924
- */
925
- constructor(schema) {
926
- super();
927
- for (const [addr, def] of Object.entries(schema)) this.defaultState.set(addr, def.default);
928
- this.reset();
929
- }
930
- /**
931
- * Resets all state parameters to their default values defined in the schema.
932
- */
933
- reset() {
934
- this.state.clear();
935
- this.defaultState.forEach((val, key) => {
936
- this.state.set(key, val);
937
- });
938
- }
939
- /**
940
- * Retrieves the value of a specific OSC node.
941
- * @param address - The full OSC address path.
942
- * @returns The stored value (number or string) or undefined if not found.
943
- */
944
- get(address) {
945
- return this.state.get(address);
946
- }
947
- /**
948
- * Updates the value of a specific OSC node and notifies subscribers.
949
- * @param address - The full OSC address path.
950
- * @param value - The new value to store.
951
- */
952
- set(address, value) {
953
- this.state.set(address, value);
954
- this.emit("change", {
955
- address,
956
- value
957
- });
958
- }
959
- /**
960
- * Specialized logic to handle X32 Mute Groups side-effects.
961
- * When a mute group is toggled, it iterates through all channels
962
- * assigned to that group and updates their individual mute status.
963
- * @param groupIdx - The index of the mute group (1-6).
964
- * @param isOn - The new state of the group master switch (0 or 1).
965
- */
966
- handleMuteGroupChange(groupIdx, isOn) {
967
- for (let i = 1; i <= 32; i++) {
968
- const ch = i.toString().padStart(2, "0");
969
- const grpVal = this.get(`/ch/${ch}/grp/mute`);
970
- if (typeof grpVal === "number") {
971
- if ((grpVal & 1 << groupIdx - 1) !== 0) {
972
- const targetMute = isOn === 1 ? 0 : 1;
973
- const muteAddr = `/ch/${ch}/mix/on`;
974
- this.set(muteAddr, targetMute);
975
- }
976
- }
977
- }
978
- }
979
- };
980
-
981
- //#endregion
982
- //#region src/domain/models/X32Node.ts
983
- /**
984
- * Metadata for a single state node in the X32 schema.
985
- * Represents a "Knob" or "Variable" on the console.
986
- */
987
- var X32Node = class X32Node {
988
- /** Value type (f=float, i=int, s=string). */
989
- type;
990
- /** Default value for reset. */
991
- default;
992
- /**
993
- * Creates a new X32Node.
994
- * @param type - The OSC data type ('f', 'i', 's').
995
- * @param defaultValue - The default value.
996
- */
997
- constructor(type, defaultValue) {
998
- this.type = type;
999
- this.default = defaultValue;
1000
- }
1001
- /**
1002
- * Validates if a value is compatible with this node's type.
1003
- * @param value - The value to check.
1004
- * @returns True if valid.
1005
- */
1006
- validate(value) {
1007
- if (this.type === "f") return typeof value === "number";
1008
- if (this.type === "i") return typeof value === "number";
1009
- if (this.type === "s") return typeof value === "string";
1010
- return false;
1011
- }
1012
- /**
1013
- * Factory method to create from a plain object (for compatibility/migration).
1014
- * @param obj - Plain object.
1015
- * @param obj.type - OSC data type.
1016
- * @param obj.default - Default value.
1017
- * @returns A new X32Node instance.
1018
- */
1019
- static from(obj) {
1020
- return new X32Node(obj.type, obj.default);
1021
- }
1022
- };
1023
-
1024
- //#endregion
1025
- //#region src/infrastructure/repositories/InMemoryStateRepository.ts
1026
- /**
1027
- * In-memory implementation of the state repository.
1028
- * Stores the mixer state in volatile memory during the simulator's execution.
1029
- */
1030
- var InMemoryStateRepository = class {
1031
- state;
1032
- /**
1033
- * Creates a new InMemoryStateRepository.
1034
- * @param logger - Logger service.
1035
- * @param schemaRegistry - Registry providing the initial state schema.
1036
- */
1037
- constructor(logger, schemaRegistry) {
1038
- this.logger = logger;
1039
- this.state = new X32State(schemaRegistry.getSchema());
1040
- }
1041
- /**
1042
- * Returns the current mixer state instance.
1043
- * @returns The X32State entity.
1044
- */
1045
- getState() {
1046
- return this.state;
1047
- }
1048
- /**
1049
- * Resets the entire state to its default values.
1050
- */
1051
- reset() {
1052
- this.logger.info(LogCategory.SYSTEM, "Resetting state to defaults");
1053
- this.state.reset();
1054
- }
1055
- };
1056
-
1057
- //#endregion
1058
- //#region src/infrastructure/services/ConsoleLogger.ts
1059
- /**
1060
- * Log levels for the application.
1061
- */
1062
- let LogLevel = /* @__PURE__ */ function(LogLevel$1) {
1063
- LogLevel$1[LogLevel$1["DEBUG"] = 0] = "DEBUG";
1064
- LogLevel$1[LogLevel$1["INFO"] = 1] = "INFO";
1065
- LogLevel$1[LogLevel$1["WARN"] = 2] = "WARN";
1066
- LogLevel$1[LogLevel$1["ERROR"] = 3] = "ERROR";
1067
- LogLevel$1[LogLevel$1["NONE"] = 4] = "NONE";
1068
- return LogLevel$1;
1069
- }({});
1070
- /**
1071
- * Enhanced logger with category support and environment-based filtering.
1072
- */
1073
- var ConsoleLogger = class ConsoleLogger {
1074
- static instance;
1075
- level = LogLevel.DEBUG;
1076
- hiddenPatterns = [];
1077
- enabledCategories = new Set([
1078
- LogCategory.SYSTEM,
1079
- LogCategory.OSC_IN,
1080
- LogCategory.OSC_OUT,
1081
- LogCategory.DISPATCH,
1082
- LogCategory.STATE,
1083
- LogCategory.SUB
1084
- ]);
1085
- constructor() {
1086
- if (process.env.HIDDEN_LOG) this.hiddenPatterns = process.env.HIDDEN_LOG.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
1087
- }
1088
- /**
1089
- * Gets the singleton instance.
1090
- * @returns ConsoleLogger instance.
1091
- */
1092
- static getInstance() {
1093
- if (!ConsoleLogger.instance) ConsoleLogger.instance = new ConsoleLogger();
1094
- return ConsoleLogger.instance;
1095
- }
1096
- /**
1097
- * Sets the minimum log level.
1098
- * @param level - LogLevel.
1099
- */
1100
- setLevel(level) {
1101
- this.level = level;
1102
- }
1103
- /**
1104
- * Enables a category for output.
1105
- * @param cat - Category name.
1106
- */
1107
- enableCategory(cat) {
1108
- this.enabledCategories.add(cat);
1109
- }
1110
- /**
1111
- * Disables a category for output.
1112
- * @param cat - Category name.
1113
- */
1114
- disableCategory(cat) {
1115
- this.enabledCategories.delete(cat);
1116
- }
1117
- /**
1118
- * Logs a debug message.
1119
- * @param category - Log category.
1120
- * @param msg - Message string.
1121
- * @param data - Optional metadata.
1122
- */
1123
- debug(category, msg, data) {
1124
- if (this.shouldHide(msg, data)) return;
1125
- if (this.level <= LogLevel.DEBUG && this.enabledCategories.has(category)) console.log(this.format("DEBUG", category, msg, data));
1126
- }
1127
- /**
1128
- * Logs an info message.
1129
- * @param category - Log category.
1130
- * @param msg - Message string.
1131
- * @param data - Optional metadata.
1132
- */
1133
- info(category, msg, data) {
1134
- if (this.shouldHide(msg, data)) return;
1135
- if (this.level <= LogLevel.INFO && this.enabledCategories.has(category)) console.log(this.format("INFO ", category, msg, data));
1136
- }
1137
- /**
1138
- * Logs a warning message.
1139
- * @param category - Log category.
1140
- * @param msg - Message string.
1141
- * @param data - Optional metadata.
1142
- */
1143
- warn(category, msg, data) {
1144
- if (this.shouldHide(msg, data)) return;
1145
- if (this.level <= LogLevel.WARN && this.enabledCategories.has(category)) console.log(this.format("WARN ", category, msg, data));
1146
- }
1147
- /**
1148
- * Logs an error message.
1149
- * @param category - Log category.
1150
- * @param msg - Message string.
1151
- * @param err - Optional error object.
1152
- */
1153
- error(category, msg, err) {
1154
- if (this.shouldHide(msg, err)) return;
1155
- if (this.level <= LogLevel.ERROR) console.log(this.format("ERROR", category, msg, err));
1156
- }
1157
- /**
1158
- * Checks if a log should be hidden based on patterns.
1159
- * @param msg - Message.
1160
- * @param data - Metadata.
1161
- * @returns True if log should be suppressed.
1162
- */
1163
- shouldHide(msg, data) {
1164
- if (this.hiddenPatterns.length === 0) return false;
1165
- if (this.hiddenPatterns.some((p) => msg.includes(p))) return true;
1166
- if (data !== void 0) {
1167
- const strData = Buffer.isBuffer(data) ? data.toString("hex") : typeof data === "object" ? JSON.stringify(data) : String(data);
1168
- if (this.hiddenPatterns.some((p) => strData.includes(p))) return true;
1169
- }
1170
- return false;
1171
- }
1172
- /**
1173
- * Formats the log message.
1174
- * @param level - Level label.
1175
- * @param category - Category label.
1176
- * @param msg - Message.
1177
- * @param data - Metadata.
1178
- * @returns Formatted string.
1179
- */
1180
- format(level, category, msg, data) {
1181
- const now = /* @__PURE__ */ new Date();
1182
- let out = `\x1b[90m[${`${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}.${now.getMilliseconds().toString().padStart(3, "0")}`}]\x1b[0m `;
1183
- switch (level) {
1184
- case "DEBUG":
1185
- out += `\x1b[36m[DEBUG]\x1b[0m`;
1186
- break;
1187
- case "INFO ":
1188
- out += `\x1b[32m[INFO ]\x1b[0m`;
1189
- break;
1190
- case "WARN ":
1191
- out += `\x1b[33m[WARN ]\x1b[0m`;
1192
- break;
1193
- case "ERROR":
1194
- out += `\x1b[31m[ERROR]\x1b[0m`;
1195
- break;
1196
- }
1197
- out += ` \x1b[35m[${category.padEnd(8)}]\x1b[0m ${msg}`;
1198
- if (data !== void 0) try {
1199
- if (Buffer.isBuffer(data)) out += ` \x1b[90m<Buffer ${data.length}b>\x1b[0m`;
1200
- else if (typeof data === "object" && data !== null) out += ` \x1b[90m${JSON.stringify(data)}\x1b[0m`;
1201
- else out += ` \x1b[90m${data}\x1b[0m`;
1202
- } catch {
1203
- out += ` [Circular/Error]`;
1204
- }
1205
- return out;
1206
- }
1207
- };
1208
-
1209
- //#endregion
1210
- //#region src/infrastructure/services/UdpNetworkGateway.ts
1211
- /**
1212
- * Node.js UDP implementation of the network gateway.
1213
- * Handles the low-level socket communication and OSC packet routing.
1214
- */
1215
- var UdpNetworkGateway = class {
1216
- socket;
1217
- isRunning = false;
1218
- packetCallback = null;
1219
- /**
1220
- * Creates a new UdpNetworkGateway.
1221
- * @param logger - Logger service.
1222
- * @param codec - OSC codec for encoding/decoding.
1223
- */
1224
- constructor(logger, codec) {
1225
- this.logger = logger;
1226
- this.codec = codec;
1227
- this.socket = dgram.createSocket("udp4");
1228
- }
1229
- /**
1230
- * Registers a callback to be executed whenever a new OSC packet arrives.
1231
- * @param callback - Function called with decoded packet and source info.
1232
- */
1233
- onPacket(callback) {
1234
- this.packetCallback = callback;
1235
- }
1236
- /**
1237
- * Starts the UDP server on the specified port and IP.
1238
- * @param port - UDP port.
1239
- * @param ip - IP address to bind to.
1240
- * @returns Promise resolving when the socket is bound.
1241
- */
1242
- start(port, ip) {
1243
- return new Promise((resolve, reject) => {
1244
- this.socket.on("error", (err) => {
1245
- this.logger.error(LogCategory.SYSTEM, "Socket Error", err);
1246
- reject(err);
1247
- });
1248
- this.socket.on("message", (msg, rinfo) => {
1249
- try {
1250
- this.logger.debug(LogCategory.OSC_IN, `Packet received ${msg.length}b`, { ip: rinfo.address });
1251
- const decoded = this.codec.decode(msg);
1252
- if (this.packetCallback) this.packetCallback(decoded, {
1253
- address: rinfo.address,
1254
- port: rinfo.port
1255
- });
1256
- } catch (err) {
1257
- this.logger.error(LogCategory.OSC_IN, "Decode Error", err instanceof Error ? err : new Error(String(err)));
1258
- }
1259
- });
1260
- this.socket.bind(port, ip, () => {
1261
- this.logger.info(LogCategory.SYSTEM, `Server bound to ${ip}:${port}`);
1262
- this.isRunning = true;
1263
- resolve();
1264
- });
1265
- });
1266
- }
1267
- /**
1268
- * Shuts down the UDP server.
1269
- * @returns Promise resolving when the socket is closed.
1270
- */
1271
- stop() {
1272
- return new Promise((resolve) => {
1273
- if (!this.isRunning) return resolve();
1274
- this.socket.close(() => {
1275
- this.isRunning = false;
1276
- this.logger.info(LogCategory.SYSTEM, "Server stopped");
1277
- resolve();
1278
- });
1279
- });
1280
- }
1281
- /**
1282
- * Sends an OSC message to a specific remote client.
1283
- * @param target - Target client info (IP/port).
1284
- * @param address - OSC address pattern.
1285
- * @param args - Array of arguments.
1286
- */
1287
- send(target, address, args) {
1288
- const buf = this.codec.encode(address, args);
1289
- const cat = address.startsWith("/meters") ? LogCategory.METER : LogCategory.OSC_OUT;
1290
- this.logger.debug(cat, `Sending ${address}`, {
1291
- ip: target.address,
1292
- args
1293
- });
1294
- this.socket.send(buf, target.port, target.address, (err) => {
1295
- if (err) this.logger.error(LogCategory.OSC_OUT, "Send Error", err);
1296
- });
1297
- }
1298
- };
1299
-
1300
- //#endregion
1301
- //#region node_modules/node-osc/lib/Message.mjs
1302
- const typeTags = {
1303
- s: "string",
1304
- f: "float",
1305
- i: "integer",
1306
- b: "blob",
1307
- m: "midi"
1308
- };
1309
- /**
1310
- * Represents a typed argument for an OSC message.
1311
- *
1312
- * @class
1313
- * @private
1314
- */
1315
- var Argument = class {
1316
- /**
1317
- * @param {string} type - The type of the argument (string, float, integer, blob, boolean).
1318
- * @param {*} value - The value of the argument.
1319
- */
1320
- constructor(type, value) {
1321
- this.type = type;
1322
- this.value = value;
1323
- }
1324
- };
1325
- /**
1326
- * Represents an OSC message with an address and arguments.
1327
- *
1328
- * OSC messages consist of an address pattern (string starting with '/')
1329
- * and zero or more arguments of various types.
1330
- *
1331
- * @class
1332
- *
1333
- * @example
1334
- * // Create a message with constructor arguments
1335
- * const msg = new Message('/test', 1, 2, 'hello');
1336
- *
1337
- * @example
1338
- * // Create a message and append arguments
1339
- * const msg = new Message('/test');
1340
- * msg.append(1);
1341
- * msg.append('hello');
1342
- * msg.append(3.14);
1343
- */
1344
- var Message = class {
1345
- /**
1346
- * Create an OSC Message.
1347
- *
1348
- * @param {string} address - The OSC address pattern (e.g., '/oscillator/frequency').
1349
- * @param {...*} args - Optional arguments to include in the message.
1350
- *
1351
- * @example
1352
- * const msg = new Message('/test');
1353
- *
1354
- * @example
1355
- * const msg = new Message('/test', 1, 2, 3);
1356
- *
1357
- * @example
1358
- * const msg = new Message('/synth', 'note', 60, 0.5);
1359
- */
1360
- constructor(address, ...args) {
1361
- this.oscType = "message";
1362
- this.address = address;
1363
- this.args = args;
1364
- }
1365
- /**
1366
- * Append an argument to the message.
1367
- *
1368
- * Automatically detects the type based on the JavaScript type:
1369
- * - Integers are encoded as OSC integers
1370
- * - Floats are encoded as OSC floats
1371
- * - Strings are encoded as OSC strings
1372
- * - Booleans are encoded as OSC booleans
1373
- * - Buffers are encoded as OSC blobs
1374
- * - Arrays are recursively appended
1375
- * - Objects with a 'type' property are used as-is
1376
- *
1377
- * @param {*} arg - The argument to append. Can be:
1378
- * - A primitive value (number, string, boolean)
1379
- * - A Buffer (encoded as blob)
1380
- * - An array of values (will be recursively appended)
1381
- * - An object with 'type' and 'value' properties for explicit type control
1382
- *
1383
- * @throws {Error} If the argument type cannot be encoded.
1384
- *
1385
- * @example
1386
- * const msg = new Message('/test');
1387
- * msg.append(42); // Integer
1388
- * msg.append(3.14); // Float
1389
- * msg.append('hello'); // String
1390
- * msg.append(true); // Boolean
1391
- *
1392
- * @example
1393
- * // Append multiple values at once
1394
- * msg.append([1, 2, 3]);
1395
- *
1396
- * @example
1397
- * // Explicitly specify type
1398
- * msg.append({ type: 'float', value: 42 });
1399
- * msg.append({ type: 'blob', value: Buffer.from('data') });
1400
- *
1401
- * @example
1402
- * // MIDI messages (4 bytes: port, status, data1, data2)
1403
- * msg.append({ type: 'midi', value: { port: 0, status: 144, data1: 60, data2: 127 } });
1404
- * msg.append({ type: 'm', value: Buffer.from([0, 144, 60, 127]) });
1405
- */
1406
- append(arg) {
1407
- let argOut;
1408
- switch (typeof arg) {
1409
- case "object":
1410
- if (Buffer.isBuffer(arg)) this.args.push(arg);
1411
- else if (arg instanceof Array) arg.forEach((a) => this.append(a));
1412
- else if (arg.type) {
1413
- if (typeTags[arg.type]) arg.type = typeTags[arg.type];
1414
- this.args.push(arg);
1415
- } else throw new Error(`don't know how to encode object ${arg}`);
1416
- break;
1417
- case "number":
1418
- if (Math.floor(arg) === arg) argOut = new Argument("integer", arg);
1419
- else argOut = new Argument("float", arg);
1420
- break;
1421
- case "string":
1422
- argOut = new Argument("string", arg);
1423
- break;
1424
- case "boolean":
1425
- argOut = new Argument("boolean", arg);
1426
- break;
1427
- default: throw new Error(`don't know how to encode ${arg}`);
1428
- }
1429
- if (argOut) this.args.push(argOut);
1430
- }
1431
- };
1432
- var Message_default = Message;
1433
-
1434
- //#endregion
1435
- //#region node_modules/node-osc/lib/osc.mjs
1436
- function padString(str) {
1437
- const nullTerminated = str + "\0";
1438
- const padding = (4 - Buffer$1.byteLength(nullTerminated) % 4) % 4;
1439
- return nullTerminated + "\0".repeat(padding);
1440
- }
1441
- function readString(buffer, offset) {
1442
- let end = offset;
1443
- while (end < buffer.length && buffer[end] !== 0) end++;
1444
- if (end >= buffer.length) throw new Error("Malformed Packet: Missing null terminator for string");
1445
- return {
1446
- value: buffer.subarray(offset, end).toString("utf8"),
1447
- offset: offset + Math.ceil((end - offset + 1) / 4) * 4
1448
- };
1449
- }
1450
- function writeInt32(value) {
1451
- const buffer = Buffer$1.alloc(4);
1452
- buffer.writeInt32BE(value, 0);
1453
- return buffer;
1454
- }
1455
- function readInt32(buffer, offset) {
1456
- if (offset + 4 > buffer.length) throw new Error("Malformed Packet: Not enough bytes for int32");
1457
- return {
1458
- value: buffer.readInt32BE(offset),
1459
- offset: offset + 4
1460
- };
1461
- }
1462
- function writeFloat32(value) {
1463
- const buffer = Buffer$1.alloc(4);
1464
- buffer.writeFloatBE(value, 0);
1465
- return buffer;
1466
- }
1467
- function readFloat32(buffer, offset) {
1468
- if (offset + 4 > buffer.length) throw new Error("Malformed Packet: Not enough bytes for float32");
1469
- return {
1470
- value: buffer.readFloatBE(offset),
1471
- offset: offset + 4
1472
- };
1473
- }
1474
- function writeBlob(value) {
1475
- const length = value.length;
1476
- const lengthBuffer = writeInt32(length);
1477
- const padding = 4 - length % 4;
1478
- const paddingBuffer = Buffer$1.alloc(padding === 4 ? 0 : padding);
1479
- return Buffer$1.concat([
1480
- lengthBuffer,
1481
- value,
1482
- paddingBuffer
1483
- ]);
1484
- }
1485
- function readBlob(buffer, offset) {
1486
- const lengthResult = readInt32(buffer, offset);
1487
- const length = lengthResult.value;
1488
- if (length < 0) throw new Error("Malformed Packet: Invalid blob length");
1489
- if (lengthResult.offset + length > buffer.length) throw new Error("Malformed Packet: Not enough bytes for blob");
1490
- const data = buffer.subarray(lengthResult.offset, lengthResult.offset + length);
1491
- const padding = 4 - length % 4;
1492
- const nextOffset = lengthResult.offset + length + (padding === 4 ? 0 : padding);
1493
- if (nextOffset > buffer.length) throw new Error("Malformed Packet: Not enough bytes for blob padding");
1494
- return {
1495
- value: data,
1496
- offset: nextOffset
1497
- };
1498
- }
1499
- function writeTimeTag(value) {
1500
- const buffer = Buffer$1.alloc(8);
1501
- if (value === 0 || value === null || value === void 0) {
1502
- buffer.writeUInt32BE(0, 0);
1503
- buffer.writeUInt32BE(1, 4);
1504
- } else if (typeof value === "number") {
1505
- const seconds = Math.floor(value);
1506
- const fraction = Math.floor((value - seconds) * 4294967296);
1507
- buffer.writeUInt32BE(seconds + 2208988800, 0);
1508
- buffer.writeUInt32BE(fraction, 4);
1509
- } else {
1510
- buffer.writeUInt32BE(0, 0);
1511
- buffer.writeUInt32BE(1, 4);
1512
- }
1513
- return buffer;
1514
- }
1515
- function readTimeTag(buffer, offset) {
1516
- if (offset + 8 > buffer.length) throw new Error("Malformed Packet: Not enough bytes for timetag");
1517
- const seconds = buffer.readUInt32BE(offset);
1518
- const fraction = buffer.readUInt32BE(offset + 4);
1519
- let value;
1520
- if (seconds === 0 && fraction === 1) value = 0;
1521
- else value = seconds - 2208988800 + fraction / 4294967296;
1522
- return {
1523
- value,
1524
- offset: offset + 8
1525
- };
1526
- }
1527
- function writeMidi(value) {
1528
- const buffer = Buffer$1.alloc(4);
1529
- if (Buffer$1.isBuffer(value)) {
1530
- if (value.length !== 4) throw new Error("MIDI message must be exactly 4 bytes");
1531
- value.copy(buffer);
1532
- } else if (typeof value === "object" && value !== null) {
1533
- buffer.writeUInt8(value.port || 0, 0);
1534
- buffer.writeUInt8(value.status || 0, 1);
1535
- buffer.writeUInt8(value.data1 || 0, 2);
1536
- buffer.writeUInt8(value.data2 || 0, 3);
1537
- } else throw new Error("MIDI value must be a 4-byte Buffer or object with port, status, data1, data2 properties");
1538
- return buffer;
1539
- }
1540
- function readMidi(buffer, offset) {
1541
- if (offset + 4 > buffer.length) throw new Error("Not enough bytes for MIDI message");
1542
- return {
1543
- value: buffer.subarray(offset, offset + 4),
1544
- offset: offset + 4
1545
- };
1546
- }
1547
- function encodeArgument(arg) {
1548
- if (typeof arg === "object" && arg.type && arg.value !== void 0) switch (arg.type) {
1549
- case "i":
1550
- case "integer": return {
1551
- tag: "i",
1552
- data: writeInt32(arg.value)
1553
- };
1554
- case "f":
1555
- case "float": return {
1556
- tag: "f",
1557
- data: writeFloat32(arg.value)
1558
- };
1559
- case "s":
1560
- case "string": return {
1561
- tag: "s",
1562
- data: Buffer$1.from(padString(arg.value))
1563
- };
1564
- case "b":
1565
- case "blob": return {
1566
- tag: "b",
1567
- data: writeBlob(arg.value)
1568
- };
1569
- case "d":
1570
- case "double": return {
1571
- tag: "f",
1572
- data: writeFloat32(arg.value)
1573
- };
1574
- case "T": return {
1575
- tag: "T",
1576
- data: Buffer$1.alloc(0)
1577
- };
1578
- case "F": return {
1579
- tag: "F",
1580
- data: Buffer$1.alloc(0)
1581
- };
1582
- case "boolean": return arg.value ? {
1583
- tag: "T",
1584
- data: Buffer$1.alloc(0)
1585
- } : {
1586
- tag: "F",
1587
- data: Buffer$1.alloc(0)
1588
- };
1589
- case "m":
1590
- case "midi": return {
1591
- tag: "m",
1592
- data: writeMidi(arg.value)
1593
- };
1594
- default: throw new Error(`Unknown argument type: ${arg.type}`);
1595
- }
1596
- switch (typeof arg) {
1597
- case "number": if (Number.isInteger(arg)) return {
1598
- tag: "i",
1599
- data: writeInt32(arg)
1600
- };
1601
- else return {
1602
- tag: "f",
1603
- data: writeFloat32(arg)
1604
- };
1605
- case "string": return {
1606
- tag: "s",
1607
- data: Buffer$1.from(padString(arg))
1608
- };
1609
- case "boolean": return arg ? {
1610
- tag: "T",
1611
- data: Buffer$1.alloc(0)
1612
- } : {
1613
- tag: "F",
1614
- data: Buffer$1.alloc(0)
1615
- };
1616
- default:
1617
- if (Buffer$1.isBuffer(arg)) return {
1618
- tag: "b",
1619
- data: writeBlob(arg)
1620
- };
1621
- throw new Error(`Don't know how to encode argument: ${arg}`);
1622
- }
1623
- }
1624
- function decodeArgument(tag, buffer, offset) {
1625
- switch (tag) {
1626
- case "i": return readInt32(buffer, offset);
1627
- case "f": return readFloat32(buffer, offset);
1628
- case "s": return readString(buffer, offset);
1629
- case "b": return readBlob(buffer, offset);
1630
- case "T": return {
1631
- value: true,
1632
- offset
1633
- };
1634
- case "F": return {
1635
- value: false,
1636
- offset
1637
- };
1638
- case "N": return {
1639
- value: null,
1640
- offset
1641
- };
1642
- case "m": return readMidi(buffer, offset);
1643
- default: throw new Error(`I don't understand the argument code ${tag}`);
1644
- }
1645
- }
1646
- /**
1647
- * Encode an OSC message or bundle to a Buffer.
1648
- *
1649
- * This low-level function converts OSC messages and bundles into binary format
1650
- * for transmission or storage. Useful for sending OSC over custom transports
1651
- * (WebSocket, TCP, HTTP), storing to files, or implementing custom OSC routers.
1652
- *
1653
- * @param {Object} message - OSC message or bundle object with oscType property
1654
- * @returns {Buffer} The encoded OSC data ready for transmission
1655
- *
1656
- * @example
1657
- * // Encode a message
1658
- * import { Message, encode } from 'node-osc';
1659
- *
1660
- * const message = new Message('/oscillator/frequency', 440);
1661
- * const buffer = encode(message);
1662
- * console.log('Encoded bytes:', buffer.length);
1663
- *
1664
- * @example
1665
- * // Encode a bundle
1666
- * import { Bundle, encode } from 'node-osc';
1667
- *
1668
- * const bundle = new Bundle(['/one', 1], ['/two', 2]);
1669
- * const buffer = encode(bundle);
1670
- *
1671
- * @example
1672
- * // Send over WebSocket
1673
- * const buffer = encode(message);
1674
- * websocket.send(buffer);
1675
- */
1676
- function encode(message) {
1677
- if (message.oscType === "bundle") return encodeBundleToBuffer(message);
1678
- else return encodeMessageToBuffer(message);
1679
- }
1680
- function encodeMessageToBuffer(message) {
1681
- const address = padString(message.address);
1682
- const addressBuffer = Buffer$1.from(address);
1683
- const encodedArgs = message.args.map(encodeArgument);
1684
- const typeTags$1 = "," + encodedArgs.map((arg) => arg.tag).join("");
1685
- const typeTagsBuffer = Buffer$1.from(padString(typeTags$1));
1686
- const argumentBuffers = encodedArgs.map((arg) => arg.data);
1687
- return Buffer$1.concat([
1688
- addressBuffer,
1689
- typeTagsBuffer,
1690
- ...argumentBuffers
1691
- ]);
1692
- }
1693
- function encodeBundleToBuffer(bundle) {
1694
- const bundleString = padString("#bundle");
1695
- const bundleStringBuffer = Buffer$1.from(bundleString);
1696
- const timetagBuffer = writeTimeTag(bundle.timetag);
1697
- const elementBuffers = bundle.elements.map((element) => {
1698
- let elementBuffer;
1699
- if (element.oscType === "bundle") elementBuffer = encodeBundleToBuffer(element);
1700
- else elementBuffer = encodeMessageToBuffer(element);
1701
- const sizeBuffer = writeInt32(elementBuffer.length);
1702
- return Buffer$1.concat([sizeBuffer, elementBuffer]);
1703
- });
1704
- return Buffer$1.concat([
1705
- bundleStringBuffer,
1706
- timetagBuffer,
1707
- ...elementBuffers
1708
- ]);
1709
- }
1710
- /**
1711
- * Decode a Buffer containing OSC data into a message or bundle object.
1712
- *
1713
- * This low-level function parses binary OSC data back into JavaScript objects.
1714
- * Useful for receiving OSC over custom transports, reading from files,
1715
- * or implementing custom OSC routers.
1716
- *
1717
- * @param {Buffer} buffer - The Buffer containing OSC data
1718
- * @returns {Object} The decoded OSC message or bundle. Messages have
1719
- * {oscType: 'message', address: string, args: Array}, bundles have
1720
- * {oscType: 'bundle', timetag: number, elements: Array}
1721
- * @throws {Error} If the buffer contains malformed OSC data
1722
- *
1723
- * @example
1724
- * // Decode received data
1725
- * import { decode } from 'node-osc';
1726
- *
1727
- * const decoded = decode(buffer);
1728
- * if (decoded.oscType === 'message') {
1729
- * console.log('Address:', decoded.address);
1730
- * console.log('Arguments:', decoded.args);
1731
- * }
1732
- *
1733
- * @example
1734
- * // Round-trip encode/decode
1735
- * import { Message, encode, decode } from 'node-osc';
1736
- *
1737
- * const original = new Message('/test', 42, 'hello');
1738
- * const buffer = encode(original);
1739
- * const decoded = decode(buffer);
1740
- * console.log(decoded.address); // '/test'
1741
- */
1742
- function decode(buffer) {
1743
- if (buffer.length >= 8 && buffer.subarray(0, 8).toString() === "#bundle\0") return decodeBundleFromBuffer(buffer);
1744
- else return decodeMessageFromBuffer(buffer);
1745
- }
1746
- function decodeMessageFromBuffer(buffer) {
1747
- let offset = 0;
1748
- const addressResult = readString(buffer, offset);
1749
- const address = addressResult.value;
1750
- offset = addressResult.offset;
1751
- const typeTagsResult = readString(buffer, offset);
1752
- const typeTags$1 = typeTagsResult.value;
1753
- offset = typeTagsResult.offset;
1754
- if (!typeTags$1.startsWith(",")) throw new Error("Malformed Packet");
1755
- const tags = typeTags$1.slice(1);
1756
- const args = [];
1757
- for (const tag of tags) {
1758
- const argResult = decodeArgument(tag, buffer, offset);
1759
- args.push({ value: argResult.value });
1760
- offset = argResult.offset;
1761
- }
1762
- return {
1763
- oscType: "message",
1764
- address,
1765
- args
1766
- };
1767
- }
1768
- function decodeBundleFromBuffer(buffer) {
1769
- let offset = 8;
1770
- const timetagResult = readTimeTag(buffer, offset);
1771
- const timetag = timetagResult.value;
1772
- offset = timetagResult.offset;
1773
- const elements = [];
1774
- while (offset < buffer.length) {
1775
- const sizeResult = readInt32(buffer, offset);
1776
- const size = sizeResult.value;
1777
- offset = sizeResult.offset;
1778
- if (size <= 0 || offset + size > buffer.length) throw new Error("Malformed Packet");
1779
- const element = decode(buffer.subarray(offset, offset + size));
1780
- elements.push(element);
1781
- offset += size;
1782
- }
1783
- return {
1784
- oscType: "bundle",
1785
- timetag,
1786
- elements
1787
- };
1788
- }
1789
-
1790
- //#endregion
1791
- //#region src/infrastructure/mappers/OscCodec.ts
1792
- /**
1793
- * Handles encoding and decoding of X32 OSC messages.
1794
- */
1795
- var OscCodec = class {
1796
- constructor(schemaRegistry) {
1797
- this.schemaRegistry = schemaRegistry;
1798
- }
1799
- /**
1800
- * Decodes a binary OSC message into a packet object.
1801
- * @param msg - Raw UDP buffer.
1802
- * @returns Decoded OscPacket.
1803
- */
1804
- decode(msg) {
1805
- return decode(msg);
1806
- }
1807
- /**
1808
- * Encodes an address and arguments into a binary OSC message.
1809
- * @param address - OSC address pattern.
1810
- * @param args - Array of arguments.
1811
- * @returns Binary buffer.
1812
- */
1813
- encode(address, args) {
1814
- return encode(this.createMessage(address, args));
1815
- }
1816
- /**
1817
- * Creates a typed node-osc Message based on X32 schema.
1818
- * @param address - Target address.
1819
- * @param args - Untyped arguments.
1820
- * @returns Typed Message.
1821
- */
1822
- createMessage(address, args) {
1823
- return new Message_default(address, ...args.map((arg) => {
1824
- if (typeof arg === "object" && arg !== null && "type" in arg && "value" in arg) return arg;
1825
- if (Buffer.isBuffer(arg)) return arg;
1826
- const node = this.schemaRegistry.getNode(address);
1827
- if (node) {
1828
- if (node.type === "f" && typeof arg === "number") return {
1829
- type: "f",
1830
- value: arg
1831
- };
1832
- if (node.type === "i" && typeof arg === "number") return {
1833
- type: "i",
1834
- value: Math.round(arg)
1835
- };
1836
- if (node.type === "s" && typeof arg === "string") return {
1837
- type: "s",
1838
- value: arg
1839
- };
1840
- }
1841
- return arg;
1842
- }));
1843
- }
1844
- };
1845
-
1846
- //#endregion
1847
- //#region src/domain/services/SchemaFactory.ts
1848
- /**
1849
- * Factory service responsible for constructing the X32 OSC Schema.
1850
- * Encapsulates all the logic for generating channel strips, routing blocks, etc.
1851
- */
1852
- var SchemaFactory = class {
1853
- /**
1854
- * Builds the complete X32 OSC Schema.
1855
- * @returns The constructed schema map.
1856
- */
1857
- createSchema() {
1858
- const schema = {
1859
- ...this.generateNodes(32, "ch"),
1860
- ...this.generateNodes(16, "bus"),
1861
- ...this.generateNodes(8, "dca"),
1862
- ...this.generateNodes(8, "auxin"),
1863
- ...this.generateNodes(8, "fxrtn"),
1864
- ...this.generateNodes(6, "mtx"),
1865
- ...Object.fromEntries(Array.from({ length: 8 }, (_, i) => [`/fx/${i + 1}/type`, this.node("i", 0)])),
1866
- ...this.generateRange(8, "/fx", "/type", "i", 0),
1867
- ...this.generateRange(8, "/fx", "/source/l", "i", 0),
1868
- ...this.generateRange(8, "/fx", "/source/r", "i", 0),
1869
- ...Object.fromEntries(Array.from({ length: 8 }, (_, slot) => Object.entries(this.generateRange(64, `/fx/${slot + 1}/par`, "", "f", 0, 2, 1))).flat()),
1870
- ...this.generateRange(128, "/headamp", "/gain", "f", 0, 3, 0),
1871
- ...this.generateRange(128, "/headamp", "/phantom", "i", 0, 3, 0),
1872
- ...this.generateRange(6, "/config/mute", "", "i", 0),
1873
- ...this.generateRange(80, "/-stat/solosw", "", "i", 0),
1874
- "/-stat/selidx": this.node("i", 0),
1875
- "/-stat/sendsonfader": this.node("i", 0),
1876
- "/-stat/bussendbank": this.node("i", 0),
1877
- "/-stat/keysolo": this.node("i", 0),
1878
- "/-stat/screen/screen": this.node("i", 0),
1879
- "/-stat/screen/CHAN/page": this.node("i", 0),
1880
- "/-stat/screen/METER/page": this.node("i", 0),
1881
- "/-stat/screen/ROUTE/page": this.node("i", 0),
1882
- "/-stat/screen/SETUP/page": this.node("i", 0),
1883
- "/-stat/screen/LIBRARY/page": this.node("i", 0),
1884
- "/-stat/screen/FX/page": this.node("i", 0),
1885
- "/-stat/screen/MON/page": this.node("i", 0),
1886
- "/-stat/screen/USB/page": this.node("i", 0),
1887
- "/-stat/screen/SCENE/page": this.node("i", 0),
1888
- "/-stat/screen/ASSIGN/page": this.node("i", 0),
1889
- "/-stat/talk/A": this.node("i", 0),
1890
- "/-stat/talk/B": this.node("i", 0),
1891
- "/-stat/osc/on": this.node("i", 0),
1892
- "/-prefs/autosel": this.node("i", 1),
1893
- "/-action/setrtasrc": this.node("i", 0),
1894
- "/-action/playtrack": this.node("i", 0),
1895
- "/-action/goscene": this.node("i", 0),
1896
- "/-action/setscene": this.node("i", 0),
1897
- "/config/routing/AES50A/1-8": this.node("i", 0),
1898
- "/config/routing/AES50B/1-8": this.node("i", 0),
1899
- "/config/routing/CARD/1-8": this.node("i", 0),
1900
- "/config/routing/OUT/1-4": this.node("i", 0),
1901
- "/-prefs/invertmutes": this.node("i", 0),
1902
- ...this.generateChannelStrip("/main/st", 6, false),
1903
- ...this.generateChannelStrip("/main/m", 6, false),
1904
- ...Object.fromEntries(Array.from({ length: 16 }, (_, i) => [`/config/chlink/${i * 2 + 1}-${i * 2 + 2}`, this.node("i", 0)])),
1905
- ...Object.fromEntries(Array.from({ length: 8 }, (_, i) => [`/config/buslink/${i * 2 + 1}-${i * 2 + 2}`, this.node("i", 0)])),
1906
- ...Object.fromEntries(Array.from({ length: 4 }, (_, i) => [`/config/auxlink/${i * 2 + 1}-${i * 2 + 2}`, this.node("i", 0)])),
1907
- ...Object.fromEntries(Array.from({ length: 4 }, (_, i) => [`/config/fxlink/${i * 2 + 1}-${i * 2 + 2}`, this.node("i", 0)])),
1908
- ...this.generateRange(32, "/config/userrout/in", "", "i", 0),
1909
- ...this.generateRange(48, "/config/userrout/out", "", "i", 0),
1910
- "/config/solo/level": this.node("f", 0),
1911
- "/config/solo/source": this.node("i", 0),
1912
- "/config/solo/sourcetrim": this.node("f", 0),
1913
- "/config/solo/exclusive": this.node("i", 0),
1914
- "/config/solo/dim": this.node("i", 0),
1915
- "/config/solo/dimpfl": this.node("i", 0),
1916
- "/config/solo/dimatt": this.node("f", 0),
1917
- "/config/solo/mono": this.node("i", 0),
1918
- "/config/solo/chmode": this.node("i", 0),
1919
- "/config/solo/busmode": this.node("i", 0),
1920
- "/config/solo/dcamode": this.node("i", 0),
1921
- "/config/solo/masterctrl": this.node("i", 0),
1922
- "/config/solo/delay": this.node("i", 0),
1923
- "/config/solo/delaytime": this.node("f", 0),
1924
- "/config/solo/followsel": this.node("i", 0),
1925
- "/config/solo/followsolo": this.node("i", 0),
1926
- "/config/talk/enable": this.node("i", 0),
1927
- "/config/talk/source": this.node("i", 0),
1928
- "/config/talk/A/level": this.node("f", 0),
1929
- "/config/talk/B/level": this.node("f", 0),
1930
- "/config/talk/A/dim": this.node("i", 0),
1931
- "/config/talk/B/dim": this.node("i", 0),
1932
- "/config/talk/A/latch": this.node("i", 0),
1933
- "/config/talk/B/latch": this.node("i", 0),
1934
- "/config/talk/A/destmap": this.node("i", 0),
1935
- "/config/talk/B/destmap": this.node("i", 0),
1936
- "/config/osc/on": this.node("i", 0),
1937
- "/config/osc/type": this.node("i", 0),
1938
- "/config/osc/fsel": this.node("i", 0),
1939
- "/config/osc/f1": this.node("f", .5),
1940
- "/config/osc/f2": this.node("f", .5),
1941
- "/config/osc/level": this.node("f", 0),
1942
- "/config/osc/dest": this.node("i", 0),
1943
- ...this.generateOutputs("main", 16),
1944
- ...this.generateOutputs("aux", 6),
1945
- ...this.generateOutputs("p16", 16),
1946
- ...this.generateOutputs("aes", 2),
1947
- ...this.generateOutputs("rec", 2)
1948
- };
1949
- Object.keys(STATIC_RESPONSES_DATA).forEach((key) => {
1950
- if (key.startsWith("/-") || key.startsWith("/stat")) {
1951
- const val = STATIC_RESPONSES_DATA[key][0];
1952
- const type = typeof val === "string" ? "s" : Number.isInteger(val) ? "i" : "f";
1953
- schema[key] = this.node(type, val);
1954
- }
1955
- });
1956
- [
1957
- "/config/routing/IN/1-8",
1958
- "/config/routing/IN/9-16",
1959
- "/config/routing/IN/17-24",
1960
- "/config/routing/IN/25-32",
1961
- "/config/routing/AUX/1-4",
1962
- "/config/routing/OUT/1-4",
1963
- "/config/routing/OUT/5-8",
1964
- "/config/routing/OUT/9-12",
1965
- "/config/routing/OUT/13-16",
1966
- "/config/routing/P16/1-8",
1967
- "/config/routing/P16/9-16",
1968
- "/config/routing/CARD/1-8",
1969
- "/config/routing/CARD/9-16",
1970
- "/config/routing/CARD/17-24",
1971
- "/config/routing/CARD/25-32",
1972
- "/config/routing/AES50A/1-8",
1973
- "/config/routing/AES50A/9-16",
1974
- "/config/routing/AES50A/17-24",
1975
- "/config/routing/AES50A/25-32",
1976
- "/config/routing/AES50A/33-40",
1977
- "/config/routing/AES50A/41-48",
1978
- "/config/routing/AES50B/1-8",
1979
- "/config/routing/AES50B/9-16",
1980
- "/config/routing/AES50B/17-24",
1981
- "/config/routing/AES50B/25-32",
1982
- "/config/routing/AES50B/33-40",
1983
- "/config/routing/AES50B/41-48",
1984
- "/config/routing/PLAY/1-8",
1985
- "/config/routing/PLAY/9-16",
1986
- "/config/routing/PLAY/17-24",
1987
- "/config/routing/PLAY/25-32"
1988
- ].forEach((path) => {
1989
- schema[path] = this.node("i", 0);
1990
- });
1991
- return schema;
1992
- }
1993
- node(type, def) {
1994
- return new X32Node(type, def);
1995
- }
1996
- generateChannelStrip(base, eqBands = 4, hasPreamp = false) {
1997
- const nodes = {};
1998
- nodes[`${base}/config/name`] = this.node("s", base.split("/").pop()?.toUpperCase() || "");
1999
- nodes[`${base}/config/icon`] = this.node("i", 1);
2000
- nodes[`${base}/config/color`] = this.node("i", 1);
2001
- nodes[`${base}/config/source`] = this.node("i", 1);
2002
- nodes[`${base}/mix/fader`] = this.node("f", .75);
2003
- nodes[`${base}/mix/on`] = this.node("i", 0);
2004
- nodes[`${base}/mix/pan`] = this.node("f", .5);
2005
- nodes[`${base}/mix/mono`] = this.node("i", 0);
2006
- nodes[`${base}/mix/mlevel`] = this.node("f", 0);
2007
- nodes[`${base}/mix/st`] = this.node("i", 1);
2008
- if (hasPreamp) {
2009
- nodes[`${base}/preamp/trim`] = this.node("f", .5);
2010
- nodes[`${base}/preamp/hpon`] = this.node("i", 0);
2011
- nodes[`${base}/preamp/hpf`] = this.node("f", 0);
2012
- nodes[`${base}/preamp/phantom`] = this.node("i", 0);
2013
- nodes[`${base}/preamp/rtnsw`] = this.node("i", 0);
2014
- nodes[`${base}/preamp/invert`] = this.node("i", 0);
2015
- }
2016
- nodes[`${base}/delay/on`] = this.node("i", 0);
2017
- nodes[`${base}/delay/time`] = this.node("f", 0);
2018
- nodes[`${base}/insert/on`] = this.node("i", 0);
2019
- nodes[`${base}/insert/pos`] = this.node("i", 0);
2020
- nodes[`${base}/insert/sel`] = this.node("i", 0);
2021
- nodes[`${base}/gate/on`] = this.node("i", 0);
2022
- nodes[`${base}/gate/mode`] = this.node("i", 0);
2023
- nodes[`${base}/gate/thr`] = this.node("f", 0);
2024
- nodes[`${base}/gate/range`] = this.node("f", 0);
2025
- nodes[`${base}/gate/attack`] = this.node("f", 0);
2026
- nodes[`${base}/gate/hold`] = this.node("f", 0);
2027
- nodes[`${base}/gate/release`] = this.node("f", 0);
2028
- nodes[`${base}/gate/keysrc`] = this.node("i", 0);
2029
- nodes[`${base}/gate/filter/on`] = this.node("i", 0);
2030
- nodes[`${base}/gate/filter/type`] = this.node("i", 0);
2031
- nodes[`${base}/gate/filter/f`] = this.node("f", .5);
2032
- nodes[`${base}/dyn/on`] = this.node("i", 0);
2033
- nodes[`${base}/dyn/mode`] = this.node("i", 0);
2034
- nodes[`${base}/dyn/pos`] = this.node("i", 0);
2035
- nodes[`${base}/dyn/det`] = this.node("i", 0);
2036
- nodes[`${base}/dyn/env`] = this.node("i", 0);
2037
- nodes[`${base}/dyn/thr`] = this.node("f", 0);
2038
- nodes[`${base}/dyn/ratio`] = this.node("i", 0);
2039
- nodes[`${base}/dyn/knee`] = this.node("f", 0);
2040
- nodes[`${base}/dyn/mgain`] = this.node("f", 0);
2041
- nodes[`${base}/dyn/attack`] = this.node("f", 0);
2042
- nodes[`${base}/dyn/hold`] = this.node("f", 0);
2043
- nodes[`${base}/dyn/release`] = this.node("f", 0);
2044
- nodes[`${base}/dyn/mix`] = this.node("f", 1);
2045
- nodes[`${base}/dyn/auto`] = this.node("i", 0);
2046
- nodes[`${base}/dyn/keysrc`] = this.node("i", 0);
2047
- nodes[`${base}/dyn/filter/on`] = this.node("i", 0);
2048
- nodes[`${base}/dyn/filter/type`] = this.node("i", 0);
2049
- nodes[`${base}/dyn/filter/f`] = this.node("f", .5);
2050
- nodes[`${base}/eq/on`] = this.node("i", 0);
2051
- nodes[`${base}/eq/mode`] = this.node("i", 0);
2052
- for (let b = 1; b <= eqBands; b++) {
2053
- nodes[`${base}/eq/${b}/type`] = this.node("i", 0);
2054
- nodes[`${base}/eq/${b}/f`] = this.node("f", .5);
2055
- nodes[`${base}/eq/${b}/g`] = this.node("f", .5);
2056
- nodes[`${base}/eq/${b}/q`] = this.node("f", .5);
2057
- }
2058
- nodes[`${base}/grp/dca`] = this.node("i", 0);
2059
- nodes[`${base}/grp/mute`] = this.node("i", 0);
2060
- return nodes;
2061
- }
2062
- generateNodes(count, prefix) {
2063
- const nodes = {};
2064
- const isChannelOrAux = prefix === "ch" || prefix === "auxin";
2065
- const eqBands = prefix === "bus" || prefix === "mtx" ? 6 : 4;
2066
- for (let i = 1; i <= count; i++) {
2067
- const padId = i.toString().padStart(2, "0");
2068
- [i.toString(), padId].forEach((id) => {
2069
- const base = `/${prefix}/${id}`;
2070
- if (prefix === "dca") {
2071
- nodes[`${base}/config/name`] = this.node("s", `DCA ${id}`);
2072
- nodes[`${base}/config/color`] = this.node("i", 1);
2073
- nodes[`${base}/fader`] = this.node("f", .75);
2074
- nodes[`${base}/on`] = this.node("i", 0);
2075
- } else {
2076
- Object.assign(nodes, this.generateChannelStrip(base, eqBands, isChannelOrAux));
2077
- if (prefix === "ch" || prefix === "auxin" || prefix === "fxrtn" || prefix === "bus") for (let b = 1; b <= 16; b++) {
2078
- const busId = b.toString().padStart(2, "0");
2079
- nodes[`${base}/mix/${busId}/level`] = this.node("f", 0);
2080
- nodes[`${base}/mix/${busId}/on`] = this.node("i", 0);
2081
- nodes[`${base}/mix/${busId}/pan`] = this.node("f", .5);
2082
- nodes[`${base}/mix/${busId}/type`] = this.node("i", 0);
2083
- }
2084
- }
2085
- });
2086
- }
2087
- return nodes;
2088
- }
2089
- generateRange(count, prefix, suffix, type, def, pad = 2, start = 1) {
2090
- const nodes = {};
2091
- for (let i = start; i < start + count; i++) {
2092
- const id = i.toString().padStart(pad, "0");
2093
- nodes[`${prefix}/${i}${suffix}`] = this.node(type, def);
2094
- nodes[`${prefix}/${id}${suffix}`] = this.node(type, def);
2095
- }
2096
- return nodes;
2097
- }
2098
- generateOutputs(prefix, count) {
2099
- const nodes = {};
2100
- for (let i = 1; i <= count; i++) {
2101
- const base = `/outputs/${prefix}/${i.toString().padStart(2, "0")}`;
2102
- nodes[`${base}/src`] = this.node("i", 0);
2103
- nodes[`${base}/pos`] = this.node("i", 0);
2104
- nodes[`${base}/invert`] = this.node("i", 0);
2105
- nodes[`${base}/delay/on`] = this.node("i", 0);
2106
- nodes[`${base}/delay/time`] = this.node("f", 0);
2107
- if (prefix === "p16") {
2108
- nodes[`${base}/iQ/group`] = this.node("i", 0);
2109
- nodes[`${base}/iQ/model`] = this.node("i", 0);
2110
- nodes[`${base}/iQ/eq`] = this.node("i", 0);
2111
- nodes[`${base}/iQ/speaker`] = this.node("i", 0);
2112
- }
2113
- }
2114
- return nodes;
2115
- }
2116
- };
2117
-
2118
- //#endregion
2119
- //#region src/domain/services/SchemaRegistry.ts
2120
- /**
2121
- * Service providing access to the X32 OSC Schema.
2122
- * Acts as the "Registry" of all available console parameters.
2123
- */
2124
- var SchemaRegistry = class {
2125
- _schema;
2126
- constructor(schemaFactory) {
2127
- this.schemaFactory = schemaFactory;
2128
- this._schema = this.schemaFactory.createSchema();
2129
- }
2130
- /**
2131
- * Retrieves the entire schema map.
2132
- * @returns The internal schema definition record.
2133
- */
2134
- getSchema() {
2135
- return this._schema;
2136
- }
2137
- /**
2138
- * Retrieves the node definition for a given path.
2139
- * @param path - The OSC path.
2140
- * @returns The X32Node definition or undefined if not found.
2141
- */
2142
- getNode(path) {
2143
- return this._schema[path];
2144
- }
2145
- /**
2146
- * Checks if a path exists in the schema.
2147
- * @param path - The path to check.
2148
- * @returns True if the path is registered.
2149
- */
2150
- has(path) {
2151
- return path in this._schema;
2152
- }
2153
- /**
2154
- * Returns all paths in the schema.
2155
- * @returns Array of all registered OSC paths.
2156
- */
2157
- getAllPaths() {
2158
- return Object.keys(this._schema);
2159
- }
2160
- /**
2161
- * Maps an absolute X32 global index to its specific OSC root path.
2162
- * Used for batch subscriptions where clients request ranges of channels.
2163
- * @param index - The absolute integer index.
2164
- * @returns The root path string or null if index is out of bounds.
2165
- */
2166
- getRootFromIndex(index) {
2167
- if (index >= 0 && index <= 31) return `/ch/${(index + 1).toString().padStart(2, "0")}`;
2168
- if (index >= 32 && index <= 39) return `/auxin/${(index - 31).toString().padStart(2, "0")}`;
2169
- if (index >= 40 && index <= 47) return `/fxrtn/${(index - 39).toString().padStart(2, "0")}`;
2170
- if (index >= 48 && index <= 63) return `/bus/${(index - 47).toString().padStart(2, "0")}`;
2171
- if (index >= 64 && index <= 69) return `/mtx/${(index - 63).toString().padStart(2, "0")}`;
2172
- if (index === 70) return "/main/st";
2173
- if (index === 71) return "/main/m";
2174
- if (index >= 72 && index <= 79) return `/dca/${(index - 71).toString().padStart(2, "0")}`;
2175
- return null;
2176
- }
2177
- };
2178
-
2179
- //#endregion
2180
- export { ConsoleLogger as a, X32Node as c, METER_COUNTS as d, MeterData as f, UdpNetworkGateway as i, X32State as l, LogCategory as m, SchemaFactory as n, LogLevel as o, SubscriptionManager as p, OscCodec as r, InMemoryStateRepository as s, SchemaRegistry as t, SimulationService as u };