@openrobops/iso21423 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +358 -2
  2. package/dist/ccs-CU8XD5sl.d.cts +69 -0
  3. package/dist/ccs-CU8XD5sl.d.ts +69 -0
  4. package/dist/chunk-3JNSIJSX.js +31 -0
  5. package/dist/chunk-3JNSIJSX.js.map +1 -0
  6. package/dist/chunk-5ZIUSUHF.js +55 -0
  7. package/dist/chunk-5ZIUSUHF.js.map +1 -0
  8. package/dist/chunk-DMJ6T3RX.js +445 -0
  9. package/dist/chunk-DMJ6T3RX.js.map +1 -0
  10. package/dist/chunk-GPNR37CI.js +1915 -0
  11. package/dist/chunk-GPNR37CI.js.map +1 -0
  12. package/dist/chunk-JDO725KR.js +210 -0
  13. package/dist/chunk-JDO725KR.js.map +1 -0
  14. package/dist/chunk-JIYCTQXR.js +1 -0
  15. package/dist/chunk-JIYCTQXR.js.map +1 -0
  16. package/dist/chunk-JLUENXGS.js +48 -0
  17. package/dist/chunk-JLUENXGS.js.map +1 -0
  18. package/dist/chunk-JQAMNFAF.js +1 -0
  19. package/dist/chunk-JQAMNFAF.js.map +1 -0
  20. package/dist/chunk-LTPOAVGF.js +44 -0
  21. package/dist/chunk-LTPOAVGF.js.map +1 -0
  22. package/dist/chunk-ODBIFZN3.js +65 -0
  23. package/dist/chunk-ODBIFZN3.js.map +1 -0
  24. package/dist/chunk-OH2DOPKJ.js +107 -0
  25. package/dist/chunk-OH2DOPKJ.js.map +1 -0
  26. package/dist/chunk-QAA44UNO.js +1 -0
  27. package/dist/chunk-QAA44UNO.js.map +1 -0
  28. package/dist/chunk-RD7PYTIT.js +107 -0
  29. package/dist/chunk-RD7PYTIT.js.map +1 -0
  30. package/dist/chunk-UJC46NTA.js +13 -0
  31. package/dist/chunk-UJC46NTA.js.map +1 -0
  32. package/dist/chunk-UW6WTEPT.js +293 -0
  33. package/dist/chunk-UW6WTEPT.js.map +1 -0
  34. package/dist/chunk-W7DIDPTG.js +1 -0
  35. package/dist/chunk-W7DIDPTG.js.map +1 -0
  36. package/dist/core.cjs +2874 -0
  37. package/dist/core.cjs.map +1 -0
  38. package/dist/core.d.cts +996 -0
  39. package/dist/core.d.ts +996 -0
  40. package/dist/core.js +59 -0
  41. package/dist/core.js.map +1 -0
  42. package/dist/gateway.cjs +2937 -0
  43. package/dist/gateway.cjs.map +1 -0
  44. package/dist/gateway.d.cts +165 -0
  45. package/dist/gateway.d.ts +165 -0
  46. package/dist/gateway.js +21 -0
  47. package/dist/gateway.js.map +1 -0
  48. package/dist/geometry.cjs +98 -0
  49. package/dist/geometry.cjs.map +1 -0
  50. package/dist/geometry.d.cts +38 -0
  51. package/dist/geometry.d.ts +38 -0
  52. package/dist/geometry.js +14 -0
  53. package/dist/geometry.js.map +1 -0
  54. package/dist/identity-BGr2FJmC.d.cts +258 -0
  55. package/dist/identity-Bw8Dik5S.d.ts +258 -0
  56. package/dist/index.cjs +3327 -0
  57. package/dist/index.cjs.map +1 -0
  58. package/dist/index.d.cts +118 -0
  59. package/dist/index.d.ts +118 -0
  60. package/dist/index.js +193 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/schema.cjs +375 -0
  63. package/dist/schema.cjs.map +1 -0
  64. package/dist/schema.d.cts +28 -0
  65. package/dist/schema.d.ts +28 -0
  66. package/dist/schema.js +14 -0
  67. package/dist/schema.js.map +1 -0
  68. package/dist/session-RV32MFpV.d.cts +139 -0
  69. package/dist/session-ueiESY7Y.d.ts +139 -0
  70. package/dist/session.cjs +855 -0
  71. package/dist/session.cjs.map +1 -0
  72. package/dist/session.d.cts +94 -0
  73. package/dist/session.d.ts +94 -0
  74. package/dist/session.js +20 -0
  75. package/dist/session.js.map +1 -0
  76. package/dist/testing.cjs +205 -0
  77. package/dist/testing.cjs.map +1 -0
  78. package/dist/testing.d.cts +94 -0
  79. package/dist/testing.d.ts +94 -0
  80. package/dist/testing.js +169 -0
  81. package/dist/testing.js.map +1 -0
  82. package/dist/topics-BiVeZyTW.d.cts +43 -0
  83. package/dist/topics-BiVeZyTW.d.ts +43 -0
  84. package/dist/topics.cjs +134 -0
  85. package/dist/topics.cjs.map +1 -0
  86. package/dist/topics.d.cts +41 -0
  87. package/dist/topics.d.ts +41 -0
  88. package/dist/topics.js +30 -0
  89. package/dist/topics.js.map +1 -0
  90. package/dist/transport-BT4AjTn9.d.cts +61 -0
  91. package/dist/transport-BT4AjTn9.d.ts +61 -0
  92. package/dist/types.cjs +186 -0
  93. package/dist/types.cjs.map +1 -0
  94. package/dist/types.d.cts +83 -0
  95. package/dist/types.d.ts +83 -0
  96. package/dist/types.js +50 -0
  97. package/dist/types.js.map +1 -0
  98. package/dist/validators-Be0ce1b8.d.cts +29 -0
  99. package/dist/validators-Be0ce1b8.d.ts +29 -0
  100. package/package.json +48 -4
@@ -0,0 +1,855 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/session/index.ts
31
+ var session_exports = {};
32
+ __export(session_exports, {
33
+ Iso21423Session: () => Iso21423Session,
34
+ RateGate: () => RateGate,
35
+ createMqttTransport: () => createMqttTransport,
36
+ wrapMqttClient: () => wrapMqttClient
37
+ });
38
+ module.exports = __toCommonJS(session_exports);
39
+
40
+ // src/errors.ts
41
+ var Iso21423Error = class extends Error {
42
+ constructor(message) {
43
+ super(message);
44
+ this.name = new.target.name;
45
+ }
46
+ };
47
+ var ValidationError = class extends Iso21423Error {
48
+ constructor(message, errors) {
49
+ super(message);
50
+ this.errors = errors;
51
+ }
52
+ errors;
53
+ };
54
+ var BrokerUnavailable = class extends Iso21423Error {
55
+ };
56
+ var AuthorizationDenied = class extends Iso21423Error {
57
+ constructor(message, topic) {
58
+ super(message);
59
+ this.topic = topic;
60
+ }
61
+ topic;
62
+ };
63
+
64
+ // src/session/rateGate.ts
65
+ var RateGate = class {
66
+ intervalMs;
67
+ lastEmit = -Infinity;
68
+ pending;
69
+ timer;
70
+ constructor(maxHz) {
71
+ if (!(maxHz > 0) || !Number.isFinite(maxHz)) {
72
+ throw new Iso21423Error(`RateGate requires a finite maxHz > 0, got ${maxHz}`);
73
+ }
74
+ this.intervalMs = 1e3 / maxHz;
75
+ }
76
+ /** Offers a value for emission; emits now if the interval has elapsed, else schedules a trailing emit and discards any previously-pending value. */
77
+ offer(value, emit) {
78
+ const now = Date.now();
79
+ if (now - this.lastEmit >= this.intervalMs) {
80
+ this.lastEmit = now;
81
+ emit(value);
82
+ return;
83
+ }
84
+ this.pending = { value, emit };
85
+ if (this.timer === void 0) {
86
+ const wait = this.intervalMs - (now - this.lastEmit);
87
+ this.timer = setTimeout(() => {
88
+ this.timer = void 0;
89
+ const p = this.pending;
90
+ this.pending = void 0;
91
+ if (p) {
92
+ this.lastEmit = Date.now();
93
+ p.emit(p.value);
94
+ }
95
+ }, wait);
96
+ }
97
+ }
98
+ /** Cancels any pending trailing emit. The pending value is dropped, not flushed. */
99
+ dispose() {
100
+ if (this.timer !== void 0) clearTimeout(this.timer);
101
+ this.timer = void 0;
102
+ this.pending = void 0;
103
+ }
104
+ };
105
+
106
+ // src/topics/resources.ts
107
+ var RESOURCE_CONFIG = {
108
+ identity: { qos: 1, retain: true },
109
+ status: { qos: 1, retain: true },
110
+ batteryStatus: { qos: 0, retain: true },
111
+ footprint: { qos: 1, retain: true },
112
+ odometry: { qos: 0, retain: false, minHz: 0.5, maxHz: 30 },
113
+ localTrajectory: { qos: 0, retain: false, minHz: 1, maxHz: 10 },
114
+ globalPath: { qos: 1, retain: true },
115
+ globalPlan: { qos: 1, retain: true },
116
+ request: { qos: 2, retain: true },
117
+ requestStatus: { qos: 2, retain: true },
118
+ activeRequestsStatus: { qos: 1, retain: true },
119
+ disconnection: { qos: 1, retain: true }
120
+ // B.4 LWT parameters
121
+ };
122
+ var STANDARD_RESOURCES = new Set(Object.keys(RESOURCE_CONFIG));
123
+
124
+ // src/types/constants.ts
125
+ var ROOT_NAMESPACE = "/ISO_21423/v1";
126
+ var KNOWN_OPERATING_STATES = [
127
+ "STOP_CATEGORY_0",
128
+ "STOP_CATEGORY_1",
129
+ "STOP_CATEGORY_2",
130
+ "PAUSED",
131
+ "WAIT_FOR_RESET",
132
+ "MAPPING",
133
+ "LOST",
134
+ "WAIT_FOR_ATTACHMENT",
135
+ "WAIT_FOR_EVENT",
136
+ "BLOCKED",
137
+ "ATTACHMENT_ACTIVE",
138
+ "STOPPED",
139
+ "DOCKING",
140
+ "SLOWING",
141
+ "ACCELERATING",
142
+ "LEFT_TURN",
143
+ "RIGHT_TURN",
144
+ "REVERSE",
145
+ "FORWARD",
146
+ "LINE_FOLLOWING",
147
+ "CHARGING",
148
+ "LOW_BATTERY",
149
+ "IDLE",
150
+ "PARKED",
151
+ "OFFLINE",
152
+ "READY",
153
+ "NOT_READY",
154
+ "MODE_AUTO",
155
+ "MODE_SEMIAUTO",
156
+ "MODE_TELEOP",
157
+ "MODE_MANUAL",
158
+ "MODE_MAINTENANCE"
159
+ ];
160
+ var LOST_CONNECTION_STATE = "LOST_CONNECTION";
161
+
162
+ // src/topics/topics.ts
163
+ function topicFor(ref, resource) {
164
+ return `${ROOT_NAMESPACE}/${ref.entityType}/${ref.entityUuid}/${resource}`;
165
+ }
166
+ function disconnectionTopic(ref) {
167
+ return topicFor(ref, "disconnection");
168
+ }
169
+ function parseTopic(topic) {
170
+ if (!topic.startsWith(`${ROOT_NAMESPACE}/`)) return null;
171
+ const rest = topic.slice(ROOT_NAMESPACE.length + 1).split("/");
172
+ const [entityType, entityUuid, resource, ...tail] = rest;
173
+ if (!entityType || !entityUuid || !resource) return null;
174
+ if (resource === "request" && tail.length >= 1) {
175
+ const [requestUuid, maybeStatus] = tail;
176
+ if (!requestUuid || maybeStatus !== void 0 && maybeStatus !== "status" || tail.length > 2) return null;
177
+ return { entityType, entityUuid, resource, requestUuid, isRequestStatus: maybeStatus === "status" };
178
+ }
179
+ if (tail.length > 0) return null;
180
+ return { entityType, entityUuid, resource, isRequestStatus: false };
181
+ }
182
+ function topicFilterMatches(filter, topic) {
183
+ const f = filter.split("/");
184
+ const t = topic.split("/");
185
+ for (let i = 0; i < f.length; i++) {
186
+ const seg = f[i];
187
+ if (seg === "#") return true;
188
+ if (i >= t.length) return false;
189
+ if (seg !== "+" && seg !== t[i]) return false;
190
+ }
191
+ return f.length === t.length;
192
+ }
193
+
194
+ // src/types/common.ts
195
+ function nowTimestamp(date = /* @__PURE__ */ new Date()) {
196
+ return date.toISOString();
197
+ }
198
+
199
+ // src/schema/validators.ts
200
+ var import__ = require("ajv/dist/2020.js");
201
+ var import_ajv_formats = __toESM(require("ajv-formats"), 1);
202
+
203
+ // src/schema/iso21423.schema.json
204
+ var iso21423_schema_default = {
205
+ $schema: "https://json-schema.org/draft/2020-12/schema",
206
+ $id: "https://openrobops.org/schemas/iso21423/v1.json",
207
+ $defs: {
208
+ uuid: { type: "string", pattern: "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$" },
209
+ timestamp: { type: "string", format: "date-time" },
210
+ point: {
211
+ type: "object",
212
+ required: ["x", "y"],
213
+ properties: { x: { type: "number" }, y: { type: "number" } }
214
+ },
215
+ locationPoint: {
216
+ type: "object",
217
+ required: ["ccsId", "x", "y", "z"],
218
+ properties: {
219
+ ccsId: { $ref: "#/$defs/uuid" },
220
+ x: { type: "number" },
221
+ y: { type: "number" },
222
+ z: { type: "number" }
223
+ }
224
+ },
225
+ orientation: {
226
+ type: "object",
227
+ required: ["yaw", "pitch", "roll"],
228
+ properties: { yaw: { type: "number" }, pitch: { type: "number" }, roll: { type: "number" } }
229
+ },
230
+ capabilities: {
231
+ type: "object",
232
+ required: ["provides", "accepts"],
233
+ properties: {
234
+ provides: { type: "array", items: { type: "string" } },
235
+ accepts: {
236
+ type: "object",
237
+ required: ["requests"],
238
+ properties: { requests: { type: "array", items: { type: "string" } } }
239
+ },
240
+ manages: { type: "array", items: { $ref: "#/$defs/uuid" } },
241
+ managedBy: { $ref: "#/$defs/uuid" }
242
+ }
243
+ },
244
+ softwareVersion: {
245
+ type: "object",
246
+ required: ["moduleName", "moduleVersion"],
247
+ properties: { moduleName: { type: "string" }, moduleVersion: { type: "string" } }
248
+ },
249
+ locationPointStamped: {
250
+ type: "object",
251
+ required: ["timestamp", "locationPoint"],
252
+ properties: {
253
+ timestamp: { $ref: "#/$defs/timestamp" },
254
+ locationPoint: { $ref: "#/$defs/locationPoint" }
255
+ }
256
+ },
257
+ requestDetail: {
258
+ type: "object",
259
+ required: ["type", "version"],
260
+ properties: {
261
+ type: { type: "string" },
262
+ version: { type: "string" },
263
+ format: { type: "string" },
264
+ blocking: { type: "boolean" },
265
+ atomic: { type: "boolean" },
266
+ properties: { type: "object" }
267
+ }
268
+ },
269
+ requestDetailStatus: {
270
+ type: "object",
271
+ required: ["type", "version", "status"],
272
+ properties: {
273
+ type: { type: "string" },
274
+ version: { type: "string" },
275
+ blocking: { type: "boolean" },
276
+ status: {
277
+ type: "object",
278
+ required: ["code"],
279
+ properties: {
280
+ code: { enum: ["RECEIVED", "ACCEPTED", "EXECUTING", "CANCELED", "SUCCEEDED", "ABORTED"] },
281
+ reason: { type: "string" },
282
+ message: { type: "string" }
283
+ }
284
+ },
285
+ properties: { type: "object" }
286
+ }
287
+ },
288
+ entityIdentity: {
289
+ type: "object",
290
+ required: ["id", "timestamp", "entityType", "manufacturerName", "capabilities", "details"],
291
+ properties: {
292
+ id: { $ref: "#/$defs/uuid" },
293
+ timestamp: { $ref: "#/$defs/timestamp" },
294
+ entityType: { type: "string" },
295
+ manufacturerName: { type: "string" },
296
+ iso21423Version: { type: "string" },
297
+ capabilities: { $ref: "#/$defs/capabilities" },
298
+ details: { type: "object" }
299
+ }
300
+ },
301
+ entityStatus: {
302
+ type: "object",
303
+ required: ["entityId", "timestamp", "states"],
304
+ properties: {
305
+ entityId: { $ref: "#/$defs/uuid" },
306
+ timestamp: { $ref: "#/$defs/timestamp" },
307
+ states: { type: "array", items: { type: "string", pattern: "^[A-Z0-9_]+$" } },
308
+ disabledCapabilities: { $ref: "#/$defs/capabilities" }
309
+ }
310
+ },
311
+ batteryStatus: {
312
+ type: "object",
313
+ required: ["timestamp", "batterySoc"],
314
+ properties: {
315
+ timestamp: { $ref: "#/$defs/timestamp" },
316
+ batterySoc: { type: "number", minimum: 0, maximum: 1 },
317
+ batteryHealth: { type: "string" },
318
+ batteryTemperature: { type: "number" },
319
+ batteryVoltage: { type: "number" },
320
+ batteryCurrent: { type: "number" },
321
+ batteryChargingState: { type: "string" }
322
+ }
323
+ },
324
+ odometry: {
325
+ type: "object",
326
+ required: ["timestamp", "pose", "velocity"],
327
+ properties: {
328
+ timestamp: { $ref: "#/$defs/timestamp" },
329
+ pose: {
330
+ type: "object",
331
+ required: ["locationPoint", "orientation"],
332
+ properties: {
333
+ locationPoint: { $ref: "#/$defs/locationPoint" },
334
+ orientation: { $ref: "#/$defs/orientation" }
335
+ }
336
+ },
337
+ velocity: {
338
+ type: "object",
339
+ required: ["linear", "angular"],
340
+ properties: { linear: { type: "number" }, angular: { type: "number" } }
341
+ }
342
+ }
343
+ },
344
+ localTrajectory: {
345
+ type: "object",
346
+ required: ["timestamp", "localTrajectory"],
347
+ properties: {
348
+ timestamp: { $ref: "#/$defs/timestamp" },
349
+ localTrajectory: { type: "array", items: { $ref: "#/$defs/locationPointStamped" } }
350
+ }
351
+ },
352
+ globalPath: {
353
+ type: "object",
354
+ required: ["timestamp", "globalPath"],
355
+ properties: {
356
+ timestamp: { $ref: "#/$defs/timestamp" },
357
+ globalPath: {
358
+ type: "object",
359
+ required: ["degree", "controlPoints", "knots"],
360
+ properties: {
361
+ degree: { type: "integer", minimum: 1 },
362
+ controlPoints: {
363
+ type: "array",
364
+ items: {
365
+ type: "object",
366
+ required: ["locationPoint"],
367
+ properties: {
368
+ locationPoint: { $ref: "#/$defs/locationPoint" },
369
+ weight: { type: "number" }
370
+ }
371
+ }
372
+ },
373
+ knots: { type: "array", items: { type: "number" }, minItems: 4 }
374
+ }
375
+ }
376
+ }
377
+ },
378
+ globalPlan: {
379
+ type: "object",
380
+ required: ["timestamp", "globalPlan"],
381
+ properties: {
382
+ timestamp: { $ref: "#/$defs/timestamp" },
383
+ globalPlan: { type: "array", items: { $ref: "#/$defs/locationPointStamped" } }
384
+ }
385
+ },
386
+ request: {
387
+ type: "object",
388
+ required: ["destination", "source", "sequenceId", "timestamp", "details"],
389
+ properties: {
390
+ destination: { anyOf: [{ $ref: "#/$defs/uuid" }, { const: "" }] },
391
+ source: { $ref: "#/$defs/uuid" },
392
+ sequenceId: { type: "integer", minimum: 0 },
393
+ timestamp: { $ref: "#/$defs/timestamp" },
394
+ priority: { type: "integer", minimum: 0, maximum: 255 },
395
+ atomic: { type: "boolean" },
396
+ details: { type: "array", minItems: 1, items: { $ref: "#/$defs/requestDetail" } },
397
+ recoveries: { type: "array", items: { $ref: "#/$defs/requestDetail" } }
398
+ }
399
+ },
400
+ requestStatus: {
401
+ type: "object",
402
+ required: ["source", "destination", "sequenceId", "requestSequenceId", "timestamp", "status", "detailStatuses"],
403
+ properties: {
404
+ source: { $ref: "#/$defs/uuid" },
405
+ destination: { $ref: "#/$defs/uuid" },
406
+ sequenceId: { type: "integer", minimum: 0 },
407
+ requestSequenceId: { type: "integer", minimum: 0 },
408
+ timestamp: { $ref: "#/$defs/timestamp" },
409
+ status: { enum: ["RECEIVED", "ACCEPTED", "EXECUTING", "CANCELED", "SUCCEEDED", "ABORTED", "RECOVERY"] },
410
+ detailStatuses: { type: "array", items: { $ref: "#/$defs/requestDetailStatus" } },
411
+ recoveryStatuses: { type: "array", items: { $ref: "#/$defs/requestDetailStatus" } }
412
+ }
413
+ },
414
+ requestStatusArray: { type: "array", items: { $ref: "#/$defs/requestStatus" } }
415
+ }
416
+ };
417
+
418
+ // src/schema/normalize.ts
419
+ var TIMESTAMP_KEYS = /* @__PURE__ */ new Set(["timestamp", "arrivalTime"]);
420
+ var COMMA_TS = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}),(\d+)(Z|[+-]\d{2}:?\d{2})$/;
421
+ function fixTimestamps(value, warnings, path) {
422
+ if (Array.isArray(value)) return value.map((v, i) => fixTimestamps(v, warnings, `${path}[${i}]`));
423
+ if (value === null || typeof value !== "object") return value;
424
+ const out = {};
425
+ for (const [k, v] of Object.entries(value)) {
426
+ if (TIMESTAMP_KEYS.has(k) && typeof v === "string" && COMMA_TS.test(v)) {
427
+ out[k] = v.replace(COMMA_TS, "$1.$2$3");
428
+ warnings.push(`${path}.${k}: comma-decimal timestamp normalized to dot form`);
429
+ } else {
430
+ out[k] = fixTimestamps(v, warnings, `${path}.${k}`);
431
+ }
432
+ }
433
+ return out;
434
+ }
435
+ function normalizeInbound(kind, value) {
436
+ const warnings = [];
437
+ let v = fixTimestamps(value, warnings, kind);
438
+ if (kind === "entityStatus" && v !== null && typeof v === "object" && !Array.isArray(v)) {
439
+ const o = v;
440
+ if (o.entityId === void 0 && typeof o.id === "string") {
441
+ const { id, ...rest } = o;
442
+ v = { ...rest, entityId: id };
443
+ warnings.push('entityStatus: legacy field "id" renamed to "entityId" (spec \xA73.1)');
444
+ }
445
+ }
446
+ return { value: v, warnings };
447
+ }
448
+
449
+ // src/schema/validators.ts
450
+ var ajv = new import__.Ajv2020({ allErrors: true, strict: false });
451
+ (0, import_ajv_formats.default)(ajv);
452
+ ajv.addSchema(iso21423_schema_default);
453
+ var KNOWN_STATES = new Set(KNOWN_OPERATING_STATES);
454
+ function collectWarnings(kind, value, warnings) {
455
+ if (kind !== "entityStatus") return;
456
+ const states = value?.states;
457
+ if (!Array.isArray(states)) return;
458
+ for (const s of states) {
459
+ if (typeof s === "string" && !KNOWN_STATES.has(s)) {
460
+ warnings.push(`entityStatus: unknown operating state "${s}" (deployment extension?)`);
461
+ }
462
+ }
463
+ }
464
+ function validateMessage(kind, raw) {
465
+ const { value, warnings } = normalizeInbound(kind, raw);
466
+ const validate = ajv.getSchema(`https://openrobops.org/schemas/iso21423/v1.json#/$defs/${kind}`);
467
+ if (!validate) throw new Error(`No schema for message kind: ${kind}`);
468
+ const ok = validate(value);
469
+ collectWarnings(kind, value, warnings);
470
+ return ok ? { ok: true, value, warnings } : { ok: false, value, warnings, errors: validate.errors ?? [] };
471
+ }
472
+ function assertValid(kind, value) {
473
+ const r = validateMessage(kind, value);
474
+ if (!r.ok) {
475
+ throw new ValidationError(`outbound ${kind} message is not ISO 21423 conformant`, r.errors ?? []);
476
+ }
477
+ }
478
+
479
+ // src/session/session.ts
480
+ var Iso21423Session = class _Iso21423Session {
481
+ constructor(transport, entity, validateOutbound, armWill) {
482
+ this.transport = transport;
483
+ this.entity = entity;
484
+ this.validateOutbound = validateOutbound;
485
+ this.armWill = armWill;
486
+ }
487
+ transport;
488
+ entity;
489
+ validateOutbound;
490
+ armWill;
491
+ retainedOwned = /* @__PURE__ */ new Map();
492
+ rateGates = /* @__PURE__ */ new Map();
493
+ topicSubs = [];
494
+ listeners = {
495
+ connection: [],
496
+ "validation-warning": [],
497
+ error: []
498
+ };
499
+ wasConnected = false;
500
+ state = "closed";
501
+ /**
502
+ * Connects the transport and, unless `armWill` is false, arms the B.4 Last Will and clears any
503
+ * stale retained LOST_CONNECTION left over from a prior ungraceful disconnect (spec §4).
504
+ */
505
+ static async connect(opts) {
506
+ const armWill = opts.armWill ?? true;
507
+ const session = new _Iso21423Session(opts.transport, opts.entity, opts.validateOutbound ?? true, armWill);
508
+ opts.transport.onMessage((m) => session.dispatch(m.topic, m.payload));
509
+ opts.transport.onConnectionState((s) => session.handleConnectionState(s));
510
+ await opts.transport.connect({
511
+ clientId: `iso21423-${opts.entity.entityType}-${opts.entity.entityUuid}`,
512
+ cleanSession: false,
513
+ keepalive: 60,
514
+ username: opts.credentials?.username,
515
+ password: opts.credentials?.password,
516
+ will: armWill ? {
517
+ topic: disconnectionTopic(opts.entity),
518
+ payload: JSON.stringify({ states: [LOST_CONNECTION_STATE] }),
519
+ qos: 1,
520
+ retain: true
521
+ } : void 0
522
+ });
523
+ if (armWill) await session.clearRetained(disconnectionTopic(opts.entity));
524
+ return session;
525
+ }
526
+ /** Passthrough so `/core` never rebuilds topics itself (Task 3 implementer note). */
527
+ topicFor(ref, resource) {
528
+ return topicFor(ref, resource);
529
+ }
530
+ on(event, cb) {
531
+ this.listeners[event].push(cb);
532
+ }
533
+ /**
534
+ * Publishes a known resource (looked up in {@link RESOURCE_CONFIG} for its QoS/retain/rate).
535
+ * Retained resources are deduped on-change (a re-publish with identical body is a no-op) and
536
+ * rolled back from the dedup cache if the publish itself fails. Rate-limited (streaming)
537
+ * resources go through a per-topic {@link RateGate} and are fire-and-forget: publish failures
538
+ * there are reported via the `error` event, not thrown.
539
+ */
540
+ async publishResource(ref, resource, kind, payload) {
541
+ const config = RESOURCE_CONFIG[resource];
542
+ if (!config) throw new Iso21423Error(`unknown resource "${resource}"`);
543
+ if (kind && this.validateOutbound) assertValid(kind, payload);
544
+ const topic = topicFor(ref, resource);
545
+ const body = JSON.stringify(payload);
546
+ if (config.retain) {
547
+ if (this.retainedOwned.get(topic)?.payload === body) return;
548
+ this.retainedOwned.set(topic, { payload: body, qos: config.qos });
549
+ try {
550
+ await this.transport.publish(topic, body, { qos: config.qos, retain: true });
551
+ } catch (err) {
552
+ this.retainedOwned.delete(topic);
553
+ throw err;
554
+ }
555
+ return;
556
+ }
557
+ if (config.maxHz !== void 0) {
558
+ let gate = this.rateGates.get(topic);
559
+ if (!gate) {
560
+ gate = new RateGate(config.maxHz);
561
+ this.rateGates.set(topic, gate);
562
+ }
563
+ gate.offer(body, (b) => {
564
+ this.transport.publish(topic, b, { qos: config.qos, retain: false }).catch((err) => this.emitError(err));
565
+ });
566
+ return;
567
+ }
568
+ await this.transport.publish(topic, body, { qos: config.qos, retain: false });
569
+ }
570
+ /** Last non-wildcard resource segment → Table B.1 QoS, defaulting to QoS 1 when unknown. */
571
+ qosForFilter(filter) {
572
+ const parsed = parseTopic(filter);
573
+ if (!parsed) return 1;
574
+ const key = parsed.isRequestStatus ? "requestStatus" : parsed.resource;
575
+ return RESOURCE_CONFIG[key]?.qos ?? 1;
576
+ }
577
+ /**
578
+ * Always issues a broker SUBSCRIBE (a real broker redelivers retained messages on every
579
+ * SUBSCRIBE, so a late second handler must see the current retained value); the broker-side
580
+ * unsubscribe still only fires once the last local listener on the filter leaves (ND-17).
581
+ */
582
+ async subscribeTopic(topicFilter, kind, handler, opts = {}) {
583
+ const qos = opts.qos ?? this.qosForFilter(topicFilter);
584
+ const { granted } = await this.transport.subscribe(topicFilter, { qos });
585
+ if (!granted) {
586
+ throw new AuthorizationDenied(`subscription denied by broker: ${topicFilter}`, topicFilter);
587
+ }
588
+ const sub = { filter: topicFilter, kind, handler };
589
+ this.topicSubs.push(sub);
590
+ return {
591
+ unsubscribe: async () => {
592
+ this.topicSubs = this.topicSubs.filter((s) => s !== sub);
593
+ if (!this.topicSubs.some((s) => s.filter === topicFilter)) {
594
+ await this.transport.unsubscribe(topicFilter);
595
+ }
596
+ }
597
+ };
598
+ }
599
+ /** Publish to an exact topic (request / requestStatus topics are not plain resources). */
600
+ async publishTopic(topic, kind, payload, opts) {
601
+ if (kind && this.validateOutbound) assertValid(kind, payload);
602
+ await this.transport.publish(topic, JSON.stringify(payload), opts);
603
+ }
604
+ get connectionState() {
605
+ return this.state;
606
+ }
607
+ /**
608
+ * Subscribe to a resource topic with optional validation.
609
+ * When kind is null, handler receives raw payload text without parsing or validation.
610
+ */
611
+ async subscribeResource(filter, resource, kind, handler) {
612
+ const config = RESOURCE_CONFIG[resource];
613
+ if (!config) throw new Iso21423Error(`unknown resource "${resource}"`);
614
+ const topicFilter = `${ROOT_NAMESPACE}/${filter.entityType ?? "+"}/${filter.entityUuid ?? "+"}/${resource}`;
615
+ const sub = await this.subscribeTopic(topicFilter, kind, handler, { qos: config.qos });
616
+ return { unsubscribe: sub.unsubscribe, [Symbol.asyncDispose]: sub.unsubscribe };
617
+ }
618
+ /** For subscribers that opt out of schema routing (kind: null) but still want to surface a
619
+ * malformed payload as the usual 'validation-warning' event (D-13's RequestServer). */
620
+ reportValidationWarning(w) {
621
+ this.emitWarning(w);
622
+ }
623
+ async publishRaw(topic, payload, opts) {
624
+ await this.transport.publish(topic, payload, opts);
625
+ }
626
+ /** Clears a retained topic by publishing an empty retained payload, and drops it from the owned-retained dedup cache. */
627
+ async clearRetained(topic) {
628
+ this.retainedOwned.delete(topic);
629
+ await this.transport.publish(topic, "", { qos: 1, retain: true });
630
+ }
631
+ /** Optionally publishes a final status, disposes all rate gates, then ends the transport. */
632
+ async close(finalStates) {
633
+ if (finalStates) {
634
+ await this.publishResource(this.entity, "status", "entityStatus", {
635
+ entityId: this.entity.entityUuid,
636
+ timestamp: nowTimestamp(),
637
+ states: finalStates
638
+ });
639
+ }
640
+ for (const gate of this.rateGates.values()) gate.dispose();
641
+ await this.transport.end();
642
+ }
643
+ /**
644
+ * Routes an inbound message to every registered {@link TopicSub} whose filter matches the
645
+ * topic. `kind: null` subscribers get the raw text with no parsing; typed subscribers get an
646
+ * empty payload treated as a retained-clear (skipped silently) and malformed/non-conformant
647
+ * payloads reported via `emitWarning` rather than delivered to the handler.
648
+ */
649
+ dispatch(topic, payload) {
650
+ const parsed = parseTopic(topic);
651
+ if (!parsed) return;
652
+ const text = payload.toString();
653
+ const meta = {
654
+ topic,
655
+ entityType: parsed.entityType,
656
+ entityUuid: parsed.entityUuid,
657
+ resource: parsed.resource,
658
+ requestUuid: parsed.requestUuid,
659
+ isRequestStatus: parsed.isRequestStatus
660
+ };
661
+ for (const sub of this.topicSubs) {
662
+ if (!topicFilterMatches(sub.filter, topic)) continue;
663
+ if (!sub.kind) {
664
+ sub.handler(text, meta);
665
+ continue;
666
+ }
667
+ if (text === "") continue;
668
+ let value;
669
+ try {
670
+ value = JSON.parse(text);
671
+ } catch {
672
+ this.emitWarning({ topic, payload: text, errors: ["invalid JSON"] });
673
+ continue;
674
+ }
675
+ const result = validateMessage(sub.kind, value);
676
+ if (!result.ok) {
677
+ this.emitWarning({ topic, payload: text, errors: result.errors ?? [] });
678
+ continue;
679
+ }
680
+ sub.handler(result.value, meta);
681
+ }
682
+ }
683
+ handleConnectionState(s) {
684
+ this.state = s;
685
+ for (const cb of this.listeners.connection) cb(s);
686
+ if (s === "connected" && this.wasConnected) {
687
+ for (const [topic, { payload, qos }] of this.retainedOwned) {
688
+ this.transport.publish(topic, payload, { qos, retain: true }).catch((err) => this.emitError(err));
689
+ }
690
+ if (this.armWill) {
691
+ this.clearRetained(disconnectionTopic(this.entity)).catch((err) => this.emitError(err));
692
+ }
693
+ }
694
+ if (s === "connected") this.wasConnected = true;
695
+ }
696
+ emitWarning(w) {
697
+ for (const cb of this.listeners["validation-warning"]) cb(w);
698
+ }
699
+ emitError(err) {
700
+ const errorListeners = this.listeners.error;
701
+ if (errorListeners.length > 0) {
702
+ for (const cb of errorListeners) cb(err);
703
+ } else {
704
+ console.error("[Iso21423Session] async publish failed:", err);
705
+ }
706
+ }
707
+ };
708
+
709
+ // src/session/mqttTransport.ts
710
+ var MqttAdapter = class {
711
+ constructor(acquire, checkWill, ownsClient) {
712
+ this.acquire = acquire;
713
+ this.checkWill = checkWill;
714
+ this.ownsClient = ownsClient;
715
+ }
716
+ acquire;
717
+ checkWill;
718
+ ownsClient;
719
+ client;
720
+ ended = false;
721
+ wired = false;
722
+ messageCbs = [];
723
+ stateCbs = [];
724
+ /**
725
+ * Acquires the underlying mqtt client (via the constructor-supplied `acquire`) and wires
726
+ * message/connection-state listeners exactly once per adapter instance, so repeated `connect()`
727
+ * calls (e.g. reconnect flows) don't accumulate duplicate listeners. For a caller-constructed
728
+ * client whose will doesn't match `opts.will`, throws (P-4) rather than silently diverging.
729
+ */
730
+ async connect(opts) {
731
+ const client = await this.acquire(opts);
732
+ if (this.checkWill && opts.will && client.options?.will?.topic !== opts.will.topic) {
733
+ throw new Iso21423Error(
734
+ `caller-constructed mqtt client must be created with will { topic: "${opts.will.topic}", payload: '${opts.will.payload}', qos: ${opts.will.qos}, retain: ${opts.will.retain} } (P-4)`
735
+ );
736
+ }
737
+ if (!this.wired) {
738
+ this.wired = true;
739
+ client.on("message", ((topic, payload, packet) => {
740
+ const msg = {
741
+ topic,
742
+ payload,
743
+ qos: packet?.qos ?? 0,
744
+ retain: packet?.retain ?? false
745
+ };
746
+ for (const cb of this.messageCbs) cb(msg);
747
+ }));
748
+ client.on("reconnect", (() => this.emitState("reconnecting")));
749
+ client.on("offline", (() => this.emitState("offline")));
750
+ client.on("close", (() => this.emitState("closed")));
751
+ client.on("connect", (() => this.emitState("connected")));
752
+ }
753
+ if (client.connected) {
754
+ this.client = client;
755
+ this.emitState("connected");
756
+ return;
757
+ }
758
+ let settled = false;
759
+ const resolveReject = { resolve: null, reject: null };
760
+ const onConnect = (() => {
761
+ if (settled) return;
762
+ settled = true;
763
+ this.client = client;
764
+ resolveReject.resolve();
765
+ });
766
+ const onError = ((err) => {
767
+ if (settled) return;
768
+ settled = true;
769
+ if (this.ownsClient) {
770
+ client.endAsync(true).catch(() => {
771
+ });
772
+ }
773
+ resolveReject.reject(new BrokerUnavailable(`mqtt connect failed: ${err.message}`));
774
+ });
775
+ try {
776
+ await new Promise((resolve, reject) => {
777
+ resolveReject.resolve = resolve;
778
+ resolveReject.reject = reject;
779
+ client.on("connect", onConnect);
780
+ client.on("error", onError);
781
+ });
782
+ } finally {
783
+ try {
784
+ const clientWithRemoval = client;
785
+ (clientWithRemoval.off ?? clientWithRemoval.removeListener)?.("connect", onConnect);
786
+ (clientWithRemoval.off ?? clientWithRemoval.removeListener)?.("error", onError);
787
+ } catch {
788
+ }
789
+ }
790
+ }
791
+ async publish(topic, payload, opts) {
792
+ await this.live().publishAsync(topic, payload, opts);
793
+ }
794
+ /** Subscribes and reports whether the broker granted it — false if any SUBACK return code was a refusal (>= 0x80, ND-15) or no grants came back. */
795
+ async subscribe(filter, opts) {
796
+ const grants = await this.live().subscribeAsync(filter, opts);
797
+ const granted = grants.length > 0 && grants.every((g) => g.qos < 128);
798
+ return { granted };
799
+ }
800
+ async unsubscribe(filter) {
801
+ await this.live().unsubscribeAsync(filter);
802
+ }
803
+ onMessage(cb) {
804
+ this.messageCbs.push(cb);
805
+ }
806
+ onConnectionState(cb) {
807
+ this.stateCbs.push(cb);
808
+ }
809
+ async end() {
810
+ this.ended = true;
811
+ if (this.client) await this.client.endAsync();
812
+ this.emitState("closed");
813
+ }
814
+ /** Returns the connected client or throws {@link BrokerUnavailable} if `end()` was called or `connect()` hasn't completed. */
815
+ live() {
816
+ if (this.ended || !this.client) throw new BrokerUnavailable("mqtt transport is not connected");
817
+ return this.client;
818
+ }
819
+ emitState(s) {
820
+ for (const cb of this.stateCbs) cb(s);
821
+ }
822
+ };
823
+ function wrapMqttClient(client) {
824
+ return new MqttAdapter(async () => client, true, false);
825
+ }
826
+ function createMqttTransport(url, opts = {}) {
827
+ return new MqttAdapter(async (connectOpts) => {
828
+ let mod;
829
+ try {
830
+ mod = await import("mqtt");
831
+ } catch (err) {
832
+ throw new BrokerUnavailable(
833
+ `the "mqtt" peer dependency is not installed: ${err.message}`
834
+ );
835
+ }
836
+ return mod.connect(url, {
837
+ ...opts.tls,
838
+ clientId: connectOpts.clientId,
839
+ clean: connectOpts.cleanSession,
840
+ keepalive: connectOpts.keepalive,
841
+ username: connectOpts.username ?? opts.username,
842
+ password: connectOpts.password ?? opts.password,
843
+ reconnectPeriod: opts.reconnectPeriod,
844
+ will: connectOpts.will
845
+ });
846
+ }, false, true);
847
+ }
848
+ // Annotate the CommonJS export names for ESM import in node:
849
+ 0 && (module.exports = {
850
+ Iso21423Session,
851
+ RateGate,
852
+ createMqttTransport,
853
+ wrapMqttClient
854
+ });
855
+ //# sourceMappingURL=session.cjs.map