forked from ChelseaKR/nearmiss
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathus-coverage.js
More file actions
3177 lines (3041 loc) · 120 KB
/
Copy pathus-coverage.js
File metadata and controls
3177 lines (3041 loc) · 120 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
/* Auditable nationwide FARS context — framework-free, bilingual, and driven
* only by a hash-bound release index and its checked-in public projections.
* Suppressed cells never acquire a numeric value in this UI. */
(function () {
"use strict";
var INDEX_URL = "/data/published/fars-state-mode-index-v2.json";
var DATA_ROOT = "/data/published/";
var DEFAULT_2024_DATA_URL = DATA_ROOT + "fars-2024-state-mode-r2.json";
var BOUNDARY_URL = "/data/published/us-state-boundaries-2024.json";
var EXPECTED_INDEX_BYTES = 5273;
var EXPECTED_INDEX_SHA256 = "594b13a65f5b88661db8acb21c73fc55ddc61ba94e5a659cdd27463c178f50f5";
var EXPECTED_BOUNDARY_ARTIFACT_BYTES = 323232;
var EXPECTED_BOUNDARY_ARTIFACT_SHA256 = "705219b3339077f1d03466391bb286fe7f1841298fc0bcce948de1d8c66df25d";
var EXPECTED_BOUNDARY_SOURCE_URL =
"https://www2.census.gov/geo/tiger/GENZ2024/kml/cb_2024_us_state_20m.zip";
var EXPECTED_BOUNDARY_SOURCE_SHA256 = "37337db59415f010c594fba96a48aa6e950e633dc0e555cc7b1ce8edd794c673";
var EXPECTED_BOUNDARY_SOURCE_BYTES = 158066;
var SUPPORTED_YEARS = [2020, 2021, 2022, 2023, 2024];
var EXPECTED_MODES = [
"motor_vehicle_occupant",
"motorcyclist",
"pedalcyclist",
"pedestrian",
"other_road_user",
"unknown",
];
var EXPECTED_INDEX_SCHEMA_VERSION = "1.0.0";
var EXPECTED_INDEX_ARTIFACT_TYPE = "nearmiss.public.fars_state_context_index";
var EXPECTED_ARTIFACT_SCHEMA_VERSION = "1.0.0";
var EXPECTED_ARTIFACT_TYPE = "nearmiss.public.fars_state_context";
var EXPECTED_ALGORITHM_VERSION = "state-involved-mode-v1";
var EXPECTED_YEAR_CONTRACTS = {
2020: {
contract_revision: 1,
contract_sha256: "c6294413066bb2e83b2aea02408dcfa2fa40441dda7de115983a45fb8aab132c",
crash_mapping_version: "1.0.0",
person_mapping_version: "1.0.0",
semantic_regime_id: "fars_per_typ_2020_2021_v1",
state_code_system: "nhtsa_fars_state_2020",
},
2021: {
contract_revision: 1,
contract_sha256: "5c2c198cd4e3eee80f9e27874e3f42521b0e0b7cbc53a8bd0bf2684ef66a855e",
crash_mapping_version: "1.0.0",
person_mapping_version: "1.0.0",
semantic_regime_id: "fars_per_typ_2020_2021_v1",
state_code_system: "nhtsa_fars_state_2021",
},
2022: {
contract_revision: 1,
contract_sha256: "18713f23f657334459febf729e4005bfd9e94492da37afb0255d9e5fd4159158",
crash_mapping_version: "1.0.0",
person_mapping_version: "1.0.0",
semantic_regime_id: "fars_per_typ_2022_2024_v1",
state_code_system: "nhtsa_fars_state_2022",
},
2023: {
contract_revision: 1,
contract_sha256: "557a8edf2418c7794d349c932ae2237db6cad7165f62c80a2e7f3b15baeca143",
crash_mapping_version: "1.0.0",
person_mapping_version: "1.0.0",
semantic_regime_id: "fars_per_typ_2022_2024_v1",
state_code_system: "nhtsa_fars_state_2023",
},
2024: {
contract_revision: 2,
contract_sha256: "2a24d2cad5341a8ffbe77272b59ccaf0c983a2e9beb763551bb3df7f4ef02b63",
crash_mapping_version: "1.0.0",
person_mapping_version: "1.0.0",
semantic_regime_id: "fars_per_typ_2022_2024_v1",
state_code_system: "nhtsa_fars_state_2024",
},
};
var EXPECTED_RELEASE_STAGES = {
2020: "final",
2021: "final",
2022: "final",
2023: "final",
2024: "annual_report_file",
};
var EXPECTED_STATES = [
"1|AL|Alabama",
"2|AK|Alaska",
"4|AZ|Arizona",
"5|AR|Arkansas",
"6|CA|California",
"8|CO|Colorado",
"9|CT|Connecticut",
"10|DE|Delaware",
"11|DC|District of Columbia",
"12|FL|Florida",
"13|GA|Georgia",
"15|HI|Hawaii",
"16|ID|Idaho",
"17|IL|Illinois",
"18|IN|Indiana",
"19|IA|Iowa",
"20|KS|Kansas",
"21|KY|Kentucky",
"22|LA|Louisiana",
"23|ME|Maine",
"24|MD|Maryland",
"25|MA|Massachusetts",
"26|MI|Michigan",
"27|MN|Minnesota",
"28|MS|Mississippi",
"29|MO|Missouri",
"30|MT|Montana",
"31|NE|Nebraska",
"32|NV|Nevada",
"33|NH|New Hampshire",
"34|NJ|New Jersey",
"35|NM|New Mexico",
"36|NY|New York",
"37|NC|North Carolina",
"38|ND|North Dakota",
"39|OH|Ohio",
"40|OK|Oklahoma",
"41|OR|Oregon",
"42|PA|Pennsylvania",
"44|RI|Rhode Island",
"45|SC|South Carolina",
"46|SD|South Dakota",
"47|TN|Tennessee",
"48|TX|Texas",
"49|UT|Utah",
"50|VT|Vermont",
"51|VA|Virginia",
"53|WA|Washington",
"54|WV|West Virginia",
"55|WI|Wisconsin",
"56|WY|Wyoming",
];
var lang = window.NearmissI18n.langFromQuery("en");
var i18n = window.NearmissI18n.create("web.coverage.");
var releaseIndex = null;
var currentRelease = null;
var artifact = null;
var boundaryArtifact = null;
var boundaryPromise = null;
var rows = [];
var artifactPromises = {};
var profileArtifacts = null;
var profileState = "";
var requestSerial = 0;
var profileRequestSerial = 0;
var languageRequestSerial = 0;
var requestedModeFromUrl = null;
var viewState = {
view: "map",
mapLevel: "national",
primaryMode: "pedalcyclist",
secondaryMode: "pedestrian",
selectedState: null,
compareA: null,
compareB: null,
scale: "linear",
saved: [],
};
var VALID_VIEWS = { map: true, matrix: true, rank: true, scatter: true, compare: true };
var VALID_MAP_LEVELS = { national: true, state: true };
var SVG_NS = "http://www.w3.org/2000/svg";
function t(key) {
return i18n.t(key);
}
function tpl(text, values) {
return text.replace(/\{(\w+)\}/g, function (_, key) {
return values[key];
});
}
function renderTranslation(element, key) {
var translated = t(key);
if (element.tagName === "UL") {
var listPattern = /^(?:<li>[^<>]*<\/li>)+$/;
if (!listPattern.test(translated)) {
element.textContent = translated;
return;
}
element.textContent = "";
(translated.match(/<li>[^<>]*<\/li>/g) || []).forEach(function (item) {
var listItem = document.createElement("li");
listItem.textContent = item.slice(4, -5);
element.appendChild(listItem);
});
return;
}
var strongParts = /^([^<>]*)<strong>([^<>]*)<\/strong>([^<>]*)$/.exec(translated);
if (!strongParts) {
element.textContent = translated;
return;
}
element.textContent = "";
element.appendChild(document.createTextNode(strongParts[1]));
var emphasis = document.createElement("strong");
emphasis.textContent = strongParts[2];
element.appendChild(emphasis);
element.appendChild(document.createTextNode(strongParts[3]));
}
function isObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function isNonNegativeInteger(value) {
return Number.isInteger(value) && value >= 0;
}
function hasOwn(object, key) {
return Object.prototype.hasOwnProperty.call(object, key);
}
function assert(condition, message) {
if (!condition) throw new Error("Invalid public FARS release: " + message);
}
function assertExactKeys(object, expected, label) {
assert(isObject(object), label + " must be an object");
var actual = Object.keys(object).sort();
var wanted = expected.slice().sort();
assert(sameOrderedValues(actual, wanted), label + " has missing or unexpected fields");
}
function sameOrderedValues(actual, expected) {
return (
Array.isArray(actual) &&
actual.length === expected.length &&
actual.every(function (value, index) {
return value === expected[index];
})
);
}
function isSha256(value) {
return typeof value === "string" && /^[0-9a-f]{64}$/.test(value);
}
function isSupportedYear(value) {
return Number.isInteger(value) && SUPPORTED_YEARS.indexOf(value) >= 0;
}
function stateParts(value) {
var parts = value.split("|");
return { code: parts[0], abbreviation: parts[1], name: parts[2] };
}
function stateDefinition(abbreviation) {
return (
EXPECTED_STATES.map(stateParts).find(function (state) {
return state.abbreviation === abbreviation;
}) || null
);
}
function isValidState(abbreviation) {
return typeof abbreviation === "string" && stateDefinition(abbreviation) !== null;
}
function expectedSourceUrl(year) {
return (
"https://static.nhtsa.gov/nhtsa/downloads/FARS/" +
year +
"/National/FARS" +
year +
"NationalCSV.zip"
);
}
function expectedTitle(year) {
return year + " US fatal-crash burden by state and involved mode";
}
function expectedCaveat(year) {
return (
"Counts are distinct " +
year +
" FARS fatal crashes with at least one person in the involved mode, " +
"counted at most once per crash per mode. They are fatal-crash burden context, not " +
"exposure-normalized risk, incidence, causation, nonfatal crashes, near misses, record " +
"linkage, outcome validation, or a safety ranking. Mode cells overlap and are non-additive. " +
"A suppressed_or_zero cell combines a true zero with a positive count below k=10 and must " +
"never be read as zero. k=10 is a stability and publication guard for already-public FARS " +
"data, not a confidentiality guarantee. The official " +
year +
" National archive covers the 50 states and District " +
"of Columbia; Puerto Rico requires a separately verified source."
);
}
function validateIndex(data) {
assertExactKeys(
data,
["schema_version", "artifact_type", "visibility", "default_year", "contract", "releases"],
"release index"
);
assert(data.schema_version === EXPECTED_INDEX_SCHEMA_VERSION, "index schema version is unsupported");
assert(data.artifact_type === EXPECTED_INDEX_ARTIFACT_TYPE, "index artifact type is unsupported");
assert(data.visibility === "public", "index visibility must be public");
var contract = data.contract;
assertExactKeys(
contract,
[
"algorithm_version",
"artifact_schema_version",
"artifact_type",
"contribution_unit",
"dimension",
"effective_k",
"modes",
"modes_non_additive",
"state_count",
],
"index contract"
);
assert(contract.algorithm_version === EXPECTED_ALGORITHM_VERSION, "index algorithm is unsupported");
assert(contract.artifact_schema_version === EXPECTED_ARTIFACT_SCHEMA_VERSION, "artifact schema is unsupported");
assert(contract.artifact_type === EXPECTED_ARTIFACT_TYPE, "indexed artifact type is unsupported");
assert(contract.contribution_unit === "distinct_crash_once_per_involved_mode", "contribution unit is unsupported");
assert(contract.dimension === "involved_mode", "index dimension is unsupported");
assert(contract.effective_k === 10, "index publication floor is unsupported");
assert(contract.modes_non_additive === true, "index must mark modes non-additive");
assert(contract.state_count === 51, "index must cover 50 states and DC");
assert(sameOrderedValues(contract.modes, EXPECTED_MODES), "index mode inventory is unsupported");
assert(Array.isArray(data.releases) && data.releases.length >= 1 && data.releases.length <= 5, "index release inventory is invalid");
var years = [];
data.releases.forEach(function (release) {
assertExactKeys(
release,
["artifact_bytes", "artifact_path", "artifact_sha256", "contract", "dataset_year", "geography", "source"],
"index release"
);
var year = release.dataset_year;
assert(isSupportedYear(year), "release year is not supported");
years.push(year);
assert(
Number.isInteger(release.artifact_bytes) && release.artifact_bytes >= 1 && release.artifact_bytes <= 262144,
"release byte length is invalid"
);
assert(isSha256(release.artifact_sha256), "release artifact digest is invalid");
assertExactKeys(
release.contract,
[
"contract_revision",
"contract_sha256",
"crash_mapping_version",
"person_mapping_version",
"semantic_regime_id",
"state_code_system",
],
"release annual contract"
);
assert(
Object.keys(EXPECTED_YEAR_CONTRACTS[year]).every(function (field) {
return release.contract[field] === EXPECTED_YEAR_CONTRACTS[year][field];
}),
"release annual contract provenance is not reviewed"
);
var expectedPath =
"fars-" +
year +
"-state-mode" +
(release.contract.contract_revision === 1 ? "" : "-r" + release.contract.contract_revision) +
".json";
assert(release.artifact_path === expectedPath, "release path is not canonical");
assertExactKeys(
release.source,
["distribution_url", "raw_sha256", "raw_size_bytes", "source_revision_id"],
"release source"
);
assert(release.source.distribution_url === expectedSourceUrl(year), "release source URL is not fixed-year National FARS");
assert(isSha256(release.source.raw_sha256), "release raw digest is invalid");
assert(
Number.isInteger(release.source.raw_size_bytes) &&
release.source.raw_size_bytes >= 1 &&
release.source.raw_size_bytes <= 268435456,
"release raw byte size is invalid"
);
assert(
typeof release.source.source_revision_id === "string" &&
/^reviewed-[0-9]{8}-[0-9a-f]{12}$/.test(release.source.source_revision_id),
"release source revision is invalid"
);
assertExactKeys(
release.geography,
["coverage", "state_crosswalk_sha256", "state_crosswalk_version"],
"release geography"
);
assert(
release.geography.coverage === "official_" + year + "_national_50_states_and_dc",
"release geography coverage is invalid"
);
assert(
release.geography.state_crosswalk_version === "fars-usps-50-states-dc-" + year + "-v1",
"release crosswalk version is invalid"
);
assert(isSha256(release.geography.state_crosswalk_sha256), "release crosswalk digest is invalid");
});
assert(
years.every(function (year, index) {
return index === 0 || year > years[index - 1];
}),
"release years must be unique and ascending"
);
assert(data.default_year === years[years.length - 1], "default year must be the newest published release");
return data;
}
function validateAccounting(data, observed) {
var accounting = data.accounting;
var integerFields = [
"case_count",
"state_count",
"state_mode_cell_count",
"published_cell_count",
"suppressed_or_zero_cell_count",
"positive_candidate_cell_count",
"positive_suppressed_cell_count",
"crash_contribution_total",
"published_crash_contribution_total",
"suppressed_crash_contribution_total",
];
assertExactKeys(accounting, integerFields, "accounting");
integerFields.forEach(function (field) {
assert(isNonNegativeInteger(accounting[field]), "accounting." + field + " must be a non-negative integer");
});
assert(accounting.case_count >= 30000 && accounting.case_count <= 45000, "case count is outside the national bound");
assert(accounting.state_count === observed.states, "accounting state count does not match states");
assert(accounting.state_mode_cell_count === observed.cells, "accounting cell count does not match cells");
assert(accounting.published_cell_count === observed.published, "accounting published count does not match cells");
assert(
accounting.suppressed_or_zero_cell_count === observed.withheld,
"accounting suppressed-or-zero count does not match cells"
);
assert(
accounting.published_crash_contribution_total === observed.publishedContributions,
"accounting published contributions do not match public counts"
);
assert(
accounting.published_cell_count + accounting.suppressed_or_zero_cell_count === accounting.state_mode_cell_count,
"accounting cell totals do not reconcile"
);
assert(
accounting.positive_candidate_cell_count ===
accounting.published_cell_count + accounting.positive_suppressed_cell_count,
"accounting positive-cell totals do not reconcile"
);
assert(
accounting.positive_suppressed_cell_count <= accounting.suppressed_or_zero_cell_count,
"positive suppressed cells exceed suppressed-or-zero cells"
);
assert(
(accounting.positive_suppressed_cell_count === 0 && accounting.suppressed_crash_contribution_total === 0) ||
(accounting.positive_suppressed_cell_count >= 2 &&
accounting.suppressed_crash_contribution_total >= accounting.positive_suppressed_cell_count &&
accounting.suppressed_crash_contribution_total <
accounting.positive_suppressed_cell_count * data.metric.effective_k),
"suppressed contribution total is inconsistent with k"
);
assert(
accounting.published_crash_contribution_total + accounting.suppressed_crash_contribution_total ===
accounting.crash_contribution_total,
"accounting contribution totals do not reconcile"
);
assert(
accounting.crash_contribution_total >= accounting.case_count &&
accounting.crash_contribution_total <= accounting.case_count * EXPECTED_MODES.length,
"accounting contributions are outside the case-count bound"
);
}
function validateArtifact(data, release, contract) {
assert(release && contract, "artifact validation requires its indexed release");
assertExactKeys(
data,
["schema_version", "artifact_type", "visibility", "title", "dataset_year", "source", "geography", "metric", "accounting", "caveat", "states"],
"artifact top level"
);
var year = release.dataset_year;
assert(data.visibility === "public", "artifact visibility must be public");
assert(data.dataset_year === year, "artifact year does not match its index entry");
assert(data.schema_version === contract.artifact_schema_version, "artifact schema version is unsupported");
assert(data.artifact_type === contract.artifact_type, "artifact type is unsupported");
assert(data.title === expectedTitle(year), "artifact title does not match its year");
assert(data.caveat === expectedCaveat(year), "artifact caveat does not match its year");
assertExactKeys(
data.source,
["name", "release_stage", "distribution_url", "source_revision_id", "raw_size_bytes", "raw_sha256"],
"artifact source"
);
assert(
data.source.release_stage === EXPECTED_RELEASE_STAGES[year],
"artifact release stage is not the reviewed annual stage"
);
assert(data.source.name === "NHTSA Fatality Analysis Reporting System (FARS)", "source name is unsupported");
["distribution_url", "source_revision_id", "raw_size_bytes", "raw_sha256"].forEach(function (field) {
assert(data.source[field] === release.source[field], "artifact source." + field + " drifted from the index");
});
assertExactKeys(
data.geography,
["type", "coverage", "state_count", "state_crosswalk_version", "state_crosswalk_sha256"],
"artifact geography"
);
assert(data.geography.type === "fars_state_code", "geography must use source-native FARS state codes");
assert(data.geography.state_count === contract.state_count, "geography must contain 50 states and DC");
["coverage", "state_crosswalk_version", "state_crosswalk_sha256"].forEach(function (field) {
assert(data.geography[field] === release.geography[field], "artifact geography." + field + " drifted from the index");
});
assertExactKeys(
data.metric,
["algorithm_version", "dimension", "contribution_unit", "effective_k", "modes_non_additive", "modes"],
"artifact metric"
);
assert(data.metric.algorithm_version === contract.algorithm_version, "metric algorithm drifted from the index");
assert(data.metric.dimension === contract.dimension, "metric dimension drifted from the index");
assert(data.metric.contribution_unit === contract.contribution_unit, "metric contribution unit drifted from the index");
assert(data.metric.modes_non_additive === contract.modes_non_additive, "mode additivity flag drifted from the index");
assert(data.metric.effective_k === contract.effective_k, "publication floor drifted from the index");
assert(sameOrderedValues(data.metric.modes, contract.modes), "mode inventory or order drifted from the index");
assert(Array.isArray(data.states) && data.states.length === contract.state_count, "states must contain 50 states and DC");
var observed = { states: data.states.length, cells: 0, published: 0, withheld: 0, publishedContributions: 0 };
data.states.forEach(function (state, stateIndex) {
assertExactKeys(state, ["state_code", "state_abbreviation", "state_name", "cells"], "artifact state");
assert(typeof state.state_code === "string", "state code must remain a source-native string");
assert(
[state.state_code, state.state_abbreviation, state.state_name].join("|") === EXPECTED_STATES[stateIndex],
"state crosswalk or canonical ordering is unsupported"
);
assert(Array.isArray(state.cells) && state.cells.length === contract.modes.length, "each state needs six mode cells");
var cellModes = [];
state.cells.forEach(function (cell) {
assert(isObject(cell), "each cell must be an object");
cellModes.push(cell.involved_mode);
observed.cells += 1;
if (cell.status === "published") {
assertExactKeys(cell, ["involved_mode", "status", "crash_count"], "published cell");
assert(
isNonNegativeInteger(cell.crash_count) &&
cell.crash_count >= data.metric.effective_k &&
cell.crash_count <= data.accounting.case_count,
"published count is outside its fixed-year bounds"
);
observed.published += 1;
observed.publishedContributions += cell.crash_count;
} else {
assertExactKeys(cell, ["involved_mode", "status"], "suppressed-or-zero cell");
assert(cell.status === "suppressed_or_zero", "cell status is unsupported");
assert(!hasOwn(cell, "crash_count"), "suppressed-or-zero cells must not contain a count");
observed.withheld += 1;
}
});
assert(sameOrderedValues(cellModes, contract.modes), "state cells do not follow the canonical mode order");
});
validateAccounting(data, observed);
return data;
}
function validateBoundaryRing(ring, label) {
assert(Array.isArray(ring) && ring.length >= 4, label + " must contain at least four positions");
ring.forEach(function (position) {
assert(
Array.isArray(position) &&
position.length === 2 &&
Number.isFinite(position[0]) &&
Number.isFinite(position[1]),
label + " positions must be finite [longitude, latitude] pairs"
);
assert(position[0] >= -180 && position[0] <= 180, label + " longitude is outside WGS84 bounds");
assert(position[1] >= -90 && position[1] <= 90, label + " latitude is outside WGS84 bounds");
});
assert(
ring[0][0] === ring[ring.length - 1][0] && ring[0][1] === ring[ring.length - 1][1],
label + " must be closed"
);
}
function validateBoundaryArtifact(data) {
assertExactKeys(data, ["type", "name", "source", "features"], "boundary top level");
assert(data.type === "FeatureCollection", "boundary type must be FeatureCollection");
assert(
data.name === "2024 Census cartographic boundaries for the 50 states and DC",
"boundary title is not reviewed"
);
assertExactKeys(
data.source,
["name", "vintage", "resolution", "distribution_url", "raw_zip_sha256", "raw_zip_size_bytes", "conversion"],
"boundary source"
);
assert(
data.source.name === "U.S. Census Bureau 2024 Cartographic Boundary Files",
"boundary source name is not reviewed"
);
assert(data.source.vintage === 2024, "boundary vintage is not reviewed");
assert(data.source.resolution === "1:20,000,000", "boundary resolution is not reviewed");
assert(data.source.distribution_url === EXPECTED_BOUNDARY_SOURCE_URL, "boundary source URL is not reviewed");
assert(data.source.raw_zip_sha256 === EXPECTED_BOUNDARY_SOURCE_SHA256, "boundary source checksum is not reviewed");
assert(data.source.raw_zip_size_bytes === EXPECTED_BOUNDARY_SOURCE_BYTES, "boundary source size is not reviewed");
assert(
data.source.conversion ===
"KML polygons to RFC 7946 GeoJSON; coordinates rounded to 6 decimals; 50 states and DC retained",
"boundary conversion is not reviewed"
);
assert(Array.isArray(data.features) && data.features.length === 51, "boundaries must contain 50 states and DC");
data.features.forEach(function (feature, index) {
assertExactKeys(feature, ["type", "id", "properties", "geometry"], "boundary feature");
assert(feature.type === "Feature", "boundary member must be a Feature");
assertExactKeys(
feature.properties,
["state_fips", "state_abbreviation", "state_name"],
"boundary properties"
);
var expected = EXPECTED_STATES[index].split("|");
assert(String(Number(feature.properties.state_fips)) === expected[0], "boundary FIPS order is not reviewed");
assert(feature.properties.state_abbreviation === expected[1], "boundary abbreviation is not reviewed");
assert(feature.properties.state_name === expected[2], "boundary state name is not reviewed");
assert(feature.id === expected[1], "boundary feature ID is not reviewed");
assertExactKeys(feature.geometry, ["type", "coordinates"], "boundary geometry");
assert(
feature.geometry.type === "Polygon" || feature.geometry.type === "MultiPolygon",
"boundary geometry type is not supported"
);
var polygons = feature.geometry.type === "Polygon" ? [feature.geometry.coordinates] : feature.geometry.coordinates;
assert(Array.isArray(polygons) && polygons.length > 0, "boundary geometry must contain polygons");
polygons.forEach(function (polygon, polygonIndex) {
assert(Array.isArray(polygon) && polygon.length > 0, "boundary polygon must contain rings");
polygon.forEach(function (ring, ringIndex) {
validateBoundaryRing(ring, "boundary polygon " + polygonIndex + " ring " + ringIndex);
});
});
});
return data;
}
function verifiedJson(response, expectedBytes, expectedSha256, label) {
var payload;
if (!response.ok) throw new Error("HTTP " + response.status);
assert(typeof response.arrayBuffer === "function", label + " response cannot provide exact bytes");
return response
.arrayBuffer()
.then(function (buffer) {
payload = buffer;
assert(payload && payload.byteLength === expectedBytes, label + " byte length is not reviewed");
assert(
window.crypto && window.crypto.subtle && typeof window.crypto.subtle.digest === "function",
"Web Crypto SHA-256 support is required"
);
return window.crypto.subtle.digest("SHA-256", payload);
})
.then(function (digest) {
var actual = Array.from(new Uint8Array(digest))
.map(function (byte) {
return byte.toString(16).padStart(2, "0");
})
.join("");
assert(actual === expectedSha256, label + " SHA-256 is not reviewed");
assert(typeof window.TextDecoder === "function", "UTF-8 decoder support is required");
return JSON.parse(new window.TextDecoder("utf-8", { fatal: true }).decode(payload));
});
}
function loadArtifact(release) {
var year = release.dataset_year;
if (!hasOwn(artifactPromises, year)) {
artifactPromises[year] = fetch(DATA_ROOT + release.artifact_path)
.then(function (response) {
return verifiedJson(response, release.artifact_bytes, release.artifact_sha256, "annual artifact");
})
.then(function (data) {
return validateArtifact(data, release, releaseIndex.contract);
})
.catch(function (error) {
delete artifactPromises[year];
throw error;
});
}
return artifactPromises[year];
}
function loadBoundaryArtifact() {
if (!boundaryPromise) {
boundaryPromise = fetch(BOUNDARY_URL)
.then(function (response) {
return verifiedJson(
response,
EXPECTED_BOUNDARY_ARTIFACT_BYTES,
EXPECTED_BOUNDARY_ARTIFACT_SHA256,
"boundary artifact"
);
})
.then(validateBoundaryArtifact)
.catch(function (error) {
boundaryPromise = null;
throw error;
});
}
return boundaryPromise;
}
function flatten(data) {
var output = [];
data.states.forEach(function (state) {
state.cells.forEach(function (cell) {
output.push({
year: data.dataset_year,
stateCode: state.state_code,
stateAbbreviation: state.state_abbreviation,
stateName: state.state_name,
mode: cell.involved_mode,
status: cell.status,
count: cell.status === "published" ? cell.crash_count : null,
});
});
});
return output;
}
function modeLabel(mode) {
return t("mode_" + mode);
}
function number(value) {
return new Intl.NumberFormat(lang).format(value);
}
function cell(tag, value, className) {
var element = document.createElement(tag);
element.textContent = value;
if (className) element.className = className;
return element;
}
function svgElement(tag, attributes, textValue) {
var element = document.createElementNS(SVG_NS, tag);
Object.keys(attributes || {}).forEach(function (key) {
element.setAttribute(key, String(attributes[key]));
});
if (textValue != null) element.textContent = textValue;
return element;
}
function stateRecord(abbreviation) {
if (!artifact || !abbreviation) return null;
return (
artifact.states.find(function (state) {
return state.state_abbreviation === abbreviation;
}) || null
);
}
function rowFor(abbreviation, mode) {
return (
rows.find(function (row) {
return row.stateAbbreviation === abbreviation && row.mode === mode;
}) || null
);
}
function rowsForState(abbreviation) {
return rows.filter(function (row) {
return row.stateAbbreviation === abbreviation;
});
}
function focusMode() {
var select = document.getElementById("mode-filter");
return (select && select.value) || viewState.primaryMode;
}
function statusText(status) {
return status === "published" ? t("cell_published") : t("cell_not_published");
}
function clearProfileTable() {
document.getElementById("profile-early-body").textContent = "";
document.getElementById("profile-late-body").textContent = "";
document.getElementById("state-profile-wrap").hidden = true;
}
function setProfileStatus(key, className) {
var status = document.getElementById("state-profile-status");
document
.getElementById("state-profile")
.setAttribute("aria-busy", className === "is-loading" ? "true" : "false");
status.setAttribute("data-i18n", key);
status.textContent = t(key);
status.className = "state-profile-status" + (className ? " " + className : "");
}
function showProfileEmpty() {
profileArtifacts = null;
profileState = "";
clearProfileTable();
setProfileStatus("profile_empty", "");
}
function showProfileLoading() {
profileArtifacts = null;
profileState = "";
clearProfileTable();
setProfileStatus("profile_loading", "is-loading");
}
function showProfileError() {
profileArtifacts = null;
profileState = "";
clearProfileTable();
setProfileStatus("profile_error", "is-error");
}
function profileStateFromArtifact(data, abbreviation) {
return (
data.states.find(function (state) {
return state.state_abbreviation === abbreviation;
}) || null
);
}
function renderRegimeGroup(body, labelKey, years) {
body.textContent = "";
var labelRow = document.createElement("tr");
labelRow.className = "profile-regime-label";
var label = cell("th", t(labelKey));
label.id = body.id + "-label";
label.colSpan = 7;
label.scope = "rowgroup";
body.setAttribute("aria-labelledby", label.id);
labelRow.appendChild(label);
body.appendChild(labelRow);
years.forEach(function (year) {
var data = profileArtifacts[year];
var state = profileStateFromArtifact(data, profileState);
assert(state, "selected profile state is missing from an annual artifact");
var row = document.createElement("tr");
row.className = "profile-year-row";
row.dataset.year = String(year);
row.appendChild(cell("th", String(year)));
row.firstElementChild.scope = "row";
EXPECTED_MODES.forEach(function (mode, modeIndex) {
var result = state.cells[modeIndex];
assert(result.involved_mode === mode, "profile mode order drifted after validation");
var value;
if (result.status === "published") {
value = cell("td", number(result.crash_count), "profile-value");
} else {
value = cell("td", t("cell_not_published"), "profile-withheld");
}
value.dataset.status = result.status;
value.dataset.mode = mode;
row.appendChild(value);
});
body.appendChild(row);
});
}
function renderStateProfile() {
if (!profileArtifacts || !profileState) return;
var definition = stateDefinition(profileState);
assert(definition, "selected profile state is unsupported");
renderRegimeGroup(
document.getElementById("profile-early-body"),
"profile_regime_early",
[2020, 2021]
);
renderRegimeGroup(
document.getElementById("profile-late-body"),
"profile_regime_late",
[2022, 2023, 2024]
);
var caption = document.getElementById("profile-caption");
caption.removeAttribute("data-i18n");
caption.textContent = tpl(t("profile_caption"), { state: definition.name });
document.getElementById("state-profile-wrap").hidden = false;
var status = document.getElementById("state-profile-status");
status.removeAttribute("data-i18n");
status.className = "state-profile-status is-ready";
status.textContent = tpl(t("profile_ready"), { state: definition.name });
document.getElementById("state-profile").setAttribute("aria-busy", "false");
if (viewState.mapLevel === "state" && viewState.selectedState === profileState) {
renderStateLens();
}
}
function loadStateProfile(abbreviation) {
var serial = ++profileRequestSerial;
if (!abbreviation) {
showProfileEmpty();
return Promise.resolve();
}
if (!isValidState(abbreviation)) {
showProfileError();
return Promise.resolve();
}
showProfileLoading();
return Promise.all(
releaseIndex.releases.map(function (release) {
return loadArtifact(release);
})
)
.then(function (artifacts) {
if (
serial !== profileRequestSerial ||
document.getElementById("state-filter").value !== abbreviation
) {
return;
}
profileArtifacts = {};
artifacts.forEach(function (data) {
profileArtifacts[data.dataset_year] = data;
});
profileState = abbreviation;
renderStateProfile();
})
.catch(function () {
if (
serial === profileRequestSerial &&
document.getElementById("state-filter").value === abbreviation
) {
showProfileError();
}
});
}
function selectedRows() {
var state = document.getElementById("state-filter").value;
var mode = document.getElementById("ledger-mode-filter").value;
var status = document.getElementById("status-filter").value;
return rows.filter(function (row) {
return (
(!state || row.stateAbbreviation === state) &&
(!mode || row.mode === mode) &&
(!status || row.status === status)
);
});
}
function selectState(abbreviation, mode, openLens) {
if (!isValidState(abbreviation)) return;
var activeElement = document.activeElement;
var activeControl = activeElement && activeElement.closest && activeElement.closest("[data-focus-key]");
var focusKey = activeControl ? activeControl.getAttribute("data-focus-key") : null;
viewState.selectedState = abbreviation;
viewState.compareA = abbreviation;
if (openLens) viewState.mapLevel = "state";
if (mode) {
requestedModeFromUrl = null;
viewState.primaryMode = mode;
}
var stateSelect = document.getElementById("state-filter");
if (stateSelect) stateSelect.value = abbreviation;
var modeSelect = document.getElementById("mode-filter");
if (mode && modeSelect) modeSelect.value = mode;
renderAll();
loadStateProfile(abbreviation);
if (focusKey) {
var replacement = document.querySelector('[data-focus-key="' + focusKey + '"]');
if (replacement && replacement.focus) replacement.focus();
}
syncUrl(Boolean(openLens));
if (openLens) {
var lensHeading = document.getElementById("state-lens-heading");
if (lensHeading && lensHeading.focus) lensHeading.focus();
}
}
function leaveStateLens() {
var abbreviation = viewState.selectedState;
viewState.mapLevel = "national";
renderAll();
syncUrl(true);
var target = abbreviation && document.querySelector('[data-focus-key="map:' + abbreviation + '"]');
if (target && target.focus) target.focus();
}
function renderTable() {
if (!artifact) return;
var selectedState = document.getElementById("state-filter").value;
var selected = selectedRows();
var body = document.getElementById("coverage-body");
var caption = document.getElementById("coverage-caption");
var status = document.getElementById("coverage-status");
body.textContent = "";
if (!selected.length) {
var emptyRow = document.createElement("tr");
var emptyCell = cell("td", t("no_results"));
emptyCell.colSpan = 5;
emptyRow.appendChild(emptyCell);