ot-gateway 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3844,6 +3844,19 @@ __export(Context_exports, {
3844
3844
  pick: () => pick
3845
3845
  });
3846
3846
 
3847
+ // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js
3848
+ var Equal_exports = {};
3849
+ __export(Equal_exports, {
3850
+ asEquivalence: () => asEquivalence,
3851
+ byReference: () => byReference,
3852
+ byReferenceUnsafe: () => byReferenceUnsafe,
3853
+ equals: () => equals,
3854
+ isEqual: () => isEqual,
3855
+ makeCompareMap: () => makeCompareMap,
3856
+ makeCompareSet: () => makeCompareSet,
3857
+ symbol: () => symbol2
3858
+ });
3859
+
3847
3860
  // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js
3848
3861
  var pipeArguments = (self, args2) => {
3849
3862
  switch (args2.length) {
@@ -4400,6 +4413,7 @@ function makeCompareSet(equivalence) {
4400
4413
  }
4401
4414
  var isEqual = (u) => hasProperty(u, symbol2) && typeof u[symbol2] === "function";
4402
4415
  var asEquivalence = () => equals;
4416
+ var byReference = (obj) => byReferenceUnsafe(new Proxy(obj, {}));
4403
4417
  var byReferenceUnsafe = (obj) => {
4404
4418
  byReferenceInstances.add(obj);
4405
4419
  return obj;
@@ -11698,11 +11712,40 @@ var doneUnsafe = (self, effect2) => {
11698
11712
  var into = /* @__PURE__ */ dual(2, (self, deferred) => uninterruptibleMask((restore) => flatMap4(exit(restore(self)), (exit3) => done3(deferred, exit3))));
11699
11713
 
11700
11714
  // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/References.js
11715
+ var References_exports = {};
11716
+ __export(References_exports, {
11717
+ CurrentLogAnnotations: () => CurrentLogAnnotations2,
11718
+ CurrentLogLevel: () => CurrentLogLevel2,
11719
+ CurrentLogSpans: () => CurrentLogSpans2,
11720
+ CurrentLoggers: () => CurrentLoggers2,
11721
+ CurrentStackFrame: () => CurrentStackFrame2,
11722
+ CurrentTraceLevel: () => CurrentTraceLevel,
11723
+ DisablePropagation: () => DisablePropagation,
11724
+ LogToStderr: () => LogToStderr2,
11725
+ MaxOpsBeforeYield: () => MaxOpsBeforeYield,
11726
+ MinimumLogLevel: () => MinimumLogLevel2,
11727
+ MinimumTraceLevel: () => MinimumTraceLevel,
11728
+ PreventSchedulerYield: () => PreventSchedulerYield,
11729
+ Scheduler: () => Scheduler,
11730
+ Tracer: () => Tracer,
11731
+ TracerEnabled: () => TracerEnabled2,
11732
+ TracerSpanAnnotations: () => TracerSpanAnnotations2,
11733
+ TracerSpanLinks: () => TracerSpanLinks2,
11734
+ TracerTimingEnabled: () => TracerTimingEnabled2,
11735
+ UnhandledLogLevel: () => UnhandledLogLevel2
11736
+ });
11701
11737
  var CurrentLogAnnotations2 = CurrentLogAnnotations;
11738
+ var CurrentLogLevel2 = CurrentLogLevel;
11702
11739
  var CurrentLogSpans2 = CurrentLogSpans;
11703
11740
  var CurrentStackFrame2 = CurrentStackFrame;
11704
11741
  var MinimumLogLevel2 = MinimumLogLevel;
11742
+ var TracerEnabled2 = TracerEnabled;
11743
+ var TracerSpanAnnotations2 = TracerSpanAnnotations;
11744
+ var TracerSpanLinks2 = TracerSpanLinks;
11705
11745
  var TracerTimingEnabled2 = TracerTimingEnabled;
11746
+ var UnhandledLogLevel2 = UnhandledLogLevel;
11747
+ var CurrentLoggers2 = CurrentLoggers;
11748
+ var LogToStderr2 = LogToStderr;
11706
11749
 
11707
11750
  // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js
11708
11751
  var Scope_exports = {};
@@ -23176,8 +23219,8 @@ var decodeJsonError = (input) => {
23176
23219
  };
23177
23220
  var encodeUnknownAsJson = (input) => {
23178
23221
  try {
23179
- const json3 = formatJson(input);
23180
- return json3 === void 0 ? format(input) : JSON.parse(json3);
23222
+ const json4 = formatJson(input);
23223
+ return json4 === void 0 ? format(input) : JSON.parse(json4);
23181
23224
  } catch {
23182
23225
  return format(input);
23183
23226
  }
@@ -25589,14 +25632,14 @@ var template = (strings, ...expressions) => {
25589
25632
  var unwrap5 = (item) => isRedacted(item) ? value3(item) : String(item);
25590
25633
  var toWord = (item) => isRedacted(item) ? item : String(item);
25591
25634
  var reservedWords = /* @__PURE__ */ new Set(["!", "{", "}", "and", "begin", "case", "coproc", "do", "done", "elif", "else", "end", "esac", "fi", "for", "foreach", "function", "if", "in", "nocorrect", "not", "or", "repeat", "select", "switch", "then", "time", "until", "while"]);
25592
- var quoteWord = (format11, value4, program2) => {
25635
+ var quoteWord = (format11, value4, program) => {
25593
25636
  switch (format11) {
25594
25637
  case "posix":
25595
- return program2 && reservedWords.has(value4) ? `'${value4}'` : quotePosix(value4);
25638
+ return program && reservedWords.has(value4) ? `'${value4}'` : quotePosix(value4);
25596
25639
  case "powershell":
25597
25640
  return quotePowerShell(value4);
25598
25641
  case "windows":
25599
- return program2 && !value4.includes('"') ? quoteWindowsProgram(value4) : quoteWindowsArgument(value4);
25642
+ return program && !value4.includes('"') ? quoteWindowsProgram(value4) : quoteWindowsArgument(value4);
25600
25643
  }
25601
25644
  };
25602
25645
  var joinWords = (format11, quoted) => format11 === "powershell" ? `& ${quoted.join(" ")}` : quoted.join(" ");
@@ -25787,14 +25830,14 @@ var parseFdName = (name) => {
25787
25830
  };
25788
25831
  var fdName = (fd) => `fd${fd}`;
25789
25832
  var parseTemplate2 = (templates, expressions) => {
25790
- const [program2 = "", ...args2] = getOrThrow2(template(templates, ...expressions));
25791
- if (typeof program2 !== "string") {
25833
+ const [program = "", ...args2] = getOrThrow2(template(templates, ...expressions));
25834
+ if (typeof program !== "string") {
25792
25835
  throw new CommandLineError({
25793
25836
  reason: "InvalidArgument",
25794
25837
  message: "The program name of a command cannot be Redacted"
25795
25838
  });
25796
25839
  }
25797
- return [program2, args2];
25840
+ return [program, args2];
25798
25841
  };
25799
25842
  var shellScript = (templates, expressions) => {
25800
25843
  if (expressions.length > 0) {
@@ -39150,8 +39193,8 @@ var dnsSeconds = /* @__PURE__ */ dnsUint32.pipe(/* @__PURE__ */ decodeTo2(Durati
39150
39193
  var dnsRecordOfType = (type, fields) => declare((u) => isDnsRecord(u) && u._tag === type, {
39151
39194
  identifier: `Dns${type.charAt(0)}${type.slice(1).toLowerCase()}Record`,
39152
39195
  toCodecJson: () => {
39153
- const json3 = TaggedStruct(type, fields);
39154
- return link3()(json3, transformEffect2({
39196
+ const json4 = TaggedStruct(type, fields);
39197
+ return link3()(json4, transformEffect2({
39155
39198
  decode: (input, options3) => {
39156
39199
  const {
39157
39200
  _tag,
@@ -41502,8 +41545,8 @@ var awaitEmpty = (self) => whileLoop2({
41502
41545
  // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Logger.js
41503
41546
  var Logger_exports = {};
41504
41547
  __export(Logger_exports, {
41505
- CurrentLoggers: () => CurrentLoggers2,
41506
- LogToStderr: () => LogToStderr2,
41548
+ CurrentLoggers: () => CurrentLoggers3,
41549
+ LogToStderr: () => LogToStderr3,
41507
41550
  batched: () => batched,
41508
41551
  consoleJson: () => consoleJson,
41509
41552
  consoleLogFmt: () => consoleLogFmt,
@@ -41528,8 +41571,8 @@ __export(Logger_exports, {
41528
41571
  });
41529
41572
  var TypeId56 = "~effect/Logger";
41530
41573
  var isLogger = (u) => hasProperty(u, TypeId56);
41531
- var CurrentLoggers2 = CurrentLoggers;
41532
- var LogToStderr2 = LogToStderr;
41574
+ var CurrentLoggers3 = CurrentLoggers;
41575
+ var LogToStderr3 = LogToStderr;
41533
41576
  var map15 = /* @__PURE__ */ dual(2, (self, f) => loggerMake((options3) => f(self.log(options3))));
41534
41577
  var withConsoleLog = (self) => loggerMake((options3) => {
41535
41578
  const console2 = options3.fiber.getRef(ConsoleRef);
@@ -41653,7 +41696,7 @@ var consoleLogFmt = /* @__PURE__ */ withConsoleLog(formatLogFmt);
41653
41696
  var consoleStructured = /* @__PURE__ */ withConsoleLog(formatStructured);
41654
41697
  var consoleJson = /* @__PURE__ */ withConsoleLog(formatJson2);
41655
41698
  var tracerLogger2 = tracerLogger;
41656
- var layer13 = (loggers, options3) => effect(CurrentLoggers2, withFiber(fnUntraced(function* (fiber3) {
41699
+ var layer13 = (loggers, options3) => effect(CurrentLoggers3, withFiber(fnUntraced(function* (fiber3) {
41657
41700
  const currentLoggers = new Set(options3?.mergeWithExisting === true ? fiber3.getRef(CurrentLoggers) : []);
41658
41701
  for (const logger2 of loggers) {
41659
41702
  currentLoggers.add(isEffect(logger2) ? yield* logger2 : logger2);
@@ -49802,17 +49845,17 @@ var resolveFormatter = /* @__PURE__ */ contextWith2((context3) => succeed7(getOr
49802
49845
  })));
49803
49846
 
49804
49847
  // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/cli/internal/lexer.js
49805
- function lex(argv) {
49806
- const endIndex = argv.indexOf("--");
49848
+ function lex(argv2) {
49849
+ const endIndex = argv2.indexOf("--");
49807
49850
  if (endIndex === -1) {
49808
49851
  return {
49809
- tokens: lexTokens(argv),
49852
+ tokens: lexTokens(argv2),
49810
49853
  trailingOperands: []
49811
49854
  };
49812
49855
  }
49813
49856
  return {
49814
- tokens: lexTokens(argv.slice(0, endIndex)),
49815
- trailingOperands: argv.slice(endIndex + 1)
49857
+ tokens: lexTokens(argv2.slice(0, endIndex)),
49858
+ trailingOperands: argv2.slice(endIndex + 1)
49816
49859
  };
49817
49860
  }
49818
49861
  var negativeNumberRegex = /^-(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
@@ -51027,19 +51070,19 @@ var runWith2 = (command, config) => {
51027
51070
  });
51028
51071
  }
51029
51072
  const input = yield* commandImpl.parse(parsedArgs).pipe(toShowHelp);
51030
- let program2 = commandImpl.handle(input, [command.name]);
51073
+ let program = commandImpl.handle(input, [command.name]);
51031
51074
  const logLevel = activeFlags.includes(LogLevel2) ? (yield* LogLevel2.flag.parse(emptyArgs).pipe(toShowHelp))[1] : none2();
51032
- program2 = provideService2(program2, LogLevel2, logLevel);
51075
+ program = provideService2(program, LogLevel2, logLevel);
51033
51076
  for (const flag of activeFlags) {
51034
51077
  if (flag._tag !== "Setting" || flag === LogLevel2) continue;
51035
51078
  const [, value4] = yield* flag.flag.parse(emptyArgs).pipe(toShowHelp);
51036
- program2 = provideService2(program2, flag, value4);
51079
+ program = provideService2(program, flag, value4);
51037
51080
  }
51038
51081
  const services = match(logLevel, {
51039
51082
  onNone: () => empty(),
51040
51083
  onSome: (level) => make5(MinimumLogLevel2, level)
51041
51084
  });
51042
- yield* provideContext2(program2, services);
51085
+ yield* provideContext2(program, services);
51043
51086
  }, catchFilter2((error2) => isCliError(error2) && error2._tag === "ShowHelp" ? succeed2(error2) : fail2(error2), (error2) => andThen4(showHelp(command, error2, config.renderErrors !== false), fail7(error2))), catchFilter2((error2) => {
51044
51087
  if (config.renderErrors === false || !isObjectKeyword(error2)) return fail2(error2);
51045
51088
  const userMessage2 = getUserMessage(error2);
@@ -51342,6 +51385,22 @@ var makeMemoryPublisher = Effect_exports.sync(() => {
51342
51385
  });
51343
51386
 
51344
51387
  // ../../packages/core/src/Telemetry.ts
51388
+ function makeValueCounters() {
51389
+ return {
51390
+ published: Metric_exports.counter("ot_gateway_values_published", {
51391
+ description: "Point values published",
51392
+ incremental: true
51393
+ }),
51394
+ suppressed: Metric_exports.counter("ot_gateway_values_suppressed", {
51395
+ description: "Point values held back in change mode",
51396
+ incremental: true
51397
+ }),
51398
+ pushed: Metric_exports.counter("ot_gateway_pushed_readings", {
51399
+ description: "Values pushed by devices between polls",
51400
+ incremental: true
51401
+ })
51402
+ };
51403
+ }
51345
51404
  var seconds2 = { unit: "seconds" };
51346
51405
  var pollCycles = Metric_exports.counter("ot_gateway_poll_cycles", {
51347
51406
  description: "Polling cycles finished, by outcome",
@@ -51362,14 +51421,8 @@ var publishFailures = Metric_exports.counter("ot_gateway_publish_failures", {
51362
51421
  description: "Messages that failed to publish",
51363
51422
  incremental: true
51364
51423
  });
51365
- var valuesPublished = Metric_exports.counter("ot_gateway_values_published", {
51366
- description: "Point values published",
51367
- incremental: true
51368
- });
51369
- var valuesSuppressed = Metric_exports.counter("ot_gateway_values_suppressed", {
51370
- description: "Point values held back in change mode",
51371
- incremental: true
51372
- });
51424
+ var valuesPublished = makeValueCounters().published;
51425
+ var valuesSuppressed = makeValueCounters().suppressed;
51373
51426
  var deviceLastSuccess = Metric_exports.gauge("ot_gateway_device_last_success_timestamp_seconds", {
51374
51427
  description: "Unix time of the last successful polling cycle of a device",
51375
51428
  attributes: seconds2
@@ -51382,10 +51435,7 @@ var deviceRestarts = Metric_exports.counter("ot_gateway_device_restarts", {
51382
51435
  description: "Device pipelines restarted after a defect",
51383
51436
  incremental: true
51384
51437
  });
51385
- var pushedReadings = Metric_exports.counter("ot_gateway_pushed_readings", {
51386
- description: "Values pushed by devices between polls",
51387
- incremental: true
51388
- });
51438
+ var pushedReadings = makeValueCounters().pushed;
51389
51439
  var pushedPoints = Metric_exports.gauge("ot_gateway_pushed_points", {
51390
51440
  description: "Points kept up to date by device pushes instead of polling",
51391
51441
  attributes: { unit: "{point}" }
@@ -52959,6 +53009,7 @@ var isRetryable = (driver, error2) => {
52959
53009
  var countCycle = (outcome) => Metric_exports.update(Metric_exports.withAttributes(pollCycles, { outcome }), 1);
52960
53010
  var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
52961
53011
  const publisher = yield* Publisher;
53012
+ const counters = makeValueCounters();
52962
53013
  const points2 = new Map(driver.points.map((p) => [p.id, p]));
52963
53014
  const policies = new Map(driver.points.map((p) => [p.id, publishOf(ctx.publish, p)]));
52964
53015
  const policyOf = (pointId) => policies.get(pointId) ?? everyRead;
@@ -53075,7 +53126,7 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53075
53126
  const sentAt = lastSentAt.get(point.id);
53076
53127
  const quietTooLong = policy2.maxSilenceMs !== void 0 && sentAt !== void 0 && atMono - sentAt >= policy2.maxSilenceMs;
53077
53128
  if (!quietTooLong && !exceedsDeadband(Option_exports.fromUndefinedOr(last2.get(point.id)), value4, policy2.deadband)) {
53078
- return yield* Metric_exports.update(valuesSuppressed, 1);
53129
+ return yield* Metric_exports.update(counters.suppressed, 1);
53079
53130
  }
53080
53131
  if (!(yield* send(point.id, message))) return;
53081
53132
  last2.set(point.id, value4);
@@ -53089,7 +53140,7 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53089
53140
  Effect_exports.as(true),
53090
53141
  Effect_exports.catchTag("PublishError", (error2) => Effect_exports.as(skipRefused(error2), false))
53091
53142
  );
53092
- if (sent) yield* Metric_exports.update(valuesPublished, 1);
53143
+ if (sent) yield* Metric_exports.update(counters.published, 1);
53093
53144
  return sent;
53094
53145
  });
53095
53146
  const closeWindows = Effect_exports.fnUntraced(function* (intervalMs, endMs) {
@@ -53196,7 +53247,7 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53196
53247
  const pushLost = (message, annotations2) => Effect_exports.all([publishFailed("values", message, annotations2), Metric_exports.update(publishFailures, 1)]);
53197
53248
  const pushed = driver.changes === void 0 ? Effect_exports.void : Stream_exports.runForEach(
53198
53249
  driver.changes,
53199
- (reading) => Metric_exports.update(pushedReadings, 1).pipe(
53250
+ (reading) => Metric_exports.update(counters.pushed, 1).pipe(
53200
53251
  // Under the deadline, so a hung publish cannot keep the permit from the polling cycle forever.
53201
53252
  Effect_exports.andThen(handling.withPermit(handleReading(reading)).pipe(deadline("pushed-value"))),
53202
53253
  // The value is lost; the next change, renewal notification or poll brings the point's value again.
@@ -55828,7 +55879,14 @@ var logDefect = (message) => (defect) => Effect_exports.logError(message).pipe(E
55828
55879
  var BACKLOG = 1024;
55829
55880
  var COV_CONCURRENCY = 4;
55830
55881
  var COV_SILENT_IN_A_ROW = 2 * COV_CONCURRENCY;
55831
- var sameAddress = (left, right) => formatInet(left.address) === formatInet(right.address) && left.network?.network === right.network?.network && (left.network?.address ?? []).join(".") === (right.network?.address ?? []).join(".");
55882
+ var sameInet = (left, right) => left.port === right.port && (left._tag === "InetAddressV4" ? right._tag === "InetAddressV4" : right._tag === "InetAddressV6" && left.scopeId === right.scopeId) && left.address[Equal_exports.symbol](right.address);
55883
+ var sameAddress = (left, right) => {
55884
+ if (!sameInet(left.address, right.address)) return false;
55885
+ if (left.network?.network !== right.network?.network) return false;
55886
+ const leftHops = left.network?.address ?? [];
55887
+ const rightHops = right.network?.address ?? [];
55888
+ return leftHops.length === rightHops.length && leftHops.every((byte, index2) => byte === rightHops[index2]);
55889
+ };
55832
55890
  var describeObject = (object) => `${nameOf(ObjectType, object.objectType)}:${object.instance}`;
55833
55891
  var OTHER_DEVICE = "for another device";
55834
55892
  var makeCovSubscriptions = (deps) => {
@@ -57854,8 +57912,9 @@ var decodeVariableByteInteger = (bytes3, offset = 0) => {
57854
57912
  }
57855
57913
  return new MqttCodecError({ message: "malformed variable byte integer" });
57856
57914
  };
57915
+ var utf82 = new TextEncoder();
57857
57916
  var encodeUtf8String = (value4) => {
57858
- const encoded = new TextEncoder().encode(value4);
57917
+ const encoded = utf82.encode(value4);
57859
57918
  if (encoded.length > 65535) throw new RangeError("string too long");
57860
57919
  const out = new Uint8Array(2 + encoded.length);
57861
57920
  new DataView(out.buffer).setUint16(0, encoded.length);
@@ -58217,23 +58276,74 @@ var connackReasonName = (code) => ({
58217
58276
  159: "connection rate exceeded"
58218
58277
  })[code] ?? `reason code 0x${code.toString(16)}`;
58219
58278
  var encodePublish = (publish2, version2 = 5) => {
58220
- const body = new Writer2().string(publish2.topic);
58221
- if (publish2.qos > 0) body.u16(publish2.packetId ?? 0);
58222
- if (version2 === 4) {
58223
- body.bytes(publish2.payload);
58224
- return packet(PacketType.PUBLISH, publish2.qos << 1 | (publish2.retain ? 1 : 0), body.toBytes());
58225
- }
58226
- body.bytes(
58227
- encodeProperties((w) => {
58228
- w.byte(Property.PayloadFormatIndicator).byte(1);
58229
- if (publish2.messageExpirySeconds !== void 0) {
58230
- w.byte(Property.MessageExpiryInterval).u32(publish2.messageExpirySeconds);
58231
- }
58232
- if (publish2.responseTopic !== void 0) w.byte(Property.ResponseTopic).string(publish2.responseTopic);
58233
- if (publish2.correlationData !== void 0) w.byte(Property.CorrelationData).binary(publish2.correlationData);
58234
- })
58235
- ).bytes(publish2.payload);
58236
- return packet(PacketType.PUBLISH, publish2.qos << 1 | (publish2.retain ? 1 : 0), body.toBytes());
58279
+ const topic = utf8String(publish2.topic);
58280
+ const withProperties = version2 === 5;
58281
+ const responseTopic = withProperties && publish2.responseTopic !== void 0 ? utf8String(publish2.responseTopic) : void 0;
58282
+ const expiry = withProperties ? publish2.messageExpirySeconds : void 0;
58283
+ const correlation = withProperties ? publish2.correlationData : void 0;
58284
+ let propertiesLength = 0;
58285
+ if (withProperties) {
58286
+ propertiesLength = 2;
58287
+ if (expiry !== void 0) propertiesLength += 5;
58288
+ if (responseTopic !== void 0) propertiesLength += 3 + responseTopic.length;
58289
+ if (correlation !== void 0) propertiesLength += 3 + correlation.length;
58290
+ }
58291
+ const bodyLength = 2 + topic.length + (publish2.qos > 0 ? 2 : 0) + (withProperties ? variableByteIntegerLength(propertiesLength) + propertiesLength : 0) + publish2.payload.length;
58292
+ const out = new Uint8Array(1 + variableByteIntegerLength(bodyLength) + bodyLength);
58293
+ out[0] = PacketType.PUBLISH << 4 | publish2.qos << 1 | (publish2.retain ? 1 : 0);
58294
+ let offset = writeVariableByteInteger(out, 1, bodyLength);
58295
+ offset = writeU16(out, offset, topic.length);
58296
+ out.set(topic, offset);
58297
+ offset += topic.length;
58298
+ if (publish2.qos > 0) offset = writeU16(out, offset, publish2.packetId ?? 0);
58299
+ if (withProperties) {
58300
+ offset = writeVariableByteInteger(out, offset, propertiesLength);
58301
+ out[offset++] = Property.PayloadFormatIndicator;
58302
+ out[offset++] = 1;
58303
+ if (expiry !== void 0) {
58304
+ out[offset++] = Property.MessageExpiryInterval;
58305
+ new DataView(out.buffer).setUint32(offset, expiry >>> 0);
58306
+ offset += 4;
58307
+ }
58308
+ if (responseTopic !== void 0) {
58309
+ out[offset++] = Property.ResponseTopic;
58310
+ offset = writeU16(out, offset, responseTopic.length);
58311
+ out.set(responseTopic, offset);
58312
+ offset += responseTopic.length;
58313
+ }
58314
+ if (correlation !== void 0) {
58315
+ out[offset++] = Property.CorrelationData;
58316
+ offset = writeU16(out, offset, correlation.length);
58317
+ out.set(correlation, offset);
58318
+ offset += correlation.length;
58319
+ }
58320
+ }
58321
+ out.set(publish2.payload, offset);
58322
+ return out;
58323
+ };
58324
+ var utf8String = (value4) => {
58325
+ const bytes3 = encoder9.encode(value4);
58326
+ if (bytes3.length > 65535) throw new RangeError("string too long");
58327
+ return bytes3;
58328
+ };
58329
+ var variableByteIntegerLength = (value4) => {
58330
+ if (value4 > MAX_VARIABLE_BYTE_INTEGER) throw new RangeError(`value out of range: ${value4}`);
58331
+ return value4 < 128 ? 1 : value4 < 16384 ? 2 : value4 < 2097152 ? 3 : 4;
58332
+ };
58333
+ var writeVariableByteInteger = (out, offset, value4) => {
58334
+ let rest = value4;
58335
+ do {
58336
+ let byte = rest % 128;
58337
+ rest = Math.floor(rest / 128);
58338
+ if (rest > 0) byte |= 128;
58339
+ out[offset++] = byte;
58340
+ } while (rest > 0);
58341
+ return offset;
58342
+ };
58343
+ var writeU16 = (out, offset, value4) => {
58344
+ out[offset] = value4 >> 8 & 255;
58345
+ out[offset + 1] = value4 & 255;
58346
+ return offset + 2;
58237
58347
  };
58238
58348
  var decodePublish = (flags, body, version2 = 5) => decodeWith2(body, (r) => {
58239
58349
  const qos = flags >> 1 & 3;
@@ -58360,7 +58470,7 @@ var countConnect3 = (outcome) => Metric_exports.update(Metric_exports.withAttrib
58360
58470
  var topicProblem = (topic) => {
58361
58471
  if (topic.length === 0) return "topic is empty";
58362
58472
  if (topic.includes("+") || topic.includes("#")) return "topic contains a wildcard";
58363
- if (encoder10.encode(topic).length > 65535) return "topic is longer than 65,535 bytes";
58473
+ if (topic.length > 65535 / 3 && encoder10.encode(topic).length > 65535) return "topic is longer than 65,535 bytes";
58364
58474
  return void 0;
58365
58475
  };
58366
58476
  var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, options3) {
@@ -59330,6 +59440,48 @@ var csvField = (value4) => {
59330
59440
  var toCsv = (rows) => `${rows.map((fields) => fields.map(csvField).join(",")).join("\n")}
59331
59441
  `;
59332
59442
 
59443
+ // src/Output.ts
59444
+ var isJsonMode = (argv2) => argv2.includes("--json");
59445
+ var ResultConsole = Context_exports.Reference("@ot-gateway/gateway/ResultConsole", {
59446
+ defaultValue: () => void 0
59447
+ });
59448
+ var printResult = (text4) => Effect_exports.flatMap(
59449
+ ResultConsole,
59450
+ (results2) => results2 === void 0 ? Console_exports.log(text4) : Effect_exports.sync(() => {
59451
+ results2.log(text4);
59452
+ })
59453
+ );
59454
+ var printJson = (value4) => printResult(JSON.stringify(value4, null, 2));
59455
+ var stderrConsole = (base) => ({
59456
+ assert: (condition, ...args2) => base.assert(condition, ...args2),
59457
+ clear: () => base.clear(),
59458
+ count: (label2) => base.count(label2),
59459
+ countReset: (label2) => base.countReset(label2),
59460
+ debug: (...args2) => base.debug(...args2),
59461
+ dir: (...args2) => base.error(...args2),
59462
+ dirxml: (...args2) => base.error(...args2),
59463
+ error: (...args2) => base.error(...args2),
59464
+ group: (...args2) => base.group(...args2),
59465
+ groupCollapsed: (...args2) => base.groupCollapsed(...args2),
59466
+ groupEnd: () => base.groupEnd(),
59467
+ info: (...args2) => base.error(...args2),
59468
+ log: (...args2) => base.error(...args2),
59469
+ table: (data) => base.error(data),
59470
+ time: (label2) => base.time(label2),
59471
+ timeEnd: (label2) => base.timeEnd(label2),
59472
+ timeLog: (label2, ...args2) => base.timeLog(label2, ...args2),
59473
+ trace: (...args2) => base.trace(...args2),
59474
+ warn: (...args2) => base.warn(...args2)
59475
+ });
59476
+ var isUsageError = (error2) => error2._tag === "ShowHelp" && error2.errors.length > 0;
59477
+ var USAGE_EXIT_CODE = 2;
59478
+ var usageFailure = (error2) => ({
59479
+ ok: false,
59480
+ code: "usage",
59481
+ error: error2.errors.map((each) => each.message).join("; "),
59482
+ hint: `ot-gateway ${[...error2.commandPath.slice(1), "--help"].join(" ")} lists the commands and flags`
59483
+ });
59484
+
59333
59485
  // src/Discover.ts
59334
59486
  var LISTEN = "3 seconds";
59335
59487
  var TRUSTED_SOURCE = "a source you trust (commissioning sheet, device display, DHCP reservation)";
@@ -59468,10 +59620,7 @@ var discoverDrafts = (config, network, options3 = {}) => Effect_exports.gen(func
59468
59620
  const existing = config.devices.map((device) => device.id);
59469
59621
  return draftDevices(described.flat(), existing);
59470
59622
  }).pipe(Effect_exports.scoped);
59471
- var discover = (config, network, options3 = {}) => Effect_exports.flatMap(
59472
- discoverDrafts(config, network, options3),
59473
- (devices) => Console_exports.log(JSON.stringify({ devices }, null, 2))
59474
- );
59623
+ var discover = (config, network, options3 = {}) => Effect_exports.flatMap(discoverDrafts(config, network, options3), (devices) => printJson({ devices }));
59475
59624
  var pointColumn = (point) => slugify(point.name) === point.id && !/^[=+\-@\t\r]/.test(point.name) ? point.name : point.id;
59476
59625
  var draftPointsList = (drafts) => {
59477
59626
  const header = ["device", "point", "unit", "device_instance", "address", "object_type", "object_instance"];
@@ -60616,6 +60765,8 @@ var nextSteps = (path, config, folder = { written: [], kept: [] }) => {
60616
60765
  ];
60617
60766
  const commands2 = [
60618
60767
  ...folderPath === "." ? [] : [[`cd ${folderPath}`, "the gateway's folder"]],
60768
+ // Before anything is started: a wrong URL, port or password shows here, not later as a stale gateway.
60769
+ [`ot-gateway broker${argument}`, `check that ${config.mqtt.url} answers, with a message there and back`],
60619
60770
  ...devices,
60620
60771
  ...compose5 ? [
60621
60772
  ["docker compose up -d", "start it in Docker, restarted after a crash or a reboot"],
@@ -61823,8 +61974,8 @@ var HttpClientError = class extends (/* @__PURE__ */ TaggedError2("HttpClientErr
61823
61974
  var formatReason = (tag2) => tag2.endsWith("Error") ? tag2.slice(0, -5) : tag2;
61824
61975
  var formatMessage = (reason, description, info2) => description ? `${reason}: ${description} (${info2})` : `${reason} error (${info2})`;
61825
61976
  var formatMethodAndUrl = (request3) => `${request3.method} ${redactUrl(request3.url)}`;
61826
- var reasonToJSON = (reason, json3) => ({
61827
- ...json3,
61977
+ var reasonToJSON = (reason, json4) => ({
61978
+ ...json4,
61828
61979
  request: {
61829
61980
  _id: "HttpClientRequest",
61830
61981
  method: reason.request.method,
@@ -69731,7 +69882,7 @@ function makePayloadStreamDecoder(schema2, options3) {
69731
69882
  return (request3) => readBody(request3).pipe(pipeThroughChannel(decode8({
69732
69883
  ignoreEmptyLines: true,
69733
69884
  maxLineBytes
69734
- })), mapEffect2((json3) => decodeElement(json3)), mapError6((error2) => {
69885
+ })), mapEffect2((json4) => decodeElement(json4)), mapError6((error2) => {
69735
69886
  if (HttpApiPayloadTooLarge.is(error2)) return error2;
69736
69887
  if (!isNdjsonError(error2)) return new HttpApiSchemaError({
69737
69888
  kind: "Payload",
@@ -70590,7 +70741,7 @@ function makeStreamBodyDecoder(streamSchema, options3) {
70590
70741
  description: `NDJSON line exceeds maxElementBytes of ${maxElementBytes} bytes`
70591
70742
  })
70592
70743
  });
70593
- }), mapEffect2((json3) => decodeElement(json3)));
70744
+ }), mapEffect2((json4) => decodeElement(json4)));
70594
70745
  }
70595
70746
  const decoder6 = makeSseDecoder(streamSchema, options3);
70596
70747
  return (response, sseOptions) => decodeSseStream(response.stream, streamSchema, decoder6(sseOptions));
@@ -71498,7 +71649,7 @@ var fetchGatewayStatus = (url) => HttpApiClient_exports.make(OtGatewayApi, { bas
71498
71649
  );
71499
71650
  var statusReport = Effect_exports.fn("statusReport")(function* (url, options3 = {}) {
71500
71651
  const status3 = yield* fetchGatewayStatus(url);
71501
- yield* Console_exports.log(options3.json === true ? JSON.stringify(status3, null, 2) : formatStatus(status3));
71652
+ yield* options3.json === true ? printJson(status3) : Console_exports.log(formatStatus(status3));
71502
71653
  });
71503
71654
 
71504
71655
  // src/Broker.ts
@@ -71527,7 +71678,14 @@ var firstDialOf = (client, url) => client.firstDial.pipe(
71527
71678
  duration: DIAL_TIMEOUT,
71528
71679
  orElse: () => Effect_exports.fail(new MqttConnectionError({ message: `no answer within ${DIAL_TIMEOUT}` }))
71529
71680
  }),
71530
- Effect_exports.mapError((error2) => new BrokerCommandError({ message: `could not connect to ${url}: ${error2.message}` }))
71681
+ Effect_exports.mapError(
71682
+ (error2) => (
71683
+ // The socket's message starts with "could not connect" itself: say it once, with the URL.
71684
+ new BrokerCommandError({
71685
+ message: `could not connect to ${url}: ${error2.message.replace(/^could not connect(: )?/, "")}`
71686
+ })
71687
+ )
71688
+ )
71531
71689
  );
71532
71690
  var brokerWarnings = (info2, roundTripMs, topic) => [
71533
71691
  ...info2.protocolVersion === "3.1.1" ? [
@@ -71609,6 +71767,14 @@ var formatMessage2 = (message, at) => {
71609
71767
  const payload = flat.length > MAX_PAYLOAD ? `${flat.slice(0, MAX_PAYLOAD)}\u2026` : flat;
71610
71768
  return `${time2} ${message.retain ? "retained " : ""}${message.topic} ${payload}`;
71611
71769
  };
71770
+ var messageRecord = (message, at) => {
71771
+ let payload = message.payload;
71772
+ try {
71773
+ payload = JSON.parse(message.payload);
71774
+ } catch {
71775
+ }
71776
+ return JSON.stringify({ at: at.toISOString(), topic: message.topic, retained: message.retain, payload });
71777
+ };
71612
71778
  var watch3 = Effect_exports.fn("watch")(function* (config, options3 = {}) {
71613
71779
  const filter14 = options3.topic ?? watchFilter(config);
71614
71780
  yield* brokerClient(config.mqtt, "watch", {
@@ -71616,7 +71782,7 @@ var watch3 = Effect_exports.fn("watch")(function* (config, options3 = {}) {
71616
71782
  onConnect: () => Console_exports.error(
71617
71783
  `watching ${filter14} on ${config.mqtt.url} (${options3.seconds === void 0 ? "Ctrl-C to stop" : `for ${options3.seconds} s`})`
71618
71784
  ),
71619
- onMessage: (message) => Console_exports.log(formatMessage2(message, /* @__PURE__ */ new Date()))
71785
+ onMessage: (message) => options3.json === true ? printResult(messageRecord(message, /* @__PURE__ */ new Date())) : Console_exports.log(formatMessage2(message, /* @__PURE__ */ new Date()))
71620
71786
  });
71621
71787
  yield* Console_exports.error(`connecting to ${config.mqtt.url}\u2026`);
71622
71788
  if (options3.seconds === void 0) return yield* Effect_exports.never;
@@ -75219,8 +75385,8 @@ function jsonReplacer(key5, value4) {
75219
75385
  return value4;
75220
75386
  }
75221
75387
  var jsonBody = (data) => {
75222
- const json3 = JSON.stringify(data);
75223
- return text2(json3.includes("null") || json3.includes('"bytesValue":') ? JSON.stringify(data, jsonReplacer) : json3, "application/json");
75388
+ const json4 = JSON.stringify(data);
75389
+ return text2(json4.includes("null") || json4.includes('"bytesValue":') ? JSON.stringify(data, jsonReplacer) : json4, "application/json");
75224
75390
  };
75225
75391
  var layerJson = /* @__PURE__ */ succeed6(OtlpSerialization, {
75226
75392
  traces: (spans) => jsonBody(spans),
@@ -76379,12 +76545,7 @@ var jsonFlag = Flag_exports.Boolean("json").pipe(
76379
76545
  Flag_exports.withDefault(false)
76380
76546
  );
76381
76547
  var errorText = (error2) => error2 instanceof Error ? error2.message : String(error2);
76382
- var jsonFailure = (json3, fields = {}) => (effect2) => json3 ? effect2.pipe(
76383
- Effect_exports.tapError(
76384
- (error2) => Console_exports.log(JSON.stringify({ ok: false, ...fields, error: errorText(error2) }, null, 2))
76385
- )
76386
- ) : effect2;
76387
- var printJson = (value4) => Console_exports.log(JSON.stringify(value4, null, 2));
76548
+ var jsonFailure = (json4, fields = {}) => (effect2) => json4 ? effect2.pipe(Effect_exports.tapError((error2) => printJson({ ok: false, ...fields, error: errorText(error2) }))) : effect2;
76388
76549
  var dryRunFlag = (description) => Flag_exports.Boolean("dry-run").pipe(Flag_exports.withDescription(description), Flag_exports.withDefault(false));
76389
76550
  var runConfigured = Effect_exports.fn("runConfigured")(function* (config) {
76390
76551
  const version2 = yield* readVersion;
@@ -76419,9 +76580,9 @@ var run9 = Command_exports.make(
76419
76580
  var check2 = Command_exports.make(
76420
76581
  "check",
76421
76582
  { config: configPath, json: jsonFlag },
76422
- ({ config, json: json3 }) => loadConfig(config).pipe(
76423
- Effect_exports.flatMap((decoded) => json3 ? printJson(configSummary(decoded)) : Console_exports.log(describeConfig(decoded))),
76424
- jsonFailure(json3, { path: config })
76583
+ ({ config, json: json4 }) => loadConfig(config).pipe(
76584
+ Effect_exports.flatMap((decoded) => json4 ? printJson(configSummary(decoded)) : Console_exports.log(describeConfig(decoded))),
76585
+ jsonFailure(json4, { path: config })
76425
76586
  )
76426
76587
  ).pipe(Command_exports.withDescription("Validate a config without connecting to anything; lists every mistake with its path"));
76427
76588
  var discoverCommand = Command_exports.make(
@@ -76441,10 +76602,10 @@ var discoverCommand = Command_exports.make(
76441
76602
  json: jsonFlag
76442
76603
  },
76443
76604
  // The draft is JSON already; --json makes a failure JSON too.
76444
- ({ config, pointsList, address, json: json3 }) => Effect_exports.flatMap(loadConfig(config), (decoded) => {
76605
+ ({ config, pointsList, address, json: json4 }) => Effect_exports.flatMap(loadConfig(config), (decoded) => {
76445
76606
  const options3 = { address: Option_exports.getOrUndefined(address) };
76446
76607
  return Option_exports.isSome(pointsList) ? discoverToPointsList(decoded, pointsList.value, void 0, options3) : discover(decoded, void 0, options3);
76447
- }).pipe(jsonFailure(json3, { path: config }))
76608
+ }).pipe(jsonFailure(json4, { path: config }))
76448
76609
  ).pipe(
76449
76610
  Command_exports.withDescription(
76450
76611
  "Find BACnet devices through the config's bacnet settings and print a draft of their devices entries, read-only"
@@ -76517,9 +76678,9 @@ var init2 = Command_exports.make(
76517
76678
  Flag_exports.withDefault(false)
76518
76679
  )
76519
76680
  },
76520
- ({ directory, json: json3, ...given }) => Effect_exports.gen(function* () {
76521
- const interactive = !json3 && isInteractive(given.yes, process.stdin.isTTY);
76522
- if (!given.yes && !json3 && !interactive) {
76681
+ ({ directory, json: json4, ...given }) => Effect_exports.gen(function* () {
76682
+ const interactive = !json4 && isInteractive(given.yes, process.stdin.isTTY);
76683
+ if (!given.yes && !json4 && !interactive) {
76523
76684
  yield* Console_exports.error(
76524
76685
  "no terminal, so init asks nothing: the flags answer and the defaults fill the rest (--help lists the flags)"
76525
76686
  );
@@ -76530,7 +76691,7 @@ var init2 = Command_exports.make(
76530
76691
  if (written === void 0) return yield* Console_exports.log(`kept ${config} as it is`);
76531
76692
  const folder = yield* writeFolderFiles(config, written, { dryRun: flags.dryRun });
76532
76693
  const files = { ...folder, written: [config, ...folder.written] };
76533
- if (json3) {
76694
+ if (json4) {
76534
76695
  return yield* printJson({
76535
76696
  ...configSummary(written),
76536
76697
  dryRun: flags.dryRun,
@@ -76551,7 +76712,7 @@ var init2 = Command_exports.make(
76551
76712
  yield* Console_exports.log(describeConfig(written));
76552
76713
  yield* Console_exports.log(nextSteps(config, written, files));
76553
76714
  }).pipe(
76554
- jsonFailure(json3),
76715
+ jsonFailure(json4),
76555
76716
  Effect_exports.catchTag(
76556
76717
  "QuitError",
76557
76718
  () => Console_exports.error("init cancelled, nothing written").pipe(Effect_exports.andThen(Effect_exports.sync(() => process.exitCode = 1)))
@@ -76584,14 +76745,14 @@ var importCommand = Command_exports.make(
76584
76745
  dryRun: dryRunFlag("Check the list and print its devices instead of adding them to the config"),
76585
76746
  json: jsonFlag
76586
76747
  },
76587
- ({ list, config, dryRun, json: json3 }) => Effect_exports.gen(function* () {
76748
+ ({ list, config, dryRun, json: json4 }) => Effect_exports.gen(function* () {
76588
76749
  const { added, config: written } = yield* importPointsList(list, config, { dryRun });
76589
76750
  const points2 = added.reduce((total, device) => total + device.points.length, 0);
76590
- if (json3) return yield* printJson({ ok: true, dryRun, path: config, points: points2, devices: added });
76751
+ if (json4) return yield* printJson({ ok: true, dryRun, path: config, points: points2, devices: added });
76591
76752
  if (written === void 0) return yield* printJson({ devices: added });
76592
76753
  yield* Console_exports.log(`added ${added.length} device(s) with ${points2} point(s) to ${config}, none writable`);
76593
76754
  yield* Console_exports.log(describeConfig(written));
76594
- }).pipe(jsonFailure(json3, { path: config }))
76755
+ }).pipe(jsonFailure(json4, { path: config }))
76595
76756
  ).pipe(
76596
76757
  Command_exports.withDescription(
76597
76758
  "Add the devices of a points list (CSV: device, point, host, register, type, unit, \u2026) to the config"
@@ -76604,7 +76765,7 @@ var importCommand = Command_exports.make(
76604
76765
  var schemaCommand = Command_exports.make(
76605
76766
  "schema",
76606
76767
  { json: jsonFlag },
76607
- ({ json: json3 }) => Console_exports.log(json3 ? JSON.stringify(pointsListSchema(), null, 2) : describePointsListSchema())
76768
+ ({ json: json4 }) => json4 ? printJson(pointsListSchema()) : Console_exports.log(describePointsListSchema())
76608
76769
  ).pipe(Command_exports.withDescription("The points list's columns, rules and allowed values"));
76609
76770
  var templateCommand = Command_exports.make(
76610
76771
  "template",
@@ -76632,9 +76793,9 @@ var fromEdeCommand = Command_exports.make(
76632
76793
  var profilesList = Command_exports.make(
76633
76794
  "list",
76634
76795
  { json: jsonFlag },
76635
- ({ json: json3 }) => Effect_exports.gen(function* () {
76796
+ ({ json: json4 }) => Effect_exports.gen(function* () {
76636
76797
  const profiles2 = yield* libraryProfiles();
76637
- if (json3) {
76798
+ if (json4) {
76638
76799
  return yield* printJson(
76639
76800
  profiles2.map(({ id: id2, vendor, model, verified, points: points2 }) => ({
76640
76801
  id: id2,
@@ -76651,7 +76812,7 @@ var profilesList = Command_exports.make(
76651
76812
  (profile) => `${profile.id.padEnd(width3)}${profile.vendor} ${profile.model}, ${profile.points.length} points${profile.verified ? "" : ", from its register map (not yet checked on a device)"}`
76652
76813
  ).join("\n")
76653
76814
  );
76654
- }).pipe(jsonFailure(json3))
76815
+ }).pipe(jsonFailure(json4))
76655
76816
  ).pipe(Command_exports.withDescription("The device profiles a points list can name in its profile column"));
76656
76817
  var profilesShow = Command_exports.make(
76657
76818
  "show",
@@ -76659,19 +76820,21 @@ var profilesShow = Command_exports.make(
76659
76820
  profile: Argument_exports.String("profile").pipe(Argument_exports.withDescription("A profile id, or a path ending in .json")),
76660
76821
  json: jsonFlag
76661
76822
  },
76662
- ({ profile, json: json3 }) => Effect_exports.gen(function* () {
76823
+ ({ profile, json: json4 }) => Effect_exports.gen(function* () {
76663
76824
  const found = yield* resolveProfile(profile, { relativeTo: process.cwd() });
76664
- if (json3) return yield* printJson(found);
76825
+ if (json4) return yield* printJson(found);
76665
76826
  yield* Console_exports.log(describeProfile(found));
76666
- }).pipe(jsonFailure(json3))
76827
+ }).pipe(jsonFailure(json4))
76667
76828
  ).pipe(
76668
76829
  Command_exports.withDescription("One profile's points: names, registers, types and units"),
76830
+ // `get`, as other CLIs name reading one thing.
76831
+ Command_exports.withAlias("get"),
76669
76832
  Command_exports.withExamples([{ command: "ot-gateway profiles show eastron-sdm630", description: "The SDM630's points" }])
76670
76833
  );
76671
76834
  var profilesSchema = Command_exports.make(
76672
76835
  "schema",
76673
76836
  { json: jsonFlag },
76674
- ({ json: json3 }) => Console_exports.log(json3 ? JSON.stringify(profileJsonSchema(), null, 2) : describeProfileFormat())
76837
+ ({ json: json4 }) => json4 ? printJson(profileJsonSchema()) : Console_exports.log(describeProfileFormat())
76675
76838
  ).pipe(Command_exports.withDescription("The profile format, to write one from a register map"));
76676
76839
  var profiles = Command_exports.make("profiles").pipe(
76677
76840
  Command_exports.withDescription("Device profiles: a Modbus model's registers, named once and reused by points lists"),
@@ -76696,27 +76859,32 @@ var watchCommand = Command_exports.make(
76696
76859
  (seconds3) => `--seconds takes 1 or more, not ${seconds3}`
76697
76860
  ),
76698
76861
  Flag_exports.optional
76862
+ ),
76863
+ json: Flag_exports.Boolean("json").pipe(
76864
+ Flag_exports.withDescription("One JSON object per message and line (NDJSON): at, topic, retained, payload"),
76865
+ Flag_exports.withDefault(false)
76699
76866
  )
76700
76867
  },
76701
- ({ config, topic, seconds: seconds3 }) => Effect_exports.flatMap(
76868
+ ({ config, topic, seconds: seconds3, json: json4 }) => Effect_exports.flatMap(
76702
76869
  loadConfig(config),
76703
- (decoded) => watch3(decoded, { topic: Option_exports.getOrUndefined(topic), seconds: Option_exports.getOrUndefined(seconds3) })
76704
- )
76870
+ (decoded) => watch3(decoded, { topic: Option_exports.getOrUndefined(topic), seconds: Option_exports.getOrUndefined(seconds3), json: json4 })
76871
+ ).pipe(jsonFailure(json4, { path: config }))
76705
76872
  ).pipe(
76706
76873
  Command_exports.withDescription("Print what arrives at the config's broker under its site and building, as it arrives"),
76707
76874
  Command_exports.withExamples([
76708
76875
  { command: "ot-gateway watch", description: "Watch the broker in ot-gateway.json" },
76709
76876
  { command: "ot-gateway watch --topic 'my-site/main/ahu-1/#'", description: "Only one device" },
76710
- { command: "ot-gateway watch --seconds 10", description: "Ten seconds of it, then stop" }
76877
+ { command: "ot-gateway watch --seconds 10", description: "Ten seconds of it, then stop" },
76878
+ { command: "ot-gateway watch --seconds 10 --json", description: "The same as JSON lines, for scripts and agents" }
76711
76879
  ])
76712
76880
  );
76713
76881
  var brokerCommand = Command_exports.make(
76714
76882
  "broker",
76715
76883
  { config: configPath, json: jsonFlag },
76716
- ({ config, json: json3 }) => loadConfig(config).pipe(
76884
+ ({ config, json: json4 }) => loadConfig(config).pipe(
76717
76885
  Effect_exports.flatMap(checkBroker),
76718
- Effect_exports.flatMap((report) => json3 ? printJson(report) : Console_exports.log(formatBrokerReport(report))),
76719
- jsonFailure(json3, { path: config })
76886
+ Effect_exports.flatMap((report) => json4 ? printJson(report) : Console_exports.log(formatBrokerReport(report))),
76887
+ jsonFailure(json4, { path: config })
76720
76888
  )
76721
76889
  ).pipe(
76722
76890
  Command_exports.withDescription(
@@ -76754,10 +76922,10 @@ var publishCommand = Command_exports.make(
76754
76922
  ),
76755
76923
  json: jsonFlag
76756
76924
  },
76757
- ({ topic, payload, config, retain, qos, json: json3 }) => loadConfig(config).pipe(
76925
+ ({ topic, payload, config, retain, qos, json: json4 }) => loadConfig(config).pipe(
76758
76926
  Effect_exports.flatMap((decoded) => publishOnce(decoded, topic, payload, { retain, qos })),
76759
- Effect_exports.flatMap((result4) => json3 ? printJson(result4) : Console_exports.log(formatPublished(result4))),
76760
- jsonFailure(json3, { topic })
76927
+ Effect_exports.flatMap((result4) => json4 ? printJson(result4) : Console_exports.log(formatPublished(result4))),
76928
+ jsonFailure(json4, { topic })
76761
76929
  )
76762
76930
  ).pipe(
76763
76931
  Command_exports.withDescription("Send one message to the config's broker, as the gateway's user"),
@@ -76778,10 +76946,10 @@ var status2 = Command_exports.make(
76778
76946
  ),
76779
76947
  json: jsonFlag
76780
76948
  },
76781
- ({ url, json: json3 }) => statusReport(url, { json: json3 }).pipe(jsonFailure(json3, { url }))
76949
+ ({ url, json: json4 }) => statusReport(url, { json: json4 }).pipe(jsonFailure(json4, { url }))
76782
76950
  ).pipe(Command_exports.withDescription("The running gateway's status: its broker, buffer and one line per device"));
76783
76951
  var rootDescription = [
76784
- "OT Gateway: Modbus TCP and BACnet/IP in, MQTT 5 out, safe commands back",
76952
+ "OT Gateway: Modbus TCP and BACnet/IP in, MQTT 5 or 3.1.1 out, safe commands back",
76785
76953
  "",
76786
76954
  " For AI agents: nothing asks without a terminal, and --json prints results and failures as JSON.",
76787
76955
  " points schema --json the points list's columns: translate any list or EDE file into it",
@@ -76823,19 +76991,28 @@ var subcommands = /* @__PURE__ */ new Set([
76823
76991
  "publish",
76824
76992
  "status"
76825
76993
  ]);
76826
- var toCliArgs = (argv) => {
76827
- const [first] = argv;
76994
+ var toCliArgs = (argv2) => {
76995
+ const [first] = argv2;
76828
76996
  if (first !== void 0 && (subcommands.has(first) || first.startsWith("-") && !legacyFlags.has(first))) {
76829
- return argv;
76997
+ return argv2;
76998
+ }
76999
+ if (first !== void 0 && !legacyFlags.has(first) && !looksLikePath(first) && !argv2.some((arg) => legacyFlags.has(arg))) {
77000
+ return argv2;
76830
77001
  }
76831
77002
  for (const flag of legacyFlags) {
76832
- if (argv.includes(flag)) return [flag.slice(2), ...argv.filter((arg) => arg !== flag)];
77003
+ if (argv2.includes(flag)) return [flag.slice(2), ...argv2.filter((arg) => arg !== flag)];
76833
77004
  }
76834
- return ["run", ...argv];
77005
+ return ["run", ...argv2];
76835
77006
  };
76836
77007
  var legacyFlags = /* @__PURE__ */ new Set(["--check", "--discover"]);
77008
+ var looksLikePath = (arg) => arg.includes("/") || arg.includes("\\") || arg.includes(".");
76837
77009
  var cliVersion = (version2) => version2.replace(/^v(?=\d)/, "");
76838
- var runCli = (argv) => Effect_exports.flatMap(readVersion, (version2) => Command_exports.runWith(cli, { version: cliVersion(version2) })(toCliArgs(argv)));
77010
+ var runCli = (argv2) => {
77011
+ const args2 = toCliArgs(argv2);
77012
+ const program = Effect_exports.flatMap(readVersion, (version2) => Command_exports.runWith(cli, { version: cliVersion(version2) })(args2));
77013
+ return longRunning.has(args2[0] ?? "") ? program : Effect_exports.provideService(program, References_exports.MinimumLogLevel, "Warn");
77014
+ };
77015
+ var longRunning = /* @__PURE__ */ new Set(["run", "demo"]);
76839
77016
 
76840
77017
  // src/EnvFile.ts
76841
77018
  import { readFileSync } from "node:fs";
@@ -76858,6 +77035,12 @@ var loadEnvFile = (file3 = envFileName, env = process.env) => {
76858
77035
  // src/Shutdown.ts
76859
77036
  var gatewayTeardown = (exit3, onExit5) => {
76860
77037
  if (Exit_exports.isFailure(exit3) && Cause_exports.hasInterruptsOnly(exit3.cause)) return onExit5(0);
77038
+ if (Exit_exports.isFailure(exit3)) {
77039
+ const error2 = Cause_exports.findError(exit3.cause);
77040
+ if (Result_exports.isSuccess(error2) && CliError_exports.isCliError(error2.success) && isUsageError(error2.success)) {
77041
+ return onExit5(USAGE_EXIT_CODE);
77042
+ }
77043
+ }
76861
77044
  return Runtime_exports.defaultTeardown(exit3, onExit5);
76862
77045
  };
76863
77046
 
@@ -76867,15 +77050,23 @@ var reportFailure = (cause) => {
76867
77050
  if (Cause_exports.hasInterruptsOnly(cause)) return Effect_exports.void;
76868
77051
  const error2 = Cause_exports.findError(cause);
76869
77052
  if (Result_exports.isFailure(error2) || Cause_exports.hasDies(cause)) return Effect_exports.logError(cause);
76870
- if (CliError_exports.isCliError(error2.success)) return Effect_exports.void;
76871
- return Effect_exports.logError(error2.success.message);
77053
+ if (CliError_exports.isCliError(error2.success)) {
77054
+ return json3 && isUsageError(error2.success) ? printJson(usageFailure(error2.success)) : Effect_exports.void;
77055
+ }
77056
+ return json3 ? Effect_exports.void : Effect_exports.logError(error2.success.message);
76872
77057
  };
76873
77058
  loadEnvFile();
76874
77059
  var extraEnvFile = process.env["OT_GATEWAY_ENV_FILE"];
76875
77060
  if (extraEnvFile !== void 0 && extraEnvFile !== "") loadEnvFile(extraEnvFile);
76876
- var program = runCli(process.argv.slice(2));
76877
- program.pipe(
77061
+ var argv = process.argv.slice(2);
77062
+ var json3 = isJsonMode(argv);
77063
+ runCli(argv).pipe(
76878
77064
  Effect_exports.tapCause(reportFailure),
77065
+ // --json: stdout is the JSON result alone (Output.ts), so help, banners and progress go to stderr.
77066
+ json3 ? (effect2) => effect2.pipe(
77067
+ Effect_exports.updateService(Console_exports.Console, stderrConsole),
77068
+ Effect_exports.provideService(ResultConsole, globalThis.console)
77069
+ ) : identity,
76879
77070
  // Logs, the final failure among them, go to stderr: stdout is for results, so `check --json | jq` gets JSON only.
76880
77071
  Effect_exports.provideService(Logger_exports.LogToStderr, true),
76881
77072
  Effect_exports.provide(layer11),