generated from vvo/javascript-library-template
-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
generate.js
343 lines (282 loc) · 9.21 KB
/
generate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import fs from "fs";
import path from "path";
import { parse as csvParse } from "csv-parse";
// eslint-disable-next-line import/no-unresolved
import { parse as csvParseSync } from "csv-parse/sync";
import unzipper from "unzipper";
import got from "got";
import { DateTime } from "luxon";
import { orderBy, uniq } from "lodash";
import tzdata from "tzdata";
import abbreviations from "./abbreviations.json";
import formatTimeZone from "./lib/formatTimeZone.js";
const timeZonesLinks = Object.entries(tzdata.zones).filter(([, value]) => {
return typeof value === "string";
});
async function run() {
const continents = {
AF: "Africa",
AS: "Asia",
EU: "Europe",
NA: "North America",
OC: "Oceania",
SA: "South America",
AN: "Antarctica",
};
const { body: countriesData } = await got(
"https://download.geonames.org/export/dump/countryInfo.txt",
);
const countriesDataValidCsv = countriesData
.split("EquivalentFipsCode")[1]
.trim();
const countriesParser = csvParseSync(countriesDataValidCsv, {
delimiter: "\t",
skipRecordsWithError: true,
});
const countries = {};
const countriesToContinents = {};
for await (const countryFields of countriesParser) {
countries[countryFields[0]] = countryFields[4];
countriesToContinents[countryFields[0]] = countryFields[8];
}
// prepare deprecated time zone names map, example:
// {
// 'Australia/Sydney': [ 'Australia/ACT', 'Australia/Canberra', 'Australia/NSW' ].
// ...
// }
const { body: deprecatedNamesData } = await got(
"https://data.iana.org/time-zones/data/backward",
);
const deprecatedNames = {};
for (const line of deprecatedNamesData.split("\n")) {
if (line.startsWith("#") || line === "") {
continue;
}
const [, newName, deprecatedName] = line.replace(/\t+/g, ",").split(",");
deprecatedNames[newName] ??= [];
deprecatedNames[newName].push(deprecatedName);
}
const citiesCsv = got
.stream("https://download.geonames.org/export/dump/cities15000.zip")
.pipe(unzipper.ParseOne());
const citiesParser = citiesCsv.pipe(
csvParse({
delimiter: "\t",
skipRecordsWithError: true,
}),
);
const timeZoneCities = {};
for await (const cityFields of citiesParser) {
// http://download.geonames.org/export/dump/readme.txt geoname section has 19 fields
if (cityFields.length > 19) {
console.error(
`Number of fields changed or not accurate for record ${cityFields}`,
);
console.log(cityFields.length);
process.exit(1);
}
// const modificationDate = cityFields[18];
const name = cityFields[1];
const population = parseInt(cityFields[14], 10);
const countryCode = cityFields[8];
const timeZoneName = cityFields[17];
timeZoneCities[countryCode] = timeZoneCities[countryCode] || {};
timeZoneCities[countryCode][timeZoneName] =
timeZoneCities[countryCode][timeZoneName] || [];
timeZoneCities[countryCode][timeZoneName].push({
name,
population,
timeZoneName,
});
}
// Time zones
const timeZonesNames = [];
const timeZonesInfo = {};
const timeZonesParser = got
.stream("http://download.geonames.org/export/dump/timeZones.txt")
.pipe(
csvParse({ delimiter: "\t", from_line: 2, skipRecordsWithError: true }),
);
const countryStats = {};
for await (const timeZoneFields of timeZonesParser) {
const timeZoneName = timeZoneFields[1];
const tz = DateTime.fromObject(
{},
{
zone: timeZoneName,
},
);
if (tz.isValid !== true) {
console.error(
"Time zone data not accurate, please investigate",
tz.invalidReason,
timeZoneName,
);
continue;
}
timeZonesNames.push(timeZoneName);
const countryCode = timeZoneFields[0];
const gmtOffset = timeZoneFields[2];
const dstOffset = timeZoneFields[3];
const rawOffset = timeZoneFields[4];
// there's no "easy way" to get all the raw offset from time zones (when not in DST) because DST times
// are happening at various dates given countries (GOOD JOB GOVERNEMENTS!). Since geonames provides it,
// we save it for later usage
timeZonesInfo[timeZoneName] = {
rawOffset,
};
if (countryStats[countryCode] === undefined) {
countryStats[countryCode] = {};
}
const offsetKey = `${gmtOffset}${dstOffset}${rawOffset}`;
if (countryStats[countryCode][offsetKey] === undefined) {
countryStats[countryCode][offsetKey] = [];
}
if (timeZoneCities?.[countryCode]?.[timeZoneName] !== undefined) {
countryStats[countryCode][offsetKey].push(
...timeZoneCities[countryCode][timeZoneName],
);
} else {
countryStats[countryCode][offsetKey].push({
// we push a default city in case we have no cities present in timeZoneCities
name: timeZoneName.split("/").pop().replace(/_/g, " "),
population: 10000,
timeZoneName,
});
}
}
// Node.js can't seem to get nice alt names for these zones for now
const alternativeNameCorrections = {
"Antarctica/Palmer": "Chile Time",
"America/Punta_Arenas": "Chile Time",
"Africa/Casablanca": "Western European Time",
"Africa/El_Aaiun": "Western European Time",
"Europe/Istanbul": "Turkey Time",
"Asia/Urumqi": "China Time",
"Pacific/Bougainville": "Bougainville Time",
};
const rawTimeZones = [];
for (let [countryCode, countryTimeZones] of Object.entries(countryStats)) {
const continentCode = countriesToContinents[countryCode];
for (let [, timeZoneWithCities] of Object.entries(countryTimeZones)) {
const orderedCities = orderBy(timeZoneWithCities, "population", "desc");
const mainCitiesObject = orderedCities.slice(0, 4);
const mainCities = mainCitiesObject.map(({ name }) => {
return name;
});
const uniqueCitiesTimeZones = uniq(
timeZoneWithCities.map(({ timeZoneName }) => {
return timeZoneName;
}),
);
const deprecatedTimeZonesForGroup = uniqueCitiesTimeZones
.filter((timeZoneName) => {
return deprecatedNames[timeZoneName];
})
.map((timeZoneName) => {
return deprecatedNames[timeZoneName];
})
.flat();
const group = uniq([
...uniqueCitiesTimeZones,
...deprecatedTimeZonesForGroup,
]);
const { timeZoneName } = mainCitiesObject[0];
const januaryDate = DateTime.fromObject(
{
day: 1,
month: 1,
},
{
locale: "en-US",
zone: timeZoneName,
},
);
let alternativeTimeZoneName = januaryDate
.toFormat(`ZZZZZ`)
.replace(/Standard Time/g, "Time")
.replace(/Daylight Time/g, "Time")
.replace(/Summer Time/g, "Time");
// there are some cases where Node.js tz data won't be giving actual alternative names
// for time zones and instead will send GMT +03:00, so we fix that
if (/^GMT[+-]\d{2}:\d{2}$/.test(alternativeTimeZoneName)) {
alternativeTimeZoneName =
alternativeNameCorrections[timeZoneName] || timeZoneName;
}
const rawTimeZone = {
name: timeZoneName,
alternativeName: alternativeTimeZoneName,
group,
continentCode,
continentName: continents[continentCode],
countryName: countries[countryCode],
countryCode,
mainCities,
rawOffsetInMinutes: parseFloat(
timeZonesInfo[timeZoneName].rawOffset * 60,
),
abbreviation: getAbbreviation({
date: januaryDate,
timeZoneName: alternativeTimeZoneName,
}),
};
rawTimeZones.push({
...rawTimeZone,
rawFormat: formatTimeZone(rawTimeZone),
});
}
}
timeZonesLinks.forEach(([link, target]) => {
const isLinkAlreadyAMainTimeZone = rawTimeZones.some((rawTimeZone) => {
return rawTimeZone.name === link;
});
if (isLinkAlreadyAMainTimeZone) {
return;
}
const timeZone = rawTimeZones.find((rawTimeZone) => {
return rawTimeZone.name === target;
});
// We could try to find the name inside the group of a timezone, if someone asks for that let's do it
if (timeZone === undefined) {
return;
}
if (!timeZone.group.includes(link)) {
timeZone.group.push(link);
}
});
fs.writeFileSync(
path.join(__dirname, "time-zones-names.json"),
JSON.stringify(timeZonesNames.sort()).replace(/",/g, '",\n'),
);
fs.writeFileSync(
path.join(__dirname, "raw-time-zones.json"),
JSON.stringify(
orderBy(rawTimeZones, [
"rawOffsetInMinutes",
"alternativeName",
"mainCities[0]",
]),
).replace(/},/g, "},\n"),
);
}
run().catch((error) => {
console.error(error);
process.exit(1);
});
function getAbbreviation({ date, timeZoneName }) {
const standardAbbreviation =
abbreviations[timeZoneName.replace("Time", "Standard Time")];
if (standardAbbreviation) {
return standardAbbreviation;
}
const exactAbbreviation = abbreviations[timeZoneName];
if (exactAbbreviation) {
return exactAbbreviation;
}
console.log(
'Could not find abbreviation for "%s"',
timeZoneName,
date.toFormat(`ZZZZ`),
);
return date.toFormat(`ZZZZ`);
}