@gadicc/loom 2.3.1 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.loom-source-manifest.json +7 -1
- package/esm/src/geo/client.d.ts +74 -0
- package/esm/src/geo/client.d.ts.map +1 -0
- package/esm/src/geo/client.js +135 -0
- package/esm/src/geo/client.js.map +1 -0
- package/esm/src/geo/mod.d.ts +5 -0
- package/esm/src/geo/mod.d.ts.map +1 -0
- package/esm/src/geo/mod.js +5 -0
- package/esm/src/geo/mod.js.map +1 -0
- package/esm/src/geo/place.d.ts +28 -0
- package/esm/src/geo/place.d.ts.map +1 -0
- package/esm/src/geo/place.js +41 -0
- package/esm/src/geo/place.js.map +1 -0
- package/esm/src/geo/places.d.ts +16 -0
- package/esm/src/geo/places.d.ts.map +1 -0
- package/esm/src/geo/places.js +154 -0
- package/esm/src/geo/places.js.map +1 -0
- package/esm/src/geo/placesFormat.d.ts +49 -0
- package/esm/src/geo/placesFormat.d.ts.map +1 -0
- package/esm/src/geo/placesFormat.js +38 -0
- package/esm/src/geo/placesFormat.js.map +1 -0
- package/esm/src/geo/preference.d.ts +15 -0
- package/esm/src/geo/preference.d.ts.map +1 -0
- package/esm/src/geo/preference.js +21 -0
- package/esm/src/geo/preference.js.map +1 -0
- package/esm/src/geo/timeZone.d.ts +20 -0
- package/esm/src/geo/timeZone.d.ts.map +1 -0
- package/esm/src/geo/timeZone.js +65 -0
- package/esm/src/geo/timeZone.js.map +1 -0
- package/esm/src/geo/vercel.d.ts +15 -0
- package/esm/src/geo/vercel.d.ts.map +1 -0
- package/esm/src/geo/vercel.js +64 -0
- package/esm/src/geo/vercel.js.map +1 -0
- package/package.json +26 -2
- package/source/src/geo/client.ts +241 -0
- package/source/src/geo/mod.ts +12 -0
- package/source/src/geo/place.ts +61 -0
- package/source/src/geo/places.ts +195 -0
- package/source/src/geo/placesFormat.ts +58 -0
- package/source/src/geo/preference.ts +24 -0
- package/source/src/geo/timeZone.ts +78 -0
- package/source/src/geo/vercel.ts +78 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import type { Place } from "./place.ts";
|
|
2
|
+
import {
|
|
3
|
+
foldPlaceName,
|
|
4
|
+
PLACES_FORMAT,
|
|
5
|
+
type PlacesHeader,
|
|
6
|
+
} from "./placesFormat.ts";
|
|
7
|
+
export {
|
|
8
|
+
foldPlaceName,
|
|
9
|
+
PLACES_FORMAT,
|
|
10
|
+
type PlacesHeader,
|
|
11
|
+
} from "./placesFormat.ts";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Common names for a country that are neither its ISO code nor a prefix of
|
|
15
|
+
* its English name, so "london, uk" and "paris, usa" narrow as people type
|
|
16
|
+
* them.
|
|
17
|
+
*/
|
|
18
|
+
const COUNTRY_ALIASES: Record<string, string> = {
|
|
19
|
+
uk: "GB",
|
|
20
|
+
usa: "US",
|
|
21
|
+
uae: "AE",
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** Longer queries are cut; no place name needs more. */
|
|
25
|
+
export const MAX_QUERY_LENGTH = 64;
|
|
26
|
+
const MAX_LIMIT = 50;
|
|
27
|
+
|
|
28
|
+
interface Region {
|
|
29
|
+
country: string;
|
|
30
|
+
name: string;
|
|
31
|
+
/** Folded region name, for "paris, texas". */
|
|
32
|
+
folded: string;
|
|
33
|
+
/** Folded English country name, for "paris, united states". */
|
|
34
|
+
countryName: string;
|
|
35
|
+
/** Lower-case letter code, for "paris, tx"; "" without one. */
|
|
36
|
+
code: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface Row {
|
|
40
|
+
place: Place;
|
|
41
|
+
region: number;
|
|
42
|
+
/** Folded name and, when it differs, folded ASCII name. */
|
|
43
|
+
keys: string[];
|
|
44
|
+
alternates: string[];
|
|
45
|
+
district: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The parsed places file and a search over it. */
|
|
49
|
+
export interface PlaceIndex {
|
|
50
|
+
size: number;
|
|
51
|
+
search(q: string, limit?: number): Place[];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Ranks, best first; a row takes the best that applies. */
|
|
55
|
+
const EXACT = 0;
|
|
56
|
+
const PREFIX = 1; // also an exact alternate name ("munchen" → Munich)
|
|
57
|
+
const WORD_PREFIX = 2; // "york" in "new york"
|
|
58
|
+
const ALTERNATE_PREFIX = 3;
|
|
59
|
+
const DISTRICT = 4; // any match on a city's district ("Zürich (Kreis 11)")
|
|
60
|
+
|
|
61
|
+
function regionsOf(header: PlacesHeader): Region[] {
|
|
62
|
+
const names = new Intl.DisplayNames(["en"], { type: "region" });
|
|
63
|
+
const countryNames = new Map<string, string>();
|
|
64
|
+
return header.regions.map(([country, name, code = ""]) => {
|
|
65
|
+
let countryName = countryNames.get(country);
|
|
66
|
+
if (countryName === undefined) {
|
|
67
|
+
try {
|
|
68
|
+
countryName = foldPlaceName(names.of(country) ?? country);
|
|
69
|
+
} catch {
|
|
70
|
+
countryName = country.toLowerCase();
|
|
71
|
+
}
|
|
72
|
+
countryNames.set(country, countryName);
|
|
73
|
+
}
|
|
74
|
+
return {
|
|
75
|
+
country,
|
|
76
|
+
name,
|
|
77
|
+
folded: foldPlaceName(name),
|
|
78
|
+
countryName,
|
|
79
|
+
code: code.toLowerCase(),
|
|
80
|
+
};
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Parses a places file (format in `placesFormat.ts`). Throws on a header
|
|
86
|
+
* it doesn't know or a row count that doesn't match, rather than serving
|
|
87
|
+
* a half-read list.
|
|
88
|
+
*/
|
|
89
|
+
export function createPlaceIndex(text: string): PlaceIndex {
|
|
90
|
+
const end = text.indexOf("\n");
|
|
91
|
+
const header = JSON.parse(text.slice(0, end)) as PlacesHeader;
|
|
92
|
+
if (
|
|
93
|
+
header.format !== PLACES_FORMAT ||
|
|
94
|
+
!Array.isArray(header.timezones) ||
|
|
95
|
+
!Array.isArray(header.regions)
|
|
96
|
+
) {
|
|
97
|
+
throw new Error("places: unknown file format");
|
|
98
|
+
}
|
|
99
|
+
const regions = regionsOf(header);
|
|
100
|
+
const rows: Row[] = [];
|
|
101
|
+
for (const line of text.slice(end + 1).split("\n")) {
|
|
102
|
+
if (!line) continue;
|
|
103
|
+
const [name, ascii, region, latitude, longitude, timezone, district, alts] =
|
|
104
|
+
line.split("\t");
|
|
105
|
+
const r = regions[Number(region)];
|
|
106
|
+
const tz = header.timezones[Number(timezone)];
|
|
107
|
+
const lat = Number(latitude);
|
|
108
|
+
const lon = Number(longitude);
|
|
109
|
+
if (!name || !r || !tz || !Number.isFinite(lat) || !Number.isFinite(lon)) {
|
|
110
|
+
throw new Error(`places: bad row ${rows.length + 1}`);
|
|
111
|
+
}
|
|
112
|
+
const place: Place = {
|
|
113
|
+
name,
|
|
114
|
+
...(r.name ? { region: r.name } : {}),
|
|
115
|
+
country: r.country,
|
|
116
|
+
latitude: lat,
|
|
117
|
+
longitude: lon,
|
|
118
|
+
timezone: tz,
|
|
119
|
+
};
|
|
120
|
+
const folded = foldPlaceName(name);
|
|
121
|
+
const foldedAscii = ascii ? foldPlaceName(ascii) : folded;
|
|
122
|
+
rows.push({
|
|
123
|
+
place,
|
|
124
|
+
region: Number(region),
|
|
125
|
+
keys: foldedAscii === folded ? [folded] : [folded, foldedAscii],
|
|
126
|
+
alternates: alts ? alts.split("|") : [],
|
|
127
|
+
district: district === "1",
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
if (rows.length !== header.rows) {
|
|
131
|
+
throw new Error(`places: ${rows.length} rows, header says ${header.rows}`);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Which regions every "where" term after the first comma allows. */
|
|
135
|
+
function allowedRegions(wheres: string[]): boolean[] | null {
|
|
136
|
+
if (!wheres.length) return null;
|
|
137
|
+
return regions.map((r) =>
|
|
138
|
+
wheres.every(
|
|
139
|
+
(w) =>
|
|
140
|
+
r.country.toLowerCase() === w ||
|
|
141
|
+
COUNTRY_ALIASES[w] === r.country ||
|
|
142
|
+
// Exactly: "n" or "ni" is not Northern Ireland ("NIR").
|
|
143
|
+
(r.code !== "" && r.code === w) ||
|
|
144
|
+
r.countryName.startsWith(w) ||
|
|
145
|
+
r.folded.startsWith(w),
|
|
146
|
+
),
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function rank(row: Row, q: string): number {
|
|
151
|
+
if (row.keys.includes(q)) return EXACT;
|
|
152
|
+
if (row.keys.some((k) => k.startsWith(q)) || row.alternates.includes(q)) {
|
|
153
|
+
return PREFIX;
|
|
154
|
+
}
|
|
155
|
+
if (row.keys.some((k) => k.includes(` ${q}`) || k.includes(`-${q}`))) {
|
|
156
|
+
return WORD_PREFIX;
|
|
157
|
+
}
|
|
158
|
+
if (row.alternates.some((a) => a.startsWith(q))) return ALTERNATE_PREFIX;
|
|
159
|
+
return -1;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
size: rows.length,
|
|
164
|
+
search(q, limit = 8) {
|
|
165
|
+
const text = q.trim().slice(0, MAX_QUERY_LENGTH);
|
|
166
|
+
if (text.length < 2) return [];
|
|
167
|
+
const [first, ...rest] = text.split(",");
|
|
168
|
+
const name = foldPlaceName(first);
|
|
169
|
+
if (name.length < 2) return [];
|
|
170
|
+
const allowed = allowedRegions(
|
|
171
|
+
rest.map(foldPlaceName).filter((w) => w !== ""),
|
|
172
|
+
);
|
|
173
|
+
const max = Number.isFinite(limit)
|
|
174
|
+
? Math.min(Math.max(Math.floor(limit), 1), MAX_LIMIT)
|
|
175
|
+
: 8;
|
|
176
|
+
|
|
177
|
+
// Rows are in population order, so each tier fills biggest first.
|
|
178
|
+
const tiers: Place[][] = [[], [], [], [], []];
|
|
179
|
+
for (const row of rows) {
|
|
180
|
+
if (allowed && !allowed[row.region]) continue;
|
|
181
|
+
let tier = rank(row, name);
|
|
182
|
+
if (tier < 0) continue;
|
|
183
|
+
if (row.district) tier = DISTRICT;
|
|
184
|
+
if (tiers[tier].length < max) tiers[tier].push(row.place);
|
|
185
|
+
// Nothing found later can outrank a full first tier.
|
|
186
|
+
if (tiers[EXACT].length >= max) break;
|
|
187
|
+
}
|
|
188
|
+
// Copies, so a caller can't change the index.
|
|
189
|
+
return tiers
|
|
190
|
+
.flat()
|
|
191
|
+
.slice(0, max)
|
|
192
|
+
.map((place) => ({ ...place }));
|
|
193
|
+
},
|
|
194
|
+
};
|
|
195
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The format of `places.tsv`, shared by the script that writes it
|
|
3
|
+
* (`scripts/geonames/build.ts`) and the search that reads it
|
|
4
|
+
* (`places.ts`). Pure and free of `server-only` so the build script can
|
|
5
|
+
* import it; nothing here holds the data itself.
|
|
6
|
+
*
|
|
7
|
+
* The file is one JSON header line, then one tab-separated line per place
|
|
8
|
+
* in descending population order (the order is the ranking, so there is
|
|
9
|
+
* no population column):
|
|
10
|
+
*
|
|
11
|
+
* ```
|
|
12
|
+
* {"format":2,...,"rows":N,"timezones":[...],"regions":[["GB","England","ENG"],["UA","Kyiv City"],...]}
|
|
13
|
+
* name ascii region latitude longitude timezone district alternates
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* - `ascii`: GeoNames' ASCII name, empty when it equals `name`.
|
|
17
|
+
* - `region`, `timezone`: indexes into the header's lists.
|
|
18
|
+
* - `latitude`, `longitude`: degrees rounded to 3 decimals (~100 m).
|
|
19
|
+
* - `district`: `1` for a section of a city (GeoNames `PPLX`), else empty.
|
|
20
|
+
* - `alternates`: `|`-separated, already folded (`foldPlaceName`).
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** Bumped whenever a column or the header changes meaning. */
|
|
24
|
+
export const PLACES_FORMAT = 2;
|
|
25
|
+
|
|
26
|
+
/** The JSON header on the file's first line. */
|
|
27
|
+
export interface PlacesHeader {
|
|
28
|
+
format: typeof PLACES_FORMAT;
|
|
29
|
+
/** Which GeoNames files, from when. */
|
|
30
|
+
source: string;
|
|
31
|
+
/** Licence and a pointer to what was changed. */
|
|
32
|
+
license: string;
|
|
33
|
+
/** Number of place lines that follow. */
|
|
34
|
+
rows: number;
|
|
35
|
+
/** IANA time zones, indexed by the timezone column. */
|
|
36
|
+
timezones: string[];
|
|
37
|
+
/**
|
|
38
|
+
* `[country code, first-level region name or ""]`, indexed by the region
|
|
39
|
+
* column, with the region's code third when it is letters (GeoNames'
|
|
40
|
+
* admin1 code: "TX", "DC", "ENG"; not Canada's "08").
|
|
41
|
+
*/
|
|
42
|
+
regions: ([string, string] | [string, string, string])[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Lower case, without accents or repeated spaces, so "São Paulo", "sao
|
|
47
|
+
* paulo" and "SAO PAULO" compare equal. The build folds the alternates
|
|
48
|
+
* with this and the search folds names and queries with it, so the two
|
|
49
|
+
* must stay one function.
|
|
50
|
+
*/
|
|
51
|
+
export function foldPlaceName(text: string): string {
|
|
52
|
+
return text
|
|
53
|
+
.normalize("NFD")
|
|
54
|
+
.replace(/\p{M}/gu, "")
|
|
55
|
+
.toLowerCase()
|
|
56
|
+
.replace(/\s+/g, " ")
|
|
57
|
+
.trim();
|
|
58
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type Place, toPlace } from "./place.ts";
|
|
2
|
+
|
|
3
|
+
/** A future default, distinct from an acquired position or an entry override. */
|
|
4
|
+
export type LocationPreference =
|
|
5
|
+
| { version: 2; mode: "automatic" }
|
|
6
|
+
| { version: 2; mode: "fixed"; place: Place };
|
|
7
|
+
/** The default stores no detected or device coordinates. */
|
|
8
|
+
export const AUTOMATIC_LOCATION: LocationPreference = Object.freeze({
|
|
9
|
+
version: 2,
|
|
10
|
+
mode: "automatic",
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
/** Validates versioned browser JSON, preserving only explicit fixed-city intent. */
|
|
14
|
+
export function toLocationPreference(
|
|
15
|
+
value: unknown,
|
|
16
|
+
): LocationPreference | null {
|
|
17
|
+
if (typeof value !== "object" || value === null) return null;
|
|
18
|
+
const v = value as Record<string, unknown>;
|
|
19
|
+
if (v.version !== 2) return null;
|
|
20
|
+
if (v.mode === "automatic") return AUTOMATIC_LOCATION;
|
|
21
|
+
if (v.mode !== "fixed") return null;
|
|
22
|
+
const place = toPlace(v.place);
|
|
23
|
+
return place ? { version: 2, mode: "fixed", place } : null;
|
|
24
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
const formatters = new Map<string, Intl.DateTimeFormat>();
|
|
2
|
+
|
|
3
|
+
function formatterFor(zone: string): Intl.DateTimeFormat {
|
|
4
|
+
let formatter = formatters.get(zone);
|
|
5
|
+
if (!formatter) {
|
|
6
|
+
formatter = new Intl.DateTimeFormat("en-US", {
|
|
7
|
+
timeZone: zone,
|
|
8
|
+
hourCycle: "h23",
|
|
9
|
+
year: "numeric",
|
|
10
|
+
month: "numeric",
|
|
11
|
+
day: "numeric",
|
|
12
|
+
hour: "numeric",
|
|
13
|
+
minute: "numeric",
|
|
14
|
+
second: "numeric",
|
|
15
|
+
});
|
|
16
|
+
formatters.set(zone, formatter);
|
|
17
|
+
}
|
|
18
|
+
return formatter;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The zone's offset from UTC at `date`, in minutes east (London in summer
|
|
23
|
+
* 60, New York in winter -300). Throws a RangeError for a zone the runtime
|
|
24
|
+
* does not know.
|
|
25
|
+
*/
|
|
26
|
+
export function utcOffsetMinutes(zone: string, date: Date): number {
|
|
27
|
+
const parts: Record<string, number> = {};
|
|
28
|
+
for (const part of formatterFor(zone).formatToParts(date)) {
|
|
29
|
+
if (part.type !== "literal") parts[part.type] = Number(part.value);
|
|
30
|
+
}
|
|
31
|
+
const wall = Date.UTC(
|
|
32
|
+
parts.year,
|
|
33
|
+
parts.month - 1,
|
|
34
|
+
parts.day,
|
|
35
|
+
parts.hour,
|
|
36
|
+
parts.minute,
|
|
37
|
+
parts.second,
|
|
38
|
+
);
|
|
39
|
+
const instant = Math.floor(date.getTime() / 1000) * 1000;
|
|
40
|
+
return Math.round((wall - instant) / 60_000);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The device's IANA time zone, or undefined where the runtime has none or
|
|
45
|
+
* names one it can't then use.
|
|
46
|
+
*/
|
|
47
|
+
export function deviceTimeZone(): string | undefined {
|
|
48
|
+
try {
|
|
49
|
+
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
50
|
+
if (!zone) return undefined;
|
|
51
|
+
formatterFor(zone);
|
|
52
|
+
return zone;
|
|
53
|
+
} catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Whether a clock in `zone` would read differently from one in `deviceZone`
|
|
60
|
+
* at any of `times`. Compares UTC offsets, not names, since sources name the
|
|
61
|
+
* same zone differently (GeoNames' Asia/Kolkata is V8's Asia/Calcutta, and
|
|
62
|
+
* Europe/Kyiv is Europe/Kiev in older data). False when either zone is
|
|
63
|
+
* unknown to the runtime: no note is better than a wrong one.
|
|
64
|
+
*/
|
|
65
|
+
export function clocksDiffer(
|
|
66
|
+
zone: string,
|
|
67
|
+
deviceZone: string,
|
|
68
|
+
times: readonly Date[],
|
|
69
|
+
): boolean {
|
|
70
|
+
try {
|
|
71
|
+
return times.some(
|
|
72
|
+
(time) =>
|
|
73
|
+
utcOffsetMinutes(zone, time) !== utcOffsetMinutes(deviceZone, time),
|
|
74
|
+
);
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { type Place, toPlace } from "./place.ts";
|
|
2
|
+
|
|
3
|
+
/** `@vercel/functions` has no constant for this one. */
|
|
4
|
+
export const TIMEZONE_HEADER_NAME = "x-vercel-ip-timezone";
|
|
5
|
+
|
|
6
|
+
/** A plain decimal, as Vercel sends: no exponent, hex or empty string. */
|
|
7
|
+
const DECIMAL = /^-?\d+(?:\.\d+)?$/;
|
|
8
|
+
|
|
9
|
+
function coordinate(headers: HeaderReader, name: string): number | undefined {
|
|
10
|
+
const value = headers.get(name)?.trim();
|
|
11
|
+
return value && DECIMAL.test(value) ? Number(value) : undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The city, decoded from RFC 3986, or undefined when it doesn't decode. */
|
|
15
|
+
function city(headers: HeaderReader): string | undefined {
|
|
16
|
+
const raw = headers.get("x-vercel-ip-city");
|
|
17
|
+
if (!raw) return undefined;
|
|
18
|
+
try {
|
|
19
|
+
return decodeURIComponent(raw).trim() || undefined;
|
|
20
|
+
} catch {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The country's English name ("United Kingdom"), when Intl knows it. */
|
|
26
|
+
function countryName(country: string): string | undefined {
|
|
27
|
+
try {
|
|
28
|
+
const name = new Intl.DisplayNames(["en"], { type: "region" }).of(country);
|
|
29
|
+
return name && name !== country ? name : undefined;
|
|
30
|
+
} catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The zone when this runtime knows it as an IANA name, else undefined. */
|
|
36
|
+
function timezone(headers: HeaderReader): string | undefined {
|
|
37
|
+
const value = headers.get(TIMEZONE_HEADER_NAME)?.trim();
|
|
38
|
+
if (!value) return undefined;
|
|
39
|
+
try {
|
|
40
|
+
new Intl.DateTimeFormat("en", { timeZone: value });
|
|
41
|
+
return value;
|
|
42
|
+
} catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A request-header reader, including Next's read-only headers. */
|
|
48
|
+
export interface HeaderReader {
|
|
49
|
+
get(name: string): string | null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A usable IP place and decoded city label, which is not an accuracy guarantee. */
|
|
53
|
+
export interface DetectedPlace {
|
|
54
|
+
place: Place;
|
|
55
|
+
cityName?: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Parses Vercel hints without throwing on missing coordinates or encoded cities. */
|
|
59
|
+
export function parseVercelLocation(
|
|
60
|
+
headers: HeaderReader,
|
|
61
|
+
unnamed = "Your area",
|
|
62
|
+
): DetectedPlace | null {
|
|
63
|
+
const latitude = coordinate(headers, "x-vercel-ip-latitude");
|
|
64
|
+
const longitude = coordinate(headers, "x-vercel-ip-longitude");
|
|
65
|
+
if (latitude === undefined || longitude === undefined) return null;
|
|
66
|
+
const code = headers.get("x-vercel-ip-country")?.trim().toUpperCase();
|
|
67
|
+
const country = code && /^[A-Z]{2}$/.test(code) ? code : undefined;
|
|
68
|
+
const decoded = city(headers);
|
|
69
|
+
const cityName = decoded && decoded.length <= 200 ? decoded : undefined;
|
|
70
|
+
const place = toPlace({
|
|
71
|
+
name: cityName ?? (country ? countryName(country) : undefined) ?? unnamed,
|
|
72
|
+
country,
|
|
73
|
+
latitude,
|
|
74
|
+
longitude,
|
|
75
|
+
timezone: timezone(headers),
|
|
76
|
+
});
|
|
77
|
+
return place ? { place, ...(cityName ? { cityName } : {}) } : null;
|
|
78
|
+
}
|