@7365admin1/core 3.114.0 → 3.115.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.
@@ -0,0 +1,580 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+
4
+ import {
5
+ jcs,
6
+ padbotSignature,
7
+ padbotSignedRequest,
8
+ parsePadbotAuthorization,
9
+ sha256Hex,
10
+ signedPath,
11
+ } from "./.build/utils/padbot-sign.util.mjs";
12
+ import {
13
+ PADBOT_ACTION_TEXT,
14
+ PADBOT_ALARM_TEXT,
15
+ PADBOT_CAPABILITIES,
16
+ PADBOT_PATHS,
17
+ clearPadbotCache,
18
+ createPadbotAdapter,
19
+ padbotAlarmFault,
20
+ padbotErrorText,
21
+ padbotMode,
22
+ padbotPatrolPlan,
23
+ padbotPatrolRecord,
24
+ padbotCheckpointVisit,
25
+ padbotPlanShare,
26
+ statesByType,
27
+ } from "./.build/services/padbot.adapter.mjs";
28
+ import { commandSupported, normalisePatrolPlan, robotTier } from "./.build/utils/robot-adapter.util.mjs";
29
+ import { planFaultChanges, robotFaultText } from "./.build/utils/robot-fault.util.mjs";
30
+ import { parseRobotCommand } from "./.build/utils/robot-cloud.util.mjs";
31
+
32
+ /* ---------------------------------------------- §2.4 the vendor's own examples */
33
+
34
+ const DOC = {
35
+ accessKeyId: "4252e5d70b5b4d268503a09e4ace321b",
36
+ timestamp: 1445307713,
37
+ requestId: "7c9e6679-7425-40de-944b-e07fc1f90ae7",
38
+ accessKeySecret: "Vxt19d7B69wrCF9d", // the document's published sample secret, not a credential
39
+ method: "POST",
40
+ };
41
+ const EXAMPLES = [
42
+ {
43
+ name: "1 flat body",
44
+ path: "/api/v1/robots/location/get",
45
+ body: { serialNumber: "PX0001" },
46
+ canonical: '{"serialNumber":"PX0001"}',
47
+ digest: "5ba1adcac801f9b9ad8e00d3485b78652eb3660c6ea6791b80a6574d1addf883",
48
+ signature: "aea15d994297a70b2c5543a3058f13e1cc00b87ef5ffb256307fd76456680a58",
49
+ },
50
+ {
51
+ name: "2 nested objects",
52
+ path: "/api/v1/robots/target-points/update",
53
+ body: {
54
+ mapId: "a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0",
55
+ targetPoint: { targetPointId: "f1e2d3c4b5a69788766554433221100a", name: "conference room", worldX: 5.0, worldY: 10.0, yaw: 90, targetPointType: 0 },
56
+ },
57
+ canonical:
58
+ '{"mapId":"a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0","targetPoint":{"name":"conference room","targetPointId":"f1e2d3c4b5a69788766554433221100a","targetPointType":0,"worldX":5,"worldY":10,"yaw":90}}',
59
+ digest: "0941785087fa686eb3b875afda05e493bd7ca4e09f645989bb4f7235a2fc0502",
60
+ signature: "739d25dabbe9932420af4b2979bd24fa6e90be5f7bf49244f784486502519175",
61
+ },
62
+ {
63
+ name: "3 arrays keep order",
64
+ path: "/api/v1/robots/patrol/alarms/resolve",
65
+ body: { alarmIds: ["9b8081f58b949423018b9967d74d1e3f", "8a8081f58b949423018b9967d74d1e2e"] },
66
+ canonical: '{"alarmIds":["9b8081f58b949423018b9967d74d1e3f","8a8081f58b949423018b9967d74d1e2e"]}',
67
+ digest: "927bd860815cb10400971aa72cebc24411a5ec20135f1b2aa1110702e019401e",
68
+ signature: "c617c118dc7bff23472a16366a191285d16901140fc610e1b18a5a665525bf55",
69
+ },
70
+ {
71
+ // The document's step 3 quotes digest aaa9d753...; its own step 2 digest
72
+ // (859a6fe3...) is the one that produces its published signature.
73
+ name: "4 arrays of objects",
74
+ path: "/api/v1/robots/delivery/tasks/vending-machine-loading-tasks/create",
75
+ body: {
76
+ serialNumber: "PX0001",
77
+ orderNumber: "order001",
78
+ vendingMachineSn: "ANDSYDV",
79
+ items: [
80
+ { quantity: 1, channelCode: "A1" },
81
+ { quantity: 1, channelCode: "C2" },
82
+ ],
83
+ destinationPointId: "59cf10397ee3a770844031f47de9f3e7",
84
+ },
85
+ canonical:
86
+ '{"destinationPointId":"59cf10397ee3a770844031f47de9f3e7","items":[{"channelCode":"A1","quantity":1},{"channelCode":"C2","quantity":1}],"orderNumber":"order001","serialNumber":"PX0001","vendingMachineSn":"ANDSYDV"}',
87
+ digest: "859a6fe36044d7f58d832e2bf97807132cddb3238b3d2a049292f5840bebe030",
88
+ signature: "2fe6e67eeedd6338d15426a62fbb23fef4802248b67c1ceca4a980dd41c80844",
89
+ },
90
+ ];
91
+
92
+ for (const ex of EXAMPLES) {
93
+ test(`§2.4 example ${ex.name}: canonical body, digest and signature match the document`, () => {
94
+ const canonicalBody = jcs(ex.body);
95
+ assert.equal(canonicalBody, ex.canonical);
96
+ assert.equal(sha256Hex(canonicalBody), ex.digest);
97
+ assert.equal(padbotSignature({ ...DOC, path: ex.path, canonicalBody }), ex.signature);
98
+ });
99
+ }
100
+
101
+ test("§2.3.2 empty body signs as {} with the documented digest", () => {
102
+ assert.equal(jcs({}), "{}");
103
+ assert.equal(sha256Hex("{}"), "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a");
104
+ const req = padbotSignedRequest({ path: "/api/v1/robots/mqtt/credentials", accessKeyId: "k", accessKeySecret: "s" });
105
+ assert.equal(req.body, "{}");
106
+ });
107
+
108
+ test("signed request: headers per §2.2.1, body = the signed canonical string, fresh request id each call", () => {
109
+ const a = padbotSignedRequest({
110
+ path: EXAMPLES[1].path,
111
+ body: EXAMPLES[1].body,
112
+ accessKeyId: DOC.accessKeyId,
113
+ accessKeySecret: DOC.accessKeySecret,
114
+ now: () => DOC.timestamp * 1000 + 999,
115
+ uuid: () => DOC.requestId,
116
+ });
117
+ assert.equal(a.body, EXAMPLES[1].canonical);
118
+ assert.equal(a.headers.Authorization, `PadBot accessKeyId=${DOC.accessKeyId},timestamp=${DOC.timestamp},signature=${EXAMPLES[1].signature}`);
119
+ assert.equal(a.headers["X-Request-ID"], DOC.requestId);
120
+ assert.equal(a.headers["Content-Type"], "application/json");
121
+ assert.equal(a.headers.Accept, "application/json");
122
+ assert.match(a.headers["User-Agent"], /^[^/]+\/[\d.]+$/);
123
+ assert.ok(!JSON.stringify(a).includes(DOC.accessKeySecret), "the secret is never in a header or the body");
124
+ const b = padbotSignedRequest({ path: "/x", accessKeyId: "k", accessKeySecret: "s" });
125
+ const c = padbotSignedRequest({ path: "/x", accessKeyId: "k", accessKeySecret: "s" });
126
+ assert.notEqual(b.headers["X-Request-ID"], c.headers["X-Request-ID"]);
127
+ assert.match(b.headers["X-Request-ID"], /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
128
+ assert.deepEqual(parsePadbotAuthorization(a.headers.Authorization), {
129
+ accessKeyId: DOC.accessKeyId,
130
+ timestamp: DOC.timestamp,
131
+ signature: EXAMPLES[1].signature,
132
+ });
133
+ assert.equal(parsePadbotAuthorization("Bearer x"), null);
134
+ });
135
+
136
+ /* ----------------------------------------------------- RFC 8785 edge cases */
137
+
138
+ test("JCS: RFC 8785 appendix sample (numbers, escapes, literals)", () => {
139
+ const input = JSON.parse(
140
+ '{"numbers":[333333333.33333329,1E30,4.50,2e-3,0.000000000000000000000000001],"string":"\\u20ac$\\u000F\\u000aA\'\\u0042\\u0022\\u005c\\\\\\"\\/","literals":[null,true,false]}',
141
+ );
142
+ assert.equal(
143
+ jcs(input),
144
+ '{"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27],"string":"€$\\u000f\\nA\'B\\"\\\\\\\\\\"/"}',
145
+ );
146
+ });
147
+
148
+ test("JCS: keys sort by UTF-16 code units (RFC 8785 §3.2.3 sample), recursively; arrays keep order", () => {
149
+ const input = JSON.parse('{"\\u20ac":"Euro Sign","\\r":"Carriage Return","\\ufb33":"Hebrew Letter Dalet With Dagesh","1":"One","\\ud83d\\ude00":"Emoji: Grinning Face","\\u0080":"Control","\\u00f6":"Latin Small Letter O With Diaeresis"}');
150
+ // Read the order off the string: JS objects would move "1" first on parse.
151
+ const keys = [...jcs(input).matchAll(/"((?:[^"\\]|\\.)*)":"[^"]*"/g)].map((m) => JSON.parse(`"${m[1]}"`));
152
+ assert.deepEqual(keys, ["\r", "1", "\u0080", "ö", "€", "😀", "דּ"]);
153
+ assert.equal(jcs({ b: [3, 1, { d: 1, c: 2 }], a: { z: 1, y: { x: 2, w: 1 } } }), '{"a":{"y":{"w":1,"x":2},"z":1},"b":[3,1,{"c":2,"d":1}]}');
154
+ });
155
+
156
+ test("JCS: number canonical form (integers and floats with equal value are equal)", () => {
157
+ assert.equal(jcs(5.0), "5");
158
+ assert.equal(jcs(-0), "0");
159
+ assert.equal(jcs(1e21), "1e+21");
160
+ assert.equal(jcs(1e-7), "1e-7");
161
+ assert.equal(jcs(0.1), "0.1");
162
+ assert.equal(jcs(123456789012345680000), "123456789012345680000");
163
+ assert.equal(jcs({ worldX: 5.0, coordinateX: 100 }), '{"coordinateX":100,"worldX":5}');
164
+ });
165
+
166
+ test("JCS: refuses what is not JSON; drops undefined members; UTF-8 multi-byte kept literal", () => {
167
+ assert.throws(() => jcs(NaN), /finite/);
168
+ assert.throws(() => jcs(Infinity), /finite/);
169
+ assert.throws(() => jcs("\ud800"), /surrogate/);
170
+ assert.throws(() => jcs({ a: "x\udc00" }), /surrogate/);
171
+ assert.throws(() => jcs(() => 1), /cannot/);
172
+ assert.equal(jcs({ a: undefined, b: 1 }), '{"b":1}');
173
+ assert.equal(jcs([undefined]), "[null]");
174
+ assert.equal(jcs({ name: "会议室" }), '{"name":"会议室"}');
175
+ assert.equal(sha256Hex('{"name":"会议室"}'), sha256Hex(Buffer.from('{"name":"会议室"}', "utf8").toString()));
176
+ });
177
+
178
+ test("signed path: ASCII kept, non-ASCII / reserved percent-encoded", () => {
179
+ assert.equal(signedPath("/api/v1/robots/list"), "/api/v1/robots/list");
180
+ assert.equal(signedPath("/api/v1/a b/会"), "/api/v1/a%20b/%E4%BC%9A");
181
+ });
182
+
183
+ /* ------------------------------------------------------ status mapping */
184
+
185
+ const NOW = Date.parse("2026-09-26T08:00:00.000Z");
186
+ const fresh = "2026-09-26T07:59:50.000Z";
187
+ const st = (extra = {}) => ({ "1000": { updatedAt: fresh }, ...extra });
188
+
189
+ test("status: no heartbeat, a null (expired) heartbeat, or a stale one = offline", () => {
190
+ assert.deepEqual(padbotMode({}, NOW), { online: false, mode: "UNAVAILABLE", statusName: "Not reporting to PadBot" });
191
+ assert.equal(padbotMode({ "1000": null }, NOW).online, false);
192
+ assert.equal(padbotMode({ "1000": { updatedAt: "2026-09-26T07:57:00.000Z" } }, NOW).online, false);
193
+ assert.equal(padbotMode(st(), NOW).online, true);
194
+ });
195
+
196
+ test("status: standby, patrolling, other work, charging, charged", () => {
197
+ assert.deepEqual(padbotMode(st(), NOW), { online: true, mode: "IDLE", statusName: "Standing by" });
198
+ assert.equal(padbotMode(st({ "1010": { workState: 1, taskType: 2 } }), NOW).statusName, "Patrolling");
199
+ assert.equal(padbotMode(st({ "1010": { workState: 1, taskType: 2 } }), NOW).mode, "WORKING");
200
+ assert.deepEqual(padbotMode(st({ "1010": { workState: 1, taskType: 6 } }), NOW).mode, "WORKING");
201
+ assert.equal(padbotMode(st({ "1010": { workState: 1, taskType: 6 } }), NOW).statusName, "Working on a task");
202
+ assert.equal(padbotMode(st({ "1002": { chargingState: 1 }, "1001": { batteryPercent: 60 } }), NOW).mode, "CHARGING_CYCLE");
203
+ assert.equal(padbotMode(st({ "1002": { chargingState: 1 }, "1001": { batteryPercent: 99 } }), NOW).mode, "CHARGED");
204
+ assert.equal(padbotMode(st({ "1002": { chargingState: 0 } }), NOW).mode, "IDLE");
205
+ });
206
+
207
+ test("status: every navigation action type while navigating, in plain words", () => {
208
+ for (let type = 1; type <= 13; type++) {
209
+ const r = padbotMode(st({ "1003": { actionType: type, actionState: 2 }, "1010": { workState: 1, taskType: 2 } }), NOW);
210
+ assert.equal(r.statusName, PADBOT_ACTION_TEXT[type], `type ${type}`);
211
+ // Lift phases are "Changing floor"; everything else while moving is working.
212
+ assert.equal(r.mode, type <= 5 ? "IN_TRANSIT" : "WORKING", `type ${type}`);
213
+ }
214
+ assert.equal(
215
+ padbotMode(st({ "1003": { actionType: 11, actionState: 2, nextTargetPointName: "Lobby" } }), NOW).statusName,
216
+ "Heading to Lobby",
217
+ );
218
+ assert.match(PADBOT_ACTION_TEXT[9], /access door/);
219
+ assert.match(PADBOT_ACTION_TEXT[4], /lift/);
220
+ });
221
+
222
+ test("status: every navigation action state", () => {
223
+ const nav = (actionState, extra = {}) => padbotMode(st({ "1003": { actionType: 11, actionState, finalTargetPointName: "Gate", ...extra } }), NOW);
224
+ assert.equal(nav(0).mode, "IDLE");
225
+ assert.equal(nav(1).mode, "WORKING");
226
+ assert.equal(nav(2).mode, "WORKING");
227
+ assert.equal(nav(3).mode, "PAUSED");
228
+ assert.equal(nav(3).statusName, "Heading to the next point (paused)");
229
+ assert.equal(nav(4).statusName, "Stopping");
230
+ assert.equal(nav(5).statusName, "Arrived at Gate");
231
+ assert.equal(nav(5).mode, "IDLE");
232
+ assert.equal(nav(6).statusName, "Could not reach Gate");
233
+ assert.equal(nav(6, { message: "blocked" }).statusName, "Could not reach Gate (blocked)");
234
+ assert.equal(nav(6).mode, "IDLE");
235
+ // A lift phase while paused stays "Changing floor".
236
+ assert.equal(padbotMode(st({ "1003": { actionType: 4, actionState: 3 } }), NOW).mode, "IN_TRANSIT");
237
+ // Charging outranks a navigation phase: a dock is a dock.
238
+ assert.equal(padbotMode(st({ "1003": { actionType: 12, actionState: 2 }, "1002": { chargingState: 1 } }), NOW).mode, "CHARGING_CYCLE");
239
+ });
240
+
241
+ test("status: network suffix (Wi-Fi first, then mobile)", () => {
242
+ assert.equal(padbotMode(st({ "1107": { wifi: { signalStrength: -61 } } }), NOW).statusName, "Standing by · Wi-Fi -61 dBm");
243
+ assert.equal(padbotMode(st({ "1107": { cellular: { signalStrength: -90 } } }), NOW).statusName, "Standing by · Mobile -90 dBm");
244
+ });
245
+
246
+ test("statesByType keys the §4.2 answer by state type", () => {
247
+ const s = statesByType({ serialNumber: "P", states: [{ stateType: "1001", data: { batteryPercent: 68 } }, { stateType: "1002", data: null }] });
248
+ assert.deepEqual(s, { 1001: { batteryPercent: 68 }, 1002: null });
249
+ });
250
+
251
+ /* ------------------------------------------------------ plan frame */
252
+
253
+ test("plan share: metres -> 0-100 from the image's top-left (origin bottom-left)", () => {
254
+ const frame = { width: 200, height: 100, resolution: 0.05, originX: 0, originY: 0 }; // 10 m x 5 m
255
+ assert.deepEqual(padbotPlanShare(frame, 5, 2.5), { x: 50, y: 50 });
256
+ assert.deepEqual(padbotPlanShare(frame, 0, 0), { x: 0, y: 100 });
257
+ assert.deepEqual(padbotPlanShare({ ...frame, originX: -1, originY: -1 }, 0, 0), { x: 10, y: 80 });
258
+ assert.equal(padbotPlanShare(frame, 20, 1), null, "outside the image");
259
+ assert.equal(padbotPlanShare({ width: 200, height: 100 }, 1, 1), null, "no resolution");
260
+ });
261
+
262
+ /* ------------------------------------------------------ alarms */
263
+
264
+ test("alarm -> fault: one code per type, plain words, since = when it happened, flagged as alarm", () => {
265
+ for (const [type, text] of Object.entries(PADBOT_ALARM_TEXT)) {
266
+ const f = padbotAlarmFault({ alarmType: type, occurredAt: "2026-07-25T08:04:17.010Z", toPointName: "Lobby" });
267
+ assert.equal(f.code, `ALARM-${type}`);
268
+ assert.equal(f.message, `${text} near Lobby`);
269
+ assert.equal(f.since, Date.parse("2026-07-25T08:04:17.010Z"));
270
+ assert.equal(f.alarm, true);
271
+ }
272
+ assert.equal(padbotAlarmFault(null), null);
273
+ assert.equal(padbotAlarmFault({ alarmType: "99" }).message, "Alarm type 99");
274
+ assert.equal(robotFaultText("PB-1", { code: "ALARM-3", message: "Smoke detected near Lobby" }).title, "Robot alert");
275
+ assert.equal(robotFaultText("PB-1", { code: "E-STOP", message: "x" }).title, "Robot fault");
276
+ });
277
+
278
+ test("alarm dedupe: the same alarm on every read opens once; a new occurrence re-opens; resolved clears", () => {
279
+ const alarm = { alarmType: "3", occurredAt: "2026-07-25T08:04:17.010Z" };
280
+ const f = padbotAlarmFault(alarm);
281
+ const first = planFaultChanges([], { ok: true, online: true, fault: f });
282
+ assert.equal(first.open.length, 1);
283
+ const rec = { _id: "r1", code: f.code, since: new Date(f.since) };
284
+ const again = planFaultChanges([rec], { ok: true, online: true, fault: padbotAlarmFault(alarm) });
285
+ assert.deepEqual(again, { open: [], clear: [] });
286
+ const later = padbotAlarmFault({ alarmType: "3", occurredAt: "2026-07-25T09:04:17.010Z" });
287
+ const second = planFaultChanges([rec], { ok: true, online: true, fault: later });
288
+ assert.deepEqual(second.clear, ["r1"]);
289
+ assert.equal(second.open.length, 1);
290
+ const resolved = planFaultChanges([rec], { ok: true, online: true, fault: null });
291
+ assert.deepEqual(resolved, { open: [], clear: ["r1"] });
292
+ });
293
+
294
+ /* ------------------------------------------------------ patrol */
295
+
296
+ const MAPS = [
297
+ {
298
+ mapId: "m1",
299
+ floor: 1,
300
+ width: 200,
301
+ height: 100,
302
+ resolution: 0.05,
303
+ originX: 0,
304
+ originY: 0,
305
+ targetPoints: [
306
+ { targetPointId: "t1", name: "Entrance", worldX: 1, worldY: 1 },
307
+ { targetPointId: "t2", name: "Hall", worldX: 5, worldY: 2.5 },
308
+ { targetPointId: "t3", name: "Dock", worldX: 9, worldY: 4, targetPointType: 10 },
309
+ ],
310
+ },
311
+ ];
312
+ const PATHS = [
313
+ {
314
+ pathId: "p2",
315
+ pathName: "Night loop",
316
+ mapId: "m1",
317
+ isDefault: false,
318
+ points: [
319
+ { targetPointId: "t3", targetPointName: "Dock", pointIndex: 1 },
320
+ { targetPointId: "t1", targetPointName: "Entrance", pointIndex: 0 },
321
+ ],
322
+ },
323
+ {
324
+ pathId: "p1",
325
+ pathName: "Lobby",
326
+ mapId: "m1",
327
+ isDefault: true,
328
+ points: [
329
+ { targetPointId: "t1", targetPointName: "Entrance", pointIndex: 0 },
330
+ { targetPointId: "t2", targetPointName: "Hall", pointIndex: 1 },
331
+ { targetPointId: "zz", targetPointName: "Nowhere", pointIndex: 2 },
332
+ ],
333
+ },
334
+ ];
335
+
336
+ test("patrol: routes -> ordered named checkpoints on the plan frame; default first; no schedule", () => {
337
+ const plan = normalisePatrolPlan(padbotPatrolPlan(PATHS, MAPS, {}));
338
+ assert.deepEqual(plan.routes.map((r) => r.id), ["p1", "p2"]);
339
+ assert.equal(plan.routes[0].name, "Lobby (default)");
340
+ assert.equal(plan.routes[0].floorNo, 1);
341
+ assert.deepEqual(plan.routes[0].checkpoints, [
342
+ { name: "Entrance", x: 10, y: 80 },
343
+ { name: "Hall", x: 50, y: 50 },
344
+ ]);
345
+ assert.deepEqual(plan.routes[1].checkpoints.map((c) => c.name), ["Entrance", "Dock"]);
346
+ assert.equal(plan.routes[0].currentCheckpoint, null);
347
+ assert.deepEqual(plan.schedule, []);
348
+ });
349
+
350
+ test("patrol: current checkpoint only while patrolling that map and one route names the point", () => {
351
+ const walking = { "1010": { workState: 1, taskType: 2 }, "1007": { mapId: "m1" }, "1003": { nextTargetPointName: "Dock" } };
352
+ const plan = normalisePatrolPlan(padbotPatrolPlan(PATHS, MAPS, walking));
353
+ assert.equal(plan.routes[0].id, "p2", "the route being walked comes first");
354
+ assert.equal(plan.routes[0].currentCheckpoint, 1);
355
+ const ambiguous = { ...walking, "1003": { nextTargetPointName: "Entrance" } };
356
+ assert.ok(normalisePatrolPlan(padbotPatrolPlan(PATHS, MAPS, ambiguous)).routes.every((r) => r.currentCheckpoint === null));
357
+ const idle = { ...walking, "1010": { workState: 0 } };
358
+ assert.ok(normalisePatrolPlan(padbotPatrolPlan(PATHS, MAPS, idle)).routes.every((r) => r.currentCheckpoint === null));
359
+ });
360
+
361
+ test("patrol history + checkpoint visits map every completion state", () => {
362
+ const states = { 0: "in-progress", 1: "failed", 2: "completed", 3: "partial", 9: "unknown" };
363
+ for (const [c, want] of Object.entries(states)) {
364
+ assert.equal(padbotPatrolRecord({ completionState: Number(c) }).result, want);
365
+ }
366
+ assert.deepEqual(
367
+ padbotPatrolRecord({ patrolRecordId: "r", patrolPathName: "test04", completionState: 2, startedAt: "a", endedAt: null, duration: 101, mileage: 19.89, alarmCount: 3 }),
368
+ { id: "r", routeName: "test04", result: "completed", startedAt: "a", endedAt: null, durationS: 101, distanceM: 19.89, alarmCount: 3 },
369
+ );
370
+ assert.deepEqual(
371
+ padbotCheckpointVisit({ targetPointName: "07", capturedAt: "t", skipped: false, visibleLightImageUrl: "v", thermalImageUrl: null, centerTemperature: 24.5, maxTemperature: 25.7 }),
372
+ { checkpoint: "07", at: "t", skipped: false, imageUrl: "v", thermalImageUrl: null, centerTempC: 24.5, maxTempC: 25.7 },
373
+ );
374
+ });
375
+
376
+ /* ------------------------------------------------------ capabilities */
377
+
378
+ test("capabilities: what PadBot's API offers; Cancel yes, Pause no; demo keeps Pause", () => {
379
+ assert.equal(commandSupported(PADBOT_CAPABILITIES, "cancel"), true);
380
+ assert.equal(commandSupported(PADBOT_CAPABILITIES, "pause"), false);
381
+ assert.equal(commandSupported(PADBOT_CAPABILITIES, "resume"), false);
382
+ assert.equal(commandSupported(PADBOT_CAPABILITIES, "patrol-resume"), true);
383
+ assert.equal(commandSupported(PADBOT_CAPABILITIES, "spot"), false);
384
+ for (const k of ["full", "area", "return", "navigate", "relocalize"]) assert.equal(commandSupported(PADBOT_CAPABILITIES, k), true, k);
385
+ // Open-RMF's tiers all need path/ETA (read-only) or pause (the others), which
386
+ // PadBot's API lacks - so its RMF tier is honestly none; the HERO badge is command level.
387
+ assert.equal(robotTier(PADBOT_CAPABILITIES), "no-interface");
388
+ assert.equal(commandSupported({ pauseResume: true, pauseProcess: true }, "pause"), true);
389
+ assert.deepEqual(parseRobotCommand({ kind: "patrol-resume" }), { ok: true, command: { kind: "patrol-resume" } });
390
+ assert.equal(parseRobotCommand({ kind: "patrol-resume", areas: ["x"] }).ok, false);
391
+ });
392
+
393
+ test("error codes read as plain words", () => {
394
+ assert.equal(padbotErrorText(1518), "There is no interrupted patrol to resume.");
395
+ assert.match(padbotErrorText(1500), /does not know this robot/);
396
+ assert.match(padbotErrorText(2002), /route no longer exists/);
397
+ assert.match(padbotErrorText(4242), /code 4242/);
398
+ });
399
+
400
+ /* ------------------------------------------------------ adapter over a verifying fake */
401
+
402
+ const CREDS = { appid: "ak-test-id", secret: "sk-test-secret-never-logged" };
403
+
404
+ function fakePadbot(routes, { now = NOW } = {}) {
405
+ const calls = [];
406
+ const fetch = async (url, init) => {
407
+ const path = new URL(url).pathname;
408
+ const auth = parsePadbotAuthorization(init.headers.Authorization);
409
+ const expect = padbotSignature({
410
+ method: "POST",
411
+ path,
412
+ accessKeyId: auth?.accessKeyId ?? "",
413
+ timestamp: auth?.timestamp ?? 0,
414
+ requestId: init.headers["X-Request-ID"],
415
+ canonicalBody: init.body,
416
+ accessKeySecret: CREDS.secret,
417
+ });
418
+ calls.push({ path, body: JSON.parse(init.body), signed: auth?.signature === expect, requestId: init.headers["X-Request-ID"] });
419
+ const hit = routes[path];
420
+ if (!hit) return { status: 404, text: async () => "" };
421
+ const out = hit(JSON.parse(init.body));
422
+ if (out?.__status) return { status: out.__status, text: async () => "" };
423
+ return { status: 200, text: async () => JSON.stringify(out?.__raw ?? { code: 0, message: "success", requestId: init.headers["X-Request-ID"], data: out ?? null }) };
424
+ };
425
+ return { fetch, calls, now: () => now };
426
+ }
427
+
428
+ const STATE_ANSWER = [
429
+ {
430
+ serialNumber: "PS0001",
431
+ states: [
432
+ { stateType: "1000", data: { updatedAt: fresh } },
433
+ { stateType: "1001", data: { batteryPercent: 68 } },
434
+ { stateType: "1003", data: { actionType: 9, actionState: 2 } },
435
+ { stateType: "1007", data: { mapId: "m1", floor: 1 } },
436
+ { stateType: "1010", data: { workState: 1, taskType: 2 } },
437
+ ],
438
+ },
439
+ ];
440
+
441
+ test("adapter getRobot: signed calls, state + location + newest open alarm, plan position", async () => {
442
+ clearPadbotCache();
443
+ const f = fakePadbot({
444
+ [PADBOT_PATHS.states]: () => STATE_ANSWER,
445
+ [PADBOT_PATHS.robots]: () => [{ serialNumber: "PS0001", robotName: "Patrol 1", robotType: "PATROL", robotModel: "S2" }],
446
+ [PADBOT_PATHS.location]: () => ({ mapId: "m1", worldX: 5, worldY: 2.5, yaw: -90 }),
447
+ [PADBOT_PATHS.maps]: () => MAPS,
448
+ [PADBOT_PATHS.alarms]: () => ({ items: [{ alarmId: "a1", alarmType: "8", occurredAt: "2026-09-26T07:00:00.000Z", toPointName: "Fire door" }], totalItems: 1, totalPages: 1 }),
449
+ });
450
+ const adapter = createPadbotAdapter(CREDS, { baseUrl: "https://pb.test", fetch: f.fetch, now: f.now });
451
+ const r = await adapter.getRobot("PS0001");
452
+ assert.equal(r.online, true);
453
+ assert.equal(r.mode, "WORKING");
454
+ assert.equal(r.statusName, "Waiting for the access door to open");
455
+ assert.equal(r.batteryPercent, 68);
456
+ assert.equal(r.floorNo, 1);
457
+ assert.equal(r.model, "PadBot S2");
458
+ assert.deepEqual(r.planPosition, { x: 50, y: 50 });
459
+ assert.equal(Math.round((r.position.theta * 180) / Math.PI), -90);
460
+ assert.equal(r.fault.code, "ALARM-8");
461
+ assert.equal(r.fault.message, "Door found open near Fire door");
462
+ assert.ok(f.calls.every((c) => c.signed), "every request carries a valid signature");
463
+ assert.equal(new Set(f.calls.map((c) => c.requestId)).size, f.calls.length, "a fresh X-Request-ID per request");
464
+ assert.deepEqual(f.calls.find((c) => c.path === PADBOT_PATHS.robots).body, { robotTypes: ["PATROL"] });
465
+ });
466
+
467
+ test("adapter getRobot: e-stop outranks alarms; unknown serial = null; offline skips location", async () => {
468
+ clearPadbotCache();
469
+ const estop = [{ serialNumber: "PS0001", states: [...STATE_ANSWER[0].states, { stateType: "1006", data: { emergencyStopState: 1, updatedAt: fresh } }] }];
470
+ const f = fakePadbot({ [PADBOT_PATHS.states]: () => estop, [PADBOT_PATHS.robots]: () => [], [PADBOT_PATHS.location]: () => null });
471
+ const a = createPadbotAdapter(CREDS, { baseUrl: "https://pb.test", fetch: f.fetch, now: f.now });
472
+ const r = await a.getRobot("PS0001");
473
+ assert.equal(r.fault.code, "E-STOP");
474
+ assert.ok(!f.calls.some((c) => c.path === PADBOT_PATHS.alarms));
475
+ assert.equal(await a.getRobot("NOPE"), null);
476
+
477
+ clearPadbotCache();
478
+ const g = fakePadbot({ [PADBOT_PATHS.states]: () => [{ serialNumber: "PS0001", states: [{ stateType: "1000", data: null }] }], [PADBOT_PATHS.robots]: () => [] });
479
+ const off = await createPadbotAdapter(CREDS, { baseUrl: "https://pb.test", fetch: g.fetch, now: g.now }).getRobot("PS0001");
480
+ assert.equal(off.online, false);
481
+ assert.ok(!g.calls.some((c) => c.path === PADBOT_PATHS.location));
482
+ });
483
+
484
+ test("adapter commands: each of ours becomes the documented PadBot call", async () => {
485
+ const f = fakePadbot(Object.fromEntries(Object.values(PADBOT_PATHS).map((p) => [p, () => null])));
486
+ const a = createPadbotAdapter(CREDS, { baseUrl: "https://pb.test", fetch: f.fetch, now: f.now });
487
+ await a.sendCommand("PS1", { kind: "full" });
488
+ await a.sendCommand("PS1", { kind: "area", areas: ["p1"], options: { cleanTimes: 3 } });
489
+ await a.sendCommand("PS1", { kind: "patrol-resume" });
490
+ await a.sendCommand("PS1", { kind: "cancel" });
491
+ await a.sendCommand("PS1", { kind: "return" });
492
+ await a.sendCommand("PS1", { kind: "navigate", x: 1.5, y: 2, theta: Math.PI });
493
+ await a.sendCommand("PS1", { kind: "relocalize", floorNo: 1, x: 1, y: 2, theta: 0 });
494
+ assert.deepEqual(
495
+ f.calls.map((c) => [c.path, c.body]),
496
+ [
497
+ [PADBOT_PATHS.patrolStart, { serialNumber: "PS1", patrolCount: 1 }],
498
+ [PADBOT_PATHS.patrolStart, { serialNumber: "PS1", pathId: "p1", patrolCount: 3 }],
499
+ [PADBOT_PATHS.patrolResume, { serialNumber: "PS1" }],
500
+ [PADBOT_PATHS.stop, { serialNumber: "PS1" }],
501
+ [PADBOT_PATHS.charge, { serialNumber: "PS1" }],
502
+ [PADBOT_PATHS.navigate, { serialNumber: "PS1", worldX: 1.5, worldY: 2, yaw: -180 }],
503
+ [PADBOT_PATHS.relocate, { serialNumber: "PS1", worldX: 1, worldY: 2 }],
504
+ ],
505
+ );
506
+ await assert.rejects(a.sendCommand("PS1", { kind: "pause" }), /cannot "pause"/);
507
+ await assert.rejects(a.sendCommand("PS1", { kind: "area", areas: ["a", "b"] }), /one patrol route/);
508
+ });
509
+
510
+ test("adapter errors: business codes, HTTP 401/403/5xx and timeouts are plain words; the secret never appears", async () => {
511
+ const err = async (answer) => {
512
+ const f = fakePadbot({ [PADBOT_PATHS.patrolResume]: () => answer });
513
+ const a = createPadbotAdapter(CREDS, { baseUrl: "https://pb.test", fetch: f.fetch, now: f.now });
514
+ try {
515
+ await a.sendCommand("PS1", { kind: "patrol-resume" });
516
+ } catch (e) {
517
+ return e;
518
+ }
519
+ assert.fail("expected a refusal");
520
+ };
521
+ const e1 = await err({ __raw: { code: 1518, message: "No recoverable patrol record", requestId: "x", data: null } });
522
+ assert.equal(e1.message, "There is no interrupted patrol to resume.");
523
+ assert.equal(e1.statusCode, 400);
524
+ assert.match((await err({ __status: 401 })).message, /refused the AccessKey/);
525
+ assert.match((await err({ __status: 403 })).message, /not allowed/);
526
+ const e5 = await err({ __status: 503 });
527
+ assert.equal(e5.statusCode, 502);
528
+ const timeout = createPadbotAdapter(CREDS, {
529
+ baseUrl: "https://pb.test",
530
+ fetch: () => Promise.reject(Object.assign(new Error("t"), { name: "TimeoutError" })),
531
+ });
532
+ await assert.rejects(timeout.sendCommand("PS1", { kind: "cancel" }), /timed out/);
533
+ for (const e of [e1, e5]) assert.ok(!String(e.message + e.stack).includes(CREDS.secret));
534
+ });
535
+
536
+ test("adapter extras: patrol routes, live video, resolve alerts (by type, batched), history", async () => {
537
+ clearPadbotCache();
538
+ const alarms = Array.from({ length: 150 }, (_, i) => ({ alarmId: `a${i}`, alarmType: "3" }));
539
+ const f = fakePadbot({
540
+ [PADBOT_PATHS.patrolRoutes]: () => PATHS,
541
+ [PADBOT_PATHS.maps]: () => MAPS,
542
+ [PADBOT_PATHS.states]: () => STATE_ANSWER,
543
+ [PADBOT_PATHS.video]: () => ({ playbackUrl: "https://video.test/play", expiresAt: "2026-09-26T09:00:00.000Z" }),
544
+ [PADBOT_PATHS.alarms]: (b) => ({ items: alarms.slice((b.pageNumber - 1) * 100, b.pageNumber * 100), totalItems: 150, totalPages: 2 }),
545
+ [PADBOT_PATHS.resolve]: () => null,
546
+ [PADBOT_PATHS.records]: () => ({ items: [{ patrolRecordId: "r1", completionState: 2 }], totalItems: 1, totalPages: 1 }),
547
+ [PADBOT_PATHS.recordDetails]: () => ({ items: [{ targetPointName: "07", skipped: true }], totalItems: 1, totalPages: 1 }),
548
+ });
549
+ const a = createPadbotAdapter(CREDS, { baseUrl: "https://pb.test", fetch: f.fetch, now: f.now });
550
+ const plan = normalisePatrolPlan(await a.getPatrolRoutes("PS0001"));
551
+ assert.equal(plan.routes.length, 2);
552
+ assert.deepEqual(await a.getLiveVideo("PS0001"), { url: "https://video.test/play", expiresAt: "2026-09-26T09:00:00.000Z" });
553
+ assert.deepEqual(f.calls.find((c) => c.path === PADBOT_PATHS.video).body, { serialNumber: "PS0001", quality: 2 });
554
+ assert.equal(await a.resolveAlerts("PS0001", "ALARM-3"), 150);
555
+ const resolves = f.calls.filter((c) => c.path === PADBOT_PATHS.resolve);
556
+ assert.deepEqual(resolves.map((c) => c.body.alarmIds.length), [100, 50]);
557
+ assert.deepEqual(f.calls.find((c) => c.path === PADBOT_PATHS.alarms && c.body.pageSize === 100).body.alarmTypes, ["3"]);
558
+ const hist = await a.getPatrolHistory("PS0001", 1, 20);
559
+ assert.equal(hist.total, 1);
560
+ assert.equal(hist.items[0].result, "completed");
561
+ const visits = await a.getPatrolVisits("PS0001", "r1", 1, 20);
562
+ assert.equal(visits.items[0].skipped, true);
563
+ assert.deepEqual(f.calls.find((c) => c.path === PADBOT_PATHS.recordDetails).body, { patrolRecordId: "r1", pageNumber: 1, pageSize: 20 });
564
+ assert.ok(f.calls.every((c) => c.signed));
565
+ });
566
+
567
+ test("adapter listRobots: the account's patrol robots with one batched state read", async () => {
568
+ clearPadbotCache();
569
+ const f = fakePadbot({
570
+ [PADBOT_PATHS.robots]: () => [
571
+ { serialNumber: "PS0001", robotName: "A", robotModel: "S2" },
572
+ { serialNumber: "PS0002", robotName: "B" },
573
+ ],
574
+ [PADBOT_PATHS.states]: () => [{ serialNumber: "PS0001", states: [{ stateType: "1000", data: { updatedAt: fresh } }] }],
575
+ });
576
+ const list = await createPadbotAdapter(CREDS, { baseUrl: "https://pb.test", fetch: f.fetch, now: f.now }).listRobots();
577
+ assert.deepEqual(list.map((r) => [r.robotSn, r.online, r.statusName]), [["PS0001", true, "Standing by"], ["PS0002", false, ""]]);
578
+ assert.deepEqual(f.calls.find((c) => c.path === PADBOT_PATHS.states).body.serialNumbers, ["PS0001", "PS0002"]);
579
+ assert.equal(f.calls.filter((c) => c.path === PADBOT_PATHS.states).length, 1);
580
+ });