-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathWME-BDP-Check.js
More file actions
2378 lines (2129 loc) · 110 KB
/
Copy pathWME-BDP-Check.js
File metadata and controls
2378 lines (2129 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name WME BDP Check
// @namespace https://greasyfork.org/users/166843
// @version 2026.06.26.00
// @description Check for possible BDP routes between two selected segments.
// @author dBsooner
// @match *://*.waze.com/*editor*
// @exclude *://*.waze.com/user/editor*
// @exclude *://*.waze.com/editor/sdk/*
// @require https://greasyfork.org/scripts/509664/code/WME%20Utils%20-%20Bootstrap.js
// @require https://greasyfork.org/scripts/24851-wazewrap/code/WazeWrap.js
// @grant GM_xmlhttpRequest
// @license GPLv3
// @connect greasyfork.org
// @connect waze.com
// ==/UserScript==
/* global GM_info, GM_xmlhttpRequest, WazeWrap, bootstrap*/
(async function () {
'use strict';
// ═════════════════════════════════════════════════════════════════════════════════════
// SETUP
// ═════════════════════════════════════════════════════════════════════════════════════
// ── Script metadata ──────────────────────────────────────────────────────────────────
const _SCRIPT_SHORT_NAME = 'WME BDPC';
const _SCRIPT_LONG_NAME = GM_info.script.name;
const _SCRIPT_AUTHOR = GM_info.script.author;
const _SCRIPT_VERSION = GM_info.script.version;
const _SETTINGS_STORE_NAME = 'WMEBDPC';
const _LOAD_BEGIN_TIME = performance.now();
const _DEBUG = false; // Set to false before release
const _DOWNLOAD_URL = 'https://greasyfork.org/scripts/393407-wme-bdp-check/code/WME%20BDP%20Check.user.js'; // need to update once GF URL is updated.
const _SHOW_UPDATE_MESSAGE = true;
const _SCRIPT_VERSION_CHANGES = ['MIGRATION: Updated to WME SDK!'];
// ── Global SDK instance assigned by bootstrap() ──────────────────────────────────────
let wmeSdk; // WME SDK - initialized by bootstrap()
let _settings = {};
// ── Runtime state ─────────────────────────────────────────────────────────────────────
let _pathEndSegId;
let _restoreZoomLevel;
let _restoreMapCenter;
// ── Element cache ─────────────────────────────────────────────────────────────────────
const _elems = {
div: document.createElement('div'),
'wz-button': document.createElement('wz-button'),
'wz-card': document.createElement('wz-card'),
};
const _timeouts = { saveSettingsToStorage: undefined };
let _bdpCheckButton = null;
let _bdpCheckViaLMButton = null;
// ── Logging utilities ───────────────────────────────────────────────────────────────
function log(message, data = '') {
console.log(`${_SCRIPT_SHORT_NAME}:`, message, data);
}
function logError(message, data = '') {
console.error(`${_SCRIPT_SHORT_NAME}:`, new Error(message), data);
}
function logWarning(message, data = '') {
console.warn(`${_SCRIPT_SHORT_NAME}:`, message, data);
}
function logDebug(message, data = '') {
if (_DEBUG) {
log(message, data);
}
}
// ── Object extend utility (like jQuery.extend) ──────────────────────────────────────
function $extend(...args) {
const extended = {};
const deep = Object.prototype.toString.call(args[0]) === '[object Boolean]' ? args[0] : false;
const merge = function (obj) {
Object.keys(obj).forEach((prop) => {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') {
extended[prop] = $extend(true, extended[prop], obj[prop]);
} else if (obj[prop] !== undefined && obj[prop] !== null) {
extended[prop] = obj[prop];
}
}
});
};
for (let i = deep ? 1 : 0, { length } = args; i < length; i++) {
if (args[i]) {
merge(args[i]);
}
}
return extended;
}
// ── DOM element creation utility ────────────────────────────────────────────────────
function createElem(type = '', attrs = {}, eventListener = []) {
const el = _elems[type]?.cloneNode(false) || _elems.div.cloneNode(false);
const applyEventListeners = function ([evt, cb]) {
return this.addEventListener(evt, cb);
};
Object.keys(attrs).forEach((attr) => {
if (attrs[attr] !== undefined && attrs[attr] !== 'undefined' && attrs[attr] !== null && attrs[attr] !== 'null') {
if (attr === 'textContent' || attr === 'innerHTML') {
el[attr] = attrs[attr];
} else if (attr === 'disabled' || attr === 'checked' || attr === 'selected') {
// For web components, set both property AND attribute to ensure proper state
el[attr] = attrs[attr];
if (attrs[attr] === true) {
el.setAttribute(attr, '');
} else if (attrs[attr] === false) {
el.removeAttribute(attr);
}
} else {
el.setAttribute(attr, attrs[attr]);
}
}
});
if (eventListener.length > 0) {
eventListener.forEach((obj) => {
Object.entries(obj).map(applyEventListeners.bind(el));
});
}
return el;
}
// ═════════════════════════════════════════════════════════════════════════════════════
// SETTINGS MANAGEMENT (localStorage)
// ═════════════════════════════════════════════════════════════════════════════════════
/**
* Load settings from localStorage (no WazeWrap.Remote)
* @returns {Promise<void>}
*/
function loadSettingsFromStorage() {
const defaultSettings = {
lastSaved: 0,
lastVersion: undefined,
};
const stored = localStorage.getItem(_SETTINGS_STORE_NAME);
const loadedSettings = stored ? JSON.parse(stored) : {};
_settings = $extend(true, {}, defaultSettings, loadedSettings);
if (_timeouts.saveSettingsToStorage) {
window.clearTimeout(_timeouts.saveSettingsToStorage);
}
_timeouts.saveSettingsToStorage = window.setTimeout(saveSettingsToStorage, 5000);
return Promise.resolve();
}
/**
* Save settings to localStorage only
*/
function saveSettingsToStorage() {
if (_timeouts.saveSettingsToStorage) {
window.clearTimeout(_timeouts.saveSettingsToStorage);
_timeouts.saveSettingsToStorage = undefined;
}
if (localStorage) {
_settings.lastVersion = _SCRIPT_VERSION;
_settings.lastSaved = Date.now();
localStorage.setItem(_SETTINGS_STORE_NAME, JSON.stringify(_settings));
logDebug('Settings saved to localStorage.');
}
}
/**
* Displays the WazeWrap "script updated" notification banner when the script version changes.
*
* Compares `SCRIPT_VERSION` against the `lastVersion` value stored in `options`. If they
* differ (and `SHOW_UPDATE_MESSAGE` is true) it calls `WazeWrap.Interface.ShowScriptUpdate`
* with the current release notes built from `SCRIPT_VERSION_CHANGES`, then updates
* `lastVersion` and persists it to `localStorage` so the banner is not shown
* again on the next page load.
*
*/
function showScriptInfoAlert() {
/* Check version and alert on update */
if (_SHOW_UPDATE_MESSAGE && _SCRIPT_VERSION !== _settings['lastVersion']) {
let releaseNotes = '';
releaseNotes += "<p>What's New:</p>";
if (_SCRIPT_VERSION_CHANGES.length > 0) {
releaseNotes += '<ul>';
for (let idx = 0; idx < _SCRIPT_VERSION_CHANGES.length; idx++) releaseNotes += `<li>${_SCRIPT_VERSION_CHANGES[idx]}</li>`;
releaseNotes += '</ul>';
} else {
releaseNotes += '<ul><li>Nothing major.</li></ul>';
}
WazeWrap.Interface.ShowScriptUpdate(_SCRIPT_LONG_NAME, _SCRIPT_VERSION, releaseNotes, _DOWNLOAD_URL);
_settings['lastVersion'] = _SCRIPT_VERSION;
if (localStorage) {
saveSettingsToStorage();
}
}
}
// ═════════════════════════════════════════════════════════════════════════════════════
// REPORT CARD DATA STRUCTURE
// ═════════════════════════════════════════════════════════════════════════════════════
/**
* @typedef {Object} BDPReportCard
* @property {string} mode - 'MODE_1' or 'MODE_2' or 'ERROR'
* @property {string} verdict - 'BDP_WILL_APPLY' | 'BDP_WONT_APPLY' | 'ERROR'
* @property {string} verdictMessage - Human-readable verdict (e.g., "BDP will be applied")
* @property {Array<Object>} tests - Array of test results
* @property {string} tests[].name - Test name (e.g., "NAME CONTINUITY")
* @property {boolean} tests[].passed - Whether test passed
* @property {string} tests[].explanation - Short explanation of result
* @property {Object|null} directRoute - Found direct route, if any
* @property {number[]} directRoute.segmentIds - IDs of direct route segments
* @property {number} directRoute.length - Total length in meters
* @property {Array<string>} directRoute.streetNames - Street names in route
*/
/**
* Create empty report card (for error states)
* @returns {BDPReportCard}
*/
/**
* Get human-readable verdict message from verdict code
* @param {string} verdict - 'BDP_WILL_APPLY' | 'BDP_WONT_APPLY' | 'ERROR'
* @param {string} mode - 'MODE_1' or 'MODE_2'
* @returns {string}
*/
function getVerdictMessage(verdict, mode) {
if (verdict === 'BDP_WILL_APPLY') {
if (mode === 'MODE_1') {
return 'Valid direct route exists — BDP will protect against detours';
}
return 'BDP will be applied to this detour route';
}
if (verdict === 'BDP_WONT_APPLY') {
if (mode === 'MODE_1') {
return 'No valid direct route found — BDP cannot be applied';
}
return 'BDP will NOT be applied — detour is not a valid route';
}
return 'Unable to determine result';
}
/**
* Build BDP report card from check results
* Called at the END of doCheckBDP after all checks complete
* @param {Object} checkResults - Results from check (passed to this function by doCheckBDP)
* @param {string} checkResults.mode - 'MODE_1' or 'MODE_2'
* @param {Array<Object>} checkResults.testResults - Array of { name, passed, explanation }
* @param {string} checkResults.verdict - Final verdict
* @param {string} checkResults.verdictMessage - Verdict explanation
* @param {Object|null} checkResults.directRoute - Direct route if found
* @returns {BDPReportCard}
*/
function buildBDPReport(checkResults) {
if (!checkResults) {
return {
mode: 'ERROR',
verdict: 'ERROR',
verdictMessage: 'No check performed',
tests: [],
directRoute: null,
};
}
return {
mode: checkResults.mode || 'ERROR',
verdict: checkResults.verdict || 'ERROR',
verdictMessage: checkResults.verdictMessage || 'Unknown result',
tests: checkResults.testResults || [],
directRoute: checkResults.directRoute || null,
};
}
// ═════════════════════════════════════════════════════════════════════════════════════
// REPORT CARD HTML RENDERING
// ═════════════════════════════════════════════════════════════════════════════════════
/**
* Render report card to HTML
* @param {BDPReportCard} report - Report card object
* @returns {string} HTML string
*/
function renderReportCardHTML(report) {
if (report.verdict === 'ERROR') {
return `
<div class="bdc-card">
<div class="bdc-card-header">
<i class="fa fa-exclamation-circle"></i>
<span>Check Error</span>
</div>
<div class="bdc-card-body" style="padding: 10px;">
<p style="margin: 0; font-size: 11px; color: #666;">${escapeHTML(report.verdictMessage)}</p>
</div>
</div>
`;
}
// Build verdict section (with support for inconclusive)
let verdictClass = 'bdc-verdict-no';
let verdictEmoji = '🚫';
let verdictIcon = 'fa-times-circle';
if (report.verdict === 'BDP_WILL_APPLY') {
verdictClass = 'bdc-verdict-yes';
verdictEmoji = '📍';
verdictIcon = 'fa-check-circle';
} else if (report.verdict === 'INCONCLUSIVE' || report.tests?.some((t) => t.passed === 'inconclusive')) {
verdictClass = 'bdc-verdict-inconclusive';
verdictEmoji = '⚠️';
verdictIcon = 'fa-exclamation-triangle';
}
// Build test results HTML (with support for inconclusive state)
const testsHTML = report.tests
.map((test) => {
let icon = '❌';
if (test.passed === true) {
icon = '✅';
} else if (test.passed === 'inconclusive') {
icon = '⚠️';
}
return `
<div class="bdc-test-result">
<span class="bdc-test-icon">${icon}</span>
<span class="bdc-test-name">${escapeHTML(test.name)}</span>
<span class="bdc-test-explanation">${escapeHTML(test.explanation)}</span>
</div>
`;
})
.join('');
// Build direct route link if applicable
let directRouteHTML = '';
if (report.directRoute && report.directRoute.segmentIds && report.directRoute.segmentIds.length > 0) {
const routeLength = (report.directRoute.length / 1000).toFixed(2);
const routeDataJson = JSON.stringify(report.directRoute);
const routeDataAttr = escapeHTML(routeDataJson);
directRouteHTML = `
<div class="bdc-row" style="flex-direction: column; gap: 8px; align-items: flex-start;">
<div style="font-weight: 600; font-size: 11px;">Direct Route: ${report.directRoute.segmentIds.length} segs, ${routeLength} km</div>
<wz-button color="primary" size="sm" class="bdc-show-route-btn" data-route='${routeDataAttr}'>Show on Map</wz-button>
</div>
`;
}
return `
<div class="bdc-card">
<div class="bdc-card-header">
<i class="fa ${verdictIcon}"></i>
<span>Report (${escapeHTML(report.mode)})</span>
</div>
<div class="bdc-card-body">
<div class="bdc-verdict-box ${verdictClass}">
<span class="bdc-verdict-emoji">${verdictEmoji}</span>
<span class="bdc-verdict-text">${escapeHTML(report.verdictMessage)}</span>
</div>
<div style="border-top: 1px solid var(--hairline, #f0f0f0);">
<div style="padding: 8px 10px; font-weight: 700; font-size: 10px; text-transform: uppercase; letter-spacing: 0.03em; color: #666;">Tests</div>
${testsHTML}
</div>
${directRouteHTML ? `<div style="border-top: 1px solid var(--hairline, #f0f0f0);">${directRouteHTML}</div>` : ''}
</div>
</div>
`;
}
/**
* Global event listener for "Show Direct Route" buttons
* Triggered when user clicks button in report card
* showDirectRouteFromReport() is defined in Task 4
*/
document.addEventListener('click', function (e) {
if (e.target.classList.contains('bdc-show-route-btn')) {
const routeDataJson = e.target.dataset.route;
if (routeDataJson) {
try {
const directRoute = JSON.parse(routeDataJson);
if (typeof showDirectRouteFromReport !== 'undefined') {
showDirectRouteFromReport(directRoute);
}
} catch (err) {
console.error('[BDP Check] Failed to parse route data:', err);
}
}
}
});
/**
* Escape HTML to prevent injection
* @param {string} text
* @returns {string}
*/
function escapeHTML(text) {
if (!text) return '';
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
};
return text.replace(/[&<>"']/g, (m) => map[m]);
}
/**
* Show the direct route segments on the map when user clicks "Show Direct Route" button
* Matches behavior of "Yes" in the direct route confirmation alert:
* - Selects the route segments
* - Restores original zoom level (doesn't zoom in to view route)
* @param {Object} directRoute - Route object from report { segmentIds, length, streetNames }
*/
async function showDirectRouteFromReport(directRoute) {
if (!directRoute || !directRoute.segmentIds || directRoute.segmentIds.length === 0) {
logWarning('showDirectRouteFromReport: No direct route to display');
return;
}
try {
// Select all segments in the direct route (matches line 1301-1305 in alert handler)
wmeSdk.Editing.setSelection({
selection: {
objectType: 'segment',
ids: directRoute.segmentIds,
},
});
// Restore original zoom level (matches line 1307 in alert handler)
await doZoom(true, _restoreZoomLevel, _restoreMapCenter);
logDebug(`showDirectRouteFromReport: Selected ${directRoute.segmentIds.length} segments and restored zoom`);
} catch (err) {
logError('showDirectRouteFromReport error:', err);
}
}
/**
* Get the report container element (creates if missing)
* Used by Task 6 to display report card HTML
* Returns null if container cannot be created/found
* @returns {HTMLElement|null}
*/
function getReportContainer() {
let container = document.getElementById('bdc-report-container');
if (!container) {
// Create container if it doesn't exist
container = createElem('div', {
id: 'bdc-report-container',
className: 'bdc-report-container',
});
const bdcTab = document.getElementById('bdc-check-tab');
if (!bdcTab) {
console.warn('[BDP Check] BDP tab not found; report container created but not attached to DOM');
return null;
}
bdcTab.appendChild(container);
}
return container;
}
// ═════════════════════════════════════════════════════════════════════════════════════
// UTILITY FUNCTIONS (pure math)
// ═════════════════════════════════════════════════════════════════════════════════════
/**
* Get the middle coordinate of a coordinate array
* Returns null for empty arrays
*/
function findMiddle(coordinates) {
if (!coordinates?.length) return null;
return coordinates[Math.floor(coordinates.length / 2)];
}
/**
* Calculate the geographic midpoint between the centers of two segments.
* Uses simple WGS84 averaging - sufficient for small distances at map zoom levels.
*
* @param {Object} startSeg - Segment with geometry.coordinates (GeoJSON LineString)
* @param {Object} endSeg - Segment with geometry.coordinates (GeoJSON LineString)
* @returns {{ lon: number, lat: number } | null}
*/
function getMidpoint(startSeg, endSeg) {
const startCoords = startSeg?.geometry?.coordinates;
const endCoords = endSeg?.geometry?.coordinates;
const startCenter = findMiddle(startCoords);
const endCenter = findMiddle(endCoords);
// Validate before doing any math
if (!startCenter || !endCenter) {
logError('getMidpoint: missing or empty coordinates', { startCoords, endCoords });
return startCenter ? { lon: startCenter[0], lat: startCenter[1] } : null;
}
// Simple average is accurate enough for short inter-segment distances.
const lon = (startCenter[0] + endCenter[0]) / 2;
const lat = (startCenter[1] + endCenter[1]) / 2;
logDebug(`getMidpoint: [${lon}, ${lat}]`);
return { lon, lat };
}
// ═════════════════════════════════════════════════════════════════════════════════════
// SDK HELPER FUNCTIONS
// ═════════════════════════════════════════════════════════════════════════════════════
/**
* Batch-fetches segment objects from SDK by ID array.
* Filters out any nulls (segments not loaded in current map view)
* and logs a warning for each missing segment.
*
* @param {number[]} segmentIds - Array of segment IDs
* @returns {Object[]} Array of non-null segment objects from SDK
*/
function getSegmentsByIds(segmentIds) {
return segmentIds
.map((segmentId) => wmeSdk.DataModel.Segments.getById({ segmentId }))
.filter((seg) => {
if (seg == null) {
logWarning('getSegmentsByIds: a segment was not found or not loaded in current map view');
}
return seg != null;
});
}
/**
* Get street by ID from SDK.
* Returns null if streetId is falsy (0, null, undefined) without
* making a redundant SDK call.
*
* @param {number} streetId - Street ID
* @returns {Object|null} Street object or null
*/
function getStreetById(streetId) {
if (!streetId) return null;
return wmeSdk.DataModel.Streets.getById({ streetId });
}
// ── Live Map Routing Helpers ────────────────────────────────────────────────
/**
* Get the correct Live Map routing API URL based on region code
* @returns {string} Live Map routing API endpoint URL
*/
function getLiveMapRouterUrl() {
const regionCode = wmeSdk.Settings.getRegionCode();
const regionStr = String(regionCode).toLowerCase();
logDebug('getLiveMapRouterUrl: regionCode =', regionCode, 'lowercase =', regionStr);
if (regionStr === 'il') {
return 'https://routing-livemap-il.waze.com/RoutingManager/routingRequest';
} else if (regionStr === 'usa') {
return 'https://routing-livemap-am.waze.com/RoutingManager/routingRequest';
} else {
// REGION_CODE_ROW or unknown
return 'https://routing-livemap-row.waze.com/RoutingManager/routingRequest';
}
}
/**
* Extract center coordinate from a segment using existing findMiddle() utility
* @param {Object} segment - Segment object with geometry.coordinates
* @returns {{ lon: number, lat: number } | null} Center coordinate or null if unavailable
*/
function getSegmentCenter(segment) {
const coords = segment?.geometry?.coordinates;
const middle = findMiddle(coords);
if (!middle) {
logWarning(`getSegmentCenter: segment ${segment?.id} has no coordinates`);
return null;
}
return {
lon: middle[0],
lat: middle[1],
};
}
/**
* Get turns from a segment using getTurnsFromSegment, handling multiple SDK response formats.
* Replicates proven pattern from WME Routing Debugger.JS (line 109-119).
* Returns array of turn objects or empty array on error/missing data.
*/
function getTurnsFromSeg(segId) {
try {
const result = wmeSdk.DataModel.Turns.getTurnsFromSegment({ segmentId: segId });
if (Array.isArray(result)) return result;
if (result?.turns && Array.isArray(result.turns)) return result.turns;
return [];
} catch (e) {
logDebug(`getTurnsFromSeg(${segId}) threw: ${e.message}`);
return [];
}
}
/**
* Verifies if a turn from segA to segB at sharedNodeId is valid using getTurnsFromSegment.
* Based on reference: WME SDK to Verify Routes Between Segments.md
*
* Returns: { valid: boolean, state: 'red'|'unverified'|'allowed'|'conditional', reason: string }
*/
function verifyTurn(fromSegId, nodeId, toSegId) {
try {
// Get segment objects to determine which direction they exit/enter the node
const fromSeg = wmeSdk.DataModel.Segments.getById({ segmentId: fromSegId });
const toSeg = wmeSdk.DataModel.Segments.getById({ segmentId: toSegId });
if (!fromSeg || !toSeg) {
return {
valid: false,
state: 'error',
reason: 'Segment not found',
};
}
// Determine exit direction of fromSeg: true if exiting at toNode (A→B), false if at fromNode (B→A)
const fromSegExitsAtTo = fromSeg.toNodeId === nodeId;
const toSegEntersAtFrom = toSeg.fromNodeId === nodeId;
logDebug(`verifyTurn: ${fromSegId}→${toSegId} at node ${nodeId}`);
logDebug(` fromSeg nodes: from=${fromSeg.fromNodeId} to=${fromSeg.toNodeId}`);
logDebug(` toSeg nodes: from=${toSeg.fromNodeId} to=${toSeg.toNodeId}`);
logDebug(` Looking for: fromSegFwd=${fromSegExitsAtTo}, toSegFwd=${toSegEntersAtFrom}`);
// Get all turns from fromSegment (using proven wrapper pattern)
const turns = getTurnsFromSeg(fromSegId);
logDebug(` Found ${turns.length} turns from segment ${fromSegId}`);
if (turns.length === 0) {
logDebug(` WARNING: No turns returned. Turn data may not be loaded yet.`);
// Return TURN_DATA_UNAVAILABLE status instead of hard failure (Phase 3)
return {
valid: false,
state: 'TURN_DATA_UNAVAILABLE',
reason: 'Turn data not available (SDK data may still be loading)',
};
}
turns.forEach((t, i) => {
if (t.toSegmentId === toSegId) {
logDebug(` Turn ${i}: to=${t.toSegmentId}, fromFwd=${t.fromSegmentFwd}, toFwd=${t.toSegmentFwd}, allowed=${t.isAllowed}`);
}
});
// Find turn that matches BOTH segment IDs AND the correct direction through the node
const turn = turns.find((t) => t.toSegmentId === toSegId && t.fromSegmentFwd === fromSegExitsAtTo && t.toSegmentFwd === toSegEntersAtFrom);
if (!turn) {
// turn object does not exist in this direction
logDebug(` No turn found matching direction!`);
return {
valid: false,
state: 'red',
reason: 'Turn is blocked (turn restriction prevents routing at this junction)',
};
}
logDebug(` Turn found! isAllowed=${turn.isAllowed}`);
if (!turn.isAllowed && turn.restrictions.length === 0) {
// turn exists but isAllowed=false with no restrictions
return {
valid: false,
state: 'red',
reason: 'Turn is blocked (turn restriction prevents routing at this junction)',
};
}
if (turn.isAllowed && turn.restrictions.length > 0) {
// Conditional — allowed with restrictions (time, vehicle, etc)
return {
valid: true,
state: 'conditional',
reason: `Turn allowed with ${turn.restrictions.length} restriction(s) (e.g., time-of-day, vehicle type)`,
restrictions: turn.restrictions,
};
}
// Green arrow — isAllowed=true with no restrictions
return {
valid: true,
state: 'allowed',
reason: 'Turn allowed',
};
} catch (err) {
logDebug(`verifyTurn: SDK error for ${fromSegId}→${toSegId}: ${err.message}`);
return {
valid: false,
state: 'error',
reason: `Error checking turn: ${err.message}`,
};
}
}
/**
* Direction-only check: can traffic physically exit fromSeg at nodeId?
* Used by findDirectRoute to validate segment directionality.
*/
function canExitSegment(segment, nodeId) {
const exitsAtTo = segment.toNodeId === nodeId;
const exitsAtFrom = segment.fromNodeId === nodeId;
const canExit = (exitsAtTo && (segment.isAtoB || segment.isTwoWay)) || (exitsAtFrom && (segment.isBtoA || segment.isTwoWay));
return canExit;
}
/**
* Returns segments connected at a specific end of a segment.
* end === 'from' → segments entering/leaving at the FROM node
* end === 'to' → segments entering/leaving at the TO node
* Uses reverseDirection to target the correct physical end.
*/
function getConnectedAtEnd(segment, end) {
// end: 'from' = get segments connected at fromNodeId (A point)
// 'to' = get segments connected at toNodeId (B point)
const nodeId = end === 'from' ? segment.fromNodeId : segment.toNodeId;
if (nodeId == null) {
logDebug(`getConnectedAtEnd: segment ${segment.id} has no ${end}NodeId`);
return [];
}
try {
const node = wmeSdk.DataModel.Nodes.getById({ nodeId });
if (!node) {
logDebug(`getConnectedAtEnd: node ${nodeId} not found`);
return [];
}
// Filter out the segment itself, return segment objects
return node.connectedSegmentIds
.filter((id) => id !== segment.id)
.map((id) => wmeSdk.DataModel.Segments.getById({ segmentId: id }))
.filter((s) => s != null);
} catch (err) {
logError(`getConnectedAtEnd error:`, err);
return [];
}
}
/**
* Validates that [seg0, seg1, ..., segN] is a fully drivable path.
* Uses getTurnsFromSegment to check actual turn state (red/unverified/green/conditional).
*
* For each consecutive pair:
* 1. Finds shared node
* 2. Checks if traffic can exit segA at that node (direction check)
* 3. Verifies turn using getTurnsFromSegment (turn state check)
*/
function validatePath(segments) {
for (let i = 0; i < segments.length - 1; i++) {
const segA = segments[i];
const segB = segments[i + 1];
// Step 1: Find shared node
const sharedNodeId = getConnectingNode(segA, segB);
if (sharedNodeId == null) {
return {
valid: false,
failIndex: i,
reason: `Segments ${segA.id} and ${segB.id} do not share a node`,
state: 'not_connected',
};
}
// Step 2: Check direction — can segA exit toward the shared node?
if (!canExitSegment(segA, sharedNodeId)) {
return {
valid: false,
failIndex: i,
reason: `Segment ${segA.id} is one-way and flows away from node ${sharedNodeId}`,
state: 'direction_blocked',
};
}
// Step 3: Check turn using getTurnsFromSegment
const turnResult = verifyTurn(segA.id, sharedNodeId, segB.id);
if (!turnResult.valid) {
return {
valid: false,
failIndex: i,
reason: `Segments ${segA.id} to ${segB.id}: ${turnResult.reason}`,
state: turnResult.state,
};
}
}
return { valid: true, failIndex: null, reason: null };
}
/**
* Get the other node from a segment (SDK replacement for segment.getOtherNode())
* Given a segment and one of its nodes, returns the other node
* @param {Object} segment - Segment object with fromNodeId and toNodeId
* @param {Object} knownNode - Node object with id property
* @returns {Object|null} The other node object or null if not found
*/
function getOtherNode(segment, knownNode) {
//logDebug('getOtherNode called');
try {
if (!segment || !knownNode) return null;
if (segment.fromNodeId === knownNode.id) {
return wmeSdk.DataModel.Nodes.getById({ nodeId: segment.toNodeId });
} else if (segment.toNodeId === knownNode.id) {
return wmeSdk.DataModel.Nodes.getById({ nodeId: segment.fromNodeId });
}
logDebug('getOtherNode returning null');
return null;
} catch (err) {
logError('getOtherNode error:', err);
return null;
}
}
// Helper: Find shared node between two segments (JAI pattern from ja_get_connecting_node)
function getConnectingNode(segA, segB) {
if (!segA || !segB) return null;
if (segA.fromNodeId === segB.fromNodeId || segA.fromNodeId === segB.toNodeId) return segA.fromNodeId;
if (segA.toNodeId === segB.fromNodeId || segA.toNodeId === segB.toNodeId) return segA.toNodeId;
return null;
}
// Helper: Given entry node, determine exit node for traversal, respecting one-way direction
function getExitNode(segment, entryNodeId) {
const isAtoB = segment.isAtoB;
const isBtoA = segment.isBtoA;
const isTwoWay = isAtoB && isBtoA;
if (isTwoWay) {
// Two-way: can enter at either node, exit is the other
if (entryNodeId === segment.fromNodeId) return segment.toNodeId;
if (entryNodeId === segment.toNodeId) return segment.fromNodeId;
return null;
}
if (isAtoB) {
// One-way A→B: must enter at fromNode, exits at toNode
if (entryNodeId === segment.fromNodeId) return segment.toNodeId;
return null; // wrong way
}
if (isBtoA) {
// One-way B→A: must enter at toNode, exits at fromNode
if (entryNodeId === segment.toNodeId) return segment.fromNodeId;
return null; // wrong way
}
// Neither isAtoB nor isBtoA — not drivable (railroad, etc.)
return null;
}
// ═════════════════════════════════════════════════════════════════════════════════════
// doZOOM FUNCTION
// ═════════════════════════════════════════════════════════════════════════════════════
/**
* Zoom and pan to a specific location
* Migrated to use wmeSdk.Map APIs
*
* @param {boolean} restore - If true, restore previous zoom/center; otherwise show alert
* @param {number} zoom - Zoom level to set
* @param {Object} coordObj - Coordinates { lon, lat } to center on
*/
async function doZoom(restore = false, zoom = -1, coordObj = {}) {
if (zoom === -1 || Object.entries(coordObj).length === 0) {
return Promise.resolve();
}
try {
// Get current zoom level using SDK (replaces W.map.getZoom)
const currentZoom = wmeSdk.Map.getZoomLevel();
wmeSdk.Map.setMapCenter({
lonLat: {
lon: coordObj.lon,
lat: coordObj.lat,
},
zoomLevel: zoom,
});
logDebug(`doZoom: Set map center to [${coordObj.lon}, ${coordObj.lat}] at zoom ${zoom}`);
if (restore) {
logDebug(`doZoom: Restore mode - no event wait needed`);
_restoreZoomLevel = null;
_restoreMapCenter = undefined;
} else {
// Wait for map data to load at new zoom/center, with 2-second timeout to prevent hanging
logDebug(`doZoom: Waiting for map data with 2s timeout...`);
await Promise.race([
new Promise((resolve) => {
const handleMapDataLoaded = () => {
wmeSdk.Events.off({
eventName: 'wme-map-data-loaded',
eventHandler: handleMapDataLoaded,
});
logDebug(`doZoom: Map data loaded event received`);
resolve();
};
wmeSdk.Events.on({
eventName: 'wme-map-data-loaded',
eventHandler: handleMapDataLoaded,
});
}),
new Promise((resolve) => {
setTimeout(() => {
logDebug(`doZoom: Timeout after 2s - proceeding anyway`);
resolve();
}, 2000);
}),
]);
}
} catch (err) {
logError('doZoom error:', err);
}
return Promise.resolve();
}
// ═════════════════════════════════════════════════════════════════════════════════════
// RTG and Name Continuity FUNCTIONS
// ═════════════════════════════════════════════════════════════════════════════════════
function rtgContinuityCheck([...segs] = []) {
if (segs.length < 2) return false;
const rtg = { 7: 'mH', 6: 'MHFW', 3: 'MHFW' };
const seg1rtg = rtg[segs[0].roadType];
// If the first segment has no defined RTG group, can't check continuity
if (seg1rtg === undefined) return false;
// Compare all remaining segments against the first segment's RTG
// Uses slice(1) instead of splice(0,1) — no mutation needed
return segs.slice(1).every((el) => {
const currentRTG = rtg[el.roadType];
if (currentRTG === undefined) return false;
return seg1rtg === currentRTG;
});
}
function nameContinuityCheck([...segs] = []) {
if (segs.length < 2) return false;
// Helper: collect all non-empty street names from a segment
function getSegStreetNames(seg) {
const names = [];
if (seg.primaryStreetId) {
const street = getStreetById(seg.primaryStreetId);
if (street?.name?.length > 0) names.push(street.name);
}
if (seg.alternateStreetIds?.length > 0) {
for (const streetId of seg.alternateStreetIds) {
const street = getStreetById(streetId);
if (street?.name?.length > 0) names.push(street.name);
}
}
return names;
}
if (segs.length === 2) {
// ── TWO-SEGMENT MODE ──────────────────────────────────────────────────────
// Used for: bracketing segment pair check (must share a name)
const seg0Names = getSegStreetNames(segs[0]);
if (seg0Names.length === 0) return false;
const seg1Names = getSegStreetNames(segs[1]);
// True if any name in seg1 appears in seg0's name list
return seg1Names.some((name) => seg0Names.includes(name));
} else {
// ── MULTI-SEGMENT MODE ────────────────────────────────────────────────────
// Used for: full route continuity check
// Rule: every middle segment must share a name with EITHER
// the first segment OR the last segment
const firstSeg = segs[0];
const lastSeg = segs[segs.length - 1];
const middleSegs = segs.slice(1, -1); // everything between first and last
const bs1Names = getSegStreetNames(firstSeg);
const bs2Names = getSegStreetNames(lastSeg);
if (bs1Names.length === 0) return false;
if (bs2Names.length === 0) return false;
return middleSegs.every((el) => {
const elNames = getSegStreetNames(el);
return elNames.some((name) => bs1Names.includes(name) || bs2Names.includes(name));
});
}
}
// ═════════════════════════════════════════════════════════════════════════════════════
// LIVE MAP ROUTING FUNCTION