drone-path 0.0.0-stage → 0.8.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.
Files changed (64) hide show
  1. package/CHANGELOG.md +179 -0
  2. package/LICENSE +21 -0
  3. package/README.md +84 -2
  4. package/THIRD-PARTY-NOTICES.md +77 -0
  5. package/app/main.mjs +496 -0
  6. package/app/preload.cjs +31 -0
  7. package/app/update-policy.d.mts +6 -0
  8. package/app/update-policy.mjs +6 -0
  9. package/app/update.d.mts +10 -0
  10. package/app/update.mjs +54 -0
  11. package/bin/drone-path.mjs +5 -0
  12. package/dist/appassets.js +44 -0
  13. package/dist/apppaths.js +28 -0
  14. package/dist/appsession.js +128 -0
  15. package/dist/appstate.js +109 -0
  16. package/dist/assets.js +67 -0
  17. package/dist/cammeta.js +292 -0
  18. package/dist/changeset-gate.js +46 -0
  19. package/dist/cli.js +156 -0
  20. package/dist/config.js +469 -0
  21. package/dist/configfile.js +81 -0
  22. package/dist/decimate.js +94 -0
  23. package/dist/errors.js +4 -0
  24. package/dist/exportjob.js +106 -0
  25. package/dist/ff.js +121 -0
  26. package/dist/fftools.js +65 -0
  27. package/dist/geo.js +70 -0
  28. package/dist/inputs.js +59 -0
  29. package/dist/manual/anchors.js +23 -0
  30. package/dist/manual/build.js +78 -0
  31. package/dist/manual/cliref.js +36 -0
  32. package/dist/manual/links.js +76 -0
  33. package/dist/manual/markdown.js +101 -0
  34. package/dist/manual/model.js +4 -0
  35. package/dist/manual/module.js +8 -0
  36. package/dist/manual/nav.js +13 -0
  37. package/dist/manual/reference.js +26 -0
  38. package/dist/page.js +108 -0
  39. package/dist/paths.js +28 -0
  40. package/dist/plan.js +119 -0
  41. package/dist/png.js +52 -0
  42. package/dist/proto.js +102 -0
  43. package/dist/range.js +58 -0
  44. package/dist/render.js +408 -0
  45. package/dist/renderer/boot.js +7 -0
  46. package/dist/renderer/dom.js +132 -0
  47. package/dist/renderer/framemath.js +34 -0
  48. package/dist/renderer/leaflet.js +5 -0
  49. package/dist/renderer/scene.js +358 -0
  50. package/dist/renderer/theme.js +34 -0
  51. package/dist/renderer/tilesources.js +34 -0
  52. package/dist/renderer/trail.js +53 -0
  53. package/dist/restyle.js +24 -0
  54. package/dist/run.js +446 -0
  55. package/dist/serve.js +70 -0
  56. package/dist/srt.js +76 -0
  57. package/dist/summary.js +22 -0
  58. package/dist/telemetry-math.js +302 -0
  59. package/dist/telemetry.js +38 -0
  60. package/dist/tilecache.js +26 -0
  61. package/dist/tiles.js +241 -0
  62. package/dist/tracing.js +208 -0
  63. package/dist/version.js +3 -0
  64. package/package.json +100 -4
package/app/main.mjs ADDED
@@ -0,0 +1,496 @@
1
+ #!/usr/bin/env node
2
+ // Electron shell for the Drone Path desktop app: window, native file
3
+ // dialog, the app:// scheme and process lifecycle only. All behavior lives in
4
+ // dist/ (compiled from src/), so the app and the CLI stay one code base.
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import process from 'node:process';
9
+ import { Readable } from 'node:stream';
10
+ import { pathToFileURL } from 'node:url';
11
+
12
+ import { app, BrowserWindow, dialog, ipcMain, net, protocol, shell } from 'electron';
13
+
14
+ import { resolveAppAsset } from '../dist/appassets.js';
15
+ import { APP_ORIGIN, appStateFile, uiExportRoot } from '../dist/apppaths.js';
16
+ import {
17
+ applyAppState,
18
+ emptyAppState,
19
+ readAppState,
20
+ rememberOpenedFile,
21
+ writeAppState,
22
+ } from '../dist/appstate.js';
23
+ import { createAppSession, parsePickRequest } from '../dist/appsession.js';
24
+ import { parseExportRequest, parseSettingsPatch } from '../dist/config.js';
25
+ import { resolveConfig } from '../dist/configfile.js';
26
+ import { ERROR_PREFIX, errorMessage } from '../dist/errors.js';
27
+ import { createExportRunner } from '../dist/exportjob.js';
28
+ import { requireTools } from '../dist/ff.js';
29
+ import { resolveFfTools } from '../dist/fftools.js';
30
+ import { rangePlan } from '../dist/range.js';
31
+ import { outputPathFor } from '../dist/run.js';
32
+ import { createTileTraffic } from '../dist/tiles.js';
33
+ import { initUpdates } from './update.mjs';
34
+
35
+ const SCHEME = 'app';
36
+ // --dev-url points the window at `next dev` (hot reload) instead of the
37
+ // built export; kept an argv flag so no cross-platform env helper is needed.
38
+ const devUrlIndex = process.argv.indexOf('--dev-url');
39
+ const DEV_URL = devUrlIndex >= 0 ? process.argv[devUrlIndex + 1] : null;
40
+ const DEV_MODE = DEV_URL !== null;
41
+ const log = (msg) => process.stderr.write(`[drone-path] ${msg}\n`);
42
+
43
+ // Must run before app ready so the scheme gets standard/secure semantics.
44
+ protocol.registerSchemesAsPrivileged([
45
+ {
46
+ scheme: SCHEME,
47
+ privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true },
48
+ },
49
+ ]);
50
+
51
+ // Resolved against this script's directory (works in a checkout and in
52
+ // app.asar); app.getAppPath() does not point at the repo root when Electron
53
+ // is started with a script path.
54
+ const exportRoot = uiExportRoot(import.meta.dirname);
55
+
56
+ // The one window's mutable state, created in startup() and handed to every
57
+ // stage as one object: the IPC handlers, the export runner callbacks and the
58
+ // window lifecycle handlers share it, so each writer (export completion, the
59
+ // close guard, window-all-closed) is a named handler instead of a nested
60
+ // closure over scattered module globals.
61
+ function createShellState() {
62
+ return {
63
+ win: null,
64
+ session: null,
65
+ config: null,
66
+ appState: emptyAppState(),
67
+ tileTraffic: null,
68
+ // The one tile prefetch entry point every in-process lane drives.
69
+ tilePrefetch: null,
70
+ exportRunner: null,
71
+ // The update controller, or null when this build cannot self-update.
72
+ updates: null,
73
+ // A downloaded update waits even if its announcement raced the renderer.
74
+ updateReady: false,
75
+ // The destination of the last successful export: the only path the
76
+ // renderer may reveal or open.
77
+ lastExportOut: null,
78
+ closePromptOpen: false,
79
+ pendingClose: false,
80
+ };
81
+ }
82
+
83
+ async function pickRecording(state) {
84
+ const options = {
85
+ title: 'Choose a drone recording',
86
+ filters: [{ name: 'DJI recordings', extensions: ['mp4'] }],
87
+ properties: ['openFile'],
88
+ // Back where the last recording came from, when that folder still exists.
89
+ defaultPath: rememberedOpenDir(state) ?? undefined,
90
+ };
91
+ const result = state.win
92
+ ? await dialog.showOpenDialog(state.win, options)
93
+ : await dialog.showOpenDialog(options);
94
+ const picked = result.canceled ? null : result.filePaths[0];
95
+ if (picked) rememberPicked(state, picked);
96
+ return picked;
97
+ }
98
+
99
+ function rememberedOpenDir(state) {
100
+ const dir = state.appState.lastOpenDir;
101
+ return dir && fs.existsSync(dir) ? dir : undefined;
102
+ }
103
+
104
+ function rememberPicked(state, filePath) {
105
+ state.appState = rememberOpenedFile(state.appState, filePath);
106
+ try {
107
+ writeAppState(appStateFile(), state.appState);
108
+ } catch (e) {
109
+ // The pick and the look still apply when the state file cannot be written.
110
+ log(`app state not saved: ${errorMessage(e)}`);
111
+ }
112
+ }
113
+
114
+ function fail(error) {
115
+ const message = errorMessage(error);
116
+ process.stderr.write(`${ERROR_PREFIX}${message}\n`);
117
+ dialog.showErrorBox('Drone Path', message);
118
+ app.quit();
119
+ }
120
+
121
+ function sendToWindow(state, channel, payload) {
122
+ if (state.win && !state.win.isDestroyed()) state.win.webContents.send(channel, payload);
123
+ }
124
+
125
+ function handleExportDone(state, outcome) {
126
+ if (outcome.status === 'ok') state.lastExportOut = outcome.summary.out;
127
+ sendToWindow(state, 'dronepath:export:done', outcome);
128
+ if (state.pendingClose) {
129
+ state.pendingClose = false;
130
+ if (state.win && !state.win.isDestroyed()) state.win.close();
131
+ else app.quit();
132
+ }
133
+ }
134
+
135
+ function videoResponse(request, filePath) {
136
+ const size = fs.statSync(filePath).size;
137
+ const plan = rangePlan(request.headers.get('range') ?? undefined, size, 'video/mp4');
138
+ if (plan.status === 416) {
139
+ return new Response(plan.body, { status: 416, headers: plan.headers });
140
+ }
141
+ const stream =
142
+ plan.status === 206
143
+ ? fs.createReadStream(filePath, { start: plan.span.start, end: plan.span.end })
144
+ : fs.createReadStream(filePath);
145
+ return new Response(Readable.toWeb(stream), { status: plan.status, headers: plan.headers });
146
+ }
147
+
148
+ // net.fetch only sets request headers; wrapping the body gives the client
149
+ // the intended MIME and status.
150
+ async function fileResponse(filePath, mime, status = 200) {
151
+ const fetched = await net.fetch(pathToFileURL(filePath).toString());
152
+ return new Response(fetched.body, { status, headers: { 'Content-Type': mime } });
153
+ }
154
+
155
+ function notFound() {
156
+ const fallback = path.join(exportRoot, '404.html');
157
+ return fs.existsSync(fallback)
158
+ ? fileResponse(fallback, 'text/html; charset=utf-8', 404)
159
+ : new Response('not found', { status: 404 });
160
+ }
161
+
162
+ async function handleRequest(state, request) {
163
+ let pathname;
164
+ try {
165
+ pathname = decodeURIComponent(new URL(request.url).pathname);
166
+ } catch {
167
+ return new Response('bad request', { status: 400 });
168
+ }
169
+ const plan = resolveAppAsset(pathname, {
170
+ exportRoot,
171
+ tileCache: state.config.tileCache,
172
+ videoPath: state.session ? state.session.videoPath() : null,
173
+ });
174
+ switch (plan.kind) {
175
+ case 'video':
176
+ return videoResponse(request, plan.filePath);
177
+ case 'tile': {
178
+ // Always through the tile traffic: it serves cached tiles immediately,
179
+ // retries tiles whose earlier download failed (so they recover once
180
+ // connectivity returns) and falls back to the placeholder.
181
+ const file = await state.tileTraffic.ensure(plan.style, plan.tile);
182
+ return fileResponse(file, 'image/png');
183
+ }
184
+ case 'export':
185
+ if (fs.existsSync(plan.filePath)) return fileResponse(plan.filePath, plan.mime);
186
+ return notFound();
187
+ case 'not-found':
188
+ return notFound();
189
+ }
190
+ }
191
+
192
+ // Only this app's window may drive the session state machine.
193
+ function assertTrusted(event) {
194
+ const url = (event.senderFrame && event.senderFrame.url) || '';
195
+ const devOk = DEV_URL !== null && url.startsWith(DEV_URL);
196
+ if (!url.startsWith(APP_ORIGIN + '/') && !devOk) {
197
+ throw new Error('untrusted ipc sender');
198
+ }
199
+ }
200
+
201
+ function exportOutputOf(state, payload) {
202
+ const out = payload && typeof payload === 'object' ? payload.out : null;
203
+ if (typeof out !== 'string' || out !== state.lastExportOut) {
204
+ throw new Error('unknown export output');
205
+ }
206
+ return out;
207
+ }
208
+
209
+ // The backing services behind the window: tool check, config, tile cache and
210
+ // the recording session.
211
+ async function initServices(state) {
212
+ const resolved = resolveConfig({});
213
+ state.appState = readAppState(appStateFile());
214
+ state.config = applyAppState(resolved.config, state.appState);
215
+ await requireTools(resolveFfTools(state.config));
216
+ // One polite tile queue for the whole app: on-demand tiles and the export
217
+ // prefetch share its request budget, and on-demand tiles the player needs
218
+ // right now jump the queue.
219
+ state.tileTraffic = createTileTraffic(state.config.tileCache);
220
+ state.tilePrefetch = (options) => state.tileTraffic.stream(options);
221
+ state.session = createAppSession({
222
+ config: state.config,
223
+ pickFile: () => pickRecording(state),
224
+ log,
225
+ onPreparing: () => sendToWindow(state, 'dronepath:preparing'),
226
+ onPrepareProgress: (progress) =>
227
+ sendToWindow(state, 'dronepath:preparing:progress', progress),
228
+ });
229
+ }
230
+
231
+ function initExportRunner(state) {
232
+ state.exportRunner = createExportRunner({
233
+ log: (msg) => {
234
+ log(msg);
235
+ sendToWindow(state, 'dronepath:export:progress', msg);
236
+ },
237
+ onCapture: (progress) =>
238
+ sendToWindow(state, 'dronepath:export:capture', progress),
239
+ onDone: (outcome) => handleExportDone(state, outcome),
240
+ // An export warms tiles next to the live app: same queue, same budget.
241
+ deps: { prefetchTiles: state.tilePrefetch },
242
+ });
243
+ }
244
+
245
+ function registerIpcHandlers(state) {
246
+ ipcMain.handle('dronepath:pick', (event, raw) => {
247
+ assertTrusted(event);
248
+ try {
249
+ return state.session.pick(parsePickRequest(raw));
250
+ } catch (e) {
251
+ return { ok: false, error: errorMessage(e) };
252
+ }
253
+ });
254
+ ipcMain.handle('dronepath:session', (event) => {
255
+ assertTrusted(event);
256
+ return state.session.getSession();
257
+ });
258
+ ipcMain.handle('dronepath:settings', (event) => {
259
+ assertTrusted(event);
260
+ return state.config;
261
+ });
262
+ ipcMain.handle('dronepath:settings:save', (event, raw) => {
263
+ assertTrusted(event);
264
+ let settings;
265
+ try {
266
+ settings = parseSettingsPatch(raw, 'settings');
267
+ } catch (e) {
268
+ return { ok: false, error: errorMessage(e) };
269
+ }
270
+ state.appState = { ...state.appState, settings };
271
+ state.config = applyAppState(state.config, state.appState);
272
+ try {
273
+ writeAppState(appStateFile(), state.appState);
274
+ } catch (e) {
275
+ // The look still applies when the state file cannot be written.
276
+ log(`app state not saved: ${errorMessage(e)}`);
277
+ }
278
+ return { ok: true };
279
+ });
280
+
281
+ ipcMain.handle('dronepath:export:pick-output', async (event) => {
282
+ assertTrusted(event);
283
+ const video = state.session ? state.session.videoPath() : null;
284
+ if (!video) return { ok: false, error: 'no recording loaded' };
285
+ // The CLI's default naming, with a relative out dir anchored at the
286
+ // recording: the app process has no meaningful working directory.
287
+ const outDir = state.config.outDir
288
+ ? path.resolve(path.dirname(video), state.config.outDir)
289
+ : null;
290
+ const options = {
291
+ title: 'Export flight map',
292
+ defaultPath: outputPathFor(video, { ...state.config, outDir }),
293
+ filters: [{ name: 'MP4 video', extensions: ['mp4'] }],
294
+ };
295
+ const result = state.win
296
+ ? await dialog.showSaveDialog(state.win, options)
297
+ : await dialog.showSaveDialog(options);
298
+ if (result.canceled || !result.filePath) return { ok: false, canceled: true };
299
+ const chosen = result.filePath.toLowerCase().endsWith('.mp4')
300
+ ? result.filePath
301
+ : `${result.filePath}.mp4`;
302
+ // The native dialog confirmed the name as typed, but `.mp4` may have been
303
+ // appended after it: re-check the final path on every platform so an
304
+ // existing file is never replaced without a confirmation.
305
+ if (fs.existsSync(chosen)) {
306
+ const box = {
307
+ type: 'warning',
308
+ buttons: ['Replace', 'Cancel'],
309
+ defaultId: 1,
310
+ cancelId: 1,
311
+ message: `Replace ${path.basename(chosen)}?`,
312
+ detail: chosen,
313
+ };
314
+ const confirm = state.win
315
+ ? await dialog.showMessageBox(state.win, box)
316
+ : await dialog.showMessageBox(box);
317
+ if (confirm.response !== 0) return { ok: false, canceled: true };
318
+ }
319
+ return { ok: true, path: chosen };
320
+ });
321
+ ipcMain.handle('dronepath:export:start', (event, raw) => {
322
+ assertTrusted(event);
323
+ try {
324
+ const video = state.session ? state.session.videoPath() : null;
325
+ if (!video) return { ok: false, error: 'no recording loaded' };
326
+ state.exportRunner.start(video, parseExportRequest(raw, state.config));
327
+ return { ok: true };
328
+ } catch (e) {
329
+ return { ok: false, error: errorMessage(e) };
330
+ }
331
+ });
332
+ ipcMain.handle('dronepath:export:cancel', (event) => {
333
+ assertTrusted(event);
334
+ state.exportRunner.cancel();
335
+ return { ok: true };
336
+ });
337
+ ipcMain.handle('dronepath:export:reveal', (event, payload) => {
338
+ assertTrusted(event);
339
+ try {
340
+ shell.showItemInFolder(exportOutputOf(state, payload));
341
+ return { ok: true };
342
+ } catch (e) {
343
+ return { ok: false, error: errorMessage(e) };
344
+ }
345
+ });
346
+ ipcMain.handle('dronepath:export:open', async (event, payload) => {
347
+ assertTrusted(event);
348
+ try {
349
+ const error = await shell.openPath(exportOutputOf(state, payload));
350
+ return error ? { ok: false, error } : { ok: true };
351
+ } catch (e) {
352
+ return { ok: false, error: errorMessage(e) };
353
+ }
354
+ });
355
+ ipcMain.handle('dronepath:update:restart', (event) => {
356
+ assertTrusted(event);
357
+ if (!state.updates) return { ok: false, error: 'this build does not self-update' };
358
+ // No pendingClose here: the prompt never opens over a running export, and
359
+ // a failed restart must not poison the export close guard.
360
+ return state.updates.restart({
361
+ onError: (message) => sendToWindow(state, 'dronepath:update:restart-failed', message),
362
+ });
363
+ });
364
+ ipcMain.handle('dronepath:update:state', (event) => {
365
+ assertTrusted(event);
366
+ return { ready: state.updateReady };
367
+ });
368
+ }
369
+
370
+ function installProtocolHandler(state) {
371
+ protocol.handle(SCHEME, (request) =>
372
+ handleRequest(state, request).catch((e) => {
373
+ log(`scheme error: ${errorMessage(e)}`);
374
+ return new Response('internal error', { status: 500 });
375
+ }),
376
+ );
377
+ }
378
+
379
+ function ensureUiExport() {
380
+ if (!DEV_MODE && !fs.existsSync(path.join(exportRoot, 'index.html'))) {
381
+ throw new Error('ui export missing; run "npm run build" first');
382
+ }
383
+ }
384
+
385
+ function createWindow(state) {
386
+ state.win = new BrowserWindow({
387
+ width: 1600,
388
+ height: 950,
389
+ // The control bar needs ~1000px of min-content width; below this the
390
+ // right-hand buttons would become unreachable.
391
+ minWidth: 1024,
392
+ minHeight: 600,
393
+ // Match --page in ui/app/globals.css so startup shows one background.
394
+ backgroundColor: '#232323',
395
+ autoHideMenuBar: true,
396
+ // The loaded page's <title> takes over after load (ui/app/layout.tsx).
397
+ title: 'Drone Path',
398
+ // Windows renders an ICO best, Linux a PNG (Electron docs); both are
399
+ // derived from build/icon-master.png (see build/README.md).
400
+ icon:
401
+ process.platform === 'win32'
402
+ ? path.join(import.meta.dirname, '..', 'build', 'icon.ico')
403
+ : path.join(import.meta.dirname, '..', 'build', 'icons', '256x256.png'),
404
+ webPreferences: {
405
+ preload: path.join(import.meta.dirname, 'preload.cjs'),
406
+ contextIsolation: true,
407
+ sandbox: true,
408
+ nodeIntegration: false,
409
+ },
410
+ });
411
+ state.win.on('closed', () => {
412
+ state.win = null;
413
+ });
414
+ // Web links (e.g. in the user manual) open in the system browser, never in
415
+ // a second app window.
416
+ state.win.webContents.setWindowOpenHandler(({ url }) => {
417
+ if (/^(https?|mailto):/i.test(url)) void shell.openExternal(url);
418
+ return { action: 'deny' };
419
+ });
420
+ }
421
+
422
+ // Closing the window must not silently kill a running export and strand
423
+ // minutes of work; the user chooses between stopping and keeping it.
424
+ function installCloseGuard(state) {
425
+ state.win.on('close', (e) => {
426
+ // A close already confirmed by the user, or with nothing running, passes.
427
+ if (state.pendingClose || !state.exportRunner || !state.exportRunner.running()) return;
428
+ if (state.closePromptOpen) {
429
+ e.preventDefault();
430
+ return;
431
+ }
432
+ e.preventDefault();
433
+ state.closePromptOpen = true;
434
+ const box = {
435
+ type: 'warning',
436
+ buttons: ['Stop Export and Close', 'Keep Exporting'],
437
+ defaultId: 1,
438
+ cancelId: 1,
439
+ message: 'An export is in progress',
440
+ detail: 'Closing the window stops the export and removes its working file.',
441
+ };
442
+ void (state.win ? dialog.showMessageBox(state.win, box) : dialog.showMessageBox(box)).then(
443
+ ({ response }) => {
444
+ state.closePromptOpen = false;
445
+ if (response !== 0) return;
446
+ // Cancellation settles asynchronously: the close completes from the
447
+ // job's onDone, never from a synchronous running() check.
448
+ state.pendingClose = true;
449
+ state.exportRunner.cancel();
450
+ },
451
+ );
452
+ });
453
+ }
454
+
455
+ async function loadUi(state) {
456
+ await state.win.loadURL(DEV_MODE ? DEV_URL : `${APP_ORIGIN}/`);
457
+ }
458
+
459
+ // The window is the app: closing it quits. A still-running export delays the
460
+ // quit until its job has settled and cleaned up after itself.
461
+ function handleWindowAllClosed(state) {
462
+ if (state.exportRunner && state.exportRunner.running()) {
463
+ state.pendingClose = true;
464
+ state.exportRunner.cancel();
465
+ return;
466
+ }
467
+ app.quit();
468
+ }
469
+
470
+ async function startup() {
471
+ const state = createShellState();
472
+ app.on('window-all-closed', () => handleWindowAllClosed(state));
473
+ try {
474
+ await initServices(state);
475
+ initExportRunner(state);
476
+ state.updates = initUpdates({
477
+ log,
478
+ onReady: () => {
479
+ // Buffered: the cache fast path can announce before the renderer
480
+ // subscribes, and the state handler replays it on mount.
481
+ state.updateReady = true;
482
+ sendToWindow(state, 'dronepath:update:ready');
483
+ },
484
+ });
485
+ registerIpcHandlers(state);
486
+ installProtocolHandler(state);
487
+ ensureUiExport();
488
+ createWindow(state);
489
+ installCloseGuard(state);
490
+ await loadUi(state);
491
+ } catch (e) {
492
+ fail(e);
493
+ }
494
+ }
495
+
496
+ app.whenReady().then(startup);
@@ -0,0 +1,31 @@
1
+ // Preload bridge for the UI: the only surface the renderer sees. CommonJS
2
+ // (.cjs) because sandboxed preload scripts cannot use ESM.
3
+ const { contextBridge, ipcRenderer } = require('electron');
4
+
5
+ function subscribe(channel, adapt) {
6
+ const handler = (_event, payload) => adapt(payload);
7
+ ipcRenderer.on(channel, handler);
8
+ return () => ipcRenderer.removeListener(channel, handler);
9
+ }
10
+
11
+ contextBridge.exposeInMainWorld('dronepath', {
12
+ pickRecording: (request) => ipcRenderer.invoke('dronepath:pick', request),
13
+ getSession: () => ipcRenderer.invoke('dronepath:session'),
14
+ getSettings: () => ipcRenderer.invoke('dronepath:settings'),
15
+ saveSettings: (patch) => ipcRenderer.invoke('dronepath:settings:save', patch),
16
+ pickExportOutput: () => ipcRenderer.invoke('dronepath:export:pick-output'),
17
+ startExport: (request) => ipcRenderer.invoke('dronepath:export:start', request),
18
+ cancelExport: () => ipcRenderer.invoke('dronepath:export:cancel'),
19
+ revealExportOutput: (payload) => ipcRenderer.invoke('dronepath:export:reveal', payload),
20
+ openExportOutput: (payload) => ipcRenderer.invoke('dronepath:export:open', payload),
21
+ onExportProgress: (cb) => subscribe('dronepath:export:progress', cb),
22
+ onExportCapture: (cb) => subscribe('dronepath:export:capture', cb),
23
+ onExportDone: (cb) => subscribe('dronepath:export:done', cb),
24
+ onPreparing: (cb) => subscribe('dronepath:preparing', () => cb()),
25
+ onPrepareProgress: (cb) => subscribe('dronepath:preparing:progress', cb),
26
+ onUpdateReady: (cb) => subscribe('dronepath:update:ready', () => cb()),
27
+ onUpdateRestartFailed: (cb) =>
28
+ subscribe('dronepath:update:restart-failed', (message) => cb(message)),
29
+ getUpdateState: () => ipcRenderer.invoke('dronepath:update:state'),
30
+ restartToUpdate: () => ipcRenderer.invoke('dronepath:update:restart'),
31
+ });
@@ -0,0 +1,6 @@
1
+ export interface UpdateGateInput {
2
+ packaged: boolean;
3
+ hasUpdateMetadata: boolean;
4
+ }
5
+
6
+ export declare function shouldCheckForUpdates(input: UpdateGateInput): boolean;
@@ -0,0 +1,6 @@
1
+ // Whether this install can ever self-update. Only packaged builds that carry
2
+ // electron-builder's update metadata talk to the feed: NSIS and AppImage
3
+ // builds ship app-update.yml, portable installs and dev runs never do.
4
+ export function shouldCheckForUpdates({ packaged, hasUpdateMetadata }) {
5
+ return packaged && hasUpdateMetadata;
6
+ }
@@ -0,0 +1,10 @@
1
+ export interface UpdateController {
2
+ restart(deps: { onError: (message: string) => void }): { ok: true } | { ok: false; error: string };
3
+ }
4
+
5
+ export interface InitUpdatesOptions {
6
+ log: (message: string) => void;
7
+ onReady: () => void;
8
+ }
9
+
10
+ export function initUpdates(options: InitUpdatesOptions): UpdateController | null;
package/app/update.mjs ADDED
@@ -0,0 +1,54 @@
1
+ // Auto-update for the packaged desktop app: check the GitHub release feed,
2
+ // download in the background and let the UI prompt before the restart. Every
3
+ // failure stays a stderr line and never touches startup.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import process from 'node:process';
7
+
8
+ import { app } from 'electron';
9
+ // The default import then destructuring keeps ESM consumers off the CJS named
10
+ // export interop (electron-builder issue #7976).
11
+ import electronUpdater from 'electron-updater';
12
+
13
+ import { errorMessage } from '../dist/errors.js';
14
+ import { shouldCheckForUpdates } from './update-policy.mjs';
15
+
16
+ const { autoUpdater } = electronUpdater;
17
+
18
+ export function initUpdates({ log, onReady }) {
19
+ const hasUpdateMetadata = fs.existsSync(path.join(process.resourcesPath, 'app-update.yml'));
20
+ if (!shouldCheckForUpdates({ packaged: app.isPackaged, hasUpdateMetadata })) return null;
21
+
22
+ autoUpdater.autoDownload = true;
23
+ // A postponed prompt must still install the update on the next regular quit.
24
+ autoUpdater.autoInstallOnAppQuit = true;
25
+ autoUpdater.logger = {
26
+ info: (message) => log(`update: ${message}`),
27
+ warn: (message) => log(`update: ${message}`),
28
+ error: (message) => log(`update: ${message}`),
29
+ };
30
+ // Feed and download failures are background noise: report and continue.
31
+ autoUpdater.on('error', (e) => log(`update failed: ${errorMessage(e)}`));
32
+ autoUpdater.on('update-downloaded', () => onReady());
33
+ autoUpdater.checkForUpdates().catch((e) => log(`update check failed: ${errorMessage(e)}`));
34
+
35
+ return {
36
+ // electron-updater swallows install failures onto its 'error' event and
37
+ // keeps running: both the thrown and the emitted failure must surface or
38
+ // the restart prompt would wait forever.
39
+ restart({ onError }) {
40
+ const fail = (e) => {
41
+ autoUpdater.removeListener('error', fail);
42
+ onError(errorMessage(e));
43
+ };
44
+ autoUpdater.once('error', fail);
45
+ try {
46
+ autoUpdater.quitAndInstall(true, true);
47
+ } catch (e) {
48
+ fail(e);
49
+ return { ok: false, error: errorMessage(e) };
50
+ }
51
+ return { ok: true };
52
+ },
53
+ };
54
+ }
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ // bin/drone-path.mjs - launcher shim for the compiled CLI (dist/cli.js).
3
+ import { main } from '../dist/cli.js';
4
+
5
+ await main();
@@ -0,0 +1,44 @@
1
+ // Pure routing for the app's custom-scheme server: maps a request pathname to
2
+ // the resource that backs it. The Electron glue performs the I/O; the
3
+ // path-traversal guard lives here so it stays unit-testable.
4
+ import path from 'node:path';
5
+ import { mimeFor, resolveTileRoute } from './assets.js';
6
+ import { MEDIA_PATH } from './apppaths.js';
7
+ /** Resolves an already-decoded URL pathname (e.g. "/index.html"). */
8
+ export function resolveAppAsset(pathname, routes) {
9
+ if (pathname === MEDIA_PATH) {
10
+ return routes.videoPath
11
+ ? { kind: 'video', filePath: routes.videoPath }
12
+ : { kind: 'not-found' };
13
+ }
14
+ // Every known style routes into the shared cache ({ anyStyle: true }):
15
+ // live restyle switches styles without a reload, so no single style owns
16
+ // the tile route. Anything tile-shaped but not a tile resolves like any
17
+ // other static path.
18
+ const tile = resolveTileRoute(pathname, routes.tileCache, { anyStyle: true });
19
+ if (tile) {
20
+ return { kind: 'tile', ...tile };
21
+ }
22
+ return exportFile(pathname, routes.exportRoot);
23
+ }
24
+ function exportFile(pathname, exportRoot) {
25
+ let rel = pathname.replace(/^\/+/, '');
26
+ if (rel === '' || rel.endsWith('/'))
27
+ rel += 'index.html';
28
+ // URL pathnames are POSIX-style; a drive prefix or backslash marks a
29
+ // Windows-flavored path that POSIX resolution would mistake for a plain
30
+ // file name. Refuse it outright so the guard behaves the same on every OS.
31
+ if (rel.split('/').some((s) => s.includes('\\') || /^[a-zA-Z]:/.test(s))) {
32
+ return { kind: 'not-found' };
33
+ }
34
+ const filePath = path.resolve(exportRoot, rel);
35
+ const relCheck = path.relative(exportRoot, filePath);
36
+ if (relCheck === '' || relCheck.startsWith('..') || path.isAbsolute(relCheck)) {
37
+ return { kind: 'not-found' };
38
+ }
39
+ return {
40
+ kind: 'export',
41
+ filePath,
42
+ mime: mimeFor(filePath),
43
+ };
44
+ }
@@ -0,0 +1,28 @@
1
+ // URL and path layout for the desktop app: the custom-scheme vocabulary,
2
+ // build-artifact locations and the per-user state file have exactly one home.
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ export const APP_ORIGIN = 'app://bundle';
6
+ export const MEDIA_PATH = '/media/video';
7
+ export const MEDIA_URL = APP_ORIGIN + MEDIA_PATH;
8
+ export const TILE_BASE = APP_ORIGIN + '/tiles';
9
+ /** The media URL for one recording: the query names the file, so a reload
10
+ * can never replay another recording's bytes from a URL-keyed cache. */
11
+ export function mediaUrlFor(videoPath) {
12
+ return `${MEDIA_URL}?v=${encodeURIComponent(videoPath)}`;
13
+ }
14
+ /** The Next.js static export (ui/out) next to the app shell directory. */
15
+ export function uiExportRoot(shellDir) {
16
+ return path.join(shellDir, '..', 'ui', 'out');
17
+ }
18
+ // The per-user data root (LOCALAPPDATA on Windows, the cache convention
19
+ // elsewhere): the tile cache and the state file share it, so one machine-local
20
+ // place holds everything the app keeps per user.
21
+ export function userDataDir() {
22
+ const base = process.env['LOCALAPPDATA'] ?? path.join(os.homedir(), '.cache');
23
+ return path.join(base, 'drone-path');
24
+ }
25
+ /** The per-user state file the desktop app restores its settings from. */
26
+ export function appStateFile() {
27
+ return path.join(userDataDir(), 'state.json');
28
+ }