Repository navigation
Expand file tree
/
Copy pathmap.ts
More file actions
310 lines (291 loc) · 8.51 KB
/
Copy pathmap.ts
File metadata and controls
310 lines (291 loc) · 8.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import { readCache, writeCache, type EvenStorage } from "./live-cache";
import type {
Coordinate,
DataState,
MapLabel,
MapRoad,
MapValue,
} from "./live-state";
export const MAP_MAX_AGE_MS = 24 * 60 * 60 * 1_000;
export const MAP_RADIUS_METERS = 650;
const MAP_TIMEOUT_MS = 8_000;
const MAP_MAX_ROADS = 180;
const MAP_MAX_POINTS = 4_000;
const MAP_MAX_LABELS = 24;
const MAP_MAX_LABEL_CODE_POINTS = 40;
const MAP_CACHE_KEY = "map-labels";
const MAP_CELL_DEGREES = 0.0018;
const MAP_LABEL_KINDS = new Set<MapLabel["kind"]>([
"place",
"transit",
"landmark",
"road",
]);
type MapCache = {
readonly value: MapValue;
readonly fetchedAt: number;
readonly cell: string;
};
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isFiniteCoordinate(value: unknown): value is Coordinate {
return isRecord(value)
&& typeof value.latitude === "number"
&& Number.isFinite(value.latitude)
&& value.latitude >= -90
&& value.latitude <= 90
&& typeof value.longitude === "number"
&& Number.isFinite(value.longitude)
&& value.longitude >= -180
&& value.longitude <= 180;
}
function isMapRoad(value: unknown): value is MapRoad {
return isRecord(value)
&& (value.kind === "major" || value.kind === "minor")
&& Array.isArray(value.points)
&& value.points.length >= 2
&& value.points.every(isFiniteCoordinate);
}
function isMapLabel(value: unknown): value is MapLabel {
return isRecord(value)
&& typeof value.kind === "string"
&& MAP_LABEL_KINDS.has(value.kind as MapLabel["kind"])
&& typeof value.name === "string"
&& value.name.length > 0
&& value.name.trim() === value.name
&& [...value.name].length <= MAP_MAX_LABEL_CODE_POINTS
&& !/[\u0000-\u001f\u007f]/.test(value.name)
&& isFiniteCoordinate(value.point);
}
function isMapValue(value: unknown): value is MapValue {
if (
!isRecord(value)
|| value.attribution !== "© OSM CONTRIBUTORS"
|| typeof value.cell !== "string"
|| !Array.isArray(value.roads)
|| value.roads.length > MAP_MAX_ROADS
|| !value.roads.every(isMapRoad)
|| !Array.isArray(value.labels)
|| value.labels.length > MAP_MAX_LABELS
|| !value.labels.every(isMapLabel)
) {
return false;
}
return value.roads.reduce(
(total, road) => total + road.points.length,
0,
) <= MAP_MAX_POINTS;
}
function isMapCache(value: unknown): value is MapCache {
return isRecord(value)
&& isMapValue(value.value)
&& typeof value.fetchedAt === "number"
&& Number.isFinite(value.fetchedAt)
&& typeof value.cell ==
10252
= "string"
&& value.cell === value.value.cell;
}
function cloneMapValue(value: MapValue): MapValue {
return {
cell: value.cell,
attribution: "© OSM CONTRIBUTORS",
roads: value.roads.map((road) => ({
kind: road.kind,
points: road.points.map((point) => ({ ...point })),
})),
labels: value.labels.map((label) => ({
kind: label.kind,
name: label.name,
point: { ...label.point },
})),
};
}
function mapState(
cache: MapCache,
status: "fresh" | "stale",
): DataState<MapValue> {
return {
status,
value: cloneMapValue(cache.value),
fetchedAt: cache.fetchedAt,
};
}
export function clientMapCell(coordinate: Coordinate): string {
const latitude = Math.floor(
coordinate.latitude / MAP_CELL_DEGREES,
) * MAP_CELL_DEGREES;
const longitude = Math.floor(
coordinate.longitude / MAP_CELL_DEGREES,
) * MAP_CELL_DEGREES;
return `${latitude.toFixed(4)},${longitude.toFixed(4)}`;
}
export function parseMapResponse(input: unknown): MapValue {
if (
!isRecord(input)
|| input.attribution !== "© OSM CONTRIBUTORS"
|| typeof input.cell !== "string"
|| !Array.isArray(input.roads)
|| input.roads.length > MAP_MAX_ROADS
|| !Array.isArray(input.labels)
|| input.labels.length > MAP_MAX_LABELS
) {
throw new Error("Invalid map response");
}
let totalPoints = 0;
const roads: MapRoad[] = input.roads.map((road) => {
if (
!isRecord(road)
|| (road.kind !== "major" && road.kind !== "minor")
|| !Array.isArray(road.points)
|| road.points.length < 2
) {
throw new Error("Invalid map road");
}
const points = road.points.map((point) => {
if (!Array.isArray(point) || point.length !== 2) {
throw new Error("Invalid map point");
}
const coordinate = {
latitude: point[0],
longitude: point[1],
};
if (!isFiniteCoordinate(coordinate)) {
throw new Error("Invalid map coordinate");
}
return coordinate;
});
totalPoints += points.length;
if (totalPoints > MAP_MAX_POINTS) {
throw new Error("Map response has too many points");
}
return { kind: road.kind, points };
});
const labels: MapLabel[] = input.labels.map((label) => {
if (
!isRecord(label)
|| typeof label.kind !== "string"
|| !MAP_LABEL_KINDS.has(label.kind as MapLabel["kind"])
|| typeof label.name !== "string"
|| label.name.length === 0
|| label.name.trim() !== label.name
|| [...label.name].length > MAP_MAX_LABEL_CODE_POINTS
|| /[\u0000-\u001f\u007f]/.test(label.name)
|| !Array.isArray(label.point)
|| label.point.length !== 2
) {
throw new Error("Invalid map label");
}
const point = {
latitude: label.point[0],
longitude: label.point[1],
};
if (!isFiniteCoordinate(point)) {
throw new Error("Invalid map label coordinate");
}
return {
kind: label.kind as MapLabel["kind"],
name: label.name,
point,
};
});
return {
cell: input.cell,
attribution: "© OSM CONTRIBUTORS",
roads,
labels,
};
}
export function projectCoordinate(
point: Coordinate,
center: Coordinate,
radiusMeters = MAP_RADIUS_METERS,
): { readonly x: number; readonly y: number } {
if (!Number.isFinite(radiusMeters) || radiusMeters <= 0) {
throw new Error("Invalid map radius");
}
const metersPerDegreeLatitude = 111_320;
const metersPerDegreeLongitude = 111_320 * Math.cos(
center.latitude * Math.PI / 180,
);
const east = (
point.longitude - center.longitude
) * metersPerDegreeLongitude;
const north = (
point.latitude - center.latitude
) * metersPerDegreeLatitude;
const scale = 112 / radiusMeters;
return {
x: 144 + east * scale,
y: 144 - north * scale,
};
}
export async function resolveMap(
storage: EvenStorage,
coordinate: Coordinate,
fetchImpl: typeof fetch = fetch,
now = Date.now(),
onCached?: (cached: DataState<MapValue>) => void,
): Promise<DataState<MapValue>> {
const requestCoordinate = { ...coordinate };
const cell = clientMapCell(requestCoordinate);
const cached = await readCache(storage, MAP_CACHE_KEY, isMapCache);
const fallbackCache = cached && cached.fetchedAt <= now
? cached
: undefined;
const usableCache = fallbackCache?.cell === cell
? fallbackCache
: undefined;
if (usableCache) {
const status = now - usableCache.fetchedAt <= MAP_MAX_AGE_MS
? "fresh"
: "stale";
const cachedState = mapState(usableCache, status);
try {
onCached?.(cachedState);
} catch {
// Rendering cached geometry is optional and must not stop refresh.
}
if (status === "fresh") return cachedState;
} else if (fallbackCache) {
try {
onCached?.(mapState(fallbackCache, "stale"));
} catch {
// Rendering fallback geometry is optional and must not stop refresh.
}
}
const controller = new AbortController();
const timer = globalThis.setTimeout(
() => controller.abort(),
MAP_TIMEOUT_MS,
);
try {
const response = await fetchImpl(
`/api/map?lat=${encodeURIComponent(requestCoordinate.latitude)}` +
`&lng=${encodeURIComponent(requestCoordinate.longitude)}`,
{
headers: { accept: "application/json" },
signal: controller.signal,
},
);
if (!response.ok) throw new Error("MAP_HTTP_ERROR");
const value = parseMapResponse(await response.json());
if (value.cell !== cell) throw new Error("MAP_CELL_MISMATCH");
const cache: MapCache = {
value: cloneMapValue(value),
fetchedAt: now,
cell,
};
await writeCache(storage, MAP_CACHE_KEY, cache);
return {
status: "fresh",
value: cloneMapValue(value),
fetchedAt: now,
};
} catch {
return fallbackCache
? mapState(fallbackCache, "stale")
: { status: "unavailable" };
} finally {
globalThis.clearTimeout(timer);
}
}