@aceshooting/lyra-ui 30.5.0 → 30.7.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 (203) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +1 -1
  3. package/dist/components/agent-tools/artifact-panel/artifact-panel.class.d.ts +7 -4
  4. package/dist/components/agent-tools/artifact-panel/artifact-panel.class.js +5 -5
  5. package/dist/components/conversation/code-block/onig.provenance.json +1 -1
  6. package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
  7. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  8. package/dist/components/conversation/markdown/markdown-core.class.d.ts +11 -1
  9. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  10. package/dist/components/conversation/markdown/markdown-progressive.js +2 -2
  11. package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
  12. package/dist/components/conversation/markdown/markdown-shared.js +3 -3
  13. package/dist/components/conversation/markdown/markdown.class.d.ts +11 -1
  14. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  15. package/dist/components/conversation/message-parts/message-parts.class.d.ts +1 -1
  16. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  17. package/dist/components/conversation/message-parts/message-parts.d.ts +1 -1
  18. package/dist/components/conversation/model-select/model-select.class.d.ts +8 -1
  19. package/dist/components/conversation/model-select/model-select.class.js +2 -2
  20. package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +5 -0
  21. package/dist/components/conversation/streaming-text/streaming-text-base.class.js +2 -2
  22. package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
  23. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
  24. package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
  25. package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
  26. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +6 -0
  27. package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
  28. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +9 -2
  29. package/dist/components/conversation/voice-picker/voice-picker.class.js +2 -2
  30. package/dist/components/conversation/widget-renderer/default-registry.js +1 -1
  31. package/dist/components/conversation/widget-renderer/registry.d.ts +1 -27
  32. package/dist/components/conversation/widget-renderer/registry.js +1 -1
  33. package/dist/components/conversation/widget-renderer/resolve.d.ts +1 -29
  34. package/dist/components/conversation/widget-renderer/resolve.js +1 -1
  35. package/dist/components/conversation/widget-renderer/widget-renderer.class.d.ts +1 -1
  36. package/dist/components/conversation/widget-renderer/widget-renderer.class.js +1 -1
  37. package/dist/components/forms/catalog-picker-base.d.ts +3 -1
  38. package/dist/components/forms/catalog-picker-base.js +3 -3
  39. package/dist/components/forms/combobox/combobox.class.d.ts +9 -2
  40. package/dist/components/forms/combobox/combobox.class.js +2 -2
  41. package/dist/components/forms/date-picker/date-input.class.d.ts +9 -2
  42. package/dist/components/forms/date-picker/date-input.class.js +2 -2
  43. package/dist/components/forms/input/input-shared.d.ts +9 -2
  44. package/dist/components/forms/input/input-shared.js +2 -2
  45. package/dist/components/forms/input/time-input.class.d.ts +9 -2
  46. package/dist/components/forms/input/time-input.class.js +2 -2
  47. package/dist/components/forms/input/time-input.styles.js +1 -1
  48. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +18 -3
  49. package/dist/components/forms/locale-picker/locale-picker.class.js +2 -2
  50. package/dist/components/forms/phone-input/phone-input.class.d.ts +9 -2
  51. package/dist/components/forms/phone-input/phone-input.class.js +2 -2
  52. package/dist/components/forms/phone-input/phone-input.styles.js +1 -1
  53. package/dist/components/forms/select/select.class.d.ts +9 -2
  54. package/dist/components/forms/select/select.class.js +2 -2
  55. package/dist/components/forms/textarea/textarea.class.d.ts +9 -2
  56. package/dist/components/forms/textarea/textarea.class.js +2 -2
  57. package/dist/components/forms/token-input/token-input.class.d.ts +9 -2
  58. package/dist/components/forms/token-input/token-input.class.js +2 -2
  59. package/dist/components/forms/token-input/token-input.styles.js +1 -1
  60. package/dist/components/layout/dock-panel/dock-panel.class.d.ts +5 -2
  61. package/dist/components/layout/dock-panel/dock-panel.styles.js +1 -1
  62. package/dist/components/layout/menu/menu-item.class.d.ts +7 -4
  63. package/dist/components/layout/menu/menu-item.class.js +3 -2
  64. package/dist/components/layout/multi-split/multi-split.class.d.ts +73 -6
  65. package/dist/components/layout/multi-split/multi-split.class.js +4 -4
  66. package/dist/components/layout/multi-split/multi-split.styles.js +1 -1
  67. package/dist/components/layout/page/page.class.d.ts +7 -0
  68. package/dist/components/layout/page/page.styles.js +1 -1
  69. package/dist/components/media/flag/language-map.js +1 -1
  70. package/dist/components/media/image-viewer/image-viewer-panorama.d.ts +1 -5
  71. package/dist/components/media/image-viewer/image-viewer-panorama.js +1 -8
  72. package/dist/components/media/image-viewer/image-viewer.class.d.ts +1 -1
  73. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  74. package/dist/components/media/map/map-control-options.d.ts +7 -3
  75. package/dist/components/media/map/map-control-options.js +1 -1
  76. package/dist/components/media/map/map-controls-lifecycle.js +1 -1
  77. package/dist/components/media/map/map-feature-loader.js +1 -1
  78. package/dist/components/media/map/map-loader.d.ts +10 -4
  79. package/dist/components/media/map/map-loader.js +1 -1
  80. package/dist/components/media/map/map-scene-admission.js +1 -0
  81. package/dist/components/media/map/map-scene-completion-adapter.js +1 -0
  82. package/dist/components/media/map/map-scene-completion-camera.js +1 -0
  83. package/dist/components/media/map/map-scene-configuration-controller.js +1 -0
  84. package/dist/components/media/map/map-scene-configuration.d.ts +15 -0
  85. package/dist/components/media/map/map-scene-configuration.js +1 -0
  86. package/dist/components/media/map/map-scene-controls.js +1 -0
  87. package/dist/components/media/map/map-scene-errors.js +1 -0
  88. package/dist/components/media/map/map-scene-line-layer.js +1 -0
  89. package/dist/components/media/map/map-scene-lines.js +1 -0
  90. package/dist/components/media/map/map-scene-owner.js +1 -0
  91. package/dist/components/media/map/map-scene-position-registry.js +1 -0
  92. package/dist/components/media/map/map-scene-render-controller.js +1 -0
  93. package/dist/components/media/map/map-scene-render-input.js +1 -0
  94. package/dist/components/media/map/map-scene-source-snapshot.js +1 -0
  95. package/dist/components/media/map/map-scene-status.js +1 -0
  96. package/dist/components/media/map/map-scene-types.d.ts +55 -0
  97. package/dist/components/media/map/map.class.d.ts +60 -12
  98. package/dist/components/media/map/map.class.js +23 -6
  99. package/dist/components/media/map/map.styles.js +1 -1
  100. package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +1 -1
  101. package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
  102. package/dist/components/media/video/video.class.d.ts +1 -1
  103. package/dist/components/media/video/video.class.js +1 -1
  104. package/dist/components/retrieval/graph/graph-builtin-3d-engine.js +1 -1
  105. package/dist/components/retrieval/graph/graph-curvature.js +1 -0
  106. package/dist/components/retrieval/graph/graph-engine-columns.js +1 -1
  107. package/dist/components/retrieval/graph/graph-model.d.ts +4 -0
  108. package/dist/components/retrieval/graph/graph-node-renderer.d.ts +13 -0
  109. package/dist/components/retrieval/graph/graph-node-renderer.js +1 -0
  110. package/dist/components/retrieval/graph/graph-source-controller.js +1 -1
  111. package/dist/components/retrieval/graph/graph-spatial-controller.js +3 -1
  112. package/dist/components/retrieval/graph/graph-spatial.js +1 -1
  113. package/dist/components/retrieval/graph/graph-webgl-engine.js +1 -1
  114. package/dist/components/retrieval/graph/graph.class.d.ts +11 -3
  115. package/dist/components/retrieval/graph/graph.class.js +4 -4
  116. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +8 -2
  117. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +4 -2
  118. package/dist/events.d.ts +36 -1
  119. package/dist/framework-types.d.ts +1 -1
  120. package/dist/internal/collection-policy.js +1 -0
  121. package/dist/internal/collection-snapshot.js +1 -1
  122. package/dist/internal/default-strings/media.generated.js +1 -1
  123. package/dist/internal/default-strings/retrieval.generated.js +1 -1
  124. package/dist/internal/engine-3d-loader.d.ts +8 -2
  125. package/dist/internal/engine-3d-loader.js +1 -1
  126. package/dist/internal/form-control.styles.js +1 -1
  127. package/dist/internal/locale-loaders.generated.js +1 -1
  128. package/dist/internal/localization-runtime.js +1 -1
  129. package/dist/internal/localization-types.d.ts +1 -1
  130. package/dist/internal/localization.js +1 -1
  131. package/dist/internal/map-camera-follow-controller.d.ts +9 -0
  132. package/dist/internal/map-camera-follow-controller.js +1 -0
  133. package/dist/internal/map-camera-follow-data.js +1 -0
  134. package/dist/internal/map-camera-follow-scene.js +1 -0
  135. package/dist/internal/map-camera-session-controller.d.ts +59 -0
  136. package/dist/internal/map-camera-session-controller.js +1 -0
  137. package/dist/internal/map-camera-session-data.d.ts +16 -0
  138. package/dist/internal/map-camera-session-data.js +1 -0
  139. package/dist/internal/map-camera-session.js +1 -0
  140. package/dist/internal/map-scene-session.js +1 -0
  141. package/dist/internal/media-panorama.d.ts +5 -0
  142. package/dist/internal/media-panorama.js +8 -0
  143. package/dist/internal/package-metadata.js +1 -1
  144. package/dist/internal/sequence-playback-binding.js +1 -0
  145. package/dist/internal/typed-columns.d.ts +3 -1
  146. package/dist/internal/typed-columns.js +1 -1
  147. package/dist/internal/variants.d.ts +7 -0
  148. package/dist/internal/widget-default-registry.js +1 -0
  149. package/dist/internal/widget-document.d.ts +29 -0
  150. package/dist/internal/widget-document.js +1 -0
  151. package/dist/internal/widget-type-registry.d.ts +27 -0
  152. package/dist/internal/widget-type-registry.js +1 -0
  153. package/dist/lyra.d.ts +1 -1
  154. package/dist/lyra.js +1 -1
  155. package/dist/map-camera-session.d.ts +10 -0
  156. package/dist/map-camera-session.js +1 -0
  157. package/dist/sequence-time-binding.d.ts +3 -0
  158. package/dist/sequence-time-binding.js +1 -0
  159. package/dist/simulation-clock.d.ts +3 -0
  160. package/dist/simulation-clock.js +1 -0
  161. package/dist/time-index.d.ts +3 -0
  162. package/dist/time-index.js +1 -0
  163. package/llms/components/lr-artifact-panel.md +8 -3
  164. package/llms/components/lr-combobox.md +2 -0
  165. package/llms/components/lr-country-picker.md +2 -0
  166. package/llms/components/lr-currency-picker.md +2 -0
  167. package/llms/components/lr-date-picker.md +2 -0
  168. package/llms/components/lr-dock-panel.md +5 -2
  169. package/llms/components/lr-graph.md +121 -3
  170. package/llms/components/lr-input.md +2 -0
  171. package/llms/components/lr-knowledge-graph-explorer.md +6 -1
  172. package/llms/components/lr-locale-picker.md +8 -1
  173. package/llms/components/lr-map.md +315 -7
  174. package/llms/components/lr-markdown-core.md +2 -1
  175. package/llms/components/lr-markdown.md +12 -1
  176. package/llms/components/lr-menu.md +5 -2
  177. package/llms/components/lr-model-select.md +2 -0
  178. package/llms/components/lr-multi-split.md +53 -4
  179. package/llms/components/lr-native-time-input.md +2 -0
  180. package/llms/components/lr-number-input.md +2 -0
  181. package/llms/components/lr-page.md +9 -1
  182. package/llms/components/lr-phone-input.md +2 -0
  183. package/llms/components/lr-select.md +2 -0
  184. package/llms/components/lr-sequence-playback.md +44 -0
  185. package/llms/components/lr-streaming-text-core.md +3 -2
  186. package/llms/components/lr-streaming-text.md +4 -1
  187. package/llms/components/lr-suggestion-chips.md +6 -2
  188. package/llms/components/lr-textarea.md +2 -0
  189. package/llms/components/lr-time-input.md +2 -0
  190. package/llms/components/lr-time-zone-picker.md +2 -0
  191. package/llms/components/lr-token-input.md +2 -0
  192. package/llms/components/lr-unit-picker.md +2 -0
  193. package/llms/components/lr-voice-picker.md +2 -0
  194. package/llms/peers.md +7 -7
  195. package/llms/shared/imports-and-registration.md +1 -1
  196. package/llms/shared/localization-and-rtl.md +15 -1
  197. package/llms/shared/testing-and-utilities.md +184 -0
  198. package/llms/shared.md +200 -2
  199. package/locales.json +1 -1
  200. package/package.json +37 -21
  201. package/registrations.json +1 -1
  202. package/skills/lyra-ui/lyra-gen.md +2 -0
  203. /package/dist/{components/media/image-viewer/image-viewer-panorama.styles.js → internal/media-panorama.styles.js} +0 -0
@@ -1,4 +1,4 @@
1
- export type MapOwnedControlKind='navigation'|'scale'|'geolocate'|'attribution';
1
+ import{type LyraMapTerrain}from'./map-scene-configuration.js';export type MapOwnedControlKind='navigation'|'scale'|'geolocate'|'globe'|'terrain'|'attribution';
2
2
  /** Corner a declarative control is added to. The corners follow text direction under RTL.*/
3
3
  export type LyraMapControlPosition='top-left'|'top-right'|'bottom-left'|'bottom-right';
4
4
  /** Unit system of the scale control.*/
@@ -7,13 +7,17 @@ export type LyraMapScaleUnit='metric'|'imperial';
7
7
  export interface LyraMapNavigationControlOptions{
8
8
  /** Corner to add the control to. Defaults to `'top-right'`.*/
9
9
  readonly position?:LyraMapControlPosition;
10
- /** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, attribution.*/
10
+ /** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, globe, terrain, attribution.*/
11
11
  readonly order?:number;}
12
+ /** Placement of the component-owned globe toggle; scene state follows the map projection.*/
13
+ export interface LyraMapGlobeControlOptions extends LyraMapNavigationControlOptions{}
14
+ /** Explicit elevation source requested when the component-owned terrain toggle enables terrain.*/
15
+ export interface LyraMapTerrainControlOptions extends LyraMapNavigationControlOptions,LyraMapTerrain{}
12
16
  /** Options of the declarative scale control.*/
13
17
  export interface LyraMapScaleControlOptions{
14
18
  /** Corner to add the control to. Defaults to `'bottom-left'`.*/
15
19
  readonly position?:LyraMapControlPosition;
16
- /** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, attribution.*/
20
+ /** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, globe, terrain, attribution.*/
17
21
  readonly order?:number;
18
22
  /** Unit system. Defaults to `'metric'`.*/
19
23
  readonly unit?:LyraMapScaleUnit;}
@@ -1 +1 @@
1
- import{resolveGuardedRel}from"../../../internal/link-rel.js";import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";const positions=new Set(["top-left","top-right","bottom-left","bottom-right"]);function runtimeRecord(input){try{return input!==null&&typeof input=="object"&&!Array.isArray(input)}catch{return!1}}function own(input,key){const descriptor=getOwnDataDescriptor(input,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Unsafe control option");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function optionalLegacy(input,key){try{return own(input,key)}catch{return}}function plain(input){if(!isPlainDataRecord(input))throw new TypeError("Expected plain control options");return input}function bool(input,key,fallback){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="boolean")throw new TypeError("Invalid boolean control option");return value}function number(input,key,fallback,maximum){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="number"||!Number.isFinite(value)||value<0||value>maximum)throw new RangeError("Invalid numeric control option");return value}function controlOrder(input){const value=own(input,"order");if(value===void 0)return 0;if(typeof value!="number"||!Number.isFinite(value))throw new TypeError("Invalid control order");return value}function position(input,fallback){const value=own(input,"position");if(value===void 0)return fallback;if(!positions.has(value))throw new TypeError("Invalid control position");return value}const escapeText=value=>value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;");function attributionText(input){let total=0;const labels=[],text=value=>{if(typeof value!="string"||value.length>4096||(total+=value.length)>16384)throw new RangeError("Attribution text limit");return escapeText(value)},item=value=>{if(typeof value=="string"){const label2=text(value);return labels.push(label2),label2}const record=plain(value),label=text(own(record,"label")),raw=own(record,"url");if(typeof raw!="string"||raw.length>2048||/[\u0000-\u0020\u007f-\u009f]/.test(raw))throw new TypeError("Invalid attribution URL");const url=new URL(raw);if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.href.length>2048||(total+=url.href.length)>16384)throw new TypeError("Invalid attribution URL");const snapshot=Object.freeze({label,url:url.href});return labels.push(snapshot.label),`<a href="${escapeText(snapshot.url)}" target="_blank" rel="${resolveGuardedRel(void 0,"_blank")}">${snapshot.label}</a>`};let html;if(!Array.isArray(input))html=item(input);else{const length=own(input,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>32)throw new RangeError("Attribution count limit");const result=[];for(let index=0;index<length;index++)result.push(item(own(input,String(index))));html=Object.freeze(result)}return Object.freeze({html,text:Object.freeze(labels)})}function normalizeMapControlOptions(input){const controls=new Map,diagnostics=[],done=()=>Object.freeze({controls,diagnostics:Object.freeze(diagnostics.map(item=>Object.freeze(item)))});if(!runtimeRecord(input))return done();for(const kind of["navigation","scale","geolocate","attribution"])try{const value=kind==="navigation"||kind==="scale"?optionalLegacy(input,kind):own(input,kind);if(value===void 0||value===!1)continue;if(kind==="navigation"||kind==="scale"){if(value!==!0&&!runtimeRecord(value))continue;const entry2=value===!0?{}:value,order2=controlOrder(entry2),fallback=kind==="navigation"?"top-right":"bottom-left",requested=optionalLegacy(entry2,"position"),corner2=positions.has(requested)?requested:fallback,unit=kind==="scale"?optionalLegacy(entry2,"unit")==="imperial"?"imperial":"metric":void 0;controls.set(kind,Object.freeze({kind,position:corner2,order:order2,unit,options:Object.freeze(kind==="scale"?{unit}:{}),key:`${corner2}:${order2}:${unit??""}`}));continue}const entry=value===!0?{}:plain(value),order=controlOrder(entry),corner=position(entry,kind==="geolocate"?"top-right":"bottom-right");let options,attributionLabels,initialExpanded;if(kind==="geolocate"){const rawPosition=own(entry,"positionOptions"),rawFit=own(entry,"fitBoundsOptions"),positionOptions=rawPosition===void 0?{}:plain(rawPosition),fit=rawFit===void 0?{}:plain(rawFit),showUserLocation=bool(entry,"showUserLocation",!0),showAccuracyCircle=bool(entry,"showAccuracyCircle",!0),zoomToUserAccuracy=own(entry,"zoomToUserAccuracy");if(zoomToUserAccuracy!==void 0&&typeof zoomToUserAccuracy!="boolean")throw new TypeError("Invalid zoom option");options=Object.freeze({trackUserLocation:bool(entry,"trackUserLocation",!1),showUserLocation,showAccuracyCircle:showUserLocation&&showAccuracyCircle,positionOptions:Object.freeze({enableHighAccuracy:bool(positionOptions,"enableHighAccuracy",!1),timeout:number(positionOptions,"timeout",6e3,864e5),maximumAge:number(positionOptions,"maximumAge",0,864e5)}),fitBoundsOptions:Object.freeze({maxZoom:number(fit,"maxZoom",15,24)}),...zoomToUserAccuracy===void 0?{}:{zoomToUserAccuracy}})}else{const compact=own(entry,"compact"),custom=own(entry,"customAttribution"),seed=own(entry,"initialExpanded");if(compact!==void 0&&typeof compact!="boolean")throw new TypeError("Invalid attribution mode");if(seed!==void 0&&typeof seed!="boolean")throw new TypeError("Invalid attribution expansion");initialExpanded=seed;const credits=custom===void 0?void 0:attributionText(custom);attributionLabels=credits?.text,options=Object.freeze({...compact===void 0?{}:{compact},...credits===void 0?{}:{customAttribution:credits.html}})}controls.set(kind,Object.freeze({kind,position:corner,order,unit:void 0,options,...attributionLabels?{attributionText:attributionLabels}:{},...initialExpanded===void 0?{}:{initialExpanded},key:`${corner}:${order}:${JSON.stringify(options)}${initialExpanded===void 0?"":`:${initialExpanded}`}`}))}catch{diagnostics.push({kind,code:"invalid-options"})}return done()}function mapGeolocationErrorCode(code){return code===1?"permission-denied":code===2?"position-unavailable":code===3?"timeout":"unknown"}export{mapGeolocationErrorCode,normalizeMapControlOptions};
1
+ import{admitMapTerrain}from"./map-scene-configuration.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";const positions=new Set(["top-left","top-right","bottom-left","bottom-right"]);function runtimeRecord(input){try{return input!==null&&typeof input=="object"&&!Array.isArray(input)}catch{return!1}}function own(input,key){const descriptor=getOwnDataDescriptor(input,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Unsafe control option");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function optionalLegacy(input,key){try{return own(input,key)}catch{return}}function plain(input){if(!isPlainDataRecord(input))throw new TypeError("Expected plain control options");return input}function bool(input,key,fallback){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="boolean")throw new TypeError("Invalid boolean control option");return value}function number(input,key,fallback,maximum){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="number"||!Number.isFinite(value)||value<0||value>maximum)throw new RangeError("Invalid numeric control option");return value}function controlOrder(input){const value=own(input,"order");if(value===void 0)return 0;if(typeof value!="number"||!Number.isFinite(value))throw new TypeError("Invalid control order");return value}function position(input,fallback){const value=own(input,"position");if(value===void 0)return fallback;if(!positions.has(value))throw new TypeError("Invalid control position");return value}const escapeText=value=>value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;");function attributionText(input){let total=0;const labels=[],text=value=>{if(typeof value!="string"||value.length>4096||(total+=value.length)>16384)throw new RangeError("Attribution text limit");return escapeText(value)},item=value=>{if(typeof value=="string"){const label2=text(value);return labels.push(label2),label2}const record=plain(value),label=text(own(record,"label")),raw=own(record,"url");if(typeof raw!="string"||raw.length>2048||/[\u0000-\u0020\u007f-\u009f]/.test(raw))throw new TypeError("Invalid attribution URL");const url=new URL(raw);if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.href.length>2048||(total+=url.href.length)>16384)throw new TypeError("Invalid attribution URL");const snapshot=Object.freeze({label,url:url.href});return labels.push(snapshot.label),`<a href="${escapeText(snapshot.url)}" target="_blank" rel="${resolveGuardedRel(void 0,"_blank")}">${snapshot.label}</a>`};let html;if(!Array.isArray(input))html=item(input);else{const length=own(input,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>32)throw new RangeError("Attribution count limit");const result=[];for(let index=0;index<length;index++)result.push(item(own(input,String(index))));html=Object.freeze(result)}return Object.freeze({html,text:Object.freeze(labels)})}function normalizeMapControlOptions(input){const controls=new Map,diagnostics=[],done=()=>Object.freeze({controls,diagnostics:Object.freeze(diagnostics.map(item=>Object.freeze(item)))});if(!runtimeRecord(input))return done();for(const kind of["navigation","scale","geolocate","globe","terrain","attribution"])try{const value=kind==="navigation"||kind==="scale"?optionalLegacy(input,kind):own(input,kind);if(value===void 0||value===!1)continue;if(kind==="navigation"||kind==="scale"){if(value!==!0&&!runtimeRecord(value))continue;const entry2=value===!0?{}:value,order2=controlOrder(entry2),fallback=kind==="navigation"?"top-right":"bottom-left",requested=optionalLegacy(entry2,"position"),corner2=positions.has(requested)?requested:fallback,unit=kind==="scale"?optionalLegacy(entry2,"unit")==="imperial"?"imperial":"metric":void 0;controls.set(kind,Object.freeze({kind,position:corner2,order:order2,unit,options:Object.freeze(kind==="scale"?{unit}:{}),key:`${corner2}:${order2}:${unit??""}`}));continue}if(kind==="terrain"&&value===!0)throw new TypeError("Terrain control source is required");const entry=value===!0?{}:plain(value),order=controlOrder(entry),corner=position(entry,kind==="attribution"?"bottom-right":"top-right");let options,attributionLabels,initialExpanded;if(kind==="globe")options=Object.freeze({});else if(kind==="terrain"){const terrain=admitMapTerrain(entry);if(!terrain)throw new TypeError("Terrain control source is required");options=Object.freeze({source:terrain.source,exaggeration:terrain.exaggeration})}else if(kind==="geolocate"){const rawPosition=own(entry,"positionOptions"),rawFit=own(entry,"fitBoundsOptions"),positionOptions=rawPosition===void 0?{}:plain(rawPosition),fit=rawFit===void 0?{}:plain(rawFit),showUserLocation=bool(entry,"showUserLocation",!0),showAccuracyCircle=bool(entry,"showAccuracyCircle",!0),zoomToUserAccuracy=own(entry,"zoomToUserAccuracy");if(zoomToUserAccuracy!==void 0&&typeof zoomToUserAccuracy!="boolean")throw new TypeError("Invalid zoom option");options=Object.freeze({trackUserLocation:bool(entry,"trackUserLocation",!1),showUserLocation,showAccuracyCircle:showUserLocation&&showAccuracyCircle,positionOptions:Object.freeze({enableHighAccuracy:bool(positionOptions,"enableHighAccuracy",!1),timeout:number(positionOptions,"timeout",6e3,864e5),maximumAge:number(positionOptions,"maximumAge",0,864e5)}),fitBoundsOptions:Object.freeze({maxZoom:number(fit,"maxZoom",15,24)}),...zoomToUserAccuracy===void 0?{}:{zoomToUserAccuracy}})}else{const compact=own(entry,"compact"),custom=own(entry,"customAttribution"),seed=own(entry,"initialExpanded");if(compact!==void 0&&typeof compact!="boolean")throw new TypeError("Invalid attribution mode");if(seed!==void 0&&typeof seed!="boolean")throw new TypeError("Invalid attribution expansion");initialExpanded=seed;const credits=custom===void 0?void 0:attributionText(custom);attributionLabels=credits?.text,options=Object.freeze({...compact===void 0?{}:{compact},...credits===void 0?{}:{customAttribution:credits.html}})}controls.set(kind,Object.freeze({kind,position:corner,order,unit:void 0,options,...attributionLabels?{attributionText:attributionLabels}:{},...initialExpanded===void 0?{}:{initialExpanded},key:`${corner}:${order}:${JSON.stringify(options)}${initialExpanded===void 0?"":`:${initialExpanded}`}`}))}catch{diagnostics.push({kind,code:"invalid-options"})}return done()}function mapGeolocationErrorCode(code){return code===1?"permission-denied":code===2?"position-unavailable":code===3?"timeout":"unknown"}export{mapGeolocationErrorCode,normalizeMapControlOptions};
@@ -1 +1 @@
1
- import{deepActiveElementIn}from"../../../internal/active-element.js";import{mapGeolocationErrorCode}from"./map-control-options.js";function geolocatedPosition(event){try{if(event===null||typeof event!="object")return{};const coords=event.coords;if(coords===null||typeof coords!="object")return{};const{longitude,latitude,accuracy}=coords;return typeof longitude!="number"||typeof latitude!="number"||typeof accuracy!="number"||!Number.isFinite(longitude)||!Number.isFinite(latitude)||!Number.isFinite(accuracy)||Math.abs(longitude)>180||Math.abs(latitude)>90||accuracy<0?{}:{lngLat:Object.freeze([longitude,latitude]),accuracy}}catch{return{}}}class MapControlsLifecycle{constructor(load){this.load=load,this.generation=0,this.entries=new Map}async sync(map,desired,context){const generation=++this.generation,retired=[];for(const[kind,entry]of this.entries){const next=desired.get(kind);entry.map===map&&entry.installed&&next&&(next.key===entry.options.key||entry.root&&map.controlContainer&&next.initialExpanded===entry.options.initialExpanded&&JSON.stringify(next.options)===JSON.stringify(entry.options.options))?(entry.context=context,entry.options=next):(this.entries.delete(kind),retired.push(entry))}for(const entry of retired)this.retire(entry);if(generation!==this.generation||!this.validContext(context)||generation!==this.generation)return;const pending=[];for(const[kind,options]of desired){if(generation!==this.generation)break;if(this.entries.has(kind))continue;const entry={map,options,context,installed:!1,attempted:!1,adding:!1,subscribing:!1,removed:!1,retired:!1,subscriptions:[]};this.entries.set(kind,entry),pending.push(entry)}const loaded=await Promise.all(pending.map(async entry=>{try{return await this.load(entry.options.kind)}catch{return}}));if(generation!==this.generation||!this.validContext(context))return;const constructors=new Map(pending.map((entry,index)=>[entry,loaded[index]])),priority=["navigation","scale","geolocate","attribution"];for(const corner of["top-left","top-right","bottom-left","bottom-right"]){const ordered=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order),order=corner.startsWith("bottom")?ordered.reverse():ordered;for(const entry of order){if(generation!==this.generation||!this.validContext(context))return;constructors.has(entry)&&this.install(entry,constructors.get(entry))}}for(const corner of["top-left","top-right","bottom-left","bottom-right"]){if(generation!==this.generation||!this.validContext(context))return;const entries=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.installed&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order);for(let index=entries.length-1;index>=0;index--){const entry=entries[index];if(generation!==this.generation||!this.current(entry))return;try{const parent=map.controlContainer?.(corner);if(generation!==this.generation||!this.current(entry))return;if(!parent||!entry.root)continue;const before=entries.slice(index+1).find(next=>next.root?.parentNode===parent)?.root??null,root=entry.root;if(root.parentNode===parent&&(before?root.nextSibling===before:root.nextSibling===null))continue;const active=root.getRootNode().activeElement,focus=active instanceof HTMLElement&&root.contains(active)?active:void 0;if(generation!==this.generation||!this.current(entry))return;const document=root.ownerDocument;let focusTransferred=!1;const trackFocus=()=>{focusTransferred=!0};focus&&document.addEventListener("focus",trackFocus,!0);try{parent.insertBefore(root,before)}finally{focus&&document.removeEventListener("focus",trackFocus,!0)}if(generation!==this.generation||!this.current(entry))return;const remaining=deepActiveElementIn(document),lostFocus=remaining===null||remaining===document.body||remaining===document.documentElement;if(focus?.isConnected&&root.contains(focus)&&focus.ownerDocument===document&&!focusTransferred&&lostFocus&&focus.focus({preventScroll:!0}),generation!==this.generation||!this.current(entry))return}catch{if(generation===this.generation&&this.current(entry))try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}}}pendingKinds(){return new Set([...this.entries].filter(([,entry])=>!entry.installed&&!entry.retired).map(([kind])=>kind))}ownedRoot(kind){const entry=this.entries.get(kind);return entry?.installed&&!entry.retired?entry.root:void 0}dispose(){this.generation+=1;const retired=[...this.entries.values()];this.entries.clear();for(const entry of retired)this.retire(entry)}validContext(context){try{return context.isCurrent()}catch{return!1}}current(entry){const owned=()=>!entry.retired&&this.entries.get(entry.options.kind)===entry;return owned()&&this.validContext(entry.context)&&owned()}install(entry,Constructor){try{if(!this.current(entry)){this.release(entry);return}if(typeof Constructor!="function")throw new Error("Map control is unavailable.");const control=new Constructor(entry.options.options);if(control===null||typeof control!="object"&&typeof control!="function")throw new Error("Map control is unavailable.");if(entry.control=control,!this.current(entry)){this.release(entry);return}if(entry.options.kind==="geolocate"){if(typeof entry.control.on!="function"||typeof entry.control.off!="function")throw new Error("Map control events are unavailable.");if(this.subscribe(entry,"error",event=>{if(!this.current(entry))return;let code;try{event!==null&&typeof event=="object"&&(code=event.code)}catch{}this.current(entry)&&entry.context.onEvent({kind:"geolocate-error",code:mapGeolocationErrorCode(code)})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"outofmaxbounds",()=>{this.current(entry)&&entry.context.onEvent({kind:"geolocate-out-of-bounds",code:"out-of-bounds"})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"geolocate",event=>{if(!this.current(entry))return;const position=geolocatedPosition(event);this.current(entry)&&entry.context.onEvent(Object.freeze({kind:"geolocate-success",...position}))}),!this.current(entry)){this.release(entry);return}}const onAdd=entry.control.onAdd;if(!this.current(entry)){this.release(entry);return}const descriptor=Object.getOwnPropertyDescriptor(entry.control,"onAdd");if(!this.current(entry)){this.release(entry);return}try{if(onAdd&&(entry.control.onAdd=function(...args){const root=onAdd.apply(this,args);return entry.root=root,root}),!this.current(entry)){this.release(entry);return}entry.attempted=!0,entry.adding=!0,entry.map.addControl(entry.control,entry.options.position)}finally{try{onAdd&&(descriptor?Object.defineProperty(entry.control,"onAdd",descriptor):delete entry.control.onAdd)}finally{entry.adding=!1,entry.retired&&this.retire(entry)}}if(!this.current(entry)){this.release(entry);return}const seed=entry.options.initialExpanded;if(entry.options.kind==="attribution"&&seed!==void 0&&entry.root?.classList.contains("maplibregl-compact")&&(entry.root.classList.toggle("maplibregl-compact-show",seed),entry.root.toggleAttribute("open",seed)),!this.current(entry)){this.release(entry);return}entry.installed=!0}catch{const report=this.current(entry),generation=this.generation;if(this.release(entry),report&&generation===this.generation&&this.validContext(entry.context)&&generation===this.generation)try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}subscribe(entry,type,callback){entry.subscriptions.push({type,callback}),entry.subscribing=!0;try{entry.control.on(type,callback)}finally{entry.subscribing=!1,entry.retired&&this.retire(entry)}}release(entry){this.entries.get(entry.options.kind)===entry&&this.entries.delete(entry.options.kind),this.retire(entry)}retire(entry){if(entry.retired=!0,entry.subscribing)return;const subscriptions=entry.subscriptions.splice(0);for(const{type,callback}of subscriptions)try{entry.control?.off?.(type,callback)}catch{}if(!(!entry.attempted||entry.adding||entry.removed||!entry.control)){entry.removed=!0;try{entry.map.removeControl(entry.control)}catch{}}}}export{MapControlsLifecycle};
1
+ import{deepActiveElementIn}from"../../../internal/active-element.js";import{mapGeolocationErrorCode}from"./map-control-options.js";function geolocatedPosition(event){try{if(event===null||typeof event!="object")return{};const coords=event.coords;if(coords===null||typeof coords!="object")return{};const{longitude,latitude,accuracy}=coords;return typeof longitude!="number"||typeof latitude!="number"||typeof accuracy!="number"||!Number.isFinite(longitude)||!Number.isFinite(latitude)||!Number.isFinite(accuracy)||Math.abs(longitude)>180||Math.abs(latitude)>90||accuracy<0?{}:{lngLat:Object.freeze([longitude,latitude]),accuracy}}catch{return{}}}class MapControlsLifecycle{constructor(load){this.load=load,this.generation=0,this.entries=new Map}async sync(map,desired,context){const generation=++this.generation,retired=[];for(const[kind,entry]of this.entries){const next=desired.get(kind);entry.map===map&&entry.installed&&next&&(next.key===entry.options.key||entry.root&&map.controlContainer&&next.initialExpanded===entry.options.initialExpanded&&JSON.stringify(next.options)===JSON.stringify(entry.options.options))?(entry.context=context,entry.options=next,context.scene&&entry.control?.setSceneContext?.(context.scene)):(this.entries.delete(kind),retired.push(entry))}for(const entry of retired)this.retire(entry);if(generation!==this.generation||!this.validContext(context)||generation!==this.generation)return;const pending=[];for(const[kind,options]of desired){if(generation!==this.generation)break;if(this.entries.has(kind))continue;const entry={map,options,context,installed:!1,attempted:!1,adding:!1,subscribing:!1,removed:!1,retired:!1,subscriptions:[]};this.entries.set(kind,entry),pending.push(entry)}const loaded=await Promise.all(pending.map(async entry=>{try{return await this.load(entry.options.kind)}catch{return}}));if(generation!==this.generation||!this.validContext(context))return;const constructors=new Map(pending.map((entry,index)=>[entry,loaded[index]])),priority=["navigation","scale","geolocate","globe","terrain","attribution"];for(const corner of["top-left","top-right","bottom-left","bottom-right"]){const ordered=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order),order=corner.startsWith("bottom")?ordered.reverse():ordered;for(const entry of order){if(generation!==this.generation||!this.validContext(context))return;constructors.has(entry)&&this.install(entry,constructors.get(entry))}}for(const corner of["top-left","top-right","bottom-left","bottom-right"]){if(generation!==this.generation||!this.validContext(context))return;const entries=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.installed&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order);for(let index=entries.length-1;index>=0;index--){const entry=entries[index];if(generation!==this.generation||!this.current(entry))return;try{const parent=map.controlContainer?.(corner);if(generation!==this.generation||!this.current(entry))return;if(!parent||!entry.root)continue;const before=entries.slice(index+1).find(next=>next.root?.parentNode===parent)?.root??null,root=entry.root;if(root.parentNode===parent&&(before?root.nextSibling===before:root.nextSibling===null))continue;const active=root.getRootNode().activeElement,focus=active instanceof HTMLElement&&root.contains(active)?active:void 0;if(generation!==this.generation||!this.current(entry))return;const document=root.ownerDocument;let focusTransferred=!1;const trackFocus=()=>{focusTransferred=!0};focus&&document.addEventListener("focus",trackFocus,!0);try{parent.insertBefore(root,before)}finally{focus&&document.removeEventListener("focus",trackFocus,!0)}if(generation!==this.generation||!this.current(entry))return;const remaining=deepActiveElementIn(document),lostFocus=remaining===null||remaining===document.body||remaining===document.documentElement;if(focus?.isConnected&&root.contains(focus)&&focus.ownerDocument===document&&!focusTransferred&&lostFocus&&focus.focus({preventScroll:!0}),generation!==this.generation||!this.current(entry))return}catch{if(generation===this.generation&&this.current(entry))try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}}}pendingKinds(){return new Set([...this.entries].filter(([,entry])=>!entry.installed&&!entry.retired).map(([kind])=>kind))}ownedRoot(kind){const entry=this.entries.get(kind);return entry?.installed&&!entry.retired?entry.root:void 0}refreshSceneControls(){for(const entry of this.entries.values())this.current(entry)&&entry.control?.refreshSceneControl?.()}dispose(){this.generation+=1;const retired=[...this.entries.values()];this.entries.clear();for(const entry of retired)this.retire(entry)}validContext(context){try{return context.isCurrent()}catch{return!1}}current(entry){const owned=()=>!entry.retired&&this.entries.get(entry.options.kind)===entry;return owned()&&this.validContext(entry.context)&&owned()}install(entry,Constructor){try{if(!this.current(entry)){this.release(entry);return}if(typeof Constructor!="function")throw new Error("Map control is unavailable.");const control=new Constructor(entry.options.options);if(control===null||typeof control!="object"&&typeof control!="function")throw new Error("Map control is unavailable.");if(entry.control=control,!this.current(entry)){this.release(entry);return}if(entry.options.kind==="globe"||entry.options.kind==="terrain"){if(!entry.context.scene||typeof entry.control.setSceneContext!="function"||typeof entry.control.on!="function"||typeof entry.control.off!="function")throw new Error("Scene control is unavailable");if(entry.control.setSceneContext(entry.context.scene),this.subscribe(entry,"activate",action=>{this.current(entry)&&entry.context.onEvent({kind:"scene-action",action})}),!this.current(entry)){this.release(entry);return}}if(entry.options.kind==="geolocate"){if(typeof entry.control.on!="function"||typeof entry.control.off!="function")throw new Error("Map control events are unavailable.");if(this.subscribe(entry,"error",event=>{if(!this.current(entry))return;let code;try{event!==null&&typeof event=="object"&&(code=event.code)}catch{}this.current(entry)&&entry.context.onEvent({kind:"geolocate-error",code:mapGeolocationErrorCode(code)})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"outofmaxbounds",()=>{this.current(entry)&&entry.context.onEvent({kind:"geolocate-out-of-bounds",code:"out-of-bounds"})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"geolocate",event=>{if(!this.current(entry))return;const position=geolocatedPosition(event);this.current(entry)&&entry.context.onEvent(Object.freeze({kind:"geolocate-success",...position}))}),!this.current(entry)){this.release(entry);return}}const onAdd=entry.control.onAdd;if(!this.current(entry)){this.release(entry);return}const descriptor=Object.getOwnPropertyDescriptor(entry.control,"onAdd");if(!this.current(entry)){this.release(entry);return}try{if(onAdd&&(entry.control.onAdd=function(...args){const root=onAdd.apply(this,args);return entry.root=root,root}),!this.current(entry)){this.release(entry);return}entry.attempted=!0,entry.adding=!0,entry.map.addControl(entry.control,entry.options.position)}finally{try{onAdd&&(descriptor?Object.defineProperty(entry.control,"onAdd",descriptor):delete entry.control.onAdd)}finally{entry.adding=!1,entry.retired&&this.retire(entry)}}if(!this.current(entry)){this.release(entry);return}const seed=entry.options.initialExpanded;if(entry.options.kind==="attribution"&&seed!==void 0&&entry.root?.classList.contains("maplibregl-compact")&&(entry.root.classList.toggle("maplibregl-compact-show",seed),entry.root.toggleAttribute("open",seed)),!this.current(entry)){this.release(entry);return}entry.installed=!0}catch{const report=this.current(entry),generation=this.generation;if(this.release(entry),report&&generation===this.generation&&this.validContext(entry.context)&&generation===this.generation)try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}subscribe(entry,type,callback){entry.subscriptions.push({type,callback}),entry.subscribing=!0;try{entry.control.on(type,callback)}finally{entry.subscribing=!1,entry.retired&&this.retire(entry)}}release(entry){this.entries.get(entry.options.kind)===entry&&this.entries.delete(entry.options.kind),this.retire(entry)}retire(entry){if(entry.retired=!0,entry.subscribing)return;const subscriptions=entry.subscriptions.splice(0);for(const{type,callback}of subscriptions)try{entry.control?.off?.(type,callback)}catch{}if(!(!entry.attempted||entry.adding||entry.removed||!entry.control)){entry.removed=!0;try{entry.map.removeControl(entry.control)}catch{}}}}export{MapControlsLifecycle};
@@ -1 +1 @@
1
- import{mapFeatureLoader,__setMapFeatureImporterForTesting as setImporter}from"./map-feature-loader-core.js";import{loadMapImageRuntime,loadMapStyleOverrideRuntime}from"./map-resource-feature-loaders.js";const loadMapAnchorRuntime=mapFeatureLoader(()=>import("./map-anchor-controller.js")),loadMapControlRuntime=mapFeatureLoader(()=>import("./map-controls-lifecycle.js")),loadMapDrawingRuntime=mapFeatureLoader(()=>import("./map-drawing-controller.js")),loadMapImageExportRuntime=mapFeatureLoader(()=>import("./map-image-export-controller.js")),loadMapHashRuntime=mapFeatureLoader(()=>import("./map-hash-owner.js")),loadMapFeatureStateRuntime=mapFeatureLoader(()=>import("./map-feature-state-routes.js")),loadMapOwnedFeatureRuntime=mapFeatureLoader(()=>import("./map-owned-features.js"));function __setMapFeatureImporterForTesting(loader,importer){setImporter(loader,importer)}export{__setMapFeatureImporterForTesting,loadMapAnchorRuntime,loadMapControlRuntime,loadMapDrawingRuntime,loadMapFeatureStateRuntime,loadMapHashRuntime,loadMapImageExportRuntime,loadMapImageRuntime,loadMapOwnedFeatureRuntime,loadMapStyleOverrideRuntime};
1
+ import{resolveOptionalPeerCapability}from"../../../internal/optional-peer-capabilities.js";import{mapFeatureLoader,__setMapFeatureImporterForTesting as setImporter}from"./map-feature-loader-core.js";import{loadMapImageRuntime,loadMapStyleOverrideRuntime}from"./map-resource-feature-loaders.js";const loadMapAnchorRuntime=mapFeatureLoader(()=>import("./map-anchor-controller.js")),loadMapControlRuntime=mapFeatureLoader(()=>import("./map-controls-lifecycle.js")),loadMapDrawingRuntime=mapFeatureLoader(()=>import("./map-drawing-controller.js")),loadMapImageExportRuntime=mapFeatureLoader(()=>import("./map-image-export-controller.js")),loadMapHashRuntime=mapFeatureLoader(()=>import("./map-hash-owner.js")),loadMapFeatureStateRuntime=mapFeatureLoader(()=>import("./map-feature-state-routes.js")),loadMapOwnedFeatureRuntime=mapFeatureLoader(()=>import("./map-owned-features.js"));function __setMapFeatureImporterForTesting(loader,importer){setImporter(loader,importer)}const loadMapSceneRenderRuntime=mapFeatureLoader(()=>import("./map-scene-render-controller.js")),sceneBridgeImporter=()=>import("@aceshooting/lyra-map/scene");let importSceneBridge=sceneBridgeImporter;async function importSceneBridgeRuntime(){const runtime=resolveOptionalPeerCapability(await importSceneBridge(),value=>typeof value=="object"&&value!==null&&"createSceneBridge"in value&&typeof value.createSceneBridge=="function");if(!runtime)throw new TypeError("Map scene renderer unavailable");return runtime}const loadMapSceneBridge=mapFeatureLoader(importSceneBridgeRuntime);function __setMapSceneBridgeImporterForTesting(importer){importSceneBridge=importer??sceneBridgeImporter,setImporter(loadMapSceneBridge)}export{__setMapFeatureImporterForTesting,__setMapSceneBridgeImporterForTesting,loadMapAnchorRuntime,loadMapControlRuntime,loadMapDrawingRuntime,loadMapFeatureStateRuntime,loadMapHashRuntime,loadMapImageExportRuntime,loadMapImageRuntime,loadMapOwnedFeatureRuntime,loadMapSceneBridge,loadMapSceneRenderRuntime,loadMapStyleOverrideRuntime};
@@ -17,7 +17,11 @@ prepareFeatures?(requirements:LyraMapFeatureRequirements,options?:{signal?:Abort
17
17
  /** Required, unlike setMaxBounds below: the loader validates getCanvas is callable and rejects a
18
18
  * peer without it, so holding this type already implies the method is present. Call sites still
19
19
  * guard with `?.()` against a peer that satisfies the shape check and then lies at runtime. */
20
- getCanvas():HTMLCanvasElement;getCenter():{lng:number;lat:number;};getZoom():number;getBearing?():number;getPitch?():number;setCenter(center:[number,number]):unknown;setZoom(zoom:number):unknown;resize():unknown;
20
+ getCanvas():HTMLCanvasElement;
21
+ /** Optional native allocation capabilities, feature-detected by opted-in scene rendering.*/
22
+ getContainer?():HTMLElement;getPixelRatio?():number;getPadding?():{top:number;right:number;bottom:number;left:number;};getCenter():{lng:number;lat:number;};getZoom():number;getBearing?():number;getPitch?():number;
23
+ /** Optional cancellation, required only for session-owned animated camera commands.*/
24
+ stop?():unknown;setCenter(center:[number,number]):unknown;setZoom(zoom:number):unknown;resize():unknown;
21
25
  /** Optional zoom limits; `minZoom`/`maxZoom` feature-detect them before a live update.*/
22
26
  setMinZoom?(zoom:number):unknown;setMaxZoom?(zoom:number):unknown;getMaxZoom?():number;
23
27
  /** Optional: absent on peers predating it, and the caller feature-detects before use.*/
@@ -42,9 +46,11 @@ project?(lngLat:[number,number]):{x:number;y:number;};unproject?(point:[number,n
42
46
  /** Optional: standard peer controls. A control is the peer's own object (`onAdd`/`onRemove`).*/
43
47
  addControl?(control:unknown,position?:string):unknown;removeControl?(control:unknown):unknown;
44
48
  /** Optional: the geographic box of the whole canvas.*/
45
- getBounds?():{getWest():number;getSouth():number;getEast():number;getNorth():number;};remove():void;on(type:'error',listener:(event:{error?:unknown;})=>void):this;on(type:'render'|'load'|'style.load'|'idle'|'dataloading'|'sourcedata'|'movestart'|'move'|'error',listener:()=>void):this;on(type:'moveend',listener:(event:Readonly<Record<string,unknown>> |undefined)=>void):this;on(type:'move',listener:()=>void):this;on(type:'boxzoomend',listener:()=>void):this;on(type:'movestart'|'boxzoomstart',listener:(event:Readonly<Record<string,unknown>> |undefined)=>void):this;on(type:'click',listener:(event:{point:unknown;lngLat:{lng:number;lat:number;};})=>void):this;once(type:'style.load',listener:()=>void):this;setStyle(style:unknown,options?:{diff?:boolean;}):this;
49
+ getBounds?():{getWest():number;getSouth():number;getEast():number;getNorth():number;};remove():void;on(type:'error',listener:(event:{error?:unknown;})=>void):this;on(type:'render'|'load'|'style.load'|'idle'|'dataloading'|'sourcedata'|'movestart'|'move'|'error',listener:()=>void):this;on(type:'moveend',listener:(event:Readonly<Record<string,unknown>> |undefined)=>void):this;on(type:'move',listener:()=>void):this;on(type:'boxzoomend',listener:()=>void):this;on(type:'movestart'|'boxzoomstart'|'dragstart'|'zoomstart'|'rotatestart'|'pitchstart',listener:(event:Readonly<Record<string,unknown>> |undefined)=>void):this;on(type:'click',listener:(event:{point:unknown;lngLat:{lng:number;lat:number;};})=>void):this;once(type:'style.load',listener:()=>void):this;setStyle(style:unknown,options?:{diff?:boolean;}):this;
46
50
  /** Optional native style capabilities, required only for declarative owned overlays/overrides.*/
47
- getStyle?():{readonly layers?:readonly{readonly id:string;}[];};moveLayer?(id:string,before?:string):unknown;getPaintProperty?(id:string,property:string):unknown;getLayoutProperty?(id:string,property:string):unknown;setLayoutProperty?(id:string,property:string,value:unknown):unknown;setFilter?(id:string,filter:unknown):unknown;setLayerZoomRange?(id:string,min:number,max:number):unknown;setFeatureState?(target:import('./map-feature-state.js').LyraMapFeatureIdentifier,state:import('./map-feature-state.js').LyraMapFeatureState):unknown;removeFeatureState?(target:import('./map-feature-state.js').LyraMapFeatureIdentifier,key:string):unknown;triggerRepaint?():unknown;getSource(id:string):MapLibreGeoJsonSource|undefined;addSource(id:string,source:unknown):this;removeSource(id:string):this;getLayer(id:string):unknown;addLayer(layer:unknown,before?:string):this;removeLayer(id:string):this;setPaintProperty(layerId:string,name:string,value:unknown):this;
51
+ getStyle?():{readonly layers?:readonly{readonly id:string;}[];};
52
+ /** Optional scene capabilities, required only for declarative projection/terrain overrides.*/
53
+ getProjection?():unknown;getTerrain?():unknown;setProjection?(value:unknown):unknown;setTerrain?(value:unknown):unknown;moveLayer?(id:string,before?:string):unknown;getPaintProperty?(id:string,property:string):unknown;getLayoutProperty?(id:string,property:string):unknown;setLayoutProperty?(id:string,property:string,value:unknown):unknown;setFilter?(id:string,filter:unknown):unknown;setLayerZoomRange?(id:string,min:number,max:number):unknown;setFeatureState?(target:import('./map-feature-state.js').LyraMapFeatureIdentifier,state:import('./map-feature-state.js').LyraMapFeatureState):unknown;removeFeatureState?(target:import('./map-feature-state.js').LyraMapFeatureIdentifier,key:string):unknown;triggerRepaint?():unknown;getSource(id:string):MapLibreGeoJsonSource|undefined;addSource(id:string,source:unknown):this;removeSource(id:string):this;getLayer(id:string):unknown;addLayer(layer:unknown,before?:string):this;removeLayer(id:string):this;setPaintProperty(layerId:string,name:string,value:unknown):this;
48
54
  /** Optional image-atlas capabilities; point circles remain usable when a partial peer lacks these.*/
49
55
  hasImage?(id:string):boolean;addImage?(id:string,image:ImageData,options:{pixelRatio:number;sdf?:boolean;}):unknown;
50
56
  /** Optional lazy image hook: the engine awaits it before treating a style image as missing.*/
@@ -68,4 +74,4 @@ export interface ModularMapModule extends MaplibreModule{Map:new(options:Record<
68
74
  /** Lazily loads the modular companion once per page. A failed load never selects another engine.*/
69
75
  export declare function loadModularMap():Promise<ModularMapModule|null>;
70
76
  /** The standard peer controls `<lr-map controls>` can add, by kind.*/
71
- export type MapControlKind='navigation'|'scale'|'geolocate'|'attribution';
77
+ export type MapControlKind='navigation'|'scale'|'geolocate'|'globe'|'terrain'|'attribution';
@@ -1 +1 @@
1
- import{resolveOptionalPeerCapability,unwrapOptionalPeerDefault}from"../../../internal/optional-peer-capabilities.js";const MAP_METHODS=["getCanvas","getCenter","getZoom","setCenter","setZoom","resize","remove","on","once","setStyle","getSource","addSource","removeSource","getLayer","addLayer","removeLayer","setPaintProperty","queryRenderedFeatures"],MARKER_METHODS=["setLngLat","setPopup","getPopup","addTo","remove"],POPUP_METHODS=["setHTML","setText"];function isObjectLike(value){return(typeof value=="object"||typeof value=="function")&&value!==null}function isConstructor(value){if(typeof value!="function")return!1;try{return Reflect.construct(Object,[],value),!0}catch{return!1}}function missingConstructorCapability(module,name,methods){const Constructor=module[name];if(!isConstructor(Constructor))return name;const prototype=Constructor.prototype;if(!isObjectLike(prototype))return`${name}.prototype`;for(const method of methods)if(typeof prototype[method]!="function")return`${name}.prototype.${method}`}function missingMaplibreCapability(candidate){return isObjectLike(candidate)?missingConstructorCapability(candidate,"Map",MAP_METHODS)??missingConstructorCapability(candidate,"Marker",MARKER_METHODS)??missingConstructorCapability(candidate,"Popup",POPUP_METHODS):"module namespace"}function isMaplibreModule(candidate){return missingMaplibreCapability(candidate)===void 0}function resolveMaplibreModule(value){const module=resolveOptionalPeerCapability(value,isMaplibreModule);if(module)return module;const candidate=unwrapOptionalPeerDefault(value),missing=missingMaplibreCapability(candidate)??"module namespace";throw new Error(`Invalid optional peer \`maplibre-gl\`: missing or invalid \`${missing}\` capability.`)}let maplibre,maplibreCapabilities;async function loadMaplibreModule(importer=()=>import("maplibre-gl").then(source=>maplibreCapabilities??=Object.freeze({get Map(){return source.Map},get Marker(){return source.Marker},get Popup(){return source.Popup},get NavigationControl(){return source.NavigationControl},get ScaleControl(){return source.ScaleControl},get GeolocateControl(){return source.GeolocateControl},get AttributionControl(){return source.AttributionControl},get setWorkerUrl(){return source.setWorkerUrl},get getVersion(){return source.getVersion},get default(){return source.default}}))){try{return resolveMaplibreModule(await importer())}catch(error){return console.warn("<lr-map> needs the optional peer dependency `maplibre-gl` — install it with `pnpm add maplibre-gl`.",error),null}}function loadMaplibre(){return maplibre||(maplibre=loadMaplibreModule()),maplibre}function isModularMapModule(candidate){return isMaplibreModule(candidate)&&typeof candidate.Map.prototype.prepareFeatures=="function"}let modularMapCapabilities;async function loadModularMapModule(importer=()=>import("@aceshooting/lyra-map").then(source=>modularMapCapabilities??=Object.freeze({get Map(){return source.Map},get Marker(){return source.Marker},get Popup(){return source.Popup}}))){try{const value=await importer(),module=resolveOptionalPeerCapability(value,isModularMapModule);if(module)return module;const candidate=unwrapOptionalPeerDefault(value),missing=missingMaplibreCapability(candidate)??"Map.prototype.prepareFeatures";throw new Error(`Invalid optional peer \`@aceshooting/lyra-map\`: missing or invalid \`${missing}\` capability.`)}catch(error){return console.warn("<lr-map> needs the optional peer dependency `@aceshooting/lyra-map` — install it with `pnpm add @aceshooting/lyra-map`.",error),null}}let modularMap;function loadModularMap(){return modularMap??=loadModularMapModule()}async function loadMapControl(kind,engine,module){const name={navigation:"NavigationControl",scale:"ScaleControl",geolocate:"GeolocateControl",attribution:"AttributionControl"}[kind],provided=module?.[name];if(isConstructor(provided))return provided;if(engine!=="modular")return null;try{const source=kind==="navigation"?await import("@aceshooting/lyra-map/controls/navigation"):kind==="scale"?await import("@aceshooting/lyra-map/controls/scale"):kind==="geolocate"?await import("@aceshooting/lyra-map/controls/geolocate"):await import("@aceshooting/lyra-map/controls/attribution"),candidate=unwrapOptionalPeerDefault(source),control=isObjectLike(candidate)?candidate[name]:void 0;return isConstructor(control)?control:null}catch(error){return console.warn(`<lr-map> could not load the ${kind} control from \`@aceshooting/lyra-map\`.`,error),null}}export{loadMapControl,loadMaplibre,loadMaplibreModule,loadModularMap,loadModularMapModule};
1
+ import{resolveOptionalPeerCapability,unwrapOptionalPeerDefault}from"../../../internal/optional-peer-capabilities.js";const MAP_METHODS=["getCanvas","getCenter","getZoom","setCenter","setZoom","resize","remove","on","once","setStyle","getSource","addSource","removeSource","getLayer","addLayer","removeLayer","setPaintProperty","queryRenderedFeatures"],MARKER_METHODS=["setLngLat","setPopup","getPopup","addTo","remove"],POPUP_METHODS=["setHTML","setText"];function isObjectLike(value){return(typeof value=="object"||typeof value=="function")&&value!==null}function isConstructor(value){if(typeof value!="function")return!1;try{return Reflect.construct(Object,[],value),!0}catch{return!1}}function missingConstructorCapability(module,name,methods){const Constructor=module[name];if(!isConstructor(Constructor))return name;const prototype=Constructor.prototype;if(!isObjectLike(prototype))return`${name}.prototype`;for(const method of methods)if(typeof prototype[method]!="function")return`${name}.prototype.${method}`}function missingMaplibreCapability(candidate){return isObjectLike(candidate)?missingConstructorCapability(candidate,"Map",MAP_METHODS)??missingConstructorCapability(candidate,"Marker",MARKER_METHODS)??missingConstructorCapability(candidate,"Popup",POPUP_METHODS):"module namespace"}function isMaplibreModule(candidate){return missingMaplibreCapability(candidate)===void 0}function resolveMaplibreModule(value){const module=resolveOptionalPeerCapability(value,isMaplibreModule);if(module)return module;const candidate=unwrapOptionalPeerDefault(value),missing=missingMaplibreCapability(candidate)??"module namespace";throw new Error(`Invalid optional peer \`maplibre-gl\`: missing or invalid \`${missing}\` capability.`)}let maplibre,maplibreCapabilities;async function loadMaplibreModule(importer=()=>import("maplibre-gl").then(source=>maplibreCapabilities??=Object.freeze({get Map(){return source.Map},get Marker(){return source.Marker},get Popup(){return source.Popup},get NavigationControl(){return source.NavigationControl},get ScaleControl(){return source.ScaleControl},get GeolocateControl(){return source.GeolocateControl},get AttributionControl(){return source.AttributionControl},get setWorkerUrl(){return source.setWorkerUrl},get getVersion(){return source.getVersion},get default(){return source.default}}))){try{return resolveMaplibreModule(await importer())}catch(error){return console.warn("<lr-map> needs the optional peer dependency `maplibre-gl` — install it with `pnpm add maplibre-gl`.",error),null}}function loadMaplibre(){return maplibre||(maplibre=loadMaplibreModule()),maplibre}function isModularMapModule(candidate){return isMaplibreModule(candidate)&&typeof candidate.Map.prototype.prepareFeatures=="function"}let modularMapCapabilities;async function loadModularMapModule(importer=()=>import("@aceshooting/lyra-map").then(source=>modularMapCapabilities??=Object.freeze({get Map(){return source.Map},get Marker(){return source.Marker},get Popup(){return source.Popup}}))){try{const value=await importer(),module=resolveOptionalPeerCapability(value,isModularMapModule);if(module)return module;const candidate=unwrapOptionalPeerDefault(value),missing=missingMaplibreCapability(candidate)??"Map.prototype.prepareFeatures";throw new Error(`Invalid optional peer \`@aceshooting/lyra-map\`: missing or invalid \`${missing}\` capability.`)}catch(error){return console.warn("<lr-map> needs the optional peer dependency `@aceshooting/lyra-map` — install it with `pnpm add @aceshooting/lyra-map`.",error),null}}let modularMap;function loadModularMap(){return modularMap??=loadModularMapModule()}async function loadMapControl(kind,engine,module){if(kind==="globe"||kind==="terrain"){const runtime=await import("./map-scene-controls.js");return kind==="globe"?runtime.MapGlobeControl:runtime.MapTerrainControl}const name={navigation:"NavigationControl",scale:"ScaleControl",geolocate:"GeolocateControl",attribution:"AttributionControl"}[kind],provided=module?.[name];if(isConstructor(provided))return provided;if(engine!=="modular")return null;try{const source=kind==="navigation"?await import("@aceshooting/lyra-map/controls/navigation"):kind==="scale"?await import("@aceshooting/lyra-map/controls/scale"):kind==="geolocate"?await import("@aceshooting/lyra-map/controls/geolocate"):await import("@aceshooting/lyra-map/controls/attribution"),candidate=unwrapOptionalPeerDefault(source),control=isObjectLike(candidate)?candidate[name]:void 0;return isConstructor(control)?control:null}catch(error){return console.warn(`<lr-map> could not load the ${kind} control from \`@aceshooting/lyra-map\`.`,error),null}}export{loadMapControl,loadMaplibre,loadMaplibreModule,loadModularMap,loadModularMapModule};
@@ -0,0 +1 @@
1
+ import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,readOwnArrayLength,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{createMapSceneAdmissionError,mapSceneAdmissionErrorCode}from"./map-scene-errors.js";import{captureMapSceneSourceMetadata,readMapSceneSource}from"./map-scene-source-snapshot.js";const candidates=new WeakMap,baseFields=["id","label","kind","color","opacity","interactive","showLabel"],latitudeLimit=85.0511287798066,radians=Math.PI/180;function invalid(){throw createMapSceneAdmissionError("invalid")}function limit(){throw createMapSceneAdmissionError("limit")}function own(record2,key){const descriptor=getOwnDataDescriptor(record2,key);return descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&invalid(),descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function record(value,fields){isPlainDataRecord(value)||invalid();const snapshot={};for(const key of Reflect.ownKeys(value))(typeof key!="string"||!fields.includes(key))&&invalid(),snapshot[key]=own(value,key);return snapshot}function arrayLength(value,minimum,maximum,capped=!1){Array.isArray(value)||invalid();const length=readOwnArrayLength(value);return(length===void 0||length<minimum)&&invalid(),length>maximum?capped?limit():invalid():length}function array(value,minimum,maximum,capped=!1){const length=arrayLength(value,minimum,maximum,capped);Array.isArray(value)||invalid(),Reflect.ownKeys(value).length!==length+1&&invalid();const result=[];for(let index=0;index<length;index++){const descriptor=getOwnDataDescriptor(value,String(index));(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)&&invalid(),result.push(descriptor.value)}return result}function number(value,minimum=-1/0,maximum=1/0){return(typeof value!="number"||!Number.isFinite(value)||value<minimum||value>maximum)&&invalid(),value===0?0:value}function positive(value,fallback){const result=number(value===void 0?fallback:value,0);return result===0&&invalid(),result}function boolean(value,fallback){return value===void 0?fallback:(typeof value!="boolean"&&invalid(),value)}function longitude(value){const finite=number(value);if(finite>=-180&&finite<180)return finite;const normalized=(finite%360+540)%360-180;return normalized===0?0:normalized}function position(value){const data=record(value,["lngLat","altitude","altitudeReference"]),coordinates=array(own(data,"lngLat"),2,2),lngLat=Object.freeze([longitude(coordinates[0]),number(coordinates[1],-latitudeLimit,latitudeLimit)]),altitude=own(data,"altitude"),authoredReference=own(data,"altitudeReference"),reference=authoredReference===void 0?"sea-level":authoredReference;return reference!=="sea-level"&&reference!=="terrain"&&invalid(),Object.freeze({lngLat,altitude:number(altitude===void 0?0:altitude,-12e3,1e8),altitudeReference:reference})}function orientation(value){const entries=value===void 0?[0,0,0,1]:array(value,4,4).map(entry=>number(entry)),maximum=Math.max(...entries.map(Math.abs));maximum===0&&invalid();const scaled=entries.map(entry=>entry/maximum),magnitude=Math.hypot(...scaled),normalized=scaled.map(entry=>entry===0?0:entry/magnitude);return Object.freeze([normalized[0],normalized[1],normalized[2],normalized[3]])}function segment(start,end){start.altitudeReference!==end.altitudeReference&&invalid();const unit=point=>{const lng=point.lngLat[0]*radians,lat=point.lngLat[1]*radians;return[Math.cos(lat)*Math.cos(lng),Math.cos(lat)*Math.sin(lng),Math.sin(lat)]},a=unit(start),b=unit(end),sine=Math.hypot(a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]);return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]<0&&sine<1e-8&&invalid(),start.lngLat[0]!==end.lngLat[0]||start.lngLat[1]!==end.lngLat[1]}function objectDescriptor(value){isPlainDataRecord(value)||invalid();const kind=own(value,"kind");let fields;switch(kind){case"marker":fields=["position","radius"];break;case"path":fields=["positions","interpolation","width"];break;case"arc":fields=["start","end","height","width"];break;case"model":fields=["position","source","metersPerUnit","orientation"];break;default:return invalid()}const snapshot=record(value,[...baseFields,...fields]);return own(snapshot,"kind")!==kind&&invalid(),snapshot}function preflight(values,sourceMetadata){const descriptors=values.map(objectDescriptor),pathLengths=new Map;let positions=0,text=0,models=0;for(const data of descriptors){const kind=own(data,"kind");if(kind==="path"){const length=arrayLength(own(data,"positions"),2,4096,!0);pathLengths.set(data,length),positions+=length}else positions+=kind==="arc"?2:1;positions>65536&&limit();for(const[key,maximum]of[["id",1024],["label",16384],["color",1024]]){const value=own(data,key);value===void 0&&key==="color"||(typeof value!="string"&&invalid(),value.length>maximum&&limit(),text+=value.length)}if(kind==="model"){++models>32&&limit();const source=captureMapSceneSourceMetadata(own(data,"source")),prior=sourceMetadata.get(source.record);prior&&(prior.kind!==source.kind||prior.format!==source.format||(prior.kind==="url"&&source.kind==="url"?prior.src!==source.src:prior.kind==="bytes"&&source.kind==="bytes"&&prior.bytes!==source.bytes))&&invalid(),sourceMetadata.set(source.record,source),source.kind==="url"&&(text+=source.src.length)}text>4194304&&limit()}for(const[data,length]of pathLengths){const positions2=array(own(data,"positions"),2,4096,!0);positions2.length!==length&&invalid(),data.positions=Object.freeze(positions2)}return descriptors}function object(data){const kind=own(data,"kind"),id=own(data,"id"),label=own(data,"label");(typeof id!="string"||id.length===0||id.length>1024||id.trim().length===0||typeof label!="string"||label.trim().length===0)&&invalid();const authoredColor=own(data,"color"),color=authoredColor===void 0?void 0:sanitizeCssColor(authoredColor);authoredColor!==void 0&&color===void 0&&invalid();const opacity=own(data,"opacity"),base={id,label,...color===void 0?{}:{color},opacity:number(opacity===void 0?1:opacity,0,1),interactive:boolean(own(data,"interactive"),!0),showLabel:boolean(own(data,"showLabel"),!1)};switch(kind){case"marker":return Object.freeze({...base,kind,position:position(own(data,"position")),radius:positive(own(data,"radius"),6)});case"path":{const positions=Object.freeze(array(own(data,"positions"),2,4096).map(position)),authoredInterpolation=own(data,"interpolation"),interpolation=authoredInterpolation===void 0?"great-circle":authoredInterpolation;interpolation!=="linear"&&interpolation!=="great-circle"&&invalid();let hasLength=!1;for(let index=1;index<positions.length;index++)hasLength=segment(positions[index-1],positions[index])||hasLength;return hasLength||invalid(),Object.freeze({...base,kind,positions,interpolation,width:positive(own(data,"width"),2)})}case"arc":{const start=position(own(data,"start")),end=position(own(data,"end"));return segment(start,end)||invalid(),Object.freeze({...base,kind,start,end,height:number(own(data,"height"),0),width:positive(own(data,"width"),2)})}case"model":return Object.freeze({...base,kind,position:position(own(data,"position")),source:readMapSceneSource(own(data,"source")),metersPerUnit:positive(own(data,"metersPerUnit"),1),orientation:orientation(own(data,"orientation"))});default:return invalid()}}function snapshotMapSceneRequest(value){try{const data=record(value,["connection","revision"]),connection=own(data,"connection"),revision=own(data,"revision");return(connection===null||typeof connection!="object"||typeof revision!="number"||!Number.isSafeInteger(revision)||revision<1)&&invalid(),Object.freeze({connection,revision})}catch{return invalid()}}function stageMapSceneAdmission(value,options){let sourceStage;try{const request=snapshotMapSceneRequest(options.request),scene=record(value,["objects"]),sourceMetadata=new Map,objects=preflight(array(own(scene,"objects"),0,2e3,!0),sourceMetadata).map(object),ids=new Set,sources=[],sourceIndices=new Map;for(const admitted2 of objects)ids.has(admitted2.id)&&invalid(),ids.add(admitted2.id),admitted2.kind==="model"&&(sourceIndices.has(admitted2.source)||(sourceIndices.set(admitted2.source,sources.length),sources.push(admitted2.source)));sourceStage=options.sources.stage(sources,request,sources.map(source=>sourceMetadata.get(source)));const stage=sourceStage,admitted=Object.freeze(objects.map(entry=>{if(entry.kind!=="model")return entry;const receipt=stage.receipts[sourceIndices.get(entry.source)];return receipt||invalid(),Object.freeze({...entry,source:receipt})})),state={sources:options.sources,consumed:!1},candidate=Object.freeze({request,objects:admitted,sourceStage:stage,dispose(){state.consumed=!0,stage.dispose()}});return candidates.set(candidate,state),candidate}catch(error){if(sourceStage?.dispose(),mapSceneAdmissionErrorCode(error)!==void 0)throw error;return invalid()}}function consumeMapSceneAdmission(candidate,sources,connection){const state=candidates.get(candidate);(!state||state.consumed||state.sources!==sources||candidate.request.connection!==connection)&&invalid(),state.consumed=!0}export{consumeMapSceneAdmission,snapshotMapSceneRequest,stageMapSceneAdmission};
@@ -0,0 +1 @@
1
+ const hostBindings=new WeakMap,noop=()=>{};function createMapSceneCompletionHost(options){const{owner}=options,tokens=new WeakMap;let input;function token(value){let result=tokens.get(value);return result||(result=Object.freeze({}),tokens.set(value,result)),result}function captureInput(){const next=owner.captureRenderPublication(),publicationToken=token(next);if(input?.publicationToken===publicationToken)return input;const targets=new Map(next.state.targets.map(target=>[target.id,target])),members=next.accepted.objects.map(row=>{const fact=targets.get(row.id);let target;if(fact&&(fact.kind==="marker"||fact.kind==="model")){const position=Object.freeze({lngLat:Object.freeze([fact.position.lngLat[0],fact.position.lngLat[1]]),altitude:fact.position.altitude,altitudeReference:fact.position.altitudeReference});target=Object.freeze({token:token(fact),acceptedPositionRevision:fact.acceptedPositionRevision,position})}return Object.freeze({id:row.id,kind:row.kind,rowToken:token(row),target})}),result=Object.freeze({publicationToken,stateToken:token(next.state),phase:next.phase,acceptedSceneRevision:next.accepted.acceptedSceneRevision,renderInput:next.input,members:Object.freeze(members)});return input=result,result}function current(expected){if(captureInput()!==expected||expected.phase!=="resolved")return!1;try{return options.isCurrent()&&captureInput()===expected}catch{return!1}}const host=Object.freeze({captureInput,subscribeInput:listener=>owner.subscribeRenderPublication(listener),claimPaintSerial(expected){if(current(expected))return owner.claimPaintFrameSerial(owner.captureRenderPublication())},captureCameraFacts(expected){if(current(expected))try{const facts=options.captureCameraFacts(owner.captureRenderPublication());return current(expected)?facts:void 0}catch{return}}});return hostBindings.set(host,{owner,current}),host}function createMapSceneCompletionAdapter(options){const{connection,state,owner,host,port}=options,binding=hostBindings.get(host);if(!binding||binding.owner!==owner||state!==owner.state||state.connection!==connection)throw new TypeError("Invalid map scene completion adapter");let disposed=!1;const releases=new Set,frames=new WeakMap;function live(input){return!disposed&&binding.current(input)&&!disposed&&host.captureInput()===input&&state.capture()===owner.captureRenderPublication().state}function retain(acquire){if(disposed)return noop;const release=acquire();let active=!0;const retire=()=>{if(active){active=!1,releases.delete(retire);try{release()}catch{}}};return disposed?retire():releases.add(retire),retire}function targetFor(input,id){if(!live(input))return;const fact=state.capture().targets.find(target=>target.id===id);return fact&&(fact.kind==="marker"||fact.kind==="model")?fact:void 0}function current(frame,target){const input=frames.get(frame);if(!input||targetFor(input,target.id)!==target)return!1;const member=input.members.find(row=>row.id===target.id);if(!member?.target)return!1;try{return port.current(frame,target.id,member.target.token)&&live(input)&&targetFor(input,target.id)===target}catch{return!1}}const backing=Object.freeze({connection,state,watchTarget(id){return retain(()=>port.watchTarget(id))},subscribeCompletedFrames(listener){let active=!0;return retain(()=>{const release=port.subscribeCompletedFrames(frame=>{if(disposed||!active)return;const input=host.captureInput();if(!live(input)||!active)return;const previous=frames.get(frame);previous&&previous!==input||(frames.set(frame,input),listener(frame))});return()=>{active=!1,release()}})},current,projectTarget(frame,id){const input=frames.get(frame),target=input&&targetFor(input,id);if(!(!target||!current(frame,target)))try{const projection=port.projectTarget(frame,id);return current(frame,target)?projection:void 0}catch{return}},requestFrame(){!disposed&&live(host.captureInput())&&port.requestFrame()}});return Object.freeze({backing,dispose(){if(!disposed){disposed=!0;for(const release of[...releases])release()}}})}export{createMapSceneCompletionAdapter,createMapSceneCompletionHost};
@@ -0,0 +1 @@
1
+ function captureMapSceneCompletionCamera(options){try{const{expected}=options;if(expected.phase!=="resolved"||!options.isCurrent()||options.capturePublication()!==expected)return;const map=options.captureMap();if(!map||typeof map.getCenter!="function"||typeof map.getZoom!="function"||typeof map.getPitch!="function"||typeof map.getMaxBounds!="function"||typeof map.getMinZoom!="function"||typeof map.getMaxZoom!="function"||typeof map.getTerrain!="function"||typeof map.isMoving!="function"||typeof map.getProjection!="function")return;const latitude=map.getCenter().lat,zoom=map.getZoom(),pitch=map.getPitch(),bounds=map.getMaxBounds(),nativeMinZoom=map.getMinZoom(),nativeMaxZoom=map.getMaxZoom(),terrain=map.getTerrain(),moving=map.isMoving(),projection=map.getProjection();if(!projection||typeof projection!="object"||!("type"in projection))return;const projectionType=projection.type,intent=options.captureIntent(),explicitBounds=intent.explicitBounds,explicitZoomLimits=intent.explicitZoomLimits,canPan=typeof map.panBy=="function",canStop=typeof map.stop=="function",canObserveMotion=typeof map.on=="function"&&typeof map.off=="function";if(![latitude,zoom,pitch,nativeMinZoom,nativeMaxZoom].every(Number.isFinite)||latitude<-90||latitude>90||nativeMinZoom>nativeMaxZoom||typeof moving!="boolean"||typeof explicitBounds!="boolean"||typeof explicitZoomLimits!="boolean"||projectionType!=="mercator"&&projectionType!=="globe")return;const facts=Object.freeze({latitude,zoom,pitch,explicitBounds,explicitZoomLimits,nativeBounds:bounds!=null,nativeMinZoom,nativeMaxZoom,terrain:terrain!=null,canPan,canObserveMotion,canStop,moving,hasProjection:!0});return!options.isCurrent()||options.captureMap()!==map||options.capturePublication()!==expected?void 0:facts}catch{return}}export{captureMapSceneCompletionCamera};
@@ -0,0 +1 @@
1
+ import{admitMapTerrain,mapScenePreparation,mapSceneValueEqual,snapshotMapSceneBaseline}from"./map-scene-configuration.js";class MapSceneConfigurationController{constructor(options){this.options=options,this.projectionOwned=!1,this.terrainOwned=!1,this.revision=0,this.pending=!1,this.work=Promise.resolve()}cancel(){this.revision++,this.abort?.abort(),this.abort=void 0,this.pending=!1,this.peer=void 0,this.generation=void 0,this.baseline=void 0,this.applied=void 0,this.projectionOwned=!1,this.terrainOwned=!1}sync(peer,generation,current,projection,terrain){if((peer!==this.peer||generation!==this.generation)&&(this.cancel(),this.peer=peer,this.generation=generation),!this.baseline&&projection===void 0&&terrain===void 0)return;this.abort?.abort();const abort=new AbortController;this.abort=abort;const revision=++this.revision,live=()=>!abort.signal.aborted&&this.revision===revision&&this.peer===peer&&current();try{if(!live())return;const admittedTerrain=admitMapTerrain(terrain);for(const key of["getStyle","getProjection","getTerrain"])if(typeof peer[key]!="function")throw new TypeError("Map scene reader unavailable");const style=peer.getStyle();if(!live())return;if(style===null||typeof style!="object"||Array.isArray(style))throw new TypeError("Map style unavailable");const originalProjection=peer.getProjection();if(!live())return;const originalTerrain=peer.getTerrain();if(!live())return;const observed=snapshotMapSceneBaseline(originalProjection,originalTerrain);if(!live())return;if(!this.baseline){for(const key of["projection","terrain"]){const descriptor=Object.getOwnPropertyDescriptor(style,key);if(descriptor&&!("value"in descriptor))throw new TypeError("Invalid map scene descriptor");if(!live())return}const baseline=observed,styleBaseline=snapshotMapSceneBaseline(Object.getOwnPropertyDescriptor(style,"projection")?.value,Object.getOwnPropertyDescriptor(style,"terrain")?.value);if(!mapSceneValueEqual(baseline,styleBaseline))throw new TypeError("Inconsistent map scene readers");if(!live())return;this.baseline=baseline,this.applied=baseline}const next={projection:projection===void 0?this.projectionOwned?this.baseline.projection:observed.projection:Object.freeze({type:projection}),terrain:admittedTerrain===void 0?this.terrainOwned?this.baseline.terrain:observed.terrain:admittedTerrain},projectionOwned=projection!==void 0,terrainOwned=admittedTerrain!==void 0,participatesProjection=projectionOwned||this.projectionOwned,participatesTerrain=terrainOwned||this.terrainOwned,writeProjection=participatesProjection&&!mapSceneValueEqual(next.projection,observed.projection),writeTerrain=participatesTerrain&&!mapSceneValueEqual(next.terrain,observed.terrain);if(participatesProjection&&typeof peer.setProjection!="function"||participatesTerrain&&typeof peer.setTerrain!="function")throw new TypeError("Map scene writer unavailable");const preparation=mapScenePreparation(participatesProjection?next.projection:void 0,participatesTerrain?next.terrain:void 0,style);if(!live())return;if(!writeProjection&&!writeTerrain){this.projectionOwned=projectionOwned,this.terrainOwned=terrainOwned,this.pending=!1,this.work=Promise.resolve(),this.options.changed();return}if(typeof peer.on!="function"||typeof peer.off!="function")throw new TypeError("Map error subscription unavailable");this.pending=!0,this.options.changed(),this.work=this.apply(peer,preparation,next,writeProjection,writeTerrain,participatesProjection,participatesTerrain,abort.signal,live).then(()=>{live()&&(this.projectionOwned=projectionOwned,this.terrainOwned=terrainOwned)}).catch(()=>{live()&&this.options.failed()}).finally(()=>{this.revision===revision&&(this.pending=!1,this.options.changed())})}catch{live()&&(this.pending=!1,this.options.failed()),this.work=Promise.resolve()}}async apply(peer,preparation,next,projection,terrain,participatesProjection,participatesTerrain,signal,live){let release=()=>{};const cancelled=new Promise(resolve=>{const cancel=()=>resolve();signal.addEventListener("abort",cancel,{once:!0}),release=()=>{signal.removeEventListener("abort",cancel)}});try{if(await Promise.race([peer.prepareFeatures?.(preparation,{signal})??Promise.resolve(),cancelled]),!live())return;const projectionNow=peer.getProjection();if(!live())return;const terrainNow=peer.getTerrain();if(!live())return;const observed=snapshotMapSceneBaseline(projectionNow,terrainNow);if(!live())return;const style=peer.getStyle();if(!live()||(mapScenePreparation(participatesProjection?next.projection:void 0,participatesTerrain?next.terrain:void 0,style),!live()))return;this.applied=observed;let nativeError=!1;const error=()=>{nativeError=!0};peer.on("error",error);try{if(!live())return;if(projection&&(this.applied={projection:next.projection,terrain:this.applied.terrain},this.projectionOwned=!0,peer.setProjection(next.projection)),nativeError)throw new Error("Map projection application failed");if(!live())return;if(terrain&&(this.applied={projection:this.applied.projection,terrain:next.terrain},this.terrainOwned=!0,peer.setTerrain(next.terrain)),nativeError)throw new Error("Map terrain application failed")}finally{peer.off("error",error)}}finally{release()}}}export{MapSceneConfigurationController};
@@ -0,0 +1,15 @@
1
+ import type{LyraMapFeatureRequirements}from'./map-loader.js';import{type LyraMapStyleValue}from'./map-style-value.js';
2
+ /** Declarative shorthand projection override.*/
3
+ export type LyraMapProjection='mercator'|'globe';
4
+ /** A current-style raster elevation source and its nonnegative vertical scale.*/
5
+ export interface LyraMapTerrain{readonly source:string;readonly exaggeration?:number;}
6
+ /** Complete detached native projection specification, retained for replay.*/
7
+ export type LyraMapSceneProjection={readonly[key:string]:LyraMapStyleValue;};export interface LyraMapSceneBaseline{readonly projection:LyraMapSceneProjection;readonly terrain:LyraMapTerrain|null;}export declare function normalizeMapProjection(value:unknown):LyraMapProjection|undefined;
8
+ /** Admit a detached bounded terrain value without executing caller accessors.*/
9
+ export declare function admitMapTerrain(input:unknown):LyraMapTerrain|null|undefined;
10
+ /** Snapshot complete replay data independently of modular preparation requirements.*/
11
+ export declare function snapshotMapSceneBaseline(projection:unknown,terrain:unknown):LyraMapSceneBaseline;
12
+ /** Reduced activation metadata; never pass this object to the native projection setter.*/
13
+ export declare function mapScenePreparation(projection:LyraMapSceneProjection|undefined,terrain:LyraMapTerrain|null|undefined,style:unknown):LyraMapFeatureRequirements;
14
+ /** Compare admitted plain data independent of record insertion order.*/
15
+ export declare function mapSceneValueEqual(first:unknown,second:unknown):boolean;
@@ -0,0 +1 @@
1
+ import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{safeValue}from"./map-style-value.js";function normalizeMapProjection(value){return value==="mercator"||value==="globe"?value:void 0}function own(record,key){const descriptor=getOwnDataDescriptor(record,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid map scene descriptor");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function admitMapTerrain(input){if(input==null)return input;if(!isPlainDataRecord(input))throw new TypeError("Invalid map terrain");const source=own(input,"source"),scale=own(input,"exaggeration");if(typeof source!="string"||source.trim().length===0||source.length>4096||scale!==void 0&&(typeof scale!="number"||!Number.isFinite(scale)||scale<0))throw new TypeError("Invalid map terrain");return Object.freeze({source,exaggeration:scale===void 0?1:scale})}function snapshotMapSceneBaseline(projection,terrain){const snapshot=safeValue(projection===void 0?{type:"mercator"}:projection)?.value;if(!isPlainDataRecord(snapshot))throw new TypeError("Invalid map projection");const type=own(snapshot,"type");if((typeof type!="string"||type.length===0)&&!Array.isArray(type))throw new TypeError("Invalid map projection");if(Array.isArray(type)&&type.length===0)throw new TypeError("Invalid map projection");return Object.freeze({projection:snapshot,terrain:admitMapTerrain(terrain)??null})}function terrainSource(style,source){if(!isPlainDataRecord(style))throw new TypeError("Invalid current map style");const sources=own(style,"sources");if(!isPlainDataRecord(sources))throw new TypeError("Invalid map terrain source");const descriptor=own(sources,source);if(!isPlainDataRecord(descriptor)||own(descriptor,"type")!=="raster-dem")throw new TypeError("Invalid map terrain source");const result=Object.create(null);return Object.defineProperty(result,source,{value:Object.freeze({type:"raster-dem"}),enumerable:!0}),Object.freeze(result)}function mapScenePreparation(projection,terrain,style){let projectionMetadata;if(projection!==void 0){const type=own(projection,"type");if(typeof type=="string"&&type!=="mercator"&&type!=="globe")throw new TypeError("Unsupported map projection");if(typeof type!="string"&&!Array.isArray(type))throw new TypeError("Invalid map projection");projectionMetadata=Object.freeze({type:type==="mercator"?"mercator":"globe"})}return Object.freeze({...projectionMetadata===void 0?{}:{projection:projectionMetadata},...terrain===void 0?{}:{terrain:terrain!==null},...terrain==null?{}:{sources:terrainSource(style,terrain.source)}})}function mapSceneValueEqual(first,second){if(first===second)return!0;if(Array.isArray(first)||Array.isArray(second))return Array.isArray(first)&&Array.isArray(second)&&first.length===second.length&&first.every((value,index)=>mapSceneValueEqual(value,second[index]));if(!isPlainDataRecord(first)||!isPlainDataRecord(second))return!1;const keys=Object.keys(first);return keys.length===Object.keys(second).length&&keys.every(key=>Object.hasOwn(second,key)&&mapSceneValueEqual(own(first,key),own(second,key)))}export{admitMapTerrain,mapScenePreparation,mapSceneValueEqual,normalizeMapProjection,snapshotMapSceneBaseline};
@@ -0,0 +1 @@
1
+ import{admitMapTerrain,mapScenePreparation}from"./map-scene-configuration.js";class SceneControl{constructor(kind,options){this.kind=kind,this.pressed=!1,this.queued=!1,this.generation=0,this.listeners=new Set,this.events=["terrain","projectiontransition","style.load","sourcedata","idle"],this.schedule=()=>{if(this.queued||!this.current())return;this.queued=!0;const generation=this.generation;queueMicrotask(()=>{generation===this.generation&&(this.queued=!1,this.refreshSceneControl())})},this.activate=()=>{if(this.refreshSceneControl(),!this.current()||!this.button||this.button.disabled)return;this.button.disabled=!0,this.button.setAttribute("aria-busy","true");const event=Object.freeze({kind:this.kind,pressed:this.pressed,...this.terrain?{terrain:this.terrain}:{}});for(const listener of[...this.listeners]){if(!this.current())break;listener(event)}this.schedule()},kind==="terrain"&&(this.terrain=admitMapTerrain(options)??void 0)}setSceneContext(context){this.context=context,this.refreshSceneControl()}on(type,listener){type==="activate"&&this.listeners.add(listener)}off(type,listener){type==="activate"&&this.listeners.delete(listener)}onAdd(value){const peer=value;for(const name of["getCanvas","getStyle","getProjection","getTerrain","on","off",this.kind==="globe"?"setProjection":"setTerrain"])if(typeof peer?.[name]!="function")throw new TypeError("Scene control capability is unavailable");this.peer=peer;const document=peer.getCanvas().ownerDocument,root=document.createElement("div");root.className=`maplibregl-ctrl maplibregl-ctrl-group map-scene-${this.kind}-control`,root.part.add(`${this.kind}-control`);const button=document.createElement("button");button.type="button",button.part.add(`${this.kind}-button`);const icon=document.createElementNS("http://www.w3.org/2000/svg","svg");icon.setAttribute("viewBox","0 0 24 24"),icon.setAttribute("aria-hidden","true"),icon.setAttribute("focusable","false"),icon.setAttribute("part",`${this.kind}-icon`),icon.setAttribute("class","map-scene-control-icon");const path=document.createElementNS("http://www.w3.org/2000/svg","path");path.setAttribute("d",this.kind==="globe"?"M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM3 12h18M12 3c-5 5-5 13 0 18M12 3c5 5 5 13 0 18":"m2 20 7-13 4 7 3-5 6 11ZM6 13l3 2 2-2"),icon.append(path),button.append(icon),root.append(button),this.root=root,this.button=button,button.addEventListener("click",this.activate);try{for(const event of this.events)peer.on(event,this.schedule)}catch(error){throw this.onRemove(),error}return this.refreshSceneControl(),root}onRemove(){const peer=this.peer;this.peer=void 0,this.generation++,this.button?.removeEventListener("click",this.activate);for(const event of this.events)try{peer?.off(event,this.schedule)}catch{}this.root?.remove(),this.root=void 0,this.button=void 0,this.queued=!1}current(){return!!this.peer&&!!this.context?.isCurrent()}refreshSceneControl(){const context=this.context,button=this.button,peer=this.peer;if(!context||!button||!peer||!this.current())return;const state=context.state(this.kind);if(!this.current())return;let unavailable=!1;if(state.ready&&!state.busy)try{if(this.kind==="globe"){const type=peer.getProjection()?.type;this.pressed=type==="globe"?!0:type==="mercator"||type===void 0?!1:"mixed"}else this.pressed=peer.getTerrain()!=null,this.pressed||(this.terrain?mapScenePreparation(void 0,this.terrain,peer.getStyle()):unavailable=!0)}catch{unavailable=!0}this.current()&&(button.setAttribute("aria-label",state.label),button.title=state.label,button.setAttribute("aria-pressed",String(this.pressed)),button.setAttribute("aria-busy",String(state.busy)),button.disabled=!state.ready||state.busy||unavailable,context.unavailable(this.kind,unavailable))}}class MapGlobeControl extends SceneControl{constructor(options){super("globe",options)}}class MapTerrainControl extends SceneControl{constructor(options){super("terrain",options)}}export{MapGlobeControl,MapTerrainControl};
@@ -0,0 +1 @@
1
+ const codes=new WeakMap;function createMapSceneAdmissionError(code){const error=new TypeError(code==="limit"?"Map scene input limit exceeded":"Invalid map scene descriptor");return codes.set(error,code),Object.freeze(error)}function mapSceneAdmissionErrorCode(error){return error!==null&&(typeof error=="object"||typeof error=="function")?codes.get(error):void 0}export{createMapSceneAdmissionError,mapSceneAdmissionErrorCode};
@@ -0,0 +1 @@
1
+ import{sceneLineGrounded}from"./map-scene-lines.js";const EMPTY_DATA=Object.freeze({type:"FeatureCollection",features:Object.freeze([])}),LAYOUT=Object.freeze({"line-join":"round","line-cap":"round"}),PAINT=Object.freeze({"line-color":["get","color"],"line-width":["get","width"],"line-opacity":["get","opacity"]}),MARKER_LAYER=/^scene-markers-\d+$/;let sequence=0;function terrainActive(map){try{const terrain=map.getTerrain?.();return terrain!=null}catch{return!1}}function createMapSceneLineLayer(options){const{map}=options,canvas=(()=>{try{return map.getCanvas()}catch{return}})();let request,ids,phase="pending",failure="engine",epoch=0,disposed=!1,awaitingStyle=!1,contextLost=!1,abort;const current=()=>!disposed&&options.isCurrent();function notify(){if(current())try{options.changed()}catch{}}function cancel(){epoch++,abort?.abort(),abort=void 0}function remove(){const owned=ids;if(owned){try{map.getLayer(owned.layer)&&map.removeLayer(owned.layer)}catch{}try{map.getSource(owned.source)&&map.removeSource(owned.source)}catch{}}}function allocate(){for(let attempt=0;attempt<512;attempt++){const source=`lr-scene-lines-${++sequence}`,layer=`${source}-line`;if(!map.getSource(source)&&!map.getLayer(source)&&!map.getLayer(layer))return Object.freeze({source,layer})}throw new Error("Scene line identifiers are unavailable.")}function before(){const layers=map.getStyle?.()?.layers;return Array.isArray(layers)?layers.find(layer=>typeof layer?.id=="string"&&MARKER_LAYER.test(layer.id))?.id:void 0}function fail(){disposed||(cancel(),remove(),phase="failed",failure="engine",notify())}async function install(data,attempt,signal){const live=()=>current()&&attempt===epoch&&!signal.aborted&&!awaitingStyle&&options.styleLoaded();try{if(typeof map.prepareFeatures=="function"){const owned2=ids??{source:"lr-scene-lines",layer:"lr-scene-lines-line"};await map.prepareFeatures({sources:{[owned2.source]:{type:"geojson",data:EMPTY_DATA}},layers:[{id:owned2.layer,type:"line",source:owned2.source}]},{signal})}if(!live())return;remove();const owned=ids=allocate();if(map.addSource(owned.source,{type:"geojson",data}),!live()){remove();return}if(map.addLayer({id:owned.layer,type:"line",source:owned.source,layout:LAYOUT,paint:PAINT},before()),!live()){remove();return}if(!map.getSource(owned.source)||!map.getLayer(owned.layer))throw new Error("Scene lines were not installed.");phase="installed",abort=void 0,notify()}catch{current()&&attempt===epoch&&!signal.aborted&&fail()}}function apply(){if(!current())return;const next=request;if(cancel(),!next){remove(),ids=void 0,phase="pending",notify();return}if("failure"in next){remove(),phase="failed",failure=next.failure,notify();return}if(awaitingStyle||!options.styleLoaded()){phase="pending",notify();return}const owned=ids;if(owned&&phase!=="failed")try{const source=map.getSource(owned.source);if(source&&map.getLayer(owned.layer)&&typeof source.setData=="function"){if(source.setData(next.data),!current()||request!==next)return;phase="installed",notify();return}}catch{fail();return}phase="pending",notify();const controller=abort=new AbortController,attempt=epoch;install(next.data,attempt,controller.signal)}const terrainChanged=()=>{current()&&phase==="installed"&&notify()},lost=()=>{current()&&(contextLost=!0,notify())},restored=()=>{current()&&(contextLost=!1,apply())};try{Reflect.apply(map.on,map,["terrain",terrainChanged])}catch{}return canvas?.addEventListener("webglcontextlost",lost),canvas?.addEventListener("webglcontextrestored",restored),{update(value){disposed||(request=value,apply())},styleReady(){disposed||(awaitingStyle=!1,request&&apply())},invalidateStyle(){disposed||(cancel(),awaitingStyle=!0,phase==="installed"&&(phase="pending",notify()))},capture(){const revision=request?.revision;if(!request)return{revision,outcome:{state:"none"}};if(phase==="failed")return{revision,outcome:{state:"failed",code:failure}};if(contextLost)return{revision,outcome:{state:"failed",code:"context-lost"}};if(phase!=="installed"||"failure"in request)return{revision,outcome:{state:"pending"}};const terrain=terrainActive(map);return{revision,outcome:{state:"drawn",approximate:request.objects.some(object=>!sceneLineGrounded(object,terrain))}}},dispose(){if(!disposed){cancel(),disposed=!0;try{map.off?.("terrain",terrainChanged)}catch{}canvas?.removeEventListener("webglcontextlost",lost),canvas?.removeEventListener("webglcontextrestored",restored),remove(),ids=void 0,request=void 0}}}}export{createMapSceneLineLayer};
@@ -0,0 +1 @@
1
+ const SCENE_LINE_VERTEX_LIMIT=262144,SCENE_ARC_MIN_SEGMENTS=32,radians=Math.PI/180,FINEST_STEP=radians;function unit(position){const lng=position.lngLat[0]*radians,lat=position.lngLat[1]*radians;return[Math.cos(lat)*Math.cos(lng),Math.cos(lat)*Math.sin(lng),Math.sin(lat)]}function angle(a,b){const cross=Math.hypot(a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]);return Math.atan2(cross,a[0]*b[0]+a[1]*b[1]+a[2]*b[2])}function sceneArcAltitude(start,end,height,t){return start+(end-start)*t+height*4*t*(1-t)}function sceneLineGrounded(object,terrain){return object.kind==="arc"&&object.height!==0?!1:(object.kind==="arc"?[object.start,object.end]:object.positions).every(position=>position.altitude===0&&(!terrain||position.altitudeReference==="terrain"))}function segments(object){if(object.kind==="arc")return[{start:object.start,end:object.end,angle:angle(unit(object.start),unit(object.end)),greatCircle:!0,minimum:32,height:object.height}];const greatCircle=object.interpolation==="great-circle",result=[];for(let index=1;index<object.positions.length;index++){const start=object.positions[index-1],end=object.positions[index];result.push({start,end,angle:greatCircle?angle(unit(start),unit(end)):0,greatCircle,minimum:1,height:0})}return result}function steps(segment,step){return segment.greatCircle?Math.max(segment.minimum,Math.ceil(segment.angle/step)):1}function unwrap(longitude,previous){if(previous===void 0)return longitude;let value=longitude;for(;value-previous>180;)value-=360;for(;value-previous<-180;)value+=360;return value}function emit(target,longitude,latitude,altitude){const value=unwrap(longitude,target.at(-1)?.[0]);target.push(Object.freeze([value===0?0:value,latitude===0?0:latitude,altitude===0?0:altitude]))}function trace(object,rows,step){const coordinates=[],first=rows[0].start;emit(coordinates,first.lngLat[0],first.lngLat[1],first.altitude);for(const segment of rows){const count=steps(segment,step),{start,end}=segment,a=unit(start),b=unit(end),sine=Math.sin(segment.angle);for(let index=1;index<count;index++){const t=index/count,altitude=object.kind==="arc"?sceneArcAltitude(start.altitude,end.altitude,segment.height,t):start.altitude+(end.altitude-start.altitude)*t;if(sine<1e-12){emit(coordinates,start.lngLat[0]+(unwrap(end.lngLat[0],start.lngLat[0])-start.lngLat[0])*t,start.lngLat[1]+(end.lngLat[1]-start.lngLat[1])*t,altitude);continue}const wa=Math.sin((1-t)*segment.angle)/sine,wb=Math.sin(t*segment.angle)/sine,x=wa*a[0]+wb*b[0],y=wa*a[1]+wb*b[1],z=wa*a[2]+wb*b[2];emit(coordinates,Math.atan2(y,x)/radians,Math.atan2(z,Math.hypot(x,y))/radians,altitude)}emit(coordinates,end.lngLat[0],end.lngLat[1],end.altitude)}return Object.freeze(coordinates)}function tessellateSceneLines(objects,limit=262144){const rows=objects.map(segments),count=step2=>rows.reduce((total,row)=>total+1+row.reduce((sum,segment)=>sum+steps(segment,step2),0),0);let step=FINEST_STEP;for(;count(step)>limit;){if(step>=Math.PI)return;step*=2}return Object.freeze(objects.map((object,index)=>trace(object,rows[index],step)))}function buildSceneLineData(objects,colors,limit=262144){if(objects.some(object=>!colors.has(object.id)))return;const geometry=tessellateSceneLines(objects,limit);if(!geometry)return;const features=objects.map((object,index)=>Object.freeze({type:"Feature",properties:Object.freeze({id:object.id,kind:object.kind,color:colors.get(object.id),width:object.width,opacity:object.opacity}),geometry:Object.freeze({type:"LineString",coordinates:geometry[index]})}));return Object.freeze({type:"FeatureCollection",features:Object.freeze(features)})}export{SCENE_ARC_MIN_SEGMENTS,buildSceneLineData,sceneArcAltitude,sceneLineGrounded,tessellateSceneLines};
@@ -0,0 +1 @@
1
+ import{resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{stageMapSceneAdmission}from"./map-scene-admission.js";import{createMapSceneAdmissionError,mapSceneAdmissionErrorCode}from"./map-scene-errors.js";import{createMapScenePositionRegistry}from"./map-scene-position-registry.js";import{buildSceneRenderInput,emptySceneRenderInput,nextSceneRenderRevision,snapshotScenePresentation,snapshotSceneViewport}from"./map-scene-render-input.js";import{createMapSceneSourceOwner,isStaleMapSceneSourceError}from"./map-scene-source-snapshot.js";const MAX_ENCODED_BYTES=64*1024*1024,MAX_NOTIFICATION_PASSES=6144,RENDER_STATES=new Set(["loading","ready","partial","unavailable"]),RENDER_CODES=new Set(["limit","model","resource","engine","projection","terrain","context-lost","altitude"]);function nextPaintFrameSerial(previous){return Number.isSafeInteger(previous)&&previous>=0&&previous<Number.MAX_SAFE_INTEGER?previous+1:void 0}function createMapSceneOwner(options){const{element,connection}=options;let closed=!1,notifying=!1,requestRevision=0,liveBytes=0,accepted=Object.freeze({acceptedSceneRevision:0,objects:Object.freeze([])}),view=Object.freeze({active:!1,accepted,status:void 0}),changedBaseline=view;const acceptedObservers=new Set,stateObservers=new Set,renderObservers=new Set;function current(request){return closed||request.connection!==connection||request.revision!==requestRevision?!1:options.isCurrentConnection()&&!closed&&request.connection===connection&&request.revision===requestRevision&&nextSceneRenderRevision(renderPublication.input.presentationRevision)!==void 0}let resources,stateSnapshot=Object.freeze({acceptedSceneRevision:0,registryRevision:0,targets:Object.freeze([]),viewport:void 0}),allocationRevision=0,paintFrameSerial=0,resolvedPresentation,renderPublication=Object.freeze({accepted,state:stateSnapshot,phase:"resolved",input:emptySceneRenderInput(0,1,void 0)});function createResources(){const sources=createMapSceneSourceOwner({connection,maxEncodedBytes:MAX_ENCODED_BYTES,isCurrent:current,reserveBytes(byteLength){if(!Number.isSafeInteger(byteLength)||byteLength<0)throw createMapSceneAdmissionError("invalid");if(byteLength>MAX_ENCODED_BYTES-liveBytes)throw createMapSceneAdmissionError("limit");liveBytes+=byteLength;let released=!1;return Object.freeze({release(){released||(released=!0,liveBytes-=byteLength)}})},resolveUrl(source){const target=resolveOwnerFetchTarget(element,source);return target?Object.freeze({url:target.url,owner:target.view}):null}}),registry=createMapScenePositionRegistry({connection,sources,isCurrent:current});return{sources,registry}}function subscribe(observers,listener,baseline){if(typeof listener!="function")throw new TypeError("Invalid map scene listener");if(closed)return()=>{};const observer={listener,baseline};return observers.add(observer),()=>{observers.delete(observer)}}const state=Object.freeze({connection,capture:()=>stateSnapshot,subscribe:listener=>subscribe(stateObservers,listener,stateSnapshot)});function invoke(callback){try{callback()}catch{}}function notify(){if(!(closed||notifying)){notifying=!0;try{for(let pass=0;pass<MAX_NOTIFICATION_PASSES&&!closed;pass++){let delivered=!1;for(const observer of[...stateObservers]){if(closed)return;!stateObservers.has(observer)||observer.baseline===stateSnapshot||(observer.baseline=stateSnapshot,delivered=!0,invoke(observer.listener))}for(const observer of[...acceptedObservers]){if(closed)return;!acceptedObservers.has(observer)||observer.baseline===accepted||(observer.baseline=accepted,delivered=!0,invoke(observer.listener))}for(const observer of[...renderObservers]){if(closed)return;!renderObservers.has(observer)||observer.baseline===renderPublication||(observer.baseline=renderPublication,delivered=!0,invoke(observer.listener))}if(closed||(changedBaseline!==view&&(changedBaseline=view,delivered=!0,invoke(options.changed)),!delivered))return}}finally{notifying=!1}}}function publish(active,status){view=Object.freeze({active,accepted,status}),notify()}function currentPublication(expected){if(closed||renderPublication!==expected)return!1;try{return options.isCurrentConnection()&&!closed&&renderPublication===expected}catch{return!1}}function commitRender(expected,next,presentation,nextAllocation){return currentPublication(expected)?(stateSnapshot=next.state,renderPublication=next,resolvedPresentation=presentation,allocationRevision=nextAllocation,notify(),!0):!1}function publishAccepted(objects,active){const snapshot=resources.registry.capture(),nextAccepted=Object.freeze({acceptedSceneRevision:snapshot.acceptedSceneRevision,objects}),nextState=Object.freeze({...snapshot,viewport:stateSnapshot.viewport}),revision=nextSceneRenderRevision(renderPublication.input.presentationRevision),next=Object.freeze({accepted:nextAccepted,state:nextState,phase:objects.some(object=>object.kind==="marker")?"pending":"resolved",input:emptySceneRenderInput(nextAccepted.acceptedSceneRevision,revision,nextState.viewport)});accepted=nextAccepted,stateSnapshot=nextState,renderPublication=next,resolvedPresentation=void 0,publish(active,objects.length===0?Object.freeze({revision:accepted.acceptedSceneRevision,state:"empty"}):Object.freeze({revision:accepted.acceptedSceneRevision,state:"loading"}))}function sameViewport(first,second){return first===void 0?second===void 0:second!==void 0&&first.width===second.width&&first.height===second.height&&first.pixelRatio===second.pixelRatio&&first.padding.top===second.padding.top&&first.padding.right===second.padding.right&&first.padding.bottom===second.padding.bottom&&first.padding.left===second.padding.left}return Object.freeze({state,captureAccepted:()=>accepted,captureView:()=>view,subscribeAccepted:listener=>subscribe(acceptedObservers,listener,accepted),captureRenderPublication:()=>renderPublication,claimPaintFrameSerial(expected){if(expected!==renderPublication||expected.phase!=="resolved"||!currentPublication(expected))return;const next=nextPaintFrameSerial(paintFrameSerial);return next!==void 0&&(paintFrameSerial=next),next},subscribeRenderPublication:listener=>subscribe(renderObservers,listener,renderPublication),invalidatePresentation(){const expected=renderPublication;if(closed||!accepted.objects.some(object=>object.kind==="marker"))return!1;const revision=nextSceneRenderRevision(expected.input.presentationRevision);if(revision===void 0)return!1;const next=Object.freeze({...expected,phase:"pending",input:emptySceneRenderInput(accepted.acceptedSceneRevision,revision,expected.state.viewport)});return commitRender(expected,next,void 0,allocationRevision)},commitPresentation(expected,value){if(closed||renderPublication!==expected||expected.phase!=="pending")return!1;const presentation=snapshotScenePresentation(value);if(!presentation)return!1;const revision=nextSceneRenderRevision(expected.input.presentationRevision);if(revision===void 0)return!1;const input=buildSceneRenderInput({accepted:expected.accepted,state:expected.state,phase:"resolved",presentationRevision:revision,presentation});if(!input)return!1;const next=Object.freeze({...expected,phase:"resolved",input});return commitRender(expected,next,presentation,allocationRevision)},failPresentation(expected){if(closed||renderPublication!==expected||expected.phase!=="pending")return!1;const revision=nextSceneRenderRevision(expected.input.presentationRevision);if(revision===void 0)return!1;const next=Object.freeze({...expected,phase:"unavailable",input:emptySceneRenderInput(accepted.acceptedSceneRevision,revision,expected.state.viewport)});return commitRender(expected,next,void 0,allocationRevision)},setViewport(value){const expected=renderPublication;if(closed)return!1;const copied=value===void 0?void 0:snapshotSceneViewport(value);if(value!==void 0&&!copied||sameViewport(expected.state.viewport,copied))return!1;const revision=nextSceneRenderRevision(expected.input.presentationRevision),nextAllocation=copied===void 0?allocationRevision:nextSceneRenderRevision(allocationRevision);if(revision===void 0||nextAllocation===void 0)return!1;const viewport=copied===void 0?void 0:Object.freeze({...copied,allocationRevision:nextAllocation}),nextState=Object.freeze({...expected.state,viewport}),input=expected.phase==="resolved"&&resolvedPresentation!==void 0?buildSceneRenderInput({accepted:expected.accepted,state:nextState,phase:"resolved",presentationRevision:revision,presentation:resolvedPresentation}):emptySceneRenderInput(expected.accepted.acceptedSceneRevision,revision,viewport);if(!input)return!1;const next=Object.freeze({...expected,state:nextState,input});return commitRender(expected,next,resolvedPresentation,nextAllocation)},reportRenderStatus(revision,value){if(closed||!view.active||accepted.objects.length===0||revision!==accepted.acceptedSceneRevision||value===null||typeof value!="object")return!1;const{state:next,code}=value;if(!RENDER_STATES.has(next)||code!==void 0&&!RENDER_CODES.has(code))return!1;const previous=view.status;return previous?.state==="error"||previous?.revision===revision&&previous.state===next&&previous.code===code?!1:(publish(!0,Object.freeze({revision,state:next,...code===void 0?{}:{code}})),!0)},assign(value){if(closed)return;const before=requestRevision;if(!options.isCurrentConnection()||closed||before!==requestRevision||value===void 0&&!view.active&&accepted.acceptedSceneRevision===0||nextSceneRenderRevision(renderPublication.input.presentationRevision)===void 0||!Number.isSafeInteger(requestRevision+1))return;const request=Object.freeze({connection,revision:++requestRevision});let candidate;try{const{sources,registry}=resources??=createResources();if(value===void 0){if(!registry.clear(request))return;publishAccepted(Object.freeze([]),!1);return}if(candidate=stageMapSceneAdmission(value,{request,sources}),!registry.commit(candidate))return;publishAccepted(candidate.objects,!0)}catch(error){if(candidate?.dispose(),!current(request)||isStaleMapSceneSourceError(error))return;publish(!0,Object.freeze({revision:accepted.acceptedSceneRevision,state:"error",code:mapSceneAdmissionErrorCode(error)??"invalid"}))}},close(){closed||(closed=!0,acceptedObservers.clear(),stateObservers.clear(),renderObservers.clear(),resolvedPresentation=void 0,resources?.registry.dispose(),resources?.sources.dispose(),resources=void 0)}})}export{createMapSceneOwner,nextPaintFrameSerial};
@@ -0,0 +1 @@
1
+ import{consumeMapSceneAdmission,snapshotMapSceneRequest}from"./map-scene-admission.js";import{isStaleMapSceneSourceError}from"./map-scene-source-snapshot.js";const absent=Object.freeze({status:"absent"});function targetSnapshot(facts,acceptedSceneRevision,registryRevision){const targets=[];for(const[id,lookup]of facts)lookup.status==="accepted"?targets.push(lookup.target):lookup.status==="unsupported-kind"&&targets.push(Object.freeze({id,kind:lookup.kind}));return Object.freeze({acceptedSceneRevision,registryRevision,targets:Object.freeze(targets)})}function samePosition(first,second){return first.lngLat[0]===second.lngLat[0]&&first.lngLat[1]===second.lngLat[1]&&first.altitude===second.altitude&&first.altitudeReference===second.altitudeReference}function sameFact(previous,object){return!previous||previous.status==="absent"?!1:object.kind==="path"||object.kind==="arc"?previous.status==="unsupported-kind"&&previous.kind===object.kind:previous.status==="accepted"&&previous.target.kind===object.kind&&samePosition(previous.target.position,object.position)}function release(leases){for(const lease of leases)try{lease.release()}catch{}}function createMapScenePositionRegistry(options){const{connection,sources,isCurrent}=options;let closed=!1,generation=0,acceptedSceneRevision=0,registryRevision=0,positionRevision=0,requestRevision=0,facts=new Map,snapshot=targetSnapshot(facts,acceptedSceneRevision,registryRevision),acceptedSources=[];const listeners=new Set;function current(request,expectedGeneration){return closed||request.connection!==connection||request.revision<=requestRevision?!1:isCurrent(request)&&!closed&&expectedGeneration===generation&&request.revision>requestRevision}function notify(changedIds,expectedGeneration){if(changedIds.length===0||closed||generation!==expectedGeneration)return;const notice=Object.freeze({acceptedSceneRevision,registryRevision,changedIds:Object.freeze([...changedIds])});for(const listener of[...listeners]){if(closed||generation!==expectedGeneration)return;if(listeners.has(listener))try{listener(notice)}catch{}}}function nextCounter(value){if(!Number.isSafeInteger(value+1))throw new TypeError("Map scene revision exhausted");return value+1}return Object.freeze({get acceptedSceneRevision(){return acceptedSceneRevision},target(id){return facts.get(id)??absent},capture(){return snapshot},commit(candidate){consumeMapSceneAdmission(candidate,sources,connection);const before=generation;try{if(!current(candidate.request,before))return candidate.dispose(),!1;const next=new Map,changed=[];let nextPositionRevision=positionRevision;for(const object of candidate.objects){const previous=facts.get(object.id);if(sameFact(previous,object)){next.set(object.id,previous);continue}changed.push(object.id),nextPositionRevision=nextCounter(nextPositionRevision),object.kind==="path"||object.kind==="arc"?next.set(object.id,Object.freeze({status:"unsupported-kind",kind:object.kind})):next.set(object.id,Object.freeze({status:"accepted",target:Object.freeze({id:object.id,kind:object.kind,position:object.position,acceptedPositionRevision:nextPositionRevision})}))}for(const id of facts.keys())next.has(id)||(changed.push(id),nextPositionRevision=nextCounter(nextPositionRevision));const nextSceneRevision=nextCounter(acceptedSceneRevision),nextRegistryRevision=changed.length>0?nextCounter(registryRevision):registryRevision,nextSnapshot=targetSnapshot(next,nextSceneRevision,nextRegistryRevision),published=sources.publish(candidate.sourceStage);if(closed||generation!==before)return release(published),candidate.dispose(),!1;const retired=acceptedSources;acceptedSources=published,facts=next,snapshot=nextSnapshot,acceptedSceneRevision=nextSceneRevision,registryRevision=nextRegistryRevision,positionRevision=nextPositionRevision,requestRevision=candidate.request.revision;const committedGeneration=++generation;return release(retired),notify(changed,committedGeneration),!0}catch(error){if(candidate.dispose(),closed||generation!==before||isStaleMapSceneSourceError(error))return!1;throw new TypeError("Invalid map scene commit")}},clear(value){const request=snapshotMapSceneRequest(value);if(!current(request,generation))return!1;const changed=[...facts.keys()],nextSceneRevision=nextCounter(acceptedSceneRevision),nextRegistryRevision=changed.length>0?nextCounter(registryRevision):registryRevision;let nextPositionRevision=positionRevision;for(let index=0;index<changed.length;index++)nextPositionRevision=nextCounter(nextPositionRevision);const next=new Map,nextSnapshot=targetSnapshot(next,nextSceneRevision,nextRegistryRevision);sources.sealCurrent();const retired=acceptedSources;acceptedSources=[],facts=next,snapshot=nextSnapshot,acceptedSceneRevision=nextSceneRevision,registryRevision=nextRegistryRevision,positionRevision=nextPositionRevision,requestRevision=request.revision;const committedGeneration=++generation;return release(retired),notify(changed,committedGeneration),!0},subscribe(listener){if(typeof listener!="function")throw new TypeError("Invalid map scene listener");return closed?()=>{}:(listeners.add(listener),()=>{listeners.delete(listener)})},dispose(){if(closed)return;const next=new Map,nextSnapshot=targetSnapshot(next,acceptedSceneRevision,registryRevision);closed=!0,generation++,facts=next,snapshot=nextSnapshot,listeners.clear(),sources.sealCurrent();const retired=acceptedSources;acceptedSources=[],release(retired)}})}export{createMapScenePositionRegistry};
@@ -0,0 +1 @@
1
+ import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{observeReducedMotion}from"../../../internal/motion-observer.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{createMapSceneLineLayer}from"./map-scene-line-layer.js";import{buildSceneLineData}from"./map-scene-lines.js";const isLine=row=>row.kind==="path"||row.kind==="arc";function channel(value){return Math.round(Math.min(1,Math.max(0,value))*255)}function bridgeReport(value){try{if(value===null||typeof value!="object")return;const state=Reflect.get(value,"state"),revision=Reflect.get(value,"acceptedSceneRevision"),code=Reflect.get(value,"code");if(typeof revision!="number"||!Number.isSafeInteger(revision)||revision<0)return;if(state==="installed")return{revision,outcome:{state:"drawn"}};if(state==="pending")return{revision,outcome:{state:"pending"}};if(state==="unavailable")return{revision,outcome:{state:"failed",code:code==="limit"?"limit":code==="context-lost"?"context-lost":"engine"}}}catch{}}function resolvedColor(element,expression){const color=resolveCanvasColor(element,expression,"");if(!color)return;const match=/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:\s*[,/]\s*([\d.]+))?\s*\)$/.exec(color);if(match){const channels=[Number(match[1])/255,Number(match[2])/255,Number(match[3])/255,match[4]===void 0?1:Number(match[4])];if(channels.every(value=>Number.isFinite(value)&&value>=0&&value<=1))return channels}const canvas=element.ownerDocument.createElement("canvas");canvas.width=1,canvas.height=1;const context=canvas.getContext("2d",{colorSpace:"srgb",willReadFrequently:!0});if(!context)return;context.fillStyle=color,context.fillRect(0,0,1,1);const pixel=context.getImageData(0,0,1,1).data;return[pixel[0]/255,pixel[1]/255,pixel[2]/255,pixel[3]/255]}function createMapSceneRenderController(options){const{element,map,container,owner}=options,document=element.ownerDocument,view=document.defaultView,abort=new(view?.AbortController??AbortController),releases=[];let closed=!1,intersecting=!1,visibilityObserved=!1,intersectionObserved=!1,allocationRead={},bridge,visible,loading=!1,attemptedRevision,preparing=!1,bridgeFailure,report,markerContextLost=!1,linesFor,lineColorsStale=!0;function current(){return!closed&&view!==null&&element.isConnected&&element.ownerDocument===document&&options.isCurrent()}function demand(){return owner.captureAccepted().objects.some(row=>row.kind==="marker")}function statusChanged(){if(current())try{options.onStatusChange?.()}catch{}}const lines=createMapSceneLineLayer({map,isCurrent:()=>current(),styleLoaded:()=>{try{return options.styleLoaded?.()??map.isStyleLoaded?.()===!0}catch{return!1}},changed:statusChanged});function syncLines(){if(!current())return;const accepted=owner.captureAccepted();if(accepted===linesFor&&!lineColorsStale)return;const objects=accepted.objects.filter(isLine);if(objects.length===0){linesFor=accepted,lineColorsStale=!1,lines.update(void 0);return}const colors=new Map,resolved=new Map;let request;try{for(const row of objects){const expression=row.color??`var(${options.accentToken})`;if(resolved.has(expression)||resolved.set(expression,resolvedColor(element,expression)),!current()||owner.captureAccepted()!==accepted)return;const rgba=resolved.get(expression);if(!rgba){request={revision:accepted.acceptedSceneRevision,failure:"engine"};break}colors.set(row.id,`rgba(${channel(rgba[0])}, ${channel(rgba[1])}, ${channel(rgba[2])}, ${rgba[3]})`)}if(!request){const data=buildSceneLineData(objects,colors);request=data?{revision:accepted.acceptedSceneRevision,objects,data}:{revision:accepted.acceptedSceneRevision,failure:"limit"}}}catch{request={revision:accepted.acceptedSceneRevision,failure:"engine"}}!current()||owner.captureAccepted()!==accepted||(linesFor=accepted,lineColorsStale=!1,lines.update(request))}function markerOutcome(revision){return demand()?bridgeFailure===revision?{state:"failed",code:"engine"}:markerContextLost?{state:"failed",code:"context-lost"}:report?.revision===revision?report.outcome:{state:"pending"}:{state:"none"}}function keep(release){if(current())releases.push(release);else try{release()}catch{}}function syncVisibility(){if(!current()||!bridge)return;const publication=owner.captureRenderPublication(),next=visibilityObserved&&intersectionObserved&&intersecting&&document.visibilityState!=="hidden"&&!document.hidden&&publication.phase==="resolved"&&publication.input.allocation!==void 0&&demand();if(visible!==next){visible=next;try{bridge.setVisible(next)}catch{}}}function preparePublication(expected){try{const colors=new Map,markers=[];for(const row of expected.accepted.objects){if(row.kind!=="marker")continue;const expression=row.color??`var(${options.accentToken})`;let rgba=colors.get(expression);if(!rgba){if(rgba=resolvedColor(element,expression),!rgba){current()&&owner.failPresentation(expected);return}colors.set(expression,rgba)}if(!current()||owner.captureRenderPublication()!==expected)return;markers.push({id:row.id,rgba})}const presentation={markers,reducedMotion:prefersReducedMotion(element)};current()&&owner.commitPresentation(expected,presentation)}catch{current()&&owner.failPresentation(expected)}}function prepare(){if(!(!current()||preparing)){preparing=!0;try{for(let pass=0;pass<32&&current();pass++){const expected=owner.captureRenderPublication();if(expected.phase!=="pending"||(preparePublication(expected),owner.captureRenderPublication()===expected))return}current()&&owner.failPresentation(owner.captureRenderPublication())}finally{preparing=!1}}}function refreshAllocation(){if(!current()||!demand())return;const attempt={};allocationRead=attempt;const active=()=>current()&&allocationRead===attempt;let allocation;try{const getContainer=map.getContainer;if(!active())return;const getCanvas=map.getCanvas;if(!active())return;const getPixelRatio=map.getPixelRatio;if(!active())return;const getPadding=map.getPadding;if(!active())return;if(typeof getContainer=="function"&&typeof getCanvas=="function"&&typeof getPixelRatio=="function"&&typeof getPadding=="function"){const nativeContainer=getContainer.call(map);if(!active())return;const canvas=getCanvas.call(map);if(!active())return;const width=nativeContainer.clientWidth;if(!active())return;const height=nativeContainer.clientHeight;if(!active())return;const pixelRatio=getPixelRatio.call(map);if(!active())return;const padding=getPadding.call(map);if(!active())return;const top=padding.top;if(!active())return;const right=padding.right;if(!active())return;const bottom=padding.bottom;if(!active())return;const left=padding.left;if(!active())return;const backingWidth=canvas.width;if(!active())return;const backingHeight=canvas.height;if(!active())return;const sameContainer=map.getContainer?.()===nativeContainer;if(!active())return;const sameCanvas=map.getCanvas()===canvas;if(!active())return;const sameWidth=nativeContainer.clientWidth===width;if(!active())return;const sameHeight=nativeContainer.clientHeight===height;if(!active())return;const sameBackingWidth=canvas.width===backingWidth;if(!active())return;const sameBackingHeight=canvas.height===backingHeight;if(!active())return;sameContainer&&sameCanvas&&sameWidth&&sameHeight&&sameBackingWidth&&sameBackingHeight&&nativeContainer===container&&nativeContainer.ownerDocument===document&&canvas.ownerDocument===document&&Number.isSafeInteger(width)&&width>0&&Number.isSafeInteger(height)&&height>0&&Number.isFinite(pixelRatio)&&pixelRatio>0&&Number.isSafeInteger(backingWidth)&&backingWidth>0&&Number.isSafeInteger(backingHeight)&&backingHeight>0&&backingWidth===Math.round(width*pixelRatio)&&backingHeight===Math.round(height*pixelRatio)&&[top,right,bottom,left].every(value=>Number.isFinite(value)&&value>=0)&&(allocation={width,height,pixelRatio,padding:{top,right,bottom,left}})}}catch{}active()&&(owner.setViewport(allocation),active()&&syncVisibility())}function startBridge(){if(!current()||!demand()||bridge||loading)return;const revision=owner.captureAccepted().acceptedSceneRevision;attemptedRevision!==revision&&(attemptedRevision=revision,loading=!0,options.loadBridge().then(runtime=>{if(!current()||!demand())return;let candidate;try{const created=runtime.createSceneBridge(map,{signal:abort.signal,isCurrent:current,captureRenderInput:()=>owner.captureRenderPublication().input,subscribeRenderInput:listener=>owner.subscribeRenderPublication(listener),onState:value=>{const next=current()&&bridge===created?bridgeReport(value):void 0;next&&(report=next,next.outcome.state==="drawn"&&(markerContextLost=!1),statusChanged())},onError:code=>{!current()||bridge!==created||code!=="context-lost"||(markerContextLost=!0,statusChanged())}});if(candidate=created,!created||!["dispose","invalidateStyle","setVisible","requestFrame"].every(name=>typeof Reflect.get(created,name)=="function"))throw new TypeError("Map scene renderer unavailable");if(!current()||!demand()){created.dispose();return}bridge=created,visible=void 0,syncVisibility()}catch{try{candidate?.dispose()}catch{}current()&&(bridgeFailure=revision,statusChanged())}},()=>{current()&&(bridgeFailure=revision,statusChanged())}).finally(()=>{loading=!1,current()&&owner.captureAccepted().acceptedSceneRevision!==attemptedRevision&&startBridge()}))}function retireBridge(){const previous=bridge;if(!(!previous||demand())){bridge=void 0,visible=void 0,report=void 0,markerContextLost=!1,attemptedRevision=void 0;try{previous.dispose()}catch{}}}function sync(){current()&&(retireBridge(),prepare(),syncVisibility(),startBridge(),syncLines())}function refreshPresentation(){current()&&(lineColorsStale=!0,demand()&&owner.invalidatePresentation(),sync())}function dispose(){if(closed)return;closed=!0,allocationRead={};const previous=bridge;bridge=void 0;for(const release of releases.splice(0))try{release()}catch{}abort.abort();try{previous?.dispose()}catch{}lines.dispose()}keep(owner.subscribeRenderPublication(sync));for(const event of["move","resize"])try{keep(()=>{map.off?.(event,refreshAllocation)}),current()&&(Reflect.apply(map.on,map,[event,refreshAllocation]),current()||map.off?.(event,refreshAllocation))}catch{}try{const Observer=view?.IntersectionObserver;if(Observer){const observer=new Observer(entries=>{if(current()){for(const entry of entries)entry.target===container&&(intersecting=entry.isIntersecting);syncVisibility()}});keep(()=>observer.disconnect()),current()&&(observer.observe(container),intersectionObserved=current())}}catch{intersecting=!1}keep(()=>document.removeEventListener("visibilitychange",syncVisibility));try{current()&&(document.addEventListener("visibilitychange",syncVisibility),visibilityObserved=current())}catch{intersecting=!1}try{keep(observeReducedMotion(element,refreshPresentation))}catch{}return refreshAllocation(),sync(),{sync,refreshPresentation,refreshAllocation,invalidateStyle(){if(current()){try{bridge?.invalidateStyle()}catch{}lines.invalidateStyle()}},styleReady(){current()&&lines.styleReady()},captureOutcomes(){const revision=owner.captureAccepted().acceptedSceneRevision,captured=lines.capture();return{markers:markerOutcome(revision),lines:captured.revision===revision||captured.outcome.state==="none"?captured.outcome:{state:"pending"}}},dispose}}export{createMapSceneRenderController};
@@ -0,0 +1 @@
1
+ import{isPlainDataRecord,readOwnArrayLength,readOwnDataValue}from"../../../internal/data-descriptors.js";const MAX_MARKERS=2e3,EMPTY_MARKERS=Object.freeze([]);function nextSceneRenderRevision(value){return Number.isSafeInteger(value)&&value>=0&&value<Number.MAX_SAFE_INTEGER?value+1:void 0}function finite(value,minimum,maximum=1/0){return typeof value=="number"&&Number.isFinite(value)&&value>=minimum&&value<=maximum}function snapshotScenePresentation(value){try{if(!isPlainDataRecord(value))return;const rows=readOwnDataValue(value,"markers"),reducedMotion=readOwnDataValue(value,"reducedMotion");if(!Array.isArray(rows)||typeof reducedMotion!="boolean")return;const length=readOwnArrayLength(rows);if(length===void 0||length>MAX_MARKERS)return;const markers=[],ids=new Set;for(let index=0;index<length;index++){const row=readOwnDataValue(rows,String(index));if(!isPlainDataRecord(row))return;const id=readOwnDataValue(row,"id"),color=readOwnDataValue(row,"rgba");if(typeof id!="string"||id.length===0||id.length>1024||id.trim().length===0||ids.has(id)||!Array.isArray(color)||readOwnArrayLength(color)!==4)return;const red=readOwnDataValue(color,"0"),green=readOwnDataValue(color,"1"),blue=readOwnDataValue(color,"2"),alpha=readOwnDataValue(color,"3");if(!finite(red,0,1)||!finite(green,0,1)||!finite(blue,0,1)||!finite(alpha,0,1))return;ids.add(id),markers.push(Object.freeze({id,rgba:Object.freeze([red,green,blue,alpha])}))}return Object.freeze({markers:Object.freeze(markers),reducedMotion})}catch{return}}function snapshotSceneViewport(value){try{if(!isPlainDataRecord(value))return;const width=readOwnDataValue(value,"width"),height=readOwnDataValue(value,"height"),pixelRatio=readOwnDataValue(value,"pixelRatio"),padding=readOwnDataValue(value,"padding");if(!finite(width,0)||width===0||!finite(height,0)||height===0||!finite(pixelRatio,0)||pixelRatio===0||!isPlainDataRecord(padding))return;const backingWidth=Math.round(width*pixelRatio),backingHeight=Math.round(height*pixelRatio);if(!Number.isSafeInteger(backingWidth)||backingWidth<=0||!Number.isSafeInteger(backingHeight)||backingHeight<=0)return;const top=readOwnDataValue(padding,"top"),right=readOwnDataValue(padding,"right"),bottom=readOwnDataValue(padding,"bottom"),left=readOwnDataValue(padding,"left");return!finite(top,0)||!finite(right,0)||!finite(bottom,0)||!finite(left,0)?void 0:Object.freeze({width,height,pixelRatio,padding:Object.freeze({top,right,bottom,left})})}catch{return}}function allocation(viewport){return viewport===void 0?void 0:Object.freeze({revision:viewport.allocationRevision,width:viewport.width,height:viewport.height,pixelRatio:viewport.pixelRatio,padding:Object.freeze({top:viewport.padding.top,right:viewport.padding.right,bottom:viewport.padding.bottom,left:viewport.padding.left})})}function emptySceneRenderInput(acceptedSceneRevision,presentationRevision,viewport){return Object.freeze({acceptedSceneRevision,presentationRevision,allocation:allocation(viewport),reducedMotion:!0,markers:EMPTY_MARKERS})}function buildSceneRenderInput(options){try{const{accepted,state,phase,presentationRevision}=options;if(!Number.isSafeInteger(accepted.acceptedSceneRevision)||accepted.acceptedSceneRevision<0||accepted.acceptedSceneRevision!==state.acceptedSceneRevision||!Number.isSafeInteger(presentationRevision)||presentationRevision<=0||accepted.objects.length>MAX_MARKERS||state.targets.length>MAX_MARKERS||phase!=="pending"&&phase!=="resolved"&&phase!=="unavailable")return;let viewport;if(state.viewport!==void 0){const copied=snapshotSceneViewport(state.viewport),revision=state.viewport.allocationRevision;if(!copied||!Number.isSafeInteger(revision)||revision<=0)return;viewport=Object.freeze({...copied,allocationRevision:revision})}if(phase!=="resolved")return emptySceneRenderInput(accepted.acceptedSceneRevision,presentationRevision,viewport);const objects=accepted.objects.filter(object=>object.kind==="marker");if(objects.length===0&&options.presentation===void 0)return emptySceneRenderInput(accepted.acceptedSceneRevision,presentationRevision,viewport);const presentation=snapshotScenePresentation(options.presentation);if(!presentation||presentation.markers.length!==objects.length)return;const colors=new Map(presentation.markers.map(marker=>[marker.id,marker.rgba])),targets=new Map,allIds=new Set;for(const target of state.targets){if(allIds.has(target.id))return;allIds.add(target.id),(target.kind==="marker"||target.kind==="model")&&targets.set(target.id,target)}const markers=[],seen=new Set;for(const object of objects){const target=targets.get(object.id),color=colors.get(object.id);if(seen.has(object.id)||!target||target.kind!=="marker"||!color||!Number.isSafeInteger(target.acceptedPositionRevision)||target.acceptedPositionRevision<=0||target.position.lngLat[0]!==object.position.lngLat[0]||target.position.lngLat[1]!==object.position.lngLat[1]||target.position.altitude!==object.position.altitude||target.position.altitudeReference!==object.position.altitudeReference||!finite(object.radius,0)||object.radius===0||!finite(object.opacity,0,1))return;seen.add(object.id),markers.push(Object.freeze({id:object.id,position:Object.freeze({lngLat:Object.freeze([object.position.lngLat[0],object.position.lngLat[1]]),altitude:object.position.altitude,altitudeReference:object.position.altitudeReference}),acceptedPositionRevision:target.acceptedPositionRevision,radiusCss:object.radius,rgba:Object.freeze([color[0],color[1],color[2],color[3]*object.opacity])}))}return Object.freeze({acceptedSceneRevision:accepted.acceptedSceneRevision,presentationRevision,allocation:allocation(viewport),reducedMotion:presentation.reducedMotion,markers:Object.freeze(markers)})}catch{return}}export{buildSceneRenderInput,emptySceneRenderInput,nextSceneRenderRevision,snapshotScenePresentation,snapshotSceneViewport};
@@ -0,0 +1 @@
1
+ import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,readOwnArrayLength,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{createMapSceneAdmissionError,mapSceneAdmissionErrorCode}from"./map-scene-errors.js";const SOURCE_FORMATS=["gltf","glb","stl","obj","ply","xyz","pcd"],MAX_STAGE_SOURCES=32,MAX_SOURCE_TEXT=1048576,MAX_RESOLVED_TEXT=4194304,staleErrors=new WeakSet;function invalid(){throw createMapSceneAdmissionError("invalid")}function limit(){throw createMapSceneAdmissionError("limit")}function sanitized(error){if(mapSceneAdmissionErrorCode(error)!==void 0)throw error;return invalid()}function stale(){const error=new TypeError("Stale map scene source");throw staleErrors.add(error),error}function isStaleMapSceneSourceError(error){return objectValue(error)&&staleErrors.has(error)}function objectValue(value){return value!==null&&(typeof value=="object"||typeof value=="function")}function field(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?invalid():descriptor.value}function metadata(value){if(!isPlainDataRecord(value))return invalid();const keys=Reflect.ownKeys(value);if(keys.length!==2||!keys.includes("format"))return invalid();const format=field(value,"format");if(typeof format!="string"||!SOURCE_FORMATS.includes(format))return invalid();if(keys.includes("bytes")){const bytes=field(value,"bytes");return objectValue(bytes)?{record:value,kind:"bytes",format,bytes}:invalid()}if(keys.includes("src")){const src=field(value,"src");return typeof src!="string"?invalid():src.length>MAX_SOURCE_TEXT?limit():src.trim().length===0?invalid():{record:value,kind:"url",format,src}}return invalid()}function readMapSceneSource(value){try{return metadata(value).record}catch(error){return sanitized(error)}}function captureMapSceneSourceMetadata(value){try{return Object.freeze(metadata(value))}catch(error){return sanitized(error)}}function sameMetadata(first,second){return first.record===second.record&&first.format===second.format&&(first.kind==="bytes"&&second.kind==="bytes"?first.bytes===second.bytes:first.kind==="url"&&second.kind==="url"&&first.src===second.src)}function intrinsicGetter(prototype,name){const get=Object.getOwnPropertyDescriptor(prototype,name)?.get;return get?value=>Reflect.apply(get,value,[]):void 0}const arrayBufferLength=intrinsicGetter(ArrayBuffer.prototype,"byteLength"),arrayBufferResizable=intrinsicGetter(ArrayBuffer.prototype,"resizable"),typedArrayPrototype=Object.getPrototypeOf(Uint8Array.prototype),typedArrayKind=intrinsicGetter(typedArrayPrototype,Symbol.toStringTag),typedArrayBuffer=intrinsicGetter(typedArrayPrototype,"buffer"),typedArrayOffset=intrinsicGetter(typedArrayPrototype,"byteOffset"),typedArrayLength=intrinsicGetter(typedArrayPrototype,"byteLength");function byteRange(value){let buffer=value,byteOffset=0,byteLength;if(ArrayBuffer.isView(value)){if(typedArrayKind(value)!=="Uint8Array")return invalid();buffer=typedArrayBuffer(value),byteOffset=typedArrayOffset(value),byteLength=typedArrayLength(value)}const bufferLength=arrayBufferLength(buffer);return arrayBufferResizable?.(buffer)===!0||(byteLength===void 0&&(byteLength=bufferLength),typeof byteLength!="number"||!Number.isSafeInteger(byteLength)||byteLength<0||!Number.isSafeInteger(byteOffset)||byteOffset<0)?invalid():(new Uint8Array(buffer,byteOffset,byteLength),{buffer,byteOffset,byteLength})}function requestSnapshot(value,connection){if(!isPlainDataRecord(value))return invalid();const actualConnection=field(value,"connection"),revision=field(value,"revision");return actualConnection!==connection||typeof revision!="number"||!Number.isSafeInteger(revision)||revision<1?invalid():Object.freeze({connection,revision})}function resolvedRequest(value){if(!isPlainDataRecord(value))return invalid();const url=field(value,"url"),owner=field(value,"owner");return typeof url!="string"||url.length===0||!objectValue(owner)?invalid():url.length>MAX_SOURCE_TEXT?limit():Object.freeze({url,owner})}function references(entry){return entry.candidate+entry.accepted+entry.installed}function createMapSceneSourceOwner(options){const{connection,isCurrent,reserveBytes,resolveUrl,maxEncodedBytes}=options;if(!objectValue(connection)||typeof isCurrent!="function"||typeof reserveBytes!="function"||typeof resolveUrl!="function"||!Number.isSafeInteger(maxEncodedBytes)||maxEncodedBytes<0)return invalid();const entries=new Set,receipts=new WeakMap,reusable=new WeakMap,stages=new WeakMap,pendingStages=new Set;let closed=!1,generation=0,latestRequestRevision=0,nextSourceId=1,liveBytes=0;function checkCurrent(request,expectedGeneration){if(closed||generation!==expectedGeneration||request.revision<latestRequestRevision||!isCurrent(request)||closed||generation!==expectedGeneration||request.revision<latestRequestRevision)return stale()}function retire(entry){if(references(entry)!==0||entry.snapshot===void 0)return;const meta=entry.metadata,retireBytes=entry.retire;entry.sealed=!0,entry.snapshot=void 0,entry.metadata=void 0,entry.retire=void 0,entries.delete(entry),meta&&reusable.get(meta.record)===entry&&reusable.delete(meta.record),liveBytes-=entry.byteLength;try{retireBytes?.()}catch{}}function release(entry,role){entry[role]--,retire(entry)}function lease(entry,role){let released=!1;return Object.freeze({receipt:entry.receipt,release(){released||(released=!0,release(entry,role))}})}function disposeStage(state){if(state.status==="staged"){state.status="disposed",pendingStages.delete(state);for(const entry of state.entries)release(entry,"candidate")}}function addEntry(meta,snapshot,byteLength,retireBytes){if(!Number.isSafeInteger(nextSourceId))return invalid();const receipt=Object.freeze({sourceId:nextSourceId++,format:meta.format}),entry={metadata:meta,receipt,byteLength,retire:retireBytes,snapshot,candidate:1,accepted:0,installed:0,published:!1,sealed:!1};return entries.add(entry),receipts.set(receipt,entry),entry}function newEntry(meta,request,expectedGeneration){if(meta.kind==="url"){const resolved=resolveUrl(meta.src);checkCurrent(request,expectedGeneration);const snapshot=Object.freeze({kind:"url",format:meta.format,request:resolvedRequest(resolved)});return sameMetadata(meta,metadata(meta.record))?(checkCurrent(request,expectedGeneration),addEntry(meta,snapshot,0)):invalid()}const range=byteRange(meta.bytes);if(range.byteLength>maxEncodedBytes-liveBytes)return limit();liveBytes+=range.byteLength;let reservation,owned=!1;try{if(reservation=reserveBytes(range.byteLength),checkCurrent(request,expectedGeneration),!sameMetadata(meta,metadata(meta.record)))return invalid();const bytes=new Uint8Array(range.byteLength);bytes.set(new Uint8Array(range.buffer,range.byteOffset,range.byteLength)),checkCurrent(request,expectedGeneration);const reservationOwner=reservation,entry=addEntry(meta,Object.freeze({kind:"bytes",format:meta.format,bytes}),range.byteLength,()=>reservationOwner.release());return owned=!0,entry}finally{if(!owned){liveBytes-=range.byteLength;try{reservation?.release()}catch{}}}}function stage(values,value,expected){const acquired=[];try{const request=requestSnapshot(value,connection);checkCurrent(request,generation),request.revision>latestRequestRevision&&(latestRequestRevision=request.revision,generation++);const expectedGeneration=generation;if(!Array.isArray(values))return invalid();const length=readOwnArrayLength(values);if(length===void 0)return invalid();if(length>MAX_STAGE_SOURCES)return limit();if(Reflect.ownKeys(values).length!==length+1||expected!==void 0&&expected.length!==length)return invalid();const descriptors=[],seen=new Set;for(let index=0;index<length;index++){const current=metadata(field(values,String(index))),meta=expected?.[index]??current;if(!sameMetadata(meta,current))return invalid();seen.has(meta.record)||(seen.add(meta.record),descriptors.push(meta))}let resolvedText=0;for(const meta of descriptors){checkCurrent(request,expectedGeneration);const existing=reusable.get(meta.record);if(existing){if(existing.sealed||existing.snapshot===void 0||!existing.metadata||!sameMetadata(existing.metadata,meta))return invalid();existing.candidate++,acquired.push(existing)}else acquired.push(newEntry(meta,request,expectedGeneration));const snapshot=acquired[acquired.length-1].snapshot;if(snapshot?.kind==="url"&&(resolvedText+=snapshot.request.url.length),resolvedText>MAX_RESOLVED_TEXT)return limit()}for(const meta of descriptors)if(!sameMetadata(meta,metadata(meta.record)))return invalid();checkCurrent(request,expectedGeneration);const state={request,entries:acquired,status:"staged"},result=Object.freeze({receipts:Object.freeze(acquired.map(entry=>entry.receipt)),dispose(){disposeStage(state)}});return stages.set(result,state),pendingStages.add(state),result}catch(error){for(const entry of acquired)release(entry,"candidate");return sanitized(error)}}function publish(stage2){const state=stages.get(stage2);if(!state||state.status!=="staged")return invalid();try{const expectedGeneration=generation;if(checkCurrent(state.request,expectedGeneration),state.status!=="staged")return invalid();for(const entry of state.entries){if(!entry.metadata)return invalid();const current=reusable.get(entry.metadata.record);if(entry.sealed||entry.snapshot===void 0||current!==void 0&&current!==entry)return invalid()}const result=Object.freeze(state.entries.map(entry=>lease(entry,"accepted")));generation++,state.status="published",pendingStages.delete(state);for(const entry of state.entries)entry.accepted++,entry.candidate--,entry.published=!0,reusable.set(entry.metadata.record,entry);return result}catch(error){if(isStaleMapSceneSourceError(error))throw error;return sanitized(error)}}function sealCurrent(){generation++;for(const entry of entries)entry.sealed=!0,entry.metadata&&reusable.delete(entry.metadata.record)}return Object.freeze({stage,publish,retain(receipt,role){const entry=receipts.get(receipt);return closed||!entry||entry.sealed||!entry.published||entry.snapshot===void 0||role!=="candidate"&&role!=="installed"?invalid():(entry[role]++,lease(entry,role))},snapshot(receipt){const entry=receipts.get(receipt);return!entry||entry.snapshot===void 0?invalid():entry.snapshot},sealCurrent,dispose(){if(!closed){closed=!0,sealCurrent();for(const state of[...pendingStages])disposeStage(state)}}})}export{captureMapSceneSourceMetadata,createMapSceneSourceOwner,isStaleMapSceneSourceError,readMapSceneSource};
@@ -0,0 +1 @@
1
+ const PRECEDENCE=["context-lost","engine","limit","model","altitude"];function countSceneMembers(objects){let markers=0,lines=0,models=0;for(const object of objects)object.kind==="marker"?markers++:object.kind==="path"||object.kind==="arc"?lines++:object.kind==="model"&&models++;return{markers,lines,models}}function summarizeSceneRender(counts,markers,lines){const groups=[];if(counts.markers>0&&groups.push(markers),counts.lines>0&&groups.push(lines),groups.some(group=>group.state==="pending"))return Object.freeze({state:"loading"});const codes=new Set(counts.models>0?["model"]:[]);let drawn=0;for(const group of groups)group.state==="drawn"?(drawn++,group.approximate&&codes.add("altitude")):codes.add(group.state==="failed"?group.code:"engine");const code=PRECEDENCE.find(candidate=>codes.has(candidate));return Object.freeze(drawn===0?{state:"unavailable",code:code??"engine"}:code===void 0?{state:"ready"}:{state:"partial",code})}export{countSceneMembers,summarizeSceneRender};
@@ -0,0 +1,55 @@
1
+ /** Authored geographic position; altitude is meters above sea level or displayed terrain.*/
2
+ export interface LyraMapPosition{readonly lngLat:readonly[longitude:number,latitude:number];
3
+ /** Altitude in meters. Defaults to 0.*/
4
+ readonly altitude?:number;
5
+ /** Altitude reference. Defaults to 'sea-level'.*/
6
+ readonly altitudeReference?:'sea-level'|'terrain';}export type LyraMapQuaternion=readonly[x:number,y:number,z:number,w:number];export type LyraMapModelFormat='gltf'|'glb'|'stl'|'obj'|'ply'|'xyz'|'pcd';
7
+ /** A retained record reuses its owned snapshot; replace the record to request new content.*/
8
+ export type LyraMapModelSource={readonly format:LyraMapModelFormat;readonly bytes:ArrayBuffer|Uint8Array;}|{readonly format:LyraMapModelFormat;readonly src:string;};export interface LyraMapSceneObjectBase{readonly id:string;readonly label:string;
9
+ /** Optional requested CSS color; omitted input has no authored color override.*/
10
+ readonly color?:string;
11
+ /** Requested opacity from 0 through 1. Defaults to 1.*/
12
+ readonly opacity?:number;
13
+ /** Whether the object can be activated from its text row. Defaults to true.*/
14
+ readonly interactive?:boolean;
15
+ /** Requested rendered label visibility. Defaults to false; text rows always retain the label.*/
16
+ readonly showLabel?:boolean;}export interface LyraMapSceneMarker extends LyraMapSceneObjectBase{readonly kind:'marker';readonly position:LyraMapPosition;
17
+ /** Requested positive marker radius. Defaults to 6.*/
18
+ readonly radius?:number;}
19
+ /** Drawn as a native line; altitude is carried in the data and reported as `partial`/`altitude` when not representable.*/
20
+ export interface LyraMapScenePath extends LyraMapSceneObjectBase{readonly kind:'path';readonly positions:readonly LyraMapPosition[];
21
+ /**
22
+ * Path interpolation. Defaults to 'great-circle', the shortest route on the globe; 'linear'
23
+ * joins vertices straight in longitude/latitude. Both cross the antimeridian the shorter way.
24
+ */
25
+ readonly interpolation?:'linear'|'great-circle';
26
+ /** Requested positive path width. Defaults to 2.*/
27
+ readonly width?:number;}
28
+ /**
29
+ * A great-circle ground track whose altitude interpolates linearly between the endpoints plus a
30
+ * parabolic rise of `height` meters at the midpoint. A nonzero altitude or height is drawn as the
31
+ * ground track and reported as `partial` with code `altitude`.
32
+ */
33
+ export interface LyraMapSceneArc extends LyraMapSceneObjectBase{readonly kind:'arc';readonly start:LyraMapPosition;readonly end:LyraMapPosition;
34
+ /** Nonnegative midpoint rise in meters above the chord between endpoint altitudes.*/
35
+ readonly height:number;
36
+ /** Requested positive arc width. Defaults to 2.*/
37
+ readonly width?:number;}export interface LyraMapSceneModel extends LyraMapSceneObjectBase{readonly kind:'model';readonly position:LyraMapPosition;readonly source:LyraMapModelSource;
38
+ /** Positive model scale in meters per source unit. Defaults to 1.*/
39
+ readonly metersPerUnit?:number;
40
+ /** Scalar-last quaternion, normalized on admission. Defaults to identity [0, 0, 0, 1].*/
41
+ readonly orientation?:LyraMapQuaternion;}export type LyraMapSceneObject=LyraMapSceneMarker|LyraMapScenePath|LyraMapSceneArc|LyraMapSceneModel;
42
+ /** New assignments are admitted atomically; undefined clears accepted scene ownership.*/
43
+ export interface LyraMapScene{readonly objects:readonly LyraMapSceneObject[];}
44
+ /**
45
+ * `altitude`: a path or arc is drawn as its ground track because the flat map cannot show its
46
+ * authored altitude or arc height. `model`: model objects are not drawn.
47
+ */
48
+ export type LyraMapSceneErrorCode='invalid'|'limit'|'model'|'resource'|'engine'|'projection'|'terrain'|'context-lost'|'altitude';
49
+ /**
50
+ * `loading` until every renderer settles; `ready` when every accepted object is installed on the
51
+ * map exactly; `partial` with a code when some objects are missing or drawn without altitude;
52
+ * `unavailable` with a code when nothing could be drawn. Installation does not assert that pixels
53
+ * are visible: terrain, occlusion and viewport still apply.
54
+ */
55
+ export interface LyraMapSceneStateDetail{readonly revision:number;readonly state:'loading'|'ready'|'partial'|'empty'|'unavailable'|'error';readonly code?:LyraMapSceneErrorCode;}export interface LyraMapSceneActivateDetail{readonly id:string;readonly kind:'marker'|'path'|'arc'|'model'|'custom';readonly layerId?:string;readonly source:'pointer'|'keyboard';readonly position?:LyraMapPosition;}