@yarrow-uz/rn-map-sdk 0.4.0 → 0.6.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.
@@ -0,0 +1,3013 @@
1
+ import { Animated, Image, StyleSheet, Text, View } from "react-native";
2
+ import { Camera, GeoJSONSource, Images, Layer, Map as Map$1, Marker, OfflineManager } from "@maplibre/maplibre-react-native";
3
+ import { createContext, forwardRef, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
4
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
+
6
+ // ../core/dist/index.js
7
+ /**
8
+ * Coded error thrown by the Yarrow API clients (routing, search, icon
9
+ * registry, tile cache) in both platform SDKs.
10
+ *
11
+ * Recognizable legacy messages are kept verbatim as the error `message`
12
+ * (`"Request failed: 500 Server Error"`), while `code`/`status`/`url` carry
13
+ * the structured detail. Client-side aborts are NOT wrapped — callers keep
14
+ * receiving the original `AbortError` so cancellation stays distinguishable.
15
+ */
16
+ var YarrowApiError = class extends Error {
17
+ constructor(code, message, options) {
18
+ super(message);
19
+ this.name = "YarrowApiError";
20
+ this.code = code;
21
+ if (options?.status !== void 0) this.status = options.status;
22
+ if (options?.url !== void 0) this.url = options.url;
23
+ if (options?.cause !== void 0) this.cause = options.cause;
24
+ }
25
+ };
26
+ /** Maps an HTTP status to its {@link YarrowApiErrorCode}. 402/403 follow the
27
+ * gateway's documented semantics on metered endpoints (quota/billing and
28
+ * subscription states, not authentication). */
29
+ const errorCodeFromStatus = (status) => {
30
+ if (status === 401) return "unauthorized";
31
+ if (status === 402) return "payment-required";
32
+ if (status === 403) return "forbidden";
33
+ if (status === 404) return "not-found";
34
+ if (status === 429) return "rate-limited";
35
+ return "unknown";
36
+ };
37
+ /**
38
+ * Reads `error.message` out of the API's error envelope
39
+ * (`{ error: { code, message, request_id }, detail }`), tolerating any shape.
40
+ */
41
+ const serverErrorMessageFromBody = (body) => {
42
+ if (typeof body !== "object" || body === null) return void 0;
43
+ const { error } = body;
44
+ if (typeof error !== "object" || error === null) return void 0;
45
+ const { message } = error;
46
+ return typeof message === "string" && message.length > 0 ? message : void 0;
47
+ };
48
+ /**
49
+ * Best-effort read of a response body for error-message extraction. Mocked
50
+ * or opaque responses without a usable `json()` resolve to `undefined`,
51
+ * and parse failures are swallowed — this must never mask the real error.
52
+ */
53
+ const readErrorBody = async (response) => {
54
+ try {
55
+ const json = response.json;
56
+ if (typeof json !== "function") return void 0;
57
+ return await json.call(response);
58
+ } catch {
59
+ return;
60
+ }
61
+ };
62
+ /**
63
+ * Builds the coded error for a non-OK response. The historic
64
+ * `Request failed: <status> <statusText>` message is preserved so existing
65
+ * message-based handling keeps working. HTTP/2 responses carry an empty
66
+ * `statusText`, so the API error envelope's `error.message` (pass the parsed
67
+ * body via `body`) fills in instead — e.g. the routing API's validation
68
+ * errors then read "Request failed: 422 Request validation failed".
69
+ */
70
+ const apiErrorFromResponse = (response) => {
71
+ const detail = response.statusText || serverErrorMessageFromBody(response.body) || "";
72
+ return new YarrowApiError(errorCodeFromStatus(response.status), `Request failed: ${response.status}${detail ? ` ${detail}` : ""}`, {
73
+ status: response.status,
74
+ url: response.url
75
+ });
76
+ };
77
+ const isAbortError = (error) => error instanceof Error && error.name === "AbortError";
78
+ /**
79
+ * Wraps a fetch rejection in a `network` {@link YarrowApiError}. Aborts pass
80
+ * through untouched — cancellation must stay recognizable by name. Values
81
+ * that are already coded errors pass through unchanged.
82
+ */
83
+ const wrapNetworkError = (error, url) => {
84
+ if (isAbortError(error)) return error;
85
+ if (error instanceof YarrowApiError) return error;
86
+ return new YarrowApiError("network", `Network request failed: ${error instanceof Error ? error.message : "Unknown network error"}`, {
87
+ url,
88
+ cause: error
89
+ });
90
+ };
91
+ /**
92
+ * Builds the `invalid-response` error for a response whose shape the SDK
93
+ * cannot interpret, including a short serialized snippet for debugging.
94
+ */
95
+ const invalidResponseError = (what, payload, url) => new YarrowApiError("invalid-response", `Unexpected response from the Yarrow API: ${what} — got: ${responseSnippet(payload)}`, { url });
96
+ /** Short, safe JSON preview of a malformed payload for error messages. */
97
+ const responseSnippet = (payload) => {
98
+ const MAX_LENGTH = 200;
99
+ let text;
100
+ try {
101
+ text = typeof payload === "string" ? payload : JSON.stringify(payload) ?? "";
102
+ } catch {
103
+ text = "[unserializable]";
104
+ }
105
+ return text.length > MAX_LENGTH ? `${text.slice(0, MAX_LENGTH)}…` : text || "[empty]";
106
+ };
107
+ const YARROW_MAP_URL = "https://gis.yarrow.uz";
108
+ const YARROW_SEARCH_API_URL = "https://api.yarrow.uz";
109
+ let _apiKey = null;
110
+ function setYarrowApiKey(apiKey) {
111
+ if (!apiKey) throw new Error("apiKey is required");
112
+ _apiKey = apiKey;
113
+ }
114
+ function getYarrowApiKey() {
115
+ if (!_apiKey) throw new YarrowApiError("unauthorized", "Yarrow API key not configured — pass your key to <YarrowMapView apiKey> (web: YarrowMap config, RN: YarrowMapView prop) or call setYarrowApiKey(\"YOUR_API_KEY\") before using the map SDK.");
116
+ return _apiKey;
117
+ }
118
+ /**
119
+ * Appends the configured API key as the `api_key` query parameter. Deliberately
120
+ * lenient: returns the url unchanged when no key is configured yet or the url
121
+ * cannot be parsed — this is a public utility, and the SDK's own clients
122
+ * (`fetchRoutes`, `fetchSearchResults`, `fetchYarrowIcons`, …) enforce the key
123
+ * at entry via `getYarrowApiKey()` (a coded `unauthorized` error) instead of
124
+ * letting keyless requests hit the server and fail opaquely.
125
+ */
126
+ function addApiKeyToUrl(url) {
127
+ if (!_apiKey) return url;
128
+ try {
129
+ const parsedUrl = new URL(url);
130
+ parsedUrl.searchParams.set("api_key", _apiKey);
131
+ return parsedUrl.toString();
132
+ } catch {
133
+ return url;
134
+ }
135
+ }
136
+ /**
137
+ * Computes the geographic bounding box of a FeatureCollection whose features
138
+ * are Points, LineStrings or Polygons. Pure platform-agnostic math shared by
139
+ * the web and React Native SDKs' camera helpers.
140
+ */
141
+ function getBoundingBox(data) {
142
+ const bounds = {
143
+ xMin: 180,
144
+ yMin: 90,
145
+ xMax: -180,
146
+ yMax: -90
147
+ };
148
+ const checkBounds = (coordinate) => {
149
+ const [longitude, latitude] = coordinate;
150
+ bounds.xMin = Math.min(bounds.xMin, longitude);
151
+ bounds.xMax = Math.max(bounds.xMax, longitude);
152
+ bounds.yMin = Math.min(bounds.yMin, latitude);
153
+ bounds.yMax = Math.max(bounds.yMax, latitude);
154
+ };
155
+ const isLngLat = (value) => Array.isArray(value) && value.length >= 2 && typeof value[0] === "number" && typeof value[1] === "number";
156
+ for (const feature of data.features) {
157
+ const type = feature.geometry?.type;
158
+ const coordinates = feature.geometry?.coordinates;
159
+ if (type === "Point" && isLngLat(coordinates)) checkBounds(coordinates);
160
+ else if (type === "LineString" && Array.isArray(coordinates)) {
161
+ for (const coord of coordinates) if (isLngLat(coord)) checkBounds(coord);
162
+ } else if (type === "Polygon" && Array.isArray(coordinates)) for (const ring of coordinates) {
163
+ if (!Array.isArray(ring)) continue;
164
+ for (const coord of ring) if (isLngLat(coord)) checkBounds(coord);
165
+ }
166
+ }
167
+ return bounds;
168
+ }
169
+ /** Style-API endpoint returning the icon registry (`IconListItem[]`). */
170
+ const ICONS_ENDPOINT = "/icons-image";
171
+ const DEFAULT_CACHE_LIFESPAN_DAYS = 30;
172
+ const MILLISECONDS_PER_DAY = 864e5;
173
+ const TILE_CACHE_NAME = "yarrow-cache-v1-tile";
174
+ const ICON_CACHE_NAME = "yarrow-cache-v1-icon";
175
+ const CACHE_PROTOCOL = "yarrowcache";
176
+ const CACHED_AT_HEADER = "x-yarrow-cached-at";
177
+ const hasCacheStorage = () => typeof globalThis !== "undefined" && typeof globalThis.caches !== "undefined" && typeof globalThis.caches.open === "function";
178
+ const extractCachedAt = (response) => {
179
+ const raw = response.headers.get(CACHED_AT_HEADER);
180
+ if (!raw) return null;
181
+ const parsed = Number(raw);
182
+ return Number.isFinite(parsed) ? parsed : null;
183
+ };
184
+ /**
185
+ * Pulls a `max-age=N` value (in seconds) out of a `Cache-Control` header, if
186
+ * present. Returns `null` when the header is missing or doesn't carry a
187
+ * numeric `max-age`. Returns 0 for `max-age=0` (treat as immediately stale).
188
+ *
189
+ * The Yarrow backend does not currently emit `Cache-Control` headers, so this
190
+ * is dead in production today. It's plumbed in so a future fix on the
191
+ * backend starts being honored without an SDK release.
192
+ */
193
+ const parseMaxAge = (cacheControl) => {
194
+ if (!cacheControl) return null;
195
+ for (const directive of cacheControl.split(",")) {
196
+ const [rawKey, rawValue] = directive.trim().split("=");
197
+ if (rawKey?.toLowerCase() !== "max-age") continue;
198
+ if (rawValue === void 0) return 0;
199
+ const parsed = Number(rawValue);
200
+ return Number.isFinite(parsed) ? parsed : null;
201
+ }
202
+ return null;
203
+ };
204
+ const toCachedArrayBufferResponse = async (response) => {
205
+ return {
206
+ data: await response.arrayBuffer(),
207
+ cacheControl: response.headers.get("cache-control"),
208
+ expires: response.headers.get("expires"),
209
+ contentType: response.headers.get("content-type")
210
+ };
211
+ };
212
+ const fetchFromNetwork = async (url, abortController, requestParameters) => {
213
+ let response;
214
+ try {
215
+ response = await fetch(url, {
216
+ method: requestParameters?.method ?? "GET",
217
+ headers: requestParameters?.headers,
218
+ body: requestParameters?.body,
219
+ credentials: requestParameters?.credentials,
220
+ signal: abortController.signal
221
+ });
222
+ } catch (error) {
223
+ throw wrapNetworkError(error, url);
224
+ }
225
+ if (!response.ok) throw apiErrorFromResponse({
226
+ status: response.status,
227
+ statusText: response.statusText,
228
+ url
229
+ });
230
+ return toCachedArrayBufferResponse(response);
231
+ };
232
+ /**
233
+ * Best-effort LRU eviction for quota errors. Removes the oldest entries (by
234
+ * `x-yarrow-cached-at` header) until the new write fits, or until nothing
235
+ * remains to drop. Silently stops evicting when the cache becomes empty —
236
+ * callers still treat the original quota error as non-fatal.
237
+ */
238
+ const evictOldest = async (cache) => {
239
+ try {
240
+ const keys = await cache.keys();
241
+ if (keys.length === 0) return false;
242
+ let oldestKey = null;
243
+ let oldestAt = Number.POSITIVE_INFINITY;
244
+ for (const key of keys) {
245
+ const match = await cache.match(key);
246
+ if (!match) continue;
247
+ const at = extractCachedAt(match) ?? 0;
248
+ if (at < oldestAt) {
249
+ oldestAt = at;
250
+ oldestKey = key;
251
+ }
252
+ }
253
+ if (oldestKey === null) return false;
254
+ await cache.delete(oldestKey);
255
+ return true;
256
+ } catch {
257
+ return false;
258
+ }
259
+ };
260
+ const saveToCache = async (cache, cacheKey, response) => {
261
+ const headers = new Headers();
262
+ if (response.contentType) headers.set("content-type", response.contentType);
263
+ if (response.cacheControl) headers.set("cache-control", response.cacheControl);
264
+ if (response.expires) headers.set("expires", response.expires);
265
+ headers.set(CACHED_AT_HEADER, Date.now().toString());
266
+ const MAX_WRITE_EVICTIONS = 4;
267
+ let lastError;
268
+ for (let attempt = 0;; attempt++) {
269
+ const body = new Response(response.data.slice(0), {
270
+ status: 200,
271
+ headers
272
+ });
273
+ try {
274
+ await cache.put(cacheKey, body);
275
+ return;
276
+ } catch (error) {
277
+ lastError = error;
278
+ }
279
+ if (attempt >= MAX_WRITE_EVICTIONS || !await evictOldest(cache)) break;
280
+ }
281
+ console.warn("[YarrowMap] cache write failed:", lastError);
282
+ };
283
+ const fetchArrayBufferWithCache = async (url, cacheName, lifespanMs, abortController, requestParameters) => {
284
+ if (!hasCacheStorage()) return fetchFromNetwork(url, abortController, requestParameters);
285
+ const cache = await caches.open(cacheName);
286
+ const cachedResponse = await cache.match(url);
287
+ if (cachedResponse) {
288
+ const cachedAt = extractCachedAt(cachedResponse);
289
+ const maxAgeSeconds = parseMaxAge(cachedResponse.headers.get("cache-control"));
290
+ const effectiveLifespanMs = maxAgeSeconds !== null ? maxAgeSeconds * 1e3 : lifespanMs;
291
+ if (!(cachedAt === null || Date.now() - cachedAt > effectiveLifespanMs)) return toCachedArrayBufferResponse(cachedResponse);
292
+ try {
293
+ const refreshed = await fetchFromNetwork(url, abortController, requestParameters);
294
+ await saveToCache(cache, url, refreshed);
295
+ return refreshed;
296
+ } catch {
297
+ return toCachedArrayBufferResponse(cachedResponse);
298
+ }
299
+ }
300
+ const networkResponse = await fetchFromNetwork(url, abortController, requestParameters);
301
+ await saveToCache(cache, url, networkResponse);
302
+ return networkResponse;
303
+ };
304
+ /**
305
+ * Normalizes routing-API feature coordinates to `[lng, lat]` tuples. The API
306
+ * ships `{lng, lat}` objects; tuple coordinates (already GeoJSON-canonical)
307
+ * pass through as-is. Features whose geometry is not a LineString with
308
+ * well-formed coordinates are skipped instead of crashing on the cast — a
309
+ * single malformed feature must not lose the whole route. Returns the
310
+ * surviving features; a one-line warning fires only when something was
311
+ * actually dropped (core has no `__DEV__`, and this path only triggers on a
312
+ * malformed backend response, so the warn is rare by construction).
313
+ */
314
+ const transformRouteCoordinates = (features) => {
315
+ const transformed = [];
316
+ let skipped = 0;
317
+ for (const feature of features) {
318
+ const coords = feature.geometry?.coordinates;
319
+ if (!Array.isArray(coords) || coords.length === 0) {
320
+ skipped++;
321
+ continue;
322
+ }
323
+ const normalized = [];
324
+ let malformed = false;
325
+ for (const coord of coords) {
326
+ if (Array.isArray(coord) && typeof coord[0] === "number" && typeof coord[1] === "number") {
327
+ normalized.push([coord[0], coord[1]]);
328
+ continue;
329
+ }
330
+ const lng = coord?.lng;
331
+ const lat = coord?.lat;
332
+ if (typeof lng !== "number" || typeof lat !== "number") {
333
+ malformed = true;
334
+ break;
335
+ }
336
+ normalized.push([lng, lat]);
337
+ }
338
+ if (malformed) {
339
+ skipped++;
340
+ continue;
341
+ }
342
+ transformed.push({
343
+ ...feature,
344
+ geometry: {
345
+ ...feature.geometry,
346
+ coordinates: normalized
347
+ }
348
+ });
349
+ }
350
+ if (skipped > 0) console.warn(`[YarrowMap] transformRouteCoordinates: skipped ${skipped} feature(s) with a non-LineString or malformed geometry.`);
351
+ return transformed;
352
+ };
353
+ /** Routing API endpoint used by `fetchRoutes()`. */
354
+ const ROUTE_API_URL = "https://api.yarrow.uz/api/routing/route";
355
+ const emptyResult = (profile) => ({
356
+ features: [],
357
+ directions: [],
358
+ meta: {
359
+ profile,
360
+ totalRoutes: 0,
361
+ bestRouteIndex: 0,
362
+ duration: 0,
363
+ distance: 0
364
+ }
365
+ });
366
+ /**
367
+ * Legacy friendly profile names mapped onto the routing API's wire enum
368
+ * (`'CAR' | 'FOOT' | 'BICYCLE'` — the pre-2026-11 `'DRIVING'/'WALKING'/'CYCLING'`
369
+ * values were removed from the API's validation schema). Unknown values pass
370
+ * through uppercased so the server stays the validator.
371
+ */
372
+ const ROUTE_PROFILE_WIRE = {
373
+ driving: "CAR",
374
+ walking: "FOOT",
375
+ cycling: "BICYCLE",
376
+ car: "CAR",
377
+ foot: "FOOT",
378
+ bicycle: "BICYCLE"
379
+ };
380
+ const resolveWireProfile = (profile) => ROUTE_PROFILE_WIRE[profile.trim().toLowerCase()] ?? profile.toUpperCase();
381
+ /**
382
+ * Network half of the routing flow: POSTs the route request to the Yarrow
383
+ * routing API, parses and normalizes the response (coordinate order fix
384
+ * included). Rendering, events and camera work stay in the platform SDKs —
385
+ * they consume the returned features/directions/meta verbatim.
386
+ *
387
+ * Early "no route" outcomes resolve to an empty result (never throw), exactly
388
+ * like the web SDK's historic `buildRoute()` behavior.
389
+ */
390
+ async function fetchRoutes(input) {
391
+ const { profile, coordinates, language, signal } = input;
392
+ if (coordinates.length < 2) throw new Error("At least two coordinates are required to build a route.");
393
+ getYarrowApiKey();
394
+ const url = addApiKeyToUrl(ROUTE_API_URL);
395
+ let response;
396
+ try {
397
+ response = await fetch(url, {
398
+ method: "POST",
399
+ signal,
400
+ headers: {
401
+ "Content-Type": "application/json",
402
+ ...language ? { "Accept-Language": language } : {}
403
+ },
404
+ body: JSON.stringify({
405
+ profile: resolveWireProfile(profile),
406
+ coordinates: coordinates.map((coord) => ({
407
+ lng: coord[0],
408
+ lat: coord[1]
409
+ }))
410
+ })
411
+ });
412
+ } catch (error) {
413
+ throw wrapNetworkError(error, url);
414
+ }
415
+ if (!response.ok) {
416
+ if (response.status === 400) {
417
+ console.warn("[YarrowMap] buildRoute: no route found");
418
+ return emptyResult(profile);
419
+ }
420
+ throw apiErrorFromResponse({
421
+ status: response.status,
422
+ statusText: response.statusText,
423
+ url,
424
+ body: await readErrorBody(response)
425
+ });
426
+ }
427
+ const data = await response.json();
428
+ if (!data.success) {
429
+ console.warn("[YarrowMap] buildRoute: no route found");
430
+ return emptyResult(profile);
431
+ }
432
+ if (!data.data || typeof data.data !== "object" || data.data.path !== void 0 && (typeof data.data.path !== "object" || data.data.path === null)) throw invalidResponseError("missing routing \"data\" payload", data, url);
433
+ let features = data.data.path?.features || [];
434
+ if (!Array.isArray(features)) throw invalidResponseError("\"data.path.features\" is not an array", data, url);
435
+ features = transformRouteCoordinates(features);
436
+ if (!features.length) {
437
+ console.warn("[YarrowMap] buildRoute: route has no features to render");
438
+ return emptyResult(profile);
439
+ }
440
+ const bestCoords = features[0]?.geometry?.coordinates;
441
+ 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.");
442
+ const directions = data.data.directions?.routes?.map((r) => r.properties || []) || [];
443
+ const best = features[0];
444
+ return {
445
+ features,
446
+ directions,
447
+ meta: {
448
+ profile,
449
+ totalRoutes: features.length,
450
+ bestRouteIndex: 0,
451
+ duration: best?.properties?.duration ?? 0,
452
+ distance: best?.properties?.distance ?? 0
453
+ }
454
+ };
455
+ }
456
+ const haversineDistance = (lat1, lon1, lat2, lon2) => {
457
+ const toRad = (value) => value * Math.PI / 180;
458
+ const R = 6371e3;
459
+ const phi1 = toRad(lat1);
460
+ const phi2 = toRad(lat2);
461
+ const deltaPhi = toRad(lat2 - lat1);
462
+ const deltaLambda = toRad(lon2 - lon1);
463
+ const a = Math.sin(deltaPhi / 2) ** 2 + Math.cos(phi1) * Math.cos(phi2) * Math.sin(deltaLambda / 2) ** 2;
464
+ return R * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));
465
+ };
466
+ /**
467
+ * Queries the Yarrow search API around a coordinate. Pure network + mapping —
468
+ * marker rendering stays in the platform SDKs.
469
+ */
470
+ async function fetchSearchResults(query, input) {
471
+ getYarrowApiKey();
472
+ const searchUrl = addApiKeyToUrl(`${YARROW_SEARCH_API_URL}/api/search/`);
473
+ const url = new URL(searchUrl);
474
+ url.searchParams.set("q", query);
475
+ url.searchParams.set("lat", String(input.lat));
476
+ url.searchParams.set("lng", String(input.lon));
477
+ url.searchParams.set("country", "Uzbekistan");
478
+ url.searchParams.set("sort_by", "relevance");
479
+ url.searchParams.set("page", String(input.page ?? 1));
480
+ url.searchParams.set("page_size", String(input.pageSize ?? 15));
481
+ let response;
482
+ try {
483
+ response = await fetch(url.toString(), {
484
+ headers: { "Content-Type": "application/json" },
485
+ signal: input.signal
486
+ });
487
+ } catch (error) {
488
+ throw wrapNetworkError(error, url.toString());
489
+ }
490
+ if (!response.ok) throw apiErrorFromResponse({
491
+ status: response.status,
492
+ statusText: response.statusText,
493
+ url: url.toString(),
494
+ body: await readErrorBody(response)
495
+ });
496
+ return ((await response.json())?.results || []).map((r) => ({
497
+ id: r.id,
498
+ name: r.name,
499
+ icon_img: r.icon_img,
500
+ latitude: r.address?.location?.lat,
501
+ longitude: r.address?.location?.lng,
502
+ category: r.category
503
+ }));
504
+ }
505
+ /**
506
+ * Validates a user-supplied style type, warning (and falling back to
507
+ * `"default"`) on anything unrecognized. Verbatim behavior of the web SDK's
508
+ * `changeStyles()` guard.
509
+ */
510
+ function normalizeStyleType(styleType) {
511
+ if (styleType !== void 0 && styleType !== "default" && styleType !== "satellite" && styleType !== "hybrid") console.warn(`[YarrowMap] changeStyles: unknown style type "${styleType}", falling back to "default".`);
512
+ return styleType === "satellite" || styleType === "hybrid" ? styleType : "default";
513
+ }
514
+ /**
515
+ * Style-fetch endpoint for a style type/theme combination, e.g.
516
+ * `/styles/satellite/?dark=true`. Verbatim behavior of the web SDK's
517
+ * `YarrowStylesManager.buildStyleEndpoint()`.
518
+ */
519
+ function buildStyleEndpoint(styleType, theme) {
520
+ let endpoint = "/styles/";
521
+ if (styleType === "satellite") endpoint = "/styles/satellite/";
522
+ else if (styleType === "hybrid") endpoint = "/styles/hybrid/";
523
+ if (theme === "dark") endpoint += endpoint.includes("?") ? "&dark=true" : "?dark=true";
524
+ return endpoint;
525
+ }
526
+ const STORAGE_KEY = "yarrow:user_token";
527
+ /**
528
+ * Public alias of `STORAGE_KEY` so platform SDKs can build storage adapters
529
+ * (e.g. React Native AsyncStorage bridges) without hard-coding the key.
530
+ */
531
+ const USER_TOKEN_STORAGE_KEY = STORAGE_KEY;
532
+ let override = null;
533
+ function setTokenStorage(storage) {
534
+ override = storage;
535
+ }
536
+ function resolveStorage() {
537
+ if (override) return override;
538
+ try {
539
+ if (typeof localStorage !== "undefined") return localStorage;
540
+ } catch {}
541
+ return null;
542
+ }
543
+ function generateUuid() {
544
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
545
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
546
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(bytes);
547
+ else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
548
+ bytes[6] = bytes[6] & 15 | 64;
549
+ bytes[8] = bytes[8] & 63 | 128;
550
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
551
+ 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("")}`;
552
+ }
553
+ function getOrCreateUserToken() {
554
+ const storage = resolveStorage();
555
+ if (storage) try {
556
+ const existing = storage.getItem(STORAGE_KEY);
557
+ if (existing) return existing;
558
+ const token = generateUuid();
559
+ storage.setItem(STORAGE_KEY, token);
560
+ return token;
561
+ } catch {}
562
+ return generateUuid();
563
+ }
564
+ /** Hard cap on how long a single tracking request may stay open. */
565
+ const TRACK_REQUEST_TIMEOUT_MS = 5e3;
566
+ function trackDau$1(apiKey, sdkType = "javascript") {
567
+ try {
568
+ const user_token = getOrCreateUserToken();
569
+ const controller = new AbortController();
570
+ const timeout = setTimeout(() => controller.abort(), TRACK_REQUEST_TIMEOUT_MS);
571
+ fetch(`${YARROW_SEARCH_API_URL}/api/tracking/track-dau`, {
572
+ method: "POST",
573
+ headers: { "Content-Type": "application/json" },
574
+ body: JSON.stringify({
575
+ api_key: apiKey,
576
+ sdk_type: sdkType,
577
+ user_token
578
+ }),
579
+ signal: controller.signal
580
+ }).catch(() => {}).finally(() => clearTimeout(timeout));
581
+ } catch {}
582
+ }
583
+
584
+ // src/clustering/ClusterBadge.tsx
585
+ const CLUSTER_COLORS = {
586
+ light: {
587
+ bg: "#2f80ed",
588
+ text: "#ffffff"
589
+ },
590
+ dark: {
591
+ bg: "#3b6fd4",
592
+ text: "#ffffff"
593
+ }
594
+ };
595
+ const ENTER_MS$1 = 280;
596
+ /**
597
+ * The count badge that stands in for clustered highlight/search markers —
598
+ * the native counterpart of the web SDK's cluster DOM marker (blue circle,
599
+ * white border, bold count).
600
+ */
601
+ const ClusterBadge = memo(function ClusterBadge({ lngLat, count, theme, onPress }) {
602
+ const progress = useRef(new Animated.Value(0)).current;
603
+ useEffect(() => {
604
+ Animated.timing(progress, {
605
+ toValue: 1,
606
+ duration: ENTER_MS$1,
607
+ useNativeDriver: true
608
+ }).start();
609
+ }, [progress]);
610
+ const colors = CLUSTER_COLORS[theme];
611
+ return /* @__PURE__ */ jsx(Marker, {
612
+ lngLat,
613
+ anchor: "center",
614
+ onPress: onPress ? () => onPress() : void 0,
615
+ children: /* @__PURE__ */ jsx(Animated.View, {
616
+ style: [styles$3.inner, {
617
+ transform: [{ scale: progress }],
618
+ opacity: progress
619
+ }],
620
+ children: /* @__PURE__ */ jsx(Text, {
621
+ style: [styles$3.badge, {
622
+ backgroundColor: colors.bg,
623
+ color: colors.text
624
+ }],
625
+ children: count
626
+ })
627
+ })
628
+ });
629
+ });
630
+ const styles$3 = StyleSheet.create({
631
+ inner: {
632
+ alignItems: "center",
633
+ justifyContent: "center"
634
+ },
635
+ badge: {
636
+ minWidth: 40,
637
+ height: 40,
638
+ paddingHorizontal: 10,
639
+ borderRadius: 20,
640
+ borderWidth: 3,
641
+ borderColor: "#ffffff",
642
+ fontSize: 15,
643
+ fontWeight: "700",
644
+ lineHeight: 34,
645
+ textAlign: "center",
646
+ textAlignVertical: "center"
647
+ }
648
+ });
649
+
650
+ // src/clustering/config.ts
651
+ /**
652
+ * Clustering configuration and normalization — the declarative counterpart of
653
+ * the web SDK's `setClustering`. Defaults match the web SDK exactly:
654
+ * 60 px merge radius, no clustering above zoom 16, clusters need ≥ 2 markers.
655
+ */
656
+ const DEFAULT_CLUSTER_RADIUS_PX = 60;
657
+ const DEFAULT_CLUSTER_MAX_ZOOM = 16;
658
+ const DEFAULT_CLUSTER_MIN_POINTS = 2;
659
+ /**
660
+ * Normalizes the public clustering option (`true` / config object / falsy)
661
+ * into a fully-resolved config. Passing an object enables clustering.
662
+ * `minPoints` is clamped to at least 2 — a "cluster" of one is just the
663
+ * marker itself.
664
+ */
665
+ function normalizeClusteringConfig(input) {
666
+ const disabled = {
667
+ enabled: false,
668
+ radius: 60,
669
+ maxZoom: 16,
670
+ minPoints: 2
671
+ };
672
+ if (input === void 0 || input === false) return disabled;
673
+ if (input === true) return {
674
+ ...disabled,
675
+ enabled: true
676
+ };
677
+ return {
678
+ enabled: true,
679
+ radius: input.radius ?? 60,
680
+ maxZoom: input.maxZoom ?? 16,
681
+ minPoints: Math.max(2, input.minPoints ?? 2),
682
+ onClusterClick: input.onClusterClick
683
+ };
684
+ }
685
+ /**
686
+ * Groups projected points greedily by pixel distance: each unvisited point
687
+ * seeds a group and absorbs every remaining point within `radius`. O(n²), but
688
+ * the highlighted/search-marker count is small (dozens at most), so this
689
+ * stays cheap and deterministic. Ported from the web SDK's cluster engine.
690
+ */
691
+ function groupByPixelRadius(items, radius) {
692
+ const radiusSq = radius * radius;
693
+ const visited = new Array(items.length).fill(false);
694
+ const groups = [];
695
+ for (let i = 0; i < items.length; i++) {
696
+ if (visited[i]) continue;
697
+ visited[i] = true;
698
+ const seed = items[i];
699
+ const group = [seed];
700
+ for (let j = i + 1; j < items.length; j++) {
701
+ if (visited[j]) continue;
702
+ const candidate = items[j];
703
+ const dx = seed.x - candidate.x;
704
+ const dy = seed.y - candidate.y;
705
+ if (dx * dx + dy * dy <= radiusSq) {
706
+ visited[j] = true;
707
+ group.push(candidate);
708
+ }
709
+ }
710
+ groups.push(group);
711
+ }
712
+ return groups;
713
+ }
714
+
715
+ // src/icons/registry.ts
716
+ /**
717
+ * Fetches the Yarrow icon registry (`/icons-image`) and reduces it to a
718
+ * name → URL map. Native has no Cache Storage, so the result is not persisted
719
+ * — `<YarrowMapView>` fetches it once per mount when icons are enabled.
720
+ *
721
+ * Also seeds core's API-key module state (like every standalone client), so
722
+ * the key is current even if the hook runs before a map mounts.
723
+ *
724
+ * Throws a coded {@link YarrowApiError}: `unauthorized` when no key is
725
+ * configured (or the server rejects one), `network` when the request fails.
726
+ */
727
+ async function fetchYarrowIcons(apiKey) {
728
+ if (apiKey) setYarrowApiKey(apiKey);
729
+ getYarrowApiKey();
730
+ const url = addApiKeyToUrl(`${YARROW_MAP_URL}${ICONS_ENDPOINT}`);
731
+ let response;
732
+ try {
733
+ response = await fetch(url);
734
+ } catch (error) {
735
+ throw wrapNetworkError(error, url);
736
+ }
737
+ if (!response.ok) throw apiErrorFromResponse({
738
+ status: response.status,
739
+ statusText: response.statusText,
740
+ url,
741
+ body: await readErrorBody(response)
742
+ });
743
+ return (await response.json()).reduce((acc, icon) => {
744
+ acc[icon.icon_image_name] = icon.icon_image_url;
745
+ return acc;
746
+ }, {});
747
+ }
748
+ /**
749
+ * Best-effort icon URL for a search-result `category.name` / tile
750
+ * `node_type`. The registry is keyed by sprite names, which usually match
751
+ * category names — the same fallback the web SDK applies via its icon
752
+ * expression.
753
+ */
754
+ function resolveCategoryIcon(iconsByName, name) {
755
+ if (!name) return void 0;
756
+ const icons = iconsByName;
757
+ if (!icons) return void 0;
758
+ return Object.hasOwn(icons, name) ? icons[name] : void 0;
759
+ }
760
+
761
+ // src/poiHighlight/resolve.ts
762
+ /** The base style's POI symbol layer (`node_tile` source). */
763
+ const POI_BASE_LAYER = "pois_tile_layer";
764
+ const PLACE_TIMEOUT_MS = 15e3;
765
+ /**
766
+ * Fetches a POI's coordinates and icon from the place-detail API — the
767
+ * off-screen / below-zoom fallback of the resolution chain. Returns `null`
768
+ * on any failure or missing coordinates (web parity).
769
+ *
770
+ * When the response carries no `icon_img`, the icon is derived from
771
+ * `node_type` (falling back to `category.name`) — the web SDK resolves it
772
+ * through its style `icon-image` expression; native approximates that with
773
+ * an icon-registry lookup by the same name, since the detail endpoint
774
+ * returns the node type rather than an icon URL.
775
+ */
776
+ async function fetchPlaceLocation(id, iconsByName) {
777
+ const controller = new AbortController();
778
+ const timeout = setTimeout(() => controller.abort(), PLACE_TIMEOUT_MS);
779
+ try {
780
+ getYarrowApiKey();
781
+ const url = addApiKeyToUrl(`${YARROW_SEARCH_API_URL}/api/search/${id}?is_bus_stop=false`);
782
+ const res = await fetch(url, { signal: controller.signal });
783
+ if (!res.ok) {
784
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn(`[YarrowMap] fetchPlaceLocation(${id}) failed: ${res.status} ${res.statusText} — ${url}`);
785
+ return null;
786
+ }
787
+ const data = (await res.json())?.search?.data;
788
+ const loc = data?.address?.location;
789
+ if (!loc) return null;
790
+ const nodeType = typeof data?.node_type === "string" ? data.node_type : typeof data?.category?.name === "string" ? data.category.name : void 0;
791
+ const iconUrl = data?.icon_img ?? (nodeType ? resolveCategoryIcon(iconsByName, nodeType) : void 0);
792
+ return {
793
+ lng: loc.lng,
794
+ lat: loc.lat,
795
+ iconUrl,
796
+ title: data?.name
797
+ };
798
+ } catch (error) {
799
+ if (error?.name !== "AbortError" && typeof __DEV__ !== "undefined" && __DEV__) console.warn(`[YarrowMap] fetchPlaceLocation(${id}) failed:`, error);
800
+ return null;
801
+ } finally {
802
+ clearTimeout(timeout);
803
+ }
804
+ }
805
+ /**
806
+ * Reads a POI's point geometry from the style's POI layer within the current
807
+ * viewport — the free, no-network resolution step. Native can only query
808
+ * *rendered* features (no `querySourceFeatures` on undeclared sources), so
809
+ * off-screen POIs fall through to the place-detail API. Icons are resolved
810
+ * best-effort from the registry via the feature's `node_type`.
811
+ */
812
+ async function lookupPoiInViewport(mapRef, id, iconsByName) {
813
+ let features = [];
814
+ try {
815
+ features = await mapRef.queryRenderedFeatures({
816
+ layers: [POI_BASE_LAYER],
817
+ filter: [
818
+ "==",
819
+ ["get", "id"],
820
+ id
821
+ ]
822
+ });
823
+ } catch {
824
+ return null;
825
+ }
826
+ const feature = features.find((f) => f.geometry?.type === "Point");
827
+ if (!feature) return null;
828
+ const coordinates = feature.geometry.coordinates;
829
+ const properties = feature.properties ?? {};
830
+ const nodeType = typeof properties.node_type === "string" ? properties.node_type : void 0;
831
+ const name = typeof properties.name === "string" ? properties.name : void 0;
832
+ return {
833
+ lng: coordinates[0],
834
+ lat: coordinates[1],
835
+ iconUrl: nodeType ? resolveCategoryIcon(iconsByName, nodeType) : void 0,
836
+ title: name
837
+ };
838
+ }
839
+ /**
840
+ * Resolves a POI's coordinates, icon and title cheapest-first:
841
+ * 1. caller-provided `location` / `icon` / `title`
842
+ * 2. local lookup in the rendered POI layer (no network)
843
+ * 3. the place-detail API (off-screen / below the POI zoom range, or when
844
+ * anything is still missing — web parity: the API fills icon and title
845
+ * too, not just coordinates)
846
+ *
847
+ * The web SDK additionally evaluates the style's `icon-image` expression for
848
+ * both the tile and the place-detail steps; native approximates it with a
849
+ * registry lookup by `node_type`. Coordinate resolution is the hard
850
+ * requirement — if it fails, the highlight is rolled back by the caller.
851
+ */
852
+ async function resolvePoiData(id, options, runtime) {
853
+ let lng = options.location?.lng;
854
+ let lat = options.location?.lat;
855
+ let iconUrl = options.icon;
856
+ let title = options.title;
857
+ if (lng === void 0 || iconUrl === void 0 || title === void 0) {
858
+ const mapRef = runtime.mapRef.current;
859
+ const local = mapRef ? await lookupPoiInViewport(mapRef, id, runtime.iconsByName) : null;
860
+ if (local) {
861
+ if (lng === void 0) {
862
+ lng = local.lng;
863
+ lat = local.lat;
864
+ }
865
+ if (iconUrl === void 0) iconUrl = local.iconUrl;
866
+ if (title === void 0) title = local.title;
867
+ }
868
+ }
869
+ if (lng === void 0 || iconUrl === void 0 || title === void 0) {
870
+ const remote = await fetchPlaceLocation(id, runtime.iconsByName);
871
+ if (remote) {
872
+ if (lng === void 0) {
873
+ lng = remote.lng;
874
+ lat = remote.lat;
875
+ }
876
+ if (iconUrl === void 0) iconUrl = remote.iconUrl;
877
+ if (title === void 0) title = remote.title;
878
+ }
879
+ }
880
+ if (lng === void 0 || lat === void 0) return null;
881
+ return {
882
+ lng,
883
+ lat,
884
+ iconUrl,
885
+ title
886
+ };
887
+ }
888
+
889
+ // src/runtime/context.ts
890
+ const YarrowMapContext = createContext(null);
891
+ /** Reads the enclosing `<YarrowMapView>` runtime, or `null` outside one. */
892
+ function useYarrowMapRuntime() {
893
+ return useContext(YarrowMapContext);
894
+ }
895
+
896
+ // src/events/useYarrowLayerPress.ts
897
+ const YARROW_CLICK_LAYER_IDS = {
898
+ pois: [POI_BASE_LAYER],
899
+ buildings: ["buildings_tile_layer"],
900
+ mahalla: ["mahallah_label_tile_layer"],
901
+ district: ["districts_label_tile_layer"],
902
+ region: ["regions_label_tile_layer"],
903
+ country: ["countries_label_tile_layer"]
904
+ };
905
+ /**
906
+ * Base-style-layer press handler — the native counterpart of the web SDK's
907
+ * `onIconClick('pois' | 'buildings')` and `onLayerClick(<admin label>)`. On
908
+ * every map press it queries the rendered features at the press point for the
909
+ * target layers and invokes `handler` with the topmost hit. Must be called
910
+ * inside `<YarrowMapView>` — extract a child component rendered as a map
911
+ * child (hooks outside the map can't see the runtime):
912
+ *
913
+ * ```tsx
914
+ * function PoiPressReporter() {
915
+ * useYarrowLayerPress('pois', ({ lat, lng, properties, selected }) => {
916
+ * console.log('POI pressed', properties.id, selected);
917
+ * });
918
+ * return null;
919
+ * }
920
+ *
921
+ * <YarrowMapView apiKey={KEY}>
922
+ * <PoiPressReporter />
923
+ * </YarrowMapView>
924
+ * ```
925
+ *
926
+ * Unlike the web SDK, targets resolve to the canonical Yarrow style layer
927
+ * ids (verified against the served `/styles/` document, identical in light
928
+ * and dark) instead of dynamic style inspection — override `layerIds` if
929
+ * your style variant names them differently.
930
+ */
931
+ function useYarrowLayerPress(target, handler, options) {
932
+ const runtime = useYarrowMapRuntime();
933
+ const targets = Array.isArray(target) ? target : [target];
934
+ const targetsKey = targets.join(",");
935
+ const handlerRef = useRef(handler);
936
+ handlerRef.current = handler;
937
+ useEffect(() => {
938
+ if (!runtime) {
939
+ console.warn("[YarrowMap] useYarrowLayerPress: no map runtime — call it inside <YarrowMapView>.");
940
+ return;
941
+ }
942
+ const layerIds = targets.flatMap((t) => options?.layerIds?.[t] ?? YARROW_CLICK_LAYER_IDS[t]);
943
+ const includesPois = targets.includes("pois");
944
+ return runtime.subscribePress((press) => {
945
+ const map = runtime.mapRef.current;
946
+ if (!map || layerIds.length === 0) return;
947
+ map.queryRenderedFeatures(press.point, { layers: layerIds }).then((features) => {
948
+ const feature = features[0];
949
+ if (!feature?.properties) return;
950
+ const properties = feature.properties;
951
+ let selected;
952
+ if (includesPois) {
953
+ const fid = properties.id;
954
+ selected = typeof fid === "number" ? runtime.highlightedPoiIds.current.has(fid) : false;
955
+ }
956
+ handlerRef.current({
957
+ lat: press.lngLat[1],
958
+ lng: press.lngLat[0],
959
+ properties,
960
+ selected
961
+ });
962
+ }).catch(() => {});
963
+ });
964
+ }, [
965
+ runtime,
966
+ targetsKey,
967
+ options?.layerIds
968
+ ]);
969
+ }
970
+
971
+ // src/hooks/useYarrowSearch.ts
972
+ /**
973
+ * Debounced, abortable search against the Yarrow search API.
974
+ *
975
+ * Requires the API key to be configured (`YarrowMapView` does this on mount;
976
+ * otherwise call `setYarrowApiKey()` first).
977
+ *
978
+ * ```tsx
979
+ * const { results, isLoading } = useYarrowSearch(query, {
980
+ * lat: position?.lat ?? 41.2995,
981
+ * lon: position?.lng ?? 69.2401,
982
+ * });
983
+ * ```
984
+ */
985
+ const useYarrowSearch = (query, options) => {
986
+ const { lat, lon, page = 1, pageSize = 15, debounceMs = 300, enabled = true } = options;
987
+ const [results, setResults] = useState([]);
988
+ const [isLoading, setIsLoading] = useState(false);
989
+ const [error, setError] = useState(null);
990
+ const latestRequestRef = useRef(0);
991
+ useEffect(() => {
992
+ const trimmed = query.trim();
993
+ if (!enabled || trimmed.length === 0) {
994
+ latestRequestRef.current += 1;
995
+ setResults([]);
996
+ setError(null);
997
+ setIsLoading(false);
998
+ return;
999
+ }
1000
+ const controller = new AbortController();
1001
+ const requestId = ++latestRequestRef.current;
1002
+ setIsLoading(true);
1003
+ const timeout = setTimeout(() => {
1004
+ fetchSearchResults(trimmed, {
1005
+ lat,
1006
+ lon,
1007
+ page,
1008
+ pageSize,
1009
+ signal: controller.signal
1010
+ }).then((resolved) => {
1011
+ if (latestRequestRef.current === requestId) {
1012
+ setResults(resolved);
1013
+ setError(null);
1014
+ }
1015
+ }).catch((caught) => {
1016
+ if (controller.signal.aborted) return;
1017
+ if (latestRequestRef.current === requestId) setError(caught instanceof Error ? caught : new Error(String(caught)));
1018
+ }).finally(() => {
1019
+ if (latestRequestRef.current === requestId) setIsLoading(false);
1020
+ });
1021
+ }, debounceMs);
1022
+ return () => {
1023
+ clearTimeout(timeout);
1024
+ controller.abort();
1025
+ };
1026
+ }, [
1027
+ query,
1028
+ enabled,
1029
+ lat,
1030
+ lon,
1031
+ page,
1032
+ pageSize,
1033
+ debounceMs
1034
+ ]);
1035
+ return {
1036
+ results,
1037
+ isLoading,
1038
+ error
1039
+ };
1040
+ };
1041
+
1042
+ // src/hooks/useYarrowMapSearch.ts
1043
+ const DEFAULT_THRESHOLD_METERS = 500;
1044
+ const DEFAULT_MOVE_DEBOUNCE_MS = 250;
1045
+ /**
1046
+ * `useYarrowSearch` plus web-parity re-query on camera movement: when the map
1047
+ * moves ≥ 500 m from where the current results were fetched for, the search
1048
+ * re-runs around the new center. Must be called inside `<YarrowMapView>` to
1049
+ * observe camera moves (outside one it behaves exactly like `useYarrowSearch`).
1050
+ *
1051
+ * ```tsx
1052
+ * const { results, isLoading, center } = useYarrowMapSearch(query, {
1053
+ * lat: 41.2995,
1054
+ * lon: 69.2401,
1055
+ * refetchOnMove: true,
1056
+ * });
1057
+ * <SearchResultsLayer results={results} />
1058
+ * ```
1059
+ */
1060
+ function useYarrowMapSearch(query, options) {
1061
+ const { lat, lon, refetchOnMove, ...searchOptions } = options;
1062
+ const runtime = useYarrowMapRuntime();
1063
+ const [center, setCenter] = useState({
1064
+ lat,
1065
+ lon
1066
+ });
1067
+ const centerRef = useRef(center);
1068
+ centerRef.current = center;
1069
+ const callerKey = `${lat},${lon}`;
1070
+ useEffect(() => {
1071
+ const [callerLat, callerLon] = callerKey.split(",").map(Number);
1072
+ setCenter((current) => current.lat === callerLat && current.lon === callerLon ? current : {
1073
+ lat: callerLat,
1074
+ lon: callerLon
1075
+ });
1076
+ }, [callerKey]);
1077
+ useEffect(() => {
1078
+ if (!refetchOnMove || !runtime) return;
1079
+ const { thresholdMeters = DEFAULT_THRESHOLD_METERS, debounceMs = DEFAULT_MOVE_DEBOUNCE_MS } = typeof refetchOnMove === "object" ? refetchOnMove : {};
1080
+ let timeout = null;
1081
+ const unsubscribe = runtime.subscribeRegionChange(({ center: [lng, mapLat] }) => {
1082
+ if (timeout) clearTimeout(timeout);
1083
+ timeout = setTimeout(() => {
1084
+ timeout = null;
1085
+ const current = centerRef.current;
1086
+ if (haversineDistance(current.lat, current.lon, mapLat, lng) >= thresholdMeters) setCenter({
1087
+ lat: mapLat,
1088
+ lon: lng
1089
+ });
1090
+ }, debounceMs);
1091
+ });
1092
+ return () => {
1093
+ if (timeout) clearTimeout(timeout);
1094
+ unsubscribe();
1095
+ };
1096
+ }, [refetchOnMove, runtime]);
1097
+ return {
1098
+ ...useYarrowSearch(query, {
1099
+ ...searchOptions,
1100
+ lat: center.lat,
1101
+ lon: center.lon
1102
+ }),
1103
+ center
1104
+ };
1105
+ }
1106
+
1107
+ // src/hooks/useYarrowRouting.ts
1108
+ /** Default `buildRoute` timeout — after this the request aborts and rejects. */
1109
+ const DEFAULT_TIMEOUT_MS = 3e4;
1110
+ /**
1111
+ * Headless routing state for the Yarrow routing API — pairs with
1112
+ * `<RouteLayer>` for rendering.
1113
+ *
1114
+ * Requests abort after `timeoutMs` (default 30 s) and reject with a coded
1115
+ * `YarrowApiError`; caller `signal` cancellation applies immediately, and
1116
+ * pass `timeoutMs: 0` to disable the timer.
1117
+ *
1118
+ * ```tsx
1119
+ * const { routes, isLoading, buildRoute } = useYarrowRouting({ profile: 'driving' });
1120
+ * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
1121
+ * <RouteLayer routes={routes} />
1122
+ * </YarrowMapView>
1123
+ * ```
1124
+ */
1125
+ const useYarrowRouting = (options = {}) => {
1126
+ const { profile = "driving", language, timeoutMs = DEFAULT_TIMEOUT_MS } = options;
1127
+ const [result, setResult] = useState(null);
1128
+ const [isLoading, setIsLoading] = useState(false);
1129
+ const [error, setError] = useState(null);
1130
+ const latestRequestRef = useRef(0);
1131
+ const buildRoute = useCallback(async (input) => {
1132
+ const requestId = ++latestRequestRef.current;
1133
+ setIsLoading(true);
1134
+ setError(null);
1135
+ const controller = new AbortController();
1136
+ let timedOut = false;
1137
+ let timer;
1138
+ const onCallerAbort = () => controller.abort();
1139
+ if (input.signal) {
1140
+ if (input.signal.aborted) controller.abort();
1141
+ else input.signal.addEventListener("abort", onCallerAbort);
1142
+ }
1143
+ if (timeoutMs > 0) timer = setTimeout(() => {
1144
+ timedOut = true;
1145
+ controller.abort();
1146
+ }, timeoutMs);
1147
+ const cleanup = () => {
1148
+ if (timer !== void 0) clearTimeout(timer);
1149
+ timer = void 0;
1150
+ input.signal?.removeEventListener("abort", onCallerAbort);
1151
+ };
1152
+ try {
1153
+ const resolved = await fetchRoutes({
1154
+ profile: input.profile ?? profile,
1155
+ coordinates: input.coordinates,
1156
+ language: input.language ?? language,
1157
+ signal: controller.signal
1158
+ });
1159
+ if (latestRequestRef.current === requestId) setResult(resolved);
1160
+ return resolved;
1161
+ } catch (caught) {
1162
+ let surfaced = caught;
1163
+ if (timedOut && caught?.name === "AbortError") surfaced = new YarrowApiError("network", `Routing request timed out after ${timeoutMs} ms — pass a larger timeoutMs to useYarrowRouting (0 disables the timeout).`);
1164
+ if (latestRequestRef.current === requestId) setError(surfaced instanceof Error ? surfaced : new Error(String(surfaced)));
1165
+ throw surfaced;
1166
+ } finally {
1167
+ cleanup();
1168
+ if (latestRequestRef.current === requestId) setIsLoading(false);
1169
+ }
1170
+ }, [
1171
+ profile,
1172
+ language,
1173
+ timeoutMs
1174
+ ]);
1175
+ const clearRoutes = useCallback(() => {
1176
+ latestRequestRef.current += 1;
1177
+ setResult(null);
1178
+ setError(null);
1179
+ setIsLoading(false);
1180
+ }, []);
1181
+ return {
1182
+ routes: result?.features ?? [],
1183
+ directions: result?.directions ?? [],
1184
+ meta: result?.meta ?? null,
1185
+ isLoading,
1186
+ error,
1187
+ buildRoute,
1188
+ clearRoutes
1189
+ };
1190
+ };
1191
+
1192
+ // src/icons/YarrowImages.tsx
1193
+ /**
1194
+ * Adds the Yarrow icon images to the native style so symbol layers can
1195
+ * resolve their `icon-image` names — the native counterpart of the web SDK's
1196
+ * `addIconsToMap` prefetch plus its missing-image resolver. `Images` accepts
1197
+ * remote URLs and downloads them natively; `onImageMissing` covers icons
1198
+ * referenced before the registry fetch lands or after a failed fetch.
1199
+ */
1200
+ const YarrowImages = memo(function YarrowImages({ iconsByName, onMissingIcon }) {
1201
+ const images = useMemo(() => ({ ...iconsByName }), [iconsByName]);
1202
+ const handleMissing = useCallback((event) => {
1203
+ const name = event.nativeEvent?.image;
1204
+ if (name) onMissingIcon?.(name);
1205
+ }, [onMissingIcon]);
1206
+ return /* @__PURE__ */ jsx(Images, {
1207
+ images,
1208
+ onImageMissing: handleMissing
1209
+ });
1210
+ });
1211
+
1212
+ // src/assets/brandBadgeLogo.ts
1213
+ const BRAND_BADGE_LOGO_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAi4AAACfCAYAAADeQ1ImAABmhklEQVR4nO2dB2AcxfX/v7N7Tb1Zsi1Z7r1jG7CNDTahd0JsAiTUBEJzGun5/bFTIIQkJJQECCVAIMQKndBiwBQb416wjG1Zbuq9na7uzn9m704+SVf2pNvTyZ4PnHW3tzc7OzM78+a9N29M0AGllDAo/xs4xj8Hvgs+N3A82nfB3/c8Huk7PWlG+43e/Pf8Xu93fblepN9Ey0fw933Nf8+8hLqGHvRcL1z+YzkuEAgEghMTAoFAIBAIBIJBggSBQCAQCASCQYIQXAQCgUAgEAwahOAiEAgEAoFg0CAEF4FAIBAIBIMGIbgIBAKBQCAYNAjBRSAQCAQCwaBBCC4CgUAgEAgGDUJwEQgEAoFAMGgQgotAIBAIBIJBgwnHAT23JAi1PYH/c89IwaEiB+s9FjFLOn5DYjg3ON1QqMHvQ20jEK58RDh9gUAgEAwmBmXI/6ABmWuM0sAFsNr1JrjTC5A/sQ02WyfQ4oXdbENamkJXkJrATxE7/RUqoqUXS56Ijt8pZNnDC7D49l1wucbCam2C3S7BbB6C+kMm2CuB4fMqkeFyAUM8THBxRtsHSSAQCASCZGFQCC5BAysbeOvzkJbvZQNsg97fq3cwjQQx5F7jNciTMGmRMNeMeL70EIgeYSRIU5WD6tIMDJ9azQ57hfAiEAgEgmQlqX1c2IAq0aqqVBzdNpwPpuzlIekFNbEILVo6w6ffA2MgcXohwvFQ14x0fpv2pa+8aCQhJPAd+9tMCqcd0cqXCzI1ZQW0ZgfXZIXctVogEAgEgoEiKQclbbDsqBmC9GEN8Zr9q3dqfiDH/SCszv76paabXnwd/aRLG9N5tIikFldCIBAIBIIkIKkGck1g2bs3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0lC65815W/jITWvKTQWgRCAQCwYlF8EQ12MdxUDg7+jK8imDfotPo3y54Cl73uB45D3yiEd6HOh8hztVFQsxEtbuG0t/MCF61FCmfsd5D4HwFPs1KG7nmmW9h3lWv8CCBQqMhEAgEgmRkUK/SYINrFr547Tz6r29fB3fncKhKITzOXPg0Sd7AafDdJ9X+IxE1NjTob7AgcOwvT0OSqqUH1fEwGPWxi9/F7jeWsCuqQXkK5CN83QX8g1hO/Tk2a39N1noim9pYuZWTrz78byy84TUmnDRBIBAIBIJBwnGzvDSUhiBItUSCXjToL4K+j3qJwCsRmogQeQfCa5BCoQbnM1A+QpMiEAgEgsHMCREXI97xPxI58IfIe0+hKyxCQBEIBALB8YYI6CUQCAQCgWDQkJSrigQCgUAgEAhCIQQXgUAgEAgEgwYhuAgEAoFAIBg0CMFFIBAIBALBoEEILgKBQCAQCAYNQnARCAQCgUAwaBCCi0AgEAgEgkGDEFwEAoFAIBAMGoTgIhAIBAKBYNAgBBeBQCAQCASDBiG4CAQCgUAgGDQIwUUgEAgEAsGgQQguAoFAIBAIBg1CcBEIBAKBQDBoEIKLQCAQCASCQYOJUkoYNNwJ4b7nx/nfnt+FO673u/78Nh55ifSb4O8jnROOUGXZnzyG+11/0433b/r6vUAgEAgEPfn/uHDNdswmxrsAAAAASUVORK5CYII=";
1214
+
1215
+ // src/maps/brandBadge.tsx
1216
+ const DEFAULT_BRAND_BADGE_POSITION = "bottom-left";
1217
+ const BRAND_BADGE_OFFSET_PX = 6;
1218
+ const BADGE_WEB_LOGO_WIDTH_PX = 106;
1219
+ const DEFAULT_BRAND_BADGE_SCALE = 1;
1220
+ const LOGO_ASPECT = 53 / 186;
1221
+ const BADGE_BORDER_PX = 1;
1222
+ const TINT = {
1223
+ light: "rgba(255, 255, 255, 0.55)",
1224
+ dark: "rgba(15, 23, 42, 0.55)"
1225
+ };
1226
+ const normalizeBrandBadgePosition = (position) => {
1227
+ switch (position) {
1228
+ case "top-left":
1229
+ case "top-right":
1230
+ case "bottom-left":
1231
+ case "bottom-right": return position;
1232
+ default: return DEFAULT_BRAND_BADGE_POSITION;
1233
+ }
1234
+ };
1235
+ const getPositionStyle = (position) => {
1236
+ switch (position) {
1237
+ case "top-left": return {
1238
+ top: BRAND_BADGE_OFFSET_PX,
1239
+ left: BRAND_BADGE_OFFSET_PX
1240
+ };
1241
+ case "top-right": return {
1242
+ top: BRAND_BADGE_OFFSET_PX,
1243
+ right: BRAND_BADGE_OFFSET_PX
1244
+ };
1245
+ case "bottom-right": return {
1246
+ bottom: BRAND_BADGE_OFFSET_PX,
1247
+ right: BRAND_BADGE_OFFSET_PX
1248
+ };
1249
+ default: return {
1250
+ bottom: BRAND_BADGE_OFFSET_PX,
1251
+ left: BRAND_BADGE_OFFSET_PX
1252
+ };
1253
+ }
1254
+ };
1255
+ const styles$2 = StyleSheet.create({
1256
+ badgeDark: { borderColor: "rgba(255, 255, 255, 0.16)" },
1257
+ fill: {
1258
+ display: "flex",
1259
+ alignItems: "center",
1260
+ justifyContent: "center"
1261
+ }
1262
+ });
1263
+ const badgeStyle = (scale) => {
1264
+ const logoWidth = Math.round(BADGE_WEB_LOGO_WIDTH_PX * scale);
1265
+ const logoHeight = Math.round(logoWidth * LOGO_ASPECT);
1266
+ return {
1267
+ position: "absolute",
1268
+ zIndex: 1e3,
1269
+ width: logoWidth + Math.round(10 * scale) * 2 + 2,
1270
+ height: logoHeight + Math.round(2 * scale) * 2 + 2,
1271
+ overflow: "hidden",
1272
+ borderRadius: Math.round(16 * scale),
1273
+ borderWidth: BADGE_BORDER_PX,
1274
+ borderColor: "rgba(255, 255, 255, 0.3)"
1275
+ };
1276
+ };
1277
+ /**
1278
+ * The Yarrow brand badge as an overlay view — the RN counterpart of the web
1279
+ * SDK's `BrandBadgeController` host (same pill styles, same logo, same
1280
+ * default corner). `pointerEvents="none"` so map gestures pass through.
1281
+ *
1282
+ * The pill is a translucent tint on both platforms — see the TINT note above
1283
+ * for why native skips the web badge's backdrop blur.
1284
+ */
1285
+ function BrandBadge({ theme = "light", position, scale = 1 }) {
1286
+ const dark = theme === "dark";
1287
+ const logoWidth = Math.round(BADGE_WEB_LOGO_WIDTH_PX * scale);
1288
+ const logoHeight = Math.round(logoWidth * LOGO_ASPECT);
1289
+ const tint = dark ? TINT.dark : TINT.light;
1290
+ return /* @__PURE__ */ jsx(View, {
1291
+ testID: "yarrow-brand-badge",
1292
+ pointerEvents: "none",
1293
+ accessibilityElementsHidden: true,
1294
+ importantForAccessibility: "no-hide-descendants",
1295
+ "aria-hidden": true,
1296
+ style: [
1297
+ badgeStyle(scale),
1298
+ dark ? styles$2.badgeDark : null,
1299
+ getPositionStyle(normalizeBrandBadgePosition(position))
1300
+ ],
1301
+ children: /* @__PURE__ */ jsx(View, {
1302
+ testID: "yarrow-brand-badge-tint",
1303
+ style: [
1304
+ StyleSheet.absoluteFill,
1305
+ styles$2.fill,
1306
+ { backgroundColor: tint }
1307
+ ],
1308
+ children: /* @__PURE__ */ jsx(Image, {
1309
+ source: { uri: BRAND_BADGE_LOGO_URI },
1310
+ style: {
1311
+ width: logoWidth,
1312
+ height: logoHeight
1313
+ },
1314
+ resizeMode: "contain"
1315
+ })
1316
+ })
1317
+ });
1318
+ }
1319
+
1320
+ // src/maps/config.ts
1321
+ /**
1322
+ * Validated, defaulted RN map configuration. Mirrors the web SDK's
1323
+ * `YarrowMapConfig` minus the DOM container (the native view is sized by the
1324
+ * consuming app's layout) and minus web-only rendering options (hover,
1325
+ * clustering, controls, tile cache — none of which exist on native).
1326
+ */
1327
+ var YarrowMapConfig = class {
1328
+ constructor(config) {
1329
+ const { apiKey, center, zoom: resolvedZoom = 10, minZoom: resolvedMinZoom = 0, maxZoom: resolvedMaxZoom = 19, theme: resolvedTheme = "light", styleType: resolvedStyleType } = config;
1330
+ if (!apiKey) throw new Error("apiKey is required");
1331
+ this.center = center;
1332
+ this.zoom = resolvedZoom;
1333
+ this.minZoom = resolvedMinZoom;
1334
+ this.maxZoom = resolvedMaxZoom;
1335
+ this.theme = resolvedTheme;
1336
+ this.styleType = normalizeStyleType(resolvedStyleType);
1337
+ this.apiKey = apiKey;
1338
+ }
1339
+ };
1340
+
1341
+ // src/maps/routing/types.ts
1342
+ /** Best-route + alternatives palette — same values as the web SDK's
1343
+ * `buildRoute()` defaults (index 0 is the best route, index 1 the shared
1344
+ * alternative color). */
1345
+ const ROUTE_LAYER_COLORS = [
1346
+ "#22c55e",
1347
+ "#aaaaaa",
1348
+ "#cccccc",
1349
+ "#dddddd",
1350
+ "#eeeeee"
1351
+ ];
1352
+ /** Distinct-series palette — same values as the web SDK's `renderRoutes()`. */
1353
+ const ROUTE_COLORS = [
1354
+ "#3b82f6",
1355
+ "#10b981",
1356
+ "#f59e0b",
1357
+ "#ef4444",
1358
+ "#8b5cf6"
1359
+ ];
1360
+
1361
+ // src/maps/routing/RouteLayer.tsx
1362
+ const DEFAULT_LAYER_PREFIX = "yarrow-route";
1363
+ /** Line styling of `renderRoutes()` — web parity for the distinct series. */
1364
+ const DISTINCT_ROUTE_WIDTH = 4;
1365
+ const DISTINCT_ROUTE_OPACITY = .8;
1366
+ const toFeatureCollection = (route) => ({
1367
+ type: "FeatureCollection",
1368
+ features: [route]
1369
+ });
1370
+ /**
1371
+ * Declarative route rendering: one GeoJSON source + line layer per route.
1372
+ * Compose inside `<YarrowMapView>` and drive it with `useYarrowRouting()`:
1373
+ *
1374
+ * ```tsx
1375
+ * const { routes } = useYarrowRouting();
1376
+ * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
1377
+ * <RouteLayer routes={routes} onPressRoute={…} />
1378
+ * </YarrowMapView>
1379
+ * ```
1380
+ *
1381
+ * Pass `distinct` to render independent series instead of best-route-plus-
1382
+ * alternatives — the declarative counterpart of the web SDK's
1383
+ * `renderRoutes()`.
1384
+ */
1385
+ const RouteLayer = memo(function RouteLayer({ routes, bestIndex = 0, routeColor = ROUTE_LAYER_COLORS[0], routeWidth = 5, routeOpacity = 1, alternativeColor = ROUTE_LAYER_COLORS[1], alternativeWidth = 2.5, alternativeOpacity = .5, layerPrefix = DEFAULT_LAYER_PREFIX, onPressRoute, distinct = false }) {
1386
+ const styleFor = (index) => {
1387
+ if (distinct) return {
1388
+ color: ROUTE_COLORS[index % ROUTE_COLORS.length],
1389
+ width: DISTINCT_ROUTE_WIDTH,
1390
+ opacity: DISTINCT_ROUTE_OPACITY
1391
+ };
1392
+ const isBest = index === bestIndex;
1393
+ return {
1394
+ color: isBest ? routeColor : alternativeColor,
1395
+ width: isBest ? routeWidth : alternativeWidth,
1396
+ opacity: isBest ? routeOpacity : alternativeOpacity
1397
+ };
1398
+ };
1399
+ return routes.map((route, index) => {
1400
+ const sourceId = `${layerPrefix}-${index}`;
1401
+ const { color, width, opacity } = styleFor(index);
1402
+ return /* @__PURE__ */ jsx(GeoJSONSource, {
1403
+ id: sourceId,
1404
+ data: toFeatureCollection(route),
1405
+ onPress: onPressRoute ? (event) => onPressRoute(event, index) : void 0,
1406
+ children: /* @__PURE__ */ jsx(Layer, {
1407
+ id: `${layerPrefix}-line-${index}`,
1408
+ type: "line",
1409
+ layout: {
1410
+ "line-cap": "round",
1411
+ "line-join": "round"
1412
+ },
1413
+ paint: {
1414
+ "line-color": color,
1415
+ "line-width": width,
1416
+ "line-opacity": opacity
1417
+ }
1418
+ })
1419
+ }, sourceId);
1420
+ });
1421
+ });
1422
+
1423
+ // src/maps/styles.ts
1424
+ /**
1425
+ * Full style URL for MapLibre React Native's `mapStyle` prop, built from the
1426
+ * platform-agnostic style endpoint plus the configured API key. The key comes
1427
+ * from core's module state (`setYarrowApiKey`) — `YarrowMapView` calls it for
1428
+ * you; standalone callers must set it first or this throws a coded
1429
+ * `unauthorized` `YarrowApiError` (instead of producing a keyless style URL
1430
+ * that fails opaquely on the native side).
1431
+ */
1432
+ function buildStyleUrl(styleType, theme = "light") {
1433
+ getYarrowApiKey();
1434
+ const endpoint = buildStyleEndpoint(normalizeStyleType(styleType), theme);
1435
+ return addApiKeyToUrl(`${YARROW_MAP_URL}${endpoint}`);
1436
+ }
1437
+
1438
+ // src/maps/YarrowMapView.tsx
1439
+ const assignRef = (ref, instance) => {
1440
+ if (typeof ref === "function") ref(instance);
1441
+ else if (ref) ref.current = instance;
1442
+ };
1443
+ /** Hides the API key when a style URL is echoed into an error message. */
1444
+ const redactApiKey = (url) => url.replace(/([?&])api_key=[^&]*/g, "$1api_key=***");
1445
+ /**
1446
+ * React Native Yarrow map. Renders MapLibre Native with a Yarrow style URL
1447
+ * (theme + styleType aware, API key attached) and a default camera, and
1448
+ * provides the runtime (refs, icon registry, camera/event subscriptions) to
1449
+ * the SDK layers rendered inside it.
1450
+ *
1451
+ * ```tsx
1452
+ * const mapRef = useRef<MapRef>(null);
1453
+ * <YarrowMapView
1454
+ * apiKey="YOUR_API_KEY"
1455
+ * center={[69.2401, 41.2995]} // Tashkent
1456
+ * zoom={12}
1457
+ * theme="dark"
1458
+ * onReady={(map) => map.getCenter().then(console.log)}
1459
+ * />
1460
+ * ```
1461
+ *
1462
+ * Camera props (`center`, `zoom`) apply only on mount — recenter through
1463
+ * `cameraRef` (`flyTo`, `jumpTo`, `fitBounds`). Theme and styleType changes
1464
+ * hot-swap the style URL natively.
1465
+ */
1466
+ const YarrowMapView = forwardRef(({ apiKey, center, zoom, minZoom, maxZoom, theme, styleType, onReady, onLoadError, onPress, onMoveEnd, cameraRef, attribution = false, logo = false, compass = true, brandBadgePosition, brandBadgeScale, androidView, dauTracking = true, icons = true, onIconsError, style, children }, ref) => {
1467
+ const config = useMemo(() => new YarrowMapConfig({
1468
+ apiKey,
1469
+ center,
1470
+ zoom,
1471
+ minZoom,
1472
+ maxZoom,
1473
+ theme,
1474
+ styleType
1475
+ }), [
1476
+ apiKey,
1477
+ center,
1478
+ zoom,
1479
+ minZoom,
1480
+ maxZoom,
1481
+ theme,
1482
+ styleType
1483
+ ]);
1484
+ const readyRef = useRef(onReady);
1485
+ readyRef.current = onReady;
1486
+ const dauTrackedRef = useRef(false);
1487
+ const mapRef = useRef(null);
1488
+ const internalCameraRef = useRef(null);
1489
+ const highlightedPoiIds = useRef(/* @__PURE__ */ new Set());
1490
+ const [iconsByName, setIconsByName] = useState({});
1491
+ const iconsFetchAttemptedRef = useRef(false);
1492
+ const onIconsErrorRef = useRef(onIconsError);
1493
+ onIconsErrorRef.current = onIconsError;
1494
+ useEffect(() => {
1495
+ iconsFetchAttemptedRef.current = false;
1496
+ if (!icons) {
1497
+ setIconsByName({});
1498
+ return;
1499
+ }
1500
+ let cancelled = false;
1501
+ fetchYarrowIcons(config.apiKey).then((map) => {
1502
+ if (!cancelled) {
1503
+ iconsFetchAttemptedRef.current = true;
1504
+ setIconsByName(map);
1505
+ }
1506
+ }).catch((error) => {
1507
+ console.warn("[YarrowMap] icon registry fetch failed:", error);
1508
+ onIconsErrorRef.current?.(error);
1509
+ });
1510
+ return () => {
1511
+ cancelled = true;
1512
+ };
1513
+ }, [config.apiKey, icons]);
1514
+ const handleMissingIcon = useCallback(() => {
1515
+ if (!icons || iconsFetchAttemptedRef.current) return;
1516
+ iconsFetchAttemptedRef.current = true;
1517
+ fetchYarrowIcons(config.apiKey).then(setIconsByName).catch(() => {
1518
+ iconsFetchAttemptedRef.current = false;
1519
+ });
1520
+ }, [config.apiKey, icons]);
1521
+ const regionListeners = useRef(/* @__PURE__ */ new Set());
1522
+ const pressListeners = useRef(/* @__PURE__ */ new Set());
1523
+ const onMoveEndRef = useRef(onMoveEnd);
1524
+ onMoveEndRef.current = onMoveEnd;
1525
+ const onPressRef = useRef(onPress);
1526
+ onPressRef.current = onPress;
1527
+ const subscribeRegionChange = useCallback((listener) => {
1528
+ regionListeners.current.add(listener);
1529
+ return () => {
1530
+ regionListeners.current.delete(listener);
1531
+ };
1532
+ }, []);
1533
+ const subscribePress = useCallback((listener) => {
1534
+ pressListeners.current.add(listener);
1535
+ return () => {
1536
+ pressListeners.current.delete(listener);
1537
+ };
1538
+ }, []);
1539
+ const handleRegionDidChange = useCallback((event) => {
1540
+ const { center: lngLat, zoom: eventZoom } = event.nativeEvent;
1541
+ const [lng, lat] = lngLat;
1542
+ for (const listener of regionListeners.current) listener({
1543
+ center: [lng, lat],
1544
+ zoom: eventZoom
1545
+ });
1546
+ onMoveEndRef.current?.(lat, lng, eventZoom);
1547
+ }, []);
1548
+ const handleMapPress = useCallback((event) => {
1549
+ const lngLat = event.nativeEvent?.lngLat;
1550
+ const point = event.nativeEvent?.point;
1551
+ if (lngLat && point) {
1552
+ const press = {
1553
+ lngLat: [lngLat[0], lngLat[1]],
1554
+ point: [point[0], point[1]]
1555
+ };
1556
+ for (const listener of pressListeners.current) listener(press);
1557
+ }
1558
+ onPressRef.current?.(event);
1559
+ }, []);
1560
+ const mapStyle = useMemo(() => {
1561
+ setYarrowApiKey(config.apiKey);
1562
+ return buildStyleUrl(config.styleType, config.theme);
1563
+ }, [config]);
1564
+ const handleDidFinishLoadingMap = useCallback(() => {
1565
+ if (dauTracking && !dauTrackedRef.current) {
1566
+ dauTrackedRef.current = true;
1567
+ trackDau$1(config.apiKey, "react-native");
1568
+ }
1569
+ const map = mapRef.current;
1570
+ if (map) readyRef.current?.(map);
1571
+ }, [config.apiKey, dauTracking]);
1572
+ const handleDidFailLoadingMap = useCallback((_event) => {
1573
+ onLoadError?.(/* @__PURE__ */ new Error("Yarrow map failed to load — check the API key and network. Opening the style URL in a browser shows the underlying response: " + redactApiKey(mapStyle)));
1574
+ }, [onLoadError, mapStyle]);
1575
+ const runtime = useMemo(() => ({
1576
+ apiKey: config.apiKey,
1577
+ theme: config.theme,
1578
+ mapRef,
1579
+ cameraRef: internalCameraRef,
1580
+ iconsByName,
1581
+ highlightedPoiIds,
1582
+ subscribeRegionChange,
1583
+ subscribePress
1584
+ }), [
1585
+ config.apiKey,
1586
+ config.theme,
1587
+ iconsByName,
1588
+ subscribeRegionChange,
1589
+ subscribePress
1590
+ ]);
1591
+ return /* @__PURE__ */ jsx(YarrowMapContext.Provider, {
1592
+ value: runtime,
1593
+ children: /* @__PURE__ */ jsxs(View, {
1594
+ style: [styles$1.container, style],
1595
+ children: [/* @__PURE__ */ jsxs(Map$1, {
1596
+ ref: (instance) => {
1597
+ mapRef.current = instance;
1598
+ assignRef(ref, instance);
1599
+ },
1600
+ mapStyle,
1601
+ style: styles$1.map,
1602
+ androidView,
1603
+ attribution,
1604
+ logo,
1605
+ compass,
1606
+ onPress: handleMapPress,
1607
+ onRegionDidChange: handleRegionDidChange,
1608
+ onDidFinishLoadingMap: handleDidFinishLoadingMap,
1609
+ onDidFailLoadingMap: handleDidFailLoadingMap,
1610
+ children: [
1611
+ /* @__PURE__ */ jsx(Camera, {
1612
+ ref: (instance) => {
1613
+ internalCameraRef.current = instance;
1614
+ assignRef(cameraRef, instance);
1615
+ },
1616
+ initialViewState: {
1617
+ center: config.center,
1618
+ zoom: config.zoom
1619
+ },
1620
+ minZoom: config.minZoom,
1621
+ maxZoom: config.maxZoom
1622
+ }),
1623
+ icons ? /* @__PURE__ */ jsx(YarrowImages, {
1624
+ iconsByName,
1625
+ onMissingIcon: handleMissingIcon
1626
+ }) : null,
1627
+ children
1628
+ ]
1629
+ }), /* @__PURE__ */ jsx(BrandBadge, {
1630
+ theme: config.theme,
1631
+ position: brandBadgePosition,
1632
+ scale: brandBadgeScale
1633
+ })]
1634
+ })
1635
+ });
1636
+ });
1637
+ const styles$1 = StyleSheet.create({
1638
+ container: { flex: 1 },
1639
+ map: { flex: 1 }
1640
+ });
1641
+
1642
+ // src/markers/HighlightMarkerView.tsx
1643
+ const ENTER_MS = 280;
1644
+ const EXIT_MS = 200;
1645
+ const DEFAULT_ICON_SIZE = 56;
1646
+ /**
1647
+ * The animated icon+label marker shared by `<PoiHighlightLayer>` and
1648
+ * `<SearchResultsLayer>` — the native counterpart of the web SDK's
1649
+ * `createMarkerElement` + enter/exit CSS transitions. The scale/fade runs on
1650
+ * an inner view (never on the `Marker` itself, which the map repositions
1651
+ * every frame).
1652
+ */
1653
+ const HighlightMarkerView = memo(function HighlightMarkerView({ lngLat, iconUrl, title, iconSize, leaving = false, onPress }) {
1654
+ const progress = useRef(new Animated.Value(0)).current;
1655
+ useEffect(() => {
1656
+ Animated.timing(progress, {
1657
+ toValue: leaving ? 0 : 1,
1658
+ duration: leaving ? EXIT_MS : ENTER_MS,
1659
+ useNativeDriver: true
1660
+ }).start();
1661
+ }, [progress, leaving]);
1662
+ const [width, height] = iconSize ? Array.isArray(iconSize) ? iconSize : [iconSize, iconSize] : [DEFAULT_ICON_SIZE, DEFAULT_ICON_SIZE];
1663
+ return /* @__PURE__ */ jsx(Marker, {
1664
+ lngLat,
1665
+ anchor: "center",
1666
+ onPress: onPress ? () => onPress() : void 0,
1667
+ children: /* @__PURE__ */ jsxs(Animated.View, {
1668
+ style: [styles.inner, {
1669
+ transform: [{ scale: progress }],
1670
+ opacity: progress
1671
+ }],
1672
+ children: [iconUrl ? /* @__PURE__ */ jsx(Image, {
1673
+ source: { uri: iconUrl },
1674
+ style: {
1675
+ width,
1676
+ height
1677
+ },
1678
+ resizeMode: "contain"
1679
+ }) : /* @__PURE__ */ jsx(View, { style: styles.dot }), title ? /* @__PURE__ */ jsx(View, {
1680
+ style: styles.titleWrap,
1681
+ pointerEvents: "none",
1682
+ children: /* @__PURE__ */ jsx(Text, {
1683
+ style: styles.title,
1684
+ children: title
1685
+ })
1686
+ }) : null]
1687
+ })
1688
+ });
1689
+ });
1690
+ const styles = StyleSheet.create({
1691
+ inner: {
1692
+ alignItems: "center",
1693
+ opacity: 0
1694
+ },
1695
+ dot: {
1696
+ width: 18,
1697
+ height: 18,
1698
+ borderRadius: 9,
1699
+ backgroundColor: "#2f80ed",
1700
+ borderWidth: 3,
1701
+ borderColor: "#ffffff"
1702
+ },
1703
+ titleWrap: {
1704
+ position: "absolute",
1705
+ top: "100%",
1706
+ width: "100%",
1707
+ alignItems: "center"
1708
+ },
1709
+ title: {
1710
+ marginTop: 3,
1711
+ maxWidth: 200,
1712
+ fontSize: 15,
1713
+ lineHeight: 18,
1714
+ fontWeight: "600",
1715
+ color: "#1a1a1a",
1716
+ textAlign: "center",
1717
+ textShadowColor: "#ffffff",
1718
+ textShadowRadius: 3,
1719
+ textShadowOffset: {
1720
+ width: 0,
1721
+ height: 0
1722
+ }
1723
+ }
1724
+ });
1725
+
1726
+ // src/markers/YarrowMarker.tsx
1727
+ /**
1728
+ * Declarative counterpart of the web SDK's `addMarker()` / `removeMarker()`.
1729
+ * Mounting places the marker, unmounting removes it; the React lifecycle
1730
+ * replaces the imperative manager pair.
1731
+ *
1732
+ * ```tsx
1733
+ * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
1734
+ * <YarrowMarker lngLat={[69.2401, 41.2995]} onPress={() => …}>
1735
+ * <PinIcon />
1736
+ * </YarrowMarker>
1737
+ * </YarrowMapView>
1738
+ * ```
1739
+ */
1740
+ const YarrowMarker = memo(function YarrowMarker({ lngLat, anchor = "bottom", offset, onPress, children }) {
1741
+ return /* @__PURE__ */ jsx(Marker, {
1742
+ lngLat,
1743
+ anchor,
1744
+ offset,
1745
+ onPress: onPress ? () => onPress() : void 0,
1746
+ children
1747
+ });
1748
+ });
1749
+
1750
+ // src/navigation/useYarrowCamera.ts
1751
+ const MIN_DIMENSION_DEGREES = .003;
1752
+ const DEFAULT_PADDING = 50;
1753
+ const DEFAULT_DURATION_MS = 1e3;
1754
+ /**
1755
+ * Web-parity camera helpers on top of a `CameraRef`. Reads the enclosing
1756
+ * `<YarrowMapView>` camera when called inside the map; otherwise pass a ref:
1757
+ *
1758
+ * ```tsx
1759
+ * const cameraRef = useRef<CameraRef>(null);
1760
+ * <YarrowMapView apiKey={KEY} cameraRef={cameraRef}>…</YarrowMapView>
1761
+ * const camera = useYarrowCamera(cameraRef);
1762
+ * camera.zoomTo(41.2995, 69.2401, 14);
1763
+ * ```
1764
+ */
1765
+ function useYarrowCamera(cameraRefInput) {
1766
+ const runtime = useYarrowMapRuntime();
1767
+ const cameraRef = cameraRefInput ?? runtime?.cameraRef ?? null;
1768
+ return useMemo(() => {
1769
+ const getCamera = () => cameraRef?.current ?? null;
1770
+ return {
1771
+ zoomTo(lat, lng, zoom, options) {
1772
+ const camera = getCamera();
1773
+ if (!camera) return;
1774
+ camera.flyTo({
1775
+ center: [lng, lat],
1776
+ zoom,
1777
+ ...options?.duration !== void 0 ? { duration: options.duration } : {}
1778
+ });
1779
+ },
1780
+ fitBounds(data, options) {
1781
+ const camera = getCamera();
1782
+ if (!camera) return;
1783
+ const box = getBoundingBox(data);
1784
+ if (data.features.length === 0 || box.xMin > box.xMax || box.yMin > box.yMax) {
1785
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[YarrowMap] fitBounds: nothing to fit — the FeatureCollection is empty or none of its geometries produced coordinates.");
1786
+ return;
1787
+ }
1788
+ const padding = options?.padding ?? DEFAULT_PADDING;
1789
+ const duration = options?.duration ?? DEFAULT_DURATION_MS;
1790
+ if (Math.abs(box.xMax - box.xMin) < MIN_DIMENSION_DEGREES) {
1791
+ box.xMin -= MIN_DIMENSION_DEGREES / 2;
1792
+ box.xMax += MIN_DIMENSION_DEGREES / 2;
1793
+ }
1794
+ if (Math.abs(box.yMax - box.yMin) < MIN_DIMENSION_DEGREES) {
1795
+ box.yMin -= MIN_DIMENSION_DEGREES / 2;
1796
+ box.yMax += MIN_DIMENSION_DEGREES / 2;
1797
+ }
1798
+ camera.fitBounds([
1799
+ box.xMin,
1800
+ box.yMin,
1801
+ box.xMax,
1802
+ box.yMax
1803
+ ], {
1804
+ padding: {
1805
+ top: padding,
1806
+ right: padding,
1807
+ bottom: padding,
1808
+ left: padding
1809
+ },
1810
+ duration
1811
+ });
1812
+ },
1813
+ getBoundingBox(data) {
1814
+ return getBoundingBox(data);
1815
+ }
1816
+ };
1817
+ }, [cameraRef]);
1818
+ }
1819
+
1820
+ // src/offline/estimate.ts
1821
+ /**
1822
+ * Web-Mercator latitude limit — tiles outside it don't exist.
1823
+ */
1824
+ const MAX_LAT = 85.05112878;
1825
+ /**
1826
+ * Rough bytes per downloaded `z/x/y` tile, empirically measured from a
1827
+ * Tashkent z14 tile: ≈64 KB × ~8 sources carrying data ≈ 0.5 MB. A region's
1828
+ * true size depends on the style's source count and local data density —
1829
+ * pass `avgTileBytes` for a tighter estimate.
1830
+ */
1831
+ const AVG_TILE_BYTES = 5e5;
1832
+ /**
1833
+ * Bounds must not cross the antimeridian — `west < east` strictly. Regions
1834
+ * spanning ±180° need two downloads or a shifted projection.
1835
+ */
1836
+ const validateBounds = (bounds) => {
1837
+ 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");
1838
+ const [west, south, east, north] = bounds;
1839
+ if (west < -180 || west > 180 || east < -180 || east > 180) throw new Error("bounds longitudes must be within [-180, 180]");
1840
+ 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}]`);
1841
+ if (west >= east) throw new Error("bounds west longitude must be less than east");
1842
+ if (south >= north) throw new Error("bounds south latitude must be less than north");
1843
+ };
1844
+ const validateZoomRange = (minZoom, maxZoom) => {
1845
+ if (!Number.isFinite(minZoom) || !Number.isFinite(maxZoom) || minZoom < 0 || maxZoom > 22 || minZoom > maxZoom) throw new Error("zoom range must satisfy 0 <= minZoom <= maxZoom <= 22");
1846
+ };
1847
+ const lngToWorldX = (lng, zoom) => {
1848
+ return (Math.min(180, Math.max(-180, lng)) + 180) / 360 * 2 ** zoom;
1849
+ };
1850
+ const latToWorldY = (lat, zoom) => {
1851
+ const radians = Math.min(MAX_LAT, Math.max(-85.05112878, lat)) * Math.PI / 180;
1852
+ return (1 - Math.log(Math.tan(radians) + 1 / Math.cos(radians)) / Math.PI) / 2 * 2 ** zoom;
1853
+ };
1854
+ /** Unique `z/x/y` tiles covering the bounds at one zoom level. */
1855
+ const countTilesAtZoom = (bounds, zoom) => {
1856
+ const [west, south, east, north] = bounds;
1857
+ const maxTile = 2 ** zoom - 1;
1858
+ const clamp = (index) => Math.min(maxTile, Math.max(0, index));
1859
+ const x0 = clamp(Math.floor(lngToWorldX(west, zoom)));
1860
+ const x1 = clamp(Math.floor(lngToWorldX(east, zoom)));
1861
+ const y0 = clamp(Math.floor(latToWorldY(north, zoom)));
1862
+ const y1 = clamp(Math.floor(latToWorldY(south, zoom)));
1863
+ return (x1 - x0 + 1) * (y1 - y0 + 1);
1864
+ };
1865
+ /**
1866
+ * Estimates the download/storage cost of an offline region — pure tile math,
1867
+ * no native calls. Tile counts are exact for the XYZ scheme; byte estimates
1868
+ * are rough (see `AVG_TILE_BYTES`).
1869
+ *
1870
+ * ```ts
1871
+ * const { tileCount, estSizeBytes } = estimateRegion({
1872
+ * bounds: [69.15, 41.2, 69.4, 41.4], // Tashkent
1873
+ * minZoom: 8,
1874
+ * maxZoom: 15,
1875
+ * });
1876
+ * ```
1877
+ */
1878
+ const estimateRegion = (input) => {
1879
+ validateBounds(input.bounds);
1880
+ const { bounds, avgTileBytes = AVG_TILE_BYTES, minZoom, maxZoom } = input;
1881
+ validateZoomRange(minZoom, maxZoom);
1882
+ const tilesPerLevel = [];
1883
+ let tileCount = 0;
1884
+ for (let zoom = Math.floor(minZoom); zoom <= Math.ceil(maxZoom); zoom++) {
1885
+ const tiles = countTilesAtZoom(bounds, zoom);
1886
+ tilesPerLevel.push({
1887
+ zoom,
1888
+ tiles
1889
+ });
1890
+ tileCount += tiles;
1891
+ }
1892
+ return {
1893
+ tileCount,
1894
+ estSizeBytes: tileCount * avgTileBytes,
1895
+ tilesPerLevel
1896
+ };
1897
+ };
1898
+
1899
+ // src/offline/types.ts
1900
+ /** Default minimum zoom for offline regions. */
1901
+ const DEFAULT_OFFLINE_MIN_ZOOM = 8;
1902
+ /** Default maximum zoom for offline regions. */
1903
+ const DEFAULT_OFFLINE_MAX_ZOOM = 15;
1904
+ /** Schema version of the pack metadata this SDK writes. */
1905
+ const OFFLINE_METADATA_VERSION = 1;
1906
+
1907
+ // src/offline/manager.ts
1908
+ const DAY_MS = MILLISECONDS_PER_DAY;
1909
+ const stripId = (status) => {
1910
+ const { id: _id, ...progress } = status;
1911
+ return progress;
1912
+ };
1913
+ /** Reads pack status, treating bridge-level absence (Android resolves null
1914
+ * for unknown ids — e.g. after `resetDatabase` without an app restart) as
1915
+ * `null` instead of a crash. */
1916
+ const statusOrNull = async (pack) => {
1917
+ try {
1918
+ return await pack.status() ?? null;
1919
+ } catch {
1920
+ return null;
1921
+ }
1922
+ };
1923
+ const notFoundError = (name, regionId) => {
1924
+ const error = /* @__PURE__ */ new Error(`Offline region "${name}" is no longer available natively — resetDatabase() requires an app restart to clear the JS cache.`);
1925
+ error.code = "not-found";
1926
+ error.regionId = regionId;
1927
+ return error;
1928
+ };
1929
+ /** Rejection for handles stranded by deleting a pack they point at. */
1930
+ const deletedRegionError = (name, regionId, forced) => {
1931
+ const reason = forced ? "was replaced by a forced re-download — its previous download will not finish; await the new downloadRegion call's handle instead" : "was deleted";
1932
+ const label = name ? `"${name}"` : regionId;
1933
+ const error = /* @__PURE__ */ new Error(`Offline region ${label} ${reason}.`);
1934
+ error.code = "not-found";
1935
+ error.regionId = regionId;
1936
+ return error;
1937
+ };
1938
+ const asYarrowMetadata = (pack) => {
1939
+ const meta = pack.metadata;
1940
+ if (!meta || meta.v !== 1 || typeof meta.name !== "string") return null;
1941
+ return meta;
1942
+ };
1943
+ const classifyError = (raw, regionId) => {
1944
+ const message = raw instanceof Error ? raw.message : typeof raw === "string" ? raw : "Unknown offline error";
1945
+ let code = "unknown";
1946
+ if (/tile (count )?limit|tile limit exceeded/i.test(message)) code = "tile-count-limit-exceeded";
1947
+ else if (/too large|region exceeds/i.test(message)) code = "region-too-large";
1948
+ else if (/disk|storage|space/i.test(message)) code = "disk";
1949
+ else if (/not\s*found/i.test(message)) code = "not-found";
1950
+ else if (/network|connection|offline|unreachable|timeout|resolve|host/i.test(message)) code = "network";
1951
+ const error = new Error(message);
1952
+ error.code = code;
1953
+ if (regionId) error.regionId = regionId;
1954
+ return error;
1955
+ };
1956
+ /**
1957
+ * Offline region manager for React Native — a Yarrow-flavoured wrapper around
1958
+ * MapLibre React Native's `OfflineManager`.
1959
+ *
1960
+ * The web SDK's `yarrowcache` protocol cannot exist on native (no
1961
+ * `addProtocol`), so offline support here is region packs: pick a bounding
1962
+ * box and zoom range, download it once, and the map renders from the native
1963
+ * offline database with no network.
1964
+ *
1965
+ * ```ts
1966
+ * const offline = new YarrowOfflineManager({ apiKey: 'YOUR_API_KEY' });
1967
+ * const { tileCount, estSizeBytes } = offline.estimateRegion({
1968
+ * bounds: [69.15, 41.2, 69.4, 41.4], // Tashkent
1969
+ * minZoom: 8,
1970
+ * maxZoom: 15,
1971
+ * });
1972
+ * const region = await offline.downloadRegion({
1973
+ * name: 'tashkent-city',
1974
+ * bounds: [69.15, 41.2, 69.4, 41.4],
1975
+ * maxAgeDays: 30,
1976
+ * onProgress: (p) => console.log(`${p.percentage}%`),
1977
+ * });
1978
+ * await region.done;
1979
+ * ```
1980
+ */
1981
+ var YarrowOfflineManager = class {
1982
+ constructor(options) {
1983
+ this.activeDownloads = /* @__PURE__ */ new Map();
1984
+ this.liveChannels = /* @__PURE__ */ new Map();
1985
+ if (!options.apiKey) throw new Error("apiKey is required");
1986
+ this.apiKey = options.apiKey;
1987
+ setYarrowApiKey(this.apiKey);
1988
+ }
1989
+ /**
1990
+ * Creates a `done` promise together with its settlement channel. The
1991
+ * channel registers itself under the pack id (lazily — the id is often
1992
+ * only known after `createPack` resolves, or when the first event arrives)
1993
+ * so a later deletion can reject every outstanding `done` for that pack.
1994
+ */
1995
+ createPendingDone() {
1996
+ let resolveDone;
1997
+ let rejectDone;
1998
+ const done = new Promise((resolve, reject) => {
1999
+ resolveDone = resolve;
2000
+ rejectDone = reject;
2001
+ });
2002
+ done.catch(() => {});
2003
+ let trackedId = null;
2004
+ let settled = false;
2005
+ const unregister = () => {
2006
+ if (!trackedId) return;
2007
+ const channels = this.liveChannels.get(trackedId);
2008
+ channels?.delete(channel);
2009
+ if (channels && channels.size === 0) this.liveChannels.delete(trackedId);
2010
+ };
2011
+ const channel = {
2012
+ settle: ({ progress, error }) => {
2013
+ if (settled) return;
2014
+ settled = true;
2015
+ unregister();
2016
+ if (error) rejectDone(error);
2017
+ else if (progress) resolveDone(progress);
2018
+ },
2019
+ track: (packId) => {
2020
+ if (settled) return;
2021
+ if (trackedId === packId) return;
2022
+ if (trackedId !== null) unregister();
2023
+ trackedId = packId;
2024
+ let channels = this.liveChannels.get(packId);
2025
+ if (!channels) {
2026
+ channels = /* @__PURE__ */ new Set();
2027
+ this.liveChannels.set(packId, channels);
2028
+ }
2029
+ channels.add(channel);
2030
+ }
2031
+ };
2032
+ return {
2033
+ done,
2034
+ channel
2035
+ };
2036
+ }
2037
+ /**
2038
+ * Pure tile-math estimate of a region's download/storage cost — no native
2039
+ * calls. See `estimateRegion` for the math and caveats.
2040
+ */
2041
+ estimateRegion(input) {
2042
+ return estimateRegion(input);
2043
+ }
2044
+ /**
2045
+ * Starts (or resumes) a region download. Resolves with a handle once the
2046
+ * pack is created and downloading — progress arrives via `options.onProgress`
2047
+ * and `handle.done` settles with the outcome.
2048
+ *
2049
+ * Idempotent by `name`: an existing matching region is returned as-is
2050
+ * (resumed when incomplete); a name reused with different parameters throws
2051
+ * a `params-mismatch` error. Pass `force: true` to delete and re-download.
2052
+ */
2053
+ async downloadRegion(options) {
2054
+ const name = options.name?.trim();
2055
+ if (!name) throw new Error("name is required");
2056
+ const bounds = options.bounds;
2057
+ validateBounds(bounds);
2058
+ const minZoom = options.minZoom ?? 8;
2059
+ const maxZoom = options.maxZoom ?? 15;
2060
+ validateZoomRange(minZoom, maxZoom);
2061
+ const styleType = normalizeStyleType(options.styleType);
2062
+ const theme = options.theme === "dark" ? "dark" : "light";
2063
+ await this.hydrate();
2064
+ const existing = await this.findRegionPacks(name);
2065
+ const target = existing.find((pack) => pack.meta.styleType === styleType && pack.meta.theme === theme);
2066
+ if (target && !options.force) {
2067
+ const mismatches = this.findParamMismatches(target.meta, {
2068
+ bounds,
2069
+ minZoom,
2070
+ maxZoom,
2071
+ maxAgeDays: options.maxAgeDays ?? null
2072
+ });
2073
+ if (mismatches.length > 0) {
2074
+ const error = /* @__PURE__ */ new Error(`Region "${name}" already exists with different ${mismatches.join(", ")}. Use a different name or pass force: true to re-download.`);
2075
+ error.code = "params-mismatch";
2076
+ error.regionId = target.pack.id;
2077
+ throw error;
2078
+ }
2079
+ return this.reattachExisting(target, { resumeIfIncomplete: true });
2080
+ }
2081
+ if (existing.length > 0 && !options.force) {
2082
+ const styles = existing.map(({ meta }) => `${meta.styleType}/${meta.theme}`).join(", ");
2083
+ const error = /* @__PURE__ */ new Error(`Region "${name}" is pinned to ${styles}. Use a different name or pass force: true to replace it.`);
2084
+ error.code = "params-mismatch";
2085
+ throw error;
2086
+ }
2087
+ for (const { pack, meta } of existing) await this.deletePack(pack.id, {
2088
+ name: meta.name,
2089
+ forced: true
2090
+ });
2091
+ setYarrowApiKey(this.apiKey);
2092
+ const metadata = {
2093
+ v: 1,
2094
+ name,
2095
+ styleType,
2096
+ theme,
2097
+ bounds,
2098
+ minZoom,
2099
+ maxZoom,
2100
+ maxAgeDays: options.maxAgeDays ?? null,
2101
+ createdAt: Date.now(),
2102
+ ...options.metadata ? { user: options.metadata } : {}
2103
+ };
2104
+ const { done, channel } = this.createPendingDone();
2105
+ const settle = channel.settle;
2106
+ const routeProgress = (_pack, status) => {
2107
+ channel.track(_pack.id);
2108
+ const progress = stripId(status);
2109
+ if (status.state === "complete") {
2110
+ this.activeDownloads.delete(_pack.id);
2111
+ settle({ progress });
2112
+ } else options.onProgress?.(progress);
2113
+ };
2114
+ const routeError = (_pack, raw) => {
2115
+ channel.track(_pack.id);
2116
+ this.activeDownloads.delete(_pack.id);
2117
+ const error = classifyError(raw.message, _pack.id);
2118
+ options.onError?.(error);
2119
+ settle({ error });
2120
+ };
2121
+ try {
2122
+ const pack = await OfflineManager.createPack({
2123
+ mapStyle: buildStyleUrl(styleType, theme),
2124
+ bounds,
2125
+ minZoom,
2126
+ maxZoom,
2127
+ metadata
2128
+ }, routeProgress, routeError);
2129
+ this.activeDownloads.set(pack.id, { done });
2130
+ channel.track(pack.id);
2131
+ const status = await statusOrNull(pack);
2132
+ if (status?.state === "complete") {
2133
+ OfflineManager.removeListener(pack.id);
2134
+ this.activeDownloads.delete(pack.id);
2135
+ settle({ progress: stripId(status) });
2136
+ }
2137
+ return this.toHandle(pack, metadata, done);
2138
+ } catch (caught) {
2139
+ throw classifyError(caught);
2140
+ }
2141
+ }
2142
+ /** Lists regions created through this SDK (native packs created directly
2143
+ * against `OfflineManager` are not included), newest first. */
2144
+ async listRegions() {
2145
+ const packs = await OfflineManager.getPacks();
2146
+ const summaries = [];
2147
+ for (const pack of packs) {
2148
+ const meta = asYarrowMetadata(pack);
2149
+ if (!meta) continue;
2150
+ const status = await statusOrNull(pack);
2151
+ if (!status) continue;
2152
+ summaries.push({
2153
+ id: pack.id,
2154
+ name: meta.name,
2155
+ styleType: meta.styleType,
2156
+ theme: meta.theme,
2157
+ bounds: meta.bounds,
2158
+ minZoom: meta.minZoom,
2159
+ maxZoom: meta.maxZoom,
2160
+ status: status.state,
2161
+ percentage: status.percentage,
2162
+ completedTileSize: status.completedTileSize,
2163
+ userMetadata: meta.user,
2164
+ isStale: meta.maxAgeDays !== null && Date.now() - meta.createdAt > meta.maxAgeDays * DAY_MS,
2165
+ createdAt: meta.createdAt
2166
+ });
2167
+ }
2168
+ return summaries.sort((a, b) => b.createdAt - a.createdAt);
2169
+ }
2170
+ /** Returns the handle for a region by name, or `null`. */
2171
+ async getRegion(name) {
2172
+ const entry = (await this.findRegionPacks(name.trim()))[0];
2173
+ if (!entry) return null;
2174
+ return this.reattachExisting(entry);
2175
+ }
2176
+ /** Ambient cache (seen-tiles LRU) max size in bytes. May erase resources
2177
+ * when shrinking — call once at app startup. `0` disables the cache. */
2178
+ async setAmbientCacheSize(size) {
2179
+ await OfflineManager.setMaximumAmbientCacheSize(size);
2180
+ }
2181
+ /** Revalidates ambient-cache tiles against the server — the recommended
2182
+ * way to refresh cached data. */
2183
+ async invalidateAmbientCache() {
2184
+ await OfflineManager.invalidateAmbientCache();
2185
+ }
2186
+ /** Erases ambient-cache resources. Computationally expensive. */
2187
+ async clearAmbientCache() {
2188
+ await OfflineManager.clearAmbientCache();
2189
+ }
2190
+ /** Maximum number of tiles offline packs may store. Raise it when large
2191
+ * regions fail with a `tile-count-limit-exceeded` error. */
2192
+ setTileCountLimit(limit) {
2193
+ OfflineManager.setTileCountLimit(limit);
2194
+ }
2195
+ /** Download status event throttle in ms. Platform-defined default (300 ms
2196
+ * today on both iOS and Android). Note errors bypass the throttle. */
2197
+ setProgressEventThrottle(ms) {
2198
+ OfflineManager.setProgressEventThrottle(ms);
2199
+ }
2200
+ /** Deletes the offline database (ambient cache + packs), then
2201
+ * reinitializes it. Destructive — and MLRN's JS pack cache only clears
2202
+ * on app restart, so subsequent reads may hit stale ids (guarded as
2203
+ * `not-found`). Prefer per-region `invalidate`/`delete`. */
2204
+ async resetDatabase() {
2205
+ await OfflineManager.resetDatabase();
2206
+ }
2207
+ async hydrate() {
2208
+ await OfflineManager.getPacks();
2209
+ }
2210
+ async findRegionPacks(name) {
2211
+ return (await OfflineManager.getPacks()).map((pack) => ({
2212
+ pack,
2213
+ meta: asYarrowMetadata(pack)
2214
+ })).filter((entry) => entry.meta !== null && entry.meta.name === name);
2215
+ }
2216
+ findParamMismatches(meta, params) {
2217
+ const mismatches = [];
2218
+ if (!(meta.bounds.length === params.bounds.length && meta.bounds.every((value, index) => value === params.bounds[index]))) mismatches.push("bounds");
2219
+ if (meta.minZoom !== params.minZoom) mismatches.push("minZoom");
2220
+ if (meta.maxZoom !== params.maxZoom) mismatches.push("maxZoom");
2221
+ if (meta.maxAgeDays !== params.maxAgeDays) mismatches.push("maxAgeDays");
2222
+ return mismatches;
2223
+ }
2224
+ /** Attaches listeners to a pack that may have outlived the JS layer
2225
+ * (created in a previous app session) and builds a fresh handle.
2226
+ *
2227
+ * Deliberately cautious: it never hijacks a download this session owns,
2228
+ * never attaches listeners to packs that don't need them, and — on
2229
+ * Android, where attaching an observer *activates* the region — never
2230
+ * wakes a paused pack unless the caller explicitly asked for a download. */
2231
+ async reattachExisting(entry, { resumeIfIncomplete = false } = {}) {
2232
+ const { pack, meta } = entry;
2233
+ const known = this.activeDownloads.get(pack.id);
2234
+ if (known) return this.toHandle(pack, meta, known.done);
2235
+ const status = await statusOrNull(pack);
2236
+ if (!status) throw notFoundError(meta.name, pack.id);
2237
+ if (status.state === "complete") return this.toHandle(pack, meta, Promise.resolve(stripId(status)));
2238
+ const { done, channel } = this.createPendingDone();
2239
+ channel.track(pack.id);
2240
+ const settle = channel.settle;
2241
+ const routeProgress = (_pack, progressEvent) => {
2242
+ if (progressEvent.state === "complete") settle({ progress: stripId(progressEvent) });
2243
+ };
2244
+ const routeError = (_pack, raw) => {
2245
+ settle({ error: classifyError(raw.message, pack.id) });
2246
+ };
2247
+ if (status.state === "active" || resumeIfIncomplete) {
2248
+ OfflineManager.addListener(pack.id, routeProgress, routeError);
2249
+ if (status.state !== "active") await pack.resume();
2250
+ }
2251
+ return this.toHandle(pack, meta, done);
2252
+ }
2253
+ toHandle(pack, meta, done) {
2254
+ return {
2255
+ id: pack.id,
2256
+ name: meta.name,
2257
+ done,
2258
+ refreshStatus: async () => {
2259
+ const status = await statusOrNull(pack);
2260
+ if (!status) throw notFoundError(meta.name, pack.id);
2261
+ return stripId(status);
2262
+ },
2263
+ pause: () => pack.pause(),
2264
+ resume: () => pack.resume(),
2265
+ invalidate: async () => {
2266
+ await OfflineManager.invalidatePack(pack.id);
2267
+ },
2268
+ delete: async () => {
2269
+ await this.deletePack(pack.id);
2270
+ }
2271
+ };
2272
+ }
2273
+ /**
2274
+ * Deletes a pack natively and settles every outstanding handle: their
2275
+ * `done` rejects with a `not-found` YarrowOfflineError (a deleted pack
2276
+ * never emits another event, so awaiting `done` would otherwise hang
2277
+ * forever). `forced` marks the force-re-download path for the message.
2278
+ * Native failures leave handles untouched — the pack still exists.
2279
+ */
2280
+ async deletePack(id, context) {
2281
+ try {
2282
+ await OfflineManager.deletePack(id);
2283
+ } catch (caught) {
2284
+ throw classifyError(caught, id);
2285
+ } finally {
2286
+ this.activeDownloads.delete(id);
2287
+ }
2288
+ OfflineManager.removeListener(id);
2289
+ const channels = this.liveChannels.get(id);
2290
+ if (channels) {
2291
+ this.liveChannels.delete(id);
2292
+ const error = deletedRegionError(context?.name, id, context?.forced === true);
2293
+ for (const channel of channels) channel.settle({ error });
2294
+ }
2295
+ }
2296
+ };
2297
+
2298
+ // src/offline/hook.ts
2299
+ /**
2300
+ * Offline region state for settings/offline screens — pairs with
2301
+ * `YarrowOfflineManager`. Polls the native layer while downloads run, so
2302
+ * `regions` (and progress bars) stay current.
2303
+ *
2304
+ * ```tsx
2305
+ * const { regions, download, remove } = useYarrowOfflineRegions({ apiKey });
2306
+ * await download({ name: 'tashkent', bounds: [69.15, 41.2, 69.4, 41.4] });
2307
+ * ```
2308
+ */
2309
+ const useYarrowOfflineRegions = (options) => {
2310
+ const { apiKey, pollMs = 1e3 } = options;
2311
+ const [regions, setRegions] = useState([]);
2312
+ const [isLoading, setIsLoading] = useState(true);
2313
+ const [error, setError] = useState(null);
2314
+ const managerRef = useRef(null);
2315
+ const getManager = useCallback(() => {
2316
+ const cached = managerRef.current;
2317
+ if (cached && cached.key === apiKey) return cached.manager;
2318
+ const manager = new YarrowOfflineManager({ apiKey });
2319
+ managerRef.current = {
2320
+ key: apiKey,
2321
+ manager
2322
+ };
2323
+ return manager;
2324
+ }, [apiKey]);
2325
+ const recordError = useCallback((caught) => {
2326
+ const error = caught instanceof Error ? caught : new Error(String(caught));
2327
+ setError(error);
2328
+ return error;
2329
+ }, []);
2330
+ const refresh = useCallback(async () => {
2331
+ try {
2332
+ setRegions(await getManager().listRegions());
2333
+ setError(null);
2334
+ } catch (caught) {
2335
+ recordError(caught);
2336
+ }
2337
+ }, [getManager, recordError]);
2338
+ useEffect(() => {
2339
+ if (!apiKey) {
2340
+ setIsLoading(false);
2341
+ return;
2342
+ }
2343
+ let cancelled = false;
2344
+ (async () => {
2345
+ setIsLoading(true);
2346
+ try {
2347
+ const summaries = await getManager().listRegions();
2348
+ if (!cancelled) {
2349
+ setRegions(summaries);
2350
+ setError(null);
2351
+ }
2352
+ } catch (caught) {
2353
+ if (!cancelled) recordError(caught);
2354
+ } finally {
2355
+ if (!cancelled) setIsLoading(false);
2356
+ }
2357
+ })();
2358
+ return () => {
2359
+ cancelled = true;
2360
+ };
2361
+ }, [
2362
+ apiKey,
2363
+ getManager,
2364
+ recordError
2365
+ ]);
2366
+ const hasActive = regions.some((region) => region.status === "active");
2367
+ useEffect(() => {
2368
+ if (!hasActive) return;
2369
+ const timer = setInterval(() => {
2370
+ refresh();
2371
+ }, pollMs);
2372
+ return () => clearInterval(timer);
2373
+ }, [
2374
+ hasActive,
2375
+ pollMs,
2376
+ refresh
2377
+ ]);
2378
+ const download = useCallback(async (downloadOptions) => {
2379
+ try {
2380
+ const handle = await getManager().downloadRegion(downloadOptions);
2381
+ await refresh();
2382
+ return handle;
2383
+ } catch (caught) {
2384
+ throw recordError(caught);
2385
+ }
2386
+ }, [
2387
+ getManager,
2388
+ recordError,
2389
+ refresh
2390
+ ]);
2391
+ const withRegion = useCallback(async (name, run) => {
2392
+ try {
2393
+ const handle = await getManager().getRegion(name.trim());
2394
+ if (!handle) {
2395
+ const error = /* @__PURE__ */ new Error(`Offline region "${name}" not found`);
2396
+ error.code = "not-found";
2397
+ throw error;
2398
+ }
2399
+ await run(handle);
2400
+ await refresh();
2401
+ } catch (caught) {
2402
+ throw recordError(caught);
2403
+ }
2404
+ }, [
2405
+ getManager,
2406
+ recordError,
2407
+ refresh
2408
+ ]);
2409
+ return {
2410
+ regions,
2411
+ isLoading,
2412
+ error,
2413
+ refresh,
2414
+ download,
2415
+ pause: (name) => withRegion(name, (handle) => handle.pause()),
2416
+ resume: (name) => withRegion(name, (handle) => handle.resume()),
2417
+ invalidate: (name) => withRegion(name, (handle) => handle.invalidate()),
2418
+ remove: (name) => withRegion(name, (handle) => handle.delete())
2419
+ };
2420
+ };
2421
+
2422
+ // src/clustering/usePixelClusters.ts
2423
+ const REGION_DEBOUNCE_MS = 120;
2424
+ /**
2425
+ * Clusters marker points by screen distance — the runtime counterpart of the
2426
+ * web SDK's `PoiClusterController`. Native MapLibre can only cluster GeoJSON
2427
+ * *sources*, not marker views, so this re-projects the points on every map
2428
+ * move and regroups them: members of a group large enough (`minPoints`) are
2429
+ * hidden and replaced by a single count badge.
2430
+ *
2431
+ * Recompute runs when the points/config change and (debounced) on every map
2432
+ * move; badges are keyed by their first member id so React reuses them
2433
+ * across recomputes instead of flickering.
2434
+ */
2435
+ function usePixelClusters(points, config, runtime) {
2436
+ const normalized = useMemo(() => normalizeClusteringConfig(config), [config]);
2437
+ const [clusters, setClusters] = useState([]);
2438
+ const [clusteredIds, setClusteredIds] = useState(() => /* @__PURE__ */ new Set());
2439
+ const debounceRef = useRef(null);
2440
+ const runIdRef = useRef(0);
2441
+ const pointsRef = useRef(points);
2442
+ pointsRef.current = points;
2443
+ const pointsKey = useMemo(() => points.map((p) => `${p.id}:${p.lng},${p.lat}`).join("|"), [points]);
2444
+ useEffect(() => {
2445
+ const mapRef = runtime?.mapRef;
2446
+ if (!mapRef) {
2447
+ setClusters([]);
2448
+ setClusteredIds(/* @__PURE__ */ new Set());
2449
+ return;
2450
+ }
2451
+ const recompute = async () => {
2452
+ const map = mapRef.current;
2453
+ const current = pointsRef.current;
2454
+ if (!(normalized.enabled && map != null && current.length >= normalized.minPoints) || !map) {
2455
+ runIdRef.current += 1;
2456
+ setClusters([]);
2457
+ setClusteredIds(/* @__PURE__ */ new Set());
2458
+ return;
2459
+ }
2460
+ let zoom;
2461
+ try {
2462
+ zoom = await map.getZoom();
2463
+ } catch {
2464
+ return;
2465
+ }
2466
+ if (zoom > normalized.maxZoom) {
2467
+ runIdRef.current += 1;
2468
+ setClusters([]);
2469
+ setClusteredIds(/* @__PURE__ */ new Set());
2470
+ return;
2471
+ }
2472
+ const runId = ++runIdRef.current;
2473
+ const projected = await Promise.all(current.map(async (point) => {
2474
+ const pixel = await map.project([point.lng, point.lat]);
2475
+ return {
2476
+ point,
2477
+ x: pixel[0],
2478
+ y: pixel[1]
2479
+ };
2480
+ }));
2481
+ if (runId !== runIdRef.current) return;
2482
+ const nextClusters = [];
2483
+ const nextIds = /* @__PURE__ */ new Set();
2484
+ for (const group of groupByPixelRadius(projected, normalized.radius)) {
2485
+ if (group.length < normalized.minPoints) continue;
2486
+ const members = group.map((g) => g.point);
2487
+ let sumLng = 0;
2488
+ let sumLat = 0;
2489
+ for (const m of members) {
2490
+ sumLng += m.lng;
2491
+ sumLat += m.lat;
2492
+ nextIds.add(m.id);
2493
+ }
2494
+ nextClusters.push({
2495
+ key: members[0]?.id ?? 0,
2496
+ lng: sumLng / members.length,
2497
+ lat: sumLat / members.length,
2498
+ members: members.map((m) => ({
2499
+ id: m.id,
2500
+ lng: m.lng,
2501
+ lat: m.lat
2502
+ }))
2503
+ });
2504
+ }
2505
+ setClusters(nextClusters);
2506
+ setClusteredIds(nextIds);
2507
+ };
2508
+ recompute();
2509
+ const unsubscribe = runtime.subscribeRegionChange(() => {
2510
+ if (debounceRef.current) clearTimeout(debounceRef.current);
2511
+ debounceRef.current = setTimeout(() => {
2512
+ debounceRef.current = null;
2513
+ recompute();
2514
+ }, REGION_DEBOUNCE_MS);
2515
+ });
2516
+ return () => {
2517
+ unsubscribe();
2518
+ if (debounceRef.current) {
2519
+ clearTimeout(debounceRef.current);
2520
+ debounceRef.current = null;
2521
+ }
2522
+ };
2523
+ }, [
2524
+ runtime,
2525
+ normalized,
2526
+ pointsKey
2527
+ ]);
2528
+ return {
2529
+ clusters,
2530
+ clusteredIds
2531
+ };
2532
+ }
2533
+
2534
+ // src/utils/useExitAnimation.ts
2535
+ /**
2536
+ * Duration of the marker exit animation: 200 ms of visible ease-out (web
2537
+ * parity) plus a small buffer before the marker unmounts.
2538
+ */
2539
+ const EXIT_ANIMATION_MS = 220;
2540
+ /**
2541
+ * Tracks ids that left an "active" list so their exit animation can play
2542
+ * before unmount — the declarative replacement of the web SDK's
2543
+ * `animateOutMarker`. Returns the active ids unchanged and the ids that are
2544
+ * currently animating out; a caller renders those with a `leaving` flag and
2545
+ * keeps their last-resolved data until the animation finishes.
2546
+ *
2547
+ * Each removed id gets its own timer (per-id map, not one shared timeout), so
2548
+ * removing A and then B within the window removes both when their own timers
2549
+ * fire, and an id that comes back before its timer fires stops leaving
2550
+ * immediately.
2551
+ */
2552
+ function useExitAnimation(ids, exitMs = 220) {
2553
+ const [leavingIds, setLeavingIds] = useState([]);
2554
+ const prevRef = useRef(ids);
2555
+ const timersRef = useRef(/* @__PURE__ */ new Map());
2556
+ useEffect(() => {
2557
+ const prevSet = new Set(prevRef.current);
2558
+ prevRef.current = ids;
2559
+ const activeSet = new Set(ids);
2560
+ for (const id of activeSet) {
2561
+ const timer = timersRef.current.get(id);
2562
+ if (timer !== void 0) {
2563
+ clearTimeout(timer);
2564
+ timersRef.current.delete(id);
2565
+ }
2566
+ }
2567
+ for (const id of prevSet) {
2568
+ if (activeSet.has(id) || timersRef.current.has(id)) continue;
2569
+ timersRef.current.set(id, setTimeout(() => {
2570
+ timersRef.current.delete(id);
2571
+ setLeavingIds((current) => {
2572
+ if (!current.includes(id)) return current;
2573
+ return current.filter((x) => x !== id);
2574
+ });
2575
+ }, exitMs));
2576
+ }
2577
+ setLeavingIds((current) => {
2578
+ const pending = [...timersRef.current.keys()];
2579
+ if (pending.length === current.length) {
2580
+ const currentSet = new Set(current);
2581
+ if (pending.every((id) => currentSet.has(id))) return current;
2582
+ }
2583
+ return pending;
2584
+ });
2585
+ }, [ids, exitMs]);
2586
+ useEffect(() => {
2587
+ const timers = timersRef.current;
2588
+ return () => {
2589
+ for (const timer of timers.values()) clearTimeout(timer);
2590
+ timers.clear();
2591
+ };
2592
+ }, []);
2593
+ const activeSet = useMemo(() => new Set(ids), [ids]);
2594
+ return {
2595
+ activeIds: ids,
2596
+ leavingIds: useMemo(() => leavingIds.filter((id) => !activeSet.has(id)), [leavingIds, activeSet])
2597
+ };
2598
+ }
2599
+
2600
+ // src/poiHighlight/PoiHighlightLayer.tsx
2601
+ const DEFAULT_PAN_ZOOM = 13;
2602
+ /** Milliseconds after an exit before an id's resolved data is pruned. */
2603
+ const EXIT_PRUNE_MS = 250;
2604
+ /**
2605
+ * Declarative counterpart of the web SDK's `highlightPOI()`: renders an
2606
+ * animated icon+label marker for each highlighted POI id, resolving each id
2607
+ * cheapest-first (caller data → rendered tiles → place-detail API).
2608
+ * Highlight state is owned by the `ids` prop (or
2609
+ * `useYarrowPoiHighlight().highlightedIds`); removing an id plays the exit
2610
+ * animation and unmounts the marker.
2611
+ *
2612
+ * Known native limitation (documented in the README): the base style's own
2613
+ * POI icon is not hidden behind the highlight marker — native has no runtime
2614
+ * `setFilter`, so the marker simply draws on top of it.
2615
+ *
2616
+ * ```tsx
2617
+ * <YarrowMapView apiKey={KEY} center={[69.2401, 41.2995]}>
2618
+ * <PoiHighlightLayer ids={[123]} dataById={{ 123: { location } }} panTo />
2619
+ * </YarrowMapView>
2620
+ * ```
2621
+ */
2622
+ function PoiHighlightLayer({ ids, dataById, iconSize, panTo = false, zoom, clustering, onHighlightPress, onResolveError }) {
2623
+ const runtime = useYarrowMapRuntime();
2624
+ const camera = useYarrowCamera();
2625
+ const idList = useMemo(() => {
2626
+ return [...new Set(Array.isArray(ids) ? ids : [ids])];
2627
+ }, [ids]);
2628
+ const { activeIds, leavingIds } = useExitAnimation(idList);
2629
+ const [resolved, setResolved] = useState({});
2630
+ const resolveCacheRef = useRef(/* @__PURE__ */ new Map());
2631
+ const failedIdsRef = useRef(/* @__PURE__ */ new Set());
2632
+ const dataByIdRef = useRef(dataById);
2633
+ dataByIdRef.current = dataById;
2634
+ const onResolveErrorRef = useRef(onResolveError);
2635
+ onResolveErrorRef.current = onResolveError;
2636
+ const resolveOnce = useMemo(() => (id) => {
2637
+ if (!runtime) return Promise.resolve(null);
2638
+ const pending = resolveCacheRef.current.get(id);
2639
+ if (pending) return pending;
2640
+ const promise = resolvePoiData(id, dataByIdRef.current?.[id] ?? {}, runtime).then((result) => {
2641
+ if (result === null) {
2642
+ if (resolveCacheRef.current.get(id) === promise) resolveCacheRef.current.delete(id);
2643
+ onResolveErrorRef.current?.(id);
2644
+ }
2645
+ return result;
2646
+ });
2647
+ resolveCacheRef.current.set(id, promise);
2648
+ return promise;
2649
+ }, [runtime]);
2650
+ useEffect(() => {
2651
+ if (!runtime) return;
2652
+ let cancelled = false;
2653
+ for (const id of activeIds) {
2654
+ if (resolved[id] !== void 0 || failedIdsRef.current.has(id)) continue;
2655
+ resolveOnce(id).then((data) => {
2656
+ if (cancelled) return;
2657
+ if (!data) {
2658
+ failedIdsRef.current.add(id);
2659
+ return;
2660
+ }
2661
+ setResolved((current) => current[id] !== void 0 ? current : {
2662
+ ...current,
2663
+ [id]: data
2664
+ });
2665
+ });
2666
+ }
2667
+ return () => {
2668
+ cancelled = true;
2669
+ };
2670
+ }, [
2671
+ runtime,
2672
+ activeIds,
2673
+ resolved,
2674
+ resolveOnce
2675
+ ]);
2676
+ useEffect(() => {
2677
+ const failed = failedIdsRef.current;
2678
+ for (const id of [...failed]) if (!idList.includes(id)) failed.delete(id);
2679
+ }, [idList]);
2680
+ useEffect(() => {
2681
+ if (!runtime) return;
2682
+ const registry = runtime.highlightedPoiIds.current;
2683
+ if (!registry) return;
2684
+ const next = new Set(activeIds);
2685
+ let changed = registry.size !== next.size;
2686
+ if (!changed) {
2687
+ for (const id of next) if (!registry.has(id)) {
2688
+ changed = true;
2689
+ break;
2690
+ }
2691
+ }
2692
+ if (changed) runtime.highlightedPoiIds.current = next;
2693
+ }, [runtime, activeIds]);
2694
+ useEffect(() => {
2695
+ if (leavingIds.length === 0) return;
2696
+ const timers = leavingIds.map((id) => setTimeout(() => {
2697
+ setResolved((current) => {
2698
+ if (current[id] === void 0) return current;
2699
+ const next = { ...current };
2700
+ delete next[id];
2701
+ return next;
2702
+ });
2703
+ resolveCacheRef.current.delete(id);
2704
+ }, EXIT_PRUNE_MS));
2705
+ return () => {
2706
+ for (const timer of timers) clearTimeout(timer);
2707
+ };
2708
+ }, [leavingIds]);
2709
+ const points = useMemo(() => activeIds.flatMap((id) => {
2710
+ const data = resolved[id];
2711
+ return data ? [{
2712
+ id,
2713
+ lng: data.lng,
2714
+ lat: data.lat
2715
+ }] : [];
2716
+ }), [activeIds, resolved]);
2717
+ const { clusters, clusteredIds } = usePixelClusters(points, clustering, runtime);
2718
+ const panToKey = panTo ? idList.join(",") : "";
2719
+ useEffect(() => {
2720
+ if (!panToKey || !runtime) return;
2721
+ let cancelled = false;
2722
+ const idsToPan = panToKey.split(",").map(Number);
2723
+ (async () => {
2724
+ const places = (await Promise.all(idsToPan.map((id) => resolveOnce(id)))).filter((p) => p !== null);
2725
+ if (cancelled || places.length === 0) return;
2726
+ const [first] = places;
2727
+ if (!first) return;
2728
+ if (places.length === 1) {
2729
+ const currentZoom = await runtime.mapRef.current?.getZoom().catch(() => null);
2730
+ const targetZoom = zoom ?? Math.max(DEFAULT_PAN_ZOOM, currentZoom ?? DEFAULT_PAN_ZOOM);
2731
+ camera.zoomTo(first.lat, first.lng, targetZoom);
2732
+ return;
2733
+ }
2734
+ camera.fitBounds({
2735
+ type: "FeatureCollection",
2736
+ features: places.map((p) => ({ geometry: {
2737
+ type: "Point",
2738
+ coordinates: [p.lng, p.lat]
2739
+ } }))
2740
+ });
2741
+ })();
2742
+ return () => {
2743
+ cancelled = true;
2744
+ };
2745
+ }, [
2746
+ panToKey,
2747
+ zoom,
2748
+ runtime,
2749
+ camera,
2750
+ resolveOnce
2751
+ ]);
2752
+ const handleClusterPress = (children) => {
2753
+ let zoomToExpand = true;
2754
+ if (clustering && typeof clustering === "object") {
2755
+ if (clustering.onClusterClick?.(children) === false) zoomToExpand = false;
2756
+ }
2757
+ if (!zoomToExpand || children.length === 0) return;
2758
+ camera.fitBounds({
2759
+ type: "FeatureCollection",
2760
+ features: children.map((c) => ({ geometry: {
2761
+ type: "Point",
2762
+ coordinates: [c.lng, c.lat]
2763
+ } }))
2764
+ });
2765
+ };
2766
+ if (!runtime) return null;
2767
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2768
+ activeIds.map((id) => {
2769
+ const data = resolved[id];
2770
+ if (!data || clusteredIds.has(id)) return null;
2771
+ return /* @__PURE__ */ jsx(HighlightMarkerView, {
2772
+ lngLat: [data.lng, data.lat],
2773
+ iconUrl: data.iconUrl,
2774
+ title: data.title,
2775
+ iconSize,
2776
+ onPress: () => onHighlightPress?.({
2777
+ id,
2778
+ lng: data.lng,
2779
+ lat: data.lat,
2780
+ title: data.title,
2781
+ iconUrl: data.iconUrl
2782
+ })
2783
+ }, id);
2784
+ }),
2785
+ leavingIds.map((id) => {
2786
+ const data = resolved[id];
2787
+ if (!data) return null;
2788
+ return /* @__PURE__ */ jsx(HighlightMarkerView, {
2789
+ lngLat: [data.lng, data.lat],
2790
+ iconUrl: data.iconUrl,
2791
+ title: data.title,
2792
+ iconSize,
2793
+ leaving: true
2794
+ }, `leaving-${id}`);
2795
+ }),
2796
+ clusters.map((cluster) => /* @__PURE__ */ jsx(ClusterBadge, {
2797
+ lngLat: [cluster.lng, cluster.lat],
2798
+ count: cluster.members.length,
2799
+ theme: runtime.theme,
2800
+ onPress: () => handleClusterPress(cluster.members)
2801
+ }, cluster.key))
2802
+ ] });
2803
+ }
2804
+
2805
+ // src/poiHighlight/useYarrowPoiHighlight.ts
2806
+ /**
2807
+ * Headless highlight state — the declarative counterpart of the web SDK's
2808
+ * `highlightPOI` / `resetPOIHighlight` / `isPOIHighlighted` /
2809
+ * `getHighlightedPOIs` quartet. Rendering is owned by `<PoiHighlightLayer>`:
2810
+ *
2811
+ * ```tsx
2812
+ * const { highlightedIds, highlight } = useYarrowPoiHighlight();
2813
+ * <YarrowMapView apiKey={KEY}>
2814
+ * <PoiHighlightLayer ids={highlightedIds} panTo />
2815
+ * </YarrowMapView>
2816
+ * ```
2817
+ */
2818
+ function useYarrowPoiHighlight() {
2819
+ const [highlightedIds, setHighlightedIds] = useState([]);
2820
+ const reset = useCallback((input) => {
2821
+ setHighlightedIds((current) => {
2822
+ if (input === void 0) return [];
2823
+ const remove = new Set(Array.isArray(input) ? input : [input]);
2824
+ return current.filter((id) => !remove.has(id));
2825
+ });
2826
+ }, []);
2827
+ const highlight = useCallback((input, options) => {
2828
+ const ids = Array.isArray(input) ? input : [input];
2829
+ setHighlightedIds((current) => {
2830
+ const next = [...options?.replace ? [] : current];
2831
+ for (const id of ids) if (!next.includes(id)) next.push(id);
2832
+ return next;
2833
+ });
2834
+ return ids.map((id) => ({
2835
+ id,
2836
+ remove: () => reset(id)
2837
+ }));
2838
+ }, [reset]);
2839
+ const isHighlighted = useCallback((id) => highlightedIds.includes(id), [highlightedIds]);
2840
+ return useMemo(() => ({
2841
+ highlightedIds,
2842
+ highlight,
2843
+ reset,
2844
+ isHighlighted
2845
+ }), [
2846
+ highlightedIds,
2847
+ highlight,
2848
+ reset,
2849
+ isHighlighted
2850
+ ]);
2851
+ }
2852
+
2853
+ // src/search/SearchResultsLayer.tsx
2854
+ /**
2855
+ * Renders search results on the map — the declarative counterpart of the web
2856
+ * SDK's `highlightSearchResults()`. Icon precedence per result:
2857
+ * `icon_img` → registry icon by `category.name` → blue-dot fallback.
2858
+ *
2859
+ * ```tsx
2860
+ * const { results, isLoading } = useYarrowSearch(query, { lat, lon });
2861
+ * <YarrowMapView apiKey={KEY}>
2862
+ * <SearchResultsLayer results={results} onResultPress={…} />
2863
+ * </YarrowMapView>
2864
+ * ```
2865
+ */
2866
+ function SearchResultsLayer({ results, iconSize, zoomToResults = true, fitKey, clustering, onResultPress }) {
2867
+ const runtime = useYarrowMapRuntime();
2868
+ const camera = useYarrowCamera();
2869
+ const markers = useMemo(() => {
2870
+ const keyed = [];
2871
+ const seen = /* @__PURE__ */ new Set();
2872
+ results.forEach((result) => {
2873
+ const { latitude, longitude } = result;
2874
+ if (typeof latitude !== "number" || typeof longitude !== "number") return;
2875
+ const id = result.id;
2876
+ let key;
2877
+ if (id !== void 0 && !seen.has(id)) key = id;
2878
+ else key = `idx:${keyed.length}`;
2879
+ seen.add(key);
2880
+ keyed.push({
2881
+ key,
2882
+ result,
2883
+ lng: longitude,
2884
+ lat: latitude
2885
+ });
2886
+ });
2887
+ return keyed;
2888
+ }, [results]);
2889
+ const points = useMemo(() => markers.map((m) => ({
2890
+ id: m.key,
2891
+ lng: m.lng,
2892
+ lat: m.lat
2893
+ })), [markers]);
2894
+ useEffect(() => {
2895
+ if (results.length > 0 && markers.length === 0) console.warn(`[YarrowMap] SearchResultsLayer: ${results.length} result(s) returned, none with displayable coordinates`);
2896
+ }, [results, markers]);
2897
+ const { clusters, clusteredIds } = usePixelClusters(points, clustering, runtime);
2898
+ const fittedRef = useRef(false);
2899
+ const lastFitKeyRef = useRef(fitKey);
2900
+ if (lastFitKeyRef.current !== fitKey) {
2901
+ lastFitKeyRef.current = fitKey;
2902
+ fittedRef.current = false;
2903
+ }
2904
+ const firstCoords = useMemo(() => {
2905
+ const [first] = markers;
2906
+ return first ? `${first.lat},${first.lng}` : null;
2907
+ }, [markers]);
2908
+ useEffect(() => {
2909
+ if (!zoomToResults || !runtime || fittedRef.current) return;
2910
+ if (!firstCoords) return;
2911
+ fittedRef.current = true;
2912
+ camera.fitBounds({
2913
+ type: "FeatureCollection",
2914
+ features: markers.map((m) => ({
2915
+ geometry: {
2916
+ type: "Point",
2917
+ coordinates: [m.lng, m.lat]
2918
+ },
2919
+ properties: { name: m.result.name }
2920
+ }))
2921
+ });
2922
+ }, [
2923
+ firstCoords,
2924
+ zoomToResults,
2925
+ runtime,
2926
+ camera,
2927
+ markers
2928
+ ]);
2929
+ const handleClusterPress = (children) => {
2930
+ let zoomToExpand = true;
2931
+ if (clustering && typeof clustering === "object") {
2932
+ if (clustering.onClusterClick?.(children) === false) zoomToExpand = false;
2933
+ }
2934
+ if (!zoomToExpand || children.length === 0) return;
2935
+ camera.fitBounds({
2936
+ type: "FeatureCollection",
2937
+ features: children.map((c) => ({ geometry: {
2938
+ type: "Point",
2939
+ coordinates: [c.lng, c.lat]
2940
+ } }))
2941
+ });
2942
+ };
2943
+ if (!runtime) return null;
2944
+ return /* @__PURE__ */ jsxs(Fragment, { children: [markers.map(({ key, result, lng, lat }) => {
2945
+ if (clusteredIds.has(key)) return null;
2946
+ const iconUrl = result.icon_img ?? resolveCategoryIcon(runtime.iconsByName, result.category?.name);
2947
+ return /* @__PURE__ */ jsx(HighlightMarkerView, {
2948
+ lngLat: [lng, lat],
2949
+ iconUrl: typeof iconUrl === "string" ? iconUrl : void 0,
2950
+ title: result.name,
2951
+ iconSize,
2952
+ onPress: () => onResultPress?.(lat, lng, result)
2953
+ }, key);
2954
+ }), clusters.map((cluster) => /* @__PURE__ */ jsx(ClusterBadge, {
2955
+ lngLat: [cluster.lng, cluster.lat],
2956
+ count: cluster.members.length,
2957
+ theme: runtime.theme,
2958
+ onPress: () => handleClusterPress(cluster.members)
2959
+ }, cluster.key))] });
2960
+ }
2961
+
2962
+ // src/tracking/dau.ts
2963
+ /**
2964
+ * DAU tracking for the RN SDK — wraps the platform-agnostic core
2965
+ * implementation with the RN default `sdk_type: "react-native"`. Core's own
2966
+ * default (`'javascript'`) exists for the web SDK and would misattribute
2967
+ * direct calls from React Native apps, so this wrapper owns the RN default.
2968
+ * `<YarrowMapView>` passes the key from its own config (see `dauTracking`).
2969
+ */
2970
+ function trackDau(apiKey, sdkType = "react-native") {
2971
+ trackDau$1(apiKey, sdkType);
2972
+ }
2973
+
2974
+ // src/utils/userToken.ts
2975
+ /**
2976
+ * Bridges the async AsyncStorage API onto core's synchronous TokenStorage
2977
+ * contract: the existing token hydrates into memory once, reads are served
2978
+ * synchronously from that cache, and writes mirror in-memory before flushing
2979
+ * to AsyncStorage (fire-and-forget).
2980
+ *
2981
+ * If the initial read throws, the override is left unset entirely: core then
2982
+ * degrades to ephemeral tokens *without persisting anything*, so a transient
2983
+ * read failure can never overwrite the stored identity with a fresh token.
2984
+ *
2985
+ * Await this once during app startup, before the first map or tracking call
2986
+ * (tokens generated before this resolves are ephemeral by design):
2987
+ *
2988
+ * ```ts
2989
+ * import AsyncStorage from '@react-native-async-storage/async-storage';
2990
+ * import { setAsyncStorageTokenStorage } from '@yarrow-uz/rn-map-sdk';
2991
+ *
2992
+ * await setAsyncStorageTokenStorage(AsyncStorage);
2993
+ * ```
2994
+ */
2995
+ async function setAsyncStorageTokenStorage(storage) {
2996
+ let existing;
2997
+ try {
2998
+ existing = await storage.getItem(USER_TOKEN_STORAGE_KEY);
2999
+ } catch {
3000
+ return;
3001
+ }
3002
+ const cache = /* @__PURE__ */ new Map();
3003
+ if (existing) cache.set(USER_TOKEN_STORAGE_KEY, existing);
3004
+ setTokenStorage({
3005
+ getItem: (key) => cache.get(key) ?? null,
3006
+ setItem: (key, value) => {
3007
+ cache.set(key, value);
3008
+ Promise.resolve(storage.setItem(key, value)).catch(() => {});
3009
+ }
3010
+ });
3011
+ }
3012
+
3013
+ export { addApiKeyToUrl as $, fetchPlaceLocation as A, ClusterBadge as B, useYarrowMapSearch as C, YarrowMapContext as D, useYarrowLayerPress as E, DEFAULT_CLUSTER_MAX_ZOOM as F, ICON_CACHE_NAME as G, CACHE_PROTOCOL as H, DEFAULT_CLUSTER_MIN_POINTS as I, TILE_CACHE_NAME as J, MILLISECONDS_PER_DAY as K, DEFAULT_CLUSTER_RADIUS_PX as L, resolvePoiData as M, fetchYarrowIcons as N, useYarrowMapRuntime as O, resolveCategoryIcon as P, YarrowApiError as Q, groupByPixelRadius as R, useYarrowRouting as S, YARROW_CLICK_LAYER_IDS as T, DEFAULT_CACHE_LIFESPAN_DAYS as U, CACHED_AT_HEADER as V, ICONS_ENDPOINT as W, YARROW_MAP_URL as X, USER_TOKEN_STORAGE_KEY as Y, YARROW_SEARCH_API_URL as Z, buildStyleUrl as _, PoiHighlightLayer as a, getOrCreateUserToken as at, DEFAULT_BRAND_BADGE_SCALE as b, DEFAULT_OFFLINE_MAX_ZOOM as c, haversineDistance as ct, AVG_TILE_BYTES as d, setYarrowApiKey as dt, buildStyleEndpoint as et, estimateRegion as f, transformRouteCoordinates as ft, YarrowMapView as g, HighlightMarkerView as h, useYarrowPoiHighlight as i, getBoundingBox as it, lookupPoiInViewport as j, POI_BASE_LAYER as k, DEFAULT_OFFLINE_MIN_ZOOM as l, normalizeStyleType as lt, YarrowMarker as m, trackDau as n, fetchRoutes as nt, useYarrowOfflineRegions as o, getYarrowApiKey as ot, useYarrowCamera as p, ROUTE_API_URL as q, SearchResultsLayer as r, fetchSearchResults as rt, YarrowOfflineManager as s, hasCacheStorage as st, setAsyncStorageTokenStorage as t, fetchArrayBufferWithCache as tt, OFFLINE_METADATA_VERSION as u, setTokenStorage as ut, RouteLayer as v, useYarrowSearch as w, YarrowImages as x, YarrowMapConfig as y, normalizeClusteringConfig as z };