@yarrow-uz/rn-map-sdk 0.0.0-stage → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,1222 @@
1
+ import { Camera, GeoJSONSource, Layer, Map as Map$1, OfflineManager } from "@maplibre/maplibre-react-native";
2
+ import { forwardRef, memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
3
+ import { jsx, jsxs } from "react/jsx-runtime";
4
+
5
+ // ../core/dist/index.js
6
+ const YARROW_MAP_URL = "https://gis.yarrow.uz";
7
+ const YARROW_SEARCH_API_URL = "https://api.yarrow.uz";
8
+ let _apiKey = null;
9
+ function setYarrowApiKey(apiKey) {
10
+ if (!apiKey) throw new Error("apiKey is required");
11
+ _apiKey = apiKey;
12
+ }
13
+ function getYarrowApiKey() {
14
+ if (!_apiKey) throw new Error("Yarrow API key not configured");
15
+ return _apiKey;
16
+ }
17
+ /**
18
+ * Appends the configured API key as the `api_key` query parameter. Returns the
19
+ * url unchanged when no key is configured yet or the url cannot be parsed.
20
+ */
21
+ function addApiKeyToUrl(url) {
22
+ if (!_apiKey) return url;
23
+ try {
24
+ const parsedUrl = new URL(url);
25
+ parsedUrl.searchParams.set("api_key", _apiKey);
26
+ return parsedUrl.toString();
27
+ } catch {
28
+ return url;
29
+ }
30
+ }
31
+ const STORAGE_KEY = "yarrow:user_token";
32
+ /**
33
+ * Public alias of `STORAGE_KEY` so platform SDKs can build storage adapters
34
+ * (e.g. React Native AsyncStorage bridges) without hard-coding the key.
35
+ */
36
+ const USER_TOKEN_STORAGE_KEY = STORAGE_KEY;
37
+ let override = null;
38
+ function setTokenStorage(storage) {
39
+ override = storage;
40
+ }
41
+ function resolveStorage() {
42
+ if (override) return override;
43
+ try {
44
+ if (typeof localStorage !== "undefined") return localStorage;
45
+ } catch {}
46
+ return null;
47
+ }
48
+ function generateUuid() {
49
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
50
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
51
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(bytes);
52
+ else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
53
+ bytes[6] = bytes[6] & 15 | 64;
54
+ bytes[8] = bytes[8] & 63 | 128;
55
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
56
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10, 16).join("")}`;
57
+ }
58
+ function getOrCreateUserToken() {
59
+ const storage = resolveStorage();
60
+ if (storage) try {
61
+ const existing = storage.getItem(STORAGE_KEY);
62
+ if (existing) return existing;
63
+ const token = generateUuid();
64
+ storage.setItem(STORAGE_KEY, token);
65
+ return token;
66
+ } catch {}
67
+ return generateUuid();
68
+ }
69
+ /** Hard cap on how long a single tracking request may stay open. */
70
+ const TRACK_REQUEST_TIMEOUT_MS = 5e3;
71
+ function trackDau(apiKey, sdkType = "javascript") {
72
+ try {
73
+ const user_token = getOrCreateUserToken();
74
+ const controller = new AbortController();
75
+ const timeout = setTimeout(() => controller.abort(), TRACK_REQUEST_TIMEOUT_MS);
76
+ fetch(`${YARROW_SEARCH_API_URL}/api/tracking/track-dau`, {
77
+ method: "POST",
78
+ headers: { "Content-Type": "application/json" },
79
+ body: JSON.stringify({
80
+ api_key: apiKey,
81
+ sdk_type: sdkType,
82
+ user_token
83
+ }),
84
+ signal: controller.signal
85
+ }).catch(() => {}).finally(() => clearTimeout(timeout));
86
+ } catch {}
87
+ }
88
+ const DEFAULT_CACHE_LIFESPAN_DAYS = 30;
89
+ const MILLISECONDS_PER_DAY = 864e5;
90
+ const TILE_CACHE_NAME = "yarrow-cache-v1-tile";
91
+ const ICON_CACHE_NAME = "yarrow-cache-v1-icon";
92
+ const CACHE_PROTOCOL = "yarrowcache";
93
+ const CACHED_AT_HEADER = "x-yarrow-cached-at";
94
+ const hasCacheStorage = () => typeof globalThis !== "undefined" && typeof globalThis.caches !== "undefined" && typeof globalThis.caches.open === "function";
95
+ const extractCachedAt = (response) => {
96
+ const raw = response.headers.get(CACHED_AT_HEADER);
97
+ if (!raw) return null;
98
+ const parsed = Number(raw);
99
+ return Number.isFinite(parsed) ? parsed : null;
100
+ };
101
+ /**
102
+ * Pulls a `max-age=N` value (in seconds) out of a `Cache-Control` header, if
103
+ * present. Returns `null` when the header is missing or doesn't carry a
104
+ * numeric `max-age`. Returns 0 for `max-age=0` (treat as immediately stale).
105
+ *
106
+ * The Yarrow backend does not currently emit `Cache-Control` headers, so this
107
+ * is dead in production today. It's plumbed in so a future fix on the
108
+ * backend starts being honored without an SDK release.
109
+ */
110
+ const parseMaxAge = (cacheControl) => {
111
+ if (!cacheControl) return null;
112
+ for (const directive of cacheControl.split(",")) {
113
+ const [rawKey, rawValue] = directive.trim().split("=");
114
+ if (rawKey?.toLowerCase() !== "max-age") continue;
115
+ if (rawValue === void 0) return 0;
116
+ const parsed = Number(rawValue);
117
+ return Number.isFinite(parsed) ? parsed : null;
118
+ }
119
+ return null;
120
+ };
121
+ const toCachedArrayBufferResponse = async (response) => {
122
+ return {
123
+ data: await response.arrayBuffer(),
124
+ cacheControl: response.headers.get("cache-control"),
125
+ expires: response.headers.get("expires"),
126
+ contentType: response.headers.get("content-type")
127
+ };
128
+ };
129
+ const fetchFromNetwork = async (url, abortController, requestParameters) => {
130
+ const response = await fetch(url, {
131
+ method: requestParameters?.method ?? "GET",
132
+ headers: requestParameters?.headers,
133
+ body: requestParameters?.body,
134
+ credentials: requestParameters?.credentials,
135
+ signal: abortController.signal
136
+ });
137
+ if (!response.ok) throw new Error(`Request failed: ${response.status} ${response.statusText}`);
138
+ return toCachedArrayBufferResponse(response);
139
+ };
140
+ /**
141
+ * Best-effort LRU eviction for quota errors. Removes the oldest entries (by
142
+ * `x-yarrow-cached-at` header) until the new write fits, or until nothing
143
+ * remains to drop. Silently stops evicting when the cache becomes empty —
144
+ * callers still treat the original quota error as non-fatal.
145
+ */
146
+ const evictOldest = async (cache) => {
147
+ try {
148
+ const keys = await cache.keys();
149
+ if (keys.length === 0) return false;
150
+ let oldestKey = null;
151
+ let oldestAt = Number.POSITIVE_INFINITY;
152
+ for (const key of keys) {
153
+ const match = await cache.match(key);
154
+ if (!match) continue;
155
+ const at = extractCachedAt(match) ?? 0;
156
+ if (at < oldestAt) {
157
+ oldestAt = at;
158
+ oldestKey = key;
159
+ }
160
+ }
161
+ if (oldestKey === null) return false;
162
+ await cache.delete(oldestKey);
163
+ return true;
164
+ } catch {
165
+ return false;
166
+ }
167
+ };
168
+ const saveToCache = async (cache, cacheKey, response) => {
169
+ const headers = new Headers();
170
+ if (response.contentType) headers.set("content-type", response.contentType);
171
+ if (response.cacheControl) headers.set("cache-control", response.cacheControl);
172
+ if (response.expires) headers.set("expires", response.expires);
173
+ headers.set(CACHED_AT_HEADER, Date.now().toString());
174
+ const MAX_WRITE_EVICTIONS = 4;
175
+ let lastError;
176
+ for (let attempt = 0;; attempt++) {
177
+ const body = new Response(response.data.slice(0), {
178
+ status: 200,
179
+ headers
180
+ });
181
+ try {
182
+ await cache.put(cacheKey, body);
183
+ return;
184
+ } catch (error) {
185
+ lastError = error;
186
+ }
187
+ if (attempt >= MAX_WRITE_EVICTIONS || !await evictOldest(cache)) break;
188
+ }
189
+ console.warn("[YarrowMap] cache write failed:", lastError);
190
+ };
191
+ const fetchArrayBufferWithCache = async (url, cacheName, lifespanMs, abortController, requestParameters) => {
192
+ if (!hasCacheStorage()) return fetchFromNetwork(url, abortController, requestParameters);
193
+ const cache = await caches.open(cacheName);
194
+ const cachedResponse = await cache.match(url);
195
+ if (cachedResponse) {
196
+ const cachedAt = extractCachedAt(cachedResponse);
197
+ const maxAgeSeconds = parseMaxAge(cachedResponse.headers.get("cache-control"));
198
+ const effectiveLifespanMs = maxAgeSeconds !== null ? maxAgeSeconds * 1e3 : lifespanMs;
199
+ if (!(cachedAt === null || Date.now() - cachedAt > effectiveLifespanMs)) return toCachedArrayBufferResponse(cachedResponse);
200
+ try {
201
+ const refreshed = await fetchFromNetwork(url, abortController, requestParameters);
202
+ await saveToCache(cache, url, refreshed);
203
+ return refreshed;
204
+ } catch {
205
+ return toCachedArrayBufferResponse(cachedResponse);
206
+ }
207
+ }
208
+ const networkResponse = await fetchFromNetwork(url, abortController, requestParameters);
209
+ await saveToCache(cache, url, networkResponse);
210
+ return networkResponse;
211
+ };
212
+ /** Routing API endpoint used by `fetchRoutes()`. */
213
+ const ROUTE_API_URL = "https://api.yarrow.uz/api/routing/route";
214
+ const transformRouteCoordinates = (features) => {
215
+ return features.map((feature) => {
216
+ const transformedCoords = feature.geometry.coordinates.map((coord) => [coord.lng, coord.lat]);
217
+ return {
218
+ ...feature,
219
+ geometry: {
220
+ ...feature.geometry,
221
+ coordinates: transformedCoords
222
+ }
223
+ };
224
+ });
225
+ };
226
+ const emptyResult = (profile) => ({
227
+ features: [],
228
+ directions: [],
229
+ meta: {
230
+ profile,
231
+ totalRoutes: 0,
232
+ bestRouteIndex: 0,
233
+ duration: 0,
234
+ distance: 0
235
+ }
236
+ });
237
+ /**
238
+ * Network half of the routing flow: POSTs the route request to the Yarrow
239
+ * routing API, parses and normalizes the response (coordinate order fix
240
+ * included). Rendering, events and camera work stay in the platform SDKs —
241
+ * they consume the returned features/directions/meta verbatim.
242
+ *
243
+ * Early "no route" outcomes resolve to an empty result (never throw), exactly
244
+ * like the web SDK's historic `buildRoute()` behavior.
245
+ */
246
+ async function fetchRoutes(input) {
247
+ const { profile, coordinates, language, signal } = input;
248
+ if (coordinates.length < 2) throw new Error("At least two coordinates are required to build a route.");
249
+ const url = addApiKeyToUrl(ROUTE_API_URL);
250
+ const response = await fetch(url, {
251
+ method: "POST",
252
+ signal,
253
+ headers: {
254
+ "Content-Type": "application/json",
255
+ ...language ? { "Accept-Language": language } : {}
256
+ },
257
+ body: JSON.stringify({
258
+ profile: profile.toUpperCase(),
259
+ coordinates: coordinates.map((coord) => ({
260
+ lng: coord[0],
261
+ lat: coord[1]
262
+ }))
263
+ })
264
+ });
265
+ if (!response.ok) throw new Error(`Request failed: ${response.status} ${response.statusText}`);
266
+ const data = await response.json();
267
+ if (!data.success) {
268
+ console.warn("[YarrowMap] buildRoute: no route found");
269
+ return emptyResult(profile);
270
+ }
271
+ let features = data.data.path?.features || [];
272
+ features = transformRouteCoordinates(features);
273
+ if (!features.length) {
274
+ console.warn("[YarrowMap] buildRoute: route has no features to render");
275
+ return emptyResult(profile);
276
+ }
277
+ const bestCoords = features[0]?.geometry?.coordinates;
278
+ if (bestCoords?.every(([lng, lat]) => lng === bestCoords[0][0] && lat === bestCoords[0][1])) console.warn("[YarrowMap] buildRoute: the returned route has zero length — the requested coordinates may be outside the routing coverage area.");
279
+ const directions = data.data.directions?.routes?.map((r) => r.properties || []) || [];
280
+ return {
281
+ features,
282
+ directions,
283
+ meta: {
284
+ profile,
285
+ totalRoutes: features.length,
286
+ bestRouteIndex: 0,
287
+ duration: features[0]?.properties.duration || 0,
288
+ distance: features[0]?.properties.distance || 0
289
+ }
290
+ };
291
+ }
292
+ const haversineDistance = (lat1, lon1, lat2, lon2) => {
293
+ const toRad = (value) => value * Math.PI / 180;
294
+ const R = 6371e3;
295
+ const phi1 = toRad(lat1);
296
+ const phi2 = toRad(lat2);
297
+ const deltaPhi = toRad(lat2 - lat1);
298
+ const deltaLambda = toRad(lon2 - lon1);
299
+ const a = Math.sin(deltaPhi / 2) ** 2 + Math.cos(phi1) * Math.cos(phi2) * Math.sin(deltaLambda / 2) ** 2;
300
+ return R * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));
301
+ };
302
+ /**
303
+ * Queries the Yarrow search API around a coordinate. Pure network + mapping —
304
+ * marker rendering stays in the platform SDKs.
305
+ */
306
+ async function fetchSearchResults(query, input) {
307
+ const searchUrl = addApiKeyToUrl(`${YARROW_SEARCH_API_URL}/api/search/`);
308
+ const url = new URL(searchUrl);
309
+ url.searchParams.set("q", query);
310
+ url.searchParams.set("lat", String(input.lat));
311
+ url.searchParams.set("lng", String(input.lon));
312
+ url.searchParams.set("country", "Uzbekistan");
313
+ url.searchParams.set("sort_by", "relevance");
314
+ url.searchParams.set("page", String(input.page ?? 1));
315
+ url.searchParams.set("page_size", String(input.pageSize ?? 15));
316
+ const response = await fetch(url.toString(), {
317
+ headers: { "Content-Type": "application/json" },
318
+ signal: input.signal
319
+ });
320
+ if (!response.ok) throw new Error(`Request failed: ${response.status} ${response.statusText}`);
321
+ return ((await response.json())?.results || []).map((r) => ({
322
+ id: r.id,
323
+ name: r.name,
324
+ icon_img: r.icon_img,
325
+ latitude: r.address?.location?.lat,
326
+ longitude: r.address?.location?.lng,
327
+ category: r.category
328
+ }));
329
+ }
330
+ /**
331
+ * Validates a user-supplied style type, warning (and falling back to
332
+ * `"default"`) on anything unrecognized. Verbatim behavior of the web SDK's
333
+ * `changeStyles()` guard.
334
+ */
335
+ function normalizeStyleType(styleType) {
336
+ if (styleType !== void 0 && styleType !== "default" && styleType !== "satellite" && styleType !== "hybrid") console.warn(`[YarrowMap] changeStyles: unknown style type "${styleType}", falling back to "default".`);
337
+ return styleType === "satellite" || styleType === "hybrid" ? styleType : "default";
338
+ }
339
+ /**
340
+ * Style-fetch endpoint for a style type/theme combination, e.g.
341
+ * `/styles/satellite/?dark=true`. Verbatim behavior of the web SDK's
342
+ * `YarrowStylesManager.buildStyleEndpoint()`.
343
+ */
344
+ function buildStyleEndpoint(styleType, theme) {
345
+ let endpoint = "/styles/";
346
+ if (styleType === "satellite") endpoint = "/styles/satellite/";
347
+ else if (styleType === "hybrid") endpoint = "/styles/hybrid/";
348
+ if (theme === "dark") endpoint += endpoint.includes("?") ? "&dark=true" : "?dark=true";
349
+ return endpoint;
350
+ }
351
+
352
+ // src/maps/config.ts
353
+ /**
354
+ * Validated, defaulted RN map configuration. Mirrors the web SDK's
355
+ * `YarrowMapConfig` minus the DOM container (the native view is sized by the
356
+ * consuming app's layout) and minus web-only rendering options (hover,
357
+ * clustering, controls, tile cache — none of which exist on native).
358
+ */
359
+ var YarrowMapConfig = class {
360
+ constructor(config) {
361
+ const { apiKey, center, zoom: resolvedZoom = 10, minZoom: resolvedMinZoom = 0, maxZoom: resolvedMaxZoom = 19, theme: resolvedTheme = "light", styleType: resolvedStyleType } = config;
362
+ if (!apiKey) throw new Error("apiKey is required");
363
+ this.center = center;
364
+ this.zoom = resolvedZoom;
365
+ this.minZoom = resolvedMinZoom;
366
+ this.maxZoom = resolvedMaxZoom;
367
+ this.theme = resolvedTheme;
368
+ this.styleType = normalizeStyleType(resolvedStyleType);
369
+ this.apiKey = apiKey;
370
+ }
371
+ };
372
+
373
+ // src/maps/styles.ts
374
+ /**
375
+ * Full style URL for MapLibre React Native's `mapStyle` prop, built from the
376
+ * platform-agnostic style endpoint plus the configured API key. The key comes
377
+ * from core's module state (`setYarrowApiKey`) — `YarrowMapView` calls it for
378
+ * you; standalone callers must set it first.
379
+ */
380
+ function buildStyleUrl(styleType, theme = "light") {
381
+ const endpoint = buildStyleEndpoint(normalizeStyleType(styleType), theme);
382
+ return addApiKeyToUrl(`${YARROW_MAP_URL}${endpoint}`);
383
+ }
384
+
385
+ // src/maps/YarrowMapView.tsx
386
+ /**
387
+ * React Native Yarrow map. Renders MapLibre Native with a Yarrow style URL
388
+ * (theme + styleType aware, API key attached) and a default camera.
389
+ *
390
+ * ```tsx
391
+ * const mapRef = useRef<MapRef>(null);
392
+ * <YarrowMapView
393
+ * apiKey="YOUR_API_KEY"
394
+ * center={[69.2401, 41.2995]} // Tashkent
395
+ * zoom={12}
396
+ * theme="dark"
397
+ * onReady={(map) => map.getCenter().then(console.log)}
398
+ * />
399
+ * ```
400
+ *
401
+ * Camera props (`center`, `zoom`) apply only on mount — recenter through
402
+ * `cameraRef` (`flyTo`, `jumpTo`, `fitBounds`). Theme and styleType changes
403
+ * hot-swap the style URL natively.
404
+ */
405
+ const YarrowMapView = forwardRef(({ apiKey, center, zoom, minZoom, maxZoom, theme, styleType, onReady, onLoadError, onPress, cameraRef, attribution = true, logo = true, compass = true, dauTracking = true, style, children }, ref) => {
406
+ const config = useMemo(() => new YarrowMapConfig({
407
+ apiKey,
408
+ center,
409
+ zoom,
410
+ minZoom,
411
+ maxZoom,
412
+ theme,
413
+ styleType
414
+ }), [
415
+ apiKey,
416
+ center,
417
+ zoom,
418
+ minZoom,
419
+ maxZoom,
420
+ theme,
421
+ styleType
422
+ ]);
423
+ const readyRef = useRef(onReady);
424
+ readyRef.current = onReady;
425
+ const dauTrackedRef = useRef(false);
426
+ const mapRef = useRef(null);
427
+ const mapStyle = useMemo(() => {
428
+ setYarrowApiKey(config.apiKey);
429
+ return buildStyleUrl(config.styleType, config.theme);
430
+ }, [config]);
431
+ const handleDidFinishLoadingMap = useCallback(() => {
432
+ if (dauTracking && !dauTrackedRef.current) {
433
+ dauTrackedRef.current = true;
434
+ trackDau(config.apiKey, "react-native");
435
+ }
436
+ const map = mapRef.current;
437
+ if (map) readyRef.current?.(map);
438
+ }, [config.apiKey, dauTracking]);
439
+ const handleDidFailLoadingMap = useCallback(() => {
440
+ onLoadError?.(/* @__PURE__ */ new Error("Yarrow map failed to load — check the API key/network."));
441
+ }, [onLoadError]);
442
+ return /* @__PURE__ */ jsxs(Map$1, {
443
+ ref: (instance) => {
444
+ mapRef.current = instance;
445
+ if (typeof ref === "function") ref(instance);
446
+ else if (ref) ref.current = instance;
447
+ },
448
+ mapStyle,
449
+ style,
450
+ attribution,
451
+ logo,
452
+ compass,
453
+ onPress,
454
+ onDidFinishLoadingMap: handleDidFinishLoadingMap,
455
+ onDidFailLoadingMap: handleDidFailLoadingMap,
456
+ children: [/* @__PURE__ */ jsx(Camera, {
457
+ ref: cameraRef,
458
+ initialViewState: {
459
+ center: config.center,
460
+ zoom: config.zoom
461
+ },
462
+ minZoom: config.minZoom,
463
+ maxZoom: config.maxZoom
464
+ }), children]
465
+ });
466
+ });
467
+
468
+ // src/maps/routing/types.ts
469
+ /** Best-route + alternatives palette — same values as the web SDK's
470
+ * `buildRoute()` defaults (index 0 is the best route). */
471
+ const ROUTE_LAYER_COLORS = [
472
+ "#22c55e",
473
+ "#aaaaaa",
474
+ "#cccccc",
475
+ "#dddddd",
476
+ "#eeeeee"
477
+ ];
478
+
479
+ // src/maps/routing/RouteLayer.tsx
480
+ const DEFAULT_LAYER_PREFIX = "yarrow-route";
481
+ const toFeatureCollection = (route) => ({
482
+ type: "FeatureCollection",
483
+ features: [route]
484
+ });
485
+ /**
486
+ * Declarative route rendering: one GeoJSON source + line layer per route.
487
+ * Compose inside `<YarrowMapView>` and drive it with `useYarrowRouting()`:
488
+ *
489
+ * ```tsx
490
+ * const { routes } = useYarrowRouting();
491
+ * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
492
+ * <RouteLayer routes={routes} onPressRoute={…} />
493
+ * </YarrowMapView>
494
+ * ```
495
+ */
496
+ const RouteLayer = memo(function RouteLayer({ routes, bestIndex = 0, routeColor = ROUTE_LAYER_COLORS[0], routeWidth = 5, routeOpacity = 1, alternativeColor, alternativeWidth = 2.5, alternativeOpacity = .5, layerPrefix = DEFAULT_LAYER_PREFIX, onPressRoute }) {
497
+ return routes.map((route, index) => {
498
+ const isBest = index === bestIndex;
499
+ const sourceId = `${layerPrefix}-${index}`;
500
+ const color = isBest ? routeColor : alternativeColor ?? ROUTE_LAYER_COLORS[index % ROUTE_LAYER_COLORS.length];
501
+ const width = isBest ? routeWidth : alternativeWidth;
502
+ const opacity = isBest ? routeOpacity : alternativeOpacity;
503
+ return /* @__PURE__ */ jsx(GeoJSONSource, {
504
+ id: sourceId,
505
+ data: toFeatureCollection(route),
506
+ onPress: onPressRoute ? (event) => onPressRoute(event, index) : void 0,
507
+ children: /* @__PURE__ */ jsx(Layer, {
508
+ id: `${layerPrefix}-line-${index}`,
509
+ type: "line",
510
+ layout: {
511
+ "line-cap": "round",
512
+ "line-join": "round"
513
+ },
514
+ paint: {
515
+ "line-color": color,
516
+ "line-width": width,
517
+ "line-opacity": opacity
518
+ }
519
+ })
520
+ }, sourceId);
521
+ });
522
+ });
523
+
524
+ // src/hooks/useYarrowSearch.ts
525
+ /**
526
+ * Debounced, abortable search against the Yarrow search API.
527
+ *
528
+ * Requires the API key to be configured (`YarrowMapView` does this on mount;
529
+ * otherwise call `setYarrowApiKey()` first).
530
+ *
531
+ * ```tsx
532
+ * const { results, isLoading } = useYarrowSearch(query, {
533
+ * lat: position?.lat ?? 41.2995,
534
+ * lon: position?.lng ?? 69.2401,
535
+ * });
536
+ * ```
537
+ */
538
+ const useYarrowSearch = (query, options) => {
539
+ const { lat, lon, page = 1, pageSize = 15, debounceMs = 300, enabled = true } = options;
540
+ const [results, setResults] = useState([]);
541
+ const [isLoading, setIsLoading] = useState(false);
542
+ const [error, setError] = useState(null);
543
+ const latestRequestRef = useRef(0);
544
+ useEffect(() => {
545
+ const trimmed = query.trim();
546
+ if (!enabled || trimmed.length === 0) {
547
+ latestRequestRef.current += 1;
548
+ setResults([]);
549
+ setError(null);
550
+ setIsLoading(false);
551
+ return;
552
+ }
553
+ const controller = new AbortController();
554
+ const requestId = ++latestRequestRef.current;
555
+ setIsLoading(true);
556
+ const timeout = setTimeout(() => {
557
+ fetchSearchResults(trimmed, {
558
+ lat,
559
+ lon,
560
+ page,
561
+ pageSize,
562
+ signal: controller.signal
563
+ }).then((resolved) => {
564
+ if (latestRequestRef.current === requestId) {
565
+ setResults(resolved);
566
+ setError(null);
567
+ }
568
+ }).catch((caught) => {
569
+ if (controller.signal.aborted) return;
570
+ if (latestRequestRef.current === requestId) setError(caught instanceof Error ? caught : new Error(String(caught)));
571
+ }).finally(() => {
572
+ if (latestRequestRef.current === requestId) setIsLoading(false);
573
+ });
574
+ }, debounceMs);
575
+ return () => {
576
+ clearTimeout(timeout);
577
+ controller.abort();
578
+ };
579
+ }, [
580
+ query,
581
+ enabled,
582
+ lat,
583
+ lon,
584
+ page,
585
+ pageSize,
586
+ debounceMs
587
+ ]);
588
+ return {
589
+ results,
590
+ isLoading,
591
+ error
592
+ };
593
+ };
594
+
595
+ // src/hooks/useYarrowRouting.ts
596
+ /**
597
+ * Headless routing state for the Yarrow routing API — pairs with
598
+ * `<RouteLayer>` for rendering.
599
+ *
600
+ * ```tsx
601
+ * const { routes, isLoading, buildRoute } = useYarrowRouting({ profile: 'driving' });
602
+ * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
603
+ * <RouteLayer routes={routes} />
604
+ * </YarrowMapView>
605
+ * ```
606
+ */
607
+ const useYarrowRouting = (options = {}) => {
608
+ const { profile = "driving", language } = options;
609
+ const [result, setResult] = useState(null);
610
+ const [isLoading, setIsLoading] = useState(false);
611
+ const [error, setError] = useState(null);
612
+ const latestRequestRef = useRef(0);
613
+ const buildRoute = useCallback(async (input) => {
614
+ const requestId = ++latestRequestRef.current;
615
+ setIsLoading(true);
616
+ setError(null);
617
+ try {
618
+ const resolved = await fetchRoutes({
619
+ profile: input.profile ?? profile,
620
+ coordinates: input.coordinates,
621
+ language: input.language ?? language,
622
+ signal: input.signal
623
+ });
624
+ if (latestRequestRef.current === requestId) setResult(resolved);
625
+ return resolved;
626
+ } catch (caught) {
627
+ if (latestRequestRef.current === requestId) setError(caught instanceof Error ? caught : new Error(String(caught)));
628
+ throw caught;
629
+ } finally {
630
+ if (latestRequestRef.current === requestId) setIsLoading(false);
631
+ }
632
+ }, [profile, language]);
633
+ const clearRoutes = useCallback(() => {
634
+ latestRequestRef.current += 1;
635
+ setResult(null);
636
+ setError(null);
637
+ setIsLoading(false);
638
+ }, []);
639
+ return {
640
+ routes: result?.features ?? [],
641
+ directions: result?.directions ?? [],
642
+ meta: result?.meta ?? null,
643
+ isLoading,
644
+ error,
645
+ buildRoute,
646
+ clearRoutes
647
+ };
648
+ };
649
+
650
+ // src/offline/estimate.ts
651
+ /**
652
+ * Web-Mercator latitude limit — tiles outside it don't exist.
653
+ */
654
+ const MAX_LAT = 85.05112878;
655
+ /**
656
+ * Rough bytes per downloaded `z/x/y` tile, empirically measured from a
657
+ * Tashkent z14 tile: ≈64 KB × ~8 sources carrying data ≈ 0.5 MB. A region's
658
+ * true size depends on the style's source count and local data density —
659
+ * pass `avgTileBytes` for a tighter estimate.
660
+ */
661
+ const AVG_TILE_BYTES = 5e5;
662
+ /**
663
+ * Bounds must not cross the antimeridian — `west < east` strictly. Regions
664
+ * spanning ±180° need two downloads or a shifted projection.
665
+ */
666
+ const validateBounds = (bounds) => {
667
+ if (!Array.isArray(bounds) || bounds.length !== 4 || !bounds.every((value) => typeof value === "number" && Number.isFinite(value))) throw new Error("bounds must be [west, south, east, north] with four finite numbers");
668
+ const [west, south, east, north] = bounds;
669
+ if (west < -180 || west > 180 || east < -180 || east > 180) throw new Error("bounds longitudes must be within [-180, 180]");
670
+ if (south < -85.05112878 || south > MAX_LAT || north < -85.05112878 || north > MAX_LAT) throw new Error(`bounds latitudes must be within [-85.05112878, ${MAX_LAT}]`);
671
+ if (west >= east) throw new Error("bounds west longitude must be less than east");
672
+ if (south >= north) throw new Error("bounds south latitude must be less than north");
673
+ };
674
+ const validateZoomRange = (minZoom, maxZoom) => {
675
+ if (!Number.isFinite(minZoom) || !Number.isFinite(maxZoom) || minZoom < 0 || maxZoom > 22 || minZoom > maxZoom) throw new Error("zoom range must satisfy 0 <= minZoom <= maxZoom <= 22");
676
+ };
677
+ const lngToWorldX = (lng, zoom) => {
678
+ return (Math.min(180, Math.max(-180, lng)) + 180) / 360 * 2 ** zoom;
679
+ };
680
+ const latToWorldY = (lat, zoom) => {
681
+ const radians = Math.min(MAX_LAT, Math.max(-85.05112878, lat)) * Math.PI / 180;
682
+ return (1 - Math.log(Math.tan(radians) + 1 / Math.cos(radians)) / Math.PI) / 2 * 2 ** zoom;
683
+ };
684
+ /** Unique `z/x/y` tiles covering the bounds at one zoom level. */
685
+ const countTilesAtZoom = (bounds, zoom) => {
686
+ const [west, south, east, north] = bounds;
687
+ const maxTile = 2 ** zoom - 1;
688
+ const clamp = (index) => Math.min(maxTile, Math.max(0, index));
689
+ const x0 = clamp(Math.floor(lngToWorldX(west, zoom)));
690
+ const x1 = clamp(Math.floor(lngToWorldX(east, zoom)));
691
+ const y0 = clamp(Math.floor(latToWorldY(north, zoom)));
692
+ const y1 = clamp(Math.floor(latToWorldY(south, zoom)));
693
+ return (x1 - x0 + 1) * (y1 - y0 + 1);
694
+ };
695
+ /**
696
+ * Estimates the download/storage cost of an offline region — pure tile math,
697
+ * no native calls. Tile counts are exact for the XYZ scheme; byte estimates
698
+ * are rough (see `AVG_TILE_BYTES`).
699
+ *
700
+ * ```ts
701
+ * const { tileCount, estSizeBytes } = estimateRegion({
702
+ * bounds: [69.15, 41.2, 69.4, 41.4], // Tashkent
703
+ * minZoom: 8,
704
+ * maxZoom: 15,
705
+ * });
706
+ * ```
707
+ */
708
+ const estimateRegion = (input) => {
709
+ validateBounds(input.bounds);
710
+ const { bounds, avgTileBytes = AVG_TILE_BYTES, minZoom, maxZoom } = input;
711
+ validateZoomRange(minZoom, maxZoom);
712
+ const tilesPerLevel = [];
713
+ let tileCount = 0;
714
+ for (let zoom = Math.floor(minZoom); zoom <= Math.ceil(maxZoom); zoom++) {
715
+ const tiles = countTilesAtZoom(bounds, zoom);
716
+ tilesPerLevel.push({
717
+ zoom,
718
+ tiles
719
+ });
720
+ tileCount += tiles;
721
+ }
722
+ return {
723
+ tileCount,
724
+ estSizeBytes: tileCount * avgTileBytes,
725
+ tilesPerLevel
726
+ };
727
+ };
728
+
729
+ // src/offline/types.ts
730
+ /** Default minimum zoom for offline regions. */
731
+ const DEFAULT_OFFLINE_MIN_ZOOM = 8;
732
+ /** Default maximum zoom for offline regions. */
733
+ const DEFAULT_OFFLINE_MAX_ZOOM = 15;
734
+ /** Schema version of the pack metadata this SDK writes. */
735
+ const OFFLINE_METADATA_VERSION = 1;
736
+
737
+ // src/offline/manager.ts
738
+ const DAY_MS = MILLISECONDS_PER_DAY;
739
+ const stripId = (status) => {
740
+ const { id: _id, ...progress } = status;
741
+ return progress;
742
+ };
743
+ /** Reads pack status, treating bridge-level absence (Android resolves null
744
+ * for unknown ids — e.g. after `resetDatabase` without an app restart) as
745
+ * `null` instead of a crash. */
746
+ const statusOrNull = async (pack) => {
747
+ try {
748
+ return await pack.status() ?? null;
749
+ } catch {
750
+ return null;
751
+ }
752
+ };
753
+ const notFoundError = (name, regionId) => {
754
+ const error = /* @__PURE__ */ new Error(`Offline region "${name}" is no longer available natively — resetDatabase() requires an app restart to clear the JS cache.`);
755
+ error.code = "not-found";
756
+ error.regionId = regionId;
757
+ return error;
758
+ };
759
+ const asYarrowMetadata = (pack) => {
760
+ const meta = pack.metadata;
761
+ if (!meta || meta.v !== 1 || typeof meta.name !== "string") return null;
762
+ return meta;
763
+ };
764
+ const classifyError = (raw, regionId) => {
765
+ const message = raw instanceof Error ? raw.message : typeof raw === "string" ? raw : "Unknown offline error";
766
+ let code = "unknown";
767
+ if (/tile (count )?limit|tile limit exceeded/i.test(message)) code = "tile-count-limit-exceeded";
768
+ else if (/too large|region exceeds/i.test(message)) code = "region-too-large";
769
+ else if (/disk|storage|space/i.test(message)) code = "disk";
770
+ else if (/not\s*found/i.test(message)) code = "not-found";
771
+ else if (/network|connection|offline|unreachable|timeout|resolve|host/i.test(message)) code = "network";
772
+ const error = new Error(message);
773
+ error.code = code;
774
+ if (regionId) error.regionId = regionId;
775
+ return error;
776
+ };
777
+ /**
778
+ * Offline region manager for React Native — a Yarrow-flavoured wrapper around
779
+ * MapLibre React Native's `OfflineManager`.
780
+ *
781
+ * The web SDK's `yarrowcache` protocol cannot exist on native (no
782
+ * `addProtocol`), so offline support here is region packs: pick a bounding
783
+ * box and zoom range, download it once, and the map renders from the native
784
+ * offline database with no network.
785
+ *
786
+ * ```ts
787
+ * const offline = new YarrowOfflineManager({ apiKey: 'YOUR_API_KEY' });
788
+ * const { tileCount, estSizeBytes } = offline.estimateRegion({
789
+ * bounds: [69.15, 41.2, 69.4, 41.4], // Tashkent
790
+ * minZoom: 8,
791
+ * maxZoom: 15,
792
+ * });
793
+ * const region = await offline.downloadRegion({
794
+ * name: 'tashkent-city',
795
+ * bounds: [69.15, 41.2, 69.4, 41.4],
796
+ * maxAgeDays: 30,
797
+ * onProgress: (p) => console.log(`${p.percentage}%`),
798
+ * });
799
+ * await region.done;
800
+ * ```
801
+ */
802
+ var YarrowOfflineManager = class {
803
+ constructor(options) {
804
+ this.activeDownloads = /* @__PURE__ */ new Map();
805
+ if (!options.apiKey) throw new Error("apiKey is required");
806
+ this.apiKey = options.apiKey;
807
+ setYarrowApiKey(this.apiKey);
808
+ }
809
+ /**
810
+ * Pure tile-math estimate of a region's download/storage cost — no native
811
+ * calls. See `estimateRegion` for the math and caveats.
812
+ */
813
+ estimateRegion(input) {
814
+ return estimateRegion(input);
815
+ }
816
+ /**
817
+ * Starts (or resumes) a region download. Resolves with a handle once the
818
+ * pack is created and downloading — progress arrives via `options.onProgress`
819
+ * and `handle.done` settles with the outcome.
820
+ *
821
+ * Idempotent by `name`: an existing matching region is returned as-is
822
+ * (resumed when incomplete); a name reused with different parameters throws
823
+ * a `params-mismatch` error. Pass `force: true` to delete and re-download.
824
+ */
825
+ async downloadRegion(options) {
826
+ const name = options.name?.trim();
827
+ if (!name) throw new Error("name is required");
828
+ const bounds = options.bounds;
829
+ validateBounds(bounds);
830
+ const minZoom = options.minZoom ?? 8;
831
+ const maxZoom = options.maxZoom ?? 15;
832
+ validateZoomRange(minZoom, maxZoom);
833
+ const styleType = normalizeStyleType(options.styleType);
834
+ const theme = options.theme === "dark" ? "dark" : "light";
835
+ await this.hydrate();
836
+ const existing = await this.findRegionPacks(name);
837
+ const target = existing.find((pack) => pack.meta.styleType === styleType && pack.meta.theme === theme);
838
+ if (target && !options.force) {
839
+ const mismatches = this.findParamMismatches(target.meta, {
840
+ bounds,
841
+ minZoom,
842
+ maxZoom,
843
+ maxAgeDays: options.maxAgeDays ?? null
844
+ });
845
+ if (mismatches.length > 0) {
846
+ const error = /* @__PURE__ */ new Error(`Region "${name}" already exists with different ${mismatches.join(", ")}. Use a different name or pass force: true to re-download.`);
847
+ error.code = "params-mismatch";
848
+ error.regionId = target.pack.id;
849
+ throw error;
850
+ }
851
+ return this.reattachExisting(target, { resumeIfIncomplete: true });
852
+ }
853
+ if (existing.length > 0 && !options.force) {
854
+ const styles = existing.map(({ meta }) => `${meta.styleType}/${meta.theme}`).join(", ");
855
+ const error = /* @__PURE__ */ new Error(`Region "${name}" is pinned to ${styles}. Use a different name or pass force: true to replace it.`);
856
+ error.code = "params-mismatch";
857
+ throw error;
858
+ }
859
+ for (const { pack } of existing) await this.deletePack(pack.id);
860
+ setYarrowApiKey(this.apiKey);
861
+ const metadata = {
862
+ v: 1,
863
+ name,
864
+ styleType,
865
+ theme,
866
+ bounds,
867
+ minZoom,
868
+ maxZoom,
869
+ maxAgeDays: options.maxAgeDays ?? null,
870
+ createdAt: Date.now(),
871
+ ...options.metadata ? { user: options.metadata } : {}
872
+ };
873
+ let settle = () => {};
874
+ const done = new Promise((resolve, reject) => {
875
+ settle = ({ progress, error }) => {
876
+ if (error) reject(error);
877
+ else if (progress) resolve(progress);
878
+ };
879
+ });
880
+ const routeProgress = (_pack, status) => {
881
+ const progress = stripId(status);
882
+ if (status.state === "complete") {
883
+ this.activeDownloads.delete(_pack.id);
884
+ settle({ progress });
885
+ } else options.onProgress?.(progress);
886
+ };
887
+ const routeError = (_pack, raw) => {
888
+ this.activeDownloads.delete(_pack.id);
889
+ const error = classifyError(raw.message, _pack.id);
890
+ options.onError?.(error);
891
+ settle({ error });
892
+ };
893
+ try {
894
+ const pack = await OfflineManager.createPack({
895
+ mapStyle: buildStyleUrl(styleType, theme),
896
+ bounds,
897
+ minZoom,
898
+ maxZoom,
899
+ metadata
900
+ }, routeProgress, routeError);
901
+ this.activeDownloads.set(pack.id, { done });
902
+ const status = await statusOrNull(pack);
903
+ if (status?.state === "complete") {
904
+ OfflineManager.removeListener(pack.id);
905
+ this.activeDownloads.delete(pack.id);
906
+ settle({ progress: stripId(status) });
907
+ }
908
+ return this.toHandle(pack, metadata, done);
909
+ } catch (caught) {
910
+ throw classifyError(caught);
911
+ }
912
+ }
913
+ /** Lists regions created through this SDK (native packs created directly
914
+ * against `OfflineManager` are not included), newest first. */
915
+ async listRegions() {
916
+ const packs = await OfflineManager.getPacks();
917
+ const summaries = [];
918
+ for (const pack of packs) {
919
+ const meta = asYarrowMetadata(pack);
920
+ if (!meta) continue;
921
+ const status = await statusOrNull(pack);
922
+ if (!status) continue;
923
+ summaries.push({
924
+ id: pack.id,
925
+ name: meta.name,
926
+ styleType: meta.styleType,
927
+ theme: meta.theme,
928
+ bounds: meta.bounds,
929
+ minZoom: meta.minZoom,
930
+ maxZoom: meta.maxZoom,
931
+ status: status.state,
932
+ percentage: status.percentage,
933
+ completedTileSize: status.completedTileSize,
934
+ userMetadata: meta.user,
935
+ isStale: meta.maxAgeDays !== null && Date.now() - meta.createdAt > meta.maxAgeDays * DAY_MS,
936
+ createdAt: meta.createdAt
937
+ });
938
+ }
939
+ return summaries.sort((a, b) => b.createdAt - a.createdAt);
940
+ }
941
+ /** Returns the handle for a region by name, or `null`. */
942
+ async getRegion(name) {
943
+ const entry = (await this.findRegionPacks(name.trim()))[0];
944
+ if (!entry) return null;
945
+ return this.reattachExisting(entry);
946
+ }
947
+ /** Ambient cache (seen-tiles LRU) max size in bytes. May erase resources
948
+ * when shrinking — call once at app startup. `0` disables the cache. */
949
+ async setAmbientCacheSize(size) {
950
+ await OfflineManager.setMaximumAmbientCacheSize(size);
951
+ }
952
+ /** Revalidates ambient-cache tiles against the server — the recommended
953
+ * way to refresh cached data. */
954
+ async invalidateAmbientCache() {
955
+ await OfflineManager.invalidateAmbientCache();
956
+ }
957
+ /** Erases ambient-cache resources. Computationally expensive. */
958
+ async clearAmbientCache() {
959
+ await OfflineManager.clearAmbientCache();
960
+ }
961
+ /** Maximum number of tiles offline packs may store. Raise it when large
962
+ * regions fail with a `tile-count-limit-exceeded` error. */
963
+ setTileCountLimit(limit) {
964
+ OfflineManager.setTileCountLimit(limit);
965
+ }
966
+ /** Download status event throttle in ms. Platform-defined default (300 ms
967
+ * today on both iOS and Android). Note errors bypass the throttle. */
968
+ setProgressEventThrottle(ms) {
969
+ OfflineManager.setProgressEventThrottle(ms);
970
+ }
971
+ /** Deletes the offline database (ambient cache + packs), then
972
+ * reinitializes it. Destructive — and MLRN's JS pack cache only clears
973
+ * on app restart, so subsequent reads may hit stale ids (guarded as
974
+ * `not-found`). Prefer per-region `invalidate`/`delete`. */
975
+ async resetDatabase() {
976
+ await OfflineManager.resetDatabase();
977
+ }
978
+ async hydrate() {
979
+ await OfflineManager.getPacks();
980
+ }
981
+ async findRegionPacks(name) {
982
+ return (await OfflineManager.getPacks()).map((pack) => ({
983
+ pack,
984
+ meta: asYarrowMetadata(pack)
985
+ })).filter((entry) => entry.meta !== null && entry.meta.name === name);
986
+ }
987
+ findParamMismatches(meta, params) {
988
+ const mismatches = [];
989
+ if (!(meta.bounds.length === params.bounds.length && meta.bounds.every((value, index) => value === params.bounds[index]))) mismatches.push("bounds");
990
+ if (meta.minZoom !== params.minZoom) mismatches.push("minZoom");
991
+ if (meta.maxZoom !== params.maxZoom) mismatches.push("maxZoom");
992
+ if (meta.maxAgeDays !== params.maxAgeDays) mismatches.push("maxAgeDays");
993
+ return mismatches;
994
+ }
995
+ /** Attaches listeners to a pack that may have outlived the JS layer
996
+ * (created in a previous app session) and builds a fresh handle.
997
+ *
998
+ * Deliberately cautious: it never hijacks a download this session owns,
999
+ * never attaches listeners to packs that don't need them, and — on
1000
+ * Android, where attaching an observer *activates* the region — never
1001
+ * wakes a paused pack unless the caller explicitly asked for a download. */
1002
+ async reattachExisting(entry, { resumeIfIncomplete = false } = {}) {
1003
+ const { pack, meta } = entry;
1004
+ const known = this.activeDownloads.get(pack.id);
1005
+ if (known) return this.toHandle(pack, meta, known.done);
1006
+ const status = await statusOrNull(pack);
1007
+ if (!status) throw notFoundError(meta.name, pack.id);
1008
+ if (status.state === "complete") return this.toHandle(pack, meta, Promise.resolve(stripId(status)));
1009
+ let settle = () => {};
1010
+ const done = new Promise((resolve, reject) => {
1011
+ settle = ({ progress, error }) => {
1012
+ if (error) reject(error);
1013
+ else if (progress) resolve(progress);
1014
+ };
1015
+ });
1016
+ const routeProgress = (_pack, progressEvent) => {
1017
+ if (progressEvent.state === "complete") settle({ progress: stripId(progressEvent) });
1018
+ };
1019
+ const routeError = (_pack, raw) => {
1020
+ settle({ error: classifyError(raw.message, pack.id) });
1021
+ };
1022
+ if (status.state === "active" || resumeIfIncomplete) {
1023
+ OfflineManager.addListener(pack.id, routeProgress, routeError);
1024
+ if (status.state !== "active") await pack.resume();
1025
+ }
1026
+ return this.toHandle(pack, meta, done);
1027
+ }
1028
+ toHandle(pack, meta, done) {
1029
+ return {
1030
+ id: pack.id,
1031
+ name: meta.name,
1032
+ done,
1033
+ refreshStatus: async () => {
1034
+ const status = await statusOrNull(pack);
1035
+ if (!status) throw notFoundError(meta.name, pack.id);
1036
+ return stripId(status);
1037
+ },
1038
+ pause: () => pack.pause(),
1039
+ resume: () => pack.resume(),
1040
+ invalidate: async () => {
1041
+ await OfflineManager.invalidatePack(pack.id);
1042
+ },
1043
+ delete: async () => {
1044
+ await this.deletePack(pack.id);
1045
+ }
1046
+ };
1047
+ }
1048
+ async deletePack(id) {
1049
+ try {
1050
+ await OfflineManager.deletePack(id);
1051
+ } catch (caught) {
1052
+ throw classifyError(caught, id);
1053
+ } finally {
1054
+ this.activeDownloads.delete(id);
1055
+ }
1056
+ }
1057
+ };
1058
+
1059
+ // src/offline/hook.ts
1060
+ /**
1061
+ * Offline region state for settings/offline screens — pairs with
1062
+ * `YarrowOfflineManager`. Polls the native layer while downloads run, so
1063
+ * `regions` (and progress bars) stay current.
1064
+ *
1065
+ * ```tsx
1066
+ * const { regions, download, remove } = useYarrowOfflineRegions({ apiKey });
1067
+ * await download({ name: 'tashkent', bounds: [69.15, 41.2, 69.4, 41.4] });
1068
+ * ```
1069
+ */
1070
+ const useYarrowOfflineRegions = (options) => {
1071
+ const { apiKey, pollMs = 1e3 } = options;
1072
+ const [regions, setRegions] = useState([]);
1073
+ const [isLoading, setIsLoading] = useState(true);
1074
+ const [error, setError] = useState(null);
1075
+ const managerRef = useRef(null);
1076
+ const getManager = useCallback(() => {
1077
+ const cached = managerRef.current;
1078
+ if (cached && cached.key === apiKey) return cached.manager;
1079
+ const manager = new YarrowOfflineManager({ apiKey });
1080
+ managerRef.current = {
1081
+ key: apiKey,
1082
+ manager
1083
+ };
1084
+ return manager;
1085
+ }, [apiKey]);
1086
+ const recordError = useCallback((caught) => {
1087
+ const error = caught instanceof Error ? caught : new Error(String(caught));
1088
+ setError(error);
1089
+ return error;
1090
+ }, []);
1091
+ const refresh = useCallback(async () => {
1092
+ try {
1093
+ setRegions(await getManager().listRegions());
1094
+ setError(null);
1095
+ } catch (caught) {
1096
+ recordError(caught);
1097
+ }
1098
+ }, [getManager, recordError]);
1099
+ useEffect(() => {
1100
+ if (!apiKey) {
1101
+ setIsLoading(false);
1102
+ return;
1103
+ }
1104
+ let cancelled = false;
1105
+ (async () => {
1106
+ setIsLoading(true);
1107
+ try {
1108
+ const summaries = await getManager().listRegions();
1109
+ if (!cancelled) {
1110
+ setRegions(summaries);
1111
+ setError(null);
1112
+ }
1113
+ } catch (caught) {
1114
+ if (!cancelled) recordError(caught);
1115
+ } finally {
1116
+ if (!cancelled) setIsLoading(false);
1117
+ }
1118
+ })();
1119
+ return () => {
1120
+ cancelled = true;
1121
+ };
1122
+ }, [
1123
+ apiKey,
1124
+ getManager,
1125
+ recordError
1126
+ ]);
1127
+ const hasActive = regions.some((region) => region.status === "active");
1128
+ useEffect(() => {
1129
+ if (!hasActive) return;
1130
+ const timer = setInterval(() => {
1131
+ refresh();
1132
+ }, pollMs);
1133
+ return () => clearInterval(timer);
1134
+ }, [
1135
+ hasActive,
1136
+ pollMs,
1137
+ refresh
1138
+ ]);
1139
+ const download = useCallback(async (downloadOptions) => {
1140
+ try {
1141
+ const handle = await getManager().downloadRegion(downloadOptions);
1142
+ await refresh();
1143
+ return handle;
1144
+ } catch (caught) {
1145
+ throw recordError(caught);
1146
+ }
1147
+ }, [
1148
+ getManager,
1149
+ recordError,
1150
+ refresh
1151
+ ]);
1152
+ const withRegion = useCallback(async (name, run) => {
1153
+ try {
1154
+ const handle = await getManager().getRegion(name.trim());
1155
+ if (!handle) {
1156
+ const error = /* @__PURE__ */ new Error(`Offline region "${name}" not found`);
1157
+ error.code = "not-found";
1158
+ throw error;
1159
+ }
1160
+ await run(handle);
1161
+ await refresh();
1162
+ } catch (caught) {
1163
+ throw recordError(caught);
1164
+ }
1165
+ }, [
1166
+ getManager,
1167
+ recordError,
1168
+ refresh
1169
+ ]);
1170
+ return {
1171
+ regions,
1172
+ isLoading,
1173
+ error,
1174
+ refresh,
1175
+ download,
1176
+ pause: (name) => withRegion(name, (handle) => handle.pause()),
1177
+ resume: (name) => withRegion(name, (handle) => handle.resume()),
1178
+ invalidate: (name) => withRegion(name, (handle) => handle.invalidate()),
1179
+ remove: (name) => withRegion(name, (handle) => handle.delete())
1180
+ };
1181
+ };
1182
+
1183
+ // src/utils/userToken.ts
1184
+ /**
1185
+ * Bridges the async AsyncStorage API onto core's synchronous TokenStorage
1186
+ * contract: the existing token hydrates into memory once, reads are served
1187
+ * synchronously from that cache, and writes mirror in-memory before flushing
1188
+ * to AsyncStorage (fire-and-forget).
1189
+ *
1190
+ * If the initial read throws, the override is left unset entirely: core then
1191
+ * degrades to ephemeral tokens *without persisting anything*, so a transient
1192
+ * read failure can never overwrite the stored identity with a fresh token.
1193
+ *
1194
+ * Await this once during app startup, before the first map or tracking call
1195
+ * (tokens generated before this resolves are ephemeral by design):
1196
+ *
1197
+ * ```ts
1198
+ * import AsyncStorage from '@react-native-async-storage/async-storage';
1199
+ * import { setAsyncStorageTokenStorage } from '@yarrow-uz/rn-map-sdk';
1200
+ *
1201
+ * await setAsyncStorageTokenStorage(AsyncStorage);
1202
+ * ```
1203
+ */
1204
+ async function setAsyncStorageTokenStorage(storage) {
1205
+ let existing;
1206
+ try {
1207
+ existing = await storage.getItem(USER_TOKEN_STORAGE_KEY);
1208
+ } catch {
1209
+ return;
1210
+ }
1211
+ const cache = /* @__PURE__ */ new Map();
1212
+ if (existing) cache.set(USER_TOKEN_STORAGE_KEY, existing);
1213
+ setTokenStorage({
1214
+ getItem: (key) => cache.get(key) ?? null,
1215
+ setItem: (key, value) => {
1216
+ cache.set(key, value);
1217
+ Promise.resolve(storage.setItem(key, value)).catch(() => {});
1218
+ }
1219
+ });
1220
+ }
1221
+
1222
+ export { AVG_TILE_BYTES, CACHED_AT_HEADER, CACHE_PROTOCOL, DEFAULT_CACHE_LIFESPAN_DAYS, DEFAULT_OFFLINE_MAX_ZOOM, DEFAULT_OFFLINE_MIN_ZOOM, ICON_CACHE_NAME, MILLISECONDS_PER_DAY, OFFLINE_METADATA_VERSION, ROUTE_API_URL, RouteLayer, TILE_CACHE_NAME, USER_TOKEN_STORAGE_KEY, YARROW_MAP_URL, YARROW_SEARCH_API_URL, YarrowMapConfig, YarrowMapView, YarrowOfflineManager, addApiKeyToUrl, buildStyleEndpoint, buildStyleUrl, estimateRegion, fetchArrayBufferWithCache, fetchRoutes, fetchSearchResults, getOrCreateUserToken, getYarrowApiKey, hasCacheStorage, haversineDistance, normalizeStyleType, setAsyncStorageTokenStorage, setTokenStorage, setYarrowApiKey, trackDau, transformRouteCoordinates, useYarrowOfflineRegions, useYarrowRouting, useYarrowSearch };