@supraio/client-daemon-js 0.0.1 → 1.0.0-mzbrightsigndecoder.473

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/daemon.js CHANGED
@@ -10290,12 +10290,12 @@
10290
10290
  if (process2["initializeTTYs"]) {
10291
10291
  process2["initializeTTYs"]();
10292
10292
  }
10293
- function install2(obj) {
10293
+ function install(obj) {
10294
10294
  obj.Buffer = Buffer2;
10295
10295
  obj.process = process2;
10296
10296
  var oldRequire = obj.require ? obj.require : null;
10297
10297
  obj.require = function(arg) {
10298
- var rv = BFSRequire(arg);
10298
+ var rv = BFSRequire2(arg);
10299
10299
  if (!rv) {
10300
10300
  return oldRequire.apply(null, Array.prototype.slice.call(arguments, 0));
10301
10301
  } else {
@@ -10306,7 +10306,7 @@
10306
10306
  function registerFileSystem(name, fs2) {
10307
10307
  Backends[name] = fs2;
10308
10308
  }
10309
- function BFSRequire(module4) {
10309
+ function BFSRequire2(module4) {
10310
10310
  switch (module4) {
10311
10311
  case "fs":
10312
10312
  return _fsMock;
@@ -10421,9 +10421,9 @@
10421
10421
  };
10422
10422
  }
10423
10423
  }
10424
- exports2.install = install2;
10424
+ exports2.install = install;
10425
10425
  exports2.registerFileSystem = registerFileSystem;
10426
- exports2.BFSRequire = BFSRequire;
10426
+ exports2.BFSRequire = BFSRequire2;
10427
10427
  exports2.initialize = initialize;
10428
10428
  exports2.configure = configure2;
10429
10429
  exports2.getFileSystem = getFileSystem;
@@ -16830,6 +16830,3426 @@
16830
16830
  }
16831
16831
  });
16832
16832
 
16833
+ // node_modules/@signageos/brightsign-decoder/dist/contracts.js
16834
+ var require_contracts = __commonJS({
16835
+ "node_modules/@signageos/brightsign-decoder/dist/contracts.js"(exports) {
16836
+ "use strict";
16837
+ Object.defineProperty(exports, "__esModule", { value: true });
16838
+ exports.ConnectionState = exports.FrameType = void 0;
16839
+ var FrameType;
16840
+ (function(FrameType2) {
16841
+ FrameType2[FrameType2["Delta"] = 0] = "Delta";
16842
+ FrameType2[FrameType2["Key"] = 1] = "Key";
16843
+ })(FrameType || (exports.FrameType = FrameType = {}));
16844
+ var ConnectionState;
16845
+ (function(ConnectionState2) {
16846
+ ConnectionState2["Connecting"] = "connecting";
16847
+ ConnectionState2["Connected"] = "connected";
16848
+ ConnectionState2["Closed"] = "closed";
16849
+ ConnectionState2["Error"] = "error";
16850
+ })(ConnectionState || (exports.ConnectionState = ConnectionState = {}));
16851
+ }
16852
+ });
16853
+
16854
+ // node_modules/@signageos/brightsign-decoder/dist/tcp/PacketParser.js
16855
+ var require_PacketParser = __commonJS({
16856
+ "node_modules/@signageos/brightsign-decoder/dist/tcp/PacketParser.js"(exports) {
16857
+ "use strict";
16858
+ Object.defineProperty(exports, "__esModule", { value: true });
16859
+ exports.PacketParser = void 0;
16860
+ var HEADER_SIZE = 2;
16861
+ var DEFAULT_MAX_PACKET_SIZE = 32 * 1024;
16862
+ var DEFAULT_MAX_QUEUED_BYTES = 1024 * 1024;
16863
+ var PacketParser = class {
16864
+ constructor(options) {
16865
+ this.chunks = [];
16866
+ this.headIndex = 0;
16867
+ this.chunkOffset = 0;
16868
+ this.queuedBytes = 0;
16869
+ this.pending = [];
16870
+ this.maxPacketSize = options !== void 0 && options !== null && options.maxPacketSize !== void 0 ? options.maxPacketSize : DEFAULT_MAX_PACKET_SIZE;
16871
+ this.maxQueuedBytes = options !== void 0 && options !== null && options.maxQueuedBytes !== void 0 ? options.maxQueuedBytes : DEFAULT_MAX_QUEUED_BYTES;
16872
+ if (!Number.isSafeInteger(this.maxPacketSize) || this.maxPacketSize <= 0 || this.maxPacketSize > 65535) {
16873
+ throw new RangeError(`maxPacketSize must be an integer in 1..65535, got ${this.maxPacketSize}`);
16874
+ }
16875
+ if (!Number.isSafeInteger(this.maxQueuedBytes) || this.maxQueuedBytes <= 0) {
16876
+ throw new RangeError(`maxQueuedBytes must be positive, got ${this.maxQueuedBytes}`);
16877
+ }
16878
+ }
16879
+ /** Push a socket chunk. Returns array of complete packets parsed so far. */
16880
+ push(data) {
16881
+ if (data.byteLength === 0) {
16882
+ return [];
16883
+ }
16884
+ const nextQueuedBytes = this.queuedBytes + data.byteLength;
16885
+ if (nextQueuedBytes > this.maxQueuedBytes) {
16886
+ throw new RangeError(`Queued bytes would exceed limit: ${nextQueuedBytes} > ${this.maxQueuedBytes}`);
16887
+ }
16888
+ this.chunks.push(data);
16889
+ this.queuedBytes = nextQueuedBytes;
16890
+ this.pending.length = 0;
16891
+ this.parse();
16892
+ const result = this.pending.slice();
16893
+ this.pending.length = 0;
16894
+ return result;
16895
+ }
16896
+ /** Verify no leftover bytes remain. */
16897
+ finish() {
16898
+ if (this.queuedBytes !== 0) {
16899
+ throw new Error(`TCP stream ended with ${this.queuedBytes} unparsed bytes`);
16900
+ }
16901
+ }
16902
+ /** Clear buffered chunks, cursors, and pending parser state. */
16903
+ reset() {
16904
+ this.clearState();
16905
+ }
16906
+ /** Idempotently discard all parser state. */
16907
+ destroy() {
16908
+ this.clearState();
16909
+ }
16910
+ /** Current number of queued bytes. */
16911
+ get bufferedBytes() {
16912
+ return this.queuedBytes;
16913
+ }
16914
+ peekByte(offset) {
16915
+ let remaining = offset;
16916
+ for (let index = this.headIndex; index < this.chunks.length; index += 1) {
16917
+ const start = index === this.headIndex ? this.chunkOffset : 0;
16918
+ const chunk = this.chunks[index];
16919
+ if (chunk === void 0) {
16920
+ break;
16921
+ }
16922
+ const available = chunk.byteLength - start;
16923
+ if (remaining < available) {
16924
+ const byteValue = chunk[start + remaining];
16925
+ if (byteValue === void 0) {
16926
+ throw new Error("Packet parser peek: unexpected undefined byte");
16927
+ }
16928
+ return byteValue;
16929
+ }
16930
+ remaining -= available;
16931
+ }
16932
+ throw new Error("Packet parser peek exceeded queued bytes");
16933
+ }
16934
+ readInto(destination) {
16935
+ let written = 0;
16936
+ while (written < destination.byteLength) {
16937
+ const chunk = this.chunks[this.headIndex];
16938
+ if (chunk === void 0) {
16939
+ throw new Error("Packet parser read: no more chunks");
16940
+ }
16941
+ const available = chunk.byteLength - this.chunkOffset;
16942
+ const length = Math.min(available, destination.byteLength - written);
16943
+ destination.set(chunk.subarray(this.chunkOffset, this.chunkOffset + length), written);
16944
+ written += length;
16945
+ this.chunkOffset += length;
16946
+ this.queuedBytes -= length;
16947
+ if (this.chunkOffset === chunk.byteLength) {
16948
+ this.headIndex += 1;
16949
+ this.chunkOffset = 0;
16950
+ if (this.queuedBytes === 0) {
16951
+ this.chunks.length = 0;
16952
+ this.headIndex = 0;
16953
+ } else if (this.headIndex >= 16 && this.headIndex * 2 >= this.chunks.length) {
16954
+ this.chunks.splice(0, this.headIndex);
16955
+ this.headIndex = 0;
16956
+ }
16957
+ }
16958
+ }
16959
+ }
16960
+ parse() {
16961
+ while (this.queuedBytes >= HEADER_SIZE) {
16962
+ const packetLength = this.peekByte(0) * 256 + this.peekByte(1);
16963
+ if (packetLength === 0) {
16964
+ throw new RangeError("Packet length is zero");
16965
+ }
16966
+ if (packetLength > this.maxPacketSize) {
16967
+ throw new RangeError(`Packet length ${packetLength} exceeds maxPacketSize ${this.maxPacketSize}`);
16968
+ }
16969
+ if (this.queuedBytes < packetLength + HEADER_SIZE) {
16970
+ return;
16971
+ }
16972
+ const header = new Uint8Array(HEADER_SIZE);
16973
+ this.readInto(header);
16974
+ const packet = new Uint8Array(packetLength);
16975
+ this.readInto(packet);
16976
+ this.pending.push(packet);
16977
+ }
16978
+ }
16979
+ clearState() {
16980
+ this.chunks.length = 0;
16981
+ this.headIndex = 0;
16982
+ this.chunkOffset = 0;
16983
+ this.queuedBytes = 0;
16984
+ this.pending.length = 0;
16985
+ }
16986
+ };
16987
+ exports.PacketParser = PacketParser;
16988
+ }
16989
+ });
16990
+
16991
+ // node_modules/@signageos/brightsign-decoder/dist/frame/protocol.js
16992
+ var require_protocol = __commonJS({
16993
+ "node_modules/@signageos/brightsign-decoder/dist/frame/protocol.js"(exports) {
16994
+ "use strict";
16995
+ Object.defineProperty(exports, "__esModule", { value: true });
16996
+ exports.FIRST_HEADER_SIZE = exports.FIRST_PACKET_EXTRA = exports.GENERAL_HEADER_SIZE = void 0;
16997
+ exports.parseInnerHeader = parseInnerHeader;
16998
+ exports.parseFirstPacketMeta = parseFirstPacketMeta;
16999
+ exports.GENERAL_HEADER_SIZE = 6;
17000
+ exports.FIRST_PACKET_EXTRA = 9;
17001
+ exports.FIRST_HEADER_SIZE = exports.GENERAL_HEADER_SIZE + exports.FIRST_PACKET_EXTRA;
17002
+ function parseInnerHeader(packet) {
17003
+ if (packet.byteLength < exports.GENERAL_HEADER_SIZE) {
17004
+ throw new RangeError(`Packet too short for inner header: ${packet.byteLength} < ${exports.GENERAL_HEADER_SIZE}`);
17005
+ }
17006
+ const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
17007
+ return {
17008
+ frameId: view.getUint16(0),
17009
+ sequence: view.getUint16(2),
17010
+ totalPackets: view.getUint16(4)
17011
+ };
17012
+ }
17013
+ function parseFirstPacketMeta(packet) {
17014
+ if (packet.byteLength < exports.FIRST_HEADER_SIZE) {
17015
+ throw new RangeError(`Packet too short for first-packet header: ${packet.byteLength} < ${exports.FIRST_HEADER_SIZE}`);
17016
+ }
17017
+ const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
17018
+ return {
17019
+ frameType: view.getUint8(6),
17020
+ timestampHi: view.getUint32(7),
17021
+ timestampLo: view.getUint32(11)
17022
+ };
17023
+ }
17024
+ }
17025
+ });
17026
+
17027
+ // node_modules/@signageos/brightsign-decoder/dist/frame/FrameCollector.js
17028
+ var require_FrameCollector = __commonJS({
17029
+ "node_modules/@signageos/brightsign-decoder/dist/frame/FrameCollector.js"(exports) {
17030
+ "use strict";
17031
+ Object.defineProperty(exports, "__esModule", { value: true });
17032
+ exports.FrameCollector = void 0;
17033
+ var contracts_1 = require_contracts();
17034
+ var protocol_1 = require_protocol();
17035
+ var DEFAULT_MAX_ASSEMBLING = 16;
17036
+ var DEFAULT_MAX_COMPLETED = 1;
17037
+ var DEFAULT_MAX_PACKET_SIZE = 32 * 1024;
17038
+ var DEFAULT_MAX_FRAME_SIZE = 4 * 1024 * 1024;
17039
+ function validatePositiveInt(name, value) {
17040
+ if (!Number.isInteger(value) || value <= 0) {
17041
+ throw new RangeError(`${name} must be a positive integer, got ${value}`);
17042
+ }
17043
+ }
17044
+ var FrameCollector = class {
17045
+ constructor(registry, options) {
17046
+ this.assembling = /* @__PURE__ */ new Map();
17047
+ this.completed = [];
17048
+ this.registry = registry;
17049
+ this.maxAssembling = options !== void 0 && options !== null && options.maxAssembling !== void 0 ? options.maxAssembling : DEFAULT_MAX_ASSEMBLING;
17050
+ this.maxCompleted = options !== void 0 && options !== null && options.maxCompleted !== void 0 ? options.maxCompleted : DEFAULT_MAX_COMPLETED;
17051
+ this.maxPacketSize = options !== void 0 && options !== null && options.maxPacketSize !== void 0 ? options.maxPacketSize : DEFAULT_MAX_PACKET_SIZE;
17052
+ this.maxFrameSize = options !== void 0 && options !== null && options.maxFrameSize !== void 0 ? options.maxFrameSize : DEFAULT_MAX_FRAME_SIZE;
17053
+ validatePositiveInt("maxAssembling", this.maxAssembling);
17054
+ validatePositiveInt("maxCompleted", this.maxCompleted);
17055
+ validatePositiveInt("maxPacketSize", this.maxPacketSize);
17056
+ validatePositiveInt("maxFrameSize", this.maxFrameSize);
17057
+ if (this.maxPacketSize <= protocol_1.FIRST_HEADER_SIZE) {
17058
+ throw new RangeError(`maxPacketSize (${this.maxPacketSize}) must be greater than first-packet header size (${protocol_1.FIRST_HEADER_SIZE})`);
17059
+ }
17060
+ }
17061
+ /** Can the collector accept another packet? */
17062
+ get canAccept() {
17063
+ return this.completed.length < this.maxCompleted || this.assembling.size < this.maxAssembling;
17064
+ }
17065
+ /** Number of completed frames awaiting consumption. */
17066
+ get completedCount() {
17067
+ return this.completed.length;
17068
+ }
17069
+ /** Number of currently assembling frames. */
17070
+ get assemblingCount() {
17071
+ return this.assembling.size;
17072
+ }
17073
+ /** Is the completed queue full? */
17074
+ get isCompletedFull() {
17075
+ return this.completed.length >= this.maxCompleted;
17076
+ }
17077
+ /** Take the oldest completed frame reference and transfer exposure to the caller. Returns undefined if none. */
17078
+ take() {
17079
+ const completedFrame = this.completed.shift();
17080
+ if (completedFrame !== void 0) {
17081
+ this.promoteReadyFrames();
17082
+ }
17083
+ return completedFrame;
17084
+ }
17085
+ /**
17086
+ * Accept a protocol fragment packet.
17087
+ * Completed frames stay owned by the collector until a later take() call
17088
+ * dequeues the oldest ready frame in first-seen order.
17089
+ */
17090
+ accept(packet) {
17091
+ if (packet.byteLength > this.maxPacketSize) {
17092
+ throw new RangeError(`Inner packet length ${packet.byteLength} exceeds maxPacketSize ${this.maxPacketSize}`);
17093
+ }
17094
+ const header = (0, protocol_1.parseInnerHeader)(packet);
17095
+ const { frameId, sequence, totalPackets } = header;
17096
+ if (totalPackets === 0) {
17097
+ throw new RangeError(`Frame ${frameId}: totalPackets is zero`);
17098
+ }
17099
+ if (sequence >= totalPackets) {
17100
+ throw new RangeError(`Frame ${frameId}: sequence ${sequence} >= totalPackets ${totalPackets}`);
17101
+ }
17102
+ const headerSize = sequence === 0 ? protocol_1.FIRST_HEADER_SIZE : protocol_1.GENERAL_HEADER_SIZE;
17103
+ if (packet.byteLength < headerSize) {
17104
+ throw new RangeError(`Frame ${frameId}: packet too short for header: ${packet.byteLength} < ${headerSize}`);
17105
+ }
17106
+ const normalCapacity = this.maxPacketSize - protocol_1.GENERAL_HEADER_SIZE;
17107
+ if (normalCapacity <= 0) {
17108
+ throw new RangeError("maxPacketSize too small for frame header");
17109
+ }
17110
+ const worstCaseCapacity = totalPackets * normalCapacity - protocol_1.FIRST_PACKET_EXTRA;
17111
+ if (worstCaseCapacity <= 0) {
17112
+ throw new RangeError(`Frame ${frameId}: computed capacity ${worstCaseCapacity} is non-positive`);
17113
+ }
17114
+ if (worstCaseCapacity > this.maxFrameSize) {
17115
+ throw new RangeError(`Frame ${frameId}: computed capacity ${worstCaseCapacity} exceeds maxFrameSize ${this.maxFrameSize}`);
17116
+ }
17117
+ if (sequence !== 0 && sequence < totalPackets - 1) {
17118
+ const expectedPayload = normalCapacity;
17119
+ const actualPayload = packet.byteLength - headerSize;
17120
+ if (actualPayload !== expectedPayload) {
17121
+ throw new RangeError(`Frame ${frameId}: non-final fragment seq ${sequence} has ${actualPayload} payload bytes, expected ${expectedPayload}`);
17122
+ }
17123
+ }
17124
+ if (sequence === 0 && totalPackets > 1) {
17125
+ const firstCapacity = this.maxPacketSize - protocol_1.FIRST_HEADER_SIZE;
17126
+ const actualPayload = packet.byteLength - headerSize;
17127
+ if (actualPayload !== firstCapacity) {
17128
+ throw new RangeError(`Frame ${frameId}: non-final first packet has ${actualPayload} payload bytes, expected ${firstCapacity}`);
17129
+ }
17130
+ }
17131
+ let parsedFrameType;
17132
+ let parsedTimestampHi = 0;
17133
+ let parsedTimestampLo = 0;
17134
+ if (sequence === 0) {
17135
+ const meta = (0, protocol_1.parseFirstPacketMeta)(packet);
17136
+ if (meta.frameType !== contracts_1.FrameType.Delta && meta.frameType !== contracts_1.FrameType.Key) {
17137
+ throw new RangeError(`Frame ${frameId}: invalid frameType ${meta.frameType}`);
17138
+ }
17139
+ parsedFrameType = meta.frameType;
17140
+ parsedTimestampHi = meta.timestampHi;
17141
+ parsedTimestampLo = meta.timestampLo;
17142
+ }
17143
+ const payload = packet.subarray(headerSize);
17144
+ const destinationOffset = sequence === 0 ? 0 : sequence * normalCapacity - protocol_1.FIRST_PACKET_EXTRA;
17145
+ if (destinationOffset < 0) {
17146
+ throw new RangeError(`Frame ${frameId}: negative destination offset for sequence ${sequence}`);
17147
+ }
17148
+ const destinationEnd = destinationOffset + payload.byteLength;
17149
+ if (destinationEnd > worstCaseCapacity) {
17150
+ throw new RangeError(`Frame ${frameId}: payload exceeds allocation at sequence ${sequence}`);
17151
+ }
17152
+ let frame = this.assembling.get(frameId);
17153
+ if (frame === void 0) {
17154
+ const wouldCompleteOldest = totalPackets === 1 && this.assembling.size === 0;
17155
+ if (wouldCompleteOldest && this.completed.length >= this.maxCompleted) {
17156
+ throw new Error("Frame collector: completed queue full");
17157
+ }
17158
+ if (this.assembling.size >= this.maxAssembling) {
17159
+ throw new Error("Frame collector: assembling capacity exceeded");
17160
+ }
17161
+ frame = {
17162
+ buffer: new Uint8Array(worstCaseCapacity),
17163
+ frameId,
17164
+ totalPackets,
17165
+ received: Array.from({ length: totalPackets }).fill(false),
17166
+ receivedCount: 0,
17167
+ usedLength: 0,
17168
+ frameType: contracts_1.FrameType.Delta,
17169
+ timestampHi: 0,
17170
+ timestampLo: 0,
17171
+ hasFirstPacket: false,
17172
+ ready: false
17173
+ };
17174
+ this.assembling.set(frameId, frame);
17175
+ }
17176
+ if (frame.totalPackets !== totalPackets) {
17177
+ throw new Error(`Frame ${frameId}: conflicting totalPackets: ${frame.totalPackets} vs ${totalPackets}`);
17178
+ }
17179
+ if (frame.received[sequence] === true) {
17180
+ throw new Error(`Frame ${frameId}: duplicate sequence ${sequence}`);
17181
+ }
17182
+ const willComplete = frame.receivedCount + 1 === frame.totalPackets;
17183
+ if (willComplete && this.isOldestAssembling(frame) && this.completed.length >= this.maxCompleted) {
17184
+ throw new Error("Frame collector: completed queue full");
17185
+ }
17186
+ if (sequence === 0) {
17187
+ if (frame.hasFirstPacket) {
17188
+ throw new Error(`Frame ${frameId}: duplicate first packet`);
17189
+ }
17190
+ if (parsedFrameType === void 0) {
17191
+ throw new Error(`Frame ${frameId}: missing parsed first-packet metadata`);
17192
+ }
17193
+ frame.frameType = parsedFrameType;
17194
+ frame.timestampHi = parsedTimestampHi;
17195
+ frame.timestampLo = parsedTimestampLo;
17196
+ frame.hasFirstPacket = true;
17197
+ }
17198
+ frame.buffer.set(payload, destinationOffset);
17199
+ frame.usedLength = Math.max(frame.usedLength, destinationEnd);
17200
+ frame.received[sequence] = true;
17201
+ frame.receivedCount += 1;
17202
+ if (frame.receivedCount !== frame.totalPackets) {
17203
+ return;
17204
+ }
17205
+ for (let s = 0; s < frame.totalPackets; s += 1) {
17206
+ if (frame.received[s] !== true) {
17207
+ throw new Error(`Frame ${frameId}: missing sequence ${s} at completion`);
17208
+ }
17209
+ }
17210
+ if (!frame.hasFirstPacket) {
17211
+ throw new Error(`Frame ${frameId}: completed without first-packet metadata`);
17212
+ }
17213
+ frame.ready = true;
17214
+ this.promoteReadyFrames();
17215
+ }
17216
+ isOldestAssembling(target) {
17217
+ for (const frame of this.assembling.values()) {
17218
+ return frame === target;
17219
+ }
17220
+ return false;
17221
+ }
17222
+ promoteReadyFrames() {
17223
+ while (this.completed.length < this.maxCompleted) {
17224
+ let oldest;
17225
+ for (const frame of this.assembling.values()) {
17226
+ oldest = frame;
17227
+ break;
17228
+ }
17229
+ if (oldest === void 0 || !oldest.ready) {
17230
+ return;
17231
+ }
17232
+ const removed = this.assembling.delete(oldest.frameId);
17233
+ if (!removed) {
17234
+ throw new Error(`Frame ${oldest.frameId}: failed to remove ready frame`);
17235
+ }
17236
+ const trimmed = oldest.buffer.subarray(0, oldest.usedLength);
17237
+ const timestamp = { hi: oldest.timestampHi, lo: oldest.timestampLo };
17238
+ const reference = this.registry.register(trimmed, oldest.frameType, timestamp);
17239
+ this.completed.push({
17240
+ reference,
17241
+ frameId: oldest.frameId,
17242
+ frameType: oldest.frameType,
17243
+ timestamp
17244
+ });
17245
+ }
17246
+ }
17247
+ /**
17248
+ * Mark input complete, abandon incomplete frames, and expose every complete
17249
+ * frame that remains in first-seen order. Completed references stay owned by
17250
+ * the collector until taken or destroyed.
17251
+ */
17252
+ finish() {
17253
+ for (const [frameId, frame] of this.assembling) {
17254
+ if (!frame.ready) {
17255
+ this.assembling.delete(frameId);
17256
+ }
17257
+ }
17258
+ this.promoteReadyFrames();
17259
+ }
17260
+ /** Release all assembling frames and clear completed queue, releasing refs. */
17261
+ destroy() {
17262
+ for (const frame of this.completed) {
17263
+ this.registry.release(frame.reference);
17264
+ }
17265
+ this.assembling.clear();
17266
+ this.completed.length = 0;
17267
+ }
17268
+ };
17269
+ exports.FrameCollector = FrameCollector;
17270
+ }
17271
+ });
17272
+
17273
+ // node_modules/@signageos/brightsign-decoder/dist/frame/FrameReferenceRegistry.js
17274
+ var require_FrameReferenceRegistry = __commonJS({
17275
+ "node_modules/@signageos/brightsign-decoder/dist/frame/FrameReferenceRegistry.js"(exports) {
17276
+ "use strict";
17277
+ Object.defineProperty(exports, "__esModule", { value: true });
17278
+ exports.FrameReferenceRegistry = void 0;
17279
+ var RefState;
17280
+ (function(RefState2) {
17281
+ RefState2[RefState2["Available"] = 0] = "Available";
17282
+ RefState2[RefState2["Claimed"] = 1] = "Claimed";
17283
+ RefState2[RefState2["Released"] = 2] = "Released";
17284
+ })(RefState || (RefState = {}));
17285
+ var refMeta = /* @__PURE__ */ new WeakMap();
17286
+ function createOpaqueRef(id, generation, owner) {
17287
+ const ref = Object.freeze({ __frameRef: true });
17288
+ refMeta.set(ref, { id, generation, owner });
17289
+ return ref;
17290
+ }
17291
+ function readRef(reference) {
17292
+ const meta = refMeta.get(reference);
17293
+ if (meta === void 0) {
17294
+ throw new TypeError("Invalid frame reference");
17295
+ }
17296
+ return meta;
17297
+ }
17298
+ var FrameReferenceRegistry2 = class {
17299
+ constructor() {
17300
+ this.entries = /* @__PURE__ */ new Map();
17301
+ this.nextId = 0;
17302
+ this.generation = 0;
17303
+ }
17304
+ /** Register a completed frame buffer and return an opaque reference. */
17305
+ register(data, frameType, timestamp) {
17306
+ const id = this.nextId;
17307
+ this.nextId += 1;
17308
+ this.entries.set(id, {
17309
+ state: RefState.Available,
17310
+ claimant: void 0,
17311
+ generation: this.generation,
17312
+ data,
17313
+ frameType,
17314
+ timestamp
17315
+ });
17316
+ return createOpaqueRef(id, this.generation, this);
17317
+ }
17318
+ /**
17319
+ * Atomically claim a reference. Returns the underlying frame data.
17320
+ * Throws on stale generation, double claim, or released reference.
17321
+ */
17322
+ claim(reference) {
17323
+ const meta = readRef(reference);
17324
+ return meta.owner.claimOwned(meta, this);
17325
+ }
17326
+ claimOwned(meta, claimant) {
17327
+ const entry = this.entries.get(meta.id);
17328
+ if (entry === void 0) {
17329
+ throw new Error(`Frame reference ${meta.id} does not exist`);
17330
+ }
17331
+ if (entry.generation !== meta.generation) {
17332
+ throw new Error(`Stale generation: expected ${entry.generation}, got ${meta.generation}`);
17333
+ }
17334
+ if (entry.state === RefState.Claimed) {
17335
+ throw new Error(`Frame reference ${meta.id} is already claimed`);
17336
+ }
17337
+ if (entry.state === RefState.Released) {
17338
+ throw new Error(`Frame reference ${meta.id} is already released`);
17339
+ }
17340
+ entry.state = RefState.Claimed;
17341
+ entry.claimant = claimant;
17342
+ return {
17343
+ data: entry.data,
17344
+ frameType: entry.frameType,
17345
+ timestamp: entry.timestamp
17346
+ };
17347
+ }
17348
+ /** Restore this registry's claim after downstream admission rejected ownership. */
17349
+ restoreClaim(reference) {
17350
+ const meta = refMeta.get(reference);
17351
+ if (meta === void 0) {
17352
+ return;
17353
+ }
17354
+ meta.owner.restoreOwnedClaim(meta, this);
17355
+ }
17356
+ restoreOwnedClaim(meta, claimant) {
17357
+ const entry = this.entries.get(meta.id);
17358
+ if (entry === void 0 || entry.generation !== meta.generation || entry.state !== RefState.Claimed || entry.claimant !== claimant) {
17359
+ return;
17360
+ }
17361
+ entry.state = RefState.Available;
17362
+ entry.claimant = void 0;
17363
+ }
17364
+ /**
17365
+ * Release a reference. Only claimed or available (explicit TCP close) refs
17366
+ * can be released. Stale generation is a no-op during teardown.
17367
+ */
17368
+ release(reference) {
17369
+ const meta = refMeta.get(reference);
17370
+ if (meta === void 0) {
17371
+ return;
17372
+ }
17373
+ meta.owner.releaseOwned(meta, this);
17374
+ }
17375
+ releaseOwned(meta, releaser) {
17376
+ const entry = this.entries.get(meta.id);
17377
+ if (entry === void 0 || entry.generation !== meta.generation || entry.state === RefState.Released) {
17378
+ return;
17379
+ }
17380
+ if (entry.state === RefState.Available && releaser !== this) {
17381
+ return;
17382
+ }
17383
+ if (entry.state === RefState.Claimed && entry.claimant !== releaser) {
17384
+ return;
17385
+ }
17386
+ entry.state = RefState.Released;
17387
+ entry.claimant = void 0;
17388
+ this.entries.delete(meta.id);
17389
+ }
17390
+ /** Number of currently tracked references. */
17391
+ get size() {
17392
+ return this.entries.size;
17393
+ }
17394
+ /** Increment generation and release all entries. */
17395
+ destroy() {
17396
+ this.generation += 1;
17397
+ this.entries.clear();
17398
+ this.nextId = 0;
17399
+ }
17400
+ };
17401
+ exports.FrameReferenceRegistry = FrameReferenceRegistry2;
17402
+ }
17403
+ });
17404
+
17405
+ // node_modules/@signageos/brightsign-decoder/dist/tcp/ConnectionRegistry.js
17406
+ var require_ConnectionRegistry = __commonJS({
17407
+ "node_modules/@signageos/brightsign-decoder/dist/tcp/ConnectionRegistry.js"(exports) {
17408
+ "use strict";
17409
+ Object.defineProperty(exports, "__esModule", { value: true });
17410
+ exports.ConnectionRegistry = void 0;
17411
+ var ConnectionRegistry = class {
17412
+ constructor() {
17413
+ this.slots = /* @__PURE__ */ new Map();
17414
+ this.freeSlots = [];
17415
+ this.nextSlot = 0;
17416
+ }
17417
+ /** Allocate a new connection slot and return its handle. */
17418
+ allocate() {
17419
+ const reusable = this.freeSlots.pop();
17420
+ if (reusable !== void 0) {
17421
+ const entry = this.slots.get(reusable);
17422
+ if (entry === void 0 || entry.active) {
17423
+ throw new Error("Connection registry free-list corruption");
17424
+ }
17425
+ entry.active = true;
17426
+ return { slot: reusable, generation: entry.generation };
17427
+ }
17428
+ const slot = this.nextSlot;
17429
+ this.nextSlot += 1;
17430
+ this.slots.set(slot, { generation: 0, active: true });
17431
+ return { slot, generation: 0 };
17432
+ }
17433
+ /** Check whether a handle is still valid (same generation, active). */
17434
+ isValid(handle) {
17435
+ const entry = this.slots.get(handle.slot);
17436
+ if (entry === void 0) {
17437
+ return false;
17438
+ }
17439
+ return entry.active && entry.generation === handle.generation;
17440
+ }
17441
+ /**
17442
+ * Close a connection slot.
17443
+ * Increments generation before releasing so delayed callbacks on the old
17444
+ * generation see an invalid handle.
17445
+ */
17446
+ close(handle) {
17447
+ const entry = this.slots.get(handle.slot);
17448
+ if (entry === void 0) {
17449
+ return;
17450
+ }
17451
+ if (entry.generation !== handle.generation) {
17452
+ return;
17453
+ }
17454
+ entry.generation += 1;
17455
+ entry.active = false;
17456
+ this.freeSlots.push(handle.slot);
17457
+ }
17458
+ /** Number of currently active connections. */
17459
+ get activeCount() {
17460
+ let count = 0;
17461
+ for (const entry of this.slots.values()) {
17462
+ if (entry.active) {
17463
+ count += 1;
17464
+ }
17465
+ }
17466
+ return count;
17467
+ }
17468
+ /** Close all active connections. */
17469
+ destroy() {
17470
+ for (const [slot, entry] of this.slots) {
17471
+ if (entry.active) {
17472
+ entry.generation += 1;
17473
+ entry.active = false;
17474
+ this.freeSlots.push(slot);
17475
+ }
17476
+ }
17477
+ }
17478
+ };
17479
+ exports.ConnectionRegistry = ConnectionRegistry;
17480
+ }
17481
+ });
17482
+
17483
+ // node_modules/@signageos/brightsign-decoder/dist/tcp/TCP.js
17484
+ var require_TCP = __commonJS({
17485
+ "node_modules/@signageos/brightsign-decoder/dist/tcp/TCP.js"(exports) {
17486
+ "use strict";
17487
+ Object.defineProperty(exports, "__esModule", { value: true });
17488
+ exports.TCP = void 0;
17489
+ exports.narrowSocketLike = narrowSocketLike;
17490
+ var contracts_1 = require_contracts();
17491
+ var FrameCollector_1 = require_FrameCollector();
17492
+ var FrameReferenceRegistry_1 = require_FrameReferenceRegistry();
17493
+ var ConnectionRegistry_1 = require_ConnectionRegistry();
17494
+ var PacketParser_1 = require_PacketParser();
17495
+ var DEFAULT_MAX_PACKET_SIZE = 32 * 1024;
17496
+ var DEFAULT_MAX_QUEUED_BYTES = 1024 * 1024;
17497
+ var DEFAULT_MAX_QUEUED_PACKETS = 64;
17498
+ var ManagedConnection = class {
17499
+ constructor(net, registry, handle, maxQueuedPackets, inputMode, maxPacketSize, maxQueuedBytes, referenceRegistry2, unregister) {
17500
+ this.net = net;
17501
+ this.registry = registry;
17502
+ this.handle = handle;
17503
+ this.maxQueuedPackets = maxQueuedPackets;
17504
+ this.inputMode = inputMode;
17505
+ this.maxQueuedBytes = maxQueuedBytes;
17506
+ this.unregister = unregister;
17507
+ this.pendingPackets = [];
17508
+ this.pendingRawBytes = 0;
17509
+ this.byteWaiters = [];
17510
+ this.frameWaiters = [];
17511
+ this.pendingWrites = [];
17512
+ this.paused = false;
17513
+ this.closed = false;
17514
+ this.cleanEof = false;
17515
+ this.collectorFinished = false;
17516
+ this.resourcesReleased = false;
17517
+ this.stateValue = contracts_1.ConnectionState.Connecting;
17518
+ this.parser = new PacketParser_1.PacketParser({ maxPacketSize, maxQueuedBytes });
17519
+ this.collector = new FrameCollector_1.FrameCollector(referenceRegistry2, { maxPacketSize });
17520
+ }
17521
+ get state() {
17522
+ return this.stateValue;
17523
+ }
17524
+ async connect(options) {
17525
+ await new Promise((resolve, reject) => {
17526
+ this.connectResolve = resolve;
17527
+ this.connectReject = reject;
17528
+ let connectedSynchronously = false;
17529
+ try {
17530
+ const created = this.net.createConnection({ host: options.host, port: options.port }, () => {
17531
+ if (this.socket === void 0) {
17532
+ connectedSynchronously = true;
17533
+ return;
17534
+ }
17535
+ this.markConnected();
17536
+ });
17537
+ this.socket = created;
17538
+ this.installSocketListeners(created);
17539
+ if (connectedSynchronously) {
17540
+ this.markConnected();
17541
+ }
17542
+ } catch (error) {
17543
+ this.fail(toError(error, "TCP connection creation failed"));
17544
+ }
17545
+ });
17546
+ }
17547
+ readBytes(signal) {
17548
+ var _a;
17549
+ this.selectMode("raw");
17550
+ const queued = this.pendingPackets.shift();
17551
+ if (queued !== void 0) {
17552
+ this.pendingRawBytes -= this.inputMode === "raw" ? queued.byteLength : 0;
17553
+ this.updateBackpressure();
17554
+ this.finalizeCleanEofIfDrained();
17555
+ return Promise.resolve(queued);
17556
+ }
17557
+ if (this.closed) {
17558
+ this.finalizeCleanEofIfDrained();
17559
+ return Promise.reject((_a = this.closeError) != null ? _a : new Error("TCP connection is closed"));
17560
+ }
17561
+ return new Promise((resolve, reject) => {
17562
+ if ((signal == null ? void 0 : signal.aborted) === true) {
17563
+ reject(abortError());
17564
+ return;
17565
+ }
17566
+ let waiter;
17567
+ const abort = signal === void 0 ? void 0 : () => {
17568
+ this.removeByteWaiter(waiter);
17569
+ this.settleByteWaiter(waiter, void 0, abortError());
17570
+ };
17571
+ waiter = { resolve, reject, signal, abort, settled: false };
17572
+ this.byteWaiters.push(waiter);
17573
+ if (signal !== void 0 && abort !== void 0) {
17574
+ signal.addEventListener("abort", abort, { once: true });
17575
+ }
17576
+ });
17577
+ }
17578
+ readReference(signal) {
17579
+ return this.readFrame(signal).then((frame) => frame.reference);
17580
+ }
17581
+ readFrame(signal) {
17582
+ var _a;
17583
+ this.selectMode("frames");
17584
+ const pumpError = this.pumpFrameDataSafely();
17585
+ if (pumpError !== void 0) {
17586
+ return Promise.reject(pumpError);
17587
+ }
17588
+ const completed = this.collector.take();
17589
+ if (completed !== void 0) {
17590
+ this.pumpFrameDataSafely();
17591
+ this.updateBackpressure();
17592
+ this.finalizeCleanEofIfDrained();
17593
+ return Promise.resolve(completed);
17594
+ }
17595
+ if (this.closed) {
17596
+ this.finalizeCleanEofIfDrained();
17597
+ return Promise.reject((_a = this.closeError) != null ? _a : new Error("TCP connection is closed"));
17598
+ }
17599
+ return new Promise((resolve, reject) => {
17600
+ if ((signal == null ? void 0 : signal.aborted) === true) {
17601
+ reject(abortError());
17602
+ return;
17603
+ }
17604
+ let waiter;
17605
+ const abort = signal === void 0 ? void 0 : () => {
17606
+ this.removeFrameWaiter(waiter);
17607
+ this.settleFrameWaiter(waiter, void 0, abortError());
17608
+ };
17609
+ waiter = { resolve, reject, signal, abort, settled: false };
17610
+ this.frameWaiters.push(waiter);
17611
+ if (signal !== void 0 && abort !== void 0) {
17612
+ signal.addEventListener("abort", abort, { once: true });
17613
+ }
17614
+ this.pumpFrameDataSafely();
17615
+ });
17616
+ }
17617
+ write(data) {
17618
+ var _a;
17619
+ if (this.closed || this.stateValue !== contracts_1.ConnectionState.Connected) {
17620
+ return Promise.reject((_a = this.closeError) != null ? _a : new Error("TCP connection is not connected"));
17621
+ }
17622
+ let owned;
17623
+ try {
17624
+ owned = narrowBytes(data);
17625
+ } catch (error) {
17626
+ return Promise.reject(toError(error, "TCP write data must be bytes"));
17627
+ }
17628
+ return new Promise((resolve, reject) => {
17629
+ this.pendingWrites.push({ data: owned, resolve, reject, settled: false });
17630
+ this.startNextWrite();
17631
+ });
17632
+ }
17633
+ close(reason) {
17634
+ if (this.closed && !this.cleanEof) {
17635
+ return;
17636
+ }
17637
+ this.closed = true;
17638
+ this.cleanEof = false;
17639
+ this.closeError = reason != null ? reason : new Error("TCP connection is closed");
17640
+ this.stateValue = reason === void 0 ? contracts_1.ConnectionState.Closed : contracts_1.ConnectionState.Error;
17641
+ this.registry.close(this.handle);
17642
+ this.pendingPackets.length = 0;
17643
+ this.pendingRawBytes = 0;
17644
+ this.parser.reset();
17645
+ for (const waiter of this.byteWaiters.splice(0)) {
17646
+ this.settleByteWaiter(waiter, void 0, this.closeError);
17647
+ }
17648
+ for (const waiter of this.frameWaiters.splice(0)) {
17649
+ this.settleFrameWaiter(waiter, void 0, this.closeError);
17650
+ }
17651
+ this.rejectWrites(this.closeError);
17652
+ const rejectConnect = this.connectReject;
17653
+ this.connectResolve = void 0;
17654
+ this.connectReject = void 0;
17655
+ if (rejectConnect !== void 0) {
17656
+ rejectConnect(this.closeError);
17657
+ }
17658
+ const socket = this.socket;
17659
+ if (socket !== void 0) {
17660
+ socket.removeAllListeners();
17661
+ if (!socket.destroyed) {
17662
+ socket.destroy();
17663
+ }
17664
+ }
17665
+ this.releaseResources();
17666
+ }
17667
+ installSocketListeners(socket) {
17668
+ socket.on("data", (value) => {
17669
+ if (!this.registry.isValid(this.handle) || this.closed) {
17670
+ return;
17671
+ }
17672
+ try {
17673
+ const bytes = narrowBytes(value);
17674
+ if (this.inputMode === "raw") {
17675
+ this.pendingPackets.push(bytes);
17676
+ this.pendingRawBytes += bytes.byteLength;
17677
+ } else {
17678
+ const packets = this.parser.push(bytes);
17679
+ this.pendingPackets.push(...packets);
17680
+ }
17681
+ this.deliverPending();
17682
+ if (this.pendingRawBytes > this.maxQueuedBytes) {
17683
+ throw new Error("TCP raw byte queue capacity exceeded");
17684
+ }
17685
+ if (this.pendingPackets.length > this.maxQueuedPackets) {
17686
+ throw new Error("TCP packet queue capacity exceeded");
17687
+ }
17688
+ } catch (error) {
17689
+ this.fail(toError(error, "TCP packet processing failed"));
17690
+ }
17691
+ });
17692
+ socket.on("error", (error) => {
17693
+ if (this.registry.isValid(this.handle)) {
17694
+ this.fail(toError(error, "TCP socket error"));
17695
+ }
17696
+ });
17697
+ socket.on("close", () => {
17698
+ if (!this.registry.isValid(this.handle)) {
17699
+ return;
17700
+ }
17701
+ try {
17702
+ if (this.inputMode === "framed") {
17703
+ this.parser.finish();
17704
+ }
17705
+ this.handleCleanEof();
17706
+ } catch (error) {
17707
+ this.fail(toError(error, "TCP socket closed with an incomplete packet"));
17708
+ }
17709
+ });
17710
+ }
17711
+ markConnected() {
17712
+ if (this.closed || this.stateValue !== contracts_1.ConnectionState.Connecting) {
17713
+ return;
17714
+ }
17715
+ this.stateValue = contracts_1.ConnectionState.Connected;
17716
+ const resolveConnect = this.connectResolve;
17717
+ this.connectResolve = void 0;
17718
+ this.connectReject = void 0;
17719
+ resolveConnect == null ? void 0 : resolveConnect();
17720
+ }
17721
+ fail(error) {
17722
+ this.close(error);
17723
+ }
17724
+ selectMode(mode) {
17725
+ if (mode === "frames" && this.inputMode === "raw") {
17726
+ throw new Error("Raw TCP streams do not support frame collection");
17727
+ }
17728
+ if (this.mode !== void 0 && this.mode !== mode) {
17729
+ throw new Error("TCP stream cannot mix raw packet reads and frame-reference reads");
17730
+ }
17731
+ if (this.mode === void 0) {
17732
+ this.mode = mode;
17733
+ }
17734
+ }
17735
+ deliverPending() {
17736
+ if (this.mode === "raw") {
17737
+ while (this.pendingPackets.length > 0 && this.byteWaiters.length > 0) {
17738
+ const packet = this.pendingPackets.shift();
17739
+ const waiter = this.byteWaiters.shift();
17740
+ if (packet !== void 0 && waiter !== void 0) {
17741
+ this.pendingRawBytes -= this.inputMode === "raw" ? packet.byteLength : 0;
17742
+ this.settleByteWaiter(waiter, packet, void 0);
17743
+ }
17744
+ }
17745
+ if (this.cleanEof && this.pendingPackets.length === 0) {
17746
+ this.rejectByteWaitersAtEof();
17747
+ }
17748
+ } else if (this.mode === "frames") {
17749
+ this.pumpFrameData();
17750
+ }
17751
+ this.updateBackpressure();
17752
+ this.finalizeCleanEofIfDrained();
17753
+ }
17754
+ drainFramePackets() {
17755
+ while (this.pendingPackets.length > 0 && !this.collector.isCompletedFull) {
17756
+ const packet = this.pendingPackets[0];
17757
+ if (packet === void 0) {
17758
+ break;
17759
+ }
17760
+ this.collector.accept(packet);
17761
+ this.pendingPackets.shift();
17762
+ }
17763
+ }
17764
+ deliverFrames() {
17765
+ while (this.frameWaiters.length > 0) {
17766
+ const completed = this.collector.take();
17767
+ if (completed === void 0) {
17768
+ return;
17769
+ }
17770
+ const waiter = this.frameWaiters.shift();
17771
+ if (waiter !== void 0) {
17772
+ this.settleFrameWaiter(waiter, completed, void 0);
17773
+ }
17774
+ }
17775
+ }
17776
+ pumpFrameData() {
17777
+ let progressed = true;
17778
+ while (progressed) {
17779
+ const packetCount = this.pendingPackets.length;
17780
+ const completedCount = this.collector.completedCount;
17781
+ const waiterCount = this.frameWaiters.length;
17782
+ this.drainFramePackets();
17783
+ if (this.cleanEof && this.pendingPackets.length === 0 && !this.collectorFinished) {
17784
+ this.collector.finish();
17785
+ this.collectorFinished = true;
17786
+ }
17787
+ this.deliverFrames();
17788
+ progressed = packetCount !== this.pendingPackets.length || completedCount !== this.collector.completedCount || waiterCount !== this.frameWaiters.length;
17789
+ }
17790
+ if (this.cleanEof && this.pendingPackets.length === 0 && this.collector.completedCount === 0) {
17791
+ this.rejectFrameWaitersAtEof();
17792
+ }
17793
+ }
17794
+ pumpFrameDataSafely() {
17795
+ try {
17796
+ this.pumpFrameData();
17797
+ return void 0;
17798
+ } catch (error) {
17799
+ const failure = toError(error, "TCP frame processing failed");
17800
+ this.fail(failure);
17801
+ return failure;
17802
+ }
17803
+ }
17804
+ handleCleanEof() {
17805
+ this.closed = true;
17806
+ this.cleanEof = true;
17807
+ this.closeError = new Error("TCP connection reached end of stream");
17808
+ this.stateValue = contracts_1.ConnectionState.Closed;
17809
+ this.registry.close(this.handle);
17810
+ const socket = this.socket;
17811
+ if (socket !== void 0) {
17812
+ socket.removeAllListeners();
17813
+ }
17814
+ const rejectConnect = this.connectReject;
17815
+ this.connectResolve = void 0;
17816
+ this.connectReject = void 0;
17817
+ if (rejectConnect !== void 0) {
17818
+ rejectConnect(this.closeError);
17819
+ }
17820
+ this.rejectWrites(this.closeError);
17821
+ this.deliverPending();
17822
+ }
17823
+ rejectByteWaitersAtEof() {
17824
+ var _a;
17825
+ const error = (_a = this.closeError) != null ? _a : new Error("TCP connection reached end of stream");
17826
+ for (const waiter of this.byteWaiters.splice(0)) {
17827
+ this.settleByteWaiter(waiter, void 0, error);
17828
+ }
17829
+ }
17830
+ rejectFrameWaitersAtEof() {
17831
+ var _a;
17832
+ const error = (_a = this.closeError) != null ? _a : new Error("TCP connection reached end of stream");
17833
+ for (const waiter of this.frameWaiters.splice(0)) {
17834
+ this.settleFrameWaiter(waiter, void 0, error);
17835
+ }
17836
+ }
17837
+ finalizeCleanEofIfDrained() {
17838
+ if (!this.cleanEof) {
17839
+ return;
17840
+ }
17841
+ const rawDrained = this.mode !== "frames" && this.pendingPackets.length === 0;
17842
+ const framesDrained = this.mode === "frames" && this.pendingPackets.length === 0 && this.collectorFinished && this.collector.completedCount === 0;
17843
+ if (rawDrained || framesDrained) {
17844
+ this.releaseResources();
17845
+ }
17846
+ }
17847
+ releaseResources() {
17848
+ if (this.resourcesReleased) {
17849
+ return;
17850
+ }
17851
+ this.resourcesReleased = true;
17852
+ this.parser.destroy();
17853
+ this.collector.destroy();
17854
+ this.unregister(this);
17855
+ }
17856
+ startNextWrite() {
17857
+ if (this.activeWrite !== void 0 || this.closed) {
17858
+ return;
17859
+ }
17860
+ const operation = this.pendingWrites.shift();
17861
+ if (operation === void 0) {
17862
+ return;
17863
+ }
17864
+ const socket = this.socket;
17865
+ if (socket === void 0) {
17866
+ this.rejectWrite(operation, new Error("TCP socket is unavailable"));
17867
+ this.startNextWrite();
17868
+ return;
17869
+ }
17870
+ this.activeWrite = operation;
17871
+ try {
17872
+ socket.write(operation.data, (error) => {
17873
+ if (this.activeWrite !== operation || operation.settled) {
17874
+ return;
17875
+ }
17876
+ if (error !== void 0 && error !== null) {
17877
+ this.fail(toError(error, "TCP socket write failed"));
17878
+ return;
17879
+ }
17880
+ operation.settled = true;
17881
+ this.activeWrite = void 0;
17882
+ operation.resolve();
17883
+ this.startNextWrite();
17884
+ });
17885
+ } catch (error) {
17886
+ this.fail(toError(error, "TCP socket write failed"));
17887
+ }
17888
+ }
17889
+ rejectWrites(error) {
17890
+ const active = this.activeWrite;
17891
+ this.activeWrite = void 0;
17892
+ if (active !== void 0) {
17893
+ this.rejectWrite(active, error);
17894
+ }
17895
+ for (const operation of this.pendingWrites.splice(0)) {
17896
+ this.rejectWrite(operation, error);
17897
+ }
17898
+ }
17899
+ rejectWrite(operation, error) {
17900
+ if (operation.settled) {
17901
+ return;
17902
+ }
17903
+ operation.settled = true;
17904
+ operation.reject(error);
17905
+ }
17906
+ updateBackpressure() {
17907
+ const socket = this.socket;
17908
+ if (socket === void 0 || this.closed) {
17909
+ return;
17910
+ }
17911
+ const shouldPause = this.pendingPackets.length >= this.maxQueuedPackets || this.pendingRawBytes >= this.maxQueuedBytes || this.mode === "frames" && this.collector.isCompletedFull;
17912
+ if (shouldPause && !this.paused) {
17913
+ socket.pause();
17914
+ this.paused = true;
17915
+ } else if (!shouldPause && this.paused) {
17916
+ socket.resume();
17917
+ this.paused = false;
17918
+ }
17919
+ }
17920
+ removeByteWaiter(waiter) {
17921
+ const index = this.byteWaiters.indexOf(waiter);
17922
+ if (index >= 0) {
17923
+ this.byteWaiters.splice(index, 1);
17924
+ }
17925
+ }
17926
+ removeFrameWaiter(waiter) {
17927
+ const index = this.frameWaiters.indexOf(waiter);
17928
+ if (index >= 0) {
17929
+ this.frameWaiters.splice(index, 1);
17930
+ }
17931
+ }
17932
+ settleByteWaiter(waiter, value, error) {
17933
+ if (waiter.settled) {
17934
+ return;
17935
+ }
17936
+ waiter.settled = true;
17937
+ if (waiter.signal !== void 0 && waiter.abort !== void 0) {
17938
+ waiter.signal.removeEventListener("abort", waiter.abort);
17939
+ }
17940
+ if (error !== void 0) {
17941
+ waiter.reject(error);
17942
+ } else if (value !== void 0) {
17943
+ waiter.resolve(value);
17944
+ }
17945
+ }
17946
+ settleFrameWaiter(waiter, value, error) {
17947
+ if (waiter.settled) {
17948
+ return;
17949
+ }
17950
+ waiter.settled = true;
17951
+ if (waiter.signal !== void 0 && waiter.abort !== void 0) {
17952
+ waiter.signal.removeEventListener("abort", waiter.abort);
17953
+ }
17954
+ if (error !== void 0) {
17955
+ waiter.reject(error);
17956
+ } else if (value !== void 0) {
17957
+ waiter.resolve(value);
17958
+ }
17959
+ }
17960
+ };
17961
+ var TCP = class {
17962
+ constructor(options) {
17963
+ var _a, _b, _c, _d;
17964
+ this.options = options;
17965
+ this.registry = new ConnectionRegistry_1.ConnectionRegistry();
17966
+ this.connections = /* @__PURE__ */ new Set();
17967
+ this.destroyed = false;
17968
+ this.maxPacketSize = (_a = options.maxPacketSize) != null ? _a : DEFAULT_MAX_PACKET_SIZE;
17969
+ this.maxQueuedBytes = (_b = options.maxQueuedBytes) != null ? _b : DEFAULT_MAX_QUEUED_BYTES;
17970
+ this.maxQueuedPackets = (_c = options.maxQueuedPackets) != null ? _c : DEFAULT_MAX_QUEUED_PACKETS;
17971
+ this.referenceRegistry = (_d = options.referenceRegistry) != null ? _d : new FrameReferenceRegistry_1.FrameReferenceRegistry();
17972
+ if (!Number.isSafeInteger(this.maxQueuedPackets) || this.maxQueuedPackets <= 0) {
17973
+ throw new RangeError("maxQueuedPackets must be a positive integer");
17974
+ }
17975
+ }
17976
+ async createPacket(options) {
17977
+ const connection = await this.createConnection(options, "framed");
17978
+ return {
17979
+ read(signal) {
17980
+ return connection.readBytes(signal);
17981
+ },
17982
+ write(data) {
17983
+ const body = narrowBytes(data);
17984
+ if (body.byteLength > 65535) {
17985
+ return Promise.reject(new RangeError("TCP packet body exceeds the u16 length limit"));
17986
+ }
17987
+ const packet = new Uint8Array(body.byteLength + 2);
17988
+ packet[0] = body.byteLength >>> 8;
17989
+ packet[1] = body.byteLength & 255;
17990
+ packet.set(body, 2);
17991
+ return connection.write(packet);
17992
+ },
17993
+ readFrame(signal) {
17994
+ return connection.readFrame(signal);
17995
+ },
17996
+ readFrameRef(signal) {
17997
+ return connection.readReference(signal);
17998
+ },
17999
+ close() {
18000
+ connection.close();
18001
+ },
18002
+ get state() {
18003
+ return connection.state;
18004
+ }
18005
+ };
18006
+ }
18007
+ async createStream(options) {
18008
+ const connection = await this.createConnection(options, "framed");
18009
+ return {
18010
+ read(signal) {
18011
+ return connection.readBytes(signal);
18012
+ },
18013
+ write(data) {
18014
+ return connection.write(data);
18015
+ },
18016
+ readFrame(signal) {
18017
+ return connection.readFrame(signal);
18018
+ },
18019
+ readFrameRef(signal) {
18020
+ return connection.readReference(signal);
18021
+ },
18022
+ close() {
18023
+ connection.close();
18024
+ },
18025
+ get state() {
18026
+ return connection.state;
18027
+ }
18028
+ };
18029
+ }
18030
+ async createRawStream(options) {
18031
+ const connection = await this.createConnection(options, "raw");
18032
+ return {
18033
+ read(signal) {
18034
+ return connection.readBytes(signal);
18035
+ },
18036
+ write(data) {
18037
+ return connection.write(data);
18038
+ },
18039
+ close() {
18040
+ connection.close();
18041
+ },
18042
+ get state() {
18043
+ return connection.state;
18044
+ }
18045
+ };
18046
+ }
18047
+ async destroy() {
18048
+ if (this.destroyed) {
18049
+ return;
18050
+ }
18051
+ this.destroyed = true;
18052
+ for (const connection of Array.from(this.connections)) {
18053
+ connection.close();
18054
+ }
18055
+ this.registry.destroy();
18056
+ }
18057
+ async createConnection(options, inputMode) {
18058
+ if (this.destroyed) {
18059
+ throw new Error("TCP communication is destroyed");
18060
+ }
18061
+ if (options.secure === true) {
18062
+ throw new Error("secure: true is not supported until a tested TLS contract exists");
18063
+ }
18064
+ if (!Number.isSafeInteger(options.port) || options.port <= 0 || options.port > 65535) {
18065
+ throw new RangeError("TCP port must be an integer in 1..65535");
18066
+ }
18067
+ if (options.host.length === 0) {
18068
+ throw new RangeError("TCP host must not be empty");
18069
+ }
18070
+ const connection = new ManagedConnection(this.options.net, this.registry, this.registry.allocate(), this.maxQueuedPackets, inputMode, this.maxPacketSize, this.maxQueuedBytes, this.referenceRegistry, (value) => this.connections.delete(value));
18071
+ this.connections.add(connection);
18072
+ try {
18073
+ await connection.connect(options);
18074
+ return connection;
18075
+ } catch (error) {
18076
+ connection.close(toError(error, "TCP connection failed"));
18077
+ throw error;
18078
+ }
18079
+ }
18080
+ };
18081
+ exports.TCP = TCP;
18082
+ function narrowSocketLike(value) {
18083
+ if (typeof value !== "object" || value === null) {
18084
+ throw new TypeError("Expected a socket object");
18085
+ }
18086
+ const on = Reflect.get(value, "on");
18087
+ const removeAllListeners = Reflect.get(value, "removeAllListeners");
18088
+ const write = Reflect.get(value, "write");
18089
+ const pause = Reflect.get(value, "pause");
18090
+ const resume = Reflect.get(value, "resume");
18091
+ const destroy = Reflect.get(value, "destroy");
18092
+ if (typeof on !== "function" || typeof removeAllListeners !== "function" || typeof write !== "function" || typeof pause !== "function" || typeof resume !== "function" || typeof destroy !== "function") {
18093
+ throw new TypeError("Object does not satisfy the socket contract");
18094
+ }
18095
+ return {
18096
+ on(event, listener) {
18097
+ Reflect.apply(on, value, [event, listener]);
18098
+ },
18099
+ removeAllListeners(event) {
18100
+ Reflect.apply(removeAllListeners, value, event === void 0 ? [] : [event]);
18101
+ },
18102
+ write(data, callback) {
18103
+ const args = callback === void 0 ? [data] : [data, callback];
18104
+ return Reflect.apply(write, value, args) !== false;
18105
+ },
18106
+ pause() {
18107
+ Reflect.apply(pause, value, []);
18108
+ },
18109
+ resume() {
18110
+ Reflect.apply(resume, value, []);
18111
+ },
18112
+ destroy() {
18113
+ Reflect.apply(destroy, value, []);
18114
+ },
18115
+ get destroyed() {
18116
+ return Reflect.get(value, "destroyed") === true;
18117
+ }
18118
+ };
18119
+ }
18120
+ function narrowBytes(value) {
18121
+ if (!ArrayBuffer.isView(value) || Reflect.get(value, "BYTES_PER_ELEMENT") !== 1) {
18122
+ throw new TypeError("TCP data event did not contain a one-byte element view");
18123
+ }
18124
+ const byteLength = Reflect.get(value, "byteLength");
18125
+ if (typeof byteLength !== "number" || !Number.isSafeInteger(byteLength) || byteLength < 0) {
18126
+ throw new TypeError("TCP data event contained an invalid byte length");
18127
+ }
18128
+ const normalized = new Uint8Array(byteLength);
18129
+ Reflect.apply(Uint8Array.prototype.set, normalized, [value]);
18130
+ return normalized;
18131
+ }
18132
+ function toError(value, fallback) {
18133
+ return value instanceof Error ? value : new Error(fallback);
18134
+ }
18135
+ function abortError() {
18136
+ const error = new Error("Operation aborted");
18137
+ error.name = "AbortError";
18138
+ return error;
18139
+ }
18140
+ }
18141
+ });
18142
+
18143
+ // node_modules/@signageos/brightsign-decoder/dist/remux/AnnexB.js
18144
+ var require_AnnexB = __commonJS({
18145
+ "node_modules/@signageos/brightsign-decoder/dist/remux/AnnexB.js"(exports) {
18146
+ "use strict";
18147
+ Object.defineProperty(exports, "__esModule", { value: true });
18148
+ exports.NalType = void 0;
18149
+ exports.findStartCodes = findStartCodes;
18150
+ exports.startCodeLength = startCodeLength;
18151
+ exports.getNalType = getNalType;
18152
+ exports.parseNalUnits = parseNalUnits;
18153
+ exports.inspectAccessUnit = inspectAccessUnit;
18154
+ var NalType;
18155
+ (function(NalType2) {
18156
+ NalType2[NalType2["NonIDRSlice"] = 1] = "NonIDRSlice";
18157
+ NalType2[NalType2["IDRSlice"] = 5] = "IDRSlice";
18158
+ NalType2[NalType2["SEI"] = 6] = "SEI";
18159
+ NalType2[NalType2["SPS"] = 7] = "SPS";
18160
+ NalType2[NalType2["PPS"] = 8] = "PPS";
18161
+ NalType2[NalType2["AUD"] = 9] = "AUD";
18162
+ })(NalType || (exports.NalType = NalType = {}));
18163
+ function findStartCodes(data) {
18164
+ const positions = [];
18165
+ let index = 0;
18166
+ while (index + 2 < data.byteLength) {
18167
+ const b0 = data[index];
18168
+ const b1 = data[index + 1];
18169
+ const b2 = data[index + 2];
18170
+ if (b0 === void 0 || b1 === void 0 || b2 === void 0) {
18171
+ break;
18172
+ }
18173
+ if (b0 === 0 && b1 === 0) {
18174
+ if (b2 === 1) {
18175
+ positions.push(index);
18176
+ index += 3;
18177
+ continue;
18178
+ }
18179
+ const b3 = data[index + 3];
18180
+ if (b2 === 0 && b3 === 1) {
18181
+ positions.push(index);
18182
+ index += 4;
18183
+ continue;
18184
+ }
18185
+ }
18186
+ index += 1;
18187
+ }
18188
+ return positions;
18189
+ }
18190
+ function startCodeLength(data, position) {
18191
+ const b2 = data[position + 2];
18192
+ if (b2 === 1) {
18193
+ return 3;
18194
+ }
18195
+ return 4;
18196
+ }
18197
+ function getNalType(data, startCodePosition) {
18198
+ const prefixLen = startCodeLength(data, startCodePosition);
18199
+ const nalByte = data[startCodePosition + prefixLen];
18200
+ if (nalByte === void 0) {
18201
+ throw new RangeError("NAL unit header byte is missing");
18202
+ }
18203
+ return nalByte & 31;
18204
+ }
18205
+ function parseNalUnits(data) {
18206
+ if (data.byteLength === 0) {
18207
+ throw new RangeError("Annex-B access unit is empty");
18208
+ }
18209
+ const positions = findStartCodes(data);
18210
+ const firstPosition = positions[0];
18211
+ if (firstPosition === void 0) {
18212
+ throw new RangeError("Annex-B access unit has no start code");
18213
+ }
18214
+ for (let index = 0; index < firstPosition; index += 1) {
18215
+ if (data[index] !== 0) {
18216
+ throw new RangeError("Annex-B access unit has non-zero bytes before its first start code");
18217
+ }
18218
+ }
18219
+ const units = [];
18220
+ for (let i = 0; i < positions.length; i += 1) {
18221
+ const pos = positions[i];
18222
+ if (pos === void 0) {
18223
+ continue;
18224
+ }
18225
+ const nextPos = positions[i + 1];
18226
+ const end = nextPos !== void 0 ? nextPos : data.byteLength;
18227
+ const prefixLength = startCodeLength(data, pos);
18228
+ if (end <= pos + prefixLength) {
18229
+ throw new RangeError("Annex-B access unit contains an empty NAL unit");
18230
+ }
18231
+ const type = getNalType(data, pos);
18232
+ units.push({ type, offset: pos, length: end - pos });
18233
+ }
18234
+ return units;
18235
+ }
18236
+ function inspectAccessUnit(data) {
18237
+ const nalUnits = parseNalUnits(data);
18238
+ let isIDR = false;
18239
+ let hasSPS = false;
18240
+ let hasPPS = false;
18241
+ let spsData;
18242
+ let ppsData;
18243
+ for (const unit of nalUnits) {
18244
+ if (unit.type === NalType.IDRSlice) {
18245
+ isIDR = true;
18246
+ }
18247
+ if (unit.type === NalType.SPS) {
18248
+ hasSPS = true;
18249
+ spsData = data.slice(unit.offset, unit.offset + unit.length);
18250
+ }
18251
+ if (unit.type === NalType.PPS) {
18252
+ hasPPS = true;
18253
+ ppsData = data.slice(unit.offset, unit.offset + unit.length);
18254
+ }
18255
+ }
18256
+ return { isIDR, hasSPS, hasPPS, nalUnits, spsData, ppsData };
18257
+ }
18258
+ }
18259
+ });
18260
+
18261
+ // node_modules/@signageos/brightsign-decoder/dist/remux/TransportClock.js
18262
+ var require_TransportClock = __commonJS({
18263
+ "node_modules/@signageos/brightsign-decoder/dist/remux/TransportClock.js"(exports) {
18264
+ "use strict";
18265
+ Object.defineProperty(exports, "__esModule", { value: true });
18266
+ exports.TransportClock = void 0;
18267
+ exports.u64ToBigInt = u64ToBigInt;
18268
+ exports.u64Sub = u64Sub;
18269
+ var PTS_MASK_N = BigInt("0x1FFFFFFFF");
18270
+ var NINE = BigInt(9);
18271
+ var ONE_HUNDRED_THOUSAND = BigInt(1e5);
18272
+ var ZERO = BigInt(0);
18273
+ function u64ToBigInt(ts) {
18274
+ validateU32(ts.hi, "timestamp.hi");
18275
+ validateU32(ts.lo, "timestamp.lo");
18276
+ return BigInt(ts.hi) << BigInt(32) | BigInt(ts.lo);
18277
+ }
18278
+ var TransportClock = class {
18279
+ constructor(initialPts = 0) {
18280
+ if (!Number.isSafeInteger(initialPts) || initialPts < 0 || initialPts > Number(PTS_MASK_N)) {
18281
+ throw new RangeError("initialPts must be an integer in the 33-bit MPEG timestamp range");
18282
+ }
18283
+ this.initialPts = BigInt(initialPts);
18284
+ }
18285
+ /**
18286
+ * Convert a source timestamp to a 33-bit 90 kHz PTS value.
18287
+ * First call establishes the base and returns the configured initial PTS.
18288
+ * Subsequent calls compute monotonic offsets; regression throws.
18289
+ */
18290
+ toPts(timestamp) {
18291
+ const tsBig = u64ToBigInt(timestamp);
18292
+ if (this.baseTimestamp === void 0) {
18293
+ this.baseTimestamp = tsBig;
18294
+ this.lastInputBig = tsBig;
18295
+ return Number(this.initialPts);
18296
+ }
18297
+ const lastInput = this.lastInputBig;
18298
+ if (lastInput !== void 0 && tsBig < lastInput) {
18299
+ throw new RangeError(`Timestamp regression: ${tsBig} < previous ${lastInput}`);
18300
+ }
18301
+ this.lastInputBig = tsBig;
18302
+ const deltaNs = tsBig - this.baseTimestamp;
18303
+ const ticks = deltaNs * NINE / ONE_HUNDRED_THOUSAND;
18304
+ const pts33 = ticks + this.initialPts & PTS_MASK_N;
18305
+ return Number(pts33);
18306
+ }
18307
+ /** Capture immutable timestamp state for an access-unit transaction. */
18308
+ captureState() {
18309
+ return {
18310
+ baseTimestamp: this.baseTimestamp,
18311
+ lastInput: this.lastInputBig
18312
+ };
18313
+ }
18314
+ /** Restore timestamp state when an access unit was not delivered. */
18315
+ restoreState(state) {
18316
+ this.baseTimestamp = state.baseTimestamp;
18317
+ this.lastInputBig = state.lastInput;
18318
+ }
18319
+ /** Reset clock to uninitialized state. */
18320
+ reset() {
18321
+ this.baseTimestamp = void 0;
18322
+ this.lastInputBig = void 0;
18323
+ }
18324
+ };
18325
+ exports.TransportClock = TransportClock;
18326
+ function validateU32(value, name) {
18327
+ if (!Number.isInteger(value) || !Number.isFinite(value) || value < 0 || value > 4294967295) {
18328
+ throw new RangeError(`${name} must be an unsigned 32-bit integer`);
18329
+ }
18330
+ }
18331
+ function u64Sub(a, b) {
18332
+ const aBig = u64ToBigInt(a);
18333
+ const bBig = u64ToBigInt(b);
18334
+ const diff = aBig - bBig;
18335
+ if (diff < ZERO) {
18336
+ throw new RangeError(`u64Sub: a < b (${aBig} < ${bBig})`);
18337
+ }
18338
+ return diff;
18339
+ }
18340
+ }
18341
+ });
18342
+
18343
+ // node_modules/@signageos/brightsign-decoder/dist/remux/MpegTsMuxer.js
18344
+ var require_MpegTsMuxer = __commonJS({
18345
+ "node_modules/@signageos/brightsign-decoder/dist/remux/MpegTsMuxer.js"(exports) {
18346
+ "use strict";
18347
+ Object.defineProperty(exports, "__esModule", { value: true });
18348
+ exports.MpegTsMuxer = void 0;
18349
+ exports.computeCrc32 = computeCrc32;
18350
+ exports.verifyCrc32 = verifyCrc32;
18351
+ var AnnexB_1 = require_AnnexB();
18352
+ var TransportClock_1 = require_TransportClock();
18353
+ var TS_PACKET_SIZE = 188;
18354
+ var PAT_PID = 0;
18355
+ var PMT_PID = 4096;
18356
+ var VIDEO_PID = 256;
18357
+ var H264_STREAM_TYPE = 27;
18358
+ var PES_STREAM_ID = 224;
18359
+ var crcTable = [];
18360
+ for (let i = 0; i < 256; i += 1) {
18361
+ let crc = i << 24;
18362
+ for (let bit = 0; bit < 8; bit += 1) {
18363
+ if (crc & 2147483648) {
18364
+ crc = (crc << 1 ^ 79764919) >>> 0;
18365
+ } else {
18366
+ crc = crc << 1 >>> 0;
18367
+ }
18368
+ }
18369
+ crcTable.push(crc >>> 0);
18370
+ }
18371
+ function computeCrc32(data, start, end) {
18372
+ let crc = 4294967295;
18373
+ for (let i = start; i < end; i += 1) {
18374
+ const byte = data[i];
18375
+ if (byte === void 0) {
18376
+ break;
18377
+ }
18378
+ const tableIndex = (crc >>> 24 ^ byte) & 255;
18379
+ const tableValue = crcTable[tableIndex];
18380
+ if (tableValue === void 0) {
18381
+ throw new Error("CRC table index out of bounds");
18382
+ }
18383
+ crc = (crc << 8 ^ tableValue) >>> 0;
18384
+ }
18385
+ return crc >>> 0;
18386
+ }
18387
+ function verifyCrc32(data, sectionStart, sectionLength) {
18388
+ if (sectionLength < 4) {
18389
+ return false;
18390
+ }
18391
+ const crcOffset = sectionStart + sectionLength - 4;
18392
+ const computed = computeCrc32(data, sectionStart, crcOffset);
18393
+ const b0 = data[crcOffset];
18394
+ const b1 = data[crcOffset + 1];
18395
+ const b2 = data[crcOffset + 2];
18396
+ const b3 = data[crcOffset + 3];
18397
+ if (b0 === void 0 || b1 === void 0 || b2 === void 0 || b3 === void 0) {
18398
+ return false;
18399
+ }
18400
+ const stored = (b0 << 24 | b1 << 16 | b2 << 8 | b3) >>> 0;
18401
+ return computed === stored;
18402
+ }
18403
+ function encodePts(pts, target, offset) {
18404
+ const pts30 = Math.floor(pts / 1073741824) & 7;
18405
+ const pts22 = Math.floor(pts / 4194304) & 255;
18406
+ const pts15 = Math.floor(pts / 32768) & 127;
18407
+ const pts7 = Math.floor(pts / 128) & 255;
18408
+ const pts0 = pts & 127;
18409
+ target[offset] = 33 | pts30 << 1;
18410
+ target[offset + 1] = pts22;
18411
+ target[offset + 2] = pts15 << 1 | 1;
18412
+ target[offset + 3] = pts7;
18413
+ target[offset + 4] = pts0 << 1 | 1;
18414
+ }
18415
+ function encodePcr(pcrBase, target, offset) {
18416
+ const b32 = Math.floor(pcrBase / 4294967296) & 1;
18417
+ const b24 = Math.floor(pcrBase / 16777216) & 255;
18418
+ const b16 = Math.floor(pcrBase / 65536) & 255;
18419
+ const b8 = Math.floor(pcrBase / 256) & 255;
18420
+ const b0 = pcrBase & 255;
18421
+ target[offset] = b32 << 7 | b24 >>> 1;
18422
+ target[offset + 1] = (b24 & 1) << 7 | b16 >>> 1;
18423
+ target[offset + 2] = (b16 & 1) << 7 | b8 >>> 1;
18424
+ target[offset + 3] = (b8 & 1) << 7 | b0 >>> 1;
18425
+ target[offset + 4] = (b0 & 1) << 7 | 126;
18426
+ target[offset + 5] = 0;
18427
+ }
18428
+ var RbspBitReader = class {
18429
+ constructor(data) {
18430
+ this.data = data;
18431
+ this.byteOffset = 0;
18432
+ this.bitOffset = 0;
18433
+ }
18434
+ readUnsignedExpGolomb() {
18435
+ let leadingZeroBits = 0;
18436
+ while (this.readBit() === 0) {
18437
+ leadingZeroBits += 1;
18438
+ if (leadingZeroBits > 52) {
18439
+ throw new Error("unsigned Exp-Golomb value exceeds safe integer range");
18440
+ }
18441
+ }
18442
+ let suffix = 0;
18443
+ for (let index = 0; index < leadingZeroBits; index += 1) {
18444
+ suffix = suffix * 2 + this.readBit();
18445
+ }
18446
+ const value = 2 ** leadingZeroBits - 1 + suffix;
18447
+ if (!Number.isSafeInteger(value)) {
18448
+ throw new Error("unsigned Exp-Golomb value exceeds safe integer range");
18449
+ }
18450
+ return value;
18451
+ }
18452
+ readBit() {
18453
+ const byte = this.data[this.byteOffset];
18454
+ if (byte === void 0) {
18455
+ throw new Error("truncated unsigned Exp-Golomb value");
18456
+ }
18457
+ const bit = byte >> 7 - this.bitOffset & 1;
18458
+ this.bitOffset += 1;
18459
+ if (this.bitOffset === 8) {
18460
+ this.bitOffset = 0;
18461
+ this.byteOffset += 1;
18462
+ }
18463
+ return bit;
18464
+ }
18465
+ };
18466
+ function ebspToRbsp(ebsp) {
18467
+ const rbsp = [];
18468
+ let consecutiveZeros = 0;
18469
+ for (let index = 0; index < ebsp.byteLength; index += 1) {
18470
+ const byte = ebsp[index];
18471
+ if (byte === void 0) {
18472
+ throw new Error("slice payload ended unexpectedly");
18473
+ }
18474
+ if (consecutiveZeros >= 2 && byte === 3) {
18475
+ const followingByte = ebsp[index + 1];
18476
+ if (followingByte === void 0 || followingByte > 3) {
18477
+ throw new Error("invalid emulation-prevention sequence");
18478
+ }
18479
+ consecutiveZeros = 0;
18480
+ continue;
18481
+ }
18482
+ rbsp.push(byte);
18483
+ consecutiveZeros = byte === 0 ? consecutiveZeros + 1 : 0;
18484
+ }
18485
+ return new Uint8Array(rbsp);
18486
+ }
18487
+ function parseSliceType(data, unit) {
18488
+ const nalHeaderOffset = unit.offset + (0, AnnexB_1.startCodeLength)(data, unit.offset);
18489
+ const payloadOffset = nalHeaderOffset + 1;
18490
+ const unitEnd = unit.offset + unit.length;
18491
+ if (payloadOffset >= unitEnd) {
18492
+ throw new Error("slice header is missing");
18493
+ }
18494
+ const reader = new RbspBitReader(ebspToRbsp(data.subarray(payloadOffset, unitEnd)));
18495
+ reader.readUnsignedExpGolomb();
18496
+ const sliceType = reader.readUnsignedExpGolomb();
18497
+ if (sliceType > 9) {
18498
+ throw new Error(`slice_type ${sliceType} is outside the valid range 0..9`);
18499
+ }
18500
+ return sliceType;
18501
+ }
18502
+ function validateSliceHeaders(data, nalUnits) {
18503
+ for (const unit of nalUnits) {
18504
+ if (unit.type !== AnnexB_1.NalType.NonIDRSlice && unit.type !== AnnexB_1.NalType.IDRSlice) {
18505
+ continue;
18506
+ }
18507
+ let sliceType;
18508
+ try {
18509
+ sliceType = parseSliceType(data, unit);
18510
+ } catch (error) {
18511
+ const detail = error instanceof Error ? error.message : "unknown slice-header parse error";
18512
+ throw new Error(`Invalid H.264 slice header in NAL type ${unit.type}: ${detail}`);
18513
+ }
18514
+ if (sliceType % 5 === 1) {
18515
+ throw new Error("H.264 B slices are unsupported because the muxer cannot derive DTS separately from PTS");
18516
+ }
18517
+ }
18518
+ }
18519
+ var MpegTsMuxer = class {
18520
+ constructor(options) {
18521
+ var _a, _b;
18522
+ this.patCc = 0;
18523
+ this.pmtCc = 0;
18524
+ this.videoCc = 0;
18525
+ this.needPat = true;
18526
+ this.waitingForIdr = true;
18527
+ this.preparedTransactionOutstanding = false;
18528
+ this.clock = new TransportClock_1.TransportClock((_a = options == null ? void 0 : options.initialPts) != null ? _a : 0);
18529
+ this.pcrLeadTicks = (_b = options == null ? void 0 : options.pcrLeadTicks) != null ? _b : 0;
18530
+ if (!Number.isSafeInteger(this.pcrLeadTicks) || this.pcrLeadTicks < 0 || this.pcrLeadTicks >= 8589934592) {
18531
+ throw new RangeError("pcrLeadTicks must be an integer in the 33-bit MPEG timestamp range");
18532
+ }
18533
+ }
18534
+ /**
18535
+ * Prepare one access unit without exposing its state changes until transport accepts it.
18536
+ * Decoder operations are serialized, so only one prepared unit may be unsettled at a time.
18537
+ */
18538
+ prepare(data, timestamp) {
18539
+ this.assertNoPreparedTransaction("prepare another access unit");
18540
+ const previous = this.captureState();
18541
+ let packets;
18542
+ try {
18543
+ packets = this.mux(data, timestamp);
18544
+ } catch (error) {
18545
+ this.restoreState(previous);
18546
+ throw error;
18547
+ }
18548
+ const next = this.captureState();
18549
+ this.restoreState(previous);
18550
+ this.preparedTransactionOutstanding = true;
18551
+ let settled = false;
18552
+ return {
18553
+ packets,
18554
+ commit: () => {
18555
+ if (settled) {
18556
+ return;
18557
+ }
18558
+ settled = true;
18559
+ this.preparedTransactionOutstanding = false;
18560
+ this.restoreState(next);
18561
+ },
18562
+ rejectBeforeWrite: () => {
18563
+ if (settled) {
18564
+ return;
18565
+ }
18566
+ settled = true;
18567
+ this.preparedTransactionOutstanding = false;
18568
+ this.restoreState(previous);
18569
+ this.waitingForIdr = true;
18570
+ this.needPat = true;
18571
+ }
18572
+ };
18573
+ }
18574
+ assertNoPreparedTransaction(operation) {
18575
+ if (this.preparedTransactionOutstanding) {
18576
+ throw new Error(`Cannot ${operation} while a prepared transaction is outstanding`);
18577
+ }
18578
+ }
18579
+ captureState() {
18580
+ return {
18581
+ clock: this.clock.captureState(),
18582
+ patContinuity: this.patCc,
18583
+ pmtContinuity: this.pmtCc,
18584
+ videoContinuity: this.videoCc,
18585
+ needPat: this.needPat,
18586
+ sps: this.lastSps,
18587
+ pps: this.lastPps,
18588
+ waitingForIdr: this.waitingForIdr
18589
+ };
18590
+ }
18591
+ restoreState(state) {
18592
+ this.clock.restoreState(state.clock);
18593
+ this.patCc = state.patContinuity;
18594
+ this.pmtCc = state.pmtContinuity;
18595
+ this.videoCc = state.videoContinuity;
18596
+ this.needPat = state.needPat;
18597
+ this.lastSps = state.sps;
18598
+ this.lastPps = state.pps;
18599
+ this.waitingForIdr = state.waitingForIdr;
18600
+ }
18601
+ /** Reset counters for a new TS epoch (SPS/PPS change). */
18602
+ resetEpoch() {
18603
+ this.assertNoPreparedTransaction("reset the muxer epoch");
18604
+ this.patCc = 0;
18605
+ this.pmtCc = 0;
18606
+ this.videoCc = 0;
18607
+ this.needPat = true;
18608
+ this.clock.reset();
18609
+ this.lastSps = void 0;
18610
+ this.lastPps = void 0;
18611
+ this.waitingForIdr = true;
18612
+ }
18613
+ /**
18614
+ * Mux an Annex-B access unit into aligned 188-byte TS packets.
18615
+ * Returns array of TS packet buffers.
18616
+ *
18617
+ * PAT/PMT are emitted immediately before every IDR so each random-access
18618
+ * access unit is a self-contained replay boundary. PCR is emitted on the
18619
+ * first video packet of every access unit; random-access indication remains
18620
+ * IDR-only.
18621
+ */
18622
+ mux(data, timestamp) {
18623
+ var _a, _b;
18624
+ this.assertNoPreparedTransaction("mux an access unit");
18625
+ const info = (0, AnnexB_1.inspectAccessUnit)(data);
18626
+ validateSliceHeaders(data, info.nalUnits);
18627
+ const hasVcl = info.nalUnits.some((unit) => unit.type === AnnexB_1.NalType.NonIDRSlice || unit.type === AnnexB_1.NalType.IDRSlice);
18628
+ const spsChanged = info.spsData !== void 0 && this.lastSps !== void 0 && !bytesEqual(this.lastSps, info.spsData);
18629
+ const ppsChanged = info.ppsData !== void 0 && this.lastPps !== void 0 && !bytesEqual(this.lastPps, info.ppsData);
18630
+ const candidateSps = (_a = info.spsData) != null ? _a : this.lastSps;
18631
+ const candidatePps = (_b = info.ppsData) != null ? _b : this.lastPps;
18632
+ const parameterChanged = spsChanged || ppsChanged;
18633
+ if (!hasVcl) {
18634
+ if (info.spsData !== void 0) {
18635
+ this.lastSps = info.spsData.slice();
18636
+ }
18637
+ if (info.ppsData !== void 0) {
18638
+ this.lastPps = info.ppsData.slice();
18639
+ }
18640
+ if (parameterChanged) {
18641
+ this.waitingForIdr = true;
18642
+ this.needPat = true;
18643
+ }
18644
+ return [];
18645
+ }
18646
+ const recoveryRequired = this.waitingForIdr || parameterChanged;
18647
+ if (recoveryRequired && !info.isIDR) {
18648
+ throw new Error("Waiting for an IDR access unit after startup or parameter change");
18649
+ }
18650
+ if (info.isIDR && (candidateSps === void 0 || candidatePps === void 0)) {
18651
+ throw new Error("Cannot establish a random-access epoch without both SPS and PPS");
18652
+ }
18653
+ const payload = info.isIDR ? prependParameterSets(data, info.hasSPS, info.hasPPS, candidateSps, candidatePps) : data;
18654
+ const pts = this.clock.toPts(timestamp);
18655
+ if (info.spsData !== void 0) {
18656
+ this.lastSps = info.spsData.slice();
18657
+ }
18658
+ if (info.ppsData !== void 0) {
18659
+ this.lastPps = info.ppsData.slice();
18660
+ }
18661
+ if (recoveryRequired) {
18662
+ this.waitingForIdr = false;
18663
+ this.needPat = true;
18664
+ }
18665
+ const packets = [];
18666
+ if (this.needPat || info.isIDR) {
18667
+ packets.push(this.buildPat());
18668
+ packets.push(this.buildPmt());
18669
+ this.needPat = false;
18670
+ }
18671
+ const pesHeader = buildPesHeader(pts, payload.byteLength);
18672
+ const pesLength = pesHeader.byteLength + payload.byteLength;
18673
+ let offset = 0;
18674
+ let first = true;
18675
+ while (offset < pesLength) {
18676
+ const packet = new Uint8Array(TS_PACKET_SIZE);
18677
+ packet.fill(255);
18678
+ packet[0] = 71;
18679
+ const pusi = first ? 64 : 0;
18680
+ packet[1] = pusi | VIDEO_PID >> 8 & 31;
18681
+ packet[2] = VIDEO_PID & 255;
18682
+ const remaining = pesLength - offset;
18683
+ const maxPayload = TS_PACKET_SIZE - 4;
18684
+ if (first) {
18685
+ const adaptationFlags = 16 | (info.isIDR ? 64 : 0);
18686
+ const minimumAdaptationLength = 7;
18687
+ const payloadCapacity = TS_PACKET_SIZE - 4 - 1 - minimumAdaptationLength;
18688
+ const bytesToCopy = Math.min(remaining, payloadCapacity);
18689
+ const adaptationLength = bytesToCopy < payloadCapacity ? TS_PACKET_SIZE - 5 - bytesToCopy : minimumAdaptationLength;
18690
+ const payloadStart = 5 + adaptationLength;
18691
+ packet[3] = 48 | this.videoCc & 15;
18692
+ this.videoCc = this.videoCc + 1 & 15;
18693
+ packet[4] = adaptationLength;
18694
+ packet[5] = adaptationFlags;
18695
+ const pcr = (pts - this.pcrLeadTicks + 8589934592) % 8589934592;
18696
+ encodePcr(pcr, packet, 6);
18697
+ copyPesBytes(pesHeader, payload, offset, bytesToCopy, packet, payloadStart);
18698
+ offset += bytesToCopy;
18699
+ } else if (remaining >= maxPayload) {
18700
+ packet[3] = 16 | this.videoCc & 15;
18701
+ this.videoCc = this.videoCc + 1 & 15;
18702
+ copyPesBytes(pesHeader, payload, offset, maxPayload, packet, 4);
18703
+ offset += maxPayload;
18704
+ } else {
18705
+ const adaptFieldLength = 183 - remaining;
18706
+ packet[3] = 48 | this.videoCc & 15;
18707
+ this.videoCc = this.videoCc + 1 & 15;
18708
+ packet[4] = adaptFieldLength;
18709
+ if (adaptFieldLength > 0) {
18710
+ packet[5] = 0;
18711
+ }
18712
+ const payloadStart = 5 + adaptFieldLength;
18713
+ copyPesBytes(pesHeader, payload, offset, remaining, packet, payloadStart);
18714
+ offset = pesLength;
18715
+ }
18716
+ first = false;
18717
+ packets.push(packet);
18718
+ }
18719
+ return packets;
18720
+ }
18721
+ /** Build a PAT (Program Association Table) TS packet. */
18722
+ buildPat() {
18723
+ const packet = new Uint8Array(TS_PACKET_SIZE);
18724
+ packet.fill(255);
18725
+ packet[0] = 71;
18726
+ packet[1] = 64 | PAT_PID >> 8 & 31;
18727
+ packet[2] = PAT_PID & 255;
18728
+ packet[3] = 16 | this.patCc & 15;
18729
+ this.patCc = this.patCc + 1 & 15;
18730
+ packet[4] = 0;
18731
+ const sectionStart = 5;
18732
+ packet[sectionStart] = 0;
18733
+ packet[sectionStart + 1] = 176;
18734
+ packet[sectionStart + 2] = 13;
18735
+ packet[sectionStart + 3] = 0;
18736
+ packet[sectionStart + 4] = 1;
18737
+ packet[sectionStart + 5] = 193;
18738
+ packet[sectionStart + 6] = 0;
18739
+ packet[sectionStart + 7] = 0;
18740
+ packet[sectionStart + 8] = 0;
18741
+ packet[sectionStart + 9] = 1;
18742
+ packet[sectionStart + 10] = 224 | PMT_PID >> 8 & 31;
18743
+ packet[sectionStart + 11] = PMT_PID & 255;
18744
+ const crc = computeCrc32(packet, sectionStart, sectionStart + 12);
18745
+ const crcOffset = sectionStart + 12;
18746
+ packet[crcOffset] = crc >>> 24 & 255;
18747
+ packet[crcOffset + 1] = crc >>> 16 & 255;
18748
+ packet[crcOffset + 2] = crc >>> 8 & 255;
18749
+ packet[crcOffset + 3] = crc & 255;
18750
+ return packet;
18751
+ }
18752
+ /** Build a PMT (Program Map Table) TS packet. */
18753
+ buildPmt() {
18754
+ const packet = new Uint8Array(TS_PACKET_SIZE);
18755
+ packet.fill(255);
18756
+ packet[0] = 71;
18757
+ packet[1] = 64 | PMT_PID >> 8 & 31;
18758
+ packet[2] = PMT_PID & 255;
18759
+ packet[3] = 16 | this.pmtCc & 15;
18760
+ this.pmtCc = this.pmtCc + 1 & 15;
18761
+ packet[4] = 0;
18762
+ const sectionStart = 5;
18763
+ packet[sectionStart] = 2;
18764
+ packet[sectionStart + 1] = 176;
18765
+ packet[sectionStart + 2] = 18;
18766
+ packet[sectionStart + 3] = 0;
18767
+ packet[sectionStart + 4] = 1;
18768
+ packet[sectionStart + 5] = 193;
18769
+ packet[sectionStart + 6] = 0;
18770
+ packet[sectionStart + 7] = 0;
18771
+ packet[sectionStart + 8] = 224 | VIDEO_PID >> 8 & 31;
18772
+ packet[sectionStart + 9] = VIDEO_PID & 255;
18773
+ packet[sectionStart + 10] = 240;
18774
+ packet[sectionStart + 11] = 0;
18775
+ packet[sectionStart + 12] = H264_STREAM_TYPE;
18776
+ packet[sectionStart + 13] = 224 | VIDEO_PID >> 8 & 31;
18777
+ packet[sectionStart + 14] = VIDEO_PID & 255;
18778
+ packet[sectionStart + 15] = 240;
18779
+ packet[sectionStart + 16] = 0;
18780
+ const crc = computeCrc32(packet, sectionStart, sectionStart + 17);
18781
+ const crcOffset = sectionStart + 17;
18782
+ packet[crcOffset] = crc >>> 24 & 255;
18783
+ packet[crcOffset + 1] = crc >>> 16 & 255;
18784
+ packet[crcOffset + 2] = crc >>> 8 & 255;
18785
+ packet[crcOffset + 3] = crc & 255;
18786
+ return packet;
18787
+ }
18788
+ /** Get current continuity counter state for diagnostics. */
18789
+ get counters() {
18790
+ return { pat: this.patCc, pmt: this.pmtCc, video: this.videoCc };
18791
+ }
18792
+ };
18793
+ exports.MpegTsMuxer = MpegTsMuxer;
18794
+ function buildPesHeader(pts, dataLength) {
18795
+ const pesHeaderLength = 14;
18796
+ const header = new Uint8Array(pesHeaderLength);
18797
+ header[0] = 0;
18798
+ header[1] = 0;
18799
+ header[2] = 1;
18800
+ header[3] = PES_STREAM_ID;
18801
+ const pesPayloadLength = dataLength + 8;
18802
+ if (pesPayloadLength > 65535) {
18803
+ header[4] = 0;
18804
+ header[5] = 0;
18805
+ } else {
18806
+ header[4] = pesPayloadLength >> 8 & 255;
18807
+ header[5] = pesPayloadLength & 255;
18808
+ }
18809
+ header[6] = 128;
18810
+ header[7] = 128;
18811
+ header[8] = 5;
18812
+ encodePts(pts, header, 9);
18813
+ return header;
18814
+ }
18815
+ function prependParameterSets(data, hasSps, hasPps, sps, pps) {
18816
+ if (sps === void 0 || pps === void 0) {
18817
+ throw new Error("SPS/PPS state is unavailable");
18818
+ }
18819
+ const spsLength = hasSps ? 0 : sps.byteLength;
18820
+ const ppsLength = hasPps ? 0 : pps.byteLength;
18821
+ if (spsLength === 0 && ppsLength === 0) {
18822
+ return data;
18823
+ }
18824
+ const result = new Uint8Array(spsLength + ppsLength + data.byteLength);
18825
+ let offset = 0;
18826
+ if (!hasSps) {
18827
+ result.set(sps, offset);
18828
+ offset += sps.byteLength;
18829
+ }
18830
+ if (!hasPps) {
18831
+ result.set(pps, offset);
18832
+ offset += pps.byteLength;
18833
+ }
18834
+ result.set(data, offset);
18835
+ return result;
18836
+ }
18837
+ function copyPesBytes(header, payload, sourceOffset, length, destination, destinationOffset) {
18838
+ let remaining = length;
18839
+ let source = sourceOffset;
18840
+ let target = destinationOffset;
18841
+ if (source < header.byteLength && remaining > 0) {
18842
+ const headerLength = Math.min(remaining, header.byteLength - source);
18843
+ destination.set(header.subarray(source, source + headerLength), target);
18844
+ source += headerLength;
18845
+ target += headerLength;
18846
+ remaining -= headerLength;
18847
+ }
18848
+ if (remaining > 0) {
18849
+ const payloadOffset = source - header.byteLength;
18850
+ destination.set(payload.subarray(payloadOffset, payloadOffset + remaining), target);
18851
+ }
18852
+ }
18853
+ function bytesEqual(a, b) {
18854
+ if (a.byteLength !== b.byteLength) {
18855
+ return false;
18856
+ }
18857
+ for (let i = 0; i < a.byteLength; i += 1) {
18858
+ if (a[i] !== b[i]) {
18859
+ return false;
18860
+ }
18861
+ }
18862
+ return true;
18863
+ }
18864
+ }
18865
+ });
18866
+
18867
+ // node_modules/@signageos/brightsign-decoder/dist/decoder/NativeHttpServer.js
18868
+ var require_NativeHttpServer = __commonJS({
18869
+ "node_modules/@signageos/brightsign-decoder/dist/decoder/NativeHttpServer.js"(exports) {
18870
+ "use strict";
18871
+ Object.defineProperty(exports, "__esModule", { value: true });
18872
+ exports.NativeHttpServer = exports.NativeHttpPreWriteError = void 0;
18873
+ var TS_PACKET_SIZE = 188;
18874
+ var DEFAULT_MAX_REPLAY_PACKETS = 8192;
18875
+ var DEFAULT_MAX_REPLAY_BYTES = 2 * 1024 * 1024;
18876
+ var DEFAULT_PROBE_PROMOTION_DELAY_MS = 100;
18877
+ var NativeHttpPreWriteError = class extends Error {
18878
+ constructor(message) {
18879
+ super(message);
18880
+ this.name = "NativeHttpPreWriteError";
18881
+ }
18882
+ };
18883
+ exports.NativeHttpPreWriteError = NativeHttpPreWriteError;
18884
+ var NativeHttpServer = class {
18885
+ constructor(options) {
18886
+ var _a, _b, _c, _d;
18887
+ this.requests = /* @__PURE__ */ new Set();
18888
+ this.backpressureWaits = [];
18889
+ this.totalRequests = 0;
18890
+ this.closedRequests = 0;
18891
+ this.responseCloseEvents = 0;
18892
+ this.responseErrorEvents = 0;
18893
+ this.rejectedRequests = 0;
18894
+ this.probeReplacements = 0;
18895
+ this.playbackPromotions = 0;
18896
+ this.playbackReconnects = 0;
18897
+ this.playbackClosures = 0;
18898
+ this.backpressureEvents = 0;
18899
+ this.totalBackpressureWaitMs = 0;
18900
+ this.packetsWritten = 0;
18901
+ this.bytesWritten = 0;
18902
+ this.replayBoundaries = 0;
18903
+ this.replayReplacements = 0;
18904
+ this.replayFreezes = 0;
18905
+ this.lastClosedRequestPackets = 0;
18906
+ this.lastClosedRequestBytes = 0;
18907
+ this.replayUnits = [];
18908
+ this.replayPacketCount = 0;
18909
+ this.replayByteLength = 0;
18910
+ this.replayFrozen = false;
18911
+ this.writeChain = Promise.resolve();
18912
+ this.port = 0;
18913
+ this.destroyed = false;
18914
+ this.teardownComplete = false;
18915
+ this.serverClosed = false;
18916
+ this.maxReplayPackets = (_a = options == null ? void 0 : options.maxReplayPackets) != null ? _a : DEFAULT_MAX_REPLAY_PACKETS;
18917
+ this.maxReplayBytes = (_b = options == null ? void 0 : options.maxReplayBytes) != null ? _b : DEFAULT_MAX_REPLAY_BYTES;
18918
+ this.probePromotionDelayMs = (_c = options == null ? void 0 : options.probePromotionDelayMs) != null ? _c : DEFAULT_PROBE_PROMOTION_DELAY_MS;
18919
+ this.now = (_d = options == null ? void 0 : options.now) != null ? _d : Date.now;
18920
+ if (!Number.isSafeInteger(this.maxReplayPackets) || this.maxReplayPackets <= 0) {
18921
+ throw new RangeError("maxReplayPackets must be a positive integer");
18922
+ }
18923
+ if (!Number.isSafeInteger(this.maxReplayBytes) || this.maxReplayBytes <= 0) {
18924
+ throw new RangeError("maxReplayBytes must be a positive integer");
18925
+ }
18926
+ if (!Number.isFinite(this.probePromotionDelayMs) || this.probePromotionDelayMs < 0) {
18927
+ throw new RangeError("probePromotionDelayMs must be a finite non-negative number");
18928
+ }
18929
+ }
18930
+ async start(httpModule) {
18931
+ if (this.destroyed) {
18932
+ throw new Error("NativeHttpServer has been destroyed");
18933
+ }
18934
+ if (this.server !== void 0) {
18935
+ throw new Error("NativeHttpServer is already started");
18936
+ }
18937
+ await new Promise((resolve, reject) => {
18938
+ let settled = false;
18939
+ try {
18940
+ const created = httpModule.createServer((_request, response) => {
18941
+ this.handleRequest(response);
18942
+ });
18943
+ const server = narrowToHttpServerLike(created);
18944
+ this.server = server;
18945
+ server.on("error", (value) => {
18946
+ const error = toError(value, "Loopback HTTP server error");
18947
+ if (!settled) {
18948
+ settled = true;
18949
+ reject(error);
18950
+ return;
18951
+ }
18952
+ this.recordServerFailure(error);
18953
+ });
18954
+ server.listen(0, "127.0.0.1", () => {
18955
+ if (settled) {
18956
+ return;
18957
+ }
18958
+ const address = server.address();
18959
+ if (typeof address !== "object" || address === null || !Number.isInteger(address.port)) {
18960
+ settled = true;
18961
+ reject(new Error("Loopback HTTP server did not report a bound port"));
18962
+ return;
18963
+ }
18964
+ this.port = address.port;
18965
+ settled = true;
18966
+ resolve();
18967
+ });
18968
+ } catch (error) {
18969
+ settled = true;
18970
+ reject(toError(error, "Loopback HTTP server creation failed"));
18971
+ }
18972
+ });
18973
+ return this.port;
18974
+ }
18975
+ getDiagnostics() {
18976
+ var _a;
18977
+ const activeBackpressureWaitMs = this.backpressureWaits.reduce((total, wait) => total + Math.max(0, this.now() - wait.startedAtMs), 0);
18978
+ return {
18979
+ activeRequests: this.requests.size,
18980
+ totalRequests: this.totalRequests,
18981
+ closedRequests: this.closedRequests,
18982
+ responseCloseEvents: this.responseCloseEvents,
18983
+ responseErrorEvents: this.responseErrorEvents,
18984
+ rejectedRequests: this.rejectedRequests,
18985
+ probeReplacements: this.probeReplacements,
18986
+ playbackPromotions: this.playbackPromotions,
18987
+ playbackReconnects: this.playbackReconnects,
18988
+ playbackClosures: this.playbackClosures,
18989
+ backpressureEvents: this.backpressureEvents,
18990
+ activeBackpressureWaits: this.backpressureWaits.length,
18991
+ totalBackpressureWaitMs: this.totalBackpressureWaitMs + activeBackpressureWaitMs,
18992
+ packetsWritten: this.packetsWritten,
18993
+ bytesWritten: this.bytesWritten,
18994
+ replayUnits: this.replayUnits.length,
18995
+ replayPackets: this.replayPacketCount,
18996
+ replayBytes: this.replayByteLength,
18997
+ replayFrozen: this.replayFrozen,
18998
+ replayBoundaries: this.replayBoundaries,
18999
+ replayReplacements: this.replayReplacements,
19000
+ replayFreezes: this.replayFreezes,
19001
+ waitingForBoundary: ((_a = this.playbackRequest) == null ? void 0 : _a.waitingForBoundary) === true,
19002
+ lastClosedRequestPackets: this.lastClosedRequestPackets,
19003
+ lastClosedRequestBytes: this.lastClosedRequestBytes
19004
+ };
19005
+ }
19006
+ async writeAccessUnit(packets) {
19007
+ if (this.destroyed) {
19008
+ throw new NativeHttpPreWriteError("NativeHttpServer has been destroyed");
19009
+ }
19010
+ if (this.serverFailure !== void 0) {
19011
+ throw new NativeHttpPreWriteError(this.serverFailure.message);
19012
+ }
19013
+ if (packets.length === 0) {
19014
+ return;
19015
+ }
19016
+ for (const packet of packets) {
19017
+ if (packet.byteLength !== TS_PACKET_SIZE || packet[0] !== 71) {
19018
+ throw new NativeHttpPreWriteError("Native HTTP transport accepts only aligned 188-byte TS packets");
19019
+ }
19020
+ }
19021
+ const replayBoundary = packets.some(isPatPacket) && packets.some(isPmtPacket) && packets.some(hasRandomAccessIndicator);
19022
+ await this.enqueueWrite(async () => {
19023
+ if (this.destroyed) {
19024
+ throw new NativeHttpPreWriteError("NativeHttpServer has been destroyed");
19025
+ }
19026
+ if (this.serverFailure !== void 0) {
19027
+ throw new NativeHttpPreWriteError(this.serverFailure.message);
19028
+ }
19029
+ const replayState = this.captureReplayState();
19030
+ let playback;
19031
+ let packetsWrittenBefore = 0;
19032
+ try {
19033
+ this.retainReplayUnit(packets, replayBoundary);
19034
+ playback = this.playbackRequest;
19035
+ if (playback === void 0 || playback.closed) {
19036
+ return;
19037
+ }
19038
+ if (playback.waitingForBoundary && !replayBoundary) {
19039
+ return;
19040
+ }
19041
+ packetsWrittenBefore = playback.packetsWritten;
19042
+ for (const packet of packets) {
19043
+ await this.writePacketToRequest(playback, packet);
19044
+ }
19045
+ if (replayBoundary && !playback.closed) {
19046
+ playback.waitingForBoundary = false;
19047
+ }
19048
+ } catch (error) {
19049
+ const normalized = toError(error, "Native HTTP response failed during access-unit delivery");
19050
+ if (playback !== void 0) {
19051
+ this.retireRequest(playback, normalized);
19052
+ }
19053
+ if (playback === void 0 || playback.packetsWritten === packetsWrittenBefore) {
19054
+ this.restoreReplayState(replayState);
19055
+ throw new NativeHttpPreWriteError(normalized.message);
19056
+ }
19057
+ throw normalized;
19058
+ }
19059
+ });
19060
+ }
19061
+ async writePacket(packet) {
19062
+ await this.writeAccessUnit([packet]);
19063
+ }
19064
+ get uri() {
19065
+ if (this.port === 0) {
19066
+ throw new Error("NativeHttpServer is not started");
19067
+ }
19068
+ return `http://127.0.0.1:${this.port}/stream.ts`;
19069
+ }
19070
+ destroy() {
19071
+ if (this.teardownComplete) {
19072
+ return Promise.resolve();
19073
+ }
19074
+ if (this.teardown !== void 0) {
19075
+ return this.teardown;
19076
+ }
19077
+ this.destroyed = true;
19078
+ const attempt = this.performTeardown();
19079
+ const promise = attempt.then(() => {
19080
+ this.teardownComplete = true;
19081
+ }, (error) => {
19082
+ if (this.teardown === promise) {
19083
+ this.teardown = void 0;
19084
+ }
19085
+ throw error;
19086
+ });
19087
+ this.teardown = promise;
19088
+ return promise;
19089
+ }
19090
+ async performTeardown() {
19091
+ if (this.promotionTimer !== void 0) {
19092
+ clearTimeout(this.promotionTimer);
19093
+ this.promotionTimer = void 0;
19094
+ }
19095
+ for (const request of this.requests) {
19096
+ this.closeRequest(request);
19097
+ request.response.destroy();
19098
+ }
19099
+ this.requests.clear();
19100
+ this.playbackRequest = void 0;
19101
+ this.promotingRequest = void 0;
19102
+ this.probeRequest = void 0;
19103
+ this.replayUnits.length = 0;
19104
+ this.replayPacketCount = 0;
19105
+ this.replayByteLength = 0;
19106
+ this.replayFrozen = false;
19107
+ await this.writeChain;
19108
+ const server = this.server;
19109
+ if (!this.serverClosed && server !== void 0) {
19110
+ await new Promise((resolve) => {
19111
+ server.close(resolve);
19112
+ });
19113
+ this.serverClosed = true;
19114
+ this.server = void 0;
19115
+ }
19116
+ }
19117
+ handleRequest(value) {
19118
+ if (this.destroyed) {
19119
+ return;
19120
+ }
19121
+ let response;
19122
+ try {
19123
+ response = narrowToHttpResponseLike(value);
19124
+ } catch {
19125
+ return;
19126
+ }
19127
+ response.writeHead(200, {
19128
+ "Cache-Control": "no-store",
19129
+ Connection: "keep-alive",
19130
+ "Content-Type": "video/mp2t",
19131
+ "Transfer-Encoding": "chunked"
19132
+ });
19133
+ this.totalRequests += 1;
19134
+ const request = {
19135
+ response,
19136
+ drainWaiters: /* @__PURE__ */ new Set(),
19137
+ closed: false,
19138
+ waitingForBoundary: false,
19139
+ bytesWritten: 0,
19140
+ packetsWritten: 0
19141
+ };
19142
+ this.requests.add(request);
19143
+ response.once("close", () => {
19144
+ this.responseCloseEvents += 1;
19145
+ this.closeRequest(request, new Error("Native HTTP response closed before delivery completed"));
19146
+ });
19147
+ response.once("error", (...args) => {
19148
+ this.responseErrorEvents += 1;
19149
+ this.closeRequest(request, toError(args[0], "Native HTTP response failed before delivery completed"));
19150
+ });
19151
+ if (this.hasConnectedPlaybackRequest()) {
19152
+ if (this.probeRequest !== void 0 && !this.probeRequest.closed) {
19153
+ this.probeReplacements += 1;
19154
+ this.probeRequest.response.end();
19155
+ this.closeRequest(this.probeRequest);
19156
+ }
19157
+ this.probeRequest = request;
19158
+ return;
19159
+ }
19160
+ if (this.probeRequest === void 0 || this.probeRequest.closed) {
19161
+ this.probeRequest = request;
19162
+ this.scheduleProbePromotion(request, this.playbackPromotions > 0 ? 0 : this.probePromotionDelayMs);
19163
+ return;
19164
+ }
19165
+ const probe = this.probeRequest;
19166
+ if (!probe.closed) {
19167
+ this.probeReplacements += 1;
19168
+ probe.response.end();
19169
+ this.closeRequest(probe);
19170
+ }
19171
+ this.promoteToPlayback(request);
19172
+ }
19173
+ scheduleProbePromotion(request, delayMs) {
19174
+ this.promotionTimer = setTimeout(() => {
19175
+ this.promotionTimer = void 0;
19176
+ if (!request.closed && this.playbackRequest === void 0 && this.probeRequest === request) {
19177
+ this.promoteToPlayback(request);
19178
+ }
19179
+ }, delayMs);
19180
+ }
19181
+ promoteToPlayback(request) {
19182
+ if (request.closed || this.destroyed || this.playbackRequest !== void 0 || this.promotingRequest !== void 0) {
19183
+ return;
19184
+ }
19185
+ if (this.promotionTimer !== void 0) {
19186
+ clearTimeout(this.promotionTimer);
19187
+ this.promotionTimer = void 0;
19188
+ }
19189
+ if (this.probeRequest === request) {
19190
+ this.probeRequest = void 0;
19191
+ }
19192
+ this.promotingRequest = request;
19193
+ void this.enqueueWrite(async () => {
19194
+ if (request.closed || this.destroyed || this.promotingRequest !== request || this.playbackRequest !== void 0) {
19195
+ if (this.promotingRequest === request) {
19196
+ this.promotingRequest = void 0;
19197
+ }
19198
+ return;
19199
+ }
19200
+ if (this.replayFrozen || this.replayUnits.length === 0) {
19201
+ this.promotingRequest = void 0;
19202
+ this.recordPlaybackPromotion();
19203
+ this.playbackRequest = request;
19204
+ request.waitingForBoundary = true;
19205
+ return;
19206
+ }
19207
+ const replay = this.replayUnits.slice();
19208
+ try {
19209
+ for (const unit of replay) {
19210
+ for (const packet of unit.packets) {
19211
+ await this.writePacketToRequest(request, packet);
19212
+ }
19213
+ }
19214
+ } catch (error) {
19215
+ this.retireRequest(request, toError(error, "Native HTTP response failed during replay"));
19216
+ return;
19217
+ }
19218
+ if (request.closed || this.destroyed || this.promotingRequest !== request || this.playbackRequest !== void 0) {
19219
+ if (this.promotingRequest === request) {
19220
+ this.promotingRequest = void 0;
19221
+ }
19222
+ return;
19223
+ }
19224
+ this.promotingRequest = void 0;
19225
+ this.recordPlaybackPromotion();
19226
+ this.playbackRequest = request;
19227
+ });
19228
+ }
19229
+ recordPlaybackPromotion() {
19230
+ if (this.playbackPromotions > 0) {
19231
+ this.playbackReconnects += 1;
19232
+ }
19233
+ this.playbackPromotions += 1;
19234
+ }
19235
+ hasConnectedPlaybackRequest() {
19236
+ return this.playbackRequest !== void 0 && !this.playbackRequest.closed || this.promotingRequest !== void 0 && !this.promotingRequest.closed;
19237
+ }
19238
+ captureReplayState() {
19239
+ return {
19240
+ units: this.replayUnits.slice(),
19241
+ packetCount: this.replayPacketCount,
19242
+ byteLength: this.replayByteLength,
19243
+ frozen: this.replayFrozen
19244
+ };
19245
+ }
19246
+ restoreReplayState(state) {
19247
+ this.replayUnits.length = 0;
19248
+ this.replayUnits.push(...state.units);
19249
+ this.replayPacketCount = state.packetCount;
19250
+ this.replayByteLength = state.byteLength;
19251
+ this.replayFrozen = state.frozen;
19252
+ }
19253
+ retainReplayUnit(packets, replayBoundary) {
19254
+ const byteLength = packets.reduce((total, packet) => total + packet.byteLength, 0);
19255
+ if (replayBoundary) {
19256
+ if (packets.length > this.maxReplayPackets || byteLength > this.maxReplayBytes) {
19257
+ throw new NativeHttpPreWriteError("A replay-boundary access unit exceeds the replay capacity");
19258
+ }
19259
+ this.replayBoundaries += 1;
19260
+ if (this.replayUnits.length > 0) {
19261
+ this.replayReplacements += 1;
19262
+ }
19263
+ const replacement = copyPackets(packets);
19264
+ this.replayUnits.length = 0;
19265
+ this.replayUnits.push({ packets: replacement, byteLength });
19266
+ this.replayPacketCount = packets.length;
19267
+ this.replayByteLength = byteLength;
19268
+ this.replayFrozen = false;
19269
+ return;
19270
+ }
19271
+ if (this.replayUnits.length === 0 || this.replayFrozen) {
19272
+ return;
19273
+ }
19274
+ if (this.replayPacketCount + packets.length > this.maxReplayPackets || this.replayByteLength + byteLength > this.maxReplayBytes) {
19275
+ this.replayFrozen = true;
19276
+ this.replayFreezes += 1;
19277
+ return;
19278
+ }
19279
+ this.replayUnits.push({ packets: copyPackets(packets), byteLength });
19280
+ this.replayPacketCount += packets.length;
19281
+ this.replayByteLength += byteLength;
19282
+ }
19283
+ enqueueWrite(operation) {
19284
+ const next = this.writeChain.then(operation);
19285
+ this.writeChain = next.catch(() => void 0);
19286
+ return next;
19287
+ }
19288
+ async writePacketToRequest(request, packet) {
19289
+ if (request.closed) {
19290
+ throw new Error("Native HTTP response closed before packet submission");
19291
+ }
19292
+ if (this.destroyed) {
19293
+ return;
19294
+ }
19295
+ const accepted = request.response.write(packet);
19296
+ request.bytesWritten += packet.byteLength;
19297
+ request.packetsWritten += 1;
19298
+ this.bytesWritten += packet.byteLength;
19299
+ this.packetsWritten += 1;
19300
+ if (accepted) {
19301
+ return;
19302
+ }
19303
+ this.backpressureEvents += 1;
19304
+ const wait = { startedAtMs: this.now() };
19305
+ this.backpressureWaits.push(wait);
19306
+ await new Promise((resolve, reject) => {
19307
+ let settled = false;
19308
+ const settle = (error) => {
19309
+ if (settled) {
19310
+ return;
19311
+ }
19312
+ settled = true;
19313
+ request.drainWaiters.delete(settle);
19314
+ const waitIndex = this.backpressureWaits.indexOf(wait);
19315
+ if (waitIndex >= 0) {
19316
+ this.backpressureWaits.splice(waitIndex, 1);
19317
+ }
19318
+ this.totalBackpressureWaitMs += Math.max(0, this.now() - wait.startedAtMs);
19319
+ if (error === void 0) {
19320
+ resolve();
19321
+ } else {
19322
+ reject(error);
19323
+ }
19324
+ };
19325
+ request.drainWaiters.add(settle);
19326
+ request.response.once("drain", () => settle(void 0));
19327
+ if (request.closed) {
19328
+ settle(new Error("Native HTTP response closed before backpressure drained"));
19329
+ } else if (this.destroyed) {
19330
+ settle(void 0);
19331
+ }
19332
+ });
19333
+ }
19334
+ recordServerFailure(error) {
19335
+ if (this.destroyed || this.serverFailure !== void 0) {
19336
+ return;
19337
+ }
19338
+ this.serverFailure = error;
19339
+ for (const request of this.requests) {
19340
+ this.retireRequest(request, error);
19341
+ }
19342
+ }
19343
+ retireRequest(request, error) {
19344
+ this.closeRequest(request, error);
19345
+ request.response.destroy();
19346
+ }
19347
+ closeRequest(request, error) {
19348
+ if (request.closed) {
19349
+ return;
19350
+ }
19351
+ const wasPlaybackRequest = this.playbackRequest === request;
19352
+ request.closed = true;
19353
+ this.closedRequests += 1;
19354
+ this.lastClosedRequestPackets = request.packetsWritten;
19355
+ this.lastClosedRequestBytes = request.bytesWritten;
19356
+ if (wasPlaybackRequest) {
19357
+ this.playbackClosures += 1;
19358
+ }
19359
+ for (const settle of request.drainWaiters) {
19360
+ settle(error);
19361
+ }
19362
+ request.drainWaiters.clear();
19363
+ this.requests.delete(request);
19364
+ if (this.playbackRequest === request) {
19365
+ this.playbackRequest = void 0;
19366
+ }
19367
+ if (this.promotingRequest === request) {
19368
+ this.promotingRequest = void 0;
19369
+ }
19370
+ if (this.probeRequest === request) {
19371
+ this.probeRequest = void 0;
19372
+ }
19373
+ if (wasPlaybackRequest && this.probeRequest !== void 0 && !this.probeRequest.closed) {
19374
+ this.promoteToPlayback(this.probeRequest);
19375
+ }
19376
+ }
19377
+ };
19378
+ exports.NativeHttpServer = NativeHttpServer;
19379
+ function copyPackets(packets) {
19380
+ return packets.map((packet) => {
19381
+ const copy = new Uint8Array(packet.byteLength);
19382
+ copy.set(packet);
19383
+ return copy;
19384
+ });
19385
+ }
19386
+ function packetPid(packet) {
19387
+ const high = packet[1];
19388
+ const low = packet[2];
19389
+ if (high === void 0 || low === void 0) {
19390
+ return void 0;
19391
+ }
19392
+ return (high & 31) << 8 | low;
19393
+ }
19394
+ function isPatPacket(packet) {
19395
+ return packetPid(packet) === 0;
19396
+ }
19397
+ function isPmtPacket(packet) {
19398
+ return packetPid(packet) === 4096;
19399
+ }
19400
+ function hasRandomAccessIndicator(packet) {
19401
+ const control = packet[3];
19402
+ const flags = packet[5];
19403
+ if (control === void 0 || flags === void 0) {
19404
+ return false;
19405
+ }
19406
+ const hasAdaptation = (control & 32) !== 0;
19407
+ return packetPid(packet) === 256 && hasAdaptation && (flags & 64) !== 0;
19408
+ }
19409
+ function narrowToHttpServerLike(value) {
19410
+ if (typeof value !== "object" || value === null) {
19411
+ throw new TypeError("Expected an HTTP server object");
19412
+ }
19413
+ const listen = Reflect.get(value, "listen");
19414
+ const close = Reflect.get(value, "close");
19415
+ const address = Reflect.get(value, "address");
19416
+ const on = Reflect.get(value, "on");
19417
+ if (typeof listen !== "function" || typeof close !== "function" || typeof address !== "function" || typeof on !== "function") {
19418
+ throw new TypeError("Object does not satisfy the HTTP server contract");
19419
+ }
19420
+ return {
19421
+ listen(port, host, callback) {
19422
+ Reflect.apply(listen, value, [port, host, callback]);
19423
+ },
19424
+ close(callback) {
19425
+ Reflect.apply(close, value, callback === void 0 ? [] : [callback]);
19426
+ },
19427
+ address() {
19428
+ const result = Reflect.apply(address, value, []);
19429
+ if (typeof result === "string" || result === null) {
19430
+ return result;
19431
+ }
19432
+ if (typeof result === "object") {
19433
+ const port = Reflect.get(result, "port");
19434
+ if (typeof port === "number") {
19435
+ return { port };
19436
+ }
19437
+ }
19438
+ return null;
19439
+ },
19440
+ on(event, listener) {
19441
+ Reflect.apply(on, value, [event, listener]);
19442
+ }
19443
+ };
19444
+ }
19445
+ function narrowToHttpResponseLike(value) {
19446
+ if (typeof value !== "object" || value === null) {
19447
+ throw new TypeError("Expected an HTTP response object");
19448
+ }
19449
+ const writeHead = Reflect.get(value, "writeHead");
19450
+ const write = Reflect.get(value, "write");
19451
+ const end = Reflect.get(value, "end");
19452
+ const destroy = Reflect.get(value, "destroy");
19453
+ const on = Reflect.get(value, "on");
19454
+ const once = Reflect.get(value, "once");
19455
+ if (typeof writeHead !== "function" || typeof write !== "function" || typeof end !== "function" || typeof destroy !== "function" || typeof on !== "function" || typeof once !== "function") {
19456
+ throw new TypeError("Object does not satisfy the HTTP response contract");
19457
+ }
19458
+ return {
19459
+ writeHead(statusCode, headers) {
19460
+ Reflect.apply(writeHead, value, [statusCode, headers]);
19461
+ },
19462
+ write(chunk) {
19463
+ return Reflect.apply(write, value, [chunk]) !== false;
19464
+ },
19465
+ end() {
19466
+ Reflect.apply(end, value, []);
19467
+ },
19468
+ destroy() {
19469
+ Reflect.apply(destroy, value, []);
19470
+ },
19471
+ on(event, listener) {
19472
+ Reflect.apply(on, value, [event, listener]);
19473
+ },
19474
+ once(event, listener) {
19475
+ Reflect.apply(once, value, [event, listener]);
19476
+ }
19477
+ };
19478
+ }
19479
+ function toError(value, fallback) {
19480
+ return value instanceof Error ? value : new Error(fallback);
19481
+ }
19482
+ }
19483
+ });
19484
+
19485
+ // node_modules/@signageos/brightsign-decoder/dist/decoder/PlaybackSession.js
19486
+ var require_PlaybackSession = __commonJS({
19487
+ "node_modules/@signageos/brightsign-decoder/dist/decoder/PlaybackSession.js"(exports) {
19488
+ "use strict";
19489
+ Object.defineProperty(exports, "__esModule", { value: true });
19490
+ exports.PlaybackSession = void 0;
19491
+ var bridgesWithErrorListener = /* @__PURE__ */ new WeakSet();
19492
+ var PlaybackSession = class {
19493
+ constructor(bridge) {
19494
+ this.playing = false;
19495
+ this.bridge = bridge;
19496
+ if (this.bridge.onError !== void 0 && !bridgesWithErrorListener.has(this.bridge)) {
19497
+ bridgesWithErrorListener.add(this.bridge);
19498
+ this.bridge.onError((event) => {
19499
+ console.error("BrightSign native stream playback error", event);
19500
+ });
19501
+ }
19502
+ }
19503
+ /** Start native playback at the given URI and coordinates. */
19504
+ async start(uri, coords, options = {}) {
19505
+ if (this.playing) {
19506
+ await this.stop();
19507
+ }
19508
+ this.uri = uri;
19509
+ this.coordinates = coords;
19510
+ await this.bridge.play(uri, coords.x, coords.y, coords.width, coords.height, { protocol: "HTTP", ...options });
19511
+ this.playing = true;
19512
+ }
19513
+ /**
19514
+ * Stop native playback. Idempotent after success.
19515
+ *
19516
+ * If bridge.stop fails, playback state (uri, coordinates, playing flag) is
19517
+ * preserved so a subsequent stop() retries the bridge teardown rather than
19518
+ * silently no-oping with lost context.
19519
+ */
19520
+ async stop() {
19521
+ if (!this.playing || this.uri === void 0 || this.coordinates === void 0) {
19522
+ return;
19523
+ }
19524
+ await this.bridge.stop(this.uri, this.coordinates.x, this.coordinates.y, this.coordinates.width, this.coordinates.height);
19525
+ this.playing = false;
19526
+ this.uri = void 0;
19527
+ this.coordinates = void 0;
19528
+ }
19529
+ /** Whether playback is active. */
19530
+ get isPlaying() {
19531
+ return this.playing;
19532
+ }
19533
+ };
19534
+ exports.PlaybackSession = PlaybackSession;
19535
+ }
19536
+ });
19537
+
19538
+ // node_modules/@signageos/brightsign-decoder/dist/decoder/NativeH264Decoder.js
19539
+ var require_NativeH264Decoder = __commonJS({
19540
+ "node_modules/@signageos/brightsign-decoder/dist/decoder/NativeH264Decoder.js"(exports) {
19541
+ "use strict";
19542
+ Object.defineProperty(exports, "__esModule", { value: true });
19543
+ exports.NativeH264Decoder = void 0;
19544
+ var FrameReferenceRegistry_1 = require_FrameReferenceRegistry();
19545
+ var MpegTsMuxer_1 = require_MpegTsMuxer();
19546
+ var NativeHttpServer_1 = require_NativeHttpServer();
19547
+ var PlaybackSession_1 = require_PlaybackSession();
19548
+ var DEFAULT_MAX_QUEUED_ACCESS_UNITS = 16;
19549
+ var DEFAULT_MAX_QUEUED_BYTES = 8 * 1024 * 1024;
19550
+ var NativeH264Decoder = class {
19551
+ constructor(dependencies) {
19552
+ var _a, _b, _c, _d, _e, _f;
19553
+ this.dependencies = dependencies;
19554
+ this.queuedAtMs = [];
19555
+ this.operationChain = Promise.resolve();
19556
+ this.teardownComplete = false;
19557
+ this.queuedAccessUnits = 0;
19558
+ this.queuedBytes = 0;
19559
+ this.highWaterAccessUnits = 0;
19560
+ this.highWaterBytes = 0;
19561
+ this.admittedAccessUnits = 0;
19562
+ this.completedAccessUnits = 0;
19563
+ this.failedAccessUnits = 0;
19564
+ this.capacityRejections = 0;
19565
+ this.destroyed = false;
19566
+ this.httpServerDestroyed = false;
19567
+ this.playbackStopped = false;
19568
+ this.initialized = false;
19569
+ this.httpServer = (_a = dependencies.httpServer) != null ? _a : new NativeHttpServer_1.NativeHttpServer();
19570
+ this.playback = new PlaybackSession_1.PlaybackSession(dependencies.streamBridge);
19571
+ this.muxer = (_b = dependencies.muxer) != null ? _b : new MpegTsMuxer_1.MpegTsMuxer();
19572
+ this.referenceRegistry = (_c = dependencies.refRegistry) != null ? _c : new FrameReferenceRegistry_1.FrameReferenceRegistry();
19573
+ this.maxQueuedAccessUnits = (_d = dependencies.maxQueuedAccessUnits) != null ? _d : DEFAULT_MAX_QUEUED_ACCESS_UNITS;
19574
+ this.maxQueuedBytes = (_e = dependencies.maxQueuedBytes) != null ? _e : DEFAULT_MAX_QUEUED_BYTES;
19575
+ this.now = (_f = dependencies.now) != null ? _f : Date.now;
19576
+ if (!Number.isSafeInteger(this.maxQueuedAccessUnits) || this.maxQueuedAccessUnits <= 0) {
19577
+ throw new RangeError("maxQueuedAccessUnits must be a positive integer");
19578
+ }
19579
+ if (!Number.isSafeInteger(this.maxQueuedBytes) || this.maxQueuedBytes <= 0) {
19580
+ throw new RangeError("maxQueuedBytes must be a positive integer");
19581
+ }
19582
+ }
19583
+ async initialize(options) {
19584
+ if (this.destroyed) {
19585
+ throw new Error("Decoder has been destroyed");
19586
+ }
19587
+ if (this.initialized) {
19588
+ return;
19589
+ }
19590
+ if (this.initialization === void 0) {
19591
+ validateDecoderOptions(options);
19592
+ this.options = options;
19593
+ this.initialization = this.performInitialization();
19594
+ }
19595
+ await this.initialization;
19596
+ }
19597
+ decodeAndRender(frame, signal) {
19598
+ this.assertReady();
19599
+ try {
19600
+ return this.admitFrame(frame, signal);
19601
+ } catch (error) {
19602
+ return Promise.reject(error);
19603
+ }
19604
+ }
19605
+ async decodeAndRenderRef(reference, signal) {
19606
+ this.assertReady();
19607
+ const frame = this.referenceRegistry.claim(reference);
19608
+ let operation;
19609
+ try {
19610
+ operation = this.admitFrame({
19611
+ data: frame.data,
19612
+ frameType: frame.frameType,
19613
+ timestamp: frame.timestamp
19614
+ }, signal);
19615
+ } catch (error) {
19616
+ this.referenceRegistry.restoreClaim(reference);
19617
+ throw error;
19618
+ }
19619
+ this.referenceRegistry.release(reference);
19620
+ await operation;
19621
+ }
19622
+ async flush(signal) {
19623
+ this.assertReady();
19624
+ await waitForPromise(this.operationChain, signal);
19625
+ if (this.pendingError !== void 0) {
19626
+ const error = this.pendingError;
19627
+ this.pendingError = void 0;
19628
+ throw error;
19629
+ }
19630
+ }
19631
+ getDiagnostics() {
19632
+ const oldest = this.queuedAtMs[0];
19633
+ return {
19634
+ queuedAccessUnits: this.queuedAccessUnits,
19635
+ queuedBytes: this.queuedBytes,
19636
+ highWaterAccessUnits: this.highWaterAccessUnits,
19637
+ highWaterBytes: this.highWaterBytes,
19638
+ oldestQueuedAgeMs: oldest === void 0 ? 0 : Math.max(0, this.now() - oldest),
19639
+ admittedAccessUnits: this.admittedAccessUnits,
19640
+ completedAccessUnits: this.completedAccessUnits,
19641
+ failedAccessUnits: this.failedAccessUnits,
19642
+ capacityRejections: this.capacityRejections,
19643
+ pendingError: this.pendingError !== void 0,
19644
+ httpTransport: this.httpServer.getDiagnostics()
19645
+ };
19646
+ }
19647
+ destroy() {
19648
+ if (this.teardownComplete) {
19649
+ return Promise.resolve();
19650
+ }
19651
+ if (this.teardown !== void 0) {
19652
+ return this.teardown;
19653
+ }
19654
+ this.destroyed = true;
19655
+ const attempt = this.performTeardown();
19656
+ const promise = attempt.then(() => {
19657
+ this.teardownComplete = true;
19658
+ }, (error) => {
19659
+ if (this.teardown === promise) {
19660
+ this.teardown = void 0;
19661
+ }
19662
+ throw error;
19663
+ });
19664
+ this.teardown = promise;
19665
+ return promise;
19666
+ }
19667
+ async performTeardown() {
19668
+ let firstError;
19669
+ if (this.initialization !== void 0) {
19670
+ try {
19671
+ await this.initialization;
19672
+ } catch {
19673
+ }
19674
+ }
19675
+ if (!this.httpServerDestroyed) {
19676
+ try {
19677
+ await this.httpServer.destroy();
19678
+ this.httpServerDestroyed = true;
19679
+ } catch (error) {
19680
+ firstError = firstError != null ? firstError : toError(error, "HTTP transport teardown failed");
19681
+ }
19682
+ }
19683
+ try {
19684
+ await this.operationChain;
19685
+ } catch (error) {
19686
+ firstError = firstError != null ? firstError : toError(error, "Decoder queue teardown failed");
19687
+ }
19688
+ if (!this.playbackStopped) {
19689
+ try {
19690
+ await this.playback.stop();
19691
+ this.playbackStopped = true;
19692
+ } catch (error) {
19693
+ firstError = firstError != null ? firstError : toError(error, "Native playback teardown failed");
19694
+ }
19695
+ }
19696
+ this.initialized = false;
19697
+ if (firstError !== void 0) {
19698
+ throw firstError;
19699
+ }
19700
+ }
19701
+ async performInitialization() {
19702
+ var _a, _b;
19703
+ try {
19704
+ const options = this.options;
19705
+ if (options === void 0) {
19706
+ throw new Error("Decoder options are unavailable");
19707
+ }
19708
+ await this.httpServer.start(this.dependencies.httpModule);
19709
+ if (this.destroyed) {
19710
+ throw new Error("Decoder was destroyed during initialization");
19711
+ }
19712
+ await this.playback.start(this.httpServer.uri, {
19713
+ x: (_a = options.x) != null ? _a : 0,
19714
+ y: (_b = options.y) != null ? _b : 0,
19715
+ width: options.width,
19716
+ height: options.height
19717
+ }, options.streamOptions);
19718
+ if (this.destroyed) {
19719
+ throw new Error("Decoder was destroyed during initialization");
19720
+ }
19721
+ this.initialized = true;
19722
+ } catch (error) {
19723
+ let result = toError(error, "Decoder initialization failed");
19724
+ try {
19725
+ await this.httpServer.destroy();
19726
+ this.httpServerDestroyed = true;
19727
+ } catch (cleanupError) {
19728
+ result = new Error(`${result.message}; HTTP cleanup failed: ${toError(cleanupError, "unknown error").message}`);
19729
+ }
19730
+ try {
19731
+ await this.playback.stop();
19732
+ this.playbackStopped = true;
19733
+ } catch (cleanupError) {
19734
+ result = new Error(`${result.message}; playback cleanup failed: ${toError(cleanupError, "unknown error").message}`);
19735
+ }
19736
+ throw result;
19737
+ }
19738
+ }
19739
+ assertReady() {
19740
+ if (this.destroyed) {
19741
+ throw new Error("Decoder has been destroyed");
19742
+ }
19743
+ if (!this.initialized) {
19744
+ throw new Error("Decoder is not initialized");
19745
+ }
19746
+ }
19747
+ /**
19748
+ * Validate and synchronously copy a frame into the bounded queue. Once this
19749
+ * method returns, decoder ownership has transferred even if the returned wait
19750
+ * later rejects because transport failed or the caller aborted its wait.
19751
+ */
19752
+ admitFrame(frame, signal) {
19753
+ if ((signal == null ? void 0 : signal.aborted) === true) {
19754
+ throw abortError();
19755
+ }
19756
+ if (frame.data.byteLength === 0) {
19757
+ throw new RangeError("Cannot decode an empty access unit");
19758
+ }
19759
+ if (this.queuedAccessUnits >= this.maxQueuedAccessUnits || this.queuedBytes + frame.data.byteLength > this.maxQueuedBytes) {
19760
+ this.capacityRejections += 1;
19761
+ throw new Error("Decoder remux queue capacity exceeded");
19762
+ }
19763
+ const ownedData = frame.data.slice();
19764
+ const ownedTimestamp = { hi: frame.timestamp.hi, lo: frame.timestamp.lo };
19765
+ this.queuedAccessUnits += 1;
19766
+ this.queuedBytes += ownedData.byteLength;
19767
+ this.admittedAccessUnits += 1;
19768
+ this.highWaterAccessUnits = Math.max(this.highWaterAccessUnits, this.queuedAccessUnits);
19769
+ this.highWaterBytes = Math.max(this.highWaterBytes, this.queuedBytes);
19770
+ this.queuedAtMs.push(this.now());
19771
+ const operation = this.operationChain.then(async () => {
19772
+ const prepared = this.muxer.prepare(ownedData, ownedTimestamp);
19773
+ try {
19774
+ await this.httpServer.writeAccessUnit(prepared.packets);
19775
+ prepared.commit();
19776
+ } catch (error) {
19777
+ if (error instanceof NativeHttpServer_1.NativeHttpPreWriteError) {
19778
+ prepared.rejectBeforeWrite();
19779
+ } else {
19780
+ prepared.commit();
19781
+ }
19782
+ throw error;
19783
+ }
19784
+ });
19785
+ this.operationChain = operation.then(() => {
19786
+ this.completedAccessUnits += 1;
19787
+ this.releaseQueueCapacity(ownedData.byteLength);
19788
+ }, (error) => {
19789
+ this.failedAccessUnits += 1;
19790
+ this.releaseQueueCapacity(ownedData.byteLength);
19791
+ const normalized = toError(error, "Native decoder operation failed");
19792
+ if (this.pendingError === void 0) {
19793
+ this.pendingError = normalized;
19794
+ }
19795
+ });
19796
+ return waitForPromise(operation, signal);
19797
+ }
19798
+ releaseQueueCapacity(byteLength) {
19799
+ this.queuedAtMs.shift();
19800
+ this.queuedAccessUnits -= 1;
19801
+ this.queuedBytes -= byteLength;
19802
+ }
19803
+ };
19804
+ exports.NativeH264Decoder = NativeH264Decoder;
19805
+ function validateDecoderOptions(options) {
19806
+ if (!Number.isFinite(options.width) || options.width <= 0 || !Number.isFinite(options.height) || options.height <= 0) {
19807
+ throw new RangeError("Decoder width and height must be finite positive numbers");
19808
+ }
19809
+ if (options.x !== void 0 && !Number.isFinite(options.x)) {
19810
+ throw new RangeError("Decoder x coordinate must be finite");
19811
+ }
19812
+ if (options.y !== void 0 && !Number.isFinite(options.y)) {
19813
+ throw new RangeError("Decoder y coordinate must be finite");
19814
+ }
19815
+ }
19816
+ function waitForPromise(promise, signal) {
19817
+ if (signal === void 0) {
19818
+ return promise;
19819
+ }
19820
+ if (signal.aborted) {
19821
+ return Promise.reject(abortError());
19822
+ }
19823
+ return new Promise((resolve, reject) => {
19824
+ let settled = false;
19825
+ const finish = (error) => {
19826
+ if (settled) {
19827
+ return;
19828
+ }
19829
+ settled = true;
19830
+ signal.removeEventListener("abort", onAbort);
19831
+ if (error === void 0) {
19832
+ resolve();
19833
+ } else {
19834
+ reject(error);
19835
+ }
19836
+ };
19837
+ const onAbort = () => finish(abortError());
19838
+ signal.addEventListener("abort", onAbort, { once: true });
19839
+ promise.then(() => finish(), (error) => finish(toError(error, "Flush failed")));
19840
+ });
19841
+ }
19842
+ function abortError() {
19843
+ const error = new Error("The operation was aborted");
19844
+ error.name = "AbortError";
19845
+ return error;
19846
+ }
19847
+ function toError(value, fallback) {
19848
+ return value instanceof Error ? value : new Error(fallback);
19849
+ }
19850
+ }
19851
+ });
19852
+
19853
+ // node_modules/@signageos/brightsign-decoder/dist/decoder/WebCodecsH264Decoder.js
19854
+ var require_WebCodecsH264Decoder = __commonJS({
19855
+ "node_modules/@signageos/brightsign-decoder/dist/decoder/WebCodecsH264Decoder.js"(exports) {
19856
+ "use strict";
19857
+ Object.defineProperty(exports, "__esModule", { value: true });
19858
+ exports.WebCodecsH264Decoder = void 0;
19859
+ var WebCodecsH264Decoder = class {
19860
+ async initialize(_options) {
19861
+ throw new Error("WebCodecs H.264 decoder is not yet implemented. Measured 40.2 ms median decode latency missed the performance target.");
19862
+ }
19863
+ async decodeAndRender(_frame, _signal) {
19864
+ throw new Error("WebCodecs decoder is not initialized");
19865
+ }
19866
+ async decodeAndRenderRef(_reference, _signal) {
19867
+ throw new Error("WebCodecs decoder is not initialized");
19868
+ }
19869
+ async flush(_signal) {
19870
+ }
19871
+ async destroy() {
19872
+ }
19873
+ };
19874
+ exports.WebCodecsH264Decoder = WebCodecsH264Decoder;
19875
+ }
19876
+ });
19877
+
19878
+ // node_modules/@signageos/brightsign-decoder/dist/runtime/support.js
19879
+ var require_support = __commonJS({
19880
+ "node_modules/@signageos/brightsign-decoder/dist/runtime/support.js"(exports) {
19881
+ "use strict";
19882
+ Object.defineProperty(exports, "__esModule", { value: true });
19883
+ exports.detectCapabilities = detectCapabilities;
19884
+ exports.isBrightSignDecoderSupported = isBrightSignDecoderSupported2;
19885
+ function detectCapabilities() {
19886
+ const hasNativeNode = probeParentNode();
19887
+ const hasStreamBridge = probeStreamBridge();
19888
+ const native = hasNativeNode && hasStreamBridge;
19889
+ const reasons = [];
19890
+ if (!hasNativeNode) {
19891
+ reasons.push("no parent-realm Node http module");
19892
+ }
19893
+ if (!hasStreamBridge) {
19894
+ reasons.push("no signageOS stream bridge");
19895
+ }
19896
+ if (native) {
19897
+ reasons.push("native player available");
19898
+ }
19899
+ return {
19900
+ native,
19901
+ webcodecs: false,
19902
+ reason: reasons.join("; ") || "unsupported runtime"
19903
+ };
19904
+ }
19905
+ function safeGet(target, key) {
19906
+ try {
19907
+ if (typeof target !== "object" || target === null) {
19908
+ return void 0;
19909
+ }
19910
+ return Reflect.get(target, key);
19911
+ } catch {
19912
+ return void 0;
19913
+ }
19914
+ }
19915
+ function probeParentNode() {
19916
+ try {
19917
+ if (typeof globalThis === "undefined") {
19918
+ return false;
19919
+ }
19920
+ const parentWindow = safeGet(globalThis, "parent");
19921
+ if (parentWindow === void 0 || parentWindow === null) {
19922
+ return false;
19923
+ }
19924
+ const parentRequire = safeGet(parentWindow, "require");
19925
+ if (typeof parentRequire !== "function") {
19926
+ return false;
19927
+ }
19928
+ const http = Reflect.apply(parentRequire, parentWindow, ["http"]);
19929
+ if (typeof http !== "object" || http === null) {
19930
+ return false;
19931
+ }
19932
+ return typeof Reflect.get(http, "createServer") === "function";
19933
+ } catch {
19934
+ return false;
19935
+ }
19936
+ }
19937
+ function probeStreamBridge() {
19938
+ try {
19939
+ if (typeof globalThis === "undefined") {
19940
+ return false;
19941
+ }
19942
+ const sos = safeGet(globalThis, "sos");
19943
+ if (typeof sos !== "object" || sos === null) {
19944
+ return false;
19945
+ }
19946
+ const stream = Reflect.get(sos, "stream");
19947
+ if (typeof stream !== "object" || stream === null) {
19948
+ return false;
19949
+ }
19950
+ return typeof Reflect.get(stream, "play") === "function" && typeof Reflect.get(stream, "stop") === "function";
19951
+ } catch {
19952
+ return false;
19953
+ }
19954
+ }
19955
+ function isBrightSignDecoderSupported2() {
19956
+ const caps = detectCapabilities();
19957
+ return caps.native;
19958
+ }
19959
+ }
19960
+ });
19961
+
19962
+ // node_modules/@signageos/brightsign-decoder/dist/runtime/parentNode.js
19963
+ var require_parentNode = __commonJS({
19964
+ "node_modules/@signageos/brightsign-decoder/dist/runtime/parentNode.js"(exports) {
19965
+ "use strict";
19966
+ Object.defineProperty(exports, "__esModule", { value: true });
19967
+ exports.discoverParentRequire = discoverParentRequire;
19968
+ exports.validateNetModule = validateNetModule;
19969
+ exports.validateHttpModule = validateHttpModule;
19970
+ function safeGet(target, key) {
19971
+ try {
19972
+ if (typeof target !== "object" || target === null) {
19973
+ return void 0;
19974
+ }
19975
+ return Reflect.get(target, key);
19976
+ } catch {
19977
+ return void 0;
19978
+ }
19979
+ }
19980
+ function wrapRequire(fn, receiver) {
19981
+ return (moduleName) => {
19982
+ if (typeof fn !== "function") {
19983
+ return void 0;
19984
+ }
19985
+ return Reflect.apply(fn, receiver, [moduleName]);
19986
+ };
19987
+ }
19988
+ function discoverParentRequire() {
19989
+ if (typeof globalThis === "undefined") {
19990
+ return void 0;
19991
+ }
19992
+ const parentWindow = safeGet(globalThis, "parent");
19993
+ if (parentWindow !== void 0 && parentWindow !== null) {
19994
+ const parentRequire = safeGet(parentWindow, "require");
19995
+ if (typeof parentRequire === "function") {
19996
+ return wrapRequire(parentRequire, parentWindow);
19997
+ }
19998
+ }
19999
+ const topWindow = safeGet(globalThis, "top");
20000
+ if (topWindow !== void 0 && topWindow !== null && topWindow !== parentWindow) {
20001
+ const topRequire = safeGet(topWindow, "require");
20002
+ if (typeof topRequire === "function") {
20003
+ return wrapRequire(topRequire, topWindow);
20004
+ }
20005
+ }
20006
+ return void 0;
20007
+ }
20008
+ function validateNetModule(mod) {
20009
+ if (typeof mod !== "object" || mod === null) {
20010
+ return false;
20011
+ }
20012
+ const cc = Reflect.get(mod, "createConnection");
20013
+ return typeof cc === "function";
20014
+ }
20015
+ function validateHttpModule(mod) {
20016
+ if (typeof mod !== "object" || mod === null) {
20017
+ return false;
20018
+ }
20019
+ const cs = Reflect.get(mod, "createServer");
20020
+ return typeof cs === "function";
20021
+ }
20022
+ }
20023
+ });
20024
+
20025
+ // node_modules/@signageos/brightsign-decoder/dist/index.js
20026
+ var require_dist = __commonJS({
20027
+ "node_modules/@signageos/brightsign-decoder/dist/index.js"(exports) {
20028
+ "use strict";
20029
+ Object.defineProperty(exports, "__esModule", { value: true });
20030
+ exports.validateHttpModule = exports.validateNetModule = exports.discoverParentRequire = exports.detectCapabilities = exports.isBrightSignDecoderSupported = exports.NativeHttpServer = exports.PlaybackSession = exports.WebCodecsH264Decoder = exports.NativeH264Decoder = exports.parseNalUnits = exports.NalType = exports.inspectAccessUnit = exports.getNalType = exports.findStartCodes = exports.u64Sub = exports.u64ToBigInt = exports.TransportClock = exports.verifyCrc32 = exports.computeCrc32 = exports.MpegTsMuxer = exports.TCP = exports.ConnectionRegistry = exports.FrameReferenceRegistry = exports.FrameCollector = exports.PacketParser = exports.FrameType = exports.ConnectionState = void 0;
20031
+ exports.createBrightSignDecoder = createBrightSignDecoder2;
20032
+ exports.createBrightSignTCP = createBrightSignTCP2;
20033
+ var contracts_1 = require_contracts();
20034
+ Object.defineProperty(exports, "ConnectionState", { enumerable: true, get: function() {
20035
+ return contracts_1.ConnectionState;
20036
+ } });
20037
+ Object.defineProperty(exports, "FrameType", { enumerable: true, get: function() {
20038
+ return contracts_1.FrameType;
20039
+ } });
20040
+ var PacketParser_1 = require_PacketParser();
20041
+ Object.defineProperty(exports, "PacketParser", { enumerable: true, get: function() {
20042
+ return PacketParser_1.PacketParser;
20043
+ } });
20044
+ var FrameCollector_1 = require_FrameCollector();
20045
+ Object.defineProperty(exports, "FrameCollector", { enumerable: true, get: function() {
20046
+ return FrameCollector_1.FrameCollector;
20047
+ } });
20048
+ var FrameReferenceRegistry_1 = require_FrameReferenceRegistry();
20049
+ Object.defineProperty(exports, "FrameReferenceRegistry", { enumerable: true, get: function() {
20050
+ return FrameReferenceRegistry_1.FrameReferenceRegistry;
20051
+ } });
20052
+ var ConnectionRegistry_1 = require_ConnectionRegistry();
20053
+ Object.defineProperty(exports, "ConnectionRegistry", { enumerable: true, get: function() {
20054
+ return ConnectionRegistry_1.ConnectionRegistry;
20055
+ } });
20056
+ var TCP_1 = require_TCP();
20057
+ Object.defineProperty(exports, "TCP", { enumerable: true, get: function() {
20058
+ return TCP_1.TCP;
20059
+ } });
20060
+ var MpegTsMuxer_1 = require_MpegTsMuxer();
20061
+ Object.defineProperty(exports, "MpegTsMuxer", { enumerable: true, get: function() {
20062
+ return MpegTsMuxer_1.MpegTsMuxer;
20063
+ } });
20064
+ Object.defineProperty(exports, "computeCrc32", { enumerable: true, get: function() {
20065
+ return MpegTsMuxer_1.computeCrc32;
20066
+ } });
20067
+ Object.defineProperty(exports, "verifyCrc32", { enumerable: true, get: function() {
20068
+ return MpegTsMuxer_1.verifyCrc32;
20069
+ } });
20070
+ var TransportClock_1 = require_TransportClock();
20071
+ Object.defineProperty(exports, "TransportClock", { enumerable: true, get: function() {
20072
+ return TransportClock_1.TransportClock;
20073
+ } });
20074
+ Object.defineProperty(exports, "u64ToBigInt", { enumerable: true, get: function() {
20075
+ return TransportClock_1.u64ToBigInt;
20076
+ } });
20077
+ Object.defineProperty(exports, "u64Sub", { enumerable: true, get: function() {
20078
+ return TransportClock_1.u64Sub;
20079
+ } });
20080
+ var AnnexB_1 = require_AnnexB();
20081
+ Object.defineProperty(exports, "findStartCodes", { enumerable: true, get: function() {
20082
+ return AnnexB_1.findStartCodes;
20083
+ } });
20084
+ Object.defineProperty(exports, "getNalType", { enumerable: true, get: function() {
20085
+ return AnnexB_1.getNalType;
20086
+ } });
20087
+ Object.defineProperty(exports, "inspectAccessUnit", { enumerable: true, get: function() {
20088
+ return AnnexB_1.inspectAccessUnit;
20089
+ } });
20090
+ Object.defineProperty(exports, "NalType", { enumerable: true, get: function() {
20091
+ return AnnexB_1.NalType;
20092
+ } });
20093
+ Object.defineProperty(exports, "parseNalUnits", { enumerable: true, get: function() {
20094
+ return AnnexB_1.parseNalUnits;
20095
+ } });
20096
+ var NativeH264Decoder_1 = require_NativeH264Decoder();
20097
+ Object.defineProperty(exports, "NativeH264Decoder", { enumerable: true, get: function() {
20098
+ return NativeH264Decoder_1.NativeH264Decoder;
20099
+ } });
20100
+ var WebCodecsH264Decoder_1 = require_WebCodecsH264Decoder();
20101
+ Object.defineProperty(exports, "WebCodecsH264Decoder", { enumerable: true, get: function() {
20102
+ return WebCodecsH264Decoder_1.WebCodecsH264Decoder;
20103
+ } });
20104
+ var PlaybackSession_1 = require_PlaybackSession();
20105
+ Object.defineProperty(exports, "PlaybackSession", { enumerable: true, get: function() {
20106
+ return PlaybackSession_1.PlaybackSession;
20107
+ } });
20108
+ var NativeHttpServer_1 = require_NativeHttpServer();
20109
+ Object.defineProperty(exports, "NativeHttpServer", { enumerable: true, get: function() {
20110
+ return NativeHttpServer_1.NativeHttpServer;
20111
+ } });
20112
+ var support_1 = require_support();
20113
+ Object.defineProperty(exports, "isBrightSignDecoderSupported", { enumerable: true, get: function() {
20114
+ return support_1.isBrightSignDecoderSupported;
20115
+ } });
20116
+ Object.defineProperty(exports, "detectCapabilities", { enumerable: true, get: function() {
20117
+ return support_1.detectCapabilities;
20118
+ } });
20119
+ var parentNode_1 = require_parentNode();
20120
+ Object.defineProperty(exports, "discoverParentRequire", { enumerable: true, get: function() {
20121
+ return parentNode_1.discoverParentRequire;
20122
+ } });
20123
+ Object.defineProperty(exports, "validateNetModule", { enumerable: true, get: function() {
20124
+ return parentNode_1.validateNetModule;
20125
+ } });
20126
+ Object.defineProperty(exports, "validateHttpModule", { enumerable: true, get: function() {
20127
+ return parentNode_1.validateHttpModule;
20128
+ } });
20129
+ var parentNode_2 = require_parentNode();
20130
+ var NativeH264Decoder_2 = require_NativeH264Decoder();
20131
+ var TCP_2 = require_TCP();
20132
+ var FrameReferenceRegistry_2 = require_FrameReferenceRegistry();
20133
+ var discoveredStreamBridges = /* @__PURE__ */ new WeakMap();
20134
+ function createBrightSignDecoder2(deps) {
20135
+ var _a;
20136
+ const resolved = deps != null ? deps : {};
20137
+ let httpModule = resolved.httpModule;
20138
+ let streamBridge = resolved.streamBridge;
20139
+ const refRegistry = (_a = resolved.refRegistry) != null ? _a : new FrameReferenceRegistry_2.FrameReferenceRegistry();
20140
+ if (httpModule === void 0) {
20141
+ const parentRequire = (0, parentNode_2.discoverParentRequire)();
20142
+ if (parentRequire !== void 0) {
20143
+ const http = parentRequire("http");
20144
+ if ((0, parentNode_2.validateHttpModule)(http) && typeof http === "object" && http !== null) {
20145
+ const createServer = Reflect.get(http, "createServer");
20146
+ if (typeof createServer === "function") {
20147
+ httpModule = {
20148
+ createServer(handler) {
20149
+ return Reflect.apply(createServer, http, [handler]);
20150
+ }
20151
+ };
20152
+ }
20153
+ }
20154
+ }
20155
+ }
20156
+ if (httpModule === void 0) {
20157
+ throw new Error("No http module available \u2014 provide httpModule or ensure parent-realm Node is accessible");
20158
+ }
20159
+ if (streamBridge === void 0) {
20160
+ streamBridge = discoverStreamBridge();
20161
+ }
20162
+ if (streamBridge === void 0) {
20163
+ throw new Error("No stream bridge available \u2014 provide streamBridge or ensure sos.stream is accessible");
20164
+ }
20165
+ const fullDeps = {
20166
+ httpModule,
20167
+ streamBridge,
20168
+ refRegistry
20169
+ };
20170
+ return new NativeH264Decoder_2.NativeH264Decoder(fullDeps);
20171
+ }
20172
+ function createBrightSignTCP2(options) {
20173
+ const resolved = options != null ? options : {};
20174
+ let net = resolved.net;
20175
+ if (net === void 0) {
20176
+ const parentRequire = (0, parentNode_2.discoverParentRequire)();
20177
+ if (parentRequire !== void 0) {
20178
+ const netMod = parentRequire("net");
20179
+ if ((0, parentNode_2.validateNetModule)(netMod) && typeof netMod === "object" && netMod !== null) {
20180
+ const createConnection = Reflect.get(netMod, "createConnection");
20181
+ if (typeof createConnection === "function") {
20182
+ net = {
20183
+ createConnection(connOpts, callback) {
20184
+ return (0, TCP_2.narrowSocketLike)(Reflect.apply(createConnection, netMod, [connOpts, callback]));
20185
+ }
20186
+ };
20187
+ }
20188
+ }
20189
+ }
20190
+ }
20191
+ if (net === void 0) {
20192
+ throw new Error("No net module available \u2014 provide net or ensure parent-realm Node is accessible");
20193
+ }
20194
+ const tcpOptions = {
20195
+ net,
20196
+ maxPacketSize: resolved.maxPacketSize,
20197
+ maxQueuedBytes: resolved.maxQueuedBytes,
20198
+ maxQueuedPackets: resolved.maxQueuedPackets,
20199
+ referenceRegistry: resolved.refRegistry
20200
+ };
20201
+ return new TCP_2.TCP(tcpOptions);
20202
+ }
20203
+ function discoverStreamBridge() {
20204
+ try {
20205
+ if (typeof globalThis === "undefined") {
20206
+ return void 0;
20207
+ }
20208
+ const sos = Reflect.get(globalThis, "sos");
20209
+ if (typeof sos !== "object" || sos === null) {
20210
+ return void 0;
20211
+ }
20212
+ const stream = Reflect.get(sos, "stream");
20213
+ if (typeof stream !== "object" || stream === null) {
20214
+ return void 0;
20215
+ }
20216
+ const cachedBridge = discoveredStreamBridges.get(stream);
20217
+ if (cachedBridge !== void 0) {
20218
+ return cachedBridge;
20219
+ }
20220
+ const play = Reflect.get(stream, "play");
20221
+ const stop = Reflect.get(stream, "stop");
20222
+ const onError = Reflect.get(stream, "onError");
20223
+ if (typeof play !== "function" || typeof stop !== "function") {
20224
+ return void 0;
20225
+ }
20226
+ const bridge = {
20227
+ play(uri, x, y, width, height, opts) {
20228
+ return Promise.resolve(Reflect.apply(play, stream, [uri, x, y, width, height, opts]));
20229
+ },
20230
+ stop(uri, x, y, width, height) {
20231
+ return Promise.resolve(Reflect.apply(stop, stream, [uri, x, y, width, height]));
20232
+ }
20233
+ };
20234
+ if (typeof onError !== "function") {
20235
+ discoveredStreamBridges.set(stream, bridge);
20236
+ return bridge;
20237
+ }
20238
+ const bridgeWithErrorListener = {
20239
+ ...bridge,
20240
+ onError(listener) {
20241
+ Reflect.apply(onError, stream, [listener]);
20242
+ }
20243
+ };
20244
+ discoveredStreamBridges.set(stream, bridgeWithErrorListener);
20245
+ return bridgeWithErrorListener;
20246
+ } catch {
20247
+ return void 0;
20248
+ }
20249
+ }
20250
+ }
20251
+ });
20252
+
16833
20253
  // node_modules/@signageos/nacl-decoder/dist/NaClDecoder/messageListeners.js
16834
20254
  var require_messageListeners = __commonJS({
16835
20255
  "node_modules/@signageos/nacl-decoder/dist/NaClDecoder/messageListeners.js"(exports) {
@@ -17206,6 +20626,37 @@
17206
20626
  }
17207
20627
  });
17208
20628
 
20629
+ // node_modules/@signageos/nacl-decoder/dist/NaClDecoder/geometry.js
20630
+ var require_geometry = __commonJS({
20631
+ "node_modules/@signageos/nacl-decoder/dist/NaClDecoder/geometry.js"(exports) {
20632
+ "use strict";
20633
+ var __assign = exports && exports.__assign || function() {
20634
+ __assign = Object.assign || function(t) {
20635
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
20636
+ s = arguments[i];
20637
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
20638
+ t[p] = s[p];
20639
+ }
20640
+ return t;
20641
+ };
20642
+ return __assign.apply(this, arguments);
20643
+ };
20644
+ Object.defineProperty(exports, "__esModule", { value: true });
20645
+ exports.normalizeGeometry = normalizeGeometry2;
20646
+ function normalizeGeometry2(geometry) {
20647
+ if (!Number.isFinite(geometry.x) || !Number.isFinite(geometry.y) || !Number.isFinite(geometry.width) || !Number.isFinite(geometry.height)) {
20648
+ throw new RangeError("NaCl module geometry values must be finite.");
20649
+ }
20650
+ var width = Math.floor(geometry.width);
20651
+ var height = Math.floor(geometry.height);
20652
+ if (width <= 0 || height <= 0) {
20653
+ throw new RangeError("NaCl module geometry width and height must be positive.");
20654
+ }
20655
+ return __assign(__assign({}, geometry), { width, height });
20656
+ }
20657
+ }
20658
+ });
20659
+
17209
20660
  // node_modules/@signageos/nacl-decoder/dist/NaClDecoder/module.js
17210
20661
  var require_module = __commonJS({
17211
20662
  "node_modules/@signageos/nacl-decoder/dist/NaClDecoder/module.js"(exports) {
@@ -17213,14 +20664,17 @@
17213
20664
  Object.defineProperty(exports, "__esModule", { value: true });
17214
20665
  exports.createNaClModule = createNaClModule;
17215
20666
  exports.removeNaClModule = removeNaClModule;
20667
+ var geometry_1 = require_geometry();
17216
20668
  function handleLoad(event) {
17217
20669
  console.log("nacl load", event);
17218
20670
  }
17219
20671
  function handleCrash(event) {
17220
20672
  console.log("nacl crash", event);
17221
20673
  }
17222
- function createNaClModule(handleMessage) {
17223
- var _a, _b;
20674
+ var messageListeners = /* @__PURE__ */ new WeakMap();
20675
+ function createNaClModule(handleMessage, geometry) {
20676
+ var _a, _b, _c, _d;
20677
+ var normalizedGeometry = geometry ? (0, geometry_1.normalizeGeometry)(geometry) : void 0;
17224
20678
  var listenerEl = document.createElement("div");
17225
20679
  listenerEl.setAttribute("id", "listener");
17226
20680
  listenerEl.addEventListener("message", handleMessage, true);
@@ -17230,22 +20684,34 @@
17230
20684
  var baseHref = (_b = (_a = document.getElementsByTagName("base")[0]) === null || _a === void 0 ? void 0 : _a.href) !== null && _b !== void 0 ? _b : location.href;
17231
20685
  var nmpPath = new URL("nacl-decoder.nmf", baseHref).href;
17232
20686
  var naclModuleEl = document.createElement("embed");
17233
- naclModuleEl.setAttribute("width", "".concat(window.screen.width));
17234
- naclModuleEl.setAttribute("height", "".concat(window.screen.height));
20687
+ var width = (_c = normalizedGeometry === null || normalizedGeometry === void 0 ? void 0 : normalizedGeometry.width) !== null && _c !== void 0 ? _c : window.screen.width;
20688
+ var height = (_d = normalizedGeometry === null || normalizedGeometry === void 0 ? void 0 : normalizedGeometry.height) !== null && _d !== void 0 ? _d : window.screen.height;
20689
+ naclModuleEl.setAttribute("width", "".concat(width));
20690
+ naclModuleEl.setAttribute("height", "".concat(height));
20691
+ if (normalizedGeometry) {
20692
+ naclModuleEl.style.position = "absolute";
20693
+ naclModuleEl.style.left = "".concat(normalizedGeometry.x, "px");
20694
+ naclModuleEl.style.top = "".concat(normalizedGeometry.y, "px");
20695
+ }
17235
20696
  naclModuleEl.setAttribute("src", nmpPath);
17236
20697
  naclModuleEl.setAttribute("type", "application/x-nacl");
17237
20698
  naclModuleEl.setAttribute("id", "nacl_module");
17238
20699
  listenerEl.appendChild(naclModuleEl);
20700
+ messageListeners.set(naclModuleEl, handleMessage);
17239
20701
  return naclModuleEl;
17240
20702
  }
17241
20703
  function removeNaClModule(naclModuleEl) {
17242
20704
  var listenerEl = naclModuleEl.parentElement;
17243
20705
  if (listenerEl) {
17244
- listenerEl.removeEventListener("message", handleLoad, true);
20706
+ var handleMessage = messageListeners.get(naclModuleEl);
20707
+ if (handleMessage) {
20708
+ listenerEl.removeEventListener("message", handleMessage, true);
20709
+ }
17245
20710
  listenerEl.removeEventListener("load", handleLoad, true);
17246
20711
  listenerEl.removeEventListener("crash", handleCrash, true);
17247
20712
  listenerEl.remove();
17248
20713
  }
20714
+ messageListeners.delete(naclModuleEl);
17249
20715
  naclModuleEl.remove();
17250
20716
  }
17251
20717
  }
@@ -17969,14 +21435,17 @@
17969
21435
  var NaClDecoder = (
17970
21436
  /** @class */
17971
21437
  function() {
17972
- function NaClDecoder2(messageSender, naclModuleEl) {
21438
+ function NaClDecoder2(messageSender, naclModuleEl, onDestroy) {
17973
21439
  this.messageSender = messageSender;
17974
21440
  this.naclModuleEl = naclModuleEl;
21441
+ this.onDestroy = onDestroy;
17975
21442
  }
17976
21443
  NaClDecoder2.prototype.destroy = function() {
17977
21444
  return __awaiter(this, void 0, void 0, function() {
17978
- return __generator(this, function(_a) {
21445
+ var _a;
21446
+ return __generator(this, function(_b) {
17979
21447
  (0, module_1.removeNaClModule)(this.naclModuleEl);
21448
+ (_a = this.onDestroy) === null || _a === void 0 ? void 0 : _a.call(this);
17980
21449
  return [
17981
21450
  2
17982
21451
  /*return*/
@@ -18262,9 +21731,28 @@
18262
21731
  });
18263
21732
 
18264
21733
  // node_modules/@signageos/nacl-decoder/dist/index.js
18265
- var require_dist = __commonJS({
21734
+ var require_dist2 = __commonJS({
18266
21735
  "node_modules/@signageos/nacl-decoder/dist/index.js"(exports) {
18267
21736
  "use strict";
21737
+ var __extends = exports && exports.__extends || /* @__PURE__ */ function() {
21738
+ var extendStatics = function(d, b) {
21739
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
21740
+ d2.__proto__ = b2;
21741
+ } || function(d2, b2) {
21742
+ for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
21743
+ };
21744
+ return extendStatics(d, b);
21745
+ };
21746
+ return function(d, b) {
21747
+ if (typeof b !== "function" && b !== null)
21748
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
21749
+ extendStatics(d, b);
21750
+ function __() {
21751
+ this.constructor = d;
21752
+ }
21753
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21754
+ };
21755
+ }();
18268
21756
  var __assign = exports && exports.__assign || function() {
18269
21757
  __assign = Object.assign || function(t) {
18270
21758
  for (var s, i = 1, n = arguments.length; i < n; i++) {
@@ -18276,6 +21764,102 @@
18276
21764
  };
18277
21765
  return __assign.apply(this, arguments);
18278
21766
  };
21767
+ var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
21768
+ function adopt(value) {
21769
+ return value instanceof P ? value : new P(function(resolve) {
21770
+ resolve(value);
21771
+ });
21772
+ }
21773
+ return new (P || (P = Promise))(function(resolve, reject) {
21774
+ function fulfilled(value) {
21775
+ try {
21776
+ step(generator.next(value));
21777
+ } catch (e) {
21778
+ reject(e);
21779
+ }
21780
+ }
21781
+ function rejected(value) {
21782
+ try {
21783
+ step(generator["throw"](value));
21784
+ } catch (e) {
21785
+ reject(e);
21786
+ }
21787
+ }
21788
+ function step(result) {
21789
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
21790
+ }
21791
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
21792
+ });
21793
+ };
21794
+ var __generator = exports && exports.__generator || function(thisArg, body) {
21795
+ var _ = { label: 0, sent: function() {
21796
+ if (t[0] & 1) throw t[1];
21797
+ return t[1];
21798
+ }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
21799
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
21800
+ return this;
21801
+ }), g;
21802
+ function verb(n) {
21803
+ return function(v) {
21804
+ return step([n, v]);
21805
+ };
21806
+ }
21807
+ function step(op) {
21808
+ if (f) throw new TypeError("Generator is already executing.");
21809
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
21810
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
21811
+ if (y = 0, t) op = [op[0] & 2, t.value];
21812
+ switch (op[0]) {
21813
+ case 0:
21814
+ case 1:
21815
+ t = op;
21816
+ break;
21817
+ case 4:
21818
+ _.label++;
21819
+ return { value: op[1], done: false };
21820
+ case 5:
21821
+ _.label++;
21822
+ y = op[1];
21823
+ op = [0];
21824
+ continue;
21825
+ case 7:
21826
+ op = _.ops.pop();
21827
+ _.trys.pop();
21828
+ continue;
21829
+ default:
21830
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
21831
+ _ = 0;
21832
+ continue;
21833
+ }
21834
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
21835
+ _.label = op[1];
21836
+ break;
21837
+ }
21838
+ if (op[0] === 6 && _.label < t[1]) {
21839
+ _.label = t[1];
21840
+ t = op;
21841
+ break;
21842
+ }
21843
+ if (t && _.label < t[2]) {
21844
+ _.label = t[2];
21845
+ _.ops.push(op);
21846
+ break;
21847
+ }
21848
+ if (t[2]) _.ops.pop();
21849
+ _.trys.pop();
21850
+ continue;
21851
+ }
21852
+ op = body.call(thisArg, _);
21853
+ } catch (e) {
21854
+ op = [6, e];
21855
+ y = 0;
21856
+ } finally {
21857
+ f = t = 0;
21858
+ }
21859
+ if (op[0] & 5) throw op[1];
21860
+ return { value: op[0] ? op[1] : void 0, done: true };
21861
+ }
21862
+ };
18279
21863
  Object.defineProperty(exports, "__esModule", { value: true });
18280
21864
  exports.NaClTCPStreamConnection = exports.NaClTCPStream = exports.NaClTCPPacketConnection = exports.NaClTCPPacket = exports.NaClFrameCollector = exports.VideoProfile = exports.ResultStatus = exports.HWAcceleration = exports.NaClDecoder = void 0;
18281
21865
  exports.isNaClSupported = isNaClSupported3;
@@ -18318,6 +21902,29 @@
18318
21902
  var DEFAULT_OPTIONS = {
18319
21903
  timeoutMs: 1e3
18320
21904
  };
21905
+ var RuntimeOwnedNaClDecoder = (
21906
+ /** @class */
21907
+ function(_super) {
21908
+ __extends(RuntimeOwnedNaClDecoder2, _super);
21909
+ function RuntimeOwnedNaClDecoder2(messageSender, naclModuleEl, releaseRuntime) {
21910
+ var _this = _super.call(this, messageSender, naclModuleEl) || this;
21911
+ _this.releaseRuntime = releaseRuntime;
21912
+ return _this;
21913
+ }
21914
+ RuntimeOwnedNaClDecoder2.prototype.destroy = function() {
21915
+ return __awaiter(this, void 0, void 0, function() {
21916
+ return __generator(this, function(_a) {
21917
+ this.releaseRuntime();
21918
+ return [
21919
+ 2
21920
+ /*return*/
21921
+ ];
21922
+ });
21923
+ });
21924
+ };
21925
+ return RuntimeOwnedNaClDecoder2;
21926
+ }(naclDecoder_1.NaClDecoder)
21927
+ );
18321
21928
  var naclRuntime = null;
18322
21929
  function isNaClSupported3() {
18323
21930
  return (
@@ -18330,26 +21937,48 @@
18330
21937
  if (!isNaClSupported3()) {
18331
21938
  throw new Error("NaCl is not supported in this browser.");
18332
21939
  }
18333
- var runtime = getNaClRuntime(requiredOptions.timeoutMs);
18334
- return new naclDecoder_1.NaClDecoder(runtime.messageSender, runtime.naclModuleEl);
21940
+ var _a = acquireNaClRuntime(requiredOptions.timeoutMs, options === null || options === void 0 ? void 0 : options.geometry), runtime = _a.runtime, release = _a.release;
21941
+ return new RuntimeOwnedNaClDecoder(runtime.messageSender, runtime.naclModuleEl, release);
18335
21942
  }
18336
21943
  function createNaClTCP2(options) {
18337
21944
  var decoder = createNaClDecoder2(options);
18338
- return decoder.createTCP();
21945
+ return __assign(__assign({}, decoder.createTCP()), { destroy: function() {
21946
+ return decoder.destroy();
21947
+ } });
18339
21948
  }
18340
- function getNaClRuntime(timeoutMs) {
18341
- if (naclRuntime) {
18342
- return naclRuntime;
18343
- }
18344
- var messageListeners = (0, messageListeners_1.createMessageListeners)();
18345
- var messageReceiver = new messageReceiver_1.MessageReceiver(messageListeners);
18346
- var naclModuleEl = (0, module_1.createNaClModule)(messageReceiver.handleMessage.bind(messageReceiver));
18347
- var messageSender = new messageSender_1.MessageSender(naclModuleEl, messageListeners, timeoutMs);
18348
- naclRuntime = {
18349
- messageSender,
18350
- naclModuleEl
21949
+ function acquireNaClRuntime(timeoutMs, geometry) {
21950
+ var runtime = naclRuntime;
21951
+ if (!runtime) {
21952
+ var messageListeners = (0, messageListeners_1.createMessageListeners)();
21953
+ var messageReceiver = new messageReceiver_1.MessageReceiver(messageListeners);
21954
+ var naclModuleEl = (0, module_1.createNaClModule)(messageReceiver.handleMessage.bind(messageReceiver), geometry);
21955
+ var messageSender = new messageSender_1.MessageSender(naclModuleEl, messageListeners, timeoutMs);
21956
+ runtime = {
21957
+ messageSender,
21958
+ naclModuleEl,
21959
+ ownerCount: 0
21960
+ };
21961
+ naclRuntime = runtime;
21962
+ }
21963
+ runtime.ownerCount += 1;
21964
+ var released = false;
21965
+ return {
21966
+ runtime,
21967
+ release: function() {
21968
+ if (released) {
21969
+ return;
21970
+ }
21971
+ released = true;
21972
+ runtime.ownerCount -= 1;
21973
+ if (runtime.ownerCount > 0) {
21974
+ return;
21975
+ }
21976
+ (0, module_1.removeNaClModule)(runtime.naclModuleEl);
21977
+ if (naclRuntime === runtime) {
21978
+ naclRuntime = null;
21979
+ }
21980
+ }
18351
21981
  };
18352
- return naclRuntime;
18353
21982
  }
18354
21983
  }
18355
21984
  });
@@ -18376,6 +22005,36 @@
18376
22005
  }
18377
22006
  });
18378
22007
 
22008
+ // node_modules/@signageos/samsung-wasm-decoder/dist/WasmDecoder/videoElementGeometry.js
22009
+ var require_videoElementGeometry = __commonJS({
22010
+ "node_modules/@signageos/samsung-wasm-decoder/dist/WasmDecoder/videoElementGeometry.js"(exports) {
22011
+ "use strict";
22012
+ Object.defineProperty(exports, "__esModule", { value: true });
22013
+ exports.normalizeVideoElementGeometry = normalizeVideoElementGeometry;
22014
+ function normalizeDimension(name, value) {
22015
+ var normalizedValue = Math.floor(value);
22016
+ if (!Number.isFinite(value) || normalizedValue <= 0) {
22017
+ throw new RangeError("".concat(name, " must be a finite positive number."));
22018
+ }
22019
+ return normalizedValue;
22020
+ }
22021
+ function normalizeCoordinate(name, value) {
22022
+ if (!Number.isFinite(value)) {
22023
+ throw new RangeError("".concat(name, " must be a finite number."));
22024
+ }
22025
+ return value;
22026
+ }
22027
+ function normalizeVideoElementGeometry(geometry) {
22028
+ return {
22029
+ x: normalizeCoordinate("x", geometry.x),
22030
+ y: normalizeCoordinate("y", geometry.y),
22031
+ width: normalizeDimension("width", geometry.width),
22032
+ height: normalizeDimension("height", geometry.height)
22033
+ };
22034
+ }
22035
+ }
22036
+ });
22037
+
18379
22038
  // node_modules/@signageos/samsung-wasm-decoder/dist/dom/script.js
18380
22039
  var require_script = __commonJS({
18381
22040
  "node_modules/@signageos/samsung-wasm-decoder/dist/dom/script.js"(exports) {
@@ -19660,6 +23319,7 @@
19660
23319
  Object.defineProperty(exports, "__esModule", { value: true });
19661
23320
  exports.SamsungWasmDecoder = void 0;
19662
23321
  var videoDecoder_1 = require_videoDecoder2();
23322
+ var videoElementGeometry_1 = require_videoElementGeometry();
19663
23323
  var wasmLoader_1 = require_wasmLoader();
19664
23324
  var wasmTCP_1 = require_wasmTCP();
19665
23325
  function detectKeyFrameAnnexB(bytes) {
@@ -19690,19 +23350,25 @@
19690
23350
  }
19691
23351
  return false;
19692
23352
  }
19693
- function ensureVideoElement(videoElementId) {
23353
+ function ensureVideoElement(videoElementId, geometry) {
23354
+ var normalizedGeometry = (0, videoElementGeometry_1.normalizeVideoElementGeometry)(geometry !== null && geometry !== void 0 ? geometry : {
23355
+ x: 0,
23356
+ y: 0,
23357
+ width: screen.width,
23358
+ height: screen.height
23359
+ });
19694
23360
  var el = document.getElementById(videoElementId);
19695
23361
  if (!el) {
19696
23362
  el = document.createElement("video");
19697
23363
  el.id = videoElementId;
19698
- el.style.position = "absolute";
19699
- el.style.top = "0";
19700
- el.style.left = "0";
19701
- el.style.width = "1920px";
19702
- el.style.height = "1080px";
19703
23364
  el.style.backgroundColor = "#000";
19704
23365
  document.body.appendChild(el);
19705
23366
  }
23367
+ el.style.position = "absolute";
23368
+ el.style.top = "".concat(normalizedGeometry.y, "px");
23369
+ el.style.left = "".concat(normalizedGeometry.x, "px");
23370
+ el.style.width = "".concat(normalizedGeometry.width, "px");
23371
+ el.style.height = "".concat(normalizedGeometry.height, "px");
19706
23372
  el.autoplay = true;
19707
23373
  el.muted = true;
19708
23374
  el.playsInline = true;
@@ -19711,14 +23377,14 @@
19711
23377
  var SamsungWasmDecoder2 = (
19712
23378
  /** @class */
19713
23379
  function() {
19714
- function SamsungWasmDecoder3(videoElementId) {
23380
+ function SamsungWasmDecoder3(videoElementId, geometry) {
19715
23381
  this.videoElementId = videoElementId;
19716
23382
  this.initialized = false;
19717
23383
  this.destroyed = false;
19718
23384
  this.decoderHandle = 0;
19719
23385
  this.ptsSeconds = 0;
19720
23386
  this.frameDurationSeconds = 0;
19721
- this.videoElement = ensureVideoElement(videoElementId);
23387
+ this.videoElement = ensureVideoElement(videoElementId, geometry);
19722
23388
  }
19723
23389
  SamsungWasmDecoder3.prototype.destroy = function() {
19724
23390
  return __awaiter(this, void 0, void 0, function() {
@@ -19947,7 +23613,7 @@
19947
23613
  });
19948
23614
 
19949
23615
  // node_modules/@signageos/samsung-wasm-decoder/dist/index.js
19950
- var require_dist2 = __commonJS({
23616
+ var require_dist3 = __commonJS({
19951
23617
  "node_modules/@signageos/samsung-wasm-decoder/dist/index.js"(exports) {
19952
23618
  "use strict";
19953
23619
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
@@ -20091,7 +23757,7 @@
20091
23757
  return [4, (0, wasmLoader_1.loadWasmModule)()];
20092
23758
  case 1:
20093
23759
  _a.sent();
20094
- return [2, new wasmDecoder_1.SamsungWasmDecoder(options.videoElementId)];
23760
+ return [2, new wasmDecoder_1.SamsungWasmDecoder(options.videoElementId, options.geometry)];
20095
23761
  }
20096
23762
  });
20097
23763
  });
@@ -20222,14 +23888,14 @@
20222
23888
  async function injectScript(url) {
20223
23889
  return new Promise((resolve, reject) => {
20224
23890
  const scriptEl = document.createElement("script");
20225
- scriptEl.src = url;
20226
- document.head.appendChild(scriptEl);
20227
- scriptEl.onerror = async function(error) {
20228
- reject(error);
23891
+ scriptEl.onerror = function() {
23892
+ reject(new Error(`Failed to load script: ${url}`));
20229
23893
  };
20230
- scriptEl.onload = async function() {
23894
+ scriptEl.onload = function() {
20231
23895
  resolve();
20232
23896
  };
23897
+ scriptEl.src = url;
23898
+ document.head.appendChild(scriptEl);
20233
23899
  });
20234
23900
  }
20235
23901
 
@@ -20240,7 +23906,7 @@
20240
23906
  options: {}
20241
23907
  };
20242
23908
  async function initBrowserFS() {
20243
- BrowserFS.install(window);
23909
+ installBrowserFSGlobals();
20244
23910
  await new Promise((resolve, reject) => {
20245
23911
  BrowserFS.configure(config, (error) => {
20246
23912
  if (error) {
@@ -20254,6 +23920,73 @@
20254
23920
  shim(fs);
20255
23921
  return fs;
20256
23922
  }
23923
+ var installedBrowserFSRequire;
23924
+ function installBrowserFSGlobals() {
23925
+ const browserFSProcess = BrowserFS.BFSRequire("process");
23926
+ if (!window.process) {
23927
+ Object.defineProperty(window, "process", {
23928
+ configurable: true,
23929
+ enumerable: true,
23930
+ value: {},
23931
+ writable: true
23932
+ });
23933
+ }
23934
+ const processPolyfills = /* @__PURE__ */ new Map([
23935
+ ["browser", true],
23936
+ ["env", {}],
23937
+ ["getuid", browserFSProcess.getuid.bind(browserFSProcess)],
23938
+ ["getgid", browserFSProcess.getgid.bind(browserFSProcess)],
23939
+ ["geteuid", browserFSProcess.getuid.bind(browserFSProcess)],
23940
+ ["getegid", browserFSProcess.getgid.bind(browserFSProcess)],
23941
+ ["getgroups", () => {
23942
+ throw createNotImplementedError();
23943
+ }],
23944
+ ["pid", browserFSProcess.pid],
23945
+ ["ppid", -1],
23946
+ ["umask", browserFSProcess.umask.bind(browserFSProcess)],
23947
+ ["cwd", browserFSProcess.cwd.bind(browserFSProcess)],
23948
+ ["chdir", browserFSProcess.chdir.bind(browserFSProcess)]
23949
+ ]);
23950
+ for (const [property, value] of processPolyfills) {
23951
+ if (Reflect.get(window.process, property) === void 0) {
23952
+ Object.defineProperty(window.process, property, {
23953
+ configurable: true,
23954
+ value,
23955
+ writable: true
23956
+ });
23957
+ }
23958
+ }
23959
+ if (!installedBrowserFSRequire) {
23960
+ const previousRequire = window.require;
23961
+ installedBrowserFSRequire = (moduleName) => {
23962
+ const browserFSModule = BrowserFS.BFSRequire(moduleName);
23963
+ if (browserFSModule) {
23964
+ return browserFSModule;
23965
+ }
23966
+ if (previousRequire) {
23967
+ return previousRequire(moduleName);
23968
+ }
23969
+ throw new Error(`Cannot find module '${moduleName}'`);
23970
+ };
23971
+ }
23972
+ Object.defineProperty(window, "Buffer", {
23973
+ configurable: true,
23974
+ enumerable: true,
23975
+ value: BrowserFS.BFSRequire("buffer").Buffer,
23976
+ writable: true
23977
+ });
23978
+ Object.defineProperty(window, "require", {
23979
+ configurable: true,
23980
+ enumerable: true,
23981
+ value: installedBrowserFSRequire,
23982
+ writable: true
23983
+ });
23984
+ }
23985
+ function createNotImplementedError() {
23986
+ const error = new Error("not implemented");
23987
+ Object.defineProperty(error, "code", { value: "ENOSYS" });
23988
+ return error;
23989
+ }
20257
23990
  function getStringFlagsByNumber(fs, origFlags) {
20258
23991
  if ((origFlags & (fs.constants.O_APPEND | fs.constants.O_CREAT)) !== 0) {
20259
23992
  return "a";
@@ -20445,11 +24178,82 @@
20445
24178
  }
20446
24179
  }
20447
24180
 
24181
+ // screen/brightsign.ts
24182
+ var import_brightsign_decoder = __toESM(require_dist());
24183
+ var referenceRegistry;
24184
+ var streamErrorListenerRegistered = false;
24185
+ var teardownRegistered = false;
24186
+ function isBrightSignRuntimeAvailable() {
24187
+ return (0, import_brightsign_decoder.isBrightSignDecoderSupported)();
24188
+ }
24189
+ function initBrightSignTCP() {
24190
+ registerStreamErrorListener();
24191
+ if (window.brightSignTCP) {
24192
+ return true;
24193
+ }
24194
+ try {
24195
+ const registry = getReferenceRegistry();
24196
+ window.brightSignTCP = (0, import_brightsign_decoder.createBrightSignTCP)({
24197
+ refRegistry: registry,
24198
+ maxPacketSize: 65535
24199
+ });
24200
+ registerTeardown();
24201
+ return true;
24202
+ } catch (error) {
24203
+ console.log("BrightSign TCP is not available", error);
24204
+ return false;
24205
+ }
24206
+ }
24207
+ function registerStreamErrorListener() {
24208
+ if (streamErrorListenerRegistered) {
24209
+ return;
24210
+ }
24211
+ const sos = Reflect.get(globalThis, "sos");
24212
+ if (typeof sos !== "object" || sos === null) {
24213
+ return;
24214
+ }
24215
+ const stream = Reflect.get(sos, "stream");
24216
+ if (typeof stream !== "object" || stream === null) {
24217
+ return;
24218
+ }
24219
+ const onError = Reflect.get(stream, "onError");
24220
+ if (typeof onError !== "function") {
24221
+ return;
24222
+ }
24223
+ Reflect.apply(onError, stream, [
24224
+ (event) => console.error("BrightSign native stream error", event)
24225
+ ]);
24226
+ streamErrorListenerRegistered = true;
24227
+ }
24228
+ function getReferenceRegistry() {
24229
+ if (!referenceRegistry) {
24230
+ referenceRegistry = new import_brightsign_decoder.FrameReferenceRegistry();
24231
+ window.brightSignReleaseFrameReference = (reference) => {
24232
+ referenceRegistry == null ? void 0 : referenceRegistry.release(reference);
24233
+ };
24234
+ }
24235
+ return referenceRegistry;
24236
+ }
24237
+ function registerTeardown() {
24238
+ if (teardownRegistered) {
24239
+ return;
24240
+ }
24241
+ teardownRegistered = true;
24242
+ window.addEventListener("unload", () => {
24243
+ const decoder = window.brightSignDecoder;
24244
+ const tcp = window.brightSignTCP;
24245
+ window.brightSignDecoder = void 0;
24246
+ window.brightSignTCP = void 0;
24247
+ void (decoder == null ? void 0 : decoder.destroy());
24248
+ void (tcp == null ? void 0 : tcp.destroy());
24249
+ });
24250
+ }
24251
+
20448
24252
  // screen/nacltcp.ts
20449
- var import_nacl_decoder = __toESM(require_dist());
20450
- async function initNaClTCP() {
24253
+ var import_nacl_decoder = __toESM(require_dist2());
24254
+ async function initNaClTCP(options) {
20451
24255
  if ((0, import_nacl_decoder.isNaClSupported)()) {
20452
- const { tcpPacket, tcpStream } = (0, import_nacl_decoder.createNaClTCP)();
24256
+ const { tcpPacket, tcpStream } = (0, import_nacl_decoder.createNaClTCP)({ geometry: options == null ? void 0 : options.geometry });
20453
24257
  if (!window.naclTCPPacket) {
20454
24258
  window.naclTCPPacket = tcpPacket;
20455
24259
  }
@@ -20460,7 +24264,7 @@
20460
24264
  }
20461
24265
 
20462
24266
  // screen/samsungwasmtcp.ts
20463
- var import_samsung_wasm_decoder = __toESM(require_dist2());
24267
+ var import_samsung_wasm_decoder = __toESM(require_dist3());
20464
24268
  async function initSamsungWasmTCP() {
20465
24269
  if ((0, import_samsung_wasm_decoder.isSamsungWasmSupported)()) {
20466
24270
  const { tcpPacket, tcpStream } = await (0, import_samsung_wasm_decoder.createSamsungWasmTCP)();
@@ -20474,8 +24278,9 @@
20474
24278
  }
20475
24279
 
20476
24280
  // daemon/plain.ts
20477
- var DAEMON_JS_URL = "supra-client-daemon.js?v=0.0.1";
24281
+ var DAEMON_JS_URL = "supra-client-daemon.js?v=1.0.0-mzbrightsigndecoder.473";
20478
24282
  async function startPlainDaemon() {
24283
+ initBrightSignTCP();
20479
24284
  await initNaClTCP();
20480
24285
  await initSamsungWasmTCP();
20481
24286
  const fs = await initBrowserFS();
@@ -20487,8 +24292,9 @@
20487
24292
  }
20488
24293
 
20489
24294
  // daemon/wasm.ts
20490
- var DAEMON_WASM_URL = "supra-client-daemon.wasm?v=0.0.1";
24295
+ var DAEMON_WASM_URL = "supra-client-daemon.wasm?v=1.0.0-mzbrightsigndecoder.473";
20491
24296
  async function startWasmDaemon() {
24297
+ initBrightSignTCP();
20492
24298
  await initNaClTCP();
20493
24299
  await initSamsungWasmTCP();
20494
24300
  await initGoEnvironment();
@@ -20508,10 +24314,10 @@
20508
24314
  }
20509
24315
 
20510
24316
  // screen/nacldecoder.ts
20511
- var import_nacl_decoder2 = __toESM(require_dist());
24317
+ var import_nacl_decoder2 = __toESM(require_dist2());
20512
24318
 
20513
24319
  // screen/samsungwasmdecoder.ts
20514
- var import_samsung_wasm_decoder2 = __toESM(require_dist2());
24320
+ var import_samsung_wasm_decoder2 = __toESM(require_dist3());
20515
24321
  var import_videoDecoder = __toESM(require_videoDecoder2());
20516
24322
 
20517
24323
  // screen/shared.ts
@@ -20519,10 +24325,13 @@
20519
24325
 
20520
24326
  // sdk.ts
20521
24327
  async function startDaemon(options) {
24328
+ if ((options == null ? void 0 : options.requireBrightSignRuntime) && !isBrightSignRuntimeAvailable()) {
24329
+ throw new Error("BrightSign TCP requires a native controller with Node.js capabilities");
24330
+ }
20522
24331
  if (shouldUsePlainJS(options)) {
20523
- startPlainDaemon();
24332
+ await startPlainDaemon();
20524
24333
  } else {
20525
- startWasmDaemon();
24334
+ await startWasmDaemon();
20526
24335
  }
20527
24336
  }
20528
24337
  function shouldUsePlainJS(options) {