drone-path-engine 0.0.0-bootstrap

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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +34 -0
  3. package/THIRD-PARTY-NOTICES.md +11 -0
  4. package/dist/assets.d.ts +34 -0
  5. package/dist/assets.js +60 -0
  6. package/dist/config.d.ts +207 -0
  7. package/dist/config.js +581 -0
  8. package/dist/configfile.d.ts +20 -0
  9. package/dist/configfile.js +86 -0
  10. package/dist/decimate.d.ts +11 -0
  11. package/dist/decimate.js +84 -0
  12. package/dist/ffmpeg-output.d.ts +9 -0
  13. package/dist/ffmpeg-output.js +40 -0
  14. package/dist/logging.d.ts +1 -0
  15. package/dist/logging.js +1 -0
  16. package/dist/paths.d.ts +4 -0
  17. package/dist/paths.js +21 -0
  18. package/dist/pipeline.d.ts +90 -0
  19. package/dist/pipeline.js +430 -0
  20. package/dist/plan.d.ts +47 -0
  21. package/dist/plan.js +112 -0
  22. package/dist/png.d.ts +1 -0
  23. package/dist/png.js +32 -0
  24. package/dist/range.d.ts +19 -0
  25. package/dist/range.js +50 -0
  26. package/dist/recordings.d.ts +5 -0
  27. package/dist/recordings.js +45 -0
  28. package/dist/render-page.d.ts +35 -0
  29. package/dist/render-page.js +85 -0
  30. package/dist/render.d.ts +57 -0
  31. package/dist/render.js +397 -0
  32. package/dist/renderer/boot.d.ts +4 -0
  33. package/dist/renderer/boot.js +28 -0
  34. package/dist/renderer/dom.d.ts +28 -0
  35. package/dist/renderer/dom.js +179 -0
  36. package/dist/renderer/framemath.d.ts +5 -0
  37. package/dist/renderer/framemath.js +30 -0
  38. package/dist/renderer/scene.d.ts +38 -0
  39. package/dist/renderer/scene.js +401 -0
  40. package/dist/renderer/theme.d.ts +13 -0
  41. package/dist/renderer/theme.js +82 -0
  42. package/dist/renderer/tilesources.d.ts +14 -0
  43. package/dist/renderer/tilesources.js +38 -0
  44. package/dist/renderer/trail.d.ts +18 -0
  45. package/dist/renderer/trail.js +42 -0
  46. package/dist/restyle.d.ts +13 -0
  47. package/dist/restyle.js +16 -0
  48. package/dist/serve.d.ts +6 -0
  49. package/dist/serve.js +27 -0
  50. package/dist/tilecache.d.ts +12 -0
  51. package/dist/tilecache.js +21 -0
  52. package/dist/tiles.d.ts +25 -0
  53. package/dist/tiles.js +215 -0
  54. package/dist/version.d.ts +1 -0
  55. package/dist/version.js +3 -0
  56. package/package.json +39 -0
@@ -0,0 +1,82 @@
1
+ const TRAIL_COLOR = '#e87f54';
2
+ function parseHexColor(hex) {
3
+ const m = /^#([0-9a-f]{6}|[0-9a-f]{8})$/i.exec(hex);
4
+ if (!m)
5
+ throw new Error(`invalid trail color: ${hex}`);
6
+ const [r, g, b, a] = [0, 2, 4, 6].map((i) => i < m[1].length ? Number.parseInt(m[1].slice(i, i + 2), 16) : 255);
7
+ return { r, g, b, a: a / 255 };
8
+ }
9
+ function rgba(c, alpha) {
10
+ return `rgba(${c.r},${c.g},${c.b},${Math.round(alpha * 10000) / 10000})`;
11
+ }
12
+ function luminance(c) {
13
+ const linear = (v) => {
14
+ const s = v / 255;
15
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
16
+ };
17
+ return 0.2126 * linear(c.r) + 0.7152 * linear(c.g) + 0.0722 * linear(c.b);
18
+ }
19
+ function mix(base, tint, amount) {
20
+ const k = (x, y) => Math.round(x + (y - x) * amount);
21
+ return { r: k(base.r, tint.r), g: k(base.g, tint.g), b: k(base.b, tint.b), a: 1 };
22
+ }
23
+ const CASING_ANCHORS = {
24
+ satellite: {
25
+ anchor: { r: 10, g: 14, b: 20, a: 1 },
26
+ opposite: { r: 255, g: 255, b: 255, a: 1 },
27
+ alpha: 0.9,
28
+ },
29
+ topo: {
30
+ anchor: { r: 255, g: 255, b: 255, a: 1 },
31
+ opposite: { r: 10, g: 14, b: 20, a: 1 },
32
+ alpha: 1,
33
+ },
34
+ };
35
+ const CONTRAST_FLIP = 0.18;
36
+ const CORE_TINT = 0.2;
37
+ function deriveCasing(style, core) {
38
+ const { anchor, opposite, alpha } = CASING_ANCHORS[style];
39
+ const base = Math.abs(luminance(core) - luminance(anchor)) < CONTRAST_FLIP ? opposite : anchor;
40
+ return rgba(mix(base, core, CORE_TINT), alpha);
41
+ }
42
+ const GLOW_ALPHA = { satellite: 0.32, topo: 0.26 };
43
+ function trailGlow(alpha) {
44
+ return rgba(parseHexColor(TRAIL_COLOR), alpha);
45
+ }
46
+ const THEMES = {
47
+ satellite: {
48
+ core: TRAIL_COLOR,
49
+ trailCore: TRAIL_COLOR,
50
+ glow: trailGlow(GLOW_ALPHA.satellite),
51
+ casing: 'rgba(10,14,20,0.9)',
52
+ ghost: '#ffffff',
53
+ ghostOpacity: 0.85,
54
+ ghostCasing: 'rgba(8,12,18,0.55)',
55
+ discBg: 'rgba(10,14,20,0.82)',
56
+ vignette: 0.16,
57
+ },
58
+ topo: {
59
+ core: TRAIL_COLOR,
60
+ trailCore: TRAIL_COLOR,
61
+ glow: trailGlow(GLOW_ALPHA.topo),
62
+ casing: '#ffffff',
63
+ ghost: '#6b6252',
64
+ ghostOpacity: 0.7,
65
+ ghostCasing: 'rgba(255,255,255,0.8)',
66
+ discBg: 'rgba(26,22,18,0.85)',
67
+ vignette: 0.06,
68
+ },
69
+ };
70
+ export function themeFor(style, trailColor = null) {
71
+ const base = THEMES[style];
72
+ if (trailColor === null)
73
+ return base;
74
+ const core = parseHexColor(trailColor);
75
+ return {
76
+ ...base,
77
+ core: rgba(core, 1),
78
+ trailCore: trailColor,
79
+ glow: rgba(core, GLOW_ALPHA[style] * core.a),
80
+ casing: deriveCasing(style, core),
81
+ };
82
+ }
@@ -0,0 +1,14 @@
1
+ import type { MapStyle } from '../config.js';
2
+ export interface TileSource {
3
+ cacheKey: string;
4
+ url: string;
5
+ subdomains: string[];
6
+ attribution: string;
7
+ bg: string;
8
+ placeholderBg: string;
9
+ tileFilter: string | null;
10
+ maxZoom: number;
11
+ maxNativeZoom?: number;
12
+ }
13
+ export declare const TILE_SOURCES: Record<MapStyle, TileSource>;
14
+ export declare const TILE_CREDITS: string;
@@ -0,0 +1,38 @@
1
+ export const TILE_SOURCES = {
2
+ // Esri World Imagery (free for non-commercial use, attribution required).
3
+ satellite: {
4
+ cacheKey: 'esri-imagery',
5
+ url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
6
+ subdomains: [''],
7
+ attribution: 'Imagery &copy; <a href="https://www.esri.com/">Esri</a>, Maxar, Earthstar Geographics, and the GIS User Community',
8
+ bg: '#0b0e14',
9
+ placeholderBg: '#2a2f38',
10
+ tileFilter: 'saturate(1.06) contrast(1.03)',
11
+ maxZoom: 19,
12
+ },
13
+ topo: {
14
+ cacheKey: 'opentopomap',
15
+ url: 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
16
+ subdomains: ['a', 'b', 'c'],
17
+ attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, SRTM | Style: &copy; <a href="https://opentopomap.org">OpenTopoMap</a> (CC-BY-SA)',
18
+ bg: '#eae5da',
19
+ placeholderBg: '#eae5da',
20
+ tileFilter: null,
21
+ maxZoom: 19,
22
+ maxNativeZoom: 17,
23
+ },
24
+ };
25
+ /** Leaflet wants HTML and the map style thumbnails plain text; the thumbnail
26
+ credits derive from these attributions so the wording can never drift. */
27
+ function plainCredit(html) {
28
+ return html
29
+ .replaceAll('&copy;', '©')
30
+ .replace(/<a [^>]+>/g, '')
31
+ .replaceAll('</a>', '')
32
+ .split(' | ')
33
+ .map((part) => part.replace('Style: ', 'Style ')); // the thumbnail wording drops the colon
34
+ }
35
+ export const TILE_CREDITS = [
36
+ ...plainCredit(TILE_SOURCES.satellite.attribution),
37
+ ...plainCredit(TILE_SOURCES.topo.attribution),
38
+ ].join(' · ');
@@ -0,0 +1,18 @@
1
+ import type { LatLngTuple } from 'leaflet';
2
+ export interface TrailLayer {
3
+ setLatLngs(points: LatLngTuple[]): void;
4
+ }
5
+ export interface TrailController {
6
+ setFrame(i: number): void;
7
+ }
8
+ export interface TrailTrack {
9
+ lat: readonly number[];
10
+ lon: readonly number[];
11
+ frame: readonly number[];
12
+ }
13
+ export interface FrameTrack {
14
+ lat: readonly number[];
15
+ lon: readonly number[];
16
+ }
17
+ export declare function lastIndexAtOrBefore(trailFrame: readonly number[], i: number): number;
18
+ export declare function createTrailController(trail: TrailTrack, frames: FrameTrack, layers: readonly TrailLayer[]): TrailController;
@@ -0,0 +1,42 @@
1
+ export function lastIndexAtOrBefore(trailFrame, i) {
2
+ let lo = 0;
3
+ let hi = trailFrame.length - 1;
4
+ let k = -1;
5
+ while (lo <= hi) {
6
+ const mid = (lo + hi) >> 1;
7
+ if (trailFrame[mid] <= i) {
8
+ k = mid;
9
+ lo = mid + 1;
10
+ }
11
+ else {
12
+ hi = mid - 1;
13
+ }
14
+ }
15
+ return k;
16
+ }
17
+ export function createTrailController(trail, frames, layers) {
18
+ let lastFrame = null;
19
+ let drawn = false;
20
+ return {
21
+ setFrame(i) {
22
+ if (i === lastFrame)
23
+ return;
24
+ const tip = i >= 0 && i < frames.lat.length ? [frames.lat[i], frames.lon[i]] : null;
25
+ // A kept point at exactly frame i would duplicate the tip's position.
26
+ let end = lastIndexAtOrBefore(trail.frame, i);
27
+ if (tip !== null && trail.frame[end] === i)
28
+ end -= 1;
29
+ const points = [];
30
+ for (let j = 0; j <= end; j++)
31
+ points.push([trail.lat[j], trail.lon[j]]);
32
+ if (tip !== null)
33
+ points.push(tip);
34
+ lastFrame = i;
35
+ if (points.length === 0 && !drawn)
36
+ return;
37
+ drawn = points.length > 0;
38
+ for (const layer of layers)
39
+ layer.setLatLngs(points);
40
+ },
41
+ };
42
+ }
@@ -0,0 +1,13 @@
1
+ import type { AppearanceSettings } from './config.js';
2
+ import type { Bbox } from 'drone-path-core/geo';
3
+ import type { SceneData } from './renderer/scene.js';
4
+ export interface RestyleMeta {
5
+ fps: number;
6
+ frames: number;
7
+ tileBase: string;
8
+ bbox: Bbox;
9
+ }
10
+ export declare function restyleSceneData(prev: SceneData, config: AppearanceSettings, meta: RestyleMeta, size?: {
11
+ width: number;
12
+ height: number;
13
+ }): SceneData;
@@ -0,0 +1,16 @@
1
+ import { buildSceneData, planPageOpts } from './render-page.js';
2
+ export function restyleSceneData(prev, config, meta, size = { width: prev.width, height: prev.height }) {
3
+ const planned = planPageOpts({
4
+ bbox: meta.bbox,
5
+ width: size.width,
6
+ height: size.height,
7
+ config,
8
+ source: { fps: meta.fps, frames: meta.frames },
9
+ frames: prev,
10
+ previous: {
11
+ zoom: prev.zoom,
12
+ decimated: { lat: prev.trailLat, lon: prev.trailLon, frame: prev.trailFrame },
13
+ },
14
+ });
15
+ return buildSceneData(planned, meta.tileBase);
16
+ }
@@ -0,0 +1,6 @@
1
+ import type http from 'node:http';
2
+ import type { AssetRoutes } from './assets.js';
3
+ export declare const RENDERER_DIR: string;
4
+ type ServeRoutes = Omit<AssetRoutes, 'leafletDir'>;
5
+ export declare function serveAsset(url: string, res: http.ServerResponse, routes: ServeRoutes): boolean;
6
+ export {};
package/dist/serve.js ADDED
@@ -0,0 +1,27 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { resolveAsset } from './assets.js';
6
+ const require_ = createRequire(import.meta.url);
7
+ const LEAFLET_DIR = path.dirname(require_.resolve('leaflet/dist/leaflet.js'));
8
+ export const RENDERER_DIR = fileURLToPath(new URL('./renderer/', import.meta.url));
9
+ export function serveAsset(url, res, routes) {
10
+ const asset = resolveAsset(url, { ...routes, leafletDir: LEAFLET_DIR });
11
+ if (asset.kind === 'unrouted')
12
+ return false;
13
+ if (asset.kind === 'file') {
14
+ let file = asset.filePath;
15
+ if (!fs.existsSync(file) && asset.fallbackPath && fs.existsSync(asset.fallbackPath)) {
16
+ file = asset.fallbackPath;
17
+ }
18
+ if (fs.existsSync(file) && fs.statSync(file).isFile()) {
19
+ res.writeHead(200, { 'Content-Type': asset.mime });
20
+ res.end(fs.readFileSync(file));
21
+ return true;
22
+ }
23
+ }
24
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
25
+ res.end('not found');
26
+ return true;
27
+ }
@@ -0,0 +1,12 @@
1
+ import type { MapStyle } from './config.js';
2
+ import type { TileCoord } from './plan.js';
3
+ interface TileRef {
4
+ style: MapStyle;
5
+ tile: TileCoord;
6
+ }
7
+ export declare function parseTilePathname(pathname: string): TileRef | null;
8
+ export declare function tilePaths(cacheDir: string, style: MapStyle, tile: TileCoord): {
9
+ file: string;
10
+ placeholder: string;
11
+ };
12
+ export {};
@@ -0,0 +1,21 @@
1
+ import path from 'node:path';
2
+ import { TILE_SOURCES } from './renderer/tilesources.js';
3
+ function cacheKeyFor(style) {
4
+ return TILE_SOURCES[style].cacheKey;
5
+ }
6
+ export function parseTilePathname(pathname) {
7
+ const m = /^\/tiles\/([a-z0-9_-]+)\/(\d+)\/(\d+)\/(\d+)\.png$/.exec(pathname);
8
+ if (!m)
9
+ return null;
10
+ const style = Object.hasOwn(TILE_SOURCES, m[1]) ? m[1] : null;
11
+ return style === null
12
+ ? null
13
+ : { style, tile: { z: Number(m[2]), x: Number(m[3]), y: Number(m[4]) } };
14
+ }
15
+ export function tilePaths(cacheDir, style, tile) {
16
+ const dir = path.join(cacheDir, cacheKeyFor(style), String(tile.z), String(tile.x));
17
+ return {
18
+ file: path.join(dir, `${tile.y}.png`),
19
+ placeholder: path.join(dir, `${tile.y}.placeholder.png`),
20
+ };
21
+ }
@@ -0,0 +1,25 @@
1
+ import type { MapStyle } from './config.js';
2
+ import type { TileCoord } from './plan.js';
3
+ type TileStatus = 'cached' | 'downloaded' | 'failed';
4
+ export interface PrefetchStats {
5
+ downloaded: number;
6
+ failed: number;
7
+ total: number;
8
+ }
9
+ export interface WarmOptions {
10
+ style: MapStyle;
11
+ tiles: TileCoord[];
12
+ log?: (msg: string) => void;
13
+ onTile?: (status: TileStatus) => void;
14
+ signal?: AbortSignal;
15
+ }
16
+ interface PrefetchOptions extends WarmOptions {
17
+ cacheDir: string;
18
+ }
19
+ interface TileTraffic {
20
+ ensure(style: MapStyle, tile: TileCoord): Promise<string>;
21
+ stream(options: WarmOptions): Promise<PrefetchStats>;
22
+ }
23
+ export declare function createTileTraffic(cacheDir: string, version?: string): TileTraffic;
24
+ export declare function prefetchTiles(options: PrefetchOptions): Promise<PrefetchStats>;
25
+ export {};
package/dist/tiles.js ADDED
@@ -0,0 +1,215 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import PQueue from 'p-queue';
4
+ import { errorMessage } from 'drone-path-core/errors';
5
+ import { solidPng } from './png.js';
6
+ import { tilePaths } from './tilecache.js';
7
+ import { TILE_SOURCES } from './renderer/tilesources.js';
8
+ import { VERSION } from './version.js';
9
+ function sleep(ms, signal) {
10
+ if (signal?.aborted)
11
+ return Promise.reject(canceledError(signal));
12
+ return new Promise((resolve, reject) => {
13
+ const onAbort = () => {
14
+ clearTimeout(timer);
15
+ reject(canceledError(signal));
16
+ };
17
+ const timer = setTimeout(() => {
18
+ signal?.removeEventListener('abort', onAbort);
19
+ resolve();
20
+ }, ms);
21
+ signal?.addEventListener('abort', onAbort, { once: true });
22
+ });
23
+ }
24
+ const DOWNLOAD_ATTEMPTS = 2;
25
+ const DOWNLOAD_WORKERS = 2;
26
+ const REQUEST_INTERVAL_MS = 500;
27
+ const RETRY_DELAY_MS = 500;
28
+ const FETCH_TIMEOUT_MS = 20000;
29
+ // p-queue starts higher priorities first, so 'now' jumps the queued pre-warm.
30
+ const TASK_PRIORITY = { now: 1, background: 0 };
31
+ function tileUrl(style, tile) {
32
+ const source = TILE_SOURCES[style];
33
+ const subdomain = source.subdomains.length
34
+ ? source.subdomains[(tile.x + tile.y) % source.subdomains.length]
35
+ : '';
36
+ return source.url
37
+ .replace('{s}', subdomain)
38
+ .replace('{z}', String(tile.z))
39
+ .replace('{x}', String(tile.x))
40
+ .replace('{y}', String(tile.y));
41
+ }
42
+ function canceledError(signal) {
43
+ return new Error('tile download canceled', { cause: signal.reason });
44
+ }
45
+ async function fetchBody(url, userAgent, signal) {
46
+ const res = await fetch(url, {
47
+ headers: { 'User-Agent': userAgent },
48
+ signal: signal
49
+ ? AbortSignal.any([AbortSignal.timeout(FETCH_TIMEOUT_MS), signal])
50
+ : AbortSignal.timeout(FETCH_TIMEOUT_MS),
51
+ });
52
+ return res.ok ? Buffer.from(await res.arrayBuffer()) : null;
53
+ }
54
+ async function downloadTile(ctx, url, priority, signal) {
55
+ for (let attempt = 0; attempt < DOWNLOAD_ATTEMPTS; attempt++) {
56
+ if (signal?.aborted)
57
+ throw canceledError(signal);
58
+ try {
59
+ const body = await ctx.queue.add(() => fetchBody(url, ctx.userAgent, signal), {
60
+ priority: TASK_PRIORITY[priority],
61
+ signal,
62
+ });
63
+ if (body)
64
+ return body;
65
+ }
66
+ catch {
67
+ if (signal?.aborted)
68
+ throw canceledError(signal);
69
+ }
70
+ if (attempt + 1 < DOWNLOAD_ATTEMPTS) {
71
+ await sleep(RETRY_DELAY_MS, signal);
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+ let cacheWriteSeq = 0;
77
+ function writeCacheFile(cachePath, data) {
78
+ const dir = path.dirname(cachePath);
79
+ const tmpPath = path.join(dir, `${path.basename(cachePath)}.${process.pid}.${++cacheWriteSeq}.tmp`);
80
+ try {
81
+ fs.mkdirSync(dir, { recursive: true });
82
+ fs.writeFileSync(tmpPath, data);
83
+ fs.renameSync(tmpPath, cachePath);
84
+ }
85
+ catch (e) {
86
+ try {
87
+ fs.rmSync(tmpPath, { force: true });
88
+ }
89
+ catch {
90
+ // best-effort cleanup so the original cache write error propagates
91
+ }
92
+ throw new Error(`cache write failed: ${cachePath}: ${errorMessage(e)}`, { cause: e });
93
+ }
94
+ }
95
+ function createPlaceholderSource() {
96
+ const cache = new Map();
97
+ return (style) => {
98
+ let png = cache.get(style);
99
+ if (!png) {
100
+ png = solidPng(TILE_SOURCES[style].placeholderBg);
101
+ cache.set(style, png);
102
+ }
103
+ return png;
104
+ };
105
+ }
106
+ async function fetchTileToCache(ctx, style, tile, priority, signal) {
107
+ if (signal?.aborted)
108
+ throw canceledError(signal);
109
+ const paths = tilePaths(ctx.cacheDir, style, tile);
110
+ if (fs.existsSync(paths.file))
111
+ return { file: paths.file, status: 'cached' };
112
+ const body = await downloadTile(ctx, tileUrl(style, tile), priority, signal);
113
+ if (body) {
114
+ writeCacheFile(paths.file, body);
115
+ return { file: paths.file, status: 'downloaded' };
116
+ }
117
+ if (signal?.aborted)
118
+ throw canceledError(signal);
119
+ writeCacheFile(paths.placeholder, ctx.placeholderPng(style));
120
+ return { file: paths.placeholder, status: 'failed' };
121
+ }
122
+ function withAbort(promise, signal) {
123
+ if (!signal)
124
+ return promise;
125
+ if (signal.aborted)
126
+ return Promise.reject(canceledError(signal));
127
+ return new Promise((resolve, reject) => {
128
+ const onAbort = () => reject(canceledError(signal));
129
+ signal.addEventListener('abort', onAbort, { once: true });
130
+ promise.then((value) => {
131
+ signal.removeEventListener('abort', onAbort);
132
+ resolve(value);
133
+ }, (err) => {
134
+ signal.removeEventListener('abort', onAbort);
135
+ reject(err);
136
+ });
137
+ });
138
+ }
139
+ function createDownloader(cacheDir, userAgent, placeholderPng) {
140
+ const queue = new PQueue({
141
+ concurrency: DOWNLOAD_WORKERS,
142
+ intervalCap: 1,
143
+ interval: REQUEST_INTERVAL_MS,
144
+ // Sliding window: no more than intervalCap starts in any interval window,
145
+ // matching the old request gate's nextFreeAt semantics.
146
+ strict: true,
147
+ });
148
+ const ctx = { cacheDir, queue, userAgent, placeholderPng };
149
+ const inFlight = new Map();
150
+ const enqueue = (style, tile, options = {}) => {
151
+ if (options.signal?.aborted) {
152
+ return Promise.reject(canceledError(options.signal));
153
+ }
154
+ const priority = options.priority ?? 'background';
155
+ const key = tilePaths(cacheDir, style, tile).file;
156
+ const shared = inFlight.get(key);
157
+ if (shared && !shared.signal?.aborted) {
158
+ return withAbort(shared.promise, options.signal).catch((e) => {
159
+ if (shared.signal?.aborted && !options.signal?.aborted) {
160
+ return enqueue(style, tile, options);
161
+ }
162
+ throw e;
163
+ });
164
+ }
165
+ const task = fetchTileToCache(ctx, style, tile, priority, options.signal);
166
+ const entry = { promise: task, signal: options.signal };
167
+ const clear = () => {
168
+ options.signal?.removeEventListener('abort', clear);
169
+ if (inFlight.get(key) === entry)
170
+ inFlight.delete(key);
171
+ };
172
+ options.signal?.addEventListener('abort', clear, { once: true });
173
+ void task.then(clear, clear);
174
+ inFlight.set(key, entry);
175
+ return task;
176
+ };
177
+ return { enqueue };
178
+ }
179
+ export function createTileTraffic(cacheDir, version = VERSION) {
180
+ const userAgent = `drone-path/${version} (flight-path map renderer; https://github.com/MrManny/drone-path)`;
181
+ const downloader = createDownloader(cacheDir, userAgent, createPlaceholderSource());
182
+ return {
183
+ ensure(style, tile) {
184
+ return downloader.enqueue(style, tile, { priority: 'now' }).then((result) => result.file);
185
+ },
186
+ stream(options) {
187
+ const { style, tiles, log = () => { }, onTile = () => { }, signal } = options;
188
+ if (signal?.aborted)
189
+ return Promise.reject(canceledError(signal));
190
+ const missing = [];
191
+ for (const tile of tiles) {
192
+ if (fs.existsSync(tilePaths(cacheDir, style, tile).file))
193
+ onTile('cached');
194
+ else
195
+ missing.push(tile);
196
+ }
197
+ if (missing.length === 0) {
198
+ return Promise.resolve({ downloaded: 0, failed: 0, total: tiles.length });
199
+ }
200
+ log(`tiles: ${tiles.length} needed, ${missing.length} to download (${style})`);
201
+ let downloaded = 0;
202
+ let failed = 0;
203
+ return Promise.all(missing.map((tile) => downloader.enqueue(style, tile, { priority: 'background', signal }).then((result) => {
204
+ if (result.status === 'downloaded')
205
+ downloaded++;
206
+ else if (result.status === 'failed')
207
+ failed++;
208
+ onTile(result.status);
209
+ }))).then(() => ({ downloaded, failed, total: tiles.length }));
210
+ },
211
+ };
212
+ }
213
+ export function prefetchTiles(options) {
214
+ return createTileTraffic(options.cacheDir).stream(options);
215
+ }
@@ -0,0 +1 @@
1
+ export declare const VERSION: string;
@@ -0,0 +1,3 @@
1
+ import { readFileSync } from 'node:fs';
2
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
3
+ export const VERSION = pkg.version;
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "drone-path-engine",
3
+ "version": "0.0.0-bootstrap",
4
+ "description": "Plan and render flight-path map overlays from drone telemetry.",
5
+ "type": "module",
6
+ "exports": {
7
+ "./*": {
8
+ "types": "./dist/*.d.ts",
9
+ "default": "./dist/*.js"
10
+ }
11
+ },
12
+ "files": [
13
+ "dist/**/*.js",
14
+ "dist/**/*.d.ts",
15
+ "THIRD-PARTY-NOTICES.md"
16
+ ],
17
+ "engines": {
18
+ "node": ">=24"
19
+ },
20
+ "scripts": {
21
+ "build": "node ../../scripts/clean-package-dist.mjs && tsc -p tsconfig.json",
22
+ "prepack": "npm run build:shared --prefix ../.."
23
+ },
24
+ "author": "Manuel Warum",
25
+ "license": "MIT",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/MrManny/drone-path.git",
29
+ "directory": "packages/engine"
30
+ },
31
+ "dependencies": {
32
+ "@types/leaflet": "~1.9.22",
33
+ "drone-path-core": "~0.0.0-bootstrap",
34
+ "leaflet": "~1.9.4",
35
+ "p-queue": "~10.0.0",
36
+ "playwright-core": "~1.65.0",
37
+ "zod": "~4.6.7"
38
+ }
39
+ }