@mountaya/studio 0.1.0 → 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 (260) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/agent/index.cjs +2561 -2815
  3. package/dist/agent/index.cjs.map +1 -1
  4. package/dist/agent/index.d.cts +766 -786
  5. package/dist/agent/index.d.ts +766 -786
  6. package/dist/agent/index.js +2553 -2790
  7. package/dist/agent/index.js.map +1 -1
  8. package/dist/chunk-3Oi_Zrtm.js +9 -0
  9. package/dist/chunk-3Oi_Zrtm.js.map +1 -0
  10. package/dist/chunk-B18OPIu_.js +6 -0
  11. package/dist/chunk-B18OPIu_.js.map +1 -0
  12. package/dist/chunk-B5Uz3Qct.cjs +15 -0
  13. package/dist/chunk-B5Uz3Qct.cjs.map +1 -0
  14. package/dist/chunk-BBEJwkd3.d.cts +839 -0
  15. package/dist/chunk-BIEc_SkR.cjs +29 -0
  16. package/dist/chunk-BIEc_SkR.cjs.map +1 -0
  17. package/dist/chunk-BKMFOe-N.js +171 -0
  18. package/dist/chunk-BKMFOe-N.js.map +1 -0
  19. package/dist/chunk-BP4uy7E1.d.ts +11583 -0
  20. package/dist/chunk-BSHTsFiB.js +1403 -0
  21. package/dist/chunk-BSHTsFiB.js.map +1 -0
  22. package/dist/chunk-BTUUABGI.js +17 -0
  23. package/dist/chunk-BTUUABGI.js.map +1 -0
  24. package/dist/chunk-BaPiaz5X.cjs +115 -0
  25. package/dist/chunk-BaPiaz5X.cjs.map +1 -0
  26. package/dist/chunk-BeCVpkYr.cjs +542 -0
  27. package/dist/chunk-BeCVpkYr.cjs.map +1 -0
  28. package/dist/chunk-BgngsvK8.cjs +6202 -0
  29. package/dist/chunk-BgngsvK8.cjs.map +1 -0
  30. package/dist/chunk-BhInd7CJ.d.cts +253 -0
  31. package/dist/chunk-Bn6ZbxkS.cjs +27 -0
  32. package/dist/chunk-By9ZnkVI.js +60 -0
  33. package/dist/chunk-By9ZnkVI.js.map +1 -0
  34. package/dist/chunk-BzqPhxsz.cjs +367 -0
  35. package/dist/chunk-BzqPhxsz.cjs.map +1 -0
  36. package/dist/chunk-C2mMX81q.d.ts +443 -0
  37. package/dist/chunk-C2rr9Q0V.cjs +1402 -0
  38. package/dist/chunk-C2rr9Q0V.cjs.map +1 -0
  39. package/dist/{directorThreads-CqmvsV8b.d.cts → chunk-CDJCbwIQ.d.cts} +20 -22
  40. package/dist/chunk-CLGvBOVH.d.cts +1654 -0
  41. package/dist/chunk-COdw1dc6.d.ts +525 -0
  42. package/dist/chunk-CQCJnT2i.d.ts +511 -0
  43. package/dist/chunk-CSyHY67q.cjs +353 -0
  44. package/dist/chunk-CSyHY67q.cjs.map +1 -0
  45. package/dist/chunk-CiK1Iqrv.js +950 -0
  46. package/dist/chunk-CiK1Iqrv.js.map +1 -0
  47. package/dist/chunk-CmJBgSwZ.cjs +24 -0
  48. package/dist/chunk-CmJBgSwZ.cjs.map +1 -0
  49. package/dist/chunk-CnrsRK2u.cjs +83 -0
  50. package/dist/chunk-CnrsRK2u.cjs.map +1 -0
  51. package/dist/chunk-Co782_9r.js +326 -0
  52. package/dist/chunk-Co782_9r.js.map +1 -0
  53. package/dist/chunk-Csr3KDpZ.cjs +32 -0
  54. package/dist/chunk-Csr3KDpZ.cjs.map +1 -0
  55. package/dist/chunk-CwkmccXv.js +89 -0
  56. package/dist/chunk-CwkmccXv.js.map +1 -0
  57. package/dist/chunk-D0Q4iL9B.cjs +255 -0
  58. package/dist/chunk-D0Q4iL9B.cjs.map +1 -0
  59. package/dist/chunk-DFwiSzUS.cjs +72 -0
  60. package/dist/chunk-DFwiSzUS.cjs.map +1 -0
  61. package/dist/chunk-DIFayl2P.d.cts +443 -0
  62. package/dist/chunk-DIGF58ux.d.cts +525 -0
  63. package/dist/chunk-DKuuuld5.js +101 -0
  64. package/dist/chunk-DKuuuld5.js.map +1 -0
  65. package/dist/chunk-DMePkFEo.js +5054 -0
  66. package/dist/chunk-DMePkFEo.js.map +1 -0
  67. package/dist/chunk-DO5SIBgu.js +305 -0
  68. package/dist/chunk-DO5SIBgu.js.map +1 -0
  69. package/dist/chunk-DOQ_7eE5.d.ts +6662 -0
  70. package/dist/{tabs-B2nRO4p_.d.ts → chunk-DThaaNeb.d.cts} +2 -2
  71. package/dist/{tabs-B2nRO4p_.d.cts → chunk-DThaaNeb.d.ts} +2 -2
  72. package/dist/{directorThreads-CqmvsV8b.d.ts → chunk-DUQzjUJy.d.ts} +20 -22
  73. package/dist/chunk-DX37IPhV.cjs +1903 -0
  74. package/dist/chunk-DX37IPhV.cjs.map +1 -0
  75. package/dist/chunk-Damps5Tk.cjs +155 -0
  76. package/dist/chunk-Damps5Tk.cjs.map +1 -0
  77. package/dist/chunk-DbK5PhpJ.d.ts +1654 -0
  78. package/dist/chunk-De0vAASv.d.ts +253 -0
  79. package/dist/chunk-DhSZ7YZt.d.cts +6662 -0
  80. package/dist/chunk-DjEvqvPA.cjs +43 -0
  81. package/dist/chunk-DjEvqvPA.cjs.map +1 -0
  82. package/dist/{saveFile-j-1kkApx.d.cts → chunk-DkwDzwvu.d.cts} +7 -9
  83. package/dist/{saveFile-j-1kkApx.d.ts → chunk-DkwDzwvu.d.ts} +7 -9
  84. package/dist/chunk-Dmszv9If.js +71 -0
  85. package/dist/chunk-Dmszv9If.js.map +1 -0
  86. package/dist/chunk-Dp_ftNWY.d.cts +511 -0
  87. package/dist/chunk-DsHQySz0.js +31 -0
  88. package/dist/chunk-DsHQySz0.js.map +1 -0
  89. package/dist/chunk-DwoUyHHh.js +281 -0
  90. package/dist/chunk-DwoUyHHh.js.map +1 -0
  91. package/dist/chunk-IaIDQflj.d.cts +2315 -0
  92. package/dist/chunk-IaIDQflj.d.ts +2315 -0
  93. package/dist/chunk-cVXLsZfL.d.ts +839 -0
  94. package/dist/chunk-mIaCX9EJ.d.cts +11583 -0
  95. package/dist/chunk-nJQxbOwQ.cjs +8962 -0
  96. package/dist/chunk-nJQxbOwQ.cjs.map +1 -0
  97. package/dist/chunk-o9jaxhCO.js +8852 -0
  98. package/dist/chunk-o9jaxhCO.js.map +1 -0
  99. package/dist/chunk-p-Tt_Lwz.js +14 -0
  100. package/dist/chunk-p-Tt_Lwz.js.map +1 -0
  101. package/dist/engines/index.cjs +2046 -3401
  102. package/dist/engines/index.cjs.map +1 -1
  103. package/dist/engines/index.d.cts +1510 -1550
  104. package/dist/engines/index.d.ts +1510 -1550
  105. package/dist/engines/index.js +2039 -3380
  106. package/dist/engines/index.js.map +1 -1
  107. package/dist/handlers/index.cjs +47 -93
  108. package/dist/handlers/index.cjs.map +1 -1
  109. package/dist/handlers/index.d.cts +61 -103
  110. package/dist/handlers/index.d.ts +61 -103
  111. package/dist/handlers/index.js +27 -36
  112. package/dist/handlers/index.js.map +1 -1
  113. package/dist/index.cjs +3347 -4398
  114. package/dist/index.cjs.map +1 -1
  115. package/dist/index.d.cts +8 -7297
  116. package/dist/index.d.ts +8 -7297
  117. package/dist/index.js +2997 -3187
  118. package/dist/index.js.map +1 -1
  119. package/dist/plugins/index.cjs +482 -949
  120. package/dist/plugins/index.cjs.map +1 -1
  121. package/dist/plugins/index.d.cts +44 -61
  122. package/dist/plugins/index.d.ts +44 -61
  123. package/dist/plugins/index.js +471 -915
  124. package/dist/plugins/index.js.map +1 -1
  125. package/dist/seams/index.cjs +77 -140
  126. package/dist/seams/index.cjs.map +1 -1
  127. package/dist/seams/index.d.cts +125 -158
  128. package/dist/seams/index.d.ts +125 -158
  129. package/dist/seams/index.js +41 -71
  130. package/dist/seams/index.js.map +1 -1
  131. package/dist/strings/fr/index.cjs +2130 -2116
  132. package/dist/strings/fr/index.cjs.map +1 -1
  133. package/dist/strings/fr/index.d.cts +3 -5
  134. package/dist/strings/fr/index.d.ts +3 -5
  135. package/dist/strings/fr/index.js +2125 -2114
  136. package/dist/strings/fr/index.js.map +1 -1
  137. package/dist/strings/index.cjs +2331 -2625
  138. package/dist/strings/index.cjs.map +1 -1
  139. package/dist/strings/index.d.cts +3 -731
  140. package/dist/strings/index.d.ts +3 -731
  141. package/dist/strings/index.js +2324 -2615
  142. package/dist/strings/index.js.map +1 -1
  143. package/dist/testing/index.cjs +214 -276
  144. package/dist/testing/index.cjs.map +1 -1
  145. package/dist/testing/index.d.cts +61 -121
  146. package/dist/testing/index.d.ts +61 -121
  147. package/dist/testing/index.js +208 -273
  148. package/dist/testing/index.js.map +1 -1
  149. package/dist/time/index.cjs +23 -23
  150. package/dist/time/index.cjs.map +1 -1
  151. package/dist/time/index.d.cts +5 -7
  152. package/dist/time/index.d.ts +5 -7
  153. package/dist/time/index.js +18 -21
  154. package/dist/time/index.js.map +1 -1
  155. package/package.json +14 -15
  156. package/src/agent/rules/stateDelta.ts +1 -0
  157. package/src/agent/stores/agentThreads.ts +1 -4
  158. package/src/bus/rules/bus.ts +1 -2
  159. package/src/bus/rules/defineRegistry.ts +3 -5
  160. package/src/bus/rules/types.ts +6 -7
  161. package/src/chrome/stores/uiStore.ts +4 -2
  162. package/src/embed/rules/fieldDependencies.ts +2 -0
  163. package/src/embed/rules/safetyRules.ts +2 -0
  164. package/src/embed/rules/tableCode.ts +4 -3
  165. package/src/index.ts +6 -27
  166. package/src/itinerary/rules/import.ts +6 -8
  167. package/src/plugins/contracts/plugin.ts +4 -2
  168. package/src/seams/rules/formatters.ts +5 -3
  169. package/src/testing/index.ts +1 -5
  170. package/src/viewer/rules/platformViewer.ts +1 -0
  171. package/dist/bus-BwiNiXdH.d.ts +0 -514
  172. package/dist/bus-DzmhPwdK.d.cts +0 -514
  173. package/dist/chainModel-B23pEP_1.d.cts +0 -127
  174. package/dist/chainModel-B23pEP_1.d.ts +0 -127
  175. package/dist/chunk-2HFY7ETU.js +0 -5721
  176. package/dist/chunk-2HFY7ETU.js.map +0 -1
  177. package/dist/chunk-355TOXSB.js +0 -72
  178. package/dist/chunk-355TOXSB.js.map +0 -1
  179. package/dist/chunk-4ZCUZVSV.js +0 -10275
  180. package/dist/chunk-4ZCUZVSV.js.map +0 -1
  181. package/dist/chunk-6HEKY3NF.js +0 -95
  182. package/dist/chunk-6HEKY3NF.js.map +0 -1
  183. package/dist/chunk-7GFLGGBX.cjs +0 -8
  184. package/dist/chunk-7GFLGGBX.cjs.map +0 -1
  185. package/dist/chunk-7NBRCENN.cjs +0 -19
  186. package/dist/chunk-7NBRCENN.cjs.map +0 -1
  187. package/dist/chunk-AF5GCXE3.js +0 -8
  188. package/dist/chunk-AF5GCXE3.js.map +0 -1
  189. package/dist/chunk-CJDIFRGZ.cjs +0 -2005
  190. package/dist/chunk-CJDIFRGZ.cjs.map +0 -1
  191. package/dist/chunk-CNPZY7N3.js +0 -349
  192. package/dist/chunk-CNPZY7N3.js.map +0 -1
  193. package/dist/chunk-DZJHTWSF.cjs +0 -45
  194. package/dist/chunk-DZJHTWSF.cjs.map +0 -1
  195. package/dist/chunk-EABIHHWA.js +0 -42
  196. package/dist/chunk-EABIHHWA.js.map +0 -1
  197. package/dist/chunk-EKZWV6RS.cjs +0 -415
  198. package/dist/chunk-EKZWV6RS.cjs.map +0 -1
  199. package/dist/chunk-EOKRXXAC.cjs +0 -24
  200. package/dist/chunk-EOKRXXAC.cjs.map +0 -1
  201. package/dist/chunk-F73W2ZTJ.js +0 -1126
  202. package/dist/chunk-F73W2ZTJ.js.map +0 -1
  203. package/dist/chunk-H4DVOZ5O.js +0 -1897
  204. package/dist/chunk-H4DVOZ5O.js.map +0 -1
  205. package/dist/chunk-HI52PBFT.cjs +0 -10314
  206. package/dist/chunk-HI52PBFT.cjs.map +0 -1
  207. package/dist/chunk-IDBXFBLG.cjs +0 -1225
  208. package/dist/chunk-IDBXFBLG.cjs.map +0 -1
  209. package/dist/chunk-LBWTJZUJ.js +0 -297
  210. package/dist/chunk-LBWTJZUJ.js.map +0 -1
  211. package/dist/chunk-NCLA6DKD.cjs +0 -310
  212. package/dist/chunk-NCLA6DKD.cjs.map +0 -1
  213. package/dist/chunk-O4MC5DPD.js +0 -19
  214. package/dist/chunk-O4MC5DPD.js.map +0 -1
  215. package/dist/chunk-OP37FKW6.cjs +0 -98
  216. package/dist/chunk-OP37FKW6.cjs.map +0 -1
  217. package/dist/chunk-OQSYFH3Z.cjs +0 -5945
  218. package/dist/chunk-OQSYFH3Z.cjs.map +0 -1
  219. package/dist/chunk-PACIO4NS.cjs +0 -26
  220. package/dist/chunk-PACIO4NS.cjs.map +0 -1
  221. package/dist/chunk-PSZ2R3TC.cjs +0 -75
  222. package/dist/chunk-PSZ2R3TC.cjs.map +0 -1
  223. package/dist/chunk-QFO5CZG2.cjs +0 -136
  224. package/dist/chunk-QFO5CZG2.cjs.map +0 -1
  225. package/dist/chunk-QL63MUEW.cjs +0 -140
  226. package/dist/chunk-QL63MUEW.cjs.map +0 -1
  227. package/dist/chunk-RFUPPVZO.js +0 -17
  228. package/dist/chunk-RFUPPVZO.js.map +0 -1
  229. package/dist/chunk-RPG2LWMP.js +0 -23
  230. package/dist/chunk-RPG2LWMP.js.map +0 -1
  231. package/dist/chunk-TIBXK6B7.cjs +0 -12
  232. package/dist/chunk-TIBXK6B7.cjs.map +0 -1
  233. package/dist/chunk-UU65VNEV.js +0 -381
  234. package/dist/chunk-UU65VNEV.js.map +0 -1
  235. package/dist/chunk-VGX6TR2I.js +0 -209
  236. package/dist/chunk-VGX6TR2I.js.map +0 -1
  237. package/dist/chunk-WUTDDBVP.js +0 -130
  238. package/dist/chunk-WUTDDBVP.js.map +0 -1
  239. package/dist/chunk-WVQQLKCI.cjs +0 -224
  240. package/dist/chunk-WVQQLKCI.cjs.map +0 -1
  241. package/dist/chunk-WZYXG3SE.js +0 -111
  242. package/dist/chunk-WZYXG3SE.js.map +0 -1
  243. package/dist/chunk-XDI2X3KE.js +0 -6
  244. package/dist/chunk-XDI2X3KE.js.map +0 -1
  245. package/dist/chunk-XKHLRIC7.cjs +0 -381
  246. package/dist/chunk-XKHLRIC7.cjs.map +0 -1
  247. package/dist/context-DNtd2WUv.d.cts +0 -11666
  248. package/dist/context-DgB72Bur.d.ts +0 -11666
  249. package/dist/en-Bu4Ti9Ev.d.cts +0 -2315
  250. package/dist/en-Bu4Ti9Ev.d.ts +0 -2315
  251. package/dist/shareLink-B6hlt942.d.ts +0 -144
  252. package/dist/shareLink-C7rIMb7x.d.ts +0 -527
  253. package/dist/shareLink-CnTxxXjp.d.cts +0 -144
  254. package/dist/shareLink-DyZVYH2V.d.cts +0 -527
  255. package/dist/studioPlugin-C3C7VjMy.d.ts +0 -847
  256. package/dist/studioPlugin-Cf3OBNUv.d.cts +0 -847
  257. package/dist/types-BzJRV6UI.d.cts +0 -845
  258. package/dist/types-BzJRV6UI.d.ts +0 -845
  259. package/dist/zoneForm-CdYNtnnA.d.cts +0 -320
  260. package/dist/zoneForm-mG85yt5e.d.ts +0 -320
@@ -0,0 +1,1403 @@
1
+ import { _ as isSegmentDraftDirty, ft as createItinerarySlice, l as createSegmentEditSlice, pt as itineraryInitialState, u as segmentEditInitialState } from "./chunk-CiK1Iqrv.js";
2
+ import { Bt as selectedCandidate, Dr as createCollabSlice, F as videoExportInitialState, N as createVideoExportSlice, Rn as createZoneEditSlice, Vn as zoneEditInitialState, _ as createWaypointEditSlice, _r as collabInitialState, _t as POI_GROUP_IDS, b as waypointEditInitialState, ct as segmentGroupEditInitialState, d as segmentLengthMeters, dn as DEFAULT_TERRAIN, dt as createRoadAccessDialogSlice, f as agentHandoffTarget, ft as roadAccessDialogInitialState, h as studioToolContracts, in as createCollectionsSlice, ir as createChromeSlice, it as segmentSplitInitialState, mt as DEFAULT_ENABLED_POI_GROUP_IDS, nn as collectionsInitialState, p as selectActiveEditEngine, rt as createSegmentSplitSlice, st as createSegmentGroupEditSlice, tr as chromeInitialState, u as projectOnSegment } from "./chunk-DMePkFEo.js";
3
+ import { w as isZoneGeometryDirty } from "./chunk-Co782_9r.js";
4
+ import { t as notifyListeners } from "./chunk-BTUUABGI.js";
5
+ import { a as failureFromThrown, c as messageOf, o as lockHolderOf, s as memberOf$1 } from "./chunk-DKuuuld5.js";
6
+ import { r as studioSeamAbsences } from "./chunk-BKMFOe-N.js";
7
+ import * as z$1 from "zod";
8
+ import { DIRECTIONS_VIA_MAX, extractVias } from "@mountaya/elements/geo";
9
+ import { MountayaElementsError } from "@mountaya/elements/errors";
10
+ import { POIS_OVERLAY_SLUG, POIS_OVERLAY_SLUG as POIS_OVERLAY_SLUG$1, findOverlay, isEnrichmentCategory } from "@mountaya/elements/layers";
11
+ import { BASEMAP_ATTRIBUTION } from "@mountaya/elements/style";
12
+ import { defaultUnits } from "@mountaya/elements/profile";
13
+ import { createStore } from "zustand/vanilla";
14
+ const nameKeyedSchemaKeys = /* @__PURE__ */ new Set([
15
+ "$defs",
16
+ "patternProperties",
17
+ "properties"
18
+ ]);
19
+ const valueKeyedSchemaKeys = /* @__PURE__ */ new Set([
20
+ "const",
21
+ "default",
22
+ "enum",
23
+ "examples"
24
+ ]);
25
+ const kindsJsonCannotCarry = /* @__PURE__ */ new Set([
26
+ "bigint",
27
+ "date",
28
+ "map",
29
+ "nan",
30
+ "set",
31
+ "symbol"
32
+ ]);
33
+ const UNION_KEYWORDS = ["anyOf", "oneOf"];
34
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
35
+ const isModelInert = (key, entry) => key === "$schema" || key === "additionalProperties" && (typeof entry === "boolean" || isRecord(entry) && Object.keys(entry).length === 0);
36
+ const acceptsNothing = (schema) => isRecord(schema) && isRecord(schema.not) && Object.keys(schema.not).length === 0;
37
+ const withoutUnsendableArms = (schema) => {
38
+ for (const keyword of UNION_KEYWORDS) {
39
+ const arms = schema[keyword];
40
+ if (!Array.isArray(arms)) continue;
41
+ const kept = arms.filter((arm) => !acceptsNothing(arm));
42
+ if (kept.length === arms.length) continue;
43
+ const beside = Object.entries(schema).filter(([key]) => key !== keyword);
44
+ const [only] = kept;
45
+ if (kept.length === 0) return {
46
+ ...Object.fromEntries(beside),
47
+ not: {}
48
+ };
49
+ if (kept.length === 1 && isRecord(only)) return {
50
+ ...only,
51
+ ...Object.fromEntries(beside)
52
+ };
53
+ return Object.fromEntries(Object.entries(schema).map(([key, entry]) => [key, key === keyword ? kept : entry]));
54
+ }
55
+ return schema;
56
+ };
57
+ const slim = (value) => {
58
+ if (Array.isArray(value)) return value.map(slim);
59
+ if (!isRecord(value)) return value;
60
+ const slimmed = {};
61
+ for (const [key, entry] of Object.entries(value)) {
62
+ if (isModelInert(key, entry)) continue;
63
+ if (valueKeyedSchemaKeys.has(key)) slimmed[key] = entry;
64
+ else if (nameKeyedSchemaKeys.has(key) && isRecord(entry)) slimmed[key] = Object.fromEntries(Object.entries(entry).map(([name, schema]) => [name, slim(schema)]));
65
+ else slimmed[key] = slim(entry);
66
+ }
67
+ return withoutUnsendableArms(slimmed);
68
+ };
69
+ const renderedSchemas = /* @__PURE__ */ new WeakMap();
70
+ const renderInputSchema = (input) => {
71
+ const cached = renderedSchemas.get(input);
72
+ if (cached) return cached;
73
+ const rendered = slim(z$1.toJSONSchema(input, {
74
+ io: "input",
75
+ override: ({ jsonSchema, zodSchema }) => {
76
+ const { def } = zodSchema._zod;
77
+ const coerced = "coerce" in def && def.coerce === true;
78
+ if (kindsJsonCannotCarry.has(def.type) && !coerced) jsonSchema.not = {};
79
+ },
80
+ unrepresentable: "any"
81
+ }));
82
+ renderedSchemas.set(input, rendered);
83
+ return rendered;
84
+ };
85
+ const MAX_LISTED_PARAMETERS = 8;
86
+ const MAX_LISTED_ENUM_VALUES = 12;
87
+ const MAX_LISTED_SHAPES = 6;
88
+ const isSchemaObject = (schema) => typeof schema === "object" && schema !== null;
89
+ const ROOT_POINTER = "#";
90
+ const DEFINITION_POINTER = "#/$defs/";
91
+ const targetOf = (pointer, root) => {
92
+ if (pointer === ROOT_POINTER) return root;
93
+ if (!pointer.startsWith(DEFINITION_POINTER) || root.$defs === void 0) return;
94
+ const name = pointer.slice(8);
95
+ return Object.hasOwn(root.$defs, name) ? root.$defs[name] : void 0;
96
+ };
97
+ const typeWord = (schema) => {
98
+ if (Array.isArray(schema.type)) return schema.type.join(" | ");
99
+ return typeof schema.type === "string" ? schema.type : "any";
100
+ };
101
+ const describeType = (schema, scope) => {
102
+ if (!isSchemaObject(schema)) return "any";
103
+ if (typeof schema.$ref === "string") {
104
+ const target = targetOf(schema.$ref, scope.root);
105
+ if (target === void 0) return "any";
106
+ return scope.reading.includes(schema.$ref) ? typeWord(target) : describeType(target, {
107
+ reading: [...scope.reading, schema.$ref],
108
+ root: scope.root
109
+ });
110
+ }
111
+ if (acceptsNothing(schema)) return "no value a JSON call can carry";
112
+ if (schema.const !== void 0) return JSON.stringify(schema.const);
113
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) {
114
+ const values = schema.enum.slice(0, MAX_LISTED_ENUM_VALUES).map((value) => JSON.stringify(value));
115
+ const rest = schema.enum.length - values.length;
116
+ return `one of ${values.join(" | ")}${rest > 0 ? ` (+${rest} more)` : ""}`;
117
+ }
118
+ const branches = schema.anyOf ?? schema.oneOf;
119
+ if (Array.isArray(branches) && branches.length > 0) return branches.map((branch) => describeType(branch, scope)).join(" | ");
120
+ if (Array.isArray(schema.allOf) && schema.allOf.length > 0) return [...new Set(schema.allOf.map((part) => describeType(part, scope)))].join(" & ");
121
+ if (schema.type === "array") return Array.isArray(schema.prefixItems) ? `[${schema.prefixItems.map((item) => describeType(item, scope)).join(", ")}]` : `array of ${describeType(Array.isArray(schema.items) ? void 0 : schema.items, scope)}`;
122
+ if (schema.type === "object" && schema.properties === void 0 && isSchemaObject(schema.additionalProperties)) return `object of ${describeType(schema.additionalProperties, scope)}`;
123
+ return typeWord(schema);
124
+ };
125
+ const valueAt = (root, path) => {
126
+ let current = root;
127
+ try {
128
+ for (const key of path) {
129
+ if (current === null || typeof current !== "object") return;
130
+ current = current[key];
131
+ }
132
+ } catch {
133
+ return;
134
+ }
135
+ return current;
136
+ };
137
+ const pathOf = (path) => path.length > 0 ? path.map((key) => String(key)).join(".") : "(root)";
138
+ const typeName = (value) => {
139
+ if (Array.isArray(value)) return "array";
140
+ return value === null ? "null" : typeof value;
141
+ };
142
+ const describeIssue = (issue, rawInput) => {
143
+ const path = pathOf(issue.path);
144
+ if (issue.code === "invalid_type") {
145
+ const received = valueAt(rawInput, issue.path);
146
+ return received === void 0 ? `${path} is required and was not supplied` : `${path} must be ${issue.expected}, not ${typeName(received)}`;
147
+ }
148
+ return `${path}: ${issue.message}`;
149
+ };
150
+ const describeParameters = (shape, root) => {
151
+ const properties = Object.entries(shape.properties ?? {});
152
+ if (properties.length === 0) return null;
153
+ const scope = {
154
+ reading: [ROOT_POINTER],
155
+ root
156
+ };
157
+ const required = new Set(Array.isArray(shape.required) ? shape.required : []);
158
+ const listed = properties.slice(0, MAX_LISTED_PARAMETERS);
159
+ const accepted = listed.map(([key, value]) => `${key} (${describeType(value, scope)}${required.has(key) ? ", required" : ", optional"})`).join(", ");
160
+ const omitted = properties.length - listed.length;
161
+ return `${accepted}${omitted > 0 ? `, and ${omitted} more` : ""}`;
162
+ };
163
+ const partsAsOneShape = (parts) => {
164
+ const properties = {};
165
+ const required = /* @__PURE__ */ new Set();
166
+ for (const shapes of parts) {
167
+ const [only] = shapes;
168
+ if (shapes.length !== 1 || only === void 0) return null;
169
+ Object.assign(properties, only.properties);
170
+ for (const name of Array.isArray(only.required) ? only.required : []) required.add(name);
171
+ }
172
+ return {
173
+ properties,
174
+ required: [...required],
175
+ type: "object"
176
+ };
177
+ };
178
+ const shapesOf = (schema, scope) => {
179
+ if (typeof schema.$ref === "string") {
180
+ const target = targetOf(schema.$ref, scope.root);
181
+ if (target === void 0) return [schema];
182
+ return scope.reading.includes(schema.$ref) ? [] : shapesOf(target, {
183
+ reading: [...scope.reading, schema.$ref],
184
+ root: scope.root
185
+ });
186
+ }
187
+ const branches = schema.oneOf ?? schema.anyOf;
188
+ if (Array.isArray(branches)) return branches.flatMap((branch) => isSchemaObject(branch) ? shapesOf(branch, scope) : []);
189
+ if (Array.isArray(schema.allOf) && schema.allOf.length > 0) return [partsAsOneShape(schema.allOf.map((part) => shapesOf(part, scope))) ?? schema];
190
+ return [schema];
191
+ };
192
+ const selectorOf = (shape, rawInput) => {
193
+ const pinned = Object.entries(shape.properties ?? {}).flatMap(([key, value]) => isSchemaObject(value) && value.const !== void 0 ? [{
194
+ key,
195
+ literal: value.const
196
+ }] : []);
197
+ if (pinned.length === 0 || pinned.some(({ key, literal }) => valueAt(rawInput, [key]) !== literal)) return null;
198
+ return pinned.map(({ key, literal }) => `${key} is ${JSON.stringify(literal)}`).join(" and ");
199
+ };
200
+ const describeAccepted = (schema, rawInput) => {
201
+ const shapes = shapesOf(schema, {
202
+ reading: [ROOT_POINTER],
203
+ root: schema
204
+ });
205
+ const parametersOf = (shape) => describeParameters(shape, schema);
206
+ const [only] = shapes;
207
+ if (shapes.length === 1 && only !== void 0) {
208
+ const parameters = parametersOf(only);
209
+ return parameters === null ? null : `Accepted parameters: ${parameters}.`;
210
+ }
211
+ if (shapes.every((shape) => parametersOf(shape) === null)) return null;
212
+ const selected = shapes.flatMap((shape) => {
213
+ const selector = selectorOf(shape, rawInput);
214
+ return selector === null ? [] : [{
215
+ selector,
216
+ shape
217
+ }];
218
+ });
219
+ const [chosen] = selected;
220
+ if (selected.length === 1 && chosen !== void 0) return `Accepted parameters when ${chosen.selector}: ${parametersOf(chosen.shape) ?? "none"}.`;
221
+ const listed = shapes.slice(0, MAX_LISTED_SHAPES).map((shape, index) => `[${index + 1}] ${parametersOf(shape) ?? "no parameters"}`).join("; ");
222
+ const omitted = shapes.length - Math.min(shapes.length, MAX_LISTED_SHAPES);
223
+ return `Accepted parameters, in one of these shapes: ${listed}${omitted > 0 ? `; and ${omitted} more` : ""}.`;
224
+ };
225
+ const describeRejection = (name, input, error, rawInput) => {
226
+ const problems = error.issues.map((issue) => describeIssue(issue, rawInput)).join("; ");
227
+ let schema;
228
+ try {
229
+ schema = renderInputSchema(input);
230
+ } catch {
231
+ return `invalid input for ${name}: ${problems}`;
232
+ }
233
+ const accepted = describeAccepted(schema, rawInput);
234
+ if (accepted === null) return `invalid input for ${name}: ${problems}. It takes no parameters.`;
235
+ return `invalid input for ${name}: ${problems}. ${accepted} Use exactly these names, and send values as their stated types: a number is 12000, not "12000".`;
236
+ };
237
+ const describeInvalidInput = (name, input, error, rawInput) => {
238
+ try {
239
+ return describeRejection(name, input, error, rawInput);
240
+ } catch {
241
+ return `invalid input for ${name}`;
242
+ }
243
+ };
244
+ const toolCapabilitySchema = z$1.enum(["authenticated", "editor"]);
245
+ const confirmationToneSchema = z$1.enum([
246
+ "affirmative",
247
+ "cautionary",
248
+ "destructive"
249
+ ]);
250
+ const toolConfirmationSchema = z$1.object({
251
+ acknowledgeLabel: z$1.string().optional(),
252
+ confirmLabel: z$1.string().optional(),
253
+ descriptionLabel: z$1.string().optional(),
254
+ titleLabel: z$1.string().optional(),
255
+ tone: confirmationToneSchema.optional()
256
+ });
257
+ const toolErrorCodeSchema = z$1.enum({
258
+ canceled: "canceled",
259
+ "capability-denied": "capability-denied",
260
+ "collab-locked": "collab-locked",
261
+ "confirmation-denied": "confirmation-denied",
262
+ "confirmation-timeout": "confirmation-timeout",
263
+ conflict: "conflict",
264
+ "draft-open": "draft-open",
265
+ "edit-in-progress": "edit-in-progress",
266
+ forbidden: "forbidden",
267
+ internal: "internal",
268
+ "invalid-input": "invalid-input",
269
+ "limit-reached": "limit-reached",
270
+ "no-api": "no-api",
271
+ "no-map": "no-map",
272
+ "no-session": "no-session",
273
+ "not-found": "not-found",
274
+ "rate-limited": "rate-limited",
275
+ "split-on-end": "split-on-end",
276
+ "split-too-far": "split-too-far",
277
+ timeout: "timeout",
278
+ unavailable: "unavailable",
279
+ "unknown-tool": "unknown-tool",
280
+ "upgrade-required": "upgrade-required"
281
+ });
282
+ const resolveConfirmationValues = (tool, ctx, input) => {
283
+ if (!tool.confirmationValues) return;
284
+ try {
285
+ return tool.confirmationValues(ctx, input);
286
+ } catch {
287
+ return;
288
+ }
289
+ };
290
+ const askConfirmation = async (tool, ctx, input) => {
291
+ if (!ctx.confirm) return false;
292
+ try {
293
+ return await ctx.confirm({
294
+ acknowledge: tool.confirmation,
295
+ confirmLabel: tool.confirmation?.confirmLabel,
296
+ description: tool.description,
297
+ descriptionLabel: tool.confirmation?.descriptionLabel,
298
+ input,
299
+ name: tool.name,
300
+ titleLabel: tool.confirmation?.titleLabel,
301
+ tone: tool.confirmation?.tone,
302
+ values: resolveConfirmationValues(tool, ctx, input)
303
+ });
304
+ } catch {
305
+ return false;
306
+ }
307
+ };
308
+ const isToolFailure = (value) => typeof value === "object" && value !== null && "ok" in value && value.ok === false && "error" in value && typeof value.error === "string";
309
+ const refusalBeforeAsking = (tool, ctx, input, recognizers) => {
310
+ if (!tool.precondition) return null;
311
+ try {
312
+ const answered = tool.precondition(ctx, input);
313
+ if (answered === null || answered === void 0) return null;
314
+ if (isToolFailure(answered)) return answered;
315
+ } catch (err) {
316
+ return failureFromThrown(err, recognizers);
317
+ }
318
+ return {
319
+ code: "internal",
320
+ error: `the precondition of ${tool.name} answered neither a refusal nor null`,
321
+ ok: false
322
+ };
323
+ };
324
+ const playbookDescriptions = (playbook) => new Map((playbook ?? []).map((entry) => [entry.id, entry.description]));
325
+ const playbookReadOnly = (playbook) => new Set((playbook ?? []).filter((entry) => entry.kind === "read").map((entry) => entry.id));
326
+ var ToolBus = class {
327
+ observers = /* @__PURE__ */ new Set();
328
+ tools = /* @__PURE__ */ new Map();
329
+ descriptions;
330
+ readOnly;
331
+ recognizers;
332
+ reserved;
333
+ dispatcher;
334
+ constructor(options = {}) {
335
+ this.descriptions = playbookDescriptions(options.playbook);
336
+ this.readOnly = playbookReadOnly(options.playbook);
337
+ this.recognizers = options.recognizers ?? [];
338
+ this.reserved = new Set(options.reserved ?? []);
339
+ this.dispatcher = {
340
+ dispatch: (ctx, name, rawInput) => this.dispatch(ctx, name, rawInput),
341
+ dispatchUnsafe: (ctx, name, rawInput) => this.dispatchUnsafe(ctx, name, rawInput)
342
+ };
343
+ }
344
+ register(tool) {
345
+ if (this.tools.has(tool.name)) {
346
+ const segment = tool.name.split(".")[0] ?? "";
347
+ throw new MountayaElementsError(this.reserved.has(segment) ? `tool already registered: ${tool.name}. Its "${segment}" segment is reserved on this bus, so unregister keeps it: hand the replacement to the handlers the bus is built with (overrideStudioHandler replaces one studio verb).` : `tool already registered: ${tool.name}. Take it off with unregister("${tool.name}"), then register the replacement.`);
348
+ }
349
+ if (tool.requiresConfirmation && tool.confirmation !== void 0) {
350
+ const parsed = toolConfirmationSchema.safeParse(tool.confirmation);
351
+ if (!parsed.success) throw new MountayaElementsError(`tool ${tool.name} carries an invalid confirmation policy: ${parsed.error.message}`);
352
+ }
353
+ this.tools.set(tool.name, tool);
354
+ }
355
+ registerAll(registry) {
356
+ for (const tool of Object.values(registry)) this.register(tool);
357
+ }
358
+ registered() {
359
+ return [...this.tools.values()];
360
+ }
361
+ unregister(name) {
362
+ if (this.reserved.has(name.split(".")[0] ?? "")) return false;
363
+ return this.tools.delete(name);
364
+ }
365
+ observe(observer) {
366
+ this.observers.add(observer);
367
+ return () => {
368
+ this.observers.delete(observer);
369
+ };
370
+ }
371
+ emit(event) {
372
+ notifyListeners(this.observers, event);
373
+ }
374
+ refuseInput(capability, name, start, error) {
375
+ this.emit({
376
+ capability,
377
+ errorClass: "invalid-input",
378
+ errorCode: "invalid-input",
379
+ errorMessage: error,
380
+ latencyMs: performance.now() - start,
381
+ name,
382
+ ok: false
383
+ });
384
+ return {
385
+ code: "invalid-input",
386
+ error,
387
+ ok: false
388
+ };
389
+ }
390
+ manifest(capabilities, surface) {
391
+ const entries = [];
392
+ for (const tool of this.tools.values()) {
393
+ if (!capabilities.has(tool.capability) || tool.agentHidden) continue;
394
+ if (surface !== void 0 && !surface.has(tool.name)) continue;
395
+ entries.push({
396
+ capability: tool.capability,
397
+ description: this.descriptions.get(tool.name) ?? tool.description,
398
+ inputSchema: renderInputSchema(tool.input),
399
+ name: tool.name,
400
+ readOnly: this.readOnly.has(tool.name),
401
+ requiresConfirmation: tool.requiresConfirmation ?? false
402
+ });
403
+ }
404
+ return entries;
405
+ }
406
+ async dispatchUnsafe(ctx, name, rawInput) {
407
+ const start = performance.now();
408
+ const tool = this.tools.get(name);
409
+ if (!tool) {
410
+ this.emit({
411
+ errorClass: "unknown-tool",
412
+ errorCode: "unknown-tool",
413
+ errorMessage: `unknown tool: ${name}`,
414
+ latencyMs: performance.now() - start,
415
+ name,
416
+ ok: false
417
+ });
418
+ return {
419
+ code: "unknown-tool",
420
+ error: `unknown tool: ${name}`,
421
+ ok: false
422
+ };
423
+ }
424
+ if (!ctx.capabilities.has(tool.capability)) {
425
+ this.emit({
426
+ capability: tool.capability,
427
+ errorClass: "capability-denied",
428
+ errorCode: "capability-denied",
429
+ errorMessage: `capability not granted: ${tool.capability}`,
430
+ latencyMs: performance.now() - start,
431
+ name,
432
+ ok: false
433
+ });
434
+ return {
435
+ code: "capability-denied",
436
+ error: `capability not granted: ${tool.capability}`,
437
+ ok: false
438
+ };
439
+ }
440
+ let parsed;
441
+ try {
442
+ parsed = tool.input.safeParse(rawInput);
443
+ } catch (err) {
444
+ return this.refuseInput(tool.capability, name, start, `invalid input for ${name}: ${messageOf(err)}`);
445
+ }
446
+ if (!parsed.success) return this.refuseInput(tool.capability, name, start, describeInvalidInput(name, tool.input, parsed.error, rawInput));
447
+ const refused = refusalBeforeAsking(tool, ctx, parsed.data, this.recognizers);
448
+ if (refused !== null) {
449
+ this.emit({
450
+ capability: tool.capability,
451
+ errorClass: "handler-error",
452
+ errorCode: refused.code,
453
+ errorMessage: refused.error,
454
+ latencyMs: performance.now() - start,
455
+ name,
456
+ ok: false
457
+ });
458
+ return refused;
459
+ }
460
+ if (tool.requiresConfirmation && !await askConfirmation(tool, ctx, parsed.data)) {
461
+ this.emit({
462
+ capability: tool.capability,
463
+ errorClass: "confirmation-denied",
464
+ errorCode: "confirmation-denied",
465
+ errorMessage: `confirmation required, not granted: ${tool.name}`,
466
+ latencyMs: performance.now() - start,
467
+ name,
468
+ ok: false
469
+ });
470
+ return {
471
+ code: "confirmation-denied",
472
+ error: `confirmation required, not granted: ${tool.name}`,
473
+ ok: false
474
+ };
475
+ }
476
+ try {
477
+ const result = await tool.handler(ctx, parsed.data);
478
+ this.emit({
479
+ capability: tool.capability,
480
+ errorClass: result.ok ? void 0 : "handler-error",
481
+ errorCode: result.ok ? void 0 : result.code,
482
+ errorMessage: result.ok ? void 0 : result.error,
483
+ latencyMs: performance.now() - start,
484
+ name,
485
+ ok: result.ok
486
+ });
487
+ return result;
488
+ } catch (err) {
489
+ const failure = failureFromThrown(err, this.recognizers);
490
+ this.emit({
491
+ capability: tool.capability,
492
+ errorClass: "handler-error",
493
+ errorCode: failure.code,
494
+ errorMessage: failure.error,
495
+ latencyMs: performance.now() - start,
496
+ name,
497
+ ok: false
498
+ });
499
+ return failure;
500
+ }
501
+ }
502
+ async dispatchFromModel(ctx, name, rawInput) {
503
+ const tool = this.tools.get(name);
504
+ if (tool?.agentHidden) {
505
+ const error = `tool not available to the agent: ${name}`;
506
+ this.emit({
507
+ capability: tool.capability,
508
+ errorClass: "agent-hidden",
509
+ errorCode: "forbidden",
510
+ errorMessage: error,
511
+ latencyMs: 0,
512
+ name,
513
+ ok: false
514
+ });
515
+ return {
516
+ code: "forbidden",
517
+ error,
518
+ ok: false
519
+ };
520
+ }
521
+ return this.dispatchUnsafe(ctx, name, rawInput);
522
+ }
523
+ dispatch(ctx, name, rawInput) {
524
+ return this.dispatchUnsafe(ctx, name, rawInput);
525
+ }
526
+ };
527
+ const isStudioToolName = (name) => Object.hasOwn(studioToolContracts, name);
528
+ const build = (builder, handlers) => {
529
+ const entries = Object.entries(handlers).filter(([, entry]) => entry !== void 0);
530
+ const unknown = entries.flatMap(([name]) => isStudioToolName(name) ? [] : [`"${name}"`]);
531
+ if (unknown.length > 0) throw new MountayaElementsError(`${builder}: no studio tool is named ${unknown.join(", ")}. A handler map is keyed by studio tool names: correct the key, or register a tool of your own with bus.register().`);
532
+ const registry = {};
533
+ for (const [name, entry] of entries) {
534
+ if (entry === void 0 || !isStudioToolName(name)) continue;
535
+ const definition = typeof entry === "function" ? { handler: entry } : entry;
536
+ registry[name] = {
537
+ ...studioToolContracts[name],
538
+ ...definition,
539
+ name
540
+ };
541
+ }
542
+ return registry;
543
+ };
544
+ const registerStudioTools = (bus, handlers) => {
545
+ const registry = build("registerStudioTools", handlers);
546
+ bus.registerAll(registry);
547
+ return registry;
548
+ };
549
+ const studioRegistry = () => (handlers) => build("studioRegistry", handlers);
550
+ const editorReservationInitialState = { editorReservation: null };
551
+ const createEditorReservationSlice = (set) => ({
552
+ releaseEditor: (mark) => set((state) => state.editorReservation === mark ? { editorReservation: null } : {}),
553
+ reserveEditor: (mark) => set({ editorReservation: mark })
554
+ });
555
+ const formsUnsavedInitialState = {
556
+ itineraryFormUnsaved: false,
557
+ waypointDetailsUnsaved: false
558
+ };
559
+ const memberOf = {
560
+ itinerary: "itineraryFormUnsaved",
561
+ waypointDetails: "waypointDetailsUnsaved"
562
+ };
563
+ const createFormsUnsavedSlice = (set) => ({ setFormUnsaved: (form, unsaved) => set((state) => state[memberOf[form]] === unsaved ? {} : { [memberOf[form]]: unsaved }) });
564
+ const embedInitialState = { embed: null };
565
+ const createEmbedSlice = (set) => ({ setEmbed: (embed) => set({ embed }) });
566
+ const selectEmbed = (state) => state.embed;
567
+ const embedContentInitialState = { embedContent: null };
568
+ const createEmbedContentSlice = (set) => ({ setEmbedContent: (embedContent) => set({ embedContent }) });
569
+ const selectEmbedContent = (state) => state.embedContent;
570
+ const draftSurfaceNames = Object.freeze({
571
+ import: "import",
572
+ suggest: "suggest-itineraries"
573
+ });
574
+ const showingDraftSurface = (state) => {
575
+ if (state.openContent === "import") return state.importSession === null ? null : "import";
576
+ if (state.openContent === "suggest") return state.suggestSession === null ? null : "suggest";
577
+ return null;
578
+ };
579
+ const showingDraftSession = (state) => {
580
+ const surface = showingDraftSurface(state);
581
+ if (surface === null) return null;
582
+ const session = surface === "import" ? state.importSession : state.suggestSession;
583
+ return session?.draft ? session : null;
584
+ };
585
+ const showingDraft = (state) => showingDraftSession(state)?.draft ?? null;
586
+ const draftSessionIdentity = (state, surface) => {
587
+ const session = surface === "import" ? state.importSession : state.suggestSession;
588
+ return session === null ? null : {
589
+ draftId: session.draftId,
590
+ sessionId: session.sessionId
591
+ };
592
+ };
593
+ const holdsDraftSession = (state, surface, sent) => {
594
+ const standing = draftSessionIdentity(state, surface);
595
+ return sent !== null && standing !== null && standing.sessionId === sent.sessionId && standing.draftId === sent.draftId;
596
+ };
597
+ const holdDuringDraftCommit = (ctx, surface, verb) => ctx.ui.getState().editorReservation?.session === surface ? {
598
+ code: "conflict",
599
+ error: `${verb}: the ${draftSurfaceNames[surface]} draft is being saved; send it again once its commit has settled`,
600
+ ok: false
601
+ } : null;
602
+ const holdDuringPreview = (ctx, surface, verb) => {
603
+ const status = surface === "import" ? ctx.ui.getState().importSession?.status : void 0;
604
+ return status?.kind === "settling" || status?.kind === "previewing" ? {
605
+ code: "conflict",
606
+ error: `${verb}: the ${draftSurfaceNames[surface]} draft is being previewed again for a changed option; send it again once the preview lands`,
607
+ ok: false
608
+ } : null;
609
+ };
610
+ const holdDraftWrite = (ctx, surface, verb) => holdDuringDraftCommit(ctx, surface, verb) ?? holdDuringPreview(ctx, surface, verb);
611
+ const holdShowingDraft = (ctx, verb) => {
612
+ const surface = showingDraftSurface(ctx.ui.getState());
613
+ return surface === null ? null : holdDraftWrite(ctx, surface, verb);
614
+ };
615
+ let minted = 0;
616
+ const mintSessionIdentity = () => {
617
+ minted += 1;
618
+ return minted;
619
+ };
620
+ const editedDraftIdentity = (session, draft) => {
621
+ if (draft === null) return null;
622
+ return session.draft !== null && session.draftId !== null ? session.draftId : mintSessionIdentity();
623
+ };
624
+ const importSessionInitialState = { importSession: null };
625
+ const createImportSessionSlice = (set) => ({
626
+ closeImport: () => set({ importSession: null }),
627
+ openImport: (provider) => set({ importSession: {
628
+ activityId: null,
629
+ collectionIds: [],
630
+ draft: null,
631
+ draftGranularity: null,
632
+ draftId: null,
633
+ file: null,
634
+ granularity: "auto",
635
+ isPrivate: true,
636
+ name: "",
637
+ organizationId: null,
638
+ preview: null,
639
+ provider,
640
+ sessionId: mintSessionIdentity(),
641
+ status: { kind: "idle" }
642
+ } }),
643
+ removeImportDraftSegment: (segmentId) => set((state) => {
644
+ const draft = state.importSession?.draft;
645
+ if (!state.importSession || !draft) return state;
646
+ return { importSession: {
647
+ ...state.importSession,
648
+ draft: {
649
+ ...draft,
650
+ segments: draft.segments.filter((segment) => segment.id !== segmentId)
651
+ }
652
+ } };
653
+ }),
654
+ setImportActivity: (activityId) => set((state) => state.importSession ? { importSession: {
655
+ ...state.importSession,
656
+ activityId
657
+ } } : state),
658
+ setImportCollections: (collectionIds) => set((state) => state.importSession ? { importSession: {
659
+ ...state.importSession,
660
+ collectionIds
661
+ } } : state),
662
+ setImportDraft: (draft) => set((state) => {
663
+ const session = state.importSession;
664
+ if (!session) return state;
665
+ return { importSession: {
666
+ ...session,
667
+ draft,
668
+ draftGranularity: draft === null ? null : session.draftGranularity,
669
+ draftId: editedDraftIdentity(session, draft)
670
+ } };
671
+ }),
672
+ setImportDraftSegmentSpeed: (segmentId, speed) => set((state) => {
673
+ const draft = state.importSession?.draft;
674
+ if (!state.importSession || !draft) return state;
675
+ return { importSession: {
676
+ ...state.importSession,
677
+ draft: {
678
+ ...draft,
679
+ segments: draft.segments.map((segment) => segment.id === segmentId ? {
680
+ ...segment,
681
+ speed
682
+ } : segment)
683
+ }
684
+ } };
685
+ }),
686
+ setImportFile: (file) => set((state) => state.importSession ? { importSession: {
687
+ ...state.importSession,
688
+ file
689
+ } } : state),
690
+ setImportGranularity: (granularity) => set((state) => state.importSession ? { importSession: {
691
+ ...state.importSession,
692
+ granularity
693
+ } } : state),
694
+ setImportName: (name) => set((state) => state.importSession ? { importSession: {
695
+ ...state.importSession,
696
+ name
697
+ } } : state),
698
+ setImportOrganization: (organizationId) => set((state) => state.importSession ? { importSession: {
699
+ ...state.importSession,
700
+ organizationId
701
+ } } : state),
702
+ setImportPreview: (preview) => set((state) => state.importSession ? { importSession: {
703
+ ...state.importSession,
704
+ preview
705
+ } } : state),
706
+ setImportPrivate: (isPrivate) => set((state) => state.importSession ? { importSession: {
707
+ ...state.importSession,
708
+ isPrivate
709
+ } } : state),
710
+ setImportProvider: (provider) => set((state) => state.importSession ? { importSession: {
711
+ ...state.importSession,
712
+ provider
713
+ } } : state),
714
+ setImportStatus: (status) => set((state) => state.importSession ? { importSession: {
715
+ ...state.importSession,
716
+ status
717
+ } } : state),
718
+ stageImportDraft: (draft, granularity) => set((state) => state.importSession ? { importSession: {
719
+ ...state.importSession,
720
+ draft,
721
+ draftGranularity: granularity ?? null,
722
+ draftId: mintSessionIdentity()
723
+ } } : state)
724
+ });
725
+ z$1.object({ itineraryId: z$1.string() });
726
+ const itineraryDuplicateInitialState = { itineraryDuplicate: null };
727
+ const createItineraryDuplicateSlice = (set) => ({ setItineraryDuplicate: (itineraryDuplicate) => set({ itineraryDuplicate }) });
728
+ const suggestSessionInitialState = { suggestSession: null };
729
+ const createSuggestSessionSlice = (set) => ({
730
+ closeSuggest: () => set({ suggestSession: null }),
731
+ openSuggest: (options) => set({ suggestSession: {
732
+ activityId: null,
733
+ agentSelected: false,
734
+ ascentMeters: null,
735
+ candidates: [],
736
+ collectionIds: [],
737
+ distanceMeters: 1e4,
738
+ draft: null,
739
+ draftId: null,
740
+ end: null,
741
+ exhausted: false,
742
+ isPrivate: true,
743
+ name: "",
744
+ organizationId: null,
745
+ picking: options?.picking === void 0 ? "start" : options.picking,
746
+ routeType: "loop",
747
+ seenSeeds: [],
748
+ selectedSeed: null,
749
+ sessionId: mintSessionIdentity(),
750
+ speedKmh: null,
751
+ start: null,
752
+ status: { kind: "idle" },
753
+ targetSegmentId: null
754
+ } }),
755
+ selectSuggestionCandidate: (seed) => set((state) => state.suggestSession ? { suggestSession: {
756
+ ...state.suggestSession,
757
+ selectedSeed: seed
758
+ } } : state),
759
+ setSuggestActivity: (activityId) => set((state) => state.suggestSession ? { suggestSession: {
760
+ ...state.suggestSession,
761
+ activityId
762
+ } } : state),
763
+ setSuggestAgentSelected: (agentSelected) => set((state) => state.suggestSession ? { suggestSession: {
764
+ ...state.suggestSession,
765
+ agentSelected
766
+ } } : state),
767
+ setSuggestAscent: (ascentMeters) => set((state) => state.suggestSession ? { suggestSession: {
768
+ ...state.suggestSession,
769
+ ascentMeters
770
+ } } : state),
771
+ setSuggestCollections: (collectionIds) => set((state) => state.suggestSession ? { suggestSession: {
772
+ ...state.suggestSession,
773
+ collectionIds
774
+ } } : state),
775
+ setSuggestDistance: (distanceMeters) => set((state) => state.suggestSession ? { suggestSession: {
776
+ ...state.suggestSession,
777
+ distanceMeters
778
+ } } : state),
779
+ setSuggestDraft: (draft) => set((state) => {
780
+ const session = state.suggestSession;
781
+ if (!session) return state;
782
+ return { suggestSession: {
783
+ ...session,
784
+ draft,
785
+ draftId: editedDraftIdentity(session, draft)
786
+ } };
787
+ }),
788
+ setSuggestEnd: (end) => set((state) => state.suggestSession ? { suggestSession: {
789
+ ...state.suggestSession,
790
+ end
791
+ } } : state),
792
+ setSuggestionCandidates: (candidates, seenSeeds, exhausted = false) => set((state) => {
793
+ const session = state.suggestSession;
794
+ if (!session) return state;
795
+ const selectedSeed = session.selectedSeed !== null && candidates.some((candidate) => candidate.seed === session.selectedSeed) ? session.selectedSeed : null;
796
+ return { suggestSession: {
797
+ ...session,
798
+ candidates,
799
+ exhausted,
800
+ seenSeeds,
801
+ selectedSeed
802
+ } };
803
+ }),
804
+ setSuggestionStatus: (status) => set((state) => state.suggestSession ? { suggestSession: {
805
+ ...state.suggestSession,
806
+ status
807
+ } } : state),
808
+ setSuggestName: (name) => set((state) => state.suggestSession ? { suggestSession: {
809
+ ...state.suggestSession,
810
+ name
811
+ } } : state),
812
+ setSuggestOrganization: (organizationId) => set((state) => state.suggestSession ? { suggestSession: {
813
+ ...state.suggestSession,
814
+ organizationId
815
+ } } : state),
816
+ setSuggestPicking: (picking) => set((state) => state.suggestSession ? { suggestSession: {
817
+ ...state.suggestSession,
818
+ picking
819
+ } } : state),
820
+ setSuggestPrivate: (isPrivate) => set((state) => state.suggestSession ? { suggestSession: {
821
+ ...state.suggestSession,
822
+ isPrivate
823
+ } } : state),
824
+ setSuggestRouteType: (routeType) => set((state) => state.suggestSession ? { suggestSession: {
825
+ ...state.suggestSession,
826
+ routeType
827
+ } } : state),
828
+ setSuggestSpeed: (speedKmh) => set((state) => state.suggestSession ? { suggestSession: {
829
+ ...state.suggestSession,
830
+ speedKmh
831
+ } } : state),
832
+ setSuggestStart: (start) => set((state) => state.suggestSession ? { suggestSession: {
833
+ ...state.suggestSession,
834
+ start
835
+ } } : state),
836
+ setSuggestTargetSegment: (targetSegmentId) => set((state) => state.suggestSession ? { suggestSession: {
837
+ ...state.suggestSession,
838
+ targetSegmentId
839
+ } } : state),
840
+ stageSuggestDraft: (draft) => set((state) => state.suggestSession ? { suggestSession: {
841
+ ...state.suggestSession,
842
+ draft,
843
+ draftId: mintSessionIdentity()
844
+ } } : state),
845
+ toggleSuggestionKeep: (seed) => set((state) => {
846
+ const session = state.suggestSession;
847
+ if (!session) return state;
848
+ const target = session.candidates.find((candidate) => candidate.seed === seed);
849
+ if (!target) return state;
850
+ const keptCount = session.candidates.filter((candidate) => candidate.kept).length;
851
+ if (!target.kept && keptCount >= 3) return state;
852
+ return { suggestSession: {
853
+ ...session,
854
+ candidates: session.candidates.map((candidate) => candidate.seed === seed ? {
855
+ ...candidate,
856
+ kept: !candidate.kept
857
+ } : candidate)
858
+ } };
859
+ })
860
+ });
861
+ const gatedBooleanRules = {
862
+ withOverlaysControl: "with_overlays_control",
863
+ withProfileAnalysis: "with_profile_analysis",
864
+ withProfileElevation: "with_profile_elevation"
865
+ };
866
+ const isGatedBooleanKey = (key) => Object.hasOwn(gatedBooleanRules, key);
867
+ const isFieldRestricted = (key, safetyRules) => {
868
+ if (!safetyRules || !isGatedBooleanKey(key)) return false;
869
+ return safetyRules[gatedBooleanRules[key]] === false;
870
+ };
871
+ const allowlistUnrestricted = (allowed) => allowed.length === 0 || allowed.includes("*");
872
+ const allowlistMode = (allowed, variant) => {
873
+ if (allowed.includes("*")) return "all";
874
+ if (allowed.length === 0) return variant === "cap" ? "none" : "all";
875
+ return "specific";
876
+ };
877
+ const allowlistForMode = (mode, variant, selection) => {
878
+ if (mode === "all") return variant === "cap" ? ["*"] : [];
879
+ return mode === "none" ? [] : [...selection];
880
+ };
881
+ const clampConfigToSafetyRules = (config, safetyRules) => {
882
+ if (!safetyRules) return config;
883
+ let next = config;
884
+ for (const key of Object.keys(gatedBooleanRules).filter(isGatedBooleanKey)) if (isFieldRestricted(key, safetyRules) && next[key]) next = {
885
+ ...next,
886
+ [key]: false
887
+ };
888
+ return next;
889
+ };
890
+ const HILLSHADE_OVERLAY_SLUG = "hillshade";
891
+ const enrichmentOverlays = (layers) => layers.overlays.filter(isEnrichmentCategory).flatMap((category) => category.children);
892
+ const classicOverlays = (layers) => layers.overlays.filter((category) => !isEnrichmentCategory(category)).flatMap((category) => category.children);
893
+ const collectAttributions = (layers, activeOverlaySlug, activeEnrichments) => {
894
+ const overlays = { overlays: layers.overlays ?? [] };
895
+ const active = activeOverlaySlug === null ? null : findOverlay(overlays, activeOverlaySlug);
896
+ const enrichmentSources = activeEnrichments.flatMap((slug) => findOverlay(overlays, slug)?.sources ?? []);
897
+ const sources = [
898
+ ...layers.itineraries?.sources ?? [],
899
+ ...layers.zones?.sources ?? [],
900
+ ...active?.sources ?? [],
901
+ ...enrichmentSources
902
+ ];
903
+ const seen = /* @__PURE__ */ new Set();
904
+ const attributions = [];
905
+ for (const source of sources) {
906
+ const attribution = source.attribution?.trim();
907
+ if (attribution !== void 0 && attribution !== "" && !seen.has(attribution)) {
908
+ seen.add(attribution);
909
+ attributions.push(attribution);
910
+ }
911
+ }
912
+ if (!seen.has(BASEMAP_ATTRIBUTION)) attributions.push(BASEMAP_ATTRIBUTION);
913
+ return attributions;
914
+ };
915
+ const filterTerrains = (terrains, allowed) => {
916
+ if (allowlistUnrestricted(allowed)) return [...terrains];
917
+ const allowedSlugs = new Set(allowed);
918
+ return terrains.filter((terrain) => allowedSlugs.has(terrain.slug));
919
+ };
920
+ const filterOverlayCategories = (categories, allowed, overlaysEntitled) => {
921
+ if (!overlaysEntitled) return [];
922
+ const unrestricted = allowlistUnrestricted(allowed);
923
+ const allowedSlugs = new Set(allowed);
924
+ return categories.map((category) => ({
925
+ ...category,
926
+ children: category.children.filter((overlay) => unrestricted || allowedSlugs.has(overlay.slug))
927
+ })).filter((category) => category.children.length > 0);
928
+ };
929
+ const filterEnrichmentOverlays = (overlays, allowed, overlaysEntitled) => {
930
+ if (!overlaysEntitled) return [];
931
+ const unrestricted = allowlistUnrestricted(allowed);
932
+ const allowedSlugs = new Set(allowed);
933
+ return overlays.filter((overlay) => overlay.slug !== POIS_OVERLAY_SLUG && (unrestricted || allowedSlugs.has(overlay.slug)));
934
+ };
935
+ const findHillshadeOverlay = (layers) => findOverlay({ overlays: layers.overlays ?? [] }, HILLSHADE_OVERLAY_SLUG, "enrichment");
936
+ const toggleSlug = (slugs, slug, enabled) => {
937
+ if (slugs.includes(slug) === enabled) return slugs;
938
+ return enabled ? [...slugs, slug] : slugs.filter((active) => active !== slug);
939
+ };
940
+ const reconcilePoisEnrichment = (enrichments, groups) => {
941
+ const shouldHavePois = groups.length > 0;
942
+ return toggleSlug(enrichments, POIS_OVERLAY_SLUG$1, shouldHavePois);
943
+ };
944
+ const poiGroupsForSource = (groups, enabled) => {
945
+ if (groups.length > 0 === enabled) return groups;
946
+ return enabled ? [...DEFAULT_ENABLED_POI_GROUP_IDS] : [];
947
+ };
948
+ const knownPoiGroups = new Set(POI_GROUP_IDS);
949
+ const uniquePoiGroups = (groups) => {
950
+ const seen = /* @__PURE__ */ new Set();
951
+ const result = [];
952
+ for (const group of groups) if (knownPoiGroups.has(group) && !seen.has(group)) {
953
+ seen.add(group);
954
+ result.push(group);
955
+ }
956
+ return result;
957
+ };
958
+ const layersInitialState = {
959
+ activeEnrichments: [POIS_OVERLAY_SLUG$1],
960
+ activeOverlay: null,
961
+ activeOverlayCategorySlug: null,
962
+ activePoiGroups: [...DEFAULT_ENABLED_POI_GROUP_IDS],
963
+ overlayTimestamp: null,
964
+ poiFilterNoticeNonce: 0,
965
+ terrain: DEFAULT_TERRAIN,
966
+ terrainVariant: "light"
967
+ };
968
+ const createLayersSlice = (set, get) => ({
969
+ bumpPoiFilterNotice: () => set((state) => ({ poiFilterNoticeNonce: state.poiFilterNoticeNonce + 1 })),
970
+ setActiveOverlay: (activeOverlay) => set({ activeOverlay }),
971
+ setActiveOverlayCategorySlug: (activeOverlayCategorySlug) => set({ activeOverlayCategorySlug }),
972
+ setAllPoiGroups: (enabled) => {
973
+ get().setPoiGroups(enabled ? [...POI_GROUP_IDS] : []);
974
+ },
975
+ setEnrichment: (slug, enabled) => set((state) => {
976
+ if (slug !== POIS_OVERLAY_SLUG$1) return { activeEnrichments: toggleSlug(state.activeEnrichments, slug, enabled) };
977
+ const groups = poiGroupsForSource(state.activePoiGroups, enabled);
978
+ return {
979
+ activeEnrichments: reconcilePoisEnrichment(state.activeEnrichments, groups),
980
+ activePoiGroups: groups
981
+ };
982
+ }),
983
+ setOverlayTimestamp: (overlayTimestamp) => set({ overlayTimestamp }),
984
+ setPoiGroup: (group, enabled) => set((state) => {
985
+ if (!knownPoiGroups.has(group)) return {};
986
+ const groups = toggleSlug(state.activePoiGroups, group, enabled);
987
+ return {
988
+ activeEnrichments: reconcilePoisEnrichment(state.activeEnrichments, groups),
989
+ activePoiGroups: groups
990
+ };
991
+ }),
992
+ setPoiGroups: (groups) => set((state) => {
993
+ const next = uniquePoiGroups(groups);
994
+ return {
995
+ activeEnrichments: reconcilePoisEnrichment(state.activeEnrichments, next),
996
+ activePoiGroups: next
997
+ };
998
+ }),
999
+ setTerrain: (terrain) => set({ terrain }),
1000
+ setTerrainVariant: (terrainVariant) => set({ terrainVariant })
1001
+ });
1002
+ const resolveWrite = (handed, state) => isWriteFunction(handed) ? handed(state) : handed;
1003
+ const isWriteFunction = (handed) => typeof handed === "function";
1004
+ const searchInitialState = {
1005
+ searchQuery: "",
1006
+ searchViewportScope: true
1007
+ };
1008
+ const createSearchSlice = (set) => ({
1009
+ setSearchQuery: (searchQuery) => set({ searchQuery }),
1010
+ setSearchViewportScope: (searchViewportScope) => set({ searchViewportScope })
1011
+ });
1012
+ const directionsTargetSchema = z$1.object({
1013
+ itineraryId: z$1.string(),
1014
+ segmentId: z$1.string().nullable()
1015
+ });
1016
+ const directionsInitialState = { directionsTarget: null };
1017
+ const createDirectionsSlice = (set) => ({ setDirections: (directionsTarget) => set({ directionsTarget }) });
1018
+ const selectDirections = (state) => state.directionsTarget;
1019
+ const shareInitialState = { share: null };
1020
+ const createShareSlice = (set) => ({ setShare: (share) => set({ share }) });
1021
+ const selectShare = (state) => state.share;
1022
+ const waypointDetailsInitialState = { waypointDetailsDialog: null };
1023
+ const createWaypointDetailsSlice = (set) => ({ setWaypointDetailsDialog: (waypointDetailsDialog) => set({ waypointDetailsDialog }) });
1024
+ const selectWaypointDetails = (state) => state.waypointDetailsDialog;
1025
+ const createActiveDraftSlice = (_set, get) => ({
1026
+ removeActiveDraftSegment: (segmentId) => {
1027
+ const state = get();
1028
+ const session = showingDraftSession(state);
1029
+ if (session !== null && session === state.importSession) {
1030
+ state.removeImportDraftSegment(segmentId);
1031
+ return;
1032
+ }
1033
+ const draft = session?.draft;
1034
+ if (!draft) return;
1035
+ state.setSuggestDraft({
1036
+ ...draft,
1037
+ segments: draft.segments.filter((segment) => segment.id !== segmentId)
1038
+ });
1039
+ },
1040
+ setActiveDraft: (draft) => {
1041
+ const state = get();
1042
+ const session = showingDraftSession(state);
1043
+ if (session === null) return;
1044
+ if (session === state.importSession) {
1045
+ state.setImportDraft(draft);
1046
+ return;
1047
+ }
1048
+ state.setSuggestDraft(draft);
1049
+ },
1050
+ setActiveDraftSegmentSpeed: (segmentId, speed) => {
1051
+ const state = get();
1052
+ const session = showingDraftSession(state);
1053
+ if (session !== null && session === state.importSession) {
1054
+ state.setImportDraftSegmentSpeed(segmentId, speed);
1055
+ return;
1056
+ }
1057
+ const draft = session?.draft;
1058
+ if (!draft) return;
1059
+ state.setSuggestDraft({
1060
+ ...draft,
1061
+ segments: draft.segments.map((segment) => segment.id === segmentId ? {
1062
+ ...segment,
1063
+ speed
1064
+ } : segment)
1065
+ });
1066
+ }
1067
+ });
1068
+ const initialState = {
1069
+ ...chromeInitialState,
1070
+ ...collabInitialState,
1071
+ ...collectionsInitialState,
1072
+ ...directionsInitialState,
1073
+ ...editorReservationInitialState,
1074
+ ...formsUnsavedInitialState,
1075
+ ...embedContentInitialState,
1076
+ ...embedInitialState,
1077
+ ...importSessionInitialState,
1078
+ ...itineraryDuplicateInitialState,
1079
+ ...itineraryInitialState,
1080
+ ...layersInitialState,
1081
+ ...roadAccessDialogInitialState,
1082
+ ...searchInitialState,
1083
+ ...segmentEditInitialState,
1084
+ ...segmentGroupEditInitialState,
1085
+ ...segmentSplitInitialState,
1086
+ ...shareInitialState,
1087
+ ...suggestSessionInitialState,
1088
+ ...videoExportInitialState,
1089
+ ...waypointDetailsInitialState,
1090
+ ...waypointEditInitialState,
1091
+ ...zoneEditInitialState
1092
+ };
1093
+ const embedUiBaseline = {
1094
+ activeEnrichments: [],
1095
+ activePoiGroups: []
1096
+ };
1097
+ const createUiStore = (overrides) => createStore(withUnchangedWritesDropped((set, get, store) => ({
1098
+ ...initialState,
1099
+ ...overrides,
1100
+ ...createActiveDraftSlice(set, get, store),
1101
+ ...createChromeSlice(set, get, store),
1102
+ ...createCollabSlice(set, get, store),
1103
+ ...createCollectionsSlice(set, get, store),
1104
+ ...createDirectionsSlice(set, get, store),
1105
+ ...createEditorReservationSlice(set, get, store),
1106
+ ...createFormsUnsavedSlice(set, get, store),
1107
+ ...createEmbedContentSlice(set, get, store),
1108
+ ...createEmbedSlice(set, get, store),
1109
+ ...createImportSessionSlice(set, get, store),
1110
+ ...createItineraryDuplicateSlice(set, get, store),
1111
+ ...createItinerarySlice(set, get, store),
1112
+ ...createLayersSlice(set, get, store),
1113
+ ...createRoadAccessDialogSlice(set, get, store),
1114
+ ...createSearchSlice(set, get, store),
1115
+ ...createSegmentEditSlice(set, get, store),
1116
+ ...createSegmentGroupEditSlice(set, get, store),
1117
+ ...createSegmentSplitSlice(set, get, store),
1118
+ ...createShareSlice(set, get, store),
1119
+ ...createSuggestSessionSlice(set, get, store),
1120
+ ...createVideoExportSlice(set, get, store),
1121
+ ...createWaypointDetailsSlice(set, get, store),
1122
+ ...createWaypointEditSlice(set, get, store),
1123
+ ...createZoneEditSlice(set, get, store)
1124
+ })));
1125
+ const withUnchangedWritesDropped = (creator) => (set, get, store) => {
1126
+ const dropping = (...write) => {
1127
+ if (write[1] === true) {
1128
+ set(write[0], true);
1129
+ return;
1130
+ }
1131
+ const [handed] = write;
1132
+ set((state) => {
1133
+ const patch = resolveWrite(handed, state);
1134
+ return changesNothing(patch, state) ? state : patch;
1135
+ });
1136
+ };
1137
+ store.setState = dropping;
1138
+ return creator(dropping, get, store);
1139
+ };
1140
+ const changesNothing = (patch, state) => {
1141
+ for (const key in patch) if (Object.hasOwn(patch, key) && !Object.is(patch[key], state[key])) return false;
1142
+ return true;
1143
+ };
1144
+ const selectProfilePaceKmh = (itineraryId) => (state) => {
1145
+ const override = state.profilePace;
1146
+ if (!override || !itineraryId || override.itineraryId !== itineraryId) return null;
1147
+ return override.speedKmh;
1148
+ };
1149
+ const selectProfileSheetSnap = (state) => state.profileSheetSnap;
1150
+ const selectSegmentViaPrompt = (state) => state.segmentViaPrompt;
1151
+ const selectActiveDraftSession = (state) => showingDraftSession(state);
1152
+ const selectActiveDraft = (state) => showingDraft(state);
1153
+ const selectBaseMapLocked = (state) => selectActiveEditEngine(state) !== null;
1154
+ const selectZoneEditDirty = (state) => isZoneGeometryDirty(state.zoneEditSession);
1155
+ const selectZoneCreateSetup = (state) => state.openContent === "zone" && state.activeZone === null && state.zoneEditSession === null;
1156
+ const selectEditDirtyTick = (state) => state.editDirtyTick;
1157
+ const selectVideoExport = (state) => state.videoExport;
1158
+ const selectVideoExportPlan = (state) => state.videoExport?.plan ?? null;
1159
+ const selectVideoExportRoute = (state) => state.videoExport?.route ?? null;
1160
+ const selectVideoExportStatus = (state) => state.videoExport?.status ?? null;
1161
+ const selectImportSession = (state) => state.importSession;
1162
+ const selectSelectedSuggestionCandidate = (state) => {
1163
+ const session = state.suggestSession;
1164
+ if (!session || session.draft) return null;
1165
+ return selectedCandidate(session);
1166
+ };
1167
+ const selectAgentHandoffArmed = (state) => {
1168
+ const handoff = state.agentHandoff;
1169
+ if (!handoff) return false;
1170
+ const armed = agentHandoffTarget(state);
1171
+ return armed !== null && armed.kind === handoff.kind && armed.id === handoff.id;
1172
+ };
1173
+ const declaredBody = (value, fields) => {
1174
+ const body = {};
1175
+ for (const key of Object.keys(fields)) {
1176
+ const member = Reflect.get(value, key);
1177
+ if (Object.hasOwn(value, key) && member !== void 0) body[key] = member;
1178
+ }
1179
+ return body;
1180
+ };
1181
+ const CONFLICT = "CONFLICT";
1182
+ const ANSWER_UNAVAILABLE = "IDEMPOTENCY_ANSWER_UNAVAILABLE";
1183
+ const KEY_IN_USE = "IDEMPOTENCY_KEY_IN_USE";
1184
+ const PRECONDITION_FAILED_STATUS = 412;
1185
+ const REVISION_CONFLICT_NAME = "RevisionConflictError";
1186
+ var RevisionConflictError = class extends MountayaElementsError {
1187
+ name = REVISION_CONFLICT_NAME;
1188
+ };
1189
+ const SEGMENT_DELETE_NOT_EDGE_NAME = "SegmentDeleteNotEdgeError";
1190
+ var SegmentDeleteNotEdgeError = class extends MountayaElementsError {
1191
+ name = SEGMENT_DELETE_NOT_EDGE_NAME;
1192
+ detail;
1193
+ constructor(message, detail, options) {
1194
+ super(message, options);
1195
+ this.detail = detail;
1196
+ }
1197
+ };
1198
+ const errorName = (error) => {
1199
+ if (typeof error !== "object" || error === null || !("name" in error)) return;
1200
+ return typeof error.name === "string" ? error.name : void 0;
1201
+ };
1202
+ const isRevisionConflict = (error) => errorName(error) === REVISION_CONFLICT_NAME;
1203
+ const isSegmentDeleteNotEdge = (error) => errorName(error) === SEGMENT_DELETE_NOT_EDGE_NAME;
1204
+ const isFailureEntry = (value) => typeof value === "object" && value !== null && "message" in value && typeof value.message === "string";
1205
+ const apiFailure = (error) => {
1206
+ if (typeof error !== "object" || error === null || !("status" in error && "errors" in error)) return;
1207
+ if (typeof error.status !== "number" || !Array.isArray(error.errors)) return;
1208
+ return {
1209
+ entries: error.errors.filter(isFailureEntry),
1210
+ status: error.status
1211
+ };
1212
+ };
1213
+ const isAnswerUnavailable = (error) => {
1214
+ const failure = apiFailure(error);
1215
+ return failure?.status === 409 && failure.entries[0]?.extensions?.code === ANSWER_UNAVAILABLE;
1216
+ };
1217
+ const isKeyInUse = (error) => {
1218
+ const failure = apiFailure(error);
1219
+ return failure?.status === 409 && failure.entries[0]?.extensions?.code === KEY_IN_USE;
1220
+ };
1221
+ const madeAnswerOf = (error) => {
1222
+ if (!isAnswerUnavailable(error)) return;
1223
+ const answer = memberOf$1(error, "answer");
1224
+ const etag = memberOf$1(answer, "etag");
1225
+ const location = memberOf$1(answer, "location");
1226
+ return {
1227
+ etag: typeof etag === "string" && etag !== "" ? etag : void 0,
1228
+ location: typeof location === "string" && location !== "" ? location : void 0
1229
+ };
1230
+ };
1231
+ const createdIdOf = (answer) => {
1232
+ if (answer.location === void 0) return;
1233
+ const [path = ""] = answer.location.split(/[?#]/, 1);
1234
+ const id = path.split("/").findLast((segment) => segment !== "");
1235
+ return id === void 0 ? void 0 : decodeURIComponent(id);
1236
+ };
1237
+ const reconcileMadeWrite = async (write, made) => {
1238
+ try {
1239
+ return await write();
1240
+ } catch (error) {
1241
+ const answer = madeAnswerOf(error);
1242
+ if (answer === void 0) throw error;
1243
+ return made(answer);
1244
+ }
1245
+ };
1246
+ const isChainShapeRefusal = (failure, error) => failure.status === 409 && failure.entries[0]?.extensions?.code === CONFLICT && lockHolderOf(error) === void 0;
1247
+ const rethrowSegmentWriteError = (error, write) => {
1248
+ if (isAnswerUnavailable(error) || isKeyInUse(error)) throw error;
1249
+ const failure = apiFailure(error);
1250
+ if (failure !== void 0) {
1251
+ const message = error instanceof Error ? error.message : "";
1252
+ if (write === "delete" && isChainShapeRefusal(failure, error)) throw new SegmentDeleteNotEdgeError(message, failure.entries[0]?.message, { cause: error });
1253
+ if (failure.status === PRECONDITION_FAILED_STATUS || failure.status === 409 && lockHolderOf(error) === void 0) throw new RevisionConflictError(message, { cause: error });
1254
+ }
1255
+ throw error;
1256
+ };
1257
+ const hasErrorCode = (error, code) => apiFailure(error)?.entries.some((entry) => entry.extensions?.code === code) ?? false;
1258
+ const isPreconditionFailed = (error) => apiFailure(error)?.status === PRECONDITION_FAILED_STATUS;
1259
+ const withSegmentAnalysis = (segment) => ({
1260
+ ...segment,
1261
+ slope_info: segment.slope_info ?? [],
1262
+ steps: segment.steps ?? [],
1263
+ surface_info: segment.surface_info ?? [],
1264
+ trail_difficulty_info: segment.trail_difficulty_info ?? [],
1265
+ way_type_info: segment.way_type_info ?? []
1266
+ });
1267
+ const withItineraryAnalysis = (itinerary) => ({
1268
+ ...itinerary,
1269
+ segments: itinerary.segments.map(withSegmentAnalysis)
1270
+ });
1271
+ const fetchItineraryRecord = async (client, itineraryId, surface) => {
1272
+ const body = await client.studio.itineraries.getItinerary({
1273
+ itinerary_id: itineraryId,
1274
+ query: surface === "published" ? { surface: "published" } : void 0
1275
+ });
1276
+ return withItineraryAnalysis(body.data);
1277
+ };
1278
+ const SPLIT_PICK_GESTURE = "split-pick";
1279
+ const selectEditorTakenBy = (state) => {
1280
+ const active = selectActiveEditEngine(state);
1281
+ if (active) return active.kind;
1282
+ if (state.segmentSplitPick !== null) return SPLIT_PICK_GESTURE;
1283
+ return state.editorReservation?.kind ?? null;
1284
+ };
1285
+ const samePoint = (a, b) => a === null || b === null ? a === b : a[0] === b[0] && a[1] === b[1];
1286
+ const isWaypointDraftDirty = (session) => {
1287
+ if (session === null) return false;
1288
+ const { draft, savedDraft } = session;
1289
+ if (savedDraft === null) return true;
1290
+ return draft.color !== savedDraft.color || draft.icon !== savedDraft.icon || draft.name !== savedDraft.name || !samePoint(draft.lngLat, savedDraft.lngLat) || draft.poiSeed?.sourceFeatureId !== savedDraft.poiSeed?.sourceFeatureId;
1291
+ };
1292
+ const isZoneWorkUnsaved = (state) => isZoneGeometryDirty(state.zoneEditSession) || state.zoneFormUnsaved;
1293
+ const selectUnsavedWork = (state) => isSegmentDraftDirty(state.segmentEditSession) || isWaypointDraftDirty(state.waypointEditSession) || isZoneWorkUnsaved(state) || state.itineraryFormUnsaved || state.waypointDetailsUnsaved || showingDraft(state) !== null;
1294
+ const lngLatOf = (position) => {
1295
+ const [lng, lat] = position ?? [];
1296
+ return lng !== void 0 && lat !== void 0 && Number.isFinite(lng) && Number.isFinite(lat) ? [lng, lat] : null;
1297
+ };
1298
+ const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1299
+ const hasUuidShape = (value) => uuidPattern.test(value);
1300
+ const indexById = (segments) => {
1301
+ const indices = /* @__PURE__ */ new Map();
1302
+ for (const [index, segment] of segments.entries()) indices.set(segment.id, index);
1303
+ return indices;
1304
+ };
1305
+ const runBoundsFrom = (indices, ids) => {
1306
+ const seen = /* @__PURE__ */ new Set();
1307
+ let first = Number.POSITIVE_INFINITY;
1308
+ let last = Number.NEGATIVE_INFINITY;
1309
+ for (const id of ids) {
1310
+ const index = indices.get(id);
1311
+ if (index === void 0 || seen.has(id)) return null;
1312
+ seen.add(id);
1313
+ first = Math.min(first, index);
1314
+ last = Math.max(last, index);
1315
+ }
1316
+ if (seen.size === 0) return null;
1317
+ return last - first + 1 === seen.size ? {
1318
+ first,
1319
+ last
1320
+ } : null;
1321
+ };
1322
+ const contiguousRunBounds = (segments, ids) => runBoundsFrom(indexById(segments), ids);
1323
+ const isContiguousRun = (segments, ids) => contiguousRunBounds(segments, ids) !== null;
1324
+ const toggleableSegmentIds = (segments, keptIds) => {
1325
+ const indices = indexById(segments);
1326
+ const keptList = [...keptIds];
1327
+ const kept = new Set(keptList);
1328
+ const toggleable = /* @__PURE__ */ new Set();
1329
+ if (kept.size === 0) {
1330
+ for (const segment of segments) toggleable.add(segment.id);
1331
+ return toggleable;
1332
+ }
1333
+ const bounds = runBoundsFrom(indices, keptList);
1334
+ if (bounds !== null) {
1335
+ const head = segments[bounds.first];
1336
+ const tail = segments[bounds.last];
1337
+ if (head && tail && bounds.last > bounds.first) {
1338
+ toggleable.add(head.id);
1339
+ toggleable.add(tail.id);
1340
+ }
1341
+ const above = bounds.first > 0 ? segments[bounds.first - 1] : void 0;
1342
+ const below = segments[bounds.last + 1];
1343
+ if (above) toggleable.add(above.id);
1344
+ if (below) toggleable.add(below.id);
1345
+ return toggleable;
1346
+ }
1347
+ for (const segment of segments) {
1348
+ const candidate = kept.has(segment.id) ? keptList.filter((id) => id !== segment.id) : [...keptList, segment.id];
1349
+ if (runBoundsFrom(indices, candidate) !== null) toggleable.add(segment.id);
1350
+ }
1351
+ return toggleable;
1352
+ };
1353
+ const mergedViaCount = (head, tail) => {
1354
+ const headVias = extractVias(head.geojson);
1355
+ const tailVias = extractVias(tail.geojson);
1356
+ const junction = headVias.at(-1);
1357
+ const opening = tailVias.at(0);
1358
+ if (junction === void 0 || opening === void 0) return headVias.length + tailVias.length;
1359
+ const [junctionLng, junctionLat] = junction;
1360
+ const [openingLng, openingLat] = opening;
1361
+ const shared = junctionLng === openingLng && junctionLat === openingLat;
1362
+ return headVias.length + tailVias.length - (shared ? 1 : 0);
1363
+ };
1364
+ const exceedsMergeViaCeiling = (head, tail) => head.mode === "directions" && mergedViaCount(head, tail) > DIRECTIONS_VIA_MAX;
1365
+ const splitPickVerdict = (geojson, lngLat, toleranceMeters) => {
1366
+ const projection = projectOnSegment(geojson, lngLat);
1367
+ if (!projection) return {
1368
+ code: "invalid-input",
1369
+ ok: false
1370
+ };
1371
+ if (!(projection.distanceMeters <= toleranceMeters)) return {
1372
+ code: "split-too-far",
1373
+ ok: false,
1374
+ projection
1375
+ };
1376
+ const { fraction } = projection;
1377
+ if (isSplitOnEnd(geojson, fraction)) return {
1378
+ code: "split-on-end",
1379
+ ok: false,
1380
+ projection
1381
+ };
1382
+ return {
1383
+ fraction,
1384
+ ok: true,
1385
+ projection
1386
+ };
1387
+ };
1388
+ const isSplitOnEnd = (geojson, fraction) => {
1389
+ const lengthMeters = segmentLengthMeters(geojson);
1390
+ const headMeters = lengthMeters * fraction;
1391
+ return fraction <= 0 || fraction >= 1 || headMeters < 10 || lengthMeters - headMeters < 10;
1392
+ };
1393
+ const resolveViewerUnits = (preferences) => ({
1394
+ language: preferences?.language || defaultUnits.language,
1395
+ length: preferences?.length ?? defaultUnits.length,
1396
+ pace: preferences?.pace ?? defaultUnits.pace,
1397
+ slope: preferences?.slope ?? defaultUnits.slope,
1398
+ temperature: preferences?.temperature ?? defaultUnits.temperature
1399
+ });
1400
+ const makeWaypointId = (ids = studioSeamAbsences.ids) => ids.next();
1401
+ export { classicOverlays as $, embedUiBaseline as A, describeInvalidInput as At, selectSelectedSuggestionCandidate as B, isPreconditionFailed as C, registerStudioTools as Ct, rethrowSegmentWriteError as D, toolCapabilitySchema as Dt, reconcileMadeWrite as E, confirmationToneSchema as Et, selectEditDirtyTick as F, selectZoneCreateSetup as G, selectVideoExportPlan as H, selectImportSession as I, selectShare as J, selectZoneEditDirty as K, selectProfilePaceKmh as L, selectActiveDraftSession as M, selectAgentHandoffArmed as N, declaredBody as O, toolConfirmationSchema as Ot, selectBaseMapLocked as P, POIS_OVERLAY_SLUG$1 as Q, selectProfileSheetSnap as R, isKeyInUse as S, selectEmbed as St, isSegmentDeleteNotEdge as T, ToolBus as Tt, selectVideoExportRoute as U, selectVideoExport as V, selectVideoExportStatus as W, selectDirections as X, directionsTargetSchema as Y, HILLSHADE_OVERLAY_SLUG as Z, withSegmentAnalysis as _, holdsDraftSession as _t, exceedsMergeViaCeiling as a, findHillshadeOverlay as at, hasErrorCode as b, showingDraftSurface as bt, toggleableSegmentIds as c, allowlistUnrestricted as ct, isZoneWorkUnsaved as d, draftSessionIdentity as dt, collectAttributions as et, selectUnsavedWork as f, draftSurfaceNames as ft, withItineraryAnalysis as g, holdShowingDraft as gt, fetchItineraryRecord as h, holdDuringPreview as ht, splitPickVerdict as i, filterTerrains as it, selectActiveDraft as j, createUiStore as k, toolErrorCodeSchema as kt, hasUuidShape as l, clampConfigToSafetyRules as lt, selectEditorTakenBy as m, holdDuringDraftCommit as mt, resolveViewerUnits as n, filterEnrichmentOverlays as nt, contiguousRunBounds as o, allowlistForMode as ot, SPLIT_PICK_GESTURE as p, holdDraftWrite as pt, selectWaypointDetails as q, isSplitOnEnd as r, filterOverlayCategories as rt, isContiguousRun as s, allowlistMode as st, makeWaypointId as t, enrichmentOverlays as tt, lngLatOf as u, isFieldRestricted as ut, SegmentDeleteNotEdgeError as v, showingDraft as vt, isRevisionConflict as w, studioRegistry as wt, isAnswerUnavailable as x, selectEmbedContent as xt, createdIdOf as y, showingDraftSession as yt, selectSegmentViaPrompt as z };
1402
+
1403
+ //# sourceMappingURL=chunk-BSHTsFiB.js.map