@mountaya/studio 0.0.0-stage → 0.2.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 (521) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/LICENCE.fr.txt +280 -0
  3. package/LICENSE.txt +262 -0
  4. package/README.md +917 -2
  5. package/dist/agent/index.cjs +2600 -0
  6. package/dist/agent/index.cjs.map +1 -0
  7. package/dist/agent/index.d.cts +1237 -0
  8. package/dist/agent/index.d.ts +1237 -0
  9. package/dist/agent/index.js +2581 -0
  10. package/dist/agent/index.js.map +1 -0
  11. package/dist/chunk-3Oi_Zrtm.js +9 -0
  12. package/dist/chunk-3Oi_Zrtm.js.map +1 -0
  13. package/dist/chunk-B18OPIu_.js +6 -0
  14. package/dist/chunk-B18OPIu_.js.map +1 -0
  15. package/dist/chunk-B5Uz3Qct.cjs +15 -0
  16. package/dist/chunk-B5Uz3Qct.cjs.map +1 -0
  17. package/dist/chunk-BBEJwkd3.d.cts +839 -0
  18. package/dist/chunk-BIEc_SkR.cjs +29 -0
  19. package/dist/chunk-BIEc_SkR.cjs.map +1 -0
  20. package/dist/chunk-BKMFOe-N.js +171 -0
  21. package/dist/chunk-BKMFOe-N.js.map +1 -0
  22. package/dist/chunk-BP4uy7E1.d.ts +11583 -0
  23. package/dist/chunk-BSHTsFiB.js +1403 -0
  24. package/dist/chunk-BSHTsFiB.js.map +1 -0
  25. package/dist/chunk-BTUUABGI.js +17 -0
  26. package/dist/chunk-BTUUABGI.js.map +1 -0
  27. package/dist/chunk-BaPiaz5X.cjs +115 -0
  28. package/dist/chunk-BaPiaz5X.cjs.map +1 -0
  29. package/dist/chunk-BeCVpkYr.cjs +542 -0
  30. package/dist/chunk-BeCVpkYr.cjs.map +1 -0
  31. package/dist/chunk-BgngsvK8.cjs +6202 -0
  32. package/dist/chunk-BgngsvK8.cjs.map +1 -0
  33. package/dist/chunk-BhInd7CJ.d.cts +253 -0
  34. package/dist/chunk-Bn6ZbxkS.cjs +27 -0
  35. package/dist/chunk-By9ZnkVI.js +60 -0
  36. package/dist/chunk-By9ZnkVI.js.map +1 -0
  37. package/dist/chunk-BzqPhxsz.cjs +367 -0
  38. package/dist/chunk-BzqPhxsz.cjs.map +1 -0
  39. package/dist/chunk-C2mMX81q.d.ts +443 -0
  40. package/dist/chunk-C2rr9Q0V.cjs +1402 -0
  41. package/dist/chunk-C2rr9Q0V.cjs.map +1 -0
  42. package/dist/chunk-CDJCbwIQ.d.cts +78 -0
  43. package/dist/chunk-CLGvBOVH.d.cts +1654 -0
  44. package/dist/chunk-COdw1dc6.d.ts +525 -0
  45. package/dist/chunk-CQCJnT2i.d.ts +511 -0
  46. package/dist/chunk-CSyHY67q.cjs +353 -0
  47. package/dist/chunk-CSyHY67q.cjs.map +1 -0
  48. package/dist/chunk-CiK1Iqrv.js +950 -0
  49. package/dist/chunk-CiK1Iqrv.js.map +1 -0
  50. package/dist/chunk-CmJBgSwZ.cjs +24 -0
  51. package/dist/chunk-CmJBgSwZ.cjs.map +1 -0
  52. package/dist/chunk-CnrsRK2u.cjs +83 -0
  53. package/dist/chunk-CnrsRK2u.cjs.map +1 -0
  54. package/dist/chunk-Co782_9r.js +326 -0
  55. package/dist/chunk-Co782_9r.js.map +1 -0
  56. package/dist/chunk-Csr3KDpZ.cjs +32 -0
  57. package/dist/chunk-Csr3KDpZ.cjs.map +1 -0
  58. package/dist/chunk-CwkmccXv.js +89 -0
  59. package/dist/chunk-CwkmccXv.js.map +1 -0
  60. package/dist/chunk-D0Q4iL9B.cjs +255 -0
  61. package/dist/chunk-D0Q4iL9B.cjs.map +1 -0
  62. package/dist/chunk-DFwiSzUS.cjs +72 -0
  63. package/dist/chunk-DFwiSzUS.cjs.map +1 -0
  64. package/dist/chunk-DIFayl2P.d.cts +443 -0
  65. package/dist/chunk-DIGF58ux.d.cts +525 -0
  66. package/dist/chunk-DKuuuld5.js +101 -0
  67. package/dist/chunk-DKuuuld5.js.map +1 -0
  68. package/dist/chunk-DMePkFEo.js +5054 -0
  69. package/dist/chunk-DMePkFEo.js.map +1 -0
  70. package/dist/chunk-DO5SIBgu.js +305 -0
  71. package/dist/chunk-DO5SIBgu.js.map +1 -0
  72. package/dist/chunk-DOQ_7eE5.d.ts +6662 -0
  73. package/dist/chunk-DThaaNeb.d.cts +15 -0
  74. package/dist/chunk-DThaaNeb.d.ts +15 -0
  75. package/dist/chunk-DUQzjUJy.d.ts +78 -0
  76. package/dist/chunk-DX37IPhV.cjs +1903 -0
  77. package/dist/chunk-DX37IPhV.cjs.map +1 -0
  78. package/dist/chunk-Damps5Tk.cjs +155 -0
  79. package/dist/chunk-Damps5Tk.cjs.map +1 -0
  80. package/dist/chunk-DbK5PhpJ.d.ts +1654 -0
  81. package/dist/chunk-De0vAASv.d.ts +253 -0
  82. package/dist/chunk-DhSZ7YZt.d.cts +6662 -0
  83. package/dist/chunk-DjEvqvPA.cjs +43 -0
  84. package/dist/chunk-DjEvqvPA.cjs.map +1 -0
  85. package/dist/chunk-DkwDzwvu.d.cts +121 -0
  86. package/dist/chunk-DkwDzwvu.d.ts +121 -0
  87. package/dist/chunk-Dmszv9If.js +71 -0
  88. package/dist/chunk-Dmszv9If.js.map +1 -0
  89. package/dist/chunk-Dp_ftNWY.d.cts +511 -0
  90. package/dist/chunk-DsHQySz0.js +31 -0
  91. package/dist/chunk-DsHQySz0.js.map +1 -0
  92. package/dist/chunk-DwoUyHHh.js +281 -0
  93. package/dist/chunk-DwoUyHHh.js.map +1 -0
  94. package/dist/chunk-IaIDQflj.d.cts +2315 -0
  95. package/dist/chunk-IaIDQflj.d.ts +2315 -0
  96. package/dist/chunk-cVXLsZfL.d.ts +839 -0
  97. package/dist/chunk-mIaCX9EJ.d.cts +11583 -0
  98. package/dist/chunk-nJQxbOwQ.cjs +8962 -0
  99. package/dist/chunk-nJQxbOwQ.cjs.map +1 -0
  100. package/dist/chunk-o9jaxhCO.js +8852 -0
  101. package/dist/chunk-o9jaxhCO.js.map +1 -0
  102. package/dist/chunk-p-Tt_Lwz.js +14 -0
  103. package/dist/chunk-p-Tt_Lwz.js.map +1 -0
  104. package/dist/engines/index.cjs +2091 -0
  105. package/dist/engines/index.cjs.map +1 -0
  106. package/dist/engines/index.d.cts +2176 -0
  107. package/dist/engines/index.d.ts +2176 -0
  108. package/dist/engines/index.js +2075 -0
  109. package/dist/engines/index.js.map +1 -0
  110. package/dist/handlers/index.cjs +53 -0
  111. package/dist/handlers/index.cjs.map +1 -0
  112. package/dist/handlers/index.d.cts +403 -0
  113. package/dist/handlers/index.d.ts +403 -0
  114. package/dist/handlers/index.js +33 -0
  115. package/dist/handlers/index.js.map +1 -0
  116. package/dist/index.cjs +3511 -0
  117. package/dist/index.cjs.map +1 -0
  118. package/dist/index.d.cts +8 -0
  119. package/dist/index.d.ts +8 -0
  120. package/dist/index.js +3033 -0
  121. package/dist/index.js.map +1 -0
  122. package/dist/plugins/index.cjs +510 -0
  123. package/dist/plugins/index.cjs.map +1 -0
  124. package/dist/plugins/index.d.cts +296 -0
  125. package/dist/plugins/index.d.ts +296 -0
  126. package/dist/plugins/index.js +489 -0
  127. package/dist/plugins/index.js.map +1 -0
  128. package/dist/seams/index.cjs +89 -0
  129. package/dist/seams/index.cjs.map +1 -0
  130. package/dist/seams/index.d.cts +452 -0
  131. package/dist/seams/index.d.ts +452 -0
  132. package/dist/seams/index.js +49 -0
  133. package/dist/seams/index.js.map +1 -0
  134. package/dist/strings/fr/index.cjs +2135 -0
  135. package/dist/strings/fr/index.cjs.map +1 -0
  136. package/dist/strings/fr/index.d.cts +17 -0
  137. package/dist/strings/fr/index.d.ts +17 -0
  138. package/dist/strings/fr/index.js +2130 -0
  139. package/dist/strings/fr/index.js.map +1 -0
  140. package/dist/strings/index.cjs +2384 -0
  141. package/dist/strings/index.cjs.map +1 -0
  142. package/dist/strings/index.d.cts +3 -0
  143. package/dist/strings/index.d.ts +3 -0
  144. package/dist/strings/index.js +2353 -0
  145. package/dist/strings/index.js.map +1 -0
  146. package/dist/testing/index.cjs +230 -0
  147. package/dist/testing/index.cjs.map +1 -0
  148. package/dist/testing/index.d.cts +246 -0
  149. package/dist/testing/index.d.ts +246 -0
  150. package/dist/testing/index.js +219 -0
  151. package/dist/testing/index.js.map +1 -0
  152. package/dist/time/index.cjs +28 -0
  153. package/dist/time/index.cjs.map +1 -0
  154. package/dist/time/index.d.cts +41 -0
  155. package/dist/time/index.d.ts +41 -0
  156. package/dist/time/index.js +23 -0
  157. package/dist/time/index.js.map +1 -0
  158. package/package.json +224 -4
  159. package/src/agent/engines/agentThreads.ts +1601 -0
  160. package/src/agent/engines/directorChat.ts +500 -0
  161. package/src/agent/index.ts +67 -0
  162. package/src/agent/rules/agentEditLock.ts +115 -0
  163. package/src/agent/rules/agentErrorCopy.ts +44 -0
  164. package/src/agent/rules/copilotOrganization.ts +36 -0
  165. package/src/agent/rules/playbook.gen.ts +444 -0
  166. package/src/agent/rules/router.ts +518 -0
  167. package/src/agent/rules/stateDelta.ts +29 -0
  168. package/src/agent/rules/studioRouter.ts +123 -0
  169. package/src/agent/rules/surfaces.gen.ts +633 -0
  170. package/src/agent/rules/threadsUrl.ts +48 -0
  171. package/src/agent/rules/transcriptObserver.ts +90 -0
  172. package/src/agent/stores/agentThreads.ts +451 -0
  173. package/src/bus/contracts/noData.ts +18 -0
  174. package/src/bus/contracts/shared.ts +172 -0
  175. package/src/bus/contracts/studioTools.ts +224 -0
  176. package/src/bus/rules/bus.ts +857 -0
  177. package/src/bus/rules/confirmation.ts +22 -0
  178. package/src/bus/rules/defineRegistry.ts +24 -0
  179. package/src/bus/rules/errors.ts +401 -0
  180. package/src/bus/rules/handlerErrors.ts +103 -0
  181. package/src/bus/rules/handlerRegistry.ts +627 -0
  182. package/src/bus/rules/inputSchema.ts +232 -0
  183. package/src/bus/rules/invalidInput.ts +441 -0
  184. package/src/bus/rules/lateBoundTools.ts +100 -0
  185. package/src/bus/rules/studioRegistry.ts +324 -0
  186. package/src/bus/rules/studioToolBus.ts +73 -0
  187. package/src/bus/rules/types.ts +804 -0
  188. package/src/chrome/contracts/alert.ts +42 -0
  189. package/src/chrome/contracts/itinerary.ts +26 -0
  190. package/src/chrome/contracts/map.ts +23 -0
  191. package/src/chrome/contracts/overlay.ts +46 -0
  192. package/src/chrome/contracts/panel.ts +29 -0
  193. package/src/chrome/contracts/question.ts +52 -0
  194. package/src/chrome/contracts/selection.ts +26 -0
  195. package/src/chrome/contracts/sidenav.ts +23 -0
  196. package/src/chrome/contracts/snapshot.ts +319 -0
  197. package/src/chrome/contracts/state.ts +22 -0
  198. package/src/chrome/contracts/tabs.ts +56 -0
  199. package/src/chrome/handlers/alert.ts +91 -0
  200. package/src/chrome/handlers/introspection.ts +180 -0
  201. package/src/chrome/handlers/panels.ts +42 -0
  202. package/src/chrome/handlers/question.ts +24 -0
  203. package/src/chrome/handlers/sidenav.ts +116 -0
  204. package/src/chrome/handlers/snapshot.ts +451 -0
  205. package/src/chrome/handlers/stateDelta.ts +125 -0
  206. package/src/chrome/handlers/tabs.ts +143 -0
  207. package/src/chrome/handlers/timestamp.ts +19 -0
  208. package/src/chrome/rules/agentSelectors.ts +210 -0
  209. package/src/chrome/rules/mapAlert.ts +13 -0
  210. package/src/chrome/rules/question.ts +25 -0
  211. package/src/chrome/rules/tabs.ts +13 -0
  212. package/src/chrome/stores/activeDraftSession.ts +134 -0
  213. package/src/chrome/stores/chrome.ts +527 -0
  214. package/src/chrome/stores/uiStore.ts +575 -0
  215. package/src/collab/contracts/collab.ts +261 -0
  216. package/src/collab/handlers/collab.ts +468 -0
  217. package/src/collab/rules/toolNames.ts +33 -0
  218. package/src/collab/stores/collab.ts +899 -0
  219. package/src/collections/contracts/collection.ts +182 -0
  220. package/src/collections/handlers/collectionAttach.ts +141 -0
  221. package/src/collections/handlers/collections.ts +499 -0
  222. package/src/collections/handlers/heldCollection.ts +42 -0
  223. package/src/collections/handlers/restCollections.ts +386 -0
  224. package/src/collections/rules/collections.ts +138 -0
  225. package/src/collections/rules/entityCollections.ts +53 -0
  226. package/src/collections/stores/collections.ts +133 -0
  227. package/src/data/contracts/data.ts +233 -0
  228. package/src/data/contracts/itinerary.ts +71 -0
  229. package/src/data/handlers/activityResolve.ts +76 -0
  230. package/src/data/handlers/data.ts +200 -0
  231. package/src/data/handlers/graphql.ts +26 -0
  232. package/src/data/handlers/mutationSink.ts +1577 -0
  233. package/src/data/handlers/profile.ts +83 -0
  234. package/src/data/handlers/writeThrough.ts +417 -0
  235. package/src/data/rules/cache.ts +181 -0
  236. package/src/data/rules/dataTypes.ts +40 -0
  237. package/src/data/rules/keys.ts +106 -0
  238. package/src/data/rules/persistence.ts +1058 -0
  239. package/src/data/rules/requestBody.ts +43 -0
  240. package/src/data/rules/restErrors.ts +354 -0
  241. package/src/data/rules/sessionSurface.ts +156 -0
  242. package/src/data/rules/toolResultData.ts +73 -0
  243. package/src/data/rules/uuid.ts +24 -0
  244. package/src/edit/contracts/edit.ts +37 -0
  245. package/src/edit/contracts/itinerary.ts +57 -0
  246. package/src/edit/handlers/draftCommit.ts +257 -0
  247. package/src/edit/handlers/editDiscard.ts +34 -0
  248. package/src/edit/handlers/editLock.ts +949 -0
  249. package/src/edit/handlers/editor.ts +203 -0
  250. package/src/edit/handlers/formUnsaved.ts +24 -0
  251. package/src/edit/rules/draftMetadata.ts +117 -0
  252. package/src/edit/rules/editKeyboard.ts +222 -0
  253. package/src/edit/rules/editShortcuts.ts +102 -0
  254. package/src/edit/rules/editTooltip.ts +174 -0
  255. package/src/edit/rules/editorTaken.ts +49 -0
  256. package/src/edit/rules/history.ts +26 -0
  257. package/src/edit/rules/unsavedWork.ts +60 -0
  258. package/src/edit/stores/editorReservation.ts +70 -0
  259. package/src/edit/stores/formsUnsaved.ts +54 -0
  260. package/src/embed/contracts/embed.ts +48 -0
  261. package/src/embed/engines/embedFraming.ts +1329 -0
  262. package/src/embed/engines/embedReady.ts +353 -0
  263. package/src/embed/engines/framingPageSession.ts +169 -0
  264. package/src/embed/handlers/embed.ts +130 -0
  265. package/src/embed/rules/allowedDomains.ts +71 -0
  266. package/src/embed/rules/bridgeMessages.ts +224 -0
  267. package/src/embed/rules/defaults.ts +173 -0
  268. package/src/embed/rules/displaySeed.ts +115 -0
  269. package/src/embed/rules/embedAllowlist.ts +146 -0
  270. package/src/embed/rules/embedConstraints.ts +215 -0
  271. package/src/embed/rules/embedElements.ts +277 -0
  272. package/src/embed/rules/embedSectionFields.ts +126 -0
  273. package/src/embed/rules/embedSecurity.ts +116 -0
  274. package/src/embed/rules/fieldDependencies.ts +89 -0
  275. package/src/embed/rules/fieldOptions.ts +138 -0
  276. package/src/embed/rules/layerOptions.ts +161 -0
  277. package/src/embed/rules/readyProtocol.ts +66 -0
  278. package/src/embed/rules/safetyRules.ts +215 -0
  279. package/src/embed/rules/snippet.ts +531 -0
  280. package/src/embed/rules/tableCode.ts +270 -0
  281. package/src/embed/stores/embed.ts +60 -0
  282. package/src/embed/stores/embedContent.ts +77 -0
  283. package/src/engines/index.ts +81 -0
  284. package/src/handlers/index.ts +66 -0
  285. package/src/index.ts +1065 -0
  286. package/src/itinerary/contracts/itinerary.ts +705 -0
  287. package/src/itinerary/engines/itineraryPace.ts +612 -0
  288. package/src/itinerary/engines/profileMarker.ts +238 -0
  289. package/src/itinerary/handlers/importStaging.ts +352 -0
  290. package/src/itinerary/handlers/itinerary.ts +572 -0
  291. package/src/itinerary/handlers/itineraryDuplicate.ts +177 -0
  292. package/src/itinerary/handlers/itineraryExport.ts +117 -0
  293. package/src/itinerary/handlers/itineraryImport.ts +783 -0
  294. package/src/itinerary/handlers/itineraryPublish.ts +118 -0
  295. package/src/itinerary/handlers/itinerarySelection.ts +354 -0
  296. package/src/itinerary/handlers/itinerarySuggest.ts +1186 -0
  297. package/src/itinerary/handlers/itineraryUnpublish.ts +101 -0
  298. package/src/itinerary/handlers/publicationScope.ts +118 -0
  299. package/src/itinerary/handlers/restItineraries.ts +752 -0
  300. package/src/itinerary/handlers/restItineraryExport.ts +70 -0
  301. package/src/itinerary/handlers/restItineraryImport.ts +311 -0
  302. package/src/itinerary/handlers/restItineraryPace.ts +87 -0
  303. package/src/itinerary/handlers/restItineraryRecord.ts +36 -0
  304. package/src/itinerary/handlers/suggestParams.ts +379 -0
  305. package/src/itinerary/handlers/suggestStaging.ts +363 -0
  306. package/src/itinerary/handlers/surfaceOpen.ts +389 -0
  307. package/src/itinerary/rules/activity.ts +139 -0
  308. package/src/itinerary/rules/analysis.ts +42 -0
  309. package/src/itinerary/rules/ceiling.ts +49 -0
  310. package/src/itinerary/rules/createFlow.ts +107 -0
  311. package/src/itinerary/rules/densify.ts +440 -0
  312. package/src/itinerary/rules/draftSurface.ts +219 -0
  313. package/src/itinerary/rules/editorView.ts +83 -0
  314. package/src/itinerary/rules/export.ts +159 -0
  315. package/src/itinerary/rules/friendlyName.ts +77 -0
  316. package/src/itinerary/rules/import.ts +1050 -0
  317. package/src/itinerary/rules/importFiles.ts +140 -0
  318. package/src/itinerary/rules/importTotals.ts +77 -0
  319. package/src/itinerary/rules/liveSegment.ts +712 -0
  320. package/src/itinerary/rules/lngLat.ts +17 -0
  321. package/src/itinerary/rules/mapSync.ts +100 -0
  322. package/src/itinerary/rules/previewRender.ts +416 -0
  323. package/src/itinerary/rules/profileReadout.ts +216 -0
  324. package/src/itinerary/rules/routing.ts +707 -0
  325. package/src/itinerary/rules/suggest.ts +522 -0
  326. package/src/itinerary/rules/suggestionPreview.ts +119 -0
  327. package/src/itinerary/rules/view.ts +61 -0
  328. package/src/itinerary/stores/importSession.ts +319 -0
  329. package/src/itinerary/stores/itinerary.ts +331 -0
  330. package/src/itinerary/stores/itineraryDuplicate.ts +76 -0
  331. package/src/itinerary/stores/sessionIdentity.ts +43 -0
  332. package/src/itinerary/stores/suggestSession.ts +418 -0
  333. package/src/layers/contracts/itinerary.ts +46 -0
  334. package/src/layers/contracts/overlay.ts +132 -0
  335. package/src/layers/handlers/enrichment.ts +36 -0
  336. package/src/layers/handlers/overlay.ts +406 -0
  337. package/src/layers/handlers/restLayers.ts +94 -0
  338. package/src/layers/handlers/tiles.ts +25 -0
  339. package/src/layers/rules/layers.ts +212 -0
  340. package/src/layers/rules/overlayInstant.ts +12 -0
  341. package/src/layers/rules/reachabilityIcon.ts +18 -0
  342. package/src/layers/rules/readout.ts +102 -0
  343. package/src/layers/stores/layers.ts +262 -0
  344. package/src/map/contracts/contextmenu.ts +33 -0
  345. package/src/map/contracts/geolocate.ts +37 -0
  346. package/src/map/contracts/map.ts +146 -0
  347. package/src/map/contracts/streetview.ts +53 -0
  348. package/src/map/contracts/terrain.ts +152 -0
  349. package/src/map/handlers/contextMenu.ts +135 -0
  350. package/src/map/handlers/geolocate.ts +52 -0
  351. package/src/map/handlers/map.ts +391 -0
  352. package/src/map/handlers/streetview.ts +94 -0
  353. package/src/map/handlers/terrain.ts +663 -0
  354. package/src/map/rules/baseTerrain.ts +75 -0
  355. package/src/map/rules/clickTargets.ts +464 -0
  356. package/src/map/rules/constraints.ts +32 -0
  357. package/src/map/rules/contextMenuReadout.ts +67 -0
  358. package/src/map/rules/coordinates.ts +71 -0
  359. package/src/map/rules/itineraryFit.ts +8 -0
  360. package/src/map/rules/mapEvents.ts +64 -0
  361. package/src/map/rules/mapProjection.ts +476 -0
  362. package/src/map/rules/terrainReading.ts +62 -0
  363. package/src/plugins/contracts/ids.ts +66 -0
  364. package/src/plugins/contracts/plugin.ts +202 -0
  365. package/src/plugins/contracts/slots.ts +137 -0
  366. package/src/plugins/engines/studioPlugin.ts +1365 -0
  367. package/src/plugins/index.ts +111 -0
  368. package/src/plugins/rules/contributions.ts +152 -0
  369. package/src/plugins/rules/errors.ts +60 -0
  370. package/src/plugins/rules/ids.ts +42 -0
  371. package/src/plugins/rules/validation.ts +249 -0
  372. package/src/rules/listeners.ts +57 -0
  373. package/src/rules/origin.ts +13 -0
  374. package/src/rules/storeWrite.ts +37 -0
  375. package/src/rules/types.ts +136 -0
  376. package/src/seams/index.ts +79 -0
  377. package/src/seams/rules/clock.ts +28 -0
  378. package/src/seams/rules/formatters.ts +211 -0
  379. package/src/seams/rules/ids.ts +102 -0
  380. package/src/seams/rules/links.ts +66 -0
  381. package/src/seams/rules/navigation.ts +222 -0
  382. package/src/seams/rules/notify.ts +49 -0
  383. package/src/seams/rules/persistenceDrawer.ts +220 -0
  384. package/src/seams/rules/saveFile.ts +101 -0
  385. package/src/seams/rules/seams.ts +156 -0
  386. package/src/seams/rules/storage.ts +116 -0
  387. package/src/search/contracts/overlay.ts +74 -0
  388. package/src/search/contracts/search.ts +197 -0
  389. package/src/search/handlers/pois.ts +57 -0
  390. package/src/search/handlers/search.ts +280 -0
  391. package/src/search/rules/params.ts +925 -0
  392. package/src/search/rules/poiGroups.ts +138 -0
  393. package/src/search/rules/searchFetch.ts +139 -0
  394. package/src/search/rules/timeWindow.ts +30 -0
  395. package/src/search/stores/search.ts +51 -0
  396. package/src/segments/contracts/itinerary.ts +433 -0
  397. package/src/segments/contracts/segment.ts +35 -0
  398. package/src/segments/engines/segmentDraft.ts +926 -0
  399. package/src/segments/handlers/chainGuards.ts +67 -0
  400. package/src/segments/handlers/directions.ts +44 -0
  401. package/src/segments/handlers/itineraryEcho.ts +45 -0
  402. package/src/segments/handlers/roadAccessDialog.ts +34 -0
  403. package/src/segments/handlers/segment.ts +111 -0
  404. package/src/segments/handlers/segmentEdit.ts +1341 -0
  405. package/src/segments/handlers/segmentGroups.ts +347 -0
  406. package/src/segments/handlers/segmentStructure.ts +1144 -0
  407. package/src/segments/rules/chain.ts +196 -0
  408. package/src/segments/rules/chainModel.ts +217 -0
  409. package/src/segments/rules/colors.ts +11 -0
  410. package/src/segments/rules/commit.ts +76 -0
  411. package/src/segments/rules/draft.ts +90 -0
  412. package/src/segments/rules/draftDisposition.ts +43 -0
  413. package/src/segments/rules/draftSegmentEdit.ts +129 -0
  414. package/src/segments/rules/engine.ts +222 -0
  415. package/src/segments/rules/groupSave.ts +234 -0
  416. package/src/segments/rules/hazardPrompt.ts +60 -0
  417. package/src/segments/rules/itineraryEcho.ts +40 -0
  418. package/src/segments/rules/liveSegmentProjection.ts +55 -0
  419. package/src/segments/rules/merge.ts +51 -0
  420. package/src/segments/rules/metrics.ts +456 -0
  421. package/src/segments/rules/naming.ts +168 -0
  422. package/src/segments/rules/segmentArming.ts +144 -0
  423. package/src/segments/rules/splitPick.ts +84 -0
  424. package/src/segments/rules/viaSimplify.ts +230 -0
  425. package/src/segments/stores/directions.ts +77 -0
  426. package/src/segments/stores/roadAccessDialog.ts +58 -0
  427. package/src/segments/stores/segmentEdit.ts +922 -0
  428. package/src/segments/stores/segmentGroupEdit.ts +84 -0
  429. package/src/segments/stores/segmentSplit.ts +77 -0
  430. package/src/share/contracts/share.ts +39 -0
  431. package/src/share/contracts/shareLink.ts +63 -0
  432. package/src/share/engines/shareLink.ts +1053 -0
  433. package/src/share/handlers/share.ts +47 -0
  434. package/src/share/handlers/shareLink.ts +231 -0
  435. package/src/share/handlers/shareScope.ts +54 -0
  436. package/src/share/rules/link.ts +89 -0
  437. package/src/share/rules/shareLink.ts +218 -0
  438. package/src/share/rules/targets.ts +92 -0
  439. package/src/share/rules/viewConfig.ts +95 -0
  440. package/src/share/stores/share.ts +58 -0
  441. package/src/strings/fr/index.ts +18 -0
  442. package/src/strings/fr/rules/fr.ts +2368 -0
  443. package/src/strings/index.ts +98 -0
  444. package/src/strings/rules/confirmCopy.ts +156 -0
  445. package/src/strings/rules/draftToolNames.ts +94 -0
  446. package/src/strings/rules/en.ts +2519 -0
  447. package/src/strings/rules/failureAlert.ts +115 -0
  448. package/src/strings/rules/formError.ts +400 -0
  449. package/src/strings/rules/maneuvers.ts +107 -0
  450. package/src/strings/rules/outputOptions.ts +126 -0
  451. package/src/strings/rules/publicationState.ts +100 -0
  452. package/src/strings/rules/routeHazardCopy.ts +62 -0
  453. package/src/strings/rules/searchLabels.ts +50 -0
  454. package/src/strings/rules/segmentChainVerbs.ts +62 -0
  455. package/src/strings/rules/studioCopy.ts +130 -0
  456. package/src/strings/rules/unitOptions.ts +119 -0
  457. package/src/testing/checkedBus.ts +226 -0
  458. package/src/testing/index.ts +30 -0
  459. package/src/testing/plugins.ts +106 -0
  460. package/src/testing/studio.ts +267 -0
  461. package/src/testing/urlSeam.ts +153 -0
  462. package/src/time/index.ts +12 -0
  463. package/src/time/rules/sun.ts +78 -0
  464. package/src/video/contracts/cameraSchemas.ts +266 -0
  465. package/src/video/contracts/profileSchemas.ts +37 -0
  466. package/src/video/contracts/video.ts +601 -0
  467. package/src/video/handlers/video.ts +1638 -0
  468. package/src/video/handlers/videoDirector.ts +114 -0
  469. package/src/video/rules/previewRefresh.ts +76 -0
  470. package/src/video/rules/profileSource.ts +51 -0
  471. package/src/video/rules/routeSpans.ts +79 -0
  472. package/src/video/rules/shotDefaults.ts +28 -0
  473. package/src/video/rules/stepOrder.ts +17 -0
  474. package/src/video/rules/videoSnapshot.ts +136 -0
  475. package/src/video/stores/directorThreads.ts +167 -0
  476. package/src/video/stores/videoExport.ts +290 -0
  477. package/src/viewer/contracts/preferences.ts +40 -0
  478. package/src/viewer/handlers/preferences.ts +91 -0
  479. package/src/viewer/rules/capabilities.ts +42 -0
  480. package/src/viewer/rules/config.ts +266 -0
  481. package/src/viewer/rules/context.ts +375 -0
  482. package/src/viewer/rules/ownership.ts +134 -0
  483. package/src/viewer/rules/platformViewer.ts +199 -0
  484. package/src/viewer/rules/scope.ts +197 -0
  485. package/src/viewer/rules/url.ts +145 -0
  486. package/src/viewer/rules/viewer.ts +307 -0
  487. package/src/viewer/rules/viewerSeam.ts +49 -0
  488. package/src/viewer/rules/viewerUnits.ts +34 -0
  489. package/src/waypoints/contracts/itinerary.ts +417 -0
  490. package/src/waypoints/handlers/poiWaypointStyle.ts +32 -0
  491. package/src/waypoints/handlers/waypointDetailsDialog.ts +38 -0
  492. package/src/waypoints/handlers/waypointEdit.ts +1073 -0
  493. package/src/waypoints/rules/amenities.ts +30 -0
  494. package/src/waypoints/rules/defaults.ts +31 -0
  495. package/src/waypoints/rules/details.ts +213 -0
  496. package/src/waypoints/rules/detailsDraft.ts +312 -0
  497. package/src/waypoints/rules/detailsPreview.ts +76 -0
  498. package/src/waypoints/rules/detailsSave.ts +356 -0
  499. package/src/waypoints/rules/draftDirty.ts +45 -0
  500. package/src/waypoints/rules/icons.ts +32 -0
  501. package/src/waypoints/rules/liveWaypoint.ts +63 -0
  502. package/src/waypoints/rules/naming.ts +185 -0
  503. package/src/waypoints/rules/sections.ts +77 -0
  504. package/src/waypoints/rules/waypointDraft.ts +62 -0
  505. package/src/waypoints/stores/waypointDetails.ts +62 -0
  506. package/src/waypoints/stores/waypointEdit.ts +566 -0
  507. package/src/zones/contracts/collection.ts +37 -0
  508. package/src/zones/contracts/zone.ts +528 -0
  509. package/src/zones/engines/zoneForm.ts +1773 -0
  510. package/src/zones/handlers/restZones.ts +287 -0
  511. package/src/zones/handlers/zonePublish.ts +206 -0
  512. package/src/zones/handlers/zoneUnpublish.ts +56 -0
  513. package/src/zones/handlers/zones.ts +2254 -0
  514. package/src/zones/rules/geometry.ts +946 -0
  515. package/src/zones/rules/zoneDefaults.ts +34 -0
  516. package/src/zones/rules/zoneDraft.ts +54 -0
  517. package/src/zones/rules/zoneForm.ts +563 -0
  518. package/src/zones/rules/zoneMetadata.ts +29 -0
  519. package/src/zones/rules/zoneSource.ts +87 -0
  520. package/src/zones/rules/zoneSourceRefusal.ts +104 -0
  521. package/src/zones/stores/zoneEdit.ts +998 -0
@@ -0,0 +1,1577 @@
1
+ import type { MultiPoint, Position } from "geojson";
2
+
3
+ import type {
4
+ ItinerarySegment,
5
+ ItineraryWaypoint,
6
+ Mountaya,
7
+ SegmentMode,
8
+ WaypointCreateParams,
9
+ WaypointIcon,
10
+ } from "@mountaya/client";
11
+ import { buildGeometryCollection, buildSegmentGeometry } from "@mountaya/elements/geo";
12
+ import { durationForSpeed, resolveSpeedKmh } from "@mountaya/elements/profile";
13
+
14
+ import type { ToolFailure, ToolResult } from "../../bus/rules/types.js";
15
+ import { toDataActivity } from "../../itinerary/rules/activity.js";
16
+ import { densifyFreehandLine, lineLengthMeters } from "../../itinerary/rules/densify.js";
17
+ import {
18
+ holdShowingDraft,
19
+ showingDraft,
20
+ showingDraftSession,
21
+ showingDraftSurface,
22
+ } from "../../itinerary/rules/draftSurface.js";
23
+ import {
24
+ draftToView,
25
+ freehandCandidateOfRoute,
26
+ type ImportCandidate,
27
+ type ItineraryDraft,
28
+ type ItineraryDraftSegment,
29
+ type ItineraryDraftWaypoint,
30
+ } from "../../itinerary/rules/import.js";
31
+ import {
32
+ graphqlAnalysisToEntries,
33
+ graphqlElevationToSummary,
34
+ graphqlRouteToLiveRoute,
35
+ } from "../../itinerary/rules/liveSegment.js";
36
+ import type { WaypointDetailsPatch } from "../../itinerary/stores/itinerary.js";
37
+ import { studioSeamAbsences } from "../../seams/rules/seams.js";
38
+ import { activityForId, defaultSpeedForActivity } from "../../segments/rules/engine.js";
39
+ import { renumberDefaultSegments } from "../../segments/rules/naming.js";
40
+ import type { StudioToolContext } from "../../viewer/rules/context.js";
41
+ import { refuseUngrantedItinerary } from "../../viewer/rules/ownership.js";
42
+ import { invalidateLanded } from "../rules/cache.js";
43
+ import { writeThrough } from "./writeThrough.js";
44
+
45
+ /**
46
+ * SegmentCommitPayload is the validated geometry-commit a `segment.editCommit`
47
+ * hands the sink: the itinerary scope, the authoring mode, the new coordinate
48
+ * window (the directions vias or the freehand line vertices, already range-
49
+ * checked at the bus boundary), the segment id when editing an existing segment
50
+ * (absent for a from-scratch create), the name a from-scratch create carries,
51
+ * and the color a from-scratch create persists (so a new segment keeps the
52
+ * lively hue it was drawn in). The discriminated `mode` is preserved so the sink
53
+ * builds the mode-correct wire geometry (RestSink) or recomputes the mode-correct
54
+ * candidate (DraftSink).
55
+ */
56
+ interface SegmentCommitPayload {
57
+ color?: string | undefined;
58
+ coordinates: Position[];
59
+ /**
60
+ * insertBefore places a from-scratch segment INSIDE the chain rather than at its
61
+ * tail: `segmentId` names the segment the new one lands ahead of, the chain's first
62
+ * for a head insert. Absent for every other commit: an existing-segment reshape and
63
+ * a tail append both leave the chain's shape alone. The tool resolves the "after
64
+ * this row" anchor the gutter holds into this "before that row" wire spelling, so
65
+ * the sink never has to read chain positions itself.
66
+ */
67
+ insertBefore?: { segmentId: string } | undefined;
68
+ itineraryId: string;
69
+ mode: SegmentMode;
70
+ name?: string | undefined;
71
+ segmentId?: string | undefined;
72
+ }
73
+
74
+ /** RenameSegmentPayload is the validated segment rename the sink persists. */
75
+ interface RenameSegmentPayload {
76
+ itineraryId: string;
77
+ name: string;
78
+ segmentId: string;
79
+ }
80
+
81
+ /** RecolorSegmentPayload is the validated segment recolor the sink persists. */
82
+ interface RecolorSegmentPayload {
83
+ color: string;
84
+ itineraryId: string;
85
+ segmentId: string;
86
+ }
87
+
88
+ /** RemoveSegmentPayload is the validated segment delete the sink persists. */
89
+ interface RemoveSegmentPayload {
90
+ itineraryId: string;
91
+ segmentId: string;
92
+ }
93
+
94
+ /**
95
+ * SetSegmentSpeedPayload is the validated segment speed edit the sink persists:
96
+ * the itinerary scope, the segment, and the new speed in km/h (null clears it back
97
+ * to the activity default). The wire value is always km/h: the speed control
98
+ * converts on the way in.
99
+ */
100
+ interface SetSegmentSpeedPayload {
101
+ itineraryId: string;
102
+ segmentId: string;
103
+ speed: number | null;
104
+ }
105
+
106
+ /**
107
+ * WaypointCommitPayload is the validated waypoint-draft commit the sink writes:
108
+ * the itinerary scope, the waypoint id the session is keyed on, the persist
109
+ * intent (POST on create, PUT on update), the resolved Point geometry, the
110
+ * persisted `mode` (a `poi-pick` engine becomes a `poi` waypoint, a point drop a
111
+ * `point` waypoint), and the draft's display attributes. The tool resolves all
112
+ * of this from the active waypoint session before handing it to the sink, so the
113
+ * sink never reads the session itself.
114
+ */
115
+ export interface WaypointCommitPayload {
116
+ color: string;
117
+ geojson: { coordinates: Position; type: "Point" };
118
+ icon: WaypointIcon;
119
+ intent: "create" | "update";
120
+ itineraryId: string;
121
+ mode: "point" | "poi";
122
+ name: string;
123
+ waypointId: string;
124
+ }
125
+
126
+ /**
127
+ * RenameWaypointPayload is the validated waypoint rename the sink persists. A null `name` is the
128
+ * clear, which puts a point back on its automatic name.
129
+ */
130
+ interface RenameWaypointPayload {
131
+ itineraryId: string;
132
+ name: string | null;
133
+ waypointId: string;
134
+ }
135
+
136
+ /** RecolorWaypointPayload is the validated waypoint recolor the sink persists. */
137
+ interface RecolorWaypointPayload {
138
+ color: string;
139
+ itineraryId: string;
140
+ waypointId: string;
141
+ }
142
+
143
+ /**
144
+ * SetWaypointDetailsPayload is the validated waypoint enrichment the sink persists.
145
+ *
146
+ * A PARTIAL patch: a key absent from `details` is left alone, a key present replaces its stored
147
+ * value wholesale, and an explicit null clears it. The three states are the wire's own, so the
148
+ * patch is forwarded rather than reshaped.
149
+ */
150
+ interface SetWaypointDetailsPayload {
151
+ details: WaypointDetailsPatch;
152
+ itineraryId: string;
153
+ waypointId: string;
154
+ }
155
+
156
+ /** SetWaypointIconPayload is the validated waypoint icon change the sink persists. */
157
+ interface SetWaypointIconPayload {
158
+ icon: WaypointIcon;
159
+ itineraryId: string;
160
+ waypointId: string;
161
+ }
162
+
163
+ /** RemoveWaypointPayload is the validated waypoint delete the sink persists. */
164
+ interface RemoveWaypointPayload {
165
+ itineraryId: string;
166
+ waypointId: string;
167
+ }
168
+
169
+ /** RenameItineraryPayload is the validated itinerary rename the sink persists. */
170
+ interface RenameItineraryPayload {
171
+ itineraryId: string;
172
+ name: string;
173
+ }
174
+
175
+ /**
176
+ * SinkResult is what every method of a sink answers: a summary and no data, or a refusal. It is
177
+ * the answer of a verb that states no data, so a handler of one returns it as it comes, and a
178
+ * handler of a verb that states data builds its own answer from it.
179
+ */
180
+ type SinkResult = ToolResult<undefined>;
181
+
182
+ /**
183
+ * createdSegments holds the segment a sink's commit created, as the API answered it or as the
184
+ * staged draft holds it, by the answer that commit gave.
185
+ */
186
+ const createdSegments = new WeakMap<SinkResult, ItinerarySegment>();
187
+
188
+ /**
189
+ * createdWaypoints holds the waypoint a sink's commit created, as the API answered it or as the
190
+ * staged draft holds it, by the answer that commit gave.
191
+ */
192
+ const createdWaypoints = new WeakMap<SinkResult, ItineraryWaypoint>();
193
+
194
+ /**
195
+ * sinkCreatedSegment reads the segment that a sink's commit created: as the API saved it, or,
196
+ * for an append onto a staged draft, as the draft holds it. It answers null when the commit
197
+ * created none: it saved a segment that existed, it was refused, it updated a segment of a
198
+ * draft, or the answer does not hold what it created.
199
+ *
200
+ * A session that draws a segment from scratch is keyed on an id the client minted, which
201
+ * neither the API nor the draft sink keeps: the created segment answers to another. This is
202
+ * where a handler learns that one, to go on editing what it has just created.
203
+ *
204
+ * It is read beside the answer and is no member of it. A commit answers a summary and no data,
205
+ * as every method of a sink does, so the handler of a verb that states no data returns the
206
+ * answer as it comes.
207
+ *
208
+ * @param committed - The answer of `commitSegment`, as the sink returned it: the object is what
209
+ * the segment is held by, so a copy names nothing.
210
+ */
211
+ export const sinkCreatedSegment = (committed: SinkResult): ItinerarySegment | null =>
212
+ createdSegments.get(committed) ?? null;
213
+
214
+ /**
215
+ * sinkCreatedWaypoint reads the waypoint that a sink's commit created: as the API saved it, or,
216
+ * for a create onto a staged draft, as the draft holds it. It answers null when the commit created
217
+ * none, as {@link sinkCreatedSegment} does for a segment.
218
+ *
219
+ * @param committed - The answer of `commitWaypoint`, as the sink returned it: the object is what
220
+ * the waypoint is held by, so a copy names nothing.
221
+ */
222
+ export const sinkCreatedWaypoint = (committed: SinkResult): ItineraryWaypoint | null =>
223
+ createdWaypoints.get(committed) ?? null;
224
+
225
+ /**
226
+ * createdAs records `entity` in `created` as what the commit that answered `committed` created,
227
+ * and hands the answer back. A refusal created nothing, and a null entity names nothing, so
228
+ * neither is recorded.
229
+ */
230
+ const createdAs = <Entity extends object>(
231
+ created: WeakMap<SinkResult, Entity>,
232
+ committed: SinkResult,
233
+ entity: Entity | null,
234
+ ): SinkResult => {
235
+ if (committed.ok && entity !== null) {
236
+ created.set(committed, entity);
237
+ }
238
+
239
+ return committed;
240
+ };
241
+
242
+ /**
243
+ * MutationSink is the write surface the editor mutation tools route through: one
244
+ * method per editor mutation, each taking the tool's already-validated payload
245
+ * and returning the same normalized ToolResult the tool returns. Two
246
+ * implementations satisfy it: RestSink (the persisted itinerary, written through
247
+ * to the backend) and DraftSink (the staged draft of an import or a suggestion,
248
+ * written in memory, its geometry recomputed through the Data API, persisted
249
+ * nowhere), so the SAME tools serve a persisted edit and a draft edit. The tool
250
+ * keeps the validation, capability gate, and any map/session teardown; only the
251
+ * persistence side lives behind this interface.
252
+ */
253
+ interface MutationSink {
254
+ commitSegment: (ctx: StudioToolContext, payload: SegmentCommitPayload) => Promise<SinkResult>;
255
+ commitWaypoint: (ctx: StudioToolContext, payload: WaypointCommitPayload) => Promise<SinkResult>;
256
+ recolorSegment: (ctx: StudioToolContext, payload: RecolorSegmentPayload) => Promise<SinkResult>;
257
+ recolorWaypoint: (ctx: StudioToolContext, payload: RecolorWaypointPayload) => Promise<SinkResult>;
258
+ setWaypointDetails: (
259
+ ctx: StudioToolContext,
260
+ payload: SetWaypointDetailsPayload,
261
+ ) => Promise<SinkResult>;
262
+ removeSegment: (ctx: StudioToolContext, payload: RemoveSegmentPayload) => Promise<SinkResult>;
263
+ removeWaypoint: (ctx: StudioToolContext, payload: RemoveWaypointPayload) => Promise<SinkResult>;
264
+ renameItinerary: (ctx: StudioToolContext, payload: RenameItineraryPayload) => Promise<SinkResult>;
265
+ renameSegment: (ctx: StudioToolContext, payload: RenameSegmentPayload) => Promise<SinkResult>;
266
+ renameWaypoint: (ctx: StudioToolContext, payload: RenameWaypointPayload) => Promise<SinkResult>;
267
+ setSegmentSpeed: (ctx: StudioToolContext, payload: SetSegmentSpeedPayload) => Promise<SinkResult>;
268
+ setWaypointIcon: (ctx: StudioToolContext, payload: SetWaypointIconPayload) => Promise<SinkResult>;
269
+ }
270
+
271
+ /**
272
+ * blankNameWrite answers what a name left blank writes on a saved waypoint's update, by the mode
273
+ * the waypoint is saved under.
274
+ *
275
+ * A point may be unnamed, so the blank clears its name: `null`, the wire's own clear. A point of
276
+ * interest is never unnamed, and the API refuses a clear of its name, so the name is left out of
277
+ * the write (`undefined`) and the saved one stays. A waypoint whose mode is not known is treated
278
+ * as the one that cannot be cleared.
279
+ */
280
+ const blankNameWrite = (mode: ItineraryDraftWaypoint["mode"] | undefined): null | undefined =>
281
+ mode === "point" ? null : undefined;
282
+
283
+ /**
284
+ * nameClearRefused is the refusal a rename to null answers for a point of interest: the bus's
285
+ * `invalid-input`, the code the API's own refusal of that clear is read as.
286
+ *
287
+ * An edit session's commit leaves a blank name of a point of interest out of its write
288
+ * ({@link blankNameWrite}), since the other fields of that write still land. A rename writes the
289
+ * name and nothing else, so one that wrote nothing would answer that it had cleared the name.
290
+ */
291
+ const nameClearRefused = (): ToolFailure => ({
292
+ code: "invalid-input",
293
+ error:
294
+ "rename waypoint: a point of interest is never unnamed, so its name cannot be cleared; " +
295
+ "pass a name of 2 to 30 characters",
296
+ ok: false,
297
+ });
298
+
299
+ /**
300
+ * restSink is the persisted itinerary write surface: a write-through (optimistic store patch,
301
+ * REST mutation, cache eviction) for a geometry commit, a REST call and a store patch for the
302
+ * rename family, and a delete with its eviction for the remove family. With no staged draft
303
+ * showing, resolveMutationSink answers this sink.
304
+ *
305
+ * Every write it sends on the open itinerary is refused with `forbidden` first for a reader who
306
+ * holds no write grant on it (`refuseUngrantedItinerary`), the write-through's own and the
307
+ * renames' alike.
308
+ */
309
+ export const restSink: MutationSink = {
310
+ /**
311
+ * commitSegment persists the segment geometry draft: updateGeometry when a
312
+ * segmentId is present (an existing segment), and create otherwise: ahead of the
313
+ * anchored segment when the draft was opened from a gutter between two rows, and
314
+ * appended at the tail for a from-scratch segment, which carries a name. All three run
315
+ * the same write-through so the conflict/cascade handling is identical: the
316
+ * backend re-routes the edited segment and its neighbours, knowable only on the
317
+ * refetch, so no branch patches optimistically. The map/session teardown stays in
318
+ * the tool. The segment an insert or a create made is read through
319
+ * {@link sinkCreatedSegment}.
320
+ */
321
+ commitSegment: async (ctx, payload) => {
322
+ const geojson = buildSegmentGeometry(payload.mode, payload.coordinates);
323
+ const { insertBefore, name, segmentId } = payload;
324
+
325
+ if (segmentId) {
326
+ return writeThrough(ctx, {
327
+ itineraryId: payload.itineraryId,
328
+ optimistic: () => {},
329
+ persist: (api) =>
330
+ api.persistence.updateSegment(payload.itineraryId, segmentId, { geojson }),
331
+ skipTileRefresh: true,
332
+ summary: () => `Saved segment ${segmentId}.`,
333
+ });
334
+ }
335
+
336
+ // A new segment is created under the name its commit carries, and the API takes none
337
+ // without one, so a commit that names nothing is refused before a request is built.
338
+ if (name === undefined) {
339
+ return {
340
+ code: "invalid-input",
341
+ error: "commit segment edit: a new segment needs a name",
342
+ ok: false,
343
+ };
344
+ }
345
+
346
+ // The segment the write creates, which sinkCreatedSegment answers.
347
+ let created: ItinerarySegment | null = null;
348
+
349
+ // A draw opened from a gutter lands INSIDE the chain, so the create names the segment it
350
+ // lands before: the chain renumbers and both adjoining boundaries are recomputed
351
+ // server-side, which an append does not do.
352
+ return createdAs(
353
+ createdSegments,
354
+ await writeThrough(ctx, {
355
+ itineraryId: payload.itineraryId,
356
+ optimistic: () => {},
357
+ persist: async (api) => {
358
+ const segment = await api.persistence.createSegment(payload.itineraryId, {
359
+ ...(insertBefore ? { before_segment_id: insertBefore.segmentId } : {}),
360
+ color: payload.color,
361
+ geojson,
362
+ mode: payload.mode,
363
+ name,
364
+ });
365
+ created = segment;
366
+
367
+ return segment;
368
+ },
369
+ skipTileRefresh: true,
370
+ summary: (segment) =>
371
+ insertBefore ? `Inserted segment “${segment.name}”.` : `Saved segment “${segment.name}”.`,
372
+ }),
373
+ created,
374
+ );
375
+ },
376
+
377
+ /**
378
+ * commitWaypoint persists the active waypoint draft (POST on create, PUT on
379
+ * update). The wire shape is the WaypointCreateParams / WaypointUpdateParams
380
+ * the backend expects: the draft's geojson Point, name, icon, and color, plus
381
+ * the itinerary and waypoint ids the session is keyed on. The pre-session POI
382
+ * view restore + engine teardown stay in the tool.
383
+ *
384
+ * A name left blank on an update follows {@link blankNameWrite}, the rule the draft sink
385
+ * follows too: it clears the name of a saved point and is left out of the write for a point
386
+ * of interest. The saved waypoint's mode is read from the open itinerary, and a waypoint not
387
+ * found there keeps its name. A create sends a blank name as none, and the waypoint the API
388
+ * answers it with is read through {@link sinkCreatedWaypoint}.
389
+ */
390
+ commitWaypoint: async (ctx, payload) => {
391
+ const blank = payload.name.trim() === "";
392
+ const saved = ctx.ui
393
+ .getState()
394
+ .activeItinerary?.waypoints.find((waypoint) => waypoint.id === payload.waypointId);
395
+
396
+ // The waypoint a create makes, which sinkCreatedWaypoint answers.
397
+ let created: ItineraryWaypoint | null = null;
398
+
399
+ return createdAs(
400
+ createdWaypoints,
401
+ await writeThrough(ctx, {
402
+ itineraryId: payload.itineraryId,
403
+ optimistic: () => {},
404
+ persist: async (api) => {
405
+ if (payload.intent === "update") {
406
+ return api.persistence.updateWaypoint(payload.itineraryId, payload.waypointId, {
407
+ color: payload.color,
408
+ geojson: payload.geojson,
409
+ icon: payload.icon,
410
+ name: blank ? blankNameWrite(saved?.mode) : payload.name,
411
+ });
412
+ }
413
+
414
+ const params: WaypointCreateParams = {
415
+ color: payload.color,
416
+ geojson: payload.geojson,
417
+ icon: payload.icon,
418
+ mode: payload.mode,
419
+ name: blank ? undefined : payload.name,
420
+ position: 0,
421
+ };
422
+ const waypoint = await api.persistence.createWaypoint(payload.itineraryId, params);
423
+ created = waypoint;
424
+
425
+ return waypoint;
426
+ },
427
+ skipTileRefresh: true,
428
+ summary: (waypoint) =>
429
+ `Saved waypoint${waypoint.name ? ` “${waypoint.name}”` : ` ${waypoint.id}`}.`,
430
+ }),
431
+ created,
432
+ );
433
+ },
434
+
435
+ /**
436
+ * recolorSegment persists a new color, writing through to the backend. The
437
+ * optimistic patch recolors the segment in the open itinerary so the change
438
+ * shows on the tile render after the refetch. The mid-edit setSegmentDraftStyle
439
+ * (the live editing render of the segment under edit) stays in the tool, since
440
+ * it drives the map, not persistence.
441
+ */
442
+ recolorSegment: (ctx, payload) =>
443
+ writeThrough(ctx, {
444
+ itineraryId: payload.itineraryId,
445
+ optimistic: () => ctx.ui.getState().recolorSegment(payload.segmentId, payload.color),
446
+ persist: (api) =>
447
+ api.persistence.updateSegment(payload.itineraryId, payload.segmentId, {
448
+ color: payload.color,
449
+ }),
450
+ summary: () => `Recolored segment ${payload.segmentId}.`,
451
+ }),
452
+
453
+ /**
454
+ * recolorWaypoint persists a new color for a saved waypoint, writing through to
455
+ * the backend. The optimistic patch recolors it in the open itinerary so the
456
+ * sidenav row + (on the next tile refetch) the on-map sprite pick up the change.
457
+ */
458
+ recolorWaypoint: (ctx, payload) =>
459
+ writeThrough(ctx, {
460
+ itineraryId: payload.itineraryId,
461
+ optimistic: () => ctx.ui.getState().recolorWaypoint(payload.waypointId, payload.color),
462
+ persist: (api) =>
463
+ api.persistence.updateWaypoint(payload.itineraryId, payload.waypointId, {
464
+ color: payload.color,
465
+ }),
466
+ summary: () => `Recolored waypoint ${payload.waypointId}.`,
467
+ }),
468
+
469
+ /**
470
+ * removeSegment deletes a segment from its itinerary, writing through to the backend.
471
+ * Deletion is server-enforced ends-only (the first or the last segment); the optimistic patch
472
+ * drops the segment and renumbers every sibling still carrying the auto-assigned `Segment #N`
473
+ * label so the position numbers stay continuous (customised names survive). The refetch
474
+ * reconciles, restoring the segment if the server rejected the delete.
475
+ */
476
+ removeSegment: (ctx, payload) =>
477
+ writeThrough(ctx, {
478
+ conflictSummary:
479
+ "The itinerary changed since this delete started. Reloaded the latest version; try again.",
480
+ itineraryId: payload.itineraryId,
481
+ optimistic: () => {
482
+ const state = ctx.ui.getState();
483
+ state.removeSegment(payload.segmentId);
484
+ const itinerary = ctx.ui.getState().activeItinerary;
485
+ if (!itinerary) {
486
+ return;
487
+ }
488
+
489
+ const renumbered = renumberDefaultSegments(itinerary.segments);
490
+
491
+ const changed = renumbered.some((segment, index) => segment !== itinerary.segments[index]);
492
+ if (!changed) {
493
+ return;
494
+ }
495
+
496
+ state.setActiveItinerary({ ...itinerary, segments: renumbered });
497
+ },
498
+ persist: (api) => api.persistence.deleteSegment(payload.itineraryId, payload.segmentId),
499
+ summary: () => `Deleted segment ${payload.segmentId}.`,
500
+ }),
501
+
502
+ /**
503
+ * removeWaypoint deletes a waypoint from its itinerary, writing through to the
504
+ * backend. Waypoints are standalone POIs (not part of the append-only chain),
505
+ * so any waypoint may be deleted; the optimistic patch drops it from the open
506
+ * itinerary immediately and the refetch reconciles.
507
+ */
508
+ removeWaypoint: (ctx, payload) =>
509
+ writeThrough(ctx, {
510
+ itineraryId: payload.itineraryId,
511
+ optimistic: () => ctx.ui.getState().removeWaypoint(payload.waypointId),
512
+ persist: (api) => api.persistence.deleteWaypoint(payload.itineraryId, payload.waypointId),
513
+ summary: () => `Deleted waypoint ${payload.waypointId}.`,
514
+ }),
515
+
516
+ /**
517
+ * renameItinerary persists a new display name, then evicts every itinerary
518
+ * listing so the sidenav re-reads the renamed entry. When the renamed itinerary is
519
+ * the one open in the editor it also patches the active slot's name so the open
520
+ * editor updates instantly. The api seam must be wired: without one it answers a
521
+ * failure rather than silently dropping the write. The eviction follows a rename that has
522
+ * landed, here and in the renames below, so a cache that fails it fails nothing
523
+ * ({@link invalidateLanded}).
524
+ */
525
+ renameItinerary: async (ctx, payload) => {
526
+ if (!ctx.api) {
527
+ return { code: "no-api", error: "rename itinerary: no persistence seam", ok: false };
528
+ }
529
+
530
+ const ungranted = refuseUngrantedItinerary(ctx, payload.itineraryId);
531
+ if (ungranted) {
532
+ return ungranted;
533
+ }
534
+
535
+ await ctx.api.persistence.updateItinerary(payload.itineraryId, { name: payload.name });
536
+
537
+ if (ctx.ui.getState().activeItinerary?.id === payload.itineraryId) {
538
+ ctx.ui.getState().renameActiveItinerary(payload.name);
539
+ }
540
+
541
+ await invalidateLanded(ctx.api.cache, { kind: "itineraries" });
542
+
543
+ return { ok: true, summary: `Renamed itinerary to “${payload.name}”.` };
544
+ },
545
+
546
+ /**
547
+ * renameSegment persists a new display name, then evicts that itinerary's detail
548
+ * cache so a reopen re-reads the renamed segment. When that itinerary is open in
549
+ * the editor it also patches the matching segment's name in the active slot. The
550
+ * groups cache is left untouched (the segment name shows only in the detail).
551
+ */
552
+ renameSegment: async (ctx, payload) => {
553
+ if (!ctx.api) {
554
+ return { code: "no-api", error: "rename segment: no persistence seam", ok: false };
555
+ }
556
+
557
+ const ungranted = refuseUngrantedItinerary(ctx, payload.itineraryId);
558
+ if (ungranted) {
559
+ return ungranted;
560
+ }
561
+
562
+ await ctx.api.persistence.updateSegment(payload.itineraryId, payload.segmentId, {
563
+ name: payload.name,
564
+ });
565
+
566
+ if (ctx.ui.getState().activeItinerary?.id === payload.itineraryId) {
567
+ ctx.ui.getState().renameSegment(payload.segmentId, payload.name);
568
+ }
569
+
570
+ await invalidateLanded(ctx.api.cache, { id: payload.itineraryId, kind: "itinerary" });
571
+
572
+ return { ok: true, summary: `Renamed segment to “${payload.name}”.` };
573
+ },
574
+
575
+ /**
576
+ * renameWaypoint persists a new display name, then evicts that itinerary's
577
+ * detail cache so a reopen re-reads the renamed waypoint. When that itinerary is
578
+ * open in the editor it also patches the matching waypoint's name in the active
579
+ * slot. The groups cache is left untouched (the waypoint name shows only in the
580
+ * detail and on the map sprite).
581
+ *
582
+ * A null name is sent as the wire's own clear, which puts a point back on its automatic name.
583
+ * A point of interest the open itinerary holds is refused ahead of the request
584
+ * ({@link nameClearRefused}). The store holds no mode for a waypoint of an itinerary that is
585
+ * not the one open, so the clear of one is sent and the API judges it.
586
+ */
587
+ renameWaypoint: async (ctx, payload) => {
588
+ if (!ctx.api) {
589
+ return { code: "no-api", error: "rename waypoint: no persistence seam", ok: false };
590
+ }
591
+
592
+ const ungranted = refuseUngrantedItinerary(ctx, payload.itineraryId);
593
+ if (ungranted) {
594
+ return ungranted;
595
+ }
596
+
597
+ const open = ctx.ui.getState().activeItinerary;
598
+ const saved =
599
+ open?.id === payload.itineraryId
600
+ ? open.waypoints.find((waypoint) => waypoint.id === payload.waypointId)
601
+ : undefined;
602
+ if (payload.name === null && saved?.mode === "poi") {
603
+ return nameClearRefused();
604
+ }
605
+
606
+ await ctx.api.persistence.updateWaypoint(payload.itineraryId, payload.waypointId, {
607
+ name: payload.name,
608
+ });
609
+
610
+ if (ctx.ui.getState().activeItinerary?.id === payload.itineraryId) {
611
+ ctx.ui.getState().renameWaypoint(payload.waypointId, payload.name);
612
+ }
613
+
614
+ await invalidateLanded(ctx.api.cache, { id: payload.itineraryId, kind: "itinerary" });
615
+
616
+ return {
617
+ ok: true,
618
+ summary:
619
+ payload.name === null
620
+ ? `Cleared the name of waypoint ${payload.waypointId}.`
621
+ : `Renamed waypoint to “${payload.name}”.`,
622
+ };
623
+ },
624
+
625
+ /**
626
+ * setSegmentSpeed persists a new travel speed (km/h, null = the activity
627
+ * default) for one segment, writing through to the backend. It patches the new
628
+ * speed AND a rescaled duration optimistically: a speed change rescales the
629
+ * duration for a fixed geometry (`duration ∝ 1/speed`), so the local estimate
630
+ * (durationForSpeed off the resolved speeds) lets the elevation profile + the
631
+ * duration stat update live. Because the client default speed equals the
632
+ * backend's, the estimate matches the server recompute, and the write-through
633
+ * refetch reconciles it regardless (rolling it back on a failed write).
634
+ */
635
+ setSegmentSpeed: (ctx, payload) =>
636
+ writeThrough(ctx, {
637
+ itineraryId: payload.itineraryId,
638
+ // Patch the new speed and a rescaled duration so the profile/stat move
639
+ // immediately; the refetch reconciles with the server's recompute (values
640
+ // match), and a failed write rolls both fields back.
641
+ optimistic: () => {
642
+ const state = ctx.ui.getState();
643
+ const itinerary = state.activeItinerary;
644
+ const segment = itinerary?.segments.find((candidate) => candidate.id === payload.segmentId);
645
+ if (!itinerary || !segment) {
646
+ return;
647
+ }
648
+
649
+ const activityDefault = resolveActivityDefaultSpeed(ctx, itinerary.activity_id);
650
+ const duration = durationForSpeed({
651
+ baseDurationSeconds: segment.duration,
652
+ baseSpeedKmh: resolveSpeedKmh(segment.speed, activityDefault),
653
+ distanceMeters: segment.distance,
654
+ targetSpeedKmh: resolveSpeedKmh(payload.speed, activityDefault),
655
+ });
656
+
657
+ state.setSegmentSpeed(payload.segmentId, payload.speed, duration);
658
+ },
659
+ persist: (api) =>
660
+ api.persistence.updateSegment(payload.itineraryId, payload.segmentId, {
661
+ speed: payload.speed,
662
+ }),
663
+ summary: () =>
664
+ payload.speed === null
665
+ ? `Cleared segment ${payload.segmentId} speed.`
666
+ : `Set segment ${payload.segmentId} speed to ${payload.speed} km/h.`,
667
+ }),
668
+
669
+ /**
670
+ * setWaypointDetails persists what a waypoint says about the place it marks, writing through
671
+ * to the backend. The optimistic patch updates it in the open itinerary so the sidenav row
672
+ * and the profile's badges pick up the change instantly.
673
+ *
674
+ * The patch is forwarded to the REST layer unreshaped: `updateWaypoint` takes the same
675
+ * three-state fields the wire does, so translating them here would be one more place for
676
+ * "absent" and "explicitly null" to be confused.
677
+ */
678
+ setWaypointDetails: (ctx, payload) =>
679
+ writeThrough(ctx, {
680
+ itineraryId: payload.itineraryId,
681
+ optimistic: () => ctx.ui.getState().setWaypointDetails(payload.waypointId, payload.details),
682
+ persist: (api) =>
683
+ api.persistence.updateWaypoint(payload.itineraryId, payload.waypointId, payload.details),
684
+ summary: () => `Updated the details of waypoint ${payload.waypointId}.`,
685
+ }),
686
+
687
+ /**
688
+ * setWaypointIcon persists a new icon for a saved waypoint, writing through to
689
+ * the backend. The optimistic patch updates it in the open itinerary so the
690
+ * sidenav row + (on the next tile refetch) the on-map sprite pick up the change.
691
+ */
692
+ setWaypointIcon: (ctx, payload) =>
693
+ writeThrough(ctx, {
694
+ itineraryId: payload.itineraryId,
695
+ optimistic: () => ctx.ui.getState().setWaypointIcon(payload.waypointId, payload.icon),
696
+ persist: (api) =>
697
+ api.persistence.updateWaypoint(payload.itineraryId, payload.waypointId, {
698
+ icon: payload.icon,
699
+ }),
700
+ summary: () => `Set waypoint ${payload.waypointId} icon.`,
701
+ }),
702
+ };
703
+
704
+ /**
705
+ * requireDraft reads the draft that answers for the editor ({@link showingDraft}: the import's
706
+ * or the suggestion's, while its surface shows) for a draft mutation to clone and replace. It
707
+ * answers null when none does. A draft sink method is not reached then, since the resolver hands
708
+ * the draft sink back only while a draft answers, so each method answers a structured failure on
709
+ * the null branch as a floor.
710
+ */
711
+ const requireDraft = (ctx: StudioToolContext): ItineraryDraft | null =>
712
+ showingDraft(ctx.ui.getState());
713
+
714
+ /**
715
+ * activeDraftId reads the identity of the working copy that answers for the editor, or null
716
+ * when no draft does.
717
+ *
718
+ * A draft has no identity of its own: its ids are positions, and every edit replaces the object.
719
+ * The session names its working copy instead (`draftId`, minted as a draft is staged and kept
720
+ * across every edit of it), so two reads that answer the same identity are one working copy,
721
+ * whichever writer edited it in between and however many of its entities were replaced. A draft
722
+ * staged since (a second import, a preview read again, another suggestion) answers another, and
723
+ * so does the other session's draft once its surface shows in place of this one's.
724
+ */
725
+ const activeDraftId = (ctx: StudioToolContext): number | null =>
726
+ showingDraftSession(ctx.ui.getState())?.draftId ?? null;
727
+
728
+ /**
729
+ * writeDraft replaces the draft that answers for the editor with `next`, a draft after one edit,
730
+ * through the setter of the session whose surface shows, which keeps the draft's identity.
731
+ *
732
+ * The session is named by the surface and never by which one holds a draft, so a write lands on
733
+ * the draft the reader sees whatever the other session holds. With no draft answering it writes
734
+ * nothing.
735
+ */
736
+ const writeDraft = (ctx: StudioToolContext, next: ItineraryDraft): void => {
737
+ const state = ctx.ui.getState();
738
+ if (showingDraftSession(state) === null) {
739
+ return;
740
+ }
741
+
742
+ if (showingDraftSurface(state) === "import") {
743
+ state.setImportDraft(next);
744
+ } else {
745
+ state.setSuggestDraft(next);
746
+ }
747
+ };
748
+
749
+ /**
750
+ * mapDraftSegment returns a new draft with one segment replaced by the projection
751
+ * of `update` over the matched segment (by client id), writing the result back
752
+ * through {@link writeDraft}. The draft is plain data with no per-field store action,
753
+ * so a draft edit is a clone-and-replace of the whole draft, the same stance the
754
+ * store's draft setter contract takes (the editor mutates a working copy). It returns
755
+ * whether a segment matched, so a caller can fail an edit that targets a segment not
756
+ * in the draft.
757
+ */
758
+ const mapDraftSegment = (
759
+ ctx: StudioToolContext,
760
+ draft: ItineraryDraft,
761
+ segmentId: string,
762
+ update: (segment: ItineraryDraftSegment) => ItineraryDraftSegment,
763
+ ): boolean => {
764
+ let matched = false;
765
+ const segments = draft.segments.map((segment) => {
766
+ if (segment.id !== segmentId) {
767
+ return segment;
768
+ }
769
+
770
+ matched = true;
771
+
772
+ return update(segment);
773
+ });
774
+
775
+ if (matched) {
776
+ writeDraft(ctx, { ...draft, segments });
777
+ }
778
+
779
+ return matched;
780
+ };
781
+
782
+ /**
783
+ * mapDraftWaypoint mirrors mapDraftSegment for a draft waypoint: it replaces the
784
+ * waypoint matched by client id with `update`'s projection and writes the new
785
+ * draft back through {@link writeDraft}, returning whether a waypoint matched.
786
+ */
787
+ const mapDraftWaypoint = (
788
+ ctx: StudioToolContext,
789
+ draft: ItineraryDraft,
790
+ waypointId: string,
791
+ update: (waypoint: ItineraryDraft["waypoints"][number]) => ItineraryDraft["waypoints"][number],
792
+ ): boolean => {
793
+ let matched = false;
794
+ const waypoints = draft.waypoints.map((waypoint) => {
795
+ if (waypoint.id !== waypointId) {
796
+ return waypoint;
797
+ }
798
+
799
+ matched = true;
800
+
801
+ return update(waypoint);
802
+ });
803
+
804
+ if (matched) {
805
+ writeDraft(ctx, { ...draft, waypoints });
806
+ }
807
+
808
+ return matched;
809
+ };
810
+
811
+ /**
812
+ * notInDraft is the refusal a draft verb answers for an entity the draft does not hold: the
813
+ * bus's `not-found`, with the verb and the id in the narration.
814
+ */
815
+ const notInDraft = (verb: string, kind: "segment" | "waypoint", id: string): ToolFailure => ({
816
+ code: "not-found",
817
+ error: `${verb}: ${kind} ${id} not in the staged draft`,
818
+ ok: false,
819
+ });
820
+
821
+ /**
822
+ * resolveDraftActivitySlug resolves the REST activity slug a draft's geometry
823
+ * recompute routes/analyzes for: the draft carries only the immutable activity
824
+ * id, so it is mapped through the activity catalog the useActivities cache holds
825
+ * (the same resolution segmentEditPropose does). Returns null when the catalog is
826
+ * absent or the activity is unknown, in which case a geometry recompute cannot be
827
+ * attempted and the commit fails with a structured error.
828
+ */
829
+ const resolveDraftActivitySlug = (
830
+ ctx: StudioToolContext,
831
+ activityId: string | null,
832
+ ): string | null => {
833
+ if (!activityId) {
834
+ return null;
835
+ }
836
+
837
+ const categories = ctx.api?.cache.get({ kind: "activities" });
838
+
839
+ return categories ? (activityForId(categories, activityId)?.slug ?? null) : null;
840
+ };
841
+
842
+ /**
843
+ * resolveActivityDefaultSpeed reads the activity's default travel speed (km/h)
844
+ * from the catalog cache, mirroring resolveDraftActivitySlug. Null when the
845
+ * catalog has not loaded or the activity is unknown.
846
+ */
847
+ const resolveActivityDefaultSpeed = (
848
+ ctx: StudioToolContext,
849
+ activityId: string | null,
850
+ ): number | null => {
851
+ if (!activityId) {
852
+ return null;
853
+ }
854
+
855
+ const categories = ctx.api?.cache.get({ kind: "activities" });
856
+ const activity = categories ? activityForId(categories, activityId) : null;
857
+
858
+ return defaultSpeedForActivity(activity?.capabilities ?? null);
859
+ };
860
+
861
+ /**
862
+ * routedDraftCandidate reads the route a directions commit of a draft segment asks for, and
863
+ * answers the candidate the draft stores for it, or the commit's refusal: `not-found` where the
864
+ * router finds no route between the points, and `internal` where the route answered is no line.
865
+ *
866
+ * @param client - The client the Data API is read through.
867
+ * @param slug - The REST slug of the draft's activity.
868
+ * @param waypoints - The committed vias, as [lng, lat] pairs.
869
+ */
870
+ const routedDraftCandidate = async (
871
+ client: Mountaya,
872
+ slug: string,
873
+ waypoints: number[][],
874
+ ): Promise<ImportCandidate | ToolFailure> => {
875
+ const result = await client.data.directions({
876
+ activity: toDataActivity(slug),
877
+ waypoints,
878
+ });
879
+ const route = result.routes[0];
880
+ // The router found nothing between these points, which is the request's answer.
881
+ if (!route) {
882
+ return {
883
+ code: "not-found",
884
+ error: "commit segment edit: the router found no route between these points",
885
+ ok: false,
886
+ };
887
+ }
888
+
889
+ // A route is a line. A geometry of another type is a fault of the answer, and no route
890
+ // to store.
891
+ const routed = route.geometry;
892
+ if (routed.type !== "LineString") {
893
+ return {
894
+ code: "internal",
895
+ error: `commit segment edit: the route answered is a ${routed.type}, where a LineString is stored`,
896
+ ok: false,
897
+ };
898
+ }
899
+
900
+ // Convert the routed result through the shared wire→live-route projector
901
+ // (the same one the segment editor's routeFn uses) so the candidate keeps
902
+ // its elevation summary + surface/way-type/slope analysis at rest. Without
903
+ // this the saved draft segment's ascent and the elevation panel's profile
904
+ // would vanish the moment the live edit closes; carrying them matches a
905
+ // persisted edit, whose post-commit refetch reloads the same data. The
906
+ // blocks stay null for a 2D-only route (graphqlRouteToLiveRoute leaves them
907
+ // undefined).
908
+ const live = graphqlRouteToLiveRoute({
909
+ analysis: route.analysis,
910
+ distance: route.distance,
911
+ duration: route.duration,
912
+ elevation: route.elevation,
913
+ geometry: routed,
914
+ });
915
+
916
+ // The directions candidate's geojson is the single-level GeometryCollection
917
+ // the wire contract uses, carrying BOTH the routed LineString AND a MultiPoint
918
+ // of the committed vias, mirroring routedSegmentToDraft and the shape the
919
+ // import confirm reads its vias from. Storing only the bare routed LineString here
920
+ // drops the vias, so the confirm finds no waypoints and refuses the directions
921
+ // segment, which needs two. The vias are the routed waypoints, already 2-D.
922
+ const viasGeometry: MultiPoint = { coordinates: waypoints, type: "MultiPoint" };
923
+
924
+ return {
925
+ analysis: live.analysis ?? null,
926
+ ascent: live.elevation?.ascent ?? null,
927
+ descent: live.elevation?.descent ?? null,
928
+ distance: route.distance,
929
+ duration: route.duration,
930
+ elevation: live.elevation ?? null,
931
+ geojson: buildGeometryCollection([routed, viasGeometry]),
932
+ mode: "directions",
933
+ };
934
+ };
935
+
936
+ /**
937
+ * analysedDraftCandidate analyses the line a freehand commit of a draft segment draws, and
938
+ * answers the candidate the draft stores for it: the line densified along its own arc with each
939
+ * vertex's altitude, its length, the time the travel model gives it, its elevation summary and
940
+ * its bands. A persisted segment holds the same members, and the draft's rows, totals and profile
941
+ * read them, which nothing computes for a staged draft later.
942
+ *
943
+ * The line is densified as `buildAnalyzeFn` of the routing rules densifies the live edit's
944
+ * profile ({@link densifyFreehandLine}), so the draft and the profile drawn during the edit sample
945
+ * the same points. That is the segment-save path's budget, so the candidate of a line drawn
946
+ * within the positions a confirm takes for a segment holds no more than that either.
947
+ *
948
+ * Where `buildAnalyzeFn` answers null for a query that throws, this one lets the throw reach the
949
+ * bus, so the status table and a host's recognizers classify it: a refusal of the agreement or a
950
+ * timeout keeps its own code, and the draft keeps the segment as it was.
951
+ *
952
+ * @param client - The client the Data API is read through.
953
+ * @param slug - The REST slug of the draft's activity.
954
+ * @param line - The drawn line, as [lng, lat] positions.
955
+ * @returns The `linestring` candidate the draft stores.
956
+ * @throws What `analyzeGeometry` throws.
957
+ */
958
+ const analysedDraftCandidate = async (
959
+ client: Mountaya,
960
+ slug: string,
961
+ line: Position[],
962
+ ): Promise<ImportCandidate> => {
963
+ const densified = densifyFreehandLine(line);
964
+ const { analysis, duration } = await client.data.analyzeGeometry({
965
+ activity: toDataActivity(slug),
966
+ coordinates: densified.map((position) => [...position]),
967
+ });
968
+
969
+ // One altitude answers each position sent, in order. A position the answer holds none for
970
+ // stays 2-D rather than taking a zero altitude.
971
+ const coordinates: Position[] = densified.map((position, index) => {
972
+ const lng = position[0] ?? 0;
973
+ const lat = position[1] ?? 0;
974
+ const altitude = analysis.elevations[index];
975
+ return altitude === undefined ? [lng, lat] : [lng, lat, altitude];
976
+ });
977
+ const elevation = graphqlElevationToSummary(analysis.elevation);
978
+
979
+ // A collection of the one LineString, as the draft's other freehand candidates hold it. The
980
+ // confirm accepts it in place of the bare line, and the API never answers one: a linestring
981
+ // candidate the API proposes is the bare line, or the line beside the MultiPoint of its drawn
982
+ // vertices. The readers flatten all three alike.
983
+ return {
984
+ analysis: graphqlAnalysisToEntries(analysis),
985
+ ascent: elevation.ascent,
986
+ descent: elevation.descent,
987
+ distance: lineLengthMeters(densified),
988
+ duration,
989
+ elevation,
990
+ geojson: buildGeometryCollection([{ coordinates, type: "LineString" }]),
991
+ mode: "linestring",
992
+ };
993
+ };
994
+
995
+ /**
996
+ * appendedDraftSegment builds the draft segment a draw from scratch appends to a draft's chain,
997
+ * from the candidate its commit computed.
998
+ *
999
+ * A draft segment always holds a freehand candidate. A routed draw holds its routed line as each
1000
+ * candidate, as the suggestion's own segment does: with its vias as the `directions` one, and
1001
+ * alone as the `linestring` one ({@link freehandCandidateOfRoute}, which fits a line past the
1002
+ * positions a freehand confirm takes), so a switch of engine still draws a geometry and still
1003
+ * confirms. A freehand draw holds its line and no routed candidate. The id is minted through the context's ids seam, the
1004
+ * colour is the commit's or none (`""`, which the confirm leaves out), and the segment states no
1005
+ * speed and no recommendation, since no preview measured it.
1006
+ */
1007
+ const appendedDraftSegment = (
1008
+ ctx: StudioToolContext,
1009
+ candidate: ImportCandidate,
1010
+ name: string,
1011
+ color: string | undefined,
1012
+ ): ItineraryDraftSegment => ({
1013
+ color: color ?? "",
1014
+ directions: candidate.mode === "directions" ? candidate : null,
1015
+ id: (ctx.ids ?? studioSeamAbsences.ids).next(),
1016
+ linestring: candidate.mode === "directions" ? freehandCandidateOfRoute(candidate) : candidate,
1017
+ mode: candidate.mode,
1018
+ name,
1019
+ recommendationReason: null,
1020
+ snapLocked: false,
1021
+ speed: null,
1022
+ });
1023
+
1024
+ /**
1025
+ * draftSink is the in-memory write surface of a staged draft, the non-persisted twin of
1026
+ * restSink. Every method writes the draft whose surface shows, the import's or the suggestion's,
1027
+ * immutably, and persists nothing: no REST call, no query-cache eviction. A geometry commit
1028
+ * recomputes the affected candidate through the Data API (the directions op in directions mode,
1029
+ * analyzeGeometry in linestring mode), so the draft segment carries the routed or analysed line
1030
+ * with its distance, duration, elevation and bands; every metadata edit (rename, recolor, icon,
1031
+ * reorder, remove) projects the new value over the matched draft entity. The commit of the
1032
+ * staged surface is what turns the finished draft into a persisted itinerary; until then the
1033
+ * draft is the only thing these writes touch.
1034
+ *
1035
+ * That commit sends the draft as it stands when it goes out, and closes the session as its create
1036
+ * lands. So while it is out every method answers `conflict` and writes nothing
1037
+ * ({@link holdShowingDraft}), and a geometry commit whose recompute lands meanwhile does too: a
1038
+ * write the commit did not send would answer `ok` and reach no itinerary.
1039
+ */
1040
+ export const draftSink: MutationSink = {
1041
+ /**
1042
+ * commitSegment recomputes the edited segment's geometry against the Data API
1043
+ * and writes it into the matched draft segment's candidate. In directions mode
1044
+ * it routes the vias (the `directions` op) and stores the routed line + its
1045
+ * distance/duration into the `directions` candidate; in linestring mode it
1046
+ * analyzes the freehand line (the `analyzeGeometry` op, over the line densified along its
1047
+ * own arc) and stores the analysed line, with its altitudes, distance, duration, elevation
1048
+ * and bands, into the `linestring` candidate. A throw of the analysis reaches the bus, which
1049
+ * classifies it ({@link analysedDraftCandidate}), and nothing is written. Either way it sets
1050
+ * the segment's chosen `mode` to the committed mode so the view follows the edit.
1051
+ *
1052
+ * A commit that names no segment is a segment drawn from scratch, which is appended to the
1053
+ * draft's chain under the name the commit carries and an id the sink mints
1054
+ * ({@link appendedDraftSegment}). It is read beside the answer through
1055
+ * {@link sinkCreatedSegment}, as a created segment is. A draft's chain takes a new segment at
1056
+ * its tail alone, so one that names a gap (`insertBefore`) is refused with `draft-open`.
1057
+ *
1058
+ * The recompute is a request, and the draft goes on being edited while it is out. So the
1059
+ * candidate is written into the draft the store holds when the answer lands, over the
1060
+ * segment as it stands then: a rename, a recolor or a removal made meanwhile is kept. When
1061
+ * that draft is closed the commit answers `no-session`, and when another working copy stands
1062
+ * in its place ({@link activeDraftId}) it answers `conflict`. Either way nothing is written.
1063
+ *
1064
+ * An append is drawn from the end of the draft's last segment, so it lands only while that
1065
+ * segment is still the last one: a chain whose tail was removed, or took another segment,
1066
+ * while the recompute was out answers `not-found` and nothing is written, as an anchor the
1067
+ * chain no longer holds is refused at dispatch.
1068
+ */
1069
+ commitSegment: async (ctx, payload) => {
1070
+ const held = holdShowingDraft(ctx, "commit segment edit");
1071
+ if (held) {
1072
+ return held;
1073
+ }
1074
+
1075
+ const draft = requireDraft(ctx);
1076
+ const draftId = activeDraftId(ctx);
1077
+ // The segment an append is drawn after, read before the request and again as it lands.
1078
+ const tailId = draft?.segments.at(-1)?.id ?? null;
1079
+ if (!draft) {
1080
+ return {
1081
+ code: "no-session",
1082
+ error: "commit segment edit: no staged draft shows",
1083
+ ok: false,
1084
+ };
1085
+ }
1086
+
1087
+ const { name, segmentId } = payload;
1088
+ if (segmentId === undefined && payload.insertBefore) {
1089
+ return {
1090
+ code: "draft-open",
1091
+ error:
1092
+ "commit segment edit: a draft's chain takes a new segment at its tail alone, so draw it after the last segment",
1093
+ ok: false,
1094
+ };
1095
+ }
1096
+
1097
+ // A new segment is appended under the name its commit carries, as the persisted path
1098
+ // creates one.
1099
+ if (segmentId === undefined && name === undefined) {
1100
+ return {
1101
+ code: "invalid-input",
1102
+ error: "commit segment edit: a new segment needs a name",
1103
+ ok: false,
1104
+ };
1105
+ }
1106
+
1107
+ if (segmentId !== undefined && !draft.segments.some((segment) => segment.id === segmentId)) {
1108
+ return notInDraft("commit segment edit", "segment", segmentId);
1109
+ }
1110
+
1111
+ if (!ctx.api?.client) {
1112
+ return { code: "no-api", error: "commit segment edit: no data-api seam", ok: false };
1113
+ }
1114
+
1115
+ const slug = resolveDraftActivitySlug(ctx, draft.activityId);
1116
+ if (!slug) {
1117
+ return {
1118
+ code: "not-found",
1119
+ error: "commit segment edit: cannot resolve the draft activity",
1120
+ ok: false,
1121
+ };
1122
+ }
1123
+
1124
+ const graphql = ctx.api.client;
1125
+ const waypoints = payload.coordinates.map((coordinate) => [...coordinate]);
1126
+
1127
+ let nextCandidate: ImportCandidate;
1128
+ if (payload.mode === "directions") {
1129
+ const routed = await routedDraftCandidate(graphql, slug, waypoints);
1130
+ if ("ok" in routed) {
1131
+ return routed;
1132
+ }
1133
+
1134
+ nextCandidate = routed;
1135
+ } else {
1136
+ nextCandidate = await analysedDraftCandidate(graphql, slug, payload.coordinates);
1137
+ }
1138
+
1139
+ // A commit of the draft sent while the recompute was out has the draft as it stood then.
1140
+ const heldAtLanding = holdShowingDraft(ctx, "commit segment edit");
1141
+ if (heldAtLanding) {
1142
+ return heldAtLanding;
1143
+ }
1144
+
1145
+ // The draft as the store holds it now, which is not the one read before the request.
1146
+ const landed = requireDraft(ctx);
1147
+ if (!landed) {
1148
+ return {
1149
+ code: "no-session",
1150
+ error: "commit segment edit: the staged draft closed before the recompute answered",
1151
+ ok: false,
1152
+ };
1153
+ }
1154
+
1155
+ if (draftId === null || activeDraftId(ctx) !== draftId) {
1156
+ return {
1157
+ code: "conflict",
1158
+ error:
1159
+ "commit segment edit: another draft took the place of the one this edit was " +
1160
+ "computed for; nothing was written",
1161
+ ok: false,
1162
+ };
1163
+ }
1164
+
1165
+ if (segmentId === undefined) {
1166
+ if ((landed.segments.at(-1)?.id ?? null) !== tailId) {
1167
+ return {
1168
+ code: "not-found",
1169
+ error:
1170
+ "commit segment edit: the draft's last segment changed while the recompute was " +
1171
+ "out, so the segment drawn after it has no place; nothing was written",
1172
+ ok: false,
1173
+ };
1174
+ }
1175
+
1176
+ const appended = appendedDraftSegment(ctx, nextCandidate, name ?? "", payload.color);
1177
+ const next = { ...landed, segments: [...landed.segments, appended] };
1178
+ writeDraft(ctx, next);
1179
+
1180
+ return createdAs(
1181
+ createdSegments,
1182
+ { ok: true, summary: `Added draft segment “${appended.name}”.` },
1183
+ draftToView(next).segments.at(-1) ?? null,
1184
+ );
1185
+ }
1186
+
1187
+ const matched = mapDraftSegment(ctx, landed, segmentId, (segment) =>
1188
+ payload.mode === "directions"
1189
+ ? { ...segment, directions: nextCandidate, mode: "directions" }
1190
+ : { ...segment, linestring: nextCandidate, mode: "linestring" },
1191
+ );
1192
+ if (!matched) {
1193
+ return notInDraft("commit segment edit", "segment", segmentId);
1194
+ }
1195
+
1196
+ return { ok: true, summary: `Saved draft segment ${segmentId}.` };
1197
+ },
1198
+
1199
+ /**
1200
+ * commitWaypoint writes the committed waypoint draft attributes (position, icon, name) into
1201
+ * the matched draft waypoint. A draft waypoint has no color: its marker takes the activity's
1202
+ * tint until the confirm persists it, so the session's color is not written, as
1203
+ * `recolorWaypoint` refuses for the same reason.
1204
+ *
1205
+ * A `create` appends a draft waypoint to the draft's list, under the id the payload carries
1206
+ * (minted once, by the verb, through the context's ids seam), as a segment drawn from scratch
1207
+ * is appended to the chain. It is read
1208
+ * beside the answer through {@link sinkCreatedWaypoint}, as a created waypoint is, and the
1209
+ * confirm sends it with the rest.
1210
+ */
1211
+ commitWaypoint: async (ctx, payload) => {
1212
+ const held = holdShowingDraft(ctx, "commit waypoint edit");
1213
+ if (held) {
1214
+ return held;
1215
+ }
1216
+
1217
+ const draft = requireDraft(ctx);
1218
+ if (!draft) {
1219
+ return {
1220
+ code: "no-session",
1221
+ error: "commit waypoint edit: no staged draft shows",
1222
+ ok: false,
1223
+ };
1224
+ }
1225
+
1226
+ if (payload.intent === "create") {
1227
+ const added: ItineraryDraftWaypoint = {
1228
+ geojson: payload.geojson,
1229
+ icon: payload.icon,
1230
+ id: payload.waypointId,
1231
+ mode: payload.mode,
1232
+ name: payload.name,
1233
+ };
1234
+ const next = { ...draft, waypoints: [...draft.waypoints, added] };
1235
+ writeDraft(ctx, next);
1236
+
1237
+ return createdAs(
1238
+ createdWaypoints,
1239
+ { ok: true, summary: `Added draft waypoint “${added.name}”.` },
1240
+ draftToView(next).waypoints.at(-1) ?? null,
1241
+ );
1242
+ }
1243
+
1244
+ const matched = mapDraftWaypoint(ctx, draft, payload.waypointId, (waypoint) => ({
1245
+ ...waypoint,
1246
+ geojson: payload.geojson,
1247
+ icon: payload.icon,
1248
+ // A name left blank follows the rule the persisted path follows (blankNameWrite): a
1249
+ // point of interest is never unnamed and keeps its name, and a point takes the blank,
1250
+ // which the confirm sends as no name at all.
1251
+ name: payload.name.trim() === "" && waypoint.mode === "poi" ? waypoint.name : payload.name,
1252
+ }));
1253
+ if (!matched) {
1254
+ return notInDraft("commit waypoint edit", "waypoint", payload.waypointId);
1255
+ }
1256
+
1257
+ return { ok: true, summary: `Saved draft waypoint ${payload.waypointId}.` };
1258
+ },
1259
+
1260
+ /** recolorSegment recolors the matched draft segment. */
1261
+ recolorSegment: async (ctx, payload) => {
1262
+ const held = holdShowingDraft(ctx, "recolor segment");
1263
+ if (held) {
1264
+ return held;
1265
+ }
1266
+
1267
+ const draft = requireDraft(ctx);
1268
+ if (!draft) {
1269
+ return { code: "no-session", error: "recolor segment: no staged draft shows", ok: false };
1270
+ }
1271
+
1272
+ const matched = mapDraftSegment(ctx, draft, payload.segmentId, (segment) => ({
1273
+ ...segment,
1274
+ color: payload.color,
1275
+ }));
1276
+ if (!matched) {
1277
+ return notInDraft("recolor segment", "segment", payload.segmentId);
1278
+ }
1279
+
1280
+ return { ok: true, summary: `Recolored draft segment ${payload.segmentId}.` };
1281
+ },
1282
+
1283
+ /**
1284
+ * recolorWaypoint is unsupported on a draft: the draft waypoint shape carries
1285
+ * no color field (its marker uses the activity tint until the confirm persists
1286
+ * it), so there is nothing to write. It surfaces a structured failure rather
1287
+ * than a silent success so the import editor does not offer a recolor control
1288
+ * that does nothing. The payload is unread, hence omitted.
1289
+ */
1290
+ recolorWaypoint: async (ctx) => {
1291
+ const held = holdShowingDraft(ctx, "recolor waypoint");
1292
+ if (held) {
1293
+ return held;
1294
+ }
1295
+
1296
+ if (!requireDraft(ctx)) {
1297
+ return { code: "no-session", error: "recolor waypoint: no staged draft shows", ok: false };
1298
+ }
1299
+
1300
+ return {
1301
+ code: "draft-open",
1302
+ error: "recolor waypoint: draft waypoints have no color",
1303
+ ok: false,
1304
+ };
1305
+ },
1306
+
1307
+ /**
1308
+ * removeSegment drops the matched segment from the draft. Deletion is ends-only,
1309
+ * mirroring the rule the API enforces on a persisted chain, which shrinks from its
1310
+ * ends only: the first or the last draft segment may be removed, so the draft stays
1311
+ * a continuous chain the confirm can snap end-to-end. Dropping the head simply
1312
+ * promotes its successor, which has nothing before it to meet. An interior target
1313
+ * is rejected rather than leaving a gap mid-chain.
1314
+ */
1315
+ removeSegment: async (ctx, payload) => {
1316
+ const held = holdShowingDraft(ctx, "remove segment");
1317
+ if (held) {
1318
+ return held;
1319
+ }
1320
+
1321
+ const draft = requireDraft(ctx);
1322
+ if (!draft) {
1323
+ return { code: "no-session", error: "remove segment: no staged draft shows", ok: false };
1324
+ }
1325
+
1326
+ const index = draft.segments.findIndex((segment) => segment.id === payload.segmentId);
1327
+ if (index === -1) {
1328
+ return notInDraft("remove segment", "segment", payload.segmentId);
1329
+ }
1330
+
1331
+ // The chain-shape refusal, under the code the persisted delete answers it with: the chain's
1332
+ // state forbids it, a conflict.
1333
+ if (index !== 0 && index !== draft.segments.length - 1) {
1334
+ return {
1335
+ code: "conflict",
1336
+ error: "remove segment: only the first or the last draft segment may be deleted",
1337
+ ok: false,
1338
+ };
1339
+ }
1340
+
1341
+ const segments = draft.segments.filter((segment) => segment.id !== payload.segmentId);
1342
+ writeDraft(ctx, { ...draft, segments });
1343
+
1344
+ return { ok: true, summary: `Deleted draft segment ${payload.segmentId}.` };
1345
+ },
1346
+
1347
+ /** removeWaypoint drops the matched waypoint from the draft. */
1348
+ removeWaypoint: async (ctx, payload) => {
1349
+ const held = holdShowingDraft(ctx, "remove waypoint");
1350
+ if (held) {
1351
+ return held;
1352
+ }
1353
+
1354
+ const draft = requireDraft(ctx);
1355
+ if (!draft) {
1356
+ return { code: "no-session", error: "remove waypoint: no staged draft shows", ok: false };
1357
+ }
1358
+
1359
+ const waypoints = draft.waypoints.filter((waypoint) => waypoint.id !== payload.waypointId);
1360
+ if (waypoints.length === draft.waypoints.length) {
1361
+ return notInDraft("remove waypoint", "waypoint", payload.waypointId);
1362
+ }
1363
+
1364
+ writeDraft(ctx, { ...draft, waypoints });
1365
+
1366
+ return { ok: true, summary: `Deleted draft waypoint ${payload.waypointId}.` };
1367
+ },
1368
+
1369
+ /**
1370
+ * renameItinerary renames the draft itinerary by writing the new name onto the
1371
+ * open draft session (the draft's name lives on the session, not inside the
1372
+ * draft's segment/waypoint lists), so the shell's name field reflects the edit.
1373
+ * The name lives per-session, so it writes through the import OR the suggest name
1374
+ * setter, by the surface that shows.
1375
+ */
1376
+ renameItinerary: async (ctx, payload) => {
1377
+ const held = holdShowingDraft(ctx, "rename itinerary");
1378
+ if (held) {
1379
+ return held;
1380
+ }
1381
+
1382
+ const state = ctx.ui.getState();
1383
+ if (!showingDraftSession(state)) {
1384
+ return { code: "no-session", error: "rename itinerary: no active draft", ok: false };
1385
+ }
1386
+
1387
+ if (showingDraftSurface(state) === "import") {
1388
+ state.setImportName(payload.name);
1389
+ } else {
1390
+ state.setSuggestName(payload.name);
1391
+ }
1392
+
1393
+ return { ok: true, summary: `Renamed draft itinerary to “${payload.name}”.` };
1394
+ },
1395
+
1396
+ /** renameSegment renames the matched draft segment. */
1397
+ renameSegment: async (ctx, payload) => {
1398
+ const held = holdShowingDraft(ctx, "rename segment");
1399
+ if (held) {
1400
+ return held;
1401
+ }
1402
+
1403
+ const draft = requireDraft(ctx);
1404
+ if (!draft) {
1405
+ return { code: "no-session", error: "rename segment: no staged draft shows", ok: false };
1406
+ }
1407
+
1408
+ const matched = mapDraftSegment(ctx, draft, payload.segmentId, (segment) => ({
1409
+ ...segment,
1410
+ name: payload.name,
1411
+ }));
1412
+ if (!matched) {
1413
+ return notInDraft("rename segment", "segment", payload.segmentId);
1414
+ }
1415
+
1416
+ return { ok: true, summary: `Renamed draft segment to “${payload.name}”.` };
1417
+ },
1418
+
1419
+ /**
1420
+ * renameWaypoint renames the matched draft waypoint.
1421
+ *
1422
+ * A null name clears a draft point's, which the draft holds as the empty string and the
1423
+ * confirm sends as no name at all. A draft point of interest is never unnamed, so a clear of
1424
+ * one is refused ({@link nameClearRefused}), as the persisted path refuses it.
1425
+ */
1426
+ renameWaypoint: async (ctx, payload) => {
1427
+ const held = holdShowingDraft(ctx, "rename waypoint");
1428
+ if (held) {
1429
+ return held;
1430
+ }
1431
+
1432
+ const draft = requireDraft(ctx);
1433
+ if (!draft) {
1434
+ return { code: "no-session", error: "rename waypoint: no staged draft shows", ok: false };
1435
+ }
1436
+
1437
+ const { name } = payload;
1438
+ const renamed = draft.waypoints.find((waypoint) => waypoint.id === payload.waypointId);
1439
+ if (name === null && renamed?.mode === "poi") {
1440
+ return nameClearRefused();
1441
+ }
1442
+
1443
+ const matched = mapDraftWaypoint(ctx, draft, payload.waypointId, (waypoint) => ({
1444
+ ...waypoint,
1445
+ name: name ?? "",
1446
+ }));
1447
+ if (!matched) {
1448
+ return notInDraft("rename waypoint", "waypoint", payload.waypointId);
1449
+ }
1450
+
1451
+ return {
1452
+ ok: true,
1453
+ summary:
1454
+ name === null
1455
+ ? `Cleared the name of draft waypoint ${payload.waypointId}.`
1456
+ : `Renamed draft waypoint to “${name}”.`,
1457
+ };
1458
+ },
1459
+
1460
+ /**
1461
+ * setSegmentSpeed writes the suggested speed (km/h, null = the activity default)
1462
+ * onto the matched draft segment. It persists nothing: the confirm threads the
1463
+ * draft speed into the wire params, where the server computes the segment
1464
+ * duration from it. A pure store write keyed on the segment's client id.
1465
+ */
1466
+ setSegmentSpeed: async (ctx, payload) => {
1467
+ const held = holdShowingDraft(ctx, "set segment speed");
1468
+ if (held) {
1469
+ return held;
1470
+ }
1471
+
1472
+ const draft = requireDraft(ctx);
1473
+ if (!draft) {
1474
+ return { code: "no-session", error: "set segment speed: no staged draft shows", ok: false };
1475
+ }
1476
+
1477
+ const matched = mapDraftSegment(ctx, draft, payload.segmentId, (segment) => ({
1478
+ ...segment,
1479
+ speed: payload.speed,
1480
+ }));
1481
+ if (!matched) {
1482
+ return notInDraft("set segment speed", "segment", payload.segmentId);
1483
+ }
1484
+
1485
+ return {
1486
+ ok: true,
1487
+ summary:
1488
+ payload.speed === null
1489
+ ? `Cleared draft segment ${payload.segmentId} speed.`
1490
+ : `Set draft segment ${payload.segmentId} speed to ${payload.speed} km/h.`,
1491
+ };
1492
+ },
1493
+
1494
+ /**
1495
+ * setWaypointDetails REFUSES against a draft, and that is the scope rather than a gap.
1496
+ *
1497
+ * A draft waypoint comes from a GPX or KML import, and neither format carries services, a
1498
+ * cut-off or a contact: `ProposedWaypoint` has nowhere to put them, so there is nothing for
1499
+ * an import to propose and nothing for this to project. The place details are set once the
1500
+ * itinerary is persisted and the row is a real waypoint.
1501
+ *
1502
+ * A structured refusal rather than a silent success: a tool that reported `ok` while writing
1503
+ * nothing would tell the agent the edit landed.
1504
+ */
1505
+ setWaypointDetails: async () => ({
1506
+ code: "draft-open",
1507
+ error: "set waypoint details: a staged draft carries no place details to set",
1508
+ ok: false,
1509
+ }),
1510
+
1511
+ /** setWaypointIcon sets the icon on the matched draft waypoint. */
1512
+ setWaypointIcon: async (ctx, payload) => {
1513
+ const held = holdShowingDraft(ctx, "set waypoint icon");
1514
+ if (held) {
1515
+ return held;
1516
+ }
1517
+
1518
+ const draft = requireDraft(ctx);
1519
+ if (!draft) {
1520
+ return { code: "no-session", error: "set waypoint icon: no staged draft shows", ok: false };
1521
+ }
1522
+
1523
+ const matched = mapDraftWaypoint(ctx, draft, payload.waypointId, (waypoint) => ({
1524
+ ...waypoint,
1525
+ icon: payload.icon,
1526
+ }));
1527
+ if (!matched) {
1528
+ return notInDraft("set waypoint icon", "waypoint", payload.waypointId);
1529
+ }
1530
+
1531
+ return { ok: true, summary: `Set draft waypoint ${payload.waypointId} icon.` };
1532
+ },
1533
+ };
1534
+
1535
+ /**
1536
+ * resolveMutationSink is the single selection point for the editor mutation tools: it answers
1537
+ * the draft sink while a draft answers for the editor ({@link showingDraft}: the import's or the
1538
+ * suggestion's, while its surface shows) and the rest sink otherwise.
1539
+ *
1540
+ * Every editor mutation tool routes its write through the sink this resolves, so one branch
1541
+ * decides which target a write reaches.
1542
+ */
1543
+ export const resolveMutationSink = (ctx: StudioToolContext): MutationSink =>
1544
+ showingDraft(ctx.ui.getState()) ? draftSink : restSink;
1545
+
1546
+ /**
1547
+ * draftOpenError is the structured refusal a persisted-itinerary-only verb returns
1548
+ * while a draft owns the editor. It is shaped exactly like the other shared refusals
1549
+ * (a tagged code plus a `${verb}: reason` message) so a surface branches on the code
1550
+ * and the log line still names which verb was asked for.
1551
+ */
1552
+ const draftOpenError = (verb: string): ToolFailure => ({
1553
+ code: "draft-open",
1554
+ error: `${verb}: an import or suggestion draft is open in the editor`,
1555
+ ok: false,
1556
+ });
1557
+
1558
+ /**
1559
+ * guardNoActiveDraft refuses a verb that has no meaning against a draft, returning
1560
+ * the structured {@link draftOpenError} when one is open and null otherwise.
1561
+ *
1562
+ * It is the counterpart of {@link resolveMutationSink}: that resolver exists because
1563
+ * a verb has a draft target AND a persisted target, and this guard marks the verbs
1564
+ * that have only the second. Grouping, splitting, merging, inserting into the chain,
1565
+ * changing an engine, publishing, and duplicating are all server operations on stored
1566
+ * rows (a proposal has no rows, no group entity, no publication, and no id to copy),
1567
+ * so without the guard they would write straight through to the persisted itinerary
1568
+ * the user is not looking at, or bottom out in a `not-found` naming an itinerary that
1569
+ * is simply not what is on screen.
1570
+ *
1571
+ * A draft owns the editor only while its surface shows ({@link showingDraft}).
1572
+ *
1573
+ * `verb` is the same human phrase the module's other refusals lead with, so one tool
1574
+ * reports one name whichever way it is refused. ctx is the first positional parameter.
1575
+ */
1576
+ export const guardNoActiveDraft = (ctx: StudioToolContext, verb: string): ToolFailure | null =>
1577
+ showingDraft(ctx.ui.getState()) ? draftOpenError(verb) : null;