atmosx-nwws-parser 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +17 -0
  2. package/README.md +6 -0
  3. package/dist/cjs/bootstrap.cjs +1009 -0
  4. package/dist/cjs/database.cjs +1114 -0
  5. package/dist/cjs/dictionaries/awips.cjs +379 -0
  6. package/dist/cjs/dictionaries/events.cjs +139 -0
  7. package/dist/cjs/dictionaries/icao.cjs +265 -0
  8. package/dist/cjs/dictionaries/offshore.cjs +40 -0
  9. package/dist/cjs/dictionaries/signatures.cjs +132 -0
  10. package/dist/cjs/eas.cjs +2857 -0
  11. package/dist/cjs/helper.cjs +3014 -0
  12. package/dist/cjs/parsers/events.cjs +2857 -0
  13. package/dist/cjs/parsers/stanza.cjs +1108 -0
  14. package/dist/cjs/parsers/text.cjs +1142 -0
  15. package/dist/cjs/parsers/types/api.cjs +2857 -0
  16. package/dist/cjs/parsers/types/cap.cjs +2857 -0
  17. package/dist/cjs/parsers/types/text.cjs +2857 -0
  18. package/dist/cjs/parsers/types/ugc.cjs +2857 -0
  19. package/dist/cjs/parsers/types/vtec.cjs +2857 -0
  20. package/dist/cjs/parsers/ugc.cjs +1139 -0
  21. package/dist/cjs/parsers/vtec.cjs +1060 -0
  22. package/dist/cjs/types.cjs +17 -0
  23. package/dist/cjs/utils.cjs +2857 -0
  24. package/dist/cjs/xmpp.cjs +2857 -0
  25. package/dist/esm/bootstrap.mjs +972 -0
  26. package/dist/esm/database.mjs +1079 -0
  27. package/dist/esm/dictionaries/awips.mjs +355 -0
  28. package/dist/esm/dictionaries/events.mjs +111 -0
  29. package/dist/esm/dictionaries/icao.mjs +241 -0
  30. package/dist/esm/dictionaries/offshore.mjs +16 -0
  31. package/dist/esm/dictionaries/signatures.mjs +106 -0
  32. package/dist/esm/eas.mjs +2824 -0
  33. package/dist/esm/helper.mjs +2974 -0
  34. package/dist/esm/parsers/events.mjs +2824 -0
  35. package/dist/esm/parsers/stanza.mjs +1072 -0
  36. package/dist/esm/parsers/text.mjs +1106 -0
  37. package/dist/esm/parsers/types/api.mjs +2824 -0
  38. package/dist/esm/parsers/types/cap.mjs +2824 -0
  39. package/dist/esm/parsers/types/text.mjs +2824 -0
  40. package/dist/esm/parsers/types/ugc.mjs +2824 -0
  41. package/dist/esm/parsers/types/vtec.mjs +2824 -0
  42. package/dist/esm/parsers/ugc.mjs +1104 -0
  43. package/dist/esm/parsers/vtec.mjs +1025 -0
  44. package/dist/esm/types.mjs +0 -0
  45. package/dist/esm/utils.mjs +2824 -0
  46. package/dist/esm/xmpp.mjs +2824 -0
  47. package/package.json +47 -0
  48. package/shapefiles/FireCounties.dbf +0 -0
  49. package/shapefiles/FireCounties.shp +0 -0
  50. package/shapefiles/FireZones.dbf +0 -0
  51. package/shapefiles/FireZones.shp +0 -0
  52. package/shapefiles/ForecastZones.dbf +0 -0
  53. package/shapefiles/ForecastZones.shp +0 -0
  54. package/shapefiles/Marine.dbf +0 -0
  55. package/shapefiles/Marine.shp +0 -0
  56. package/shapefiles/OffShoreZones.dbf +0 -0
  57. package/shapefiles/OffShoreZones.shp +0 -0
  58. package/shapefiles/USCounties.dbf +0 -0
  59. package/shapefiles/USCounties.shp +0 -0
  60. package/src/bootstrap.ts +171 -0
  61. package/src/database.ts +99 -0
  62. package/src/dictionaries/awips.ts +351 -0
  63. package/src/dictionaries/events.ts +109 -0
  64. package/src/dictionaries/icao.ts +237 -0
  65. package/src/dictionaries/offshore.ts +12 -0
  66. package/src/dictionaries/signatures.ts +103 -0
  67. package/src/eas.ts +428 -0
  68. package/src/helper.ts +167 -0
  69. package/src/parsers/events.ts +289 -0
  70. package/src/parsers/stanza.ts +103 -0
  71. package/src/parsers/text.ts +167 -0
  72. package/src/parsers/types/api.ts +94 -0
  73. package/src/parsers/types/cap.ts +89 -0
  74. package/src/parsers/types/text.ts +54 -0
  75. package/src/parsers/types/ugc.ts +85 -0
  76. package/src/parsers/types/vtec.ts +60 -0
  77. package/src/parsers/ugc.ts +148 -0
  78. package/src/parsers/vtec.ts +66 -0
  79. package/src/types.ts +187 -0
  80. package/src/utils.ts +216 -0
  81. package/src/xmpp.ts +123 -0
  82. package/test.js +1 -0
  83. package/tsconfig.json +14 -0
  84. package/tsup.config.ts +11 -0
@@ -0,0 +1,2857 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __export = (target, all) => {
25
+ for (var name in all)
26
+ __defProp(target, name, { get: all[name], enumerable: true });
27
+ };
28
+ var __copyProps = (to, from, except, desc) => {
29
+ if (from && typeof from === "object" || typeof from === "function") {
30
+ for (let key of __getOwnPropNames(from))
31
+ if (!__hasOwnProp.call(to, key) && key !== except)
32
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
33
+ }
34
+ return to;
35
+ };
36
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
37
+ // If the importer is in node compatibility mode or this is not an ESM
38
+ // file that has been converted to a CommonJS file using a Babel-
39
+ // compatible transform (i.e. "__esModule" has not been set), then set
40
+ // "default" to the CommonJS "module.exports" for node compatibility.
41
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
42
+ mod
43
+ ));
44
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
45
+ var __async = (__this, __arguments, generator) => {
46
+ return new Promise((resolve, reject) => {
47
+ var fulfilled = (value) => {
48
+ try {
49
+ step(generator.next(value));
50
+ } catch (e) {
51
+ reject(e);
52
+ }
53
+ };
54
+ var rejected = (value) => {
55
+ try {
56
+ step(generator.throw(value));
57
+ } catch (e) {
58
+ reject(e);
59
+ }
60
+ };
61
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
62
+ step((generator = generator.apply(__this, __arguments)).next());
63
+ });
64
+ };
65
+
66
+ // src/parsers/types/vtec.ts
67
+ var vtec_exports = {};
68
+ __export(vtec_exports, {
69
+ VTECAlerts: () => VTECAlerts,
70
+ default: () => vtec_default2
71
+ });
72
+ module.exports = __toCommonJS(vtec_exports);
73
+
74
+ // src/bootstrap.ts
75
+ var fs = __toESM(require("fs"));
76
+ var path = __toESM(require("path"));
77
+ var events = __toESM(require("events"));
78
+ var xmpp = __toESM(require("@xmpp/client"));
79
+ var shapefile = __toESM(require("shapefile"));
80
+ var xml2js = __toESM(require("xml2js"));
81
+ var cron = __toESM(require("node-cron"));
82
+ var import_better_sqlite3 = __toESM(require("better-sqlite3"));
83
+ var import_axios = __toESM(require("axios"));
84
+ var import_crypto = __toESM(require("crypto"));
85
+ var import_os = __toESM(require("os"));
86
+ var import_say = __toESM(require("say"));
87
+
88
+ // src/dictionaries/events.ts
89
+ var EVENTS = {
90
+ "AF": "Ashfall",
91
+ "AS": "Air Stagnation",
92
+ "BH": "Beach Hazard",
93
+ "BW": "Brisk Wind",
94
+ "BZ": "Blizzard",
95
+ "CF": "Coastal Flood",
96
+ "DF": "Debris Flow",
97
+ "DS": "Dust Storm",
98
+ "EC": "Extreme Cold",
99
+ "EH": "Excessive Heat",
100
+ "XH": "Extreme Heat",
101
+ "EW": "Extreme Wind",
102
+ "FA": "Areal Flood",
103
+ "FF": "Flash Flood",
104
+ "FG": "Dense Fog",
105
+ "FL": "Flood",
106
+ "FR": "Frost",
107
+ "FW": "Fire Weather",
108
+ "FZ": "Freeze",
109
+ "GL": "Gale",
110
+ "HF": "Hurricane Force Wind",
111
+ "HT": "Heat",
112
+ "HU": "Hurricane",
113
+ "HW": "High Wind",
114
+ "HY": "Hydrologic",
115
+ "HZ": "Hard Freeze",
116
+ "IS": "Ice Storm",
117
+ "LE": "Lake Effect Snow",
118
+ "LO": "Low Water",
119
+ "LS": "Lakeshore Flood",
120
+ "LW": "Lake Wind",
121
+ "MA": "Special Marine",
122
+ "EQ": "Earthquake",
123
+ "MF": "Dense Fog",
124
+ "MH": "Ashfall",
125
+ "MS": "Dense Smoke",
126
+ "RB": "Small Craft for Rough Bar",
127
+ "RP": "Rip Current Risk",
128
+ "SC": "Small Craft",
129
+ "SE": "Hazardous Seas",
130
+ "SI": "Small Craft for Winds",
131
+ "SM": "Dense Smoke",
132
+ "SQ": "Snow Squall",
133
+ "SR": "Storm",
134
+ "SS": "Storm Surge",
135
+ "SU": "High Surf",
136
+ "SV": "Severe Thunderstorm",
137
+ "SW": "Small Craft for Hazardous Seas",
138
+ "TO": "Tornado",
139
+ "TR": "Tropical Storm",
140
+ "TS": "Tsunami",
141
+ "TY": "Typhoon",
142
+ "SP": "Special Weather",
143
+ "UP": "Heavy Freezing Spray",
144
+ "WC": "Wind Chill",
145
+ "WI": "Wind",
146
+ "WS": "Winter Storm",
147
+ "WW": "Winter Weather",
148
+ "ZF": "Freezing Fog",
149
+ "ZR": "Freezing Rain",
150
+ "ZY": "Freezing Spray"
151
+ };
152
+ var ACTIONS = {
153
+ "W": "Warning",
154
+ "F": "Forecast",
155
+ "A": "Watch",
156
+ "O": "Outlook",
157
+ "Y": "Advisory",
158
+ "N": "Synopsis",
159
+ "S": "Statement"
160
+ };
161
+ var STATUS = {
162
+ "NEW": "Issued",
163
+ "CON": "Updated",
164
+ "EXT": "Extended",
165
+ "EXA": "Extended",
166
+ "EXB": "Extended",
167
+ "UPG": "Upgraded",
168
+ "COR": "Correction",
169
+ "ROU": "Routine",
170
+ "CAN": "Cancelled",
171
+ "EXP": "Expired"
172
+ };
173
+ var TYPES = {
174
+ "O": "Operational Product",
175
+ "T": "Test Product",
176
+ "E": "Experimental Product",
177
+ "X": "Experimental Product (Non-Operational)"
178
+ };
179
+ var STATUS_CORRELATIONS = [
180
+ { type: "Update", forward: "Updated", cancel: false },
181
+ { type: "Cancel", forward: "Cancelled", cancel: true },
182
+ { type: "Alert", forward: "Issued", cancel: false },
183
+ { type: "Updated", forward: "Updated", cancel: false },
184
+ { type: "Expired", forward: "Expired", cancel: true },
185
+ { type: "Issued", forward: "Issued", cancel: false },
186
+ { type: "Extended", forward: "Updated", cancel: false },
187
+ { type: "Correction", forward: "Updated", cancel: false },
188
+ { type: "Upgraded", forward: "Upgraded", cancel: false },
189
+ { type: "Cancelled", forward: "Cancelled", cancel: true },
190
+ { type: "Routine", forward: "Routine", cancel: false }
191
+ ];
192
+
193
+ // src/dictionaries/offshore.ts
194
+ var OFFSHORE = {
195
+ "Special Weather Statement": "Special Weather Statement",
196
+ "Hurricane Warning": "Hurricane Warning",
197
+ "Hurricane Force Wind Warning": "Hurricane Force Wind Warning",
198
+ "Hurricane Watch": "Hurricane Watch",
199
+ "Tropical Storm Warning": "Tropical Storm Warning",
200
+ "Tropical Storm Watch": "Tropical Storm Watch",
201
+ "High Wind Warning": "High Wind Warning",
202
+ "Gale Warning": "Gale Warning",
203
+ "Small Craft Advisory": "Small Craft Advisory",
204
+ "Small Craft Warning": "Small Craft Warning"
205
+ };
206
+
207
+ // src/dictionaries/awips.ts
208
+ var AWIPS = {
209
+ ABV: `abv`,
210
+ ADA: `administrative-message`,
211
+ ADM: `administrative-message`,
212
+ ADR: `administrative-message`,
213
+ AHD: `area-hydrological-discussion`,
214
+ AHONT1: `high-density-observations-usaf-noaa`,
215
+ AHOPA1: `high-density-observations-usaf-noaa-west-pac`,
216
+ AHOPN1: `high-density-observations-usaf-noaa`,
217
+ AFD: `area-forecast-discussion`,
218
+ AQA: `air-quality-alert`,
219
+ AQI: `ground-level-ozone-forecast`,
220
+ AVA: `avalanche-watch`,
221
+ AVW: `avalanche-warning`,
222
+ AWU: `area-weather-update`,
223
+ AVG: `avalanche-weather-guidance`,
224
+ AWW: `airport-weather-warning`,
225
+ BLU: `blue-alert`,
226
+ CAE: `child-abduction-emergency`,
227
+ CDW: `civil-danger-warning`,
228
+ CEM: `civil-emergency-message`,
229
+ CFW: `coastal-hazard-message`,
230
+ CGR: `coastal-weather-observations`,
231
+ CLI: `daily-climate-report`,
232
+ CLM: `monthly-climate-report`,
233
+ CRF: `contingency-river-forecast`,
234
+ CWA: `center-weather-advisory`,
235
+ CWF: `coastal-waters-forecast`,
236
+ DGT: `drought-information`,
237
+ DSA: `tropical-disturbance-statement`,
238
+ DSW: `dust-storm-warning`,
239
+ EQI: `earthquake-information`,
240
+ EQR: `earthquake-report`,
241
+ EQW: `earthquake-warning`,
242
+ ESF: `hydrologic-outlook`,
243
+ EVI: `evacuation-immediate`,
244
+ EWW: `extreme-wind-warning`,
245
+ FFA: `flood-watch`,
246
+ FFG: `flash-flood-guidance`,
247
+ FFGMPD: `mesoscale-precipitation-discussion`,
248
+ FLS: `flood-advisory`,
249
+ FLW: `flood-warning`,
250
+ FFS: `flash-flood-statement`,
251
+ FFW: `flash-flood-warning`,
252
+ MWS: `marine-weather-statement`,
253
+ MWW: `marine-weather-warning`,
254
+ NMN: `network-message-notification`,
255
+ NOW: `short-term-forecast`,
256
+ NPW: `non-convective-advisory`,
257
+ NSH: `nearshore-marine-forecast`,
258
+ NUW: `nuclear-power-plant-warning`,
259
+ PMDAK: `alaska-discussion`,
260
+ PMDCA: `tropical-discussion`,
261
+ PMDEPD: `extended-forecast-discussion`,
262
+ PMDHI: `hawaii-discussion`,
263
+ PMDHMD: `model-diagnostic-discussion`,
264
+ PMDSA: `south-america-forecast-discussion`,
265
+ PMDSPD: `short-range-forecast-discussion`,
266
+ PNS: `public-information-statement`,
267
+ FRW: `fire-warning`,
268
+ FTM: `free-text-message`,
269
+ FWF: `fire-weather-planning-forecast`,
270
+ FWA: `fire-weather-administrative-message`,
271
+ FWS: `fire-weather-spot-forecast`,
272
+ GLF: `open-lake-forecast`,
273
+ HCM: `hydromet-coordination-message`,
274
+ HMT: `hmt`,
275
+ HMW: `hazardous-materials-warning`,
276
+ HPA: `high-pollution-advisory`,
277
+ HLS: `hurricane-local-statement`,
278
+ HMD: `rainfall-and-flood-outlook-product`,
279
+ HSF: `high-seas-forecast`,
280
+ HWO: `hazardous-weather-outlook`,
281
+ HYD: `supplementary-temp-and-precip`,
282
+ LAE: `local-area-emergency`,
283
+ LCO: `local-cooperative-observation`,
284
+ LEW: `law-enforcement-warning`,
285
+ LSR: `local-storm-report`,
286
+ ICE: `ice-outlook`,
287
+ MIS: `meteorological-impact-statement`,
288
+ OAV: `other-aviation-report`,
289
+ OEP: `taf-collaboration-product`,
290
+ OFF: `offshore-waters-forecast`,
291
+ OMR: `other-marine-reports`,
292
+ OSO: `weather-roundup`,
293
+ PFM: `point-forecast-matrices`,
294
+ PSH: `post-tropical-event-report`,
295
+ PWO: `public-severe-weather-outlook`,
296
+ QPFERD: `excessive-rainfall-discussion`,
297
+ QPFHSD: `heavy-snow-discussion`,
298
+ QPS: `quantitative-precipitation-forecast`,
299
+ REC: `recreational-forecast`,
300
+ REPNT0: `recco-observations-non-tropical-cyclone`,
301
+ REPNT1: `recco-observations-tropical-cyclone`,
302
+ REPNT2: `vortex-data-message`,
303
+ REPNTS: `supplementary-vortex-data-message`,
304
+ REPNT3: `dropsonde-observations`,
305
+ REPPN0: `recco-observations-non-tropical-cyclone`,
306
+ REPPN1: `recco-observations-tropical-cyclone`,
307
+ REPPN2: `vortex-data-message`,
308
+ REPPNS: `supplementary-vortex-data-message`,
309
+ REPPN3: `dropsonde-observations`,
310
+ REPPA0: `recco-observations-west-pac-non-tropical-cyclone`,
311
+ REPPA1: `recco-observations-west-pac-tropical-cyclone`,
312
+ REPPA2: `vortex-data-message-west-pac`,
313
+ REPPAS: `supplementary-vortex-data-message-west-pac`,
314
+ REPPA3: `dropsonde-observations-west-pac`,
315
+ REPRPD: `weather-reconnaissance-flights`,
316
+ RER: `record-event-report`,
317
+ RFD: `grassland-fire-danger`,
318
+ RFW: `red-flag-warning`,
319
+ RHW: `radiological-hazard-warning`,
320
+ RRM: `rainfall-storm-total`,
321
+ RTP: `regional-temperature-and-precipitation`,
322
+ RVA: `hydrologic-summary`,
323
+ RVD: `river-and-lake-summary`,
324
+ RVF: `river-forecast`,
325
+ RVS: `hydrologic-statement`,
326
+ RWR: `weather-roundup`,
327
+ RWS: `regional-weather-summary`,
328
+ SAB: `special-avalanche-bulletin`,
329
+ SCC: `storm-summary`,
330
+ SFT: `state-forecast-tabular-product`,
331
+ SIG: `convective-sigment`,
332
+ SMF: `smoke-management-weather-forecast`,
333
+ SMW: `special-marine-warning`,
334
+ SPS: `special-weather-statement`,
335
+ SPW: `shelter-in-place-warning`,
336
+ SQW: `snow-squall-warning`,
337
+ SRF: `surf-zone-forecast`,
338
+ STF: `tabular-state-forecast`,
339
+ STQ: `spot-forecast-request`,
340
+ SVR: `severe-thunderstorm-warning`,
341
+ SVS: `severe-weather-statement`,
342
+ SWOMCD: `mesoscale-convective-discussion`,
343
+ TAF: `terminal-aerodrome-forecast`,
344
+ TCD: `tropical-cyclone-discussion`,
345
+ TCE: `tropical-cyclone-position-estimate`,
346
+ TCM: `tropical-storm-forecast`,
347
+ TCU: `tropical-cyclone-update`,
348
+ TCV: `tropical-watch-warning-local-statement`,
349
+ TIB: `tsunami-information-statement`,
350
+ TID: `tide-data`,
351
+ TMA: `tsunami-message-acknowledgement`,
352
+ TOE: `telephone-outage-emergency`,
353
+ TOR: `tornado-warning`,
354
+ TWD: `tropical-weather-discussion`,
355
+ TWO: `tropical-weather-outlook`,
356
+ VAA: `volcanic-ash-advisory`,
357
+ VOW: `volcano-warning`,
358
+ WCN: `watch-county-notification`,
359
+ WRK: `work-product`,
360
+ WSV: `volcanic-ash-sigmet`,
361
+ WSW: `winter-weather-message`,
362
+ XTEUS: `wpc-contiguous-us-daily-max-min-temps`,
363
+ ZFP: `zone-forecast-package`,
364
+ RR1: `hydro-meteorological-data-report-pt1`,
365
+ RR2: `hydro-meteorological-data-report-pt2`,
366
+ RR3: `hydro-meteorological-data-report-pt3`,
367
+ RR4: `hydro-meteorological-data-report-pt4`,
368
+ RR5: `hydro-meteorological-data-report-pt5`,
369
+ RR6: `hydro-meteorological-data-report-pt6`,
370
+ RR7: `hydro-meteorological-data-report-pt7`,
371
+ RR8: `hydro-meteorological-data-report-pt8`,
372
+ RR9: `hydro-meteorological-data-report-pt9`,
373
+ SFP: `state-forecast-product`,
374
+ AFM: `area-forecast-matrices`,
375
+ AAG: `aag`,
376
+ ADV: `adv`,
377
+ AFP: `afp`,
378
+ AFW: `afw`,
379
+ AGO: `ago`,
380
+ AIR: `air`,
381
+ ALG: `alg`,
382
+ ALT: `alt`,
383
+ AVD: `avd`,
384
+ AWO: `awo`,
385
+ BOY: `boy`,
386
+ BRT: `brt`,
387
+ CF6: `cf6`,
388
+ CFP: `cfp`,
389
+ CLS: `cls`,
390
+ CMM: `cmm`,
391
+ COD: `cod`,
392
+ CRN: `crn`,
393
+ CUR: `cur`,
394
+ CWD: `cwd`,
395
+ CWS: `cws`,
396
+ DAY: `day`,
397
+ DDO: `ddo`,
398
+ DMO: `dmo`,
399
+ DSM: `dsm`,
400
+ ECD: `ecd`,
401
+ EFP: `efp`,
402
+ EOL: `eol`,
403
+ EOM: `eom`,
404
+ ESG: `esg`,
405
+ ESP: `esp`,
406
+ ESS: `ess`,
407
+ ETT: `ett`,
408
+ FA0: `fa0`,
409
+ FA7: `fa7`,
410
+ FA8: `fa8`,
411
+ FA9: `fa9`,
412
+ FD0: `fd0`,
413
+ FD1: `fd1`,
414
+ FD3: `fd3`,
415
+ FD5: `fd5`,
416
+ FD8: `fd8`,
417
+ FD9: `fd9`,
418
+ FDI: `fdi`,
419
+ FFH: `ffh`,
420
+ FFP: `ffp`,
421
+ FLR: `flr`,
422
+ FOP: `fop`,
423
+ FRH: `frh`,
424
+ FSH: `fsh`,
425
+ FTP: `ftp`,
426
+ FWD: `fwd`,
427
+ FWL: `fwl`,
428
+ FWM: `fwm`,
429
+ FWN: `fwn`,
430
+ FWO: `fwo`,
431
+ FZL: `fzl`,
432
+ GEN: `gen`,
433
+ GMT: `gmt`,
434
+ HD0: `hd0`,
435
+ HD2: `hd2`,
436
+ HD3: `hd3`,
437
+ HD4: `hd4`,
438
+ HD6: `hd6`,
439
+ HD8: `hd8`,
440
+ HML: `hml`,
441
+ HWR: `hwr`,
442
+ LAK: `lak`,
443
+ LEV: `lev`,
444
+ LLL: `lll`,
445
+ HP2: `hp2`,
446
+ HRR: `hrr`,
447
+ HYM: `hym`,
448
+ ICO: `ico`,
449
+ IDM: `idm`,
450
+ MAN: `man`,
451
+ MAP: `map`,
452
+ MAR: `mar`,
453
+ MAV: `mav`,
454
+ MCG: `mcg`,
455
+ MCX: `mcx`,
456
+ MET: `met`,
457
+ MEX: `mex`,
458
+ MFM: `mfm`,
459
+ MFP: `mfp`,
460
+ MHF: `mhf`,
461
+ MME: `mme`,
462
+ MMG: `mmg`,
463
+ MRP: `mrp`,
464
+ MSM: `msm`,
465
+ MTR: `mtr`,
466
+ MTT: `mtt`,
467
+ MVF: `mvf`,
468
+ NWR: `nwr`,
469
+ OFA: `ofa`,
470
+ OPU: `opu`,
471
+ OPW: `opw`,
472
+ OSB: `osb`,
473
+ PFW: `pfw`,
474
+ PLS: `pls`,
475
+ PMD: `pmd`,
476
+ POE: `poe`,
477
+ PRB: `prb`,
478
+ PTS: `pts`,
479
+ PWS: `pws`,
480
+ QPF: `qpf`,
481
+ QPG: `qpg`,
482
+ RBG: `rbg`,
483
+ REP: `rep`,
484
+ RFM: `rfm`,
485
+ RFR: `rfr`,
486
+ RRA: `rra`,
487
+ RRS: `rrs`,
488
+ RRY: `rry`,
489
+ RRZ: `rrz`,
490
+ RVC: `rvc`,
491
+ RVG: `rvg`,
492
+ RVK: `rvk`,
493
+ RVM: `rvm`,
494
+ RVO: `rvo`,
495
+ RVR: `rvr`,
496
+ RVU: `rvu`,
497
+ SAF: `saf`,
498
+ SAG: `sag`,
499
+ SAT: `sat`,
500
+ SAW: `saw`,
501
+ SCN: `scn`,
502
+ SCP: `scp`,
503
+ SCS: `scs`,
504
+ SCV: `scv`,
505
+ SEL: `sel`,
506
+ SGL: `sgl`,
507
+ SPE: `spe`,
508
+ SPN: `spn`,
509
+ SRG: `srg`,
510
+ SSM: `ssm`,
511
+ STA: `sta`,
512
+ SUM: `sum`,
513
+ SWE: `swe`,
514
+ SYN: `syn`,
515
+ TAP: `tap`,
516
+ TCA: `tca`,
517
+ TCP: `tcp`,
518
+ TCS: `tcs`,
519
+ TPT: `tpt`,
520
+ TST: `tst`,
521
+ TSU: `tsu`,
522
+ TUV: `tuv`,
523
+ TVL: `tvl`,
524
+ TWS: `tws`,
525
+ TXT: `txt`,
526
+ UVI: `uvi`,
527
+ VFT: `vft`,
528
+ WA0: `wa0`,
529
+ WA1: `wa1`,
530
+ WA2: `wa2`,
531
+ WA3: `wa3`,
532
+ WA4: `wa4`,
533
+ WA5: `wa5`,
534
+ WA6: `wa6`,
535
+ WA7: `wa7`,
536
+ WA8: `wa8`,
537
+ WA9: `wa9`,
538
+ WAR: `war`,
539
+ WAT: `wat`,
540
+ WCL: `wcl`,
541
+ WEE: `wee`,
542
+ WEK: `wek`,
543
+ WOU: `wou`,
544
+ WRM: `wrm`,
545
+ WS1: `ws1`,
546
+ WS2: `ws2`,
547
+ WS3: `ws3`,
548
+ WS4: `ws4`,
549
+ WS5: `ws5`,
550
+ WS6: `ws6`,
551
+ WSC: `wsc`,
552
+ WST: `wst`,
553
+ WTA: `wta`,
554
+ WWA: `wwa`,
555
+ WWP: `wwp`,
556
+ XF0: `xf0`,
557
+ XOB: `xob`
558
+ };
559
+
560
+ // src/dictionaries/signatures.ts
561
+ var TAGS = {
562
+ "A LARGE AND EXTREMELY DANGEROUS TORNADO": "Large and Dangerous Tornado",
563
+ "THIS IS A PARTICULARLY DANGEROUS SITUATION": "Particularly Dangerous Situation",
564
+ "RADAR INDICATED ROTATION": "Radar Indicated Tornado",
565
+ "WEATHER SPOTTERS CONFIRMED TORNADO": "Confirmed by Storm Spotters",
566
+ "A SEVERE THUNDERSTORM CAPABLE OF PRODUCING A TORNADO": "Developing Tornado",
567
+ "LAW ENFORCEMENT CONFIRMED TORNADO": "Reported by Law Enforcement",
568
+ "A TORNADO IS ON THE GROUND": "Confirmed Tornado",
569
+ "WEATHER SPOTTERS REPORTED FUNNEL CLOUD": "Confirmed Funnel Cloud by Storm Spotters",
570
+ "PUBLIC CONFIRMED TORNADO": "Public reports of Tornado",
571
+ "RADAR CONFIRMED": "Radar Confirmed",
572
+ "TORNADO WAS REPORTED BRIEFLY ON THE GROUND": "Tornado no longer on ground",
573
+ "SPOTTERS INDICATE THAT A FUNNEL CLOUD CONTINUES WITH THIS STORM": "Funnel Cloud Continues",
574
+ "A TORNADO MAY DEVELOP AT ANY TIME": "Potentional still exists for Tornado to form",
575
+ "LIFE-THREATENING SITUATION": "Life Threating Situation",
576
+ "COMPLETE DESTRUCTION IS POSSIBLE": "Extremly Damaging Tornado",
577
+ "POTENTIALLY DEADLY TORNADO": "Deadly Tornado",
578
+ "RADAR INDICATED": "Radar Indicated",
579
+ "HAIL DAMAGE TO VEHICLES IS EXPECTED": "Damaging to Vehicles",
580
+ "EXPECT WIND DAMAGE": "Wind Damage",
581
+ "FREQUENT LIGHTNING": "Frequent Lightning",
582
+ "PEOPLE AND ANIMALS OUTDOORS WILL BE INJURED": "Capable of Injuring People and Animals",
583
+ "TRAINED WEATHER SPOTTERS": "Confirmed by Storm Spotters",
584
+ "SOURCE...PUBLIC": "Confirmed by Public",
585
+ "SMALL CRAFT COULD BE DAMAGED": "Potential Damage to Small Craft",
586
+ "A TORNADO WATCH REMAINS IN EFFECT": "Active Tornado Watch",
587
+ "TENNIS BALL SIZE HAIL": "Tennis Ball Size Hail",
588
+ "BASEBALL SIZE HAIL": "Baseball Size Hail",
589
+ "GOLF BALL SIZE HAIL": "Golf Ball Size Hail",
590
+ "QUARTER SIZE HAIL": "Quarter Size Hail",
591
+ "PING PONG BALL SIZE HAIL": "Ping Pong Ball Size Hail",
592
+ "NICKEL SIZE HAIL": "Nickel Size Hail",
593
+ "DOPPLER RADAR.": "Confirmed by Radar",
594
+ "DOPPLER RADAR AND AUTOMATED GAUGES.": "Confirmed by Radar and Gauges",
595
+ "FLASH FLOODING CAUSED BY THUNDERSTORMS.": "Caused by Thunderstorm",
596
+ "SOURCE...EMERGENCY MANAGEMENT.": "Confirmed by Emergency Management",
597
+ "FLASH FLOODING CAUSED BY HEAVY RAIN.": "Caused by heavy rain",
598
+ "SOURCE...LAW ENFORCEMENT REPORTED.": "Confirmed by Law Enforcement"
599
+ };
600
+ var CANCEL_SIGNATURES = [
601
+ "THIS_MESSAGE_IS_FOR_TEST_PURPOSES_ONLY",
602
+ "this is a test",
603
+ "subsided sufficiently for the advisory to be cancelled",
604
+ "has been cancelled",
605
+ "will be allowed to expire",
606
+ "has diminished",
607
+ "and no longer",
608
+ "has been replaced",
609
+ "The threat has ended",
610
+ "has weakened below severe"
611
+ ];
612
+ var MESSAGE_SIGNATURES = [
613
+ { regex: /\r?\n/g, replacement: " " },
614
+ { regex: /\s+/g, replacement: " " },
615
+ { regex: /\*/g, replacement: "." },
616
+ { regex: /\bUTC\b/g, replacement: "Coordinated Universal Time" },
617
+ { regex: /\bGMT\b/g, replacement: "Greenwich Mean Time" },
618
+ { regex: /\bEST\b/g, replacement: "Eastern Standard Time" },
619
+ { regex: /\bEDT\b/g, replacement: "Eastern Daylight Time" },
620
+ { regex: /\bCST\b/g, replacement: "Central Standard Time" },
621
+ { regex: /\bCDT\b/g, replacement: "Central Daylight Time" },
622
+ { regex: /\bMST\b/g, replacement: "Mountain Standard Time" },
623
+ { regex: /\bMDT\b/g, replacement: "Mountain Daylight Time" },
624
+ { regex: /\bPST\b/g, replacement: "Pacific Standard Time" },
625
+ { regex: /\bPDT\b/g, replacement: "Pacific Daylight Time" },
626
+ { regex: /\bAKST\b/g, replacement: "Alaska Standard Time" },
627
+ { regex: /\bAKDT\b/g, replacement: "Alaska Daylight Time" },
628
+ { regex: /\bHST\b/g, replacement: "Hawaii Standard Time" },
629
+ { regex: /\bHDT\b/g, replacement: "Hawaii Daylight Time" },
630
+ { regex: /\bmph\b/g, replacement: "miles per hour" },
631
+ { regex: /\bkm\/h\b/g, replacement: "kilometers per hour" },
632
+ { regex: /\bkmh\b/g, replacement: "kilometers per hour" },
633
+ { regex: /\bkt\b/g, replacement: "knots" },
634
+ { regex: /\bNE\b/g, replacement: "northeast" },
635
+ { regex: /\bNW\b/g, replacement: "northwest" },
636
+ { regex: /\bSE\b/g, replacement: "southeast" },
637
+ { regex: /\bSW\b/g, replacement: "southwest" },
638
+ { regex: /\bNM\b/g, replacement: "nautical miles" },
639
+ { regex: /\bdeg\b/g, replacement: "degrees" },
640
+ { regex: /\btstm\b/g, replacement: "thunderstorm" },
641
+ { regex: /\bmm\b/g, replacement: "millimeters" },
642
+ { regex: /\bcm\b/g, replacement: "centimeters" },
643
+ { regex: /\bin\b/g, replacement: "inches" },
644
+ { regex: /\bft\b/g, replacement: "feet" },
645
+ { regex: /\bmi\b/g, replacement: "miles" },
646
+ { regex: /\bhr\b/g, replacement: "hour" },
647
+ { regex: /\bhourly\b/g, replacement: "per hour" },
648
+ { regex: /\bkg\b/g, replacement: "kilograms" },
649
+ { regex: /\bg\/kg\b/g, replacement: "grams per kilogram" },
650
+ { regex: /\bmb\b/g, replacement: "millibars" },
651
+ { regex: /\bhPa\b/g, replacement: "hectopascals" },
652
+ { regex: /\bPa\b/g, replacement: "pascals" },
653
+ { regex: /\bKPa\b/g, replacement: "kilopascals" },
654
+ { regex: /\bC\/hr\b/g, replacement: "degrees Celsius per hour" },
655
+ { regex: /\bF\/hr\b/g, replacement: "degrees Fahrenheit per hour" },
656
+ { regex: /\bC\/min\b/g, replacement: "degrees Celsius per minute" },
657
+ { regex: /\bF\/min\b/g, replacement: "degrees Fahrenheit per minute" },
658
+ { regex: /\bC\b/g, replacement: "degrees Celsius" },
659
+ { regex: /\bF\b/g, replacement: "degrees Fahrenheit" }
660
+ ];
661
+
662
+ // src/dictionaries/icao.ts
663
+ var ICAOs = {
664
+ "KLCH": "Lake Charles, LA",
665
+ "TSTL": "St. Louis, MO",
666
+ "PABC": "Bethel, AK",
667
+ "TCMH": "Columbus, OH",
668
+ "KEPZ": "El Paso, TX",
669
+ "KCYS": "Cheyenne, WY",
670
+ "KJKL": "Jackson, KY",
671
+ "KPAH": "Paducah, KY",
672
+ "KEMX": "Tucson, AZ",
673
+ "KMHX": "Morehead City, NC",
674
+ "PAPD": "Fairbanks, AK",
675
+ "KDLH": "Duluth, MN",
676
+ "TADW": "Andrews Air Force Base, MD",
677
+ "KOKX": "Brookhaven, NY",
678
+ "KLZK": "Little Rock, AR",
679
+ "KHGX": "Houston, TX",
680
+ "TMSY": "New Orleans, LA",
681
+ "KDGX": "Jackson/Brandon, MS",
682
+ "KCTP": "Caribou, ME",
683
+ "KAMA": "Amarillo, TX",
684
+ "PGUA": "Andersen AFB, GU",
685
+ "KAPX": "Gaylord, MI",
686
+ "PAHG": "Kenai, AK",
687
+ "KLWX": "Sterling, VA",
688
+ "HWPA2": "Homer, AK",
689
+ "KGRK": "Fort Hood, TX",
690
+ "KAKQ": "Wakefield, VA",
691
+ "ROCO2": "Norman, OK",
692
+ "KCLX": "Charleston, SC",
693
+ "TPHX": "Phoenix, AZ",
694
+ "KNKX": "San Diego, CA",
695
+ "TDEN": "Denver, CO",
696
+ "TLAS": "Las Vegas, NV",
697
+ "KBUF": "Buffalo, NY",
698
+ "KTLX": "Norman, OK",
699
+ "KILX": "Lincoln, IL",
700
+ "KHDC": "Hammond, LA",
701
+ "KVWX": "Evansville, IN",
702
+ "TCLT": "Charlotte, NC",
703
+ "TEWR": "Newark, NJ",
704
+ "KFSD": "Sioux Falls, SD",
705
+ "KEAX": "Pleasant Hill, MO",
706
+ "KICX": "Cedar City, UT",
707
+ "KHTX": "Huntsville, AL",
708
+ "PACG": "Sitka, AK",
709
+ "KSOX": "Santa Ana Mountains, CA",
710
+ "TPBI": "West Palm Beach, FL",
711
+ "TSLC": "Salt Lake City, UT",
712
+ "KGLD": "Goodland, KS",
713
+ "TRDU": "Raleigh-Durham, NC",
714
+ "KATX": "Seattle, WA",
715
+ "TICH": "Wichita, KS",
716
+ "TSDF": "Louisville, KY",
717
+ "TBOS": "Boston, MA",
718
+ "TDCA": "Washington, DC",
719
+ "KUEX": "Grand Island, NE",
720
+ "TLKA2": "Talkeetna, AK",
721
+ "KBGM": "Binghamton, NY",
722
+ "TLVE": "Cleveland, OH",
723
+ "KCAE": "Columbia, SC",
724
+ "KDVN": "Quad Cities, IA",
725
+ "KABR": "Aberdeen, SD",
726
+ "KBYX": "Key West, FL",
727
+ "KMPX": "Minneapolis, MN",
728
+ "KCRP": "Corpus Christi, TX",
729
+ "KCBW": "Caribou, ME",
730
+ "KMRX": "Knoxville, TN",
731
+ "KSHV": "Shreveport, LA",
732
+ "KIWA": "Phoenix, AZ",
733
+ "KRGX": "Reno, NV",
734
+ "PHKM": "Kamuela, HI",
735
+ "KABX": "Albuquerque, NM",
736
+ "KBMX": "Birmingham, AL",
737
+ "TMDW": "Chicago Midway, IL",
738
+ "KVAX": "Moody AFB, GA",
739
+ "KHDX": "Holloman AFB, NM",
740
+ "KBRO": "Brownsville, TX",
741
+ "KTWX": "Topeka, KS",
742
+ "KRTX": "Portland, OR",
743
+ "KCXX": "Burlington, VT",
744
+ "KFCX": "Roanoke, VA",
745
+ "KFFC": "Atlanta, GA",
746
+ "KBOX": "Boston, MA",
747
+ "KTLH": "Tallahassee, FL",
748
+ "KPUX": "Pueblo, CO",
749
+ "KFDR": "Altus AFB, OK",
750
+ "KGJX": "Grand Junction, CO",
751
+ "KDTX": "Detroit, MI",
752
+ "PHWA": "Waimea, HI",
753
+ "KMQT": "Marquette, MI",
754
+ "KSJT": "San Angelo, TX",
755
+ "KUDX": "Rapid City, SD",
756
+ "TIAH": "Houston, TX",
757
+ "KSRX": "Fort Smith, AR",
758
+ "TJFK": "New York City, NY",
759
+ "KDDC": "Dodge City, KS",
760
+ "PAKC": "King Salmon, AK",
761
+ "PAIH": "Middleton Island, AK",
762
+ "RODN": "Kadena AB, JA",
763
+ "TBWI": "Baltimore/Washington, MD",
764
+ "KIWX": "Northern Indiana, IN",
765
+ "KFDX": "Cannon AFB, NM",
766
+ "TMIA": "Miami, FL",
767
+ "KICT": "Wichita, KS",
768
+ "TMKE": "Milwaukee, WI",
769
+ "TFLL": "Fort Lauderdale, FL",
770
+ "KARX": "La Crosse, WI",
771
+ "KLRX": "Elko, NV",
772
+ "KDAX": "Sacramento, CA",
773
+ "KGRB": "Green Bay, WI",
774
+ "KLGX": "Langley Hill, WA",
775
+ "KFTG": "Denver, CO",
776
+ "KMKX": "Milwaukee, WI",
777
+ "TTUL": "Tulsa, OK",
778
+ "TDFW": "Dallas/Fort Worth, TX",
779
+ "TTPA": "Tampa Bay, FL",
780
+ "TDAL": "Dallas Love Field, TX",
781
+ "KDFX": "Laughlin AFB, TX",
782
+ "KSFX": "Pocatello, ID",
783
+ "KMTX": "Salt Lake City, UT",
784
+ "PAEC": "Nome, AK",
785
+ "RKSG": "Camp Humphreys, KR",
786
+ "KOAX": "Omaha, NE",
787
+ "PHMO": "Molokai, HI",
788
+ "TDTW": "Detroit, MI",
789
+ "THOU": "Houston, TX",
790
+ "AWPA2": "Anchorage, AK",
791
+ "KTYX": "Fort Drum, NY",
792
+ "KCCX": "State College, PA",
793
+ "TMSP": "Minneapolis, MN",
794
+ "KMVX": "Grand Forks, ND",
795
+ "KBIS": "Bismarck, ND",
796
+ "KBBX": "Beale AFB, CA",
797
+ "KVBX": "Vandenberg AFB, CA",
798
+ "KPOE": "Fort Polk, LA",
799
+ "KMOB": "Mobile, AL",
800
+ "KJGX": "Robins AFB, GA",
801
+ "KMUX": "San Francisco, CA",
802
+ "TMCI": "Kansas City, MO",
803
+ "KLSX": "St. Louis, MO",
804
+ "KMAX": "Medford, OR",
805
+ "KRAX": "Raleigh/Durham, NC",
806
+ "KINX": "Tulsa, OK",
807
+ "RKJK": "Kunsan AB, KR",
808
+ "KSGF": "Springfield, MO",
809
+ "TDAY": "Dayton, OH",
810
+ "KDOX": "Dover AFB, DE",
811
+ "KGGW": "Glasgow, MT",
812
+ "KAMX": "Miami, FL",
813
+ "KENX": "Albany, NY",
814
+ "KTFX": "Great Falls, MT",
815
+ "KPBZ": "Pittsburgh, PA",
816
+ "KMAF": "Midland/Odessa, TX",
817
+ "KPDT": "Pendleton, OR",
818
+ "KLNX": "North Platte, NE",
819
+ "KEOX": "Fort Rucker, AL",
820
+ "KGSP": "Greer, SC",
821
+ "KHPX": "Fort Campbell, KY",
822
+ "KGRR": "Grand Rapids, MI",
823
+ "KLOT": "Chicago, IL",
824
+ "TPIT": "Pittsburgh, PA",
825
+ "KEYX": "Edwards AFB, CA",
826
+ "TIAD": "Dulles, VA",
827
+ "KFWS": "Dallas/Fort Worth, TX",
828
+ "KMLB": "Melbourne, FL",
829
+ "KMBX": "Minot AFB, ND",
830
+ "KDMX": "Des Moines, IA",
831
+ "KEVX": "Eglin AFB, FL",
832
+ "TBNA": "Nashville, TN",
833
+ "KDYX": "Dyess AFB, TX",
834
+ "TOKC": "Oklahoma City, OK",
835
+ "PHKI": "South Kauai, HI",
836
+ "TMCO": "Orlando, FL",
837
+ "KDIX": "Philadelphia, PA",
838
+ "TORD": "Chicago, IL",
839
+ "KYUX": "Yuma, AZ",
840
+ "KVNX": "Vance AFB, OK",
841
+ "TJUA": "San Juan, PR",
842
+ "TATL": "Atlanta, GA",
843
+ "KVTX": "Los Angeles, CA",
844
+ "KIND": "Indianapolis, IN",
845
+ "KCBX": "Boise, ID",
846
+ "KGYX": "Portland, ME",
847
+ "KMXX": "Maxwell AFB, AL",
848
+ "TSJU": "San Juan, PR",
849
+ "KHNX": "San Joaquin Valley, CA",
850
+ "KLVX": "Louisville, KY",
851
+ "KMSX": "Missoula, MT",
852
+ "KJAX": "Jacksonville, FL",
853
+ "KNQA": "Memphis, TN",
854
+ "KRIW": "Riverton/Lander, WY",
855
+ "TCVG": "Covington, KY",
856
+ "KBLX": "Billings, MT",
857
+ "TPHL": "Philadelphia, PA",
858
+ "KRLX": "Charleston, WV",
859
+ "TMEM": "Memphis, TN",
860
+ "KCLE": "Cleveland, OH",
861
+ "KBHX": "Eureka, CA",
862
+ "KLBB": "Lubbock, TX",
863
+ "KOTX": "Spokane, WA",
864
+ "KEWX": "Austin/San Antonio, TX",
865
+ "KGWX": "Columbus AFB, MS",
866
+ "KESX": "Las Vegas, NV",
867
+ "KTBW": "Tampa, FL",
868
+ "KOHX": "Nashville, TN",
869
+ "KLTX": "Wilmington, NC",
870
+ "KFSX": "Flagstaff, AZ",
871
+ "TIDS": "Indianapolis, IN",
872
+ "KILN": "Cincinnati, OH",
873
+ "PAFG": "Fairbanks, AK",
874
+ "KPQR": "Portland, OR",
875
+ "KILM": "Wilmington, NC",
876
+ "KEKA": "Eureka, CA",
877
+ "KCHS": "Charleston, SC",
878
+ "KPHI": "Philadelphia/Mt. Holly, NJ",
879
+ "KUNR": "Rapid City, SD",
880
+ "KMFL": "Miami, FL",
881
+ "TJSJ": "San Juan, PR",
882
+ "KFGF": "Grand Forks, ND",
883
+ "KSEW": "Seattle, WA",
884
+ "PAFC": "Anchorage, AK",
885
+ "KLMK": "Louisville, KY",
886
+ "PHFO": "Honolulu, HI",
887
+ "KLIX": "New Orleans/Baton Rouge, LA",
888
+ "KBOI": "Boise, ID",
889
+ "KPIH": "Pocatello, ID",
890
+ "KMTR": "San Francisco/Monterey, CA",
891
+ "KGJT": "Grand Junction, CO",
892
+ "PAAQ": "Anchorage, AK",
893
+ "KABQ": "Albuquerque, NM",
894
+ "KTAE": "Tallahassee, FL",
895
+ "KCAR": "Caribou, ME",
896
+ "KMFR": "Medford, OR",
897
+ "PGUM": "Guam, GU",
898
+ "PAJK": "Juneau, AK"
899
+ };
900
+
901
+ // src/bootstrap.ts
902
+ var packages = {
903
+ fs,
904
+ path,
905
+ events,
906
+ xmpp,
907
+ shapefile,
908
+ xml2js,
909
+ sqlite3: import_better_sqlite3.default,
910
+ cron,
911
+ axios: import_axios.default,
912
+ crypto: import_crypto.default,
913
+ os: import_os.default,
914
+ say: import_say.default
915
+ };
916
+ var cache = {
917
+ isReady: true,
918
+ sigHalt: false,
919
+ isConnected: false,
920
+ attemptingReconnect: false,
921
+ totalReconnects: 0,
922
+ lastStanza: null,
923
+ session: null,
924
+ lastConnect: null,
925
+ db: null,
926
+ events: new events.EventEmitter(),
927
+ isProcessingAudioQueue: false,
928
+ audioQueue: []
929
+ };
930
+ var settings = {
931
+ database: path.join(process.cwd(), "shapefiles.db"),
932
+ isNWWS: true,
933
+ NoaaWeatherWireService: {
934
+ clientReconnections: {
935
+ canReconnect: true,
936
+ currentInterval: 60
937
+ },
938
+ clientCredentials: {
939
+ username: null,
940
+ password: null,
941
+ nickname: "AtmosphericX Standalone Parser"
942
+ },
943
+ cache: {
944
+ read: false,
945
+ maxSizeMB: 5,
946
+ maxHistory: 5e3,
947
+ directory: null
948
+ },
949
+ alertPreferences: {
950
+ isCapOnly: false,
951
+ isShapefileUGC: false
952
+ }
953
+ },
954
+ NationalWeatherService: {
955
+ checkInterval: 15,
956
+ endpoint: "https://api.weather.gov/alerts/active"
957
+ },
958
+ global: {
959
+ useParentEvents: true,
960
+ betterEventParsing: true,
961
+ alertFiltering: {
962
+ filteredEvents: [],
963
+ filteredICOAs: [],
964
+ ignoredICOAs: [`KWNS`],
965
+ ignoredEvents: [`Unknown`, `Test Message`],
966
+ ugcFilter: [],
967
+ stateFilter: [],
968
+ checkExpired: true
969
+ },
970
+ easSettings: {
971
+ easAlerts: [],
972
+ easDirectory: null,
973
+ easIntroWav: null
974
+ }
975
+ }
976
+ };
977
+ var definitions = {
978
+ events: EVENTS,
979
+ actions: ACTIONS,
980
+ status: STATUS,
981
+ productTypes: TYPES,
982
+ correlations: STATUS_CORRELATIONS,
983
+ offshore: OFFSHORE,
984
+ awips: AWIPS,
985
+ cancelSignatures: CANCEL_SIGNATURES,
986
+ messageSignatures: MESSAGE_SIGNATURES,
987
+ tags: TAGS,
988
+ ICAO: ICAOs,
989
+ enhancedEvents: [
990
+ { "Tornado Warning": {
991
+ "Tornado Emergency": { description: "tornado emergency", condition: (tornadoThreatTag) => tornadoThreatTag === "OBSERVED" },
992
+ "PDS Tornado Warning": { description: "particularly dangerous situation", condition: (damageThreatTag) => damageThreatTag === "CONSIDERABLE" },
993
+ "Confirmed Tornado Warning": { condition: (tornadoThreatTag) => tornadoThreatTag === "OBSERVED" },
994
+ "Radar Indicated Tornado Warning": { condition: (tornadoThreatTag) => tornadoThreatTag !== "OBSERVED" }
995
+ } },
996
+ { "Tornado Watch": {
997
+ "PDS Tornado Watch": { description: "particularly dangerous situation" }
998
+ } },
999
+ { "Flash Flood Warning": {
1000
+ "Flash Flood Emergency": { description: "flash flood emergency" },
1001
+ "Considerable Flash Flood Warning": { condition: (damageThreatTag) => damageThreatTag === "CONSIDERABLE" }
1002
+ } },
1003
+ { "Severe Thunderstorm Warning": {
1004
+ "EDS Severe Thunderstorm Warning": { description: "extremely dangerous situation" },
1005
+ "Destructive Severe Thunderstorm Warning": { condition: (damageThreatTag) => damageThreatTag === "DESTRUCTIVE" },
1006
+ "Considerable Severe Thunderstorm Warning": { condition: (damageThreatTag) => damageThreatTag === "CONSIDERABLE" }
1007
+ } }
1008
+ ],
1009
+ expressions: {
1010
+ vtec: `[OTEX].(NEW|CON|EXT|EXA|EXB|UPG|CAN|EXP|COR|ROU).[A-Z]{4}.[A-Z]{2}.[WAYSFON].[0-9]{4}.[0-9]{6}T[0-9]{4}Z-[0-9]{6}T[0-9]{4}Z`,
1011
+ wmo: `[A-Z0-9]{6}\\s[A-Z]{4}\\s\\d{6}`,
1012
+ ugc1: `(\\w{2}[CZ](\\d{3}((-|>)\\s?(
1013
+
1014
+ )?))+)`,
1015
+ ugc2: `(\\d{6}(-|>)\\s?(
1016
+
1017
+ )?)`,
1018
+ ugc3: `(\\d{6})(?=-|$)`,
1019
+ dateline: `/d{3,4}s*(AM|PM)?s*[A-Z]{2,4}s+[A-Z]{3,}s+[A-Z]{3,}s+d{1,2}s+d{4}`,
1020
+ wmoID: `[A-Z0-9]{2}([A-Z]{3})`
1021
+ },
1022
+ shapefiles: [
1023
+ { id: `C`, file: `USCounties` },
1024
+ { id: `Z`, file: `ForecastZones` },
1025
+ { id: `Z`, file: `FireZones` },
1026
+ { id: `Z`, file: `OffShoreZones` },
1027
+ { id: `Z`, file: `FireCounties` },
1028
+ { id: `Z`, file: `Marine` }
1029
+ ],
1030
+ messages: {
1031
+ shapefile_creation: `[NOTICE] DO NOT CLOSE THIS PROJECT UNTIL THE SHAPEFILES ARE DONE COMPLETING!
1032
+ THIS COULD TAKE A WHILE DEPENDING ON THE SPEED OF YOUR STORAGE!!
1033
+ IF YOU CLOSE YOUR PROJECT, THE SHAPEFILES WILL NOT BE CREATED AND YOU WILL NEED TO DELETE ${settings.database} AND RESTART TO CREATE THEM AGAIN!`,
1034
+ shapefile_creation_finished: `[NOTICE] SHAPEFILES HAVE BEEN SUCCESSFULLY CREATED AND THE DATABASE IS READY FOR USE!`,
1035
+ not_ready: "[ERROR] You can NOT create another instance without shutting down the current one first, please make sure to call the stop() method first!",
1036
+ invalid_nickname: "[WARNING] The nickname you provided is invalid, please provide a valid nickname to continue.",
1037
+ eas_no_directory: "[WARNING] You have not set a directory for EAS audio files to be saved to, please set the 'easDirectory' setting in the global settings to enable EAS audio generation."
1038
+ }
1039
+ };
1040
+
1041
+ // src/parsers/vtec.ts
1042
+ var VtecParser = class {
1043
+ /**
1044
+ * vtecExtractor extracts and parses VTEC codes from a given message string.
1045
+ *
1046
+ * @public
1047
+ * @static
1048
+ * @async
1049
+ * @param {string} message
1050
+ * @returns {unknown}
1051
+ */
1052
+ static vtecExtractor(message) {
1053
+ return __async(this, null, function* () {
1054
+ const vtecs = [];
1055
+ const matches = message.match(new RegExp(definitions.expressions.vtec, "g"));
1056
+ if (!matches) return null;
1057
+ for (let i = 0; i < matches.length; i++) {
1058
+ const vtec = matches[i];
1059
+ const parts = vtec.split(`.`);
1060
+ const dates = parts[6].split(`-`);
1061
+ vtecs.push({
1062
+ raw: vtec,
1063
+ type: definitions.productTypes[parts[0]],
1064
+ tracking: `${parts[2]}-${parts[3]}-${parts[4]}-${parts[5]}`,
1065
+ event: `${definitions.events[parts[3]]} ${definitions.actions[parts[4]]}`,
1066
+ status: definitions.status[parts[1]],
1067
+ wmo: message.match(new RegExp(definitions.expressions.wmo, "gimu")),
1068
+ expires: this.parseExpiryDate(dates)
1069
+ });
1070
+ }
1071
+ return vtecs;
1072
+ });
1073
+ }
1074
+ /**
1075
+ * parseExpiryDate converts VTEC expiry date format to a standard ISO 8601 format with timezone adjustment.
1076
+ *
1077
+ * @private
1078
+ * @static
1079
+ * @param {String[]} args
1080
+ * @returns {string}
1081
+ */
1082
+ static parseExpiryDate(args) {
1083
+ if (args[1] == `000000T0000Z`) return `Invalid Date Format`;
1084
+ const expires = `${(/* @__PURE__ */ new Date()).getFullYear().toString().substring(0, 2)}${args[1].substring(0, 2)}-${args[1].substring(2, 4)}-${args[1].substring(4, 6)}T${args[1].substring(7, 9)}:${args[1].substring(9, 11)}:00`;
1085
+ const local = new Date(new Date(expires).getTime() - 4 * 60 * 6e4);
1086
+ const pad = (n) => n.toString().padStart(2, "0");
1087
+ return `${local.getFullYear()}-${pad(local.getMonth() + 1)}-${pad(local.getDate())}T${pad(local.getHours())}:${pad(local.getMinutes())}:00.000-04:00`;
1088
+ }
1089
+ };
1090
+ var vtec_default = VtecParser;
1091
+
1092
+ // src/parsers/ugc.ts
1093
+ var UGCParser = class {
1094
+ /**
1095
+ * ugcExtractor extracts and parses UGC codes from a given message string.
1096
+ *
1097
+ * @public
1098
+ * @static
1099
+ * @async
1100
+ * @param {string} message
1101
+ * @returns {unknown}
1102
+ */
1103
+ static ugcExtractor(message) {
1104
+ return __async(this, null, function* () {
1105
+ const header = this.getHeader(message);
1106
+ const zones = this.getZones(header);
1107
+ const expiry = this.getExpiry(message);
1108
+ const locations = yield this.getLocations(zones);
1109
+ const ugc = zones.length > 0 ? { zones, locations, expiry } : null;
1110
+ return ugc;
1111
+ });
1112
+ }
1113
+ /**
1114
+ * getHeader extracts the UGC header from a UGC message string.
1115
+ *
1116
+ * @public
1117
+ * @static
1118
+ * @param {string} message
1119
+ * @returns {*}
1120
+ */
1121
+ static getHeader(message) {
1122
+ const start = message.search(new RegExp(definitions.expressions.ugc1, "gimu"));
1123
+ const end = message.substring(start).search(new RegExp(definitions.expressions.ugc2, "gimu"));
1124
+ const full = message.substring(start, start + end).replace(/\s+/g, "").slice(0, -1);
1125
+ return full;
1126
+ }
1127
+ /**
1128
+ * getExpiry extracts the expiry date and time from a UGC message and returns it as a Date object.
1129
+ *
1130
+ * @public
1131
+ * @static
1132
+ * @param {string} message
1133
+ * @returns {*}
1134
+ */
1135
+ static getExpiry(message) {
1136
+ const start = message.match(new RegExp(definitions.expressions.ugc3, "gimu"));
1137
+ if (start != null) {
1138
+ const day = parseInt(start[0].substring(0, 2), 10);
1139
+ const hour = parseInt(start[0].substring(2, 4), 10);
1140
+ const minute = parseInt(start[0].substring(4, 6), 10);
1141
+ const now = /* @__PURE__ */ new Date();
1142
+ const expires = new Date(now.getUTCFullYear(), now.getUTCMonth(), day, hour, minute, 0);
1143
+ return expires;
1144
+ }
1145
+ return null;
1146
+ }
1147
+ /**
1148
+ * getLocations retrieves unique location names for the provided UGC zone codes from the database.
1149
+ *
1150
+ * @public
1151
+ * @static
1152
+ * @async
1153
+ * @param {String[]} zones
1154
+ * @returns {unknown}
1155
+ */
1156
+ static getLocations(zones) {
1157
+ return __async(this, null, function* () {
1158
+ const locations = [];
1159
+ for (let i = 0; i < zones.length; i++) {
1160
+ const id = zones[i].trim();
1161
+ const located = yield cache.db.prepare(`SELECT location FROM shapefiles WHERE id = ?`).get(id);
1162
+ located != void 0 ? locations.push(located.location) : locations.push(id);
1163
+ }
1164
+ return Array.from(new Set(locations)).sort();
1165
+ });
1166
+ }
1167
+ /**
1168
+ * getCoordinates retrieves geographical coordinates for the provided UGC zone codes from the database.
1169
+ *
1170
+ * @public
1171
+ * @static
1172
+ * @param {String[]} zones
1173
+ * @returns {{}}
1174
+ */
1175
+ static getCoordinates(zones) {
1176
+ let coordinates = [];
1177
+ for (let i = 0; i < zones.length; i++) {
1178
+ const id = zones[i].trim();
1179
+ let located = cache.db.prepare(`SELECT geometry FROM shapefiles WHERE id = ?`).get(id);
1180
+ if (located != void 0) {
1181
+ let geometry = JSON.parse(located.geometry);
1182
+ if ((geometry == null ? void 0 : geometry.type) === "Polygon") {
1183
+ coordinates.push(...geometry.coordinates[0].map((coord) => [coord[0], coord[1]]));
1184
+ break;
1185
+ }
1186
+ }
1187
+ }
1188
+ return coordinates;
1189
+ }
1190
+ /**
1191
+ * getZones parses a UGC header string and returns an array of individual UGC zone codes.
1192
+ *
1193
+ * @public
1194
+ * @static
1195
+ * @param {string} header
1196
+ * @returns {*}
1197
+ */
1198
+ static getZones(header) {
1199
+ const ugcSplit = header.split("-");
1200
+ const zones = [];
1201
+ let state = ugcSplit[0].substring(0, 2);
1202
+ let format = ugcSplit[0].substring(2, 3);
1203
+ for (let i = 0; i < ugcSplit.length; i++) {
1204
+ if (/^[A-Z]/.test(ugcSplit[i])) {
1205
+ state = ugcSplit[i].substring(0, 2);
1206
+ if (ugcSplit[i].includes(">")) {
1207
+ let [start, end] = ugcSplit[i].split(">"), startNum = parseInt(start.substring(3), 10), endNum = parseInt(end, 10);
1208
+ for (let j = startNum; j <= endNum; j++) zones.push(`${state}${format}${j.toString().padStart(3, "0")}`);
1209
+ } else zones.push(ugcSplit[i]);
1210
+ continue;
1211
+ }
1212
+ if (ugcSplit[i].includes(">")) {
1213
+ let [start, end] = ugcSplit[i].split(">"), startNum = parseInt(start, 10), endNum = parseInt(end, 10);
1214
+ for (let j = startNum; j <= endNum; j++) zones.push(`${state}${format}${j.toString().padStart(3, "0")}`);
1215
+ } else zones.push(`${state}${format}${ugcSplit[i]}`);
1216
+ }
1217
+ return zones.filter((item) => item !== "");
1218
+ }
1219
+ };
1220
+ var ugc_default = UGCParser;
1221
+
1222
+ // src/parsers/text.ts
1223
+ var TextParser = class {
1224
+ /**
1225
+ * textProductToString extracts a specific value from a text-based weather product message based on a given key and optional removal strings.
1226
+ *
1227
+ * @public
1228
+ * @static
1229
+ * @param {string} message
1230
+ * @param {string} value
1231
+ * @param {string[]} [removal=[]]
1232
+ * @returns {(string | null)}
1233
+ */
1234
+ static textProductToString(message, value, removal = []) {
1235
+ const lines = message.split("\n");
1236
+ for (const line of lines) {
1237
+ if (line.includes(value)) {
1238
+ let result = line.slice(line.indexOf(value) + value.length).trim();
1239
+ for (const str of removal) {
1240
+ result = result.split(str).join("");
1241
+ }
1242
+ result = result.replace(value, "").replace("<", "").trim();
1243
+ return result || null;
1244
+ }
1245
+ }
1246
+ return null;
1247
+ }
1248
+ /**
1249
+ * textProductToPolygon extracts geographical coordinates from a text-based weather product message and returns them as an array of [longitude, latitude] pairs.
1250
+ *
1251
+ * @public
1252
+ * @static
1253
+ * @param {string} message
1254
+ * @returns {[number, number][]}
1255
+ */
1256
+ static textProductToPolygon(message) {
1257
+ const coordinates = [];
1258
+ const latLonMatch = message.match(/LAT\.{3}LON\s+([\d\s]+)/i);
1259
+ if (!latLonMatch || !latLonMatch[1]) return coordinates;
1260
+ const coordStrings = latLonMatch[1].replace(/\n/g, " ").trim().split(/\s+/);
1261
+ for (let i = 0; i < coordStrings.length - 1; i += 2) {
1262
+ const lat = parseFloat(coordStrings[i]) / 100;
1263
+ const lon = -parseFloat(coordStrings[i + 1]) / 100;
1264
+ if (!isNaN(lat) && !isNaN(lon)) {
1265
+ coordinates.push([lon, lat]);
1266
+ }
1267
+ }
1268
+ if (coordinates.length > 2) {
1269
+ coordinates.push(coordinates[0]);
1270
+ }
1271
+ return coordinates;
1272
+ }
1273
+ /**
1274
+ * textProductToDescription extracts the main description from a text-based weather product message.
1275
+ *
1276
+ * @public
1277
+ * @static
1278
+ * @param {string} message
1279
+ * @param {string} [handle=null]
1280
+ * @returns {string}
1281
+ */
1282
+ static textProductToDescription(message, handle = null) {
1283
+ const original = message;
1284
+ const dateRegex = /\d{3,4}\s*(AM|PM)?\s*[A-Z]{2,4}\s+[A-Z]{3,}\s+[A-Z]{3,}\s+\d{1,2}\s+\d{4}/gim;
1285
+ const discoveredDates = Array.from(message.matchAll(dateRegex));
1286
+ if (discoveredDates.length) {
1287
+ const lastMatch = discoveredDates[discoveredDates.length - 1][0];
1288
+ const startIdx = message.lastIndexOf(lastMatch);
1289
+ if (startIdx !== -1) {
1290
+ const endIdx = message.indexOf("&&", startIdx);
1291
+ message = message.substring(startIdx + lastMatch.length, endIdx !== -1 ? endIdx : void 0).trimStart();
1292
+ if (message.startsWith("/")) message = message.slice(1).trimStart();
1293
+ if (handle && message.includes(handle)) {
1294
+ const handleIdx = message.indexOf(handle);
1295
+ message = message.substring(handleIdx + handle.length).trimStart();
1296
+ if (message.startsWith("/")) message = message.slice(1).trimStart();
1297
+ }
1298
+ }
1299
+ } else if (handle) {
1300
+ const handleIdx = message.indexOf(handle);
1301
+ if (handleIdx !== -1) {
1302
+ let afterHandle = message.substring(handleIdx + handle.length).trimStart();
1303
+ if (afterHandle.startsWith("/")) afterHandle = afterHandle.slice(1).trimStart();
1304
+ const latEnd = afterHandle.indexOf("&&");
1305
+ message = latEnd !== -1 ? afterHandle.substring(0, latEnd).trim() : afterHandle.trim();
1306
+ }
1307
+ }
1308
+ return message.replace(/\s+/g, " ").trim().startsWith("ISSUED TIME...") ? original : message.trim();
1309
+ }
1310
+ /**
1311
+ * awipTextToEvent converts an AWIPS ID prefix from a text-based weather product message to its corresponding event type and prefix.
1312
+ *
1313
+ * @public
1314
+ * @static
1315
+ * @param {string} message
1316
+ * @returns {{ type: any; prefix: any; }}
1317
+ */
1318
+ static awipTextToEvent(message) {
1319
+ for (const [prefix, type] of Object.entries(definitions.awips)) {
1320
+ if (message.startsWith(prefix)) {
1321
+ return { type, prefix };
1322
+ }
1323
+ }
1324
+ return { type: `XX`, prefix: `XX` };
1325
+ }
1326
+ /**
1327
+ * getXmlValues recursively searches a parsed XML object for specified keys and extracts their values.
1328
+ *
1329
+ * @public
1330
+ * @static
1331
+ * @param {*} parsed
1332
+ * @param {string[]} valuesToExtract
1333
+ * @returns {Record<string, any>}
1334
+ */
1335
+ static getXmlValues(parsed, valuesToExtract) {
1336
+ const extracted = {};
1337
+ const findValueByKey = (obj, searchKey) => {
1338
+ const results = [];
1339
+ if (obj === null || typeof obj !== "object") {
1340
+ return results;
1341
+ }
1342
+ const searchKeyLower = searchKey.toLowerCase();
1343
+ for (const key in obj) {
1344
+ if (obj.hasOwnProperty(key) && key.toLowerCase() === searchKeyLower) {
1345
+ results.push(obj[key]);
1346
+ }
1347
+ }
1348
+ if (Array.isArray(obj)) {
1349
+ for (const item of obj) {
1350
+ if (item.valueName && item.valueName.toLowerCase() === searchKeyLower && item.value !== void 0) {
1351
+ results.push(item.value);
1352
+ }
1353
+ const nestedResults = findValueByKey(item, searchKey);
1354
+ results.push(...nestedResults);
1355
+ }
1356
+ }
1357
+ for (const key in obj) {
1358
+ if (obj.hasOwnProperty(key)) {
1359
+ const nestedResults = findValueByKey(obj[key], searchKey);
1360
+ results.push(...nestedResults);
1361
+ }
1362
+ }
1363
+ return results;
1364
+ };
1365
+ for (const key of valuesToExtract) {
1366
+ const values = findValueByKey(parsed.alert, key);
1367
+ const uniqueValues = [...new Set(values)];
1368
+ extracted[key] = uniqueValues.length === 0 ? null : uniqueValues.length === 1 ? uniqueValues[0] : uniqueValues;
1369
+ }
1370
+ return extracted;
1371
+ }
1372
+ };
1373
+ var text_default = TextParser;
1374
+
1375
+ // src/parsers/types/ugc.ts
1376
+ var UGCAlerts = class {
1377
+ /**
1378
+ * getTracking generates a unique tracking identifier based on the sender's ICAO code and a hash of the UGC zones.
1379
+ *
1380
+ * @private
1381
+ * @static
1382
+ * @param {types.BaseProperties} baseProperties
1383
+ * @param {string[]} zones
1384
+ * @returns {string}
1385
+ */
1386
+ static getTracking(baseProperties, zones) {
1387
+ return `${baseProperties.sender_icao} (${packages.crypto.createHash("md5").update(zones.join(``)).digest("hex")}})`;
1388
+ }
1389
+ /**
1390
+ * getEvent determines the event name based on offshore definitions or formats it from the attributes.
1391
+ *
1392
+ * @private
1393
+ * @static
1394
+ * @param {string} message
1395
+ * @param {Record<string, any>} attributes
1396
+ * @returns {*}
1397
+ */
1398
+ static getEvent(message, attributes) {
1399
+ const offshoreEvent = Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1400
+ if (offshoreEvent != void 0) return Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1401
+ return attributes.type.split(`-`).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(` `);
1402
+ }
1403
+ /**
1404
+ * event processes validated UGC alert messages, extracting relevant information and compiling it into structured event objects.
1405
+ *
1406
+ * @public
1407
+ * @static
1408
+ * @async
1409
+ * @param {types.TypeCompiled} validated
1410
+ * @returns {*}
1411
+ */
1412
+ static event(validated) {
1413
+ return __async(this, null, function* () {
1414
+ var _a;
1415
+ let processed = [];
1416
+ const messages = (_a = validated.message.split(/(?=\$\$|ISSUED TIME...|=================================================)/g)) == null ? void 0 : _a.map((msg) => msg.trim());
1417
+ if (!messages || messages.length == 0) return;
1418
+ for (let i = 0; i < messages.length; i++) {
1419
+ const tick = performance.now();
1420
+ const message = messages[i];
1421
+ const getUGC = yield ugc_default.ugcExtractor(message);
1422
+ if (getUGC != null) {
1423
+ const getBaseProperties = yield events_default.getBaseProperties(message, validated, getUGC);
1424
+ const getHeader = events_default.getHeader(__spreadValues(__spreadValues({}, validated.attributes), getBaseProperties.attributes), getBaseProperties);
1425
+ const getEvent = this.getEvent(message, getBaseProperties.attributes.getAwip);
1426
+ processed.push({
1427
+ preformance: performance.now() - tick,
1428
+ tracking: this.getTracking(getBaseProperties, getUGC.zones),
1429
+ header: getHeader,
1430
+ vtec: `N/A`,
1431
+ history: [{ description: getBaseProperties.description, issued: getBaseProperties.issued, type: `Issued` }],
1432
+ properties: __spreadValues({ event: getEvent, parent: getEvent, action_type: `Issued` }, getBaseProperties)
1433
+ });
1434
+ }
1435
+ }
1436
+ events_default.validateEvents(processed);
1437
+ });
1438
+ }
1439
+ };
1440
+ var ugc_default2 = UGCAlerts;
1441
+
1442
+ // src/parsers/types/text.ts
1443
+ var UGCAlerts2 = class {
1444
+ static getTracking(baseProperties) {
1445
+ return `${baseProperties.sender_icao}`;
1446
+ }
1447
+ static getEvent(message, attributes) {
1448
+ const offshoreEvent = Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1449
+ if (offshoreEvent) return Object.keys(definitions.offshore).find((event) => message.toLowerCase().includes(event.toLowerCase()));
1450
+ return attributes.type.split(`-`).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(` `);
1451
+ }
1452
+ static event(validated) {
1453
+ return __async(this, null, function* () {
1454
+ var _a;
1455
+ let processed = [];
1456
+ const messages = (_a = validated.message.split(/(?=\$\$|ISSUED TIME...|=================================================)/g)) == null ? void 0 : _a.map((msg) => msg.trim());
1457
+ if (!messages || messages.length == 0) return;
1458
+ for (let i = 0; i < messages.length; i++) {
1459
+ const tick = performance.now();
1460
+ const message = messages[i];
1461
+ const getBaseProperties = yield events_default.getBaseProperties(message, validated);
1462
+ const getHeader = events_default.getHeader(__spreadValues(__spreadValues({}, validated.attributes), getBaseProperties.attributes), getBaseProperties);
1463
+ const getEvent = this.getEvent(message, getBaseProperties.attributes.getAwip);
1464
+ processed.push({
1465
+ preformance: performance.now() - tick,
1466
+ tracking: this.getTracking(getBaseProperties),
1467
+ header: getHeader,
1468
+ vtec: `N/A`,
1469
+ history: [{ description: getBaseProperties.description, issued: getBaseProperties.issued, type: `Issued` }],
1470
+ properties: __spreadValues({ event: getEvent, parent: getEvent, action_type: `Issued` }, getBaseProperties)
1471
+ });
1472
+ }
1473
+ events_default.validateEvents(processed);
1474
+ });
1475
+ }
1476
+ };
1477
+ var text_default2 = UGCAlerts2;
1478
+
1479
+ // src/parsers/types/cap.ts
1480
+ var CapAlerts = class {
1481
+ static getTracking(extracted) {
1482
+ return extracted.vtec ? (() => {
1483
+ const vtecValue = Array.isArray(extracted.vtec) ? extracted.vtec[0] : extracted.vtec;
1484
+ const splitVTEC = vtecValue.split(".");
1485
+ return `${splitVTEC[2]}-${splitVTEC[3]}-${splitVTEC[4]}-${splitVTEC[5]}`;
1486
+ })() : `${extracted.wmoidentifier} (${extracted.ugc})`;
1487
+ }
1488
+ static event(validated) {
1489
+ return __async(this, null, function* () {
1490
+ var _a;
1491
+ let processed = [];
1492
+ const messages = (_a = validated.message.match(/<\?xml[\s\S]*?<\/alert>/g)) == null ? void 0 : _a.map((msg) => msg.trim());
1493
+ if (messages == null || messages.length === 0) return;
1494
+ for (let message of messages) {
1495
+ const tick = performance.now();
1496
+ message = message.substring(message.indexOf(`<?xml version="1.0"`), message.lastIndexOf(`>`) + 1);
1497
+ const parser = new packages.xml2js.Parser({ explicitArray: false, mergeAttrs: true, trim: true });
1498
+ const parsed = yield parser.parseStringPromise(message);
1499
+ if (parsed == null || parsed.alert == null) continue;
1500
+ const extracted = text_default.getXmlValues(parsed, [
1501
+ `vtec`,
1502
+ `wmoidentifier`,
1503
+ `ugc`,
1504
+ `areadesc`,
1505
+ `expires`,
1506
+ `sent`,
1507
+ `msgtype`,
1508
+ `description`,
1509
+ `event`,
1510
+ `sendername`,
1511
+ `tornadodetection`,
1512
+ `polygon`,
1513
+ `maxHailSize`,
1514
+ `maxWindGust`,
1515
+ `thunderstormdamagethreat`,
1516
+ `tornadodamagethreat`,
1517
+ `waterspoutdetection`,
1518
+ `flooddetection`
1519
+ ]);
1520
+ const getHeader = events_default.getHeader(__spreadValues({}, validated.attributes));
1521
+ const getSource = text_default.textProductToString(extracted.description, `SOURCE...`, [`.`]) || `N/A`;
1522
+ processed.push({
1523
+ preformance: performance.now() - tick,
1524
+ tracking: this.getTracking(extracted),
1525
+ header: getHeader,
1526
+ vtec: extracted.vtec || `N/A`,
1527
+ history: [{ description: extracted.description || `N/A`, issued: extracted.sent ? new Date(extracted.sent).toLocaleString() : `N/A`, type: extracted.msgtype || `N/A` }],
1528
+ properties: {
1529
+ locations: extracted.areadesc || `N/A`,
1530
+ event: extracted.event || `N/A`,
1531
+ issued: extracted.sent ? new Date(extracted.sent).toLocaleString() : `N/A`,
1532
+ expires: extracted.expires ? new Date(extracted.expires).toLocaleString() : `N/A`,
1533
+ parent: extracted.event || `N/A`,
1534
+ action_type: extracted.msgtype || `N/A`,
1535
+ description: extracted.description || `N/A`,
1536
+ sender_name: extracted.sendername || `N/A`,
1537
+ sender_icao: extracted.wmoidentifier ? extracted.wmoidentifier.substring(extracted.wmoidentifier.length - 4) : `N/A`,
1538
+ attributes: validated.attributes,
1539
+ geocode: {
1540
+ UGC: [extracted.ugc]
1541
+ },
1542
+ parameters: {
1543
+ wmo: extracted.wmoidentifier || `N/A`,
1544
+ source: getSource,
1545
+ max_hail_size: extracted.maxHailSize || `N/A`,
1546
+ max_wind_gust: extracted.maxWindGust || `N/A`,
1547
+ damage_threat: extracted.thunderstormdamagethreat || `N/A`,
1548
+ tornado_detection: extracted.tornadodetection || extracted.waterspoutdetection || `N/A`,
1549
+ flood_detection: extracted.flooddetection || `N/A`,
1550
+ discussion_tornado_intensity: `N/A`,
1551
+ discussion_wind_intensity: `N/A`,
1552
+ discussion_hail_intensity: `N/A`
1553
+ },
1554
+ geometry: extracted.polygon ? { type: `Polygon`, coordinates: extracted.polygon.split(` `).map((coord) => coord.split(`,`).map((num) => parseFloat(num))) } : null
1555
+ }
1556
+ });
1557
+ }
1558
+ events_default.validateEvents(processed);
1559
+ });
1560
+ }
1561
+ };
1562
+ var cap_default = CapAlerts;
1563
+
1564
+ // src/parsers/types/api.ts
1565
+ var APIAlerts = class {
1566
+ static getTracking(extracted) {
1567
+ return extracted.vtec ? (() => {
1568
+ const vtecValue = Array.isArray(extracted.vtec) ? extracted.vtec[0] : extracted.vtec;
1569
+ const splitVTEC = vtecValue.split(".");
1570
+ return `${splitVTEC[2]}-${splitVTEC[3]}-${splitVTEC[4]}-${splitVTEC[5]}`;
1571
+ })() : `${extracted.wmoidentifier} (${extracted.ugc})`;
1572
+ }
1573
+ static getICAO(vtec) {
1574
+ var _a, _b;
1575
+ const icao = vtec ? vtec.split(`.`)[2] : `N/A`;
1576
+ const name = (_b = (_a = definitions.ICAO) == null ? void 0 : _a[icao]) != null ? _b : `N/A`;
1577
+ return { icao, name };
1578
+ }
1579
+ static event(validated) {
1580
+ return __async(this, null, function* () {
1581
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca;
1582
+ let processed = [];
1583
+ const messages = Object.values(JSON.parse(validated.message).features);
1584
+ for (let feature of messages) {
1585
+ const tick = performance.now();
1586
+ const getVTEC = (_d = (_c = (_b = (_a = feature == null ? void 0 : feature.properties) == null ? void 0 : _a.parameters) == null ? void 0 : _b.VTEC) == null ? void 0 : _c[0]) != null ? _d : null;
1587
+ const getWmo = (_g = (_f = (_e = feature == null ? void 0 : feature.properties) == null ? void 0 : _e.parameters) == null ? void 0 : _f.WMOidentifier[0]) != null ? _g : null;
1588
+ const getUgc = (_j = (_i = (_h = feature == null ? void 0 : feature.properties) == null ? void 0 : _h.geocode) == null ? void 0 : _i.UGC) != null ? _j : null;
1589
+ const getHeadline = (_n = (_m = (_l = (_k = feature == null ? void 0 : feature.properties) == null ? void 0 : _k.parameters) == null ? void 0 : _l.NWSheadline) == null ? void 0 : _m[0]) != null ? _n : "";
1590
+ const getDescription = `${getHeadline} ${(_p = (_o = feature == null ? void 0 : feature.properties) == null ? void 0 : _o.description) != null ? _p : ``}`;
1591
+ const getAWIP = (_t = (_s = (_r = (_q = feature == null ? void 0 : feature.properties) == null ? void 0 : _q.parameters) == null ? void 0 : _r.AWIPSidentifier) == null ? void 0 : _s[0]) != null ? _t : null;
1592
+ const getHeader = events_default.getHeader(__spreadValues({}, { getAwip: { prefix: getAWIP == null ? void 0 : getAWIP.slice(0, -3) } }));
1593
+ const getSource = text_default.textProductToString(getDescription, `SOURCE...`, [`.`]) || `N/A`;
1594
+ const getOffice = this.getICAO(getVTEC || ``);
1595
+ processed.push({
1596
+ preformance: performance.now() - tick,
1597
+ tracking: this.getTracking({ vtec: getVTEC, wmoidentifier: getWmo, ugc: getUgc ? getUgc.join(`,`) : null }),
1598
+ header: getHeader,
1599
+ vtec: getVTEC || `N/A`,
1600
+ history: [{
1601
+ description: (_v = (_u = feature == null ? void 0 : feature.properties) == null ? void 0 : _u.description) != null ? _v : `N/A`,
1602
+ action: (_x = (_w = feature == null ? void 0 : feature.properties) == null ? void 0 : _w.messageType) != null ? _x : `N/A`,
1603
+ time: ((_y = feature == null ? void 0 : feature.properties) == null ? void 0 : _y.sent) ? new Date((_z = feature == null ? void 0 : feature.properties) == null ? void 0 : _z.sent).toLocaleString() : `N/A`
1604
+ }],
1605
+ properties: {
1606
+ locations: (_B = (_A = feature == null ? void 0 : feature.properties) == null ? void 0 : _A.areaDesc) != null ? _B : `N/A`,
1607
+ event: (_D = (_C = feature == null ? void 0 : feature.properties) == null ? void 0 : _C.event) != null ? _D : `N/A`,
1608
+ issued: ((_E = feature == null ? void 0 : feature.properties) == null ? void 0 : _E.sent) ? new Date((_F = feature == null ? void 0 : feature.properties) == null ? void 0 : _F.sent).toLocaleString() : `N/A`,
1609
+ expires: ((_G = feature == null ? void 0 : feature.properties) == null ? void 0 : _G.expires) ? new Date((_H = feature == null ? void 0 : feature.properties) == null ? void 0 : _H.expires).toLocaleString() : `N/A`,
1610
+ parent: (_J = (_I = feature == null ? void 0 : feature.properties) == null ? void 0 : _I.event) != null ? _J : `N/A`,
1611
+ action_type: (_L = (_K = feature == null ? void 0 : feature.properties) == null ? void 0 : _K.messageType) != null ? _L : `N/A`,
1612
+ description: (_N = (_M = feature == null ? void 0 : feature.properties) == null ? void 0 : _M.description) != null ? _N : `N/A`,
1613
+ sender_name: getOffice.name || `N/A`,
1614
+ sender_icao: getOffice.icao || `N/A`,
1615
+ attributes: validated.attributes,
1616
+ geocode: {
1617
+ UGC: (_Q = (_P = (_O = feature == null ? void 0 : feature.properties) == null ? void 0 : _O.geocode) == null ? void 0 : _P.UGC) != null ? _Q : [`XX000`]
1618
+ },
1619
+ parameters: {
1620
+ wmo: ((_T = (_S = (_R = feature == null ? void 0 : feature.properties) == null ? void 0 : _R.parameters) == null ? void 0 : _S.WMOidentifier) == null ? void 0 : _T[0]) || getWmo || `N/A`,
1621
+ source: getSource,
1622
+ max_hail_size: ((_V = (_U = feature == null ? void 0 : feature.properties) == null ? void 0 : _U.parameters) == null ? void 0 : _V.maxHailSize) || `N/A`,
1623
+ max_wind_gust: ((_X = (_W = feature == null ? void 0 : feature.properties) == null ? void 0 : _W.parameters) == null ? void 0 : _X.maxWindGust) || `N/A`,
1624
+ damage_threat: ((_Z = (_Y = feature == null ? void 0 : feature.properties) == null ? void 0 : _Y.parameters) == null ? void 0 : _Z.thunderstormDamageThreat) || [`N/A`],
1625
+ tornado_detection: ((_$ = (__ = feature == null ? void 0 : feature.properties) == null ? void 0 : __.parameters) == null ? void 0 : _$.tornadoDetection) || [`N/A`],
1626
+ flood_detection: ((_ba = (_aa = feature == null ? void 0 : feature.properties) == null ? void 0 : _aa.parameters) == null ? void 0 : _ba.floodDetection) || [`N/A`],
1627
+ discussion_tornado_intensity: "N/A",
1628
+ peakWindGust: `N/A`,
1629
+ peakHailSize: `N/A`
1630
+ },
1631
+ geometry: (_ca = feature == null ? void 0 : feature.geometry) != null ? _ca : null
1632
+ }
1633
+ });
1634
+ }
1635
+ events_default.validateEvents(processed);
1636
+ });
1637
+ }
1638
+ };
1639
+ var api_default = APIAlerts;
1640
+
1641
+ // src/parsers/stanza.ts
1642
+ var StanzaParser = class {
1643
+ /**
1644
+ * validate handles the validation of incoming XMPP stanzas to ensure they contain valid alert data.
1645
+ * You can also feed debug / cache data directly into this function by specifying the second parameter
1646
+ * which is the attributes object that would normally be parsed from the XMPP stanza.
1647
+ *
1648
+ * @public
1649
+ * @static
1650
+ * @param {*} stanza
1651
+ * @param {(boolean | types.TypeAttributes)} [isDebug=false]
1652
+ * @returns {{ message: any; attributes: types.TypeAttributes; isCap: any; isVtec: boolean; isCapDescription: any; awipsType: any; isApi: boolean; ignore: boolean; }}
1653
+ */
1654
+ static validate(stanza, isDebug = false) {
1655
+ var _a;
1656
+ if (isDebug !== false) {
1657
+ const vTypes = isDebug;
1658
+ const message = stanza;
1659
+ const attributes = vTypes;
1660
+ const isCap = (_a = vTypes.isCap) != null ? _a : message.includes(`<?xml`);
1661
+ const isCapDescription = message.includes(`<areaDesc>`);
1662
+ const isVtec = message.match(definitions.expressions.vtec) != null;
1663
+ const isUGC = message.match(definitions.expressions.ugc1) != null;
1664
+ const awipsType = this.getType(attributes);
1665
+ return { message, attributes, isCap, isVtec, isUGC, isCapDescription, awipsType, isApi: false, ignore: false };
1666
+ }
1667
+ if (stanza.is(`message`)) {
1668
+ let cb = stanza.getChild(`x`);
1669
+ if (cb && cb.children) {
1670
+ let message = unescape(cb.children[0]);
1671
+ let attributes = cb.attrs;
1672
+ if (attributes.awipsid && attributes.awipsid.length > 1) {
1673
+ const isCap = message.includes(`<?xml`);
1674
+ const isCapDescription = message.includes(`<areaDesc>`);
1675
+ const isVtec = message.match(definitions.expressions.vtec) != null;
1676
+ const isUGC = message.match(definitions.expressions.ugc1) != null;
1677
+ const awipsType = this.getType(attributes);
1678
+ const isApi = false;
1679
+ this.cache({ message, attributes, isCap, isVtec, awipsType: awipsType.type, awipsPrefix: awipsType.prefix });
1680
+ return { message, attributes, isCap, isApi, isVtec, isUGC, isCapDescription, awipsType, ignore: false };
1681
+ }
1682
+ }
1683
+ }
1684
+ return { message: null, attributes: null, isApi: null, isCap: null, isVtec: null, isUGC: null, isCapDescription: null, awipsType: null, ignore: true };
1685
+ }
1686
+ /**
1687
+ * getType determines the AWIPS type of the alert based on its attributes, specifically the awipsid.
1688
+ * If no matching type is found, it defaults to 'default'.
1689
+ *
1690
+ * @private
1691
+ * @static
1692
+ * @param {unknown} attributes
1693
+ * @returns {*}
1694
+ */
1695
+ static getType(attributes) {
1696
+ const attrs = attributes;
1697
+ if (!attrs || !attrs.awipsid) return { type: `XX`, prefix: `XX` };
1698
+ for (const [prefix, type] of Object.entries(definitions.awips)) {
1699
+ if (attrs.awipsid.startsWith(prefix)) {
1700
+ return { type, prefix };
1701
+ }
1702
+ }
1703
+ return { type: `XX`, prefix: `XX` };
1704
+ }
1705
+ /**
1706
+ * cache stores the compiled alert data into a cache file if caching is enabled in the settings.
1707
+ *
1708
+ * @private
1709
+ * @static
1710
+ * @param {unknown} compiled
1711
+ */
1712
+ static cache(compiled) {
1713
+ const data = compiled;
1714
+ const settings2 = settings;
1715
+ if (!settings2.NoaaWeatherWireService.cache.directory) return;
1716
+ if (!packages.fs.existsSync(settings2.NoaaWeatherWireService.cache.directory)) {
1717
+ packages.fs.mkdirSync(settings2.NoaaWeatherWireService.cache.directory, { recursive: true });
1718
+ }
1719
+ data.message = data.message.replace(/\$\$/g, `
1720
+ STANZA ATTRIBUTES...${JSON.stringify(data.attributes)}
1721
+ ISSUED TIME...${(/* @__PURE__ */ new Date()).toISOString()}
1722
+ $$$
1723
+ `);
1724
+ if (!data.message.includes(`STANZA ATTRIBUTES...`)) {
1725
+ data.message += `
1726
+ STANZA ATTRIBUTES...${JSON.stringify(data.attributes)}
1727
+ ISSUED TIME...${(/* @__PURE__ */ new Date()).toISOString()}
1728
+ $$
1729
+ `;
1730
+ }
1731
+ packages.fs.appendFileSync(`${settings2.NoaaWeatherWireService.cache.directory}/category-${data.awipsPrefix}-${data.awipsType}s-${data.isCap ? `cap` : `raw`}${data.isVtec ? `-vtec` : ``}.bin`, `=================================================
1732
+ ${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}
1733
+ =================================================
1734
+ ${data.message}`, "utf8");
1735
+ packages.fs.appendFileSync(`${settings2.NoaaWeatherWireService.cache.directory}/cache-${data.isCap ? `cap` : `raw`}${data.isVtec ? `-vtec` : ``}.bin`, `=================================================
1736
+ ${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}
1737
+ =================================================
1738
+ ${data.message}`, "utf8");
1739
+ }
1740
+ };
1741
+ var stanza_default = StanzaParser;
1742
+
1743
+ // src/database.ts
1744
+ var Database = class {
1745
+ /**
1746
+ * handleAlertCache stores a unique alert in the SQLite database and ensures the total number of alerts does not exceed 5000.
1747
+ *
1748
+ * @public
1749
+ * @static
1750
+ * @async
1751
+ * @param {*} alert
1752
+ * @returns {*}
1753
+ */
1754
+ static stanzaCacheImport(stanza) {
1755
+ return __async(this, null, function* () {
1756
+ const settings2 = settings;
1757
+ cache.db.prepare(`INSERT OR IGNORE INTO stanzas (stanza) VALUES (?)`).run(stanza);
1758
+ const count = cache.db.prepare(`SELECT COUNT(*) as total FROM stanzas`).get();
1759
+ if (count.total > settings2.NoaaWeatherWireService.cache.maxHistory) {
1760
+ cache.db.prepare(`DELETE FROM stanzas WHERE rowid IN (SELECT rowid FROM stanzas ORDER BY rowid ASC LIMIT ?)`).run(count.total - settings2.NoaaWeatherWireService.cache.maxHistory / 2);
1761
+ }
1762
+ });
1763
+ }
1764
+ /**
1765
+ * loadDatabase initializes the SQLite database and imports shapefile data if the database or table does not exist.
1766
+ *
1767
+ * @public
1768
+ * @static
1769
+ * @async
1770
+ * @returns {Promise<void>}
1771
+ */
1772
+ static loadDatabase() {
1773
+ return __async(this, null, function* () {
1774
+ const settings2 = settings;
1775
+ try {
1776
+ if (!packages.fs.existsSync(settings2.database)) {
1777
+ packages.fs.writeFileSync(settings2.database, "");
1778
+ }
1779
+ cache.db = new packages.sqlite3(settings2.database);
1780
+ const shapfileTable = cache.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='shapefiles'`).get();
1781
+ const stanzaTable = cache.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='stanzas'`).get();
1782
+ if (!stanzaTable) {
1783
+ cache.db.prepare(`CREATE TABLE stanzas (id INTEGER PRIMARY KEY AUTOINCREMENT, stanza TEXT)`).run();
1784
+ }
1785
+ if (!shapfileTable) {
1786
+ cache.db.prepare(`CREATE TABLE shapefiles (id TEXT PRIMARY KEY, location TEXT, geometry TEXT)`).run();
1787
+ console.log(definitions.messages.shapefile_creation);
1788
+ for (const shape of definitions.shapefiles) {
1789
+ const { id, file } = shape;
1790
+ const filepath = packages.path.join(__dirname, `../../shapefiles`, file);
1791
+ const { features } = yield packages.shapefile.read(filepath, filepath);
1792
+ console.log(`Importing ${features.length} entries from ${file}...`);
1793
+ const insertStmt = cache.db.prepare(`INSERT OR REPLACE INTO shapefiles (id, location, geometry)VALUES (?, ?, ?)`);
1794
+ const insertTransaction = cache.db.transaction((entries) => {
1795
+ for (const feature of entries) {
1796
+ const { properties, geometry } = feature;
1797
+ let final, location;
1798
+ switch (true) {
1799
+ case !!properties.FIPS:
1800
+ final = `${properties.STATE}${id}${properties.FIPS.substring(2)}`;
1801
+ location = `${properties.COUNTYNAME}, ${properties.STATE}`;
1802
+ break;
1803
+ case !!properties.FULLSTAID:
1804
+ final = `${properties.ST}${id}${properties.WFO}`;
1805
+ location = `${properties.CITY}, ${properties.STATE}`;
1806
+ break;
1807
+ case !!properties.STATE:
1808
+ final = `${properties.STATE}${id}${properties.ZONE}`;
1809
+ location = `${properties.NAME}, ${properties.STATE}`;
1810
+ break;
1811
+ default:
1812
+ final = properties.ID;
1813
+ location = properties.NAME;
1814
+ break;
1815
+ }
1816
+ insertStmt.run(final, location, JSON.stringify(geometry));
1817
+ }
1818
+ });
1819
+ yield insertTransaction(features);
1820
+ }
1821
+ console.log(definitions.messages.shapefile_creation_finished);
1822
+ }
1823
+ } catch (error) {
1824
+ cache.events.emit("onError", { code: "error-load-database", message: `Failed to load database: ${error.message}` });
1825
+ }
1826
+ });
1827
+ }
1828
+ };
1829
+ var database_default = Database;
1830
+
1831
+ // src/xmpp.ts
1832
+ var Xmpp = class {
1833
+ /**
1834
+ * isSessionReconnectionEligible checks if the XMPP session is eligible for reconnection based on the last
1835
+ * received stanza time and current interval.
1836
+ *
1837
+ * @public
1838
+ * @static
1839
+ * @async
1840
+ * @param {number} currentInterval
1841
+ * @returns {Promise<void>}
1842
+ */
1843
+ static isSessionReconnectionEligible(currentInterval) {
1844
+ return __async(this, null, function* () {
1845
+ const settings2 = settings;
1846
+ if ((cache.isConnected || cache.sigHalt) && cache.session) {
1847
+ const lastStanza = Date.now() - cache.lastStanza;
1848
+ if (lastStanza >= currentInterval * 1e3) {
1849
+ if (!cache.attemptingReconnect) {
1850
+ cache.attemptingReconnect = true;
1851
+ cache.isConnected = false;
1852
+ cache.totalReconnects += 1;
1853
+ cache.events.emit(`onReconnect`, { reconnects: cache.totalReconnects, lastStanza, lastName: settings2.NoaaWeatherWireService.clientCredentials.nickname });
1854
+ yield cache.session.stop().catch(() => {
1855
+ });
1856
+ yield cache.session.start().catch(() => {
1857
+ });
1858
+ }
1859
+ }
1860
+ }
1861
+ });
1862
+ }
1863
+ /**
1864
+ * deploySession initializes and starts the XMPP client session, setting up event listeners for
1865
+ * connection management and message handling. This function is specifically tailored for
1866
+ * NoaaWeatherWireService and connects to their XMPP server.
1867
+ *
1868
+ * @public
1869
+ * @static
1870
+ * @async
1871
+ * @returns {Promise<void>}
1872
+ */
1873
+ static deploySession() {
1874
+ return __async(this, null, function* () {
1875
+ var _a, _b;
1876
+ const settings2 = settings;
1877
+ cache.session = packages.xmpp.client({
1878
+ service: `xmpp://nwws-oi.weather.gov`,
1879
+ domain: `nwws-oi.weather.gov`,
1880
+ username: settings2.NoaaWeatherWireService.clientCredentials.username,
1881
+ password: settings2.NoaaWeatherWireService.clientCredentials.password
1882
+ });
1883
+ (_b = (_a = settings2.NoaaWeatherWireService.clientCredentials).nickname) != null ? _b : _a.nickname = settings2.NoaaWeatherWireService.clientCredentials.username;
1884
+ cache.session.on(`online`, (address) => __async(null, null, function* () {
1885
+ if (cache.lastConnect && Date.now() - cache.lastConnect < 10 * 1e3) {
1886
+ cache.sigHalt = true;
1887
+ utils_default.sleep(2 * 1e3).then(() => __async(null, null, function* () {
1888
+ yield cache.session.stop();
1889
+ }));
1890
+ cache.events.emit(`onError`, { code: `error-reconnecting-too-fast`, message: `The client is attempting to reconnect too fast. Please wait a few seconds before trying again.` });
1891
+ return;
1892
+ }
1893
+ cache.isConnected = true;
1894
+ cache.sigHalt = false;
1895
+ cache.lastConnect = Date.now();
1896
+ cache.session.send(packages.xmpp.xml("presence", { to: `nwws@conference.nwws-oi.weather.gov/${settings2.NoaaWeatherWireService.clientCredentials.nickname}`, xmlns: "http://jabber.org/protocol/muc" }));
1897
+ cache.session.send(packages.xmpp.xml("presence", { to: `nwws@conference.nwws-oi.weather.gov`, type: "available" }));
1898
+ cache.events.emit(`onConnection`, settings2.NoaaWeatherWireService.clientCredentials.nickname);
1899
+ if (cache.attemptingReconnect) {
1900
+ utils_default.sleep(15 * 1e3).then(() => {
1901
+ cache.attemptingReconnect = false;
1902
+ });
1903
+ }
1904
+ }));
1905
+ cache.session.on(`offline`, () => __async(null, null, function* () {
1906
+ cache.isConnected = false;
1907
+ cache.sigHalt = true;
1908
+ cache.events.emit(`onError`, { code: `connection-lost`, message: `XMPP connection went offline` });
1909
+ }));
1910
+ cache.session.on(`error`, (error) => __async(null, null, function* () {
1911
+ cache.isConnected = false;
1912
+ cache.sigHalt = true;
1913
+ cache.events.emit(`onError`, { code: `connection-error`, message: error.message });
1914
+ }));
1915
+ cache.session.on(`stanza`, (stanza) => __async(null, null, function* () {
1916
+ try {
1917
+ cache.lastStanza = Date.now();
1918
+ if (stanza.is(`message`)) {
1919
+ const validate = stanza_default.validate(stanza);
1920
+ if (validate.ignore || validate.isCap && !settings2.NoaaWeatherWireService.alertPreferences.isCapOnly || !validate.isCap && settings2.NoaaWeatherWireService.alertPreferences.isCapOnly || validate.isCap && !validate.isCapDescription) return;
1921
+ events_default.eventHandler(validate);
1922
+ cache.events.emit(`onMessage`, validate);
1923
+ database_default.stanzaCacheImport(JSON.stringify(validate));
1924
+ }
1925
+ if (stanza.is(`presence`) && stanza.attrs.from && stanza.attrs.from.startsWith("nwws@conference.nwws-oi.weather.gov/")) {
1926
+ const occupant = stanza.attrs.from.split("/").slice(1).join("/");
1927
+ cache.events.emit("onOccupant", { occupant, type: stanza.attrs.type === "unavailable" ? "unavailable" : "available" });
1928
+ }
1929
+ } catch (e) {
1930
+ cache.events.emit(`onError`, { code: `error-processing-stanza`, message: e.message });
1931
+ }
1932
+ }));
1933
+ yield cache.session.start();
1934
+ });
1935
+ }
1936
+ };
1937
+ var xmpp_default = Xmpp;
1938
+
1939
+ // src/utils.ts
1940
+ var Utils = class {
1941
+ /**
1942
+ * Zzzzzzz... yeah not much to explain here. Simple sleep function that returns a promise after the specified milliseconds.
1943
+ *
1944
+ * @public
1945
+ * @static
1946
+ * @async
1947
+ * @param {number} ms
1948
+ * @returns {Promise<void>}
1949
+ */
1950
+ static sleep(ms) {
1951
+ return __async(this, null, function* () {
1952
+ return new Promise((resolve) => setTimeout(resolve, ms));
1953
+ });
1954
+ }
1955
+ /**
1956
+ * loadCollectionCache reads cached alert files from the specified cache directory and processes them.
1957
+ *
1958
+ * @public
1959
+ * @static
1960
+ * @async
1961
+ * @returns {Promise<void>}
1962
+ */
1963
+ static loadCollectionCache() {
1964
+ return __async(this, null, function* () {
1965
+ try {
1966
+ const settings2 = settings;
1967
+ if (settings2.NoaaWeatherWireService.cache.read && settings2.NoaaWeatherWireService.cache.directory) {
1968
+ if (!packages.fs.existsSync(settings2.NoaaWeatherWireService.cache.directory)) return;
1969
+ const cacheDir = settings2.NoaaWeatherWireService.cache.directory;
1970
+ const getAllFiles = packages.fs.readdirSync(cacheDir).filter((file) => file.endsWith(".bin") && file.startsWith("cache-"));
1971
+ for (const file of getAllFiles) {
1972
+ const start = Date.now();
1973
+ const filepath = packages.path.join(cacheDir, file);
1974
+ const readFile = packages.fs.readFileSync(filepath, { encoding: "utf-8" });
1975
+ const isCap = readFile.includes(`<?xml`);
1976
+ if (isCap && !settings2.NoaaWeatherWireService.alertPreferences.isCapOnly) continue;
1977
+ if (!isCap && settings2.NoaaWeatherWireService.alertPreferences.isCapOnly) continue;
1978
+ const validate = stanza_default.validate(readFile, { awipsid: file, isCap, raw: true, issue: void 0 });
1979
+ yield events_default.eventHandler(validate);
1980
+ }
1981
+ }
1982
+ } catch (error) {
1983
+ cache.events.emit("onError", { code: "error-load-cache", message: `Failed to load cache: ${error.message}` });
1984
+ }
1985
+ });
1986
+ }
1987
+ /**
1988
+ * loadGeoJsonData fetches GeoJSON data from the National Weather Service endpoint and processes each alert.
1989
+ *
1990
+ * @public
1991
+ * @static
1992
+ * @async
1993
+ * @returns {Promise<void>}
1994
+ */
1995
+ static loadGeoJsonData() {
1996
+ return __async(this, null, function* () {
1997
+ try {
1998
+ const settings2 = settings;
1999
+ const response = yield this.createHttpRequest(settings2.NationalWeatherService.endpoint);
2000
+ if (!response.error) {
2001
+ events_default.eventHandler({ message: JSON.stringify(response.message), attributes: {}, isCap: true, isApi: true, isVtec: false, isUGC: false, isCapDescription: false, awipsType: { type: "api", prefix: "AP" }, ignore: false });
2002
+ }
2003
+ } catch (error) {
2004
+ cache.events.emit("onError", { code: "error-fetching-nws-data", message: `Failed to fetch NWS data: ${error.message}` });
2005
+ }
2006
+ });
2007
+ }
2008
+ /**
2009
+ * detectUncaughtExceptions sets up a global handler for uncaught exceptions in the Node.js process,
2010
+ *
2011
+ * @public
2012
+ * @static
2013
+ */
2014
+ static detectUncaughtExceptions() {
2015
+ if (process.listeners("uncaughtException").some((l) => l.name === "uncaughtExceptionHandler")) return;
2016
+ process.on(`uncaughtException`, (error) => {
2017
+ cache.events.emit(`onError`, { message: `Uncaught Exception: ${error.message}`, code: `error-uncaught-exception`, stack: error.stack });
2018
+ });
2019
+ }
2020
+ /**
2021
+ * createHttpRequest performs an HTTP GET request to the specified URL with optional settings.
2022
+ *
2023
+ * @public
2024
+ * @static
2025
+ * @async
2026
+ * @param {string} url
2027
+ * @param {?types.HTTPSettings} [options]
2028
+ * @returns {unknown}
2029
+ */
2030
+ static createHttpRequest(url, options) {
2031
+ return __async(this, null, function* () {
2032
+ var _a, _b;
2033
+ const defaultOptions = {
2034
+ timeout: 1e4,
2035
+ headers: {
2036
+ "User-Agent": "AtmosphericX",
2037
+ "Accept": "application/geo+json, text/plain, */*; q=0.9",
2038
+ "Accept-Language": "en-US,en;q=0.9"
2039
+ }
2040
+ };
2041
+ const requestOptions = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), options), {
2042
+ headers: __spreadValues(__spreadValues({}, defaultOptions.headers), (_a = options == null ? void 0 : options.headers) != null ? _a : {})
2043
+ });
2044
+ try {
2045
+ const resp = yield packages.axios.get(url, {
2046
+ headers: requestOptions.headers,
2047
+ timeout: requestOptions.timeout,
2048
+ maxRedirects: 0,
2049
+ validateStatus: (status) => status === 200 || status === 500
2050
+ });
2051
+ return { error: false, message: resp.data };
2052
+ } catch (err) {
2053
+ return { error: true, message: (_b = err == null ? void 0 : err.message) != null ? _b : String(err) };
2054
+ }
2055
+ });
2056
+ }
2057
+ /**
2058
+ * garbageCollectionCache removes files from the cache directory that exceed the specified maximum file size in megabytes.
2059
+ *
2060
+ * @public
2061
+ * @static
2062
+ * @param {number} maxFileMegabytes
2063
+ */
2064
+ static garbageCollectionCache(maxFileMegabytes) {
2065
+ try {
2066
+ const settings2 = settings;
2067
+ if (!settings2.NoaaWeatherWireService.cache.directory) return;
2068
+ if (!packages.fs.existsSync(settings2.NoaaWeatherWireService.cache.directory)) return;
2069
+ const maxBytes = maxFileMegabytes * 1024 * 1024;
2070
+ const cacheDirectory = settings2.NoaaWeatherWireService.cache.directory;
2071
+ const stackFiles = [cacheDirectory], files = [];
2072
+ while (stackFiles.length) {
2073
+ const currentDirectory = stackFiles.pop();
2074
+ packages.fs.readdirSync(currentDirectory).forEach((file) => {
2075
+ const fullPath = packages.path.join(currentDirectory, file);
2076
+ const stat = packages.fs.statSync(fullPath);
2077
+ if (stat.isDirectory()) stackFiles.push(fullPath);
2078
+ else files.push({ file: fullPath, size: stat.size });
2079
+ });
2080
+ }
2081
+ if (!files.length) return;
2082
+ files.forEach((f) => {
2083
+ if (f.size > maxBytes) packages.fs.unlinkSync(f.file);
2084
+ });
2085
+ } catch (error) {
2086
+ cache.events.emit("onError", { code: "error-garbage-collection", message: `Failed to perform garbage collection: ${error.message}` });
2087
+ }
2088
+ }
2089
+ /**
2090
+ * handleCronJob performs periodic tasks based on whether the client is connected to NWWS or fetching data from NWS.
2091
+ *
2092
+ * @public
2093
+ * @static
2094
+ * @param {boolean} isNwws
2095
+ */
2096
+ static handleCronJob(isNwws) {
2097
+ try {
2098
+ const settings2 = settings;
2099
+ if (isNwws) {
2100
+ if (settings2.NoaaWeatherWireService.cache.read) void this.garbageCollectionCache(settings2.NoaaWeatherWireService.cache.maxSizeMB);
2101
+ if (settings2.NoaaWeatherWireService.clientReconnections.canReconnect) void xmpp_default.isSessionReconnectionEligible(settings2.NoaaWeatherWireService.clientReconnections.currentInterval);
2102
+ } else {
2103
+ void this.loadGeoJsonData();
2104
+ }
2105
+ } catch (error) {
2106
+ cache.events.emit("onError", { code: "error-cron-job", message: `Failed to perform scheduled tasks: ${error.message}` });
2107
+ }
2108
+ }
2109
+ /**
2110
+ * mergeClientSettings merges user-provided settings into the existing client settings, allowing for nested objects to be merged correctly.
2111
+ *
2112
+ * @public
2113
+ * @static
2114
+ * @param {Record<string, any>} target
2115
+ * @param {Record<string, any>} settings
2116
+ */
2117
+ static mergeClientSettings(target, settings2) {
2118
+ for (const key in settings2) {
2119
+ if (settings2.hasOwnProperty(key)) {
2120
+ if (typeof settings2[key] === "object" && settings2[key] !== null && !Array.isArray(settings2[key])) {
2121
+ if (!target[key] || typeof target[key] !== "object") {
2122
+ target[key] = {};
2123
+ }
2124
+ this.mergeClientSettings(target[key], settings2[key]);
2125
+ } else {
2126
+ target[key] = settings2[key];
2127
+ }
2128
+ }
2129
+ }
2130
+ }
2131
+ };
2132
+ var utils_default = Utils;
2133
+
2134
+ // src/eas.ts
2135
+ var EAS = class {
2136
+ /**
2137
+ * generateEASAudio creates an EAS-compliant audio file in WAV format containing the provided message and VTEC header.
2138
+ *
2139
+ * @public
2140
+ * @static
2141
+ * @param {string} message
2142
+ * @param {string} vtec
2143
+ * @returns {*}
2144
+ */
2145
+ static generateEASAudio(message, vtec) {
2146
+ return new Promise((resolve) => __async(this, null, function* () {
2147
+ const settings2 = settings;
2148
+ for (const { regex, replacement } of definitions.messageSignatures) {
2149
+ message = message.replace(regex, replacement);
2150
+ }
2151
+ const assetsDir = settings2.global.easSettings.easDirectory;
2152
+ if (!assetsDir) {
2153
+ console.warn(definitions.messages.eas_no_directory);
2154
+ return resolve(null);
2155
+ }
2156
+ const rngFile = `${vtec.replace(/[^a-zA-Z0-9]/g, `_`)}`.substring(0, 32).replace(/^_+|_+$/g, "");
2157
+ if (!packages.fs.existsSync(assetsDir)) {
2158
+ packages.fs.mkdirSync(assetsDir);
2159
+ }
2160
+ const tmpTTS = packages.path.join(assetsDir, `/tmp/${rngFile}.wav`);
2161
+ const outTTS = packages.path.join(assetsDir, `/output/${rngFile}.wav`);
2162
+ const voice = process.platform === "win32" ? "Microsoft David Desktop" : "en-US-GuyNeural";
2163
+ if (!packages.fs.existsSync(packages.path.join(assetsDir, `/tmp`))) {
2164
+ packages.fs.mkdirSync(packages.path.join(assetsDir, `/tmp`), { recursive: true });
2165
+ }
2166
+ if (!packages.fs.existsSync(packages.path.join(assetsDir, `/output`))) {
2167
+ packages.fs.mkdirSync(packages.path.join(assetsDir, `/output`), { recursive: true });
2168
+ }
2169
+ packages.say.export(message, voice, 1, tmpTTS);
2170
+ yield utils_default.sleep(2500);
2171
+ let ttsBuffer = null;
2172
+ while (!packages.fs.existsSync(tmpTTS) || (ttsBuffer = packages.fs.readFileSync(tmpTTS)).length === 0) {
2173
+ yield utils_default.sleep(500);
2174
+ }
2175
+ const ttsWav = this.parseWavPCM16(ttsBuffer);
2176
+ const ttsSamples = this.resamplePCM16(ttsWav.samples, ttsWav.sampleRate, 8e3);
2177
+ const ttsRadio = this.applyNWREffect(ttsSamples, 8e3);
2178
+ let toneRadio = null;
2179
+ if (packages.fs.existsSync(settings2.global.easSettings.easIntroWav)) {
2180
+ const toneBuffer = packages.fs.readFileSync(settings2.global.easSettings.easIntroWav);
2181
+ const toneWav = this.parseWavPCM16(toneBuffer);
2182
+ const toneSamples = toneWav.sampleRate !== 8e3 ? this.resamplePCM16(toneWav.samples, toneWav.sampleRate, 8e3) : toneWav.samples;
2183
+ toneRadio = this.applyNWREffect(toneSamples, 8e3);
2184
+ }
2185
+ let build = toneRadio != null ? [toneRadio, this.generateSilence(0.5, 8e3)] : [];
2186
+ build.push(this.generateSAMEHeader(vtec, 3, 8e3, { preMarkSec: 1.1, gapSec: 0.5 }), this.generateSilence(0.5, 8e3), this.generateAttentionTone(8, 8e3), this.generateSilence(0.5, 8e3), ttsRadio);
2187
+ for (let i = 0; i < 3; i++) {
2188
+ build.push(this.generateSAMEHeader(vtec, 1, 8e3, { preMarkSec: 0.5, gapSec: 0.1 }));
2189
+ build.push(this.generateSilence(0.5, 8e3));
2190
+ }
2191
+ const allSamples = this.concatPCM16(build);
2192
+ const finalSamples = this.addNoise(allSamples, 2e-3);
2193
+ const outBuffer = this.encodeWavPCM16(Array.from(finalSamples).map((v) => ({ value: v })), 8e3);
2194
+ packages.fs.writeFileSync(outTTS, outBuffer);
2195
+ try {
2196
+ packages.fs.unlinkSync(tmpTTS);
2197
+ } catch (error) {
2198
+ if (error.code !== "EBUSY") {
2199
+ throw error;
2200
+ }
2201
+ }
2202
+ return Promise.resolve(outTTS);
2203
+ }));
2204
+ }
2205
+ /**
2206
+ * encodeWavPCM16 encodes an array of samples into a WAV PCM 16-bit Buffer.
2207
+ *
2208
+ * @private
2209
+ * @static
2210
+ * @param {Record<string, number>[]} samples
2211
+ * @param {number} [sampleRate=8000]
2212
+ * @returns {Buffer}
2213
+ */
2214
+ static encodeWavPCM16(samples, sampleRate = 8e3) {
2215
+ const bytesPerSample = 2;
2216
+ const blockAlign = 1 * bytesPerSample;
2217
+ const byteRate = sampleRate * blockAlign;
2218
+ const subchunk2Size = samples.length * bytesPerSample;
2219
+ const chunkSize = 36 + subchunk2Size;
2220
+ const buffer = Buffer.alloc(44 + subchunk2Size);
2221
+ let o = 0;
2222
+ buffer.write("RIFF", o);
2223
+ o += 4;
2224
+ buffer.writeUInt32LE(chunkSize, o);
2225
+ o += 4;
2226
+ buffer.write("WAVE", o);
2227
+ o += 4;
2228
+ buffer.write("fmt ", o);
2229
+ o += 4;
2230
+ buffer.writeUInt32LE(16, o);
2231
+ o += 4;
2232
+ buffer.writeUInt16LE(1, o);
2233
+ o += 2;
2234
+ buffer.writeUInt16LE(1, o);
2235
+ o += 2;
2236
+ buffer.writeUInt32LE(sampleRate, o);
2237
+ o += 4;
2238
+ buffer.writeUInt32LE(byteRate, o);
2239
+ o += 4;
2240
+ buffer.writeUInt16LE(blockAlign, o);
2241
+ o += 2;
2242
+ buffer.writeUInt16LE(16, o);
2243
+ o += 2;
2244
+ buffer.write("data", o);
2245
+ o += 4;
2246
+ buffer.writeUInt32LE(subchunk2Size, o);
2247
+ o += 4;
2248
+ for (let i = 0; i < samples.length; i++, o += 2) {
2249
+ buffer.writeInt16LE(samples[i].value, o);
2250
+ }
2251
+ return buffer;
2252
+ }
2253
+ /**
2254
+ * parseWavPCM16 decodes a WAV PCM 16-bit Buffer into its sample data and format information.
2255
+ *
2256
+ * @private
2257
+ * @static
2258
+ * @param {Buffer} buffer
2259
+ * @returns {{ samples: any; sampleRate: any; channels: any; bitsPerSample: any; }}
2260
+ */
2261
+ static parseWavPCM16(buffer) {
2262
+ if (buffer.toString("ascii", 0, 4) !== "RIFF" || buffer.toString("ascii", 8, 12) !== "WAVE") {
2263
+ return null;
2264
+ }
2265
+ let fmt = null;
2266
+ let data = null;
2267
+ let i = 12;
2268
+ while (i + 8 <= buffer.length) {
2269
+ const id = buffer.toString("ascii", i, i + 4);
2270
+ const size = buffer.readUInt32LE(i + 4);
2271
+ const start = i + 8;
2272
+ const end = start + size;
2273
+ if (id === "fmt ") fmt = buffer.slice(start, end);
2274
+ if (id === "data") data = buffer.slice(start, end);
2275
+ i = end + size % 2;
2276
+ }
2277
+ if (!fmt || !data) return null;
2278
+ const audioFormat = fmt.readUInt16LE(0);
2279
+ const channels = fmt.readUInt16LE(2);
2280
+ const sampleRate = fmt.readUInt32LE(4);
2281
+ const bitsPerSample = fmt.readUInt16LE(14);
2282
+ if (audioFormat !== 1 || bitsPerSample !== 16 || channels !== 1) {
2283
+ return null;
2284
+ }
2285
+ const samples = new Int16Array(data.buffer, data.byteOffset, data.length / 2);
2286
+ return { samples: new Int16Array(samples), sampleRate, channels, bitsPerSample };
2287
+ }
2288
+ /**
2289
+ * concatPCM16 concatenates multiple Int16Array buffers into a single Int16Array buffer.
2290
+ *
2291
+ * @private
2292
+ * @static
2293
+ * @param {Int16Array[]} arrays
2294
+ * @returns {*}
2295
+ */
2296
+ static concatPCM16(arrays) {
2297
+ let total = 0;
2298
+ for (const a of arrays) total += a.length;
2299
+ const out = new Int16Array(total);
2300
+ let o = 0;
2301
+ for (const a of arrays) {
2302
+ out.set(a, o);
2303
+ o += a.length;
2304
+ }
2305
+ return out;
2306
+ }
2307
+ /**
2308
+ * pcm16toFloat converts an Int16Array of PCM 16-bit samples to a Float32Array of normalized float samples.
2309
+ *
2310
+ * @private
2311
+ * @static
2312
+ * @param {Int16Array} int16
2313
+ * @returns {*}
2314
+ */
2315
+ static pcm16toFloat(int16) {
2316
+ const out = new Float32Array(int16.length);
2317
+ for (let i = 0; i < int16.length; i++) out[i] = int16[i] / 32768;
2318
+ return out;
2319
+ }
2320
+ /**
2321
+ * floatToPcm16 converts a Float32Array of normalized float samples to an Int16Array of PCM 16-bit samples.
2322
+ *
2323
+ * @private
2324
+ * @static
2325
+ * @param {Float32Array} float32
2326
+ * @returns {*}
2327
+ */
2328
+ static floatToPcm16(float32) {
2329
+ const out = new Int16Array(float32.length);
2330
+ for (let i = 0; i < float32.length; i++) {
2331
+ let v = Math.max(-1, Math.min(1, float32[i]));
2332
+ out[i] = Math.round(v * 32767);
2333
+ }
2334
+ return out;
2335
+ }
2336
+ /**
2337
+ * resamplePCM16 resamples an Int16Array of PCM 16-bit samples from the original sample rate to the target sample rate using linear interpolation.
2338
+ *
2339
+ * @private
2340
+ * @static
2341
+ * @param {Int16Array} int16
2342
+ * @param {number} originalRate
2343
+ * @param {number} targetRate
2344
+ * @returns {*}
2345
+ */
2346
+ static resamplePCM16(int16, originalRate, targetRate) {
2347
+ if (originalRate === targetRate) return int16;
2348
+ const ratio = targetRate / originalRate;
2349
+ const outLen = Math.max(1, Math.round(int16.length * ratio));
2350
+ const out = new Int16Array(outLen);
2351
+ for (let i = 0; i < outLen; i++) {
2352
+ const pos = i / ratio;
2353
+ const i0 = Math.floor(pos);
2354
+ const i1 = Math.min(i0 + 1, int16.length - 1);
2355
+ const frac = pos - i0;
2356
+ const v = int16[i0] * (1 - frac) + int16[i1] * frac;
2357
+ out[i] = Math.round(v);
2358
+ }
2359
+ return out;
2360
+ }
2361
+ /**
2362
+ * generateSilence creates an Int16Array of PCM 16-bit samples representing silence for the specified duration in milliseconds.
2363
+ *
2364
+ * @private
2365
+ * @static
2366
+ * @param {number} ms
2367
+ * @param {number} [sampleRate=8000]
2368
+ * @returns {*}
2369
+ */
2370
+ static generateSilence(ms, sampleRate = 8e3) {
2371
+ return new Int16Array(Math.floor(ms * sampleRate));
2372
+ }
2373
+ /**
2374
+ * generateAttentionTone creates an Int16Array of PCM 16-bit samples representing the EAS attention tone for the specified duration in milliseconds.
2375
+ *
2376
+ * @private
2377
+ * @static
2378
+ * @param {*} ms
2379
+ * @param {number} [sampleRate=8000]
2380
+ * @returns {*}
2381
+ */
2382
+ static generateAttentionTone(ms, sampleRate = 8e3) {
2383
+ const len = Math.floor(ms * sampleRate);
2384
+ const out = new Int16Array(len);
2385
+ const f1 = 853;
2386
+ const f2 = 960;
2387
+ const twoPi = Math.PI * 2;
2388
+ const amp = 0.1;
2389
+ const fadeLen = Math.floor(sampleRate * 0);
2390
+ for (let i = 0; i < len; i++) {
2391
+ const t = i / sampleRate;
2392
+ const s = Math.sin(twoPi * f1 * t) + Math.sin(twoPi * f2 * t);
2393
+ let gain = 1;
2394
+ if (i < fadeLen) gain = i / fadeLen;
2395
+ else if (i > len - fadeLen) gain = (len - i) / fadeLen;
2396
+ const v = Math.max(-1, Math.min(1, s / 2 * amp * gain));
2397
+ out[i] = Math.round(v * 32767);
2398
+ }
2399
+ return out;
2400
+ }
2401
+ /**
2402
+ * applyNWREffect applies a series of audio processing effects to simulate the sound characteristics of NOAA Weather Radio broadcasts.
2403
+ *
2404
+ * @private
2405
+ * @static
2406
+ * @param {Int16Array} int16
2407
+ * @param {number} [sampleRate=8000]
2408
+ * @returns {*}
2409
+ */
2410
+ static applyNWREffect(int16, sampleRate = 8e3) {
2411
+ const hpCut = 3555;
2412
+ const lpCut = 1600;
2413
+ const noiseLevel = 0;
2414
+ const crushBits = 8;
2415
+ const x = this.pcm16toFloat(int16);
2416
+ const dt = 1 / sampleRate;
2417
+ const rcHP = 1 / (2 * Math.PI * hpCut);
2418
+ const aHP = rcHP / (rcHP + dt);
2419
+ let yHP = 0, xPrev = 0;
2420
+ for (let i = 0; i < x.length; i++) {
2421
+ const xi = x[i];
2422
+ yHP = aHP * (yHP + xi - xPrev);
2423
+ xPrev = xi;
2424
+ x[i] = yHP;
2425
+ }
2426
+ const rcLP = 1 / (2 * Math.PI * lpCut);
2427
+ const aLP = dt / (rcLP + dt);
2428
+ let yLP = 0;
2429
+ for (let i = 0; i < x.length; i++) {
2430
+ yLP = yLP + aLP * (x[i] - yLP);
2431
+ x[i] = yLP;
2432
+ }
2433
+ const compGain = 2;
2434
+ const norm = Math.tanh(compGain);
2435
+ for (let i = 0; i < x.length; i++) x[i] = Math.tanh(x[i] * compGain) / norm;
2436
+ const levels = Math.pow(2, crushBits) - 1;
2437
+ return this.floatToPcm16(x);
2438
+ }
2439
+ /**
2440
+ * addNoise adds low-level white noise to an Int16Array of PCM 16-bit samples to simulate analog broadcast imperfections.
2441
+ *
2442
+ * @private
2443
+ * @static
2444
+ * @param {Int16Array} int16
2445
+ * @param {number} [noiseLevel=0.02]
2446
+ * @returns {*}
2447
+ */
2448
+ static addNoise(int16, noiseLevel = 0.02) {
2449
+ const x = this.pcm16toFloat(int16);
2450
+ for (let i = 0; i < x.length; i++) x[i] += (Math.random() * 2 - 1) * noiseLevel;
2451
+ let peak = 0;
2452
+ for (let i = 0; i < x.length; i++) peak = Math.max(peak, Math.abs(x[i]));
2453
+ if (peak > 1) for (let i = 0; i < x.length; i++) x[i] *= 0.98 / peak;
2454
+ return this.floatToPcm16(x);
2455
+ }
2456
+ /**
2457
+ * asciiTo8N1Bits converts an ASCII string to a sequence of bits using 8-N-1 encoding (8 data bits, no parity, 1 stop bit).
2458
+ *
2459
+ * @private
2460
+ * @static
2461
+ * @param {string} str
2462
+ * @returns {{}}
2463
+ */
2464
+ static asciiTo8N1Bits(str) {
2465
+ const bits = [];
2466
+ for (let i = 0; i < str.length; i++) {
2467
+ const c = str.charCodeAt(i) & 255;
2468
+ bits.push(0);
2469
+ for (let b = 0; b < 8; b++) bits.push(c >> b & 1);
2470
+ bits.push(1, 1);
2471
+ }
2472
+ return bits;
2473
+ }
2474
+ /**
2475
+ * generateAFSK generates an Int16Array of PCM 16-bit samples representing AFSK modulation of the provided bit sequence.
2476
+ *
2477
+ * @private
2478
+ * @static
2479
+ * @param {number[]} bits
2480
+ * @param {number} [sampleRate=8000]
2481
+ * @returns {*}
2482
+ */
2483
+ static generateAFSK(bits, sampleRate = 8e3) {
2484
+ const baud = 520.83;
2485
+ const markFreq = 2083.3;
2486
+ const spaceFreq = 1562.5;
2487
+ const amplitude = 0.6;
2488
+ const twoPi = Math.PI * 2;
2489
+ const result = [];
2490
+ let phase = 0;
2491
+ let frac = 0;
2492
+ for (let b = 0; b < bits.length; b++) {
2493
+ const bit = bits[b];
2494
+ const freq = bit ? markFreq : spaceFreq;
2495
+ const samplesPerBit = sampleRate / baud + frac;
2496
+ const n = Math.round(samplesPerBit);
2497
+ frac = samplesPerBit - n;
2498
+ const inc = twoPi * freq / sampleRate;
2499
+ for (let i = 0; i < n; i++) {
2500
+ result.push(Math.round(Math.sin(phase) * amplitude * 32767));
2501
+ phase += inc;
2502
+ if (phase > twoPi) phase -= twoPi;
2503
+ }
2504
+ }
2505
+ const fadeSamples = Math.floor(sampleRate * 2e-3);
2506
+ for (let i = 0; i < fadeSamples; i++) {
2507
+ const gain = i / fadeSamples;
2508
+ result[i] = Math.round(result[i] * gain);
2509
+ result[result.length - 1 - i] = Math.round(result[result.length - 1 - i] * gain);
2510
+ }
2511
+ return Int16Array.from(result);
2512
+ }
2513
+ /**
2514
+ * generateSAMEHeader generates an Int16Array of PCM 16-bit samples representing the SAME header repeated the specified number of times.
2515
+ *
2516
+ * @private
2517
+ * @static
2518
+ * @param {string} vtec
2519
+ * @param {number} repeats
2520
+ * @param {number} [sampleRate=8000]
2521
+ * @param {{preMarkSec?: number, gapSec?: number}} [options={}]
2522
+ * @returns {*}
2523
+ */
2524
+ static generateSAMEHeader(vtec, repeats, sampleRate = 8e3, options = {}) {
2525
+ var _a, _b;
2526
+ const preMarkSec = (_a = options.preMarkSec) != null ? _a : 0.3;
2527
+ const gapSec = (_b = options.gapSec) != null ? _b : 0.1;
2528
+ const bursts = [];
2529
+ const gap = this.generateSilence(gapSec, sampleRate);
2530
+ for (let i = 0; i < repeats; i++) {
2531
+ const bodyBits = this.asciiTo8N1Bits(vtec);
2532
+ const body = this.generateAFSK(bodyBits, sampleRate);
2533
+ const extendedBodyDuration = Math.round(preMarkSec * sampleRate);
2534
+ const extendedBody = new Int16Array(extendedBodyDuration + gap.length);
2535
+ for (let j = 0; j < extendedBodyDuration; j++) {
2536
+ extendedBody[j] = Math.round(body[j % body.length] * 0.2);
2537
+ }
2538
+ extendedBody.set(gap, extendedBodyDuration);
2539
+ bursts.push(extendedBody);
2540
+ if (i !== repeats - 1) bursts.push(gap);
2541
+ }
2542
+ return this.concatPCM16(bursts);
2543
+ }
2544
+ };
2545
+ var eas_default = EAS;
2546
+
2547
+ // src/parsers/events.ts
2548
+ var EventParser = class {
2549
+ /**
2550
+ * getBaseProperties extracts and compiles the base properties of an alert message, including location, timing, description, sender information, and various parameters.
2551
+ *
2552
+ * @public
2553
+ * @static
2554
+ * @async
2555
+ * @param {string} message
2556
+ * @param {types.TypeCompiled} validated
2557
+ * @param {types.UGCParsed} [ugc=null]
2558
+ * @param {types.VTECParsed} [vtec=null]
2559
+ * @returns {Promise<types.BaseProperties>}
2560
+ */
2561
+ static getBaseProperties(message, validated, ugc = null, vtec = null) {
2562
+ return __async(this, null, function* () {
2563
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2564
+ const settings2 = settings;
2565
+ const definitions2 = {
2566
+ tornado: text_default.textProductToString(message, `TORNADO...`) || text_default.textProductToString(message, `WATERSPOUT...`) || `N/A`,
2567
+ hail: text_default.textProductToString(message, `MAX HAIL SIZE...`, [`IN`]) || text_default.textProductToString(message, `HAIL...`, [`IN`]) || `N/A`,
2568
+ gusts: text_default.textProductToString(message, `MAX WIND GUST...`) || text_default.textProductToString(message, `WIND...`) || `N/A`,
2569
+ flood: text_default.textProductToString(message, `FLASH FLOOD...`) || `N/A`,
2570
+ damage: text_default.textProductToString(message, `DAMAGE THREAT...`) || `N/A`,
2571
+ source: text_default.textProductToString(message, `SOURCE...`, [`.`]) || `N/A`,
2572
+ attributes: text_default.textProductToString(message, `STANZA ATTRIBUTES...`) ? JSON.parse(text_default.textProductToString(message, `STANZA ATTRIBUTES...`)) : null,
2573
+ polygon: text_default.textProductToPolygon(message),
2574
+ description: text_default.textProductToDescription(message, (_a = vtec == null ? void 0 : vtec.raw) != null ? _a : null),
2575
+ wmo: message.match(new RegExp(definitions.expressions.wmo, "imu")),
2576
+ mdTorIntensity: text_default.textProductToString(message, `MOST PROBABLE PEAK TORNADO INTENSITY...`) || `N/A`,
2577
+ mdWindGusts: text_default.textProductToString(message, `MOST PROBABLE PEAK WIND GUST...`) || `N/A`,
2578
+ mdHailSize: text_default.textProductToString(message, `MOST PROBABLE PEAK HAIL SIZE...`) || `N/A`
2579
+ };
2580
+ const getOffice = this.getICAO(vtec, (_c = (_b = validated.attributes) != null ? _b : definitions2.attributes) != null ? _c : {}, definitions2.wmo);
2581
+ const getCorrectIssued = this.getCorrectIssuedDate((_e = (_d = definitions2.attributes) != null ? _d : validated.attributes) != null ? _e : {});
2582
+ const getCorrectExpiry = this.getCorrectExpiryDate(vtec, ugc);
2583
+ const getAwip = text_default.awipTextToEvent((_g = (_f = definitions2.attributes) == null ? void 0 : _f.awipsid) != null ? _g : validated.awipsType.prefix);
2584
+ const base = {
2585
+ locations: (ugc == null ? void 0 : ugc.locations.join(`; `)) || `No Location Specified (UGC Missing)`,
2586
+ issued: getCorrectIssued,
2587
+ expires: getCorrectExpiry,
2588
+ geocode: { UGC: (ugc == null ? void 0 : ugc.zones) || [`XX000`] },
2589
+ description: definitions2.description,
2590
+ sender_name: getOffice.name,
2591
+ sender_icao: getOffice.icao,
2592
+ attributes: __spreadProps(__spreadValues(__spreadValues({}, validated.attributes), definitions2.attributes), {
2593
+ getAwip
2594
+ }),
2595
+ parameters: {
2596
+ wmo: Array.isArray(definitions2.wmo) ? definitions2.wmo[0] : (_h = definitions2.wmo) != null ? _h : `N/A`,
2597
+ source: definitions2.source,
2598
+ max_hail_size: definitions2.hail,
2599
+ max_wind_gust: definitions2.gusts,
2600
+ damage_threat: definitions2.damage,
2601
+ tornado_detection: definitions2.tornado,
2602
+ flood_detection: definitions2.flood,
2603
+ discussion_tornado_intensity: definitions2.mdTorIntensity,
2604
+ discussion_wind_intensity: definitions2.mdWindGusts,
2605
+ discussion_hail_intensity: definitions2.mdHailSize
2606
+ },
2607
+ geometry: definitions2.polygon.length > 0 ? { type: "Polygon", coordinates: definitions2.polygon } : null
2608
+ };
2609
+ if (settings2.NoaaWeatherWireService.alertPreferences.isShapefileUGC && base.geometry == null && ugc != null) {
2610
+ const coordinates = yield ugc_default.getCoordinates(ugc.zones);
2611
+ base.geometry = { type: "Polygon", coordinates };
2612
+ }
2613
+ return base;
2614
+ });
2615
+ }
2616
+ /**
2617
+ * enhanceEvent refines the event name based on specific conditions and tags found in the event's description and parameters.
2618
+ *
2619
+ * @public
2620
+ * @static
2621
+ * @param {types.TypeAlert} event
2622
+ * @returns {{ eventName: any; tags: any; }}
2623
+ */
2624
+ static enhanceEvent(event) {
2625
+ var _a, _b, _c, _d, _e;
2626
+ let eventName = (_b = (_a = event == null ? void 0 : event.properties) == null ? void 0 : _a.event) != null ? _b : `Unknown Event`;
2627
+ const defEventTable = definitions.enhancedEvents;
2628
+ const defEventTags = definitions.tags;
2629
+ const properties = event == null ? void 0 : event.properties;
2630
+ const parameters = properties == null ? void 0 : properties.parameters;
2631
+ const description = (_c = properties == null ? void 0 : properties.description) != null ? _c : `Unknown Description`;
2632
+ const damageThreatTag = (_d = parameters == null ? void 0 : parameters.damage_threat) != null ? _d : `N/A`;
2633
+ const tornadoThreatTag = (_e = parameters == null ? void 0 : parameters.tornado_detection) != null ? _e : `N/A`;
2634
+ for (const eventGroup of defEventTable) {
2635
+ const [baseEvent, conditions] = Object.entries(eventGroup)[0];
2636
+ if (eventName === baseEvent) {
2637
+ for (const [specificEvent, condition] of Object.entries(conditions)) {
2638
+ const conditionMet = condition.description && description.includes(condition.description.toLowerCase()) || condition.condition && condition.condition(damageThreatTag || tornadoThreatTag);
2639
+ if (conditionMet) {
2640
+ eventName = specificEvent;
2641
+ break;
2642
+ }
2643
+ }
2644
+ if (baseEvent === "Severe Thunderstorm Warning" && damageThreatTag === "POSSIBLE" && !eventName.includes("(TPROB)")) eventName += " (TPROB)";
2645
+ break;
2646
+ }
2647
+ }
2648
+ const tags = Object.entries(defEventTags).filter(([key]) => description.includes(key.toLowerCase())).map(([, value]) => value);
2649
+ return { eventName, tags: tags.length > 0 ? tags : [`N/A`] };
2650
+ }
2651
+ /**
2652
+ * getCorrectExpiryDate determines the correct expiration date for an alert based on VTEC information or UGC zones.
2653
+ *
2654
+ * @public
2655
+ * @static
2656
+ * @param {unknown[]} events
2657
+ */
2658
+ static validateEvents(events2) {
2659
+ var _a, _b, _c, _d, _e;
2660
+ if (events2.length == 0) return;
2661
+ const settings2 = settings;
2662
+ const filteringSettings = (_b = (_a = settings) == null ? void 0 : _a.global) == null ? void 0 : _b.alertFiltering;
2663
+ const easSettings = (_d = (_c = settings) == null ? void 0 : _c.global) == null ? void 0 : _d.easSettings;
2664
+ const globalSettings = (_e = settings) == null ? void 0 : _e.global;
2665
+ const sets = {};
2666
+ const bools = {};
2667
+ const megered = __spreadValues(__spreadValues(__spreadValues({}, filteringSettings), easSettings), globalSettings);
2668
+ for (const key in megered) {
2669
+ const setting = megered[key];
2670
+ if (Array.isArray(setting)) {
2671
+ sets[key] = new Set(setting.map((item) => item.toLowerCase()));
2672
+ }
2673
+ if (typeof setting === "boolean") {
2674
+ bools[key] = setting;
2675
+ }
2676
+ }
2677
+ const filtered = events2.filter((alert) => {
2678
+ var _a2, _b2, _c2, _d2;
2679
+ const originalEvent = alert;
2680
+ const props = originalEvent == null ? void 0 : originalEvent.properties;
2681
+ const ugcs = (_b2 = (_a2 = props == null ? void 0 : props.geocode) == null ? void 0 : _a2.UGC) != null ? _b2 : [];
2682
+ if (bools == null ? void 0 : bools.betterEventParsing) {
2683
+ const { eventName, tags } = this.enhanceEvent(originalEvent);
2684
+ originalEvent.properties.event = eventName;
2685
+ originalEvent.properties.tags = tags;
2686
+ }
2687
+ const eventCheck = (bools == null ? void 0 : bools.useParentEvents) ? (_c2 = props.parent) == null ? void 0 : _c2.toLowerCase() : (_d2 = props.event) == null ? void 0 : _d2.toLowerCase();
2688
+ const statusCorrelation = definitions.correlations.find((c) => c.type === originalEvent.properties.action_type);
2689
+ for (const key in sets) {
2690
+ const setting = sets[key];
2691
+ if (key === "filteredEvents" && setting.size > 0 && eventCheck != null && !setting.has(eventCheck)) return false;
2692
+ if (key === "ignoredEvents" && setting.size > 0 && eventCheck != null && setting.has(eventCheck)) return false;
2693
+ if (key === "filteredICOAs" && setting.size > 0 && props.sender_icao != null && !setting.has(props.sender_icao.toLowerCase())) return false;
2694
+ if (key === "ignoredICOAs" && setting.size > 0 && props.sender_icao != null && setting.has(props.sender_icao.toLowerCase())) return false;
2695
+ if (key === "ugcFilter" && setting.size > 0 && ugcs.length > 0 && !ugcs.some((ugc) => setting.has(ugc.toLowerCase()))) return false;
2696
+ if (key === "stateFilter" && setting.size > 0 && ugcs.length > 0 && !ugcs.some((ugc) => setting.has(ugc.substring(0, 2).toLowerCase()))) return false;
2697
+ if (key === "easAlerts" && setting.size > 0 && eventCheck != null && setting.has(eventCheck) && settings2.isNWWS) {
2698
+ eas_default.generateEASAudio(props.description, alert.header);
2699
+ }
2700
+ }
2701
+ for (const key in bools) {
2702
+ const setting = bools[key];
2703
+ if (key === "checkExpired" && setting && new Date(props == null ? void 0 : props.expires).getTime() < (/* @__PURE__ */ new Date()).getTime()) return false;
2704
+ }
2705
+ originalEvent.properties.action_type = statusCorrelation ? statusCorrelation.forward : originalEvent.properties.action_type;
2706
+ originalEvent.properties.is_cancelled = statusCorrelation ? statusCorrelation.cancel == true && bools.checkExpired : false;
2707
+ if (props.description) {
2708
+ const detectedPhrase = definitions.cancelSignatures.find((sig) => props.description.toLowerCase().includes(sig.toLowerCase()));
2709
+ if (detectedPhrase && bools.checkExpired) {
2710
+ originalEvent.properties.action_type = "Cancel";
2711
+ originalEvent.properties.is_cancelled = true;
2712
+ return false;
2713
+ }
2714
+ }
2715
+ if (originalEvent.vtec) {
2716
+ const getType = originalEvent.vtec.split(`.`)[0];
2717
+ const isTestProduct = definitions.productTypes[getType] == `Test Product`;
2718
+ if (isTestProduct) {
2719
+ return false;
2720
+ }
2721
+ }
2722
+ cache.events.emit(`on${originalEvent.properties.parent.replace(/\s+/g, "")}`);
2723
+ return true;
2724
+ });
2725
+ if (filtered.length > 0) {
2726
+ cache.events.emit(`onAlerts`, filtered);
2727
+ }
2728
+ }
2729
+ /**
2730
+ * getHeader constructs a standardized alert header string based on provided attributes, properties, and VTEC information.
2731
+ *
2732
+ * @public
2733
+ * @static
2734
+ * @param {types.TypeAttributes} attributes
2735
+ * @param {?types.BaseProperties} [properties]
2736
+ * @param {?types.VTECParsed} [vtec]
2737
+ * @returns {string}
2738
+ */
2739
+ static getHeader(attributes, properties, vtec) {
2740
+ var _a, _b, _c, _d, _e, _f, _g;
2741
+ const parent = `ATSX`;
2742
+ const alertType = (_d = (_c = (_a = attributes == null ? void 0 : attributes.awipsType) == null ? void 0 : _a.type) != null ? _c : (_b = attributes == null ? void 0 : attributes.getAwip) == null ? void 0 : _b.prefix) != null ? _d : `XX`;
2743
+ const ugc = ((_e = properties == null ? void 0 : properties.geocode) == null ? void 0 : _e.UGC) != null ? (_f = properties == null ? void 0 : properties.geocode) == null ? void 0 : _f.UGC.join(`-`) : `000000`;
2744
+ const status = (vtec == null ? void 0 : vtec.status) || "Issued";
2745
+ const issued = (properties == null ? void 0 : properties.issued) != null ? (_g = new Date(properties == null ? void 0 : properties.issued)) == null ? void 0 : _g.toISOString().replace(/[-:]/g, "").split(".")[0] : (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").split(".")[0];
2746
+ const sender = (properties == null ? void 0 : properties.sender_icao) || `XXXX`;
2747
+ const header = `ZCZC-${parent}-${alertType}-${ugc}-${status}-${issued}-${sender}-`;
2748
+ return header;
2749
+ }
2750
+ /**
2751
+ * eventHandler routes the validated alert message to the appropriate event parser based on its type (API, CAP, VTEC, UGC, or plain text).
2752
+ *
2753
+ * @public
2754
+ * @static
2755
+ * @param {types.TypeCompiled} validated
2756
+ * @returns {*}
2757
+ */
2758
+ static eventHandler(validated) {
2759
+ if (validated.isApi) return api_default.event(validated);
2760
+ if (validated.isCap) return cap_default.event(validated);
2761
+ if (!validated.isCap && validated.isVtec && validated.isUGC) return vtec_default2.event(validated);
2762
+ if (!validated.isCap && !validated.isVtec && validated.isUGC) return ugc_default2.event(validated);
2763
+ if (!validated.isCap && !validated.isVtec && !validated.isUGC) return text_default2.event(validated);
2764
+ }
2765
+ /**
2766
+ * getICAO retrieves the ICAO code and corresponding office name based on VTEC tracking information, message attributes, or WMO code.
2767
+ *
2768
+ * @private
2769
+ * @static
2770
+ * @param {types.VTECParsed} vtec
2771
+ * @param {Record<string, string>} attributes
2772
+ * @param {(RegExpMatchArray | string | null)} WMO
2773
+ * @returns {{ icao: any; name: any; }}
2774
+ */
2775
+ static getICAO(vtec, attributes, WMO) {
2776
+ var _a, _b, _c;
2777
+ const icao = vtec != null ? vtec == null ? void 0 : vtec.tracking.split(`-`)[0] : (_a = attributes == null ? void 0 : attributes.cccc) != null ? _a : WMO != null ? Array.isArray(WMO) ? WMO[0] : WMO : `N/A`;
2778
+ const name = (_c = (_b = definitions.ICAO) == null ? void 0 : _b[icao]) != null ? _c : `N/A`;
2779
+ return { icao, name };
2780
+ }
2781
+ /**
2782
+ * getCorrectIssuedDate ensures the issued date is valid and falls back to the current date if not.
2783
+ *
2784
+ * @private
2785
+ * @static
2786
+ * @param {Record<string, string>} attributes
2787
+ * @returns {*}
2788
+ */
2789
+ static getCorrectIssuedDate(attributes) {
2790
+ const time = attributes.issue != null ? new Date(attributes.issue).toLocaleString() : (attributes == null ? void 0 : attributes.issue) != null ? new Date(attributes.issue).toLocaleString() : (/* @__PURE__ */ new Date()).toLocaleString();
2791
+ if (time == `Invalid Date`) return (/* @__PURE__ */ new Date()).toLocaleString();
2792
+ return time;
2793
+ }
2794
+ /**
2795
+ * getCorrectExpiryDate determines the correct expiration date for an alert based on VTEC information or UGC zones.
2796
+ *
2797
+ * @private
2798
+ * @static
2799
+ * @param {types.VTECParsed} vtec
2800
+ * @param {types.UGCParsed} ugc
2801
+ * @returns {*}
2802
+ */
2803
+ static getCorrectExpiryDate(vtec, ugc) {
2804
+ const time = (vtec == null ? void 0 : vtec.expires) && !isNaN(new Date(vtec.expires).getTime()) ? new Date(vtec.expires).toLocaleString() : (ugc == null ? void 0 : ugc.expiry) != null ? new Date(ugc.expiry).toLocaleString() : new Date((/* @__PURE__ */ new Date()).getTime() + 1 * 60 * 60 * 1e3).toLocaleString();
2805
+ if (time == `Invalid Date`) return new Date((/* @__PURE__ */ new Date()).getTime() + 1 * 60 * 60 * 1e3).toLocaleString();
2806
+ return time;
2807
+ }
2808
+ };
2809
+ var events_default = EventParser;
2810
+
2811
+ // src/parsers/types/vtec.ts
2812
+ var VTECAlerts = class {
2813
+ /**
2814
+ * event processes validated VTEC alert messages, extracting relevant information and compiling it into structured event objects.
2815
+ *
2816
+ * @public
2817
+ * @static
2818
+ * @async
2819
+ * @param {types.TypeCompiled} validated
2820
+ * @returns {*}
2821
+ */
2822
+ static event(validated) {
2823
+ return __async(this, null, function* () {
2824
+ var _a;
2825
+ let processed = [];
2826
+ const messages = (_a = validated.message.split(/(?=\$\$)/g)) == null ? void 0 : _a.map((msg) => msg.trim());
2827
+ if (!messages || messages.length == 0) return;
2828
+ for (let i = 0; i < messages.length; i++) {
2829
+ const tick = performance.now();
2830
+ const message = messages[i];
2831
+ const getVTEC = yield vtec_default.vtecExtractor(message);
2832
+ const getUGC = yield ugc_default.ugcExtractor(message);
2833
+ if (getVTEC != null && getUGC != null) {
2834
+ for (let j = 0; j < getVTEC.length; j++) {
2835
+ const vtec = getVTEC[j];
2836
+ const getBaseProperties = yield events_default.getBaseProperties(message, validated, getUGC, vtec);
2837
+ const getHeader = events_default.getHeader(__spreadValues(__spreadValues({}, validated.attributes), getBaseProperties.attributes), getBaseProperties, vtec);
2838
+ processed.push({
2839
+ preformance: performance.now() - tick,
2840
+ tracking: vtec.tracking,
2841
+ header: getHeader,
2842
+ vtec: vtec.raw,
2843
+ history: [{ description: getBaseProperties.description, issued: getBaseProperties.issued, type: vtec.status }],
2844
+ properties: __spreadValues({ event: vtec.event, parent: vtec.event, action_type: vtec.status }, getBaseProperties)
2845
+ });
2846
+ }
2847
+ }
2848
+ }
2849
+ events_default.validateEvents(processed);
2850
+ });
2851
+ }
2852
+ };
2853
+ var vtec_default2 = VTECAlerts;
2854
+ // Annotate the CommonJS export names for ESM import in node:
2855
+ 0 && (module.exports = {
2856
+ VTECAlerts
2857
+ });