{"version":3,"sources":["mod::locata/node_modules/leaflet/src/core/Util.js","mod::locata/node_modules/leaflet/src/core/Class.js","mod::locata/node_modules/leaflet/src/core/Events.js","mod::locata/node_modules/leaflet/src/geometry/Point.js","mod::locata/node_modules/leaflet/src/geometry/Bounds.js","mod::locata/node_modules/leaflet/src/geo/LatLngBounds.js","mod::locata/node_modules/leaflet/src/geo/LatLng.js","mod::locata/node_modules/leaflet/src/geo/crs/CRS.js","mod::locata/node_modules/leaflet/src/geo/crs/CRS.Earth.js","mod::locata/node_modules/leaflet/src/geo/projection/Projection.SphericalMercator.js","mod::locata/node_modules/leaflet/src/geometry/Transformation.js","mod::locata/node_modules/leaflet/src/geo/crs/CRS.EPSG3857.js","mod::locata/node_modules/leaflet/src/layer/vector/SVG.Util.js","mod::locata/node_modules/leaflet/src/core/Browser.js","mod::locata/node_modules/leaflet/src/dom/DomEvent.Pointer.js","mod::locata/node_modules/leaflet/src/dom/DomEvent.DoubleTap.js","mod::locata/node_modules/leaflet/src/dom/DomUtil.js","mod::locata/node_modules/leaflet/src/dom/DomEvent.js","mod::locata/node_modules/leaflet/src/dom/PosAnimation.js","mod::locata/node_modules/leaflet/src/map/Map.js","mod::locata/node_modules/leaflet/src/control/Control.js","mod::locata/node_modules/leaflet/src/control/Control.Layers.js","mod::locata/node_modules/leaflet/src/control/Control.Zoom.js","mod::locata/node_modules/leaflet/src/control/Control.Scale.js","mod::locata/node_modules/leaflet/src/control/Control.Attribution.js","mod::locata/node_modules/leaflet/src/control/index.js","mod::locata/node_modules/leaflet/src/core/Handler.js","mod::locata/node_modules/leaflet/src/core/index.js","mod::locata/node_modules/leaflet/src/dom/Draggable.js","mod::locata/node_modules/leaflet/src/geometry/PolyUtil.js","mod::locata/node_modules/leaflet/src/geometry/LineUtil.js","mod::locata/node_modules/leaflet/src/geo/projection/Projection.LonLat.js","mod::locata/node_modules/leaflet/src/geo/projection/Projection.Mercator.js","mod::locata/node_modules/leaflet/src/geo/projection/index.js","mod::locata/node_modules/leaflet/src/geo/crs/CRS.EPSG3395.js","mod::locata/node_modules/leaflet/src/geo/crs/CRS.EPSG4326.js","mod::locata/node_modules/leaflet/src/geo/crs/CRS.Simple.js","mod::locata/node_modules/leaflet/src/geo/crs/index.js","mod::locata/node_modules/leaflet/src/layer/Layer.js","mod::locata/node_modules/leaflet/src/layer/LayerGroup.js","mod::locata/node_modules/leaflet/src/layer/FeatureGroup.js","mod::locata/node_modules/leaflet/src/layer/marker/Icon.js","mod::locata/node_modules/leaflet/src/layer/marker/Icon.Default.js","mod::locata/node_modules/leaflet/src/layer/marker/Marker.Drag.js","mod::locata/node_modules/leaflet/src/layer/marker/Marker.js","mod::locata/node_modules/leaflet/src/layer/vector/Path.js","mod::locata/node_modules/leaflet/src/layer/vector/CircleMarker.js","mod::locata/node_modules/leaflet/src/layer/vector/Circle.js","mod::locata/node_modules/leaflet/src/layer/vector/Polyline.js","mod::locata/node_modules/leaflet/src/layer/vector/Polygon.js","mod::locata/node_modules/leaflet/src/layer/GeoJSON.js","mod::locata/node_modules/leaflet/src/layer/ImageOverlay.js","mod::locata/node_modules/leaflet/src/layer/VideoOverlay.js","mod::locata/node_modules/leaflet/src/layer/SVGOverlay.js","mod::locata/node_modules/leaflet/src/layer/DivOverlay.js","mod::locata/node_modules/leaflet/src/layer/Popup.js","mod::locata/node_modules/leaflet/src/layer/Tooltip.js","mod::locata/node_modules/leaflet/src/layer/marker/DivIcon.js","mod::locata/node_modules/leaflet/src/layer/marker/index.js","mod::locata/node_modules/leaflet/src/layer/tile/GridLayer.js","mod::locata/node_modules/leaflet/src/layer/tile/TileLayer.js","mod::locata/node_modules/leaflet/src/layer/tile/TileLayer.WMS.js","mod::locata/node_modules/leaflet/src/layer/tile/index.js","mod::locata/node_modules/leaflet/src/layer/vector/Renderer.js","mod::locata/node_modules/leaflet/src/layer/vector/Canvas.js","mod::locata/node_modules/leaflet/src/layer/vector/SVG.VML.js","mod::locata/node_modules/leaflet/src/layer/vector/SVG.js","mod::locata/node_modules/leaflet/src/layer/vector/Renderer.getRenderer.js","mod::locata/node_modules/leaflet/src/layer/vector/Rectangle.js","mod::locata/node_modules/leaflet/src/layer/vector/index.js","mod::locata/node_modules/leaflet/src/layer/index.js","mod::locata/node_modules/leaflet/src/map/handler/Map.BoxZoom.js","mod::locata/node_modules/leaflet/src/map/handler/Map.DoubleClickZoom.js","mod::locata/node_modules/leaflet/src/map/handler/Map.Drag.js","mod::locata/node_modules/leaflet/src/map/handler/Map.Keyboard.js","mod::locata/node_modules/leaflet/src/map/handler/Map.ScrollWheelZoom.js","mod::locata/node_modules/leaflet/src/map/handler/Map.TapHold.js","mod::locata/node_modules/leaflet/src/map/handler/Map.TouchZoom.js","mod::locata/node_modules/leaflet/src/map/index.js","@webhare/env/src/envbackend.ts","@webhare/env/src/init-browser.ts","@webhare/dompack/src/tree.ts","@webhare/std/src/quacks.ts","@webhare/std/src/finmath.ts","@webhare/std/src/money.ts","@webhare/std/src/types.ts","@webhare/std/src/strings.ts","@webhare/std/src/collections.ts","@webhare/std/src/localmutex.ts","@webhare/frontend/src/init.ts","@webhare/tsrun/src/polyfills.ts","mod::publisher/js/internal/polyfills/iterator-helpers.ts","@webhare/env/src/navigation.ts","@webhare/env/src/whglobal.ts","mod::system/js/dompack/src/events.ts","@webhare/dompack/src/busy.ts","mod::system/js/dompack/src/tree.ts","mod::system/js/dompack/src/components.ts","@webhare/dompack/src/storage.ts","@webhare/dompack/src/browser.ts","mod::publisher/js/internal/polyfills/publisher-integration.ts","mod::companyos/webdesigns/pages/frontend/login-background.ts","node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js","@webhare/js-api-tools/src/stacktracing.ts","@webhare/jsonrpc-client/src/jsonrpc-client.ts","@webhare/rpc/src/rpc.ts","@webhare/auth/src/shared.ts","@webhare/frontend/src/auth.ts","@webhare/frontend/src/gtm.ts","@webhare/frontend/src/frontend.ts","mod::companyos/webdesigns/pages/frontend/login.ts","mod::companyos/webdesigns/pages/frontend/arrays.ts","mod::companyos/webdesigns/pages/frontend/lib/app-session-cache.ts","mod::companyos/webdesigns/pages/frontend/lib/rpc.ts","mod::companyos/webdesigns/pages/frontend/lib/read-cache.ts","mod::companyos/webdesigns/pages/frontend/lib/screen-data.ts","mod::companyos/webdesigns/pages/frontend/app-access/app-access-data.ts","mod::companyos/webdesigns/pages/frontend/lib/app-session.ts","mod::companyos/webdesigns/pages/frontend/settings.ts","mod::companyos/webdesigns/pages/frontend/apps.ts","mod::companyos/node_modules/@lit/reactive-element/src/css-tag.ts","mod::companyos/node_modules/@lit/reactive-element/src/reactive-element.ts","mod::companyos/node_modules/lit-html/src/lit-html.ts","mod::companyos/node_modules/lit-element/src/lit-element.ts","mod::companyos/webdesigns/pages/frontend/lib/context-menu.ts","mod::companyos/node_modules/lit-html/src/directives/if-defined.ts","mod::companyos/webdesigns/pages/frontend/icons/icon-data.ts","mod::companyos/webdesigns/pages/frontend/screen/icon.ts","mod::companyos/webdesigns/pages/frontend/menu.ts","mod::companyos/webdesigns/pages/frontend/lib/theme.ts","mod::companyos/webdesigns/pages/frontend/theme.ts","mod::companyos/webdesigns/pages/frontend/account.ts","mod::companyos/webdesigns/pages/frontend/page-header.ts","mod::companyos/webdesigns/pages/frontend/section.ts","mod::companyos/webdesigns/pages/frontend/unsaved.ts","mod::companyos/webdesigns/pages/frontend/sections.ts","mod::companyos/webdesigns/pages/frontend/lib/list.ts","mod::companyos/webdesigns/pages/frontend/screen/column.ts","mod::companyos/webdesigns/pages/frontend/screen/controls.ts","mod::companyos/webdesigns/pages/frontend/screen/list.ts","mod::companyos/webdesigns/pages/frontend/screen/dialog.ts","mod::companyos/webdesigns/pages/frontend/screen/signature.ts","mod::companyos/webdesigns/pages/frontend/lib/toasts.ts","mod::companyos/webdesigns/pages/frontend/screen/toast.ts","mod::companyos/webdesigns/pages/frontend/lib/tabs.ts","mod::companyos/webdesigns/pages/frontend/screen/tabs.ts","mod::companyos/webdesigns/pages/frontend/screen/master-detail.ts","mod::locata/webdesigns/portal/frontend/lib/login-form.ts","mod::locata/webdesigns/pages/frontend/login.ts","mod::locata/webdesigns/pages/frontend/switch.ts","mod::locata/webdesigns/pages/frontend/pages.ts","mod::twentemilieu/webdesigns/app/pages/inventory.ts","mod::twentemilieu/webdesigns/app/pages/containers/containers.ts","mod::locata/webdesigns/pages/frontend/map.ts","mod::twentemilieu/webdesigns/app/pages/explorer/explorer.ts","/entrypoint.js"],"sourcesContent":["/*\r\n * @namespace Util\r\n *\r\n * Various utility functions, used by Leaflet internally.\r\n */\r\n\r\n// @function extend(dest: Object, src?: Object): Object\r\n// Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.\r\nexport function extend(dest) {\r\n\tvar i, j, len, src;\r\n\r\n\tfor (j = 1, len = arguments.length; j < len; j++) {\r\n\t\tsrc = arguments[j];\r\n\t\tfor (i in src) {\r\n\t\t\tdest[i] = src[i];\r\n\t\t}\r\n\t}\r\n\treturn dest;\r\n}\r\n\r\n// @function create(proto: Object, properties?: Object): Object\r\n// Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)\r\nexport var create = Object.create || (function () {\r\n\tfunction F() {}\r\n\treturn function (proto) {\r\n\t\tF.prototype = proto;\r\n\t\treturn new F();\r\n\t};\r\n})();\r\n\r\n// @function bind(fn: Function, …): Function\r\n// Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).\r\n// Has a `L.bind()` shortcut.\r\nexport function bind(fn, obj) {\r\n\tvar slice = Array.prototype.slice;\r\n\r\n\tif (fn.bind) {\r\n\t\treturn fn.bind.apply(fn, slice.call(arguments, 1));\r\n\t}\r\n\r\n\tvar args = slice.call(arguments, 2);\r\n\r\n\treturn function () {\r\n\t\treturn fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);\r\n\t};\r\n}\r\n\r\n// @property lastId: Number\r\n// Last unique ID used by [`stamp()`](#util-stamp)\r\nexport var lastId = 0;\r\n\r\n// @function stamp(obj: Object): Number\r\n// Returns the unique ID of an object, assigning it one if it doesn't have it.\r\nexport function stamp(obj) {\r\n\tif (!('_leaflet_id' in obj)) {\r\n\t\tobj['_leaflet_id'] = ++lastId;\r\n\t}\r\n\treturn obj._leaflet_id;\r\n}\r\n\r\n// @function throttle(fn: Function, time: Number, context: Object): Function\r\n// Returns a function which executes function `fn` with the given scope `context`\r\n// (so that the `this` keyword refers to `context` inside `fn`'s code). The function\r\n// `fn` will be called no more than one time per given amount of `time`. The arguments\r\n// received by the bound function will be any arguments passed when binding the\r\n// function, followed by any arguments passed when invoking the bound function.\r\n// Has an `L.throttle` shortcut.\r\nexport function throttle(fn, time, context) {\r\n\tvar lock, args, wrapperFn, later;\r\n\r\n\tlater = function () {\r\n\t\t// reset lock and call if queued\r\n\t\tlock = false;\r\n\t\tif (args) {\r\n\t\t\twrapperFn.apply(context, args);\r\n\t\t\targs = false;\r\n\t\t}\r\n\t};\r\n\r\n\twrapperFn = function () {\r\n\t\tif (lock) {\r\n\t\t\t// called too soon, queue to call later\r\n\t\t\targs = arguments;\r\n\r\n\t\t} else {\r\n\t\t\t// call and lock until later\r\n\t\t\tfn.apply(context, arguments);\r\n\t\t\tsetTimeout(later, time);\r\n\t\t\tlock = true;\r\n\t\t}\r\n\t};\r\n\r\n\treturn wrapperFn;\r\n}\r\n\r\n// @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number\r\n// Returns the number `num` modulo `range` in such a way so it lies within\r\n// `range[0]` and `range[1]`. The returned value will be always smaller than\r\n// `range[1]` unless `includeMax` is set to `true`.\r\nexport function wrapNum(x, range, includeMax) {\r\n\tvar max = range[1],\r\n\t    min = range[0],\r\n\t    d = max - min;\r\n\treturn x === max && includeMax ? x : ((x - min) % d + d) % d + min;\r\n}\r\n\r\n// @function falseFn(): Function\r\n// Returns a function which always returns `false`.\r\nexport function falseFn() { return false; }\r\n\r\n// @function formatNum(num: Number, precision?: Number|false): Number\r\n// Returns the number `num` rounded with specified `precision`.\r\n// The default `precision` value is 6 decimal places.\r\n// `false` can be passed to skip any processing (can be useful to avoid round-off errors).\r\nexport function formatNum(num, precision) {\r\n\tif (precision === false) { return num; }\r\n\tvar pow = Math.pow(10, precision === undefined ? 6 : precision);\r\n\treturn Math.round(num * pow) / pow;\r\n}\r\n\r\n// @function trim(str: String): String\r\n// Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)\r\nexport function trim(str) {\r\n\treturn str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\r\n}\r\n\r\n// @function splitWords(str: String): String[]\r\n// Trims and splits the string on whitespace and returns the array of parts.\r\nexport function splitWords(str) {\r\n\treturn trim(str).split(/\\s+/);\r\n}\r\n\r\n// @function setOptions(obj: Object, options: Object): Object\r\n// Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.\r\nexport function setOptions(obj, options) {\r\n\tif (!Object.prototype.hasOwnProperty.call(obj, 'options')) {\r\n\t\tobj.options = obj.options ? create(obj.options) : {};\r\n\t}\r\n\tfor (var i in options) {\r\n\t\tobj.options[i] = options[i];\r\n\t}\r\n\treturn obj.options;\r\n}\r\n\r\n// @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String\r\n// Converts an object into a parameter URL string, e.g. `{a: \"foo\", b: \"bar\"}`\r\n// translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will\r\n// be appended at the end. If `uppercase` is `true`, the parameter names will\r\n// be uppercased (e.g. `'?A=foo&B=bar'`)\r\nexport function getParamString(obj, existingUrl, uppercase) {\r\n\tvar params = [];\r\n\tfor (var i in obj) {\r\n\t\tparams.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));\r\n\t}\r\n\treturn ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');\r\n}\r\n\r\nvar templateRe = /\\{ *([\\w_ -]+) *\\}/g;\r\n\r\n// @function template(str: String, data: Object): String\r\n// Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`\r\n// and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string\r\n// `('Hello foo, bar')`. You can also specify functions instead of strings for\r\n// data values — they will be evaluated passing `data` as an argument.\r\nexport function template(str, data) {\r\n\treturn str.replace(templateRe, function (str, key) {\r\n\t\tvar value = data[key];\r\n\r\n\t\tif (value === undefined) {\r\n\t\t\tthrow new Error('No value provided for variable ' + str);\r\n\r\n\t\t} else if (typeof value === 'function') {\r\n\t\t\tvalue = value(data);\r\n\t\t}\r\n\t\treturn value;\r\n\t});\r\n}\r\n\r\n// @function isArray(obj): Boolean\r\n// Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)\r\nexport var isArray = Array.isArray || function (obj) {\r\n\treturn (Object.prototype.toString.call(obj) === '[object Array]');\r\n};\r\n\r\n// @function indexOf(array: Array, el: Object): Number\r\n// Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)\r\nexport function indexOf(array, el) {\r\n\tfor (var i = 0; i < array.length; i++) {\r\n\t\tif (array[i] === el) { return i; }\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\n// @property emptyImageUrl: String\r\n// Data URI string containing a base64-encoded empty GIF image.\r\n// Used as a hack to free memory from unused images on WebKit-powered\r\n// mobile devices (by setting image `src` to this string).\r\nexport var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';\r\n\r\n// inspired by https://paulirish.com/2011/requestanimationframe-for-smart-animating/\r\n\r\nfunction getPrefixed(name) {\r\n\treturn window['webkit' + name] || window['moz' + name] || window['ms' + name];\r\n}\r\n\r\nvar lastTime = 0;\r\n\r\n// fallback for IE 7-8\r\nfunction timeoutDefer(fn) {\r\n\tvar time = +new Date(),\r\n\t    timeToCall = Math.max(0, 16 - (time - lastTime));\r\n\r\n\tlastTime = time + timeToCall;\r\n\treturn window.setTimeout(fn, timeToCall);\r\n}\r\n\r\nexport var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;\r\nexport var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||\r\n\t\tgetPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };\r\n\r\n// @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number\r\n// Schedules `fn` to be executed when the browser repaints. `fn` is bound to\r\n// `context` if given. When `immediate` is set, `fn` is called immediately if\r\n// the browser doesn't have native support for\r\n// [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),\r\n// otherwise it's delayed. Returns a request ID that can be used to cancel the request.\r\nexport function requestAnimFrame(fn, context, immediate) {\r\n\tif (immediate && requestFn === timeoutDefer) {\r\n\t\tfn.call(context);\r\n\t} else {\r\n\t\treturn requestFn.call(window, bind(fn, context));\r\n\t}\r\n}\r\n\r\n// @function cancelAnimFrame(id: Number): undefined\r\n// Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).\r\nexport function cancelAnimFrame(id) {\r\n\tif (id) {\r\n\t\tcancelFn.call(window, id);\r\n\t}\r\n}\r\n","import * as Util from './Util';\r\n\r\n// @class Class\r\n// @aka L.Class\r\n\r\n// @section\r\n// @uninheritable\r\n\r\n// Thanks to John Resig and Dean Edwards for inspiration!\r\n\r\nexport function Class() {}\r\n\r\nClass.extend = function (props) {\r\n\r\n\t// @function extend(props: Object): Function\r\n\t// [Extends the current class](#class-inheritance) given the properties to be included.\r\n\t// Returns a Javascript function that is a class constructor (to be called with `new`).\r\n\tvar NewClass = function () {\r\n\r\n\t\tUtil.setOptions(this);\r\n\r\n\t\t// call the constructor\r\n\t\tif (this.initialize) {\r\n\t\t\tthis.initialize.apply(this, arguments);\r\n\t\t}\r\n\r\n\t\t// call all constructor hooks\r\n\t\tthis.callInitHooks();\r\n\t};\r\n\r\n\tvar parentProto = NewClass.__super__ = this.prototype;\r\n\r\n\tvar proto = Util.create(parentProto);\r\n\tproto.constructor = NewClass;\r\n\r\n\tNewClass.prototype = proto;\r\n\r\n\t// inherit parent's statics\r\n\tfor (var i in this) {\r\n\t\tif (Object.prototype.hasOwnProperty.call(this, i) && i !== 'prototype' && i !== '__super__') {\r\n\t\t\tNewClass[i] = this[i];\r\n\t\t}\r\n\t}\r\n\r\n\t// mix static properties into the class\r\n\tif (props.statics) {\r\n\t\tUtil.extend(NewClass, props.statics);\r\n\t}\r\n\r\n\t// mix includes into the prototype\r\n\tif (props.includes) {\r\n\t\tcheckDeprecatedMixinEvents(props.includes);\r\n\t\tUtil.extend.apply(null, [proto].concat(props.includes));\r\n\t}\r\n\r\n\t// mix given properties into the prototype\r\n\tUtil.extend(proto, props);\r\n\tdelete proto.statics;\r\n\tdelete proto.includes;\r\n\r\n\t// merge options\r\n\tif (proto.options) {\r\n\t\tproto.options = parentProto.options ? Util.create(parentProto.options) : {};\r\n\t\tUtil.extend(proto.options, props.options);\r\n\t}\r\n\r\n\tproto._initHooks = [];\r\n\r\n\t// add method for calling all hooks\r\n\tproto.callInitHooks = function () {\r\n\r\n\t\tif (this._initHooksCalled) { return; }\r\n\r\n\t\tif (parentProto.callInitHooks) {\r\n\t\t\tparentProto.callInitHooks.call(this);\r\n\t\t}\r\n\r\n\t\tthis._initHooksCalled = true;\r\n\r\n\t\tfor (var i = 0, len = proto._initHooks.length; i < len; i++) {\r\n\t\t\tproto._initHooks[i].call(this);\r\n\t\t}\r\n\t};\r\n\r\n\treturn NewClass;\r\n};\r\n\r\n\r\n// @function include(properties: Object): this\r\n// [Includes a mixin](#class-includes) into the current class.\r\nClass.include = function (props) {\r\n\tvar parentOptions = this.prototype.options;\r\n\tUtil.extend(this.prototype, props);\r\n\tif (props.options) {\r\n\t\tthis.prototype.options = parentOptions;\r\n\t\tthis.mergeOptions(props.options);\r\n\t}\r\n\treturn this;\r\n};\r\n\r\n// @function mergeOptions(options: Object): this\r\n// [Merges `options`](#class-options) into the defaults of the class.\r\nClass.mergeOptions = function (options) {\r\n\tUtil.extend(this.prototype.options, options);\r\n\treturn this;\r\n};\r\n\r\n// @function addInitHook(fn: Function): this\r\n// Adds a [constructor hook](#class-constructor-hooks) to the class.\r\nClass.addInitHook = function (fn) { // (Function) || (String, args...)\r\n\tvar args = Array.prototype.slice.call(arguments, 1);\r\n\r\n\tvar init = typeof fn === 'function' ? fn : function () {\r\n\t\tthis[fn].apply(this, args);\r\n\t};\r\n\r\n\tthis.prototype._initHooks = this.prototype._initHooks || [];\r\n\tthis.prototype._initHooks.push(init);\r\n\treturn this;\r\n};\r\n\r\nfunction checkDeprecatedMixinEvents(includes) {\r\n\t/* global L: true */\r\n\tif (typeof L === 'undefined' || !L || !L.Mixin) { return; }\r\n\r\n\tincludes = Util.isArray(includes) ? includes : [includes];\r\n\r\n\tfor (var i = 0; i < includes.length; i++) {\r\n\t\tif (includes[i] === L.Mixin.Events) {\r\n\t\t\tconsole.warn('Deprecated include of L.Mixin.Events: ' +\r\n\t\t\t\t'this property will be removed in future releases, ' +\r\n\t\t\t\t'please inherit from L.Evented instead.', new Error().stack);\r\n\t\t}\r\n\t}\r\n}\r\n","import {Class} from './Class';\r\nimport * as Util from './Util';\r\n\r\n/*\r\n * @class Evented\r\n * @aka L.Evented\r\n * @inherits Class\r\n *\r\n * A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event).\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * map.on('click', function(e) {\r\n * \talert(e.latlng);\r\n * } );\r\n * ```\r\n *\r\n * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:\r\n *\r\n * ```js\r\n * function onClick(e) { ... }\r\n *\r\n * map.on('click', onClick);\r\n * map.off('click', onClick);\r\n * ```\r\n */\r\n\r\nexport var Events = {\r\n\t/* @method on(type: String, fn: Function, context?: Object): this\r\n\t * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).\r\n\t *\r\n\t * @alternative\r\n\t * @method on(eventMap: Object): this\r\n\t * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\n\t */\r\n\ton: function (types, fn, context) {\r\n\r\n\t\t// types can be a map of types/handlers\r\n\t\tif (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\t// we don't process space-separated events here for performance;\r\n\t\t\t\t// it's a hot path since Layer uses the on(obj) syntax\r\n\t\t\t\tthis._on(type, types[type], fn);\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\t// types can be a string of space-separated words\r\n\t\t\ttypes = Util.splitWords(types);\r\n\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tthis._on(types[i], fn, context);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t/* @method off(type: String, fn?: Function, context?: Object): this\r\n\t * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.\r\n\t *\r\n\t * @alternative\r\n\t * @method off(eventMap: Object): this\r\n\t * Removes a set of type/listener pairs.\r\n\t *\r\n\t * @alternative\r\n\t * @method off: this\r\n\t * Removes all listeners to all events on the object. This includes implicitly attached events.\r\n\t */\r\n\toff: function (types, fn, context) {\r\n\r\n\t\tif (!arguments.length) {\r\n\t\t\t// clear all listeners if called without arguments\r\n\t\t\tdelete this._events;\r\n\r\n\t\t} else if (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\tthis._off(type, types[type], fn);\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\ttypes = Util.splitWords(types);\r\n\r\n\t\t\tvar removeAll = arguments.length === 1;\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tif (removeAll) {\r\n\t\t\t\t\tthis._off(types[i]);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthis._off(types[i], fn, context);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// attach listener (without syntactic sugar now)\r\n\t_on: function (type, fn, context, _once) {\r\n\t\tif (typeof fn !== 'function') {\r\n\t\t\tconsole.warn('wrong listener type: ' + typeof fn);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// check if fn already there\r\n\t\tif (this._listens(type, fn, context) !== false) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (context === this) {\r\n\t\t\t// Less memory footprint.\r\n\t\t\tcontext = undefined;\r\n\t\t}\r\n\r\n\t\tvar newListener = {fn: fn, ctx: context};\r\n\t\tif (_once) {\r\n\t\t\tnewListener.once = true;\r\n\t\t}\r\n\r\n\t\tthis._events = this._events || {};\r\n\t\tthis._events[type] = this._events[type] || [];\r\n\t\tthis._events[type].push(newListener);\r\n\t},\r\n\r\n\t_off: function (type, fn, context) {\r\n\t\tvar listeners,\r\n\t\t    i,\r\n\t\t    len;\r\n\r\n\t\tif (!this._events) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tlisteners = this._events[type];\r\n\t\tif (!listeners) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (arguments.length === 1) { // remove all\r\n\t\t\tif (this._firingCount) {\r\n\t\t\t\t// Set all removed listeners to noop\r\n\t\t\t\t// so they are not called if remove happens in fire\r\n\t\t\t\tfor (i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\t\t\tlisteners[i].fn = Util.falseFn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// clear all listeners for a type if function isn't specified\r\n\t\t\tdelete this._events[type];\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (typeof fn !== 'function') {\r\n\t\t\tconsole.warn('wrong listener type: ' + typeof fn);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// find fn and remove it\r\n\t\tvar index = this._listens(type, fn, context);\r\n\t\tif (index !== false) {\r\n\t\t\tvar listener = listeners[index];\r\n\t\t\tif (this._firingCount) {\r\n\t\t\t\t// set the removed listener to noop so that's not called if remove happens in fire\r\n\t\t\t\tlistener.fn = Util.falseFn;\r\n\r\n\t\t\t\t/* copy array in case events are being fired */\r\n\t\t\t\tthis._events[type] = listeners = listeners.slice();\r\n\t\t\t}\r\n\t\t\tlisteners.splice(index, 1);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method fire(type: String, data?: Object, propagate?: Boolean): this\r\n\t// Fires an event of the specified type. You can optionally provide a data\r\n\t// object — the first argument of the listener function will contain its\r\n\t// properties. The event can optionally be propagated to event parents.\r\n\tfire: function (type, data, propagate) {\r\n\t\tif (!this.listens(type, propagate)) { return this; }\r\n\r\n\t\tvar event = Util.extend({}, data, {\r\n\t\t\ttype: type,\r\n\t\t\ttarget: this,\r\n\t\t\tsourceTarget: data && data.sourceTarget || this\r\n\t\t});\r\n\r\n\t\tif (this._events) {\r\n\t\t\tvar listeners = this._events[type];\r\n\t\t\tif (listeners) {\r\n\t\t\t\tthis._firingCount = (this._firingCount + 1) || 1;\r\n\t\t\t\tfor (var i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\t\t\tvar l = listeners[i];\r\n\t\t\t\t\t// off overwrites l.fn, so we need to copy fn to a var\r\n\t\t\t\t\tvar fn = l.fn;\r\n\t\t\t\t\tif (l.once) {\r\n\t\t\t\t\t\tthis.off(type, fn, l.ctx);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfn.call(l.ctx || this, event);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tthis._firingCount--;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (propagate) {\r\n\t\t\t// propagate the event to parents (set with addEventParent)\r\n\t\t\tthis._propagateEvent(event);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method listens(type: String, propagate?: Boolean): Boolean\r\n\t// @method listens(type: String, fn: Function, context?: Object, propagate?: Boolean): Boolean\r\n\t// Returns `true` if a particular event type has any listeners attached to it.\r\n\t// The verification can optionally be propagated, it will return `true` if parents have the listener attached to it.\r\n\tlistens: function (type, fn, context, propagate) {\r\n\t\tif (typeof type !== 'string') {\r\n\t\t\tconsole.warn('\"string\" type argument expected');\r\n\t\t}\r\n\r\n\t\t// we don't overwrite the input `fn` value, because we need to use it for propagation\r\n\t\tvar _fn = fn;\r\n\t\tif (typeof fn !== 'function') {\r\n\t\t\tpropagate = !!fn;\r\n\t\t\t_fn = undefined;\r\n\t\t\tcontext = undefined;\r\n\t\t}\r\n\r\n\t\tvar listeners = this._events && this._events[type];\r\n\t\tif (listeners && listeners.length) {\r\n\t\t\tif (this._listens(type, _fn, context) !== false) {\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (propagate) {\r\n\t\t\t// also check parents for listeners if event propagates\r\n\t\t\tfor (var id in this._eventParents) {\r\n\t\t\t\tif (this._eventParents[id].listens(type, fn, context, propagate)) { return true; }\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t},\r\n\r\n\t// returns the index (number) or false\r\n\t_listens: function (type, fn, context) {\r\n\t\tif (!this._events) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tvar listeners = this._events[type] || [];\r\n\t\tif (!fn) {\r\n\t\t\treturn !!listeners.length;\r\n\t\t}\r\n\r\n\t\tif (context === this) {\r\n\t\t\t// Less memory footprint.\r\n\t\t\tcontext = undefined;\r\n\t\t}\r\n\r\n\t\tfor (var i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\tif (listeners[i].fn === fn && listeners[i].ctx === context) {\r\n\t\t\t\treturn i;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\r\n\t},\r\n\r\n\t// @method once(…): this\r\n\t// Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.\r\n\tonce: function (types, fn, context) {\r\n\r\n\t\t// types can be a map of types/handlers\r\n\t\tif (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\t// we don't process space-separated events here for performance;\r\n\t\t\t\t// it's a hot path since Layer uses the on(obj) syntax\r\n\t\t\t\tthis._on(type, types[type], fn, true);\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\t// types can be a string of space-separated words\r\n\t\t\ttypes = Util.splitWords(types);\r\n\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tthis._on(types[i], fn, context, true);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method addEventParent(obj: Evented): this\r\n\t// Adds an event parent - an `Evented` that will receive propagated events\r\n\taddEventParent: function (obj) {\r\n\t\tthis._eventParents = this._eventParents || {};\r\n\t\tthis._eventParents[Util.stamp(obj)] = obj;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeEventParent(obj: Evented): this\r\n\t// Removes an event parent, so it will stop receiving propagated events\r\n\tremoveEventParent: function (obj) {\r\n\t\tif (this._eventParents) {\r\n\t\t\tdelete this._eventParents[Util.stamp(obj)];\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_propagateEvent: function (e) {\r\n\t\tfor (var id in this._eventParents) {\r\n\t\t\tthis._eventParents[id].fire(e.type, Util.extend({\r\n\t\t\t\tlayer: e.target,\r\n\t\t\t\tpropagatedFrom: e.target\r\n\t\t\t}, e), true);\r\n\t\t}\r\n\t}\r\n};\r\n\r\n// aliases; we should ditch those eventually\r\n\r\n// @method addEventListener(…): this\r\n// Alias to [`on(…)`](#evented-on)\r\nEvents.addEventListener = Events.on;\r\n\r\n// @method removeEventListener(…): this\r\n// Alias to [`off(…)`](#evented-off)\r\n\r\n// @method clearAllEventListeners(…): this\r\n// Alias to [`off()`](#evented-off)\r\nEvents.removeEventListener = Events.clearAllEventListeners = Events.off;\r\n\r\n// @method addOneTimeEventListener(…): this\r\n// Alias to [`once(…)`](#evented-once)\r\nEvents.addOneTimeEventListener = Events.once;\r\n\r\n// @method fireEvent(…): this\r\n// Alias to [`fire(…)`](#evented-fire)\r\nEvents.fireEvent = Events.fire;\r\n\r\n// @method hasEventListeners(…): Boolean\r\n// Alias to [`listens(…)`](#evented-listens)\r\nEvents.hasEventListeners = Events.listens;\r\n\r\nexport var Evented = Class.extend(Events);\r\n","import {isArray, formatNum} from '../core/Util';\r\n\r\n/*\r\n * @class Point\r\n * @aka L.Point\r\n *\r\n * Represents a point with `x` and `y` coordinates in pixels.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var point = L.point(200, 300);\r\n * ```\r\n *\r\n * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:\r\n *\r\n * ```js\r\n * map.panBy([200, 300]);\r\n * map.panBy(L.point(200, 300));\r\n * ```\r\n *\r\n * Note that `Point` does not inherit from Leaflet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nexport function Point(x, y, round) {\r\n\t// @property x: Number; The `x` coordinate of the point\r\n\tthis.x = (round ? Math.round(x) : x);\r\n\t// @property y: Number; The `y` coordinate of the point\r\n\tthis.y = (round ? Math.round(y) : y);\r\n}\r\n\r\nvar trunc = Math.trunc || function (v) {\r\n\treturn v > 0 ? Math.floor(v) : Math.ceil(v);\r\n};\r\n\r\nPoint.prototype = {\r\n\r\n\t// @method clone(): Point\r\n\t// Returns a copy of the current point.\r\n\tclone: function () {\r\n\t\treturn new Point(this.x, this.y);\r\n\t},\r\n\r\n\t// @method add(otherPoint: Point): Point\r\n\t// Returns the result of addition of the current and the given points.\r\n\tadd: function (point) {\r\n\t\t// non-destructive, returns a new point\r\n\t\treturn this.clone()._add(toPoint(point));\r\n\t},\r\n\r\n\t_add: function (point) {\r\n\t\t// destructive, used directly for performance in situations where it's safe to modify existing point\r\n\t\tthis.x += point.x;\r\n\t\tthis.y += point.y;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method subtract(otherPoint: Point): Point\r\n\t// Returns the result of subtraction of the given point from the current.\r\n\tsubtract: function (point) {\r\n\t\treturn this.clone()._subtract(toPoint(point));\r\n\t},\r\n\r\n\t_subtract: function (point) {\r\n\t\tthis.x -= point.x;\r\n\t\tthis.y -= point.y;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method divideBy(num: Number): Point\r\n\t// Returns the result of division of the current point by the given number.\r\n\tdivideBy: function (num) {\r\n\t\treturn this.clone()._divideBy(num);\r\n\t},\r\n\r\n\t_divideBy: function (num) {\r\n\t\tthis.x /= num;\r\n\t\tthis.y /= num;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method multiplyBy(num: Number): Point\r\n\t// Returns the result of multiplication of the current point by the given number.\r\n\tmultiplyBy: function (num) {\r\n\t\treturn this.clone()._multiplyBy(num);\r\n\t},\r\n\r\n\t_multiplyBy: function (num) {\r\n\t\tthis.x *= num;\r\n\t\tthis.y *= num;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method scaleBy(scale: Point): Point\r\n\t// Multiply each coordinate of the current point by each coordinate of\r\n\t// `scale`. In linear algebra terms, multiply the point by the\r\n\t// [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)\r\n\t// defined by `scale`.\r\n\tscaleBy: function (point) {\r\n\t\treturn new Point(this.x * point.x, this.y * point.y);\r\n\t},\r\n\r\n\t// @method unscaleBy(scale: Point): Point\r\n\t// Inverse of `scaleBy`. Divide each coordinate of the current point by\r\n\t// each coordinate of `scale`.\r\n\tunscaleBy: function (point) {\r\n\t\treturn new Point(this.x / point.x, this.y / point.y);\r\n\t},\r\n\r\n\t// @method round(): Point\r\n\t// Returns a copy of the current point with rounded coordinates.\r\n\tround: function () {\r\n\t\treturn this.clone()._round();\r\n\t},\r\n\r\n\t_round: function () {\r\n\t\tthis.x = Math.round(this.x);\r\n\t\tthis.y = Math.round(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method floor(): Point\r\n\t// Returns a copy of the current point with floored coordinates (rounded down).\r\n\tfloor: function () {\r\n\t\treturn this.clone()._floor();\r\n\t},\r\n\r\n\t_floor: function () {\r\n\t\tthis.x = Math.floor(this.x);\r\n\t\tthis.y = Math.floor(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method ceil(): Point\r\n\t// Returns a copy of the current point with ceiled coordinates (rounded up).\r\n\tceil: function () {\r\n\t\treturn this.clone()._ceil();\r\n\t},\r\n\r\n\t_ceil: function () {\r\n\t\tthis.x = Math.ceil(this.x);\r\n\t\tthis.y = Math.ceil(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method trunc(): Point\r\n\t// Returns a copy of the current point with truncated coordinates (rounded towards zero).\r\n\ttrunc: function () {\r\n\t\treturn this.clone()._trunc();\r\n\t},\r\n\r\n\t_trunc: function () {\r\n\t\tthis.x = trunc(this.x);\r\n\t\tthis.y = trunc(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method distanceTo(otherPoint: Point): Number\r\n\t// Returns the cartesian distance between the current and the given points.\r\n\tdistanceTo: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\tvar x = point.x - this.x,\r\n\t\t    y = point.y - this.y;\r\n\r\n\t\treturn Math.sqrt(x * x + y * y);\r\n\t},\r\n\r\n\t// @method equals(otherPoint: Point): Boolean\r\n\t// Returns `true` if the given point has the same coordinates.\r\n\tequals: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\treturn point.x === this.x &&\r\n\t\t       point.y === this.y;\r\n\t},\r\n\r\n\t// @method contains(otherPoint: Point): Boolean\r\n\t// Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).\r\n\tcontains: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\treturn Math.abs(point.x) <= Math.abs(this.x) &&\r\n\t\t       Math.abs(point.y) <= Math.abs(this.y);\r\n\t},\r\n\r\n\t// @method toString(): String\r\n\t// Returns a string representation of the point for debugging purposes.\r\n\ttoString: function () {\r\n\t\treturn 'Point(' +\r\n\t\t        formatNum(this.x) + ', ' +\r\n\t\t        formatNum(this.y) + ')';\r\n\t}\r\n};\r\n\r\n// @factory L.point(x: Number, y: Number, round?: Boolean)\r\n// Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.\r\n\r\n// @alternative\r\n// @factory L.point(coords: Number[])\r\n// Expects an array of the form `[x, y]` instead.\r\n\r\n// @alternative\r\n// @factory L.point(coords: Object)\r\n// Expects a plain object of the form `{x: Number, y: Number}` instead.\r\nexport function toPoint(x, y, round) {\r\n\tif (x instanceof Point) {\r\n\t\treturn x;\r\n\t}\r\n\tif (isArray(x)) {\r\n\t\treturn new Point(x[0], x[1]);\r\n\t}\r\n\tif (x === undefined || x === null) {\r\n\t\treturn x;\r\n\t}\r\n\tif (typeof x === 'object' && 'x' in x && 'y' in x) {\r\n\t\treturn new Point(x.x, x.y);\r\n\t}\r\n\treturn new Point(x, y, round);\r\n}\r\n","import {Point, toPoint} from './Point';\r\n\r\n/*\r\n * @class Bounds\r\n * @aka L.Bounds\r\n *\r\n * Represents a rectangular area in pixel coordinates.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var p1 = L.point(10, 10),\r\n * p2 = L.point(40, 60),\r\n * bounds = L.bounds(p1, p2);\r\n * ```\r\n *\r\n * All Leaflet methods that accept `Bounds` objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:\r\n *\r\n * ```js\r\n * otherBounds.intersects([[10, 10], [40, 60]]);\r\n * ```\r\n *\r\n * Note that `Bounds` does not inherit from Leaflet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nexport function Bounds(a, b) {\r\n\tif (!a) { return; }\r\n\r\n\tvar points = b ? [a, b] : a;\r\n\r\n\tfor (var i = 0, len = points.length; i < len; i++) {\r\n\t\tthis.extend(points[i]);\r\n\t}\r\n}\r\n\r\nBounds.prototype = {\r\n\t// @method extend(point: Point): this\r\n\t// Extends the bounds to contain the given point.\r\n\r\n\t// @alternative\r\n\t// @method extend(otherBounds: Bounds): this\r\n\t// Extend the bounds to contain the given bounds\r\n\textend: function (obj) {\r\n\t\tvar min2, max2;\r\n\t\tif (!obj) { return this; }\r\n\r\n\t\tif (obj instanceof Point || typeof obj[0] === 'number' || 'x' in obj) {\r\n\t\t\tmin2 = max2 = toPoint(obj);\r\n\t\t} else {\r\n\t\t\tobj = toBounds(obj);\r\n\t\t\tmin2 = obj.min;\r\n\t\t\tmax2 = obj.max;\r\n\r\n\t\t\tif (!min2 || !max2) { return this; }\r\n\t\t}\r\n\r\n\t\t// @property min: Point\r\n\t\t// The top left corner of the rectangle.\r\n\t\t// @property max: Point\r\n\t\t// The bottom right corner of the rectangle.\r\n\t\tif (!this.min && !this.max) {\r\n\t\t\tthis.min = min2.clone();\r\n\t\t\tthis.max = max2.clone();\r\n\t\t} else {\r\n\t\t\tthis.min.x = Math.min(min2.x, this.min.x);\r\n\t\t\tthis.max.x = Math.max(max2.x, this.max.x);\r\n\t\t\tthis.min.y = Math.min(min2.y, this.min.y);\r\n\t\t\tthis.max.y = Math.max(max2.y, this.max.y);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getCenter(round?: Boolean): Point\r\n\t// Returns the center point of the bounds.\r\n\tgetCenter: function (round) {\r\n\t\treturn toPoint(\r\n\t\t        (this.min.x + this.max.x) / 2,\r\n\t\t        (this.min.y + this.max.y) / 2, round);\r\n\t},\r\n\r\n\t// @method getBottomLeft(): Point\r\n\t// Returns the bottom-left point of the bounds.\r\n\tgetBottomLeft: function () {\r\n\t\treturn toPoint(this.min.x, this.max.y);\r\n\t},\r\n\r\n\t// @method getTopRight(): Point\r\n\t// Returns the top-right point of the bounds.\r\n\tgetTopRight: function () { // -> Point\r\n\t\treturn toPoint(this.max.x, this.min.y);\r\n\t},\r\n\r\n\t// @method getTopLeft(): Point\r\n\t// Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).\r\n\tgetTopLeft: function () {\r\n\t\treturn this.min; // left, top\r\n\t},\r\n\r\n\t// @method getBottomRight(): Point\r\n\t// Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).\r\n\tgetBottomRight: function () {\r\n\t\treturn this.max; // right, bottom\r\n\t},\r\n\r\n\t// @method getSize(): Point\r\n\t// Returns the size of the given bounds\r\n\tgetSize: function () {\r\n\t\treturn this.max.subtract(this.min);\r\n\t},\r\n\r\n\t// @method contains(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle contains the given one.\r\n\t// @alternative\r\n\t// @method contains(point: Point): Boolean\r\n\t// Returns `true` if the rectangle contains the given point.\r\n\tcontains: function (obj) {\r\n\t\tvar min, max;\r\n\r\n\t\tif (typeof obj[0] === 'number' || obj instanceof Point) {\r\n\t\t\tobj = toPoint(obj);\r\n\t\t} else {\r\n\t\t\tobj = toBounds(obj);\r\n\t\t}\r\n\r\n\t\tif (obj instanceof Bounds) {\r\n\t\t\tmin = obj.min;\r\n\t\t\tmax = obj.max;\r\n\t\t} else {\r\n\t\t\tmin = max = obj;\r\n\t\t}\r\n\r\n\t\treturn (min.x >= this.min.x) &&\r\n\t\t       (max.x <= this.max.x) &&\r\n\t\t       (min.y >= this.min.y) &&\r\n\t\t       (max.y <= this.max.y);\r\n\t},\r\n\r\n\t// @method intersects(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle intersects the given bounds. Two bounds\r\n\t// intersect if they have at least one point in common.\r\n\tintersects: function (bounds) { // (Bounds) -> Boolean\r\n\t\tbounds = toBounds(bounds);\r\n\r\n\t\tvar min = this.min,\r\n\t\t    max = this.max,\r\n\t\t    min2 = bounds.min,\r\n\t\t    max2 = bounds.max,\r\n\t\t    xIntersects = (max2.x >= min.x) && (min2.x <= max.x),\r\n\t\t    yIntersects = (max2.y >= min.y) && (min2.y <= max.y);\r\n\r\n\t\treturn xIntersects && yIntersects;\r\n\t},\r\n\r\n\t// @method overlaps(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle overlaps the given bounds. Two bounds\r\n\t// overlap if their intersection is an area.\r\n\toverlaps: function (bounds) { // (Bounds) -> Boolean\r\n\t\tbounds = toBounds(bounds);\r\n\r\n\t\tvar min = this.min,\r\n\t\t    max = this.max,\r\n\t\t    min2 = bounds.min,\r\n\t\t    max2 = bounds.max,\r\n\t\t    xOverlaps = (max2.x > min.x) && (min2.x < max.x),\r\n\t\t    yOverlaps = (max2.y > min.y) && (min2.y < max.y);\r\n\r\n\t\treturn xOverlaps && yOverlaps;\r\n\t},\r\n\r\n\t// @method isValid(): Boolean\r\n\t// Returns `true` if the bounds are properly initialized.\r\n\tisValid: function () {\r\n\t\treturn !!(this.min && this.max);\r\n\t},\r\n\r\n\r\n\t// @method pad(bufferRatio: Number): Bounds\r\n\t// Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.\r\n\t// For example, a ratio of 0.5 extends the bounds by 50% in each direction.\r\n\t// Negative values will retract the bounds.\r\n\tpad: function (bufferRatio) {\r\n\t\tvar min = this.min,\r\n\t\tmax = this.max,\r\n\t\theightBuffer = Math.abs(min.x - max.x) * bufferRatio,\r\n\t\twidthBuffer = Math.abs(min.y - max.y) * bufferRatio;\r\n\r\n\r\n\t\treturn toBounds(\r\n\t\t\ttoPoint(min.x - heightBuffer, min.y - widthBuffer),\r\n\t\t\ttoPoint(max.x + heightBuffer, max.y + widthBuffer));\r\n\t},\r\n\r\n\r\n\t// @method equals(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle is equivalent to the given bounds.\r\n\tequals: function (bounds) {\r\n\t\tif (!bounds) { return false; }\r\n\r\n\t\tbounds = toBounds(bounds);\r\n\r\n\t\treturn this.min.equals(bounds.getTopLeft()) &&\r\n\t\t\tthis.max.equals(bounds.getBottomRight());\r\n\t},\r\n};\r\n\r\n\r\n// @factory L.bounds(corner1: Point, corner2: Point)\r\n// Creates a Bounds object from two corners coordinate pairs.\r\n// @alternative\r\n// @factory L.bounds(points: Point[])\r\n// Creates a Bounds object from the given array of points.\r\nexport function toBounds(a, b) {\r\n\tif (!a || a instanceof Bounds) {\r\n\t\treturn a;\r\n\t}\r\n\treturn new Bounds(a, b);\r\n}\r\n","import {LatLng, toLatLng} from './LatLng';\r\n\r\n/*\r\n * @class LatLngBounds\r\n * @aka L.LatLngBounds\r\n *\r\n * Represents a rectangular geographical area on a map.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var corner1 = L.latLng(40.712, -74.227),\r\n * corner2 = L.latLng(40.774, -74.125),\r\n * bounds = L.latLngBounds(corner1, corner2);\r\n * ```\r\n *\r\n * All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:\r\n *\r\n * ```js\r\n * map.fitBounds([\r\n * \t[40.712, -74.227],\r\n * \t[40.774, -74.125]\r\n * ]);\r\n * ```\r\n *\r\n * Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range.\r\n *\r\n * Note that `LatLngBounds` does not inherit from Leaflet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nexport function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])\r\n\tif (!corner1) { return; }\r\n\r\n\tvar latlngs = corner2 ? [corner1, corner2] : corner1;\r\n\r\n\tfor (var i = 0, len = latlngs.length; i < len; i++) {\r\n\t\tthis.extend(latlngs[i]);\r\n\t}\r\n}\r\n\r\nLatLngBounds.prototype = {\r\n\r\n\t// @method extend(latlng: LatLng): this\r\n\t// Extend the bounds to contain the given point\r\n\r\n\t// @alternative\r\n\t// @method extend(otherBounds: LatLngBounds): this\r\n\t// Extend the bounds to contain the given bounds\r\n\textend: function (obj) {\r\n\t\tvar sw = this._southWest,\r\n\t\t    ne = this._northEast,\r\n\t\t    sw2, ne2;\r\n\r\n\t\tif (obj instanceof LatLng) {\r\n\t\t\tsw2 = obj;\r\n\t\t\tne2 = obj;\r\n\r\n\t\t} else if (obj instanceof LatLngBounds) {\r\n\t\t\tsw2 = obj._southWest;\r\n\t\t\tne2 = obj._northEast;\r\n\r\n\t\t\tif (!sw2 || !ne2) { return this; }\r\n\r\n\t\t} else {\r\n\t\t\treturn obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;\r\n\t\t}\r\n\r\n\t\tif (!sw && !ne) {\r\n\t\t\tthis._southWest = new LatLng(sw2.lat, sw2.lng);\r\n\t\t\tthis._northEast = new LatLng(ne2.lat, ne2.lng);\r\n\t\t} else {\r\n\t\t\tsw.lat = Math.min(sw2.lat, sw.lat);\r\n\t\t\tsw.lng = Math.min(sw2.lng, sw.lng);\r\n\t\t\tne.lat = Math.max(ne2.lat, ne.lat);\r\n\t\t\tne.lng = Math.max(ne2.lng, ne.lng);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method pad(bufferRatio: Number): LatLngBounds\r\n\t// Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.\r\n\t// For example, a ratio of 0.5 extends the bounds by 50% in each direction.\r\n\t// Negative values will retract the bounds.\r\n\tpad: function (bufferRatio) {\r\n\t\tvar sw = this._southWest,\r\n\t\t    ne = this._northEast,\r\n\t\t    heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,\r\n\t\t    widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;\r\n\r\n\t\treturn new LatLngBounds(\r\n\t\t        new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),\r\n\t\t        new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));\r\n\t},\r\n\r\n\t// @method getCenter(): LatLng\r\n\t// Returns the center point of the bounds.\r\n\tgetCenter: function () {\r\n\t\treturn new LatLng(\r\n\t\t        (this._southWest.lat + this._northEast.lat) / 2,\r\n\t\t        (this._southWest.lng + this._northEast.lng) / 2);\r\n\t},\r\n\r\n\t// @method getSouthWest(): LatLng\r\n\t// Returns the south-west point of the bounds.\r\n\tgetSouthWest: function () {\r\n\t\treturn this._southWest;\r\n\t},\r\n\r\n\t// @method getNorthEast(): LatLng\r\n\t// Returns the north-east point of the bounds.\r\n\tgetNorthEast: function () {\r\n\t\treturn this._northEast;\r\n\t},\r\n\r\n\t// @method getNorthWest(): LatLng\r\n\t// Returns the north-west point of the bounds.\r\n\tgetNorthWest: function () {\r\n\t\treturn new LatLng(this.getNorth(), this.getWest());\r\n\t},\r\n\r\n\t// @method getSouthEast(): LatLng\r\n\t// Returns the south-east point of the bounds.\r\n\tgetSouthEast: function () {\r\n\t\treturn new LatLng(this.getSouth(), this.getEast());\r\n\t},\r\n\r\n\t// @method getWest(): Number\r\n\t// Returns the west longitude of the bounds\r\n\tgetWest: function () {\r\n\t\treturn this._southWest.lng;\r\n\t},\r\n\r\n\t// @method getSouth(): Number\r\n\t// Returns the south latitude of the bounds\r\n\tgetSouth: function () {\r\n\t\treturn this._southWest.lat;\r\n\t},\r\n\r\n\t// @method getEast(): Number\r\n\t// Returns the east longitude of the bounds\r\n\tgetEast: function () {\r\n\t\treturn this._northEast.lng;\r\n\t},\r\n\r\n\t// @method getNorth(): Number\r\n\t// Returns the north latitude of the bounds\r\n\tgetNorth: function () {\r\n\t\treturn this._northEast.lat;\r\n\t},\r\n\r\n\t// @method contains(otherBounds: LatLngBounds): Boolean\r\n\t// Returns `true` if the rectangle contains the given one.\r\n\r\n\t// @alternative\r\n\t// @method contains (latlng: LatLng): Boolean\r\n\t// Returns `true` if the rectangle contains the given point.\r\n\tcontains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean\r\n\t\tif (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {\r\n\t\t\tobj = toLatLng(obj);\r\n\t\t} else {\r\n\t\t\tobj = toLatLngBounds(obj);\r\n\t\t}\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t    ne = this._northEast,\r\n\t\t    sw2, ne2;\r\n\r\n\t\tif (obj instanceof LatLngBounds) {\r\n\t\t\tsw2 = obj.getSouthWest();\r\n\t\t\tne2 = obj.getNorthEast();\r\n\t\t} else {\r\n\t\t\tsw2 = ne2 = obj;\r\n\t\t}\r\n\r\n\t\treturn (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&\r\n\t\t       (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);\r\n\t},\r\n\r\n\t// @method intersects(otherBounds: LatLngBounds): Boolean\r\n\t// Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.\r\n\tintersects: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t    ne = this._northEast,\r\n\t\t    sw2 = bounds.getSouthWest(),\r\n\t\t    ne2 = bounds.getNorthEast(),\r\n\r\n\t\t    latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),\r\n\t\t    lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);\r\n\r\n\t\treturn latIntersects && lngIntersects;\r\n\t},\r\n\r\n\t// @method overlaps(otherBounds: LatLngBounds): Boolean\r\n\t// Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.\r\n\toverlaps: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t    ne = this._northEast,\r\n\t\t    sw2 = bounds.getSouthWest(),\r\n\t\t    ne2 = bounds.getNorthEast(),\r\n\r\n\t\t    latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),\r\n\t\t    lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);\r\n\r\n\t\treturn latOverlaps && lngOverlaps;\r\n\t},\r\n\r\n\t// @method toBBoxString(): String\r\n\t// Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.\r\n\ttoBBoxString: function () {\r\n\t\treturn [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');\r\n\t},\r\n\r\n\t// @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean\r\n\t// Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.\r\n\tequals: function (bounds, maxMargin) {\r\n\t\tif (!bounds) { return false; }\r\n\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\treturn this._southWest.equals(bounds.getSouthWest(), maxMargin) &&\r\n\t\t       this._northEast.equals(bounds.getNorthEast(), maxMargin);\r\n\t},\r\n\r\n\t// @method isValid(): Boolean\r\n\t// Returns `true` if the bounds are properly initialized.\r\n\tisValid: function () {\r\n\t\treturn !!(this._southWest && this._northEast);\r\n\t}\r\n};\r\n\r\n// TODO International date line?\r\n\r\n// @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)\r\n// Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.\r\n\r\n// @alternative\r\n// @factory L.latLngBounds(latlngs: LatLng[])\r\n// Creates a `LatLngBounds` object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds).\r\nexport function toLatLngBounds(a, b) {\r\n\tif (a instanceof LatLngBounds) {\r\n\t\treturn a;\r\n\t}\r\n\treturn new LatLngBounds(a, b);\r\n}\r\n","import * as Util from '../core/Util';\r\nimport {Earth} from './crs/CRS.Earth';\r\nimport {toLatLngBounds} from './LatLngBounds';\r\n\r\n/* @class LatLng\r\n * @aka L.LatLng\r\n *\r\n * Represents a geographical point with a certain latitude and longitude.\r\n *\r\n * @example\r\n *\r\n * ```\r\n * var latlng = L.latLng(50.5, 30.5);\r\n * ```\r\n *\r\n * All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent:\r\n *\r\n * ```\r\n * map.panTo([50, 30]);\r\n * map.panTo({lon: 30, lat: 50});\r\n * map.panTo({lat: 50, lng: 30});\r\n * map.panTo(L.latLng(50, 30));\r\n * ```\r\n *\r\n * Note that `LatLng` does not inherit from Leaflet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nexport function LatLng(lat, lng, alt) {\r\n\tif (isNaN(lat) || isNaN(lng)) {\r\n\t\tthrow new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');\r\n\t}\r\n\r\n\t// @property lat: Number\r\n\t// Latitude in degrees\r\n\tthis.lat = +lat;\r\n\r\n\t// @property lng: Number\r\n\t// Longitude in degrees\r\n\tthis.lng = +lng;\r\n\r\n\t// @property alt: Number\r\n\t// Altitude in meters (optional)\r\n\tif (alt !== undefined) {\r\n\t\tthis.alt = +alt;\r\n\t}\r\n}\r\n\r\nLatLng.prototype = {\r\n\t// @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean\r\n\t// Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.\r\n\tequals: function (obj, maxMargin) {\r\n\t\tif (!obj) { return false; }\r\n\r\n\t\tobj = toLatLng(obj);\r\n\r\n\t\tvar margin = Math.max(\r\n\t\t        Math.abs(this.lat - obj.lat),\r\n\t\t        Math.abs(this.lng - obj.lng));\r\n\r\n\t\treturn margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);\r\n\t},\r\n\r\n\t// @method toString(): String\r\n\t// Returns a string representation of the point (for debugging purposes).\r\n\ttoString: function (precision) {\r\n\t\treturn 'LatLng(' +\r\n\t\t        Util.formatNum(this.lat, precision) + ', ' +\r\n\t\t        Util.formatNum(this.lng, precision) + ')';\r\n\t},\r\n\r\n\t// @method distanceTo(otherLatLng: LatLng): Number\r\n\t// Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).\r\n\tdistanceTo: function (other) {\r\n\t\treturn Earth.distance(this, toLatLng(other));\r\n\t},\r\n\r\n\t// @method wrap(): LatLng\r\n\t// Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.\r\n\twrap: function () {\r\n\t\treturn Earth.wrapLatLng(this);\r\n\t},\r\n\r\n\t// @method toBounds(sizeInMeters: Number): LatLngBounds\r\n\t// Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.\r\n\ttoBounds: function (sizeInMeters) {\r\n\t\tvar latAccuracy = 180 * sizeInMeters / 40075017,\r\n\t\t    lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);\r\n\r\n\t\treturn toLatLngBounds(\r\n\t\t        [this.lat - latAccuracy, this.lng - lngAccuracy],\r\n\t\t        [this.lat + latAccuracy, this.lng + lngAccuracy]);\r\n\t},\r\n\r\n\tclone: function () {\r\n\t\treturn new LatLng(this.lat, this.lng, this.alt);\r\n\t}\r\n};\r\n\r\n\r\n\r\n// @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng\r\n// Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).\r\n\r\n// @alternative\r\n// @factory L.latLng(coords: Array): LatLng\r\n// Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.\r\n\r\n// @alternative\r\n// @factory L.latLng(coords: Object): LatLng\r\n// Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.\r\n\r\nexport function toLatLng(a, b, c) {\r\n\tif (a instanceof LatLng) {\r\n\t\treturn a;\r\n\t}\r\n\tif (Util.isArray(a) && typeof a[0] !== 'object') {\r\n\t\tif (a.length === 3) {\r\n\t\t\treturn new LatLng(a[0], a[1], a[2]);\r\n\t\t}\r\n\t\tif (a.length === 2) {\r\n\t\t\treturn new LatLng(a[0], a[1]);\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\tif (a === undefined || a === null) {\r\n\t\treturn a;\r\n\t}\r\n\tif (typeof a === 'object' && 'lat' in a) {\r\n\t\treturn new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);\r\n\t}\r\n\tif (b === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\treturn new LatLng(a, b, c);\r\n}\r\n","\r\nimport {Bounds} from '../../geometry/Bounds';\r\nimport {LatLng} from '../LatLng';\r\nimport {LatLngBounds} from '../LatLngBounds';\r\nimport * as Util from '../../core/Util';\r\n\r\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.Base\r\n * Object that defines coordinate reference systems for projecting\r\n * geographical points into pixel (screen) coordinates and back (and to\r\n * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See\r\n * [spatial reference system](https://en.wikipedia.org/wiki/Spatial_reference_system).\r\n *\r\n * Leaflet defines the most usual CRSs by default. If you want to use a\r\n * CRS not defined by default, take a look at the\r\n * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.\r\n *\r\n * Note that the CRS instances do not inherit from Leaflet's `Class` object,\r\n * and can't be instantiated. Also, new classes can't inherit from them,\r\n * and methods can't be added to them with the `include` function.\r\n */\r\n\r\nexport var CRS = {\r\n\t// @method latLngToPoint(latlng: LatLng, zoom: Number): Point\r\n\t// Projects geographical coordinates into pixel coordinates for a given zoom.\r\n\tlatLngToPoint: function (latlng, zoom) {\r\n\t\tvar projectedPoint = this.projection.project(latlng),\r\n\t\t    scale = this.scale(zoom);\r\n\r\n\t\treturn this.transformation._transform(projectedPoint, scale);\r\n\t},\r\n\r\n\t// @method pointToLatLng(point: Point, zoom: Number): LatLng\r\n\t// The inverse of `latLngToPoint`. Projects pixel coordinates on a given\r\n\t// zoom into geographical coordinates.\r\n\tpointToLatLng: function (point, zoom) {\r\n\t\tvar scale = this.scale(zoom),\r\n\t\t    untransformedPoint = this.transformation.untransform(point, scale);\r\n\r\n\t\treturn this.projection.unproject(untransformedPoint);\r\n\t},\r\n\r\n\t// @method project(latlng: LatLng): Point\r\n\t// Projects geographical coordinates into coordinates in units accepted for\r\n\t// this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).\r\n\tproject: function (latlng) {\r\n\t\treturn this.projection.project(latlng);\r\n\t},\r\n\r\n\t// @method unproject(point: Point): LatLng\r\n\t// Given a projected coordinate returns the corresponding LatLng.\r\n\t// The inverse of `project`.\r\n\tunproject: function (point) {\r\n\t\treturn this.projection.unproject(point);\r\n\t},\r\n\r\n\t// @method scale(zoom: Number): Number\r\n\t// Returns the scale used when transforming projected coordinates into\r\n\t// pixel coordinates for a particular zoom. For example, it returns\r\n\t// `256 * 2^zoom` for Mercator-based CRS.\r\n\tscale: function (zoom) {\r\n\t\treturn 256 * Math.pow(2, zoom);\r\n\t},\r\n\r\n\t// @method zoom(scale: Number): Number\r\n\t// Inverse of `scale()`, returns the zoom level corresponding to a scale\r\n\t// factor of `scale`.\r\n\tzoom: function (scale) {\r\n\t\treturn Math.log(scale / 256) / Math.LN2;\r\n\t},\r\n\r\n\t// @method getProjectedBounds(zoom: Number): Bounds\r\n\t// Returns the projection's bounds scaled and transformed for the provided `zoom`.\r\n\tgetProjectedBounds: function (zoom) {\r\n\t\tif (this.infinite) { return null; }\r\n\r\n\t\tvar b = this.projection.bounds,\r\n\t\t    s = this.scale(zoom),\r\n\t\t    min = this.transformation.transform(b.min, s),\r\n\t\t    max = this.transformation.transform(b.max, s);\r\n\r\n\t\treturn new Bounds(min, max);\r\n\t},\r\n\r\n\t// @method distance(latlng1: LatLng, latlng2: LatLng): Number\r\n\t// Returns the distance between two geographical coordinates.\r\n\r\n\t// @property code: String\r\n\t// Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)\r\n\t//\r\n\t// @property wrapLng: Number[]\r\n\t// An array of two numbers defining whether the longitude (horizontal) coordinate\r\n\t// axis wraps around a given range and how. Defaults to `[-180, 180]` in most\r\n\t// geographical CRSs. If `undefined`, the longitude axis does not wrap around.\r\n\t//\r\n\t// @property wrapLat: Number[]\r\n\t// Like `wrapLng`, but for the latitude (vertical) axis.\r\n\r\n\t// wrapLng: [min, max],\r\n\t// wrapLat: [min, max],\r\n\r\n\t// @property infinite: Boolean\r\n\t// If true, the coordinate space will be unbounded (infinite in both axes)\r\n\tinfinite: false,\r\n\r\n\t// @method wrapLatLng(latlng: LatLng): LatLng\r\n\t// Returns a `LatLng` where lat and lng has been wrapped according to the\r\n\t// CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.\r\n\twrapLatLng: function (latlng) {\r\n\t\tvar lng = this.wrapLng ? Util.wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,\r\n\t\t    lat = this.wrapLat ? Util.wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,\r\n\t\t    alt = latlng.alt;\r\n\r\n\t\treturn new LatLng(lat, lng, alt);\r\n\t},\r\n\r\n\t// @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds\r\n\t// Returns a `LatLngBounds` with the same size as the given one, ensuring\r\n\t// that its center is within the CRS's bounds.\r\n\t// Only accepts actual `L.LatLngBounds` instances, not arrays.\r\n\twrapLatLngBounds: function (bounds) {\r\n\t\tvar center = bounds.getCenter(),\r\n\t\t    newCenter = this.wrapLatLng(center),\r\n\t\t    latShift = center.lat - newCenter.lat,\r\n\t\t    lngShift = center.lng - newCenter.lng;\r\n\r\n\t\tif (latShift === 0 && lngShift === 0) {\r\n\t\t\treturn bounds;\r\n\t\t}\r\n\r\n\t\tvar sw = bounds.getSouthWest(),\r\n\t\t    ne = bounds.getNorthEast(),\r\n\t\t    newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),\r\n\t\t    newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);\r\n\r\n\t\treturn new LatLngBounds(newSw, newNe);\r\n\t}\r\n};\r\n","import {CRS} from './CRS';\nimport * as Util from '../../core/Util';\n\n/*\n * @namespace CRS\n * @crs L.CRS.Earth\n *\n * Serves as the base for CRS that are global such that they cover the earth.\n * Can only be used as the base for other CRS and cannot be used directly,\n * since it does not have a `code`, `projection` or `transformation`. `distance()` returns\n * meters.\n */\n\nexport var Earth = Util.extend({}, CRS, {\n\twrapLng: [-180, 180],\n\n\t// Mean Earth Radius, as recommended for use by\n\t// the International Union of Geodesy and Geophysics,\n\t// see https://rosettacode.org/wiki/Haversine_formula\n\tR: 6371000,\n\n\t// distance between two geographical points using spherical law of cosines approximation\n\tdistance: function (latlng1, latlng2) {\n\t\tvar rad = Math.PI / 180,\n\t\t    lat1 = latlng1.lat * rad,\n\t\t    lat2 = latlng2.lat * rad,\n\t\t    sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),\n\t\t    sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),\n\t\t    a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,\n\t\t    c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\t\treturn this.R * c;\n\t}\n});\n","import {LatLng} from '../LatLng';\r\nimport {Bounds} from '../../geometry/Bounds';\r\nimport {Point} from '../../geometry/Point';\r\n\r\n/*\r\n * @namespace Projection\r\n * @projection L.Projection.SphericalMercator\r\n *\r\n * Spherical Mercator projection — the most common projection for online maps,\r\n * used by almost all free and commercial tile providers. Assumes that Earth is\r\n * a sphere. Used by the `EPSG:3857` CRS.\r\n */\r\n\r\nvar earthRadius = 6378137;\r\n\r\nexport var SphericalMercator = {\r\n\r\n\tR: earthRadius,\r\n\tMAX_LATITUDE: 85.0511287798,\r\n\r\n\tproject: function (latlng) {\r\n\t\tvar d = Math.PI / 180,\r\n\t\t    max = this.MAX_LATITUDE,\r\n\t\t    lat = Math.max(Math.min(max, latlng.lat), -max),\r\n\t\t    sin = Math.sin(lat * d);\r\n\r\n\t\treturn new Point(\r\n\t\t\tthis.R * latlng.lng * d,\r\n\t\t\tthis.R * Math.log((1 + sin) / (1 - sin)) / 2);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\tvar d = 180 / Math.PI;\r\n\r\n\t\treturn new LatLng(\r\n\t\t\t(2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,\r\n\t\t\tpoint.x * d / this.R);\r\n\t},\r\n\r\n\tbounds: (function () {\r\n\t\tvar d = earthRadius * Math.PI;\r\n\t\treturn new Bounds([-d, -d], [d, d]);\r\n\t})()\r\n};\r\n","import {Point} from './Point';\r\nimport * as Util from '../core/Util';\r\n\r\n/*\r\n * @class Transformation\r\n * @aka L.Transformation\r\n *\r\n * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`\r\n * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing\r\n * the reverse. Used by Leaflet in its projections code.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var transformation = L.transformation(2, 5, -1, 10),\r\n * \tp = L.point(1, 2),\r\n * \tp2 = transformation.transform(p), //  L.point(7, 8)\r\n * \tp3 = transformation.untransform(p2); //  L.point(1, 2)\r\n * ```\r\n */\r\n\r\n\r\n// factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)\r\n// Creates a `Transformation` object with the given coefficients.\r\nexport function Transformation(a, b, c, d) {\r\n\tif (Util.isArray(a)) {\r\n\t\t// use array properties\r\n\t\tthis._a = a[0];\r\n\t\tthis._b = a[1];\r\n\t\tthis._c = a[2];\r\n\t\tthis._d = a[3];\r\n\t\treturn;\r\n\t}\r\n\tthis._a = a;\r\n\tthis._b = b;\r\n\tthis._c = c;\r\n\tthis._d = d;\r\n}\r\n\r\nTransformation.prototype = {\r\n\t// @method transform(point: Point, scale?: Number): Point\r\n\t// Returns a transformed point, optionally multiplied by the given scale.\r\n\t// Only accepts actual `L.Point` instances, not arrays.\r\n\ttransform: function (point, scale) { // (Point, Number) -> Point\r\n\t\treturn this._transform(point.clone(), scale);\r\n\t},\r\n\r\n\t// destructive transform (faster)\r\n\t_transform: function (point, scale) {\r\n\t\tscale = scale || 1;\r\n\t\tpoint.x = scale * (this._a * point.x + this._b);\r\n\t\tpoint.y = scale * (this._c * point.y + this._d);\r\n\t\treturn point;\r\n\t},\r\n\r\n\t// @method untransform(point: Point, scale?: Number): Point\r\n\t// Returns the reverse transformation of the given point, optionally divided\r\n\t// by the given scale. Only accepts actual `L.Point` instances, not arrays.\r\n\tuntransform: function (point, scale) {\r\n\t\tscale = scale || 1;\r\n\t\treturn new Point(\r\n\t\t        (point.x / scale - this._b) / this._a,\r\n\t\t        (point.y / scale - this._d) / this._c);\r\n\t}\r\n};\r\n\r\n// factory L.transformation(a: Number, b: Number, c: Number, d: Number)\r\n\r\n// @factory L.transformation(a: Number, b: Number, c: Number, d: Number)\r\n// Instantiates a Transformation object with the given coefficients.\r\n\r\n// @alternative\r\n// @factory L.transformation(coefficients: Array): Transformation\r\n// Expects an coefficients array of the form\r\n// `[a: Number, b: Number, c: Number, d: Number]`.\r\n\r\nexport function toTransformation(a, b, c, d) {\r\n\treturn new Transformation(a, b, c, d);\r\n}\r\n","import {Earth} from './CRS.Earth';\r\nimport {SphericalMercator} from '../projection/Projection.SphericalMercator';\r\nimport {toTransformation} from '../../geometry/Transformation';\r\nimport * as Util from '../../core/Util';\r\n\r\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG3857\r\n *\r\n * The most common CRS for online maps, used by almost all free and commercial\r\n * tile providers. Uses Spherical Mercator projection. Set in by default in\r\n * Map's `crs` option.\r\n */\r\n\r\nexport var EPSG3857 = Util.extend({}, Earth, {\r\n\tcode: 'EPSG:3857',\r\n\tprojection: SphericalMercator,\r\n\r\n\ttransformation: (function () {\r\n\t\tvar scale = 0.5 / (Math.PI * SphericalMercator.R);\r\n\t\treturn toTransformation(scale, 0.5, -scale, 0.5);\r\n\t}())\r\n});\r\n\r\nexport var EPSG900913 = Util.extend({}, EPSG3857, {\r\n\tcode: 'EPSG:900913'\r\n});\r\n","import Browser from '../../core/Browser';\n\n// @namespace SVG; @section\n// There are several static functions which can be called without instantiating L.SVG:\n\n// @function create(name: String): SVGElement\n// Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),\n// corresponding to the class name passed. For example, using 'line' will return\n// an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).\nexport function svgCreate(name) {\n\treturn document.createElementNS('http://www.w3.org/2000/svg', name);\n}\n\n// @function pointsToPath(rings: Point[], closed: Boolean): String\n// Generates a SVG path string for multiple rings, with each ring turning\n// into \"M..L..L..\" instructions\nexport function pointsToPath(rings, closed) {\n\tvar str = '',\n\ti, j, len, len2, points, p;\n\n\tfor (i = 0, len = rings.length; i < len; i++) {\n\t\tpoints = rings[i];\n\n\t\tfor (j = 0, len2 = points.length; j < len2; j++) {\n\t\t\tp = points[j];\n\t\t\tstr += (j ? 'L' : 'M') + p.x + ' ' + p.y;\n\t\t}\n\n\t\t// closes the ring for polygons; \"x\" is VML syntax\n\t\tstr += closed ? (Browser.svg ? 'z' : 'x') : '';\n\t}\n\n\t// SVG complains about empty path strings\n\treturn str || 'M0 0';\n}\n\n\n\n\n","import * as Util from './Util';\r\nimport {svgCreate} from '../layer/vector/SVG.Util';\r\n\r\n/*\r\n * @namespace Browser\r\n * @aka L.Browser\r\n *\r\n * A namespace with static properties for browser/feature detection used by Leaflet internally.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * if (L.Browser.ielt9) {\r\n *   alert('Upgrade your browser, dude!');\r\n * }\r\n * ```\r\n */\r\n\r\nvar style = document.documentElement.style;\r\n\r\n// @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).\r\nvar ie = 'ActiveXObject' in window;\r\n\r\n// @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.\r\nvar ielt9 = ie && !document.addEventListener;\r\n\r\n// @property edge: Boolean; `true` for the Edge web browser.\r\nvar edge = 'msLaunchUri' in navigator && !('documentMode' in document);\r\n\r\n// @property webkit: Boolean;\r\n// `true` for webkit-based browsers like Chrome and Safari (including mobile versions).\r\nvar webkit = userAgentContains('webkit');\r\n\r\n// @property android: Boolean\r\n// **Deprecated.** `true` for any browser running on an Android platform.\r\nvar android = userAgentContains('android');\r\n\r\n// @property android23: Boolean; **Deprecated.** `true` for browsers running on Android 2 or Android 3.\r\nvar android23 = userAgentContains('android 2') || userAgentContains('android 3');\r\n\r\n/* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */\r\nvar webkitVer = parseInt(/WebKit\\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit\r\n// @property androidStock: Boolean; **Deprecated.** `true` for the Android stock browser (i.e. not Chrome)\r\nvar androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);\r\n\r\n// @property opera: Boolean; `true` for the Opera browser\r\nvar opera = !!window.opera;\r\n\r\n// @property chrome: Boolean; `true` for the Chrome browser.\r\nvar chrome = !edge && userAgentContains('chrome');\r\n\r\n// @property gecko: Boolean; `true` for gecko-based browsers like Firefox.\r\nvar gecko = userAgentContains('gecko') && !webkit && !opera && !ie;\r\n\r\n// @property safari: Boolean; `true` for the Safari browser.\r\nvar safari = !chrome && userAgentContains('safari');\r\n\r\nvar phantom = userAgentContains('phantom');\r\n\r\n// @property opera12: Boolean\r\n// `true` for the Opera browser supporting CSS transforms (version 12 or later).\r\nvar opera12 = 'OTransition' in style;\r\n\r\n// @property win: Boolean; `true` when the browser is running in a Windows platform\r\nvar win = navigator.platform.indexOf('Win') === 0;\r\n\r\n// @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.\r\nvar ie3d = ie && ('transition' in style);\r\n\r\n// @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.\r\nvar webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;\r\n\r\n// @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.\r\nvar gecko3d = 'MozPerspective' in style;\r\n\r\n// @property any3d: Boolean\r\n// `true` for all browsers supporting CSS transforms.\r\nvar any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;\r\n\r\n// @property mobile: Boolean; `true` for all browsers running in a mobile device.\r\nvar mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');\r\n\r\n// @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.\r\nvar mobileWebkit = mobile && webkit;\r\n\r\n// @property mobileWebkit3d: Boolean\r\n// `true` for all webkit-based browsers in a mobile device supporting CSS transforms.\r\nvar mobileWebkit3d = mobile && webkit3d;\r\n\r\n// @property msPointer: Boolean\r\n// `true` for browsers implementing the Microsoft touch events model (notably IE10).\r\nvar msPointer = !window.PointerEvent && window.MSPointerEvent;\r\n\r\n// @property pointer: Boolean\r\n// `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).\r\nvar pointer = !!(window.PointerEvent || msPointer);\r\n\r\n// @property touchNative: Boolean\r\n// `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).\r\n// **This does not necessarily mean** that the browser is running in a computer with\r\n// a touchscreen, it only means that the browser is capable of understanding\r\n// touch events.\r\nvar touchNative = 'ontouchstart' in window || !!window.TouchEvent;\r\n\r\n// @property touch: Boolean\r\n// `true` for all browsers supporting either [touch](#browser-touch) or [pointer](#browser-pointer) events.\r\n// Note: pointer events will be preferred (if available), and processed for all `touch*` listeners.\r\nvar touch = !window.L_NO_TOUCH && (touchNative || pointer);\r\n\r\n// @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.\r\nvar mobileOpera = mobile && opera;\r\n\r\n// @property mobileGecko: Boolean\r\n// `true` for gecko-based browsers running in a mobile device.\r\nvar mobileGecko = mobile && gecko;\r\n\r\n// @property retina: Boolean\r\n// `true` for browsers on a high-resolution \"retina\" screen or on any screen when browser's display zoom is more than 100%.\r\nvar retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;\r\n\r\n// @property passiveEvents: Boolean\r\n// `true` for browsers that support passive events.\r\nvar passiveEvents = (function () {\r\n\tvar supportsPassiveOption = false;\r\n\ttry {\r\n\t\tvar opts = Object.defineProperty({}, 'passive', {\r\n\t\t\tget: function () { // eslint-disable-line getter-return\r\n\t\t\t\tsupportsPassiveOption = true;\r\n\t\t\t}\r\n\t\t});\r\n\t\twindow.addEventListener('testPassiveEventSupport', Util.falseFn, opts);\r\n\t\twindow.removeEventListener('testPassiveEventSupport', Util.falseFn, opts);\r\n\t} catch (e) {\r\n\t\t// Errors can safely be ignored since this is only a browser support test.\r\n\t}\r\n\treturn supportsPassiveOption;\r\n}());\r\n\r\n// @property canvas: Boolean\r\n// `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).\r\nvar canvas = (function () {\r\n\treturn !!document.createElement('canvas').getContext;\r\n}());\r\n\r\n// @property svg: Boolean\r\n// `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).\r\nvar svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);\r\n\r\nvar inlineSvg = !!svg && (function () {\r\n\tvar div = document.createElement('div');\r\n\tdiv.innerHTML = '<svg/>';\r\n\treturn (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg';\r\n})();\r\n\r\n// @property vml: Boolean\r\n// `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).\r\nvar vml = !svg && (function () {\r\n\ttry {\r\n\t\tvar div = document.createElement('div');\r\n\t\tdiv.innerHTML = '<v:shape adj=\"1\"/>';\r\n\r\n\t\tvar shape = div.firstChild;\r\n\t\tshape.style.behavior = 'url(#default#VML)';\r\n\r\n\t\treturn shape && (typeof shape.adj === 'object');\r\n\r\n\t} catch (e) {\r\n\t\treturn false;\r\n\t}\r\n}());\r\n\r\n\r\n// @property mac: Boolean; `true` when the browser is running in a Mac platform\r\nvar mac = navigator.platform.indexOf('Mac') === 0;\r\n\r\n// @property mac: Boolean; `true` when the browser is running in a Linux platform\r\nvar linux = navigator.platform.indexOf('Linux') === 0;\r\n\r\nfunction userAgentContains(str) {\r\n\treturn navigator.userAgent.toLowerCase().indexOf(str) >= 0;\r\n}\r\n\r\n\r\nexport default {\r\n\tie: ie,\r\n\tielt9: ielt9,\r\n\tedge: edge,\r\n\twebkit: webkit,\r\n\tandroid: android,\r\n\tandroid23: android23,\r\n\tandroidStock: androidStock,\r\n\topera: opera,\r\n\tchrome: chrome,\r\n\tgecko: gecko,\r\n\tsafari: safari,\r\n\tphantom: phantom,\r\n\topera12: opera12,\r\n\twin: win,\r\n\tie3d: ie3d,\r\n\twebkit3d: webkit3d,\r\n\tgecko3d: gecko3d,\r\n\tany3d: any3d,\r\n\tmobile: mobile,\r\n\tmobileWebkit: mobileWebkit,\r\n\tmobileWebkit3d: mobileWebkit3d,\r\n\tmsPointer: msPointer,\r\n\tpointer: pointer,\r\n\ttouch: touch,\r\n\ttouchNative: touchNative,\r\n\tmobileOpera: mobileOpera,\r\n\tmobileGecko: mobileGecko,\r\n\tretina: retina,\r\n\tpassiveEvents: passiveEvents,\r\n\tcanvas: canvas,\r\n\tsvg: svg,\r\n\tvml: vml,\r\n\tinlineSvg: inlineSvg,\r\n\tmac: mac,\r\n\tlinux: linux\r\n};\r\n","import * as DomEvent from './DomEvent';\nimport Browser from '../core/Browser';\nimport {falseFn} from '../core/Util';\n\n/*\n * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.\n */\n\nvar POINTER_DOWN =   Browser.msPointer ? 'MSPointerDown'   : 'pointerdown';\nvar POINTER_MOVE =   Browser.msPointer ? 'MSPointerMove'   : 'pointermove';\nvar POINTER_UP =     Browser.msPointer ? 'MSPointerUp'     : 'pointerup';\nvar POINTER_CANCEL = Browser.msPointer ? 'MSPointerCancel' : 'pointercancel';\nvar pEvent = {\n\ttouchstart  : POINTER_DOWN,\n\ttouchmove   : POINTER_MOVE,\n\ttouchend    : POINTER_UP,\n\ttouchcancel : POINTER_CANCEL\n};\nvar handle = {\n\ttouchstart  : _onPointerStart,\n\ttouchmove   : _handlePointer,\n\ttouchend    : _handlePointer,\n\ttouchcancel : _handlePointer\n};\nvar _pointers = {};\nvar _pointerDocListener = false;\n\n// Provides a touch events wrapper for (ms)pointer events.\n// ref https://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890\n\nexport function addPointerListener(obj, type, handler) {\n\tif (type === 'touchstart') {\n\t\t_addPointerDocListener();\n\t}\n\tif (!handle[type]) {\n\t\tconsole.warn('wrong event specified:', type);\n\t\treturn falseFn;\n\t}\n\thandler = handle[type].bind(this, handler);\n\tobj.addEventListener(pEvent[type], handler, false);\n\treturn handler;\n}\n\nexport function removePointerListener(obj, type, handler) {\n\tif (!pEvent[type]) {\n\t\tconsole.warn('wrong event specified:', type);\n\t\treturn;\n\t}\n\tobj.removeEventListener(pEvent[type], handler, false);\n}\n\nfunction _globalPointerDown(e) {\n\t_pointers[e.pointerId] = e;\n}\n\nfunction _globalPointerMove(e) {\n\tif (_pointers[e.pointerId]) {\n\t\t_pointers[e.pointerId] = e;\n\t}\n}\n\nfunction _globalPointerUp(e) {\n\tdelete _pointers[e.pointerId];\n}\n\nfunction _addPointerDocListener() {\n\t// need to keep track of what pointers and how many are active to provide e.touches emulation\n\tif (!_pointerDocListener) {\n\t\t// we listen document as any drags that end by moving the touch off the screen get fired there\n\t\tdocument.addEventListener(POINTER_DOWN, _globalPointerDown, true);\n\t\tdocument.addEventListener(POINTER_MOVE, _globalPointerMove, true);\n\t\tdocument.addEventListener(POINTER_UP, _globalPointerUp, true);\n\t\tdocument.addEventListener(POINTER_CANCEL, _globalPointerUp, true);\n\n\t\t_pointerDocListener = true;\n\t}\n}\n\nfunction _handlePointer(handler, e) {\n\tif (e.pointerType === (e.MSPOINTER_TYPE_MOUSE || 'mouse')) { return; }\n\n\te.touches = [];\n\tfor (var i in _pointers) {\n\t\te.touches.push(_pointers[i]);\n\t}\n\te.changedTouches = [e];\n\n\thandler(e);\n}\n\nfunction _onPointerStart(handler, e) {\n\t// IE10 specific: MsTouch needs preventDefault. See #2000\n\tif (e.MSPOINTER_TYPE_TOUCH && e.pointerType === e.MSPOINTER_TYPE_TOUCH) {\n\t\tDomEvent.preventDefault(e);\n\t}\n\t_handlePointer(handler, e);\n}\n","import * as DomEvent from './DomEvent';\r\n\r\n/*\r\n * Extends the event handling code with double tap support for mobile browsers.\r\n *\r\n * Note: currently most browsers fire native dblclick, with only a few exceptions\r\n * (see https://github.com/Leaflet/Leaflet/issues/7012#issuecomment-595087386)\r\n */\r\n\r\nfunction makeDblclick(event) {\r\n\t// in modern browsers `type` cannot be just overridden:\r\n\t// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only\r\n\tvar newEvent = {},\r\n\t    prop, i;\r\n\tfor (i in event) {\r\n\t\tprop = event[i];\r\n\t\tnewEvent[i] = prop && prop.bind ? prop.bind(event) : prop;\r\n\t}\r\n\tevent = newEvent;\r\n\tnewEvent.type = 'dblclick';\r\n\tnewEvent.detail = 2;\r\n\tnewEvent.isTrusted = false;\r\n\tnewEvent._simulated = true; // for debug purposes\r\n\treturn newEvent;\r\n}\r\n\r\nvar delay = 200;\r\nexport function addDoubleTapListener(obj, handler) {\r\n\t// Most browsers handle double tap natively\r\n\tobj.addEventListener('dblclick', handler);\r\n\r\n\t// On some platforms the browser doesn't fire native dblclicks for touch events.\r\n\t// It seems that in all such cases `detail` property of `click` event is always `1`.\r\n\t// So here we rely on that fact to avoid excessive 'dblclick' simulation when not needed.\r\n\tvar last = 0,\r\n\t    detail;\r\n\tfunction simDblclick(e) {\r\n\t\tif (e.detail !== 1) {\r\n\t\t\tdetail = e.detail; // keep in sync to avoid false dblclick in some cases\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (e.pointerType === 'mouse' ||\r\n\t\t\t(e.sourceCapabilities && !e.sourceCapabilities.firesTouchEvents)) {\r\n\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// When clicking on an <input>, the browser generates a click on its\r\n\t\t// <label> (and vice versa) triggering two clicks in quick succession.\r\n\t\t// This ignores clicks on elements which are a label with a 'for'\r\n\t\t// attribute (or children of such a label), but not children of\r\n\t\t// a <input>.\r\n\t\tvar path = DomEvent.getPropagationPath(e);\r\n\t\tif (path.some(function (el) {\r\n\t\t\treturn el instanceof HTMLLabelElement && el.attributes.for;\r\n\t\t}) &&\r\n\t\t\t!path.some(function (el) {\r\n\t\t\t\treturn (\r\n\t\t\t\t\tel instanceof HTMLInputElement ||\r\n\t\t\t\t\tel instanceof HTMLSelectElement\r\n\t\t\t\t);\r\n\t\t\t})\r\n\t\t) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar now = Date.now();\r\n\t\tif (now - last <= delay) {\r\n\t\t\tdetail++;\r\n\t\t\tif (detail === 2) {\r\n\t\t\t\thandler(makeDblclick(e));\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tdetail = 1;\r\n\t\t}\r\n\t\tlast = now;\r\n\t}\r\n\r\n\tobj.addEventListener('click', simDblclick);\r\n\r\n\treturn {\r\n\t\tdblclick: handler,\r\n\t\tsimDblclick: simDblclick\r\n\t};\r\n}\r\n\r\nexport function removeDoubleTapListener(obj, handlers) {\r\n\tobj.removeEventListener('dblclick', handlers.dblclick);\r\n\tobj.removeEventListener('click', handlers.simDblclick);\r\n}\r\n","import * as DomEvent from './DomEvent';\r\nimport * as Util from '../core/Util';\r\nimport {Point} from '../geometry/Point';\r\nimport Browser from '../core/Browser';\r\n\r\n/*\r\n * @namespace DomUtil\r\n *\r\n * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)\r\n * tree, used by Leaflet internally.\r\n *\r\n * Most functions expecting or returning a `HTMLElement` also work for\r\n * SVG elements. The only difference is that classes refer to CSS classes\r\n * in HTML and SVG classes in SVG.\r\n */\r\n\r\n\r\n// @property TRANSFORM: String\r\n// Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).\r\nexport var TRANSFORM = testProp(\r\n\t['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);\r\n\r\n// webkitTransition comes first because some browser versions that drop vendor prefix don't do\r\n// the same for the transitionend event, in particular the Android 4.1 stock browser\r\n\r\n// @property TRANSITION: String\r\n// Vendor-prefixed transition style name.\r\nexport var TRANSITION = testProp(\r\n\t['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);\r\n\r\n// @property TRANSITION_END: String\r\n// Vendor-prefixed transitionend event name.\r\nexport var TRANSITION_END =\r\n\tTRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';\r\n\r\n\r\n// @function get(id: String|HTMLElement): HTMLElement\r\n// Returns an element given its DOM id, or returns the element itself\r\n// if it was passed directly.\r\nexport function get(id) {\r\n\treturn typeof id === 'string' ? document.getElementById(id) : id;\r\n}\r\n\r\n// @function getStyle(el: HTMLElement, styleAttrib: String): String\r\n// Returns the value for a certain style attribute on an element,\r\n// including computed values or values set through CSS.\r\nexport function getStyle(el, style) {\r\n\tvar value = el.style[style] || (el.currentStyle && el.currentStyle[style]);\r\n\r\n\tif ((!value || value === 'auto') && document.defaultView) {\r\n\t\tvar css = document.defaultView.getComputedStyle(el, null);\r\n\t\tvalue = css ? css[style] : null;\r\n\t}\r\n\treturn value === 'auto' ? null : value;\r\n}\r\n\r\n// @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement\r\n// Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.\r\nexport function create(tagName, className, container) {\r\n\tvar el = document.createElement(tagName);\r\n\tel.className = className || '';\r\n\r\n\tif (container) {\r\n\t\tcontainer.appendChild(el);\r\n\t}\r\n\treturn el;\r\n}\r\n\r\n// @function remove(el: HTMLElement)\r\n// Removes `el` from its parent element\r\nexport function remove(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent) {\r\n\t\tparent.removeChild(el);\r\n\t}\r\n}\r\n\r\n// @function empty(el: HTMLElement)\r\n// Removes all of `el`'s children elements from `el`\r\nexport function empty(el) {\r\n\twhile (el.firstChild) {\r\n\t\tel.removeChild(el.firstChild);\r\n\t}\r\n}\r\n\r\n// @function toFront(el: HTMLElement)\r\n// Makes `el` the last child of its parent, so it renders in front of the other children.\r\nexport function toFront(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent && parent.lastChild !== el) {\r\n\t\tparent.appendChild(el);\r\n\t}\r\n}\r\n\r\n// @function toBack(el: HTMLElement)\r\n// Makes `el` the first child of its parent, so it renders behind the other children.\r\nexport function toBack(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent && parent.firstChild !== el) {\r\n\t\tparent.insertBefore(el, parent.firstChild);\r\n\t}\r\n}\r\n\r\n// @function hasClass(el: HTMLElement, name: String): Boolean\r\n// Returns `true` if the element's class attribute contains `name`.\r\nexport function hasClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\treturn el.classList.contains(name);\r\n\t}\r\n\tvar className = getClass(el);\r\n\treturn className.length > 0 && new RegExp('(^|\\\\s)' + name + '(\\\\s|$)').test(className);\r\n}\r\n\r\n// @function addClass(el: HTMLElement, name: String)\r\n// Adds `name` to the element's class attribute.\r\nexport function addClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\tvar classes = Util.splitWords(name);\r\n\t\tfor (var i = 0, len = classes.length; i < len; i++) {\r\n\t\t\tel.classList.add(classes[i]);\r\n\t\t}\r\n\t} else if (!hasClass(el, name)) {\r\n\t\tvar className = getClass(el);\r\n\t\tsetClass(el, (className ? className + ' ' : '') + name);\r\n\t}\r\n}\r\n\r\n// @function removeClass(el: HTMLElement, name: String)\r\n// Removes `name` from the element's class attribute.\r\nexport function removeClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\tel.classList.remove(name);\r\n\t} else {\r\n\t\tsetClass(el, Util.trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));\r\n\t}\r\n}\r\n\r\n// @function setClass(el: HTMLElement, name: String)\r\n// Sets the element's class.\r\nexport function setClass(el, name) {\r\n\tif (el.className.baseVal === undefined) {\r\n\t\tel.className = name;\r\n\t} else {\r\n\t\t// in case of SVG element\r\n\t\tel.className.baseVal = name;\r\n\t}\r\n}\r\n\r\n// @function getClass(el: HTMLElement): String\r\n// Returns the element's class.\r\nexport function getClass(el) {\r\n\t// Check if the element is an SVGElementInstance and use the correspondingElement instead\r\n\t// (Required for linked SVG elements in IE11.)\r\n\tif (el.correspondingElement) {\r\n\t\tel = el.correspondingElement;\r\n\t}\r\n\treturn el.className.baseVal === undefined ? el.className : el.className.baseVal;\r\n}\r\n\r\n// @function setOpacity(el: HTMLElement, opacity: Number)\r\n// Set the opacity of an element (including old IE support).\r\n// `opacity` must be a number from `0` to `1`.\r\nexport function setOpacity(el, value) {\r\n\tif ('opacity' in el.style) {\r\n\t\tel.style.opacity = value;\r\n\t} else if ('filter' in el.style) {\r\n\t\t_setOpacityIE(el, value);\r\n\t}\r\n}\r\n\r\nfunction _setOpacityIE(el, value) {\r\n\tvar filter = false,\r\n\t    filterName = 'DXImageTransform.Microsoft.Alpha';\r\n\r\n\t// filters collection throws an error if we try to retrieve a filter that doesn't exist\r\n\ttry {\r\n\t\tfilter = el.filters.item(filterName);\r\n\t} catch (e) {\r\n\t\t// don't set opacity to 1 if we haven't already set an opacity,\r\n\t\t// it isn't needed and breaks transparent pngs.\r\n\t\tif (value === 1) { return; }\r\n\t}\r\n\r\n\tvalue = Math.round(value * 100);\r\n\r\n\tif (filter) {\r\n\t\tfilter.Enabled = (value !== 100);\r\n\t\tfilter.Opacity = value;\r\n\t} else {\r\n\t\tel.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';\r\n\t}\r\n}\r\n\r\n// @function testProp(props: String[]): String|false\r\n// Goes through the array of style names and returns the first name\r\n// that is a valid style name for an element. If no such name is found,\r\n// it returns false. Useful for vendor-prefixed styles like `transform`.\r\nexport function testProp(props) {\r\n\tvar style = document.documentElement.style;\r\n\r\n\tfor (var i = 0; i < props.length; i++) {\r\n\t\tif (props[i] in style) {\r\n\t\t\treturn props[i];\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n// @function setTransform(el: HTMLElement, offset: Point, scale?: Number)\r\n// Resets the 3D CSS transform of `el` so it is translated by `offset` pixels\r\n// and optionally scaled by `scale`. Does not have an effect if the\r\n// browser doesn't support 3D CSS transforms.\r\nexport function setTransform(el, offset, scale) {\r\n\tvar pos = offset || new Point(0, 0);\r\n\r\n\tel.style[TRANSFORM] =\r\n\t\t(Browser.ie3d ?\r\n\t\t\t'translate(' + pos.x + 'px,' + pos.y + 'px)' :\r\n\t\t\t'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +\r\n\t\t(scale ? ' scale(' + scale + ')' : '');\r\n}\r\n\r\n// @function setPosition(el: HTMLElement, position: Point)\r\n// Sets the position of `el` to coordinates specified by `position`,\r\n// using CSS translate or top/left positioning depending on the browser\r\n// (used by Leaflet internally to position its layers).\r\nexport function setPosition(el, point) {\r\n\r\n\t/*eslint-disable */\r\n\tel._leaflet_pos = point;\r\n\t/* eslint-enable */\r\n\r\n\tif (Browser.any3d) {\r\n\t\tsetTransform(el, point);\r\n\t} else {\r\n\t\tel.style.left = point.x + 'px';\r\n\t\tel.style.top = point.y + 'px';\r\n\t}\r\n}\r\n\r\n// @function getPosition(el: HTMLElement): Point\r\n// Returns the coordinates of an element previously positioned with setPosition.\r\nexport function getPosition(el) {\r\n\t// this method is only used for elements previously positioned using setPosition,\r\n\t// so it's safe to cache the position for performance\r\n\r\n\treturn el._leaflet_pos || new Point(0, 0);\r\n}\r\n\r\n// @function disableTextSelection()\r\n// Prevents the user from generating `selectstart` DOM events, usually generated\r\n// when the user drags the mouse through a page with text. Used internally\r\n// by Leaflet to override the behaviour of any click-and-drag interaction on\r\n// the map. Affects drag interactions on the whole document.\r\n\r\n// @function enableTextSelection()\r\n// Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).\r\nexport var disableTextSelection;\r\nexport var enableTextSelection;\r\nvar _userSelect;\r\nif ('onselectstart' in document) {\r\n\tdisableTextSelection = function () {\r\n\t\tDomEvent.on(window, 'selectstart', DomEvent.preventDefault);\r\n\t};\r\n\tenableTextSelection = function () {\r\n\t\tDomEvent.off(window, 'selectstart', DomEvent.preventDefault);\r\n\t};\r\n} else {\r\n\tvar userSelectProperty = testProp(\r\n\t\t['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);\r\n\r\n\tdisableTextSelection = function () {\r\n\t\tif (userSelectProperty) {\r\n\t\t\tvar style = document.documentElement.style;\r\n\t\t\t_userSelect = style[userSelectProperty];\r\n\t\t\tstyle[userSelectProperty] = 'none';\r\n\t\t}\r\n\t};\r\n\tenableTextSelection = function () {\r\n\t\tif (userSelectProperty) {\r\n\t\t\tdocument.documentElement.style[userSelectProperty] = _userSelect;\r\n\t\t\t_userSelect = undefined;\r\n\t\t}\r\n\t};\r\n}\r\n\r\n// @function disableImageDrag()\r\n// As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but\r\n// for `dragstart` DOM events, usually generated when the user drags an image.\r\nexport function disableImageDrag() {\r\n\tDomEvent.on(window, 'dragstart', DomEvent.preventDefault);\r\n}\r\n\r\n// @function enableImageDrag()\r\n// Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).\r\nexport function enableImageDrag() {\r\n\tDomEvent.off(window, 'dragstart', DomEvent.preventDefault);\r\n}\r\n\r\nvar _outlineElement, _outlineStyle;\r\n// @function preventOutline(el: HTMLElement)\r\n// Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)\r\n// of the element `el` invisible. Used internally by Leaflet to prevent\r\n// focusable elements from displaying an outline when the user performs a\r\n// drag interaction on them.\r\nexport function preventOutline(element) {\r\n\twhile (element.tabIndex === -1) {\r\n\t\telement = element.parentNode;\r\n\t}\r\n\tif (!element.style) { return; }\r\n\trestoreOutline();\r\n\t_outlineElement = element;\r\n\t_outlineStyle = element.style.outlineStyle;\r\n\telement.style.outlineStyle = 'none';\r\n\tDomEvent.on(window, 'keydown', restoreOutline);\r\n}\r\n\r\n// @function restoreOutline()\r\n// Cancels the effects of a previous [`L.DomUtil.preventOutline`]().\r\nexport function restoreOutline() {\r\n\tif (!_outlineElement) { return; }\r\n\t_outlineElement.style.outlineStyle = _outlineStyle;\r\n\t_outlineElement = undefined;\r\n\t_outlineStyle = undefined;\r\n\tDomEvent.off(window, 'keydown', restoreOutline);\r\n}\r\n\r\n// @function getSizedParentNode(el: HTMLElement): HTMLElement\r\n// Finds the closest parent node which size (width and height) is not null.\r\nexport function getSizedParentNode(element) {\r\n\tdo {\r\n\t\telement = element.parentNode;\r\n\t} while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);\r\n\treturn element;\r\n}\r\n\r\n// @function getScale(el: HTMLElement): Object\r\n// Computes the CSS scale currently applied on the element.\r\n// Returns an object with `x` and `y` members as horizontal and vertical scales respectively,\r\n// and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).\r\nexport function getScale(element) {\r\n\tvar rect = element.getBoundingClientRect(); // Read-only in old browsers.\r\n\r\n\treturn {\r\n\t\tx: rect.width / element.offsetWidth || 1,\r\n\t\ty: rect.height / element.offsetHeight || 1,\r\n\t\tboundingClientRect: rect\r\n\t};\r\n}\r\n","import {Point} from '../geometry/Point';\r\nimport * as Util from '../core/Util';\r\nimport Browser from '../core/Browser';\r\nimport {addPointerListener, removePointerListener} from './DomEvent.Pointer';\r\nimport {addDoubleTapListener, removeDoubleTapListener} from './DomEvent.DoubleTap';\r\nimport {getScale} from './DomUtil';\r\n\r\n/*\r\n * @namespace DomEvent\r\n * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.\r\n */\r\n\r\n// Inspired by John Resig, Dean Edwards and YUI addEvent implementations.\r\n\r\n// @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this\r\n// Adds a listener function (`fn`) to a particular DOM event type of the\r\n// element `el`. You can optionally specify the context of the listener\r\n// (object the `this` keyword will point to). You can also pass several\r\n// space-separated types (e.g. `'click dblclick'`).\r\n\r\n// @alternative\r\n// @function on(el: HTMLElement, eventMap: Object, context?: Object): this\r\n// Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\nexport function on(obj, types, fn, context) {\r\n\r\n\tif (types && typeof types === 'object') {\r\n\t\tfor (var type in types) {\r\n\t\t\taddOne(obj, type, types[type], fn);\r\n\t\t}\r\n\t} else {\r\n\t\ttypes = Util.splitWords(types);\r\n\r\n\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\taddOne(obj, types[i], fn, context);\r\n\t\t}\r\n\t}\r\n\r\n\treturn this;\r\n}\r\n\r\nvar eventsKey = '_leaflet_events';\r\n\r\n// @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this\r\n// Removes a previously added listener function.\r\n// Note that if you passed a custom context to on, you must pass the same\r\n// context to `off` in order to remove the listener.\r\n\r\n// @alternative\r\n// @function off(el: HTMLElement, eventMap: Object, context?: Object): this\r\n// Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\n\r\n// @alternative\r\n// @function off(el: HTMLElement, types: String): this\r\n// Removes all previously added listeners of given types.\r\n\r\n// @alternative\r\n// @function off(el: HTMLElement): this\r\n// Removes all previously added listeners from given HTMLElement\r\nexport function off(obj, types, fn, context) {\r\n\r\n\tif (arguments.length === 1) {\r\n\t\tbatchRemove(obj);\r\n\t\tdelete obj[eventsKey];\r\n\r\n\t} else if (types && typeof types === 'object') {\r\n\t\tfor (var type in types) {\r\n\t\t\tremoveOne(obj, type, types[type], fn);\r\n\t\t}\r\n\r\n\t} else {\r\n\t\ttypes = Util.splitWords(types);\r\n\r\n\t\tif (arguments.length === 2) {\r\n\t\t\tbatchRemove(obj, function (type) {\r\n\t\t\t\treturn Util.indexOf(types, type) !== -1;\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tremoveOne(obj, types[i], fn, context);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn this;\r\n}\r\n\r\nfunction batchRemove(obj, filterFn) {\r\n\tfor (var id in obj[eventsKey]) {\r\n\t\tvar type = id.split(/\\d/)[0];\r\n\t\tif (!filterFn || filterFn(type)) {\r\n\t\t\tremoveOne(obj, type, null, null, id);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvar mouseSubst = {\r\n\tmouseenter: 'mouseover',\r\n\tmouseleave: 'mouseout',\r\n\twheel: !('onwheel' in window) && 'mousewheel'\r\n};\r\n\r\nfunction addOne(obj, type, fn, context) {\r\n\tvar id = type + Util.stamp(fn) + (context ? '_' + Util.stamp(context) : '');\r\n\r\n\tif (obj[eventsKey] && obj[eventsKey][id]) { return this; }\r\n\r\n\tvar handler = function (e) {\r\n\t\treturn fn.call(context || obj, e || window.event);\r\n\t};\r\n\r\n\tvar originalHandler = handler;\r\n\r\n\tif (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {\r\n\t\t// Needs DomEvent.Pointer.js\r\n\t\thandler = addPointerListener(obj, type, handler);\r\n\r\n\t} else if (Browser.touch && (type === 'dblclick')) {\r\n\t\thandler = addDoubleTapListener(obj, handler);\r\n\r\n\t} else if ('addEventListener' in obj) {\r\n\r\n\t\tif (type === 'touchstart' || type === 'touchmove' || type === 'wheel' ||  type === 'mousewheel') {\r\n\t\t\tobj.addEventListener(mouseSubst[type] || type, handler, Browser.passiveEvents ? {passive: false} : false);\r\n\r\n\t\t} else if (type === 'mouseenter' || type === 'mouseleave') {\r\n\t\t\thandler = function (e) {\r\n\t\t\t\te = e || window.event;\r\n\t\t\t\tif (isExternalTarget(obj, e)) {\r\n\t\t\t\t\toriginalHandler(e);\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\tobj.addEventListener(mouseSubst[type], handler, false);\r\n\r\n\t\t} else {\r\n\t\t\tobj.addEventListener(type, originalHandler, false);\r\n\t\t}\r\n\r\n\t} else {\r\n\t\tobj.attachEvent('on' + type, handler);\r\n\t}\r\n\r\n\tobj[eventsKey] = obj[eventsKey] || {};\r\n\tobj[eventsKey][id] = handler;\r\n}\r\n\r\nfunction removeOne(obj, type, fn, context, id) {\r\n\tid = id || type + Util.stamp(fn) + (context ? '_' + Util.stamp(context) : '');\r\n\tvar handler = obj[eventsKey] && obj[eventsKey][id];\r\n\r\n\tif (!handler) { return this; }\r\n\r\n\tif (!Browser.touchNative && Browser.pointer && type.indexOf('touch') === 0) {\r\n\t\tremovePointerListener(obj, type, handler);\r\n\r\n\t} else if (Browser.touch && (type === 'dblclick')) {\r\n\t\tremoveDoubleTapListener(obj, handler);\r\n\r\n\t} else if ('removeEventListener' in obj) {\r\n\r\n\t\tobj.removeEventListener(mouseSubst[type] || type, handler, false);\r\n\r\n\t} else {\r\n\t\tobj.detachEvent('on' + type, handler);\r\n\t}\r\n\r\n\tobj[eventsKey][id] = null;\r\n}\r\n\r\n// @function stopPropagation(ev: DOMEvent): this\r\n// Stop the given event from propagation to parent elements. Used inside the listener functions:\r\n// ```js\r\n// L.DomEvent.on(div, 'click', function (ev) {\r\n// \tL.DomEvent.stopPropagation(ev);\r\n// });\r\n// ```\r\nexport function stopPropagation(e) {\r\n\r\n\tif (e.stopPropagation) {\r\n\t\te.stopPropagation();\r\n\t} else if (e.originalEvent) {  // In case of Leaflet event.\r\n\t\te.originalEvent._stopped = true;\r\n\t} else {\r\n\t\te.cancelBubble = true;\r\n\t}\r\n\r\n\treturn this;\r\n}\r\n\r\n// @function disableScrollPropagation(el: HTMLElement): this\r\n// Adds `stopPropagation` to the element's `'wheel'` events (plus browser variants).\r\nexport function disableScrollPropagation(el) {\r\n\taddOne(el, 'wheel', stopPropagation);\r\n\treturn this;\r\n}\r\n\r\n// @function disableClickPropagation(el: HTMLElement): this\r\n// Adds `stopPropagation` to the element's `'click'`, `'dblclick'`, `'contextmenu'`,\r\n// `'mousedown'` and `'touchstart'` events (plus browser variants).\r\nexport function disableClickPropagation(el) {\r\n\ton(el, 'mousedown touchstart dblclick contextmenu', stopPropagation);\r\n\tel['_leaflet_disable_click'] = true;\r\n\treturn this;\r\n}\r\n\r\n// @function preventDefault(ev: DOMEvent): this\r\n// Prevents the default action of the DOM Event `ev` from happening (such as\r\n// following a link in the href of the a element, or doing a POST request\r\n// with page reload when a `<form>` is submitted).\r\n// Use it inside listener functions.\r\nexport function preventDefault(e) {\r\n\tif (e.preventDefault) {\r\n\t\te.preventDefault();\r\n\t} else {\r\n\t\te.returnValue = false;\r\n\t}\r\n\treturn this;\r\n}\r\n\r\n// @function stop(ev: DOMEvent): this\r\n// Does `stopPropagation` and `preventDefault` at the same time.\r\nexport function stop(e) {\r\n\tpreventDefault(e);\r\n\tstopPropagation(e);\r\n\treturn this;\r\n}\r\n\r\n// @function getPropagationPath(ev: DOMEvent): Array\r\n// Compatibility polyfill for [`Event.composedPath()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath).\r\n// Returns an array containing the `HTMLElement`s that the given DOM event\r\n// should propagate to (if not stopped).\r\nexport function getPropagationPath(ev) {\r\n\tif (ev.composedPath) {\r\n\t\treturn ev.composedPath();\r\n\t}\r\n\r\n\tvar path = [];\r\n\tvar el = ev.target;\r\n\r\n\twhile (el) {\r\n\t\tpath.push(el);\r\n\t\tel = el.parentNode;\r\n\t}\r\n\treturn path;\r\n}\r\n\r\n\r\n// @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point\r\n// Gets normalized mouse position from a DOM event relative to the\r\n// `container` (border excluded) or to the whole page if not specified.\r\nexport function getMousePosition(e, container) {\r\n\tif (!container) {\r\n\t\treturn new Point(e.clientX, e.clientY);\r\n\t}\r\n\r\n\tvar scale = getScale(container),\r\n\t    offset = scale.boundingClientRect; // left and top  values are in page scale (like the event clientX/Y)\r\n\r\n\treturn new Point(\r\n\t\t// offset.left/top values are in page scale (like clientX/Y),\r\n\t\t// whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).\r\n\t\t(e.clientX - offset.left) / scale.x - container.clientLeft,\r\n\t\t(e.clientY - offset.top) / scale.y - container.clientTop\r\n\t);\r\n}\r\n\r\n\r\n//  except , Safari and\r\n// We need double the scroll pixels (see #7403 and #4538) for all Browsers\r\n// except OSX (Mac) -> 3x, Chrome running on Linux 1x\r\n\r\nvar wheelPxFactor =\r\n\t(Browser.linux && Browser.chrome) ? window.devicePixelRatio :\r\n\tBrowser.mac ? window.devicePixelRatio * 3 :\r\n\twindow.devicePixelRatio > 0 ? 2 * window.devicePixelRatio : 1;\r\n// @function getWheelDelta(ev: DOMEvent): Number\r\n// Gets normalized wheel delta from a wheel DOM event, in vertical\r\n// pixels scrolled (negative if scrolling down).\r\n// Events from pointing devices without precise scrolling are mapped to\r\n// a best guess of 60 pixels.\r\nexport function getWheelDelta(e) {\r\n\treturn (Browser.edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta\r\n\t       (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels\r\n\t       (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines\r\n\t       (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages\r\n\t       (e.deltaX || e.deltaZ) ? 0 :\t// Skip horizontal/depth wheel events\r\n\t       e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels\r\n\t       (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines\r\n\t       e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages\r\n\t       0;\r\n}\r\n\r\n// check if element really left/entered the event target (for mouseenter/mouseleave)\r\nexport function isExternalTarget(el, e) {\r\n\r\n\tvar related = e.relatedTarget;\r\n\r\n\tif (!related) { return true; }\r\n\r\n\ttry {\r\n\t\twhile (related && (related !== el)) {\r\n\t\t\trelated = related.parentNode;\r\n\t\t}\r\n\t} catch (err) {\r\n\t\treturn false;\r\n\t}\r\n\treturn (related !== el);\r\n}\r\n\r\n// @function addListener(…): this\r\n// Alias to [`L.DomEvent.on`](#domevent-on)\r\nexport {on as addListener};\r\n\r\n// @function removeListener(…): this\r\n// Alias to [`L.DomEvent.off`](#domevent-off)\r\nexport {off as removeListener};\r\n","import * as Util from '../core/Util';\nimport {Evented} from '../core/Events';\nimport * as DomUtil from '../dom/DomUtil';\n\n\n/*\n * @class PosAnimation\n * @aka L.PosAnimation\n * @inherits Evented\n * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.\n *\n * @example\n * ```js\n * var myPositionMarker = L.marker([48.864716, 2.294694]).addTo(map);\n *\n * myPositionMarker.on(\"click\", function() {\n * \tvar pos = map.latLngToLayerPoint(myPositionMarker.getLatLng());\n * \tpos.y -= 25;\n * \tvar fx = new L.PosAnimation();\n *\n * \tfx.once('end',function() {\n * \t\tpos.y += 25;\n * \t\tfx.run(myPositionMarker._icon, pos, 0.8);\n * \t});\n *\n * \tfx.run(myPositionMarker._icon, pos, 0.3);\n * });\n *\n * ```\n *\n * @constructor L.PosAnimation()\n * Creates a `PosAnimation` object.\n *\n */\n\nexport var PosAnimation = Evented.extend({\n\n\t// @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)\n\t// Run an animation of a given element to a new position, optionally setting\n\t// duration in seconds (`0.25` by default) and easing linearity factor (3rd\n\t// argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1),\n\t// `0.5` by default).\n\trun: function (el, newPos, duration, easeLinearity) {\n\t\tthis.stop();\n\n\t\tthis._el = el;\n\t\tthis._inProgress = true;\n\t\tthis._duration = duration || 0.25;\n\t\tthis._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);\n\n\t\tthis._startPos = DomUtil.getPosition(el);\n\t\tthis._offset = newPos.subtract(this._startPos);\n\t\tthis._startTime = +new Date();\n\n\t\t// @event start: Event\n\t\t// Fired when the animation starts\n\t\tthis.fire('start');\n\n\t\tthis._animate();\n\t},\n\n\t// @method stop()\n\t// Stops the animation (if currently running).\n\tstop: function () {\n\t\tif (!this._inProgress) { return; }\n\n\t\tthis._step(true);\n\t\tthis._complete();\n\t},\n\n\t_animate: function () {\n\t\t// animation loop\n\t\tthis._animId = Util.requestAnimFrame(this._animate, this);\n\t\tthis._step();\n\t},\n\n\t_step: function (round) {\n\t\tvar elapsed = (+new Date()) - this._startTime,\n\t\t    duration = this._duration * 1000;\n\n\t\tif (elapsed < duration) {\n\t\t\tthis._runFrame(this._easeOut(elapsed / duration), round);\n\t\t} else {\n\t\t\tthis._runFrame(1);\n\t\t\tthis._complete();\n\t\t}\n\t},\n\n\t_runFrame: function (progress, round) {\n\t\tvar pos = this._startPos.add(this._offset.multiplyBy(progress));\n\t\tif (round) {\n\t\t\tpos._round();\n\t\t}\n\t\tDomUtil.setPosition(this._el, pos);\n\n\t\t// @event step: Event\n\t\t// Fired continuously during the animation.\n\t\tthis.fire('step');\n\t},\n\n\t_complete: function () {\n\t\tUtil.cancelAnimFrame(this._animId);\n\n\t\tthis._inProgress = false;\n\t\t// @event end: Event\n\t\t// Fired when the animation ends.\n\t\tthis.fire('end');\n\t},\n\n\t_easeOut: function (t) {\n\t\treturn 1 - Math.pow(1 - t, this._easeOutPower);\n\t}\n});\n","import * as Util from '../core/Util';\r\nimport {Evented} from '../core/Events';\r\nimport {EPSG3857} from '../geo/crs/CRS.EPSG3857';\r\nimport {Point, toPoint} from '../geometry/Point';\r\nimport {Bounds, toBounds} from '../geometry/Bounds';\r\nimport {LatLng, toLatLng} from '../geo/LatLng';\r\nimport {LatLngBounds, toLatLngBounds} from '../geo/LatLngBounds';\r\nimport Browser from '../core/Browser';\r\nimport * as DomEvent from '../dom/DomEvent';\r\nimport * as DomUtil from '../dom/DomUtil';\r\nimport {PosAnimation} from '../dom/PosAnimation';\r\n\r\n/*\r\n * @class Map\r\n * @aka L.Map\r\n * @inherits Evented\r\n *\r\n * The central class of the API — it is used to create a map on a page and manipulate it.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * // initialize the map on the \"map\" div with a given center and zoom\r\n * var map = L.map('map', {\r\n * \tcenter: [51.505, -0.09],\r\n * \tzoom: 13\r\n * });\r\n * ```\r\n *\r\n */\r\n\r\nexport var Map = Evented.extend({\r\n\r\n\toptions: {\r\n\t\t// @section Map State Options\r\n\t\t// @option crs: CRS = L.CRS.EPSG3857\r\n\t\t// The [Coordinate Reference System](#crs) to use. Don't change this if you're not\r\n\t\t// sure what it means.\r\n\t\tcrs: EPSG3857,\r\n\r\n\t\t// @option center: LatLng = undefined\r\n\t\t// Initial geographic center of the map\r\n\t\tcenter: undefined,\r\n\r\n\t\t// @option zoom: Number = undefined\r\n\t\t// Initial map zoom level\r\n\t\tzoom: undefined,\r\n\r\n\t\t// @option minZoom: Number = *\r\n\t\t// Minimum zoom level of the map.\r\n\t\t// If not specified and at least one `GridLayer` or `TileLayer` is in the map,\r\n\t\t// the lowest of their `minZoom` options will be used instead.\r\n\t\tminZoom: undefined,\r\n\r\n\t\t// @option maxZoom: Number = *\r\n\t\t// Maximum zoom level of the map.\r\n\t\t// If not specified and at least one `GridLayer` or `TileLayer` is in the map,\r\n\t\t// the highest of their `maxZoom` options will be used instead.\r\n\t\tmaxZoom: undefined,\r\n\r\n\t\t// @option layers: Layer[] = []\r\n\t\t// Array of layers that will be added to the map initially\r\n\t\tlayers: [],\r\n\r\n\t\t// @option maxBounds: LatLngBounds = null\r\n\t\t// When this option is set, the map restricts the view to the given\r\n\t\t// geographical bounds, bouncing the user back if the user tries to pan\r\n\t\t// outside the view. To set the restriction dynamically, use\r\n\t\t// [`setMaxBounds`](#map-setmaxbounds) method.\r\n\t\tmaxBounds: undefined,\r\n\r\n\t\t// @option renderer: Renderer = *\r\n\t\t// The default method for drawing vector layers on the map. `L.SVG`\r\n\t\t// or `L.Canvas` by default depending on browser support.\r\n\t\trenderer: undefined,\r\n\r\n\r\n\t\t// @section Animation Options\r\n\t\t// @option zoomAnimation: Boolean = true\r\n\t\t// Whether the map zoom animation is enabled. By default it's enabled\r\n\t\t// in all browsers that support CSS3 Transitions except Android.\r\n\t\tzoomAnimation: true,\r\n\r\n\t\t// @option zoomAnimationThreshold: Number = 4\r\n\t\t// Won't animate zoom if the zoom difference exceeds this value.\r\n\t\tzoomAnimationThreshold: 4,\r\n\r\n\t\t// @option fadeAnimation: Boolean = true\r\n\t\t// Whether the tile fade animation is enabled. By default it's enabled\r\n\t\t// in all browsers that support CSS3 Transitions except Android.\r\n\t\tfadeAnimation: true,\r\n\r\n\t\t// @option markerZoomAnimation: Boolean = true\r\n\t\t// Whether markers animate their zoom with the zoom animation, if disabled\r\n\t\t// they will disappear for the length of the animation. By default it's\r\n\t\t// enabled in all browsers that support CSS3 Transitions except Android.\r\n\t\tmarkerZoomAnimation: true,\r\n\r\n\t\t// @option transform3DLimit: Number = 2^23\r\n\t\t// Defines the maximum size of a CSS translation transform. The default\r\n\t\t// value should not be changed unless a web browser positions layers in\r\n\t\t// the wrong place after doing a large `panBy`.\r\n\t\ttransform3DLimit: 8388608, // Precision limit of a 32-bit float\r\n\r\n\t\t// @section Interaction Options\r\n\t\t// @option zoomSnap: Number = 1\r\n\t\t// Forces the map's zoom level to always be a multiple of this, particularly\r\n\t\t// right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.\r\n\t\t// By default, the zoom level snaps to the nearest integer; lower values\r\n\t\t// (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`\r\n\t\t// means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.\r\n\t\tzoomSnap: 1,\r\n\r\n\t\t// @option zoomDelta: Number = 1\r\n\t\t// Controls how much the map's zoom level will change after a\r\n\t\t// [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`\r\n\t\t// or `-` on the keyboard, or using the [zoom controls](#control-zoom).\r\n\t\t// Values smaller than `1` (e.g. `0.5`) allow for greater granularity.\r\n\t\tzoomDelta: 1,\r\n\r\n\t\t// @option trackResize: Boolean = true\r\n\t\t// Whether the map automatically handles browser window resize to update itself.\r\n\t\ttrackResize: true\r\n\t},\r\n\r\n\tinitialize: function (id, options) { // (HTMLElement or String, Object)\r\n\t\toptions = Util.setOptions(this, options);\r\n\r\n\t\t// Make sure to assign internal flags at the beginning,\r\n\t\t// to avoid inconsistent state in some edge cases.\r\n\t\tthis._handlers = [];\r\n\t\tthis._layers = {};\r\n\t\tthis._zoomBoundLayers = {};\r\n\t\tthis._sizeChanged = true;\r\n\r\n\t\tthis._initContainer(id);\r\n\t\tthis._initLayout();\r\n\r\n\t\t// hack for https://github.com/Leaflet/Leaflet/issues/1980\r\n\t\tthis._onResize = Util.bind(this._onResize, this);\r\n\r\n\t\tthis._initEvents();\r\n\r\n\t\tif (options.maxBounds) {\r\n\t\t\tthis.setMaxBounds(options.maxBounds);\r\n\t\t}\r\n\r\n\t\tif (options.zoom !== undefined) {\r\n\t\t\tthis._zoom = this._limitZoom(options.zoom);\r\n\t\t}\r\n\r\n\t\tif (options.center && options.zoom !== undefined) {\r\n\t\t\tthis.setView(toLatLng(options.center), options.zoom, {reset: true});\r\n\t\t}\r\n\r\n\t\tthis.callInitHooks();\r\n\r\n\t\t// don't animate on browsers without hardware-accelerated transitions or old Android/Opera\r\n\t\tthis._zoomAnimated = DomUtil.TRANSITION && Browser.any3d && !Browser.mobileOpera &&\r\n\t\t\t\tthis.options.zoomAnimation;\r\n\r\n\t\t// zoom transitions run with the same duration for all layers, so if one of transitionend events\r\n\t\t// happens after starting zoom animation (propagating to the map pane), we know that it ended globally\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tthis._createAnimProxy();\r\n\t\t\tDomEvent.on(this._proxy, DomUtil.TRANSITION_END, this._catchTransitionEnd, this);\r\n\t\t}\r\n\r\n\t\tthis._addLayers(this.options.layers);\r\n\t},\r\n\r\n\r\n\t// @section Methods for modifying map state\r\n\r\n\t// @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this\r\n\t// Sets the view of the map (geographical center and zoom) with the given\r\n\t// animation options.\r\n\tsetView: function (center, zoom, options) {\r\n\r\n\t\tzoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);\r\n\t\tcenter = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);\r\n\t\toptions = options || {};\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tif (this._loaded && !options.reset && options !== true) {\r\n\r\n\t\t\tif (options.animate !== undefined) {\r\n\t\t\t\toptions.zoom = Util.extend({animate: options.animate}, options.zoom);\r\n\t\t\t\toptions.pan = Util.extend({animate: options.animate, duration: options.duration}, options.pan);\r\n\t\t\t}\r\n\r\n\t\t\t// try animating pan or zoom\r\n\t\t\tvar moved = (this._zoom !== zoom) ?\r\n\t\t\t\tthis._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :\r\n\t\t\t\tthis._tryAnimatedPan(center, options.pan);\r\n\r\n\t\t\tif (moved) {\r\n\t\t\t\t// prevent resize handler call, the view will refresh after animation anyway\r\n\t\t\t\tclearTimeout(this._sizeTimer);\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// animation didn't start, just reset the map view\r\n\t\tthis._resetView(center, zoom, options.pan && options.pan.noMoveStart);\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setZoom(zoom: Number, options?: Zoom/pan options): this\r\n\t// Sets the zoom of the map.\r\n\tsetZoom: function (zoom, options) {\r\n\t\tif (!this._loaded) {\r\n\t\t\tthis._zoom = zoom;\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\treturn this.setView(this.getCenter(), zoom, {zoom: options});\r\n\t},\r\n\r\n\t// @method zoomIn(delta?: Number, options?: Zoom options): this\r\n\t// Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).\r\n\tzoomIn: function (delta, options) {\r\n\t\tdelta = delta || (Browser.any3d ? this.options.zoomDelta : 1);\r\n\t\treturn this.setZoom(this._zoom + delta, options);\r\n\t},\r\n\r\n\t// @method zoomOut(delta?: Number, options?: Zoom options): this\r\n\t// Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).\r\n\tzoomOut: function (delta, options) {\r\n\t\tdelta = delta || (Browser.any3d ? this.options.zoomDelta : 1);\r\n\t\treturn this.setZoom(this._zoom - delta, options);\r\n\t},\r\n\r\n\t// @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this\r\n\t// Zooms the map while keeping a specified geographical point on the map\r\n\t// stationary (e.g. used internally for scroll zoom and double-click zoom).\r\n\t// @alternative\r\n\t// @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this\r\n\t// Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.\r\n\tsetZoomAround: function (latlng, zoom, options) {\r\n\t\tvar scale = this.getZoomScale(zoom),\r\n\t\t    viewHalf = this.getSize().divideBy(2),\r\n\t\t    containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),\r\n\r\n\t\t    centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),\r\n\t\t    newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));\r\n\r\n\t\treturn this.setView(newCenter, zoom, {zoom: options});\r\n\t},\r\n\r\n\t_getBoundsCenterZoom: function (bounds, options) {\r\n\r\n\t\toptions = options || {};\r\n\t\tbounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);\r\n\r\n\t\tvar paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),\r\n\t\t    paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),\r\n\r\n\t\t    zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));\r\n\r\n\t\tzoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;\r\n\r\n\t\tif (zoom === Infinity) {\r\n\t\t\treturn {\r\n\t\t\t\tcenter: bounds.getCenter(),\r\n\t\t\t\tzoom: zoom\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tvar paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),\r\n\r\n\t\t    swPoint = this.project(bounds.getSouthWest(), zoom),\r\n\t\t    nePoint = this.project(bounds.getNorthEast(), zoom),\r\n\t\t    center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);\r\n\r\n\t\treturn {\r\n\t\t\tcenter: center,\r\n\t\t\tzoom: zoom\r\n\t\t};\r\n\t},\r\n\r\n\t// @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this\r\n\t// Sets a map view that contains the given geographical bounds with the\r\n\t// maximum zoom level possible.\r\n\tfitBounds: function (bounds, options) {\r\n\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (!bounds.isValid()) {\r\n\t\t\tthrow new Error('Bounds are not valid.');\r\n\t\t}\r\n\r\n\t\tvar target = this._getBoundsCenterZoom(bounds, options);\r\n\t\treturn this.setView(target.center, target.zoom, options);\r\n\t},\r\n\r\n\t// @method fitWorld(options?: fitBounds options): this\r\n\t// Sets a map view that mostly contains the whole world with the maximum\r\n\t// zoom level possible.\r\n\tfitWorld: function (options) {\r\n\t\treturn this.fitBounds([[-90, -180], [90, 180]], options);\r\n\t},\r\n\r\n\t// @method panTo(latlng: LatLng, options?: Pan options): this\r\n\t// Pans the map to a given center.\r\n\tpanTo: function (center, options) { // (LatLng)\r\n\t\treturn this.setView(center, this._zoom, {pan: options});\r\n\t},\r\n\r\n\t// @method panBy(offset: Point, options?: Pan options): this\r\n\t// Pans the map by a given number of pixels (animated).\r\n\tpanBy: function (offset, options) {\r\n\t\toffset = toPoint(offset).round();\r\n\t\toptions = options || {};\r\n\r\n\t\tif (!offset.x && !offset.y) {\r\n\t\t\treturn this.fire('moveend');\r\n\t\t}\r\n\t\t// If we pan too far, Chrome gets issues with tiles\r\n\t\t// and makes them disappear or appear in the wrong place (slightly offset) #2602\r\n\t\tif (options.animate !== true && !this.getSize().contains(offset)) {\r\n\t\t\tthis._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tif (!this._panAnim) {\r\n\t\t\tthis._panAnim = new PosAnimation();\r\n\r\n\t\t\tthis._panAnim.on({\r\n\t\t\t\t'step': this._onPanTransitionStep,\r\n\t\t\t\t'end': this._onPanTransitionEnd\r\n\t\t\t}, this);\r\n\t\t}\r\n\r\n\t\t// don't fire movestart if animating inertia\r\n\t\tif (!options.noMoveStart) {\r\n\t\t\tthis.fire('movestart');\r\n\t\t}\r\n\r\n\t\t// animate pan unless animate: false specified\r\n\t\tif (options.animate !== false) {\r\n\t\t\tDomUtil.addClass(this._mapPane, 'leaflet-pan-anim');\r\n\r\n\t\t\tvar newPos = this._getMapPanePos().subtract(offset).round();\r\n\t\t\tthis._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);\r\n\t\t} else {\r\n\t\t\tthis._rawPanBy(offset);\r\n\t\t\tthis.fire('move').fire('moveend');\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this\r\n\t// Sets the view of the map (geographical center and zoom) performing a smooth\r\n\t// pan-zoom animation.\r\n\tflyTo: function (targetCenter, targetZoom, options) {\r\n\r\n\t\toptions = options || {};\r\n\t\tif (options.animate === false || !Browser.any3d) {\r\n\t\t\treturn this.setView(targetCenter, targetZoom, options);\r\n\t\t}\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tvar from = this.project(this.getCenter()),\r\n\t\t    to = this.project(targetCenter),\r\n\t\t    size = this.getSize(),\r\n\t\t    startZoom = this._zoom;\r\n\r\n\t\ttargetCenter = toLatLng(targetCenter);\r\n\t\ttargetZoom = targetZoom === undefined ? startZoom : targetZoom;\r\n\r\n\t\tvar w0 = Math.max(size.x, size.y),\r\n\t\t    w1 = w0 * this.getZoomScale(startZoom, targetZoom),\r\n\t\t    u1 = (to.distanceTo(from)) || 1,\r\n\t\t    rho = 1.42,\r\n\t\t    rho2 = rho * rho;\r\n\r\n\t\tfunction r(i) {\r\n\t\t\tvar s1 = i ? -1 : 1,\r\n\t\t\t    s2 = i ? w1 : w0,\r\n\t\t\t    t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,\r\n\t\t\t    b1 = 2 * s2 * rho2 * u1,\r\n\t\t\t    b = t1 / b1,\r\n\t\t\t    sq = Math.sqrt(b * b + 1) - b;\r\n\r\n\t\t\t    // workaround for floating point precision bug when sq = 0, log = -Infinite,\r\n\t\t\t    // thus triggering an infinite loop in flyTo\r\n\t\t\t    var log = sq < 0.000000001 ? -18 : Math.log(sq);\r\n\r\n\t\t\treturn log;\r\n\t\t}\r\n\r\n\t\tfunction sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }\r\n\t\tfunction cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }\r\n\t\tfunction tanh(n) { return sinh(n) / cosh(n); }\r\n\r\n\t\tvar r0 = r(0);\r\n\r\n\t\tfunction w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }\r\n\t\tfunction u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }\r\n\r\n\t\tfunction easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }\r\n\r\n\t\tvar start = Date.now(),\r\n\t\t    S = (r(1) - r0) / rho,\r\n\t\t    duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;\r\n\r\n\t\tfunction frame() {\r\n\t\t\tvar t = (Date.now() - start) / duration,\r\n\t\t\t    s = easeOut(t) * S;\r\n\r\n\t\t\tif (t <= 1) {\r\n\t\t\t\tthis._flyToFrame = Util.requestAnimFrame(frame, this);\r\n\r\n\t\t\t\tthis._move(\r\n\t\t\t\t\tthis.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),\r\n\t\t\t\t\tthis.getScaleZoom(w0 / w(s), startZoom),\r\n\t\t\t\t\t{flyTo: true});\r\n\r\n\t\t\t} else {\r\n\t\t\t\tthis\r\n\t\t\t\t\t._move(targetCenter, targetZoom)\r\n\t\t\t\t\t._moveEnd(true);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._moveStart(true, options.noMoveStart);\r\n\r\n\t\tframe.call(this);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this\r\n\t// Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),\r\n\t// but takes a bounds parameter like [`fitBounds`](#map-fitbounds).\r\n\tflyToBounds: function (bounds, options) {\r\n\t\tvar target = this._getBoundsCenterZoom(bounds, options);\r\n\t\treturn this.flyTo(target.center, target.zoom, options);\r\n\t},\r\n\r\n\t// @method setMaxBounds(bounds: LatLngBounds): this\r\n\t// Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).\r\n\tsetMaxBounds: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (this.listens('moveend', this._panInsideMaxBounds)) {\r\n\t\t\tthis.off('moveend', this._panInsideMaxBounds);\r\n\t\t}\r\n\r\n\t\tif (!bounds.isValid()) {\r\n\t\t\tthis.options.maxBounds = null;\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tthis.options.maxBounds = bounds;\r\n\r\n\t\tif (this._loaded) {\r\n\t\t\tthis._panInsideMaxBounds();\r\n\t\t}\r\n\r\n\t\treturn this.on('moveend', this._panInsideMaxBounds);\r\n\t},\r\n\r\n\t// @method setMinZoom(zoom: Number): this\r\n\t// Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).\r\n\tsetMinZoom: function (zoom) {\r\n\t\tvar oldZoom = this.options.minZoom;\r\n\t\tthis.options.minZoom = zoom;\r\n\r\n\t\tif (this._loaded && oldZoom !== zoom) {\r\n\t\t\tthis.fire('zoomlevelschange');\r\n\r\n\t\t\tif (this.getZoom() < this.options.minZoom) {\r\n\t\t\t\treturn this.setZoom(zoom);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setMaxZoom(zoom: Number): this\r\n\t// Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).\r\n\tsetMaxZoom: function (zoom) {\r\n\t\tvar oldZoom = this.options.maxZoom;\r\n\t\tthis.options.maxZoom = zoom;\r\n\r\n\t\tif (this._loaded && oldZoom !== zoom) {\r\n\t\t\tthis.fire('zoomlevelschange');\r\n\r\n\t\t\tif (this.getZoom() > this.options.maxZoom) {\r\n\t\t\t\treturn this.setZoom(zoom);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this\r\n\t// Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.\r\n\tpanInsideBounds: function (bounds, options) {\r\n\t\tthis._enforcingBounds = true;\r\n\t\tvar center = this.getCenter(),\r\n\t\t    newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));\r\n\r\n\t\tif (!center.equals(newCenter)) {\r\n\t\t\tthis.panTo(newCenter, options);\r\n\t\t}\r\n\r\n\t\tthis._enforcingBounds = false;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method panInside(latlng: LatLng, options?: padding options): this\r\n\t// Pans the map the minimum amount to make the `latlng` visible. Use\r\n\t// padding options to fit the display to more restricted bounds.\r\n\t// If `latlng` is already within the (optionally padded) display bounds,\r\n\t// the map will not be panned.\r\n\tpanInside: function (latlng, options) {\r\n\t\toptions = options || {};\r\n\r\n\t\tvar paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),\r\n\t\t    paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),\r\n\t\t    pixelCenter = this.project(this.getCenter()),\r\n\t\t    pixelPoint = this.project(latlng),\r\n\t\t    pixelBounds = this.getPixelBounds(),\r\n\t\t    paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]),\r\n\t\t    paddedSize = paddedBounds.getSize();\r\n\r\n\t\tif (!paddedBounds.contains(pixelPoint)) {\r\n\t\t\tthis._enforcingBounds = true;\r\n\t\t\tvar centerOffset = pixelPoint.subtract(paddedBounds.getCenter());\r\n\t\t\tvar offset = paddedBounds.extend(pixelPoint).getSize().subtract(paddedSize);\r\n\t\t\tpixelCenter.x += centerOffset.x < 0 ? -offset.x : offset.x;\r\n\t\t\tpixelCenter.y += centerOffset.y < 0 ? -offset.y : offset.y;\r\n\t\t\tthis.panTo(this.unproject(pixelCenter), options);\r\n\t\t\tthis._enforcingBounds = false;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method invalidateSize(options: Zoom/pan options): this\r\n\t// Checks if the map container size changed and updates the map if so —\r\n\t// call it after you've changed the map size dynamically, also animating\r\n\t// pan by default. If `options.pan` is `false`, panning will not occur.\r\n\t// If `options.debounceMoveend` is `true`, it will delay `moveend` event so\r\n\t// that it doesn't happen often even if the method is called many\r\n\t// times in a row.\r\n\r\n\t// @alternative\r\n\t// @method invalidateSize(animate: Boolean): this\r\n\t// Checks if the map container size changed and updates the map if so —\r\n\t// call it after you've changed the map size dynamically, also animating\r\n\t// pan by default.\r\n\tinvalidateSize: function (options) {\r\n\t\tif (!this._loaded) { return this; }\r\n\r\n\t\toptions = Util.extend({\r\n\t\t\tanimate: false,\r\n\t\t\tpan: true\r\n\t\t}, options === true ? {animate: true} : options);\r\n\r\n\t\tvar oldSize = this.getSize();\r\n\t\tthis._sizeChanged = true;\r\n\t\tthis._lastCenter = null;\r\n\r\n\t\tvar newSize = this.getSize(),\r\n\t\t    oldCenter = oldSize.divideBy(2).round(),\r\n\t\t    newCenter = newSize.divideBy(2).round(),\r\n\t\t    offset = oldCenter.subtract(newCenter);\r\n\r\n\t\tif (!offset.x && !offset.y) { return this; }\r\n\r\n\t\tif (options.animate && options.pan) {\r\n\t\t\tthis.panBy(offset);\r\n\r\n\t\t} else {\r\n\t\t\tif (options.pan) {\r\n\t\t\t\tthis._rawPanBy(offset);\r\n\t\t\t}\r\n\r\n\t\t\tthis.fire('move');\r\n\r\n\t\t\tif (options.debounceMoveend) {\r\n\t\t\t\tclearTimeout(this._sizeTimer);\r\n\t\t\t\tthis._sizeTimer = setTimeout(Util.bind(this.fire, this, 'moveend'), 200);\r\n\t\t\t} else {\r\n\t\t\t\tthis.fire('moveend');\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// @section Map state change events\r\n\t\t// @event resize: ResizeEvent\r\n\t\t// Fired when the map is resized.\r\n\t\treturn this.fire('resize', {\r\n\t\t\toldSize: oldSize,\r\n\t\t\tnewSize: newSize\r\n\t\t});\r\n\t},\r\n\r\n\t// @section Methods for modifying map state\r\n\t// @method stop(): this\r\n\t// Stops the currently running `panTo` or `flyTo` animation, if any.\r\n\tstop: function () {\r\n\t\tthis.setZoom(this._limitZoom(this._zoom));\r\n\t\tif (!this.options.zoomSnap) {\r\n\t\t\tthis.fire('viewreset');\r\n\t\t}\r\n\t\treturn this._stop();\r\n\t},\r\n\r\n\t// @section Geolocation methods\r\n\t// @method locate(options?: Locate options): this\r\n\t// Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)\r\n\t// event with location data on success or a [`locationerror`](#map-locationerror) event on failure,\r\n\t// and optionally sets the map view to the user's location with respect to\r\n\t// detection accuracy (or to the world view if geolocation failed).\r\n\t// Note that, if your page doesn't use HTTPS, this method will fail in\r\n\t// modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))\r\n\t// See `Locate options` for more details.\r\n\tlocate: function (options) {\r\n\r\n\t\toptions = this._locateOptions = Util.extend({\r\n\t\t\ttimeout: 10000,\r\n\t\t\twatch: false\r\n\t\t\t// setView: false\r\n\t\t\t// maxZoom: <Number>\r\n\t\t\t// maximumAge: 0\r\n\t\t\t// enableHighAccuracy: false\r\n\t\t}, options);\r\n\r\n\t\tif (!('geolocation' in navigator)) {\r\n\t\t\tthis._handleGeolocationError({\r\n\t\t\t\tcode: 0,\r\n\t\t\t\tmessage: 'Geolocation not supported.'\r\n\t\t\t});\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tvar onResponse = Util.bind(this._handleGeolocationResponse, this),\r\n\t\t    onError = Util.bind(this._handleGeolocationError, this);\r\n\r\n\t\tif (options.watch) {\r\n\t\t\tthis._locationWatchId =\r\n\t\t\t        navigator.geolocation.watchPosition(onResponse, onError, options);\r\n\t\t} else {\r\n\t\t\tnavigator.geolocation.getCurrentPosition(onResponse, onError, options);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method stopLocate(): this\r\n\t// Stops watching location previously initiated by `map.locate({watch: true})`\r\n\t// and aborts resetting the map view if map.locate was called with\r\n\t// `{setView: true}`.\r\n\tstopLocate: function () {\r\n\t\tif (navigator.geolocation && navigator.geolocation.clearWatch) {\r\n\t\t\tnavigator.geolocation.clearWatch(this._locationWatchId);\r\n\t\t}\r\n\t\tif (this._locateOptions) {\r\n\t\t\tthis._locateOptions.setView = false;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_handleGeolocationError: function (error) {\r\n\t\tif (!this._container._leaflet_id) { return; }\r\n\r\n\t\tvar c = error.code,\r\n\t\t    message = error.message ||\r\n\t\t            (c === 1 ? 'permission denied' :\r\n\t\t            (c === 2 ? 'position unavailable' : 'timeout'));\r\n\r\n\t\tif (this._locateOptions.setView && !this._loaded) {\r\n\t\t\tthis.fitWorld();\r\n\t\t}\r\n\r\n\t\t// @section Location events\r\n\t\t// @event locationerror: ErrorEvent\r\n\t\t// Fired when geolocation (using the [`locate`](#map-locate) method) failed.\r\n\t\tthis.fire('locationerror', {\r\n\t\t\tcode: c,\r\n\t\t\tmessage: 'Geolocation error: ' + message + '.'\r\n\t\t});\r\n\t},\r\n\r\n\t_handleGeolocationResponse: function (pos) {\r\n\t\tif (!this._container._leaflet_id) { return; }\r\n\r\n\t\tvar lat = pos.coords.latitude,\r\n\t\t    lng = pos.coords.longitude,\r\n\t\t    latlng = new LatLng(lat, lng),\r\n\t\t    bounds = latlng.toBounds(pos.coords.accuracy * 2),\r\n\t\t    options = this._locateOptions;\r\n\r\n\t\tif (options.setView) {\r\n\t\t\tvar zoom = this.getBoundsZoom(bounds);\r\n\t\t\tthis.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);\r\n\t\t}\r\n\r\n\t\tvar data = {\r\n\t\t\tlatlng: latlng,\r\n\t\t\tbounds: bounds,\r\n\t\t\ttimestamp: pos.timestamp\r\n\t\t};\r\n\r\n\t\tfor (var i in pos.coords) {\r\n\t\t\tif (typeof pos.coords[i] === 'number') {\r\n\t\t\t\tdata[i] = pos.coords[i];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// @event locationfound: LocationEvent\r\n\t\t// Fired when geolocation (using the [`locate`](#map-locate) method)\r\n\t\t// went successfully.\r\n\t\tthis.fire('locationfound', data);\r\n\t},\r\n\r\n\t// TODO Appropriate docs section?\r\n\t// @section Other Methods\r\n\t// @method addHandler(name: String, HandlerClass: Function): this\r\n\t// Adds a new `Handler` to the map, given its name and constructor function.\r\n\taddHandler: function (name, HandlerClass) {\r\n\t\tif (!HandlerClass) { return this; }\r\n\r\n\t\tvar handler = this[name] = new HandlerClass(this);\r\n\r\n\t\tthis._handlers.push(handler);\r\n\r\n\t\tif (this.options[name]) {\r\n\t\t\thandler.enable();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method remove(): this\r\n\t// Destroys the map and clears all related event listeners.\r\n\tremove: function () {\r\n\r\n\t\tthis._initEvents(true);\r\n\t\tif (this.options.maxBounds) { this.off('moveend', this._panInsideMaxBounds); }\r\n\r\n\t\tif (this._containerId !== this._container._leaflet_id) {\r\n\t\t\tthrow new Error('Map container is being reused by another instance');\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\t// throws error in IE6-8\r\n\t\t\tdelete this._container._leaflet_id;\r\n\t\t\tdelete this._containerId;\r\n\t\t} catch (e) {\r\n\t\t\t/*eslint-disable */\r\n\t\t\tthis._container._leaflet_id = undefined;\r\n\t\t\t/* eslint-enable */\r\n\t\t\tthis._containerId = undefined;\r\n\t\t}\r\n\r\n\t\tif (this._locationWatchId !== undefined) {\r\n\t\t\tthis.stopLocate();\r\n\t\t}\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tDomUtil.remove(this._mapPane);\r\n\r\n\t\tif (this._clearControlPos) {\r\n\t\t\tthis._clearControlPos();\r\n\t\t}\r\n\t\tif (this._resizeRequest) {\r\n\t\t\tUtil.cancelAnimFrame(this._resizeRequest);\r\n\t\t\tthis._resizeRequest = null;\r\n\t\t}\r\n\r\n\t\tthis._clearHandlers();\r\n\r\n\t\tif (this._loaded) {\r\n\t\t\t// @section Map state change events\r\n\t\t\t// @event unload: Event\r\n\t\t\t// Fired when the map is destroyed with [remove](#map-remove) method.\r\n\t\t\tthis.fire('unload');\r\n\t\t}\r\n\r\n\t\tvar i;\r\n\t\tfor (i in this._layers) {\r\n\t\t\tthis._layers[i].remove();\r\n\t\t}\r\n\t\tfor (i in this._panes) {\r\n\t\t\tDomUtil.remove(this._panes[i]);\r\n\t\t}\r\n\r\n\t\tthis._layers = [];\r\n\t\tthis._panes = [];\r\n\t\tdelete this._mapPane;\r\n\t\tdelete this._renderer;\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\t// @method createPane(name: String, container?: HTMLElement): HTMLElement\r\n\t// Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,\r\n\t// then returns it. The pane is created as a child of `container`, or\r\n\t// as a child of the main map pane if not set.\r\n\tcreatePane: function (name, container) {\r\n\t\tvar className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),\r\n\t\t    pane = DomUtil.create('div', className, container || this._mapPane);\r\n\r\n\t\tif (name) {\r\n\t\t\tthis._panes[name] = pane;\r\n\t\t}\r\n\t\treturn pane;\r\n\t},\r\n\r\n\t// @section Methods for Getting Map State\r\n\r\n\t// @method getCenter(): LatLng\r\n\t// Returns the geographical center of the map view\r\n\tgetCenter: function () {\r\n\t\tthis._checkIfLoaded();\r\n\r\n\t\tif (this._lastCenter && !this._moved()) {\r\n\t\t\treturn this._lastCenter.clone();\r\n\t\t}\r\n\t\treturn this.layerPointToLatLng(this._getCenterLayerPoint());\r\n\t},\r\n\r\n\t// @method getZoom(): Number\r\n\t// Returns the current zoom level of the map view\r\n\tgetZoom: function () {\r\n\t\treturn this._zoom;\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Returns the geographical bounds visible in the current map view\r\n\tgetBounds: function () {\r\n\t\tvar bounds = this.getPixelBounds(),\r\n\t\t    sw = this.unproject(bounds.getBottomLeft()),\r\n\t\t    ne = this.unproject(bounds.getTopRight());\r\n\r\n\t\treturn new LatLngBounds(sw, ne);\r\n\t},\r\n\r\n\t// @method getMinZoom(): Number\r\n\t// Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default.\r\n\tgetMinZoom: function () {\r\n\t\treturn this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;\r\n\t},\r\n\r\n\t// @method getMaxZoom(): Number\r\n\t// Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).\r\n\tgetMaxZoom: function () {\r\n\t\treturn this.options.maxZoom === undefined ?\r\n\t\t\t(this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :\r\n\t\t\tthis.options.maxZoom;\r\n\t},\r\n\r\n\t// @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number\r\n\t// Returns the maximum zoom level on which the given bounds fit to the map\r\n\t// view in its entirety. If `inside` (optional) is set to `true`, the method\r\n\t// instead returns the minimum zoom level on which the map view fits into\r\n\t// the given bounds in its entirety.\r\n\tgetBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\t\tpadding = toPoint(padding || [0, 0]);\r\n\r\n\t\tvar zoom = this.getZoom() || 0,\r\n\t\t    min = this.getMinZoom(),\r\n\t\t    max = this.getMaxZoom(),\r\n\t\t    nw = bounds.getNorthWest(),\r\n\t\t    se = bounds.getSouthEast(),\r\n\t\t    size = this.getSize().subtract(padding),\r\n\t\t    boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),\r\n\t\t    snap = Browser.any3d ? this.options.zoomSnap : 1,\r\n\t\t    scalex = size.x / boundsSize.x,\r\n\t\t    scaley = size.y / boundsSize.y,\r\n\t\t    scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);\r\n\r\n\t\tzoom = this.getScaleZoom(scale, zoom);\r\n\r\n\t\tif (snap) {\r\n\t\t\tzoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level\r\n\t\t\tzoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;\r\n\t\t}\r\n\r\n\t\treturn Math.max(min, Math.min(max, zoom));\r\n\t},\r\n\r\n\t// @method getSize(): Point\r\n\t// Returns the current size of the map container (in pixels).\r\n\tgetSize: function () {\r\n\t\tif (!this._size || this._sizeChanged) {\r\n\t\t\tthis._size = new Point(\r\n\t\t\t\tthis._container.clientWidth || 0,\r\n\t\t\t\tthis._container.clientHeight || 0);\r\n\r\n\t\t\tthis._sizeChanged = false;\r\n\t\t}\r\n\t\treturn this._size.clone();\r\n\t},\r\n\r\n\t// @method getPixelBounds(): Bounds\r\n\t// Returns the bounds of the current map view in projected pixel\r\n\t// coordinates (sometimes useful in layer and overlay implementations).\r\n\tgetPixelBounds: function (center, zoom) {\r\n\t\tvar topLeftPoint = this._getTopLeftPoint(center, zoom);\r\n\t\treturn new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));\r\n\t},\r\n\r\n\t// TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to\r\n\t// the map pane? \"left point of the map layer\" can be confusing, specially\r\n\t// since there can be negative offsets.\r\n\t// @method getPixelOrigin(): Point\r\n\t// Returns the projected pixel coordinates of the top left point of\r\n\t// the map layer (useful in custom layer and overlay implementations).\r\n\tgetPixelOrigin: function () {\r\n\t\tthis._checkIfLoaded();\r\n\t\treturn this._pixelOrigin;\r\n\t},\r\n\r\n\t// @method getPixelWorldBounds(zoom?: Number): Bounds\r\n\t// Returns the world's bounds in pixel coordinates for zoom level `zoom`.\r\n\t// If `zoom` is omitted, the map's current zoom level is used.\r\n\tgetPixelWorldBounds: function (zoom) {\r\n\t\treturn this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\r\n\t// @method getPane(pane: String|HTMLElement): HTMLElement\r\n\t// Returns a [map pane](#map-pane), given its name or its HTML element (its identity).\r\n\tgetPane: function (pane) {\r\n\t\treturn typeof pane === 'string' ? this._panes[pane] : pane;\r\n\t},\r\n\r\n\t// @method getPanes(): Object\r\n\t// Returns a plain object containing the names of all [panes](#map-pane) as keys and\r\n\t// the panes as values.\r\n\tgetPanes: function () {\r\n\t\treturn this._panes;\r\n\t},\r\n\r\n\t// @method getContainer: HTMLElement\r\n\t// Returns the HTML element that contains the map.\r\n\tgetContainer: function () {\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\r\n\t// @section Conversion Methods\r\n\r\n\t// @method getZoomScale(toZoom: Number, fromZoom: Number): Number\r\n\t// Returns the scale factor to be applied to a map transition from zoom level\r\n\t// `fromZoom` to `toZoom`. Used internally to help with zoom animations.\r\n\tgetZoomScale: function (toZoom, fromZoom) {\r\n\t\t// TODO replace with universal implementation after refactoring projections\r\n\t\tvar crs = this.options.crs;\r\n\t\tfromZoom = fromZoom === undefined ? this._zoom : fromZoom;\r\n\t\treturn crs.scale(toZoom) / crs.scale(fromZoom);\r\n\t},\r\n\r\n\t// @method getScaleZoom(scale: Number, fromZoom: Number): Number\r\n\t// Returns the zoom level that the map would end up at, if it is at `fromZoom`\r\n\t// level and everything is scaled by a factor of `scale`. Inverse of\r\n\t// [`getZoomScale`](#map-getZoomScale).\r\n\tgetScaleZoom: function (scale, fromZoom) {\r\n\t\tvar crs = this.options.crs;\r\n\t\tfromZoom = fromZoom === undefined ? this._zoom : fromZoom;\r\n\t\tvar zoom = crs.zoom(scale * crs.scale(fromZoom));\r\n\t\treturn isNaN(zoom) ? Infinity : zoom;\r\n\t},\r\n\r\n\t// @method project(latlng: LatLng, zoom: Number): Point\r\n\t// Projects a geographical coordinate `LatLng` according to the projection\r\n\t// of the map's CRS, then scales it according to `zoom` and the CRS's\r\n\t// `Transformation`. The result is pixel coordinate relative to\r\n\t// the CRS origin.\r\n\tproject: function (latlng, zoom) {\r\n\t\tzoom = zoom === undefined ? this._zoom : zoom;\r\n\t\treturn this.options.crs.latLngToPoint(toLatLng(latlng), zoom);\r\n\t},\r\n\r\n\t// @method unproject(point: Point, zoom: Number): LatLng\r\n\t// Inverse of [`project`](#map-project).\r\n\tunproject: function (point, zoom) {\r\n\t\tzoom = zoom === undefined ? this._zoom : zoom;\r\n\t\treturn this.options.crs.pointToLatLng(toPoint(point), zoom);\r\n\t},\r\n\r\n\t// @method layerPointToLatLng(point: Point): LatLng\r\n\t// Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),\r\n\t// returns the corresponding geographical coordinate (for the current zoom level).\r\n\tlayerPointToLatLng: function (point) {\r\n\t\tvar projectedPoint = toPoint(point).add(this.getPixelOrigin());\r\n\t\treturn this.unproject(projectedPoint);\r\n\t},\r\n\r\n\t// @method latLngToLayerPoint(latlng: LatLng): Point\r\n\t// Given a geographical coordinate, returns the corresponding pixel coordinate\r\n\t// relative to the [origin pixel](#map-getpixelorigin).\r\n\tlatLngToLayerPoint: function (latlng) {\r\n\t\tvar projectedPoint = this.project(toLatLng(latlng))._round();\r\n\t\treturn projectedPoint._subtract(this.getPixelOrigin());\r\n\t},\r\n\r\n\t// @method wrapLatLng(latlng: LatLng): LatLng\r\n\t// Returns a `LatLng` where `lat` and `lng` has been wrapped according to the\r\n\t// map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the\r\n\t// CRS's bounds.\r\n\t// By default this means longitude is wrapped around the dateline so its\r\n\t// value is between -180 and +180 degrees.\r\n\twrapLatLng: function (latlng) {\r\n\t\treturn this.options.crs.wrapLatLng(toLatLng(latlng));\r\n\t},\r\n\r\n\t// @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds\r\n\t// Returns a `LatLngBounds` with the same size as the given one, ensuring that\r\n\t// its center is within the CRS's bounds.\r\n\t// By default this means the center longitude is wrapped around the dateline so its\r\n\t// value is between -180 and +180 degrees, and the majority of the bounds\r\n\t// overlaps the CRS's bounds.\r\n\twrapLatLngBounds: function (latlng) {\r\n\t\treturn this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));\r\n\t},\r\n\r\n\t// @method distance(latlng1: LatLng, latlng2: LatLng): Number\r\n\t// Returns the distance between two geographical coordinates according to\r\n\t// the map's CRS. By default this measures distance in meters.\r\n\tdistance: function (latlng1, latlng2) {\r\n\t\treturn this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));\r\n\t},\r\n\r\n\t// @method containerPointToLayerPoint(point: Point): Point\r\n\t// Given a pixel coordinate relative to the map container, returns the corresponding\r\n\t// pixel coordinate relative to the [origin pixel](#map-getpixelorigin).\r\n\tcontainerPointToLayerPoint: function (point) { // (Point)\r\n\t\treturn toPoint(point).subtract(this._getMapPanePos());\r\n\t},\r\n\r\n\t// @method layerPointToContainerPoint(point: Point): Point\r\n\t// Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),\r\n\t// returns the corresponding pixel coordinate relative to the map container.\r\n\tlayerPointToContainerPoint: function (point) { // (Point)\r\n\t\treturn toPoint(point).add(this._getMapPanePos());\r\n\t},\r\n\r\n\t// @method containerPointToLatLng(point: Point): LatLng\r\n\t// Given a pixel coordinate relative to the map container, returns\r\n\t// the corresponding geographical coordinate (for the current zoom level).\r\n\tcontainerPointToLatLng: function (point) {\r\n\t\tvar layerPoint = this.containerPointToLayerPoint(toPoint(point));\r\n\t\treturn this.layerPointToLatLng(layerPoint);\r\n\t},\r\n\r\n\t// @method latLngToContainerPoint(latlng: LatLng): Point\r\n\t// Given a geographical coordinate, returns the corresponding pixel coordinate\r\n\t// relative to the map container.\r\n\tlatLngToContainerPoint: function (latlng) {\r\n\t\treturn this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));\r\n\t},\r\n\r\n\t// @method mouseEventToContainerPoint(ev: MouseEvent): Point\r\n\t// Given a MouseEvent object, returns the pixel coordinate relative to the\r\n\t// map container where the event took place.\r\n\tmouseEventToContainerPoint: function (e) {\r\n\t\treturn DomEvent.getMousePosition(e, this._container);\r\n\t},\r\n\r\n\t// @method mouseEventToLayerPoint(ev: MouseEvent): Point\r\n\t// Given a MouseEvent object, returns the pixel coordinate relative to\r\n\t// the [origin pixel](#map-getpixelorigin) where the event took place.\r\n\tmouseEventToLayerPoint: function (e) {\r\n\t\treturn this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));\r\n\t},\r\n\r\n\t// @method mouseEventToLatLng(ev: MouseEvent): LatLng\r\n\t// Given a MouseEvent object, returns geographical coordinate where the\r\n\t// event took place.\r\n\tmouseEventToLatLng: function (e) { // (MouseEvent)\r\n\t\treturn this.layerPointToLatLng(this.mouseEventToLayerPoint(e));\r\n\t},\r\n\r\n\r\n\t// map initialization methods\r\n\r\n\t_initContainer: function (id) {\r\n\t\tvar container = this._container = DomUtil.get(id);\r\n\r\n\t\tif (!container) {\r\n\t\t\tthrow new Error('Map container not found.');\r\n\t\t} else if (container._leaflet_id) {\r\n\t\t\tthrow new Error('Map container is already initialized.');\r\n\t\t}\r\n\r\n\t\tDomEvent.on(container, 'scroll', this._onScroll, this);\r\n\t\tthis._containerId = Util.stamp(container);\r\n\t},\r\n\r\n\t_initLayout: function () {\r\n\t\tvar container = this._container;\r\n\r\n\t\tthis._fadeAnimated = this.options.fadeAnimation && Browser.any3d;\r\n\r\n\t\tDomUtil.addClass(container, 'leaflet-container' +\r\n\t\t\t(Browser.touch ? ' leaflet-touch' : '') +\r\n\t\t\t(Browser.retina ? ' leaflet-retina' : '') +\r\n\t\t\t(Browser.ielt9 ? ' leaflet-oldie' : '') +\r\n\t\t\t(Browser.safari ? ' leaflet-safari' : '') +\r\n\t\t\t(this._fadeAnimated ? ' leaflet-fade-anim' : ''));\r\n\r\n\t\tvar position = DomUtil.getStyle(container, 'position');\r\n\r\n\t\tif (position !== 'absolute' && position !== 'relative' && position !== 'fixed' && position !== 'sticky') {\r\n\t\t\tcontainer.style.position = 'relative';\r\n\t\t}\r\n\r\n\t\tthis._initPanes();\r\n\r\n\t\tif (this._initControlPos) {\r\n\t\t\tthis._initControlPos();\r\n\t\t}\r\n\t},\r\n\r\n\t_initPanes: function () {\r\n\t\tvar panes = this._panes = {};\r\n\t\tthis._paneRenderers = {};\r\n\r\n\t\t// @section\r\n\t\t//\r\n\t\t// Panes are DOM elements used to control the ordering of layers on the map. You\r\n\t\t// can access panes with [`map.getPane`](#map-getpane) or\r\n\t\t// [`map.getPanes`](#map-getpanes) methods. New panes can be created with the\r\n\t\t// [`map.createPane`](#map-createpane) method.\r\n\t\t//\r\n\t\t// Every map has the following default panes that differ only in zIndex.\r\n\t\t//\r\n\t\t// @pane mapPane: HTMLElement = 'auto'\r\n\t\t// Pane that contains all other map panes\r\n\r\n\t\tthis._mapPane = this.createPane('mapPane', this._container);\r\n\t\tDomUtil.setPosition(this._mapPane, new Point(0, 0));\r\n\r\n\t\t// @pane tilePane: HTMLElement = 200\r\n\t\t// Pane for `GridLayer`s and `TileLayer`s\r\n\t\tthis.createPane('tilePane');\r\n\t\t// @pane overlayPane: HTMLElement = 400\r\n\t\t// Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s\r\n\t\tthis.createPane('overlayPane');\r\n\t\t// @pane shadowPane: HTMLElement = 500\r\n\t\t// Pane for overlay shadows (e.g. `Marker` shadows)\r\n\t\tthis.createPane('shadowPane');\r\n\t\t// @pane markerPane: HTMLElement = 600\r\n\t\t// Pane for `Icon`s of `Marker`s\r\n\t\tthis.createPane('markerPane');\r\n\t\t// @pane tooltipPane: HTMLElement = 650\r\n\t\t// Pane for `Tooltip`s.\r\n\t\tthis.createPane('tooltipPane');\r\n\t\t// @pane popupPane: HTMLElement = 700\r\n\t\t// Pane for `Popup`s.\r\n\t\tthis.createPane('popupPane');\r\n\r\n\t\tif (!this.options.markerZoomAnimation) {\r\n\t\t\tDomUtil.addClass(panes.markerPane, 'leaflet-zoom-hide');\r\n\t\t\tDomUtil.addClass(panes.shadowPane, 'leaflet-zoom-hide');\r\n\t\t}\r\n\t},\r\n\r\n\r\n\t// private methods that modify map state\r\n\r\n\t// @section Map state change events\r\n\t_resetView: function (center, zoom, noMoveStart) {\r\n\t\tDomUtil.setPosition(this._mapPane, new Point(0, 0));\r\n\r\n\t\tvar loading = !this._loaded;\r\n\t\tthis._loaded = true;\r\n\t\tzoom = this._limitZoom(zoom);\r\n\r\n\t\tthis.fire('viewprereset');\r\n\r\n\t\tvar zoomChanged = this._zoom !== zoom;\r\n\t\tthis\r\n\t\t\t._moveStart(zoomChanged, noMoveStart)\r\n\t\t\t._move(center, zoom)\r\n\t\t\t._moveEnd(zoomChanged);\r\n\r\n\t\t// @event viewreset: Event\r\n\t\t// Fired when the map needs to redraw its content (this usually happens\r\n\t\t// on map zoom or load). Very useful for creating custom overlays.\r\n\t\tthis.fire('viewreset');\r\n\r\n\t\t// @event load: Event\r\n\t\t// Fired when the map is initialized (when its center and zoom are set\r\n\t\t// for the first time).\r\n\t\tif (loading) {\r\n\t\t\tthis.fire('load');\r\n\t\t}\r\n\t},\r\n\r\n\t_moveStart: function (zoomChanged, noMoveStart) {\r\n\t\t// @event zoomstart: Event\r\n\t\t// Fired when the map zoom is about to change (e.g. before zoom animation).\r\n\t\t// @event movestart: Event\r\n\t\t// Fired when the view of the map starts changing (e.g. user starts dragging the map).\r\n\t\tif (zoomChanged) {\r\n\t\t\tthis.fire('zoomstart');\r\n\t\t}\r\n\t\tif (!noMoveStart) {\r\n\t\t\tthis.fire('movestart');\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_move: function (center, zoom, data, supressEvent) {\r\n\t\tif (zoom === undefined) {\r\n\t\t\tzoom = this._zoom;\r\n\t\t}\r\n\t\tvar zoomChanged = this._zoom !== zoom;\r\n\r\n\t\tthis._zoom = zoom;\r\n\t\tthis._lastCenter = center;\r\n\t\tthis._pixelOrigin = this._getNewPixelOrigin(center);\r\n\r\n\t\tif (!supressEvent) {\r\n\t\t\t// @event zoom: Event\r\n\t\t\t// Fired repeatedly during any change in zoom level,\r\n\t\t\t// including zoom and fly animations.\r\n\t\t\tif (zoomChanged || (data && data.pinch)) {\t// Always fire 'zoom' if pinching because #3530\r\n\t\t\t\tthis.fire('zoom', data);\r\n\t\t\t}\r\n\r\n\t\t\t// @event move: Event\r\n\t\t\t// Fired repeatedly during any movement of the map,\r\n\t\t\t// including pan and fly animations.\r\n\t\t\tthis.fire('move', data);\r\n\t\t} else if (data && data.pinch) {\t// Always fire 'zoom' if pinching because #3530\r\n\t\t\tthis.fire('zoom', data);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_moveEnd: function (zoomChanged) {\r\n\t\t// @event zoomend: Event\r\n\t\t// Fired when the map zoom changed, after any animations.\r\n\t\tif (zoomChanged) {\r\n\t\t\tthis.fire('zoomend');\r\n\t\t}\r\n\r\n\t\t// @event moveend: Event\r\n\t\t// Fired when the center of the map stops changing\r\n\t\t// (e.g. user stopped dragging the map or after non-centered zoom).\r\n\t\treturn this.fire('moveend');\r\n\t},\r\n\r\n\t_stop: function () {\r\n\t\tUtil.cancelAnimFrame(this._flyToFrame);\r\n\t\tif (this._panAnim) {\r\n\t\t\tthis._panAnim.stop();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_rawPanBy: function (offset) {\r\n\t\tDomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));\r\n\t},\r\n\r\n\t_getZoomSpan: function () {\r\n\t\treturn this.getMaxZoom() - this.getMinZoom();\r\n\t},\r\n\r\n\t_panInsideMaxBounds: function () {\r\n\t\tif (!this._enforcingBounds) {\r\n\t\t\tthis.panInsideBounds(this.options.maxBounds);\r\n\t\t}\r\n\t},\r\n\r\n\t_checkIfLoaded: function () {\r\n\t\tif (!this._loaded) {\r\n\t\t\tthrow new Error('Set map center and zoom first.');\r\n\t\t}\r\n\t},\r\n\r\n\t// DOM event handling\r\n\r\n\t// @section Interaction events\r\n\t_initEvents: function (remove) {\r\n\t\tthis._targets = {};\r\n\t\tthis._targets[Util.stamp(this._container)] = this;\r\n\r\n\t\tvar onOff = remove ? DomEvent.off : DomEvent.on;\r\n\r\n\t\t// @event click: MouseEvent\r\n\t\t// Fired when the user clicks (or taps) the map.\r\n\t\t// @event dblclick: MouseEvent\r\n\t\t// Fired when the user double-clicks (or double-taps) the map.\r\n\t\t// @event mousedown: MouseEvent\r\n\t\t// Fired when the user pushes the mouse button on the map.\r\n\t\t// @event mouseup: MouseEvent\r\n\t\t// Fired when the user releases the mouse button on the map.\r\n\t\t// @event mouseover: MouseEvent\r\n\t\t// Fired when the mouse enters the map.\r\n\t\t// @event mouseout: MouseEvent\r\n\t\t// Fired when the mouse leaves the map.\r\n\t\t// @event mousemove: MouseEvent\r\n\t\t// Fired while the mouse moves over the map.\r\n\t\t// @event contextmenu: MouseEvent\r\n\t\t// Fired when the user pushes the right mouse button on the map, prevents\r\n\t\t// default browser context menu from showing if there are listeners on\r\n\t\t// this event. Also fired on mobile when the user holds a single touch\r\n\t\t// for a second (also called long press).\r\n\t\t// @event keypress: KeyboardEvent\r\n\t\t// Fired when the user presses a key from the keyboard that produces a character value while the map is focused.\r\n\t\t// @event keydown: KeyboardEvent\r\n\t\t// Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,\r\n\t\t// the `keydown` event is fired for keys that produce a character value and for keys\r\n\t\t// that do not produce a character value.\r\n\t\t// @event keyup: KeyboardEvent\r\n\t\t// Fired when the user releases a key from the keyboard while the map is focused.\r\n\t\tonOff(this._container, 'click dblclick mousedown mouseup ' +\r\n\t\t\t'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);\r\n\r\n\t\tif (this.options.trackResize) {\r\n\t\t\tonOff(window, 'resize', this._onResize, this);\r\n\t\t}\r\n\r\n\t\tif (Browser.any3d && this.options.transform3DLimit) {\r\n\t\t\t(remove ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);\r\n\t\t}\r\n\t},\r\n\r\n\t_onResize: function () {\r\n\t\tUtil.cancelAnimFrame(this._resizeRequest);\r\n\t\tthis._resizeRequest = Util.requestAnimFrame(\r\n\t\t        function () { this.invalidateSize({debounceMoveend: true}); }, this);\r\n\t},\r\n\r\n\t_onScroll: function () {\r\n\t\tthis._container.scrollTop  = 0;\r\n\t\tthis._container.scrollLeft = 0;\r\n\t},\r\n\r\n\t_onMoveEnd: function () {\r\n\t\tvar pos = this._getMapPanePos();\r\n\t\tif (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {\r\n\t\t\t// https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have\r\n\t\t\t// a pixel offset on very high values, see: https://jsfiddle.net/dg6r5hhb/\r\n\t\t\tthis._resetView(this.getCenter(), this.getZoom());\r\n\t\t}\r\n\t},\r\n\r\n\t_findEventTargets: function (e, type) {\r\n\t\tvar targets = [],\r\n\t\t    target,\r\n\t\t    isHover = type === 'mouseout' || type === 'mouseover',\r\n\t\t    src = e.target || e.srcElement,\r\n\t\t    dragging = false;\r\n\r\n\t\twhile (src) {\r\n\t\t\ttarget = this._targets[Util.stamp(src)];\r\n\t\t\tif (target && (type === 'click' || type === 'preclick') && this._draggableMoved(target)) {\r\n\t\t\t\t// Prevent firing click after you just dragged an object.\r\n\t\t\t\tdragging = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (target && target.listens(type, true)) {\r\n\t\t\t\tif (isHover && !DomEvent.isExternalTarget(src, e)) { break; }\r\n\t\t\t\ttargets.push(target);\r\n\t\t\t\tif (isHover) { break; }\r\n\t\t\t}\r\n\t\t\tif (src === this._container) { break; }\r\n\t\t\tsrc = src.parentNode;\r\n\t\t}\r\n\t\tif (!targets.length && !dragging && !isHover && this.listens(type, true)) {\r\n\t\t\ttargets = [this];\r\n\t\t}\r\n\t\treturn targets;\r\n\t},\r\n\r\n\t_isClickDisabled: function (el) {\r\n\t\twhile (el && el !== this._container) {\r\n\t\t\tif (el['_leaflet_disable_click']) { return true; }\r\n\t\t\tel = el.parentNode;\r\n\t\t}\r\n\t},\r\n\r\n\t_handleDOMEvent: function (e) {\r\n\t\tvar el = (e.target || e.srcElement);\r\n\t\tif (!this._loaded || el['_leaflet_disable_events'] || e.type === 'click' && this._isClickDisabled(el)) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar type = e.type;\r\n\r\n\t\tif (type === 'mousedown') {\r\n\t\t\t// prevents outline when clicking on keyboard-focusable element\r\n\t\t\tDomUtil.preventOutline(el);\r\n\t\t}\r\n\r\n\t\tthis._fireDOMEvent(e, type);\r\n\t},\r\n\r\n\t_mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],\r\n\r\n\t_fireDOMEvent: function (e, type, canvasTargets) {\r\n\r\n\t\tif (e.type === 'click') {\r\n\t\t\t// Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).\r\n\t\t\t// @event preclick: MouseEvent\r\n\t\t\t// Fired before mouse click on the map (sometimes useful when you\r\n\t\t\t// want something to happen on click before any existing click\r\n\t\t\t// handlers start running).\r\n\t\t\tvar synth = Util.extend({}, e);\r\n\t\t\tsynth.type = 'preclick';\r\n\t\t\tthis._fireDOMEvent(synth, synth.type, canvasTargets);\r\n\t\t}\r\n\r\n\t\t// Find the layer the event is propagating from and its parents.\r\n\t\tvar targets = this._findEventTargets(e, type);\r\n\r\n\t\tif (canvasTargets) {\r\n\t\t\tvar filtered = []; // pick only targets with listeners\r\n\t\t\tfor (var i = 0; i < canvasTargets.length; i++) {\r\n\t\t\t\tif (canvasTargets[i].listens(type, true)) {\r\n\t\t\t\t\tfiltered.push(canvasTargets[i]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttargets = filtered.concat(targets);\r\n\t\t}\r\n\r\n\t\tif (!targets.length) { return; }\r\n\r\n\t\tif (type === 'contextmenu') {\r\n\t\t\tDomEvent.preventDefault(e);\r\n\t\t}\r\n\r\n\t\tvar target = targets[0];\r\n\t\tvar data = {\r\n\t\t\toriginalEvent: e\r\n\t\t};\r\n\r\n\t\tif (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {\r\n\t\t\tvar isMarker = target.getLatLng && (!target._radius || target._radius <= 10);\r\n\t\t\tdata.containerPoint = isMarker ?\r\n\t\t\t\tthis.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);\r\n\t\t\tdata.layerPoint = this.containerPointToLayerPoint(data.containerPoint);\r\n\t\t\tdata.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);\r\n\t\t}\r\n\r\n\t\tfor (i = 0; i < targets.length; i++) {\r\n\t\t\ttargets[i].fire(type, data, true);\r\n\t\t\tif (data.originalEvent._stopped ||\r\n\t\t\t\t(targets[i].options.bubblingMouseEvents === false && Util.indexOf(this._mouseEvents, type) !== -1)) { return; }\r\n\t\t}\r\n\t},\r\n\r\n\t_draggableMoved: function (obj) {\r\n\t\tobj = obj.dragging && obj.dragging.enabled() ? obj : this;\r\n\t\treturn (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());\r\n\t},\r\n\r\n\t_clearHandlers: function () {\r\n\t\tfor (var i = 0, len = this._handlers.length; i < len; i++) {\r\n\t\t\tthis._handlers[i].disable();\r\n\t\t}\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\r\n\t// @method whenReady(fn: Function, context?: Object): this\r\n\t// Runs the given function `fn` when the map gets initialized with\r\n\t// a view (center and zoom) and at least one layer, or immediately\r\n\t// if it's already initialized, optionally passing a function context.\r\n\twhenReady: function (callback, context) {\r\n\t\tif (this._loaded) {\r\n\t\t\tcallback.call(context || this, {target: this});\r\n\t\t} else {\r\n\t\t\tthis.on('load', callback, context);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\r\n\t// private methods for getting map state\r\n\r\n\t_getMapPanePos: function () {\r\n\t\treturn DomUtil.getPosition(this._mapPane) || new Point(0, 0);\r\n\t},\r\n\r\n\t_moved: function () {\r\n\t\tvar pos = this._getMapPanePos();\r\n\t\treturn pos && !pos.equals([0, 0]);\r\n\t},\r\n\r\n\t_getTopLeftPoint: function (center, zoom) {\r\n\t\tvar pixelOrigin = center && zoom !== undefined ?\r\n\t\t\tthis._getNewPixelOrigin(center, zoom) :\r\n\t\t\tthis.getPixelOrigin();\r\n\t\treturn pixelOrigin.subtract(this._getMapPanePos());\r\n\t},\r\n\r\n\t_getNewPixelOrigin: function (center, zoom) {\r\n\t\tvar viewHalf = this.getSize()._divideBy(2);\r\n\t\treturn this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();\r\n\t},\r\n\r\n\t_latLngToNewLayerPoint: function (latlng, zoom, center) {\r\n\t\tvar topLeft = this._getNewPixelOrigin(center, zoom);\r\n\t\treturn this.project(latlng, zoom)._subtract(topLeft);\r\n\t},\r\n\r\n\t_latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {\r\n\t\tvar topLeft = this._getNewPixelOrigin(center, zoom);\r\n\t\treturn toBounds([\r\n\t\t\tthis.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)\r\n\t\t]);\r\n\t},\r\n\r\n\t// layer point of the current center\r\n\t_getCenterLayerPoint: function () {\r\n\t\treturn this.containerPointToLayerPoint(this.getSize()._divideBy(2));\r\n\t},\r\n\r\n\t// offset of the specified place to the current center in pixels\r\n\t_getCenterOffset: function (latlng) {\r\n\t\treturn this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());\r\n\t},\r\n\r\n\t// adjust center for view to get inside bounds\r\n\t_limitCenter: function (center, zoom, bounds) {\r\n\r\n\t\tif (!bounds) { return center; }\r\n\r\n\t\tvar centerPoint = this.project(center, zoom),\r\n\t\t    viewHalf = this.getSize().divideBy(2),\r\n\t\t    viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),\r\n\t\t    offset = this._getBoundsOffset(viewBounds, bounds, zoom);\r\n\r\n\t\t// If offset is less than a pixel, ignore.\r\n\t\t// This prevents unstable projections from getting into\r\n\t\t// an infinite loop of tiny offsets.\r\n\t\tif (Math.abs(offset.x) <= 1 && Math.abs(offset.y) <= 1) {\r\n\t\t\treturn center;\r\n\t\t}\r\n\r\n\t\treturn this.unproject(centerPoint.add(offset), zoom);\r\n\t},\r\n\r\n\t// adjust offset for view to get inside bounds\r\n\t_limitOffset: function (offset, bounds) {\r\n\t\tif (!bounds) { return offset; }\r\n\r\n\t\tvar viewBounds = this.getPixelBounds(),\r\n\t\t    newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));\r\n\r\n\t\treturn offset.add(this._getBoundsOffset(newBounds, bounds));\r\n\t},\r\n\r\n\t// returns offset needed for pxBounds to get inside maxBounds at a specified zoom\r\n\t_getBoundsOffset: function (pxBounds, maxBounds, zoom) {\r\n\t\tvar projectedMaxBounds = toBounds(\r\n\t\t        this.project(maxBounds.getNorthEast(), zoom),\r\n\t\t        this.project(maxBounds.getSouthWest(), zoom)\r\n\t\t    ),\r\n\t\t    minOffset = projectedMaxBounds.min.subtract(pxBounds.min),\r\n\t\t    maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),\r\n\r\n\t\t    dx = this._rebound(minOffset.x, -maxOffset.x),\r\n\t\t    dy = this._rebound(minOffset.y, -maxOffset.y);\r\n\r\n\t\treturn new Point(dx, dy);\r\n\t},\r\n\r\n\t_rebound: function (left, right) {\r\n\t\treturn left + right > 0 ?\r\n\t\t\tMath.round(left - right) / 2 :\r\n\t\t\tMath.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));\r\n\t},\r\n\r\n\t_limitZoom: function (zoom) {\r\n\t\tvar min = this.getMinZoom(),\r\n\t\t    max = this.getMaxZoom(),\r\n\t\t    snap = Browser.any3d ? this.options.zoomSnap : 1;\r\n\t\tif (snap) {\r\n\t\t\tzoom = Math.round(zoom / snap) * snap;\r\n\t\t}\r\n\t\treturn Math.max(min, Math.min(max, zoom));\r\n\t},\r\n\r\n\t_onPanTransitionStep: function () {\r\n\t\tthis.fire('move');\r\n\t},\r\n\r\n\t_onPanTransitionEnd: function () {\r\n\t\tDomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');\r\n\t\tthis.fire('moveend');\r\n\t},\r\n\r\n\t_tryAnimatedPan: function (center, options) {\r\n\t\t// difference between the new and current centers in pixels\r\n\t\tvar offset = this._getCenterOffset(center)._trunc();\r\n\r\n\t\t// don't animate too far unless animate: true specified in options\r\n\t\tif ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }\r\n\r\n\t\tthis.panBy(offset, options);\r\n\r\n\t\treturn true;\r\n\t},\r\n\r\n\t_createAnimProxy: function () {\r\n\r\n\t\tvar proxy = this._proxy = DomUtil.create('div', 'leaflet-proxy leaflet-zoom-animated');\r\n\t\tthis._panes.mapPane.appendChild(proxy);\r\n\r\n\t\tthis.on('zoomanim', function (e) {\r\n\t\t\tvar prop = DomUtil.TRANSFORM,\r\n\t\t\t    transform = this._proxy.style[prop];\r\n\r\n\t\t\tDomUtil.setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));\r\n\r\n\t\t\t// workaround for case when transform is the same and so transitionend event is not fired\r\n\t\t\tif (transform === this._proxy.style[prop] && this._animatingZoom) {\r\n\t\t\t\tthis._onZoomTransitionEnd();\r\n\t\t\t}\r\n\t\t}, this);\r\n\r\n\t\tthis.on('load moveend', this._animMoveEnd, this);\r\n\r\n\t\tthis._on('unload', this._destroyAnimProxy, this);\r\n\t},\r\n\r\n\t_destroyAnimProxy: function () {\r\n\t\tDomUtil.remove(this._proxy);\r\n\t\tthis.off('load moveend', this._animMoveEnd, this);\r\n\t\tdelete this._proxy;\r\n\t},\r\n\r\n\t_animMoveEnd: function () {\r\n\t\tvar c = this.getCenter(),\r\n\t\t    z = this.getZoom();\r\n\t\tDomUtil.setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));\r\n\t},\r\n\r\n\t_catchTransitionEnd: function (e) {\r\n\t\tif (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {\r\n\t\t\tthis._onZoomTransitionEnd();\r\n\t\t}\r\n\t},\r\n\r\n\t_nothingToAnimate: function () {\r\n\t\treturn !this._container.getElementsByClassName('leaflet-zoom-animated').length;\r\n\t},\r\n\r\n\t_tryAnimatedZoom: function (center, zoom, options) {\r\n\r\n\t\tif (this._animatingZoom) { return true; }\r\n\r\n\t\toptions = options || {};\r\n\r\n\t\t// don't animate if disabled, not supported or zoom difference is too large\r\n\t\tif (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||\r\n\t\t        Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }\r\n\r\n\t\t// offset is the pixel coords of the zoom origin relative to the current center\r\n\t\tvar scale = this.getZoomScale(zoom),\r\n\t\t    offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);\r\n\r\n\t\t// don't animate if the zoom origin isn't within one screen from the current center, unless forced\r\n\t\tif (options.animate !== true && !this.getSize().contains(offset)) { return false; }\r\n\r\n\t\tUtil.requestAnimFrame(function () {\r\n\t\t\tthis\r\n\t\t\t    ._moveStart(true, options.noMoveStart || false)\r\n\t\t\t    ._animateZoom(center, zoom, true);\r\n\t\t}, this);\r\n\r\n\t\treturn true;\r\n\t},\r\n\r\n\t_animateZoom: function (center, zoom, startAnim, noUpdate) {\r\n\t\tif (!this._mapPane) { return; }\r\n\r\n\t\tif (startAnim) {\r\n\t\t\tthis._animatingZoom = true;\r\n\r\n\t\t\t// remember what center/zoom to set after animation\r\n\t\t\tthis._animateToCenter = center;\r\n\t\t\tthis._animateToZoom = zoom;\r\n\r\n\t\t\tDomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');\r\n\t\t}\r\n\r\n\t\t// @section Other Events\r\n\t\t// @event zoomanim: ZoomAnimEvent\r\n\t\t// Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.\r\n\t\tthis.fire('zoomanim', {\r\n\t\t\tcenter: center,\r\n\t\t\tzoom: zoom,\r\n\t\t\tnoUpdate: noUpdate\r\n\t\t});\r\n\r\n\t\tif (!this._tempFireZoomEvent) {\r\n\t\t\tthis._tempFireZoomEvent = this._zoom !== this._animateToZoom;\r\n\t\t}\r\n\r\n\t\tthis._move(this._animateToCenter, this._animateToZoom, undefined, true);\r\n\r\n\t\t// Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693\r\n\t\tsetTimeout(Util.bind(this._onZoomTransitionEnd, this), 250);\r\n\t},\r\n\r\n\t_onZoomTransitionEnd: function () {\r\n\t\tif (!this._animatingZoom) { return; }\r\n\r\n\t\tif (this._mapPane) {\r\n\t\t\tDomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');\r\n\t\t}\r\n\r\n\t\tthis._animatingZoom = false;\r\n\r\n\t\tthis._move(this._animateToCenter, this._animateToZoom, undefined, true);\r\n\r\n\t\tif (this._tempFireZoomEvent) {\r\n\t\t\tthis.fire('zoom');\r\n\t\t}\r\n\t\tdelete this._tempFireZoomEvent;\r\n\r\n\t\tthis.fire('move');\r\n\r\n\t\tthis._moveEnd(true);\r\n\t}\r\n});\r\n\r\n// @section\r\n\r\n// @factory L.map(id: String, options?: Map options)\r\n// Instantiates a map object given the DOM ID of a `<div>` element\r\n// and optionally an object literal with `Map options`.\r\n//\r\n// @alternative\r\n// @factory L.map(el: HTMLElement, options?: Map options)\r\n// Instantiates a map object given an instance of a `<div>` HTML element\r\n// and optionally an object literal with `Map options`.\r\nexport function createMap(id, options) {\r\n\treturn new Map(id, options);\r\n}\r\n","\r\nimport {Class} from '../core/Class';\r\nimport {Map} from '../map/Map';\r\nimport * as Util from '../core/Util';\r\nimport * as DomUtil from '../dom/DomUtil';\r\n\r\n/*\r\n * @class Control\r\n * @aka L.Control\r\n * @inherits Class\r\n *\r\n * L.Control is a base class for implementing map controls. Handles positioning.\r\n * All other controls extend from this class.\r\n */\r\n\r\nexport var Control = Class.extend({\r\n\t// @section\r\n\t// @aka Control Options\r\n\toptions: {\r\n\t\t// @option position: String = 'topright'\r\n\t\t// The position of the control (one of the map corners). Possible values are `'topleft'`,\r\n\t\t// `'topright'`, `'bottomleft'` or `'bottomright'`\r\n\t\tposition: 'topright'\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tUtil.setOptions(this, options);\r\n\t},\r\n\r\n\t/* @section\r\n\t * Classes extending L.Control will inherit the following methods:\r\n\t *\r\n\t * @method getPosition: string\r\n\t * Returns the position of the control.\r\n\t */\r\n\tgetPosition: function () {\r\n\t\treturn this.options.position;\r\n\t},\r\n\r\n\t// @method setPosition(position: string): this\r\n\t// Sets the position of the control.\r\n\tsetPosition: function (position) {\r\n\t\tvar map = this._map;\r\n\r\n\t\tif (map) {\r\n\t\t\tmap.removeControl(this);\r\n\t\t}\r\n\r\n\t\tthis.options.position = position;\r\n\r\n\t\tif (map) {\r\n\t\t\tmap.addControl(this);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getContainer: HTMLElement\r\n\t// Returns the HTMLElement that contains the control.\r\n\tgetContainer: function () {\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\t// @method addTo(map: Map): this\r\n\t// Adds the control to the given map.\r\n\taddTo: function (map) {\r\n\t\tthis.remove();\r\n\t\tthis._map = map;\r\n\r\n\t\tvar container = this._container = this.onAdd(map),\r\n\t\t    pos = this.getPosition(),\r\n\t\t    corner = map._controlCorners[pos];\r\n\r\n\t\tDomUtil.addClass(container, 'leaflet-control');\r\n\r\n\t\tif (pos.indexOf('bottom') !== -1) {\r\n\t\t\tcorner.insertBefore(container, corner.firstChild);\r\n\t\t} else {\r\n\t\t\tcorner.appendChild(container);\r\n\t\t}\r\n\r\n\t\tthis._map.on('unload', this.remove, this);\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method remove: this\r\n\t// Removes the control from the map it is currently active on.\r\n\tremove: function () {\r\n\t\tif (!this._map) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tDomUtil.remove(this._container);\r\n\r\n\t\tif (this.onRemove) {\r\n\t\t\tthis.onRemove(this._map);\r\n\t\t}\r\n\r\n\t\tthis._map.off('unload', this.remove, this);\r\n\t\tthis._map = null;\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_refocusOnMap: function (e) {\r\n\t\t// if map exists and event is not a keyboard event\r\n\t\tif (this._map && e && e.screenX > 0 && e.screenY > 0) {\r\n\t\t\tthis._map.getContainer().focus();\r\n\t\t}\r\n\t}\r\n});\r\n\r\nexport var control = function (options) {\r\n\treturn new Control(options);\r\n};\r\n\r\n/* @section Extension methods\r\n * @uninheritable\r\n *\r\n * Every control should extend from `L.Control` and (re-)implement the following methods.\r\n *\r\n * @method onAdd(map: Map): HTMLElement\r\n * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).\r\n *\r\n * @method onRemove(map: Map)\r\n * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).\r\n */\r\n\r\n/* @namespace Map\r\n * @section Methods for Layers and Controls\r\n */\r\nMap.include({\r\n\t// @method addControl(control: Control): this\r\n\t// Adds the given control to the map\r\n\taddControl: function (control) {\r\n\t\tcontrol.addTo(this);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeControl(control: Control): this\r\n\t// Removes the given control from the map\r\n\tremoveControl: function (control) {\r\n\t\tcontrol.remove();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initControlPos: function () {\r\n\t\tvar corners = this._controlCorners = {},\r\n\t\t    l = 'leaflet-',\r\n\t\t    container = this._controlContainer =\r\n\t\t            DomUtil.create('div', l + 'control-container', this._container);\r\n\r\n\t\tfunction createCorner(vSide, hSide) {\r\n\t\t\tvar className = l + vSide + ' ' + l + hSide;\r\n\r\n\t\t\tcorners[vSide + hSide] = DomUtil.create('div', className, container);\r\n\t\t}\r\n\r\n\t\tcreateCorner('top', 'left');\r\n\t\tcreateCorner('top', 'right');\r\n\t\tcreateCorner('bottom', 'left');\r\n\t\tcreateCorner('bottom', 'right');\r\n\t},\r\n\r\n\t_clearControlPos: function () {\r\n\t\tfor (var i in this._controlCorners) {\r\n\t\t\tDomUtil.remove(this._controlCorners[i]);\r\n\t\t}\r\n\t\tDomUtil.remove(this._controlContainer);\r\n\t\tdelete this._controlCorners;\r\n\t\tdelete this._controlContainer;\r\n\t}\r\n});\r\n","\r\nimport {Control} from './Control';\r\nimport * as Util from '../core/Util';\r\nimport * as DomEvent from '../dom/DomEvent';\r\nimport * as DomUtil from '../dom/DomUtil';\r\n\r\n/*\r\n * @class Control.Layers\r\n * @aka L.Control.Layers\r\n * @inherits Control\r\n *\r\n * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](https://leafletjs.com/examples/layers-control/)). Extends `Control`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var baseLayers = {\r\n * \t\"Mapbox\": mapbox,\r\n * \t\"OpenStreetMap\": osm\r\n * };\r\n *\r\n * var overlays = {\r\n * \t\"Marker\": marker,\r\n * \t\"Roads\": roadsLayer\r\n * };\r\n *\r\n * L.control.layers(baseLayers, overlays).addTo(map);\r\n * ```\r\n *\r\n * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:\r\n *\r\n * ```js\r\n * {\r\n *     \"<someName1>\": layer1,\r\n *     \"<someName2>\": layer2\r\n * }\r\n * ```\r\n *\r\n * The layer names can contain HTML, which allows you to add additional styling to the items:\r\n *\r\n * ```js\r\n * {\"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>\": myLayer}\r\n * ```\r\n */\r\n\r\nexport var Layers = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Layers options\r\n\toptions: {\r\n\t\t// @option collapsed: Boolean = true\r\n\t\t// If `true`, the control will be collapsed into an icon and expanded on mouse hover, touch, or keyboard activation.\r\n\t\tcollapsed: true,\r\n\t\tposition: 'topright',\r\n\r\n\t\t// @option autoZIndex: Boolean = true\r\n\t\t// If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.\r\n\t\tautoZIndex: true,\r\n\r\n\t\t// @option hideSingleBase: Boolean = false\r\n\t\t// If `true`, the base layers in the control will be hidden when there is only one.\r\n\t\thideSingleBase: false,\r\n\r\n\t\t// @option sortLayers: Boolean = false\r\n\t\t// Whether to sort the layers. When `false`, layers will keep the order\r\n\t\t// in which they were added to the control.\r\n\t\tsortLayers: false,\r\n\r\n\t\t// @option sortFunction: Function = *\r\n\t\t// A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)\r\n\t\t// that will be used for sorting the layers, when `sortLayers` is `true`.\r\n\t\t// The function receives both the `L.Layer` instances and their names, as in\r\n\t\t// `sortFunction(layerA, layerB, nameA, nameB)`.\r\n\t\t// By default, it sorts layers alphabetically by their name.\r\n\t\tsortFunction: function (layerA, layerB, nameA, nameB) {\r\n\t\t\treturn nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);\r\n\t\t}\r\n\t},\r\n\r\n\tinitialize: function (baseLayers, overlays, options) {\r\n\t\tUtil.setOptions(this, options);\r\n\r\n\t\tthis._layerControlInputs = [];\r\n\t\tthis._layers = [];\r\n\t\tthis._lastZIndex = 0;\r\n\t\tthis._handlingClick = false;\r\n\t\tthis._preventClick = false;\r\n\r\n\t\tfor (var i in baseLayers) {\r\n\t\t\tthis._addLayer(baseLayers[i], i);\r\n\t\t}\r\n\r\n\t\tfor (i in overlays) {\r\n\t\t\tthis._addLayer(overlays[i], i, true);\r\n\t\t}\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis._initLayout();\r\n\t\tthis._update();\r\n\r\n\t\tthis._map = map;\r\n\t\tmap.on('zoomend', this._checkDisabledLayers, this);\r\n\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\t\t\tthis._layers[i].layer.on('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\taddTo: function (map) {\r\n\t\tControl.prototype.addTo.call(this, map);\r\n\t\t// Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.\r\n\t\treturn this._expandIfNotCollapsed();\r\n\t},\r\n\r\n\tonRemove: function () {\r\n\t\tthis._map.off('zoomend', this._checkDisabledLayers, this);\r\n\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\t\t\tthis._layers[i].layer.off('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addBaseLayer(layer: Layer, name: String): this\r\n\t// Adds a base layer (radio button entry) with the given name to the control.\r\n\taddBaseLayer: function (layer, name) {\r\n\t\tthis._addLayer(layer, name);\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method addOverlay(layer: Layer, name: String): this\r\n\t// Adds an overlay (checkbox entry) with the given name to the control.\r\n\taddOverlay: function (layer, name) {\r\n\t\tthis._addLayer(layer, name, true);\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method removeLayer(layer: Layer): this\r\n\t// Remove the given layer from the control.\r\n\tremoveLayer: function (layer) {\r\n\t\tlayer.off('add remove', this._onLayerChange, this);\r\n\r\n\t\tvar obj = this._getLayer(Util.stamp(layer));\r\n\t\tif (obj) {\r\n\t\t\tthis._layers.splice(this._layers.indexOf(obj), 1);\r\n\t\t}\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method expand(): this\r\n\t// Expand the control container if collapsed.\r\n\texpand: function () {\r\n\t\tDomUtil.addClass(this._container, 'leaflet-control-layers-expanded');\r\n\t\tthis._section.style.height = null;\r\n\t\tvar acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);\r\n\t\tif (acceptableHeight < this._section.clientHeight) {\r\n\t\t\tDomUtil.addClass(this._section, 'leaflet-control-layers-scrollbar');\r\n\t\t\tthis._section.style.height = acceptableHeight + 'px';\r\n\t\t} else {\r\n\t\t\tDomUtil.removeClass(this._section, 'leaflet-control-layers-scrollbar');\r\n\t\t}\r\n\t\tthis._checkDisabledLayers();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method collapse(): this\r\n\t// Collapse the control container if expanded.\r\n\tcollapse: function () {\r\n\t\tDomUtil.removeClass(this._container, 'leaflet-control-layers-expanded');\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initLayout: function () {\r\n\t\tvar className = 'leaflet-control-layers',\r\n\t\t    container = this._container = DomUtil.create('div', className),\r\n\t\t    collapsed = this.options.collapsed;\r\n\r\n\t\t// makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released\r\n\t\tcontainer.setAttribute('aria-haspopup', true);\r\n\r\n\t\tDomEvent.disableClickPropagation(container);\r\n\t\tDomEvent.disableScrollPropagation(container);\r\n\r\n\t\tvar section = this._section = DomUtil.create('section', className + '-list');\r\n\r\n\t\tif (collapsed) {\r\n\t\t\tthis._map.on('click', this.collapse, this);\r\n\r\n\t\t\tDomEvent.on(container, {\r\n\t\t\t\tmouseenter: this._expandSafely,\r\n\t\t\t\tmouseleave: this.collapse\r\n\t\t\t}, this);\r\n\t\t}\r\n\r\n\t\tvar link = this._layersLink = DomUtil.create('a', className + '-toggle', container);\r\n\t\tlink.href = '#';\r\n\t\tlink.title = 'Layers';\r\n\t\tlink.setAttribute('role', 'button');\r\n\r\n\t\tDomEvent.on(link, {\r\n\t\t\tkeydown: function (e) {\r\n\t\t\t\tif (e.keyCode === 13) {\r\n\t\t\t\t\tthis._expandSafely();\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\t// Certain screen readers intercept the key event and instead send a click event\r\n\t\t\tclick: function (e) {\r\n\t\t\t\tDomEvent.preventDefault(e);\r\n\t\t\t\tthis._expandSafely();\r\n\t\t\t}\r\n\t\t}, this);\r\n\r\n\t\tif (!collapsed) {\r\n\t\t\tthis.expand();\r\n\t\t}\r\n\r\n\t\tthis._baseLayersList = DomUtil.create('div', className + '-base', section);\r\n\t\tthis._separator = DomUtil.create('div', className + '-separator', section);\r\n\t\tthis._overlaysList = DomUtil.create('div', className + '-overlays', section);\r\n\r\n\t\tcontainer.appendChild(section);\r\n\t},\r\n\r\n\t_getLayer: function (id) {\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\r\n\t\t\tif (this._layers[i] && Util.stamp(this._layers[i].layer) === id) {\r\n\t\t\t\treturn this._layers[i];\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t_addLayer: function (layer, name, overlay) {\r\n\t\tif (this._map) {\r\n\t\t\tlayer.on('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\r\n\t\tthis._layers.push({\r\n\t\t\tlayer: layer,\r\n\t\t\tname: name,\r\n\t\t\toverlay: overlay\r\n\t\t});\r\n\r\n\t\tif (this.options.sortLayers) {\r\n\t\t\tthis._layers.sort(Util.bind(function (a, b) {\r\n\t\t\t\treturn this.options.sortFunction(a.layer, b.layer, a.name, b.name);\r\n\t\t\t}, this));\r\n\t\t}\r\n\r\n\t\tif (this.options.autoZIndex && layer.setZIndex) {\r\n\t\t\tthis._lastZIndex++;\r\n\t\t\tlayer.setZIndex(this._lastZIndex);\r\n\t\t}\r\n\r\n\t\tthis._expandIfNotCollapsed();\r\n\t},\r\n\r\n\t_update: function () {\r\n\t\tif (!this._container) { return this; }\r\n\r\n\t\tDomUtil.empty(this._baseLayersList);\r\n\t\tDomUtil.empty(this._overlaysList);\r\n\r\n\t\tthis._layerControlInputs = [];\r\n\t\tvar baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;\r\n\r\n\t\tfor (i = 0; i < this._layers.length; i++) {\r\n\t\t\tobj = this._layers[i];\r\n\t\t\tthis._addItem(obj);\r\n\t\t\toverlaysPresent = overlaysPresent || obj.overlay;\r\n\t\t\tbaseLayersPresent = baseLayersPresent || !obj.overlay;\r\n\t\t\tbaseLayersCount += !obj.overlay ? 1 : 0;\r\n\t\t}\r\n\r\n\t\t// Hide base layers section if there's only one layer.\r\n\t\tif (this.options.hideSingleBase) {\r\n\t\t\tbaseLayersPresent = baseLayersPresent && baseLayersCount > 1;\r\n\t\t\tthis._baseLayersList.style.display = baseLayersPresent ? '' : 'none';\r\n\t\t}\r\n\r\n\t\tthis._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_onLayerChange: function (e) {\r\n\t\tif (!this._handlingClick) {\r\n\t\t\tthis._update();\r\n\t\t}\r\n\r\n\t\tvar obj = this._getLayer(Util.stamp(e.target));\r\n\r\n\t\t// @namespace Map\r\n\t\t// @section Layer events\r\n\t\t// @event baselayerchange: LayersControlEvent\r\n\t\t// Fired when the base layer is changed through the [layers control](#control-layers).\r\n\t\t// @event overlayadd: LayersControlEvent\r\n\t\t// Fired when an overlay is selected through the [layers control](#control-layers).\r\n\t\t// @event overlayremove: LayersControlEvent\r\n\t\t// Fired when an overlay is deselected through the [layers control](#control-layers).\r\n\t\t// @namespace Control.Layers\r\n\t\tvar type = obj.overlay ?\r\n\t\t\t(e.type === 'add' ? 'overlayadd' : 'overlayremove') :\r\n\t\t\t(e.type === 'add' ? 'baselayerchange' : null);\r\n\r\n\t\tif (type) {\r\n\t\t\tthis._map.fire(type, obj);\r\n\t\t}\r\n\t},\r\n\r\n\t// IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see https://stackoverflow.com/a/119079)\r\n\t_createRadioElement: function (name, checked) {\r\n\r\n\t\tvar radioHtml = '<input type=\"radio\" class=\"leaflet-control-layers-selector\" name=\"' +\r\n\t\t\t\tname + '\"' + (checked ? ' checked=\"checked\"' : '') + '/>';\r\n\r\n\t\tvar radioFragment = document.createElement('div');\r\n\t\tradioFragment.innerHTML = radioHtml;\r\n\r\n\t\treturn radioFragment.firstChild;\r\n\t},\r\n\r\n\t_addItem: function (obj) {\r\n\t\tvar label = document.createElement('label'),\r\n\t\t    checked = this._map.hasLayer(obj.layer),\r\n\t\t    input;\r\n\r\n\t\tif (obj.overlay) {\r\n\t\t\tinput = document.createElement('input');\r\n\t\t\tinput.type = 'checkbox';\r\n\t\t\tinput.className = 'leaflet-control-layers-selector';\r\n\t\t\tinput.defaultChecked = checked;\r\n\t\t} else {\r\n\t\t\tinput = this._createRadioElement('leaflet-base-layers_' + Util.stamp(this), checked);\r\n\t\t}\r\n\r\n\t\tthis._layerControlInputs.push(input);\r\n\t\tinput.layerId = Util.stamp(obj.layer);\r\n\r\n\t\tDomEvent.on(input, 'click', this._onInputClick, this);\r\n\r\n\t\tvar name = document.createElement('span');\r\n\t\tname.innerHTML = ' ' + obj.name;\r\n\r\n\t\t// Helps from preventing layer control flicker when checkboxes are disabled\r\n\t\t// https://github.com/Leaflet/Leaflet/issues/2771\r\n\t\tvar holder = document.createElement('span');\r\n\r\n\t\tlabel.appendChild(holder);\r\n\t\tholder.appendChild(input);\r\n\t\tholder.appendChild(name);\r\n\r\n\t\tvar container = obj.overlay ? this._overlaysList : this._baseLayersList;\r\n\t\tcontainer.appendChild(label);\r\n\r\n\t\tthis._checkDisabledLayers();\r\n\t\treturn label;\r\n\t},\r\n\r\n\t_onInputClick: function () {\r\n\t\t// expanding the control on mobile with a click can cause adding a layer - we don't want this\r\n\t\tif (this._preventClick) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar inputs = this._layerControlInputs,\r\n\t\t    input, layer;\r\n\t\tvar addedLayers = [],\r\n\t\t    removedLayers = [];\r\n\r\n\t\tthis._handlingClick = true;\r\n\r\n\t\tfor (var i = inputs.length - 1; i >= 0; i--) {\r\n\t\t\tinput = inputs[i];\r\n\t\t\tlayer = this._getLayer(input.layerId).layer;\r\n\r\n\t\t\tif (input.checked) {\r\n\t\t\t\taddedLayers.push(layer);\r\n\t\t\t} else if (!input.checked) {\r\n\t\t\t\tremovedLayers.push(layer);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Bugfix issue 2318: Should remove all old layers before readding new ones\r\n\t\tfor (i = 0; i < removedLayers.length; i++) {\r\n\t\t\tif (this._map.hasLayer(removedLayers[i])) {\r\n\t\t\t\tthis._map.removeLayer(removedLayers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (i = 0; i < addedLayers.length; i++) {\r\n\t\t\tif (!this._map.hasLayer(addedLayers[i])) {\r\n\t\t\t\tthis._map.addLayer(addedLayers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._handlingClick = false;\r\n\r\n\t\tthis._refocusOnMap();\r\n\t},\r\n\r\n\t_checkDisabledLayers: function () {\r\n\t\tvar inputs = this._layerControlInputs,\r\n\t\t    input,\r\n\t\t    layer,\r\n\t\t    zoom = this._map.getZoom();\r\n\r\n\t\tfor (var i = inputs.length - 1; i >= 0; i--) {\r\n\t\t\tinput = inputs[i];\r\n\t\t\tlayer = this._getLayer(input.layerId).layer;\r\n\t\t\tinput.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||\r\n\t\t\t                 (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);\r\n\r\n\t\t}\r\n\t},\r\n\r\n\t_expandIfNotCollapsed: function () {\r\n\t\tif (this._map && !this.options.collapsed) {\r\n\t\t\tthis.expand();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_expandSafely: function () {\r\n\t\tvar section = this._section;\r\n\t\tthis._preventClick = true;\r\n\t\tDomEvent.on(section, 'click', DomEvent.preventDefault);\r\n\t\tthis.expand();\r\n\t\tvar that = this;\r\n\t\tsetTimeout(function () {\r\n\t\t\tDomEvent.off(section, 'click', DomEvent.preventDefault);\r\n\t\t\tthat._preventClick = false;\r\n\t\t});\r\n\t}\r\n\r\n});\r\n\r\n\r\n// @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)\r\n// Creates a layers control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.\r\nexport var layers = function (baseLayers, overlays, options) {\r\n\treturn new Layers(baseLayers, overlays, options);\r\n};\r\n","\r\nimport {Control} from './Control';\r\nimport {Map} from '../map/Map';\r\nimport * as DomUtil from '../dom/DomUtil';\r\nimport * as DomEvent from '../dom/DomEvent';\r\n\r\n/*\r\n * @class Control.Zoom\r\n * @aka L.Control.Zoom\r\n * @inherits Control\r\n *\r\n * A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`.\r\n */\r\n\r\nexport var Zoom = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Zoom options\r\n\toptions: {\r\n\t\tposition: 'topleft',\r\n\r\n\t\t// @option zoomInText: String = '<span aria-hidden=\"true\">+</span>'\r\n\t\t// The text set on the 'zoom in' button.\r\n\t\tzoomInText: '<span aria-hidden=\"true\">+</span>',\r\n\r\n\t\t// @option zoomInTitle: String = 'Zoom in'\r\n\t\t// The title set on the 'zoom in' button.\r\n\t\tzoomInTitle: 'Zoom in',\r\n\r\n\t\t// @option zoomOutText: String = '<span aria-hidden=\"true\">&#x2212;</span>'\r\n\t\t// The text set on the 'zoom out' button.\r\n\t\tzoomOutText: '<span aria-hidden=\"true\">&#x2212;</span>',\r\n\r\n\t\t// @option zoomOutTitle: String = 'Zoom out'\r\n\t\t// The title set on the 'zoom out' button.\r\n\t\tzoomOutTitle: 'Zoom out'\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tvar zoomName = 'leaflet-control-zoom',\r\n\t\t    container = DomUtil.create('div', zoomName + ' leaflet-bar'),\r\n\t\t    options = this.options;\r\n\r\n\t\tthis._zoomInButton  = this._createButton(options.zoomInText, options.zoomInTitle,\r\n\t\t        zoomName + '-in',  container, this._zoomIn);\r\n\t\tthis._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,\r\n\t\t        zoomName + '-out', container, this._zoomOut);\r\n\r\n\t\tthis._updateDisabled();\r\n\t\tmap.on('zoomend zoomlevelschange', this._updateDisabled, this);\r\n\r\n\t\treturn container;\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tmap.off('zoomend zoomlevelschange', this._updateDisabled, this);\r\n\t},\r\n\r\n\tdisable: function () {\r\n\t\tthis._disabled = true;\r\n\t\tthis._updateDisabled();\r\n\t\treturn this;\r\n\t},\r\n\r\n\tenable: function () {\r\n\t\tthis._disabled = false;\r\n\t\tthis._updateDisabled();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_zoomIn: function (e) {\r\n\t\tif (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {\r\n\t\t\tthis._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));\r\n\t\t}\r\n\t},\r\n\r\n\t_zoomOut: function (e) {\r\n\t\tif (!this._disabled && this._map._zoom > this._map.getMinZoom()) {\r\n\t\t\tthis._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));\r\n\t\t}\r\n\t},\r\n\r\n\t_createButton: function (html, title, className, container, fn) {\r\n\t\tvar link = DomUtil.create('a', className, container);\r\n\t\tlink.innerHTML = html;\r\n\t\tlink.href = '#';\r\n\t\tlink.title = title;\r\n\r\n\t\t/*\r\n\t\t * Will force screen readers like VoiceOver to read this as \"Zoom in - button\"\r\n\t\t */\r\n\t\tlink.setAttribute('role', 'button');\r\n\t\tlink.setAttribute('aria-label', title);\r\n\r\n\t\tDomEvent.disableClickPropagation(link);\r\n\t\tDomEvent.on(link, 'click', DomEvent.stop);\r\n\t\tDomEvent.on(link, 'click', fn, this);\r\n\t\tDomEvent.on(link, 'click', this._refocusOnMap, this);\r\n\r\n\t\treturn link;\r\n\t},\r\n\r\n\t_updateDisabled: function () {\r\n\t\tvar map = this._map,\r\n\t\t    className = 'leaflet-disabled';\r\n\r\n\t\tDomUtil.removeClass(this._zoomInButton, className);\r\n\t\tDomUtil.removeClass(this._zoomOutButton, className);\r\n\t\tthis._zoomInButton.setAttribute('aria-disabled', 'false');\r\n\t\tthis._zoomOutButton.setAttribute('aria-disabled', 'false');\r\n\r\n\t\tif (this._disabled || map._zoom === map.getMinZoom()) {\r\n\t\t\tDomUtil.addClass(this._zoomOutButton, className);\r\n\t\t\tthis._zoomOutButton.setAttribute('aria-disabled', 'true');\r\n\t\t}\r\n\t\tif (this._disabled || map._zoom === map.getMaxZoom()) {\r\n\t\t\tDomUtil.addClass(this._zoomInButton, className);\r\n\t\t\tthis._zoomInButton.setAttribute('aria-disabled', 'true');\r\n\t\t}\r\n\t}\r\n});\r\n\r\n// @namespace Map\r\n// @section Control options\r\n// @option zoomControl: Boolean = true\r\n// Whether a [zoom control](#control-zoom) is added to the map by default.\r\nMap.mergeOptions({\r\n\tzoomControl: true\r\n});\r\n\r\nMap.addInitHook(function () {\r\n\tif (this.options.zoomControl) {\r\n\t\t// @section Controls\r\n\t\t// @property zoomControl: Control.Zoom\r\n\t\t// The default zoom control (only available if the\r\n\t\t// [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).\r\n\t\tthis.zoomControl = new Zoom();\r\n\t\tthis.addControl(this.zoomControl);\r\n\t}\r\n});\r\n\r\n// @namespace Control.Zoom\r\n// @factory L.control.zoom(options: Control.Zoom options)\r\n// Creates a zoom control\r\nexport var zoom = function (options) {\r\n\treturn new Zoom(options);\r\n};\r\n","\nimport {Control} from './Control';\nimport * as DomUtil from '../dom/DomUtil';\n\n/*\n * @class Control.Scale\n * @aka L.Control.Scale\n * @inherits Control\n *\n * A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends `Control`.\n *\n * @example\n *\n * ```js\n * L.control.scale().addTo(map);\n * ```\n */\n\nexport var Scale = Control.extend({\n\t// @section\n\t// @aka Control.Scale options\n\toptions: {\n\t\tposition: 'bottomleft',\n\n\t\t// @option maxWidth: Number = 100\n\t\t// Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).\n\t\tmaxWidth: 100,\n\n\t\t// @option metric: Boolean = True\n\t\t// Whether to show the metric scale line (m/km).\n\t\tmetric: true,\n\n\t\t// @option imperial: Boolean = True\n\t\t// Whether to show the imperial scale line (mi/ft).\n\t\timperial: true\n\n\t\t// @option updateWhenIdle: Boolean = false\n\t\t// If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).\n\t},\n\n\tonAdd: function (map) {\n\t\tvar className = 'leaflet-control-scale',\n\t\t    container = DomUtil.create('div', className),\n\t\t    options = this.options;\n\n\t\tthis._addScales(options, className + '-line', container);\n\n\t\tmap.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);\n\t\tmap.whenReady(this._update, this);\n\n\t\treturn container;\n\t},\n\n\tonRemove: function (map) {\n\t\tmap.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);\n\t},\n\n\t_addScales: function (options, className, container) {\n\t\tif (options.metric) {\n\t\t\tthis._mScale = DomUtil.create('div', className, container);\n\t\t}\n\t\tif (options.imperial) {\n\t\t\tthis._iScale = DomUtil.create('div', className, container);\n\t\t}\n\t},\n\n\t_update: function () {\n\t\tvar map = this._map,\n\t\t    y = map.getSize().y / 2;\n\n\t\tvar maxMeters = map.distance(\n\t\t\tmap.containerPointToLatLng([0, y]),\n\t\t\tmap.containerPointToLatLng([this.options.maxWidth, y]));\n\n\t\tthis._updateScales(maxMeters);\n\t},\n\n\t_updateScales: function (maxMeters) {\n\t\tif (this.options.metric && maxMeters) {\n\t\t\tthis._updateMetric(maxMeters);\n\t\t}\n\t\tif (this.options.imperial && maxMeters) {\n\t\t\tthis._updateImperial(maxMeters);\n\t\t}\n\t},\n\n\t_updateMetric: function (maxMeters) {\n\t\tvar meters = this._getRoundNum(maxMeters),\n\t\t    label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';\n\n\t\tthis._updateScale(this._mScale, label, meters / maxMeters);\n\t},\n\n\t_updateImperial: function (maxMeters) {\n\t\tvar maxFeet = maxMeters * 3.2808399,\n\t\t    maxMiles, miles, feet;\n\n\t\tif (maxFeet > 5280) {\n\t\t\tmaxMiles = maxFeet / 5280;\n\t\t\tmiles = this._getRoundNum(maxMiles);\n\t\t\tthis._updateScale(this._iScale, miles + ' mi', miles / maxMiles);\n\n\t\t} else {\n\t\t\tfeet = this._getRoundNum(maxFeet);\n\t\t\tthis._updateScale(this._iScale, feet + ' ft', feet / maxFeet);\n\t\t}\n\t},\n\n\t_updateScale: function (scale, text, ratio) {\n\t\tscale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';\n\t\tscale.innerHTML = text;\n\t},\n\n\t_getRoundNum: function (num) {\n\t\tvar pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),\n\t\t    d = num / pow10;\n\n\t\td = d >= 10 ? 10 :\n\t\t    d >= 5 ? 5 :\n\t\t    d >= 3 ? 3 :\n\t\t    d >= 2 ? 2 : 1;\n\n\t\treturn pow10 * d;\n\t}\n});\n\n\n// @factory L.control.scale(options?: Control.Scale options)\n// Creates an scale control with the given options.\nexport var scale = function (options) {\n\treturn new Scale(options);\n};\n","\r\nimport {Control} from './Control';\r\nimport {Map} from '../map/Map';\r\nimport * as Util from '../core/Util';\r\nimport * as DomEvent from '../dom/DomEvent';\r\nimport * as DomUtil from '../dom/DomUtil';\r\nimport Browser from '../core/Browser';\r\n\r\nvar ukrainianFlag = '<svg aria-hidden=\"true\" xmlns=\"http://www.w3.org/2000/svg\" width=\"12\" height=\"8\" viewBox=\"0 0 12 8\" class=\"leaflet-attribution-flag\"><path fill=\"#4C7BE1\" d=\"M0 0h12v4H0z\"/><path fill=\"#FFD500\" d=\"M0 4h12v3H0z\"/><path fill=\"#E0BC00\" d=\"M0 7h12v1H0z\"/></svg>';\r\n\r\n\r\n/*\r\n * @class Control.Attribution\r\n * @aka L.Control.Attribution\r\n * @inherits Control\r\n *\r\n * The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its [`attributionControl` option](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control.\r\n */\r\n\r\nexport var Attribution = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Attribution options\r\n\toptions: {\r\n\t\tposition: 'bottomright',\r\n\r\n\t\t// @option prefix: String|false = 'Leaflet'\r\n\t\t// The HTML text shown before the attributions. Pass `false` to disable.\r\n\t\tprefix: '<a href=\"https://leafletjs.com\" title=\"A JavaScript library for interactive maps\">' + (Browser.inlineSvg ? ukrainianFlag + ' ' : '') + 'Leaflet</a>'\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tUtil.setOptions(this, options);\r\n\r\n\t\tthis._attributions = {};\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tmap.attributionControl = this;\r\n\t\tthis._container = DomUtil.create('div', 'leaflet-control-attribution');\r\n\t\tDomEvent.disableClickPropagation(this._container);\r\n\r\n\t\t// TODO ugly, refactor\r\n\t\tfor (var i in map._layers) {\r\n\t\t\tif (map._layers[i].getAttribution) {\r\n\t\t\t\tthis.addAttribution(map._layers[i].getAttribution());\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._update();\r\n\r\n\t\tmap.on('layeradd', this._addAttribution, this);\r\n\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tmap.off('layeradd', this._addAttribution, this);\r\n\t},\r\n\r\n\t_addAttribution: function (ev) {\r\n\t\tif (ev.layer.getAttribution) {\r\n\t\t\tthis.addAttribution(ev.layer.getAttribution());\r\n\t\t\tev.layer.once('remove', function () {\r\n\t\t\t\tthis.removeAttribution(ev.layer.getAttribution());\r\n\t\t\t}, this);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method setPrefix(prefix: String|false): this\r\n\t// The HTML text shown before the attributions. Pass `false` to disable.\r\n\tsetPrefix: function (prefix) {\r\n\t\tthis.options.prefix = prefix;\r\n\t\tthis._update();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method addAttribution(text: String): this\r\n\t// Adds an attribution text (e.g. `'&copy; OpenStreetMap contributors'`).\r\n\taddAttribution: function (text) {\r\n\t\tif (!text) { return this; }\r\n\r\n\t\tif (!this._attributions[text]) {\r\n\t\t\tthis._attributions[text] = 0;\r\n\t\t}\r\n\t\tthis._attributions[text]++;\r\n\r\n\t\tthis._update();\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeAttribution(text: String): this\r\n\t// Removes an attribution text.\r\n\tremoveAttribution: function (text) {\r\n\t\tif (!text) { return this; }\r\n\r\n\t\tif (this._attributions[text]) {\r\n\t\t\tthis._attributions[text]--;\r\n\t\t\tthis._update();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_update: function () {\r\n\t\tif (!this._map) { return; }\r\n\r\n\t\tvar attribs = [];\r\n\r\n\t\tfor (var i in this._attributions) {\r\n\t\t\tif (this._attributions[i]) {\r\n\t\t\t\tattribs.push(i);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar prefixAndAttribs = [];\r\n\r\n\t\tif (this.options.prefix) {\r\n\t\t\tprefixAndAttribs.push(this.options.prefix);\r\n\t\t}\r\n\t\tif (attribs.length) {\r\n\t\t\tprefixAndAttribs.push(attribs.join(', '));\r\n\t\t}\r\n\r\n\t\tthis._container.innerHTML = prefixAndAttribs.join(' <span aria-hidden=\"true\">|</span> ');\r\n\t}\r\n});\r\n\r\n// @namespace Map\r\n// @section Control options\r\n// @option attributionControl: Boolean = true\r\n// Whether a [attribution control](#control-attribution) is added to the map by default.\r\nMap.mergeOptions({\r\n\tattributionControl: true\r\n});\r\n\r\nMap.addInitHook(function () {\r\n\tif (this.options.attributionControl) {\r\n\t\tnew Attribution().addTo(this);\r\n\t}\r\n});\r\n\r\n// @namespace Control.Attribution\r\n// @factory L.control.attribution(options: Control.Attribution options)\r\n// Creates an attribution control.\r\nexport var attribution = function (options) {\r\n\treturn new Attribution(options);\r\n};\r\n","import {Control, control} from './Control';\nimport {Layers, layers} from './Control.Layers';\nimport {Zoom, zoom} from './Control.Zoom';\nimport {Scale, scale} from './Control.Scale';\nimport {Attribution, attribution} from './Control.Attribution';\n\nControl.Layers = Layers;\nControl.Zoom = Zoom;\nControl.Scale = Scale;\nControl.Attribution = Attribution;\n\ncontrol.layers = layers;\ncontrol.zoom = zoom;\ncontrol.scale = scale;\ncontrol.attribution = attribution;\n\nexport {Control, control};\n","import {Class} from './Class';\n\n/*\n\tL.Handler is a base class for handler classes that are used internally to inject\n\tinteraction features like dragging to classes like Map and Marker.\n*/\n\n// @class Handler\n// @aka L.Handler\n// Abstract class for map interaction handlers\n\nexport var Handler = Class.extend({\n\tinitialize: function (map) {\n\t\tthis._map = map;\n\t},\n\n\t// @method enable(): this\n\t// Enables the handler\n\tenable: function () {\n\t\tif (this._enabled) { return this; }\n\n\t\tthis._enabled = true;\n\t\tthis.addHooks();\n\t\treturn this;\n\t},\n\n\t// @method disable(): this\n\t// Disables the handler\n\tdisable: function () {\n\t\tif (!this._enabled) { return this; }\n\n\t\tthis._enabled = false;\n\t\tthis.removeHooks();\n\t\treturn this;\n\t},\n\n\t// @method enabled(): Boolean\n\t// Returns `true` if the handler is enabled\n\tenabled: function () {\n\t\treturn !!this._enabled;\n\t}\n\n\t// @section Extension methods\n\t// Classes inheriting from `Handler` must implement the two following methods:\n\t// @method addHooks()\n\t// Called when the handler is enabled, should add event hooks.\n\t// @method removeHooks()\n\t// Called when the handler is disabled, should remove the event hooks added previously.\n});\n\n// @section There is static function which can be called without instantiating L.Handler:\n// @function addTo(map: Map, name: String): this\n// Adds a new Handler to the given map with the given name.\nHandler.addTo = function (map, name) {\n\tmap.addHandler(name, this);\n\treturn this;\n};\n","import Browser from './Browser';\nexport {Browser};\n\nexport {Class} from './Class';\n\nimport {Evented} from './Events';\nimport {Events} from './Events';\nexport {Evented};\nexport var Mixin = {Events: Events};\n\nexport {Handler} from './Handler';\n\nimport * as Util from './Util';\nexport {Util};\nexport {extend, bind, stamp, setOptions} from './Util';\n","import {Evented} from '../core/Events';\r\nimport Browser from '../core/Browser';\r\nimport * as DomEvent from './DomEvent';\r\nimport * as DomUtil from './DomUtil';\r\nimport * as Util from '../core/Util';\r\nimport {Point} from '../geometry/Point';\r\n\r\n/*\r\n * @class Draggable\r\n * @aka L.Draggable\r\n * @inherits Evented\r\n *\r\n * A class for making DOM elements draggable (including touch support).\r\n * Used internally for map and marker dragging. Only works for elements\r\n * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).\r\n *\r\n * @example\r\n * ```js\r\n * var draggable = new L.Draggable(elementToDrag);\r\n * draggable.enable();\r\n * ```\r\n */\r\n\r\nvar START = Browser.touch ? 'touchstart mousedown' : 'mousedown';\r\n\r\nexport var Draggable = Evented.extend({\r\n\r\n\toptions: {\r\n\t\t// @section\r\n\t\t// @aka Draggable options\r\n\t\t// @option clickTolerance: Number = 3\r\n\t\t// The max number of pixels a user can shift the mouse pointer during a click\r\n\t\t// for it to be considered a valid click (as opposed to a mouse drag).\r\n\t\tclickTolerance: 3\r\n\t},\r\n\r\n\t// @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)\r\n\t// Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).\r\n\tinitialize: function (element, dragStartTarget, preventOutline, options) {\r\n\t\tUtil.setOptions(this, options);\r\n\r\n\t\tthis._element = element;\r\n\t\tthis._dragStartTarget = dragStartTarget || element;\r\n\t\tthis._preventOutline = preventOutline;\r\n\t},\r\n\r\n\t// @method enable()\r\n\t// Enables the dragging ability\r\n\tenable: function () {\r\n\t\tif (this._enabled) { return; }\r\n\r\n\t\tDomEvent.on(this._dragStartTarget, START, this._onDown, this);\r\n\r\n\t\tthis._enabled = true;\r\n\t},\r\n\r\n\t// @method disable()\r\n\t// Disables the dragging ability\r\n\tdisable: function () {\r\n\t\tif (!this._enabled) { return; }\r\n\r\n\t\t// If we're currently dragging this draggable,\r\n\t\t// disabling it counts as first ending the drag.\r\n\t\tif (Draggable._dragging === this) {\r\n\t\t\tthis.finishDrag(true);\r\n\t\t}\r\n\r\n\t\tDomEvent.off(this._dragStartTarget, START, this._onDown, this);\r\n\r\n\t\tthis._enabled = false;\r\n\t\tthis._moved = false;\r\n\t},\r\n\r\n\t_onDown: function (e) {\r\n\t\t// Ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (!this._enabled) { return; }\r\n\r\n\t\tthis._moved = false;\r\n\r\n\t\tif (DomUtil.hasClass(this._element, 'leaflet-zoom-anim')) { return; }\r\n\r\n\t\tif (e.touches && e.touches.length !== 1) {\r\n\t\t\t// Finish dragging to avoid conflict with touchZoom\r\n\t\t\tif (Draggable._dragging === this) {\r\n\t\t\t\tthis.finishDrag();\r\n\t\t\t}\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }\r\n\t\tDraggable._dragging = this;  // Prevent dragging multiple objects at once.\r\n\r\n\t\tif (this._preventOutline) {\r\n\t\t\tDomUtil.preventOutline(this._element);\r\n\t\t}\r\n\r\n\t\tDomUtil.disableImageDrag();\r\n\t\tDomUtil.disableTextSelection();\r\n\r\n\t\tif (this._moving) { return; }\r\n\r\n\t\t// @event down: Event\r\n\t\t// Fired when a drag is about to start.\r\n\t\tthis.fire('down');\r\n\r\n\t\tvar first = e.touches ? e.touches[0] : e,\r\n\t\t    sizedParent = DomUtil.getSizedParentNode(this._element);\r\n\r\n\t\tthis._startPoint = new Point(first.clientX, first.clientY);\r\n\t\tthis._startPos = DomUtil.getPosition(this._element);\r\n\r\n\t\t// Cache the scale, so that we can continuously compensate for it during drag (_onMove).\r\n\t\tthis._parentScale = DomUtil.getScale(sizedParent);\r\n\r\n\t\tvar mouseevent = e.type === 'mousedown';\r\n\t\tDomEvent.on(document, mouseevent ? 'mousemove' : 'touchmove', this._onMove, this);\r\n\t\tDomEvent.on(document, mouseevent ? 'mouseup' : 'touchend touchcancel', this._onUp, this);\r\n\t},\r\n\r\n\t_onMove: function (e) {\r\n\t\t// Ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (!this._enabled) { return; }\r\n\r\n\t\tif (e.touches && e.touches.length > 1) {\r\n\t\t\tthis._moved = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),\r\n\t\t    offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);\r\n\r\n\t\tif (!offset.x && !offset.y) { return; }\r\n\t\tif (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }\r\n\r\n\t\t// We assume that the parent container's position, border and scale do not change for the duration of the drag.\r\n\t\t// Therefore there is no need to account for the position and border (they are eliminated by the subtraction)\r\n\t\t// and we can use the cached value for the scale.\r\n\t\toffset.x /= this._parentScale.x;\r\n\t\toffset.y /= this._parentScale.y;\r\n\r\n\t\tDomEvent.preventDefault(e);\r\n\r\n\t\tif (!this._moved) {\r\n\t\t\t// @event dragstart: Event\r\n\t\t\t// Fired when a drag starts\r\n\t\t\tthis.fire('dragstart');\r\n\r\n\t\t\tthis._moved = true;\r\n\r\n\t\t\tDomUtil.addClass(document.body, 'leaflet-dragging');\r\n\r\n\t\t\tthis._lastTarget = e.target || e.srcElement;\r\n\t\t\t// IE and Edge do not give the <use> element, so fetch it\r\n\t\t\t// if necessary\r\n\t\t\tif (window.SVGElementInstance && this._lastTarget instanceof window.SVGElementInstance) {\r\n\t\t\t\tthis._lastTarget = this._lastTarget.correspondingUseElement;\r\n\t\t\t}\r\n\t\t\tDomUtil.addClass(this._lastTarget, 'leaflet-drag-target');\r\n\t\t}\r\n\r\n\t\tthis._newPos = this._startPos.add(offset);\r\n\t\tthis._moving = true;\r\n\r\n\t\tthis._lastEvent = e;\r\n\t\tthis._updatePosition();\r\n\t},\r\n\r\n\t_updatePosition: function () {\r\n\t\tvar e = {originalEvent: this._lastEvent};\r\n\r\n\t\t// @event predrag: Event\r\n\t\t// Fired continuously during dragging *before* each corresponding\r\n\t\t// update of the element's position.\r\n\t\tthis.fire('predrag', e);\r\n\t\tDomUtil.setPosition(this._element, this._newPos);\r\n\r\n\t\t// @event drag: Event\r\n\t\t// Fired continuously during dragging.\r\n\t\tthis.fire('drag', e);\r\n\t},\r\n\r\n\t_onUp: function () {\r\n\t\t// Ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (!this._enabled) { return; }\r\n\t\tthis.finishDrag();\r\n\t},\r\n\r\n\tfinishDrag: function (noInertia) {\r\n\t\tDomUtil.removeClass(document.body, 'leaflet-dragging');\r\n\r\n\t\tif (this._lastTarget) {\r\n\t\t\tDomUtil.removeClass(this._lastTarget, 'leaflet-drag-target');\r\n\t\t\tthis._lastTarget = null;\r\n\t\t}\r\n\r\n\t\tDomEvent.off(document, 'mousemove touchmove', this._onMove, this);\r\n\t\tDomEvent.off(document, 'mouseup touchend touchcancel', this._onUp, this);\r\n\r\n\t\tDomUtil.enableImageDrag();\r\n\t\tDomUtil.enableTextSelection();\r\n\r\n\t\tvar fireDragend = this._moved && this._moving;\r\n\r\n\t\tthis._moving = false;\r\n\t\tDraggable._dragging = false;\r\n\r\n\t\tif (fireDragend) {\r\n\t\t\t// @event dragend: DragEndEvent\r\n\t\t\t// Fired when the drag ends.\r\n\t\t\tthis.fire('dragend', {\r\n\t\t\t\tnoInertia: noInertia,\r\n\t\t\t\tdistance: this._newPos.distanceTo(this._startPos)\r\n\t\t\t});\r\n\t\t}\r\n\t}\r\n\r\n});\r\n","import * as LineUtil from './LineUtil';\r\nimport {toLatLng} from '../geo/LatLng';\r\nimport {toPoint} from './Point';\r\nimport {toLatLngBounds} from '../geo/LatLngBounds';\r\n/*\r\n * @namespace PolyUtil\r\n * Various utility functions for polygon geometries.\r\n */\r\n\r\n/* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]\r\n * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).\r\n * Used by Leaflet to only show polygon points that are on the screen or near, increasing\r\n * performance. Note that polygon points needs different algorithm for clipping\r\n * than polyline, so there's a separate method for it.\r\n */\r\nexport function clipPolygon(points, bounds, round) {\r\n\tvar clippedPoints,\r\n\t    edges = [1, 4, 2, 8],\r\n\t    i, j, k,\r\n\t    a, b,\r\n\t    len, edge, p;\r\n\r\n\tfor (i = 0, len = points.length; i < len; i++) {\r\n\t\tpoints[i]._code = LineUtil._getBitCode(points[i], bounds);\r\n\t}\r\n\r\n\t// for each edge (left, bottom, right, top)\r\n\tfor (k = 0; k < 4; k++) {\r\n\t\tedge = edges[k];\r\n\t\tclippedPoints = [];\r\n\r\n\t\tfor (i = 0, len = points.length, j = len - 1; i < len; j = i++) {\r\n\t\t\ta = points[i];\r\n\t\t\tb = points[j];\r\n\r\n\t\t\t// if a is inside the clip window\r\n\t\t\tif (!(a._code & edge)) {\r\n\t\t\t\t// if b is outside the clip window (a->b goes out of screen)\r\n\t\t\t\tif (b._code & edge) {\r\n\t\t\t\t\tp = LineUtil._getEdgeIntersection(b, a, edge, bounds, round);\r\n\t\t\t\t\tp._code = LineUtil._getBitCode(p, bounds);\r\n\t\t\t\t\tclippedPoints.push(p);\r\n\t\t\t\t}\r\n\t\t\t\tclippedPoints.push(a);\r\n\r\n\t\t\t// else if b is inside the clip window (a->b enters the screen)\r\n\t\t\t} else if (!(b._code & edge)) {\r\n\t\t\t\tp = LineUtil._getEdgeIntersection(b, a, edge, bounds, round);\r\n\t\t\t\tp._code = LineUtil._getBitCode(p, bounds);\r\n\t\t\t\tclippedPoints.push(p);\r\n\t\t\t}\r\n\t\t}\r\n\t\tpoints = clippedPoints;\r\n\t}\r\n\r\n\treturn points;\r\n}\r\n\r\n/* @function polygonCenter(latlngs: LatLng[], crs: CRS): LatLng\r\n * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polygon.\r\n */\r\nexport function polygonCenter(latlngs, crs) {\r\n\tvar i, j, p1, p2, f, area, x, y, center;\r\n\r\n\tif (!latlngs || latlngs.length === 0) {\r\n\t\tthrow new Error('latlngs not passed');\r\n\t}\r\n\r\n\tif (!LineUtil.isFlat(latlngs)) {\r\n\t\tconsole.warn('latlngs are not flat! Only the first ring will be used');\r\n\t\tlatlngs = latlngs[0];\r\n\t}\r\n\r\n\tvar centroidLatLng = toLatLng([0, 0]);\r\n\r\n\tvar bounds = toLatLngBounds(latlngs);\r\n\tvar areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());\r\n\t// tests showed that below 1700 rounding errors are happening\r\n\tif (areaBounds < 1700) {\r\n\t\t// getting a inexact center, to move the latlngs near to [0, 0] to prevent rounding errors\r\n\t\tcentroidLatLng = centroid(latlngs);\r\n\t}\r\n\r\n\tvar len = latlngs.length;\r\n\tvar points = [];\r\n\tfor (i = 0; i < len; i++) {\r\n\t\tvar latlng = toLatLng(latlngs[i]);\r\n\t\tpoints.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));\r\n\t}\r\n\r\n\tarea = x = y = 0;\r\n\r\n\t// polygon centroid algorithm;\r\n\tfor (i = 0, j = len - 1; i < len; j = i++) {\r\n\t\tp1 = points[i];\r\n\t\tp2 = points[j];\r\n\r\n\t\tf = p1.y * p2.x - p2.y * p1.x;\r\n\t\tx += (p1.x + p2.x) * f;\r\n\t\ty += (p1.y + p2.y) * f;\r\n\t\tarea += f * 3;\r\n\t}\r\n\r\n\tif (area === 0) {\r\n\t\t// Polygon is so small that all points are on same pixel.\r\n\t\tcenter = points[0];\r\n\t} else {\r\n\t\tcenter = [x / area, y / area];\r\n\t}\r\n\r\n\tvar latlngCenter = crs.unproject(toPoint(center));\r\n\treturn toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);\r\n}\r\n\r\n/* @function centroid(latlngs: LatLng[]): LatLng\r\n * Returns the 'center of mass' of the passed LatLngs.\r\n */\r\nexport function centroid(coords) {\r\n\tvar latSum = 0;\r\n\tvar lngSum = 0;\r\n\tvar len = 0;\r\n\tfor (var i = 0; i < coords.length; i++) {\r\n\t\tvar latlng = toLatLng(coords[i]);\r\n\t\tlatSum += latlng.lat;\r\n\t\tlngSum += latlng.lng;\r\n\t\tlen++;\r\n\t}\r\n\treturn toLatLng([latSum / len, lngSum / len]);\r\n}\r\n","import {Point, toPoint} from './Point';\r\nimport * as Util from '../core/Util';\r\nimport {toLatLng} from '../geo/LatLng';\r\nimport {centroid} from './PolyUtil';\r\nimport {toLatLngBounds} from '../geo/LatLngBounds';\r\n\r\n\r\n/*\r\n * @namespace LineUtil\r\n *\r\n * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.\r\n */\r\n\r\n// Simplify polyline with vertex reduction and Douglas-Peucker simplification.\r\n// Improves rendering performance dramatically by lessening the number of points to draw.\r\n\r\n// @function simplify(points: Point[], tolerance: Number): Point[]\r\n// Dramatically reduces the number of points in a polyline while retaining\r\n// its shape and returns a new array of simplified points, using the\r\n// [Ramer-Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm).\r\n// Used for a huge performance boost when processing/displaying Leaflet polylines for\r\n// each zoom level and also reducing visual noise. tolerance affects the amount of\r\n// simplification (lesser value means higher quality but slower and with more points).\r\n// Also released as a separated micro-library [Simplify.js](https://mourner.github.io/simplify-js/).\r\nexport function simplify(points, tolerance) {\r\n\tif (!tolerance || !points.length) {\r\n\t\treturn points.slice();\r\n\t}\r\n\r\n\tvar sqTolerance = tolerance * tolerance;\r\n\r\n\t    // stage 1: vertex reduction\r\n\t    points = _reducePoints(points, sqTolerance);\r\n\r\n\t    // stage 2: Douglas-Peucker simplification\r\n\t    points = _simplifyDP(points, sqTolerance);\r\n\r\n\treturn points;\r\n}\r\n\r\n// @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number\r\n// Returns the distance between point `p` and segment `p1` to `p2`.\r\nexport function pointToSegmentDistance(p, p1, p2) {\r\n\treturn Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));\r\n}\r\n\r\n// @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number\r\n// Returns the closest point from a point `p` on a segment `p1` to `p2`.\r\nexport function closestPointOnSegment(p, p1, p2) {\r\n\treturn _sqClosestPointOnSegment(p, p1, p2);\r\n}\r\n\r\n// Ramer-Douglas-Peucker simplification, see https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm\r\nfunction _simplifyDP(points, sqTolerance) {\r\n\r\n\tvar len = points.length,\r\n\t    ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,\r\n\t    markers = new ArrayConstructor(len);\r\n\r\n\t    markers[0] = markers[len - 1] = 1;\r\n\r\n\t_simplifyDPStep(points, markers, sqTolerance, 0, len - 1);\r\n\r\n\tvar i,\r\n\t    newPoints = [];\r\n\r\n\tfor (i = 0; i < len; i++) {\r\n\t\tif (markers[i]) {\r\n\t\t\tnewPoints.push(points[i]);\r\n\t\t}\r\n\t}\r\n\r\n\treturn newPoints;\r\n}\r\n\r\nfunction _simplifyDPStep(points, markers, sqTolerance, first, last) {\r\n\r\n\tvar maxSqDist = 0,\r\n\tindex, i, sqDist;\r\n\r\n\tfor (i = first + 1; i <= last - 1; i++) {\r\n\t\tsqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);\r\n\r\n\t\tif (sqDist > maxSqDist) {\r\n\t\t\tindex = i;\r\n\t\t\tmaxSqDist = sqDist;\r\n\t\t}\r\n\t}\r\n\r\n\tif (maxSqDist > sqTolerance) {\r\n\t\tmarkers[index] = 1;\r\n\r\n\t\t_simplifyDPStep(points, markers, sqTolerance, first, index);\r\n\t\t_simplifyDPStep(points, markers, sqTolerance, index, last);\r\n\t}\r\n}\r\n\r\n// reduce points that are too close to each other to a single point\r\nfunction _reducePoints(points, sqTolerance) {\r\n\tvar reducedPoints = [points[0]];\r\n\r\n\tfor (var i = 1, prev = 0, len = points.length; i < len; i++) {\r\n\t\tif (_sqDist(points[i], points[prev]) > sqTolerance) {\r\n\t\t\treducedPoints.push(points[i]);\r\n\t\t\tprev = i;\r\n\t\t}\r\n\t}\r\n\tif (prev < len - 1) {\r\n\t\treducedPoints.push(points[len - 1]);\r\n\t}\r\n\treturn reducedPoints;\r\n}\r\n\r\nvar _lastCode;\r\n\r\n// @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean\r\n// Clips the segment a to b by rectangular bounds with the\r\n// [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)\r\n// (modifying the segment points directly!). Used by Leaflet to only show polyline\r\n// points that are on the screen or near, increasing performance.\r\nexport function clipSegment(a, b, bounds, useLastCode, round) {\r\n\tvar codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),\r\n\t    codeB = _getBitCode(b, bounds),\r\n\r\n\t    codeOut, p, newCode;\r\n\r\n\t    // save 2nd code to avoid calculating it on the next segment\r\n\t    _lastCode = codeB;\r\n\r\n\twhile (true) {\r\n\t\t// if a,b is inside the clip window (trivial accept)\r\n\t\tif (!(codeA | codeB)) {\r\n\t\t\treturn [a, b];\r\n\t\t}\r\n\r\n\t\t// if a,b is outside the clip window (trivial reject)\r\n\t\tif (codeA & codeB) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t// other cases\r\n\t\tcodeOut = codeA || codeB;\r\n\t\tp = _getEdgeIntersection(a, b, codeOut, bounds, round);\r\n\t\tnewCode = _getBitCode(p, bounds);\r\n\r\n\t\tif (codeOut === codeA) {\r\n\t\t\ta = p;\r\n\t\t\tcodeA = newCode;\r\n\t\t} else {\r\n\t\t\tb = p;\r\n\t\t\tcodeB = newCode;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nexport function _getEdgeIntersection(a, b, code, bounds, round) {\r\n\tvar dx = b.x - a.x,\r\n\t    dy = b.y - a.y,\r\n\t    min = bounds.min,\r\n\t    max = bounds.max,\r\n\t    x, y;\r\n\r\n\tif (code & 8) { // top\r\n\t\tx = a.x + dx * (max.y - a.y) / dy;\r\n\t\ty = max.y;\r\n\r\n\t} else if (code & 4) { // bottom\r\n\t\tx = a.x + dx * (min.y - a.y) / dy;\r\n\t\ty = min.y;\r\n\r\n\t} else if (code & 2) { // right\r\n\t\tx = max.x;\r\n\t\ty = a.y + dy * (max.x - a.x) / dx;\r\n\r\n\t} else if (code & 1) { // left\r\n\t\tx = min.x;\r\n\t\ty = a.y + dy * (min.x - a.x) / dx;\r\n\t}\r\n\r\n\treturn new Point(x, y, round);\r\n}\r\n\r\nexport function _getBitCode(p, bounds) {\r\n\tvar code = 0;\r\n\r\n\tif (p.x < bounds.min.x) { // left\r\n\t\tcode |= 1;\r\n\t} else if (p.x > bounds.max.x) { // right\r\n\t\tcode |= 2;\r\n\t}\r\n\r\n\tif (p.y < bounds.min.y) { // bottom\r\n\t\tcode |= 4;\r\n\t} else if (p.y > bounds.max.y) { // top\r\n\t\tcode |= 8;\r\n\t}\r\n\r\n\treturn code;\r\n}\r\n\r\n// square distance (to avoid unnecessary Math.sqrt calls)\r\nfunction _sqDist(p1, p2) {\r\n\tvar dx = p2.x - p1.x,\r\n\t    dy = p2.y - p1.y;\r\n\treturn dx * dx + dy * dy;\r\n}\r\n\r\n// return closest point on segment or distance to that point\r\nexport function _sqClosestPointOnSegment(p, p1, p2, sqDist) {\r\n\tvar x = p1.x,\r\n\t    y = p1.y,\r\n\t    dx = p2.x - x,\r\n\t    dy = p2.y - y,\r\n\t    dot = dx * dx + dy * dy,\r\n\t    t;\r\n\r\n\tif (dot > 0) {\r\n\t\tt = ((p.x - x) * dx + (p.y - y) * dy) / dot;\r\n\r\n\t\tif (t > 1) {\r\n\t\t\tx = p2.x;\r\n\t\t\ty = p2.y;\r\n\t\t} else if (t > 0) {\r\n\t\t\tx += dx * t;\r\n\t\t\ty += dy * t;\r\n\t\t}\r\n\t}\r\n\r\n\tdx = p.x - x;\r\n\tdy = p.y - y;\r\n\r\n\treturn sqDist ? dx * dx + dy * dy : new Point(x, y);\r\n}\r\n\r\n\r\n// @function isFlat(latlngs: LatLng[]): Boolean\r\n// Returns true if `latlngs` is a flat array, false is nested.\r\nexport function isFlat(latlngs) {\r\n\treturn !Util.isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');\r\n}\r\n\r\nexport function _flat(latlngs) {\r\n\tconsole.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');\r\n\treturn isFlat(latlngs);\r\n}\r\n\r\n/* @function polylineCenter(latlngs: LatLng[], crs: CRS): LatLng\r\n * Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polyline.\r\n */\r\nexport function polylineCenter(latlngs, crs) {\r\n\tvar i, halfDist, segDist, dist, p1, p2, ratio, center;\r\n\r\n\tif (!latlngs || latlngs.length === 0) {\r\n\t\tthrow new Error('latlngs not passed');\r\n\t}\r\n\r\n\tif (!isFlat(latlngs)) {\r\n\t\tconsole.warn('latlngs are not flat! Only the first ring will be used');\r\n\t\tlatlngs = latlngs[0];\r\n\t}\r\n\r\n\tvar centroidLatLng = toLatLng([0, 0]);\r\n\r\n\tvar bounds = toLatLngBounds(latlngs);\r\n\tvar areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());\r\n\t// tests showed that below 1700 rounding errors are happening\r\n\tif (areaBounds < 1700) {\r\n\t\t// getting a inexact center, to move the latlngs near to [0, 0] to prevent rounding errors\r\n\t\tcentroidLatLng = centroid(latlngs);\r\n\t}\r\n\r\n\tvar len = latlngs.length;\r\n\tvar points = [];\r\n\tfor (i = 0; i < len; i++) {\r\n\t\tvar latlng = toLatLng(latlngs[i]);\r\n\t\tpoints.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));\r\n\t}\r\n\r\n\tfor (i = 0, halfDist = 0; i < len - 1; i++) {\r\n\t\thalfDist += points[i].distanceTo(points[i + 1]) / 2;\r\n\t}\r\n\r\n\t// The line is so small in the current view that all points are on the same pixel.\r\n\tif (halfDist === 0) {\r\n\t\tcenter = points[0];\r\n\t} else {\r\n\t\tfor (i = 0, dist = 0; i < len - 1; i++) {\r\n\t\t\tp1 = points[i];\r\n\t\t\tp2 = points[i + 1];\r\n\t\t\tsegDist = p1.distanceTo(p2);\r\n\t\t\tdist += segDist;\r\n\r\n\t\t\tif (dist > halfDist) {\r\n\t\t\t\tratio = (dist - halfDist) / segDist;\r\n\t\t\t\tcenter = [\r\n\t\t\t\t\tp2.x - ratio * (p2.x - p1.x),\r\n\t\t\t\t\tp2.y - ratio * (p2.y - p1.y)\r\n\t\t\t\t];\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvar latlngCenter = crs.unproject(toPoint(center));\r\n\treturn toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);\r\n}\r\n","import {LatLng} from '../LatLng';\r\nimport {Bounds} from '../../geometry/Bounds';\r\nimport {Point} from '../../geometry/Point';\r\n\r\n/*\r\n * @namespace Projection\r\n * @section\r\n * Leaflet comes with a set of already defined Projections out of the box:\r\n *\r\n * @projection L.Projection.LonLat\r\n *\r\n * Equirectangular, or Plate Carree projection — the most simple projection,\r\n * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as\r\n * latitude. Also suitable for flat worlds, e.g. game maps. Used by the\r\n * `EPSG:4326` and `Simple` CRS.\r\n */\r\n\r\nexport var LonLat = {\r\n\tproject: function (latlng) {\r\n\t\treturn new Point(latlng.lng, latlng.lat);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\treturn new LatLng(point.y, point.x);\r\n\t},\r\n\r\n\tbounds: new Bounds([-180, -90], [180, 90])\r\n};\r\n","import {LatLng} from '../LatLng';\r\nimport {Bounds} from '../../geometry/Bounds';\r\nimport {Point} from '../../geometry/Point';\r\n\r\n/*\r\n * @namespace Projection\r\n * @projection L.Projection.Mercator\r\n *\r\n * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.\r\n */\r\n\r\nexport var Mercator = {\r\n\tR: 6378137,\r\n\tR_MINOR: 6356752.314245179,\r\n\r\n\tbounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),\r\n\r\n\tproject: function (latlng) {\r\n\t\tvar d = Math.PI / 180,\r\n\t\t    r = this.R,\r\n\t\t    y = latlng.lat * d,\r\n\t\t    tmp = this.R_MINOR / r,\r\n\t\t    e = Math.sqrt(1 - tmp * tmp),\r\n\t\t    con = e * Math.sin(y);\r\n\r\n\t\tvar ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);\r\n\t\ty = -r * Math.log(Math.max(ts, 1E-10));\r\n\r\n\t\treturn new Point(latlng.lng * d * r, y);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\tvar d = 180 / Math.PI,\r\n\t\t    r = this.R,\r\n\t\t    tmp = this.R_MINOR / r,\r\n\t\t    e = Math.sqrt(1 - tmp * tmp),\r\n\t\t    ts = Math.exp(-point.y / r),\r\n\t\t    phi = Math.PI / 2 - 2 * Math.atan(ts);\r\n\r\n\t\tfor (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {\r\n\t\t\tcon = e * Math.sin(phi);\r\n\t\t\tcon = Math.pow((1 - con) / (1 + con), e / 2);\r\n\t\t\tdphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;\r\n\t\t\tphi += dphi;\r\n\t\t}\r\n\r\n\t\treturn new LatLng(phi * d, point.x * d / r);\r\n\t}\r\n};\r\n","/*\n * @class Projection\n\n * An object with methods for projecting geographical coordinates of the world onto\n * a flat surface (and back). See [Map projection](https://en.wikipedia.org/wiki/Map_projection).\n\n * @property bounds: Bounds\n * The bounds (specified in CRS units) where the projection is valid\n\n * @method project(latlng: LatLng): Point\n * Projects geographical coordinates into a 2D point.\n * Only accepts actual `L.LatLng` instances, not arrays.\n\n * @method unproject(point: Point): LatLng\n * The inverse of `project`. Projects a 2D point into a geographical location.\n * Only accepts actual `L.Point` instances, not arrays.\n\n * Note that the projection instances do not inherit from Leaflet's `Class` object,\n * and can't be instantiated. Also, new classes can't inherit from them,\n * and methods can't be added to them with the `include` function.\n\n */\n\nexport {LonLat} from './Projection.LonLat';\nexport {Mercator} from './Projection.Mercator';\nexport {SphericalMercator} from './Projection.SphericalMercator';\n","import {Earth} from './CRS.Earth';\r\nimport {Mercator} from '../projection/Projection.Mercator';\r\nimport {toTransformation} from '../../geometry/Transformation';\r\nimport * as Util from '../../core/Util';\r\n\r\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG3395\r\n *\r\n * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.\r\n */\r\nexport var EPSG3395 = Util.extend({}, Earth, {\r\n\tcode: 'EPSG:3395',\r\n\tprojection: Mercator,\r\n\r\n\ttransformation: (function () {\r\n\t\tvar scale = 0.5 / (Math.PI * Mercator.R);\r\n\t\treturn toTransformation(scale, 0.5, -scale, 0.5);\r\n\t}())\r\n});\r\n","import {Earth} from './CRS.Earth';\r\nimport {LonLat} from '../projection/Projection.LonLat';\r\nimport {toTransformation} from '../../geometry/Transformation';\r\nimport * as Util from '../../core/Util';\r\n\r\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG4326\r\n *\r\n * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.\r\n *\r\n * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),\r\n * which is a breaking change from 0.7.x behaviour.  If you are using a `TileLayer`\r\n * with this CRS, ensure that there are two 256x256 pixel tiles covering the\r\n * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),\r\n * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.\r\n */\r\n\r\nexport var EPSG4326 = Util.extend({}, Earth, {\r\n\tcode: 'EPSG:4326',\r\n\tprojection: LonLat,\r\n\ttransformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)\r\n});\r\n","import {CRS} from './CRS';\nimport {LonLat} from '../projection/Projection.LonLat';\nimport {toTransformation} from '../../geometry/Transformation';\nimport * as Util from '../../core/Util';\n\n/*\n * @namespace CRS\n * @crs L.CRS.Simple\n *\n * A simple CRS that maps longitude and latitude into `x` and `y` directly.\n * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`\n * axis should still be inverted (going from bottom to top). `distance()` returns\n * simple euclidean distance.\n */\n\nexport var Simple = Util.extend({}, CRS, {\n\tprojection: LonLat,\n\ttransformation: toTransformation(1, 0, -1, 0),\n\n\tscale: function (zoom) {\n\t\treturn Math.pow(2, zoom);\n\t},\n\n\tzoom: function (scale) {\n\t\treturn Math.log(scale) / Math.LN2;\n\t},\n\n\tdistance: function (latlng1, latlng2) {\n\t\tvar dx = latlng2.lng - latlng1.lng,\n\t\t    dy = latlng2.lat - latlng1.lat;\n\n\t\treturn Math.sqrt(dx * dx + dy * dy);\n\t},\n\n\tinfinite: true\n});\n","import {CRS} from './CRS';\nimport {Earth} from './CRS.Earth';\nimport {EPSG3395} from './CRS.EPSG3395';\nimport {EPSG3857, EPSG900913} from './CRS.EPSG3857';\nimport {EPSG4326} from './CRS.EPSG4326';\nimport {Simple} from './CRS.Simple';\n\nCRS.Earth = Earth;\nCRS.EPSG3395 = EPSG3395;\nCRS.EPSG3857 = EPSG3857;\nCRS.EPSG900913 = EPSG900913;\nCRS.EPSG4326 = EPSG4326;\nCRS.Simple = Simple;\n\nexport {CRS};\n","import {Evented} from '../core/Events';\nimport {Map} from '../map/Map';\nimport * as Util from '../core/Util';\n\n/*\n * @class Layer\n * @inherits Evented\n * @aka L.Layer\n * @aka ILayer\n *\n * A set of methods from the Layer base class that all Leaflet layers use.\n * Inherits all methods, options and events from `L.Evented`.\n *\n * @example\n *\n * ```js\n * var layer = L.marker(latlng).addTo(map);\n * layer.addTo(map);\n * layer.remove();\n * ```\n *\n * @event add: Event\n * Fired after the layer is added to a map\n *\n * @event remove: Event\n * Fired after the layer is removed from a map\n */\n\n\nexport var Layer = Evented.extend({\n\n\t// Classes extending `L.Layer` will inherit the following options:\n\toptions: {\n\t\t// @option pane: String = 'overlayPane'\n\t\t// By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default.\n\t\tpane: 'overlayPane',\n\n\t\t// @option attribution: String = null\n\t\t// String to be shown in the attribution control, e.g. \"© OpenStreetMap contributors\". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.\n\t\tattribution: null,\n\n\t\tbubblingMouseEvents: true\n\t},\n\n\t/* @section\n\t * Classes extending `L.Layer` will inherit the following methods:\n\t *\n\t * @method addTo(map: Map|LayerGroup): this\n\t * Adds the layer to the given map or layer group.\n\t */\n\taddTo: function (map) {\n\t\tmap.addLayer(this);\n\t\treturn this;\n\t},\n\n\t// @method remove: this\n\t// Removes the layer from the map it is currently active on.\n\tremove: function () {\n\t\treturn this.removeFrom(this._map || this._mapToAdd);\n\t},\n\n\t// @method removeFrom(map: Map): this\n\t// Removes the layer from the given map\n\t//\n\t// @alternative\n\t// @method removeFrom(group: LayerGroup): this\n\t// Removes the layer from the given `LayerGroup`\n\tremoveFrom: function (obj) {\n\t\tif (obj) {\n\t\t\tobj.removeLayer(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method getPane(name? : String): HTMLElement\n\t// Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.\n\tgetPane: function (name) {\n\t\treturn this._map.getPane(name ? (this.options[name] || name) : this.options.pane);\n\t},\n\n\taddInteractiveTarget: function (targetEl) {\n\t\tthis._map._targets[Util.stamp(targetEl)] = this;\n\t\treturn this;\n\t},\n\n\tremoveInteractiveTarget: function (targetEl) {\n\t\tdelete this._map._targets[Util.stamp(targetEl)];\n\t\treturn this;\n\t},\n\n\t// @method getAttribution: String\n\t// Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).\n\tgetAttribution: function () {\n\t\treturn this.options.attribution;\n\t},\n\n\t_layerAdd: function (e) {\n\t\tvar map = e.target;\n\n\t\t// check in case layer gets added and then removed before the map is ready\n\t\tif (!map.hasLayer(this)) { return; }\n\n\t\tthis._map = map;\n\t\tthis._zoomAnimated = map._zoomAnimated;\n\n\t\tif (this.getEvents) {\n\t\t\tvar events = this.getEvents();\n\t\t\tmap.on(events, this);\n\t\t\tthis.once('remove', function () {\n\t\t\t\tmap.off(events, this);\n\t\t\t}, this);\n\t\t}\n\n\t\tthis.onAdd(map);\n\n\t\tthis.fire('add');\n\t\tmap.fire('layeradd', {layer: this});\n\t}\n});\n\n/* @section Extension methods\n * @uninheritable\n *\n * Every layer should extend from `L.Layer` and (re-)implement the following methods.\n *\n * @method onAdd(map: Map): this\n * Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer).\n *\n * @method onRemove(map: Map): this\n * Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer).\n *\n * @method getEvents(): Object\n * This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#evented-addeventlistener). The event handlers in this object will be automatically added and removed from the map with your layer.\n *\n * @method getAttribution(): String\n * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.\n *\n * @method beforeAdd(map: Map): this\n * Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only.\n */\n\n\n/* @namespace Map\n * @section Layer events\n *\n * @event layeradd: LayerEvent\n * Fired when a new layer is added to the map.\n *\n * @event layerremove: LayerEvent\n * Fired when some layer is removed from the map\n *\n * @section Methods for Layers and Controls\n */\nMap.include({\n\t// @method addLayer(layer: Layer): this\n\t// Adds the given layer to the map\n\taddLayer: function (layer) {\n\t\tif (!layer._layerAdd) {\n\t\t\tthrow new Error('The provided object is not a Layer.');\n\t\t}\n\n\t\tvar id = Util.stamp(layer);\n\t\tif (this._layers[id]) { return this; }\n\t\tthis._layers[id] = layer;\n\n\t\tlayer._mapToAdd = this;\n\n\t\tif (layer.beforeAdd) {\n\t\t\tlayer.beforeAdd(this);\n\t\t}\n\n\t\tthis.whenReady(layer._layerAdd, layer);\n\n\t\treturn this;\n\t},\n\n\t// @method removeLayer(layer: Layer): this\n\t// Removes the given layer from the map.\n\tremoveLayer: function (layer) {\n\t\tvar id = Util.stamp(layer);\n\n\t\tif (!this._layers[id]) { return this; }\n\n\t\tif (this._loaded) {\n\t\t\tlayer.onRemove(this);\n\t\t}\n\n\t\tdelete this._layers[id];\n\n\t\tif (this._loaded) {\n\t\t\tthis.fire('layerremove', {layer: layer});\n\t\t\tlayer.fire('remove');\n\t\t}\n\n\t\tlayer._map = layer._mapToAdd = null;\n\n\t\treturn this;\n\t},\n\n\t// @method hasLayer(layer: Layer): Boolean\n\t// Returns `true` if the given layer is currently added to the map\n\thasLayer: function (layer) {\n\t\treturn Util.stamp(layer) in this._layers;\n\t},\n\n\t/* @method eachLayer(fn: Function, context?: Object): this\n\t * Iterates over the layers of the map, optionally specifying context of the iterator function.\n\t * ```\n\t * map.eachLayer(function(layer){\n\t *     layer.bindPopup('Hello');\n\t * });\n\t * ```\n\t */\n\teachLayer: function (method, context) {\n\t\tfor (var i in this._layers) {\n\t\t\tmethod.call(context, this._layers[i]);\n\t\t}\n\t\treturn this;\n\t},\n\n\t_addLayers: function (layers) {\n\t\tlayers = layers ? (Util.isArray(layers) ? layers : [layers]) : [];\n\n\t\tfor (var i = 0, len = layers.length; i < len; i++) {\n\t\t\tthis.addLayer(layers[i]);\n\t\t}\n\t},\n\n\t_addZoomLimit: function (layer) {\n\t\tif (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {\n\t\t\tthis._zoomBoundLayers[Util.stamp(layer)] = layer;\n\t\t\tthis._updateZoomLevels();\n\t\t}\n\t},\n\n\t_removeZoomLimit: function (layer) {\n\t\tvar id = Util.stamp(layer);\n\n\t\tif (this._zoomBoundLayers[id]) {\n\t\t\tdelete this._zoomBoundLayers[id];\n\t\t\tthis._updateZoomLevels();\n\t\t}\n\t},\n\n\t_updateZoomLevels: function () {\n\t\tvar minZoom = Infinity,\n\t\t    maxZoom = -Infinity,\n\t\t    oldZoomSpan = this._getZoomSpan();\n\n\t\tfor (var i in this._zoomBoundLayers) {\n\t\t\tvar options = this._zoomBoundLayers[i].options;\n\n\t\t\tminZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);\n\t\t\tmaxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);\n\t\t}\n\n\t\tthis._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;\n\t\tthis._layersMinZoom = minZoom === Infinity ? undefined : minZoom;\n\n\t\t// @section Map state change events\n\t\t// @event zoomlevelschange: Event\n\t\t// Fired when the number of zoomlevels on the map is changed due\n\t\t// to adding or removing a layer.\n\t\tif (oldZoomSpan !== this._getZoomSpan()) {\n\t\t\tthis.fire('zoomlevelschange');\n\t\t}\n\n\t\tif (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {\n\t\t\tthis.setZoom(this._layersMaxZoom);\n\t\t}\n\t\tif (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {\n\t\t\tthis.setZoom(this._layersMinZoom);\n\t\t}\n\t}\n});\n","\r\nimport {Layer} from './Layer';\r\nimport * as Util from '../core/Util';\r\n\r\n/*\r\n * @class LayerGroup\r\n * @aka L.LayerGroup\r\n * @inherits Interactive layer\r\n *\r\n * Used to group several layers and handle them as one. If you add it to the map,\r\n * any layers added or removed from the group will be added/removed on the map as\r\n * well. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.layerGroup([marker1, marker2])\r\n * \t.addLayer(polyline)\r\n * \t.addTo(map);\r\n * ```\r\n */\r\n\r\nexport var LayerGroup = Layer.extend({\r\n\r\n\tinitialize: function (layers, options) {\r\n\t\tUtil.setOptions(this, options);\r\n\r\n\t\tthis._layers = {};\r\n\r\n\t\tvar i, len;\r\n\r\n\t\tif (layers) {\r\n\t\t\tfor (i = 0, len = layers.length; i < len; i++) {\r\n\t\t\t\tthis.addLayer(layers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addLayer(layer: Layer): this\r\n\t// Adds the given layer to the group.\r\n\taddLayer: function (layer) {\r\n\t\tvar id = this.getLayerId(layer);\r\n\r\n\t\tthis._layers[id] = layer;\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._map.addLayer(layer);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeLayer(layer: Layer): this\r\n\t// Removes the given layer from the group.\r\n\t// @alternative\r\n\t// @method removeLayer(id: Number): this\r\n\t// Removes the layer with the given internal ID from the group.\r\n\tremoveLayer: function (layer) {\r\n\t\tvar id = layer in this._layers ? layer : this.getLayerId(layer);\r\n\r\n\t\tif (this._map && this._layers[id]) {\r\n\t\t\tthis._map.removeLayer(this._layers[id]);\r\n\t\t}\r\n\r\n\t\tdelete this._layers[id];\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method hasLayer(layer: Layer): Boolean\r\n\t// Returns `true` if the given layer is currently added to the group.\r\n\t// @alternative\r\n\t// @method hasLayer(id: Number): Boolean\r\n\t// Returns `true` if the given internal ID is currently added to the group.\r\n\thasLayer: function (layer) {\r\n\t\tvar layerId = typeof layer === 'number' ? layer : this.getLayerId(layer);\r\n\t\treturn layerId in this._layers;\r\n\t},\r\n\r\n\t// @method clearLayers(): this\r\n\t// Removes all the layers from the group.\r\n\tclearLayers: function () {\r\n\t\treturn this.eachLayer(this.removeLayer, this);\r\n\t},\r\n\r\n\t// @method invoke(methodName: String, …): this\r\n\t// Calls `methodName` on every layer contained in this group, passing any\r\n\t// additional parameters. Has no effect if the layers contained do not\r\n\t// implement `methodName`.\r\n\tinvoke: function (methodName) {\r\n\t\tvar args = Array.prototype.slice.call(arguments, 1),\r\n\t\t    i, layer;\r\n\r\n\t\tfor (i in this._layers) {\r\n\t\t\tlayer = this._layers[i];\r\n\r\n\t\t\tif (layer[methodName]) {\r\n\t\t\t\tlayer[methodName].apply(layer, args);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis.eachLayer(map.addLayer, map);\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tthis.eachLayer(map.removeLayer, map);\r\n\t},\r\n\r\n\t// @method eachLayer(fn: Function, context?: Object): this\r\n\t// Iterates over the layers of the group, optionally specifying context of the iterator function.\r\n\t// ```js\r\n\t// group.eachLayer(function (layer) {\r\n\t// \tlayer.bindPopup('Hello');\r\n\t// });\r\n\t// ```\r\n\teachLayer: function (method, context) {\r\n\t\tfor (var i in this._layers) {\r\n\t\t\tmethod.call(context, this._layers[i]);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getLayer(id: Number): Layer\r\n\t// Returns the layer with the given internal ID.\r\n\tgetLayer: function (id) {\r\n\t\treturn this._layers[id];\r\n\t},\r\n\r\n\t// @method getLayers(): Layer[]\r\n\t// Returns an array of all the layers added to the group.\r\n\tgetLayers: function () {\r\n\t\tvar layers = [];\r\n\t\tthis.eachLayer(layers.push, layers);\r\n\t\treturn layers;\r\n\t},\r\n\r\n\t// @method setZIndex(zIndex: Number): this\r\n\t// Calls `setZIndex` on every layer contained in this group, passing the z-index.\r\n\tsetZIndex: function (zIndex) {\r\n\t\treturn this.invoke('setZIndex', zIndex);\r\n\t},\r\n\r\n\t// @method getLayerId(layer: Layer): Number\r\n\t// Returns the internal ID for a layer\r\n\tgetLayerId: function (layer) {\r\n\t\treturn Util.stamp(layer);\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.layerGroup(layers?: Layer[], options?: Object)\r\n// Create a layer group, optionally given an initial set of layers and an `options` object.\r\nexport var layerGroup = function (layers, options) {\r\n\treturn new LayerGroup(layers, options);\r\n};\r\n","import {LayerGroup} from './LayerGroup';\r\nimport {LatLngBounds} from '../geo/LatLngBounds';\r\n\r\n/*\r\n * @class FeatureGroup\r\n * @aka L.FeatureGroup\r\n * @inherits LayerGroup\r\n *\r\n * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:\r\n *  * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))\r\n *  * Events are propagated to the `FeatureGroup`, so if the group has an event\r\n * handler, it will handle events from any of the layers. This includes mouse events\r\n * and custom events.\r\n *  * Has `layeradd` and `layerremove` events\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.featureGroup([marker1, marker2, polyline])\r\n * \t.bindPopup('Hello world!')\r\n * \t.on('click', function() { alert('Clicked on a member of the group!'); })\r\n * \t.addTo(map);\r\n * ```\r\n */\r\n\r\nexport var FeatureGroup = LayerGroup.extend({\r\n\r\n\taddLayer: function (layer) {\r\n\t\tif (this.hasLayer(layer)) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tlayer.addEventParent(this);\r\n\r\n\t\tLayerGroup.prototype.addLayer.call(this, layer);\r\n\r\n\t\t// @event layeradd: LayerEvent\r\n\t\t// Fired when a layer is added to this `FeatureGroup`\r\n\t\treturn this.fire('layeradd', {layer: layer});\r\n\t},\r\n\r\n\tremoveLayer: function (layer) {\r\n\t\tif (!this.hasLayer(layer)) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\tif (layer in this._layers) {\r\n\t\t\tlayer = this._layers[layer];\r\n\t\t}\r\n\r\n\t\tlayer.removeEventParent(this);\r\n\r\n\t\tLayerGroup.prototype.removeLayer.call(this, layer);\r\n\r\n\t\t// @event layerremove: LayerEvent\r\n\t\t// Fired when a layer is removed from this `FeatureGroup`\r\n\t\treturn this.fire('layerremove', {layer: layer});\r\n\t},\r\n\r\n\t// @method setStyle(style: Path options): this\r\n\t// Sets the given path options to each layer of the group that has a `setStyle` method.\r\n\tsetStyle: function (style) {\r\n\t\treturn this.invoke('setStyle', style);\r\n\t},\r\n\r\n\t// @method bringToFront(): this\r\n\t// Brings the layer group to the top of all other layers\r\n\tbringToFront: function () {\r\n\t\treturn this.invoke('bringToFront');\r\n\t},\r\n\r\n\t// @method bringToBack(): this\r\n\t// Brings the layer group to the back of all other layers\r\n\tbringToBack: function () {\r\n\t\treturn this.invoke('bringToBack');\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).\r\n\tgetBounds: function () {\r\n\t\tvar bounds = new LatLngBounds();\r\n\r\n\t\tfor (var id in this._layers) {\r\n\t\t\tvar layer = this._layers[id];\r\n\t\t\tbounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());\r\n\t\t}\r\n\t\treturn bounds;\r\n\t}\r\n});\r\n\r\n// @factory L.featureGroup(layers?: Layer[], options?: Object)\r\n// Create a feature group, optionally given an initial set of layers and an `options` object.\r\nexport var featureGroup = function (layers, options) {\r\n\treturn new FeatureGroup(layers, options);\r\n};\r\n","import {Class} from '../../core/Class';\r\nimport {setOptions} from '../../core/Util';\r\nimport {toPoint as point} from '../../geometry/Point';\r\nimport Browser from '../../core/Browser';\r\n\r\n/*\r\n * @class Icon\r\n * @aka L.Icon\r\n *\r\n * Represents an icon to provide when creating a marker.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var myIcon = L.icon({\r\n *     iconUrl: 'my-icon.png',\r\n *     iconRetinaUrl: 'my-icon@2x.png',\r\n *     iconSize: [38, 95],\r\n *     iconAnchor: [22, 94],\r\n *     popupAnchor: [-3, -76],\r\n *     shadowUrl: 'my-icon-shadow.png',\r\n *     shadowRetinaUrl: 'my-icon-shadow@2x.png',\r\n *     shadowSize: [68, 95],\r\n *     shadowAnchor: [22, 94]\r\n * });\r\n *\r\n * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);\r\n * ```\r\n *\r\n * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.\r\n *\r\n */\r\n\r\nexport var Icon = Class.extend({\r\n\r\n\t/* @section\r\n\t * @aka Icon options\r\n\t *\r\n\t * @option iconUrl: String = null\r\n\t * **(required)** The URL to the icon image (absolute or relative to your script path).\r\n\t *\r\n\t * @option iconRetinaUrl: String = null\r\n\t * The URL to a retina sized version of the icon image (absolute or relative to your\r\n\t * script path). Used for Retina screen devices.\r\n\t *\r\n\t * @option iconSize: Point = null\r\n\t * Size of the icon image in pixels.\r\n\t *\r\n\t * @option iconAnchor: Point = null\r\n\t * The coordinates of the \"tip\" of the icon (relative to its top left corner). The icon\r\n\t * will be aligned so that this point is at the marker's geographical location. Centered\r\n\t * by default if size is specified, also can be set in CSS with negative margins.\r\n\t *\r\n\t * @option popupAnchor: Point = [0, 0]\r\n\t * The coordinates of the point from which popups will \"open\", relative to the icon anchor.\r\n\t *\r\n\t * @option tooltipAnchor: Point = [0, 0]\r\n\t * The coordinates of the point from which tooltips will \"open\", relative to the icon anchor.\r\n\t *\r\n\t * @option shadowUrl: String = null\r\n\t * The URL to the icon shadow image. If not specified, no shadow image will be created.\r\n\t *\r\n\t * @option shadowRetinaUrl: String = null\r\n\t *\r\n\t * @option shadowSize: Point = null\r\n\t * Size of the shadow image in pixels.\r\n\t *\r\n\t * @option shadowAnchor: Point = null\r\n\t * The coordinates of the \"tip\" of the shadow (relative to its top left corner) (the same\r\n\t * as iconAnchor if not specified).\r\n\t *\r\n\t * @option className: String = ''\r\n\t * A custom class name to assign to both icon and shadow images. Empty by default.\r\n\t */\r\n\r\n\toptions: {\r\n\t\tpopupAnchor: [0, 0],\r\n\t\ttooltipAnchor: [0, 0],\r\n\r\n\t\t// @option crossOrigin: Boolean|String = false\r\n\t\t// Whether the crossOrigin attribute will be added to the tiles.\r\n\t\t// If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.\r\n\t\t// Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.\r\n\t\tcrossOrigin: false\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tsetOptions(this, options);\r\n\t},\r\n\r\n\t// @method createIcon(oldIcon?: HTMLElement): HTMLElement\r\n\t// Called internally when the icon has to be shown, returns a `<img>` HTML element\r\n\t// styled according to the options.\r\n\tcreateIcon: function (oldIcon) {\r\n\t\treturn this._createIcon('icon', oldIcon);\r\n\t},\r\n\r\n\t// @method createShadow(oldIcon?: HTMLElement): HTMLElement\r\n\t// As `createIcon`, but for the shadow beneath it.\r\n\tcreateShadow: function (oldIcon) {\r\n\t\treturn this._createIcon('shadow', oldIcon);\r\n\t},\r\n\r\n\t_createIcon: function (name, oldIcon) {\r\n\t\tvar src = this._getIconUrl(name);\r\n\r\n\t\tif (!src) {\r\n\t\t\tif (name === 'icon') {\r\n\t\t\t\tthrow new Error('iconUrl not set in Icon options (see the docs).');\r\n\t\t\t}\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tvar img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);\r\n\t\tthis._setIconStyles(img, name);\r\n\r\n\t\tif (this.options.crossOrigin || this.options.crossOrigin === '') {\r\n\t\t\timg.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;\r\n\t\t}\r\n\r\n\t\treturn img;\r\n\t},\r\n\r\n\t_setIconStyles: function (img, name) {\r\n\t\tvar options = this.options;\r\n\t\tvar sizeOption = options[name + 'Size'];\r\n\r\n\t\tif (typeof sizeOption === 'number') {\r\n\t\t\tsizeOption = [sizeOption, sizeOption];\r\n\t\t}\r\n\r\n\t\tvar size = point(sizeOption),\r\n\t\t    anchor = point(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||\r\n\t\t            size && size.divideBy(2, true));\r\n\r\n\t\timg.className = 'leaflet-marker-' + name + ' ' + (options.className || '');\r\n\r\n\t\tif (anchor) {\r\n\t\t\timg.style.marginLeft = (-anchor.x) + 'px';\r\n\t\t\timg.style.marginTop  = (-anchor.y) + 'px';\r\n\t\t}\r\n\r\n\t\tif (size) {\r\n\t\t\timg.style.width  = size.x + 'px';\r\n\t\t\timg.style.height = size.y + 'px';\r\n\t\t}\r\n\t},\r\n\r\n\t_createImg: function (src, el) {\r\n\t\tel = el || document.createElement('img');\r\n\t\tel.src = src;\r\n\t\treturn el;\r\n\t},\r\n\r\n\t_getIconUrl: function (name) {\r\n\t\treturn Browser.retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.icon(options: Icon options)\r\n// Creates an icon instance with the given options.\r\nexport function icon(options) {\r\n\treturn new Icon(options);\r\n}\r\n","import {Icon} from './Icon';\nimport * as DomUtil from '../../dom/DomUtil';\n\n/*\n * @miniclass Icon.Default (Icon)\n * @aka L.Icon.Default\n * @section\n *\n * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when\n * no icon is specified. Points to the blue marker image distributed with Leaflet\n * releases.\n *\n * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`\n * (which is a set of `Icon options`).\n *\n * If you want to _completely_ replace the default icon, override the\n * `L.Marker.prototype.options.icon` with your own icon instead.\n */\n\nexport var IconDefault = Icon.extend({\n\n\toptions: {\n\t\ticonUrl:       'marker-icon.png',\n\t\ticonRetinaUrl: 'marker-icon-2x.png',\n\t\tshadowUrl:     'marker-shadow.png',\n\t\ticonSize:    [25, 41],\n\t\ticonAnchor:  [12, 41],\n\t\tpopupAnchor: [1, -34],\n\t\ttooltipAnchor: [16, -28],\n\t\tshadowSize:  [41, 41]\n\t},\n\n\t_getIconUrl: function (name) {\n\t\tif (typeof IconDefault.imagePath !== 'string') {\t// Deprecated, backwards-compatibility only\n\t\t\tIconDefault.imagePath = this._detectIconPath();\n\t\t}\n\n\t\t// @option imagePath: String\n\t\t// `Icon.Default` will try to auto-detect the location of the\n\t\t// blue icon images. If you are placing these images in a non-standard\n\t\t// way, set this option to point to the right path.\n\t\treturn (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);\n\t},\n\n\t_stripUrl: function (path) {\t// separate function to use in tests\n\t\tvar strip = function (str, re, idx) {\n\t\t\tvar match = re.exec(str);\n\t\t\treturn match && match[idx];\n\t\t};\n\t\tpath = strip(path, /^url\\((['\"])?(.+)\\1\\)$/, 2);\n\t\treturn path && strip(path, /^(.*)marker-icon\\.png$/, 1);\n\t},\n\n\t_detectIconPath: function () {\n\t\tvar el = DomUtil.create('div',  'leaflet-default-icon-path', document.body);\n\t\tvar path = DomUtil.getStyle(el, 'background-image') ||\n\t\t           DomUtil.getStyle(el, 'backgroundImage');\t// IE8\n\n\t\tdocument.body.removeChild(el);\n\t\tpath = this._stripUrl(path);\n\t\tif (path) { return path; }\n\t\tvar link = document.querySelector('link[href$=\"leaflet.css\"]');\n\t\tif (!link) { return ''; }\n\t\treturn link.href.substring(0, link.href.length - 'leaflet.css'.length - 1);\n\t}\n});\n","import {Handler} from '../../core/Handler';\nimport * as DomUtil from '../../dom/DomUtil';\nimport {Draggable} from '../../dom/Draggable';\nimport {toBounds} from '../../geometry/Bounds';\nimport {toPoint} from '../../geometry/Point';\nimport {requestAnimFrame, cancelAnimFrame} from '../../core/Util';\n\n/*\n * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.\n */\n\n\n/* @namespace Marker\n * @section Interaction handlers\n *\n * Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see `Handler` methods). Example:\n *\n * ```js\n * marker.dragging.disable();\n * ```\n *\n * @property dragging: Handler\n * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).\n */\n\nexport var MarkerDrag = Handler.extend({\n\tinitialize: function (marker) {\n\t\tthis._marker = marker;\n\t},\n\n\taddHooks: function () {\n\t\tvar icon = this._marker._icon;\n\n\t\tif (!this._draggable) {\n\t\t\tthis._draggable = new Draggable(icon, icon, true);\n\t\t}\n\n\t\tthis._draggable.on({\n\t\t\tdragstart: this._onDragStart,\n\t\t\tpredrag: this._onPreDrag,\n\t\t\tdrag: this._onDrag,\n\t\t\tdragend: this._onDragEnd\n\t\t}, this).enable();\n\n\t\tDomUtil.addClass(icon, 'leaflet-marker-draggable');\n\t},\n\n\tremoveHooks: function () {\n\t\tthis._draggable.off({\n\t\t\tdragstart: this._onDragStart,\n\t\t\tpredrag: this._onPreDrag,\n\t\t\tdrag: this._onDrag,\n\t\t\tdragend: this._onDragEnd\n\t\t}, this).disable();\n\n\t\tif (this._marker._icon) {\n\t\t\tDomUtil.removeClass(this._marker._icon, 'leaflet-marker-draggable');\n\t\t}\n\t},\n\n\tmoved: function () {\n\t\treturn this._draggable && this._draggable._moved;\n\t},\n\n\t_adjustPan: function (e) {\n\t\tvar marker = this._marker,\n\t\t    map = marker._map,\n\t\t    speed = this._marker.options.autoPanSpeed,\n\t\t    padding = this._marker.options.autoPanPadding,\n\t\t    iconPos = DomUtil.getPosition(marker._icon),\n\t\t    bounds = map.getPixelBounds(),\n\t\t    origin = map.getPixelOrigin();\n\n\t\tvar panBounds = toBounds(\n\t\t\tbounds.min._subtract(origin).add(padding),\n\t\t\tbounds.max._subtract(origin).subtract(padding)\n\t\t);\n\n\t\tif (!panBounds.contains(iconPos)) {\n\t\t\t// Compute incremental movement\n\t\t\tvar movement = toPoint(\n\t\t\t\t(Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -\n\t\t\t\t(Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),\n\n\t\t\t\t(Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -\n\t\t\t\t(Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)\n\t\t\t).multiplyBy(speed);\n\n\t\t\tmap.panBy(movement, {animate: false});\n\n\t\t\tthis._draggable._newPos._add(movement);\n\t\t\tthis._draggable._startPos._add(movement);\n\n\t\t\tDomUtil.setPosition(marker._icon, this._draggable._newPos);\n\t\t\tthis._onDrag(e);\n\n\t\t\tthis._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));\n\t\t}\n\t},\n\n\t_onDragStart: function () {\n\t\t// @section Dragging events\n\t\t// @event dragstart: Event\n\t\t// Fired when the user starts dragging the marker.\n\n\t\t// @event movestart: Event\n\t\t// Fired when the marker starts moving (because of dragging).\n\n\t\tthis._oldLatLng = this._marker.getLatLng();\n\n\t\t// When using ES6 imports it could not be set when `Popup` was not imported as well\n\t\tthis._marker.closePopup && this._marker.closePopup();\n\n\t\tthis._marker\n\t\t\t.fire('movestart')\n\t\t\t.fire('dragstart');\n\t},\n\n\t_onPreDrag: function (e) {\n\t\tif (this._marker.options.autoPan) {\n\t\t\tcancelAnimFrame(this._panRequest);\n\t\t\tthis._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));\n\t\t}\n\t},\n\n\t_onDrag: function (e) {\n\t\tvar marker = this._marker,\n\t\t    shadow = marker._shadow,\n\t\t    iconPos = DomUtil.getPosition(marker._icon),\n\t\t    latlng = marker._map.layerPointToLatLng(iconPos);\n\n\t\t// update shadow position\n\t\tif (shadow) {\n\t\t\tDomUtil.setPosition(shadow, iconPos);\n\t\t}\n\n\t\tmarker._latlng = latlng;\n\t\te.latlng = latlng;\n\t\te.oldLatLng = this._oldLatLng;\n\n\t\t// @event drag: Event\n\t\t// Fired repeatedly while the user drags the marker.\n\t\tmarker\n\t\t    .fire('move', e)\n\t\t    .fire('drag', e);\n\t},\n\n\t_onDragEnd: function (e) {\n\t\t// @event dragend: DragEndEvent\n\t\t// Fired when the user stops dragging the marker.\n\n\t\t cancelAnimFrame(this._panRequest);\n\n\t\t// @event moveend: Event\n\t\t// Fired when the marker stops moving (because of dragging).\n\t\tdelete this._oldLatLng;\n\t\tthis._marker\n\t\t    .fire('moveend')\n\t\t    .fire('dragend', e);\n\t}\n});\n","import {Layer} from '../Layer';\r\nimport {IconDefault} from './Icon.Default';\r\nimport * as Util from '../../core/Util';\r\nimport {toLatLng as latLng} from '../../geo/LatLng';\r\nimport {toPoint as point} from '../../geometry/Point';\r\nimport * as DomUtil from '../../dom/DomUtil';\r\nimport * as DomEvent from '../../dom/DomEvent';\r\nimport {MarkerDrag} from './Marker.Drag';\r\n\r\n/*\r\n * @class Marker\r\n * @inherits Interactive layer\r\n * @aka L.Marker\r\n * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.marker([50.5, 30.5]).addTo(map);\r\n * ```\r\n */\r\n\r\nexport var Marker = Layer.extend({\r\n\r\n\t// @section\r\n\t// @aka Marker options\r\n\toptions: {\r\n\t\t// @option icon: Icon = *\r\n\t\t// Icon instance to use for rendering the marker.\r\n\t\t// See [Icon documentation](#L.Icon) for details on how to customize the marker icon.\r\n\t\t// If not specified, a common instance of `L.Icon.Default` is used.\r\n\t\ticon: new IconDefault(),\r\n\r\n\t\t// Option inherited from \"Interactive layer\" abstract class\r\n\t\tinteractive: true,\r\n\r\n\t\t// @option keyboard: Boolean = true\r\n\t\t// Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.\r\n\t\tkeyboard: true,\r\n\r\n\t\t// @option title: String = ''\r\n\t\t// Text for the browser tooltip that appear on marker hover (no tooltip by default).\r\n\t\t// [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).\r\n\t\ttitle: '',\r\n\r\n\t\t// @option alt: String = 'Marker'\r\n\t\t// Text for the `alt` attribute of the icon image.\r\n\t\t// [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).\r\n\t\talt: 'Marker',\r\n\r\n\t\t// @option zIndexOffset: Number = 0\r\n\t\t// By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively).\r\n\t\tzIndexOffset: 0,\r\n\r\n\t\t// @option opacity: Number = 1.0\r\n\t\t// The opacity of the marker.\r\n\t\topacity: 1,\r\n\r\n\t\t// @option riseOnHover: Boolean = false\r\n\t\t// If `true`, the marker will get on top of others when you hover the mouse over it.\r\n\t\triseOnHover: false,\r\n\r\n\t\t// @option riseOffset: Number = 250\r\n\t\t// The z-index offset used for the `riseOnHover` feature.\r\n\t\triseOffset: 250,\r\n\r\n\t\t// @option pane: String = 'markerPane'\r\n\t\t// `Map pane` where the markers icon will be added.\r\n\t\tpane: 'markerPane',\r\n\r\n\t\t// @option shadowPane: String = 'shadowPane'\r\n\t\t// `Map pane` where the markers shadow will be added.\r\n\t\tshadowPane: 'shadowPane',\r\n\r\n\t\t// @option bubblingMouseEvents: Boolean = false\r\n\t\t// When `true`, a mouse event on this marker will trigger the same event on the map\r\n\t\t// (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).\r\n\t\tbubblingMouseEvents: false,\r\n\r\n\t\t// @option autoPanOnFocus: Boolean = true\r\n\t\t// When `true`, the map will pan whenever the marker is focused (via\r\n\t\t// e.g. pressing `tab` on the keyboard) to ensure the marker is\r\n\t\t// visible within the map's bounds\r\n\t\tautoPanOnFocus: true,\r\n\r\n\t\t// @section Draggable marker options\r\n\t\t// @option draggable: Boolean = false\r\n\t\t// Whether the marker is draggable with mouse/touch or not.\r\n\t\tdraggable: false,\r\n\r\n\t\t// @option autoPan: Boolean = false\r\n\t\t// Whether to pan the map when dragging this marker near its edge or not.\r\n\t\tautoPan: false,\r\n\r\n\t\t// @option autoPanPadding: Point = Point(50, 50)\r\n\t\t// Distance (in pixels to the left/right and to the top/bottom) of the\r\n\t\t// map edge to start panning the map.\r\n\t\tautoPanPadding: [50, 50],\r\n\r\n\t\t// @option autoPanSpeed: Number = 10\r\n\t\t// Number of pixels the map should pan by.\r\n\t\tautoPanSpeed: 10\r\n\t},\r\n\r\n\t/* @section\r\n\t *\r\n\t * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:\r\n\t */\r\n\r\n\tinitialize: function (latlng, options) {\r\n\t\tUtil.setOptions(this, options);\r\n\t\tthis._latlng = latLng(latlng);\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tmap.on('zoomanim', this._animateZoom, this);\r\n\t\t}\r\n\r\n\t\tthis._initIcon();\r\n\t\tthis.update();\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tif (this.dragging && this.dragging.enabled()) {\r\n\t\t\tthis.options.draggable = true;\r\n\t\t\tthis.dragging.removeHooks();\r\n\t\t}\r\n\t\tdelete this.dragging;\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tmap.off('zoomanim', this._animateZoom, this);\r\n\t\t}\r\n\r\n\t\tthis._removeIcon();\r\n\t\tthis._removeShadow();\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\treturn {\r\n\t\t\tzoom: this.update,\r\n\t\t\tviewreset: this.update\r\n\t\t};\r\n\t},\r\n\r\n\t// @method getLatLng: LatLng\r\n\t// Returns the current geographical position of the marker.\r\n\tgetLatLng: function () {\r\n\t\treturn this._latlng;\r\n\t},\r\n\r\n\t// @method setLatLng(latlng: LatLng): this\r\n\t// Changes the marker position to the given point.\r\n\tsetLatLng: function (latlng) {\r\n\t\tvar oldLatLng = this._latlng;\r\n\t\tthis._latlng = latLng(latlng);\r\n\t\tthis.update();\r\n\r\n\t\t// @event move: Event\r\n\t\t// Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.\r\n\t\treturn this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});\r\n\t},\r\n\r\n\t// @method setZIndexOffset(offset: Number): this\r\n\t// Changes the [zIndex offset](#marker-zindexoffset) of the marker.\r\n\tsetZIndexOffset: function (offset) {\r\n\t\tthis.options.zIndexOffset = offset;\r\n\t\treturn this.update();\r\n\t},\r\n\r\n\t// @method getIcon: Icon\r\n\t// Returns the current icon used by the marker\r\n\tgetIcon: function () {\r\n\t\treturn this.options.icon;\r\n\t},\r\n\r\n\t// @method setIcon(icon: Icon): this\r\n\t// Changes the marker icon.\r\n\tsetIcon: function (icon) {\r\n\r\n\t\tthis.options.icon = icon;\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._initIcon();\r\n\t\t\tthis.update();\r\n\t\t}\r\n\r\n\t\tif (this._popup) {\r\n\t\t\tthis.bindPopup(this._popup, this._popup.options);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\tgetElement: function () {\r\n\t\treturn this._icon;\r\n\t},\r\n\r\n\tupdate: function () {\r\n\r\n\t\tif (this._icon && this._map) {\r\n\t\t\tvar pos = this._map.latLngToLayerPoint(this._latlng).round();\r\n\t\t\tthis._setPos(pos);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initIcon: function () {\r\n\t\tvar options = this.options,\r\n\t\t    classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');\r\n\r\n\t\tvar icon = options.icon.createIcon(this._icon),\r\n\t\t    addIcon = false;\r\n\r\n\t\t// if we're not reusing the icon, remove the old one and init new one\r\n\t\tif (icon !== this._icon) {\r\n\t\t\tif (this._icon) {\r\n\t\t\t\tthis._removeIcon();\r\n\t\t\t}\r\n\t\t\taddIcon = true;\r\n\r\n\t\t\tif (options.title) {\r\n\t\t\t\ticon.title = options.title;\r\n\t\t\t}\r\n\r\n\t\t\tif (icon.tagName === 'IMG') {\r\n\t\t\t\ticon.alt = options.alt || '';\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tDomUtil.addClass(icon, classToAdd);\r\n\r\n\t\tif (options.keyboard) {\r\n\t\t\ticon.tabIndex = '0';\r\n\t\t\ticon.setAttribute('role', 'button');\r\n\t\t}\r\n\r\n\t\tthis._icon = icon;\r\n\r\n\t\tif (options.riseOnHover) {\r\n\t\t\tthis.on({\r\n\t\t\t\tmouseover: this._bringToFront,\r\n\t\t\t\tmouseout: this._resetZIndex\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tif (this.options.autoPanOnFocus) {\r\n\t\t\tDomEvent.on(icon, 'focus', this._panOnFocus, this);\r\n\t\t}\r\n\r\n\t\tvar newShadow = options.icon.createShadow(this._shadow),\r\n\t\t    addShadow = false;\r\n\r\n\t\tif (newShadow !== this._shadow) {\r\n\t\t\tthis._removeShadow();\r\n\t\t\taddShadow = true;\r\n\t\t}\r\n\r\n\t\tif (newShadow) {\r\n\t\t\tDomUtil.addClass(newShadow, classToAdd);\r\n\t\t\tnewShadow.alt = '';\r\n\t\t}\r\n\t\tthis._shadow = newShadow;\r\n\r\n\r\n\t\tif (options.opacity < 1) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\r\n\r\n\t\tif (addIcon) {\r\n\t\t\tthis.getPane().appendChild(this._icon);\r\n\t\t}\r\n\t\tthis._initInteraction();\r\n\t\tif (newShadow && addShadow) {\r\n\t\t\tthis.getPane(options.shadowPane).appendChild(this._shadow);\r\n\t\t}\r\n\t},\r\n\r\n\t_removeIcon: function () {\r\n\t\tif (this.options.riseOnHover) {\r\n\t\t\tthis.off({\r\n\t\t\t\tmouseover: this._bringToFront,\r\n\t\t\t\tmouseout: this._resetZIndex\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tif (this.options.autoPanOnFocus) {\r\n\t\t\tDomEvent.off(this._icon, 'focus', this._panOnFocus, this);\r\n\t\t}\r\n\r\n\t\tDomUtil.remove(this._icon);\r\n\t\tthis.removeInteractiveTarget(this._icon);\r\n\r\n\t\tthis._icon = null;\r\n\t},\r\n\r\n\t_removeShadow: function () {\r\n\t\tif (this._shadow) {\r\n\t\t\tDomUtil.remove(this._shadow);\r\n\t\t}\r\n\t\tthis._shadow = null;\r\n\t},\r\n\r\n\t_setPos: function (pos) {\r\n\r\n\t\tif (this._icon) {\r\n\t\t\tDomUtil.setPosition(this._icon, pos);\r\n\t\t}\r\n\r\n\t\tif (this._shadow) {\r\n\t\t\tDomUtil.setPosition(this._shadow, pos);\r\n\t\t}\r\n\r\n\t\tthis._zIndex = pos.y + this.options.zIndexOffset;\r\n\r\n\t\tthis._resetZIndex();\r\n\t},\r\n\r\n\t_updateZIndex: function (offset) {\r\n\t\tif (this._icon) {\r\n\t\t\tthis._icon.style.zIndex = this._zIndex + offset;\r\n\t\t}\r\n\t},\r\n\r\n\t_animateZoom: function (opt) {\r\n\t\tvar pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();\r\n\r\n\t\tthis._setPos(pos);\r\n\t},\r\n\r\n\t_initInteraction: function () {\r\n\r\n\t\tif (!this.options.interactive) { return; }\r\n\r\n\t\tDomUtil.addClass(this._icon, 'leaflet-interactive');\r\n\r\n\t\tthis.addInteractiveTarget(this._icon);\r\n\r\n\t\tif (MarkerDrag) {\r\n\t\t\tvar draggable = this.options.draggable;\r\n\t\t\tif (this.dragging) {\r\n\t\t\t\tdraggable = this.dragging.enabled();\r\n\t\t\t\tthis.dragging.disable();\r\n\t\t\t}\r\n\r\n\t\t\tthis.dragging = new MarkerDrag(this);\r\n\r\n\t\t\tif (draggable) {\r\n\t\t\t\tthis.dragging.enable();\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t// @method setOpacity(opacity: Number): this\r\n\t// Changes the opacity of the marker.\r\n\tsetOpacity: function (opacity) {\r\n\t\tthis.options.opacity = opacity;\r\n\t\tif (this._map) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_updateOpacity: function () {\r\n\t\tvar opacity = this.options.opacity;\r\n\r\n\t\tif (this._icon) {\r\n\t\t\tDomUtil.setOpacity(this._icon, opacity);\r\n\t\t}\r\n\r\n\t\tif (this._shadow) {\r\n\t\t\tDomUtil.setOpacity(this._shadow, opacity);\r\n\t\t}\r\n\t},\r\n\r\n\t_bringToFront: function () {\r\n\t\tthis._updateZIndex(this.options.riseOffset);\r\n\t},\r\n\r\n\t_resetZIndex: function () {\r\n\t\tthis._updateZIndex(0);\r\n\t},\r\n\r\n\t_panOnFocus: function () {\r\n\t\tvar map = this._map;\r\n\t\tif (!map) { return; }\r\n\r\n\t\tvar iconOpts = this.options.icon.options;\r\n\t\tvar size = iconOpts.iconSize ? point(iconOpts.iconSize) : point(0, 0);\r\n\t\tvar anchor = iconOpts.iconAnchor ? point(iconOpts.iconAnchor) : point(0, 0);\r\n\r\n\t\tmap.panInside(this._latlng, {\r\n\t\t\tpaddingTopLeft: anchor,\r\n\t\t\tpaddingBottomRight: size.subtract(anchor)\r\n\t\t});\r\n\t},\r\n\r\n\t_getPopupAnchor: function () {\r\n\t\treturn this.options.icon.options.popupAnchor;\r\n\t},\r\n\r\n\t_getTooltipAnchor: function () {\r\n\t\treturn this.options.icon.options.tooltipAnchor;\r\n\t}\r\n});\r\n\r\n\r\n// factory L.marker(latlng: LatLng, options? : Marker options)\r\n\r\n// @factory L.marker(latlng: LatLng, options? : Marker options)\r\n// Instantiates a Marker object given a geographical point and optionally an options object.\r\nexport function marker(latlng, options) {\r\n\treturn new Marker(latlng, options);\r\n}\r\n","import {Layer} from '../Layer';\nimport * as Util from '../../core/Util';\n\n/*\n * @class Path\n * @aka L.Path\n * @inherits Interactive layer\n *\n * An abstract class that contains options and constants shared between vector\n * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.\n */\n\nexport var Path = Layer.extend({\n\n\t// @section\n\t// @aka Path options\n\toptions: {\n\t\t// @option stroke: Boolean = true\n\t\t// Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.\n\t\tstroke: true,\n\n\t\t// @option color: String = '#3388ff'\n\t\t// Stroke color\n\t\tcolor: '#3388ff',\n\n\t\t// @option weight: Number = 3\n\t\t// Stroke width in pixels\n\t\tweight: 3,\n\n\t\t// @option opacity: Number = 1.0\n\t\t// Stroke opacity\n\t\topacity: 1,\n\n\t\t// @option lineCap: String= 'round'\n\t\t// A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.\n\t\tlineCap: 'round',\n\n\t\t// @option lineJoin: String = 'round'\n\t\t// A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.\n\t\tlineJoin: 'round',\n\n\t\t// @option dashArray: String = null\n\t\t// A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).\n\t\tdashArray: null,\n\n\t\t// @option dashOffset: String = null\n\t\t// A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).\n\t\tdashOffset: null,\n\n\t\t// @option fill: Boolean = depends\n\t\t// Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.\n\t\tfill: false,\n\n\t\t// @option fillColor: String = *\n\t\t// Fill color. Defaults to the value of the [`color`](#path-color) option\n\t\tfillColor: null,\n\n\t\t// @option fillOpacity: Number = 0.2\n\t\t// Fill opacity.\n\t\tfillOpacity: 0.2,\n\n\t\t// @option fillRule: String = 'evenodd'\n\t\t// A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.\n\t\tfillRule: 'evenodd',\n\n\t\t// className: '',\n\n\t\t// Option inherited from \"Interactive layer\" abstract class\n\t\tinteractive: true,\n\n\t\t// @option bubblingMouseEvents: Boolean = true\n\t\t// When `true`, a mouse event on this path will trigger the same event on the map\n\t\t// (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).\n\t\tbubblingMouseEvents: true\n\t},\n\n\tbeforeAdd: function (map) {\n\t\t// Renderer is set here because we need to call renderer.getEvents\n\t\t// before this.getEvents.\n\t\tthis._renderer = map.getRenderer(this);\n\t},\n\n\tonAdd: function () {\n\t\tthis._renderer._initPath(this);\n\t\tthis._reset();\n\t\tthis._renderer._addPath(this);\n\t},\n\n\tonRemove: function () {\n\t\tthis._renderer._removePath(this);\n\t},\n\n\t// @method redraw(): this\n\t// Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.\n\tredraw: function () {\n\t\tif (this._map) {\n\t\t\tthis._renderer._updatePath(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method setStyle(style: Path options): this\n\t// Changes the appearance of a Path based on the options in the `Path options` object.\n\tsetStyle: function (style) {\n\t\tUtil.setOptions(this, style);\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._updateStyle(this);\n\t\t\tif (this.options.stroke && style && Object.prototype.hasOwnProperty.call(style, 'weight')) {\n\t\t\t\tthis._updateBounds();\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method bringToFront(): this\n\t// Brings the layer to the top of all path layers.\n\tbringToFront: function () {\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._bringToFront(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method bringToBack(): this\n\t// Brings the layer to the bottom of all path layers.\n\tbringToBack: function () {\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._bringToBack(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\tgetElement: function () {\n\t\treturn this._path;\n\t},\n\n\t_reset: function () {\n\t\t// defined in child classes\n\t\tthis._project();\n\t\tthis._update();\n\t},\n\n\t_clickTolerance: function () {\n\t\t// used when doing hit detection for Canvas layers\n\t\treturn (this.options.stroke ? this.options.weight / 2 : 0) +\n\t\t  (this._renderer.options.tolerance || 0);\n\t}\n});\n","import {Path} from './Path';\nimport * as Util from '../../core/Util';\nimport {toLatLng} from '../../geo/LatLng';\nimport {Bounds} from '../../geometry/Bounds';\n\n\n/*\n * @class CircleMarker\n * @aka L.CircleMarker\n * @inherits Path\n *\n * A circle of a fixed size with radius specified in pixels. Extends `Path`.\n */\n\nexport var CircleMarker = Path.extend({\n\n\t// @section\n\t// @aka CircleMarker options\n\toptions: {\n\t\tfill: true,\n\n\t\t// @option radius: Number = 10\n\t\t// Radius of the circle marker, in pixels\n\t\tradius: 10\n\t},\n\n\tinitialize: function (latlng, options) {\n\t\tUtil.setOptions(this, options);\n\t\tthis._latlng = toLatLng(latlng);\n\t\tthis._radius = this.options.radius;\n\t},\n\n\t// @method setLatLng(latLng: LatLng): this\n\t// Sets the position of a circle marker to a new location.\n\tsetLatLng: function (latlng) {\n\t\tvar oldLatLng = this._latlng;\n\t\tthis._latlng = toLatLng(latlng);\n\t\tthis.redraw();\n\n\t\t// @event move: Event\n\t\t// Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.\n\t\treturn this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});\n\t},\n\n\t// @method getLatLng(): LatLng\n\t// Returns the current geographical position of the circle marker\n\tgetLatLng: function () {\n\t\treturn this._latlng;\n\t},\n\n\t// @method setRadius(radius: Number): this\n\t// Sets the radius of a circle marker. Units are in pixels.\n\tsetRadius: function (radius) {\n\t\tthis.options.radius = this._radius = radius;\n\t\treturn this.redraw();\n\t},\n\n\t// @method getRadius(): Number\n\t// Returns the current radius of the circle\n\tgetRadius: function () {\n\t\treturn this._radius;\n\t},\n\n\tsetStyle : function (options) {\n\t\tvar radius = options && options.radius || this._radius;\n\t\tPath.prototype.setStyle.call(this, options);\n\t\tthis.setRadius(radius);\n\t\treturn this;\n\t},\n\n\t_project: function () {\n\t\tthis._point = this._map.latLngToLayerPoint(this._latlng);\n\t\tthis._updateBounds();\n\t},\n\n\t_updateBounds: function () {\n\t\tvar r = this._radius,\n\t\t    r2 = this._radiusY || r,\n\t\t    w = this._clickTolerance(),\n\t\t    p = [r + w, r2 + w];\n\t\tthis._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));\n\t},\n\n\t_update: function () {\n\t\tif (this._map) {\n\t\t\tthis._updatePath();\n\t\t}\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updateCircle(this);\n\t},\n\n\t_empty: function () {\n\t\treturn this._radius && !this._renderer._bounds.intersects(this._pxBounds);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p) {\n\t\treturn p.distanceTo(this._point) <= this._radius + this._clickTolerance();\n\t}\n});\n\n\n// @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)\n// Instantiates a circle marker object given a geographical point, and an optional options object.\nexport function circleMarker(latlng, options) {\n\treturn new CircleMarker(latlng, options);\n}\n","import {CircleMarker} from './CircleMarker';\nimport {Path} from './Path';\nimport * as Util from '../../core/Util';\nimport {toLatLng} from '../../geo/LatLng';\nimport {LatLngBounds} from '../../geo/LatLngBounds';\nimport {Earth} from '../../geo/crs/CRS.Earth';\n\n\n/*\n * @class Circle\n * @aka L.Circle\n * @inherits CircleMarker\n *\n * A class for drawing circle overlays on a map. Extends `CircleMarker`.\n *\n * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).\n *\n * @example\n *\n * ```js\n * L.circle([50.5, 30.5], {radius: 200}).addTo(map);\n * ```\n */\n\nexport var Circle = CircleMarker.extend({\n\n\tinitialize: function (latlng, options, legacyOptions) {\n\t\tif (typeof options === 'number') {\n\t\t\t// Backwards compatibility with 0.7.x factory (latlng, radius, options?)\n\t\t\toptions = Util.extend({}, legacyOptions, {radius: options});\n\t\t}\n\t\tUtil.setOptions(this, options);\n\t\tthis._latlng = toLatLng(latlng);\n\n\t\tif (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }\n\n\t\t// @section\n\t\t// @aka Circle options\n\t\t// @option radius: Number; Radius of the circle, in meters.\n\t\tthis._mRadius = this.options.radius;\n\t},\n\n\t// @method setRadius(radius: Number): this\n\t// Sets the radius of a circle. Units are in meters.\n\tsetRadius: function (radius) {\n\t\tthis._mRadius = radius;\n\t\treturn this.redraw();\n\t},\n\n\t// @method getRadius(): Number\n\t// Returns the current radius of a circle. Units are in meters.\n\tgetRadius: function () {\n\t\treturn this._mRadius;\n\t},\n\n\t// @method getBounds(): LatLngBounds\n\t// Returns the `LatLngBounds` of the path.\n\tgetBounds: function () {\n\t\tvar half = [this._radius, this._radiusY || this._radius];\n\n\t\treturn new LatLngBounds(\n\t\t\tthis._map.layerPointToLatLng(this._point.subtract(half)),\n\t\t\tthis._map.layerPointToLatLng(this._point.add(half)));\n\t},\n\n\tsetStyle: Path.prototype.setStyle,\n\n\t_project: function () {\n\n\t\tvar lng = this._latlng.lng,\n\t\t    lat = this._latlng.lat,\n\t\t    map = this._map,\n\t\t    crs = map.options.crs;\n\n\t\tif (crs.distance === Earth.distance) {\n\t\t\tvar d = Math.PI / 180,\n\t\t\t    latR = (this._mRadius / Earth.R) / d,\n\t\t\t    top = map.project([lat + latR, lng]),\n\t\t\t    bottom = map.project([lat - latR, lng]),\n\t\t\t    p = top.add(bottom).divideBy(2),\n\t\t\t    lat2 = map.unproject(p).lat,\n\t\t\t    lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /\n\t\t\t            (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;\n\n\t\t\tif (isNaN(lngR) || lngR === 0) {\n\t\t\t\tlngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425\n\t\t\t}\n\n\t\t\tthis._point = p.subtract(map.getPixelOrigin());\n\t\t\tthis._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;\n\t\t\tthis._radiusY = p.y - top.y;\n\n\t\t} else {\n\t\t\tvar latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));\n\n\t\t\tthis._point = map.latLngToLayerPoint(this._latlng);\n\t\t\tthis._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;\n\t\t}\n\n\t\tthis._updateBounds();\n\t}\n});\n\n// @factory L.circle(latlng: LatLng, options?: Circle options)\n// Instantiates a circle object given a geographical point, and an options object\n// which contains the circle radius.\n// @alternative\n// @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)\n// Obsolete way of instantiating a circle, for compatibility with 0.7.x code.\n// Do not use in new applications or plugins.\nexport function circle(latlng, options, legacyOptions) {\n\treturn new Circle(latlng, options, legacyOptions);\n}\n","import {Path} from './Path';\nimport * as Util from '../../core/Util';\nimport * as LineUtil from '../../geometry/LineUtil';\nimport {LatLng, toLatLng} from '../../geo/LatLng';\nimport {LatLngBounds} from '../../geo/LatLngBounds';\nimport {Bounds} from '../../geometry/Bounds';\nimport {Point} from '../../geometry/Point';\n\n/*\n * @class Polyline\n * @aka L.Polyline\n * @inherits Path\n *\n * A class for drawing polyline overlays on a map. Extends `Path`.\n *\n * @example\n *\n * ```js\n * // create a red polyline from an array of LatLng points\n * var latlngs = [\n * \t[45.51, -122.68],\n * \t[37.77, -122.43],\n * \t[34.04, -118.2]\n * ];\n *\n * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);\n *\n * // zoom the map to the polyline\n * map.fitBounds(polyline.getBounds());\n * ```\n *\n * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:\n *\n * ```js\n * // create a red polyline from an array of arrays of LatLng points\n * var latlngs = [\n * \t[[45.51, -122.68],\n * \t [37.77, -122.43],\n * \t [34.04, -118.2]],\n * \t[[40.78, -73.91],\n * \t [41.83, -87.62],\n * \t [32.76, -96.72]]\n * ];\n * ```\n */\n\n\nexport var Polyline = Path.extend({\n\n\t// @section\n\t// @aka Polyline options\n\toptions: {\n\t\t// @option smoothFactor: Number = 1.0\n\t\t// How much to simplify the polyline on each zoom level. More means\n\t\t// better performance and smoother look, and less means more accurate representation.\n\t\tsmoothFactor: 1.0,\n\n\t\t// @option noClip: Boolean = false\n\t\t// Disable polyline clipping.\n\t\tnoClip: false\n\t},\n\n\tinitialize: function (latlngs, options) {\n\t\tUtil.setOptions(this, options);\n\t\tthis._setLatLngs(latlngs);\n\t},\n\n\t// @method getLatLngs(): LatLng[]\n\t// Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.\n\tgetLatLngs: function () {\n\t\treturn this._latlngs;\n\t},\n\n\t// @method setLatLngs(latlngs: LatLng[]): this\n\t// Replaces all the points in the polyline with the given array of geographical points.\n\tsetLatLngs: function (latlngs) {\n\t\tthis._setLatLngs(latlngs);\n\t\treturn this.redraw();\n\t},\n\n\t// @method isEmpty(): Boolean\n\t// Returns `true` if the Polyline has no LatLngs.\n\tisEmpty: function () {\n\t\treturn !this._latlngs.length;\n\t},\n\n\t// @method closestLayerPoint(p: Point): Point\n\t// Returns the point closest to `p` on the Polyline.\n\tclosestLayerPoint: function (p) {\n\t\tvar minDistance = Infinity,\n\t\t    minPoint = null,\n\t\t    closest = LineUtil._sqClosestPointOnSegment,\n\t\t    p1, p2;\n\n\t\tfor (var j = 0, jLen = this._parts.length; j < jLen; j++) {\n\t\t\tvar points = this._parts[j];\n\n\t\t\tfor (var i = 1, len = points.length; i < len; i++) {\n\t\t\t\tp1 = points[i - 1];\n\t\t\t\tp2 = points[i];\n\n\t\t\t\tvar sqDist = closest(p, p1, p2, true);\n\n\t\t\t\tif (sqDist < minDistance) {\n\t\t\t\t\tminDistance = sqDist;\n\t\t\t\t\tminPoint = closest(p, p1, p2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (minPoint) {\n\t\t\tminPoint.distance = Math.sqrt(minDistance);\n\t\t}\n\t\treturn minPoint;\n\t},\n\n\t// @method getCenter(): LatLng\n\t// Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline.\n\tgetCenter: function () {\n\t\t// throws error when not yet added to map as this center calculation requires projected coordinates\n\t\tif (!this._map) {\n\t\t\tthrow new Error('Must add layer to map before using getCenter()');\n\t\t}\n\t\treturn LineUtil.polylineCenter(this._defaultShape(), this._map.options.crs);\n\t},\n\n\t// @method getBounds(): LatLngBounds\n\t// Returns the `LatLngBounds` of the path.\n\tgetBounds: function () {\n\t\treturn this._bounds;\n\t},\n\n\t// @method addLatLng(latlng: LatLng, latlngs?: LatLng[]): this\n\t// Adds a given point to the polyline. By default, adds to the first ring of\n\t// the polyline in case of a multi-polyline, but can be overridden by passing\n\t// a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).\n\taddLatLng: function (latlng, latlngs) {\n\t\tlatlngs = latlngs || this._defaultShape();\n\t\tlatlng = toLatLng(latlng);\n\t\tlatlngs.push(latlng);\n\t\tthis._bounds.extend(latlng);\n\t\treturn this.redraw();\n\t},\n\n\t_setLatLngs: function (latlngs) {\n\t\tthis._bounds = new LatLngBounds();\n\t\tthis._latlngs = this._convertLatLngs(latlngs);\n\t},\n\n\t_defaultShape: function () {\n\t\treturn LineUtil.isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];\n\t},\n\n\t// recursively convert latlngs input into actual LatLng instances; calculate bounds along the way\n\t_convertLatLngs: function (latlngs) {\n\t\tvar result = [],\n\t\t    flat = LineUtil.isFlat(latlngs);\n\n\t\tfor (var i = 0, len = latlngs.length; i < len; i++) {\n\t\t\tif (flat) {\n\t\t\t\tresult[i] = toLatLng(latlngs[i]);\n\t\t\t\tthis._bounds.extend(result[i]);\n\t\t\t} else {\n\t\t\t\tresult[i] = this._convertLatLngs(latlngs[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t},\n\n\t_project: function () {\n\t\tvar pxBounds = new Bounds();\n\t\tthis._rings = [];\n\t\tthis._projectLatlngs(this._latlngs, this._rings, pxBounds);\n\n\t\tif (this._bounds.isValid() && pxBounds.isValid()) {\n\t\t\tthis._rawPxBounds = pxBounds;\n\t\t\tthis._updateBounds();\n\t\t}\n\t},\n\n\t_updateBounds: function () {\n\t\tvar w = this._clickTolerance(),\n\t\t    p = new Point(w, w);\n\n\t\tif (!this._rawPxBounds) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._pxBounds = new Bounds([\n\t\t\tthis._rawPxBounds.min.subtract(p),\n\t\t\tthis._rawPxBounds.max.add(p)\n\t\t]);\n\t},\n\n\t// recursively turns latlngs into a set of rings with projected coordinates\n\t_projectLatlngs: function (latlngs, result, projectedBounds) {\n\t\tvar flat = latlngs[0] instanceof LatLng,\n\t\t    len = latlngs.length,\n\t\t    i, ring;\n\n\t\tif (flat) {\n\t\t\tring = [];\n\t\t\tfor (i = 0; i < len; i++) {\n\t\t\t\tring[i] = this._map.latLngToLayerPoint(latlngs[i]);\n\t\t\t\tprojectedBounds.extend(ring[i]);\n\t\t\t}\n\t\t\tresult.push(ring);\n\t\t} else {\n\t\t\tfor (i = 0; i < len; i++) {\n\t\t\t\tthis._projectLatlngs(latlngs[i], result, projectedBounds);\n\t\t\t}\n\t\t}\n\t},\n\n\t// clip polyline by renderer bounds so that we have less to render for performance\n\t_clipPoints: function () {\n\t\tvar bounds = this._renderer._bounds;\n\n\t\tthis._parts = [];\n\t\tif (!this._pxBounds || !this._pxBounds.intersects(bounds)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.options.noClip) {\n\t\t\tthis._parts = this._rings;\n\t\t\treturn;\n\t\t}\n\n\t\tvar parts = this._parts,\n\t\t    i, j, k, len, len2, segment, points;\n\n\t\tfor (i = 0, k = 0, len = this._rings.length; i < len; i++) {\n\t\t\tpoints = this._rings[i];\n\n\t\t\tfor (j = 0, len2 = points.length; j < len2 - 1; j++) {\n\t\t\t\tsegment = LineUtil.clipSegment(points[j], points[j + 1], bounds, j, true);\n\n\t\t\t\tif (!segment) { continue; }\n\n\t\t\t\tparts[k] = parts[k] || [];\n\t\t\t\tparts[k].push(segment[0]);\n\n\t\t\t\t// if segment goes out of screen, or it's the last one, it's the end of the line part\n\t\t\t\tif ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {\n\t\t\t\t\tparts[k].push(segment[1]);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n\n\t// simplify each clipped part of the polyline for performance\n\t_simplifyPoints: function () {\n\t\tvar parts = this._parts,\n\t\t    tolerance = this.options.smoothFactor;\n\n\t\tfor (var i = 0, len = parts.length; i < len; i++) {\n\t\t\tparts[i] = LineUtil.simplify(parts[i], tolerance);\n\t\t}\n\t},\n\n\t_update: function () {\n\t\tif (!this._map) { return; }\n\n\t\tthis._clipPoints();\n\t\tthis._simplifyPoints();\n\t\tthis._updatePath();\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updatePoly(this);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p, closed) {\n\t\tvar i, j, k, len, len2, part,\n\t\t    w = this._clickTolerance();\n\n\t\tif (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }\n\n\t\t// hit detection for polylines\n\t\tfor (i = 0, len = this._parts.length; i < len; i++) {\n\t\t\tpart = this._parts[i];\n\n\t\t\tfor (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {\n\t\t\t\tif (!closed && (j === 0)) { continue; }\n\n\t\t\t\tif (LineUtil.pointToSegmentDistance(p, part[k], part[j]) <= w) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n});\n\n// @factory L.polyline(latlngs: LatLng[], options?: Polyline options)\n// Instantiates a polyline object given an array of geographical points and\n// optionally an options object. You can create a `Polyline` object with\n// multiple separate lines (`MultiPolyline`) by passing an array of arrays\n// of geographic points.\nexport function polyline(latlngs, options) {\n\treturn new Polyline(latlngs, options);\n}\n\n// Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.\nPolyline._flat = LineUtil._flat;\n","import {Polyline} from './Polyline';\nimport {LatLng} from '../../geo/LatLng';\nimport * as LineUtil from '../../geometry/LineUtil';\nimport {Point} from '../../geometry/Point';\nimport {Bounds} from '../../geometry/Bounds';\nimport * as PolyUtil from '../../geometry/PolyUtil';\n\n/*\n * @class Polygon\n * @aka L.Polygon\n * @inherits Polyline\n *\n * A class for drawing polygon overlays on a map. Extends `Polyline`.\n *\n * Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points.\n *\n *\n * @example\n *\n * ```js\n * // create a red polygon from an array of LatLng points\n * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];\n *\n * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);\n *\n * // zoom the map to the polygon\n * map.fitBounds(polygon.getBounds());\n * ```\n *\n * You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape:\n *\n * ```js\n * var latlngs = [\n *   [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring\n *   [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole\n * ];\n * ```\n *\n * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.\n *\n * ```js\n * var latlngs = [\n *   [ // first polygon\n *     [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring\n *     [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole\n *   ],\n *   [ // second polygon\n *     [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]\n *   ]\n * ];\n * ```\n */\n\nexport var Polygon = Polyline.extend({\n\n\toptions: {\n\t\tfill: true\n\t},\n\n\tisEmpty: function () {\n\t\treturn !this._latlngs.length || !this._latlngs[0].length;\n\t},\n\n\t// @method getCenter(): LatLng\n\t// Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the Polygon.\n\tgetCenter: function () {\n\t\t// throws error when not yet added to map as this center calculation requires projected coordinates\n\t\tif (!this._map) {\n\t\t\tthrow new Error('Must add layer to map before using getCenter()');\n\t\t}\n\t\treturn PolyUtil.polygonCenter(this._defaultShape(), this._map.options.crs);\n\t},\n\n\t_convertLatLngs: function (latlngs) {\n\t\tvar result = Polyline.prototype._convertLatLngs.call(this, latlngs),\n\t\t    len = result.length;\n\n\t\t// remove last point if it equals first one\n\t\tif (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {\n\t\t\tresult.pop();\n\t\t}\n\t\treturn result;\n\t},\n\n\t_setLatLngs: function (latlngs) {\n\t\tPolyline.prototype._setLatLngs.call(this, latlngs);\n\t\tif (LineUtil.isFlat(this._latlngs)) {\n\t\t\tthis._latlngs = [this._latlngs];\n\t\t}\n\t},\n\n\t_defaultShape: function () {\n\t\treturn LineUtil.isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];\n\t},\n\n\t_clipPoints: function () {\n\t\t// polygons need a different clipping algorithm so we redefine that\n\n\t\tvar bounds = this._renderer._bounds,\n\t\t    w = this.options.weight,\n\t\t    p = new Point(w, w);\n\n\t\t// increase clip padding by stroke width to avoid stroke on clip edges\n\t\tbounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));\n\n\t\tthis._parts = [];\n\t\tif (!this._pxBounds || !this._pxBounds.intersects(bounds)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.options.noClip) {\n\t\t\tthis._parts = this._rings;\n\t\t\treturn;\n\t\t}\n\n\t\tfor (var i = 0, len = this._rings.length, clipped; i < len; i++) {\n\t\t\tclipped = PolyUtil.clipPolygon(this._rings[i], bounds, true);\n\t\t\tif (clipped.length) {\n\t\t\t\tthis._parts.push(clipped);\n\t\t\t}\n\t\t}\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updatePoly(this, true);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p) {\n\t\tvar inside = false,\n\t\t    part, p1, p2, i, j, k, len, len2;\n\n\t\tif (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }\n\n\t\t// ray casting algorithm for detecting if point is in polygon\n\t\tfor (i = 0, len = this._parts.length; i < len; i++) {\n\t\t\tpart = this._parts[i];\n\n\t\t\tfor (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {\n\t\t\t\tp1 = part[j];\n\t\t\t\tp2 = part[k];\n\n\t\t\t\tif (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {\n\t\t\t\t\tinside = !inside;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// also check if it's on polygon stroke\n\t\treturn inside || Polyline.prototype._containsPoint.call(this, p, true);\n\t}\n\n});\n\n\n// @factory L.polygon(latlngs: LatLng[], options?: Polyline options)\nexport function polygon(latlngs, options) {\n\treturn new Polygon(latlngs, options);\n}\n","import {LayerGroup} from './LayerGroup';\r\nimport {FeatureGroup} from './FeatureGroup';\r\nimport * as Util from '../core/Util';\r\nimport {Marker} from './marker/Marker';\r\nimport {Circle} from './vector/Circle';\r\nimport {CircleMarker} from './vector/CircleMarker';\r\nimport {Polyline} from './vector/Polyline';\r\nimport {Polygon} from './vector/Polygon';\r\nimport {LatLng} from '../geo/LatLng';\r\nimport * as LineUtil from '../geometry/LineUtil';\r\nimport {toLatLng} from '../geo/LatLng';\r\n\r\n\r\n/*\r\n * @class GeoJSON\r\n * @aka L.GeoJSON\r\n * @inherits FeatureGroup\r\n *\r\n * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse\r\n * GeoJSON data and display it on the map. Extends `FeatureGroup`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.geoJSON(data, {\r\n * \tstyle: function (feature) {\r\n * \t\treturn {color: feature.properties.color};\r\n * \t}\r\n * }).bindPopup(function (layer) {\r\n * \treturn layer.feature.properties.description;\r\n * }).addTo(map);\r\n * ```\r\n */\r\n\r\nexport var GeoJSON = FeatureGroup.extend({\r\n\r\n\t/* @section\r\n\t * @aka GeoJSON options\r\n\t *\r\n\t * @option pointToLayer: Function = *\r\n\t * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally\r\n\t * called when data is added, passing the GeoJSON point feature and its `LatLng`.\r\n\t * The default is to spawn a default `Marker`:\r\n\t * ```js\r\n\t * function(geoJsonPoint, latlng) {\r\n\t * \treturn L.marker(latlng);\r\n\t * }\r\n\t * ```\r\n\t *\r\n\t * @option style: Function = *\r\n\t * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,\r\n\t * called internally when data is added.\r\n\t * The default value is to not override any defaults:\r\n\t * ```js\r\n\t * function (geoJsonFeature) {\r\n\t * \treturn {}\r\n\t * }\r\n\t * ```\r\n\t *\r\n\t * @option onEachFeature: Function = *\r\n\t * A `Function` that will be called once for each created `Feature`, after it has\r\n\t * been created and styled. Useful for attaching events and popups to features.\r\n\t * The default is to do nothing with the newly created layers:\r\n\t * ```js\r\n\t * function (feature, layer) {}\r\n\t * ```\r\n\t *\r\n\t * @option filter: Function = *\r\n\t * A `Function` that will be used to decide whether to include a feature or not.\r\n\t * The default is to include all features:\r\n\t * ```js\r\n\t * function (geoJsonFeature) {\r\n\t * \treturn true;\r\n\t * }\r\n\t * ```\r\n\t * Note: dynamically changing the `filter` option will have effect only on newly\r\n\t * added data. It will _not_ re-evaluate already included features.\r\n\t *\r\n\t * @option coordsToLatLng: Function = *\r\n\t * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.\r\n\t * The default is the `coordsToLatLng` static method.\r\n\t *\r\n\t * @option markersInheritOptions: Boolean = false\r\n\t * Whether default Markers for \"Point\" type Features inherit from group options.\r\n\t */\r\n\r\n\tinitialize: function (geojson, options) {\r\n\t\tUtil.setOptions(this, options);\r\n\r\n\t\tthis._layers = {};\r\n\r\n\t\tif (geojson) {\r\n\t\t\tthis.addData(geojson);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addData( <GeoJSON> data ): this\r\n\t// Adds a GeoJSON object to the layer.\r\n\taddData: function (geojson) {\r\n\t\tvar features = Util.isArray(geojson) ? geojson : geojson.features,\r\n\t\t    i, len, feature;\r\n\r\n\t\tif (features) {\r\n\t\t\tfor (i = 0, len = features.length; i < len; i++) {\r\n\t\t\t\t// only add this if geometry or geometries are set and not null\r\n\t\t\t\tfeature = features[i];\r\n\t\t\t\tif (feature.geometries || feature.geometry || feature.features || feature.coordinates) {\r\n\t\t\t\t\tthis.addData(feature);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tvar options = this.options;\r\n\r\n\t\tif (options.filter && !options.filter(geojson)) { return this; }\r\n\r\n\t\tvar layer = geometryToLayer(geojson, options);\r\n\t\tif (!layer) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\tlayer.feature = asFeature(geojson);\r\n\r\n\t\tlayer.defaultOptions = layer.options;\r\n\t\tthis.resetStyle(layer);\r\n\r\n\t\tif (options.onEachFeature) {\r\n\t\t\toptions.onEachFeature(geojson, layer);\r\n\t\t}\r\n\r\n\t\treturn this.addLayer(layer);\r\n\t},\r\n\r\n\t// @method resetStyle( <Path> layer? ): this\r\n\t// Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.\r\n\t// If `layer` is omitted, the style of all features in the current layer is reset.\r\n\tresetStyle: function (layer) {\r\n\t\tif (layer === undefined) {\r\n\t\t\treturn this.eachLayer(this.resetStyle, this);\r\n\t\t}\r\n\t\t// reset any custom styles\r\n\t\tlayer.options = Util.extend({}, layer.defaultOptions);\r\n\t\tthis._setLayerStyle(layer, this.options.style);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setStyle( <Function> style ): this\r\n\t// Changes styles of GeoJSON vector layers with the given style function.\r\n\tsetStyle: function (style) {\r\n\t\treturn this.eachLayer(function (layer) {\r\n\t\t\tthis._setLayerStyle(layer, style);\r\n\t\t}, this);\r\n\t},\r\n\r\n\t_setLayerStyle: function (layer, style) {\r\n\t\tif (layer.setStyle) {\r\n\t\t\tif (typeof style === 'function') {\r\n\t\t\t\tstyle = style(layer.feature);\r\n\t\t\t}\r\n\t\t\tlayer.setStyle(style);\r\n\t\t}\r\n\t}\r\n});\r\n\r\n// @section\r\n// There are several static functions which can be called without instantiating L.GeoJSON:\r\n\r\n// @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer\r\n// Creates a `Layer` from a given GeoJSON feature. Can use a custom\r\n// [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)\r\n// functions if provided as options.\r\nexport function geometryToLayer(geojson, options) {\r\n\r\n\tvar geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,\r\n\t    coords = geometry ? geometry.coordinates : null,\r\n\t    layers = [],\r\n\t    pointToLayer = options && options.pointToLayer,\r\n\t    _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,\r\n\t    latlng, latlngs, i, len;\r\n\r\n\tif (!coords && !geometry) {\r\n\t\treturn null;\r\n\t}\r\n\r\n\tswitch (geometry.type) {\r\n\tcase 'Point':\r\n\t\tlatlng = _coordsToLatLng(coords);\r\n\t\treturn _pointToLayer(pointToLayer, geojson, latlng, options);\r\n\r\n\tcase 'MultiPoint':\r\n\t\tfor (i = 0, len = coords.length; i < len; i++) {\r\n\t\t\tlatlng = _coordsToLatLng(coords[i]);\r\n\t\t\tlayers.push(_pointToLayer(pointToLayer, geojson, latlng, options));\r\n\t\t}\r\n\t\treturn new FeatureGroup(layers);\r\n\r\n\tcase 'LineString':\r\n\tcase 'MultiLineString':\r\n\t\tlatlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);\r\n\t\treturn new Polyline(latlngs, options);\r\n\r\n\tcase 'Polygon':\r\n\tcase 'MultiPolygon':\r\n\t\tlatlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);\r\n\t\treturn new Polygon(latlngs, options);\r\n\r\n\tcase 'GeometryCollection':\r\n\t\tfor (i = 0, len = geometry.geometries.length; i < len; i++) {\r\n\t\t\tvar geoLayer = geometryToLayer({\r\n\t\t\t\tgeometry: geometry.geometries[i],\r\n\t\t\t\ttype: 'Feature',\r\n\t\t\t\tproperties: geojson.properties\r\n\t\t\t}, options);\r\n\r\n\t\t\tif (geoLayer) {\r\n\t\t\t\tlayers.push(geoLayer);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn new FeatureGroup(layers);\r\n\r\n\tcase 'FeatureCollection':\r\n\t\tfor (i = 0, len = geometry.features.length; i < len; i++) {\r\n\t\t\tvar featureLayer = geometryToLayer(geometry.features[i], options);\r\n\r\n\t\t\tif (featureLayer) {\r\n\t\t\t\tlayers.push(featureLayer);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn new FeatureGroup(layers);\r\n\r\n\tdefault:\r\n\t\tthrow new Error('Invalid GeoJSON object.');\r\n\t}\r\n}\r\n\r\nfunction _pointToLayer(pointToLayerFn, geojson, latlng, options) {\r\n\treturn pointToLayerFn ?\r\n\t\tpointToLayerFn(geojson, latlng) :\r\n\t\tnew Marker(latlng, options && options.markersInheritOptions && options);\r\n}\r\n\r\n// @function coordsToLatLng(coords: Array): LatLng\r\n// Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)\r\n// or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.\r\nexport function coordsToLatLng(coords) {\r\n\treturn new LatLng(coords[1], coords[0], coords[2]);\r\n}\r\n\r\n// @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array\r\n// Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.\r\n// `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).\r\n// Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.\r\nexport function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {\r\n\tvar latlngs = [];\r\n\r\n\tfor (var i = 0, len = coords.length, latlng; i < len; i++) {\r\n\t\tlatlng = levelsDeep ?\r\n\t\t\tcoordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :\r\n\t\t\t(_coordsToLatLng || coordsToLatLng)(coords[i]);\r\n\r\n\t\tlatlngs.push(latlng);\r\n\t}\r\n\r\n\treturn latlngs;\r\n}\r\n\r\n// @function latLngToCoords(latlng: LatLng, precision?: Number|false): Array\r\n// Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function.\r\nexport function latLngToCoords(latlng, precision) {\r\n\tlatlng = toLatLng(latlng);\r\n\treturn latlng.alt !== undefined ?\r\n\t\t[Util.formatNum(latlng.lng, precision), Util.formatNum(latlng.lat, precision), Util.formatNum(latlng.alt, precision)] :\r\n\t\t[Util.formatNum(latlng.lng, precision), Util.formatNum(latlng.lat, precision)];\r\n}\r\n\r\n// @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean, precision?: Number|false): Array\r\n// Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)\r\n// `closed` determines whether the first point should be appended to the end of the array to close the feature, only used when `levelsDeep` is 0. False by default.\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function.\r\nexport function latLngsToCoords(latlngs, levelsDeep, closed, precision) {\r\n\tvar coords = [];\r\n\r\n\tfor (var i = 0, len = latlngs.length; i < len; i++) {\r\n\t\t// Check for flat arrays required to ensure unbalanced arrays are correctly converted in recursion\r\n\t\tcoords.push(levelsDeep ?\r\n\t\t\tlatLngsToCoords(latlngs[i], LineUtil.isFlat(latlngs[i]) ? 0 : levelsDeep - 1, closed, precision) :\r\n\t\t\tlatLngToCoords(latlngs[i], precision));\r\n\t}\r\n\r\n\tif (!levelsDeep && closed && coords.length > 0) {\r\n\t\tcoords.push(coords[0].slice());\r\n\t}\r\n\r\n\treturn coords;\r\n}\r\n\r\nexport function getFeature(layer, newGeometry) {\r\n\treturn layer.feature ?\r\n\t\tUtil.extend({}, layer.feature, {geometry: newGeometry}) :\r\n\t\tasFeature(newGeometry);\r\n}\r\n\r\n// @function asFeature(geojson: Object): Object\r\n// Normalize GeoJSON geometries/features into GeoJSON features.\r\nexport function asFeature(geojson) {\r\n\tif (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {\r\n\t\treturn geojson;\r\n\t}\r\n\r\n\treturn {\r\n\t\ttype: 'Feature',\r\n\t\tproperties: {},\r\n\t\tgeometry: geojson\r\n\t};\r\n}\r\n\r\nvar PointToGeoJSON = {\r\n\ttoGeoJSON: function (precision) {\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: 'Point',\r\n\t\t\tcoordinates: latLngToCoords(this.getLatLng(), precision)\r\n\t\t});\r\n\t}\r\n};\r\n\r\n// @namespace Marker\r\n// @section Other methods\r\n// @method toGeoJSON(precision?: Number|false): Object\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.\r\n// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).\r\nMarker.include(PointToGeoJSON);\r\n\r\n// @namespace CircleMarker\r\n// @method toGeoJSON(precision?: Number|false): Object\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.\r\n// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).\r\nCircle.include(PointToGeoJSON);\r\nCircleMarker.include(PointToGeoJSON);\r\n\r\n\r\n// @namespace Polyline\r\n// @method toGeoJSON(precision?: Number|false): Object\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.\r\n// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).\r\nPolyline.include({\r\n\ttoGeoJSON: function (precision) {\r\n\t\tvar multi = !LineUtil.isFlat(this._latlngs);\r\n\r\n\t\tvar coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: (multi ? 'Multi' : '') + 'LineString',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t}\r\n});\r\n\r\n// @namespace Polygon\r\n// @method toGeoJSON(precision?: Number|false): Object\r\n// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.\r\n// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).\r\nPolygon.include({\r\n\ttoGeoJSON: function (precision) {\r\n\t\tvar holes = !LineUtil.isFlat(this._latlngs),\r\n\t\t    multi = holes && !LineUtil.isFlat(this._latlngs[0]);\r\n\r\n\t\tvar coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);\r\n\r\n\t\tif (!holes) {\r\n\t\t\tcoords = [coords];\r\n\t\t}\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: (multi ? 'Multi' : '') + 'Polygon',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t}\r\n});\r\n\r\n\r\n// @namespace LayerGroup\r\nLayerGroup.include({\r\n\ttoMultiPoint: function (precision) {\r\n\t\tvar coords = [];\r\n\r\n\t\tthis.eachLayer(function (layer) {\r\n\t\t\tcoords.push(layer.toGeoJSON(precision).geometry.coordinates);\r\n\t\t});\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: 'MultiPoint',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t},\r\n\r\n\t// @method toGeoJSON(precision?: Number|false): Object\r\n\t// Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.\r\n\t// Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).\r\n\ttoGeoJSON: function (precision) {\r\n\r\n\t\tvar type = this.feature && this.feature.geometry && this.feature.geometry.type;\r\n\r\n\t\tif (type === 'MultiPoint') {\r\n\t\t\treturn this.toMultiPoint(precision);\r\n\t\t}\r\n\r\n\t\tvar isGeometryCollection = type === 'GeometryCollection',\r\n\t\t    jsons = [];\r\n\r\n\t\tthis.eachLayer(function (layer) {\r\n\t\t\tif (layer.toGeoJSON) {\r\n\t\t\t\tvar json = layer.toGeoJSON(precision);\r\n\t\t\t\tif (isGeometryCollection) {\r\n\t\t\t\t\tjsons.push(json.geometry);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tvar feature = asFeature(json);\r\n\t\t\t\t\t// Squash nested feature collections\r\n\t\t\t\t\tif (feature.type === 'FeatureCollection') {\r\n\t\t\t\t\t\tjsons.push.apply(jsons, feature.features);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tjsons.push(feature);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tif (isGeometryCollection) {\r\n\t\t\treturn getFeature(this, {\r\n\t\t\t\tgeometries: jsons,\r\n\t\t\t\ttype: 'GeometryCollection'\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\treturn {\r\n\t\t\ttype: 'FeatureCollection',\r\n\t\t\tfeatures: jsons\r\n\t\t};\r\n\t}\r\n});\r\n\r\n// @namespace GeoJSON\r\n// @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)\r\n// Creates a GeoJSON layer. Optionally accepts an object in\r\n// [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map\r\n// (you can alternatively add it later with `addData` method) and an `options` object.\r\nexport function geoJSON(geojson, options) {\r\n\treturn new GeoJSON(geojson, options);\r\n}\r\n\r\n// Backward compatibility.\r\nexport var geoJson = geoJSON;\r\n","import {Layer} from './Layer';\r\nimport * as Util from '../core/Util';\r\nimport {toLatLngBounds} from '../geo/LatLngBounds';\r\nimport {Bounds} from '../geometry/Bounds';\r\nimport * as DomUtil from '../dom/DomUtil';\r\n\r\n/*\r\n * @class ImageOverlay\r\n * @aka L.ImageOverlay\r\n * @inherits Interactive layer\r\n *\r\n * Used to load and display a single image over specific bounds of the map. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',\r\n * \timageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];\r\n * L.imageOverlay(imageUrl, imageBounds).addTo(map);\r\n * ```\r\n */\r\n\r\nexport var ImageOverlay = Layer.extend({\r\n\r\n\t// @section\r\n\t// @aka ImageOverlay options\r\n\toptions: {\r\n\t\t// @option opacity: Number = 1.0\r\n\t\t// The opacity of the image overlay.\r\n\t\topacity: 1,\r\n\r\n\t\t// @option alt: String = ''\r\n\t\t// Text for the `alt` attribute of the image (useful for accessibility).\r\n\t\talt: '',\r\n\r\n\t\t// @option interactive: Boolean = false\r\n\t\t// If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.\r\n\t\tinteractive: false,\r\n\r\n\t\t// @option crossOrigin: Boolean|String = false\r\n\t\t// Whether the crossOrigin attribute will be added to the image.\r\n\t\t// If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data.\r\n\t\t// Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.\r\n\t\tcrossOrigin: false,\r\n\r\n\t\t// @option errorOverlayUrl: String = ''\r\n\t\t// URL to the overlay image to show in place of the overlay that failed to load.\r\n\t\terrorOverlayUrl: '',\r\n\r\n\t\t// @option zIndex: Number = 1\r\n\t\t// The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.\r\n\t\tzIndex: 1,\r\n\r\n\t\t// @option className: String = ''\r\n\t\t// A custom class name to assign to the image. Empty by default.\r\n\t\tclassName: ''\r\n\t},\r\n\r\n\tinitialize: function (url, bounds, options) { // (String, LatLngBounds, Object)\r\n\t\tthis._url = url;\r\n\t\tthis._bounds = toLatLngBounds(bounds);\r\n\r\n\t\tUtil.setOptions(this, options);\r\n\t},\r\n\r\n\tonAdd: function () {\r\n\t\tif (!this._image) {\r\n\t\t\tthis._initImage();\r\n\r\n\t\t\tif (this.options.opacity < 1) {\r\n\t\t\t\tthis._updateOpacity();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (this.options.interactive) {\r\n\t\t\tDomUtil.addClass(this._image, 'leaflet-interactive');\r\n\t\t\tthis.addInteractiveTarget(this._image);\r\n\t\t}\r\n\r\n\t\tthis.getPane().appendChild(this._image);\r\n\t\tthis._reset();\r\n\t},\r\n\r\n\tonRemove: function () {\r\n\t\tDomUtil.remove(this._image);\r\n\t\tif (this.options.interactive) {\r\n\t\t\tthis.removeInteractiveTarget(this._image);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method setOpacity(opacity: Number): this\r\n\t// Sets the opacity of the overlay.\r\n\tsetOpacity: function (opacity) {\r\n\t\tthis.options.opacity = opacity;\r\n\r\n\t\tif (this._image) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\tsetStyle: function (styleOpts) {\r\n\t\tif (styleOpts.opacity) {\r\n\t\t\tthis.setOpacity(styleOpts.opacity);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method bringToFront(): this\r\n\t// Brings the layer to the top of all overlays.\r\n\tbringToFront: function () {\r\n\t\tif (this._map) {\r\n\t\t\tDomUtil.toFront(this._image);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method bringToBack(): this\r\n\t// Brings the layer to the bottom of all overlays.\r\n\tbringToBack: function () {\r\n\t\tif (this._map) {\r\n\t\t\tDomUtil.toBack(this._image);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setUrl(url: String): this\r\n\t// Changes the URL of the image.\r\n\tsetUrl: function (url) {\r\n\t\tthis._url = url;\r\n\r\n\t\tif (this._image) {\r\n\t\t\tthis._image.src = url;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setBounds(bounds: LatLngBounds): this\r\n\t// Update the bounds that this ImageOverlay covers\r\n\tsetBounds: function (bounds) {\r\n\t\tthis._bounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._reset();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\tvar events = {\r\n\t\t\tzoom: this._reset,\r\n\t\t\tviewreset: this._reset\r\n\t\t};\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tevents.zoomanim = this._animateZoom;\r\n\t\t}\r\n\r\n\t\treturn events;\r\n\t},\r\n\r\n\t// @method setZIndex(value: Number): this\r\n\t// Changes the [zIndex](#imageoverlay-zindex) of the image overlay.\r\n\tsetZIndex: function (value) {\r\n\t\tthis.options.zIndex = value;\r\n\t\tthis._updateZIndex();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Get the bounds that this ImageOverlay covers\r\n\tgetBounds: function () {\r\n\t\treturn this._bounds;\r\n\t},\r\n\r\n\t// @method getElement(): HTMLElement\r\n\t// Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)\r\n\t// used by this overlay.\r\n\tgetElement: function () {\r\n\t\treturn this._image;\r\n\t},\r\n\r\n\t_initImage: function () {\r\n\t\tvar wasElementSupplied = this._url.tagName === 'IMG';\r\n\t\tvar img = this._image = wasElementSupplied ? this._url : DomUtil.create('img');\r\n\r\n\t\tDomUtil.addClass(img, 'leaflet-image-layer');\r\n\t\tif (this._zoomAnimated) { DomUtil.addClass(img, 'leaflet-zoom-animated'); }\r\n\t\tif (this.options.className) { DomUtil.addClass(img, this.options.className); }\r\n\r\n\t\timg.onselectstart = Util.falseFn;\r\n\t\timg.onmousemove = Util.falseFn;\r\n\r\n\t\t// @event load: Event\r\n\t\t// Fired when the ImageOverlay layer has loaded its image\r\n\t\timg.onload = Util.bind(this.fire, this, 'load');\r\n\t\timg.onerror = Util.bind(this._overlayOnError, this, 'error');\r\n\r\n\t\tif (this.options.crossOrigin || this.options.crossOrigin === '') {\r\n\t\t\timg.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;\r\n\t\t}\r\n\r\n\t\tif (this.options.zIndex) {\r\n\t\t\tthis._updateZIndex();\r\n\t\t}\r\n\r\n\t\tif (wasElementSupplied) {\r\n\t\t\tthis._url = img.src;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\timg.src = this._url;\r\n\t\timg.alt = this.options.alt;\r\n\t},\r\n\r\n\t_animateZoom: function (e) {\r\n\t\tvar scale = this._map.getZoomScale(e.zoom),\r\n\t\t    offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;\r\n\r\n\t\tDomUtil.setTransform(this._image, offset, scale);\r\n\t},\r\n\r\n\t_reset: function () {\r\n\t\tvar image = this._image,\r\n\t\t    bounds = new Bounds(\r\n\t\t        this._map.latLngToLayerPoint(this._bounds.getNorthWest()),\r\n\t\t        this._map.latLngToLayerPoint(this._bounds.getSouthEast())),\r\n\t\t    size = bounds.getSize();\r\n\r\n\t\tDomUtil.setPosition(image, bounds.min);\r\n\r\n\t\timage.style.width  = size.x + 'px';\r\n\t\timage.style.height = size.y + 'px';\r\n\t},\r\n\r\n\t_updateOpacity: function () {\r\n\t\tDomUtil.setOpacity(this._image, this.options.opacity);\r\n\t},\r\n\r\n\t_updateZIndex: function () {\r\n\t\tif (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {\r\n\t\t\tthis._image.style.zIndex = this.options.zIndex;\r\n\t\t}\r\n\t},\r\n\r\n\t_overlayOnError: function () {\r\n\t\t// @event error: Event\r\n\t\t// Fired when the ImageOverlay layer fails to load its image\r\n\t\tthis.fire('error');\r\n\r\n\t\tvar errorUrl = this.options.errorOverlayUrl;\r\n\t\tif (errorUrl && this._url !== errorUrl) {\r\n\t\t\tthis._url = errorUrl;\r\n\t\t\tthis._image.src = errorUrl;\r\n\t\t}\r\n\t},\r\n\r\n\t// @method getCenter(): LatLng\r\n\t// Returns the center of the ImageOverlay.\r\n\tgetCenter: function () {\r\n\t\treturn this._bounds.getCenter();\r\n\t}\r\n});\r\n\r\n// @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)\r\n// Instantiates an image overlay object given the URL of the image and the\r\n// geographical bounds it is tied to.\r\nexport var imageOverlay = function (url, bounds, options) {\r\n\treturn new ImageOverlay(url, bounds, options);\r\n};\r\n","import {ImageOverlay} from './ImageOverlay';\r\nimport * as DomUtil from '../dom/DomUtil';\r\nimport * as Util from '../core/Util';\r\n\r\n/*\r\n * @class VideoOverlay\r\n * @aka L.VideoOverlay\r\n * @inherits ImageOverlay\r\n *\r\n * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.\r\n *\r\n * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)\r\n * HTML5 element.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',\r\n * \tvideoBounds = [[ 32, -130], [ 13, -100]];\r\n * L.videoOverlay(videoUrl, videoBounds ).addTo(map);\r\n * ```\r\n */\r\n\r\nexport var VideoOverlay = ImageOverlay.extend({\r\n\r\n\t// @section\r\n\t// @aka VideoOverlay options\r\n\toptions: {\r\n\t\t// @option autoplay: Boolean = true\r\n\t\t// Whether the video starts playing automatically when loaded.\r\n\t\t// On some browsers autoplay will only work with `muted: true`\r\n\t\tautoplay: true,\r\n\r\n\t\t// @option loop: Boolean = true\r\n\t\t// Whether the video will loop back to the beginning when played.\r\n\t\tloop: true,\r\n\r\n\t\t// @option keepAspectRatio: Boolean = true\r\n\t\t// Whether the video will save aspect ratio after the projection.\r\n\t\t// Relevant for supported browsers. See [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)\r\n\t\tkeepAspectRatio: true,\r\n\r\n\t\t// @option muted: Boolean = false\r\n\t\t// Whether the video starts on mute when loaded.\r\n\t\tmuted: false,\r\n\r\n\t\t// @option playsInline: Boolean = true\r\n\t\t// Mobile browsers will play the video right where it is instead of open it up in fullscreen mode.\r\n\t\tplaysInline: true\r\n\t},\r\n\r\n\t_initImage: function () {\r\n\t\tvar wasElementSupplied = this._url.tagName === 'VIDEO';\r\n\t\tvar vid = this._image = wasElementSupplied ? this._url : DomUtil.create('video');\r\n\r\n\t\tDomUtil.addClass(vid, 'leaflet-image-layer');\r\n\t\tif (this._zoomAnimated) { DomUtil.addClass(vid, 'leaflet-zoom-animated'); }\r\n\t\tif (this.options.className) { DomUtil.addClass(vid, this.options.className); }\r\n\r\n\t\tvid.onselectstart = Util.falseFn;\r\n\t\tvid.onmousemove = Util.falseFn;\r\n\r\n\t\t// @event load: Event\r\n\t\t// Fired when the video has finished loading the first frame\r\n\t\tvid.onloadeddata = Util.bind(this.fire, this, 'load');\r\n\r\n\t\tif (wasElementSupplied) {\r\n\t\t\tvar sourceElements = vid.getElementsByTagName('source');\r\n\t\t\tvar sources = [];\r\n\t\t\tfor (var j = 0; j < sourceElements.length; j++) {\r\n\t\t\t\tsources.push(sourceElements[j].src);\r\n\t\t\t}\r\n\r\n\t\t\tthis._url = (sourceElements.length > 0) ? sources : [vid.src];\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (!Util.isArray(this._url)) { this._url = [this._url]; }\r\n\r\n\t\tif (!this.options.keepAspectRatio && Object.prototype.hasOwnProperty.call(vid.style, 'objectFit')) {\r\n\t\t\tvid.style['objectFit'] = 'fill';\r\n\t\t}\r\n\t\tvid.autoplay = !!this.options.autoplay;\r\n\t\tvid.loop = !!this.options.loop;\r\n\t\tvid.muted = !!this.options.muted;\r\n\t\tvid.playsInline = !!this.options.playsInline;\r\n\t\tfor (var i = 0; i < this._url.length; i++) {\r\n\t\t\tvar source = DomUtil.create('source');\r\n\t\t\tsource.src = this._url[i];\r\n\t\t\tvid.appendChild(source);\r\n\t\t}\r\n\t}\r\n\r\n\t// @method getElement(): HTMLVideoElement\r\n\t// Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)\r\n\t// used by this overlay.\r\n});\r\n\r\n\r\n// @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)\r\n// Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the\r\n// geographical bounds it is tied to.\r\n\r\nexport function videoOverlay(video, bounds, options) {\r\n\treturn new VideoOverlay(video, bounds, options);\r\n}\r\n","import {ImageOverlay} from './ImageOverlay';\nimport * as DomUtil from '../dom/DomUtil';\nimport * as Util from '../core/Util';\n\n/*\n * @class SVGOverlay\n * @aka L.SVGOverlay\n * @inherits ImageOverlay\n *\n * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`.\n *\n * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element.\n *\n * @example\n *\n * ```js\n * var svgElement = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n * svgElement.setAttribute('xmlns', \"http://www.w3.org/2000/svg\");\n * svgElement.setAttribute('viewBox', \"0 0 200 200\");\n * svgElement.innerHTML = '<rect width=\"200\" height=\"200\"/><rect x=\"75\" y=\"23\" width=\"50\" height=\"50\" style=\"fill:red\"/><rect x=\"75\" y=\"123\" width=\"50\" height=\"50\" style=\"fill:#0013ff\"/>';\n * var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];\n * L.svgOverlay(svgElement, svgElementBounds).addTo(map);\n * ```\n */\n\nexport var SVGOverlay = ImageOverlay.extend({\n\t_initImage: function () {\n\t\tvar el = this._image = this._url;\n\n\t\tDomUtil.addClass(el, 'leaflet-image-layer');\n\t\tif (this._zoomAnimated) { DomUtil.addClass(el, 'leaflet-zoom-animated'); }\n\t\tif (this.options.className) { DomUtil.addClass(el, this.options.className); }\n\n\t\tel.onselectstart = Util.falseFn;\n\t\tel.onmousemove = Util.falseFn;\n\t}\n\n\t// @method getElement(): SVGElement\n\t// Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)\n\t// used by this overlay.\n});\n\n\n// @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options)\n// Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to.\n// A viewBox attribute is required on the SVG element to zoom in and out properly.\n\nexport function svgOverlay(el, bounds, options) {\n\treturn new SVGOverlay(el, bounds, options);\n}\n","import {Map} from '../map/Map';\r\nimport {Layer} from './Layer';\r\nimport {FeatureGroup} from './FeatureGroup';\r\nimport * as Util from '../core/Util';\r\nimport {toLatLng, LatLng} from '../geo/LatLng';\r\nimport {toPoint} from '../geometry/Point';\r\nimport * as DomUtil from '../dom/DomUtil';\r\n\r\n/*\r\n * @class DivOverlay\r\n * @inherits Interactive layer\r\n * @aka L.DivOverlay\r\n * Base model for L.Popup and L.Tooltip. Inherit from it for custom overlays like plugins.\r\n */\r\n\r\n// @namespace DivOverlay\r\nexport var DivOverlay = Layer.extend({\r\n\r\n\t// @section\r\n\t// @aka DivOverlay options\r\n\toptions: {\r\n\t\t// @option interactive: Boolean = false\r\n\t\t// If true, the popup/tooltip will listen to the mouse events.\r\n\t\tinteractive: false,\r\n\r\n\t\t// @option offset: Point = Point(0, 0)\r\n\t\t// The offset of the overlay position.\r\n\t\toffset: [0, 0],\r\n\r\n\t\t// @option className: String = ''\r\n\t\t// A custom CSS class name to assign to the overlay.\r\n\t\tclassName: '',\r\n\r\n\t\t// @option pane: String = undefined\r\n\t\t// `Map pane` where the overlay will be added.\r\n\t\tpane: undefined,\r\n\r\n\t\t// @option content: String|HTMLElement|Function = ''\r\n\t\t// Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be\r\n\t\t// passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay.\r\n\t\tcontent: ''\r\n\t},\r\n\r\n\tinitialize: function (options, source) {\r\n\t\tif (options && (options instanceof LatLng || Util.isArray(options))) {\r\n\t\t\tthis._latlng = toLatLng(options);\r\n\t\t\tUtil.setOptions(this, source);\r\n\t\t} else {\r\n\t\t\tUtil.setOptions(this, options);\r\n\t\t\tthis._source = source;\r\n\t\t}\r\n\t\tif (this.options.content) {\r\n\t\t\tthis._content = this.options.content;\r\n\t\t}\r\n\t},\r\n\r\n\t// @method openOn(map: Map): this\r\n\t// Adds the overlay to the map.\r\n\t// Alternative to `map.openPopup(popup)`/`.openTooltip(tooltip)`.\r\n\topenOn: function (map) {\r\n\t\tmap = arguments.length ? map : this._source._map; // experimental, not the part of public api\r\n\t\tif (!map.hasLayer(this)) {\r\n\t\t\tmap.addLayer(this);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method close(): this\r\n\t// Closes the overlay.\r\n\t// Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)`\r\n\t// and `layer.closePopup()`/`.closeTooltip()`.\r\n\tclose: function () {\r\n\t\tif (this._map) {\r\n\t\t\tthis._map.removeLayer(this);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method toggle(layer?: Layer): this\r\n\t// Opens or closes the overlay bound to layer depending on its current state.\r\n\t// Argument may be omitted only for overlay bound to layer.\r\n\t// Alternative to `layer.togglePopup()`/`.toggleTooltip()`.\r\n\ttoggle: function (layer) {\r\n\t\tif (this._map) {\r\n\t\t\tthis.close();\r\n\t\t} else {\r\n\t\t\tif (arguments.length) {\r\n\t\t\t\tthis._source = layer;\r\n\t\t\t} else {\r\n\t\t\t\tlayer = this._source;\r\n\t\t\t}\r\n\t\t\tthis._prepareOpen();\r\n\r\n\t\t\t// open the overlay on the map\r\n\t\t\tthis.openOn(layer._map);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis._zoomAnimated = map._zoomAnimated;\r\n\r\n\t\tif (!this._container) {\r\n\t\t\tthis._initLayout();\r\n\t\t}\r\n\r\n\t\tif (map._fadeAnimated) {\r\n\t\t\tDomUtil.setOpacity(this._container, 0);\r\n\t\t}\r\n\r\n\t\tclearTimeout(this._removeTimeout);\r\n\t\tthis.getPane().appendChild(this._container);\r\n\t\tthis.update();\r\n\r\n\t\tif (map._fadeAnimated) {\r\n\t\t\tDomUtil.setOpacity(this._container, 1);\r\n\t\t}\r\n\r\n\t\tthis.bringToFront();\r\n\r\n\t\tif (this.options.interactive) {\r\n\t\t\tDomUtil.addClass(this._container, 'leaflet-interactive');\r\n\t\t\tthis.addInteractiveTarget(this._container);\r\n\t\t}\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tif (map._fadeAnimated) {\r\n\t\t\tDomUtil.setOpacity(this._container, 0);\r\n\t\t\tthis._removeTimeout = setTimeout(Util.bind(DomUtil.remove, undefined, this._container), 200);\r\n\t\t} else {\r\n\t\t\tDomUtil.remove(this._container);\r\n\t\t}\r\n\r\n\t\tif (this.options.interactive) {\r\n\t\t\tDomUtil.removeClass(this._container, 'leaflet-interactive');\r\n\t\t\tthis.removeInteractiveTarget(this._container);\r\n\t\t}\r\n\t},\r\n\r\n\t// @namespace DivOverlay\r\n\t// @method getLatLng: LatLng\r\n\t// Returns the geographical point of the overlay.\r\n\tgetLatLng: function () {\r\n\t\treturn this._latlng;\r\n\t},\r\n\r\n\t// @method setLatLng(latlng: LatLng): this\r\n\t// Sets the geographical point where the overlay will open.\r\n\tsetLatLng: function (latlng) {\r\n\t\tthis._latlng = toLatLng(latlng);\r\n\t\tif (this._map) {\r\n\t\t\tthis._updatePosition();\r\n\t\t\tthis._adjustPan();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getContent: String|HTMLElement\r\n\t// Returns the content of the overlay.\r\n\tgetContent: function () {\r\n\t\treturn this._content;\r\n\t},\r\n\r\n\t// @method setContent(htmlContent: String|HTMLElement|Function): this\r\n\t// Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function.\r\n\t// The function should return a `String` or `HTMLElement` to be used in the overlay.\r\n\tsetContent: function (content) {\r\n\t\tthis._content = content;\r\n\t\tthis.update();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getElement: String|HTMLElement\r\n\t// Returns the HTML container of the overlay.\r\n\tgetElement: function () {\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\t// @method update: null\r\n\t// Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded.\r\n\tupdate: function () {\r\n\t\tif (!this._map) { return; }\r\n\r\n\t\tthis._container.style.visibility = 'hidden';\r\n\r\n\t\tthis._updateContent();\r\n\t\tthis._updateLayout();\r\n\t\tthis._updatePosition();\r\n\r\n\t\tthis._container.style.visibility = '';\r\n\r\n\t\tthis._adjustPan();\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\tvar events = {\r\n\t\t\tzoom: this._updatePosition,\r\n\t\t\tviewreset: this._updatePosition\r\n\t\t};\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tevents.zoomanim = this._animateZoom;\r\n\t\t}\r\n\t\treturn events;\r\n\t},\r\n\r\n\t// @method isOpen: Boolean\r\n\t// Returns `true` when the overlay is visible on the map.\r\n\tisOpen: function () {\r\n\t\treturn !!this._map && this._map.hasLayer(this);\r\n\t},\r\n\r\n\t// @method bringToFront: this\r\n\t// Brings this overlay in front of other overlays (in the same map pane).\r\n\tbringToFront: function () {\r\n\t\tif (this._map) {\r\n\t\t\tDomUtil.toFront(this._container);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method bringToBack: this\r\n\t// Brings this overlay to the back of other overlays (in the same map pane).\r\n\tbringToBack: function () {\r\n\t\tif (this._map) {\r\n\t\t\tDomUtil.toBack(this._container);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// prepare bound overlay to open: update latlng pos / content source (for FeatureGroup)\r\n\t_prepareOpen: function (latlng) {\r\n\t\tvar source = this._source;\r\n\t\tif (!source._map) { return false; }\r\n\r\n\t\tif (source instanceof FeatureGroup) {\r\n\t\t\tsource = null;\r\n\t\t\tvar layers = this._source._layers;\r\n\t\t\tfor (var id in layers) {\r\n\t\t\t\tif (layers[id]._map) {\r\n\t\t\t\t\tsource = layers[id];\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (!source) { return false; } // Unable to get source layer.\r\n\r\n\t\t\t// set overlay source to this layer\r\n\t\t\tthis._source = source;\r\n\t\t}\r\n\r\n\t\tif (!latlng) {\r\n\t\t\tif (source.getCenter) {\r\n\t\t\t\tlatlng = source.getCenter();\r\n\t\t\t} else if (source.getLatLng) {\r\n\t\t\t\tlatlng = source.getLatLng();\r\n\t\t\t} else if (source.getBounds) {\r\n\t\t\t\tlatlng = source.getBounds().getCenter();\r\n\t\t\t} else {\r\n\t\t\t\tthrow new Error('Unable to get source layer LatLng.');\r\n\t\t\t}\r\n\t\t}\r\n\t\tthis.setLatLng(latlng);\r\n\r\n\t\tif (this._map) {\r\n\t\t\t// update the overlay (content, layout, etc...)\r\n\t\t\tthis.update();\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t},\r\n\r\n\t_updateContent: function () {\r\n\t\tif (!this._content) { return; }\r\n\r\n\t\tvar node = this._contentNode;\r\n\t\tvar content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;\r\n\r\n\t\tif (typeof content === 'string') {\r\n\t\t\tnode.innerHTML = content;\r\n\t\t} else {\r\n\t\t\twhile (node.hasChildNodes()) {\r\n\t\t\t\tnode.removeChild(node.firstChild);\r\n\t\t\t}\r\n\t\t\tnode.appendChild(content);\r\n\t\t}\r\n\r\n\t\t// @namespace DivOverlay\r\n\t\t// @section DivOverlay events\r\n\t\t// @event contentupdate: Event\r\n\t\t// Fired when the content of the overlay is updated\r\n\t\tthis.fire('contentupdate');\r\n\t},\r\n\r\n\t_updatePosition: function () {\r\n\t\tif (!this._map) { return; }\r\n\r\n\t\tvar pos = this._map.latLngToLayerPoint(this._latlng),\r\n\t\t    offset = toPoint(this.options.offset),\r\n\t\t    anchor = this._getAnchor();\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tDomUtil.setPosition(this._container, pos.add(anchor));\r\n\t\t} else {\r\n\t\t\toffset = offset.add(pos).add(anchor);\r\n\t\t}\r\n\r\n\t\tvar bottom = this._containerBottom = -offset.y,\r\n\t\t    left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;\r\n\r\n\t\t// bottom position the overlay in case the height of the overlay changes (images loading etc)\r\n\t\tthis._container.style.bottom = bottom + 'px';\r\n\t\tthis._container.style.left = left + 'px';\r\n\t},\r\n\r\n\t_getAnchor: function () {\r\n\t\treturn [0, 0];\r\n\t}\r\n\r\n});\r\n\r\nMap.include({\r\n\t_initOverlay: function (OverlayClass, content, latlng, options) {\r\n\t\tvar overlay = content;\r\n\t\tif (!(overlay instanceof OverlayClass)) {\r\n\t\t\toverlay = new OverlayClass(options).setContent(content);\r\n\t\t}\r\n\t\tif (latlng) {\r\n\t\t\toverlay.setLatLng(latlng);\r\n\t\t}\r\n\t\treturn overlay;\r\n\t}\r\n});\r\n\r\n\r\nLayer.include({\r\n\t_initOverlay: function (OverlayClass, old, content, options) {\r\n\t\tvar overlay = content;\r\n\t\tif (overlay instanceof OverlayClass) {\r\n\t\t\tUtil.setOptions(overlay, options);\r\n\t\t\toverlay._source = this;\r\n\t\t} else {\r\n\t\t\toverlay = (old && !options) ? old : new OverlayClass(options, this);\r\n\t\t\toverlay.setContent(content);\r\n\t\t}\r\n\t\treturn overlay;\r\n\t}\r\n});\r\n","import {DivOverlay} from './DivOverlay';\r\nimport * as DomEvent from '../dom/DomEvent';\r\nimport * as DomUtil from '../dom/DomUtil';\r\nimport {Point, toPoint} from '../geometry/Point';\r\nimport {Map} from '../map/Map';\r\nimport {Layer} from './Layer';\r\nimport {Path} from './vector/Path';\r\nimport {FeatureGroup} from './FeatureGroup';\r\n\r\n/*\r\n * @class Popup\r\n * @inherits DivOverlay\r\n * @aka L.Popup\r\n * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to\r\n * open popups while making sure that only one popup is open at one time\r\n * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.\r\n *\r\n * @example\r\n *\r\n * If you want to just bind a popup to marker click and then open it, it's really easy:\r\n *\r\n * ```js\r\n * marker.bindPopup(popupContent).openPopup();\r\n * ```\r\n * Path overlays like polylines also have a `bindPopup` method.\r\n *\r\n * A popup can be also standalone:\r\n *\r\n * ```js\r\n * var popup = L.popup()\r\n * \t.setLatLng(latlng)\r\n * \t.setContent('<p>Hello world!<br />This is a nice popup.</p>')\r\n * \t.openOn(map);\r\n * ```\r\n * or\r\n * ```js\r\n * var popup = L.popup(latlng, {content: '<p>Hello world!<br />This is a nice popup.</p>')\r\n * \t.openOn(map);\r\n * ```\r\n */\r\n\r\n\r\n// @namespace Popup\r\nexport var Popup = DivOverlay.extend({\r\n\r\n\t// @section\r\n\t// @aka Popup options\r\n\toptions: {\r\n\t\t// @option pane: String = 'popupPane'\r\n\t\t// `Map pane` where the popup will be added.\r\n\t\tpane: 'popupPane',\r\n\r\n\t\t// @option offset: Point = Point(0, 7)\r\n\t\t// The offset of the popup position.\r\n\t\toffset: [0, 7],\r\n\r\n\t\t// @option maxWidth: Number = 300\r\n\t\t// Max width of the popup, in pixels.\r\n\t\tmaxWidth: 300,\r\n\r\n\t\t// @option minWidth: Number = 50\r\n\t\t// Min width of the popup, in pixels.\r\n\t\tminWidth: 50,\r\n\r\n\t\t// @option maxHeight: Number = null\r\n\t\t// If set, creates a scrollable container of the given height\r\n\t\t// inside a popup if its content exceeds it.\r\n\t\t// The scrollable container can be styled using the\r\n\t\t// `leaflet-popup-scrolled` CSS class selector.\r\n\t\tmaxHeight: null,\r\n\r\n\t\t// @option autoPan: Boolean = true\r\n\t\t// Set it to `false` if you don't want the map to do panning animation\r\n\t\t// to fit the opened popup.\r\n\t\tautoPan: true,\r\n\r\n\t\t// @option autoPanPaddingTopLeft: Point = null\r\n\t\t// The margin between the popup and the top left corner of the map\r\n\t\t// view after autopanning was performed.\r\n\t\tautoPanPaddingTopLeft: null,\r\n\r\n\t\t// @option autoPanPaddingBottomRight: Point = null\r\n\t\t// The margin between the popup and the bottom right corner of the map\r\n\t\t// view after autopanning was performed.\r\n\t\tautoPanPaddingBottomRight: null,\r\n\r\n\t\t// @option autoPanPadding: Point = Point(5, 5)\r\n\t\t// Equivalent of setting both top left and bottom right autopan padding to the same value.\r\n\t\tautoPanPadding: [5, 5],\r\n\r\n\t\t// @option keepInView: Boolean = false\r\n\t\t// Set it to `true` if you want to prevent users from panning the popup\r\n\t\t// off of the screen while it is open.\r\n\t\tkeepInView: false,\r\n\r\n\t\t// @option closeButton: Boolean = true\r\n\t\t// Controls the presence of a close button in the popup.\r\n\t\tcloseButton: true,\r\n\r\n\t\t// @option autoClose: Boolean = true\r\n\t\t// Set it to `false` if you want to override the default behavior of\r\n\t\t// the popup closing when another popup is opened.\r\n\t\tautoClose: true,\r\n\r\n\t\t// @option closeOnEscapeKey: Boolean = true\r\n\t\t// Set it to `false` if you want to override the default behavior of\r\n\t\t// the ESC key for closing of the popup.\r\n\t\tcloseOnEscapeKey: true,\r\n\r\n\t\t// @option closeOnClick: Boolean = *\r\n\t\t// Set it if you want to override the default behavior of the popup closing when user clicks\r\n\t\t// on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.\r\n\r\n\t\t// @option className: String = ''\r\n\t\t// A custom CSS class name to assign to the popup.\r\n\t\tclassName: ''\r\n\t},\r\n\r\n\t// @namespace Popup\r\n\t// @method openOn(map: Map): this\r\n\t// Alternative to `map.openPopup(popup)`.\r\n\t// Adds the popup to the map and closes the previous one.\r\n\topenOn: function (map) {\r\n\t\tmap = arguments.length ? map : this._source._map; // experimental, not the part of public api\r\n\r\n\t\tif (!map.hasLayer(this) && map._popup && map._popup.options.autoClose) {\r\n\t\t\tmap.removeLayer(map._popup);\r\n\t\t}\r\n\t\tmap._popup = this;\r\n\r\n\t\treturn DivOverlay.prototype.openOn.call(this, map);\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tDivOverlay.prototype.onAdd.call(this, map);\r\n\r\n\t\t// @namespace Map\r\n\t\t// @section Popup events\r\n\t\t// @event popupopen: PopupEvent\r\n\t\t// Fired when a popup is opened in the map\r\n\t\tmap.fire('popupopen', {popup: this});\r\n\r\n\t\tif (this._source) {\r\n\t\t\t// @namespace Layer\r\n\t\t\t// @section Popup events\r\n\t\t\t// @event popupopen: PopupEvent\r\n\t\t\t// Fired when a popup bound to this layer is opened\r\n\t\t\tthis._source.fire('popupopen', {popup: this}, true);\r\n\t\t\t// For non-path layers, we toggle the popup when clicking\r\n\t\t\t// again the layer, so prevent the map to reopen it.\r\n\t\t\tif (!(this._source instanceof Path)) {\r\n\t\t\t\tthis._source.on('preclick', DomEvent.stopPropagation);\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tDivOverlay.prototype.onRemove.call(this, map);\r\n\r\n\t\t// @namespace Map\r\n\t\t// @section Popup events\r\n\t\t// @event popupclose: PopupEvent\r\n\t\t// Fired when a popup in the map is closed\r\n\t\tmap.fire('popupclose', {popup: this});\r\n\r\n\t\tif (this._source) {\r\n\t\t\t// @namespace Layer\r\n\t\t\t// @section Popup events\r\n\t\t\t// @event popupclose: PopupEvent\r\n\t\t\t// Fired when a popup bound to this layer is closed\r\n\t\t\tthis._source.fire('popupclose', {popup: this}, true);\r\n\t\t\tif (!(this._source instanceof Path)) {\r\n\t\t\t\tthis._source.off('preclick', DomEvent.stopPropagation);\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\tvar events = DivOverlay.prototype.getEvents.call(this);\r\n\r\n\t\tif (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {\r\n\t\t\tevents.preclick = this.close;\r\n\t\t}\r\n\r\n\t\tif (this.options.keepInView) {\r\n\t\t\tevents.moveend = this._adjustPan;\r\n\t\t}\r\n\r\n\t\treturn events;\r\n\t},\r\n\r\n\t_initLayout: function () {\r\n\t\tvar prefix = 'leaflet-popup',\r\n\t\t    container = this._container = DomUtil.create('div',\r\n\t\t\tprefix + ' ' + (this.options.className || '') +\r\n\t\t\t' leaflet-zoom-animated');\r\n\r\n\t\tvar wrapper = this._wrapper = DomUtil.create('div', prefix + '-content-wrapper', container);\r\n\t\tthis._contentNode = DomUtil.create('div', prefix + '-content', wrapper);\r\n\r\n\t\tDomEvent.disableClickPropagation(container);\r\n\t\tDomEvent.disableScrollPropagation(this._contentNode);\r\n\t\tDomEvent.on(container, 'contextmenu', DomEvent.stopPropagation);\r\n\r\n\t\tthis._tipContainer = DomUtil.create('div', prefix + '-tip-container', container);\r\n\t\tthis._tip = DomUtil.create('div', prefix + '-tip', this._tipContainer);\r\n\r\n\t\tif (this.options.closeButton) {\r\n\t\t\tvar closeButton = this._closeButton = DomUtil.create('a', prefix + '-close-button', container);\r\n\t\t\tcloseButton.setAttribute('role', 'button'); // overrides the implicit role=link of <a> elements #7399\r\n\t\t\tcloseButton.setAttribute('aria-label', 'Close popup');\r\n\t\t\tcloseButton.href = '#close';\r\n\t\t\tcloseButton.innerHTML = '<span aria-hidden=\"true\">&#215;</span>';\r\n\r\n\t\t\tDomEvent.on(closeButton, 'click', function (ev) {\r\n\t\t\t\tDomEvent.preventDefault(ev);\r\n\t\t\t\tthis.close();\r\n\t\t\t}, this);\r\n\t\t}\r\n\t},\r\n\r\n\t_updateLayout: function () {\r\n\t\tvar container = this._contentNode,\r\n\t\t    style = container.style;\r\n\r\n\t\tstyle.width = '';\r\n\t\tstyle.whiteSpace = 'nowrap';\r\n\r\n\t\tvar width = container.offsetWidth;\r\n\t\twidth = Math.min(width, this.options.maxWidth);\r\n\t\twidth = Math.max(width, this.options.minWidth);\r\n\r\n\t\tstyle.width = (width + 1) + 'px';\r\n\t\tstyle.whiteSpace = '';\r\n\r\n\t\tstyle.height = '';\r\n\r\n\t\tvar height = container.offsetHeight,\r\n\t\t    maxHeight = this.options.maxHeight,\r\n\t\t    scrolledClass = 'leaflet-popup-scrolled';\r\n\r\n\t\tif (maxHeight && height > maxHeight) {\r\n\t\t\tstyle.height = maxHeight + 'px';\r\n\t\t\tDomUtil.addClass(container, scrolledClass);\r\n\t\t} else {\r\n\t\t\tDomUtil.removeClass(container, scrolledClass);\r\n\t\t}\r\n\r\n\t\tthis._containerWidth = this._container.offsetWidth;\r\n\t},\r\n\r\n\t_animateZoom: function (e) {\r\n\t\tvar pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),\r\n\t\t    anchor = this._getAnchor();\r\n\t\tDomUtil.setPosition(this._container, pos.add(anchor));\r\n\t},\r\n\r\n\t_adjustPan: function () {\r\n\t\tif (!this.options.autoPan) { return; }\r\n\t\tif (this._map._panAnim) { this._map._panAnim.stop(); }\r\n\r\n\t\t// We can endlessly recurse if keepInView is set and the view resets.\r\n\t\t// Let's guard against that by exiting early if we're responding to our own autopan.\r\n\t\tif (this._autopanning) {\r\n\t\t\tthis._autopanning = false;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar map = this._map,\r\n\t\t    marginBottom = parseInt(DomUtil.getStyle(this._container, 'marginBottom'), 10) || 0,\r\n\t\t    containerHeight = this._container.offsetHeight + marginBottom,\r\n\t\t    containerWidth = this._containerWidth,\r\n\t\t    layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);\r\n\r\n\t\tlayerPos._add(DomUtil.getPosition(this._container));\r\n\r\n\t\tvar containerPos = map.layerPointToContainerPoint(layerPos),\r\n\t\t    padding = toPoint(this.options.autoPanPadding),\r\n\t\t    paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),\r\n\t\t    paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),\r\n\t\t    size = map.getSize(),\r\n\t\t    dx = 0,\r\n\t\t    dy = 0;\r\n\r\n\t\tif (containerPos.x + containerWidth + paddingBR.x > size.x) { // right\r\n\t\t\tdx = containerPos.x + containerWidth - size.x + paddingBR.x;\r\n\t\t}\r\n\t\tif (containerPos.x - dx - paddingTL.x < 0) { // left\r\n\t\t\tdx = containerPos.x - paddingTL.x;\r\n\t\t}\r\n\t\tif (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom\r\n\t\t\tdy = containerPos.y + containerHeight - size.y + paddingBR.y;\r\n\t\t}\r\n\t\tif (containerPos.y - dy - paddingTL.y < 0) { // top\r\n\t\t\tdy = containerPos.y - paddingTL.y;\r\n\t\t}\r\n\r\n\t\t// @namespace Map\r\n\t\t// @section Popup events\r\n\t\t// @event autopanstart: Event\r\n\t\t// Fired when the map starts autopanning when opening a popup.\r\n\t\tif (dx || dy) {\r\n\t\t\t// Track that we're autopanning, as this function will be re-ran on moveend\r\n\t\t\tif (this.options.keepInView) {\r\n\t\t\t\tthis._autopanning = true;\r\n\t\t\t}\r\n\r\n\t\t\tmap\r\n\t\t\t    .fire('autopanstart')\r\n\t\t\t    .panBy([dx, dy]);\r\n\t\t}\r\n\t},\r\n\r\n\t_getAnchor: function () {\r\n\t\t// Where should we anchor the popup on the source layer?\r\n\t\treturn toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);\r\n\t}\r\n\r\n});\r\n\r\n// @namespace Popup\r\n// @factory L.popup(options?: Popup options, source?: Layer)\r\n// Instantiates a `Popup` object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the popup with a reference to the Layer to which it refers.\r\n// @alternative\r\n// @factory L.popup(latlng: LatLng, options?: Popup options)\r\n// Instantiates a `Popup` object given `latlng` where the popup will open and an optional `options` object that describes its appearance and location.\r\nexport var popup = function (options, source) {\r\n\treturn new Popup(options, source);\r\n};\r\n\r\n\r\n/* @namespace Map\r\n * @section Interaction Options\r\n * @option closePopupOnClick: Boolean = true\r\n * Set it to `false` if you don't want popups to close when user clicks the map.\r\n */\r\nMap.mergeOptions({\r\n\tclosePopupOnClick: true\r\n});\r\n\r\n\r\n// @namespace Map\r\n// @section Methods for Layers and Controls\r\nMap.include({\r\n\t// @method openPopup(popup: Popup): this\r\n\t// Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).\r\n\t// @alternative\r\n\t// @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this\r\n\t// Creates a popup with the specified content and options and opens it in the given point on a map.\r\n\topenPopup: function (popup, latlng, options) {\r\n\t\tthis._initOverlay(Popup, popup, latlng, options)\r\n\t\t  .openOn(this);\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method closePopup(popup?: Popup): this\r\n\t// Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).\r\n\tclosePopup: function (popup) {\r\n\t\tpopup = arguments.length ? popup : this._popup;\r\n\t\tif (popup) {\r\n\t\t\tpopup.close();\r\n\t\t}\r\n\t\treturn this;\r\n\t}\r\n});\r\n\r\n/*\r\n * @namespace Layer\r\n * @section Popup methods example\r\n *\r\n * All layers share a set of methods convenient for binding popups to it.\r\n *\r\n * ```js\r\n * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);\r\n * layer.openPopup();\r\n * layer.closePopup();\r\n * ```\r\n *\r\n * Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened.\r\n */\r\n\r\n// @section Popup methods\r\nLayer.include({\r\n\r\n\t// @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this\r\n\t// Binds a popup to the layer with the passed `content` and sets up the\r\n\t// necessary event listeners. If a `Function` is passed it will receive\r\n\t// the layer as the first argument and should return a `String` or `HTMLElement`.\r\n\tbindPopup: function (content, options) {\r\n\t\tthis._popup = this._initOverlay(Popup, this._popup, content, options);\r\n\t\tif (!this._popupHandlersAdded) {\r\n\t\t\tthis.on({\r\n\t\t\t\tclick: this._openPopup,\r\n\t\t\t\tkeypress: this._onKeyPress,\r\n\t\t\t\tremove: this.closePopup,\r\n\t\t\t\tmove: this._movePopup\r\n\t\t\t});\r\n\t\t\tthis._popupHandlersAdded = true;\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method unbindPopup(): this\r\n\t// Removes the popup previously bound with `bindPopup`.\r\n\tunbindPopup: function () {\r\n\t\tif (this._popup) {\r\n\t\t\tthis.off({\r\n\t\t\t\tclick: this._openPopup,\r\n\t\t\t\tkeypress: this._onKeyPress,\r\n\t\t\t\tremove: this.closePopup,\r\n\t\t\t\tmove: this._movePopup\r\n\t\t\t});\r\n\t\t\tthis._popupHandlersAdded = false;\r\n\t\t\tthis._popup = null;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method openPopup(latlng?: LatLng): this\r\n\t// Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.\r\n\topenPopup: function (latlng) {\r\n\t\tif (this._popup) {\r\n\t\t\tif (!(this instanceof FeatureGroup)) {\r\n\t\t\t\tthis._popup._source = this;\r\n\t\t\t}\r\n\t\t\tif (this._popup._prepareOpen(latlng || this._latlng)) {\r\n\t\t\t\t// open the popup on the map\r\n\t\t\t\tthis._popup.openOn(this._map);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method closePopup(): this\r\n\t// Closes the popup bound to this layer if it is open.\r\n\tclosePopup: function () {\r\n\t\tif (this._popup) {\r\n\t\t\tthis._popup.close();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method togglePopup(): this\r\n\t// Opens or closes the popup bound to this layer depending on its current state.\r\n\ttogglePopup: function () {\r\n\t\tif (this._popup) {\r\n\t\t\tthis._popup.toggle(this);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method isPopupOpen(): boolean\r\n\t// Returns `true` if the popup bound to this layer is currently open.\r\n\tisPopupOpen: function () {\r\n\t\treturn (this._popup ? this._popup.isOpen() : false);\r\n\t},\r\n\r\n\t// @method setPopupContent(content: String|HTMLElement|Popup): this\r\n\t// Sets the content of the popup bound to this layer.\r\n\tsetPopupContent: function (content) {\r\n\t\tif (this._popup) {\r\n\t\t\tthis._popup.setContent(content);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getPopup(): Popup\r\n\t// Returns the popup bound to this layer.\r\n\tgetPopup: function () {\r\n\t\treturn this._popup;\r\n\t},\r\n\r\n\t_openPopup: function (e) {\r\n\t\tif (!this._popup || !this._map) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t// prevent map click\r\n\t\tDomEvent.stop(e);\r\n\r\n\t\tvar target = e.layer || e.target;\r\n\t\tif (this._popup._source === target && !(target instanceof Path)) {\r\n\t\t\t// treat it like a marker and figure out\r\n\t\t\t// if we should toggle it open/closed\r\n\t\t\tif (this._map.hasLayer(this._popup)) {\r\n\t\t\t\tthis.closePopup();\r\n\t\t\t} else {\r\n\t\t\t\tthis.openPopup(e.latlng);\r\n\t\t\t}\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tthis._popup._source = target;\r\n\t\tthis.openPopup(e.latlng);\r\n\t},\r\n\r\n\t_movePopup: function (e) {\r\n\t\tthis._popup.setLatLng(e.latlng);\r\n\t},\r\n\r\n\t_onKeyPress: function (e) {\r\n\t\tif (e.originalEvent.keyCode === 13) {\r\n\t\t\tthis._openPopup(e);\r\n\t\t}\r\n\t}\r\n});\r\n","import {DivOverlay} from './DivOverlay';\nimport {toPoint} from '../geometry/Point';\nimport {Map} from '../map/Map';\nimport {Layer} from './Layer';\nimport * as DomUtil from '../dom/DomUtil';\nimport * as DomEvent from '../dom/DomEvent';\nimport * as Util from '../core/Util';\nimport {FeatureGroup} from './FeatureGroup';\n\n/*\n * @class Tooltip\n * @inherits DivOverlay\n * @aka L.Tooltip\n * Used to display small texts on top of map layers.\n *\n * @example\n * If you want to just bind a tooltip to marker:\n *\n * ```js\n * marker.bindTooltip(\"my tooltip text\").openTooltip();\n * ```\n * Path overlays like polylines also have a `bindTooltip` method.\n *\n * A tooltip can be also standalone:\n *\n * ```js\n * var tooltip = L.tooltip()\n * \t.setLatLng(latlng)\n * \t.setContent('Hello world!<br />This is a nice tooltip.')\n * \t.addTo(map);\n * ```\n * or\n * ```js\n * var tooltip = L.tooltip(latlng, {content: 'Hello world!<br />This is a nice tooltip.'})\n * \t.addTo(map);\n * ```\n *\n *\n * Note about tooltip offset. Leaflet takes two options in consideration\n * for computing tooltip offsetting:\n * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.\n *   Add a positive x offset to move the tooltip to the right, and a positive y offset to\n *   move it to the bottom. Negatives will move to the left and top.\n * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You\n *   should adapt this value if you use a custom icon.\n */\n\n\n// @namespace Tooltip\nexport var Tooltip = DivOverlay.extend({\n\n\t// @section\n\t// @aka Tooltip options\n\toptions: {\n\t\t// @option pane: String = 'tooltipPane'\n\t\t// `Map pane` where the tooltip will be added.\n\t\tpane: 'tooltipPane',\n\n\t\t// @option offset: Point = Point(0, 0)\n\t\t// Optional offset of the tooltip position.\n\t\toffset: [0, 0],\n\n\t\t// @option direction: String = 'auto'\n\t\t// Direction where to open the tooltip. Possible values are: `right`, `left`,\n\t\t// `top`, `bottom`, `center`, `auto`.\n\t\t// `auto` will dynamically switch between `right` and `left` according to the tooltip\n\t\t// position on the map.\n\t\tdirection: 'auto',\n\n\t\t// @option permanent: Boolean = false\n\t\t// Whether to open the tooltip permanently or only on mouseover.\n\t\tpermanent: false,\n\n\t\t// @option sticky: Boolean = false\n\t\t// If true, the tooltip will follow the mouse instead of being fixed at the feature center.\n\t\tsticky: false,\n\n\t\t// @option opacity: Number = 0.9\n\t\t// Tooltip container opacity.\n\t\topacity: 0.9\n\t},\n\n\tonAdd: function (map) {\n\t\tDivOverlay.prototype.onAdd.call(this, map);\n\t\tthis.setOpacity(this.options.opacity);\n\n\t\t// @namespace Map\n\t\t// @section Tooltip events\n\t\t// @event tooltipopen: TooltipEvent\n\t\t// Fired when a tooltip is opened in the map.\n\t\tmap.fire('tooltipopen', {tooltip: this});\n\n\t\tif (this._source) {\n\t\t\tthis.addEventParent(this._source);\n\n\t\t\t// @namespace Layer\n\t\t\t// @section Tooltip events\n\t\t\t// @event tooltipopen: TooltipEvent\n\t\t\t// Fired when a tooltip bound to this layer is opened.\n\t\t\tthis._source.fire('tooltipopen', {tooltip: this}, true);\n\t\t}\n\t},\n\n\tonRemove: function (map) {\n\t\tDivOverlay.prototype.onRemove.call(this, map);\n\n\t\t// @namespace Map\n\t\t// @section Tooltip events\n\t\t// @event tooltipclose: TooltipEvent\n\t\t// Fired when a tooltip in the map is closed.\n\t\tmap.fire('tooltipclose', {tooltip: this});\n\n\t\tif (this._source) {\n\t\t\tthis.removeEventParent(this._source);\n\n\t\t\t// @namespace Layer\n\t\t\t// @section Tooltip events\n\t\t\t// @event tooltipclose: TooltipEvent\n\t\t\t// Fired when a tooltip bound to this layer is closed.\n\t\t\tthis._source.fire('tooltipclose', {tooltip: this}, true);\n\t\t}\n\t},\n\n\tgetEvents: function () {\n\t\tvar events = DivOverlay.prototype.getEvents.call(this);\n\n\t\tif (!this.options.permanent) {\n\t\t\tevents.preclick = this.close;\n\t\t}\n\n\t\treturn events;\n\t},\n\n\t_initLayout: function () {\n\t\tvar prefix = 'leaflet-tooltip',\n\t\t    className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');\n\n\t\tthis._contentNode = this._container = DomUtil.create('div', className);\n\n\t\tthis._container.setAttribute('role', 'tooltip');\n\t\tthis._container.setAttribute('id', 'leaflet-tooltip-' + Util.stamp(this));\n\t},\n\n\t_updateLayout: function () {},\n\n\t_adjustPan: function () {},\n\n\t_setPosition: function (pos) {\n\t\tvar subX, subY,\n\t\t    map = this._map,\n\t\t    container = this._container,\n\t\t    centerPoint = map.latLngToContainerPoint(map.getCenter()),\n\t\t    tooltipPoint = map.layerPointToContainerPoint(pos),\n\t\t    direction = this.options.direction,\n\t\t    tooltipWidth = container.offsetWidth,\n\t\t    tooltipHeight = container.offsetHeight,\n\t\t    offset = toPoint(this.options.offset),\n\t\t    anchor = this._getAnchor();\n\n\t\tif (direction === 'top') {\n\t\t\tsubX = tooltipWidth / 2;\n\t\t\tsubY = tooltipHeight;\n\t\t} else if (direction === 'bottom') {\n\t\t\tsubX = tooltipWidth / 2;\n\t\t\tsubY = 0;\n\t\t} else if (direction === 'center') {\n\t\t\tsubX = tooltipWidth / 2;\n\t\t\tsubY = tooltipHeight / 2;\n\t\t} else if (direction === 'right') {\n\t\t\tsubX = 0;\n\t\t\tsubY = tooltipHeight / 2;\n\t\t} else if (direction === 'left') {\n\t\t\tsubX = tooltipWidth;\n\t\t\tsubY = tooltipHeight / 2;\n\t\t} else if (tooltipPoint.x < centerPoint.x) {\n\t\t\tdirection = 'right';\n\t\t\tsubX = 0;\n\t\t\tsubY = tooltipHeight / 2;\n\t\t} else {\n\t\t\tdirection = 'left';\n\t\t\tsubX = tooltipWidth + (offset.x + anchor.x) * 2;\n\t\t\tsubY = tooltipHeight / 2;\n\t\t}\n\n\t\tpos = pos.subtract(toPoint(subX, subY, true)).add(offset).add(anchor);\n\n\t\tDomUtil.removeClass(container, 'leaflet-tooltip-right');\n\t\tDomUtil.removeClass(container, 'leaflet-tooltip-left');\n\t\tDomUtil.removeClass(container, 'leaflet-tooltip-top');\n\t\tDomUtil.removeClass(container, 'leaflet-tooltip-bottom');\n\t\tDomUtil.addClass(container, 'leaflet-tooltip-' + direction);\n\t\tDomUtil.setPosition(container, pos);\n\t},\n\n\t_updatePosition: function () {\n\t\tvar pos = this._map.latLngToLayerPoint(this._latlng);\n\t\tthis._setPosition(pos);\n\t},\n\n\tsetOpacity: function (opacity) {\n\t\tthis.options.opacity = opacity;\n\n\t\tif (this._container) {\n\t\t\tDomUtil.setOpacity(this._container, opacity);\n\t\t}\n\t},\n\n\t_animateZoom: function (e) {\n\t\tvar pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);\n\t\tthis._setPosition(pos);\n\t},\n\n\t_getAnchor: function () {\n\t\t// Where should we anchor the tooltip on the source layer?\n\t\treturn toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);\n\t}\n\n});\n\n// @namespace Tooltip\n// @factory L.tooltip(options?: Tooltip options, source?: Layer)\n// Instantiates a `Tooltip` object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the tooltip with a reference to the Layer to which it refers.\n// @alternative\n// @factory L.tooltip(latlng: LatLng, options?: Tooltip options)\n// Instantiates a `Tooltip` object given `latlng` where the tooltip will open and an optional `options` object that describes its appearance and location.\nexport var tooltip = function (options, source) {\n\treturn new Tooltip(options, source);\n};\n\n// @namespace Map\n// @section Methods for Layers and Controls\nMap.include({\n\n\t// @method openTooltip(tooltip: Tooltip): this\n\t// Opens the specified tooltip.\n\t// @alternative\n\t// @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this\n\t// Creates a tooltip with the specified content and options and open it.\n\topenTooltip: function (tooltip, latlng, options) {\n\t\tthis._initOverlay(Tooltip, tooltip, latlng, options)\n\t\t  .openOn(this);\n\n\t\treturn this;\n\t},\n\n\t// @method closeTooltip(tooltip: Tooltip): this\n\t// Closes the tooltip given as parameter.\n\tcloseTooltip: function (tooltip) {\n\t\ttooltip.close();\n\t\treturn this;\n\t}\n\n});\n\n/*\n * @namespace Layer\n * @section Tooltip methods example\n *\n * All layers share a set of methods convenient for binding tooltips to it.\n *\n * ```js\n * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);\n * layer.openTooltip();\n * layer.closeTooltip();\n * ```\n */\n\n// @section Tooltip methods\nLayer.include({\n\n\t// @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this\n\t// Binds a tooltip to the layer with the passed `content` and sets up the\n\t// necessary event listeners. If a `Function` is passed it will receive\n\t// the layer as the first argument and should return a `String` or `HTMLElement`.\n\tbindTooltip: function (content, options) {\n\n\t\tif (this._tooltip && this.isTooltipOpen()) {\n\t\t\tthis.unbindTooltip();\n\t\t}\n\n\t\tthis._tooltip = this._initOverlay(Tooltip, this._tooltip, content, options);\n\t\tthis._initTooltipInteractions();\n\n\t\tif (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {\n\t\t\tthis.openTooltip();\n\t\t}\n\n\t\treturn this;\n\t},\n\n\t// @method unbindTooltip(): this\n\t// Removes the tooltip previously bound with `bindTooltip`.\n\tunbindTooltip: function () {\n\t\tif (this._tooltip) {\n\t\t\tthis._initTooltipInteractions(true);\n\t\t\tthis.closeTooltip();\n\t\t\tthis._tooltip = null;\n\t\t}\n\t\treturn this;\n\t},\n\n\t_initTooltipInteractions: function (remove) {\n\t\tif (!remove && this._tooltipHandlersAdded) { return; }\n\t\tvar onOff = remove ? 'off' : 'on',\n\t\t    events = {\n\t\t\tremove: this.closeTooltip,\n\t\t\tmove: this._moveTooltip\n\t\t    };\n\t\tif (!this._tooltip.options.permanent) {\n\t\t\tevents.mouseover = this._openTooltip;\n\t\t\tevents.mouseout = this.closeTooltip;\n\t\t\tevents.click = this._openTooltip;\n\t\t\tif (this._map) {\n\t\t\t\tthis._addFocusListeners();\n\t\t\t} else {\n\t\t\t\tevents.add = this._addFocusListeners;\n\t\t\t}\n\t\t} else {\n\t\t\tevents.add = this._openTooltip;\n\t\t}\n\t\tif (this._tooltip.options.sticky) {\n\t\t\tevents.mousemove = this._moveTooltip;\n\t\t}\n\t\tthis[onOff](events);\n\t\tthis._tooltipHandlersAdded = !remove;\n\t},\n\n\t// @method openTooltip(latlng?: LatLng): this\n\t// Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.\n\topenTooltip: function (latlng) {\n\t\tif (this._tooltip) {\n\t\t\tif (!(this instanceof FeatureGroup)) {\n\t\t\t\tthis._tooltip._source = this;\n\t\t\t}\n\t\t\tif (this._tooltip._prepareOpen(latlng)) {\n\t\t\t\t// open the tooltip on the map\n\t\t\t\tthis._tooltip.openOn(this._map);\n\n\t\t\t\tif (this.getElement) {\n\t\t\t\t\tthis._setAriaDescribedByOnLayer(this);\n\t\t\t\t} else if (this.eachLayer) {\n\t\t\t\t\tthis.eachLayer(this._setAriaDescribedByOnLayer, this);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method closeTooltip(): this\n\t// Closes the tooltip bound to this layer if it is open.\n\tcloseTooltip: function () {\n\t\tif (this._tooltip) {\n\t\t\treturn this._tooltip.close();\n\t\t}\n\t},\n\n\t// @method toggleTooltip(): this\n\t// Opens or closes the tooltip bound to this layer depending on its current state.\n\ttoggleTooltip: function () {\n\t\tif (this._tooltip) {\n\t\t\tthis._tooltip.toggle(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method isTooltipOpen(): boolean\n\t// Returns `true` if the tooltip bound to this layer is currently open.\n\tisTooltipOpen: function () {\n\t\treturn this._tooltip.isOpen();\n\t},\n\n\t// @method setTooltipContent(content: String|HTMLElement|Tooltip): this\n\t// Sets the content of the tooltip bound to this layer.\n\tsetTooltipContent: function (content) {\n\t\tif (this._tooltip) {\n\t\t\tthis._tooltip.setContent(content);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method getTooltip(): Tooltip\n\t// Returns the tooltip bound to this layer.\n\tgetTooltip: function () {\n\t\treturn this._tooltip;\n\t},\n\n\t_addFocusListeners: function () {\n\t\tif (this.getElement) {\n\t\t\tthis._addFocusListenersOnLayer(this);\n\t\t} else if (this.eachLayer) {\n\t\t\tthis.eachLayer(this._addFocusListenersOnLayer, this);\n\t\t}\n\t},\n\n\t_addFocusListenersOnLayer: function (layer) {\n\t\tvar el = typeof layer.getElement === 'function' && layer.getElement();\n\t\tif (el) {\n\t\t\tDomEvent.on(el, 'focus', function () {\n\t\t\t\tthis._tooltip._source = layer;\n\t\t\t\tthis.openTooltip();\n\t\t\t}, this);\n\t\t\tDomEvent.on(el, 'blur', this.closeTooltip, this);\n\t\t}\n\t},\n\n\t_setAriaDescribedByOnLayer: function (layer) {\n\t\tvar el = typeof layer.getElement === 'function' && layer.getElement();\n\t\tif (el) {\n\t\t\tel.setAttribute('aria-describedby', this._tooltip._container.id);\n\t\t}\n\t},\n\n\n\t_openTooltip: function (e) {\n\t\tif (!this._tooltip || !this._map) {\n\t\t\treturn;\n\t\t}\n\n\t\t// If the map is moving, we will show the tooltip after it's done.\n\t\tif (this._map.dragging && this._map.dragging.moving() && !this._openOnceFlag) {\n\t\t\tthis._openOnceFlag = true;\n\t\t\tvar that = this;\n\t\t\tthis._map.once('moveend', function () {\n\t\t\t\tthat._openOnceFlag = false;\n\t\t\t\tthat._openTooltip(e);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._tooltip._source = e.layer || e.target;\n\n\t\tthis.openTooltip(this._tooltip.options.sticky ? e.latlng : undefined);\n\t},\n\n\t_moveTooltip: function (e) {\n\t\tvar latlng = e.latlng, containerPoint, layerPoint;\n\t\tif (this._tooltip.options.sticky && e.originalEvent) {\n\t\t\tcontainerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);\n\t\t\tlayerPoint = this._map.containerPointToLayerPoint(containerPoint);\n\t\t\tlatlng = this._map.layerPointToLatLng(layerPoint);\n\t\t}\n\t\tthis._tooltip.setLatLng(latlng);\n\t}\n});\n","import {Icon} from './Icon';\nimport {toPoint as point} from '../../geometry/Point';\nimport {empty} from '../../dom/DomUtil';\n\n/*\n * @class DivIcon\n * @aka L.DivIcon\n * @inherits Icon\n *\n * Represents a lightweight icon for markers that uses a simple `<div>`\n * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.\n *\n * @example\n * ```js\n * var myIcon = L.divIcon({className: 'my-div-icon'});\n * // you can set .my-div-icon styles in CSS\n *\n * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);\n * ```\n *\n * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.\n */\n\nexport var DivIcon = Icon.extend({\n\toptions: {\n\t\t// @section\n\t\t// @aka DivIcon options\n\t\ticonSize: [12, 12], // also can be set through CSS\n\n\t\t// iconAnchor: (Point),\n\t\t// popupAnchor: (Point),\n\n\t\t// @option html: String|HTMLElement = ''\n\t\t// Custom HTML code to put inside the div element, empty by default. Alternatively,\n\t\t// an instance of `HTMLElement`.\n\t\thtml: false,\n\n\t\t// @option bgPos: Point = [0, 0]\n\t\t// Optional relative position of the background, in pixels\n\t\tbgPos: null,\n\n\t\tclassName: 'leaflet-div-icon'\n\t},\n\n\tcreateIcon: function (oldIcon) {\n\t\tvar div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),\n\t\t    options = this.options;\n\n\t\tif (options.html instanceof Element) {\n\t\t\tempty(div);\n\t\t\tdiv.appendChild(options.html);\n\t\t} else {\n\t\t\tdiv.innerHTML = options.html !== false ? options.html : '';\n\t\t}\n\n\t\tif (options.bgPos) {\n\t\t\tvar bgPos = point(options.bgPos);\n\t\t\tdiv.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';\n\t\t}\n\t\tthis._setIconStyles(div, 'icon');\n\n\t\treturn div;\n\t},\n\n\tcreateShadow: function () {\n\t\treturn null;\n\t}\n});\n\n// @factory L.divIcon(options: DivIcon options)\n// Creates a `DivIcon` instance with the given options.\nexport function divIcon(options) {\n\treturn new DivIcon(options);\n}\n","import {Icon} from './Icon';\nexport {icon} from './Icon';\nimport {IconDefault} from './Icon.Default';\nIcon.Default = IconDefault;\nexport {Icon};\n\nexport {DivIcon, divIcon} from './DivIcon';\nexport {Marker, marker} from './Marker';\n","import {Layer} from '../Layer';\nimport Browser from '../../core/Browser';\nimport * as Util from '../../core/Util';\nimport * as DomUtil from '../../dom/DomUtil';\nimport {Point} from '../../geometry/Point';\nimport {Bounds} from '../../geometry/Bounds';\nimport {LatLngBounds, toLatLngBounds as latLngBounds} from '../../geo/LatLngBounds';\n\n/*\n * @class GridLayer\n * @inherits Layer\n * @aka L.GridLayer\n *\n * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.\n * GridLayer can be extended to create a tiled grid of HTML elements like `<canvas>`, `<img>` or `<div>`. GridLayer will handle creating and animating these DOM elements for you.\n *\n *\n * @section Synchronous usage\n * @example\n *\n * To create a custom layer, extend GridLayer and implement the `createTile()` method, which will be passed a `Point` object with the `x`, `y`, and `z` (zoom level) coordinates to draw your tile.\n *\n * ```js\n * var CanvasLayer = L.GridLayer.extend({\n *     createTile: function(coords){\n *         // create a <canvas> element for drawing\n *         var tile = L.DomUtil.create('canvas', 'leaflet-tile');\n *\n *         // setup tile width and height according to the options\n *         var size = this.getTileSize();\n *         tile.width = size.x;\n *         tile.height = size.y;\n *\n *         // get a canvas context and draw something on it using coords.x, coords.y and coords.z\n *         var ctx = tile.getContext('2d');\n *\n *         // return the tile so it can be rendered on screen\n *         return tile;\n *     }\n * });\n * ```\n *\n * @section Asynchronous usage\n * @example\n *\n * Tile creation can also be asynchronous, this is useful when using a third-party drawing library. Once the tile is finished drawing it can be passed to the `done()` callback.\n *\n * ```js\n * var CanvasLayer = L.GridLayer.extend({\n *     createTile: function(coords, done){\n *         var error;\n *\n *         // create a <canvas> element for drawing\n *         var tile = L.DomUtil.create('canvas', 'leaflet-tile');\n *\n *         // setup tile width and height according to the options\n *         var size = this.getTileSize();\n *         tile.width = size.x;\n *         tile.height = size.y;\n *\n *         // draw something asynchronously and pass the tile to the done() callback\n *         setTimeout(function() {\n *             done(error, tile);\n *         }, 1000);\n *\n *         return tile;\n *     }\n * });\n * ```\n *\n * @section\n */\n\n\nexport var GridLayer = Layer.extend({\n\n\t// @section\n\t// @aka GridLayer options\n\toptions: {\n\t\t// @option tileSize: Number|Point = 256\n\t\t// Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.\n\t\ttileSize: 256,\n\n\t\t// @option opacity: Number = 1.0\n\t\t// Opacity of the tiles. Can be used in the `createTile()` function.\n\t\topacity: 1,\n\n\t\t// @option updateWhenIdle: Boolean = (depends)\n\t\t// Load new tiles only when panning ends.\n\t\t// `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.\n\t\t// `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the\n\t\t// [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.\n\t\tupdateWhenIdle: Browser.mobile,\n\n\t\t// @option updateWhenZooming: Boolean = true\n\t\t// By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends.\n\t\tupdateWhenZooming: true,\n\n\t\t// @option updateInterval: Number = 200\n\t\t// Tiles will not update more than once every `updateInterval` milliseconds when panning.\n\t\tupdateInterval: 200,\n\n\t\t// @option zIndex: Number = 1\n\t\t// The explicit zIndex of the tile layer.\n\t\tzIndex: 1,\n\n\t\t// @option bounds: LatLngBounds = undefined\n\t\t// If set, tiles will only be loaded inside the set `LatLngBounds`.\n\t\tbounds: null,\n\n\t\t// @option minZoom: Number = 0\n\t\t// The minimum zoom level down to which this layer will be displayed (inclusive).\n\t\tminZoom: 0,\n\n\t\t// @option maxZoom: Number = undefined\n\t\t// The maximum zoom level up to which this layer will be displayed (inclusive).\n\t\tmaxZoom: undefined,\n\n\t\t// @option maxNativeZoom: Number = undefined\n\t\t// Maximum zoom number the tile source has available. If it is specified,\n\t\t// the tiles on all zoom levels higher than `maxNativeZoom` will be loaded\n\t\t// from `maxNativeZoom` level and auto-scaled.\n\t\tmaxNativeZoom: undefined,\n\n\t\t// @option minNativeZoom: Number = undefined\n\t\t// Minimum zoom number the tile source has available. If it is specified,\n\t\t// the tiles on all zoom levels lower than `minNativeZoom` will be loaded\n\t\t// from `minNativeZoom` level and auto-scaled.\n\t\tminNativeZoom: undefined,\n\n\t\t// @option noWrap: Boolean = false\n\t\t// Whether the layer is wrapped around the antimeridian. If `true`, the\n\t\t// GridLayer will only be displayed once at low zoom levels. Has no\n\t\t// effect when the [map CRS](#map-crs) doesn't wrap around. Can be used\n\t\t// in combination with [`bounds`](#gridlayer-bounds) to prevent requesting\n\t\t// tiles outside the CRS limits.\n\t\tnoWrap: false,\n\n\t\t// @option pane: String = 'tilePane'\n\t\t// `Map pane` where the grid layer will be added.\n\t\tpane: 'tilePane',\n\n\t\t// @option className: String = ''\n\t\t// A custom class name to assign to the tile layer. Empty by default.\n\t\tclassName: '',\n\n\t\t// @option keepBuffer: Number = 2\n\t\t// When panning the map, keep this many rows and columns of tiles before unloading them.\n\t\tkeepBuffer: 2\n\t},\n\n\tinitialize: function (options) {\n\t\tUtil.setOptions(this, options);\n\t},\n\n\tonAdd: function () {\n\t\tthis._initContainer();\n\n\t\tthis._levels = {};\n\t\tthis._tiles = {};\n\n\t\tthis._resetView(); // implicit _update() call\n\t},\n\n\tbeforeAdd: function (map) {\n\t\tmap._addZoomLimit(this);\n\t},\n\n\tonRemove: function (map) {\n\t\tthis._removeAllTiles();\n\t\tDomUtil.remove(this._container);\n\t\tmap._removeZoomLimit(this);\n\t\tthis._container = null;\n\t\tthis._tileZoom = undefined;\n\t},\n\n\t// @method bringToFront: this\n\t// Brings the tile layer to the top of all tile layers.\n\tbringToFront: function () {\n\t\tif (this._map) {\n\t\t\tDomUtil.toFront(this._container);\n\t\t\tthis._setAutoZIndex(Math.max);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method bringToBack: this\n\t// Brings the tile layer to the bottom of all tile layers.\n\tbringToBack: function () {\n\t\tif (this._map) {\n\t\t\tDomUtil.toBack(this._container);\n\t\t\tthis._setAutoZIndex(Math.min);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method getContainer: HTMLElement\n\t// Returns the HTML element that contains the tiles for this layer.\n\tgetContainer: function () {\n\t\treturn this._container;\n\t},\n\n\t// @method setOpacity(opacity: Number): this\n\t// Changes the [opacity](#gridlayer-opacity) of the grid layer.\n\tsetOpacity: function (opacity) {\n\t\tthis.options.opacity = opacity;\n\t\tthis._updateOpacity();\n\t\treturn this;\n\t},\n\n\t// @method setZIndex(zIndex: Number): this\n\t// Changes the [zIndex](#gridlayer-zindex) of the grid layer.\n\tsetZIndex: function (zIndex) {\n\t\tthis.options.zIndex = zIndex;\n\t\tthis._updateZIndex();\n\n\t\treturn this;\n\t},\n\n\t// @method isLoading: Boolean\n\t// Returns `true` if any tile in the grid layer has not finished loading.\n\tisLoading: function () {\n\t\treturn this._loading;\n\t},\n\n\t// @method redraw: this\n\t// Causes the layer to clear all the tiles and request them again.\n\tredraw: function () {\n\t\tif (this._map) {\n\t\t\tthis._removeAllTiles();\n\t\t\tvar tileZoom = this._clampZoom(this._map.getZoom());\n\t\t\tif (tileZoom !== this._tileZoom) {\n\t\t\t\tthis._tileZoom = tileZoom;\n\t\t\t\tthis._updateLevels();\n\t\t\t}\n\t\t\tthis._update();\n\t\t}\n\t\treturn this;\n\t},\n\n\tgetEvents: function () {\n\t\tvar events = {\n\t\t\tviewprereset: this._invalidateAll,\n\t\t\tviewreset: this._resetView,\n\t\t\tzoom: this._resetView,\n\t\t\tmoveend: this._onMoveEnd\n\t\t};\n\n\t\tif (!this.options.updateWhenIdle) {\n\t\t\t// update tiles on move, but not more often than once per given interval\n\t\t\tif (!this._onMove) {\n\t\t\t\tthis._onMove = Util.throttle(this._onMoveEnd, this.options.updateInterval, this);\n\t\t\t}\n\n\t\t\tevents.move = this._onMove;\n\t\t}\n\n\t\tif (this._zoomAnimated) {\n\t\t\tevents.zoomanim = this._animateZoom;\n\t\t}\n\n\t\treturn events;\n\t},\n\n\t// @section Extension methods\n\t// Layers extending `GridLayer` shall reimplement the following method.\n\t// @method createTile(coords: Object, done?: Function): HTMLElement\n\t// Called only internally, must be overridden by classes extending `GridLayer`.\n\t// Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback\n\t// is specified, it must be called when the tile has finished loading and drawing.\n\tcreateTile: function () {\n\t\treturn document.createElement('div');\n\t},\n\n\t// @section\n\t// @method getTileSize: Point\n\t// Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.\n\tgetTileSize: function () {\n\t\tvar s = this.options.tileSize;\n\t\treturn s instanceof Point ? s : new Point(s, s);\n\t},\n\n\t_updateZIndex: function () {\n\t\tif (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {\n\t\t\tthis._container.style.zIndex = this.options.zIndex;\n\t\t}\n\t},\n\n\t_setAutoZIndex: function (compare) {\n\t\t// go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)\n\n\t\tvar layers = this.getPane().children,\n\t\t    edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min\n\n\t\tfor (var i = 0, len = layers.length, zIndex; i < len; i++) {\n\n\t\t\tzIndex = layers[i].style.zIndex;\n\n\t\t\tif (layers[i] !== this._container && zIndex) {\n\t\t\t\tedgeZIndex = compare(edgeZIndex, +zIndex);\n\t\t\t}\n\t\t}\n\n\t\tif (isFinite(edgeZIndex)) {\n\t\t\tthis.options.zIndex = edgeZIndex + compare(-1, 1);\n\t\t\tthis._updateZIndex();\n\t\t}\n\t},\n\n\t_updateOpacity: function () {\n\t\tif (!this._map) { return; }\n\n\t\t// IE doesn't inherit filter opacity properly, so we're forced to set it on tiles\n\t\tif (Browser.ielt9) { return; }\n\n\t\tDomUtil.setOpacity(this._container, this.options.opacity);\n\n\t\tvar now = +new Date(),\n\t\t    nextFrame = false,\n\t\t    willPrune = false;\n\n\t\tfor (var key in this._tiles) {\n\t\t\tvar tile = this._tiles[key];\n\t\t\tif (!tile.current || !tile.loaded) { continue; }\n\n\t\t\tvar fade = Math.min(1, (now - tile.loaded) / 200);\n\n\t\t\tDomUtil.setOpacity(tile.el, fade);\n\t\t\tif (fade < 1) {\n\t\t\t\tnextFrame = true;\n\t\t\t} else {\n\t\t\t\tif (tile.active) {\n\t\t\t\t\twillPrune = true;\n\t\t\t\t} else {\n\t\t\t\t\tthis._onOpaqueTile(tile);\n\t\t\t\t}\n\t\t\t\ttile.active = true;\n\t\t\t}\n\t\t}\n\n\t\tif (willPrune && !this._noPrune) { this._pruneTiles(); }\n\n\t\tif (nextFrame) {\n\t\t\tUtil.cancelAnimFrame(this._fadeFrame);\n\t\t\tthis._fadeFrame = Util.requestAnimFrame(this._updateOpacity, this);\n\t\t}\n\t},\n\n\t_onOpaqueTile: Util.falseFn,\n\n\t_initContainer: function () {\n\t\tif (this._container) { return; }\n\n\t\tthis._container = DomUtil.create('div', 'leaflet-layer ' + (this.options.className || ''));\n\t\tthis._updateZIndex();\n\n\t\tif (this.options.opacity < 1) {\n\t\t\tthis._updateOpacity();\n\t\t}\n\n\t\tthis.getPane().appendChild(this._container);\n\t},\n\n\t_updateLevels: function () {\n\n\t\tvar zoom = this._tileZoom,\n\t\t    maxZoom = this.options.maxZoom;\n\n\t\tif (zoom === undefined) { return undefined; }\n\n\t\tfor (var z in this._levels) {\n\t\t\tz = Number(z);\n\t\t\tif (this._levels[z].el.children.length || z === zoom) {\n\t\t\t\tthis._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);\n\t\t\t\tthis._onUpdateLevel(z);\n\t\t\t} else {\n\t\t\t\tDomUtil.remove(this._levels[z].el);\n\t\t\t\tthis._removeTilesAtZoom(z);\n\t\t\t\tthis._onRemoveLevel(z);\n\t\t\t\tdelete this._levels[z];\n\t\t\t}\n\t\t}\n\n\t\tvar level = this._levels[zoom],\n\t\t    map = this._map;\n\n\t\tif (!level) {\n\t\t\tlevel = this._levels[zoom] = {};\n\n\t\t\tlevel.el = DomUtil.create('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);\n\t\t\tlevel.el.style.zIndex = maxZoom;\n\n\t\t\tlevel.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();\n\t\t\tlevel.zoom = zoom;\n\n\t\t\tthis._setZoomTransform(level, map.getCenter(), map.getZoom());\n\n\t\t\t// force the browser to consider the newly added element for transition\n\t\t\tUtil.falseFn(level.el.offsetWidth);\n\n\t\t\tthis._onCreateLevel(level);\n\t\t}\n\n\t\tthis._level = level;\n\n\t\treturn level;\n\t},\n\n\t_onUpdateLevel: Util.falseFn,\n\n\t_onRemoveLevel: Util.falseFn,\n\n\t_onCreateLevel: Util.falseFn,\n\n\t_pruneTiles: function () {\n\t\tif (!this._map) {\n\t\t\treturn;\n\t\t}\n\n\t\tvar key, tile;\n\n\t\tvar zoom = this._map.getZoom();\n\t\tif (zoom > this.options.maxZoom ||\n\t\t\tzoom < this.options.minZoom) {\n\t\t\tthis._removeAllTiles();\n\t\t\treturn;\n\t\t}\n\n\t\tfor (key in this._tiles) {\n\t\t\ttile = this._tiles[key];\n\t\t\ttile.retain = tile.current;\n\t\t}\n\n\t\tfor (key in this._tiles) {\n\t\t\ttile = this._tiles[key];\n\t\t\tif (tile.current && !tile.active) {\n\t\t\t\tvar coords = tile.coords;\n\t\t\t\tif (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {\n\t\t\t\t\tthis._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (key in this._tiles) {\n\t\t\tif (!this._tiles[key].retain) {\n\t\t\t\tthis._removeTile(key);\n\t\t\t}\n\t\t}\n\t},\n\n\t_removeTilesAtZoom: function (zoom) {\n\t\tfor (var key in this._tiles) {\n\t\t\tif (this._tiles[key].coords.z !== zoom) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._removeTile(key);\n\t\t}\n\t},\n\n\t_removeAllTiles: function () {\n\t\tfor (var key in this._tiles) {\n\t\t\tthis._removeTile(key);\n\t\t}\n\t},\n\n\t_invalidateAll: function () {\n\t\tfor (var z in this._levels) {\n\t\t\tDomUtil.remove(this._levels[z].el);\n\t\t\tthis._onRemoveLevel(Number(z));\n\t\t\tdelete this._levels[z];\n\t\t}\n\t\tthis._removeAllTiles();\n\n\t\tthis._tileZoom = undefined;\n\t},\n\n\t_retainParent: function (x, y, z, minZoom) {\n\t\tvar x2 = Math.floor(x / 2),\n\t\t    y2 = Math.floor(y / 2),\n\t\t    z2 = z - 1,\n\t\t    coords2 = new Point(+x2, +y2);\n\t\tcoords2.z = +z2;\n\n\t\tvar key = this._tileCoordsToKey(coords2),\n\t\t    tile = this._tiles[key];\n\n\t\tif (tile && tile.active) {\n\t\t\ttile.retain = true;\n\t\t\treturn true;\n\n\t\t} else if (tile && tile.loaded) {\n\t\t\ttile.retain = true;\n\t\t}\n\n\t\tif (z2 > minZoom) {\n\t\t\treturn this._retainParent(x2, y2, z2, minZoom);\n\t\t}\n\n\t\treturn false;\n\t},\n\n\t_retainChildren: function (x, y, z, maxZoom) {\n\n\t\tfor (var i = 2 * x; i < 2 * x + 2; i++) {\n\t\t\tfor (var j = 2 * y; j < 2 * y + 2; j++) {\n\n\t\t\t\tvar coords = new Point(i, j);\n\t\t\t\tcoords.z = z + 1;\n\n\t\t\t\tvar key = this._tileCoordsToKey(coords),\n\t\t\t\t    tile = this._tiles[key];\n\n\t\t\t\tif (tile && tile.active) {\n\t\t\t\t\ttile.retain = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\t} else if (tile && tile.loaded) {\n\t\t\t\t\ttile.retain = true;\n\t\t\t\t}\n\n\t\t\t\tif (z + 1 < maxZoom) {\n\t\t\t\t\tthis._retainChildren(i, j, z + 1, maxZoom);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n\n\t_resetView: function (e) {\n\t\tvar animating = e && (e.pinch || e.flyTo);\n\t\tthis._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);\n\t},\n\n\t_animateZoom: function (e) {\n\t\tthis._setView(e.center, e.zoom, true, e.noUpdate);\n\t},\n\n\t_clampZoom: function (zoom) {\n\t\tvar options = this.options;\n\n\t\tif (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {\n\t\t\treturn options.minNativeZoom;\n\t\t}\n\n\t\tif (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {\n\t\t\treturn options.maxNativeZoom;\n\t\t}\n\n\t\treturn zoom;\n\t},\n\n\t_setView: function (center, zoom, noPrune, noUpdate) {\n\t\tvar tileZoom = Math.round(zoom);\n\t\tif ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||\n\t\t    (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {\n\t\t\ttileZoom = undefined;\n\t\t} else {\n\t\t\ttileZoom = this._clampZoom(tileZoom);\n\t\t}\n\n\t\tvar tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);\n\n\t\tif (!noUpdate || tileZoomChanged) {\n\n\t\t\tthis._tileZoom = tileZoom;\n\n\t\t\tif (this._abortLoading) {\n\t\t\t\tthis._abortLoading();\n\t\t\t}\n\n\t\t\tthis._updateLevels();\n\t\t\tthis._resetGrid();\n\n\t\t\tif (tileZoom !== undefined) {\n\t\t\t\tthis._update(center);\n\t\t\t}\n\n\t\t\tif (!noPrune) {\n\t\t\t\tthis._pruneTiles();\n\t\t\t}\n\n\t\t\t// Flag to prevent _updateOpacity from pruning tiles during\n\t\t\t// a zoom anim or a pinch gesture\n\t\t\tthis._noPrune = !!noPrune;\n\t\t}\n\n\t\tthis._setZoomTransforms(center, zoom);\n\t},\n\n\t_setZoomTransforms: function (center, zoom) {\n\t\tfor (var i in this._levels) {\n\t\t\tthis._setZoomTransform(this._levels[i], center, zoom);\n\t\t}\n\t},\n\n\t_setZoomTransform: function (level, center, zoom) {\n\t\tvar scale = this._map.getZoomScale(zoom, level.zoom),\n\t\t    translate = level.origin.multiplyBy(scale)\n\t\t        .subtract(this._map._getNewPixelOrigin(center, zoom)).round();\n\n\t\tif (Browser.any3d) {\n\t\t\tDomUtil.setTransform(level.el, translate, scale);\n\t\t} else {\n\t\t\tDomUtil.setPosition(level.el, translate);\n\t\t}\n\t},\n\n\t_resetGrid: function () {\n\t\tvar map = this._map,\n\t\t    crs = map.options.crs,\n\t\t    tileSize = this._tileSize = this.getTileSize(),\n\t\t    tileZoom = this._tileZoom;\n\n\t\tvar bounds = this._map.getPixelWorldBounds(this._tileZoom);\n\t\tif (bounds) {\n\t\t\tthis._globalTileRange = this._pxBoundsToTileRange(bounds);\n\t\t}\n\n\t\tthis._wrapX = crs.wrapLng && !this.options.noWrap && [\n\t\t\tMath.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),\n\t\t\tMath.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)\n\t\t];\n\t\tthis._wrapY = crs.wrapLat && !this.options.noWrap && [\n\t\t\tMath.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),\n\t\t\tMath.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)\n\t\t];\n\t},\n\n\t_onMoveEnd: function () {\n\t\tif (!this._map || this._map._animatingZoom) { return; }\n\n\t\tthis._update();\n\t},\n\n\t_getTiledPixelBounds: function (center) {\n\t\tvar map = this._map,\n\t\t    mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),\n\t\t    scale = map.getZoomScale(mapZoom, this._tileZoom),\n\t\t    pixelCenter = map.project(center, this._tileZoom).floor(),\n\t\t    halfSize = map.getSize().divideBy(scale * 2);\n\n\t\treturn new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));\n\t},\n\n\t// Private method to load tiles in the grid's active zoom level according to map bounds\n\t_update: function (center) {\n\t\tvar map = this._map;\n\t\tif (!map) { return; }\n\t\tvar zoom = this._clampZoom(map.getZoom());\n\n\t\tif (center === undefined) { center = map.getCenter(); }\n\t\tif (this._tileZoom === undefined) { return; }\t// if out of minzoom/maxzoom\n\n\t\tvar pixelBounds = this._getTiledPixelBounds(center),\n\t\t    tileRange = this._pxBoundsToTileRange(pixelBounds),\n\t\t    tileCenter = tileRange.getCenter(),\n\t\t    queue = [],\n\t\t    margin = this.options.keepBuffer,\n\t\t    noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),\n\t\t                              tileRange.getTopRight().add([margin, -margin]));\n\n\t\t// Sanity check: panic if the tile range contains Infinity somewhere.\n\t\tif (!(isFinite(tileRange.min.x) &&\n\t\t      isFinite(tileRange.min.y) &&\n\t\t      isFinite(tileRange.max.x) &&\n\t\t      isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }\n\n\t\tfor (var key in this._tiles) {\n\t\t\tvar c = this._tiles[key].coords;\n\t\t\tif (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {\n\t\t\t\tthis._tiles[key].current = false;\n\t\t\t}\n\t\t}\n\n\t\t// _update just loads more tiles. If the tile zoom level differs too much\n\t\t// from the map's, let _setView reset levels and prune old tiles.\n\t\tif (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }\n\n\t\t// create a queue of coordinates to load tiles from\n\t\tfor (var j = tileRange.min.y; j <= tileRange.max.y; j++) {\n\t\t\tfor (var i = tileRange.min.x; i <= tileRange.max.x; i++) {\n\t\t\t\tvar coords = new Point(i, j);\n\t\t\t\tcoords.z = this._tileZoom;\n\n\t\t\t\tif (!this._isValidTile(coords)) { continue; }\n\n\t\t\t\tvar tile = this._tiles[this._tileCoordsToKey(coords)];\n\t\t\t\tif (tile) {\n\t\t\t\t\ttile.current = true;\n\t\t\t\t} else {\n\t\t\t\t\tqueue.push(coords);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// sort tile queue to load tiles in order of their distance to center\n\t\tqueue.sort(function (a, b) {\n\t\t\treturn a.distanceTo(tileCenter) - b.distanceTo(tileCenter);\n\t\t});\n\n\t\tif (queue.length !== 0) {\n\t\t\t// if it's the first batch of tiles to load\n\t\t\tif (!this._loading) {\n\t\t\t\tthis._loading = true;\n\t\t\t\t// @event loading: Event\n\t\t\t\t// Fired when the grid layer starts loading tiles.\n\t\t\t\tthis.fire('loading');\n\t\t\t}\n\n\t\t\t// create DOM fragment to append tiles in one batch\n\t\t\tvar fragment = document.createDocumentFragment();\n\n\t\t\tfor (i = 0; i < queue.length; i++) {\n\t\t\t\tthis._addTile(queue[i], fragment);\n\t\t\t}\n\n\t\t\tthis._level.el.appendChild(fragment);\n\t\t}\n\t},\n\n\t_isValidTile: function (coords) {\n\t\tvar crs = this._map.options.crs;\n\n\t\tif (!crs.infinite) {\n\t\t\t// don't load tile if it's out of bounds and not wrapped\n\t\t\tvar bounds = this._globalTileRange;\n\t\t\tif ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||\n\t\t\t    (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }\n\t\t}\n\n\t\tif (!this.options.bounds) { return true; }\n\n\t\t// don't load tile if it doesn't intersect the bounds in options\n\t\tvar tileBounds = this._tileCoordsToBounds(coords);\n\t\treturn latLngBounds(this.options.bounds).overlaps(tileBounds);\n\t},\n\n\t_keyToBounds: function (key) {\n\t\treturn this._tileCoordsToBounds(this._keyToTileCoords(key));\n\t},\n\n\t_tileCoordsToNwSe: function (coords) {\n\t\tvar map = this._map,\n\t\t    tileSize = this.getTileSize(),\n\t\t    nwPoint = coords.scaleBy(tileSize),\n\t\t    sePoint = nwPoint.add(tileSize),\n\t\t    nw = map.unproject(nwPoint, coords.z),\n\t\t    se = map.unproject(sePoint, coords.z);\n\t\treturn [nw, se];\n\t},\n\n\t// converts tile coordinates to its geographical bounds\n\t_tileCoordsToBounds: function (coords) {\n\t\tvar bp = this._tileCoordsToNwSe(coords),\n\t\t    bounds = new LatLngBounds(bp[0], bp[1]);\n\n\t\tif (!this.options.noWrap) {\n\t\t\tbounds = this._map.wrapLatLngBounds(bounds);\n\t\t}\n\t\treturn bounds;\n\t},\n\t// converts tile coordinates to key for the tile cache\n\t_tileCoordsToKey: function (coords) {\n\t\treturn coords.x + ':' + coords.y + ':' + coords.z;\n\t},\n\n\t// converts tile cache key to coordinates\n\t_keyToTileCoords: function (key) {\n\t\tvar k = key.split(':'),\n\t\t    coords = new Point(+k[0], +k[1]);\n\t\tcoords.z = +k[2];\n\t\treturn coords;\n\t},\n\n\t_removeTile: function (key) {\n\t\tvar tile = this._tiles[key];\n\t\tif (!tile) { return; }\n\n\t\tDomUtil.remove(tile.el);\n\n\t\tdelete this._tiles[key];\n\n\t\t// @event tileunload: TileEvent\n\t\t// Fired when a tile is removed (e.g. when a tile goes off the screen).\n\t\tthis.fire('tileunload', {\n\t\t\ttile: tile.el,\n\t\t\tcoords: this._keyToTileCoords(key)\n\t\t});\n\t},\n\n\t_initTile: function (tile) {\n\t\tDomUtil.addClass(tile, 'leaflet-tile');\n\n\t\tvar tileSize = this.getTileSize();\n\t\ttile.style.width = tileSize.x + 'px';\n\t\ttile.style.height = tileSize.y + 'px';\n\n\t\ttile.onselectstart = Util.falseFn;\n\t\ttile.onmousemove = Util.falseFn;\n\n\t\t// update opacity on tiles in IE7-8 because of filter inheritance problems\n\t\tif (Browser.ielt9 && this.options.opacity < 1) {\n\t\t\tDomUtil.setOpacity(tile, this.options.opacity);\n\t\t}\n\t},\n\n\t_addTile: function (coords, container) {\n\t\tvar tilePos = this._getTilePos(coords),\n\t\t    key = this._tileCoordsToKey(coords);\n\n\t\tvar tile = this.createTile(this._wrapCoords(coords), Util.bind(this._tileReady, this, coords));\n\n\t\tthis._initTile(tile);\n\n\t\t// if createTile is defined with a second argument (\"done\" callback),\n\t\t// we know that tile is async and will be ready later; otherwise\n\t\tif (this.createTile.length < 2) {\n\t\t\t// mark tile as ready, but delay one frame for opacity animation to happen\n\t\t\tUtil.requestAnimFrame(Util.bind(this._tileReady, this, coords, null, tile));\n\t\t}\n\n\t\tDomUtil.setPosition(tile, tilePos);\n\n\t\t// save tile in cache\n\t\tthis._tiles[key] = {\n\t\t\tel: tile,\n\t\t\tcoords: coords,\n\t\t\tcurrent: true\n\t\t};\n\n\t\tcontainer.appendChild(tile);\n\t\t// @event tileloadstart: TileEvent\n\t\t// Fired when a tile is requested and starts loading.\n\t\tthis.fire('tileloadstart', {\n\t\t\ttile: tile,\n\t\t\tcoords: coords\n\t\t});\n\t},\n\n\t_tileReady: function (coords, err, tile) {\n\t\tif (err) {\n\t\t\t// @event tileerror: TileErrorEvent\n\t\t\t// Fired when there is an error loading a tile.\n\t\t\tthis.fire('tileerror', {\n\t\t\t\terror: err,\n\t\t\t\ttile: tile,\n\t\t\t\tcoords: coords\n\t\t\t});\n\t\t}\n\n\t\tvar key = this._tileCoordsToKey(coords);\n\n\t\ttile = this._tiles[key];\n\t\tif (!tile) { return; }\n\n\t\ttile.loaded = +new Date();\n\t\tif (this._map._fadeAnimated) {\n\t\t\tDomUtil.setOpacity(tile.el, 0);\n\t\t\tUtil.cancelAnimFrame(this._fadeFrame);\n\t\t\tthis._fadeFrame = Util.requestAnimFrame(this._updateOpacity, this);\n\t\t} else {\n\t\t\ttile.active = true;\n\t\t\tthis._pruneTiles();\n\t\t}\n\n\t\tif (!err) {\n\t\t\tDomUtil.addClass(tile.el, 'leaflet-tile-loaded');\n\n\t\t\t// @event tileload: TileEvent\n\t\t\t// Fired when a tile loads.\n\t\t\tthis.fire('tileload', {\n\t\t\t\ttile: tile.el,\n\t\t\t\tcoords: coords\n\t\t\t});\n\t\t}\n\n\t\tif (this._noTilesToLoad()) {\n\t\t\tthis._loading = false;\n\t\t\t// @event load: Event\n\t\t\t// Fired when the grid layer loaded all visible tiles.\n\t\t\tthis.fire('load');\n\n\t\t\tif (Browser.ielt9 || !this._map._fadeAnimated) {\n\t\t\t\tUtil.requestAnimFrame(this._pruneTiles, this);\n\t\t\t} else {\n\t\t\t\t// Wait a bit more than 0.2 secs (the duration of the tile fade-in)\n\t\t\t\t// to trigger a pruning.\n\t\t\t\tsetTimeout(Util.bind(this._pruneTiles, this), 250);\n\t\t\t}\n\t\t}\n\t},\n\n\t_getTilePos: function (coords) {\n\t\treturn coords.scaleBy(this.getTileSize()).subtract(this._level.origin);\n\t},\n\n\t_wrapCoords: function (coords) {\n\t\tvar newCoords = new Point(\n\t\t\tthis._wrapX ? Util.wrapNum(coords.x, this._wrapX) : coords.x,\n\t\t\tthis._wrapY ? Util.wrapNum(coords.y, this._wrapY) : coords.y);\n\t\tnewCoords.z = coords.z;\n\t\treturn newCoords;\n\t},\n\n\t_pxBoundsToTileRange: function (bounds) {\n\t\tvar tileSize = this.getTileSize();\n\t\treturn new Bounds(\n\t\t\tbounds.min.unscaleBy(tileSize).floor(),\n\t\t\tbounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));\n\t},\n\n\t_noTilesToLoad: function () {\n\t\tfor (var key in this._tiles) {\n\t\t\tif (!this._tiles[key].loaded) { return false; }\n\t\t}\n\t\treturn true;\n\t}\n});\n\n// @factory L.gridLayer(options?: GridLayer options)\n// Creates a new instance of GridLayer with the supplied options.\nexport function gridLayer(options) {\n\treturn new GridLayer(options);\n}\n","import {GridLayer} from './GridLayer';\r\nimport Browser from '../../core/Browser';\r\nimport * as Util from '../../core/Util';\r\nimport * as DomEvent from '../../dom/DomEvent';\r\nimport * as DomUtil from '../../dom/DomUtil';\r\n\r\n\r\n/*\r\n * @class TileLayer\r\n * @inherits GridLayer\r\n * @aka L.TileLayer\r\n * Used to load and display tile layers on the map. Note that most tile servers require attribution, which you can set under `Layer`. Extends `GridLayer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: '&copy; <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors'}).addTo(map);\n * ```\r\n *\r\n * @section URL template\r\n * @example\r\n *\r\n * A string of the following form:\r\n *\r\n * ```\r\n * 'https://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'\r\n * ```\r\n *\r\n * `{s}` means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; `a`, `b` or `c` by default, can be omitted), `{z}` — zoom level, `{x}` and `{y}` — tile coordinates. `{r}` can be used to add \"&commat;2x\" to the URL to load retina tiles.\r\n *\r\n * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:\r\n *\r\n * ```\r\n * L.tileLayer('https://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});\r\n * ```\r\n */\r\n\r\n\r\nexport var TileLayer = GridLayer.extend({\r\n\r\n\t// @section\r\n\t// @aka TileLayer options\r\n\toptions: {\r\n\t\t// @option minZoom: Number = 0\r\n\t\t// The minimum zoom level down to which this layer will be displayed (inclusive).\r\n\t\tminZoom: 0,\r\n\r\n\t\t// @option maxZoom: Number = 18\r\n\t\t// The maximum zoom level up to which this layer will be displayed (inclusive).\r\n\t\tmaxZoom: 18,\r\n\r\n\t\t// @option subdomains: String|String[] = 'abc'\r\n\t\t// Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.\r\n\t\tsubdomains: 'abc',\r\n\r\n\t\t// @option errorTileUrl: String = ''\r\n\t\t// URL to the tile image to show in place of the tile that failed to load.\r\n\t\terrorTileUrl: '',\r\n\r\n\t\t// @option zoomOffset: Number = 0\r\n\t\t// The zoom number used in tile URLs will be offset with this value.\r\n\t\tzoomOffset: 0,\r\n\r\n\t\t// @option tms: Boolean = false\r\n\t\t// If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).\r\n\t\ttms: false,\r\n\r\n\t\t// @option zoomReverse: Boolean = false\r\n\t\t// If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)\r\n\t\tzoomReverse: false,\r\n\r\n\t\t// @option detectRetina: Boolean = false\r\n\t\t// If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.\r\n\t\tdetectRetina: false,\r\n\r\n\t\t// @option crossOrigin: Boolean|String = false\r\n\t\t// Whether the crossOrigin attribute will be added to the tiles.\r\n\t\t// If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.\r\n\t\t// Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.\r\n\t\tcrossOrigin: false,\r\n\r\n\t\t// @option referrerPolicy: Boolean|String = false\r\n\t\t// Whether the referrerPolicy attribute will be added to the tiles.\r\n\t\t// If a String is provided, all tiles will have their referrerPolicy attribute set to the String provided.\r\n\t\t// This may be needed if your map's rendering context has a strict default but your tile provider expects a valid referrer\r\n\t\t// (e.g. to validate an API token).\r\n\t\t// Refer to [HTMLImageElement.referrerPolicy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/referrerPolicy) for valid String values.\r\n\t\treferrerPolicy: false\r\n\t},\r\n\r\n\tinitialize: function (url, options) {\r\n\r\n\t\tthis._url = url;\r\n\r\n\t\toptions = Util.setOptions(this, options);\r\n\r\n\t\t// detecting retina displays, adjusting tileSize and zoom levels\r\n\t\tif (options.detectRetina && Browser.retina && options.maxZoom > 0) {\r\n\r\n\t\t\toptions.tileSize = Math.floor(options.tileSize / 2);\r\n\r\n\t\t\tif (!options.zoomReverse) {\r\n\t\t\t\toptions.zoomOffset++;\r\n\t\t\t\toptions.maxZoom = Math.max(options.minZoom, options.maxZoom - 1);\r\n\t\t\t} else {\r\n\t\t\t\toptions.zoomOffset--;\r\n\t\t\t\toptions.minZoom = Math.min(options.maxZoom, options.minZoom + 1);\r\n\t\t\t}\r\n\r\n\t\t\toptions.minZoom = Math.max(0, options.minZoom);\r\n\t\t} else if (!options.zoomReverse) {\r\n\t\t\t// make sure maxZoom is gte minZoom\r\n\t\t\toptions.maxZoom = Math.max(options.minZoom, options.maxZoom);\r\n\t\t} else {\r\n\t\t\t// make sure minZoom is lte maxZoom\r\n\t\t\toptions.minZoom = Math.min(options.maxZoom, options.minZoom);\r\n\t\t}\r\n\r\n\t\tif (typeof options.subdomains === 'string') {\r\n\t\t\toptions.subdomains = options.subdomains.split('');\r\n\t\t}\r\n\r\n\t\tthis.on('tileunload', this._onTileRemove);\r\n\t},\r\n\r\n\t// @method setUrl(url: String, noRedraw?: Boolean): this\r\n\t// Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).\r\n\t// If the URL does not change, the layer will not be redrawn unless\r\n\t// the noRedraw parameter is set to false.\r\n\tsetUrl: function (url, noRedraw) {\r\n\t\tif (this._url === url && noRedraw === undefined) {\r\n\t\t\tnoRedraw = true;\r\n\t\t}\r\n\r\n\t\tthis._url = url;\r\n\r\n\t\tif (!noRedraw) {\r\n\t\t\tthis.redraw();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method createTile(coords: Object, done?: Function): HTMLElement\r\n\t// Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)\r\n\t// to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`\r\n\t// callback is called when the tile has been loaded.\r\n\tcreateTile: function (coords, done) {\r\n\t\tvar tile = document.createElement('img');\r\n\r\n\t\tDomEvent.on(tile, 'load', Util.bind(this._tileOnLoad, this, done, tile));\r\n\t\tDomEvent.on(tile, 'error', Util.bind(this._tileOnError, this, done, tile));\r\n\r\n\t\tif (this.options.crossOrigin || this.options.crossOrigin === '') {\r\n\t\t\ttile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;\r\n\t\t}\r\n\r\n\t\t// for this new option we follow the documented behavior\r\n\t\t// more closely by only setting the property when string\r\n\t\tif (typeof this.options.referrerPolicy === 'string') {\r\n\t\t\ttile.referrerPolicy = this.options.referrerPolicy;\r\n\t\t}\r\n\r\n\t\t// The alt attribute is set to the empty string,\r\n\t\t// allowing screen readers to ignore the decorative image tiles.\r\n\t\t// https://www.w3.org/WAI/tutorials/images/decorative/\r\n\t\t// https://www.w3.org/TR/html-aria/#el-img-empty-alt\r\n\t\ttile.alt = '';\r\n\r\n\t\ttile.src = this.getTileUrl(coords);\r\n\r\n\t\treturn tile;\r\n\t},\r\n\r\n\t// @section Extension methods\r\n\t// @uninheritable\r\n\t// Layers extending `TileLayer` might reimplement the following method.\r\n\t// @method getTileUrl(coords: Object): String\r\n\t// Called only internally, returns the URL for a tile given its coordinates.\r\n\t// Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.\r\n\tgetTileUrl: function (coords) {\r\n\t\tvar data = {\r\n\t\t\tr: Browser.retina ? '@2x' : '',\r\n\t\t\ts: this._getSubdomain(coords),\r\n\t\t\tx: coords.x,\r\n\t\t\ty: coords.y,\r\n\t\t\tz: this._getZoomForUrl()\r\n\t\t};\r\n\t\tif (this._map && !this._map.options.crs.infinite) {\r\n\t\t\tvar invertedY = this._globalTileRange.max.y - coords.y;\r\n\t\t\tif (this.options.tms) {\r\n\t\t\t\tdata['y'] = invertedY;\r\n\t\t\t}\r\n\t\t\tdata['-y'] = invertedY;\r\n\t\t}\r\n\r\n\t\treturn Util.template(this._url, Util.extend(data, this.options));\r\n\t},\r\n\r\n\t_tileOnLoad: function (done, tile) {\r\n\t\t// For https://github.com/Leaflet/Leaflet/issues/3332\r\n\t\tif (Browser.ielt9) {\r\n\t\t\tsetTimeout(Util.bind(done, this, null, tile), 0);\r\n\t\t} else {\r\n\t\t\tdone(null, tile);\r\n\t\t}\r\n\t},\r\n\r\n\t_tileOnError: function (done, tile, e) {\r\n\t\tvar errorUrl = this.options.errorTileUrl;\r\n\t\tif (errorUrl && tile.getAttribute('src') !== errorUrl) {\r\n\t\t\ttile.src = errorUrl;\r\n\t\t}\r\n\t\tdone(e, tile);\r\n\t},\r\n\r\n\t_onTileRemove: function (e) {\r\n\t\te.tile.onload = null;\r\n\t},\r\n\r\n\t_getZoomForUrl: function () {\r\n\t\tvar zoom = this._tileZoom,\r\n\t\tmaxZoom = this.options.maxZoom,\r\n\t\tzoomReverse = this.options.zoomReverse,\r\n\t\tzoomOffset = this.options.zoomOffset;\r\n\r\n\t\tif (zoomReverse) {\r\n\t\t\tzoom = maxZoom - zoom;\r\n\t\t}\r\n\r\n\t\treturn zoom + zoomOffset;\r\n\t},\r\n\r\n\t_getSubdomain: function (tilePoint) {\r\n\t\tvar index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;\r\n\t\treturn this.options.subdomains[index];\r\n\t},\r\n\r\n\t// stops loading all tiles in the background layer\r\n\t_abortLoading: function () {\r\n\t\tvar i, tile;\r\n\t\tfor (i in this._tiles) {\r\n\t\t\tif (this._tiles[i].coords.z !== this._tileZoom) {\r\n\t\t\t\ttile = this._tiles[i].el;\r\n\r\n\t\t\t\ttile.onload = Util.falseFn;\r\n\t\t\t\ttile.onerror = Util.falseFn;\r\n\r\n\t\t\t\tif (!tile.complete) {\r\n\t\t\t\t\ttile.src = Util.emptyImageUrl;\r\n\t\t\t\t\tvar coords = this._tiles[i].coords;\r\n\t\t\t\t\tDomUtil.remove(tile);\r\n\t\t\t\t\tdelete this._tiles[i];\r\n\t\t\t\t\t// @event tileabort: TileEvent\r\n\t\t\t\t\t// Fired when a tile was loading but is now not wanted.\r\n\t\t\t\t\tthis.fire('tileabort', {\r\n\t\t\t\t\t\ttile: tile,\r\n\t\t\t\t\t\tcoords: coords\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t_removeTile: function (key) {\r\n\t\tvar tile = this._tiles[key];\r\n\t\tif (!tile) { return; }\r\n\r\n\t\t// Cancels any pending http requests associated with the tile\r\n\t\ttile.el.setAttribute('src', Util.emptyImageUrl);\r\n\r\n\t\treturn GridLayer.prototype._removeTile.call(this, key);\r\n\t},\r\n\r\n\t_tileReady: function (coords, err, tile) {\r\n\t\tif (!this._map || (tile && tile.getAttribute('src') === Util.emptyImageUrl)) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\treturn GridLayer.prototype._tileReady.call(this, coords, err, tile);\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)\r\n// Instantiates a tile layer object given a `URL template` and optionally an options object.\r\n\r\nexport function tileLayer(url, options) {\r\n\treturn new TileLayer(url, options);\r\n}\r\n","import {TileLayer} from './TileLayer';\r\nimport {extend, setOptions, getParamString} from '../../core/Util';\r\nimport Browser from '../../core/Browser';\r\nimport {EPSG4326} from '../../geo/crs/CRS.EPSG4326';\r\nimport {toBounds} from '../../geometry/Bounds';\r\n\r\n/*\r\n * @class TileLayer.WMS\r\n * @inherits TileLayer\r\n * @aka L.TileLayer.WMS\r\n * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var nexrad = L.tileLayer.wms(\"http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi\", {\r\n * \tlayers: 'nexrad-n0r-900913',\r\n * \tformat: 'image/png',\r\n * \ttransparent: true,\r\n * \tattribution: \"Weather data © 2012 IEM Nexrad\"\r\n * });\r\n * ```\r\n */\r\n\r\nexport var TileLayerWMS = TileLayer.extend({\r\n\r\n\t// @section\r\n\t// @aka TileLayer.WMS options\r\n\t// If any custom options not documented here are used, they will be sent to the\r\n\t// WMS server as extra parameters in each request URL. This can be useful for\r\n\t// [non-standard vendor WMS parameters](https://docs.geoserver.org/stable/en/user/services/wms/vendor.html).\r\n\tdefaultWmsParams: {\r\n\t\tservice: 'WMS',\r\n\t\trequest: 'GetMap',\r\n\r\n\t\t// @option layers: String = ''\r\n\t\t// **(required)** Comma-separated list of WMS layers to show.\r\n\t\tlayers: '',\r\n\r\n\t\t// @option styles: String = ''\r\n\t\t// Comma-separated list of WMS styles.\r\n\t\tstyles: '',\r\n\r\n\t\t// @option format: String = 'image/jpeg'\r\n\t\t// WMS image format (use `'image/png'` for layers with transparency).\r\n\t\tformat: 'image/jpeg',\r\n\r\n\t\t// @option transparent: Boolean = false\r\n\t\t// If `true`, the WMS service will return images with transparency.\r\n\t\ttransparent: false,\r\n\r\n\t\t// @option version: String = '1.1.1'\r\n\t\t// Version of the WMS service to use\r\n\t\tversion: '1.1.1'\r\n\t},\r\n\r\n\toptions: {\r\n\t\t// @option crs: CRS = null\r\n\t\t// Coordinate Reference System to use for the WMS requests, defaults to\r\n\t\t// map CRS. Don't change this if you're not sure what it means.\r\n\t\tcrs: null,\r\n\r\n\t\t// @option uppercase: Boolean = false\r\n\t\t// If `true`, WMS request parameter keys will be uppercase.\r\n\t\tuppercase: false\r\n\t},\r\n\r\n\tinitialize: function (url, options) {\r\n\r\n\t\tthis._url = url;\r\n\r\n\t\tvar wmsParams = extend({}, this.defaultWmsParams);\r\n\r\n\t\t// all keys that are not TileLayer options go to WMS params\r\n\t\tfor (var i in options) {\r\n\t\t\tif (!(i in this.options)) {\r\n\t\t\t\twmsParams[i] = options[i];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\toptions = setOptions(this, options);\r\n\r\n\t\tvar realRetina = options.detectRetina && Browser.retina ? 2 : 1;\r\n\t\tvar tileSize = this.getTileSize();\r\n\t\twmsParams.width = tileSize.x * realRetina;\r\n\t\twmsParams.height = tileSize.y * realRetina;\r\n\r\n\t\tthis.wmsParams = wmsParams;\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\r\n\t\tthis._crs = this.options.crs || map.options.crs;\r\n\t\tthis._wmsVersion = parseFloat(this.wmsParams.version);\r\n\r\n\t\tvar projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';\r\n\t\tthis.wmsParams[projectionKey] = this._crs.code;\r\n\r\n\t\tTileLayer.prototype.onAdd.call(this, map);\r\n\t},\r\n\r\n\tgetTileUrl: function (coords) {\r\n\r\n\t\tvar tileBounds = this._tileCoordsToNwSe(coords),\r\n\t\t    crs = this._crs,\r\n\t\t    bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),\r\n\t\t    min = bounds.min,\r\n\t\t    max = bounds.max,\r\n\t\t    bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?\r\n\t\t    [min.y, min.x, max.y, max.x] :\r\n\t\t    [min.x, min.y, max.x, max.y]).join(','),\r\n\t\t    url = TileLayer.prototype.getTileUrl.call(this, coords);\r\n\t\treturn url +\r\n\t\t\tgetParamString(this.wmsParams, url, this.options.uppercase) +\r\n\t\t\t(this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;\r\n\t},\r\n\r\n\t// @method setParams(params: Object, noRedraw?: Boolean): this\r\n\t// Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).\r\n\tsetParams: function (params, noRedraw) {\r\n\r\n\t\textend(this.wmsParams, params);\r\n\r\n\t\tif (!noRedraw) {\r\n\t\t\tthis.redraw();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)\r\n// Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.\r\nexport function tileLayerWMS(url, options) {\r\n\treturn new TileLayerWMS(url, options);\r\n}\r\n","export {GridLayer, gridLayer} from './GridLayer';\nimport {TileLayer, tileLayer} from './TileLayer';\nimport {TileLayerWMS, tileLayerWMS} from './TileLayer.WMS';\nTileLayer.WMS = TileLayerWMS;\ntileLayer.wms = tileLayerWMS;\nexport {TileLayer, tileLayer};\n","import {Layer} from '../Layer';\nimport * as DomUtil from '../../dom/DomUtil';\nimport * as Util from '../../core/Util';\nimport Browser from '../../core/Browser';\nimport {Bounds} from '../../geometry/Bounds';\n\n\n\n/*\n * @class Renderer\n * @inherits Layer\n * @aka L.Renderer\n *\n * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the\n * DOM container of the renderer, its bounds, and its zoom animation.\n *\n * A `Renderer` works as an implicit layer group for all `Path`s - the renderer\n * itself can be added or removed to the map. All paths use a renderer, which can\n * be implicit (the map will decide the type of renderer and use it automatically)\n * or explicit (using the [`renderer`](#path-renderer) option of the path).\n *\n * Do not use this class directly, use `SVG` and `Canvas` instead.\n *\n * @event update: Event\n * Fired when the renderer updates its bounds, center and zoom, for example when\n * its map has moved\n */\n\nexport var Renderer = Layer.extend({\n\n\t// @section\n\t// @aka Renderer options\n\toptions: {\n\t\t// @option padding: Number = 0.1\n\t\t// How much to extend the clip area around the map view (relative to its size)\n\t\t// e.g. 0.1 would be 10% of map view in each direction\n\t\tpadding: 0.1\n\t},\n\n\tinitialize: function (options) {\n\t\tUtil.setOptions(this, options);\n\t\tUtil.stamp(this);\n\t\tthis._layers = this._layers || {};\n\t},\n\n\tonAdd: function () {\n\t\tif (!this._container) {\n\t\t\tthis._initContainer(); // defined by renderer implementations\n\n\t\t\t// always keep transform-origin as 0 0\n\t\t\tDomUtil.addClass(this._container, 'leaflet-zoom-animated');\n\t\t}\n\n\t\tthis.getPane().appendChild(this._container);\n\t\tthis._update();\n\t\tthis.on('update', this._updatePaths, this);\n\t},\n\n\tonRemove: function () {\n\t\tthis.off('update', this._updatePaths, this);\n\t\tthis._destroyContainer();\n\t},\n\n\tgetEvents: function () {\n\t\tvar events = {\n\t\t\tviewreset: this._reset,\n\t\t\tzoom: this._onZoom,\n\t\t\tmoveend: this._update,\n\t\t\tzoomend: this._onZoomEnd\n\t\t};\n\t\tif (this._zoomAnimated) {\n\t\t\tevents.zoomanim = this._onAnimZoom;\n\t\t}\n\t\treturn events;\n\t},\n\n\t_onAnimZoom: function (ev) {\n\t\tthis._updateTransform(ev.center, ev.zoom);\n\t},\n\n\t_onZoom: function () {\n\t\tthis._updateTransform(this._map.getCenter(), this._map.getZoom());\n\t},\n\n\t_updateTransform: function (center, zoom) {\n\t\tvar scale = this._map.getZoomScale(zoom, this._zoom),\n\t\t    viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),\n\t\t    currentCenterPoint = this._map.project(this._center, zoom),\n\n\t\t    topLeftOffset = viewHalf.multiplyBy(-scale).add(currentCenterPoint)\n\t\t\t\t  .subtract(this._map._getNewPixelOrigin(center, zoom));\n\n\t\tif (Browser.any3d) {\n\t\t\tDomUtil.setTransform(this._container, topLeftOffset, scale);\n\t\t} else {\n\t\t\tDomUtil.setPosition(this._container, topLeftOffset);\n\t\t}\n\t},\n\n\t_reset: function () {\n\t\tthis._update();\n\t\tthis._updateTransform(this._center, this._zoom);\n\n\t\tfor (var id in this._layers) {\n\t\t\tthis._layers[id]._reset();\n\t\t}\n\t},\n\n\t_onZoomEnd: function () {\n\t\tfor (var id in this._layers) {\n\t\t\tthis._layers[id]._project();\n\t\t}\n\t},\n\n\t_updatePaths: function () {\n\t\tfor (var id in this._layers) {\n\t\t\tthis._layers[id]._update();\n\t\t}\n\t},\n\n\t_update: function () {\n\t\t// Update pixel bounds of renderer container (for positioning/sizing/clipping later)\n\t\t// Subclasses are responsible of firing the 'update' event.\n\t\tvar p = this.options.padding,\n\t\t    size = this._map.getSize(),\n\t\t    min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();\n\n\t\tthis._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());\n\n\t\tthis._center = this._map.getCenter();\n\t\tthis._zoom = this._map.getZoom();\n\t}\n});\n","import {Renderer} from './Renderer';\nimport * as DomUtil from '../../dom/DomUtil';\nimport * as DomEvent from '../../dom/DomEvent';\nimport Browser from '../../core/Browser';\nimport * as Util from '../../core/Util';\nimport {Bounds} from '../../geometry/Bounds';\n\n/*\n * @class Canvas\n * @inherits Renderer\n * @aka L.Canvas\n *\n * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).\n * Inherits `Renderer`.\n *\n * Due to [technical limitations](https://caniuse.com/canvas), Canvas is not\n * available in all web browsers, notably IE8, and overlapping geometries might\n * not display properly in some edge cases.\n *\n * @example\n *\n * Use Canvas by default for all paths in the map:\n *\n * ```js\n * var map = L.map('map', {\n * \trenderer: L.canvas()\n * });\n * ```\n *\n * Use a Canvas renderer with extra padding for specific vector geometries:\n *\n * ```js\n * var map = L.map('map');\n * var myRenderer = L.canvas({ padding: 0.5 });\n * var line = L.polyline( coordinates, { renderer: myRenderer } );\n * var circle = L.circle( center, { renderer: myRenderer } );\n * ```\n */\n\nexport var Canvas = Renderer.extend({\n\n\t// @section\n\t// @aka Canvas options\n\toptions: {\n\t\t// @option tolerance: Number = 0\n\t\t// How much to extend the click tolerance around a path/object on the map.\n\t\ttolerance: 0\n\t},\n\n\tgetEvents: function () {\n\t\tvar events = Renderer.prototype.getEvents.call(this);\n\t\tevents.viewprereset = this._onViewPreReset;\n\t\treturn events;\n\t},\n\n\t_onViewPreReset: function () {\n\t\t// Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once\n\t\tthis._postponeUpdatePaths = true;\n\t},\n\n\tonAdd: function () {\n\t\tRenderer.prototype.onAdd.call(this);\n\n\t\t// Redraw vectors since canvas is cleared upon removal,\n\t\t// in case of removing the renderer itself from the map.\n\t\tthis._draw();\n\t},\n\n\t_initContainer: function () {\n\t\tvar container = this._container = document.createElement('canvas');\n\n\t\tDomEvent.on(container, 'mousemove', this._onMouseMove, this);\n\t\tDomEvent.on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);\n\t\tDomEvent.on(container, 'mouseout', this._handleMouseOut, this);\n\t\tcontainer['_leaflet_disable_events'] = true;\n\n\t\tthis._ctx = container.getContext('2d');\n\t},\n\n\t_destroyContainer: function () {\n\t\tUtil.cancelAnimFrame(this._redrawRequest);\n\t\tdelete this._ctx;\n\t\tDomUtil.remove(this._container);\n\t\tDomEvent.off(this._container);\n\t\tdelete this._container;\n\t},\n\n\t_updatePaths: function () {\n\t\tif (this._postponeUpdatePaths) { return; }\n\n\t\tvar layer;\n\t\tthis._redrawBounds = null;\n\t\tfor (var id in this._layers) {\n\t\t\tlayer = this._layers[id];\n\t\t\tlayer._update();\n\t\t}\n\t\tthis._redraw();\n\t},\n\n\t_update: function () {\n\t\tif (this._map._animatingZoom && this._bounds) { return; }\n\n\t\tRenderer.prototype._update.call(this);\n\n\t\tvar b = this._bounds,\n\t\t    container = this._container,\n\t\t    size = b.getSize(),\n\t\t    m = Browser.retina ? 2 : 1;\n\n\t\tDomUtil.setPosition(container, b.min);\n\n\t\t// set canvas size (also clearing it); use double size on retina\n\t\tcontainer.width = m * size.x;\n\t\tcontainer.height = m * size.y;\n\t\tcontainer.style.width = size.x + 'px';\n\t\tcontainer.style.height = size.y + 'px';\n\n\t\tif (Browser.retina) {\n\t\t\tthis._ctx.scale(2, 2);\n\t\t}\n\n\t\t// translate so we use the same path coordinates after canvas element moves\n\t\tthis._ctx.translate(-b.min.x, -b.min.y);\n\n\t\t// Tell paths to redraw themselves\n\t\tthis.fire('update');\n\t},\n\n\t_reset: function () {\n\t\tRenderer.prototype._reset.call(this);\n\n\t\tif (this._postponeUpdatePaths) {\n\t\t\tthis._postponeUpdatePaths = false;\n\t\t\tthis._updatePaths();\n\t\t}\n\t},\n\n\t_initPath: function (layer) {\n\t\tthis._updateDashArray(layer);\n\t\tthis._layers[Util.stamp(layer)] = layer;\n\n\t\tvar order = layer._order = {\n\t\t\tlayer: layer,\n\t\t\tprev: this._drawLast,\n\t\t\tnext: null\n\t\t};\n\t\tif (this._drawLast) { this._drawLast.next = order; }\n\t\tthis._drawLast = order;\n\t\tthis._drawFirst = this._drawFirst || this._drawLast;\n\t},\n\n\t_addPath: function (layer) {\n\t\tthis._requestRedraw(layer);\n\t},\n\n\t_removePath: function (layer) {\n\t\tvar order = layer._order;\n\t\tvar next = order.next;\n\t\tvar prev = order.prev;\n\n\t\tif (next) {\n\t\t\tnext.prev = prev;\n\t\t} else {\n\t\t\tthis._drawLast = prev;\n\t\t}\n\t\tif (prev) {\n\t\t\tprev.next = next;\n\t\t} else {\n\t\t\tthis._drawFirst = next;\n\t\t}\n\n\t\tdelete layer._order;\n\n\t\tdelete this._layers[Util.stamp(layer)];\n\n\t\tthis._requestRedraw(layer);\n\t},\n\n\t_updatePath: function (layer) {\n\t\t// Redraw the union of the layer's old pixel\n\t\t// bounds and the new pixel bounds.\n\t\tthis._extendRedrawBounds(layer);\n\t\tlayer._project();\n\t\tlayer._update();\n\t\t// The redraw will extend the redraw bounds\n\t\t// with the new pixel bounds.\n\t\tthis._requestRedraw(layer);\n\t},\n\n\t_updateStyle: function (layer) {\n\t\tthis._updateDashArray(layer);\n\t\tthis._requestRedraw(layer);\n\t},\n\n\t_updateDashArray: function (layer) {\n\t\tif (typeof layer.options.dashArray === 'string') {\n\t\t\tvar parts = layer.options.dashArray.split(/[, ]+/),\n\t\t\t    dashArray = [],\n\t\t\t    dashValue,\n\t\t\t    i;\n\t\t\tfor (i = 0; i < parts.length; i++) {\n\t\t\t\tdashValue = Number(parts[i]);\n\t\t\t\t// Ignore dash array containing invalid lengths\n\t\t\t\tif (isNaN(dashValue)) { return; }\n\t\t\t\tdashArray.push(dashValue);\n\t\t\t}\n\t\t\tlayer.options._dashArray = dashArray;\n\t\t} else {\n\t\t\tlayer.options._dashArray = layer.options.dashArray;\n\t\t}\n\t},\n\n\t_requestRedraw: function (layer) {\n\t\tif (!this._map) { return; }\n\n\t\tthis._extendRedrawBounds(layer);\n\t\tthis._redrawRequest = this._redrawRequest || Util.requestAnimFrame(this._redraw, this);\n\t},\n\n\t_extendRedrawBounds: function (layer) {\n\t\tif (layer._pxBounds) {\n\t\t\tvar padding = (layer.options.weight || 0) + 1;\n\t\t\tthis._redrawBounds = this._redrawBounds || new Bounds();\n\t\t\tthis._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));\n\t\t\tthis._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));\n\t\t}\n\t},\n\n\t_redraw: function () {\n\t\tthis._redrawRequest = null;\n\n\t\tif (this._redrawBounds) {\n\t\t\tthis._redrawBounds.min._floor();\n\t\t\tthis._redrawBounds.max._ceil();\n\t\t}\n\n\t\tthis._clear(); // clear layers in redraw bounds\n\t\tthis._draw(); // draw layers\n\n\t\tthis._redrawBounds = null;\n\t},\n\n\t_clear: function () {\n\t\tvar bounds = this._redrawBounds;\n\t\tif (bounds) {\n\t\t\tvar size = bounds.getSize();\n\t\t\tthis._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);\n\t\t} else {\n\t\t\tthis._ctx.save();\n\t\t\tthis._ctx.setTransform(1, 0, 0, 1, 0, 0);\n\t\t\tthis._ctx.clearRect(0, 0, this._container.width, this._container.height);\n\t\t\tthis._ctx.restore();\n\t\t}\n\t},\n\n\t_draw: function () {\n\t\tvar layer, bounds = this._redrawBounds;\n\t\tthis._ctx.save();\n\t\tif (bounds) {\n\t\t\tvar size = bounds.getSize();\n\t\t\tthis._ctx.beginPath();\n\t\t\tthis._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);\n\t\t\tthis._ctx.clip();\n\t\t}\n\n\t\tthis._drawing = true;\n\n\t\tfor (var order = this._drawFirst; order; order = order.next) {\n\t\t\tlayer = order.layer;\n\t\t\tif (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {\n\t\t\t\tlayer._updatePath();\n\t\t\t}\n\t\t}\n\n\t\tthis._drawing = false;\n\n\t\tthis._ctx.restore();  // Restore state before clipping.\n\t},\n\n\t_updatePoly: function (layer, closed) {\n\t\tif (!this._drawing) { return; }\n\n\t\tvar i, j, len2, p,\n\t\t    parts = layer._parts,\n\t\t    len = parts.length,\n\t\t    ctx = this._ctx;\n\n\t\tif (!len) { return; }\n\n\t\tctx.beginPath();\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tfor (j = 0, len2 = parts[i].length; j < len2; j++) {\n\t\t\t\tp = parts[i][j];\n\t\t\t\tctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);\n\t\t\t}\n\t\t\tif (closed) {\n\t\t\t\tctx.closePath();\n\t\t\t}\n\t\t}\n\n\t\tthis._fillStroke(ctx, layer);\n\n\t\t// TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature\n\t},\n\n\t_updateCircle: function (layer) {\n\n\t\tif (!this._drawing || layer._empty()) { return; }\n\n\t\tvar p = layer._point,\n\t\t    ctx = this._ctx,\n\t\t    r = Math.max(Math.round(layer._radius), 1),\n\t\t    s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;\n\n\t\tif (s !== 1) {\n\t\t\tctx.save();\n\t\t\tctx.scale(1, s);\n\t\t}\n\n\t\tctx.beginPath();\n\t\tctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);\n\n\t\tif (s !== 1) {\n\t\t\tctx.restore();\n\t\t}\n\n\t\tthis._fillStroke(ctx, layer);\n\t},\n\n\t_fillStroke: function (ctx, layer) {\n\t\tvar options = layer.options;\n\n\t\tif (options.fill) {\n\t\t\tctx.globalAlpha = options.fillOpacity;\n\t\t\tctx.fillStyle = options.fillColor || options.color;\n\t\t\tctx.fill(options.fillRule || 'evenodd');\n\t\t}\n\n\t\tif (options.stroke && options.weight !== 0) {\n\t\t\tif (ctx.setLineDash) {\n\t\t\t\tctx.setLineDash(layer.options && layer.options._dashArray || []);\n\t\t\t}\n\t\t\tctx.globalAlpha = options.opacity;\n\t\t\tctx.lineWidth = options.weight;\n\t\t\tctx.strokeStyle = options.color;\n\t\t\tctx.lineCap = options.lineCap;\n\t\t\tctx.lineJoin = options.lineJoin;\n\t\t\tctx.stroke();\n\t\t}\n\t},\n\n\t// Canvas obviously doesn't have mouse events for individual drawn objects,\n\t// so we emulate that by calculating what's under the mouse on mousemove/click manually\n\n\t_onClick: function (e) {\n\t\tvar point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;\n\n\t\tfor (var order = this._drawFirst; order; order = order.next) {\n\t\t\tlayer = order.layer;\n\t\t\tif (layer.options.interactive && layer._containsPoint(point)) {\n\t\t\t\tif (!(e.type === 'click' || e.type === 'preclick') || !this._map._draggableMoved(layer)) {\n\t\t\t\t\tclickedLayer = layer;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis._fireEvent(clickedLayer ? [clickedLayer] : false, e);\n\t},\n\n\t_onMouseMove: function (e) {\n\t\tif (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }\n\n\t\tvar point = this._map.mouseEventToLayerPoint(e);\n\t\tthis._handleMouseHover(e, point);\n\t},\n\n\n\t_handleMouseOut: function (e) {\n\t\tvar layer = this._hoveredLayer;\n\t\tif (layer) {\n\t\t\t// if we're leaving the layer, fire mouseout\n\t\t\tDomUtil.removeClass(this._container, 'leaflet-interactive');\n\t\t\tthis._fireEvent([layer], e, 'mouseout');\n\t\t\tthis._hoveredLayer = null;\n\t\t\tthis._mouseHoverThrottled = false;\n\t\t}\n\t},\n\n\t_handleMouseHover: function (e, point) {\n\t\tif (this._mouseHoverThrottled) {\n\t\t\treturn;\n\t\t}\n\n\t\tvar layer, candidateHoveredLayer;\n\n\t\tfor (var order = this._drawFirst; order; order = order.next) {\n\t\t\tlayer = order.layer;\n\t\t\tif (layer.options.interactive && layer._containsPoint(point)) {\n\t\t\t\tcandidateHoveredLayer = layer;\n\t\t\t}\n\t\t}\n\n\t\tif (candidateHoveredLayer !== this._hoveredLayer) {\n\t\t\tthis._handleMouseOut(e);\n\n\t\t\tif (candidateHoveredLayer) {\n\t\t\t\tDomUtil.addClass(this._container, 'leaflet-interactive'); // change cursor\n\t\t\t\tthis._fireEvent([candidateHoveredLayer], e, 'mouseover');\n\t\t\t\tthis._hoveredLayer = candidateHoveredLayer;\n\t\t\t}\n\t\t}\n\n\t\tthis._fireEvent(this._hoveredLayer ? [this._hoveredLayer] : false, e);\n\n\t\tthis._mouseHoverThrottled = true;\n\t\tsetTimeout(Util.bind(function () {\n\t\t\tthis._mouseHoverThrottled = false;\n\t\t}, this), 32);\n\t},\n\n\t_fireEvent: function (layers, e, type) {\n\t\tthis._map._fireDOMEvent(e, type || e.type, layers);\n\t},\n\n\t_bringToFront: function (layer) {\n\t\tvar order = layer._order;\n\n\t\tif (!order) { return; }\n\n\t\tvar next = order.next;\n\t\tvar prev = order.prev;\n\n\t\tif (next) {\n\t\t\tnext.prev = prev;\n\t\t} else {\n\t\t\t// Already last\n\t\t\treturn;\n\t\t}\n\t\tif (prev) {\n\t\t\tprev.next = next;\n\t\t} else if (next) {\n\t\t\t// Update first entry unless this is the\n\t\t\t// single entry\n\t\t\tthis._drawFirst = next;\n\t\t}\n\n\t\torder.prev = this._drawLast;\n\t\tthis._drawLast.next = order;\n\n\t\torder.next = null;\n\t\tthis._drawLast = order;\n\n\t\tthis._requestRedraw(layer);\n\t},\n\n\t_bringToBack: function (layer) {\n\t\tvar order = layer._order;\n\n\t\tif (!order) { return; }\n\n\t\tvar next = order.next;\n\t\tvar prev = order.prev;\n\n\t\tif (prev) {\n\t\t\tprev.next = next;\n\t\t} else {\n\t\t\t// Already first\n\t\t\treturn;\n\t\t}\n\t\tif (next) {\n\t\t\tnext.prev = prev;\n\t\t} else if (prev) {\n\t\t\t// Update last entry unless this is the\n\t\t\t// single entry\n\t\t\tthis._drawLast = prev;\n\t\t}\n\n\t\torder.prev = null;\n\n\t\torder.next = this._drawFirst;\n\t\tthis._drawFirst.prev = order;\n\t\tthis._drawFirst = order;\n\n\t\tthis._requestRedraw(layer);\n\t}\n});\n\n// @factory L.canvas(options?: Renderer options)\n// Creates a Canvas renderer with the given options.\nexport function canvas(options) {\n\treturn Browser.canvas ? new Canvas(options) : null;\n}\n","import * as DomUtil from '../../dom/DomUtil';\nimport * as Util from '../../core/Util';\nimport {Renderer} from './Renderer';\n\n/*\n * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!\n */\n\n\nexport var vmlCreate = (function () {\n\ttry {\n\t\tdocument.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');\n\t\treturn function (name) {\n\t\t\treturn document.createElement('<lvml:' + name + ' class=\"lvml\">');\n\t\t};\n\t} catch (e) {\n\t\t// Do not return fn from catch block so `e` can be garbage collected\n\t\t// See https://github.com/Leaflet/Leaflet/pull/7279\n\t}\n\treturn function (name) {\n\t\treturn document.createElement('<' + name + ' xmlns=\"urn:schemas-microsoft.com:vml\" class=\"lvml\">');\n\t};\n})();\n\n\n/*\n * @class SVG\n *\n *\n * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility\n * with old versions of Internet Explorer.\n */\n\n// mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences\nexport var vmlMixin = {\n\n\t_initContainer: function () {\n\t\tthis._container = DomUtil.create('div', 'leaflet-vml-container');\n\t},\n\n\t_update: function () {\n\t\tif (this._map._animatingZoom) { return; }\n\t\tRenderer.prototype._update.call(this);\n\t\tthis.fire('update');\n\t},\n\n\t_initPath: function (layer) {\n\t\tvar container = layer._container = vmlCreate('shape');\n\n\t\tDomUtil.addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));\n\n\t\tcontainer.coordsize = '1 1';\n\n\t\tlayer._path = vmlCreate('path');\n\t\tcontainer.appendChild(layer._path);\n\n\t\tthis._updateStyle(layer);\n\t\tthis._layers[Util.stamp(layer)] = layer;\n\t},\n\n\t_addPath: function (layer) {\n\t\tvar container = layer._container;\n\t\tthis._container.appendChild(container);\n\n\t\tif (layer.options.interactive) {\n\t\t\tlayer.addInteractiveTarget(container);\n\t\t}\n\t},\n\n\t_removePath: function (layer) {\n\t\tvar container = layer._container;\n\t\tDomUtil.remove(container);\n\t\tlayer.removeInteractiveTarget(container);\n\t\tdelete this._layers[Util.stamp(layer)];\n\t},\n\n\t_updateStyle: function (layer) {\n\t\tvar stroke = layer._stroke,\n\t\t    fill = layer._fill,\n\t\t    options = layer.options,\n\t\t    container = layer._container;\n\n\t\tcontainer.stroked = !!options.stroke;\n\t\tcontainer.filled = !!options.fill;\n\n\t\tif (options.stroke) {\n\t\t\tif (!stroke) {\n\t\t\t\tstroke = layer._stroke = vmlCreate('stroke');\n\t\t\t}\n\t\t\tcontainer.appendChild(stroke);\n\t\t\tstroke.weight = options.weight + 'px';\n\t\t\tstroke.color = options.color;\n\t\t\tstroke.opacity = options.opacity;\n\n\t\t\tif (options.dashArray) {\n\t\t\t\tstroke.dashStyle = Util.isArray(options.dashArray) ?\n\t\t\t\t    options.dashArray.join(' ') :\n\t\t\t\t    options.dashArray.replace(/( *, *)/g, ' ');\n\t\t\t} else {\n\t\t\t\tstroke.dashStyle = '';\n\t\t\t}\n\t\t\tstroke.endcap = options.lineCap.replace('butt', 'flat');\n\t\t\tstroke.joinstyle = options.lineJoin;\n\n\t\t} else if (stroke) {\n\t\t\tcontainer.removeChild(stroke);\n\t\t\tlayer._stroke = null;\n\t\t}\n\n\t\tif (options.fill) {\n\t\t\tif (!fill) {\n\t\t\t\tfill = layer._fill = vmlCreate('fill');\n\t\t\t}\n\t\t\tcontainer.appendChild(fill);\n\t\t\tfill.color = options.fillColor || options.color;\n\t\t\tfill.opacity = options.fillOpacity;\n\n\t\t} else if (fill) {\n\t\t\tcontainer.removeChild(fill);\n\t\t\tlayer._fill = null;\n\t\t}\n\t},\n\n\t_updateCircle: function (layer) {\n\t\tvar p = layer._point.round(),\n\t\t    r = Math.round(layer._radius),\n\t\t    r2 = Math.round(layer._radiusY || r);\n\n\t\tthis._setPath(layer, layer._empty() ? 'M0 0' :\n\t\t\t'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));\n\t},\n\n\t_setPath: function (layer, path) {\n\t\tlayer._path.v = path;\n\t},\n\n\t_bringToFront: function (layer) {\n\t\tDomUtil.toFront(layer._container);\n\t},\n\n\t_bringToBack: function (layer) {\n\t\tDomUtil.toBack(layer._container);\n\t}\n};\n","import {Renderer} from './Renderer';\nimport * as DomUtil from '../../dom/DomUtil';\nimport * as DomEvent from '../../dom/DomEvent';\nimport Browser from '../../core/Browser';\nimport {stamp} from '../../core/Util';\nimport {svgCreate, pointsToPath} from './SVG.Util';\nexport {pointsToPath};\nimport {vmlMixin, vmlCreate} from './SVG.VML';\n\nexport var create = Browser.vml ? vmlCreate : svgCreate;\n\n/*\n * @class SVG\n * @inherits Renderer\n * @aka L.SVG\n *\n * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).\n * Inherits `Renderer`.\n *\n * Due to [technical limitations](https://caniuse.com/svg), SVG is not\n * available in all web browsers, notably Android 2.x and 3.x.\n *\n * Although SVG is not available on IE7 and IE8, these browsers support\n * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)\n * (a now deprecated technology), and the SVG renderer will fall back to VML in\n * this case.\n *\n * @example\n *\n * Use SVG by default for all paths in the map:\n *\n * ```js\n * var map = L.map('map', {\n * \trenderer: L.svg()\n * });\n * ```\n *\n * Use a SVG renderer with extra padding for specific vector geometries:\n *\n * ```js\n * var map = L.map('map');\n * var myRenderer = L.svg({ padding: 0.5 });\n * var line = L.polyline( coordinates, { renderer: myRenderer } );\n * var circle = L.circle( center, { renderer: myRenderer } );\n * ```\n */\n\nexport var SVG = Renderer.extend({\n\n\t_initContainer: function () {\n\t\tthis._container = create('svg');\n\n\t\t// makes it possible to click through svg root; we'll reset it back in individual paths\n\t\tthis._container.setAttribute('pointer-events', 'none');\n\n\t\tthis._rootGroup = create('g');\n\t\tthis._container.appendChild(this._rootGroup);\n\t},\n\n\t_destroyContainer: function () {\n\t\tDomUtil.remove(this._container);\n\t\tDomEvent.off(this._container);\n\t\tdelete this._container;\n\t\tdelete this._rootGroup;\n\t\tdelete this._svgSize;\n\t},\n\n\t_update: function () {\n\t\tif (this._map._animatingZoom && this._bounds) { return; }\n\n\t\tRenderer.prototype._update.call(this);\n\n\t\tvar b = this._bounds,\n\t\t    size = b.getSize(),\n\t\t    container = this._container;\n\n\t\t// set size of svg-container if changed\n\t\tif (!this._svgSize || !this._svgSize.equals(size)) {\n\t\t\tthis._svgSize = size;\n\t\t\tcontainer.setAttribute('width', size.x);\n\t\t\tcontainer.setAttribute('height', size.y);\n\t\t}\n\n\t\t// movement: update container viewBox so that we don't have to change coordinates of individual layers\n\t\tDomUtil.setPosition(container, b.min);\n\t\tcontainer.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));\n\n\t\tthis.fire('update');\n\t},\n\n\t// methods below are called by vector layers implementations\n\n\t_initPath: function (layer) {\n\t\tvar path = layer._path = create('path');\n\n\t\t// @namespace Path\n\t\t// @option className: String = null\n\t\t// Custom class name set on an element. Only for SVG renderer.\n\t\tif (layer.options.className) {\n\t\t\tDomUtil.addClass(path, layer.options.className);\n\t\t}\n\n\t\tif (layer.options.interactive) {\n\t\t\tDomUtil.addClass(path, 'leaflet-interactive');\n\t\t}\n\n\t\tthis._updateStyle(layer);\n\t\tthis._layers[stamp(layer)] = layer;\n\t},\n\n\t_addPath: function (layer) {\n\t\tif (!this._rootGroup) { this._initContainer(); }\n\t\tthis._rootGroup.appendChild(layer._path);\n\t\tlayer.addInteractiveTarget(layer._path);\n\t},\n\n\t_removePath: function (layer) {\n\t\tDomUtil.remove(layer._path);\n\t\tlayer.removeInteractiveTarget(layer._path);\n\t\tdelete this._layers[stamp(layer)];\n\t},\n\n\t_updatePath: function (layer) {\n\t\tlayer._project();\n\t\tlayer._update();\n\t},\n\n\t_updateStyle: function (layer) {\n\t\tvar path = layer._path,\n\t\t    options = layer.options;\n\n\t\tif (!path) { return; }\n\n\t\tif (options.stroke) {\n\t\t\tpath.setAttribute('stroke', options.color);\n\t\t\tpath.setAttribute('stroke-opacity', options.opacity);\n\t\t\tpath.setAttribute('stroke-width', options.weight);\n\t\t\tpath.setAttribute('stroke-linecap', options.lineCap);\n\t\t\tpath.setAttribute('stroke-linejoin', options.lineJoin);\n\n\t\t\tif (options.dashArray) {\n\t\t\t\tpath.setAttribute('stroke-dasharray', options.dashArray);\n\t\t\t} else {\n\t\t\t\tpath.removeAttribute('stroke-dasharray');\n\t\t\t}\n\n\t\t\tif (options.dashOffset) {\n\t\t\t\tpath.setAttribute('stroke-dashoffset', options.dashOffset);\n\t\t\t} else {\n\t\t\t\tpath.removeAttribute('stroke-dashoffset');\n\t\t\t}\n\t\t} else {\n\t\t\tpath.setAttribute('stroke', 'none');\n\t\t}\n\n\t\tif (options.fill) {\n\t\t\tpath.setAttribute('fill', options.fillColor || options.color);\n\t\t\tpath.setAttribute('fill-opacity', options.fillOpacity);\n\t\t\tpath.setAttribute('fill-rule', options.fillRule || 'evenodd');\n\t\t} else {\n\t\t\tpath.setAttribute('fill', 'none');\n\t\t}\n\t},\n\n\t_updatePoly: function (layer, closed) {\n\t\tthis._setPath(layer, pointsToPath(layer._parts, closed));\n\t},\n\n\t_updateCircle: function (layer) {\n\t\tvar p = layer._point,\n\t\t    r = Math.max(Math.round(layer._radius), 1),\n\t\t    r2 = Math.max(Math.round(layer._radiusY), 1) || r,\n\t\t    arc = 'a' + r + ',' + r2 + ' 0 1,0 ';\n\n\t\t// drawing a circle with two half-arcs\n\t\tvar d = layer._empty() ? 'M0 0' :\n\t\t\t'M' + (p.x - r) + ',' + p.y +\n\t\t\tarc + (r * 2) + ',0 ' +\n\t\t\tarc + (-r * 2) + ',0 ';\n\n\t\tthis._setPath(layer, d);\n\t},\n\n\t_setPath: function (layer, path) {\n\t\tlayer._path.setAttribute('d', path);\n\t},\n\n\t// SVG does not have the concept of zIndex so we resort to changing the DOM order of elements\n\t_bringToFront: function (layer) {\n\t\tDomUtil.toFront(layer._path);\n\t},\n\n\t_bringToBack: function (layer) {\n\t\tDomUtil.toBack(layer._path);\n\t}\n});\n\nif (Browser.vml) {\n\tSVG.include(vmlMixin);\n}\n\n// @namespace SVG\n// @factory L.svg(options?: Renderer options)\n// Creates a SVG renderer with the given options.\nexport function svg(options) {\n\treturn Browser.svg || Browser.vml ? new SVG(options) : null;\n}\n","import {Map} from '../../map/Map';\nimport {canvas} from './Canvas';\nimport {svg} from './SVG';\n\nMap.include({\n\t// @namespace Map; @method getRenderer(layer: Path): Renderer\n\t// Returns the instance of `Renderer` that should be used to render the given\n\t// `Path`. It will ensure that the `renderer` options of the map and paths\n\t// are respected, and that the renderers do exist on the map.\n\tgetRenderer: function (layer) {\n\t\t// @namespace Path; @option renderer: Renderer\n\t\t// Use this specific instance of `Renderer` for this path. Takes\n\t\t// precedence over the map's [default renderer](#map-renderer).\n\t\tvar renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;\n\n\t\tif (!renderer) {\n\t\t\trenderer = this._renderer = this._createRenderer();\n\t\t}\n\n\t\tif (!this.hasLayer(renderer)) {\n\t\t\tthis.addLayer(renderer);\n\t\t}\n\t\treturn renderer;\n\t},\n\n\t_getPaneRenderer: function (name) {\n\t\tif (name === 'overlayPane' || name === undefined) {\n\t\t\treturn false;\n\t\t}\n\n\t\tvar renderer = this._paneRenderers[name];\n\t\tif (renderer === undefined) {\n\t\t\trenderer = this._createRenderer({pane: name});\n\t\t\tthis._paneRenderers[name] = renderer;\n\t\t}\n\t\treturn renderer;\n\t},\n\n\t_createRenderer: function (options) {\n\t\t// @namespace Map; @option preferCanvas: Boolean = false\n\t\t// Whether `Path`s should be rendered on a `Canvas` renderer.\n\t\t// By default, all `Path`s are rendered in a `SVG` renderer.\n\t\treturn (this.options.preferCanvas && canvas(options)) || svg(options);\n\t}\n});\n","import {Polygon} from './Polygon';\nimport {toLatLngBounds} from '../../geo/LatLngBounds';\n\n/*\n * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.\n */\n\n/*\n * @class Rectangle\n * @aka L.Rectangle\n * @inherits Polygon\n *\n * A class for drawing rectangle overlays on a map. Extends `Polygon`.\n *\n * @example\n *\n * ```js\n * // define rectangle geographical bounds\n * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];\n *\n * // create an orange rectangle\n * L.rectangle(bounds, {color: \"#ff7800\", weight: 1}).addTo(map);\n *\n * // zoom the map to the rectangle bounds\n * map.fitBounds(bounds);\n * ```\n *\n */\n\n\nexport var Rectangle = Polygon.extend({\n\tinitialize: function (latLngBounds, options) {\n\t\tPolygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);\n\t},\n\n\t// @method setBounds(latLngBounds: LatLngBounds): this\n\t// Redraws the rectangle with the passed bounds.\n\tsetBounds: function (latLngBounds) {\n\t\treturn this.setLatLngs(this._boundsToLatLngs(latLngBounds));\n\t},\n\n\t_boundsToLatLngs: function (latLngBounds) {\n\t\tlatLngBounds = toLatLngBounds(latLngBounds);\n\t\treturn [\n\t\t\tlatLngBounds.getSouthWest(),\n\t\t\tlatLngBounds.getNorthWest(),\n\t\t\tlatLngBounds.getNorthEast(),\n\t\t\tlatLngBounds.getSouthEast()\n\t\t];\n\t}\n});\n\n\n// @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)\nexport function rectangle(latLngBounds, options) {\n\treturn new Rectangle(latLngBounds, options);\n}\n","export {Renderer} from './Renderer';\nexport {Canvas, canvas} from './Canvas';\nimport {SVG, create, pointsToPath, svg} from './SVG';\nSVG.create = create;\nSVG.pointsToPath = pointsToPath;\nexport {SVG, svg};\nimport './Renderer.getRenderer';\t// This is a bit of a hack, but needed because circular dependencies\n\nexport {Path} from './Path';\nexport {CircleMarker, circleMarker} from './CircleMarker';\nexport {Circle, circle} from './Circle';\nexport {Polyline, polyline} from './Polyline';\nexport {Polygon, polygon} from './Polygon';\nexport {Rectangle, rectangle} from './Rectangle';\n","export {Layer} from './Layer';\nexport {LayerGroup, layerGroup} from './LayerGroup';\nexport {FeatureGroup, featureGroup} from './FeatureGroup';\nimport {GeoJSON, geoJSON, geoJson, geometryToLayer, coordsToLatLng, coordsToLatLngs, latLngToCoords, latLngsToCoords, getFeature, asFeature} from './GeoJSON';\nGeoJSON.geometryToLayer = geometryToLayer;\nGeoJSON.coordsToLatLng = coordsToLatLng;\nGeoJSON.coordsToLatLngs = coordsToLatLngs;\nGeoJSON.latLngToCoords = latLngToCoords;\nGeoJSON.latLngsToCoords = latLngsToCoords;\nGeoJSON.getFeature = getFeature;\nGeoJSON.asFeature = asFeature;\nexport {GeoJSON, geoJSON, geoJson};\n\nexport {ImageOverlay, imageOverlay} from './ImageOverlay';\nexport {VideoOverlay, videoOverlay} from './VideoOverlay';\nexport {SVGOverlay, svgOverlay} from './SVGOverlay';\n\nexport {DivOverlay} from './DivOverlay';\nexport {Popup, popup} from './Popup';\nexport {Tooltip, tooltip} from './Tooltip';\n\nexport * from './marker/index';\nexport * from './tile/index';\nexport * from './vector/index';\n","import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport * as Util from '../../core/Util';\nimport * as DomUtil from '../../dom/DomUtil';\nimport * as DomEvent from '../../dom/DomEvent';\nimport {LatLngBounds} from '../../geo/LatLngBounds';\nimport {Bounds} from '../../geometry/Bounds';\n\n/*\n * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map\n * (zoom to a selected bounding box), enabled by default.\n */\n\n// @namespace Map\n// @section Interaction Options\nMap.mergeOptions({\n\t// @option boxZoom: Boolean = true\n\t// Whether the map can be zoomed to a rectangular area specified by\n\t// dragging the mouse while pressing the shift key.\n\tboxZoom: true\n});\n\nexport var BoxZoom = Handler.extend({\n\tinitialize: function (map) {\n\t\tthis._map = map;\n\t\tthis._container = map._container;\n\t\tthis._pane = map._panes.overlayPane;\n\t\tthis._resetStateTimeout = 0;\n\t\tmap.on('unload', this._destroy, this);\n\t},\n\n\taddHooks: function () {\n\t\tDomEvent.on(this._container, 'mousedown', this._onMouseDown, this);\n\t},\n\n\tremoveHooks: function () {\n\t\tDomEvent.off(this._container, 'mousedown', this._onMouseDown, this);\n\t},\n\n\tmoved: function () {\n\t\treturn this._moved;\n\t},\n\n\t_destroy: function () {\n\t\tDomUtil.remove(this._pane);\n\t\tdelete this._pane;\n\t},\n\n\t_resetState: function () {\n\t\tthis._resetStateTimeout = 0;\n\t\tthis._moved = false;\n\t},\n\n\t_clearDeferredResetState: function () {\n\t\tif (this._resetStateTimeout !== 0) {\n\t\t\tclearTimeout(this._resetStateTimeout);\n\t\t\tthis._resetStateTimeout = 0;\n\t\t}\n\t},\n\n\t_onMouseDown: function (e) {\n\t\tif (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }\n\n\t\t// Clear the deferred resetState if it hasn't executed yet, otherwise it\n\t\t// will interrupt the interaction and orphan a box element in the container.\n\t\tthis._clearDeferredResetState();\n\t\tthis._resetState();\n\n\t\tDomUtil.disableTextSelection();\n\t\tDomUtil.disableImageDrag();\n\n\t\tthis._startPoint = this._map.mouseEventToContainerPoint(e);\n\n\t\tDomEvent.on(document, {\n\t\t\tcontextmenu: DomEvent.stop,\n\t\t\tmousemove: this._onMouseMove,\n\t\t\tmouseup: this._onMouseUp,\n\t\t\tkeydown: this._onKeyDown\n\t\t}, this);\n\t},\n\n\t_onMouseMove: function (e) {\n\t\tif (!this._moved) {\n\t\t\tthis._moved = true;\n\n\t\t\tthis._box = DomUtil.create('div', 'leaflet-zoom-box', this._container);\n\t\t\tDomUtil.addClass(this._container, 'leaflet-crosshair');\n\n\t\t\tthis._map.fire('boxzoomstart');\n\t\t}\n\n\t\tthis._point = this._map.mouseEventToContainerPoint(e);\n\n\t\tvar bounds = new Bounds(this._point, this._startPoint),\n\t\t    size = bounds.getSize();\n\n\t\tDomUtil.setPosition(this._box, bounds.min);\n\n\t\tthis._box.style.width  = size.x + 'px';\n\t\tthis._box.style.height = size.y + 'px';\n\t},\n\n\t_finish: function () {\n\t\tif (this._moved) {\n\t\t\tDomUtil.remove(this._box);\n\t\t\tDomUtil.removeClass(this._container, 'leaflet-crosshair');\n\t\t}\n\n\t\tDomUtil.enableTextSelection();\n\t\tDomUtil.enableImageDrag();\n\n\t\tDomEvent.off(document, {\n\t\t\tcontextmenu: DomEvent.stop,\n\t\t\tmousemove: this._onMouseMove,\n\t\t\tmouseup: this._onMouseUp,\n\t\t\tkeydown: this._onKeyDown\n\t\t}, this);\n\t},\n\n\t_onMouseUp: function (e) {\n\t\tif ((e.which !== 1) && (e.button !== 1)) { return; }\n\n\t\tthis._finish();\n\n\t\tif (!this._moved) { return; }\n\t\t// Postpone to next JS tick so internal click event handling\n\t\t// still see it as \"moved\".\n\t\tthis._clearDeferredResetState();\n\t\tthis._resetStateTimeout = setTimeout(Util.bind(this._resetState, this), 0);\n\n\t\tvar bounds = new LatLngBounds(\n\t\t        this._map.containerPointToLatLng(this._startPoint),\n\t\t        this._map.containerPointToLatLng(this._point));\n\n\t\tthis._map\n\t\t\t.fitBounds(bounds)\n\t\t\t.fire('boxzoomend', {boxZoomBounds: bounds});\n\t},\n\n\t_onKeyDown: function (e) {\n\t\tif (e.keyCode === 27) {\n\t\t\tthis._finish();\n\t\t\tthis._clearDeferredResetState();\n\t\t\tthis._resetState();\n\t\t}\n\t}\n});\n\n// @section Handlers\n// @property boxZoom: Handler\n// Box (shift-drag with mouse) zoom handler.\nMap.addInitHook('addHandler', 'boxZoom', BoxZoom);\n","import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\n\n/*\n * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.\n */\n\n// @namespace Map\n// @section Interaction Options\n\nMap.mergeOptions({\n\t// @option doubleClickZoom: Boolean|String = true\n\t// Whether the map can be zoomed in by double clicking on it and\n\t// zoomed out by double clicking while holding shift. If passed\n\t// `'center'`, double-click zoom will zoom to the center of the\n\t//  view regardless of where the mouse was.\n\tdoubleClickZoom: true\n});\n\nexport var DoubleClickZoom = Handler.extend({\n\taddHooks: function () {\n\t\tthis._map.on('dblclick', this._onDoubleClick, this);\n\t},\n\n\tremoveHooks: function () {\n\t\tthis._map.off('dblclick', this._onDoubleClick, this);\n\t},\n\n\t_onDoubleClick: function (e) {\n\t\tvar map = this._map,\n\t\t    oldZoom = map.getZoom(),\n\t\t    delta = map.options.zoomDelta,\n\t\t    zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;\n\n\t\tif (map.options.doubleClickZoom === 'center') {\n\t\t\tmap.setZoom(zoom);\n\t\t} else {\n\t\t\tmap.setZoomAround(e.containerPoint, zoom);\n\t\t}\n\t}\n});\n\n// @section Handlers\n//\n// Map properties include interaction handlers that allow you to control\n// interaction behavior in runtime, enabling or disabling certain features such\n// as dragging or touch zoom (see `Handler` methods). For example:\n//\n// ```js\n// map.doubleClickZoom.disable();\n// ```\n//\n// @property doubleClickZoom: Handler\n// Double click zoom handler.\nMap.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);\n","import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport {Draggable} from '../../dom/Draggable';\nimport * as Util from '../../core/Util';\nimport * as DomUtil from '../../dom/DomUtil';\nimport {toLatLngBounds as latLngBounds} from '../../geo/LatLngBounds';\nimport {toBounds} from '../../geometry/Bounds';\n\n/*\n * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.\n */\n\n// @namespace Map\n// @section Interaction Options\nMap.mergeOptions({\n\t// @option dragging: Boolean = true\n\t// Whether the map is draggable with mouse/touch or not.\n\tdragging: true,\n\n\t// @section Panning Inertia Options\n\t// @option inertia: Boolean = *\n\t// If enabled, panning of the map will have an inertia effect where\n\t// the map builds momentum while dragging and continues moving in\n\t// the same direction for some time. Feels especially nice on touch\n\t// devices. Enabled by default.\n\tinertia: true,\n\n\t// @option inertiaDeceleration: Number = 3000\n\t// The rate with which the inertial movement slows down, in pixels/second².\n\tinertiaDeceleration: 3400, // px/s^2\n\n\t// @option inertiaMaxSpeed: Number = Infinity\n\t// Max speed of the inertial movement, in pixels/second.\n\tinertiaMaxSpeed: Infinity, // px/s\n\n\t// @option easeLinearity: Number = 0.2\n\teaseLinearity: 0.2,\n\n\t// TODO refactor, move to CRS\n\t// @option worldCopyJump: Boolean = false\n\t// With this option enabled, the map tracks when you pan to another \"copy\"\n\t// of the world and seamlessly jumps to the original one so that all overlays\n\t// like markers and vector layers are still visible.\n\tworldCopyJump: false,\n\n\t// @option maxBoundsViscosity: Number = 0.0\n\t// If `maxBounds` is set, this option will control how solid the bounds\n\t// are when dragging the map around. The default value of `0.0` allows the\n\t// user to drag outside the bounds at normal speed, higher values will\n\t// slow down map dragging outside bounds, and `1.0` makes the bounds fully\n\t// solid, preventing the user from dragging outside the bounds.\n\tmaxBoundsViscosity: 0.0\n});\n\nexport var Drag = Handler.extend({\n\taddHooks: function () {\n\t\tif (!this._draggable) {\n\t\t\tvar map = this._map;\n\n\t\t\tthis._draggable = new Draggable(map._mapPane, map._container);\n\n\t\t\tthis._draggable.on({\n\t\t\t\tdragstart: this._onDragStart,\n\t\t\t\tdrag: this._onDrag,\n\t\t\t\tdragend: this._onDragEnd\n\t\t\t}, this);\n\n\t\t\tthis._draggable.on('predrag', this._onPreDragLimit, this);\n\t\t\tif (map.options.worldCopyJump) {\n\t\t\t\tthis._draggable.on('predrag', this._onPreDragWrap, this);\n\t\t\t\tmap.on('zoomend', this._onZoomEnd, this);\n\n\t\t\t\tmap.whenReady(this._onZoomEnd, this);\n\t\t\t}\n\t\t}\n\t\tDomUtil.addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');\n\t\tthis._draggable.enable();\n\t\tthis._positions = [];\n\t\tthis._times = [];\n\t},\n\n\tremoveHooks: function () {\n\t\tDomUtil.removeClass(this._map._container, 'leaflet-grab');\n\t\tDomUtil.removeClass(this._map._container, 'leaflet-touch-drag');\n\t\tthis._draggable.disable();\n\t},\n\n\tmoved: function () {\n\t\treturn this._draggable && this._draggable._moved;\n\t},\n\n\tmoving: function () {\n\t\treturn this._draggable && this._draggable._moving;\n\t},\n\n\t_onDragStart: function () {\n\t\tvar map = this._map;\n\n\t\tmap._stop();\n\t\tif (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {\n\t\t\tvar bounds = latLngBounds(this._map.options.maxBounds);\n\n\t\t\tthis._offsetLimit = toBounds(\n\t\t\t\tthis._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),\n\t\t\t\tthis._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)\n\t\t\t\t\t.add(this._map.getSize()));\n\n\t\t\tthis._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));\n\t\t} else {\n\t\t\tthis._offsetLimit = null;\n\t\t}\n\n\t\tmap\n\t\t    .fire('movestart')\n\t\t    .fire('dragstart');\n\n\t\tif (map.options.inertia) {\n\t\t\tthis._positions = [];\n\t\t\tthis._times = [];\n\t\t}\n\t},\n\n\t_onDrag: function (e) {\n\t\tif (this._map.options.inertia) {\n\t\t\tvar time = this._lastTime = +new Date(),\n\t\t\t    pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;\n\n\t\t\tthis._positions.push(pos);\n\t\t\tthis._times.push(time);\n\n\t\t\tthis._prunePositions(time);\n\t\t}\n\n\t\tthis._map\n\t\t    .fire('move', e)\n\t\t    .fire('drag', e);\n\t},\n\n\t_prunePositions: function (time) {\n\t\twhile (this._positions.length > 1 && time - this._times[0] > 50) {\n\t\t\tthis._positions.shift();\n\t\t\tthis._times.shift();\n\t\t}\n\t},\n\n\t_onZoomEnd: function () {\n\t\tvar pxCenter = this._map.getSize().divideBy(2),\n\t\t    pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);\n\n\t\tthis._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;\n\t\tthis._worldWidth = this._map.getPixelWorldBounds().getSize().x;\n\t},\n\n\t_viscousLimit: function (value, threshold) {\n\t\treturn value - (value - threshold) * this._viscosity;\n\t},\n\n\t_onPreDragLimit: function () {\n\t\tif (!this._viscosity || !this._offsetLimit) { return; }\n\n\t\tvar offset = this._draggable._newPos.subtract(this._draggable._startPos);\n\n\t\tvar limit = this._offsetLimit;\n\t\tif (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }\n\t\tif (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }\n\t\tif (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }\n\t\tif (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }\n\n\t\tthis._draggable._newPos = this._draggable._startPos.add(offset);\n\t},\n\n\t_onPreDragWrap: function () {\n\t\t// TODO refactor to be able to adjust map pane position after zoom\n\t\tvar worldWidth = this._worldWidth,\n\t\t    halfWidth = Math.round(worldWidth / 2),\n\t\t    dx = this._initialWorldOffset,\n\t\t    x = this._draggable._newPos.x,\n\t\t    newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,\n\t\t    newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,\n\t\t    newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;\n\n\t\tthis._draggable._absPos = this._draggable._newPos.clone();\n\t\tthis._draggable._newPos.x = newX;\n\t},\n\n\t_onDragEnd: function (e) {\n\t\tvar map = this._map,\n\t\t    options = map.options,\n\n\t\t    noInertia = !options.inertia || e.noInertia || this._times.length < 2;\n\n\t\tmap.fire('dragend', e);\n\n\t\tif (noInertia) {\n\t\t\tmap.fire('moveend');\n\n\t\t} else {\n\t\t\tthis._prunePositions(+new Date());\n\n\t\t\tvar direction = this._lastPos.subtract(this._positions[0]),\n\t\t\t    duration = (this._lastTime - this._times[0]) / 1000,\n\t\t\t    ease = options.easeLinearity,\n\n\t\t\t    speedVector = direction.multiplyBy(ease / duration),\n\t\t\t    speed = speedVector.distanceTo([0, 0]),\n\n\t\t\t    limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),\n\t\t\t    limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),\n\n\t\t\t    decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),\n\t\t\t    offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();\n\n\t\t\tif (!offset.x && !offset.y) {\n\t\t\t\tmap.fire('moveend');\n\n\t\t\t} else {\n\t\t\t\toffset = map._limitOffset(offset, map.options.maxBounds);\n\n\t\t\t\tUtil.requestAnimFrame(function () {\n\t\t\t\t\tmap.panBy(offset, {\n\t\t\t\t\t\tduration: decelerationDuration,\n\t\t\t\t\t\teaseLinearity: ease,\n\t\t\t\t\t\tnoMoveStart: true,\n\t\t\t\t\t\tanimate: true\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n});\n\n// @section Handlers\n// @property dragging: Handler\n// Map dragging handler (by both mouse and touch).\nMap.addInitHook('addHandler', 'dragging', Drag);\n","import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport {on, off, stop} from '../../dom/DomEvent';\nimport {toPoint} from '../../geometry/Point';\n\n\n/*\n * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.\n */\n\n// @namespace Map\n// @section Keyboard Navigation Options\nMap.mergeOptions({\n\t// @option keyboard: Boolean = true\n\t// Makes the map focusable and allows users to navigate the map with keyboard\n\t// arrows and `+`/`-` keys.\n\tkeyboard: true,\n\n\t// @option keyboardPanDelta: Number = 80\n\t// Amount of pixels to pan when pressing an arrow key.\n\tkeyboardPanDelta: 80\n});\n\nexport var Keyboard = Handler.extend({\n\n\tkeyCodes: {\n\t\tleft:    [37],\n\t\tright:   [39],\n\t\tdown:    [40],\n\t\tup:      [38],\n\t\tzoomIn:  [187, 107, 61, 171],\n\t\tzoomOut: [189, 109, 54, 173]\n\t},\n\n\tinitialize: function (map) {\n\t\tthis._map = map;\n\n\t\tthis._setPanDelta(map.options.keyboardPanDelta);\n\t\tthis._setZoomDelta(map.options.zoomDelta);\n\t},\n\n\taddHooks: function () {\n\t\tvar container = this._map._container;\n\n\t\t// make the container focusable by tabbing\n\t\tif (container.tabIndex <= 0) {\n\t\t\tcontainer.tabIndex = '0';\n\t\t}\n\n\t\ton(container, {\n\t\t\tfocus: this._onFocus,\n\t\t\tblur: this._onBlur,\n\t\t\tmousedown: this._onMouseDown\n\t\t}, this);\n\n\t\tthis._map.on({\n\t\t\tfocus: this._addHooks,\n\t\t\tblur: this._removeHooks\n\t\t}, this);\n\t},\n\n\tremoveHooks: function () {\n\t\tthis._removeHooks();\n\n\t\toff(this._map._container, {\n\t\t\tfocus: this._onFocus,\n\t\t\tblur: this._onBlur,\n\t\t\tmousedown: this._onMouseDown\n\t\t}, this);\n\n\t\tthis._map.off({\n\t\t\tfocus: this._addHooks,\n\t\t\tblur: this._removeHooks\n\t\t}, this);\n\t},\n\n\t_onMouseDown: function () {\n\t\tif (this._focused) { return; }\n\n\t\tvar body = document.body,\n\t\t    docEl = document.documentElement,\n\t\t    top = body.scrollTop || docEl.scrollTop,\n\t\t    left = body.scrollLeft || docEl.scrollLeft;\n\n\t\tthis._map._container.focus();\n\n\t\twindow.scrollTo(left, top);\n\t},\n\n\t_onFocus: function () {\n\t\tthis._focused = true;\n\t\tthis._map.fire('focus');\n\t},\n\n\t_onBlur: function () {\n\t\tthis._focused = false;\n\t\tthis._map.fire('blur');\n\t},\n\n\t_setPanDelta: function (panDelta) {\n\t\tvar keys = this._panKeys = {},\n\t\t    codes = this.keyCodes,\n\t\t    i, len;\n\n\t\tfor (i = 0, len = codes.left.length; i < len; i++) {\n\t\t\tkeys[codes.left[i]] = [-1 * panDelta, 0];\n\t\t}\n\t\tfor (i = 0, len = codes.right.length; i < len; i++) {\n\t\t\tkeys[codes.right[i]] = [panDelta, 0];\n\t\t}\n\t\tfor (i = 0, len = codes.down.length; i < len; i++) {\n\t\t\tkeys[codes.down[i]] = [0, panDelta];\n\t\t}\n\t\tfor (i = 0, len = codes.up.length; i < len; i++) {\n\t\t\tkeys[codes.up[i]] = [0, -1 * panDelta];\n\t\t}\n\t},\n\n\t_setZoomDelta: function (zoomDelta) {\n\t\tvar keys = this._zoomKeys = {},\n\t\t    codes = this.keyCodes,\n\t\t    i, len;\n\n\t\tfor (i = 0, len = codes.zoomIn.length; i < len; i++) {\n\t\t\tkeys[codes.zoomIn[i]] = zoomDelta;\n\t\t}\n\t\tfor (i = 0, len = codes.zoomOut.length; i < len; i++) {\n\t\t\tkeys[codes.zoomOut[i]] = -zoomDelta;\n\t\t}\n\t},\n\n\t_addHooks: function () {\n\t\ton(document, 'keydown', this._onKeyDown, this);\n\t},\n\n\t_removeHooks: function () {\n\t\toff(document, 'keydown', this._onKeyDown, this);\n\t},\n\n\t_onKeyDown: function (e) {\n\t\tif (e.altKey || e.ctrlKey || e.metaKey) { return; }\n\n\t\tvar key = e.keyCode,\n\t\t    map = this._map,\n\t\t    offset;\n\n\t\tif (key in this._panKeys) {\n\t\t\tif (!map._panAnim || !map._panAnim._inProgress) {\n\t\t\t\toffset = this._panKeys[key];\n\t\t\t\tif (e.shiftKey) {\n\t\t\t\t\toffset = toPoint(offset).multiplyBy(3);\n\t\t\t\t}\n\n\t\t\t\tif (map.options.maxBounds) {\n\t\t\t\t\toffset = map._limitOffset(toPoint(offset), map.options.maxBounds);\n\t\t\t\t}\n\n\t\t\t\tif (map.options.worldCopyJump) {\n\t\t\t\t\tvar newLatLng = map.wrapLatLng(map.unproject(map.project(map.getCenter()).add(offset)));\n\t\t\t\t\tmap.panTo(newLatLng);\n\t\t\t\t} else {\n\t\t\t\t\tmap.panBy(offset);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (key in this._zoomKeys) {\n\t\t\tmap.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);\n\n\t\t} else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {\n\t\t\tmap.closePopup();\n\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\n\t\tstop(e);\n\t}\n});\n\n// @section Handlers\n// @section Handlers\n// @property keyboard: Handler\n// Keyboard navigation handler.\nMap.addInitHook('addHandler', 'keyboard', Keyboard);\n","import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport * as DomEvent from '../../dom/DomEvent';\nimport * as Util from '../../core/Util';\n\n/*\n * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.\n */\n\n// @namespace Map\n// @section Interaction Options\nMap.mergeOptions({\n\t// @section Mouse wheel options\n\t// @option scrollWheelZoom: Boolean|String = true\n\t// Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,\n\t// it will zoom to the center of the view regardless of where the mouse was.\n\tscrollWheelZoom: true,\n\n\t// @option wheelDebounceTime: Number = 40\n\t// Limits the rate at which a wheel can fire (in milliseconds). By default\n\t// user can't zoom via wheel more often than once per 40 ms.\n\twheelDebounceTime: 40,\n\n\t// @option wheelPxPerZoomLevel: Number = 60\n\t// How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))\n\t// mean a change of one full zoom level. Smaller values will make wheel-zooming\n\t// faster (and vice versa).\n\twheelPxPerZoomLevel: 60\n});\n\nexport var ScrollWheelZoom = Handler.extend({\n\taddHooks: function () {\n\t\tDomEvent.on(this._map._container, 'wheel', this._onWheelScroll, this);\n\n\t\tthis._delta = 0;\n\t},\n\n\tremoveHooks: function () {\n\t\tDomEvent.off(this._map._container, 'wheel', this._onWheelScroll, this);\n\t},\n\n\t_onWheelScroll: function (e) {\n\t\tvar delta = DomEvent.getWheelDelta(e);\n\n\t\tvar debounce = this._map.options.wheelDebounceTime;\n\n\t\tthis._delta += delta;\n\t\tthis._lastMousePos = this._map.mouseEventToContainerPoint(e);\n\n\t\tif (!this._startTime) {\n\t\t\tthis._startTime = +new Date();\n\t\t}\n\n\t\tvar left = Math.max(debounce - (+new Date() - this._startTime), 0);\n\n\t\tclearTimeout(this._timer);\n\t\tthis._timer = setTimeout(Util.bind(this._performZoom, this), left);\n\n\t\tDomEvent.stop(e);\n\t},\n\n\t_performZoom: function () {\n\t\tvar map = this._map,\n\t\t    zoom = map.getZoom(),\n\t\t    snap = this._map.options.zoomSnap || 0;\n\n\t\tmap._stop(); // stop panning and fly animations if any\n\n\t\t// map the delta with a sigmoid function to -4..4 range leaning on -1..1\n\t\tvar d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),\n\t\t    d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,\n\t\t    d4 = snap ? Math.ceil(d3 / snap) * snap : d3,\n\t\t    delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;\n\n\t\tthis._delta = 0;\n\t\tthis._startTime = null;\n\n\t\tif (!delta) { return; }\n\n\t\tif (map.options.scrollWheelZoom === 'center') {\n\t\t\tmap.setZoom(zoom + delta);\n\t\t} else {\n\t\t\tmap.setZoomAround(this._lastMousePos, zoom + delta);\n\t\t}\n\t}\n});\n\n// @section Handlers\n// @property scrollWheelZoom: Handler\n// Scroll wheel zoom handler.\nMap.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);\n","import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport * as DomEvent from '../../dom/DomEvent';\nimport {Point} from '../../geometry/Point';\nimport * as Util from '../../core/Util';\nimport Browser from '../../core/Browser';\n\n/*\n * L.Map.TapHold is used to simulate `contextmenu` event on long hold,\n * which otherwise is not fired by mobile Safari.\n */\n\nvar tapHoldDelay = 600;\n\n// @namespace Map\n// @section Interaction Options\nMap.mergeOptions({\n\t// @section Touch interaction options\n\t// @option tapHold: Boolean\n\t// Enables simulation of `contextmenu` event, default is `true` for mobile Safari.\n\ttapHold: Browser.touchNative && Browser.safari && Browser.mobile,\n\n\t// @option tapTolerance: Number = 15\n\t// The max number of pixels a user can shift his finger during touch\n\t// for it to be considered a valid tap.\n\ttapTolerance: 15\n});\n\nexport var TapHold = Handler.extend({\n\taddHooks: function () {\n\t\tDomEvent.on(this._map._container, 'touchstart', this._onDown, this);\n\t},\n\n\tremoveHooks: function () {\n\t\tDomEvent.off(this._map._container, 'touchstart', this._onDown, this);\n\t},\n\n\t_onDown: function (e) {\n\t\tclearTimeout(this._holdTimeout);\n\t\tif (e.touches.length !== 1) { return; }\n\n\t\tvar first = e.touches[0];\n\t\tthis._startPos = this._newPos = new Point(first.clientX, first.clientY);\n\n\t\tthis._holdTimeout = setTimeout(Util.bind(function () {\n\t\t\tthis._cancel();\n\t\t\tif (!this._isTapValid()) { return; }\n\n\t\t\t// prevent simulated mouse events https://w3c.github.io/touch-events/#mouse-events\n\t\t\tDomEvent.on(document, 'touchend', DomEvent.preventDefault);\n\t\t\tDomEvent.on(document, 'touchend touchcancel', this._cancelClickPrevent);\n\t\t\tthis._simulateEvent('contextmenu', first);\n\t\t}, this), tapHoldDelay);\n\n\t\tDomEvent.on(document, 'touchend touchcancel contextmenu', this._cancel, this);\n\t\tDomEvent.on(document, 'touchmove', this._onMove, this);\n\t},\n\n\t_cancelClickPrevent: function cancelClickPrevent() {\n\t\tDomEvent.off(document, 'touchend', DomEvent.preventDefault);\n\t\tDomEvent.off(document, 'touchend touchcancel', cancelClickPrevent);\n\t},\n\n\t_cancel: function () {\n\t\tclearTimeout(this._holdTimeout);\n\t\tDomEvent.off(document, 'touchend touchcancel contextmenu', this._cancel, this);\n\t\tDomEvent.off(document, 'touchmove', this._onMove, this);\n\t},\n\n\t_onMove: function (e) {\n\t\tvar first = e.touches[0];\n\t\tthis._newPos = new Point(first.clientX, first.clientY);\n\t},\n\n\t_isTapValid: function () {\n\t\treturn this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;\n\t},\n\n\t_simulateEvent: function (type, e) {\n\t\tvar simulatedEvent = new MouseEvent(type, {\n\t\t\tbubbles: true,\n\t\t\tcancelable: true,\n\t\t\tview: window,\n\t\t\t// detail: 1,\n\t\t\tscreenX: e.screenX,\n\t\t\tscreenY: e.screenY,\n\t\t\tclientX: e.clientX,\n\t\t\tclientY: e.clientY,\n\t\t\t// button: 2,\n\t\t\t// buttons: 2\n\t\t});\n\n\t\tsimulatedEvent._simulated = true;\n\n\t\te.target.dispatchEvent(simulatedEvent);\n\t}\n});\n\n// @section Handlers\n// @property tapHold: Handler\n// Long tap handler to simulate `contextmenu` event (useful in mobile Safari).\nMap.addInitHook('addHandler', 'tapHold', TapHold);\n","import {Map} from '../Map';\nimport {Handler} from '../../core/Handler';\nimport * as DomEvent from '../../dom/DomEvent';\nimport * as Util from '../../core/Util';\nimport * as DomUtil from '../../dom/DomUtil';\nimport Browser from '../../core/Browser';\n\n/*\n * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.\n */\n\n// @namespace Map\n// @section Interaction Options\nMap.mergeOptions({\n\t// @section Touch interaction options\n\t// @option touchZoom: Boolean|String = *\n\t// Whether the map can be zoomed by touch-dragging with two fingers. If\n\t// passed `'center'`, it will zoom to the center of the view regardless of\n\t// where the touch events (fingers) were. Enabled for touch-capable web\n\t// browsers.\n\ttouchZoom: Browser.touch,\n\n\t// @option bounceAtZoomLimits: Boolean = true\n\t// Set it to false if you don't want the map to zoom beyond min/max zoom\n\t// and then bounce back when pinch-zooming.\n\tbounceAtZoomLimits: true\n});\n\nexport var TouchZoom = Handler.extend({\n\taddHooks: function () {\n\t\tDomUtil.addClass(this._map._container, 'leaflet-touch-zoom');\n\t\tDomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);\n\t},\n\n\tremoveHooks: function () {\n\t\tDomUtil.removeClass(this._map._container, 'leaflet-touch-zoom');\n\t\tDomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);\n\t},\n\n\t_onTouchStart: function (e) {\n\t\tvar map = this._map;\n\t\tif (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }\n\n\t\tvar p1 = map.mouseEventToContainerPoint(e.touches[0]),\n\t\t    p2 = map.mouseEventToContainerPoint(e.touches[1]);\n\n\t\tthis._centerPoint = map.getSize()._divideBy(2);\n\t\tthis._startLatLng = map.containerPointToLatLng(this._centerPoint);\n\t\tif (map.options.touchZoom !== 'center') {\n\t\t\tthis._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));\n\t\t}\n\n\t\tthis._startDist = p1.distanceTo(p2);\n\t\tthis._startZoom = map.getZoom();\n\n\t\tthis._moved = false;\n\t\tthis._zooming = true;\n\n\t\tmap._stop();\n\n\t\tDomEvent.on(document, 'touchmove', this._onTouchMove, this);\n\t\tDomEvent.on(document, 'touchend touchcancel', this._onTouchEnd, this);\n\n\t\tDomEvent.preventDefault(e);\n\t},\n\n\t_onTouchMove: function (e) {\n\t\tif (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }\n\n\t\tvar map = this._map,\n\t\t    p1 = map.mouseEventToContainerPoint(e.touches[0]),\n\t\t    p2 = map.mouseEventToContainerPoint(e.touches[1]),\n\t\t    scale = p1.distanceTo(p2) / this._startDist;\n\n\t\tthis._zoom = map.getScaleZoom(scale, this._startZoom);\n\n\t\tif (!map.options.bounceAtZoomLimits && (\n\t\t\t(this._zoom < map.getMinZoom() && scale < 1) ||\n\t\t\t(this._zoom > map.getMaxZoom() && scale > 1))) {\n\t\t\tthis._zoom = map._limitZoom(this._zoom);\n\t\t}\n\n\t\tif (map.options.touchZoom === 'center') {\n\t\t\tthis._center = this._startLatLng;\n\t\t\tif (scale === 1) { return; }\n\t\t} else {\n\t\t\t// Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng\n\t\t\tvar delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);\n\t\t\tif (scale === 1 && delta.x === 0 && delta.y === 0) { return; }\n\t\t\tthis._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);\n\t\t}\n\n\t\tif (!this._moved) {\n\t\t\tmap._moveStart(true, false);\n\t\t\tthis._moved = true;\n\t\t}\n\n\t\tUtil.cancelAnimFrame(this._animRequest);\n\n\t\tvar moveFn = Util.bind(map._move, map, this._center, this._zoom, {pinch: true, round: false}, undefined);\n\t\tthis._animRequest = Util.requestAnimFrame(moveFn, this, true);\n\n\t\tDomEvent.preventDefault(e);\n\t},\n\n\t_onTouchEnd: function () {\n\t\tif (!this._moved || !this._zooming) {\n\t\t\tthis._zooming = false;\n\t\t\treturn;\n\t\t}\n\n\t\tthis._zooming = false;\n\t\tUtil.cancelAnimFrame(this._animRequest);\n\n\t\tDomEvent.off(document, 'touchmove', this._onTouchMove, this);\n\t\tDomEvent.off(document, 'touchend touchcancel', this._onTouchEnd, this);\n\n\t\t// Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.\n\t\tif (this._map.options.zoomAnimation) {\n\t\t\tthis._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);\n\t\t} else {\n\t\t\tthis._map._resetView(this._center, this._map._limitZoom(this._zoom));\n\t\t}\n\t}\n});\n\n// @section Handlers\n// @property touchZoom: Handler\n// Touch zoom handler.\nMap.addInitHook('addHandler', 'touchZoom', TouchZoom);\n","import {Map} from './Map';\nimport {BoxZoom} from './handler/Map.BoxZoom';\nMap.BoxZoom = BoxZoom;\nimport {DoubleClickZoom} from './handler/Map.DoubleClickZoom';\nMap.DoubleClickZoom = DoubleClickZoom;\nimport {Drag} from './handler/Map.Drag';\nMap.Drag = Drag;\nimport {Keyboard} from './handler/Map.Keyboard';\nMap.Keyboard = Keyboard;\nimport {ScrollWheelZoom} from './handler/Map.ScrollWheelZoom';\nMap.ScrollWheelZoom = ScrollWheelZoom;\nimport {TapHold} from './handler/Map.TapHold';\nMap.TapHold = TapHold;\nimport {TouchZoom} from './handler/Map.TouchZoom';\nMap.TouchZoom = TouchZoom;\n\nexport {Map, createMap as map} from './Map';\n","//We implement the backend version of getWHDebugFlags so bridge can access us without going through a recursive dep\n\nimport type { DTAPStage } from \"./concepts\";\n\n/// List global polyfills currently active. This may be needed to align TypeScript hosts configuration\nexport const globalPolyfills: string[] = [];\n\n/// An object with string keys and typed values\nexport interface WellKnownFlags {\n  /** Log RPcs */\n  rpc?: boolean;\n  /** Log web traffic */\n  wrq?: boolean;\n  /** Autoprofile */\n  apr?: boolean;\n  /** IPC */\n  ipc?: boolean;\n  /** async */\n  async?: boolean;\n}\nexport type DebugFlags = WellKnownFlags & { [key: string]: boolean | undefined };\n\nexport type DebugConfig = {\n  tags: readonly string[];\n  outputsession: string;\n  context: string;\n};\n\n/// Empty or no parameter lang is get, otherwise it's a set\nexport type GetSetAssetBase = (assetBase?: string | null) => string | null;\n\nexport type EnvHooks = {\n  currentAssetBase: GetSetAssetBase;\n};\n\n\nconst settingschangedcallbacks = new Array<() => void>;\n\n/* Global debug flags are set by `wh debug`, local flags are prefilled by environment variables.\n   Edits to the debug flags will be applied to the local flags (unless setDebugFlagsOverrideCB returns\n   override records).\n*/\nconst globalDebugFlags: DebugFlags = {}, localDebugFlags: DebugFlags = {};\n\n/** Returns the flag override records. The first record is examined first, then the second, etc. */\nlet debugFlagsOverridesCB: undefined | (() => DebugFlags[]);\n\n/** Override the debug flag override getter. */\nexport function setDebugFlagsOverrideCB(cb: undefined | (() => DebugFlags[])) {\n  debugFlagsOverridesCB = cb;\n}\n\n/* Proxy handler for the published debug flags. Uses the override records (with the first record\n   examined first, then the second, etc.) to override the flags from baseDebugFlags. Setting to `true` sets\n   the flag, `false` disables it and setting to `undefined` has the same effect as deleting the property in the\n   current top record (exposing any value from a lower record, like the debug settings from `wh debug`).\n*/\nclass DebugFlagsProxyHandler implements ProxyHandler<DebugFlags> {\n  private getRecordList(): DebugFlags[] {\n    return [...debugFlagsOverridesCB?.() ?? [], localDebugFlags, globalDebugFlags];\n  }\n\n  get(target: DebugFlags, p: string) {\n    for (const record of this.getRecordList())\n      if (p in record && typeof record[p] !== \"undefined\")\n        return record[p];\n    return undefined;\n  }\n  has(target: DebugFlags, p: string): boolean {\n    return this.get(target, p) !== undefined;\n  }\n  ownKeys(target: DebugFlags): Array<string | symbol> {\n    const keys = new Array<string | symbol>;\n    for (const record of this.getRecordList())\n      for (const key of Reflect.ownKeys(record))\n        if (typeof key === \"string\" && record[key] !== undefined && !keys.includes(key))\n          keys.push(key);\n    return keys;\n  }\n  set(target: DebugFlags, p: string, newValue: boolean | undefined): boolean {\n    const toModify = this.getRecordList()[0];\n    if (typeof newValue === \"boolean\")\n      toModify[p] = newValue;\n    else\n      delete toModify[p];\n\n    runSettingsCallbacks();\n    return true;\n  }\n  deleteProperty(target: DebugFlags, p: string): boolean {\n    const toModify = this.getRecordList()[0];\n    delete toModify[p];\n\n    runSettingsCallbacks();\n    return true;\n  }\n  getOwnPropertyDescriptor(target: DebugFlags, p: string): PropertyDescriptor | undefined {\n    const value = this.get(target, p);\n    return value !== undefined ? { enumerable: true, value, configurable: true } : undefined;\n  }\n}\n\nexport const debugFlags = new Proxy<DebugFlags>({\n  [Symbol.for('nodejs.util.inspect.custom')]: formatForConsoleLogs\n}, new DebugFlagsProxyHandler());\n\nfunction formatForConsoleLogs() {\n  return `DebugFlags [${[...Object.keys(debugFlags)].filter(key => debugFlags[key]).join(\", \")}]`;\n}\n\nfunction runSettingsCallbacks() {\n  for (const cb of [...settingschangedcallbacks]) {\n    try {\n      cb();\n    } catch (e) {\n      console.error(\"Error invoking settings change callback\", cb?.name, e);\n      //ignore, debugFlags can change due to external updates so they're basically signal handlers and there's no real point in crashing whatever was really running\n    }\n  }\n}\n\n/** Update the debugconfig as present in the system configuration record\n    @param settings - debugconfig cell of the system configuration record\n*/\nexport function updateDebugConfig(settings: DebugConfig | null) {\n  const oldenabledflags = Object.keys(globalDebugFlags).sort();\n  const newenabledflags = settings?.tags ? [...settings.tags].sort() : [];\n\n  if (oldenabledflags.join(\",\") !== newenabledflags.join(\",\")) {\n    for (const flag of newenabledflags)\n      globalDebugFlags[flag] = true;\n    for (const flag of oldenabledflags)\n      if (!newenabledflags.includes(flag))\n        delete globalDebugFlags[flag];\n\n    runSettingsCallbacks();\n  }\n  if (debugFlags.async && Error.stackTraceLimit < 100)\n    Error.stackTraceLimit = 100;\n}\n\nexport function registerDebugConfigChangedCallback(cb: () => void) {\n  settingschangedcallbacks.push(cb);\n}\n\nexport function updateLocalDebugFlags(mode: \"enable\" | \"disable\" | \"clear\", flags: string[]): DebugFlags {\n  switch (mode) {\n    case \"enable\":\n    case \"disable\":\n      for (const flag of flags)\n        localDebugFlags[flag] = mode === \"enable\";\n      break;\n    case \"clear\":\n      for (const flag of Object.keys(localDebugFlags))\n        delete localDebugFlags[flag];\n  }\n  runSettingsCallbacks();\n  return { ...globalDebugFlags, ...localDebugFlags };\n}\n\n/** DTAP stage set for this WebHare */\nlet dtapStage: DTAPStage = \"production\";\n\n/** @deprecated We now recommend checking dtapStage against production/acceptance Explicitly */\nlet isLive: boolean = dtapStage === \"production\" || dtapStage === \"acceptance\";\n\n/** The backend base URL. Used for eg. autoconfiguring JSON/RPC */\nlet backendBase = \"\";\n\n/** The global assetbase */\nlet assetBase: string | null = null;\n\n//deprecated variants\n/** @deprecated For WH5.4 and up use 'dtapStage' */\nlet dtapstage: DTAPStage = dtapStage;\n/** @deprecated For WH5.4 and up compare 'dtapStage' for production or acceptance */\nlet islive: boolean = isLive;\n\nlet hooks: EnvHooks | undefined;\nlet hookFactory: (() => EnvHooks) | undefined;\nlet gotHooks = false;\n\nexport function initEnv(setDtapStage: DTAPStage, setBackendBase: string) {\n  dtapStage = setDtapStage;\n  isLive = dtapStage === \"production\" || dtapStage === \"acceptance\";\n  backendBase = setBackendBase;\n\n  dtapstage = dtapStage;\n  islive = isLive;\n}\n\nexport function setEnvHooksFactory(newHookFactory: () => EnvHooks) {\n  if (gotHooks)\n    throw new Error(`The call to setEnvHooksFactory was too late - hooks have already been retrieved once`);\n  hookFactory = newHookFactory;\n}\n\nexport function getEnvHooks() {\n  gotHooks = true;\n  return hookFactory?.();\n}\n\nfunction ensureHooks(): EnvHooks {\n  return hooks ??= getEnvHooks?.() ?? {\n    currentAssetBase: (newAssetBase) => {\n      if (newAssetBase !== undefined)\n        assetBase = newAssetBase;\n      return assetBase;\n    }\n  };\n}\n\n/** Get the base url for assets. This may point towards eg. a CDN\n * @returns The base url for assets, ending with a '/'. null if not set\n */\nexport function getAssetBase(): string | null {\n  return ensureHooks().currentAssetBase();\n}\n\n/** Get the base url for a module's public assets (those located in the module's `public` folder)\n */\nexport function getModulePublicAssetBase(module: string) {\n  return `${getAssetBase() || \"/\"}.wh/mod/${encodeURIComponent(module)}/public/`;\n}\n\n/** Set the base url for assets */\nexport function setAssetBase(base: string | null): void {\n  if (base && !base.endsWith(\"/\"))\n    throw new Error(`Asset base must end with a '/'`);\n\n  ensureHooks().currentAssetBase(base);\n}\n\nexport { dtapStage, isLive, backendBase, localDebugFlags };\nexport { dtapstage, islive }; //deprecated variants\n","\n//Note that @webhare/env does not invoke this API itself. In WebHare @webhare/frontend/src/init uses this to initialize\nexport function getBrowserDebugFlags(varname: string): string[] {\n  const flags = [];\n  const urldebugvar = new URL(location.href).searchParams.get(varname);\n  if (urldebugvar)\n    flags.push(...urldebugvar.split(','));\n\n  //not importing getCookie to solve some import ordering issues\n  if (typeof document !== \"undefined\") { //'document' is undefined in a worker but assetpacks compiled for a ServiceWorker will also load us\n    const debugcookie = document.cookie.match(`(?:^|;)\\\\s*${varname}=([^;]*)`); //TODO escape varname\n    if (debugcookie) {\n      const debugcookievalue = decodeURIComponent(debugcookie[1]);\n      if (debugcookievalue)\n        flags.push(... (debugcookievalue.split('.').filter(flag => !flag.startsWith('sig='))));\n    }\n  }\n\n  if (typeof sessionStorage !== \"undefined\") {\n    const sessionDebug = sessionStorage.getItem(varname);\n    if (sessionDebug)\n      flags.push(...sessionDebug.split(','));\n  }\n\n  return flags;\n}\n","/** Rect describing an elements position */\nexport type Rect = {\n  top: number;\n  bottom: number;\n  left: number;\n  right: number;\n  width: number;\n  height: number;\n};\n\n/** Elements you can set a value on and would have to trigger change and/or input events */\nexport type FormControlElement = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;\n\n/** Types that support querySelector(All) */\ntype QuerySelectorAble = ParentNode | ShadowRoot;\n\nexport function qS<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E | null;\nexport function qS<E extends Element = HTMLElement>(selector: string): E | null;\n\n/** Match the first element using a CSS selector\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The first matching element or null\n */\nexport function qS<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E | null {\n  if (typeof node_or_selector === 'string')\n    return document.querySelector<E>(node_or_selector);\n  else if (selector)\n    return node_or_selector.querySelector<E>(selector);\n  return null;\n}\n\n\nexport function qR<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E;\nexport function qR<E extends Element = HTMLElement>(selector: string): E;\n\n/** Match a specific element using a CSS selector, requiring it to exist and be unique\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The requested element. Throw it the selector doesn't match exactly one element\n */\nexport function qR<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E {\n  const matches = qSA<E>(node_or_selector as QuerySelectorAble, selector as string);\n  if (matches.length === 1)\n    return matches[0];\n\n  if (typeof node_or_selector !== 'string') {\n    console.error(`${matches.length} elements match selector \\`${selector}\\` with startingpoint`, node_or_selector, matches);\n    throw new Error(`${matches.length} elements match selector \\`${selector}\\` given startingpoint '${node_or_selector.nodeName}'`);\n  } else {\n    console.error(`${matches.length} elements match selector \\`${node_or_selector}\\` in the document`, matches);\n    throw new Error(`${matches.length} elements match selector \\`${node_or_selector}\\` in the document`);\n  }\n}\n\nexport function qSA<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E[];\nexport function qSA<E extends Element = HTMLElement>(selector: string): E[];\n\n/** Find multiple elements using a CSS selector\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The requested elements.\n */\nexport function qSA<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E[] {\n  if (typeof node_or_selector === 'string')\n    return Array.from(document.querySelectorAll(node_or_selector));\n  else if (selector)\n    return Array.from(node_or_selector.querySelectorAll(selector));\n\n  return [];\n}\n\n/** Return whether the passed element is a FormControlElement */\nexport function isFormControl(field: Element): field is FormControlElement {\n  return isHTMLElement(field) && [\"INPUT\", \"SELECT\", \"TEXTAREA\"].includes(field.tagName);\n}\n\n/** Return whether the passed element is an editable text field */\nexport function isEditControl(field: Element): field is HTMLElement {\n  return isHTMLElement(field) && ([\"INPUT\", \"TEXTAREA\"].includes(field.tagName) || field.isContentEditable);\n}\n\n/** Test whether node is an Element, even if it's in a different iframe */\nexport function isElement(node: unknown): node is Element {\n  //TODO What is actually going on if defaultView is missing?\n  if (!node || typeof node !== \"object\")\n    return false;\n\n  /* Getting the proto doesn't always work:\n  const proto = (node as Element).ownerDocument.defaultView?.Element;\n  (because our iframes derive off about? not sure) so until someone finds the real answer, we'll do a heuristic\n  */\n\n  /** Analyzing node.constructor.name doesn't work because custom elements don't necessarily have their constructor's name ending in Element\n  return Boolean(\"ownerDocument\" in node && node.constructor.name.match(/Element$/));\n  */\n\n  return Boolean(\"ownerDocument\" in node && (node as Element).nodeType === 1);\n\n}\n\n/** Test whether node is a HTMLElement, even if it's in a different iframe */\nexport function isHTMLElement(node: unknown): node is HTMLElement {\n  return isElement(node) && node.namespaceURI === \"http://www.w3.org/1999/xhtml\";\n}\n\n/** Test whether node is a SVGElement, even if it's in a different iframe */\nexport function isSVGElement(node: unknown): node is SVGElement {\n  return isElement(node) && node.namespaceURI === \"http://www.w3.org/2000/svg\";\n}\n\n/**\n * get the relative bound difference between two elements, and return a writable copy\n *\n * @param node - The node for which you need coordinates\n * @param relativeto - Optional reference point. If not set, you just get a 'normal' coordinate object\n */\nexport function getRelativeBounds(node: Element, relativeto?: Element): Rect {\n  if (!relativeto)\n    relativeto = node.ownerDocument.documentElement;\n\n  const nodecoords = node.getBoundingClientRect();\n  const relcoords = relativeto.getBoundingClientRect();\n  return {\n    top: nodecoords.top - relcoords.top,\n    left: nodecoords.left - relcoords.left,\n    right: nodecoords.right - relcoords.left,\n    bottom: nodecoords.bottom - relcoords.top,\n    width: nodecoords.width,\n    height: nodecoords.height\n  };\n}\n\nexport type ParsedLanguageTag = {\n  /** The full tag, eg en-US */\n  tag: string;\n  /** The language code, eg 'en' */\n  language: string;\n  region?: string;\n  /** The script, eg 'Hant' */\n  script?: string;\n};\n\n/** Parse a BCP47 language tag */\nexport function parseLanguageTag(languageTag: string): ParsedLanguageTag {\n  /* https://datatracker.ietf.org/doc/html/rfc5646#section-2.1\n     langtag       = language\n                 [\"-\" script]\n                 [\"-\" region]\n                 *(\"-\" variant)\n                 *(\"-\" extension)\n                 [\"-\" privateuse]\n     BUT: we're limiting ourselves to language, script and region for now\n\n     language      = 2*3ALPHA           ; shortest ISO 639 code\n                    [\"-\" extlang]       ; sometimes followed by\n                                          extended language subtags\n\n                                           extlang       = 3ALPHA              ; selected ISO 639 codes\n                 *2(\"-\" 3ALPHA)      ; permanently reserved\n\n      script        = 4ALPHA              ; ISO 15924 code\n\n      region        = 2ALPHA              ; ISO 3166-1 code\n                    / 3DIGIT              ; UN M.49 code\n\n     Note that we're not yet fully implementing the spec, just the parts we expect to encounter in practice\n  */\n  const match = languageTag.match(/^([a-z]{2,}(-[a-z]{3})?)(-[A-Za-z]{4,})?(-[A-Z]{2}|-\\d{3})?$/);\n  if (!match)\n    throw new Error(`Invalid language tag: ${languageTag}`);\n\n  return {\n    tag: languageTag,\n    language: match[1],\n    ...(match[3] ? { script: match[3].substring(1) } : {}),\n    ...(match[4] ? { region: match[4].substring(1) } : {})\n  };\n}\n\n/** Get the effective language for an element (or the document)\n * @param node - The element for which to get the effective language. If not specified, the documentElement and finally the browser is used\n * @returns The language code, eg. \"nl\" or \"en-GB\"\n */\nexport function getLang(node?: Element): ParsedLanguageTag {\n  if (!node && typeof document !== \"undefined\")\n    node = document.documentElement;\n  const tag = (node?.closest('[lang]')?.getAttribute(\"lang\") || navigator.language || \"en\");\n  return parseLanguageTag(tag);\n}\n","//TODO can we replace ourselves with nodejs util.types in a pure NodeJS environment?\n\nimport type { Money } from \"./money.ts\";\n\nexport function getWHType(obj: unknown): string | null { //not exporting this directly as we hope JS comes up with better solutions for instanceOf not being compatible with realms/reloading\n  // Ideally we'd use symbol but it breaks tree shaking in esbuild, so this is our workaround. Reported as https://github.com/evanw/esbuild/issues/3940\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Can't cleanly type this it seems and it's low level anyway\n  return (obj as any)?.constructor?.[\"__ $whTypeSymbol\"] ?? null;\n}\n\nfunction isCrossRealm(value: unknown): value is object {\n  return Boolean(value // it's not null\n    && typeof value === \"object\" //and it's an object\n    && !(value instanceof Object)); //and it's not an instance of our Object\n}\n\n/** Test whether a value looks like an instance of Money */\nexport function isMoney(value: unknown): value is Money {\n  return getWHType(value) === \"Money\";\n}\n\n/** Test whether a value looks like an instance of Temporal.Instant */\nexport function isTemporalInstant(value: unknown): value is Temporal.Instant {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.Instant');\n}\n\n/** Test whether a value looks like an instance of Temporal.PlainDateTime */\nexport function isTemporalPlainDateTime(value: unknown): value is Temporal.PlainDateTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainDateTime');\n}\n\n/** Test whether a value looks like an instance of Temporal.PlainDate */\nexport function isTemporalPlainDate(value: unknown): value is Temporal.PlainDate {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainDate');\n}\n\n/** Test whether a value looks like an instance of Temporal.PlainTime */\nexport function isTemporalPlainTime(value: unknown): value is Temporal.PlainTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainTime');\n}\n\n/** Test whether a value looks like an instance of Temporal.ZonedDateTime */\nexport function isTemporalZonedDateTime(value: unknown): value is Temporal.ZonedDateTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.ZonedDateTime');\n}\n\n/** Test whether a value looks like an instance of Date (assumes no subclasses) */\nexport function isDate(value: unknown): value is Date {\n  return value instanceof Date || (isCrossRealm(value) && value.constructor.name === \"Date\");\n}\n\n/** Test whether a value appears to implement the Blob interface */\nexport function isBlob(value: unknown): value is Blob {\n  return value instanceof Blob || Boolean(value && typeof value === \"object\" && \"size\" in value && \"type\" in value && \"slice\" in value && typeof value.slice === \"function\" && \"stream\" in value && typeof value.stream === \"function\");\n}\n\n/** Test whether a value appears to implement the File interface */\nexport function isFile(value: unknown): value is File {\n  return isBlob(value) && \"name\" in value;\n}\n\n/** Check if the object is probably an Error object. Can't use 'instanceof Error' as an Error might come from a different frame */\nexport function isError(e: unknown): e is Error {\n  return e instanceof Error || (isCrossRealm(e) && \"name\" in e && \"stack\" in e && \"message\" in e);\n}\n\n/** Check if the object looks like a promise */\nexport function isPromise<T>(e: T | Promise<T>): e is Promise<Awaited<T>> {\n  return Boolean(e && typeof (e as Promise<unknown>).then === \"function\" && typeof (e as Promise<unknown>).catch === \"function\");\n}\n\n/** Check the type of a value, return its JS or STD type\n * @param value - The value to check\n * @returns The type of the value. If the value is an object but recognized as any of Money, Date, Blob, Temporal.Instant/PlainDate/PlainDateTime, that type is returned.\n */\nexport function stdTypeOf(value: unknown): \"string\" | \"number\" | \"boolean\" | \"null\" | \"symbol\" | \"bigint\" | \"function\" | \"object\" | \"undefined\" | \"Date\" | \"Money\" | \"Array\" | \"Instant\" | \"PlainDate\" | \"PlainDateTime\" | \"PlainTime\" | \"ZonedDateTime\" | \"File\" | \"Blob\" {\n  const t = typeof value;\n  if (t === \"object\") {\n    if (!value)\n      return \"null\";\n    if (Array.isArray(value))\n      return \"Array\";\n    if (isMoney(value))\n      return \"Money\";\n    if (isBlob(value))\n      return isFile(value) ? \"File\" : \"Blob\";\n    if (isDate(value))\n      return \"Date\";\n    if (isTemporalInstant(value))\n      return \"Instant\";\n    if (isTemporalPlainTime(value))\n      return \"PlainTime\";\n    if (isTemporalPlainDate(value))\n      return \"PlainDate\";\n    if (isTemporalPlainDateTime(value))\n      return \"PlainDateTime\";\n    if (isTemporalZonedDateTime(value))\n      return \"ZonedDateTime\";\n  }\n  return t;\n}\n","/* A math library for safe calculation with money amounts in JS. If you don't\n   know why we need this, try to predict what the following code would print:\n   var cents=0;for(var i=0;i<100;++i)cents+=0.01;cents-=1;console.log(cents);\n   and think twice about whether you want to code anything financial in JS.\n\n   Money values supplied from HareScript should be formatted using FormatJSFinmathMoney\n*/\n\nexport type FinmathInput = string | number;\n\nexport type RoundMode = \"none\" | \"toward-zero\" | \"down\" | \"up\" | \"half-toward-zero\" | \"half-down\" | \"half-up\" | \"toward-infinity\" | \"half-toward-infinity\";\n\nexport interface SplitNumber {\n  num: number;\n  decimals: number;\n}\n\n//a 'price' is a string of the form \"nnn[.NNNN]\"\n\nfunction stripUnneededDecimals(num: number, decimals: number) {\n  //we have a maximum of 5 digits of external precision\n  if (decimals > 5) {\n    // math.round rounds toward positive infinity\n    const isneg = num < 0;\n    if (isneg)\n      num = -num;\n\n    while (decimals > 6) { //truncate excess digits\n      num = Math.floor(num / 10);\n      --decimals;\n    }\n    //round up if 6th decimal >= 5\n    num = Math.round(num / 10);\n    decimals = 5;\n\n    if (isneg)\n      num = -num;\n  }\n\n  //strip unneeded decimals\n  while (decimals > 0 && !(num % 10)) {\n    num /= 10;\n    --decimals;\n  }\n\n  return { num, decimals };\n}\n\nfunction toText(amount: SplitNumber, decimalpoint: string, mindecimals: number) {\n  if (!Number.isSafeInteger(amount.num))\n    throw new Error(\"Result would overflow the safe value range\");\n\n  let num, decimals;\n  ({ num, decimals } = stripUnneededDecimals(amount.num, amount.decimals));\n\n  // Strip sign from number, may need to prefix it\n  const isnegative = num < 0;\n  if (isnegative)\n    num = -num;\n\n  let astext = String(num);\n\n  // Ensure we have enough leading 0's to render the first integer digit\n  if (astext.length <= decimals)\n    astext = '00000000000000000000'.substr(0, decimals + 1 - astext.length) + astext;\n  // make sure we have enough 0's to show mindecimals\n  if (decimals < mindecimals) {\n    astext += '00000000000000000000'.substr(0, mindecimals - decimals);\n    decimals = mindecimals;\n  }\n\n  // insert decimal point if needed\n  if (decimals)\n    astext = astext.substr(0, astext.length - decimals) + decimalpoint + astext.substr(-decimals);\n\n  // add sign if needed\n  astext = (isnegative ? \"-\" : \"\") + astext;\n  return astext;\n}\n\n/** Convert a money of any format to a split number object\n    @param money - Either an integer number or string with a number\n    @returns Split number object\n*/\nfunction splitValue(money: FinmathInput): SplitNumber {\n  if (typeof money === 'number') {\n    if (money !== Math.floor(money))\n      throw new Error(\"Non-integer number passed\");\n    if (!Number.isSafeInteger(money))\n      throw new Error(`The value ${money} is outside the safe value range`);\n    return { num: money, decimals: 0 };\n  }\n  if (typeof money !== 'string')\n    throw new Error(\"Number or string expected, got \" + money);\n\n  const split = money.match(/^(-)?([0-9]*)(\\.([0-9]{0,5})([0-9]*))?$/);\n  if (!split)\n    throw new Error(`Illegal money value received: '${money}'`);\n\n  const sign = split[1] === '-' ? -1 : 1;\n  const decimals = split[3] ? split[4].length : 0;\n  // If there are more than 5 decimals, round up (using halfExpand strategy)\n  const num = sign * (parseInt(split[2] || \"0\") * Math.pow(10, decimals) + (parseInt((split[4] || '')) || 0) + (split[5]?.[0] >= '5' ? 1 : 0));\n  if (!Number.isSafeInteger(num))\n    throw new Error(`The value '${money}' is outside the safe value range`);\n\n  return stripUnneededDecimals(num, decimals);\n}\n\n/** Convert split number into a string\n*/\nfunction joinPrice(parts: SplitNumber): string {\n  return toText(parts, '.', 0);\n}\n\nfunction adjustDecimals(amount: SplitNumber, requiredecimals: number) {\n  const toadd = requiredecimals - amount.decimals;\n  if (toadd <= 0)\n    return;\n\n  let multiplier = 1;\n  for (let idx = 0; idx < toadd; ++idx)\n    multiplier *= 10;\n\n  if (!Number.isSafeInteger(amount.num * multiplier))\n    throw new Error(\"adjustDecimals would overflow the safe value range\");\n\n  amount.num *= multiplier;\n  amount.decimals += toadd;\n}\n\n/** Returns if a price string is valid\n*/\nexport function isValidPrice(money: string) {\n  if (typeof money !== 'string' || !money.match(/[0-9]+(\\.[0-9]{0,5})?$/))\n    return false;\n  return true;\n}\n\nfunction __add(lhs: SplitNumber, rhs: SplitNumber) {\n  //equalize # of decimals, and then it's a simple addition\n  const requiredecimals = Math.max(lhs.decimals, rhs.decimals);\n  adjustDecimals(lhs, requiredecimals);\n  adjustDecimals(rhs, requiredecimals);\n  return { num: lhs.num + rhs.num, decimals: requiredecimals };\n}\n\n/** Adds two numbers together\n*/\nexport function add(amount1: FinmathInput, amount2: FinmathInput): string {\n  return joinPrice(__add(splitValue(amount1), splitValue(amount2)));\n}\n\n/** Subtracts a number from another number\n*/\nexport function subtract(amount: FinmathInput, tosubtract: FinmathInput) {\n  const lhs = splitValue(amount), rhs = splitValue(tosubtract);\n  rhs.num = -rhs.num;\n  return joinPrice(__add(lhs, rhs));\n}\n\nfunction __multiply(lhs: SplitNumber, rhs: SplitNumber) {\n  //ADDME the naive 'add decimals, multiple nums' approach gets you out of the safe range real fast. needs tests\n  return { num: lhs.num * rhs.num, decimals: lhs.decimals + rhs.decimals };\n}\n\n/** Multiplies two numbers together\n*/\nexport function multiply(amount1: FinmathInput, amount2: FinmathInput): string {\n  const lhs = splitValue(amount1), rhs = splitValue(amount2);\n  return joinPrice(__multiply(lhs, rhs));\n}\n\n/** Compares two numbers\n    @param amount1 - Left hand value\n    @param amount2 - Right hand value\n    @returns Returns 0 if amount1 === amount2, -1 if amount1 \\< amount2, 1 if amount1 \\> amount2\n*/\nexport function cmp(amount1: FinmathInput, amount2: FinmathInput) {\n  const diff = __add(splitValue(amount1), __multiply(splitValue(amount2), { num: -1, decimals: 0 }));\n  return diff.num < 0 ? -1 : diff.num === 0 ? 0 : 1;\n}\n\n/** Returns a percentage of an amount\n    @param amount - Original amount\n    @param perc - Percentage of the amount to return\n    @returns Percentage of the amount\n*/\nexport function getPercentageOfAmount(amount: FinmathInput, perc: FinmathInput) {\n  const lhs = splitValue(amount), rhs = splitValue(perc);\n  const result = __multiply(lhs, rhs);\n  result.decimals += 2;\n  return joinPrice(normalize(result));\n}\n\nfunction normalize(amount: SplitNumber) {\n  while (amount.decimals && (amount.num % 10) === 0) {\n    amount.num /= 10;\n    --amount.decimals;\n  }\n  return amount;\n}\n\n/// format a price amount. extend # of decimals to specified # if not enough\nexport function formatPrice(money: FinmathInput, decimalpoint: string, decimals: number) {\n  return toText(splitValue(money), decimalpoint, decimals);\n}\n\n/** Rounds integer to multiple, exposed for testing only\n*/\nexport function __roundIntegerToMultiple(value: number, roundunit: number, mode: RoundMode) {\n  switch (mode) {\n    case \"none\":\n      {\n        // no rounding\n      } break;\n    case \"toward-zero\":\n      {\n        value = Math.trunc(value / roundunit) * roundunit;\n      } break;\n    case \"toward-infinity\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit - 1) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit + 1) / roundunit) * roundunit;\n      } break;\n    case \"down\":\n      {\n        if (value > 0)\n          value = Math.trunc(value / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit + 1) / roundunit) * roundunit;\n      } break;\n    case \"up\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit - 1) / roundunit) * roundunit;\n        else\n          value = Math.trunc(value / roundunit) * roundunit;\n      } break;\n    case \"half-toward-zero\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + (roundunit - 1) / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - (roundunit - 1) / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-toward-infinity\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-down\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + (roundunit - 1) / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-up\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - (roundunit - 1) / 2) / roundunit) * roundunit;\n      } break;\n    default:\n      {\n        throw new Error(`Unknown rounding mode ${mode}`);\n      }\n  }\n  return value;\n}\n\n/** Rounds a value to a multiple of a unit, with a specific rounding mode\n    @param value - Value to round\n    @param unit - The value will be rounded to a mulitple of this unit (except when rounding mode is 'none')\n    @param mode - Rounding mode. Possible values:\n      <ul>\n        <li>none: No rounding</li>\n        <li>toward-zero: Round toward zero</li>\n        <li>down: Round toward negative infity</li>\n        <li>up: Round toward positive infity</li>\n        <li>half-toward-zero: Round nearest multiple, round half of a multiple toward zero</li>\n        <li>half-down: Round nearest multiple, round half of a multiple toward negative infinity</li>\n        <li>half-up: Round nearest multiple, round half of a multiple toward positive infity</li>\n      </ul>\n    @returns The rounded value\n*/\nexport function roundToMultiple(value: FinmathInput, unit: FinmathInput, mode: RoundMode) {\n  const split_value = splitValue(value);\n  const split_unit = splitValue(unit);\n\n  const requiredecimals = Math.max(split_value.decimals, split_unit.decimals);\n  adjustDecimals(split_value, requiredecimals);\n  adjustDecimals(split_unit, requiredecimals);\n\n  const result = { num: __roundIntegerToMultiple(split_value.num, split_unit.num, mode), decimals: split_value.decimals };\n  return joinPrice(result);\n}\n\n/** Returns the minimum of all the arguments\n    @param amount - First value\n    @param amounts - Rest of the values\n    @returns The lowest value among amount and amounts\n*/\nexport function min(amount: FinmathInput, ...amounts: FinmathInput[]) {\n  for (const val of amounts)\n    if (cmp(amount, val) > 0)\n      amount = val;\n  return joinPrice(splitValue(amount));\n}\n\n/** Returns the maximum of all the arguments\n    @param amount - First value\n    @param amounts - Rest of the values\n    @returns The highest value among amount and amounts\n*/\nexport function max(amount: FinmathInput, ...amounts: FinmathInput[]) {\n  for (const val of amounts)\n    if (cmp(amount, val) < 0)\n      amount = val;\n  return joinPrice(splitValue(amount));\n}\n\n/** Returns a power of 10\n    @param exp - Integer power, must be 0 or bigger\n    @returns Requested power of 10\n*/\nfunction getNonNegativePowerOf10(exp: number) {\n  let retval = 1, running_exp = 10;\n  while (exp) {\n    if (exp & 1)\n      retval *= running_exp;\n    running_exp *= running_exp;\n    exp = exp >> 1;\n  }\n  return retval;\n}\n\n/** Divides two values, with 5 decimals of precision\n    @param value - Value To divide\n    @param divisor - Divisor\n    @returns Divided value, with 5 decimals of precision\n*/\nexport function divide(value: FinmathInput, divisor: FinmathInput) {\n  const lhs = splitValue(value), rhs = splitValue(divisor);\n  const mul10exp = lhs.decimals - rhs.decimals - 5;\n  const mulfactor = mul10exp < 0 ? getNonNegativePowerOf10(-mul10exp) : 1;\n  const roundunit = mul10exp > 0 ? getNonNegativePowerOf10(mul10exp) : 1;\n  return joinPrice({ num: __roundIntegerToMultiple(mulfactor * lhs.num / rhs.num, roundunit, \"half-toward-infinity\"), decimals: 5 });\n}\n\nexport function moneyDivide(value: FinmathInput, divisor: FinmathInput) { //divide was added in 5.0. remove this old name eventually\n  return divide(value, divisor);\n}\n\n/** Test whether two values have a specific relation\n    @param lhs - Left hand value\n    @param relation - One of '\\<', '\\<=', '==', '!=', '\\>', '\\>=''\n    @param rhs - Right hand value\n    @returns TRUE if the relation holds\n    @example\n      console.log(finmath.test(1, '\\<', 2)); // prints 'true'\n*/\nexport function test(lhs: FinmathInput, relation: \"<\" | \"<=\" | \"==\" | \"!=\" | \">\" | \">=\", rhs: FinmathInput) {\n  const compareresult = cmp(lhs, rhs);\n  switch (relation) {\n    case '<': return compareresult < 0;\n    case '<=': return compareresult <= 0;\n    case '==': return compareresult === 0;\n    case '!=': return compareresult !== 0;\n    case '>': return compareresult > 0;\n    case '>=': return compareresult >= 0;\n  }\n  throw Error(`Cannot test for unknown relation '${relation}'`);\n}\n","/* A Money type library for safe calculation with money amounts in JS. If you don't\n   know why we need this, try to predict what the following code would print:\n   var cents=0;for(var i=0;i<100;++i)cents+=0.01;cents-=1;console.log(cents);\n   and think twice about whether you want to code anything financial in JS.\n\n   We haven't decideded yet what range Money should support. To keep our options open and keep HS compatbility for now\n   we will fix ourselves to 5 digits (HS compat) and not allow values bigger than 900_000_000 (2**53 / 100000 'number' compatbiility clamped to a more readable number)\n\n  Users should not rely on JS Money keeping this smaller range in the future. Money values supplied from HareScript should be formatted using FormatJSFinmathMoney\n*/\n\nimport * as finmath from \"./finmath.ts\"; //TODO absorb into us as soon as noone externally depends on finmath anymore\nimport { isMoney } from \"./quacks.ts\";\n\nexport type MoneyRoundingMode = \"none\" | \"toward-zero\" | \"down\" | \"up\" | \"half-toward-zero\" | \"half-down\" | \"half-up\" | \"toward-infinity\" | \"half-toward-infinity\";\nexport type MoneyTestTypes = \"<\" | \"<=\" | \"==\" | \"!=\" | \">\" | \">=\";\n\ntype MoneyParameter = Money | string;\n\ninterface SplitNumber {\n  num: number;\n  decimals: number;\n}\n\nexport interface MoneyFormatOptions {\n  //thousand separator. defaults to \"\"\n  thousandsSeparator?: string;\n  //decimal separator. defaults to \".\"\n  decimalSeparator?: string;\n  //minimum # of decimals. defaults to 2\n  minDecimals?: number;\n}\n\nfunction stripUnneededDecimals(num: number, decimals: number) {\n  //we have a maximum of 5 digits of external precision\n  if (decimals > 5) {\n    // math.round rounds toward positive infinity\n    const isneg = num < 0;\n    if (isneg)\n      num = -num;\n\n    while (decimals > 6) { //truncate excess digits\n      num = Math.floor(num / 10);\n      --decimals;\n    }\n    //round up if 6th decimal >= 5\n    num = Math.round(num / 10);\n    decimals = 5;\n\n    if (isneg)\n      num = -num;\n  }\n\n  //strip unneeded decimals\n  while (decimals > 0 && !(num % 10)) {\n    num /= 10;\n    --decimals;\n  }\n\n  return { num, decimals };\n}\n\n/** Convert a money of any format to a split number object\n    @param money - Either an integer number or string with a number\n    @returns Split number object\n*/\nfunction splitValue(money: MoneyParameter): SplitNumber {\n  if (typeof money === 'number') {\n    if (money !== Math.floor(money))\n      throw new Error(\"Non-integer number passed\");\n    if (!Number.isSafeInteger(money))\n      throw new Error(`The value ${money} is outside the safe value range`);\n    return { num: money, decimals: 0 };\n  }\n  if (typeof money !== 'string')\n    throw new Error(\"Number or string expected, got \" + money);\n\n  const split = money.match(/^(-)?([0-9]*)(\\.([0-9]{0,5})([0-9]*))?$/);\n  if (!split)\n    throw new Error(`Illegal money value received: '${money}'`);\n\n  const sign = split[1] === '-' ? -1 : 1;\n  const decimals = split[3] ? split[4].length : 0;\n  // If there are more than 5 decimals, round up (using halfExpand strategy)\n  const num = sign * (parseInt(split[2] || \"0\") * Math.pow(10, decimals) + (parseInt((split[4] || '')) || 0) + (split[5]?.[0] >= '5' ? 1 : 0));\n  if (!Number.isSafeInteger(num))\n    throw new Error(`The value '${money}' is outside the safe value range`);\n\n  return stripUnneededDecimals(num, decimals);\n}\n\nfunction toText(amount: SplitNumber, decimalpoint: string, mindecimals: number, thousandpoint: string) {\n  if (!Number.isSafeInteger(amount.num))\n    throw new Error(\"Result would overflow the safe value range\");\n\n  let { num, decimals } = stripUnneededDecimals(amount.num, amount.decimals);\n\n  // Strip sign from number, may need to prefix it\n  const isnegative = num < 0;\n  if (isnegative)\n    num = -num;\n\n  let astext = String(num);\n\n  // Ensure we have enough leading 0's to render the first integer digit\n  if (astext.length <= decimals)\n    astext = '00000000000000000000'.substring(0, decimals + 1 - astext.length) + astext;\n  // make sure we have enough 0's to show mindecimals\n  if (decimals < mindecimals) {\n    astext += '00000000000000000000'.substring(0, mindecimals - decimals);\n    decimals = mindecimals;\n  }\n\n  let beforepoint = astext.substring(0, astext.length - decimals);\n  const afterpoint = astext.substring(astext.length - decimals);\n\n  // Add thouands points if neeed\n  if (thousandpoint)\n    beforepoint = beforepoint.replaceAll(/\\B(?=(\\d{3})+(?!\\d))/g, thousandpoint);\n\n  return (isnegative ? \"-\" : \"\") + beforepoint + (afterpoint.length ? decimalpoint + afterpoint : \"\");\n}\n\n/** A decimal based JS money type*/\nexport class Money {\n  /** finmath-compatible value */\n  readonly value: string;\n  private static \"__ $whTypeSymbol\" = \"Money\";\n\n  constructor(value: MoneyParameter = \"0\") {\n    this.value = Money.parseParameter(value);\n\n    const intvalue = parseInt(this.value);\n    //We need the number to be in the safe range even after adding 5 decimals\n    if (intvalue <= (Number.MIN_SAFE_INTEGER / 100000) || intvalue >= (Number.MAX_SAFE_INTEGER / 100000))\n      throw new TypeError(`Money value '${value}' is out of range`);\n  }\n\n  private static parseParameter(param: MoneyParameter): string {\n    if (typeof param === \"string\")\n      return toText(splitValue(param), \".\", 0, \"\");\n    if (Money.isMoney(param))\n      return (param as unknown as { value: string }).value;\n\n    throw new TypeError(`Money cannot be constructed out of a value of type ${typeof param}`);\n  }\n\n  static isMoney(value: unknown): value is Money {\n    return isMoney(value);\n  }\n\n  static fromNumber(value: number): Money {\n    return new Money(String(value));\n  }\n\n  /** Adds numbers together\n  */\n  static add(left: MoneyParameter, ...right: MoneyParameter[]): Money {\n    let sum = Money.parseParameter(left);\n    for (const item of right)\n      sum = finmath.add(sum, Money.parseParameter(item));\n    return new Money(sum);\n  }\n\n  /** Subtracts a number from another number\n  */\n  static subtract(left: MoneyParameter, right: MoneyParameter): Money {\n    return new Money(finmath.subtract(Money.parseParameter(left), Money.parseParameter(right)));\n  }\n\n  /** Rounds a value to a multiple of a unit, with a specific rounding mode\n      @param amount - Value to round\n      @param roundto - The value will be rounded to a mulitple of this unit (except when rounding mode is 'none')\n      @param mode - Rounding mode. Possible values:<br>\n        <ul>\n          <li>none: No rounding</li>\n          <li>toward-zero: Round toward zero</li>\n          <li>down: Round toward negative infity</li>\n          <li>up: Round toward positive infity</li>\n          <li>half-toward-zero: Round nearest multiple, round half of a multiple toward zero</li>\n          <li>half-down: Round nearest multiple, round half of a multiple toward negative infinity</li>\n          <li>half-up: Round nearest multiple, round half of a multiple toward positive infity</li>\n        </ul>\n      @returns The rounded value\n  */\n  static roundToMultiple(amount: MoneyParameter, roundto: MoneyParameter, mode: MoneyRoundingMode): Money {\n    return new Money(finmath.roundToMultiple(Money.parseParameter(amount), Money.parseParameter(roundto), mode));\n  }\n\n  /** Compares two numbers\n      @param lhs - Left hand value\n      @param rhs - Right hand value\n      @returns Returns 0 if amount1 === amount2, -1 if amount1 \\< amount2, 1 if amount1 \\> amount2\n  */\n  static cmp(lhs: MoneyParameter, rhs: MoneyParameter): -1 | 0 | 1 {\n    return finmath.cmp(Money.parseParameter(lhs), Money.parseParameter(rhs));\n  }\n\n  /** Test whether two values have a specific relation\n      @param lhs - Left hand value\n      @param relation - One of '\\<', '\\<=', '==', '!=', '\\>', '\\>=''\n      @param rhs - Right hand value\n      @returns TRUE if the relation holds\n      @example\n        console.log(Money.check(1, '\\<', 2)); // prints 'true'\n  */\n  static check(lhs: MoneyParameter, relation: MoneyTestTypes, rhs: MoneyParameter): boolean {\n    return finmath.test(Money.parseParameter(lhs), relation, Money.parseParameter(rhs));\n  }\n\n  /** Multiplies two numbers together\n  */\n  static multiply(left: MoneyParameter, right: MoneyParameter): Money {\n    return new Money(finmath.multiply(Money.parseParameter(left), Money.parseParameter(right)));\n  }\n\n  /** Returns a percentage of an amount\n      @param amount - Original amount\n      @param percentage - Percentage of the amount to return\n      @returns Percentage of the amount\n  */\n  static getPercentage(amount: MoneyParameter, percentage: MoneyParameter): Money {\n    return new Money(finmath.getPercentageOfAmount(Money.parseParameter(amount), Money.parseParameter(percentage)));\n  }\n\n  /** Divides two values, (currently with up to 5 decimals of precision)\n      @param numerator - Value to divide\n      @param divisor - Divisor\n      @returns Divided value\n  */\n  static divide(numerator: MoneyParameter, divisor: MoneyParameter): Money {\n    return new Money(finmath.divide(Money.parseParameter(numerator), Money.parseParameter(divisor)));\n  }\n  /** Returns the minimum of all the arguments\n      @param amount - First value\n      @param amounts - Rest of the values\n      @returns The lowest value among amount and amounts\n  */\n  static min(amount: MoneyParameter, ...amounts: MoneyParameter[]): Money {\n    return new Money(finmath.min(Money.parseParameter(amount), ...(amounts.map(Money.parseParameter))));\n\n  }\n\n  /** Returns the maximum of all the arguments\n      @param amount - First value\n      @param amounts - Rest of the values\n      @returns The highest value among amount and amounts\n  */\n  static max(amount: MoneyParameter, ...amounts: MoneyParameter[]): Money {\n    return new Money(finmath.max(Money.parseParameter(amount), ...(amounts.map(Money.parseParameter))));\n  }\n\n  /** format a price amount. extend # of decimals to specified # if not enough */\n  format(format?: MoneyFormatOptions): string {\n    return toText(splitValue(this.value),\n      format?.decimalSeparator ?? \".\",\n      format?.minDecimals ?? 2,\n      format?.thousandsSeparator ?? \"\");\n  }\n\n  toJSON(): string {\n    return this.value;\n  }\n\n  toString(): string {\n    return this.value;\n  }\n\n  toNumber(): number {\n    return parseFloat(this.value);\n  }\n}\n","import { Money } from \"./money.ts\";\nimport { isBlob, isDate, isMoney, isPromise, isTemporalInstant, isTemporalPlainDate, isTemporalPlainDateTime, isTemporalPlainTime, isTemporalZonedDateTime, stdTypeOf } from \"./quacks.ts\";\n\n/// Returns T or a promise resolving to T\nexport type MaybePromise<T> = Promise<T> | T;\n\nexport type ComparableType = number | null | bigint | string | Date | Money | boolean | Uint8Array | Temporal.Instant | Temporal.PlainDate | Temporal.PlainTime | Temporal.ZonedDateTime;\n\ntype CamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}`\n  ? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}`\n  : Lowercase<S>;\n\ntype KeysToCamelCase<T> = {\n  [K in keyof T as CamelCase<string & K>]: ToCamelCase<T[K]>;\n};\n\ntype CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}` ?\n  `${T extends Capitalize<T> ? \"_\" : \"\"}${Lowercase<T>}${CamelToSnakeCase<U>}` :\n  S;\n\ntype KeysToSnakeCase<T> = {\n  [K in keyof T as CamelToSnakeCase<string & K>]: ToSnakeCase<T[K]>\n};\n\ntype NonRecordTypes = Date | Money | Blob | Temporal.Instant | Temporal.PlainDate | Temporal.PlainDateTime | Temporal.ZonedDateTime;\n\nexport type ToSnakeCase<T> =\n  T extends unknown[] ? Array<ToSnakeCase<T[number]>> :\n  T extends NonRecordTypes ? T :\n  T extends object ? KeysToSnakeCase<T> :\n  T;\n\nexport type ToCamelCase<T> =\n  T extends unknown[] ? Array<ToCamelCase<T[number]>> :\n  T extends NonRecordTypes ? T :\n  T extends object ? KeysToCamelCase<T> :\n  T;\n\n/** Convert a snake_case_name to its corresponding camelCaseName\n * @param name - Name to convert\n * @returns Converted name\n*/\nexport function nameToCamelCase(name: string) {\n  return name.replaceAll(/_[a-z]/g, c => c[1].toUpperCase());\n}\n\n/** Convert a camelCaseName to corresponding snake_case_name\n * @param name - Name to convert\n * @returns Converted name\n*/\nexport function nameToSnakeCase(name: string) {\n  return name.replaceAll(/[A-Z]/g, c => '_' + c.toLowerCase());\n}\n\n/// Should we rewrite the key/values in this object?\nfunction recodeObject(inp: object) {\n  return !isDate(inp) && !isMoney(inp) && !isBlob(inp) && !isTemporalInstant(inp) && !isTemporalPlainDate(inp) && !isTemporalPlainDateTime(inp) && !isTemporalZonedDateTime(inp);\n}\n\nfunction recursiveToSnakeCase<T>(inp: T): ToSnakeCase<T> {\n  if (Array.isArray(inp))\n    return inp.map(toSnakeCase) as ToSnakeCase<T>;\n  if (inp && typeof inp === \"object\" && recodeObject(inp))\n    return Object.fromEntries(Object.entries(inp).map(([key, value]) => [nameToSnakeCase(key), recursiveToSnakeCase(value)])) as ToSnakeCase<T>;\n  return inp as ToSnakeCase<T>;\n}\n\nfunction recursiveToCamelCase<T>(inp: T): ToCamelCase<T> {\n  if (Array.isArray(inp))\n    return inp.map(toCamelCase) as ToCamelCase<T>;\n  if (inp && typeof inp === \"object\" && recodeObject(inp))\n    return Object.fromEntries(Object.entries(inp).map(([key, value]) => [nameToCamelCase(key), recursiveToCamelCase(value)])) as ToCamelCase<T>;\n  return inp as ToCamelCase<T>;\n}\n\n/** Convert all keys to camel case recursively\n * @param inp - Array or object to convert\n * @returns Converted object\n*/\nexport function toSnakeCase<T extends object | object[] | null | undefined>(inp: T): ToSnakeCase<T> {\n  return recursiveToSnakeCase(inp);\n}\n\n/** Convert all keys to snake case recursively\n * @param inp - Array or object to convert\n * @returns Converted object\n*/\nexport function toCamelCase<T extends object | object[] | null | undefined>(inp: T): ToCamelCase<T> {\n  return recursiveToCamelCase(inp);\n}\n\n// TODO make this a quack if we're sure Uint8array is what we want to support - this is here basically to give Buffer support to be compatible with hscompat' compare\nfunction isUInt8Array(value: unknown): value is Uint8Array {\n  return value !== null && typeof value === \"object\" && \"length\" in value && (value as Uint8Array).BYTES_PER_ELEMENT === 1;\n}\n\ntype AwaitedValues<T extends readonly unknown[]> = { -readonly [K in keyof T]: Awaited<T[K]> };\n\n/** Resolve an array of potential promises, returning an array with resolved results\n * @param array - Array of values or promises\n * @returns An array of resolved values, or a promise resolving to that array if any input was a promise\n*/\nexport function maybePromiseAll<const T extends readonly unknown[]>(array: T): MaybePromise<AwaitedValues<T>> {\n  const resolved: Array<Awaited<T[number]>> = [];\n  for (const item of array) {\n    if (isPromise(item))\n      return Promise.all(array) as Promise<AwaitedValues<T>>;\n    resolved.push(item as Awaited<T[number]>);\n  }\n  return resolved as AwaitedValues<T>;\n}\n\n/** Call a function on the value of a potential promise, return the result\n * @param value - Value or promise\n * @param cb - Callback to call on the value\n * @returns The result of the callback, or a promise resolving to that result if the input was a promise\n*/\nexport function mapMaybePromise<T, U>(value: T, cb: (arg: Awaited<T>) => U): U | Promise<U> {\n  return isPromise(value) ? value.then(t => cb(t as Awaited<T>)) : cb(value as Awaited<T>);\n}\n\n/** Compare two values of std-supported types\n * @param left - First value\n * @param right - Second value\n * @returns -1 if left \\< right, 0 if equal, 1 if left \\> right\n */\nexport function compare(left: ComparableType, right: ComparableType): -1 | 0 | 1 {\n  if (left === null)\n    return right === null ? 0 : -1;\n  else if (right === null)\n    return 1;\n\n  switch (typeof left) {\n    case \"boolean\": {\n      if (typeof right === \"boolean\")\n        return left !== right ? left < right ? -1 : 1 : 0;\n    } break;\n    case \"number\": {\n      switch (typeof right) {\n        case \"bigint\": {\n          const right_number = Number(right);\n          return left !== right_number ? left < right_number ? -1 : 1 : 0;\n        }\n        case \"number\": {\n          return left !== right ? left < right ? -1 : 1 : 0;\n        }\n        case \"object\": {\n          if (Money.isMoney(right))\n            return Money.cmp(left.toString(), right);\n        }\n      }\n    } break;\n    case \"bigint\": {\n      switch (typeof right) {\n        case \"bigint\": {\n          return left !== right ? left < right ? -1 : 1 : 0;\n        }\n        case \"number\": {\n          const left_number = Number(left);\n          return left_number !== right ? left_number < right ? -1 : 1 : 0;\n        }\n        case \"object\": {\n          if (Money.isMoney(right)) {\n            return Money.cmp(left.toString(), right);\n          }\n        }\n      }\n    } break;\n    case \"string\": {\n      if (typeof right === \"string\")\n        return left === right ? 0 : left < right ? -1 : 1;\n    } break;\n    case \"object\": {\n      if (Money.isMoney(left)) {\n        switch (typeof right) {\n          case \"number\":\n          case \"bigint\":\n            return Money.cmp(left, right.toString());\n          case \"object\": {\n            if (right === null) {\n              return 1;\n            } else if (Money.isMoney(right))\n              return Money.cmp(left, right);\n          }\n        }\n      } else if (isDate(left)) {\n        if (isTemporalInstant(right)) {\n          const left_value = Number(left);\n          const right_value = right.epochMilliseconds;\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        } else if (isDate(right)) {\n          const left_value = Number(left);\n          const right_value = Number(right);\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        }\n      } else if (isUInt8Array(left) && isUInt8Array(right)) {\n        const compareLength = Math.min(left.length, right.length);\n        for (let i = 0; i < compareLength; i++) {\n          if (left[i] !== right[i])\n            return left[i] < right[i] ? -1 : 1;\n        }\n        return left.length !== right.length ? left.length < right.length ? -1 : 1 : 0;\n      } else if (isTemporalInstant(left)) {\n        if (isDate(right)) {\n          const left_value = left.epochMilliseconds;\n          const right_value = Number(right);\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        } else if (isTemporalInstant(right)) {\n          const left_value = left.epochMilliseconds;\n          const right_value = right.epochMilliseconds;\n          return left_value !== right_value ? left_value < right_value ? -1 : 1 : 0;\n        }\n      } else if (isTemporalPlainDate(left) && isTemporalPlainDate(right)) {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we're not loading Temporal types when packaging @webhare/std separately\n        return (globalThis as any).Temporal.PlainDate.compare(left, right);\n      } else if (isTemporalPlainTime(left) && isTemporalPlainTime(right)) {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we're not loading Temporal types when packaging @webhare/std separately\n        return (globalThis as any).Temporal.PlainTime.compare(left, right);\n      } else if (isTemporalZonedDateTime(left) && isTemporalZonedDateTime(right)) {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we're not loading Temporal types when packaging @webhare/std separately\n        return (globalThis as any).Temporal.ZonedDateTime.compare(left, right);\n      }\n    } break;\n  }\n  throw new Error(`Cannot compare a ${stdTypeOf(left)} with a ${stdTypeOf(right)}`);\n}\n\n/** Returns all property keys of an object type whose value is comparable */\ntype ComparableFields<E extends object, K extends keyof E = keyof E> = K extends keyof E ? E[K] extends ComparableType ? K : never : never;\n\n/** Type of array elements for keys in `compareProperties` */\ntype ComparePropertiesArrayElement<E extends object> = ComparableFields<E> | [ComparableFields<E>, \"asc\" | \"desc\"];\n\n/** All possible types of object keys */\ntype AnyKey = string | symbol | number;\n\n/** Extracts the property name from an array element of CompareProperties */\ntype GetPropertyFromComparePropertiesArrayElement<T> = T extends AnyKey ? T : T extends [infer A, \"asc\" | \"desc\"] ? A : never;\n\n/** Get the list of properties referenced in the `compareProperties` keys list */\ntype GetPropertiesFromComparePropertiesKeys<K extends AnyKey | Array<AnyKey | [AnyKey, \"asc\" | \"desc\"]>> = K extends AnyKey ? K : K extends Array<infer T> ? GetPropertyFromComparePropertiesArrayElement<T> : never;\n\n/** Get all proper prefixes of a tuple, excluding the empty tuple and the source tuple */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TuplePrefixes<K extends AnyKey | [...any[]]> = K extends [any] ? never : K extends [infer A, ...infer B] ? [A] | [A, ...TuplePrefixes<B>] : never;\n\n/** Template for possible keys value (needed to make TS understand that a tuple prefix of the keys is also a valid keys list */\ntype PossibleFields<E extends object> = ComparableFields<E> | [ComparePropertiesArrayElement<E>, ...Array<ComparePropertiesArrayElement<E>>];\n\n/**\n * Build a comparator function for objects using one or more comparable properties.\n * This is extremely useful as a type-safe comparator for sort/toSorted APIs, especially\n * when dealing with multiple or non-string keys.\n *\n * Keys can be provided as:\n * - a single property key\n * - a tuple/array of keys\n * - a tuple/array with sort direction entries in the form [key, \"asc\" | \"desc\"]\n *\n * Comparison is performed in order until the first non-zero result.\n *\n * @param fields - Field selector(s) defining compare priority and optional direction.\n * @returns A compare callback suitable for Array.prototype.sort, extended with\n * `partialCompare(...)` to create a comparator for a prefix of the same key sequence.\n * @throws Error if any configured property is undefined on either compared object.\n * @example\n * ```ts\n * const byName = compareProperties(\"name\");\n * users.sort(byName);\n * ```\n *\n * @example\n * ```ts\n * const byPriorityThenDate = compareProperties([\n *   [\"priority\", \"desc\"],\n *   [\"createdAt\", \"asc\"]\n * ] as const);\n * items.sort(byPriorityThenDate);\n * ```\n *\n * @example\n * ```ts\n * const byCountryCityStreet = compareProperties([\"country\", \"city\", \"street\"] as const);\n * const byCountryCity = byCountryCityStreet.partialCompare([\"country\", \"city\"] as const);\n * addresses.sort(byCountryCity);\n * ```\n */\nexport function compareProperties<const K extends ComparableFields<E> | [...Array<ComparePropertiesArrayElement<E>>], E extends object = Record<GetPropertiesFromComparePropertiesKeys<K>, ComparableType>>(fields: K) {\n  const compareList = (Array.isArray(fields) ? fields : [fields]).map((field): [keyof E, 1 | -1] => Array.isArray(field) ? [field[0], field[1] === \"desc\" ? -1 : 1] : [field, 1]);\n  const retval: (lhs: E, rhs: E) => number = (a, b) => {\n    for (const [field, negate] of compareList) {\n      if (a[field] === undefined || b[field] === undefined)\n        throw new Error(`Property '${String(field)}' does not exist`);\n      const res = negate * compare(a[field] as ComparableType, b[field] as ComparableType);\n      if (res)\n        return res;\n    }\n    return 0;\n  };\n  return Object.assign(retval, {\n    partialCompare: <T extends TuplePrefixes<K> & PossibleFields<E>>(partialFields: T) => compareProperties<T, E>(partialFields)\n  });\n}\n\nlet enumReverseMaps: WeakMap<Record<string, string | number>, Record<string | number, string>> | undefined;\n\ntype EnumEntries<T extends Record<string, string | number>, F extends number, K extends keyof T = keyof T> = K extends keyof T ? T[K] extends F ? [K, T[K]] : never : never;\n\n/** Returns the reverse mapping of a value of an const object used as enum. Can only be used for numbers.\n * @param enumObj - The enum object to reverse map.\n * @param value - The value to look up in the reverse map.\n * @returns The key corresponding to the given value in the enum object.\n * @example\n * ```ts\n * const Color = {\n *   Red: 1,\n *   Green: 2,\n *   Blue: 3\n * } as const;\n * const key = enumReverseMap(Color, 2); // \"Green\"\n * ```\n */\nexport function enumReverseMap<const T extends Record<string, string | number>, const V extends EnumEntries<T, number>[1]>(enumObj: T, value: V): EnumEntries<T, V>[0] {\n  enumReverseMaps ??= new WeakMap<Record<string, string | number>, Record<string | number, string>>();\n  let reverse = enumReverseMaps.get(enumObj);\n  if (!reverse) {\n    reverse = {} as Record<string | number, string>;\n    for (const [key, v] of Object.entries(enumObj))\n      if (typeof v === \"number\")\n        reverse[enumObj[key]] = key;\n    enumReverseMaps.set(enumObj, reverse);\n  }\n  return reverse[value];\n}\n","import { stdTypeOf } from \"./quacks.ts\";\nimport { Money } from \"./money.ts\";\n\nexport type WildcardTypes = \"?*\";\n\n/** Encode string for use in a regexp\n * @param text - Text to encode\n * @param options - Options for encoding\n * @param options.wildcards - Type of wildcards to encode (defaults to none)\n * @returns Encoded for safe use in a RegExp\n*/\nexport function escapeRegExp(text: string, options?: { wildcards?: WildcardTypes }): string {\n  let mask = text.replaceAll(/[/\\-\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'); // $& means the whole matched string\n  if (options?.wildcards === \"?*\") {\n    mask = mask.replaceAll(\"\\\\*\", \".*\");\n    mask = mask.replaceAll(\"\\\\?\", \".\");\n  }\n  return mask;\n}\n\n/** Create a regular expression from one or more wildcard masks\n * @param masks - One or more masks with '?' and/or '*' wildcards\n * @returns Regular expression string\n*/\nexport function regExpFromWildcards(masks: string | string[], options?: { wildcards?: WildcardTypes; caseInsensitive?: boolean }): RegExp {\n  if (Array.isArray(masks) && masks.length === 0)\n    throw new Error(\"Empty mask list\");\n\n  const code = Array.isArray(masks)\n    ? `^(${masks.map(mask => escapeRegExp(mask, { wildcards: options?.wildcards || \"?*\" })).join('|')})$`\n    : `^${escapeRegExp(masks, { wildcards: options?.wildcards || \"?*\" })}$`;\n  return new RegExp(code, options?.caseInsensitive ? \"i\" : undefined);\n}\n\nfunction isHTMLUnrepresentableChar(curch: number) {\n  return (curch < 32 && curch !== 9 && curch !== 10 && curch !== 13)\n    || (curch >= 128 && curch <= 159);\n}\n\nfunction encodeEntities(str: string, html: boolean) {\n  let s = \"\";\n  for (const char of str) {\n    const curch = char.codePointAt(0);\n    if (curch === undefined || isHTMLUnrepresentableChar(curch))\n      continue;\n    if (curch >= 32 && curch < 128 && curch !== 38 && curch !== 60 && curch !== 62 && (html || curch !== 34 && curch !== 39)) {\n      s += String.fromCodePoint(curch);\n      continue;\n    }\n\n    switch (curch) {\n      case 10:\n        {\n          if (html) {\n            s += \"<br>\";\n            continue;\n          }\n          break;\n        }\n      case 13:\n        {\n          if (html)\n            continue;\n          break;\n        }\n      case 34:\n        {\n          s += \"&quot;\";\n          continue;\n        }\n      case 38:\n        {\n          s += \"&amp;\";\n          continue;\n        }\n      case 39:\n        {\n          s += \"&apos;\";\n          continue;\n        }\n      case 60:\n        {\n          s += \"&lt;\";\n          continue;\n        }\n      case 62:\n        {\n          s += \"&gt;\";\n          continue;\n        }\n    }\n\n    s += \"&#\" + curch + \";\";\n  }\n  return s;\n}\n\nfunction decodeEntities(str: string, html: boolean) {\n  if (html)\n    str = str.replace(/<br *\\/?>/g, \"\\n\");\n\n  str = str.replace(/&#(\\d+);/g, (_, dec) => String.fromCharCode(dec))\n    .replace(/&lt;/g, \"<\")\n    .replace(/&gt;/g, \">\")\n    .replace(/&quot;/g, '\"')\n    .replace(/&apos;/g, \"'\")\n    .replace(/&amp;/g, \"&\");\n\n  return str;\n}\n\nexport type StringEncodings = \"base64url\" | \"attribute\" | \"html\";\n\nexport function encodeString(str: string, encoding: StringEncodings): string {\n  if (encoding === \"base64url\")\n    return btoa(str).replaceAll(\"=\", \"\").replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\");\n  if (encoding === \"attribute\")\n    return encodeEntities(str, false);\n  if (encoding === \"html\")\n    return encodeEntities(str, true);\n\n  throw new Error(`Invalid encoding '${encoding}'`);\n}\n\nexport function decodeString(str: string, encoding: StringEncodings): string {\n  if (encoding === \"base64url\")\n    return atob(str.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\"));\n  if (encoding === \"attribute\")\n    return decodeEntities(str, false);\n  if (encoding === \"html\")\n    return decodeEntities(str, true);\n\n  throw new Error(`Invalid encoding '${encoding}'`);\n}\n\ntype JSONReplacerArgument = ((this: unknown, key: string, value: unknown) => unknown) | undefined;\n\nexport interface StringifyOptions {\n  replacer?: JSONReplacerArgument;\n  space?: string | number;\n  stable?: boolean;\n  ///Encode with types (preserve Money, Date, BigInt). Needs std.parseTyped\n  typed?: boolean;\n  ///What to target: string (like JSON.stringify), script (escapes '/') or attribute (escapes '/' and applies attribute encoding)\n  target?: \"string\" | \"script\" | \"attribute\";\n}\n\n/** Improved JSON encoder\n * @param arg - Object to encode\n * @param options - Encoding options\n*/\nexport function stringify(arg: unknown, options?: StringifyOptions) {\n  const usereplacer: JSONReplacerArgument = options?.stable || options?.typed ? (function (this: unknown, key: string, value: unknown) {\n    if (options.typed) {\n      const origvalue = (this as Record<string, unknown>)[key]; //We can't use 'value' as .toJSON() will already have been invoked\n      const type = stdTypeOf(origvalue);\n      switch (type) {\n        case \"function\":\n          throw new Error(`Cannot stringify property '${key}' of type \"${type}'`);\n        case \"Date\":\n          value = { \"$stdType\": \"Date\", date: (origvalue as Date).toISOString() };\n          break;\n        case \"Money\":\n        case \"bigint\":\n        case \"Instant\":\n        case \"PlainDate\":\n        case \"PlainTime\":\n        case \"PlainDateTime\":\n        case \"ZonedDateTime\":\n          value = { \"$stdType\": type, [type.toLowerCase()]: (origvalue as { toString: () => string }).toString() };\n          break;\n        case \"object\":\n          if (\"$stdType\" in (origvalue as { \"$stdType\": string }))\n            throw new Error(`Cannot encode objects with already embedded '$stdType's`);\n        //fallthrough\n      }\n    }\n    if (options.stable && value && typeof value === \"object\" && !Array.isArray(value))\n      value = Object.fromEntries(Object.entries(value).sort((lhs, rhs) => lhs < rhs ? -1 : lhs === rhs ? 0 : 1));\n    if (options.replacer)\n      value = options.replacer.call(this, key, value);\n    return value;\n  }) : options?.replacer ?? undefined;\n\n  let result = JSON.stringify(arg, usereplacer, options?.space);\n  if (options?.target && [\"script\", \"attribute\"].includes(options.target)) {\n    result = result.replaceAll(\"/\", \"\\\\/\");\n    if (options.target === \"attribute\")\n      result = encodeEntities(result, false);\n  }\n  return result;\n}\n\n/** Decode JSON with types (Generated using stringify with typed:true ) */\nexport function parseTyped(input: string) {\n  return JSON.parse(input, (key, value) => {\n    switch (value?.[\"$stdType\"]) {\n      case \"Money\":\n        return new Money(value.money);\n      case \"Date\":\n        return new Date(value.date);\n      case \"bigint\":\n      case \"BigInt\": //pre wh5.7 spelling\n        return BigInt(value.bigint as string);\n      case \"Instant\":\n      case \"PlainDate\":\n      case \"PlainTime\":\n      case \"PlainDateTime\":\n      case \"ZonedDateTime\":\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we just assume/require you to have Temporal installed if you expect to receive/decode Temporal types. browsers should catch up eventually\n        if (!(globalThis as any).Temporal)\n          throw new Error(`Temporal is not available in this environment, cannot deserialize value of type Temporal.${value[\"$stdType\"]}. Load eg. @webhare/deps/temporal-polyfill to use Temporal types in browsers`);\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we just assume/require you to have Temporal installed if you expect to receive/decode Temporal types. browsers should catch up eventually\n        return (globalThis as any).Temporal[value[\"$stdType\"]].from(value[value[\"$stdType\"].toLowerCase()]);\n      case undefined:\n        return value;\n      default:\n        throw new Error(`Unrecognized type '${value[\"$stdType\"]}'`);\n    }\n  });\n}\n\n/** Generate a slug from a (suggested) (file)name\n * @param text - Text to convert\n * @param options - Options for slugification\n * @param options.separator - Separator to use between words (defaults to '-')\n * @param options.keep - Set of characters to keep in addition to a-z0-9\n * @returns Slugified text or null if we couldn't generate anything reeadable\n */\nexport function slugify(text: string, { separator = \"-\", keep = \"\" }: {\n  separator?: string;\n  keep?: string;\n} = {}): string | null {\n  //This function mixes HS getSafeName with a few more modern approaches\n  const keepclass = `[^a-z0-9${escapeRegExp(keep)}]`;\n  text = text\n    .normalize('NFD')                   // split an accented letter in the base letter and the acent\n    // eslint-disable-next-line no-control-regex\n    .replaceAll(/[\\u0000-\\u001F]/g, '')\n    .replaceAll(/[\\u0300-\\u036f]/g, '')   // remove all previously split accents\n    .replaceAll(/ß/g, 'ss')               // german ss\n    .toLowerCase()\n    .replace(new RegExp(`^${keepclass}+`), \"\") //replace bad characters at the start\n    .replace(new RegExp(`${keepclass}+$`), \"\") //.. and end\n    .replaceAll(new RegExp(`${keepclass}+`, \"g\"), separator); // replace all non alphanumeric/space with a single dash\n\n  return text || null; //we return 'null' on purpose so callers realize we won't necessarily give them a string!\n}\n\n/** Check if an email address is valid in modern times (an emailcheck much closer to what a browser would do, with additional sanity checks. No attempt to allow all legacy styles supported by the RFCs but 99.9%+ sure to be an error if seen submitted in a form\n    @returns True if the email address appears to be a well-formed email address to a non-greybeard\n*/\nexport function isValidEmail(email: string): boolean {\n  if (email.length > 254) //TODO count bytes instead of characters\n    return false;\n\n  return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*(?:\\.[a-zA-Z0-9-]{2,})$/.test(email);\n}\n\n/** Uppercases a string using the C-locale (so only the ASCII characters a-z are uppercased)\n * @param str - String to uppercase\n * @returns Uppercased string\n */\nexport function toCLocaleUppercase(str: string) {\n  return str.replaceAll(/[a-z]+/g, part => part.toUpperCase());\n}\n\n/** Lowercases a string using the C-locale (so only the ASCII characters A-Z are lowercased)\n * @param str - String to lowercase\n * @returns Lowercased string\n */\nexport function toCLocaleLowercase(str: string) {\n  return str.replaceAll(/[A-Z]+/g, part => part.toLowerCase());\n}\n\n/** Calculate the levenshtein distance between two strings */\nexport function levenshteinDistance(a: string, b: string): number {\n  /* calculateLevenshteinDistance is adopted from https://github.com/gustf/js-levenshtein/blob/master/index.js, licensed MIT © Gustaf Andersson\n    Picked over fastest-levenshtein because a permanent 256KB memory area for a bit more speed doesn't seem worth it\n  */\n  function _min(d0: number, d1: number, d2: number, bx: number, ay: number) {\n    return d0 < d1 || d2 < d1\n      ? d0 > d2\n        ? d2 + 1\n        : d0 + 1\n      : bx === ay\n        ? d1\n        : d1 + 1;\n  }\n\n  if (a === b) {\n    return 0;\n  }\n\n  if (a.length > b.length) {\n    const tmp = a;\n    a = b;\n    b = tmp;\n  }\n\n  let la = a.length;\n  let lb = b.length;\n\n  while (la > 0 && (a.charCodeAt(la - 1) === b.charCodeAt(lb - 1))) {\n    la--;\n    lb--;\n  }\n\n  let offset = 0;\n\n  while (offset < la && (a.charCodeAt(offset) === b.charCodeAt(offset))) {\n    offset++;\n  }\n\n  la -= offset;\n  lb -= offset;\n\n  if (la === 0 || lb < 3) {\n    return lb;\n  }\n\n  let x = 0;\n  let y, d0, d1, d2, d3, dd = 0, dy, ay, bx0, bx1, bx2, bx3;\n\n  const vector: number[] = [];\n\n  for (y = 0; y < la; y++) {\n    vector.push(y + 1);\n    vector.push(a.charCodeAt(offset + y));\n  }\n\n  const len = vector.length - 1;\n\n  for (; x < lb - 3;) {\n    bx0 = b.charCodeAt(offset + (d0 = x));\n    bx1 = b.charCodeAt(offset + (d1 = x + 1));\n    bx2 = b.charCodeAt(offset + (d2 = x + 2));\n    bx3 = b.charCodeAt(offset + (d3 = x + 3));\n    dd = (x += 4);\n    for (y = 0; y < len; y += 2) {\n      dy = vector[y];\n      ay = vector[y + 1];\n      d0 = _min(dy, d0, d1, bx0, ay);\n      d1 = _min(d0, d1, d2, bx1, ay);\n      d2 = _min(d1, d2, d3, bx2, ay);\n      dd = _min(d2, d3, dd, bx3, ay);\n      vector[y] = dd;\n      d3 = d2;\n      d2 = d1;\n      d1 = d0;\n      d0 = dy;\n    }\n  }\n\n  for (; x < lb;) {\n    bx0 = b.charCodeAt(offset + (d0 = x));\n    dd = ++x;\n    for (y = 0; y < len; y += 2) {\n      dy = vector[y];\n      vector[y] = dd = _min(dy, d0, dd, bx0, vector[y + 1]);\n      d0 = dy;\n    }\n  }\n\n  return dd;\n}\n\n/** Return the length of the string in bytes when UTF-8 encoded */\nexport function getUTF8Length(str: string) {\n  return new TextEncoder().encode(str).length;\n}\n\n/** Truncate the string so it's at most len UTF-8 bytes long */\nexport function limitUTF8Length(str: string, len: number) {\n  // TextEncoder.encodeInto writes into the given array until there's no more room to add more valid UTF-8 sequences from the\n  // source. We can use this property to limit the number of bytes by creating an array that has room for at most the given\n  // number of bytes.\n  const utf8array = new Uint8Array(len);\n  // This function returns the actual number of bytes written to the array\n  const { written } = new TextEncoder().encodeInto(str, utf8array);\n  // Decode only the actually written bytes\n  return new TextDecoder().decode(utf8array.subarray(0, written));\n}\n\n/** Update the search parameters in a URL\n * @param inUrl - URL to update\n * @param updates - Updates to apply, use 'null' to delete a variable\n * @returns Updated URL\n */\nexport function updateURL(inUrl: string | URL, updates: Record<string, string | null>): URL {\n  const u = new URL(inUrl);\n  for (const [k, v] of Object.entries(updates)) {\n    if (v === null) {\n      u.searchParams.delete(k);\n    } else {\n      u.searchParams.set(k, v);\n    }\n  }\n  return u;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any -- Cannot specify this without using any */\n\nexport interface EmplaceHandler<ValueType> {\n  insert?: () => ValueType;\n  update?: (current: ValueType) => ValueType;\n}\n\nfunction binarySearchImpl<A, K>(compareFn: (element: A, key: K) => number, contents: A[], searchfor: K, upper_bound: boolean): { present: boolean; index: number } {\n  let first = 0;\n  let len = contents.length;\n  let present = false;\n\n  const cmpbound = upper_bound ? 1 : 0;\n  let unsorted_cmp = 0; // if this is non-0 and cmp is this value, we have an unsorted list\n  while (len > 0) {\n    const half = Math.floor(len / 2);\n    const middle = first + half;\n    const cmp = compareFn(contents[middle], searchfor);\n    if (cmp === 0) {\n      present = true;\n      unsorted_cmp = upper_bound ? -1 : 1;\n    } else if (cmp === unsorted_cmp)\n      throw new Error(`The provided array was not properly sorted!`);\n\n    if (cmp < cmpbound) {\n      first = middle + 1;\n      len -= half;\n      --len;\n    } else {\n      len = half;\n    }\n  }\n  return { present, index: first };\n}\n\n//emplace is based on https://github.com/tc39/proposal-upsert (a Map.prototype.emplace)\n/** Place a value into a Map\n * @param map - The map to place the value into\n * @param key - The key to add/replace\n * @param handler - Callbacks for inserting or updating the value\n * @returns The value that was placed into the map.\n * @throws If the key is not found and no insert handler is provided\n */\nexport function emplace<T extends Map<any, any> | WeakMap<any, any>>(\n  map: T,\n  key: T extends Map<infer K, any> ? K : T extends WeakMap<infer K, any> ? K : never,\n  handler?: T extends Map<any, infer V> ? EmplaceHandler<V> : T extends WeakMap<any, infer V> ? EmplaceHandler<V> : never):\n  T extends Map<any, infer V> ? V : T extends WeakMap<any, infer V> ? V : never {\n  let current = map.get(key);\n  if (current !== undefined) {\n    if (handler?.update) {\n      current = handler.update(current);\n      map.set(key, current);\n    }\n    return current;\n  }\n\n  if (!handler?.insert)\n    throw new Error(\"Key not found and no insert handler provided\");\n\n  const setvalue = handler.insert();\n  map.set(key, setvalue);\n  return setvalue;\n}\n\n// the `| keyof X` is needed to be able to use a `keyof X` type as key parameter in DistributedPick or DistributedOmit in generics\nexport type DistributedKeys<X extends object> = (X extends object ? keyof X : never) | keyof X;\n\n/** Applies Pick to all types in a union. Allows all keys that are present in any object in the union. Warning: You might not be\n    able to use all keys of the union if TypeScript has narrowed the union to a specific type. Eg:\n```typescript\ntype A = { x: number; t: \"a\"; a: number } | { x: number; t: \"b\"; b: number };\nconst a: A = { t: \"a\", a: 1 };\nconst b = pick(a, [\"t\", \"a\", \"b\"]); // No overload matches this call. <snip> Type '\"b\"' is not assignable to type '\"a\" | \"t\" | \"d\"'.\n```\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to return\n    @returns Type with only the specified keys (distributed over the union if present)\n*/\nexport type DistributedPick<X extends object, Y extends DistributedKeys<X>> = X extends object ? Pick<X, keyof X & Y> : never;\n\n/** Applies Omit to all types in a union. Allows all keys that are not present in any object in the union. Warning: You might not be\n    able to use all keys of the union if TypeScript has narrowed the union to a specific type. Eg:\n```typescript\ntype A = { x: number; t: \"a\"; a: number } | { x: number; t: \"b\"; b: number };\nconst a: A = { t: \"a\", a: 1 };\nconst b = omit(a, [\"b\"]); // No overload matches this call. <snip> Type '\"b\"' is not assignable to type '\"a\" | \"t\" | \"d\"'.\n```\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to leave out\n    @returns Type with only the specified keys left out (distributed over the union if present)\n*/\nexport type DistributedOmit<X extends object, Y extends DistributedKeys<X>> = X extends object ? Omit<X, keyof X & Y> : never;\n\n/** Returns an object with a selection of properties\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to return\n    @param obj - Object to pick properties out of\n    @param keys - Names of the properties to pick\n    @returns Resulting object\n*/\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(obj: T, keys: readonly K[]): DistributedPick<T, K>;\n\n/** Returns an array with a selection of properties\n    @typeParam T - Type of the supplied array\n    @typeParam K - Type of the property keys to return\n    @param arr - Array to pick properties out of\n    @param keys - Names of the properties to pick\n    @returns Resulting array\n*/\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(arr: T[], keys: readonly K[]): Array<DistributedPick<T, K>>;\n\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(value: T | T[], keys: readonly K[]): DistributedPick<T, K> | Array<DistributedPick<T, K>> {\n  if (Array.isArray(value))\n    return value.map((elt: T) => pick(elt, keys));\n  const ret = {} as T;\n  keys.forEach((key: K) => {\n    if (key in value)\n      ret[key] = value[key];\n  });\n  return ret as object as DistributedPick<T, K>;\n}\n\n/** Returns an object with a selection of properties left out\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to leave out\n    @param obj - Object to leave properties out of\n    @param keys - Names of the properties to remove\n    @returns Resulting object\n*/\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(obj: T, keys: readonly K[]): DistributedOmit<T, K>;\n\n/** Returns an array with a selection of properties left out\n    @typeParam T - Type of the supplied array\n    @typeParam K - Type of the property keys to leave out\n    @param arr - Array to leave properties out of\n    @param keys - Names of the properties to leave out\n    @returns Resulting array\n*/\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(arr: T[], keys: readonly K[]): Array<DistributedOmit<T, K>>;\n\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(value: T | T[], keys: readonly K[]): DistributedOmit<T, K> | Array<DistributedOmit<T, K>> {\n  if (Array.isArray(value))\n    return value.map((elt: T) => omit(elt, keys));\n  const ret = {} as T;\n  for (const [key, val] of Object.entries(value)) {\n    if (!keys.includes(key as K))\n      ret[key as K] = val;\n  }\n  return ret as object as DistributedOmit<T, K>;\n}\n\n/** Shuffle an array in-place\n * @param array - Array to shuffle\n * @returns The shuffled array\n*/\nexport function shuffle<T>(array: T[]): T[] {\n  for (let i = array.length - 1; i > 0; i--) {\n    const j = Math.floor(Math.random() * (i + 1));\n    [array[i], array[j]] = [array[j], array[i]];\n  }\n  return array;\n}\n\n/** Returns (and TypeScript-asserts) that the specified function is truthy. Handy for adjusting the type of an array when\n * filtering out falsy values\n * @example\n * const myarray: Array&lt;number | null&gt; = [0, null];\n * const filtered: number[] = myarray.filter(isTruthy);\n **/\nexport function isTruthy<T>(a: T): a is (T & {}) {\n  return Boolean(a);\n}\n\n/** Append to array, without overflowing the stack (eg V8 overflows at more than 32K entries)\n * @param array - Array to append to\n * @param values - Values to append\n*/\nexport function appendToArray<T>(array: T[], values: ReadonlyArray<NoInfer<T>>): void {\n  if (values.length < 1000)\n    array.push(...values); //push should be safe enough\n  else for (const value of values) //performance wise this appears just as fast as tricks with pushing blocks of slices\n    array.push(value);\n\n  //not returning the original array to make it clear we're not creating a new one\n}\n\ntype TypedEntriesInternal<T extends object, K extends keyof T> = K extends keyof T ? [K, T[K]] : never;\n\n/** Returns a union of [ key, value ] types for an object */\nexport type TypedEntries<T extends object> = T extends object ? TypedEntriesInternal<T, keyof T & string> : never;\n\n/** Returns an array of key/values of the enumerable own properties of an object, with exact types. Use when\n * no extra properties are expected on the object. Exists because Object.entries returns always string as key type.\n * @param obj - Object that contains the properties and methods\n */\nexport function typedEntries<T extends object>(obj: T): Array<TypedEntries<T>> {\n  return Object.entries(obj) as Array<TypedEntries<T>>;\n}\n\n/** Returns an array of keys of the enumerable own properties of an object, with exact types. Use when\n * no extra properties are expected on the object. Exists because Object.keys returns always string as key type.\n * @param obj - Object that contains the properties and methods\n */\nexport function typedKeys<T extends object>(obj: T): Array<keyof T & string> {\n  return Object.keys(obj) as Array<keyof T & string>;\n}\n\n/** Given a union of [key, value] types, returns the object constructed from those pairs. Exists because\n *  Object.fromEntries does not take the type of the keys and values into account.\n * @typeParam T - Union of [key, value] pairs\n */\nexport type TypedFromEntries<T extends [string, unknown]> = { [C in T as C[0]]: C[1] };\n\n/** Returns an object from an iterable of [key, value] pairs, with exact types. Exists because Object.fromEntries\n * doesn't take the type of the keys and values into account.\n * @param entries - Iterable of [key, value] pairs\n * @returns An object with the same keys and values as the input\n */\nexport function typedFromEntries<T extends [string, unknown]>(entries: Iterable<T>): TypedFromEntries<T> {\n  return Object.fromEntries(entries) as TypedFromEntries<T>;\n}\n\n\nexport class SortedMultiSet<V> {\n  private contents: V[] = [];\n  private compareFn;\n\n  constructor(compareFn: (lhs: V, rhs: V) => number, contents?: V[]) {\n    this.compareFn = compareFn;\n    if (contents)\n      this.addMultiple(contents);\n  }\n\n  get size() {\n    return this.contents.length;\n  }\n\n  at(index: number): V | undefined {\n    return this.contents.at(index);\n  }\n\n  add(value: V): number {\n    const pos = this.upperBound(value);\n    this.contents.splice(pos, 0, value);\n    return pos;\n  }\n\n  addMultiple(values: V[]): void {\n    for (const value of values) {\n      this.add(value);\n    }\n  }\n\n  delete(key: V): void {\n    const [start, limit] = this.range(key);\n    this.contents.splice(start, limit - start);\n  }\n\n  clear() {\n    this.contents.splice(0, this.contents.length);\n  }\n\n  lowerBound(key: Readonly<V>): { present: boolean; index: number } {\n    return binarySearchImpl(this.compareFn, this.contents, key, false);\n  }\n\n  upperBound(key: Readonly<V>): number {\n    return binarySearchImpl(this.compareFn, this.contents, key, true).index;\n  }\n\n  range(key: Readonly<V>): [number, number] {\n    return [this.lowerBound(key).index, this.upperBound(key)];\n  }\n\n  slice(start: number, limit: number): V[] {\n    return this.contents.slice(start, limit);\n  }\n\n  *#sliceIterator(start: number, limit: number): Generator<V, void> {\n    for (let idx = start; idx < limit; ++idx)\n      yield this.contents[idx];\n  }\n\n  sliceRange(key: Readonly<V>): V[] {\n    const [start, limit] = this.range(key);\n    return this.slice(start, limit);\n  }\n\n  rangeIterator(key: Readonly<V>): Iterable<V> {\n    const [start, limit] = this.range(key);\n    return this.#sliceIterator(start, limit);\n  }\n}\n\nexport class SortedMultiMap<K, V> {\n  private compareFn;\n  private contents: Array<[K, V]> = [];\n\n  constructor(compareFn: (lhs: K, rhs: K) => number, contents?: Array<[K, V]>) {\n    this.compareFn = (element: [K, V], key: K) => compareFn(element[0], key);\n    if (contents)\n      this.addMultiple(contents);\n  }\n\n  get size() {\n    return this.contents.length;\n  }\n\n  at(index: number): [K, V] | undefined {\n    return this.contents.at(index);\n  }\n\n  add(key: K, value: V): number {\n    const pos = this.upperBound(key);\n    this.contents.splice(pos, 0, [key, value]);\n    return pos;\n  }\n\n  addMultiple(values: Array<[K, V]>) {\n    for (const [key, value] of values) {\n      this.add(key, value);\n    }\n  }\n\n  delete(key: K): void {\n    const [start, limit] = this.range(key);\n    this.contents.splice(start, limit - start);\n  }\n\n  clear() {\n    this.contents.splice(0, this.contents.length);\n  }\n\n  lowerBound(key: Readonly<K>): { present: boolean; index: number } {\n    return binarySearchImpl(this.compareFn, this.contents, key, false);\n  }\n\n  upperBound(key: Readonly<K>): number {\n    return binarySearchImpl(this.compareFn, this.contents, key, true).index;\n  }\n\n  range(key: Readonly<K>): [number, number] {\n    return [this.lowerBound(key).index, this.upperBound(key)];\n  }\n\n  slice(start: number, limit: number): Array<[K, V]> {\n    return this.contents.slice(start, limit);\n  }\n\n  *#sliceIterator(start: number, limit: number): Generator<[K, V], void> {\n    for (let idx = start; idx < limit; ++idx)\n      yield this.contents[idx];\n  }\n\n  sliceRange(key: Readonly<K>): Array<[K, V]> {\n    const [start, limit] = this.range(key);\n    return this.slice(start, limit);\n  }\n\n  rangeIterator(key: Readonly<K>): Iterable<[K, V]> {\n    const [start, limit] = this.range(key);\n    return this.#sliceIterator(start, limit);\n  }\n}\n","const unlock = Symbol(\"unlock\");\n\n/** A mutex which is only visible in the current JavaScript VM\n\n    @example\n```ts\nconst mutex = new LocalMutex;\n\nusing lock = await mutex.lock();\nlock.release();\n\n// If you'll be relying on automatic release\nusing lock = await mutex.lock();\nvoid(lock);\n```\n\n*/\nexport class LocalMutex {\n  private locked = false;\n  private unlockList = new Array<() => void>;\n\n  /** Lock this mutex\n   * @returns Lock object. Use with `using` to ensure automatic unlock\n   */\n  async lock() {\n    if (this.locked) {\n      const defer = Promise.withResolvers<void>();\n      this.unlockList.push(() => defer.resolve());\n      await defer.promise;\n    } else {\n      this.locked = true;\n    }\n    return new LocalLock(this);\n  }\n\n  [unlock](): void {\n    if (this.unlockList.length > 0)\n      (this.unlockList.shift()!)(); //we're fair... unlock longest waiter\n    else\n      this.locked = false;\n  }\n}\n\n/** Instance of a LocalMutex lock */\nclass LocalLock implements Disposable {\n  private mutex: LocalMutex | null;\n\n  constructor(mutex: LocalMutex) {\n    this.mutex = mutex;\n  }\n  /** Explicitly release the lock\n   * @throws Error if the lock is already released\n  */\n  release() {\n    if (!this.mutex)\n      throw new Error(\"Lock already released\");\n\n    this.mutex[unlock]();\n    this.mutex = null;\n  }\n  [Symbol.dispose]() {\n    this.mutex?.[unlock]();\n  }\n}\n\nexport type { LocalLock };\n","/* frontend-config parses the wh-config object in the browser and mocks any missing data. @webhare/env does not actually expose this config, @webhare/frontend does\n   The frontend configuration is built in PageBuildRequest's 'frontendConfig' member */\n\nimport type { DTAPStage } from \"@webhare/env/src/concepts\";\nimport { debugFlags, initEnv } from \"@webhare/env/src/envbackend\";\nimport { getBrowserDebugFlags } from \"@webhare/env/src/init-browser\";\nimport { getLang } from \"@webhare/dompack/src/tree\";\nimport type { FrontendDataTypes } from \"@webhare/frontend\";\nimport { omit, throwError } from \"@webhare/std\";\n\n\n/** The format of the <script id=\"wh-config\"> object  */\nexport type WHConfigScriptData = {\n  //NOTE: existing frontend code doesn't expect site/obj to ever be null. not sure if 'object' provides the best interface or whether we need some sort of 'unknown but an existing object'\n  /** Page (targetobject) specific settings\n   *  @deprecated Use setFrontendData for type-safe settings\n  */\n  obj: { [key: string]: unknown };\n  /** Site specific settings\n   *  @deprecated Use setFrontendData for type-safe settings\n   */\n  site: { [key: string]: unknown };\n\n  /** Root URL of this site */\n  siteRoot: string;\n};\n\nexport type WHConfigScriptData_FromServer = WHConfigScriptData & { dtapStage: DTAPStage };\n\n//names fields can still have when not yet republished\ninterface WHConfigScriptData_OldPublishFields {\n  islive: boolean;\n  dtapstage: DTAPStage;\n  siteroot: string;\n}\n\n//fallback names with deprecation warnings\ninterface WHConfigScriptData_LegacyFields {\n  /** @deprecated Use dtapStage in WH5.4+ */\n  islive: boolean;\n  /** @deprecated Use `dtapStage` from \"\\@webhare/env\"; in WH5.4+ */\n  dtapstage: DTAPStage;\n  /** @deprecated Use `getSiteRoot` from \"\\@webhare/frontend\"; in WH5.7+ */\n  siteroot: string;\n}\n\nlet config: WHConfigScriptData_FromServer | undefined;\nlet siteroot: string | undefined;\nlet dtapStage: DTAPStage = \"production\";\n\n//if document is undefined, we're serverside or in a worker\nconst whconfigel = typeof document !== \"undefined\" ? document.querySelector('script#wh-config') : null;\nif (whconfigel?.textContent) {\n  const parsedConfig: WHConfigScriptData_FromServer & WHConfigScriptData_OldPublishFields = JSON.parse(whconfigel.textContent);\n  config = omit(parsedConfig, [\"siteroot\", \"dtapstage\", \"islive\"]);\n\n  //Fallbacks for pages last published with WH5.3 *and* pages published from HareScript which still emit lowercase props\n  siteroot = parsedConfig.siteRoot ?? parsedConfig.siteroot!;\n  dtapStage = parsedConfig.dtapStage ?? parsedConfig.dtapstage;\n}\n\ninitEnv(dtapStage, '/');\n\nif (typeof location !== \"undefined\")\n  for (const flag of getBrowserDebugFlags('wh-debug'))\n    debugFlags[flag] = true;\n\n\n/** @deprecated frontendConfig has been deprecated. Switch to the getFrontendData system */\n// Make sure we have obj/site as some sort of object, to prevent crashes on naive 'if ($wh.config.obj.x)' tests'\nexport const frontendConfig: WHConfigScriptData & {\n  /** @deprecated Use `getLang().tag` in WH6.0+ & WH5.9.7 */\n  locale?: string;\n} = {\n  ...config,\n  obj: config?.obj || {},\n  site: config?.site || {},\n  siteRoot: siteroot || \"\",\n  dtapstage: dtapStage,\n  islive: dtapStage === \"production\" || dtapStage === \"acceptance\",\n  siteroot: siteroot || \"\",\n  ...typeof document !== \"undefined\" ? { locale: getLang().tag } : {},\n} as WHConfigScriptData & WHConfigScriptData_LegacyFields;\n\n// this is what we actually store in the config object but is type-unsafe to access. Plugins still store data in the config object\nexport type WHConfigSerializedData = WHConfigScriptData & WHConfigScriptData_LegacyFields & { [key in keyof FrontendDataTypes]?: FrontendDataTypes[key] };\n\nif (dtapStage === \"development\") { //WH6.0: it's time to hard phase-out the old fields\n  Object.defineProperties(frontendConfig, {\n    islive: { get() { throw new Error(\"frontendConfig.islive will be removed - replace with testing 'dtapStage' for production | acceptance (WH5.4+)\"); } },\n    dtapstage: { get() { throw new Error(\"frontendConfig.dtapstage will be removed - replace with 'dtapStage' (WH5.4+)\"); } },\n    siteroot: { get() { throw new Error(\"frontendConfig.siteroot will be removed - replace with 'getSiteRoot()' (WH5.7+)\"); } },\n    //TODO but only WH6 addded this property AND getLang so there's no phasing out yet.\n    //locale: { get() { throw new Error(\"frontendConfig.locale will be removed - replace with getLang().tag in WH6.0+ & WH5.9.7\"); } },\n  });\n}\n\n//NOTE: These APIs need to live in init.ts so eg gtm.ts can access us without triggering a CSS reset through frontend.ts. When frontend.ts stops auto-resetting we might move it back\n\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(type: Type, options: { allowMissing: true }): FrontendDataTypes[Type] | null;\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(type: Type, options?: { allowMissing: boolean }): FrontendDataTypes[Type];\n\n/** Get data exported by the response\n * @typeParam Type - The type of data to get\n * @param dataObject - The data object of data to get\n * @param allowMissing - If true, return null if the data object is missing. Otherwise throw an error\n * @example\n```\n  declare module \"@webhare/frontend\" {\n    interface FrontendDataTypes {\n      \"mymodule:type\": {\n        test: number;\n      };\n    }\n  }\n\n  const data = getFrontendData(\"mymodule:type\");\n```\n*/\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(dataObject: Type, { allowMissing = false } = {}): FrontendDataTypes[Type] | null {\n  const retval = (config as undefined | WHConfigSerializedData)?.[dataObject] as FrontendDataTypes[Type];\n  if (!retval)\n    if (allowMissing)\n      return null;\n    else\n      throw new Error(`Missing frontend data object: ${dataObject}`);\n\n  return retval;\n}\n\n/** Get the current site root\n *\n * @returns The site root URL (ending with a slash)\n*/\nexport function getSiteRoot(): string { //now an API to improve treeshaking\n  return siteroot ?? throwError(\"Site root is undefined. HTML code may be broken\");\n}\n","// Set up dispose symbols - https://github.com/evanw/esbuild/pull/3192 \"you'll need to polyfill Symbol.dispose if it's not present before you use it.\n\n//@ts-expect-error -- It's marked readonly\nSymbol.dispose ||= Symbol.for('Symbol.dispose');\n//@ts-expect-error -- It's marked readonly\nSymbol.asyncDispose ||= Symbol.for('Symbol.asyncDispose');\n\n// Set up promise resolvers (ES2024)\nPromise.withResolvers ||= function <T>(): PromiseWithResolvers<T> {\n  let resolve: (value: T | PromiseLike<T>) => void;\n  let reject: (reason: Error) => void;\n  const promise = new Promise<T>((_resolve, _reject) => { resolve = _resolve; reject = _reject; });\n  // @ts-expect-error `resolve` and `reject` are assigned synchronously, which isn't picked up by the TypeScript compiler (see\n  // https://github.com/Microsoft/TypeScript/issues/30053)\n  return { promise, resolve, reject };\n};\n\n// Polyfills for https://caniuse.com/?search=groupby - needed until we can assume safari 17.4 as global baseline\nif (!Map.groupBy)\n  Map.groupBy = function <Item, Key>(items: Iterable<Item>, callbackfn: (item: Item, idx: number) => Key): Map<Key, Item[]> {\n    const retval = new Map<Key, Item[]>;\n    let idx = 0;\n    for (const item of items) {\n      const key = callbackfn(item, idx++);\n      let list = retval.get(key);\n      if (!list)\n        retval.set(key, list = []);\n      list.push(item);\n    }\n    return retval;\n  };\n\nif (!Object.groupBy)\n  Object.groupBy = function <Item, Key extends string | number | symbol>(items: Iterable<Item>, callbackfn: (item: Item, idx: number) => Key): Partial<Record<Key, Item[]>> {\n    return Object.fromEntries(Map.groupBy(items, callbackfn).entries()) as Partial<Record<Key, Item[]>>;\n  };\n","/* eslint-disable @typescript-eslint/no-loop-func */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-this-alias */\n\n/* Iterator polyfills (https://caniuse.com/?search=iterator) - stage 4 ES but not in all browsers yet\n   Based on https://github.com/alkihis/iterator-polyfill/tree/master but we removed all the AsyncIterator\n   stuff as that's still stage 2 AND not implemented in TypeScript (as of 5.6)\n\n   We're ignoring a few linting/any issues as we really don't care to maintain this much\n   Fixed an issue with .some - reported as https://github.com/alkihis/iterator-polyfill/issues/6\n*/\n\n(function () {\n  // polyfill already applied / proposal implemented\n  if ('Iterator' in globalThis) {\n    return;\n  }\n\n  // Polyfill for Iterator\n  const IteratorPrototype = {};\n\n  const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());\n  const OriginalIteratorPrototype = Object.getPrototypeOf(ArrayIteratorPrototype);\n\n  Object.setPrototypeOf(OriginalIteratorPrototype, IteratorPrototype);\n\n  Object.defineProperties(IteratorPrototype, {\n    [Symbol.iterator]: {\n      value() {\n        return this;\n      }\n    },\n    map: {\n      *value<T, R>(callback: (value: T) => R): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = callback(value.value);\n          const next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    filter: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n          if (callback(real_value)) {\n            next_value = yield real_value;\n            value = it.next(next_value);\n          } else {\n            value = it.next(next_value);\n          }\n        }\n\n        return value.value;\n      },\n    },\n    find: {\n      value<T>(callback: (value: boolean) => T) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            return real_value;\n\n          value = it.next();\n        }\n      }\n    },\n    every: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (!callback(real_value))\n            return false;\n\n          value = it.next();\n        }\n\n        return true;\n      }\n    },\n    some: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value)) {\n            it.return();\n            return true;\n          }\n\n          value = it.next();\n        }\n\n        return false;\n      }\n    },\n    toArray: {\n      value(max_count = Infinity) {\n        const values = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (max_count <= 0)\n            return values;\n\n          values.push(real_value);\n\n          if (max_count !== Infinity)\n            max_count--;\n\n          value = it.next();\n        }\n\n        return values;\n      }\n    },\n    take: {\n      *value(limit: number): Generator<any, any, any> {\n        limit = Number(limit);\n        if (limit < 0)\n          throw new RangeError('Invalid limit.');\n\n        const it = this;\n        let value = it.next();\n        let remaining = limit;\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (remaining <= 0)\n            return;\n\n          next_value = yield real_value;\n          value = it.next(next_value);\n          remaining--;\n        }\n\n        return value.value;\n      },\n    },\n    drop: {\n      *value(limit: number): Generator<any, any, any> {\n        limit = Number(limit);\n        if (limit < 0)\n          throw new RangeError('Invalid limit.');\n\n        const it = this;\n        let value = it.next();\n        let remaining = limit;\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (remaining > 0) {\n            value = it.next(next_value);\n            remaining--;\n            continue;\n          }\n\n          next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    asIndexedPairs: {\n      *value(): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let index = 0;\n\n        while (!value.done) {\n          const real_value = value.value;\n          const next_value = yield [index, real_value];\n          value = it.next(next_value);\n          index++;\n        }\n\n        return value.value;\n      }\n    },\n    flatMap: {\n      *value<T, R extends object>(mapper: (value: T) => IterableIterator<R> | R): Generator<any, any, any> {\n        if (typeof mapper !== 'function') {\n          throw new TypeError('Mapper must be a function.');\n        }\n\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n          const mapped = mapper(real_value);\n\n          if (Symbol.iterator in mapped) {\n            next_value = yield* mapped[Symbol.iterator]();\n          } else {\n            next_value = yield mapped;\n          }\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    reduce: {\n      value<T, V>(reducer: (acc: V, value: T) => V, initial_value?: V) {\n        let acc = initial_value;\n\n        const it = this;\n        if (acc === undefined) {\n          acc = it.next().value;\n        }\n\n        let value = it.next();\n        while (!value.done) {\n          const real_value = value.value;\n\n          acc = reducer(acc!, real_value);\n\n          value = it.next();\n        }\n\n        return acc;\n      }\n    },\n    forEach: {\n      value<T>(callback: (value: T) => any) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          callback(real_value);\n\n          value = it.next();\n        }\n      }\n    },\n    [Symbol.toStringTag]: {\n      value: 'IteratorPrototype'\n    },\n\n    /* OUTSIDE PROPOSAL */\n    count: {\n      value() {\n        let count = 0;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          count++;\n          value = it.next();\n        }\n\n        return count;\n      },\n    },\n    join: {\n      value(string: string) {\n        let final = '';\n        let first = true;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (first) {\n            first = false;\n            final += real_value;\n          } else {\n            final += string + real_value;\n          }\n\n          value = it.next();\n        }\n\n        return final;\n      }\n    },\n    chain: {\n      *value<I>(...iterables: IterableIterator<I>[]) {\n        yield* this;\n\n        for (const it of iterables) {\n          yield* it;\n        }\n      }\n    },\n    zip: {\n      *value<T, O>(...others: IterableIterator<O>[]): Iterator<(T | O)[]> {\n        const it_array = [this, ...others].map((e: any) => Symbol.iterator in e ? e[Symbol.iterator]() : e as Iterator<T | O>);\n        let values = it_array.map(e => e.next());\n        let next_value: any;\n\n        while (values.every(e => !e.done)) {\n          next_value = yield values.map(e => e.value);\n          values = it_array.map(e => e.next(next_value));\n        }\n      },\n    },\n    takeWhile: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            next_value = yield real_value;\n          else\n            return;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    dropWhile: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n        let finished = false;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (!finished && callback(real_value)) {\n            value = it.next(next_value);\n            continue;\n          }\n\n          finished = true;\n          next_value = yield real_value;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    fuse: {\n      *value(): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (real_value !== undefined && real_value !== null)\n            next_value = yield real_value;\n          else\n            return;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    partition: {\n      value<T>(callback: (value: T) => boolean) {\n        const partition1 = [], partition2 = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            partition1.push(real_value);\n          else\n            partition2.push(real_value);\n\n          value = it.next();\n        }\n\n        return [partition1, partition2];\n      },\n    },\n    findIndex: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let i = 0;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            return i;\n\n          value = it.next();\n          i++;\n        }\n\n        return -1;\n      }\n    },\n    max: {\n      value() {\n        let max = -Infinity;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (max < real_value)\n            max = real_value;\n\n          value = it.next();\n        }\n\n        return max;\n      },\n    },\n    min: {\n      value() {\n        let min = Infinity;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (min > real_value)\n            min = real_value;\n\n          value = it.next();\n        }\n\n        return min;\n      },\n    },\n    cycle: {\n      *value(): Generator<any, any, any> {\n        const values = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n          values.push(real_value);\n\n          const next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        while (true) {\n          yield* values;\n        }\n      },\n    },\n  });\n\n  //iterator.from from https://github.com/rauschma/iterator-helpers-polyfill/\n\n  function isObject(value: unknown) {\n    if (value === null) return false;\n    const t = typeof value;\n    return t === 'object' || t === 'function';\n  }\n\n  function GetIteratorFlattenable<T>(obj: Record<symbol, any>): T {\n    if (!isObject(obj)) {\n      throw new TypeError();\n    }\n    const method = obj[Symbol.iterator];\n    let iterator = undefined;\n    if (typeof method !== 'function') {\n      iterator = obj;\n    } else {\n      iterator = method.call(obj);\n    }\n    if (!isObject(iterator)) {\n      throw new TypeError();\n    }\n    return iterator;\n  }\n\n  if (!('Iterator' in globalThis)) {\n    const Iterator = function Iterator() { };\n\n    Iterator.prototype = IteratorPrototype;\n\n    // @ts-expect-error We're still missing From in this poyfill\n    (globalThis).Iterator = Iterator;\n  }\n\n\n  //----- Static method -----\n  // Must be done after Iterator.prototype was set up,\n  // so that `extends Iterator` works below\n\n  class WrappedIterator<T, TReturn = any, TNext = undefined> extends Iterator<T, TReturn, TNext> {\n    #iterator;\n    constructor(iterator: Iterator<T, TReturn, TNext>) {\n      super();\n      this.#iterator = iterator;\n    }\n    override next(...args: [] | [TNext]): any {\n      return this.#iterator.next(...args);\n    }\n    // `async` helps with line (*)\n    override return(value?: TReturn | PromiseLike<TReturn>): any {\n      const returnMethod = this.#iterator.return;\n      if (returnMethod === undefined) {\n        return { done: true, value: value as any }; // (*)\n      }\n      return returnMethod.call(this.#iterator);\n    }\n  }\n\n  function Iterator_from<T>(value: any) {\n    const iterator = GetIteratorFlattenable<Iterator<T>>(value);\n    if (iterator instanceof Iterator) {\n      return iterator;\n    }\n    // `iterator´ does not support the new API – wrap it so that it does\n    return new WrappedIterator(iterator);\n  }\n\n  Object.defineProperty(\n    Iterator, 'from',\n    {\n      writable: true,\n      enumerable: false,\n      configurable: true,\n      value: Iterator_from,\n    }\n  );\n})();\n","type FormValueList = Array<{ name: string; value: string }>;\n\n/** A navigation instruction encapsulates the next step that a client has to take in eg. a login, payment or wizard flow.\n * Use navigateTo to execute a navigation in a browser\n*/\n\nexport type NavigateInstruction =\n  {\n    type: \"redirect\";\n    url: string;\n  } | {\n    type: \"form\";\n    form: {\n      action: string;\n      vars: FormValueList;\n      method?: \"POST\";\n    };\n  } | {\n    type: \"reload\";\n  } | {\n    type: \"postmessage\";\n    message: unknown;\n    target?: \"parent\" | \"opener\";\n  } | {\n    type: \"close\";\n  };\n\nfunction submitForm(action: string, values: FormValueList, method = \"POST\") {\n  const form = document.createElement(\"form\");\n  form.method = method;\n  form.action = action;\n  form.append(...values.map(item => {\n    const input = document.createElement(\"input\");\n    input.type = \"hidden\";\n    input.name = item.name;\n    input.value = item.value;\n    return input;\n  }));\n  document.body.appendChild(form);\n  form.submit();\n}\n\n/** Navigate to a specific URL (may be hookable by other scripts)\n* @param navigation - Target URL or NavigateInstruction\n*/\nexport function navigateTo(navigation: string | NavigateInstruction) {\n  if (typeof window === \"undefined\")\n    throw new Error(`navigateTo() is not available in this environment`);\n\n  if (typeof navigation === \"string\")\n    navigation = { type: \"redirect\", url: navigation };\n\n  switch (navigation.type) {\n    case \"redirect\":\n      {\n        location.href = navigation.url;\n      } break;\n\n    case \"form\":\n      {\n        submitForm(navigation.form.action, navigation.form.vars, navigation.form.method);\n      } break;\n\n    case \"reload\":\n      {\n        window.location.reload();\n      } break;\n\n    case \"postmessage\":\n      {\n        if (!navigation.target || navigation.target === \"parent\")\n          window.parent.postMessage(navigation.message, \"*\");\n        else if (navigation.target === \"opener\") {\n          window.opener.postMessage(navigation.message, \"*\");\n          window.close();\n        } else\n          throw Error(\"Unknown postmessage target '\" + navigation.target + \"' received\");\n      } break;\n\n    case \"close\":\n      {\n        window.close();\n      } break;\n\n    default:\n      throw new Error(`Unknown navigation type '${(navigation as { type: string }).type}'`);\n  }\n}\n","/* Manages the $wh global, an API for just-in-time debugging */\nimport type { DebugRegistry } from \"@webhare/env\";\nimport { debugFlags } from \"./envbackend\";\n\nlet debugRegFinalizer: FinalizationRegistry<{ type: keyof DebugRegistry; key: string }> | undefined;\n\nexport type WHGlobal = DebugRegistry & {\n  debugFlags: typeof debugFlags;\n  /** Global counter to avoid HMRs from duplicating IDs */\n  nextId: number;\n};\n\ndeclare global {\n  var $wh: WHGlobal;\n}\n\nglobalThis.$wh = {\n  debugFlags,\n  nextId: 1\n} satisfies WHGlobal;\n\nexport function addToDebugRegistry<T extends keyof DebugRegistry>(type: T, key: string, value: NonNullable<ReturnType<NonNullable<DebugRegistry[T]>[string][\"deref\"]>>) {\n  const debugRegistry = globalThis.$wh as unknown as DebugRegistry;\n  //@ts-ignore prevents '>   Type '{}' is not assignable to type 'never'. in jssdk builds, probably because noone yet extends DebugRegistry there\n  debugRegistry[type] ||= {};\n  debugRegFinalizer ||= new FinalizationRegistry(({ type: t, key: k }) => {\n    delete debugRegistry![t]?.[k];\n  });\n\n  if (debugRegistry[type][key])\n    console.error(`Debug registry key ${key} already exists, overwriting it`);\n\n  (debugRegistry[type] as Record<string, unknown>)[key] = new WeakRef(value);\n  debugRegFinalizer.register(value, { type, key });\n}\n","import type { FormControlElement } from \"@webhare/dompack\";\n\nexport const CustomEvent = globalThis.CustomEvent;\n/** Wrap an event to ensure it's target is a HTMLElement\n * @typeParam EventType - The expected event type\n * @typeParam CurrentTargetType - The type of the elemnt you're binding the event to. Optional, defaults to HTMLElement\n * @typeParam RelatedTargetType - The type of the elemnt you're binding the event to. Optional, defaults to HTMLElement\n*/\nexport type DocEvent<EventType extends Event, CurrentTargetType extends HTMLElement = HTMLElement, RelatedTargetType extends HTMLElement = HTMLElement> = EventType & {\n  target: HTMLElement;\n  currentTarget: CurrentTargetType;\n  relatedTarget: RelatedTargetType | null;\n};\n\nexport type DomEventOptions =\n  {\n    bubbles?: boolean;\n    cancelable?: boolean;\n    relatedTarget?: EventTarget;\n    detail?: object;\n  };\n\n/** @deprecated Browsers finally have cross-platform event dispatching. Use element.dispatchEvent(new MouseEvent/FocusEvent/CustomEvent) */\nexport function dispatchDomEvent(element: EventTarget, eventtype: string, options?: DomEventOptions) {\n  //see here https://developer.mozilla.org/en-US/docs/Web/Events whether an event is bubbles/cancelabel\n  options = {\n    bubbles: [\n      \"input\", \"change\", \"click\", \"contextmenu\", \"dblclick\",\n      \"reset\", \"submit\"\n    ].includes(eventtype),\n    cancelable: [\n      \"animationstart\", \"animationcancel\", \"animationend\", \"animationiteration\",\n      \"beforeunload\",\n      \"click\", \"contextmenu\", \"dblclick\",\n      \"reset\", \"submit\",\n      \"transitionstart\", \"transitioncancel\", \"transitionend\", \"transitionrun\"\n    ].includes(eventtype),\n    ...options\n  };\n\n  if (!element || !(element as Node).ownerDocument)\n    return true; //the element has left the dom... so there's no more bubbling. just drop it\n\n  //FIXME the load/scroll is buggy and we should be probably be using new Event (but an earlier attempt at that triggered quite a few test failures)\n  const createtype = /*[\"load\",\"scroll\"].includes(eventtype) === \"load\" ? \"UIEvents\" :*/[\"focus\", \"blur\", \"focusin\", \"focusout\"].includes(eventtype) ? \"FocusEvent\" : eventtype === \"click\" ? \"MouseEvents\" : \"HTMLEvents\";\n  //we verified its non-null ness above but TS doesn't really understand that\n  const evt = (element as Node).ownerDocument!.createEvent(createtype);\n  evt.initEvent(eventtype, options.bubbles, options.cancelable);\n  if (options.detail)\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we should just rewrite to new Event\n    (evt as any).detail = options.detail;\n  if (options.relatedTarget) //its a readonly prop, so redefine it\n    Object.defineProperty(evt, 'relatedTarget', { value: options.relatedTarget, writable: false });\n\n  //TODO: Should we keep this code?\n  // @ts-expect-error IScroll is a custom Window property set by IScroll\n  if (eventtype === 'click' && window.IScroll)\n    // @ts-expect-error _constructed is a custom Event property used by IScroll\n    evt._constructed = true; //ensure IScroll doesn't blindly cancel our synthetic clicks\n\n  return element.dispatchEvent(evt);\n}\n\n/** Fire the proper modified events (input and/or change) on the element after changing its value\n * @param element - Element to receive event\n * @deprecated Use changeValue so we can figure out the proper events to fire\n */\nexport function fireModifiedEvents(element: FormControlElement) {\n  element.dispatchEvent(new InputEvent(\"input\"));\n  element.dispatchEvent(new Event(\"change\"));\n}\n\n/** @deprecated Browsers finally have cross-platform event dispatching. Use element.dispatchEvent(new MouseEvent/FocusEvent/CustomEvent) */\nexport function fireHTMLEvent(element: EventTarget, type: string, options?: DomEventOptions) {\n  return dispatchDomEvent(element, type, options);\n}\n\ntype CustomEventParams =\n  {\n    /** Whether this event should bubble up in the DOM */\n    bubbles: boolean;\n    /** Whether this event can be cancelled */\n    cancelable: boolean;\n    /** Custom event information */\n    detail?: unknown;\n    /** Handler to execute if the default isn't prevented by a event listener */\n    defaulthandler?: (evt: CustomEvent) => void;\n  };\n\n/** Fire a custom event\n    @param node - node to fire the event on\n    @param event - event type. You should add this event to the GlobalEventHandlersEventMap for validation in dispatchCustomEvent calls and addEventListener callbacks.\n    @param params - Event options\n    @returns true if the default wasn't prevented\n */\n\nexport function dispatchCustomEvent<K extends string>(\n  node: EventTarget,\n  event: K,\n  params: CustomEventParams & (K extends keyof GlobalEventHandlersEventMap ?\n    GlobalEventHandlersEventMap[K] extends CustomEvent ?\n    { detail: GlobalEventHandlersEventMap[K][\"detail\"] } : unknown : unknown)) {\n\n  if (!params)\n    throw new Error(`Missing dispatchCustomEvent params`);\n  ['bubbles', 'cancelable'].forEach(prop => {\n    if (!(prop in params))\n      throw new Error(`Missing '${prop}' in dispatchCustomEvent params`);\n  });\n\n  const evt = new CustomEvent(event, {\n    bubbles: params.bubbles,\n    cancelable: params.cancelable,\n    detail: params.detail\n  });\n  let defaultaction = true;\n  try {\n    if (!node.dispatchEvent(evt))\n      defaultaction = false; //defaultPrevented is unreliable on IE11, so double check\n  } finally {\n    if (!evt.defaultPrevented && params.defaulthandler && defaultaction) {\n      params.defaulthandler(evt);\n    }\n  }\n  return defaultaction && !evt.defaultPrevented;\n}\n\n/**\n     Change the value of a form element, and fire the correct events as if it were a user change\n *\n    @param element - Element to change\n    @param newvalue - New value\n */\nexport function changeValue(element: FormControlElement, newvalue: string | number | boolean) {\n  if (element.matches(`input[type=radio], input[type=checkbox]`)) {\n    if (Boolean((element as HTMLInputElement).checked) === Boolean(newvalue))\n      return;\n    (element as HTMLInputElement).checked = Boolean(newvalue);\n  } else {\n    //FIXME it's not really clean to assume that this element is changeable - throw for non input/select..\n    const asString = String(newvalue);\n    if ((element as HTMLInputElement).value === asString)\n      return;\n\n    (element as HTMLInputElement).value = String(newvalue);\n  }\n  dispatchDomEvent(element as EventTarget, 'input');\n  dispatchDomEvent(element as EventTarget, 'change');\n}\n\nlet keydata: { mapping: { [key: string]: string } };\n\nfunction initKeyMapping() {\n  keydata =\n  {\n    // Mapping from keyIdentifier/key to key. If not found, translate U+XXXX to the unicode char and return that.\n\n    // List of all current key mappings (and current inconsistencies\n    // at https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values\n    mapping:\n    {\n      \"Del\": \"Delete\", // IE/edge use 'Del' instead of 'Delete'\n      \"Esc\": \"Escape\", // IE/edge use 'Esc' instead of 'Escape'\n      \"OS\": \"Meta\", // Meta key is called OS on IE 9 and Firefox (tested v50)\n      \"Win\": \"Meta\", // Meta key is called Win on IE/Edge\n      \"Scroll\": \"ScrollLock\", // More IE/Edge, from tests\n      \"PrintScreen\": \"Print\", // More IE/Edge, from tests\n      \"MozHomeScreen\": \"GoHome\", // Prior to Firefox 37, the Home button generated a key code of \"Exit\". Starting in Firefox 37, the button generates the key code \"MozHomeScreen\".\n\n      // Internet Explorer 9 and Firefox 36 and earlier return \"Left\", \"Right\", \"Up\", and \"Down\" for the arrow keys, instead of \"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", and \"ArrowDown\".\n      \"Left\": \"ArrowLeft\",\n      \"Right\": \"ArrowRight\",\n      \"Up\": \"ArrowUp\",\n      \"Down\": \"ArrowDown\",\n      // More IE and old Firefox stuff\n      \"Crsel\": \"CrSel\",\n      \"Exsel\": \"ExSel\",\n      \"Nonconvert\": \"NonConvert\",\n      // Internet Explorer 9 and Firefox 36 and earlier report \"Apps\" instead of \"ContextMenu\" for the context menu key.\n      \"Apps\": \"ContextMenu\",\n      // Internet Explorer 9 and Firefox 36 and earlier use \"MediaNextTrack\" and \"MediaPreviousTrack\" instead of \"MediaTrackNext\" and \"MediaTrackPrevious\".\n      \"MediaNextTrack\": \"MediaTrackNext\",\n      \"MediaPreviousTrack\": \"MediaTrackPrevious\",\n      // In Internet Explorer 9, and prior to Firefox 49, \"AudioVolumeUp\", \"AudioVolumeDown\", and \"AudioVolumeMute\" were \"VolumeUp\", \"VolumeDown\", and \"VolumeMute\".\n      // In Firefox 49 they were updated to match the latest specification. The old names are still used on Boot to Gecko.\n      \"VolumeUp\": \"AudioVolumeUp\",\n      \"VolumeDown\": \"AudioVolumeDown\",\n      \"VolumeMute\": \"AudioVolumeMute\",\n      // Firefox added proper support for the \"TV\" key in Firefox 37; before that, this key generated the key code \"Live\".\n      \"Live\": \"TV\",\n      // Internet Explorer 9 and Firefox 36 and earlier identify the zoom toggle button as \"Zoom\". Firefox 37 corrects this to \"ZoomToggle\".\n      \"Zoom\": \"ZoomToggle\",\n      // Internet Explorer 9 and Firefox 36 and earlier use \"SelectMedia\" instead of \"LaunchMediaPlayer\". Firefox 37 through Firefox 48 use \"MediaSelect\". Firefox 49 has been updated to match the latest specification, and to return \"LaunchMediaPlayer\".\n      \"SelectMedia\": \"LaunchMediaPlayer\",\n      \"MediaSelect\": \"LaunchMediaPlayer\",\n      // Google Chrome returns \"LaunchCalculator\" instead of \"LaunchApplication1\". See Chromium bug 612743 for more information.\n      // Google Chrome returns \"LaunchMyComputer\" instead of \"LaunchApplication2\". See Chromium bug 612743 for more information.\n      // (LaunchCalculator and LaunchMyComputer are valid too, so no translation)\n\n      // While older browsers used words like \"Add\", \"Decimal\", \"Multiply\", and so forth modern browsers identify these using the actual character (\"+\", \".\", \"*\", and so forth).\n      \"Multiply\": \"*\",\n      \"Add\": \"+\",\n      \"Divide\": \"/\",\n      \"Subtract\": \"-\",\n      \"Decimal\": \".\", // (mozilla Key_Values doc says depends on region)\n      \"Separator\": \".\", // (mozilla Key_Values doc says depends on region)\n\n      // keyIdenfier spec mapping of non-printable keys: https://www.w3.org/TR/2009/WD-DOM-Level-3-Events-20090908/#keyset-keyidentifiers\n      // Used in safari\n      \"U+0008\": \"Backspace\",\n      \"U+0009\": \"Tab\",\n      \"U+000D\": \"Enter\",\n      \"U+0018\": \"Cancel\",\n      \"U+001B\": \"Escape\",\n      \"U+007F\": \"Delete\",\n      \"U+0300\": \"DeadGrave\",\n      \"U+0301\": \"DeadEacute\",\n      \"U+0302\": \"DeadCircumflex\",\n      \"U+0303\": \"DeadTilde\",\n      \"U+0304\": \"DeadMacron\",\n      \"U+0306\": \"DeadBreve\",\n      \"U+0307\": \"DeadAboveDot\",\n      \"U+0308\": \"DeadUmlaut\",\n      \"U+030A\": \"DeadAboveRing\",\n      \"U+030B\": \"DeadDoubleacute\",\n      \"U+030C\": \"DeadCaron\",\n      \"U+0327\": \"DeadCedilla\",\n      \"U+0328\": \"DeadOgonek\",\n      \"U+0345\": \"DeadIota\",\n      \"U+3099\": \"DeadVoicedSound\",\n      \"U+309A\": \"DeadSemivoicedSound\",\n\n      // keyIdenfier spec mapping to characters: https://www.w3.org/TR/2009/WD-DOM-Level-3-Events-20090908/#keyset-keyidentifiers\n      \"Exclamation\": \"!\",\n      \"DoubleQuote\": \"\\\"\",\n      \"Hash\": \"#\",\n      \"Dollar\": \"$\",\n      \"Ampersand\": \"&\",\n      \"LeftParen\": \"(\",\n      \"RightParen\": \")\",\n      \"Asterisk\": \"*\",\n      \"Plus\": \"+\",\n      \"Percent\": \"%\",\n      \"Comma\": \",\",\n      \"HyphenMinus\": \"-\",\n      \"Period\": \".\",\n      \"Solidus\": \"/\",\n      \"Colon\": \":\",\n      \"Semicolon\": \";\",\n      \"LessThan\": \"<\",\n      \"Equals\": \"=\",\n      \"GreaterThan\": \">\",\n      \"QuestionMark\": \"?\",\n      \"At\": \"@\",\n      \"LeftSquareBracket\": \"[\",\n      \"Backslash\": \"\\\\\",\n      \"RightSquareBracket\": \"]\",\n      \"Circumflex\": \"^\",\n      \"Underscore\": \"_\",\n      \"Grave\": \"`\",\n      \"LeftCurlyBracket\": \"{\",\n      \"Pipe\": \"|\",\n      \"RightCurlyBracket\": \"}\",\n      \"Euro\": \"€\",\n      \"InvertedExclamation\": \"¡\",\n\n      // Safari fixes: viewed in local tests\n      \"U+0010\": \"ContextMenu\"\n    }\n  };\n}\n\nexport type NormalizedKeyboardEvent =\n  {\n    type: string;\n    target: EventTarget | null;\n    key: string;\n    code: string;\n    ctrlKey: boolean;\n    altKey: boolean;\n    location: number;\n    shiftKey: boolean;\n    metaKey: boolean;\n    repeat: boolean;\n    isComposing: boolean;\n  };\n\n/**\n     Returns normalized keyboard event properties, following the current W3C UI Events spec\n *\n    @param evt - Keyboard event\n    @returns Normalized keyboard event data\n */\nexport function normalizeKeyboardEventData(evt: KeyboardEvent): NormalizedKeyboardEvent {\n  // event.key is supported from chrome:51, edge, ff: 29, ie: 9, not in safari\n  // event.keyIdentifier in chrome 26-54, opera 15-41, safara: 5.1\n  // safari doesn't provide either in keypress events, use U+evt.keyCode (uppercase 4-byte hex)\n\n  let key = evt.key;\n  if (!keydata)\n    initKeyMapping();\n  if (keydata.mapping[key])\n    key = keydata.mapping[key];\n  else if (key.startsWith(\"U+\")) // U+xxxx code\n    key = String.fromCodePoint(parseInt(key.substring(2), 16));\n\n  // Seen in chrome 56.0.2924.76 on linux, numpad '.' without numlock returns key \"\\u0000\"\n  if (evt.key === \"\\u0000\" && evt.code === \"NumpadDecimal\")\n    key = \".\";\n\n  return (\n    {\n      type: evt.type,\n      target: evt.target,\n      key: key,\n      code: evt.code || \"Unidentified\",\n      ctrlKey: evt.ctrlKey,\n      altKey: evt.altKey,\n      location: evt.location,\n      shiftKey: evt.shiftKey,\n      metaKey: evt.metaKey,\n      repeat: evt.repeat,\n      isComposing: evt.isComposing\n    });\n}\n\n/**\n * Stop, fully, an event\n *\n * @param event - Event to stop\n */\nexport function stop(event: Event) {\n  event.preventDefault();\n  event.stopImmediatePropagation();\n}\n\n/** Add an event listener to HTMLElements inside a document (which allows us to ensure that 'target' is a HTMLElement for easier typings) */\nexport function addDocEventListener<CurrentTargetType extends HTMLElement, Type extends keyof HTMLElementEventMap>(node: CurrentTargetType, type: Type, listener: (this: CurrentTargetType, ev: DocEvent<HTMLElementEventMap[Type], CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void;\nexport function addDocEventListener<CurrentTargetType extends HTMLElement>(node: CurrentTargetType, type: string, listener: (this: CurrentTargetType, evt: DocEvent<Event, CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void;\n\nexport function addDocEventListener<CurrentTargetType extends HTMLElement>(node: CurrentTargetType, type: string, listener: (this: CurrentTargetType, evt: DocEvent<Event, CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void {\n  node.addEventListener(type, listener as EventListener, options);\n}\n","import { debugFlags } from '@webhare/env';\nimport * as domevents from '../../../modules/system/js/dompack/src/events';\nimport \"@webhare/tsrun/src/polyfills\";\n\nlet locallocks: BusyLock[] = [];\nlet modallocked = false;\nlet uiwatcher: NodeJS.Timeout | null = null;\nlet installedanticancelhandler = false;\n\nlet currentbusymodaldialog: HTMLDialogElement | null = null;\nlet currentbusymodaluserdialog: HTMLDialogElement | null = null;\nlet busymodalcontent: string | HTMLElement | HTMLDialogElement | undefined;\nlet mylockmgr: LockManager | undefined;\n\nexport type BusyModalEvent = CustomEvent<{ show: boolean }>;\n\n// As 'Lock' already exists on the Web (https://developer.mozilla.org/docs/Web/API/Lock) and it's seldom used just use a longer name. Available since WH 5.4\nexport interface UIBusyLock extends Disposable {\n  release(): void;\n  [Symbol.dispose](): void;\n}\n\ndeclare global {\n  interface GlobalEventHandlersEventMap {\n    \"dompack:busymodal\": BusyModalEvent;\n  }\n  interface Window {\n    __dompack_busylockmanager?: LockManager;\n  }\n\n  // __dompack_busylockmanager: LockManager | undefined;  //\n}\n\nfunction getLockmgr(): LockManager {\n  if (!mylockmgr) {\n    mylockmgr = getParentLockManager() || new LockManager;\n    if (typeof window !== \"undefined\")\n      window.__dompack_busylockmanager = mylockmgr;\n  }\n  return mylockmgr;\n}\n\nfunction anyModalLocks() {\n  return locallocks.some(l => l.modal);\n}\n\n/* scheduleCheckUIFree is invoked by release() or when waitUIFree is explicitly called. the call from release() should\n   be a 'fast' path. We schedule a full check for the next tick if there's a chance it might actually find a free UI */\nfunction scheduleCheckUIFree() {\n  if (!uiwatcher && locallocks.length === 0)\n    uiwatcher = setTimeout(() => checkUIFree(), 0);\n}\n\n/* check if the UI is actually free. if so, remove busymodals and resolve waitUIFrees for the benefit of testfw  */\nfunction checkUIFree() {\n  uiwatcher = null;\n\n  if (modallocked && !anyModalLocks()) { //did the last frame-level *modal* lock just get released?\n    modallocked = false;\n    toggleBusyModal(false);\n  }\n\n  if (locallocks.length === 0) {\n    const lockmgr = getLockmgr();\n    lockmgr.busyframes.delete(window); //we won't release our block in the lockmanager until we've had a chance to remove our modal layer\n    lockmgr.checkUIFree(); //to resolve any waitUIFrees. runs in the top-level frame. note that lockmgr cares about ALL ui locks, not just modals\n  }\n}\n\nfunction isDialogElement(el: unknown): boolean {\n  return typeof el === \"object\" && (el as HTMLElement).matches?.(\"dialog\") || false;\n}\n\nfunction checkCancelEvent(evt: Event) {\n  if (modallocked)\n    evt.preventDefault();\n}\n\nfunction toggleBusyModal(show: boolean) {\n  //'islock' is legacy non-camel version. TypeScript typing should help us transition (since 5.3). 'as' shuts up the warning TODO remove 'islock' and the 'as'\n  if (!domevents.dispatchCustomEvent(window, 'dompack:busymodal', { bubbles: true, cancelable: true, detail: { show: show, islock: show } as BusyModalEvent['detail'] }))\n    return; //cancelled!\n\n  if (!installedanticancelhandler) {\n    //capture cancel, as it doesn't bubble up\n    addEventListener(\"cancel\", evt => checkCancelEvent(evt), { capture: true });\n    installedanticancelhandler = true;\n  }\n\n  if (show) {\n    if (isDialogElement(busymodalcontent)) { //the user provided us with an element\n      currentbusymodaluserdialog = busymodalcontent as HTMLDialogElement;\n      currentbusymodaluserdialog.showModal();\n    } else if (busymodalcontent) { //we'll create our own dialog\n      const dialog = document.createElement('dialog');\n      const toembed = typeof busymodalcontent === \"string\" ? document.createTextNode(busymodalcontent) : busymodalcontent.cloneNode(true);\n      dialog.className = \"dompack-busydialog\";\n      dialog.role = \"status\";\n      dialog.ariaLive = \"off\";\n      dialog.append(toembed);\n      document.body.appendChild(dialog);\n      currentbusymodaldialog = dialog;\n      dialog.showModal();\n      return;\n    }\n\n    document.documentElement.classList.add(\"dompack--busymodal\");\n    return;\n  }\n\n  //hiding\n  document.documentElement.classList.remove(\"dompack--busymodal\");\n  if (currentbusymodaluserdialog)\n    currentbusymodaluserdialog.close();\n  if (currentbusymodaldialog) { //we added a dialog to the dom\n    currentbusymodaldialog.close();\n    document.body.removeChild(currentbusymodaldialog);\n    currentbusymodaldialog = null;\n  }\n}\n\nclass LockManager {\n  locks: BusyLock[];\n  busyframes: Set<Window> = new Set;\n  busycounter: number;\n  deferreduipromise: PromiseWithResolvers<boolean> | null;\n\n  //this object is not for external consumption\n  constructor() {\n    this.locks = [];\n    this.busycounter = 0;\n    this.deferreduipromise = null;\n  }\n  add(lock: BusyLock) {\n    this.locks.push(lock);\n    const returnvalue = this.busycounter++;\n    return returnvalue;\n  }\n  release(lock: BusyLock) {\n    const pos = this.locks.indexOf(lock);\n    if (pos === -1) {\n      if (debugFlags.bus) {\n        console.error(\"Duplicate release of busy lock #\" + lock.locknum);\n        console.log(\"Lock allocated:\");\n        console.log(lock.acquirestack);\n        console.log(\"Lock first released:\");\n        console.log(lock.releasestack);\n      }\n      throw new Error(\"Duplicate release of busy lock\");\n    }\n\n    this.locks.splice(pos, 1);\n  }\n  getNumLocks() {\n    return this.locks.length;\n  }\n  //used by child windows to schedule a check in *our* frame (eg before they themselves are unloaded)\n  scheduleCheckUIFree() {\n    scheduleCheckUIFree();\n  }\n  checkUIFree() {\n    if (this.locks.length === 0 && this.busyframes.size === 0 && this.deferreduipromise) {\n      this.deferreduipromise.resolve(true);\n      this.deferreduipromise = null;\n    }\n  }\n  waitUIFree() {\n    if (!this.deferreduipromise)\n      this.deferreduipromise = Promise.withResolvers();\n\n    scheduleCheckUIFree(); //ensures uiwait is released at next tick if no locks are present at all\n    return this.deferreduipromise.promise;\n  }\n  logLocks() {\n    this.locks.forEach(lock => console.log('[bus] lock #' + lock.locknum, lock.acquirestack, lock));\n    console.log(\"[bus] total \" + this.locks.length + \" locks\");\n  }\n  getLockIds() {\n    return this.locks.map(l => \"#\" + l.locknum).join(\", \");\n  }\n}\n\n/** Configure an (accessible) modal dialog\n * @param bmc - What to show in the dialog: either a text or DOM fragment to clone.\n *              If a <dialog> element is passed, this dialog will be used instead of creating a new one.\n */\nexport function setupBusyModal(bmc: NonNullable<typeof busymodalcontent>) {\n  busymodalcontent = bmc;\n}\n\ninterface LockOptions {\n  ///Whether this lock should enable a modality laayer\n  modal?: boolean;\n}\n\nclass BusyLock implements UIBusyLock {\n  modal: boolean;\n  locknum: number;\n  acquirestack: string | undefined;\n  releasestack: string | undefined;\n\n  constructor(options?: LockOptions) {\n    //legacy non-camel name is 'ismodal'\n    this.modal = options?.modal ?? (options as { ismodal?: boolean })?.ismodal ?? false;\n\n    const lockmgr = getLockmgr();\n    this.locknum = lockmgr.add(this);\n    lockmgr.busyframes.add(window);\n    locallocks.push(this);\n\n    if (this.modal && !modallocked) {\n      modallocked = true;\n      toggleBusyModal(true);\n    }\n\n    if (debugFlags.bus) {\n      this.acquirestack = (new Error).stack;\n      console.trace('[bus] Busy lock #' + this.locknum + ' taken. ' + lockmgr.getNumLocks() + \" locks active now: \" + lockmgr.getLockIds());\n    }\n  }\n\n  [Symbol.dispose]() {\n    if (debugFlags.bus)\n      this.releasestack = (new Error).stack;\n\n    const lockmgr = getLockmgr();\n    lockmgr.release(this);\n    const lockpos = locallocks.indexOf(this);\n    locallocks.splice(lockpos, 1);\n\n    if (debugFlags.bus) {\n      console.trace('[bus] Busy lock #' + this.locknum + ' released. ' + lockmgr.getNumLocks() + \" locks active now: \" + lockmgr.getLockIds());\n    }\n\n    scheduleCheckUIFree();\n  }\n\n  release() {\n    this[Symbol.dispose]();\n  }\n}\n\n/** Return a promise resolving as soon as the UI (any accessible frame) is free for at least one tick */\nexport function waitUIFree() {\n  return getLockmgr().waitUIFree();\n}\n\n/**\n     flag userinterface as busy. tests then know not to interact with the UI until the busy flag is released\n *\n    @param options - Options.<br>\n                   - modal: true/false - Whether the lock is a modal lock\n */\nexport function flagUIBusy(options?: LockOptions): UIBusyLock {\n  return new BusyLock(options);\n}\n\nexport function getUIBusyCounter() {\n  return getLockmgr().busycounter;\n}\n\nfunction getParentLockManager(): LockManager | null {\n  try { //we're accessing a parent window, so we may hit security exceptions\n    if (!(window.parent?.__dompack_busylockmanager))\n      return null;\n\n    //if we connected to a parent...  deregister our locks, eg. if parent navigated our frame away\n    window.addEventListener(\"pagehide\", () => {\n      if (debugFlags.bus)\n        console.log(\"[bus] Frame unloading, \" + locallocks.length + \" locks pending.\", locallocks.map(l => \"#\" + l.locknum).join(\", \"), locallocks);\n\n      //switch to local instance in case anyone still tries to touch these locks during unload\n      const lockmgr = getLockmgr();\n      const locallockmgr = new LockManager;\n      locallocks.forEach(lock => { lockmgr.release(lock); locallockmgr.add(lock); });\n      locallocks = [];\n\n      lockmgr.busyframes.delete(window); //explicitly remove us so we won't be waited upon\n      lockmgr.scheduleCheckUIFree();\n      mylockmgr = locallockmgr;\n    });\n\n    return window.parent.__dompack_busylockmanager;\n  } catch (e) {\n    return null;\n  }\n}\n","\n/* Regex to identify dimensionless style sttributes. copied from old version of preact/src/constants.js (MIT)\n   meant to capture:\n  { boxFlex:1, boxFlexGroup:1, columnCount:1, fillOpacity:1, flex:1, flexGrow:1,\n    flexPositive:1, flexShrink:1, flexNegative:1, fontWeight:1, lineClamp:1, lineHeight:1,\n    opacity:1, order:1, orphans:1, strokeOpacity:1, widows:1, zIndex:1, zoom:1\n*/\nconst IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;\n\nexport { qS, qSA } from '@webhare/dompack/src/tree.ts';\n\nfunction generateInsertList(nodes: Array<string | Node>) {\n  if (nodes.length === 1)\n    return typeof nodes[0] === 'string' ? document.createTextNode(nodes[0]) : nodes[0];\n\n  const frag = document.createDocumentFragment();\n  nodes.forEach(node => frag.appendChild(typeof node === 'string' ? document.createTextNode(node) : node));\n  return frag;\n}\n\n/** @deprecated Use node.matches() */\nexport function matches(node: Element, selector: string): boolean {\n  //only invoke 'matches' if it exists. it *should* but past versions of dompack.matches would check for it too (and thus not fail if you passed in a string instead of a Node)\n  return node.matches?.(selector);\n}\n/** @deprecated Use node.closest() */\nexport function closest(node: Element, selector: string) {\n  if (node.closest)\n    return node.closest(selector);\n  //TODO: Warn about out-of-date browser?\n  let testNode: Element | null = node;\n  for (; testNode && !matches(testNode, selector); testNode = testNode.parentElement)\n    /*iterate*/;\n  return testNode;\n}\n//implements contains. TODO we only really need this on IE11, which doesn't consider a text node a child, we can probably fall back to native elsewhere ?\n/** @deprecated Use node.contains() */\nexport function contains(ancestor: Node, child: Node) {\n  if (ancestor.contains)\n    return ancestor.contains(child);\n  //TODO: Warn about out-of-date browser?\n  for (let testNode: Node | null = child; testNode; testNode = testNode.parentNode)\n    if (testNode === ancestor)\n      return true;\n  return false;\n}\n//insert a range of nodes before a node: https://dom.spec.whatwg.org/#dom-childnode-before\n/** @deprecated Use node.before() */\nexport function before(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.before) {\n    node.before(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.insertBefore(generateInsertList(nodes), node);\n}\n//insert a range of nodes after a node: https://dom.spec.whatwg.org/#dom-childnode-after\n/** @deprecated Use node.after() */\nexport function after(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.after) {\n    node.after(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.insertBefore(generateInsertList(nodes), node.nextSibling);\n}\n//replace node with a set of nodes : https://dom.spec.whatwg.org/#dom-childnode-replacewith\n/** @deprecated Use node.replaceWith() */\nexport function replaceWith(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.replaceWith) {\n    node.replaceWith(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.replaceChild(generateInsertList(nodes), node);\n}\n//remove node with a set of nodes : https://dom.spec.whatwg.org/#dom-childnode-remove\n/** @deprecated Use node.remove() */\nexport function remove(node: ChildNode) {\n  if (node.remove) {\n    node.remove();\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.removeChild(node);\n}\n//insert nodes at start: https://dom.spec.whatwg.org/#dom-parentnode-prepend\n/** @deprecated Use node.prepend() */\nexport function prepend(node: ParentNode, ...nodes: Array<string | Node>) {\n  if (node.prepend) {\n    node.prepend(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  node.insertBefore(generateInsertList(nodes), node.firstChild);\n}\n//insert nodes at end: https://dom.spec.whatwg.org/#dom-parentnode-append\n/** @deprecated Use node.append() */\nexport function append(node: ParentNode, ...nodes: Array<string | Node>) {\n  if (node.append) {\n    node.append(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  node.appendChild(generateInsertList(nodes));\n}\n\n/**\n * Toggle a single class\n *\n * @param node - Node to modify\n * @param classname - Class to toggle\n * @param settoggle - true to enable, false to disable, undefined to toggle\n * @deprecated Just use classList.toggle on the node itself\n */\n/** @deprecated Use classList.toggle() */\nexport function toggleClass(node: Element, classname: string, settoggle?: boolean) {\n  if (arguments.length === 2) //in old dompack, 2 argument version toggled and 3 argument version toggled off. match that behavior\n    node.classList.toggle(classname);\n  else\n    node.classList.toggle(classname, settoggle);\n}\n\n/**\n     Toggle classes in a node\n *\n    @param node - Node which classes to toggle\n    @param toggles - Object, all keys will be added/removed based on the truthyness of their values\n */\nexport function toggleClasses(node: Element, toggles: { [key: string]: boolean }) {\n  if (typeof (toggles) !== \"object\")\n    throw new Error(\"Expected an object with keys as classnames\");\n  Object.keys(toggles).forEach(key => node.classList[toggles[key] ? \"add\" : \"remove\"](key));\n}\n\n/* remove the contents of an existing node */\n/** @deprecated Use node.replaceChildren() */\nexport function empty(node: Element) {\n  if (node.replaceChildren) {\n    node.replaceChildren();\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  while (node.lastChild)\n    node.removeChild(node.lastChild);\n}\n\nexport function isDomReady() {\n  //ensure no domready events can run if there will never be a dom\n  return typeof document !== \"undefined\" && (document.readyState === \"interactive\" || document.readyState === \"complete\");\n}\n\n/* run the specified function 'on ready'. adds to DOMContentLoaded if dom is not ready yet. Exceptions/rejections from the ready handler will not be fatal to the rest of code execution */\nexport function onDomReady(callback: () => unknown | Promise<unknown>) {\n  if (isDomReady()) {\n    try {\n      void callback(); //Ignore unhandled rejections\n    } catch (e) { // We don't want our caller to 'stop' due to a domready exception as its usually the toplevel initialization code, so log the exception ourselves\n      void Promise.reject(new Error(\"Synchronous onDomReady handler failed\", { cause: e })); //Let it propagate as a standard unhandled rejection\n    }\n  } else\n    document.addEventListener(\"DOMContentLoaded\", () => void callback());\n}\n\n//parse JSON data, throw with more info on parse failure\nexport function getJSONAttribute<T>(node: Element, attributename: string): T | null {\n  try {\n    if (node.hasAttribute(attributename))\n      return JSON.parse(node.getAttribute(attributename) as string);\n  } catch (e) {\n    console.error(\"JSON parse failure on attribute '\" + attributename + \"' of node\", node);\n    throw e;\n  }\n  return null;\n}\n\n/**\n     Get the base URI of the current document. IE11 doesn't implement document.baseURI\n *\n    @param doc - Document to query. Defaults to window.document\n    @deprecated Use document.baseURI\n */\nexport function getBaseURI(doc: Document | undefined) {\n  if (!doc)\n    doc = window.document;\n  if (doc.baseURI)\n    return doc.baseURI;\n\n  const base = doc.querySelector('base');\n  if (base && base.href)\n    return base.href;\n  return doc.URL;\n}\n\n/**\n     Sets multiple styles on a node, automatically adding 'px' to numbers when appropriate\n    (can be used as replacement for Mootools .setStyles)\n *\n * @param node - Node to update\n * @param value - Styles to set\n */\nexport function setStyles(node: HTMLElement, value?: string | { [key: string]: string | number }) {\n  if (!value)\n    node.style.cssText = '';\n  else if (typeof value === 'string')\n    node.style.cssText = value || '';\n  else {\n    for (const [key, propvalue] of Object.entries(value)) {\n      // for numbers, add 'px' if the constant isn't dimensionless (eg zIndex)\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we don't know which keys will be set\n      (node.style as any)[key] = typeof value[key] === 'number' && IS_NON_DIMENSIONAL.test(key) === false\n        ? propvalue + 'px'\n        : propvalue;\n    }\n  }\n}\n","import * as domtree from './tree';\nimport * as domevents from './events';\n\nexport type TakeFocusEvent = CustomEvent<{ options?: FocusOptions }>;\n\ndeclare global {\n  interface GlobalEventHandlersEventMap {\n    \"dompack:takefocus\": TakeFocusEvent;\n  }\n}\n\ntype RegistrationHandler<E extends Element = HTMLElement> = (node: E, index?: number) => void;\ntype ComponentRegistration<E extends Element = HTMLElement> =\n  {\n    selector: string;\n    handler: RegistrationHandler<E>;\n    index: number;\n    num: number;\n    afterdomready: boolean;\n  };\n\nconst components: Array<ComponentRegistration<Element>> = [];\nconst map = new WeakMap();\n\n//is a node completely in the dom? if we can find a sibling anywhere, it must be closed\nfunction isNodeCompletelyInDom(node: Element | null) {\n  for (; node; node = node.parentElement)\n    if (node.nextSibling)\n      return true;\n  return false;\n}\nfunction processRegistration<E extends Element>(item: E, reg: ComponentRegistration<E>, domready: boolean) {\n  if (!domready && !isNodeCompletelyInDom(item))\n    return; //not safe to register\n\n  if (!map.has(item))\n    map.set(item, [reg.num]);\n  else {\n    const list = map.get(item);\n    if (list.includes(reg.num))\n      return;\n    list.push(reg.num);\n  }\n  reg.handler(item, reg.index++); //note: if an exception is reported from Object.handler,\n}\nfunction applyRegistration<E extends Element>(reg: ComponentRegistration<E>, startnode?: Element) {\n  const domready = domtree.isDomReady();\n  if (reg.afterdomready && !domready)\n    return;\n\n  const items = Array.from((startnode || document).querySelectorAll(reg.selector)) as E[];\n  if (startnode?.matches(reg.selector))\n    items.unshift(startnode as E); //if startnode matches it has to be an E\n\n  items.forEach(item => {\n    try {\n      processRegistration<E>(item, reg, domready);\n    } catch (e) {\n      console.error(\"Exception handling registration of\", item, \"for rule\", reg.selector);\n      console.log(\"Registration\", reg);\n      if (e instanceof Error) {\n        console.log(e, e.stack);\n        if (window.onerror) {\n          // Send to onerror to trigger exception reporting\n          try {\n            // @ts-expect-error: fileName, lineNumber and columnNumber are non-standard\n            window.onerror(e.message, e.fileName || \"\", e.lineNumber || 1, e.columNumber || 1, e);\n          } catch (e2) { }\n        }\n      } else\n        console.log(e);\n    }\n  });\n}\n\n/* A focus implementation that allows the node to intercept focused, allowing eg\n   radio/checkbox replacements to redirect focus but also explicitly preventing\n   focus of a disabled element\n   Returns true when the focus operation was successfull or handled by an event handler.\n   @param node Node to focus\n   @param options.preventScroll Prevent scroll to focused element\n*/\nexport function focus(node: Element, options?: FocusOptions) {\n  if (!domevents.dispatchCustomEvent(node, 'dompack:takefocus', { bubbles: true, cancelable: true, detail: { options } }))\n    return true;\n\n  if (typeof (node as HTMLElement).focus !== \"function\" || (node as HTMLInputElement).disabled)\n    return false;\n\n  (node as HTMLInputElement).focus(options);\n  return true;\n}\n\n/**\n * @param node - Node to show\n * @param options - Scroll options\n * @deprecated invoke scrollIntoView directly  on the nodes\n */\nexport function scrollIntoView(node: Element, options?: ScrollIntoViewOptions) {\n  node.scrollIntoView(options);\n  return true;\n}\n\n/**\n    Register a component for auto-initialization.\n\n    @param selector - Selector the component must match\n    @param handler - Handler\n    @param options - Any unrecognized options are passed to the handler\n\n    The handler will be invoked with two parameters\n    - the node to register\n    - the index of the node (a unique counter for this selector - first is 0)\n */\n\nexport function register<E extends Element = HTMLElement>(selector: string, handler: RegistrationHandler<E>, options?: { afterdomready: boolean }) {\n  const newreg: ComponentRegistration<E> =\n  {\n    selector: selector,\n    handler: handler,\n    index: 0,\n    num: components.length,\n    afterdomready: !options || options.afterdomready\n  };\n  if (components.length === 0 && !domtree.isDomReady()) //first component... we'll need a ready handler\n    domtree.onDomReady(() => registerMissed());\n\n  components.push(newreg as ComponentRegistration<Element>);\n  applyRegistration(newreg);\n}\n\n// register any components we missed on previous scans\nexport function registerMissed(startnode?: Element) {\n  const todo = components.slice(0);\n  todo.forEach(item => applyRegistration(item, startnode));\n}\n","import { buildCookieHeader, type CookieOptions } from '@webhare/dompack/src/cookiebuilder';\nimport { escapeRegExp, parseTyped, stringify } from '@webhare/std';\n\nconst backup: {\n  sessionStorage?: Record<string, string>;\n  localStorage?: Record<string, string>;\n} = {};\ntype BrowserStorage = keyof typeof backup;\n\nexport function listCookies() {\n  return document.cookie.split(';').map(cookie => {\n    const parts = cookie.split('=');\n    return { name: decodeURIComponent(parts[0].trim()), value: decodeURIComponent(parts[1] || '') };\n  });\n}\n\nexport function setCookie(key: string, value: string, options?: CookieOptions) {\n  document.cookie = buildCookieHeader(key, value, options);\n}\n\nexport function getCookie(key: string): string | null {\n  const value = document.cookie.match('(?:^|;)\\\\s*' + escapeRegExp(key) + '=([^;]*)');\n  return (value) ? decodeURIComponent(value[1]) : null;\n}\n\nexport function deleteCookie(key: string, options?: CookieOptions) {\n  setCookie(key, '', { ...options, duration: -1, expires: undefined });\n}\n\nfunction get(storage: BrowserStorage, key: string): unknown | null {\n  let foundvalue: string | undefined | null = backup[storage]?.[key];\n  if (foundvalue) //if it's in the backups storage encoding can't fail either\n    return parseTyped(foundvalue);\n\n  try {\n    foundvalue = window[storage].getItem(key);\n    if (foundvalue)\n      return parseTyped(foundvalue);\n  } catch (e) {\n    //we ignore parse failures\n  }\n  return null;\n}\n\nfunction set(storage: BrowserStorage, key: string, value: unknown) {\n  const tostore = value !== null && value !== undefined ? stringify(value, { typed: true }) : null;\n  try {\n    if (tostore !== null)\n      window[storage].setItem(key, tostore);\n    else\n      window[storage].removeItem(key);\n    return;\n  } catch (e) {\n    //ignore\n  }\n\n  const store = (backup[storage] ||= {});\n  if (tostore !== null)\n    store[key] = tostore;\n  else\n    delete store[key];\n}\n\nexport function getSession<T>(key: string): T | null {\n  return get(\"sessionStorage\", key) as T | null;\n}\nexport function setSession<T>(key: string, value: T | null) {\n  set(\"sessionStorage\", key, value);\n}\nexport function getLocal<T>(key: string): T | null {\n  return get(\"localStorage\", key) as T | null;\n}\nexport function setLocal<T>(key: string, value: T | null) {\n  set(\"localStorage\", key, value);\n}\nexport function listSessionKeys() {\n  try {\n    return Object.keys(window.sessionStorage);\n  } catch (e) {\n    return Object.keys(backup.sessionStorage || {});\n  }\n}\nexport function listLocalKeys() {\n  try {\n    return Object.keys(window.localStorage);\n  } catch (e) {\n    return Object.keys(backup.localStorage || {});\n  }\n}\n","/* Identify devices for the purpose of analytics/tracing\n   NOT a library for feature detection!\n   Originally based on Mootools.Browser\n*/\n\nexport type Platform = \"windows\" | \"ios\" | \"webos\" | \"android\" | \"linux\" | \"mac\" | \"other\";\nexport type Device = \"desktop\" | \"mobile\" | \"tablet\" | \"\";\n\n/** Valid KeyboardEvent.key values (next to 'plain' keys)\n    This list was built from https://www.w3.org/TR/uievents-key/\n    using `console.log([...new Set([...document.querySelectorAll(\".key-table-key .key\")].map(_ => _.textContent))].toSorted().join(' | '))`\n*/\nexport type KeyAttributeValue = \"AVRInput\" | \"AVRPower\" | \"Accept\" | \"Again\" | \"AllCandidates\" | \"Alphanumeric\" | \"Alt\" | \"AltGraph\" | \"AppSwitch\" | \"ArrowDown\" | \"ArrowLeft\" | \"ArrowRight\" | \"ArrowUp\" | \"Attn\" | \"AudioBalanceLeft\" | \"AudioBalanceRight\" | \"AudioBassBoostDown\" | \"AudioBassBoostToggle\" | \"AudioBassBoostUp\" | \"AudioFaderFront\" | \"AudioFaderRear\" | \"AudioSurroundModeNext\" | \"AudioTrebleDown\" | \"AudioTrebleUp\" | \"AudioVolumeDown\" | \"AudioVolumeMute\" | \"AudioVolumeUp\" | \"Backspace\" | \"BrightnessDown\" | \"BrightnessUp\" | \"BrowserBack\" | \"BrowserFavorites\" | \"BrowserForward\" | \"BrowserHome\" | \"BrowserRefresh\" | \"BrowserSearch\" | \"BrowserStop\" | \"Call\" | \"Camera\" | \"CameraFocus\" | \"Cancel\" | \"CapsLock\" | \"ChannelDown\" | \"ChannelUp\" | \"Clear\" | \"Close\" | \"ClosedCaptionToggle\" | \"CodeInput\" | \"ColorF0Red\" | \"ColorF1Green\" | \"ColorF2Yellow\" | \"ColorF3Blue\" | \"ColorF4Grey\" | \"ColorF5Brown\" | \"Compose\" | \"ContextMenu\" | \"Control\" | \"Convert\" | \"Copy\" | \"CrSel\" | \"Cut\" | \"DVR\" | \"Dead\" | \"Delete\" | \"Dimmer\" | \"DisplaySwap\" | \"Eisu\" | \"Eject\" | \"End\" | \"EndCall\" | \"Enter\" | \"EraseEof\" | \"Escape\" | \"ExSel\" | \"Execute\" | \"Exit\" | \"F1\" | \"F10\" | \"F11\" | \"F12\" | \"F2\" | \"F3\" | \"F4\" | \"F5\" | \"F6\" | \"F7\" | \"F8\" | \"F9\" | \"FavoriteClear0\" | \"FavoriteClear1\" | \"FavoriteClear2\" | \"FavoriteClear3\" | \"FavoriteRecall0\" | \"FavoriteRecall1\" | \"FavoriteRecall2\" | \"FavoriteRecall3\" | \"FavoriteStore0\" | \"FavoriteStore1\" | \"FavoriteStore2\" | \"FavoriteStore3\" | \"FinalMode\" | \"Find\" | \"Fn\" | \"FnLock\" | \"GoBack\" | \"GoHome\" | \"GroupFirst\" | \"GroupLast\" | \"GroupNext\" | \"GroupPrevious\" | \"Guide\" | \"GuideNextDay\" | \"GuidePreviousDay\" | \"HangulMode\" | \"HanjaMode\" | \"Hankaku\" | \"HeadsetHook\" | \"Help\" | \"Hibernate\" | \"Hiragana\" | \"HiraganaKatakana\" | \"Home\" | \"Hyper\" | \"Info\" | \"Insert\" | \"InstantReplay\" | \"JunjaMode\" | \"KanaMode\" | \"KanjiMode\" | \"Katakana\" | \"Key11\" | \"Key12\" | \"LastNumberRedial\" | \"LaunchApplication1\" | \"LaunchApplication2\" | \"LaunchCalendar\" | \"LaunchContacts\" | \"LaunchMail\" | \"LaunchMediaPlayer\" | \"LaunchMusicPlayer\" | \"LaunchPhone\" | \"LaunchScreenSaver\" | \"LaunchSpreadsheet\" | \"LaunchWebBrowser\" | \"LaunchWebCam\" | \"LaunchWordProcessor\" | \"Link\" | \"ListProgram\" | \"LiveContent\" | \"Lock\" | \"LogOff\" | \"MailForward\" | \"MailReply\" | \"MailSend\" | \"MannerMode\" | \"MediaApps\" | \"MediaAudioTrack\" | \"MediaClose\" | \"MediaFastForward\" | \"MediaLast\" | \"MediaNextTrack\" | \"MediaPause\" | \"MediaPlay\" | \"MediaPlayPause\" | \"MediaPreviousTrack\" | \"MediaRecord\" | \"MediaRewind\" | \"MediaSkipBackward\" | \"MediaSkipForward\" | \"MediaStepBackward\" | \"MediaStepForward\" | \"MediaStop\" | \"MediaTopMenu\" | \"MediaTrackNext\" | \"MediaTrackPrevious\" | \"Meta\" | \"MicrophoneToggle\" | \"MicrophoneVolumeDown\" | \"MicrophoneVolumeMute\" | \"MicrophoneVolumeUp\" | \"ModeChange\" | \"NavigateIn\" | \"NavigateNext\" | \"NavigateOut\" | \"NavigatePrevious\" | \"New\" | \"NextCandidate\" | \"NextFavoriteChannel\" | \"NextUserProfile\" | \"NonConvert\" | \"Notification\" | \"NumLock\" | \"OnDemand\" | \"Open\" | \"PageDown\" | \"PageUp\" | \"Pairing\" | \"Paste\" | \"Pause\" | \"PinPDown\" | \"PinPMove\" | \"PinPToggle\" | \"PinPUp\" | \"Play\" | \"PlaySpeedDown\" | \"PlaySpeedReset\" | \"PlaySpeedUp\" | \"Power\" | \"PowerOff\" | \"PreviousCandidate\" | \"Print\" | \"PrintScreen\" | \"Process\" | \"Props\" | \"RandomToggle\" | \"RcLowBattery\" | \"RecordSpeedNext\" | \"Redo\" | \"RfBypass\" | \"Romaji\" | \"STBInput\" | \"STBPower\" | \"Save\" | \"ScanChannelsToggle\" | \"ScreenModeNext\" | \"ScrollLock\" | \"Select\" | \"Settings\" | \"Shift\" | \"SingleCandidate\" | \"Soft1\" | \"Soft2\" | \"Soft3\" | \"Soft4\" | \"SpeechCorrectionList\" | \"SpeechInputToggle\" | \"SpellCheck\" | \"SplitScreenToggle\" | \"Standby\" | \"Subtitle\" | \"Super\" | \"Symbol\" | \"SymbolLock\" | \"TV\" | \"TV3DMode\" | \"TVAntennaCable\" | \"TVAudioDescription\" | \"TVAudioDescriptionMixDown\" | \"TVAudioDescriptionMixUp\" | \"TVContentsMenu\" | \"TVDataService\" | \"TVInput\" | \"TVInputComponent1\" | \"TVInputComponent2\" | \"TVInputComposite1\" | \"TVInputComposite2\" | \"TVInputHDMI1\" | \"TVInputHDMI2\" | \"TVInputHDMI3\" | \"TVInputHDMI4\" | \"TVInputVGA1\" | \"TVMediaContext\" | \"TVNetwork\" | \"TVNumberEntry\" | \"TVPower\" | \"TVRadioService\" | \"TVSatellite\" | \"TVSatelliteBS\" | \"TVSatelliteCS\" | \"TVSatelliteToggle\" | \"TVTerrestrialAnalog\" | \"TVTerrestrialDigital\" | \"TVTimer\" | \"Tab\" | \"Teletext\" | \"Undo\" | \"Unidentified\" | \"VideoModeNext\" | \"VoiceDial\" | \"WakeUp\" | \"Wink\" | \"Zenkaku\" | \"ZenkakuHankaku\" | \"ZoomIn\" | \"ZoomOut\" | \"ZoomToggle\";\n\nexport type UserAgentInfo =\n  {\n    /** Browser name, eg 'chrome' or 'firefox' */\n    name: string;\n    /** Browser numeric version (eg 97) */\n    version: number;\n    /** Platform the browser is running on (eg 'windows') */\n    platform: Platform;\n    /** Type of device (eg 'desktop' or 'tablet' for an iPad) */\n    device: Device;\n    /** platform-browsername-version eg ios-safari-11 */\n    triplet: string;\n  };\n\nexport function parseUserAgent(ua: string): UserAgentInfo {\n  ua = ua.toLowerCase();\n\n  // chrome is included in the edge UA, so need to check for edge first, before checking if it's chrome.\n  // safari is included in the miuibrowser UA, so need to check for miuibrowser first, before checking if it's safari.\n  let UA: RegExpMatchArray | null = ua.match(/(edge|miuibrowser)[\\s/:]([\\w\\d.]+)/);\n  if (!UA)\n    UA = ua.match(/(opera|ie|firefox|chrome|trident|crios|version)[\\s/:]([\\w\\d.]+)?.*?(safari|(?:rv[\\s/:]|version[\\s/:])([\\w\\d.]+)|$)/);\n  if (!UA) { //try ios 11.4.1\n    UA = ua.match(/; cpu os ([\\d]+)/);\n    if (UA)\n      UA = ['', 'safari', UA[1]];\n  }\n  if (!UA)\n    UA = ['', 'unknown', \"0\"];\n\n  if (UA[1] === 'trident') {\n    UA[1] = 'ie';\n    if (UA[4]) UA[2] = UA[4];\n  } else if (UA[1] === 'crios') {\n    UA[1] = 'chrome';\n  }\n\n  let platform = ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || ua.match(/mac|win|linux/) || ['other'])[0];\n  if (platform === 'win')\n    platform = 'windows';\n\n  const name = (UA[1] === 'version') ? UA[3] : UA[1];\n  const version = parseInt((UA[1] === 'opera' && UA[4]) ? UA[4] : UA[2]);\n  const device = ua.match(/ipad/) ? 'tablet' : ['ios', 'webos', 'android'].includes(platform) ? 'mobile' : ['mac', 'windows', 'linux'].includes(platform) ? 'desktop' : '';\n\n  return {\n    name,\n    version,\n    platform: platform as Platform,\n    device,\n    triplet: platform + '-' + name + '-' + version\n  };\n}\n\n/**\n * Is the native 'multiselect' modifier for this platform pressed? (Cmd for Mac, Ctrl for Windows/Linux)\n *\n * @param event - Event to check\n */\nexport function isMultiSelectKey(event: KeyboardEvent | MouseEvent): boolean {\n  return getBrowser().platform === 'mac' ? event.metaKey : event.ctrlKey;\n}\n\n/**\n * Is the native 'copy' modifier for this platform pressed?\n *\n * @param event - Event to check\n */\nexport function isCopyKey(event: KeyboardEvent | MouseEvent): boolean {\n  return getBrowser().platform === 'mac' ? event.altKey : event.ctrlKey;\n}\n\nlet browser: Readonly<UserAgentInfo> | undefined;\n\n/** Get browser information */\nexport function getBrowser(): Readonly<UserAgentInfo> {\n  browser ||= Object.freeze(parseUserAgent(globalThis.navigator?.userAgent || \"\"));\n  //Offer this as a function to improve treeshakability\n  return browser;\n}\n\n//CSS Query used to find valid submittors\nexport const submitselector = 'input[type=submit],input[type=image],button[type=submit],button:not([type])';\n//Must match possible types returned by the submitselector\nexport type SubmitSelectorType = HTMLInputElement | HTMLButtonElement;\n","import { isHTMLElement } from \"@webhare/dompack\";\nimport type { CMSConfig } from \"@mod-system/js/internal/generation/gen_misc_ts\";\n\nlet config: CMSConfig | undefined;\n\nfunction forwardPublisherNavigation(event: Event) {\n  /* we watch for clicks.. as we only want to update the Publisher's selection for user triggered actions (otherwise we'd\n     start navigation in response to JS or internal link autoredirects) */\n  if (!isHTMLElement(event.target) || !config?.interfaceServers)\n    return;\n\n  const navaction = event.target.closest<HTMLAnchorElement>('a[href]');\n  if (!navaction)\n    return;\n\n  const desturl = navaction.href;\n  if (desturl.split('#')[0] !== location.href.split('#')[0]) { //it's actual navigation...\n    for (const origin of config.interfaceServers)\n      if (origin.startsWith(document.referrer || ''))\n        try {\n          window.top?.postMessage({ type: \"webhare-navigation\", location: desturl }, origin);\n        } catch (ignore) {\n          //ignore crossdomain errors\n        }\n  }\n}\n\nasync function configureForCMS() {\n  try {\n    const res = await fetch(\"/.wh/ea/config/cms.json\");\n    config = await res.json();\n  } catch (e) {\n    console.log(\"Failed to get CMS configuration\", e);\n    return;\n  }\n  window.addEventListener(\"click\", forwardPublisherNavigation);\n}\n\nif (typeof window !== \"undefined\" && window !== window.top) { //if we're in an iframe, we may be running in WebHare and need to forward navigation events\n  //we have no way to detect whether we're in a WebHare iframe or a 3rd party iframe. assume it's webhare and grab the interface servers\n  void configureForCMS();\n}\n","// The dot lattice behind the page-base login (shell.witty, loginscreen): a slow diagonal wave raises the dots' size and\n// brightness in the brand's login_pattern color. Plain TS, one WebGL shader.\n// data-state on the canvas tells what it does: running, paused (tab hidden), still (reduced motion) or unsupported (no WebGL).\n\nconst VERTEX = \"attribute vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }\";\nconst FRAGMENT = `\nprecision highp float;\nuniform vec2 resolution;\nuniform float time;\nuniform vec3 pattern;\nfloat hash(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }\nfloat noise(vec2 p) {\n  vec2 i = floor(p), f = fract(p);\n  vec2 u = f * f * (3.0 - 2.0 * f);\n  return mix(mix(hash(i), hash(i + vec2(1, 0)), u.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), u.x), u.y);\n}\nvoid main() {\n  float cell = 22.0 * (resolution.y / 900.0) + 10.0;\n  vec2 p = gl_FragCoord.xy / cell;\n  vec2 id = floor(p), f = fract(p) - 0.5;\n  vec2 uv = id * cell / resolution.y;\n  float wave = sin(uv.x * 3.0 + uv.y * 1.6 - time * 0.35) * 0.5 + 0.5;\n  float ripple = noise(uv * 3.0 + time * 0.05);\n  float level = pow(wave, 4.0) * 0.8 + ripple * 0.2;\n  float r = mix(0.06, 0.16, level);\n  float dot = 1.0 - smoothstep(r - 0.03, r, length(f));\n  vec3 c = mix(vec3(0.16), pattern, level) * dot * mix(0.35, 1.0, level);\n  gl_FragColor = vec4(c, 1.0);\n}`;\n\nfunction hexToRgb(color: string): [number, number, number] {\n  // shell.ts always passes the brand's normalized #rrggbb\n  return [1, 3, 5].map(i => Number.parseInt(color.slice(i, i + 2), 16) / 255) as [number, number, number];\n}\n\nfunction start(el: HTMLCanvasElement): void {\n  const gl = el.getContext(\"webgl\", { antialias: false, alpha: false });\n  if (!gl) {\n    el.dataset.state = \"unsupported\"; // the screen stays plain ink\n    return;\n  }\n\n  const compile = (type: number, source: string) => {\n    const shader = gl.createShader(type);\n    if (!shader)\n      throw new Error(\"Could not create a shader\");\n    gl.shaderSource(shader, source);\n    gl.compileShader(shader);\n    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))\n      throw new Error(`Login background shader failed: ${gl.getShaderInfoLog(shader)}`);\n    return shader;\n  };\n  const program = gl.createProgram();\n  if (!program)\n    throw new Error(\"Could not create a shader program\");\n  gl.attachShader(program, compile(gl.VERTEX_SHADER, VERTEX));\n  gl.attachShader(program, compile(gl.FRAGMENT_SHADER, FRAGMENT));\n  gl.linkProgram(program);\n  gl.useProgram(program);\n\n  // One triangle that covers the whole viewport\n  gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());\n  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n  const position = gl.getAttribLocation(program, \"p\");\n  gl.enableVertexAttribArray(position);\n  gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);\n\n  const resolution = gl.getUniformLocation(program, \"resolution\");\n  const time = gl.getUniformLocation(program, \"time\");\n  gl.uniform3fv(gl.getUniformLocation(program, \"pattern\"), hexToRgb(el.dataset.pattern ?? \"\"));\n\n  const still = matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n  const startedAt = performance.now();\n  let frame = 0;\n\n  const draw = (now: number) => {\n    gl.uniform2f(resolution, el.width, el.height);\n    // Start mid-wave, so a reduced-motion still frame shows the pattern and not a blank lattice.\n    gl.uniform1f(time, still ? 20 : (now - startedAt) / 1000 + 20);\n    gl.drawArrays(gl.TRIANGLES, 0, 3);\n  };\n  const loop = (now: number) => {\n    draw(now);\n    frame = requestAnimationFrame(loop);\n  };\n  const resize = () => {\n    const ratio = Math.min(devicePixelRatio, 2);\n    el.width = Math.max(1, Math.round(el.clientWidth * ratio));\n    el.height = Math.max(1, Math.round(el.clientHeight * ratio));\n    gl.viewport(0, 0, el.width, el.height);\n    if (still)\n      draw(performance.now());\n  };\n  const onVisibility = () => {\n    cancelAnimationFrame(frame);\n    if (still)\n      return;\n    const visible = document.visibilityState === \"visible\";\n    if (visible)\n      frame = requestAnimationFrame(loop);\n    el.dataset.state = visible ? \"running\" : \"paused\";\n  };\n\n  new ResizeObserver(resize).observe(el);\n  resize();\n  if (still) {\n    draw(performance.now());\n    el.dataset.state = \"still\";\n  }\n  document.addEventListener(\"visibilitychange\", onVisibility);\n  onVisibility();\n}\n\n// Module scripts run after parsing, so the canvas is there on the login page; every other page skips this.\nconst canvas = document.querySelector<HTMLCanvasElement>(\"canvas[data-companyos-login-background]\");\nif (canvas)\n  start(canvas);\n","var UNKNOWN_FUNCTION = '<unknown>';\n/**\n * This parses the different stack traces and puts them into one format\n * This borrows heavily from TraceKit (https://github.com/csnover/TraceKit)\n */\n\nfunction parse(stackString) {\n  var lines = stackString.split('\\n');\n  return lines.reduce(function (stack, line) {\n    var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);\n\n    if (parseResult) {\n      stack.push(parseResult);\n    }\n\n    return stack;\n  }, []);\n}\nvar chromeRe = /^\\s*at (.*?) ?\\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\\/|[a-z]:\\\\|\\\\\\\\).*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nvar chromeEvalRe = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nfunction parseChrome(line) {\n  var parts = chromeRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line\n\n  var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n  var submatch = chromeEvalRe.exec(parts[2]);\n\n  if (isEval && submatch != null) {\n    // throw out eval line/column and use top-most line/column number\n    parts[2] = submatch[1]; // url\n\n    parts[3] = submatch[2]; // line\n\n    parts[4] = submatch[3]; // column\n  }\n\n  return {\n    file: !isNative ? parts[2] : null,\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: isNative ? [parts[2]] : [],\n    lineNumber: parts[3] ? +parts[3] : null,\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nvar winjsRe = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nfunction parseWinjs(line) {\n  var parts = winjsRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[2],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[3],\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nvar geckoRe = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nvar geckoEvalRe = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nfunction parseGecko(line) {\n  var parts = geckoRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  var isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n  var submatch = geckoEvalRe.exec(parts[3]);\n\n  if (isEval && submatch != null) {\n    // throw out eval line/column and use top-most line number\n    parts[3] = submatch[1];\n    parts[4] = submatch[2];\n    parts[5] = null; // no column when eval\n  }\n\n  return {\n    file: parts[3],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: parts[2] ? parts[2].split(',') : [],\n    lineNumber: parts[4] ? +parts[4] : null,\n    column: parts[5] ? +parts[5] : null\n  };\n}\n\nvar javaScriptCoreRe = /^\\s*(?:([^@]*)(?:\\((.*?)\\))?@)?(\\S.*?):(\\d+)(?::(\\d+))?\\s*$/i;\n\nfunction parseJSC(line) {\n  var parts = javaScriptCoreRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[3],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[4],\n    column: parts[5] ? +parts[5] : null\n  };\n}\n\nvar nodeRe = /^\\s*at (?:((?:\\[object object\\])?[^\\\\/]+(?: \\[as \\S+\\])?) )?\\(?(.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nfunction parseNode(line) {\n  var parts = nodeRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[2],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[3],\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nexport { parse };\n","import * as stacktrace_parser from \"stacktrace-parser\";\n\nexport type StackTraceItem = {\n  filename: string;\n  line: number;\n  col: number;\n  func: string;\n};\n\nexport type StackTrace = StackTraceItem[];\n\nexport function parseTrace(e: Error): StackTrace {\n  if (!e?.stack)\n    return [];\n\n  const trace = stacktrace_parser.parse(e.stack);\n  return trace.map(i => ({ filename: i.file || \"\", line: i.lineNumber || 1, col: i.column || 1, func: (i.methodName || \"\") }));\n}\n\nexport function getStackTrace(): StackTrace {\n  return parseTrace(new Error()).slice(1);\n}\n\nexport function formatTrace(trace: StackTraceItem[]): string {\n  return trace.map(e =>\n    `    at ${e.func} (${e.filename}:${e.line}:${e.col})`).join(\"\\n\");\n}\n\nexport function prependStackTrace(error: Error, trace: StackTrace) {\n  if (!error.stack)\n    return; //no stack to manipulate\n\n  const stacklines = error.stack?.split(\"\\n\") || [];\n  const tracelines = formatTrace(trace);\n  error.stack = (stacklines[0] ? stacklines[0] + \"\\n\" : \"\") + tracelines + '\\n' + (stacklines.slice(1).join(\"\\n\"));\n  return error;\n}\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/jsonrpc-client\" {\n}\n\nimport { debugFlags, backendBase } from \"@webhare/env\";\nimport { type StackTrace, parseTrace, prependStackTrace, type PromisifyInterface } from \"@webhare/js-api-tools\";\n\n//just number RPCs globally instead of per server, makes debug ouput more useful\nlet globalseqnr = 0;\n\nexport interface RPCCallOptions {\n  /** Append function name to URLs. Purely for better logging/visibility as the WebHare JSONRPC server will ignore it */\n  addfunctionname?: boolean;\n  /** Custom URL marker */\n  urlappend?: string;\n  /** Call timeout */\n  timeout?: number;\n  /** Abort signal to cancel the RPC */\n  signal?: AbortSignal;\n  /** Retry on 429 */\n  retry429?: boolean;\n  /** Silent - do not log errors */\n  silent?: boolean;\n  /** Debug (Follows 'rpc' debugflag if not explicity specified) */\n  debug?: boolean;\n  /** Wrap result with response info */\n  wrapresult?: boolean;\n  keepalive?: boolean;\n  /** Headers to submit (Eg Authorization) */\n  headers?: Record<string, string>;\n  /** Base URL for service paths */\n  baseUrl?: string;\n  /** Overide fetch credentials option (defaults to same-origin) */\n  credentials?: RequestCredentials;\n}\n\nexport type RequestID = number | string | null;\n\nexport interface JSONRPCBaseResponse {\n  id: RequestID;\n  debug?: {\n    consoleLog: Array<{\n      //TODO this is Serialized<ConsoleLogItem[]> - should probably rename it to SerializedToJSON and move to std or env ?\n      /** Date when console function was called */\n      when: string;\n      /** `console` method that was called (eg 'log') */\n      method: string;\n      /** Logged data */\n      data: string;\n      /** Location of caller */\n      location?: {\n        filename: string;\n        line: number;\n        col: number;\n        func: string;\n      };\n      /** Codecontext */\n      codeContextId?: string;\n    }>;\n  };\n}\n\nexport interface JSONRPCSuccesfulResponse extends JSONRPCBaseResponse {\n  error: null;\n  result: unknown;\n}\n\nexport interface JSONRPCErrorResponse extends JSONRPCBaseResponse {\n  result: null;\n  error: {\n    code: number;\n    message: string;\n    data?: {\n      trace?: StackTrace;\n    };\n  };\n}\n\nexport type JSONRPCResponse = JSONRPCSuccesfulResponse | JSONRPCErrorResponse;\n\nfunction getDebugAppend() {\n  if (typeof window !== \"undefined\" && typeof window.location !== \"undefined\") {\n    const urldebugvar = new URL(window.location.href).searchParams.get(\"wh-debug\");\n    if (urldebugvar)\n      return '?wh-debug=' + encodeURIComponent(urldebugvar);\n  }\n  return '';\n}\n\nclass ControlledCall {\n  client: RPCClient;\n  options: RPCCallOptions;\n  abortcontroller: AbortController;\n  timeout?: number;\n  _callurl: string;\n  _fetchoptions: RequestInit;\n  promise: Promise<unknown>;\n  timedout?: boolean;\n  aborted?: boolean;\n\n  constructor(client: RPCClient, method: string, stack: StackTrace | null, id: number, options: RPCCallOptions, callurl: string, fetchoptions: RequestInit) {\n    this.client = client;\n    this.options = options;\n\n    // if(options.timeout || options.signal) //as long as rpcResolve exists, we'll ALWAYS need to setup a controller\n    {\n      this.abortcontroller = new AbortController;\n      fetchoptions.signal = this.abortcontroller.signal;\n\n      if (options.timeout && options.timeout > 0) {\n        this.timeout = options.timeout;\n        setTimeout(() => this._handleTimeout(), options.timeout);\n      }\n      if (options.signal) {\n        options.signal.addEventListener(\"abort\", () => this._abort());\n      }\n    }\n\n    this._callurl = callurl;\n    this._fetchoptions = fetchoptions;\n\n    const fetchpromise = fetch(this._callurl, this._fetchoptions);\n    this.promise = this._completeCall(method, stack, id, fetchpromise) as Promise<unknown>;\n  }\n  _handleTimeout() {\n    this.timedout = true;\n    this.abortcontroller.abort();\n  }\n  _abort() {\n    this.aborted = true;\n    this.abortcontroller.abort();\n  }\n\n  async _completeCall(method: string, requestStack: StackTrace | null, id: number, fetchpromise: Promise<Response>) {\n    let response;\n    try {\n      for (; ;) { //loop to handle \"429 Conflict\"s\n        response = await fetchpromise;\n        if (response.status === 429 && !(\"retry429\" in this.options && !this.options.retry429) && response.headers.get(\"Retry-After\")) {\n          const retryafter = parseInt(response.headers.get(\"Retry-After\") || \"\");\n          if (this.client.debug)\n            console.warn(`[rpc] We are being throttled (429 Too Many Requests) - retrying after ${retryafter} seconds`);\n\n          await new Promise(resolve => setTimeout(resolve, retryafter * 1000));\n          fetchpromise = fetch(this._callurl, this._fetchoptions);\n          continue;\n        }\n        break;\n      }\n    } catch (exception) {\n      if (this.client.debug)\n        console.log(`[rpc] #${id} Exception invoking '${method}'`, exception);\n\n      if (this.aborted)\n        throw new Error(`RPC Aborted`);\n      else if (this.timedout)\n        throw new Error(`RPC Timeout: timeout was set to ${this.timeout} milliseconds`);\n      else\n        throw new Error(`RPC Failed: exception: ` + exception);\n    }\n\n    let jsonresponse;\n    try {\n      jsonresponse = await response.json() as JSONRPCResponse;\n      if (jsonresponse?.debug) {\n        if (jsonresponse.debug.consoleLog) {\n          for (const logitem of jsonresponse.debug.consoleLog) {\n            //should we log 'when'? it's getting more and more noisy then though....\n            //TODO should we match the remote's method (after validating) or just keep eveyrthing at 'log' ?\n            console.log(`[remote:${logitem.method}] ${logitem.location ? `${logitem.location.filename.split(\"/\").at(-1)}:${logitem.location.line}: ` : ''}${logitem.data}`);\n          }\n        }\n\n        delete jsonresponse.debug; //reduce noise in later logs\n      }\n\n      if (this.client.debug)\n        console.log(`[rpc] #${id} Received response to '${method}'`, jsonresponse);\n    } catch (exception) {\n      if (this.client.debug)\n        console.warn(`[rpc] #${id} Response was not valid JSON`, exception);\n    }\n\n    if (!jsonresponse)\n      throw new Error(\"RPC Failed: Invalid JSON/RPC response received\");\n\n    if (jsonresponse?.error) {\n      const err = new Error(\"RPC Error: \" + (jsonresponse.error.message || \"Unknown error\"));\n      if (jsonresponse.error.data?.trace) {\n        try {\n          prependStackTrace(err, jsonresponse.error.data.trace);\n        } catch (err2) {\n          //ignore stacktrace manipulation error\n        }\n      }\n\n      if (!this.options.silent)\n        this.client._tryLogError(requestStack, err);\n      throw err;\n    }\n\n    if (response.status === 200 && jsonresponse && jsonresponse.id !== id)\n      throw new Error(\"RPC Failed: Invalid JSON/RPC response received\");\n\n    if (this.options.wrapresult) {\n      return {\n        status: response.status,\n        result: jsonresponse.result || null,\n        error: jsonresponse.error || null,\n        retryafter: response.headers.get(\"Retry-After\") ? parseInt(response.headers.get(\"Retry-After\") || \"\") : null\n      };\n    }\n\n    return jsonresponse.result;\n  }\n}\n\n/** Invokes (WebHare) JSON/RPC\n    @param url - URL to invoke (leave empty or pass no parameters at all to callback to the current page)\n    */\nclass RPCClient {\n  url: string;\n  addfunctionname: boolean;\n  urlappend: string;\n  options: RPCCallOptions;\n  whservicematch: RegExpMatchArray | null;\n\n  constructor(url: string, options?: RPCCallOptions) {\n    this.options = {\n      timeout: 0,\n      debug: false,\n      ...options\n    };\n\n    if (!url)\n      throw new Error(`You must specify either a WebHare service name or a full URL`);\n\n    this.url = url;\n    this.whservicematch = this.url.match(/^([a-z0-9_]+):([a-z0-9_]+)$/);\n    //if shorthand syntax is used, we know we're talking to our local webhare. add function names and the profiling flag if needed\n    this.addfunctionname = this.options.addfunctionname !== undefined ? this.options.addfunctionname : Boolean(this.whservicematch);\n    this.urlappend = this.options.urlappend !== undefined ? this.options.urlappend : this.whservicematch ? getDebugAppend() : \"\";\n  }\n\n  get debug() {\n    return this.options.debug || debugFlags.rpc;\n  }\n\n  _tryLogError(requestStack: StackTrace | null, error: Error) {\n    console.group();\n    console.warn(\"RPC failed:\", error);\n    if (requestStack) {\n      console.warn(\"Stack at calling point\");\n      console.log(requestStack);\n    }\n    console.groupEnd();\n  }\n\n  //calculate the final URL. delayed here so services can be created on import (getDefaultRPCBase may require waiting for service.ready)\n  private getURL() {\n    //wh_services are always in the root (and soon inside /.wh)\n    const url = this.whservicematch ? `/wh_services/${this.whservicematch[1]}/${this.whservicematch[2]}` : this.url;\n    if (url.match(/^https?:\\/\\//))\n      return url;\n\n    if (this.options.baseUrl)\n      return new URL(url, this.options.baseUrl).toString();\n    else if (backendBase)\n      return backendBase + (backendBase.endsWith('/') && url.startsWith('/') ? url.substring(1) : url);\n    else\n      throw new Error(`You must set the baseUrl option when using the JSONRPC Client without a full URL outside Webhare`);\n  }\n\n  invoke(method: string, params: unknown[]) {\n    //build the URL, add profiling and function parameters where needed\n    let callurl = this.getURL();\n    if (this.addfunctionname) //simplifies log analysis, ignored by the server\n      callurl += `/${method}`;\n    callurl += this.urlappend;\n\n    const id = ++globalseqnr;\n    let requestStack: StackTrace | null = null;\n\n    if (this.debug) {\n      requestStack = parseTrace(new Error);\n      console.log(`[rpc] #${id} Invoking '${method}'`, params, callurl);\n    }\n\n    const fetchoptions: RequestInit = {\n      method: \"POST\",\n      credentials: this.options.credentials || 'same-origin', //this is the default since 2017-08-25, but Edge pre-18 is still around and will fail here\n      headers: {\n        \"Accept\": \"application/json\",\n        \"Content-Type\": \"application/json; charset=utf-8\",\n        ...this.options.headers\n      },\n      body: JSON.stringify(\n        {\n          id: id,\n          method: method,\n          params: params || []\n        }),\n      keepalive: Boolean(this.options.keepalive)\n    };\n\n    return new ControlledCall(this, method, requestStack, id, this.options, callurl, fetchoptions).promise;\n  }\n}\n\ntype ServiceBase<T> = {\n  withOptions(options: RPCCallOptions): T & ServiceBase<T>;\n};\n\nclass ServiceProxy<T> {\n  client: RPCClient;\n\n  constructor(client: RPCClient) {\n    this.client = client;\n  }\n\n  get(target: object, prop: string, receiver: unknown) {\n    if (prop === 'withOptions') { //create a withOptions function\n      return (options: RPCCallOptions) => {\n        const newoptions = {\n          ...this.client.options,\n          ...options,\n          headers: { ...this.client.options.headers, ...options.headers }\n        };\n        return createClient<T>(this.client.url, newoptions);\n      };\n    }\n\n    return (...args: unknown[]) => this.client.invoke(prop, args);\n  }\n}\n\n\n/** Creates an async version of the functions in a class\n * @typeParam ServiceType - Type definition of the service class that implements this service.\n*/\ntype ConvertToRPCInterface<ServiceType> = PromisifyInterface<ServiceType, `_${string}` | \"close\" | \"emit\">;\n\n/** Get the client interface type as would be returned by createClient */\nexport type GetClientInterface<Client> = ConvertToRPCInterface<Client> & ServiceBase<ConvertToRPCInterface<Client>>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- If you don't care to type the service, just assume it can do anything\nexport function createClient<Client = any>(servicename: string, options?: RPCCallOptions): GetClientInterface<Client> {\n  const rpcclient = new RPCClient(servicename, options);\n  return new Proxy({}, new ServiceProxy<Client>(rpcclient)) as GetClientInterface<Client>;\n}\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/rpc\" {\n  export interface KnownRPCServices {\n    /* Filled by generated services.ts files */\n  }\n}\n\nimport { debugFlags, backendBase } from \"@webhare/env\";\nimport { type StackTrace, parseTrace, prependStackTrace, type PromisifyInterface } from \"@webhare/js-api-tools\";\nimport { omit, parseTyped, stringify } from \"@webhare/std\";\n\n//Preload interface definitions. To solve this cleaner we would have to do some sort of auto-inject but how to robustly do that accross IDEs/Tscs ?\n\n//@ts-ignore Ignore if it doesn't exist. this line *must* remain a @ts-ignore\nimport type { } from \"@mod-platform/generated/ts/services.ts\";\n//@ts-ignore Ignore if it doesn't exist. this line *must* remain a @ts-ignore\nimport type { } from \"wh:ts/services.ts\";\n\nfunction isAbsolute(url: string) {\n  return url.startsWith(\"http:\") || url.startsWith(\"https:\");\n}\n\nfunction getBaseURL() {\n  if (!backendBase)\n    throw new Error(`You must set the baseUrl option when using the RPC Client outside Webhare`);\n  return isAbsolute(backendBase) ? backendBase : new URL(backendBase, location.origin);\n}\n\nexport interface RPCClientOptions {\n  /** Custom request update. Use to eg. set keepalive or add debug variables to the URL */\n  onBeforeRequest?: (url: URL, requestInit: RequestInit & { headers: Headers }) => void;\n  /** Response callback. Use this if you need to capture details on the incoming respones. May be invoked multiple times per request, eg due to 429 errors! */\n  onResponse?: (response: Response) => void;\n  /** Call timeout */\n  timeout?: number;\n  /** Abort signal to cancel the RPC */\n  signal?: AbortSignal;\n  /** Retry on 429 */\n  retry429?: boolean;\n  /** Silent - do not log errors */\n  silent?: boolean;\n  /** Debug (Follows 'rpc' debugflag if not explicity specified) */\n  debug?: boolean;\n  /** Headers to submit (Eg Authorization) */\n  headers?: Record<string, string>;\n  /** Base URL for service paths */\n  baseUrl?: string;\n}\n\n/** RPC Response format */\nexport type RPCResponse = ({\n  /** Result. Not present if the function didn't return anything */\n  result?: unknown;\n} | {\n  /** Error message */\n  error: string;\n  /** Captured stack trace (if 'etr' debugFlag is set) */\n  trace?: StackTrace;\n}) & {\n  /** Captured console log entries (if 'etr' debugFlag is set) */\n  consoleLog?: Array<{\n    //TODO this is Serialized<ConsoleLogItem[]> - should probably rename it to SerializedToJSON and move to std or env ?\n    /** Date when console function was called */\n    when: string;\n    /** `console` method that was called (eg 'log') */\n    method: string;\n    /** Logged data */\n    data: string;\n    /** Location of caller */\n    location?: {\n      filename: string;\n      line: number;\n      col: number;\n      func: string;\n    };\n    /** Codecontext */\n    codeContextId?: string;\n  }>;\n};\n\nclass ControlledCall {\n  client: RPCClient;\n  options: RPCClientOptions;\n  abortcontroller?: AbortController;\n  timeout?: number;\n  _callurl: string;\n  _fetchoptions: RequestInit;\n  promise: Promise<unknown>;\n  timedout?: boolean;\n  aborted?: boolean;\n\n  constructor(client: RPCClient, method: string, stack: StackTrace | null, options: RPCClientOptions, callurl: URL, fetchoptions: RequestInit) {\n    this.client = client;\n    this.options = options;\n\n    if (options.timeout || options.signal) {\n      this.abortcontroller = new AbortController;\n      fetchoptions.signal = this.abortcontroller.signal;\n\n      if (options.timeout && options.timeout > 0) {\n        this.timeout = options.timeout;\n        setTimeout(() => this._handleTimeout(), options.timeout);\n      }\n      if (options.signal) {\n        options.signal.addEventListener(\"abort\", () => this._abort());\n      }\n    }\n\n    this._callurl = callurl.toString();\n    this._fetchoptions = fetchoptions;\n\n    const fetchpromise = fetch(this._callurl, this._fetchoptions);\n    this.promise = this._completeCall(method, stack, fetchpromise) as Promise<unknown>;\n  }\n  _handleTimeout() {\n    this.timedout = true;\n    this.abortcontroller?.abort();\n  }\n  _abort() {\n    this.aborted = true;\n    this.abortcontroller?.abort();\n  }\n\n  async _completeCall(method: string, requestStack: StackTrace | null, fetchpromise: Promise<Response>) {\n    let response;\n    for (; ;) { //loop to handle \"429 Conflict\"s\n      try { //we should only guard the fetch call and specifically *not* the onResponse callback\n        response = await fetchpromise;\n      } catch (exception) {\n        if (this.client.debug)\n          console.log(`[rpc] Exception invoking '${method}'`, exception);\n\n        if (this.aborted)\n          throw new Error(`RPC Aborted`);\n        else if (this.timedout)\n          throw new Error(`RPC Timeout: timeout was set to ${this.timeout} milliseconds`);\n        else\n          throw new Error(`RPC Failed: exception: ` + exception);\n      }\n\n      this.options.onResponse?.(response); //allow hooks to capture headers\n\n      if (response.status === 429 && !(\"retry429\" in this.options && !this.options.retry429) && response.headers.get(\"Retry-After\")) {\n        const retryafter = parseInt(response.headers.get(\"Retry-After\") || \"\");\n        if (this.client.debug)\n          console.warn(`[rpc] We are being throttled (429 Too Many Requests) - retrying after ${retryafter} seconds`);\n\n        await new Promise(resolve => setTimeout(resolve, retryafter * 1000));\n        fetchpromise = fetch(this._callurl, this._fetchoptions);\n        continue;\n      }\n      break;\n    }\n\n    let jsonresponse: RPCResponse;\n    try {\n      jsonresponse = parseTyped(await response.text());\n      if (jsonresponse.consoleLog) {\n        for (const logitem of jsonresponse.consoleLog) {\n          //should we log 'when'? it's getting more and more noisy then though....\n          //TODO should we match the remote's method (after validating) or just keep everything at 'log' ?\n          console.log(`[remote:${logitem.method}] ${logitem.location ? `${logitem.location.filename.split(\"/\").at(-1)}:${logitem.location.line}: ` : ''}${logitem.data}`);\n        }\n      }\n\n      if (this.client.debug)\n        console.log(`[rpc] Received response to '${method}'`, omit(jsonresponse, [\"consoleLog\", \"trace\"]));\n    } catch (exception) {\n      if (this.client.debug)\n        console.warn(`[rpc] Response was not valid JSON`, exception);\n      throw new Error(\"RPC Failed: Invalid response received\", { cause: exception });\n    }\n\n    if (\"error\" in jsonresponse) {\n      const err = new Error(`RPC Error: ${jsonresponse.error}`);\n      if (jsonresponse.trace) {\n        try {\n          prependStackTrace(err, jsonresponse.trace);\n        } catch (err2) {\n          //ignore stacktrace manipulation error\n        }\n      }\n\n      if (this.options.debug) {\n        console.group();\n        console.warn(\"RPC failed:\", err);\n        if (requestStack) {\n          console.warn(\"Stack at calling point\");\n          console.log(requestStack);\n        }\n        console.groupEnd();\n      }\n\n      throw err;\n    }\n\n    return jsonresponse.result;\n  }\n}\n\nclass RPCClient {\n  readonly url: string;\n  options: RPCClientOptions;\n\n  constructor(url: string, options?: RPCClientOptions) {\n    this.url = url;\n    this.options = {\n      timeout: 0,\n      debug: false,\n      ...options\n    };\n  }\n\n  get debug() {\n    return this.options.debug || debugFlags.rpc;\n  }\n\n  _tryLogError(requestStack: StackTrace | null, error: Error) {\n  }\n\n  invoke(method: string, params: unknown[]) {\n    //build the URL, add profiling and function parameters where needed\n    //We'll delay the baseurl calculation until the first call to allow for the backendBase to be set up\n    const callurl = isAbsolute(this.url) ? new URL(this.url + method) : new URL(this.url + method, this.options.baseUrl || getBaseURL());\n\n    let requestStack: StackTrace | null = null;\n\n    const fetchoptions: RequestInit & { headers: Headers } = {\n      method: \"POST\",\n      headers: new Headers({\n        \"Accept\": \"application/json\",\n        \"Content-Type\": \"application/json; charset=utf-8\",\n        ...this.options.headers\n      }),\n      body: stringify(params, { typed: true }),\n    };\n\n    const pathName = typeof location !== \"undefined\" ? location.pathname : new URL(this.options.baseUrl || getBaseURL()).pathname;\n    if (pathName !== '/')\n      callurl.searchParams.set(\"pathname\", pathName);\n\n    if (this.debug) {\n      requestStack = parseTrace(new Error);\n      console.log(`[rpc] Invoking '${method}'`, params);\n    }\n\n    this.options.onBeforeRequest?.(callurl, fetchoptions);\n    return new ControlledCall(this, method, requestStack, this.options, callurl, fetchoptions).promise;\n  }\n}\n\ntype ServiceBase<T> = {\n  withOptions(options: RPCClientOptions): T & ServiceBase<T>;\n};\n\nclass ServiceProxy<Service extends keyof KnownRPCServices | object> {\n  client: RPCClient;\n\n  constructor(client: RPCClient) {\n    this.client = client;\n  }\n\n  get(target: object, prop: string, receiver: unknown) {\n    if ([\"then\", \"catch\", \"finally\"].includes(prop)) //do not appear like our object is a promise\n      return undefined;\n\n    if (prop === 'withOptions') { //create a withOptions function\n      return (options: RPCClientOptions) => {\n        const newoptions = {\n          ...this.client.options,\n          ...options,\n          headers: { ...this.client.options.headers, ...options.headers }\n        };\n        return rpc(this.client.url as (Service extends keyof KnownRPCServices ? Service : string), newoptions);\n      };\n    }\n\n    return (...args: unknown[]) => this.client.invoke(prop, args);\n  }\n}\n\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- need any to not worry about the actual first arg\ntype OmitFirstArg<F> = F extends (x: any, ...args: infer P) => infer R ? (...args: P) => R : never;\n\nexport type OmitRPCContextArgs<ServiceType> = {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- need any to not worry about the actual first arg\n  [K in keyof ServiceType as ServiceType[K] extends (...a: any) => any ? K : never]: ServiceType[K] extends (...a: any[]) => void ? OmitFirstArg<ServiceType[K]> : never;\n};\n\n\ntype ExtractInterface<Service extends object> = PromisifyInterface<Service> & ServiceBase<PromisifyInterface<Service>>;\n\n/** Get the client interface type as would be returned by createClient\n * @typeParam Service - either the `module:service` name or the interface to implement. If you want to pass the implementation's type you should wrap it into `OmitRPCContextArgs`.\n*/\nexport type GetRPCClientInterface<Service extends (keyof KnownRPCServices) | object> = Service extends keyof KnownRPCServices ? ExtractInterface<OmitRPCContextArgs<KnownRPCServices[Service]>> : Service extends object ? ExtractInterface<Service> : never;\n\n/** Create a WebHare RPC client\n  @param service - URL (https://<ORIGIN>/.wh/rpc/module/service/) or service name (module:service) to invoke\n*/\nexport function rpc<Service extends keyof KnownRPCServices>(service: Service, options?: RPCClientOptions): GetRPCClientInterface<Service>;\nexport function rpc<Service extends keyof KnownRPCServices>(service: string, options?: RPCClientOptions): GetRPCClientInterface<Service>;\nexport function rpc<Service extends object>(service: Service extends keyof KnownRPCServices ? Service : string, options?: RPCClientOptions): GetRPCClientInterface<Service>;\n\nexport function rpc<Service extends keyof KnownRPCServices | object>(service: Service extends keyof KnownRPCServices ? Service : string, options?: RPCClientOptions): GetRPCClientInterface<Service> {\n  //NOTE: needed the separate overloads to get Intellisense to list the known services for createRPClient's first argument\n\n  if (!service)\n    throw new Error(`You must specify either a WebHare rpcService name or a full URL`);\n\n  const servicematch = service.match(/^([a-z0-9_]+):([a-z0-9_]+)$/);\n  if (servicematch)\n    service = `/.wh/rpc/${servicematch[1]}/${servicematch[2]}/` as (Service extends keyof KnownRPCServices ? Service : string);\n  else if (!service.endsWith('/'))\n    throw new Error(`Service URL must end in a slash`);\n\n  const rpcclient = new RPCClient(service, options);\n  return new Proxy({}, new ServiceProxy<GetRPCClientInterface<Service>>(rpcclient)) as GetRPCClientInterface<Service>;\n}\n","import type { NavigateInstruction } from \"@webhare/env\";\n\n/** Login failure reasons that can also be used by custom isLoginDenied checks */\nexport type LoginErrorCode = \"internal-error\" | \"incorrect-login-password\" | \"incorrect-email-password\" | \"account-disabled\" | \"unknown-account\" | \"require-external-login\";\n\n/** Login reasons that require further client side work but are not errors per-se */\nexport type LoginIncompleteCode = \"totp\" | \"incomplete-account\";\n\nexport type LoginTweaks = {\n  /** Limit session duration (development servers only) */\n  limitExpiry?: number;\n  /** Language code */\n  lang?: string;\n};\n\nexport type LoginResult = {\n  loggedIn: boolean;\n  navigateTo: NavigateInstruction;\n} | {\n  loggedIn: false;\n  code: LoginErrorCode;\n  error?: string;\n};\n\nexport type LogoutResult = { success: true } | {\n  error: string;\n  code: LoginErrorCode | LoginIncompleteCode;\n};\n\nexport const PublicCookieSuffix = \"_publicauthdata\";\n\n/* APIs and types shared between the client and server */\nexport function getCompleteAccountNavigation(token: string, pathname: string): NavigateInstruction {\n  return {\n    type: \"redirect\", //TODO or use a \"form\" too? went for a session now as an excursion to followup GET pages is much more likely in this procedure than with totp\n    url: \"/.wh/common/authpages/?wrd_pwdaction=completeaccount&token=\" + encodeURIComponent(token || '') + \"&pathname=\" + encodeURIComponent(pathname)\n  };\n}\n","import { createClient } from \"@webhare/jsonrpc-client\";\nimport { type NavigateInstruction, navigateTo } from \"@webhare/env\";\nimport * as dompack from '@webhare/dompack';\nimport type { LoginOptions } from \"@webhare/auth/src/identity\";\nimport { rpc } from \"@webhare/rpc\";\n\n//NOTE: Do *NOT* load @webhare/frontend or we enforce the new CSS reset!\nimport { getFrontendData } from '@webhare/frontend/src/init';\nimport { PublicCookieSuffix, type LoginErrorCode, type LoginResult, type LoginTweaks } from \"@webhare/auth/src/shared\";\nimport { parseTyped, toSnakeCase, type ToSnakeCase } from \"@webhare/std\";\nimport type WRDAuthenticationProvider from \"@mod-wrd/js/auth\";\nimport type { OAuth2PromptFlag } from \"@webhare/auth/src/oauth2-client\";\n\n/** WRDAuth configuration */\nexport interface WRDAuthOptions {\n  /** Callback that is invoked after a succesful login. If not set the page will be reloaded. */\n  onLogin?: () => Promise<void> | void;\n}\n\nexport interface PublicAuthData {\n  expiresMs: number;\n  userInfo?: object | null;\n  persistent?: boolean;\n}\n\ndeclare module \"@webhare/frontend\" {\n  interface FrontendDataTypes {\n    \"wrd:auth\": {\n      /** WRDAuth cookiename (used to store userinfo and expiry) */\n      cookiename: string;\n    };\n  }\n}\n\ndeclare global {\n  interface Window {\n    $wh$legacyAuthProvider: WRDAuthenticationProvider;\n    triggerWebHareSSO?: (tag: string, options?: SSOLoginOptions) => Promise<void>;\n  }\n}\n\n/** Current authoptions. undefined if setupWRDAuth hasn't been invoked yet */\nlet authOptions: WRDAuthOptions | undefined;\n\n/** Get current login cookie. If empty, wrdauth is not initialized here */\nfunction getCookieName(): string | null {\n  const settings = getFrontendData(\"wrd:auth\", { allowMissing: true });\n  return settings?.cookiename || null;\n}\n\nfunction getAuthLocalData(): PublicAuthData | null {\n  const c = getCookieName();\n  if (!c)\n    return null;\n\n  try {\n    return parseTyped(dompack.getCookie(c + PublicCookieSuffix)!) as PublicAuthData;\n  } catch {\n    return null;\n  }\n}\n\nasync function submitLoginForm(node: HTMLFormElement, event: SubmitEvent) {\n  if (node.propWhFormhandler)\n    return; //already handled by publisher forms so we'll defer to that\n  dompack.stop(event);\n\n  const username = (node.elements.namedItem(\"login\") as HTMLInputElement)?.value;\n  const password = (node.elements.namedItem(\"password\") as HTMLInputElement)?.value;\n  const site = (node.elements.namedItem(\"site\") as HTMLInputElement)?.value || undefined;\n  const returnto = (node.elements.namedItem(\"returnto\") as HTMLInputElement)?.value || undefined;\n  const persistentlogin = (node.elements.namedItem(\"persistent\") as HTMLInputElement)?.checked;\n  if (!login || !password)\n    throw new Error(`submitLoginForm: required elements login/password not set or missing`);\n\n  using lock = dompack.flagUIBusy({ modal: true });\n  void (lock);\n\n  const loginresult = await login(username, password, {\n    persistent: persistentlogin,\n    site,\n    returnTo: returnto ? new URL(returnto, location.href).toString() : location.href.split('#')[0]\n  });\n  if (loginresult.loggedIn) {\n    refreshLoginStatus();\n    if (loginresult.navigateTo.type === \"redirect\" && loginresult.navigateTo.url.split('#')[0] === location.href.split('#')[0]  //stay on same page\n      && authOptions?.onLogin) {\n\n      if (loginresult.navigateTo.url.includes('#')) //execute any #hash instruction\n        history.replaceState(null, \"\", loginresult.navigateTo.url.substring(loginresult.navigateTo.url.indexOf('#')));\n\n      await authOptions.onLogin();\n    } else {\n      //Reload the page to get the new login status - TODO put this behind a 'login state change' event and allow users to cancel it if they can deal with login/logout on-page\n      console.log(\"Post login redirect\", loginresult.navigateTo);\n      navigateTo(loginresult.navigateTo);\n    }\n  } else if (\"navigateTo\" in loginresult) {\n    console.log(\"Login incomplete, redirecting to\", loginresult.navigateTo);\n    navigateTo(loginresult.navigateTo);\n  } else\n    failLogin(loginresult.error ?? loginresult.code, { code: loginresult.code, data: \"\" }, node); //FIXME restore the code & data members from old wrdauth\n}\n\nfunction refreshLoginStatus() {\n  const loggedIn = isLoggedIn();\n  document.documentElement.classList.toggle(\"wh-wrdauth--isloggedin\", loggedIn);\n\n  window.$wh$legacyAuthProvider?.refresh();\n}\n\n/** Return whether a user's currently logged in */\nexport function isLoggedIn(): boolean {\n  return (getAuthLocalData()?.expiresMs || 0) > Date.now();\n}\n\n/** Setup WRDAuth frontend integration */\nexport function setupWRDAuth(options?: WRDAuthOptions) {\n  if (authOptions)\n    throw new Error(`Duplicate setupWRDAuth call`);\n\n  authOptions = { ...options };\n\n  dompack.register<HTMLFormElement>('form.wh-wrdauth__loginform,form.wh-wrdauth-login__form', node => {\n    node.setAttribute(\"data-wh-wrdauth-attached\", \"\");\n    dompack.addDocEventListener(node, \"submit\", evt => submitLoginForm(node, evt));\n  });\n  dompack.register('.wh-wrdauth__logout', node => {\n    function handleLogoutClick(event: Event) {\n      dompack.stop(event);\n\n      //letting rejections escape - our trigger is generally setup in HTML so there's nothing to catch but uncaught rejection handlers anyway\n      if (node instanceof HTMLAnchorElement && node.href && node.href.split('#')[0] !== location.href.split('#')[0]) { //logout link sending you elsewhere\n        void doLogout().then(() => {\n          console.log(\"Logout complete, redirecting to\", node.href);\n          navigateTo({ type: \"redirect\", url: node.href });\n        });\n      } else {\n        void logout(); //TODO what if the logout only changed the anchor? but what's the usecase for that?\n      }\n    }\n\n    dompack.addDocEventListener(node, \"click\", event => handleLogoutClick(event));\n  });\n\n  dompack.onDomReady(() => {\n    if (\"$wh$wrdauth\" in window) {\n      console.error(\"Both setupWRDAuth from @webhare/frontend and @mod-wrd/js/auth are present in this page. Mixing these is not supported!\");\n    }\n  });\n\n  refreshLoginStatus();\n}\n\nfunction failLogin(message: string, response: { code: LoginErrorCode; data: string }, form: HTMLFormElement) {\n  const evtdetail = {\n    message: message,\n    code: response.code,\n    data: response.data\n  };\n\n  const cancelled = !dompack.dispatchCustomEvent(form || document.documentElement, \"wh:wrdauth-loginfailed\", { bubbles: true, cancelable: true, detail: evtdetail });\n  if (!cancelled) {\n    //TODO depending on error we may need to change a different field?\n    const loginfield = dompack.qR<HTMLInputElement>(form, \"input[name=password]\");\n    loginfield.setCustomValidity(message);\n    // loginfield.reportValidity(); //this actually blocks wh-form error handling from showing the error in-page when so desired\n    loginfield.focus();\n  }\n}\n\n/** Retrieve userinfo if set by onFrontendUserInfo in your WRDAuth customizer */\nexport function getUserInfo<T extends object = object>(): T | null {\n  return isLoggedIn() ? getAuthLocalData()?.userInfo as T | null : null;\n}\n\nfunction getLoginTweaks(): LoginTweaks {\n  const tweaks: LoginTweaks = {\n    lang: dompack.getLang().tag\n  };\n\n  const urlvars = new URL(location.href);\n  if (urlvars.searchParams.has(\"wrdauth_limit_expiry\"))\n    tweaks.limitExpiry = parseInt(urlvars.searchParams.get(\"wrdauth_limit_expiry\") || '0') || undefined;\n\n  return tweaks;\n}\n\n/** Implements the common username/password flows */\nexport async function login(username: string, password: string, options: LoginOptions = {}): Promise<LoginResult> {\n  const cookieName = getCookieName();\n  if (!cookieName)\n    throw new Error(\"WRDAuth not initialized, please call setupWRDAuth first and ensure this page has a <wrdauth> rule\");\n\n  const result = await rpc(\"platform:authservice\").login(username, password, cookieName, dompack.getBrowser().triplet, { ...options, ...getLoginTweaks() });\n  if (result.loggedIn && !getAuthLocalData())\n    throw new Error(\"Login succeeded but no auth data was set in the cookie\");\n\n  return result;\n}\n\n/** Execute and verify cookie clearance to prepare for logging out */\nasync function doLogout() {\n  const cookieName = getCookieName();\n  if (!cookieName)\n    throw new Error(\"WRDAuth not initialized, please call setupWRDAuth first and ensure this page has a <wrdauth> rule\");\n\n  await rpc(\"platform:authservice\").logout(cookieName, dompack.getBrowser().triplet);\n\n  if (getAuthLocalData())\n    throw new Error(\"Logged out but we still have auth data in the cookie\");\n}\n\n/** Logout the current user */\nexport async function logout() {\n  await doLogout();\n  console.log(\"Reloading to process the new logged out status\");\n  navigateTo({ type: \"reload\" }); //TODO put this behind a 'login state change' event\n}\n\nexport interface MyService {\n  startLogin2(urlpath: string, tag: string, options: ToSnakeCase<SSOLoginOptions>): Promise<NavigateInstruction>;\n}\n\ninterface SSOLoginOptions {\n  /** @deprecated use prompt: \"none\" from WH6.0 up */\n  passive?: boolean;\n  /** Set the prompt flag for the authorize request */\n  prompt?: OAuth2PromptFlag;\n}\n\nexport function startSSOLogin(tag: string, options?: SSOLoginOptions): Promise<void> {\n  const client = createClient<MyService>(\"wrd:auth\");\n\n  if (options?.passive)\n    options = { prompt: \"none\", ...options, passive: undefined }; //force prompt to none in passive mode, and remove the passive flag since it doesn't mean anything to the server\n\n  const defer = Promise.withResolvers<void>();\n\n  //Launch SSO login for the current page.\n  //TODO also pass getLoginTweaks() at least to OIDC logins as soon as we've ported this to authservice\n  client.startLogin2(location.pathname + location.search + location.hash, tag, toSnakeCase(options) || {}).then(instr => {\n    //we leave the promise unresolved so any busy layers stay active during the actual redirect\n    //TODO can we have navigateTo detect failed navigations so we can throw ?\n    navigateTo(instr);\n  }).catch((e: Error) => {\n    defer.reject(e);\n  });\n\n  return defer.promise;\n}\n\n/** Configure WebHare external auth buttons (even hidden ones) to listen for bookmarklet login requests */\nexport function setupWebHareSSOTrigger(): void {\n  window.triggerWebHareSSO = startSSOLogin;\n}\n","import { qSA } from \"@webhare/dompack\";\nimport { debugFlags } from \"@webhare/env\";\nimport type { FormAnalyticsEvent } from \"@webhare/forms\";\nimport type { DataLayerEntry } from \"./gtm-types\";\nimport { omit } from \"@webhare/std\";\n\ndeclare global {\n  interface Window {\n    /** The google tag manager (GTM) datalayer */\n    dataLayer: DataLayerEntry[]; //technically window.dataLayer may not exist and should be optional, but we already used to declare it as existing from gtm.ts\n  }\n  //It's safer to access dataLayer through globalThis, which will always be available in all environments unlike 'window'\n  var dataLayer: DataLayerEntry[] | undefined;\n}\n\n//ADDME if we ever figure out a bundler trick to flush this command to the top of all imports/loads, that would be great (we could consider *ALWAYS* putting this in the generated startup code, or we'd need to do a tree pre-walk to see if gtm.es is loaded anywhere)\n(globalThis as unknown as Window).dataLayer ||= [];\nlet lastSeen: DataLayerEntry | undefined;\n\nfunction showDataLayerUpdates() {\n  if (!globalThis.dataLayer)\n    return; //not set up (yet?)\n\n  if (debugFlags.anl)\n    globalThis.dataLayer.slice(globalThis.dataLayer.indexOf(lastSeen!) + 1).forEach(entry => console.log(\"[anl] dataLayer.push:\", entry));\n\n  lastSeen = globalThis.dataLayer[globalThis.dataLayer.length - 1];\n}\n\n/** Push to the dataLayer\n * @param vars - The variables to push\n * @param options - Options for the push\n *   timeout Time before any eventCallback is forcibly called (default 200ms)\n*/\nexport function pushToDataLayer(vars: DataLayerEntry, options?: { timeout?: number }) {\n  if (vars.eventCallback) {\n    //we'll wrap the callback into a promise to ensure it's only invoked once\n    const saveCallback = vars.eventCallback;\n\n    //build a promise to invoke the callback, but only once (promises can resolve only once)\n    let newCallback: () => void;\n    void (new Promise<void>(resolve => newCallback = resolve)).then(() => saveCallback());\n\n    //resolve that new promise after either timeout or datalayer signaling completion\n    setTimeout(() => newCallback(), options?.timeout || 200);\n    vars = { ...vars, eventCallback: newCallback! };\n  }\n\n  globalThis.dataLayer?.push(vars);\n  showDataLayerUpdates();\n}\n\nfunction collectFormValues(formnode: HTMLFormElement): Record<string, unknown> {\n  const donefields: Record<string, boolean> = {};\n  const outdata: Record<string, unknown> = {};\n\n  const multifields = qSA<HTMLInputElement>(formnode, 'input[type=radio], input[type=checkbox]');\n  for (const multifield of multifields) {\n    if (!multifield.name || donefields[multifield.name])\n      continue; //we did this one\n\n    donefields[multifield.name] = true;\n\n    let idx = 0;\n    const values = [];\n    const labels = [];\n    const checkboxes = multifields.filter(node => node.name === multifield.name);\n\n    for (const node of checkboxes.filter(cbox => cbox.checked)) {\n      const keyname = 'form_' + multifield.name + (idx ? '_' + idx : '');\n      let labelsfornode = node.dataset.gtmTag || qSA(`label[for=\"${CSS.escape(node.id)}\"]`).map(labelnode => labelnode.textContent).filter(labelnode => Boolean(labelnode)).join(' ');\n      labelsfornode = labelsfornode.trim(); //TODO normalize whitespace\n      outdata[keyname] = node.value;\n      outdata[keyname + '_label'] = labelsfornode;\n\n      ++idx;\n      values.push(node.value);\n      labels.push(labelsfornode);\n    }\n\n    if (values.length) {\n      const allkeyname = 'form_' + multifield.name + '_all';\n      outdata[allkeyname] = values.join(';');\n      outdata[allkeyname + '_label'] = labels.join(';');\n    }\n  }\n\n  for (const field of formnode.querySelectorAll<HTMLSelectElement | HTMLInputElement>('input:not([type=radio]):not([type=checkbox]),select,textarea')) {\n    if (!field.name || donefields[field.name])\n      continue;\n\n    donefields[field.name] = true;\n\n    const val = field.value;\n    outdata['form_' + field.name] = val;\n    if (field.matches('select')) {\n      const opt = (field as HTMLSelectElement).options[(field as HTMLSelectElement).selectedIndex];\n      if (opt)\n        outdata['form_' + field.name + '_label'] = opt.dataset.gtmTag || opt.textContent;\n    }\n  }\n  return outdata;\n}\n\n/** Setup the dataLayer */\nlet didinit: boolean | undefined;\nexport function setupGTM() {\n  if (!didinit) {\n    didinit = true;\n    if (debugFlags.anl)\n      setInterval(showDataLayerUpdates, 100);\n  }\n}\n\n/** Setup dataLayer events for form analytics events\n * @param options - Options for the form analytics setup\n     - `eventPrefix`. Prefix to use. Default is `wh-platform:form_` but existing integrations may (also) require `publisher:form`\n*/\nexport function setupFormAnalyticsForGTM(options?: { eventPrefix: string }): void {\n  setupGTM(); //ensurse the GTM basics are installed\n\n  addEventListener(\"wh:form-analytics\", (e: FormAnalyticsEvent) => {\n    //we use the same prefixing as pxl events would\n    const entry: DataLayerEntry = {\n      event: `${options?.eventPrefix || \"platform:form_\"}${e.detail.event}`\n    };\n\n    for (const [key, val] of Object.entries(e.detail))\n      if (key !== \"event\" && [\"string\", \"number\", \"boolean\"].includes(typeof val))\n        entry[`formmeta_${key}`] = val;\n\n    const form = e.target as HTMLFormElement | undefined;\n    if (form?.dataset.gtmSubmit) {\n      //When set, we push both the form: variable in gtmSubmit and the current form field avlues\n      Object.assign(entry, JSON.parse(form.dataset.gtmSubmit));\n      Object.assign(entry, collectFormValues(form));\n    }\n\n    pushToDataLayer(entry);\n  });\n}\n\nfunction processClickDataLayerTags(event: MouseEvent) {\n  const entry: Record<string, unknown> = {};\n\n  for (let node = event.target as HTMLElement | undefined | null; node; node = node?.parentElement)\n    for (const attr of node.attributes)\n      if (attr.nodeName.startsWith(\"data-wh-datalayer-onclick-\")) {\n        const key = attr.nodeName.substring(26);\n        if (key !== \"__proto__\" && !(key in entry)) //as we're working upwards, don't overwrite already set keys\n          entry[key] = attr.nodeValue || \"\";\n      } else if (attr.nodeName === \"data-wh-datalayer-onclick\") { //JSON setter\n        const data = JSON.parse(attr.nodeValue!);\n        for (const [key, value] of Object.entries(data))\n          if (key !== \"__proto__\" && !(key in entry)) //as we're working upwards, don't overwrite already set keys\n            entry[key] = value;\n      }\n\n  if (Object.keys(entry).length)\n    pushToDataLayer(entry as DataLayerEntry);\n}\n\n/** Setup support for data-wh-datalayer-onclick-xxx=\"yyy\" attributes. When clicking an element with these attributes the JSON from the attribute and all parents are merged together and pushed to the dataLayer  */\nexport function setupDataLayerTags() {\n  //we capture so we can also simply set variables for any existing GTM handlers\n  window.addEventListener(\"click\", processClickDataLayerTags, { capture: true });\n}\n\n/** Get the current variables in the GTM datalayer\n * @param win - The window to get the dataLayer from (default: current window)\n * @return The current variables in the GTM datalayer, merged together from all entries. Note that this is a snapshot and won't update as the dataLayer changes\n*/\nexport function getCurrentDataLayerVariables<DataLayerFormat extends object = Record<string, unknown>>(win: Window = window): DataLayerFormat {\n  const state: DataLayerFormat = {} as DataLayerFormat;\n  if (win.dataLayer)\n    win.dataLayer.forEach(entry =>\n      Object.assign(state, structuredClone(omit(entry, [\"event\", \"eventCallback\", \"gtm.uniqueEventId\"]))));\n  return state;\n}\n","/* To verify tree shaking viability, try:\n   whcd\n   cd whtree\n   echo 'import \"@webhare/frontend\"' | node_modules/.bin/esbuild --loader:.css=empty --tsconfig=tsconfig.json --bundle --minify\n*/\n\n// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/frontend\" {\n}\n\nimport { onDomReady } from \"@webhare/dompack\";\nexport { frontendConfig, getFrontendData, getSiteRoot } from \"./init\";\nexport { startSSOLogin, login, setupWRDAuth, isLoggedIn, logout, getUserInfo, setupWebHareSSOTrigger } from \"./auth\";\nexport { loadAssetPack, setupAuthorMode, type AuthorModeOptions } from \"./authormode\";\nexport { setPxlOptions, sendPxl, getPxlUserId, getPxlSessionId, setupFormAnalytics, type PxlData } from \"./pxl\";\nexport { getRemoteIPAddress, getGeoIPInfo, type GetIPInfoOptions, type GeoIPInfoResult } from \"./analytics\";\nexport { setupGTM, setupFormAnalyticsForGTM, pushToDataLayer, setupDataLayerTags, getCurrentDataLayerVariables } from \"./gtm\";\nexport { setupLinksInNewWindow, type LinkOpenOptions } from \"./linkhandler\";\n\nexport type * from \"./gtm-types\";\n\n// we shouldn't deprecate navigateTo exported from frontend. in fact it makes more sense to export it from frontend than env as it's browser-only\nexport { navigateTo } from \"@webhare/env\";\n\n/** Registry for data we receive from the backend */\nexport interface FrontendDataTypes {\n}\n\n/** Registry for expected PXL formats */\nexport interface PxlDataTypes {\n}\n\n/** Test whether the current page is being iframed in the WebHare test framework */\nexport function isInTestFramework(): boolean {\n  if (window.top !== window) { //in a frame\n    try {\n      if ((window.top as { __testframework?: unknown })?.__testframework)\n        return true;//we're inside a testframe, pretend to be the parent\n    } catch (ignore) {\n    }\n  }\n  return false;\n}\n\nfunction postRenderChecks() {\n  const log = document.getElementById(\"wh-console-log\");\n  if (log) {\n    const logtext = atob(log.textContent || \"\");\n    console.group(\"[etr] Server-side console output\");\n    console.log(logtext);\n    console.groupEnd();\n  }\n}\n\nonDomReady(postRenderChecks);\n","// Password login on a regular page (login.witty): WRDAuth's setupWRDAuth submits the form, this only shows its refusal.\nimport \"./tokens.scss\";\nimport \"./login.scss\";\nimport \"./login-background\";\nimport { startSSOLogin } from \"@webhare/frontend\";\n\n// Unknown account and wrong password read the same, so the form does not reveal which addresses exist.\nconst MESSAGES: Partial<Record<string, string>> = {\n  \"incorrect-login-password\": \"Onjuist e-mailadres of wachtwoord.\",\n  \"incorrect-email-password\": \"Onjuist e-mailadres of wachtwoord.\",\n  \"unknown-account\": \"Onjuist e-mailadres of wachtwoord.\",\n  \"account-disabled\": \"Dit account is uitgeschakeld.\",\n  // The CompanyOS login customizer refuses accounts without the site login right with this code.\n  \"internal-error\": \"Dit account heeft geen toegang.\",\n};\n\naddEventListener(\"wh:wrdauth-loginfailed\", event => {\n  const form = event.target instanceof Element ? event.target.closest<HTMLFormElement>(\".companyos-login__form\") : null;\n  const error = form?.querySelector<HTMLElement>(\"[data-companyos-login-error]\");\n  if (!form || !error)\n    return;\n  event.preventDefault();\n  error.textContent = MESSAGES[(event as CustomEvent<{ code?: string }>).detail?.code ?? \"\"] ?? \"Inloggen is niet gelukt. Probeer het opnieuw.\";\n  error.hidden = false;\n  for (const input of form.querySelectorAll(\"input.companyos-login__input\"))\n    input.setAttribute(\"aria-invalid\", \"true\");\n  form.querySelector<HTMLInputElement>(\"[name=password]\")?.focus();\n});\n\n// Development test logins (`testlogins` in login.witty): fill the real form and let WRDAuth submit it, as the SPA does.\naddEventListener(\"click\", event => {\n  const button = event.target instanceof Element ? event.target.closest<HTMLButtonElement>(\".companyos-login__testlogin[data-login]\") : null;\n  const form = button?.closest(\".companyos-login\")?.querySelector<HTMLFormElement>(\".companyos-login__form\");\n  if (!button || !form)\n    return;\n  form.querySelector<HTMLInputElement>(\"[name=login]\")!.value = button.dataset.login ?? \"\";\n  form.querySelector<HTMLInputElement>(\"[name=password]\")!.value = button.dataset.password ?? \"\";\n  form.requestSubmit();\n});\n\n// Single sign-on buttons (`providers` in login.witty): the platform redirects to the provider and lands on /.wh/common/oauth2/.\naddEventListener(\"click\", event => {\n  const button = event.target instanceof Element ? event.target.closest<HTMLButtonElement>(\"[data-companyos-sso-login]\") : null;\n  if (!button)\n    return;\n  button.disabled = true;\n  // Resolves only on failure: on success the page navigates away. select_account: a shared computer may hold another session.\n  startSSOLogin(button.dataset.companyosSsoLogin!, { prompt: \"select_account\" }).catch(() => {\n    button.disabled = false;\n  });\n});\n\naddEventListener(\"input\", event => {\n  const form = event.target instanceof Element ? event.target.closest<HTMLFormElement>(\".companyos-login__form\") : null;\n  if (!form)\n    return;\n  form.querySelector<HTMLElement>(\"[data-companyos-login-error]\")!.hidden = true;\n  for (const input of form.querySelectorAll(\"input.companyos-login__input\"))\n    input.removeAttribute(\"aria-invalid\");\n});\n","import { register } from \"dompack\";\n\n// WebHare renders array add/delete controls as empty <span>s (publisher/lib/internal/forms/rendering.whlib): no role,\n// no label and no keyboard access. Until the platform renders buttons, give them those here. The platform's own click\n// handler stays in charge of adding and removing rows.\nregister<HTMLElement>(\".wh-form__arrayadd, .wh-form__arraydelete\", node => {\n  node.setAttribute(\"role\", \"button\");\n  node.tabIndex = 0;\n  node.addEventListener(\"keydown\", event => {\n    if (event.key === \"Enter\" || event.key === \" \") {\n      event.preventDefault();\n      node.click();\n    }\n  });\n});\n","// The visitor's confirmed app items, kept per tab so the next page can show its navigation before the app session\n// request returns. shell.witty holds an inline copy of readCachedAppIds that runs before the first paint; keep both in\n// step (test_app_session_cache runs that copy). Convenience only: apps.ts still confirms every page with the server.\n\ntype CacheStorage = Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\">;\n\n/** WRDAuth's public cookie (platform suffix), readable from script and stable for one login. */\nconst PUBLIC_COOKIE_SUFFIX = \"_publicauthdata\";\n\n/** The app ids whose items to show. \"settings\" is the apps-per-user page, so it follows canManageApps. */\nexport function resolveVisibleAppIds({ visibleAppIds, canManageApps }: { visibleAppIds: string[]; canManageApps: boolean }): string[] {\n  return [...visibleAppIds.filter(id => id !== \"settings\"), ...canManageApps ? [\"settings\"] : []];\n}\n\n/** The raw value of the login's public cookie, or \"\" without one: ties a cache entry to one login. */\nexport function publicAuthValue({ cookies, cookieName }: { cookies: string; cookieName: string }): string {\n  const prefix = `${cookieName}${PUBLIC_COOKIE_SUFFIX}=`;\n  return cookieName ? cookies.split(\"; \").find(cookie => cookie.startsWith(prefix))?.slice(prefix.length) ?? \"\" : \"\";\n}\n\nexport function readCachedAppIds({ storage, key, auth }: { storage: CacheStorage; key: string; auth: string }): string[] | null {\n  try {\n    const cached = JSON.parse(storage.getItem(key) || \"null\") as { auth?: unknown; apps?: unknown } | null;\n    return auth && cached?.auth === auth && Array.isArray(cached.apps) ? cached.apps as string[] : null;\n  } catch {\n    return null;\n  }\n}\n\nexport function writeCachedAppIds({ storage, key, auth, appIds }: { storage: CacheStorage; key: string; auth: string; appIds: string[] }): void {\n  try {\n    if (auth)\n      storage.setItem(key, JSON.stringify({ auth, apps: appIds }));\n    else\n      storage.removeItem(key);\n  } catch {\n    // Storage denied: the navigation just waits for the server, as without the cache\n  }\n}\n","import { rpc as createRpcClient, type OmitRPCContextArgs } from \"@webhare/rpc\";\nimport type { RPC } from \"@mod-companyos/js/rpc\";\n\nexport type CompanyosRPC = OmitRPCContextArgs<typeof RPC>;\n\nexport const DEFAULT_SCHEMA = \"companyos:companyos\";\n\nconst client: CompanyosRPC = createRpcClient<CompanyosRPC>(\"companyos:rpc\");\n\nexport function useRpc(): CompanyosRPC {\n  return client;\n}\n","// What a screen last read from the server, kept per tab and per login so the next page view can render it at once and\n// refresh behind it (stale-while-revalidate across full page loads). A display cache only: the server authorizes every\n// read and write again. Screens use it through lib/screen-data.ts; this file has no browser dependencies for the tests.\nimport { parseTyped, stringify } from \"@webhare/std\";\n\nexport interface ReadCacheContext {\n  storage: Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\">;\n  /** Separates the sites on one host. */\n  scope: string;\n  /** The login's public cookie value, or \"\" without a login: an entry is only readable by the login that wrote it. */\n  auth: string;\n}\n\nexport const readCacheKey = ({ scope, name }: { scope: string; name: string }) => `${scope}:read:${name}`;\n\n/** Change `name` when the shape of the data changes: a tab may still hold an entry written by the previous release. */\nexport function readCached<T>({ name, context }: { name: string; context: ReadCacheContext }): T | undefined {\n  const key = readCacheKey({ scope: context.scope, name });\n  try {\n    const raw = context.storage.getItem(key);\n    if (!raw)\n      return undefined;\n    // Typed JSON, as the RPC transport: a Date or Temporal value comes back as one\n    const entry = parseTyped(raw) as { auth?: unknown; data?: unknown } | null;\n    if (context.auth && entry?.auth === context.auth)\n      return entry.data as T;\n    context.storage.removeItem(key);\n  } catch {\n    // Unreadable or denied storage is a miss: the screen waits for the server, as without the cache\n  }\n  return undefined;\n}\n\n/** Removes the screen entries among `keys`: those of one site, or without `scope` (a login page has none) all of them. */\nexport function clearCached({ storage, keys, scope }: { storage: Pick<Storage, \"removeItem\">; keys: string[]; scope?: string }): void {\n  const marker = readCacheKey({ scope: scope ?? \"\", name: \"\" });\n  for (const key of keys)\n    if (scope === undefined ? key.includes(marker) : key.startsWith(marker))\n      storage.removeItem(key);\n}\n\n/** `data: undefined` forgets the entry: for a screen that changed what another screen keeps. */\nexport function writeCached({ name, data, context }: { name: string; data: unknown; context: ReadCacheContext }): void {\n  if (!context.auth)\n    return;\n  try {\n    if (data === undefined)\n      context.storage.removeItem(readCacheKey({ scope: context.scope, name }));\n    else\n      context.storage.setItem(readCacheKey({ scope: context.scope, name }), stringify({ auth: context.auth, data }, { typed: true }));\n  } catch {\n    // Full or denied storage: the next page view just loads without a head start\n  }\n}\n","// The read cache (lib/read-cache.ts) bound to this page: per tab, per site and per login. A screen shows\n// `readScreenData(name)` in its first render and refreshes behind it; every successful read goes back in with\n// `writeScreenData`. `warmOnIntent` fills the cache from the page before, when the visitor points at the link.\nimport { publicAuthValue } from \"./app-session-cache\";\nimport { clearCached, readCached, writeCached, type ReadCacheContext } from \"./read-cache\";\n\nfunction pageContext(): ReadCacheContext | null {\n  // The same per-site key the shell uses for its cached navigation\n  const scope = document.querySelector<HTMLElement>(\"[data-companyos-apps-key]\")?.dataset.companyosAppsKey;\n  if (!scope)\n    return null;\n  try {\n    // Read from the page config as the shell's inline script does: importing @webhare/frontend here would run its\n    // startup in every bundle that only wants the screen parts\n    const config = JSON.parse(document.getElementById(\"wh-config\")?.textContent || \"{}\") as { \"wrd:auth\"?: { cookiename?: string } };\n    return { storage: sessionStorage, scope, auth: publicAuthValue({ cookies: document.cookie, cookieName: config[\"wrd:auth\"]?.cookiename ?? \"\" }) };\n  } catch {\n    return null; // Storage or cookies denied\n  }\n}\n\n/** What this login last read under `name` in this tab, or undefined. Change `name` when the shape of the data changes. */\nexport function readScreenData<T>(name: string): T | undefined {\n  const context = pageContext();\n  return context ? readCached<T>({ name, context }) : undefined;\n}\n\nexport function writeScreenData({ name, data }: { name: string; data: unknown }): void {\n  const context = pageContext();\n  if (context)\n    writeCached({ name, data, context });\n}\n\n/**\n * Drops what screens kept, so nothing readable stays behind after the session ended: this site's entries, or on a\n * page without the site key (the login page) every screen entry in the tab.\n */\nexport function clearScreenData(): void {\n  try {\n    clearCached({ storage: sessionStorage, keys: Object.keys(sessionStorage), scope: document.querySelector<HTMLElement>(\"[data-companyos-apps-key]\")?.dataset.companyosAppsKey });\n  } catch {\n    // Storage denied: nothing was kept either\n  }\n}\n\n/**\n * Runs `warm` once per page view when the visitor points at (hover, keyboard focus, touch) a link matching `selector`\n * that leads to another page. `warm` reads what that page needs and stores it with `writeScreenData`; it must only\n * read, since the visitor may never click.\n */\nexport function warmOnIntent({ selector, warm }: { selector: string; warm: () => Promise<unknown> }): void {\n  let warmed = false;\n  const onIntent = (event: Event): void => {\n    const link = event.target instanceof Element ? event.target.closest<HTMLAnchorElement>(\"a[href]\") : null;\n    if (warmed || !link?.matches(selector) || link.origin !== location.origin || link.pathname === location.pathname)\n      return;\n    warmed = true;\n    // A failed warm-up costs nothing: the page loads as it would have, and the next hover tries again\n    warm().catch(() => { warmed = false; });\n  };\n  for (const type of [\"pointerover\", \"focusin\"])\n    document.addEventListener(type, onIntent, { passive: true });\n}\n","// What the apps-per-user screen shows first: the users and the access of the selected one, under one cache name so\n// the screen (app-access.ts) and the navigation's warm-up (apps.ts) agree.\nimport type { AppUser, UserAppAccess } from \"@mod-companyos/js/app-access\";\nimport { DEFAULT_SCHEMA, useRpc } from \"../lib/rpc\";\nimport { writeScreenData } from \"../lib/screen-data\";\n\nexport const APP_ACCESS_DATA = \"app-access\";\n\nexport interface AppAccessData { users: AppUser[]; access: UserAppAccess }\n\n/** The first selection is the visitor (sysops may manage themselves), else the first user. */\nexport function initialAppUser({ users, userId }: { users: AppUser[]; userId: number }): AppUser | undefined {\n  return users.find(user => user.id === userId) ?? users[0];\n}\n\nexport async function warmAppAccess(userId: number): Promise<void> {\n  const users = await useRpc().listAppUsers({ schema: DEFAULT_SCHEMA });\n  const selected = initialAppUser({ users, userId });\n  if (selected)\n    writeScreenData({ name: APP_ACCESS_DATA, data: { users, access: await useRpc().getUserAppAccess({ schema: DEFAULT_SCHEMA, userId: selected.id }) } satisfies AppAccessData });\n}\n","// The visitor's app session, asked once per document: the navigation (apps.ts) and a screen that needs the same answer\n// share one request, also when two asset packs on a page each bundle the page base.\nimport { DEFAULT_SCHEMA, useRpc, type CompanyosRPC } from \"./rpc\";\n\ntype AppSession = Awaited<ReturnType<CompanyosRPC[\"getAppSession\"]>>;\n\nconst scope = globalThis as { __companyosAppSession?: Promise<AppSession> };\n\nexport function getAppSession(): Promise<AppSession> {\n  // A failed request is forgotten, so a retry asks again\n  return scope.__companyosAppSession ??= useRpc().getAppSession({ schema: DEFAULT_SCHEMA }).catch((error: unknown) => {\n    delete scope.__companyosAppSession;\n    throw error;\n  });\n}\n","/** Reveals registered sections confirmed by the site's authenticated endpoint. This never grants server access. */\nexport function setSettingsAccess(access: Readonly<Record<string, boolean>>): void {\n  const items = [...document.querySelectorAll<HTMLElement>(\"[data-companyos-setting]\")];\n  for (const item of items) {\n    const id = item.dataset.companyosSetting!;\n    if (Object.hasOwn(access, id))\n      item.hidden = access[id] !== true;\n  }\n  for (const group of document.querySelectorAll<HTMLElement>(\"[data-companyos-settings-group]\"))\n    group.hidden = !group.querySelector(\"[data-companyos-setting]:not([hidden])\");\n  const first = items.find(item => !item.hidden);\n  for (const entry of document.querySelectorAll<HTMLElement>(\"[data-companyos-settings-entry]\")) {\n    entry.hidden = !first;\n    if (first)\n      entry.querySelector<HTMLAnchorElement>(\"a\")!.href = (first instanceof HTMLAnchorElement ? first : first.querySelector<HTMLAnchorElement>(\"a\")!).href;\n  }\n  document.documentElement.dataset.companyosSettings = \"ready\";\n}\n","// Navigation that differs per visitor. The published shell and dashboard mark such items with data-companyos-app and\n// hide them; this asks the visitor's app session and reveals the confirmed ones. Convenience only: the server still\n// checks every action. Also forwards an old SPA bookmark (#/ip-toegang) on the dashboard to its page.\nimport { getFrontendData, isLoggedIn } from \"@webhare/frontend\";\nimport { publicAuthValue, resolveVisibleAppIds, writeCachedAppIds } from \"./lib/app-session-cache\";\nimport { warmAppAccess } from \"./app-access/app-access-data\";\nimport { getAppSession } from \"./lib/app-session\";\nimport { clearScreenData, warmOnIntent } from \"./lib/screen-data\";\nimport { setSettingsAccess } from \"./settings\";\n\n/** On `<html>`: \"anonymous\", \"ready\" or \"failed\" once the app items are settled; absent while pending or unused. */\nexport const APPS_STATE_ATTRIBUTE = \"data-companyos-apps\";\n\nasync function revealApps(): Promise<void> {\n  const root = document.documentElement;\n  const items = [...document.querySelectorAll<HTMLElement>(\"[data-companyos-app]\")];\n  // Also on a page without app items, such as the login page a logout lands on\n  if (!isLoggedIn())\n    clearScreenData();\n  // Two asset packs on one page both import the page base; one session request is enough\n  if ((!items.length && !document.querySelector(\"[data-companyos-setting=\\\"app-access\\\"]\")) || root.hasAttribute(APPS_STATE_ATTRIBUTE))\n    return;\n  if (!isLoggedIn()) {\n    // An expired session keeps its public cookie, so the shell may have revealed this login's cached items\n    for (const item of items)\n      item.hidden = true;\n    storeAppIds(null);\n    root.setAttribute(APPS_STATE_ATTRIBUTE, \"anonymous\");\n    return;\n  }\n  root.setAttribute(APPS_STATE_ATTRIBUTE, \"\");\n  try {\n    const { visibleAppIds, canManageApps, userId } = await getAppSession();\n    // \"settings\" is always available in the catalog, but on the page base it is the apps-per-user page: show it only\n    // to who may manage apps (sysop or a declared app manager right), the same check as its RPC.\n    setSettingsAccess({ \"app-access\": canManageApps });\n    if (canManageApps)\n      // The apps-per-user page is reached as a settings section or, on a site without sections, as the app item \"settings\"\n      warmOnIntent({ selector: \"[data-companyos-app=\\\"settings\\\"] a, [data-companyos-settings-entry] a, [data-companyos-setting=\\\"app-access\\\"] a\", warm: () => warmAppAccess(userId) });\n    const appIds = resolveVisibleAppIds({ visibleAppIds, canManageApps });\n    for (const item of items)\n      item.hidden = !appIds.includes(item.dataset.companyosApp!);\n    storeAppIds(appIds);\n    root.setAttribute(APPS_STATE_ATTRIBUTE, \"ready\");\n  } catch (error) {\n    // Hidden again, also what the shell showed from the cache: nobody sees a link the session could not confirm\n    for (const item of items)\n      item.hidden = true;\n    storeAppIds(null);\n    root.setAttribute(APPS_STATE_ATTRIBUTE, \"failed\");\n    console.error(\"Could not load the CompanyOS app session\", error);\n  }\n}\n\n/** Lets the shell's inline script show these items on the next page of this login (lib/app-session-cache.ts). */\nfunction storeAppIds(appIds: string[] | null): void {\n  const key = document.querySelector<HTMLElement>(\"[data-companyos-apps-key]\")?.dataset.companyosAppsKey;\n  if (!key)\n    return;\n  const auth = appIds ? publicAuthValue({ cookies: document.cookie, cookieName: getFrontendData(\"wrd:auth\", { allowMissing: true })?.cookiename ?? \"\" }) : \"\";\n  writeCachedAppIds({ storage: sessionStorage, key, auth, appIds: appIds ?? [] });\n}\n\nconst trimSlashes = (path: string) => path.replace(/^\\/+|\\/+$/g, \"\");\n\n/** The SPA routed on the hash (#/ip-toegang/...); the longest matching dashboard tile path wins. */\nfunction followSpaBookmark(): void {\n  const dashboard = document.querySelector(\"[data-companyos-dashboard]\");\n  if (!dashboard || !location.hash.startsWith(\"#/\"))\n    return;\n  const wanted = trimSlashes(decodeURIComponent(location.hash.slice(2)));\n  const target = [...dashboard.querySelectorAll<HTMLAnchorElement>(\"a[data-companyos-path]\")]\n    .map(link => ({ link, path: trimSlashes(link.dataset.companyosPath!) }))\n    .filter(({ path }) => path && (wanted === path || wanted.startsWith(`${path}/`)))\n    .sort((a, b) => b.path.length - a.path.length)[0];\n  if (target)\n    location.replace(target.link.href);\n}\n\nfunction start() {\n  followSpaBookmark();\n  void revealApps();\n}\n\nif (document.readyState === \"loading\")\n  document.addEventListener(\"DOMContentLoaded\", start, { once: true });\nelse\n  start();\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Whether the current browser supports `adoptedStyleSheets`.\n */\nexport const supportsAdoptingStyleSheets: boolean =\n  global.ShadowRoot &&\n  (global.ShadyCSS === undefined || global.ShadyCSS.nativeShadow) &&\n  'adoptedStyleSheets' in Document.prototype &&\n  'replace' in CSSStyleSheet.prototype;\n\n/**\n * A CSSResult or native CSSStyleSheet.\n *\n * In browsers that support constructible CSS style sheets, CSSStyleSheet\n * object can be used for styling along side CSSResult from the `css`\n * template tag.\n */\nexport type CSSResultOrNative = CSSResult | CSSStyleSheet;\n\nexport type CSSResultArray = Array<CSSResultOrNative | CSSResultArray>;\n\n/**\n * A single CSSResult, CSSStyleSheet, or an array or nested arrays of those.\n */\nexport type CSSResultGroup = CSSResultOrNative | CSSResultArray;\n\nconst constructionToken = Symbol();\n\nconst cssTagCache = new WeakMap<TemplateStringsArray, CSSStyleSheet>();\n\n/**\n * A container for a string of CSS text, that may be used to create a CSSStyleSheet.\n *\n * CSSResult is the return value of `css`-tagged template literals and\n * `unsafeCSS()`. In order to ensure that CSSResults are only created via the\n * `css` tag and `unsafeCSS()`, CSSResult cannot be constructed directly.\n */\nexport class CSSResult {\n  // This property needs to remain unminified.\n  ['_$cssResult$'] = true;\n  readonly cssText: string;\n  private _styleSheet?: CSSStyleSheet;\n  private _strings: TemplateStringsArray | undefined;\n\n  private constructor(\n    cssText: string,\n    strings: TemplateStringsArray | undefined,\n    safeToken: symbol\n  ) {\n    if (safeToken !== constructionToken) {\n      throw new Error(\n        'CSSResult is not constructable. Use `unsafeCSS` or `css` instead.'\n      );\n    }\n    this.cssText = cssText;\n    this._strings = strings;\n  }\n\n  // This is a getter so that it's lazy. In practice, this means stylesheets\n  // are not created until the first element instance is made.\n  get styleSheet(): CSSStyleSheet | undefined {\n    // If `supportsAdoptingStyleSheets` is true then we assume CSSStyleSheet is\n    // constructable.\n    let styleSheet = this._styleSheet;\n    const strings = this._strings;\n    if (supportsAdoptingStyleSheets && styleSheet === undefined) {\n      const cacheable = strings !== undefined && strings.length === 1;\n      if (cacheable) {\n        styleSheet = cssTagCache.get(strings);\n      }\n      if (styleSheet === undefined) {\n        (this._styleSheet = styleSheet = new CSSStyleSheet()).replaceSync(\n          this.cssText\n        );\n        if (cacheable) {\n          cssTagCache.set(strings, styleSheet);\n        }\n      }\n    }\n    return styleSheet;\n  }\n\n  toString(): string {\n    return this.cssText;\n  }\n}\n\ntype ConstructableCSSResult = CSSResult & {\n  new (\n    cssText: string,\n    strings: TemplateStringsArray | undefined,\n    safeToken: symbol\n  ): CSSResult;\n};\n\nconst textFromCSSResult = (value: CSSResultGroup | number) => {\n  // This property needs to remain unminified.\n  if ((value as CSSResult)['_$cssResult$'] === true) {\n    return (value as CSSResult).cssText;\n  } else if (typeof value === 'number') {\n    return value;\n  } else {\n    throw new Error(\n      `Value passed to 'css' function must be a 'css' function result: ` +\n        `${value}. Use 'unsafeCSS' to pass non-literal values, but take care ` +\n        `to ensure page security.`\n    );\n  }\n};\n\n/**\n * Wrap a value for interpolation in a {@linkcode css} tagged template literal.\n *\n * This is unsafe because untrusted CSS text can be used to phone home\n * or exfiltrate data to an attacker controlled site. Take care to only use\n * this with trusted input.\n */\nexport const unsafeCSS = (value: unknown) =>\n  new (CSSResult as ConstructableCSSResult)(\n    typeof value === 'string' ? value : String(value),\n    undefined,\n    constructionToken\n  );\n\n/**\n * A template literal tag which can be used with LitElement's\n * {@linkcode LitElement.styles} property to set element styles.\n *\n * For security reasons, only literal string values and number may be used in\n * embedded expressions. To incorporate non-literal values {@linkcode unsafeCSS}\n * may be used inside an expression.\n */\nexport const css = (\n  strings: TemplateStringsArray,\n  ...values: (CSSResultGroup | number)[]\n): CSSResult => {\n  const cssText =\n    strings.length === 1\n      ? strings[0]\n      : values.reduce(\n          (acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1],\n          strings[0]\n        );\n  return new (CSSResult as ConstructableCSSResult)(\n    cssText,\n    strings,\n    constructionToken\n  );\n};\n\n/**\n * Applies the given styles to a `shadowRoot`. When Shadow DOM is\n * available but `adoptedStyleSheets` is not, styles are appended to the\n * `shadowRoot` to [mimic the native feature](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/adoptedStyleSheets).\n * Note, when shimming is used, any styles that are subsequently placed into\n * the shadowRoot should be placed *before* any shimmed adopted styles. This\n * will match spec behavior that gives adopted sheets precedence over styles in\n * shadowRoot.\n */\nexport const adoptStyles = (\n  renderRoot: ShadowRoot,\n  styles: Array<CSSResultOrNative>\n) => {\n  if (supportsAdoptingStyleSheets) {\n    (renderRoot as ShadowRoot).adoptedStyleSheets = styles.map((s) =>\n      s instanceof CSSStyleSheet ? s : s.styleSheet!\n    );\n  } else {\n    for (const s of styles) {\n      const style = document.createElement('style');\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      const nonce = (global as any)['litNonce'];\n      if (nonce !== undefined) {\n        style.setAttribute('nonce', nonce);\n      }\n      style.textContent = (s as CSSResult).cssText;\n      renderRoot.appendChild(style);\n    }\n  }\n};\n\nconst cssResultFromStyleSheet = (sheet: CSSStyleSheet) => {\n  let cssText = '';\n  for (const rule of sheet.cssRules) {\n    cssText += rule.cssText;\n  }\n  return unsafeCSS(cssText);\n};\n\nexport const getCompatibleStyle =\n  supportsAdoptingStyleSheets ||\n  (NODE_MODE && global.CSSStyleSheet === undefined)\n    ? (s: CSSResultOrNative) => s\n    : (s: CSSResultOrNative) =>\n        s instanceof CSSStyleSheet ? cssResultFromStyleSheet(s) : s;\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * Use this module if you want to create your own base class extending\n * {@link ReactiveElement}.\n * @packageDocumentation\n */\n\nimport {\n  getCompatibleStyle,\n  adoptStyles,\n  CSSResultGroup,\n  CSSResultOrNative,\n} from './css-tag.js';\nimport type {\n  ReactiveController,\n  ReactiveControllerHost,\n} from './reactive-controller.js';\n\n// In the Node build, this import will be injected by Rollup:\n// import {HTMLElement, customElements} from '@lit-labs/ssr-dom-shim';\n\nexport * from './css-tag.js';\nexport type {\n  ReactiveController,\n  ReactiveControllerHost,\n} from './reactive-controller.js';\n\n/**\n * Removes the `readonly` modifier from properties in the union K.\n *\n * This is a safer way to cast a value to a type with a mutable version of a\n * readonly field, than casting to an interface with the field re-declared\n * because it preserves the type of all the fields and warns on typos.\n */\ntype Mutable<T, K extends keyof T> = Omit<T, K> & {\n  -readonly [P in keyof Pick<T, K>]: P extends K ? T[P] : never;\n};\n\n// TODO (justinfagnani): Add `hasOwn` here when we ship ES2022\nconst {\n  is,\n  defineProperty,\n  getOwnPropertyDescriptor,\n  getOwnPropertyNames,\n  getOwnPropertySymbols,\n  getPrototypeOf,\n} = Object;\n\nconst NODE_MODE = false;\n\n// Lets a minifier replace globalThis references with a minified name\nconst global = globalThis;\n\nif (NODE_MODE) {\n  global.customElements ??= customElements;\n}\n\nconst DEV_MODE = true;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nconst trustedTypes = (global as unknown as {trustedTypes?: {emptyScript: ''}})\n  .trustedTypes;\n\n// Temporary workaround for https://crbug.com/993268\n// Currently, any attribute starting with \"on\" is considered to be a\n// TrustedScript source. Such boolean attributes must be set to the equivalent\n// trusted emptyScript value.\nconst emptyStringForBooleanAttribute = trustedTypes\n  ? (trustedTypes.emptyScript as unknown as '')\n  : '';\n\nconst polyfillSupport = DEV_MODE\n  ? global.reactiveElementPolyfillSupportDevMode\n  : global.reactiveElementPolyfillSupport;\n\nif (DEV_MODE) {\n  // Ensure warnings are issued only 1x, even if multiple versions of Lit\n  // are loaded.\n  global.litIssuedWarnings ??= new Set();\n\n  /**\n   * Issue a warning if we haven't already, based either on `code` or `warning`.\n   * Warnings are disabled automatically only by `warning`; disabling via `code`\n   * can be done by users.\n   */\n  issueWarning = (code: string, warning: string) => {\n    warning += ` See https://lit.dev/msg/${code} for more information.`;\n    if (\n      !global.litIssuedWarnings!.has(warning) &&\n      !global.litIssuedWarnings!.has(code)\n    ) {\n      console.warn(warning);\n      global.litIssuedWarnings!.add(warning);\n    }\n  };\n\n  queueMicrotask(() => {\n    issueWarning(\n      'dev-mode',\n      `Lit is in dev mode. Not recommended for production!`\n    );\n\n    // Issue polyfill support warning.\n    if (global.ShadyDOM?.inUse && polyfillSupport === undefined) {\n      issueWarning(\n        'polyfill-support-missing',\n        `Shadow DOM is being polyfilled via \\`ShadyDOM\\` but ` +\n          `the \\`polyfill-support\\` module has not been loaded.`\n      );\n    }\n  });\n}\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace ReactiveUnstable {\n  /**\n   * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n   * we will emit 'lit-debug' events to window, with live details about the update and render\n   * lifecycle. These can be useful for writing debug tooling and visualizations.\n   *\n   * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n   * making certain operations that are normally very cheap (like a no-op render) much slower,\n   * because we must copy data and dispatch events.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-namespace\n  export namespace DebugLog {\n    export type Entry = Update;\n    export interface Update {\n      kind: 'update';\n    }\n  }\n}\n\ninterface DebugLoggingWindow {\n  // Even in dev mode, we generally don't want to emit these events, as that's\n  // another level of cost, so only emit them when DEV_MODE is true _and_ when\n  // window.emitLitDebugEvents is true.\n  emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n  ? (event: ReactiveUnstable.DebugLog.Entry) => {\n      const shouldEmit = (global as unknown as DebugLoggingWindow)\n        .emitLitDebugLogEvents;\n      if (!shouldEmit) {\n        return;\n      }\n      global.dispatchEvent(\n        new CustomEvent<ReactiveUnstable.DebugLog.Entry>('lit-debug', {\n          detail: event,\n        })\n      );\n    }\n  : undefined;\n\n/*\n * When using Closure Compiler, JSCompiler_renameProperty(property, object) is\n * replaced at compile time by the munged name for object[property]. We cannot\n * alias this function, so we have to use a small shim that has the same\n * behavior when not compiling.\n */\n/*@__INLINE__*/\nconst JSCompiler_renameProperty = <P extends PropertyKey>(\n  prop: P,\n  _obj: unknown\n): P => prop;\n\n/**\n * Converts property values to and from attribute values.\n */\nexport interface ComplexAttributeConverter<Type = unknown, TypeHint = unknown> {\n  /**\n   * Called to convert an attribute value to a property\n   * value.\n   */\n  fromAttribute?(value: string | null, type?: TypeHint): Type;\n\n  /**\n   * Called to convert a property value to an attribute\n   * value.\n   *\n   * It returns unknown instead of string, to be compatible with\n   * https://github.com/WICG/trusted-types (and similar efforts).\n   */\n  toAttribute?(value: Type, type?: TypeHint): unknown;\n}\n\ntype AttributeConverter<Type = unknown, TypeHint = unknown> =\n  | ComplexAttributeConverter<Type>\n  | ((value: string | null, type?: TypeHint) => Type);\n\n/**\n * Defines options for a property accessor.\n */\nexport interface PropertyDeclaration<Type = unknown, TypeHint = unknown> {\n  /**\n   * When set to `true`, indicates the property is internal private state. The\n   * property should not be set by users. When using TypeScript, this property\n   * should be marked as `private` or `protected`, and it is also a common\n   * practice to use a leading `_` in the name. The property is not added to\n   * `observedAttributes`.\n   */\n  readonly state?: boolean;\n\n  /**\n   * Indicates how and whether the property becomes an observed attribute.\n   * If the value is `false`, the property is not added to `observedAttributes`.\n   * If true or absent, the lowercased property name is observed (e.g. `fooBar`\n   * becomes `foobar`). If a string, the string value is observed (e.g\n   * `attribute: 'foo-bar'`).\n   */\n  readonly attribute?: boolean | string;\n\n  /**\n   * Indicates the type of the property. This is used only as a hint for the\n   * `converter` to determine how to convert the attribute\n   * to/from a property.\n   */\n  readonly type?: TypeHint;\n\n  /**\n   * Indicates how to convert the attribute to/from a property. If this value\n   * is a function, it is used to convert the attribute value a the property\n   * value. If it's an object, it can have keys for `fromAttribute` and\n   * `toAttribute`. If no `toAttribute` function is provided and\n   * `reflect` is set to `true`, the property value is set directly to the\n   * attribute. A default `converter` is used if none is provided; it supports\n   * `Boolean`, `String`, `Number`, `Object`, and `Array`. Note,\n   * when a property changes and the converter is used to update the attribute,\n   * the property is never updated again as a result of the attribute changing,\n   * and vice versa.\n   */\n  readonly converter?: AttributeConverter<Type, TypeHint>;\n\n  /**\n   * Indicates if the property should reflect to an attribute.\n   * If `true`, when the property is set, the attribute is set using the\n   * attribute name determined according to the rules for the `attribute`\n   * property option and the value of the property converted using the rules\n   * from the `converter` property option.\n   */\n  readonly reflect?: boolean;\n\n  /**\n   * A function that indicates if a property should be considered changed when\n   * it is set. The function should take the `newValue` and `oldValue` and\n   * return `true` if an update should be requested.\n   */\n  hasChanged?(value: Type, oldValue: Type): boolean;\n\n  /**\n   * Indicates whether an accessor will be created for this property. By\n   * default, an accessor will be generated for this property that requests an\n   * update when set. If this flag is `true`, no accessor will be created, and\n   * it will be the user's responsibility to call\n   * `this.requestUpdate(propertyName, oldValue)` to request an update when\n   * the property changes.\n   */\n  readonly noAccessor?: boolean;\n\n  /**\n   * Whether this property is wrapping accessors. This is set by `@property`\n   * to control the initial value change and reflection logic.\n   *\n   * @internal\n   */\n  wrapped?: boolean;\n\n  /**\n   * When `true`, uses the initial value of the property as the default value,\n   * which changes how attributes are handled:\n   *  - The initial value does *not* reflect, even if the `reflect` option is `true`.\n   *    Subsequent changes to the property will reflect, even if they are equal to the\n   *     default value.\n   *  - When the attribute is removed, the property is set to the default value\n   *  - The initial value will not trigger an old value in the `changedProperties` map\n   *    argument to update lifecycle methods.\n   *\n   * When set, properties must be initialized, either with a field initializer, or an\n   * assignment in the constructor. Not initializing the property may lead to\n   * improper handling of subsequent property assignments.\n   *\n   * While this behavior is opt-in, most properties that reflect to attributes should\n   * use `useDefault: true` so that their initial values do not reflect.\n   */\n  useDefault?: boolean;\n}\n\n/**\n * Map of properties to PropertyDeclaration options. For each property an\n * accessor is made, and the property is processed according to the\n * PropertyDeclaration options.\n */\nexport interface PropertyDeclarations {\n  readonly [key: string]: PropertyDeclaration;\n}\n\ntype PropertyDeclarationMap = Map<PropertyKey, PropertyDeclaration>;\n\ntype AttributeMap = Map<string, PropertyKey>;\n\n/**\n * A Map of property keys to values.\n *\n * Takes an optional type parameter T, which when specified as a non-any,\n * non-unknown type, will make the Map more strongly-typed, associating the map\n * keys with their corresponding value type on T.\n *\n * Use `PropertyValues<this>` when overriding ReactiveElement.update() and\n * other lifecycle methods in order to get stronger type-checking on keys\n * and values.\n */\n// This type is conditional so that if the parameter T is not specified, or\n// is `any`, the type will include `Map<PropertyKey, unknown>`. Since T is not\n// given in the uses of PropertyValues in this file, all uses here fallback to\n// meaning `Map<PropertyKey, unknown>`, but if a developer uses\n// `PropertyValues<this>` (or any other value for T) they will get a\n// strongly-typed Map type.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type PropertyValues<T = any> = T extends object\n  ? PropertyValueMap<T>\n  : Map<PropertyKey, unknown>;\n\n/**\n * Do not use, instead prefer {@linkcode PropertyValues}.\n */\n// This type must be exported such that JavaScript generated by the Google\n// Closure Compiler can import a type reference.\nexport interface PropertyValueMap<T> extends Map<PropertyKey, unknown> {\n  get<K extends keyof T>(k: K): T[K] | undefined;\n  set<K extends keyof T>(key: K, value: T[K]): this;\n  has<K extends keyof T>(k: K): boolean;\n  delete<K extends keyof T>(k: K): boolean;\n}\n\nexport const defaultConverter: ComplexAttributeConverter = {\n  toAttribute(value: unknown, type?: unknown): unknown {\n    switch (type) {\n      case Boolean:\n        value = value ? emptyStringForBooleanAttribute : null;\n        break;\n      case Object:\n      case Array:\n        // if the value is `null` or `undefined` pass this through\n        // to allow removing/no change behavior.\n        value = value == null ? value : JSON.stringify(value);\n        break;\n    }\n    return value;\n  },\n\n  fromAttribute(value: string | null, type?: unknown) {\n    let fromValue: unknown = value;\n    switch (type) {\n      case Boolean:\n        fromValue = value !== null;\n        break;\n      case Number:\n        fromValue = value === null ? null : Number(value);\n        break;\n      case Object:\n      case Array:\n        // Do *not* generate exception when invalid JSON is set as elements\n        // don't normally complain on being mis-configured.\n        // TODO(sorvell): Do generate exception in *dev mode*.\n        try {\n          // Assert to adhere to Bazel's \"must type assert JSON parse\" rule.\n          fromValue = JSON.parse(value!) as unknown;\n        } catch (e) {\n          fromValue = null;\n        }\n        break;\n    }\n    return fromValue;\n  },\n};\n\nexport interface HasChanged {\n  (value: unknown, old: unknown): boolean;\n}\n\n/**\n * Change function that returns true if `value` is different from `oldValue`.\n * This method is used as the default for a property's `hasChanged` function.\n */\nexport const notEqual: HasChanged = (value: unknown, old: unknown): boolean =>\n  !is(value, old);\n\nconst defaultPropertyDeclaration: PropertyDeclaration = {\n  attribute: true,\n  type: String,\n  converter: defaultConverter,\n  reflect: false,\n  useDefault: false,\n  hasChanged: notEqual,\n};\n\n/**\n * A string representing one of the supported dev mode warning categories.\n */\nexport type WarningKind =\n  | 'change-in-update'\n  | 'migration'\n  | 'async-perform-update';\n\nexport type Initializer = (element: ReactiveElement) => void;\n\n// Temporary, until google3 is on TypeScript 5.2\ndeclare global {\n  interface SymbolConstructor {\n    readonly metadata: unique symbol;\n  }\n}\n\n// Ensure metadata is enabled. TypeScript does not polyfill\n// Symbol.metadata, so we must ensure that it exists.\n(Symbol as {metadata: symbol}).metadata ??= Symbol('metadata');\n\ndeclare global {\n  // This is public global API, do not change!\n  // eslint-disable-next-line no-var\n  var litPropertyMetadata: WeakMap<\n    object,\n    Map<PropertyKey, PropertyDeclaration>\n  >;\n}\n\n// Map from a class's metadata object to property options\n// Note that we must use nullish-coalescing assignment so that we only use one\n// map even if we load multiple version of this module.\nglobal.litPropertyMetadata ??= new WeakMap<\n  object,\n  Map<PropertyKey, PropertyDeclaration>\n>();\n\n/**\n * Base element class which manages element properties and attributes. When\n * properties change, the `update` method is asynchronously called. This method\n * should be supplied by subclasses to render updates as desired.\n * @noInheritDoc\n */\nexport abstract class ReactiveElement\n  // In the Node build, this `extends` clause will be substituted with\n  // `(globalThis.HTMLElement ?? HTMLElement)`.\n  //\n  // This way, we will first prefer any global `HTMLElement` polyfill that the\n  // user has assigned, and then fall back to the `HTMLElement` shim which has\n  // been imported (see note at the top of this file about how this import is\n  // generated by Rollup). Note that the `HTMLElement` variable has been\n  // shadowed by this import, so it no longer refers to the global.\n  extends HTMLElement\n  implements ReactiveControllerHost\n{\n  // Note: these are patched in only in DEV_MODE.\n  /**\n   * Read or set all the enabled warning categories for this class.\n   *\n   * This property is only used in development builds.\n   *\n   * @nocollapse\n   * @category dev-mode\n   */\n  static enabledWarnings?: WarningKind[];\n\n  /**\n   * Enable the given warning category for this class.\n   *\n   * This method only exists in development builds, so it should be accessed\n   * with a guard like:\n   *\n   * ```ts\n   * // Enable for all ReactiveElement subclasses\n   * ReactiveElement.enableWarning?.('migration');\n   *\n   * // Enable for only MyElement and subclasses\n   * MyElement.enableWarning?.('migration');\n   * ```\n   *\n   * @nocollapse\n   * @category dev-mode\n   */\n  static enableWarning?: (warningKind: WarningKind) => void;\n\n  /**\n   * Disable the given warning category for this class.\n   *\n   * This method only exists in development builds, so it should be accessed\n   * with a guard like:\n   *\n   * ```ts\n   * // Disable for all ReactiveElement subclasses\n   * ReactiveElement.disableWarning?.('migration');\n   *\n   * // Disable for only MyElement and subclasses\n   * MyElement.disableWarning?.('migration');\n   * ```\n   *\n   * @nocollapse\n   * @category dev-mode\n   */\n  static disableWarning?: (warningKind: WarningKind) => void;\n\n  /**\n   * Adds an initializer function to the class that is called during instance\n   * construction.\n   *\n   * This is useful for code that runs against a `ReactiveElement`\n   * subclass, such as a decorator, that needs to do work for each\n   * instance, such as setting up a `ReactiveController`.\n   *\n   * ```ts\n   * const myDecorator = (target: typeof ReactiveElement, key: string) => {\n   *   target.addInitializer((instance: ReactiveElement) => {\n   *     // This is run during construction of the element\n   *     new MyController(instance);\n   *   });\n   * }\n   * ```\n   *\n   * Decorating a field will then cause each instance to run an initializer\n   * that adds a controller:\n   *\n   * ```ts\n   * class MyElement extends LitElement {\n   *   @myDecorator foo;\n   * }\n   * ```\n   *\n   * Initializers are stored per-constructor. Adding an initializer to a\n   * subclass does not add it to a superclass. Since initializers are run in\n   * constructors, initializers will run in order of the class hierarchy,\n   * starting with superclasses and progressing to the instance's class.\n   *\n   * @nocollapse\n   */\n  static addInitializer(initializer: Initializer) {\n    this.__prepare();\n    (this._initializers ??= []).push(initializer);\n  }\n\n  static _initializers?: Initializer[];\n\n  /*\n   * Due to closure compiler ES6 compilation bugs, @nocollapse is required on\n   * all static methods and properties with initializers.  Reference:\n   * - https://github.com/google/closure-compiler/issues/1776\n   */\n\n  /**\n   * Maps attribute names to properties; for example `foobar` attribute to\n   * `fooBar` property. Created lazily on user subclasses when finalizing the\n   * class.\n   * @nocollapse\n   */\n  private static __attributeToPropertyMap: AttributeMap;\n\n  /**\n   * Marks class as having been finalized, which includes creating properties\n   * from `static properties`, but does *not* include all properties created\n   * from decorators.\n   * @nocollapse\n   */\n  protected static finalized: true | undefined;\n\n  /**\n   * Memoized list of all element properties, including any superclass\n   * properties. Created lazily on user subclasses when finalizing the class.\n   *\n   * @nocollapse\n   * @category properties\n   */\n  static elementProperties: PropertyDeclarationMap;\n\n  /**\n   * User-supplied object that maps property names to `PropertyDeclaration`\n   * objects containing options for configuring reactive properties. When\n   * a reactive property is set the element will update and render.\n   *\n   * By default properties are public fields, and as such, they should be\n   * considered as primarily settable by element users, either via attribute or\n   * the property itself.\n   *\n   * Generally, properties that are changed by the element should be private or\n   * protected fields and should use the `state: true` option. Properties\n   * marked as `state` do not reflect from the corresponding attribute\n   *\n   * However, sometimes element code does need to set a public property. This\n   * should typically only be done in response to user interaction, and an event\n   * should be fired informing the user; for example, a checkbox sets its\n   * `checked` property when clicked and fires a `changed` event. Mutating\n   * public properties should typically not be done for non-primitive (object or\n   * array) properties. In other cases when an element needs to manage state, a\n   * private property set with the `state: true` option should be used. When\n   * needed, state properties can be initialized via public properties to\n   * facilitate complex interactions.\n   * @nocollapse\n   * @category properties\n   */\n  static properties: PropertyDeclarations;\n\n  /**\n   * Memoized list of all element styles.\n   * Created lazily on user subclasses when finalizing the class.\n   * @nocollapse\n   * @category styles\n   */\n  static elementStyles: Array<CSSResultOrNative> = [];\n\n  /**\n   * Array of styles to apply to the element. The styles should be defined\n   * using the {@linkcode css} tag function, via constructible stylesheets, or\n   * imported from native CSS module scripts.\n   *\n   * Note on Content Security Policy:\n   *\n   * Element styles are implemented with `<style>` tags when the browser doesn't\n   * support adopted StyleSheets. To use such `<style>` tags with the style-src\n   * CSP directive, the style-src value must either include 'unsafe-inline' or\n   * `nonce-<base64-value>` with `<base64-value>` replaced be a server-generated\n   * nonce.\n   *\n   * To provide a nonce to use on generated `<style>` elements, set\n   * `window.litNonce` to a server-generated nonce in your page's HTML, before\n   * loading application code:\n   *\n   * ```html\n   * <script>\n   *   // Generated and unique per request:\n   *   window.litNonce = 'a1b2c3d4';\n   * </script>\n   * ```\n   * @nocollapse\n   * @category styles\n   */\n  static styles?: CSSResultGroup;\n\n  /**\n   * Returns a list of attributes corresponding to the registered properties.\n   * @nocollapse\n   * @category attributes\n   */\n  static get observedAttributes() {\n    // Ensure we've created all properties\n    this.finalize();\n    // this.__attributeToPropertyMap is only undefined after finalize() in\n    // ReactiveElement itself. ReactiveElement.observedAttributes is only\n    // accessed with ReactiveElement as the receiver when a subclass or mixin\n    // calls super.observedAttributes\n    return (\n      this.__attributeToPropertyMap && [...this.__attributeToPropertyMap.keys()]\n    );\n  }\n\n  private __instanceProperties?: PropertyValues = undefined;\n\n  /**\n   * Creates a property accessor on the element prototype if one does not exist\n   * and stores a {@linkcode PropertyDeclaration} for the property with the\n   * given options. The property setter calls the property's `hasChanged`\n   * property option or uses a strict identity check to determine whether or not\n   * to request an update.\n   *\n   * This method may be overridden to customize properties; however,\n   * when doing so, it's important to call `super.createProperty` to ensure\n   * the property is setup correctly. This method calls\n   * `getPropertyDescriptor` internally to get a descriptor to install.\n   * To customize what properties do when they are get or set, override\n   * `getPropertyDescriptor`. To customize the options for a property,\n   * implement `createProperty` like this:\n   *\n   * ```ts\n   * static createProperty(name, options) {\n   *   options = Object.assign(options, {myOption: true});\n   *   super.createProperty(name, options);\n   * }\n   * ```\n   *\n   * @nocollapse\n   * @category properties\n   */\n  static createProperty(\n    name: PropertyKey,\n    options: PropertyDeclaration = defaultPropertyDeclaration\n  ) {\n    // If this is a state property, force the attribute to false.\n    if (options.state) {\n      (options as Mutable<PropertyDeclaration, 'attribute'>).attribute = false;\n    }\n    this.__prepare();\n    // Whether this property is wrapping accessors.\n    // Helps control the initial value change and reflection logic.\n    if (this.prototype.hasOwnProperty(name)) {\n      options = Object.create(options);\n      options.wrapped = true;\n    }\n    this.elementProperties.set(name, options);\n    if (!options.noAccessor) {\n      const key = DEV_MODE\n        ? // Use Symbol.for in dev mode to make it easier to maintain state\n          // when doing HMR.\n          Symbol.for(`${String(name)} (@property() cache)`)\n        : Symbol();\n      const descriptor = this.getPropertyDescriptor(name, key, options);\n      if (descriptor !== undefined) {\n        defineProperty(this.prototype, name, descriptor);\n      }\n    }\n  }\n\n  /**\n   * Returns a property descriptor to be defined on the given named property.\n   * If no descriptor is returned, the property will not become an accessor.\n   * For example,\n   *\n   * ```ts\n   * class MyElement extends LitElement {\n   *   static getPropertyDescriptor(name, key, options) {\n   *     const defaultDescriptor =\n   *         super.getPropertyDescriptor(name, key, options);\n   *     const setter = defaultDescriptor.set;\n   *     return {\n   *       get: defaultDescriptor.get,\n   *       set(value) {\n   *         setter.call(this, value);\n   *         // custom action.\n   *       },\n   *       configurable: true,\n   *       enumerable: true\n   *     }\n   *   }\n   * }\n   * ```\n   *\n   * @nocollapse\n   * @category properties\n   */\n  protected static getPropertyDescriptor(\n    name: PropertyKey,\n    key: string | symbol,\n    options: PropertyDeclaration\n  ): PropertyDescriptor | undefined {\n    const {get, set} = getOwnPropertyDescriptor(this.prototype, name) ?? {\n      get(this: ReactiveElement) {\n        return this[key as keyof typeof this];\n      },\n      set(this: ReactiveElement, v: unknown) {\n        (this as unknown as Record<string | symbol, unknown>)[key] = v;\n      },\n    };\n    if (DEV_MODE && get == null) {\n      if ('value' in (getOwnPropertyDescriptor(this.prototype, name) ?? {})) {\n        throw new Error(\n          `Field ${JSON.stringify(String(name))} on ` +\n            `${this.name} was declared as a reactive property ` +\n            `but it's actually declared as a value on the prototype. ` +\n            `Usually this is due to using @property or @state on a method.`\n        );\n      }\n      issueWarning(\n        'reactive-property-without-getter',\n        `Field ${JSON.stringify(String(name))} on ` +\n          `${this.name} was declared as a reactive property ` +\n          `but it does not have a getter. This will be an error in a ` +\n          `future version of Lit.`\n      );\n    }\n    return {\n      get,\n      set(this: ReactiveElement, value: unknown) {\n        const oldValue = get?.call(this);\n        set?.call(this, value);\n        this.requestUpdate(name, oldValue, options);\n      },\n      configurable: true,\n      enumerable: true,\n    };\n  }\n\n  /**\n   * Returns the property options associated with the given property.\n   * These options are defined with a `PropertyDeclaration` via the `properties`\n   * object or the `@property` decorator and are registered in\n   * `createProperty(...)`.\n   *\n   * Note, this method should be considered \"final\" and not overridden. To\n   * customize the options for a given property, override\n   * {@linkcode createProperty}.\n   *\n   * @nocollapse\n   * @final\n   * @category properties\n   */\n  static getPropertyOptions(name: PropertyKey) {\n    return this.elementProperties.get(name) ?? defaultPropertyDeclaration;\n  }\n\n  // Temporary, until google3 is on TypeScript 5.2\n  declare static [Symbol.metadata]: object & Record<PropertyKey, unknown>;\n\n  /**\n   * Initializes static own properties of the class used in bookkeeping\n   * for element properties, initializers, etc.\n   *\n   * Can be called multiple times by code that needs to ensure these\n   * properties exist before using them.\n   *\n   * This method ensures the superclass is finalized so that inherited\n   * property metadata can be copied down.\n   * @nocollapse\n   */\n  private static __prepare() {\n    if (\n      this.hasOwnProperty(JSCompiler_renameProperty('elementProperties', this))\n    ) {\n      // Already prepared\n      return;\n    }\n    // Finalize any superclasses\n    const superCtor = getPrototypeOf(this) as typeof ReactiveElement;\n    superCtor.finalize();\n\n    // Create own set of initializers for this class if any exist on the\n    // superclass and copy them down. Note, for a small perf boost, avoid\n    // creating initializers unless needed.\n    if (superCtor._initializers !== undefined) {\n      this._initializers = [...superCtor._initializers];\n    }\n    // Initialize elementProperties from the superclass\n    this.elementProperties = new Map(superCtor.elementProperties);\n  }\n\n  /**\n   * Finishes setting up the class so that it's ready to be registered\n   * as a custom element and instantiated.\n   *\n   * This method is called by the ReactiveElement.observedAttributes getter.\n   * If you override the observedAttributes getter, you must either call\n   * super.observedAttributes to trigger finalization, or call finalize()\n   * yourself.\n   *\n   * @nocollapse\n   */\n  protected static finalize() {\n    if (this.hasOwnProperty(JSCompiler_renameProperty('finalized', this))) {\n      return;\n    }\n    this.finalized = true;\n    this.__prepare();\n\n    // Create properties from the static properties block:\n    if (this.hasOwnProperty(JSCompiler_renameProperty('properties', this))) {\n      const props = this.properties;\n      const propKeys = [\n        ...getOwnPropertyNames(props),\n        ...getOwnPropertySymbols(props),\n      ] as Array<keyof typeof props>;\n      for (const p of propKeys) {\n        this.createProperty(p, props[p]);\n      }\n    }\n\n    // Create properties from standard decorator metadata:\n    const metadata = this[Symbol.metadata];\n    if (metadata !== null) {\n      const properties = litPropertyMetadata.get(metadata);\n      if (properties !== undefined) {\n        for (const [p, options] of properties) {\n          this.elementProperties.set(p, options);\n        }\n      }\n    }\n\n    // Create the attribute-to-property map\n    this.__attributeToPropertyMap = new Map();\n    for (const [p, options] of this.elementProperties) {\n      const attr = this.__attributeNameForProperty(p, options);\n      if (attr !== undefined) {\n        this.__attributeToPropertyMap.set(attr, p);\n      }\n    }\n\n    this.elementStyles = this.finalizeStyles(this.styles);\n\n    if (DEV_MODE) {\n      if (this.hasOwnProperty('createProperty')) {\n        issueWarning(\n          'no-override-create-property',\n          'Overriding ReactiveElement.createProperty() is deprecated. ' +\n            'The override will not be called with standard decorators'\n        );\n      }\n      if (this.hasOwnProperty('getPropertyDescriptor')) {\n        issueWarning(\n          'no-override-get-property-descriptor',\n          'Overriding ReactiveElement.getPropertyDescriptor() is deprecated. ' +\n            'The override will not be called with standard decorators'\n        );\n      }\n    }\n  }\n\n  /**\n   * Options used when calling `attachShadow`. Set this property to customize\n   * the options for the shadowRoot; for example, to create a closed\n   * shadowRoot: `{mode: 'closed'}`.\n   *\n   * Note, these options are used in `createRenderRoot`. If this method\n   * is customized, options should be respected if possible.\n   * @nocollapse\n   * @category rendering\n   */\n  static shadowRootOptions: ShadowRootInit = {mode: 'open'};\n\n  /**\n   * Takes the styles the user supplied via the `static styles` property and\n   * returns the array of styles to apply to the element.\n   * Override this method to integrate into a style management system.\n   *\n   * Styles are deduplicated preserving the _last_ instance in the list. This\n   * is a performance optimization to avoid duplicated styles that can occur\n   * especially when composing via subclassing. The last item is kept to try\n   * to preserve the cascade order with the assumption that it's most important\n   * that last added styles override previous styles.\n   *\n   * @nocollapse\n   * @category styles\n   */\n  protected static finalizeStyles(\n    styles?: CSSResultGroup\n  ): Array<CSSResultOrNative> {\n    const elementStyles = [];\n    if (Array.isArray(styles)) {\n      // Dedupe the flattened array in reverse order to preserve the last items.\n      // Casting to Array<unknown> works around TS error that\n      // appears to come from trying to flatten a type CSSResultArray.\n      const set = new Set((styles as Array<unknown>).flat(Infinity).reverse());\n      // Then preserve original order by adding the set items in reverse order.\n      for (const s of set) {\n        elementStyles.unshift(getCompatibleStyle(s as CSSResultOrNative));\n      }\n    } else if (styles !== undefined) {\n      elementStyles.push(getCompatibleStyle(styles));\n    }\n    return elementStyles;\n  }\n\n  /**\n   * Node or ShadowRoot into which element DOM should be rendered. Defaults\n   * to an open shadowRoot.\n   * @category rendering\n   */\n  readonly renderRoot!: HTMLElement | DocumentFragment;\n\n  /**\n   * Returns the property name for the given attribute `name`.\n   * @nocollapse\n   */\n  private static __attributeNameForProperty(\n    name: PropertyKey,\n    options: PropertyDeclaration\n  ) {\n    const attribute = options.attribute;\n    return attribute === false\n      ? undefined\n      : typeof attribute === 'string'\n        ? attribute\n        : typeof name === 'string'\n          ? name.toLowerCase()\n          : undefined;\n  }\n\n  // Initialize to an unresolved Promise so we can make sure the element has\n  // connected before first update.\n  private __updatePromise!: Promise<boolean>;\n\n  /**\n   * True if there is a pending update as a result of calling `requestUpdate()`.\n   * Should only be read.\n   * @category updates\n   */\n  isUpdatePending = false;\n\n  /**\n   * Is set to `true` after the first update. The element code cannot assume\n   * that `renderRoot` exists before the element `hasUpdated`.\n   * @category updates\n   */\n  hasUpdated = false;\n\n  /**\n   * Map with keys for any properties that have changed since the last\n   * update cycle with previous values.\n   *\n   * @internal\n   */\n  _$changedProperties!: PropertyValues;\n\n  /**\n   * Records property default values when the\n   * `useDefault` option is used.\n   */\n  private __defaultValues?: Map<PropertyKey, unknown>;\n\n  /**\n   * Properties that should be reflected when updated.\n   */\n  private __reflectingProperties?: Set<PropertyKey>;\n\n  /**\n   * Name of currently reflecting property\n   */\n  private __reflectingProperty: PropertyKey | null = null;\n\n  /**\n   * Set of controllers.\n   */\n  private __controllers?: Set<ReactiveController>;\n\n  constructor() {\n    super();\n    this.__initialize();\n  }\n\n  /**\n   * Internal only override point for customizing work done when elements\n   * are constructed.\n   */\n  private __initialize() {\n    this.__updatePromise = new Promise<boolean>(\n      (res) => (this.enableUpdating = res)\n    );\n    this._$changedProperties = new Map();\n    // This enqueues a microtask that must run before the first update, so it\n    // must be called before requestUpdate()\n    this.__saveInstanceProperties();\n    // ensures first update will be caught by an early access of\n    // `updateComplete`\n    this.requestUpdate();\n    (this.constructor as typeof ReactiveElement)._initializers?.forEach((i) =>\n      i(this)\n    );\n  }\n\n  /**\n   * Registers a `ReactiveController` to participate in the element's reactive\n   * update cycle. The element automatically calls into any registered\n   * controllers during its lifecycle callbacks.\n   *\n   * If the element is connected when `addController()` is called, the\n   * controller's `hostConnected()` callback will be immediately called.\n   * @category controllers\n   */\n  addController(controller: ReactiveController) {\n    (this.__controllers ??= new Set()).add(controller);\n    // If a controller is added after the element has been connected,\n    // call hostConnected. Note, re-using existence of `renderRoot` here\n    // (which is set in connectedCallback) to avoid the need to track a\n    // first connected state.\n    if (this.renderRoot !== undefined && this.isConnected) {\n      controller.hostConnected?.();\n    }\n  }\n\n  /**\n   * Removes a `ReactiveController` from the element.\n   * @category controllers\n   */\n  removeController(controller: ReactiveController) {\n    this.__controllers?.delete(controller);\n  }\n\n  /**\n   * Fixes any properties set on the instance before upgrade time.\n   * Otherwise these would shadow the accessor and break these properties.\n   * The properties are stored in a Map which is played back after the\n   * constructor runs.\n   */\n  private __saveInstanceProperties() {\n    const instanceProperties = new Map<PropertyKey, unknown>();\n    const elementProperties = (this.constructor as typeof ReactiveElement)\n      .elementProperties;\n    for (const p of elementProperties.keys() as IterableIterator<keyof this>) {\n      if (this.hasOwnProperty(p)) {\n        instanceProperties.set(p, this[p]);\n        delete this[p];\n      }\n    }\n    if (instanceProperties.size > 0) {\n      this.__instanceProperties = instanceProperties;\n    }\n  }\n\n  /**\n   * Returns the node into which the element should render and by default\n   * creates and returns an open shadowRoot. Implement to customize where the\n   * element's DOM is rendered. For example, to render into the element's\n   * childNodes, return `this`.\n   *\n   * @return Returns a node into which to render.\n   * @category rendering\n   */\n  protected createRenderRoot(): HTMLElement | DocumentFragment {\n    const renderRoot =\n      this.shadowRoot ??\n      this.attachShadow(\n        (this.constructor as typeof ReactiveElement).shadowRootOptions\n      );\n    adoptStyles(\n      renderRoot,\n      (this.constructor as typeof ReactiveElement).elementStyles\n    );\n    return renderRoot;\n  }\n\n  /**\n   * On first connection, creates the element's renderRoot, sets up\n   * element styling, and enables updating.\n   * @category lifecycle\n   */\n  connectedCallback() {\n    // Create renderRoot before controllers `hostConnected`\n    (this as Mutable<typeof this, 'renderRoot'>).renderRoot ??=\n      this.createRenderRoot();\n    this.enableUpdating(true);\n    this.__controllers?.forEach((c) => c.hostConnected?.());\n  }\n\n  /**\n   * Note, this method should be considered final and not overridden. It is\n   * overridden on the element instance with a function that triggers the first\n   * update.\n   * @category updates\n   */\n  protected enableUpdating(_requestedUpdate: boolean) {}\n\n  /**\n   * Allows for `super.disconnectedCallback()` in extensions while\n   * reserving the possibility of making non-breaking feature additions\n   * when disconnecting at some point in the future.\n   * @category lifecycle\n   */\n  disconnectedCallback() {\n    this.__controllers?.forEach((c) => c.hostDisconnected?.());\n  }\n\n  /**\n   * Synchronizes property values when attributes change.\n   *\n   * Specifically, when an attribute is set, the corresponding property is set.\n   * You should rarely need to implement this callback. If this method is\n   * overridden, `super.attributeChangedCallback(name, _old, value)` must be\n   * called.\n   *\n   * See [responding to attribute changes](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#responding_to_attribute_changes)\n   * on MDN for more information about the `attributeChangedCallback`.\n   * @category attributes\n   */\n  attributeChangedCallback(\n    name: string,\n    _old: string | null,\n    value: string | null\n  ) {\n    this._$attributeToProperty(name, value);\n  }\n\n  private __propertyToAttribute(name: PropertyKey, value: unknown) {\n    const elemProperties: PropertyDeclarationMap = (\n      this.constructor as typeof ReactiveElement\n    ).elementProperties;\n    const options = elemProperties.get(name)!;\n    const attr = (\n      this.constructor as typeof ReactiveElement\n    ).__attributeNameForProperty(name, options);\n    if (attr !== undefined && options.reflect === true) {\n      const converter =\n        (options.converter as ComplexAttributeConverter)?.toAttribute !==\n        undefined\n          ? (options.converter as ComplexAttributeConverter)\n          : defaultConverter;\n      const attrValue = converter.toAttribute!(value, options.type);\n      if (\n        DEV_MODE &&\n        (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n          'migration'\n        ) &&\n        attrValue === undefined\n      ) {\n        issueWarning(\n          'undefined-attribute-value',\n          `The attribute value for the ${name as string} property is ` +\n            `undefined on element ${this.localName}. The attribute will be ` +\n            `removed, but in the previous version of \\`ReactiveElement\\`, ` +\n            `the attribute would not have changed.`\n        );\n      }\n      // Track if the property is being reflected to avoid\n      // setting the property again via `attributeChangedCallback`. Note:\n      // 1. this takes advantage of the fact that the callback is synchronous.\n      // 2. will behave incorrectly if multiple attributes are in the reaction\n      // stack at time of calling. However, since we process attributes\n      // in `update` this should not be possible (or an extreme corner case\n      // that we'd like to discover).\n      // mark state reflecting\n      this.__reflectingProperty = name;\n      if (attrValue == null) {\n        this.removeAttribute(attr);\n      } else {\n        this.setAttribute(attr, attrValue as string);\n      }\n      // mark state not reflecting\n      this.__reflectingProperty = null;\n    }\n  }\n\n  /** @internal */\n  _$attributeToProperty(name: string, value: string | null) {\n    const ctor = this.constructor as typeof ReactiveElement;\n    // Note, hint this as an `AttributeMap` so closure clearly understands\n    // the type; it has issues with tracking types through statics\n    const propName = (ctor.__attributeToPropertyMap as AttributeMap).get(name);\n    // Use tracking info to avoid reflecting a property value to an attribute\n    // if it was just set because the attribute changed.\n    if (propName !== undefined && this.__reflectingProperty !== propName) {\n      const options = ctor.getPropertyOptions(propName);\n      const converter =\n        typeof options.converter === 'function'\n          ? {fromAttribute: options.converter}\n          : options.converter?.fromAttribute !== undefined\n            ? options.converter\n            : defaultConverter;\n      // mark state reflecting\n      this.__reflectingProperty = propName;\n      const convertedValue = converter.fromAttribute!(value, options.type);\n      this[propName as keyof this] =\n        convertedValue ??\n        this.__defaultValues?.get(propName) ??\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        (convertedValue as any);\n      // mark state not reflecting\n      this.__reflectingProperty = null;\n    }\n  }\n\n  /**\n   * Requests an update which is processed asynchronously. This should be called\n   * when an element should update based on some state not triggered by setting\n   * a reactive property. In this case, pass no arguments. It should also be\n   * called when manually implementing a property setter. In this case, pass the\n   * property `name` and `oldValue` to ensure that any configured property\n   * options are honored.\n   *\n   * @param name name of requesting property\n   * @param oldValue old value of requesting property\n   * @param options property options to use instead of the previously\n   *     configured options\n   * @param useNewValue if true, the newValue argument is used instead of\n   *     reading the property value. This is important to use if the reactive\n   *     property is a standard private accessor, as opposed to a plain\n   *     property, since private members can't be dynamically read by name.\n   * @param newValue the new value of the property. This is only used if\n   *     `useNewValue` is true.\n   * @category updates\n   */\n  requestUpdate(\n    name?: PropertyKey,\n    oldValue?: unknown,\n    options?: PropertyDeclaration,\n    useNewValue = false,\n    newValue?: unknown\n  ): void {\n    // If we have a property key, perform property update steps.\n    if (name !== undefined) {\n      if (DEV_MODE && (name as unknown) instanceof Event) {\n        issueWarning(\n          ``,\n          `The requestUpdate() method was called with an Event as the property name. This is probably a mistake caused by binding this.requestUpdate as an event listener. Instead bind a function that will call it with no arguments: () => this.requestUpdate()`\n        );\n      }\n      const ctor = this.constructor as typeof ReactiveElement;\n      if (useNewValue === false) {\n        newValue = this[name as keyof this];\n      }\n      options ??= ctor.getPropertyOptions(name);\n      const changed =\n        (options.hasChanged ?? notEqual)(newValue, oldValue) ||\n        // When there is no change, check a corner case that can occur when\n        // 1. there's a initial value which was not reflected\n        // 2. the property is subsequently set to this value.\n        // For example, `prop: {useDefault: true, reflect: true}`\n        // and el.prop = 'foo'. This should be considered a change if the\n        // attribute is not set because we will now reflect the property to the attribute.\n        (options.useDefault &&\n          options.reflect &&\n          newValue === this.__defaultValues?.get(name) &&\n          !this.hasAttribute(ctor.__attributeNameForProperty(name, options)!));\n      if (changed) {\n        this._$changeProperty(name, oldValue, options);\n      } else {\n        // Abort the request if the property should not be considered changed.\n        return;\n      }\n    }\n    if (this.isUpdatePending === false) {\n      this.__updatePromise = this.__enqueueUpdate();\n    }\n  }\n\n  /**\n   * @internal\n   */\n  _$changeProperty(\n    name: PropertyKey,\n    oldValue: unknown,\n    {useDefault, reflect, wrapped}: PropertyDeclaration,\n    initializeValue?: unknown\n  ) {\n    // Record default value when useDefault is used. This allows us to\n    // restore this value when the attribute is removed.\n    if (useDefault && !(this.__defaultValues ??= new Map()).has(name)) {\n      this.__defaultValues.set(\n        name,\n        initializeValue ?? oldValue ?? this[name as keyof this]\n      );\n      // if this is not wrapping an accessor, it must be an initial setting\n      // and in this case we do not want to record the change or reflect.\n      if (wrapped !== true || initializeValue !== undefined) {\n        return;\n      }\n    }\n    // TODO (justinfagnani): Create a benchmark of Map.has() + Map.set(\n    // vs just Map.set()\n    if (!this._$changedProperties.has(name)) {\n      // On the initial change, the old value should be `undefined`, except\n      // with `useDefault`\n      if (!this.hasUpdated && !useDefault) {\n        oldValue = undefined;\n      }\n      this._$changedProperties.set(name, oldValue);\n    }\n    // Add to reflecting properties set.\n    // Note, it's important that every change has a chance to add the\n    // property to `__reflectingProperties`. This ensures setting\n    // attribute + property reflects correctly.\n    if (reflect === true && this.__reflectingProperty !== name) {\n      (this.__reflectingProperties ??= new Set<PropertyKey>()).add(name);\n    }\n  }\n\n  /**\n   * Sets up the element to asynchronously update.\n   */\n  private async __enqueueUpdate() {\n    this.isUpdatePending = true;\n    try {\n      // Ensure any previous update has resolved before updating.\n      // This `await` also ensures that property changes are batched.\n      await this.__updatePromise;\n    } catch (e) {\n      // Refire any previous errors async so they do not disrupt the update\n      // cycle. Errors are refired so developers have a chance to observe\n      // them, and this can be done by implementing\n      // `window.onunhandledrejection`.\n      Promise.reject(e);\n    }\n    const result = this.scheduleUpdate();\n    // If `scheduleUpdate` returns a Promise, we await it. This is done to\n    // enable coordinating updates with a scheduler. Note, the result is\n    // checked to avoid delaying an additional microtask unless we need to.\n    if (result != null) {\n      await result;\n    }\n    return !this.isUpdatePending;\n  }\n\n  /**\n   * Schedules an element update. You can override this method to change the\n   * timing of updates by returning a Promise. The update will await the\n   * returned Promise, and you should resolve the Promise to allow the update\n   * to proceed. If this method is overridden, `super.scheduleUpdate()`\n   * must be called.\n   *\n   * For instance, to schedule updates to occur just before the next frame:\n   *\n   * ```ts\n   * override protected async scheduleUpdate(): Promise<unknown> {\n   *   await new Promise((resolve) => requestAnimationFrame(() => resolve()));\n   *   super.scheduleUpdate();\n   * }\n   * ```\n   * @category updates\n   */\n  protected scheduleUpdate(): void | Promise<unknown> {\n    const result = this.performUpdate();\n    if (\n      DEV_MODE &&\n      (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n        'async-perform-update'\n      ) &&\n      typeof (result as unknown as Promise<unknown> | undefined)?.then ===\n        'function'\n    ) {\n      issueWarning(\n        'async-perform-update',\n        `Element ${this.localName} returned a Promise from performUpdate(). ` +\n          `This behavior is deprecated and will be removed in a future ` +\n          `version of ReactiveElement.`\n      );\n    }\n    return result;\n  }\n\n  /**\n   * Performs an element update. Note, if an exception is thrown during the\n   * update, `firstUpdated` and `updated` will not be called.\n   *\n   * Call `performUpdate()` to immediately process a pending update. This should\n   * generally not be needed, but it can be done in rare cases when you need to\n   * update synchronously.\n   *\n   * @category updates\n   */\n  protected performUpdate(): void {\n    // Abort any update if one is not pending when this is called.\n    // This can happen if `performUpdate` is called early to \"flush\"\n    // the update.\n    if (!this.isUpdatePending) {\n      return;\n    }\n    debugLogEvent?.({kind: 'update'});\n    if (!this.hasUpdated) {\n      // Create renderRoot before first update. This occurs in `connectedCallback`\n      // but is done here to support out of tree calls to `enableUpdating`/`performUpdate`.\n      (this as Mutable<typeof this, 'renderRoot'>).renderRoot ??=\n        this.createRenderRoot();\n      if (DEV_MODE) {\n        // Produce warning if any reactive properties on the prototype are\n        // shadowed by class fields. Instance fields set before upgrade are\n        // deleted by this point, so any own property is caused by class field\n        // initialization in the constructor.\n        const ctor = this.constructor as typeof ReactiveElement;\n        const shadowedProperties = [...ctor.elementProperties.keys()].filter(\n          (p) => this.hasOwnProperty(p) && p in getPrototypeOf(this)\n        );\n        if (shadowedProperties.length) {\n          throw new Error(\n            `The following properties on element ${this.localName} will not ` +\n              `trigger updates as expected because they are set using class ` +\n              `fields: ${shadowedProperties.join(', ')}. ` +\n              `Native class fields and some compiled output will overwrite ` +\n              `accessors used for detecting changes. See ` +\n              `https://lit.dev/msg/class-field-shadowing ` +\n              `for more information.`\n          );\n        }\n      }\n      // Mixin instance properties once, if they exist.\n      if (this.__instanceProperties) {\n        // TODO (justinfagnani): should we use the stored value? Could a new value\n        // have been set since we stored the own property value?\n        for (const [p, value] of this.__instanceProperties) {\n          this[p as keyof this] = value as this[keyof this];\n        }\n        this.__instanceProperties = undefined;\n      }\n      // Trigger initial value reflection and populate the initial\n      // `changedProperties` map, but only for the case of properties created\n      // via `createProperty` on accessors, which will not have already\n      // populated the `changedProperties` map since they are not set.\n      // We can't know if these accessors had initializers, so we just set\n      // them anyway - a difference from experimental decorators on fields and\n      // standard decorators on auto-accessors.\n      // For context see:\n      // https://github.com/lit/lit/pull/4183#issuecomment-1711959635\n      const elementProperties = (this.constructor as typeof ReactiveElement)\n        .elementProperties;\n      if (elementProperties.size > 0) {\n        for (const [p, options] of elementProperties) {\n          const {wrapped} = options;\n          const value = this[p as keyof this];\n          if (\n            wrapped === true &&\n            !this._$changedProperties.has(p) &&\n            value !== undefined\n          ) {\n            this._$changeProperty(p, undefined, options, value);\n          }\n        }\n      }\n    }\n    let shouldUpdate = false;\n    const changedProperties = this._$changedProperties;\n    try {\n      shouldUpdate = this.shouldUpdate(changedProperties);\n      if (shouldUpdate) {\n        this.willUpdate(changedProperties);\n        this.__controllers?.forEach((c) => c.hostUpdate?.());\n        this.update(changedProperties);\n      } else {\n        this.__markUpdated();\n      }\n    } catch (e) {\n      // Prevent `firstUpdated` and `updated` from running when there's an\n      // update exception.\n      shouldUpdate = false;\n      // Ensure element can accept additional updates after an exception.\n      this.__markUpdated();\n      throw e;\n    }\n    // The update is no longer considered pending and further updates are now allowed.\n    if (shouldUpdate) {\n      this._$didUpdate(changedProperties);\n    }\n  }\n\n  /**\n   * Invoked before `update()` to compute values needed during the update.\n   *\n   * Implement `willUpdate` to compute property values that depend on other\n   * properties and are used in the rest of the update process.\n   *\n   * ```ts\n   * willUpdate(changedProperties) {\n   *   // only need to check changed properties for an expensive computation.\n   *   if (changedProperties.has('firstName') || changedProperties.has('lastName')) {\n   *     this.sha = computeSHA(`${this.firstName} ${this.lastName}`);\n   *   }\n   * }\n   *\n   * render() {\n   *   return html`SHA: ${this.sha}`;\n   * }\n   * ```\n   *\n   * @category updates\n   */\n  protected willUpdate(_changedProperties: PropertyValues): void {}\n\n  // Note, this is an override point for polyfill-support.\n  // @internal\n  _$didUpdate(changedProperties: PropertyValues) {\n    this.__controllers?.forEach((c) => c.hostUpdated?.());\n    if (!this.hasUpdated) {\n      this.hasUpdated = true;\n      this.firstUpdated(changedProperties);\n    }\n    this.updated(changedProperties);\n    if (\n      DEV_MODE &&\n      this.isUpdatePending &&\n      (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n        'change-in-update'\n      )\n    ) {\n      issueWarning(\n        'change-in-update',\n        `Element ${this.localName} scheduled an update ` +\n          `(generally because a property was set) ` +\n          `after an update completed, causing a new update to be scheduled. ` +\n          `This is inefficient and should be avoided unless the next update ` +\n          `can only be scheduled as a side effect of the previous update.`\n      );\n    }\n  }\n\n  private __markUpdated() {\n    this._$changedProperties = new Map();\n    this.isUpdatePending = false;\n  }\n\n  /**\n   * Returns a Promise that resolves when the element has completed updating.\n   * The Promise value is a boolean that is `true` if the element completed the\n   * update without triggering another update. The Promise result is `false` if\n   * a property was set inside `updated()`. If the Promise is rejected, an\n   * exception was thrown during the update.\n   *\n   * To await additional asynchronous work, override the `getUpdateComplete`\n   * method. For example, it is sometimes useful to await a rendered element\n   * before fulfilling this Promise. To do this, first await\n   * `super.getUpdateComplete()`, then any subsequent state.\n   *\n   * @return A promise of a boolean that resolves to true if the update completed\n   *     without triggering another update.\n   * @category updates\n   */\n  get updateComplete(): Promise<boolean> {\n    return this.getUpdateComplete();\n  }\n\n  /**\n   * Override point for the `updateComplete` promise.\n   *\n   * It is not safe to override the `updateComplete` getter directly due to a\n   * limitation in TypeScript which means it is not possible to call a\n   * superclass getter (e.g. `super.updateComplete.then(...)`) when the target\n   * language is ES5 (https://github.com/microsoft/TypeScript/issues/338).\n   * This method should be overridden instead. For example:\n   *\n   * ```ts\n   * class MyElement extends LitElement {\n   *   override async getUpdateComplete() {\n   *     const result = await super.getUpdateComplete();\n   *     await this._myChild.updateComplete;\n   *     return result;\n   *   }\n   * }\n   * ```\n   *\n   * @return A promise of a boolean that resolves to true if the update completed\n   *     without triggering another update.\n   * @category updates\n   */\n  protected getUpdateComplete(): Promise<boolean> {\n    return this.__updatePromise;\n  }\n\n  /**\n   * Controls whether or not `update()` should be called when the element requests\n   * an update. By default, this method always returns `true`, but this can be\n   * customized to control when to update.\n   *\n   * @param _changedProperties Map of changed properties with old values\n   * @category updates\n   */\n  protected shouldUpdate(_changedProperties: PropertyValues): boolean {\n    return true;\n  }\n\n  /**\n   * Updates the element. This method reflects property values to attributes.\n   * It can be overridden to render and keep updated element DOM.\n   * Setting properties inside this method will *not* trigger\n   * another update.\n   *\n   * @param _changedProperties Map of changed properties with old values\n   * @category updates\n   */\n  protected update(_changedProperties: PropertyValues) {\n    // The forEach() expression will only run when __reflectingProperties is\n    // defined, and it returns undefined, setting __reflectingProperties to\n    // undefined\n    this.__reflectingProperties &&= this.__reflectingProperties.forEach((p) =>\n      this.__propertyToAttribute(p, this[p as keyof this])\n    ) as undefined;\n    this.__markUpdated();\n  }\n\n  /**\n   * Invoked whenever the element is updated. Implement to perform\n   * post-updating tasks via DOM APIs, for example, focusing an element.\n   *\n   * Setting properties inside this method will trigger the element to update\n   * again after this update cycle completes.\n   *\n   * @param _changedProperties Map of changed properties with old values\n   * @category updates\n   */\n  protected updated(_changedProperties: PropertyValues) {}\n\n  /**\n   * Invoked when the element is first updated. Implement to perform one time\n   * work on the element after update.\n   *\n   * ```ts\n   * firstUpdated() {\n   *   this.renderRoot.getElementById('my-text-area').focus();\n   * }\n   * ```\n   *\n   * Setting properties inside this method will trigger the element to update\n   * again after this update cycle completes.\n   *\n   * @param _changedProperties Map of changed properties with old values\n   * @category updates\n   */\n  protected firstUpdated(_changedProperties: PropertyValues) {}\n}\n// Assigned here to work around a jscompiler bug with static fields\n// when compiling to ES5.\n// https://github.com/google/closure-compiler/issues/3177\n(ReactiveElement as unknown as Record<string, unknown>)[\n  JSCompiler_renameProperty('elementProperties', ReactiveElement)\n] = new Map();\n(ReactiveElement as unknown as Record<string, unknown>)[\n  JSCompiler_renameProperty('finalized', ReactiveElement)\n] = new Map();\n\n// Apply polyfills if available\npolyfillSupport?.({ReactiveElement});\n\n// Dev mode warnings...\nif (DEV_MODE) {\n  // Default warning set.\n  ReactiveElement.enabledWarnings = [\n    'change-in-update',\n    'async-perform-update',\n  ];\n  const ensureOwnWarnings = function (ctor: typeof ReactiveElement) {\n    if (\n      !ctor.hasOwnProperty(JSCompiler_renameProperty('enabledWarnings', ctor))\n    ) {\n      ctor.enabledWarnings = ctor.enabledWarnings!.slice();\n    }\n  };\n  ReactiveElement.enableWarning = function (\n    this: typeof ReactiveElement,\n    warning: WarningKind\n  ) {\n    ensureOwnWarnings(this);\n    if (!this.enabledWarnings!.includes(warning)) {\n      this.enabledWarnings!.push(warning);\n    }\n  };\n  ReactiveElement.disableWarning = function (\n    this: typeof ReactiveElement,\n    warning: WarningKind\n  ) {\n    ensureOwnWarnings(this);\n    const i = this.enabledWarnings!.indexOf(warning);\n    if (i >= 0) {\n      this.enabledWarnings!.splice(i, 1);\n    }\n  };\n}\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for ReactiveElement usage.\n(global.reactiveElementVersions ??= []).push('2.1.2');\nif (DEV_MODE && global.reactiveElementVersions.length > 1) {\n  queueMicrotask(() => {\n    issueWarning!(\n      'multiple-versions',\n      `Multiple versions of Lit loaded. Loading multiple versions ` +\n        `is not recommended.`\n    );\n  });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n// IMPORTANT: these imports must be type-only\nimport type {Directive, DirectiveResult, PartInfo} from './directive.js';\nimport type {TrustedHTML, TrustedTypesWindow} from 'trusted-types/lib/index.js';\n\nconst DEV_MODE = true;\nconst ENABLE_EXTRA_SECURITY_HOOKS = true;\nconst ENABLE_SHADYDOM_NOPATCH = true;\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace LitUnstable {\n  /**\n   * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n   * we will emit 'lit-debug' events to window, with live details about the update and render\n   * lifecycle. These can be useful for writing debug tooling and visualizations.\n   *\n   * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n   * making certain operations that are normally very cheap (like a no-op render) much slower,\n   * because we must copy data and dispatch events.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-namespace\n  export namespace DebugLog {\n    export type Entry =\n      | TemplatePrep\n      | TemplateInstantiated\n      | TemplateInstantiatedAndUpdated\n      | TemplateUpdating\n      | BeginRender\n      | EndRender\n      | CommitPartEntry\n      | SetPartValue;\n    export interface TemplatePrep {\n      kind: 'template prep';\n      template: Template;\n      strings: TemplateStringsArray;\n      clonableTemplate: HTMLTemplateElement;\n      parts: TemplatePart[];\n    }\n    export interface BeginRender {\n      kind: 'begin render';\n      id: number;\n      value: unknown;\n      container: RenderRootNode;\n      options: RenderOptions | undefined;\n      part: ChildPart | undefined;\n    }\n    export interface EndRender {\n      kind: 'end render';\n      id: number;\n      value: unknown;\n      container: RenderRootNode;\n      options: RenderOptions | undefined;\n      part: ChildPart;\n    }\n    export interface TemplateInstantiated {\n      kind: 'template instantiated';\n      template: Template | CompiledTemplate;\n      instance: TemplateInstance;\n      options: RenderOptions | undefined;\n      fragment: Node;\n      parts: Array<Part | undefined>;\n      values: unknown[];\n    }\n    export interface TemplateInstantiatedAndUpdated {\n      kind: 'template instantiated and updated';\n      template: Template | CompiledTemplate;\n      instance: TemplateInstance;\n      options: RenderOptions | undefined;\n      fragment: Node;\n      parts: Array<Part | undefined>;\n      values: unknown[];\n    }\n    export interface TemplateUpdating {\n      kind: 'template updating';\n      template: Template | CompiledTemplate;\n      instance: TemplateInstance;\n      options: RenderOptions | undefined;\n      parts: Array<Part | undefined>;\n      values: unknown[];\n    }\n    export interface SetPartValue {\n      kind: 'set part';\n      part: Part;\n      value: unknown;\n      valueIndex: number;\n      values: unknown[];\n      templateInstance: TemplateInstance;\n    }\n\n    export type CommitPartEntry =\n      | CommitNothingToChildEntry\n      | CommitText\n      | CommitNode\n      | CommitAttribute\n      | CommitProperty\n      | CommitBooleanAttribute\n      | CommitEventListener\n      | CommitToElementBinding;\n\n    export interface CommitNothingToChildEntry {\n      kind: 'commit nothing to child';\n      start: ChildNode;\n      end: ChildNode | null;\n      parent: Disconnectable | undefined;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitText {\n      kind: 'commit text';\n      node: Text;\n      value: unknown;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitNode {\n      kind: 'commit node';\n      start: Node;\n      parent: Disconnectable | undefined;\n      value: Node;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitAttribute {\n      kind: 'commit attribute';\n      element: Element;\n      name: string;\n      value: unknown;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitProperty {\n      kind: 'commit property';\n      element: Element;\n      name: string;\n      value: unknown;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitBooleanAttribute {\n      kind: 'commit boolean attribute';\n      element: Element;\n      name: string;\n      value: boolean;\n      options: RenderOptions | undefined;\n    }\n\n    export interface CommitEventListener {\n      kind: 'commit event listener';\n      element: Element;\n      name: string;\n      value: unknown;\n      oldListener: unknown;\n      options: RenderOptions | undefined;\n      // True if we're removing the old event listener (e.g. because settings changed, or value is nothing)\n      removeListener: boolean;\n      // True if we're adding a new event listener (e.g. because first render, or settings changed)\n      addListener: boolean;\n    }\n\n    export interface CommitToElementBinding {\n      kind: 'commit to element binding';\n      element: Element;\n      value: unknown;\n      options: RenderOptions | undefined;\n    }\n  }\n}\n\ninterface DebugLoggingWindow {\n  // Even in dev mode, we generally don't want to emit these events, as that's\n  // another level of cost, so only emit them when DEV_MODE is true _and_ when\n  // window.emitLitDebugEvents is true.\n  emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n  ? (event: LitUnstable.DebugLog.Entry) => {\n      const shouldEmit = (global as unknown as DebugLoggingWindow)\n        .emitLitDebugLogEvents;\n      if (!shouldEmit) {\n        return;\n      }\n      global.dispatchEvent(\n        new CustomEvent<LitUnstable.DebugLog.Entry>('lit-debug', {\n          detail: event,\n        })\n      );\n    }\n  : undefined;\n// Used for connecting beginRender and endRender events when there are nested\n// renders when errors are thrown preventing an endRender event from being\n// called.\nlet debugLogRenderId = 0;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n  global.litIssuedWarnings ??= new Set();\n\n  /**\n   * Issue a warning if we haven't already, based either on `code` or `warning`.\n   * Warnings are disabled automatically only by `warning`; disabling via `code`\n   * can be done by users.\n   */\n  issueWarning = (code: string, warning: string) => {\n    warning += code\n      ? ` See https://lit.dev/msg/${code} for more information.`\n      : '';\n    if (\n      !global.litIssuedWarnings!.has(warning) &&\n      !global.litIssuedWarnings!.has(code)\n    ) {\n      console.warn(warning);\n      global.litIssuedWarnings!.add(warning);\n    }\n  };\n\n  queueMicrotask(() => {\n    issueWarning(\n      'dev-mode',\n      `Lit is in dev mode. Not recommended for production!`\n    );\n  });\n}\n\nconst wrap =\n  ENABLE_SHADYDOM_NOPATCH &&\n  global.ShadyDOM?.inUse &&\n  global.ShadyDOM?.noPatch === true\n    ? (global.ShadyDOM!.wrap as <T extends Node>(node: T) => T)\n    : <T extends Node>(node: T) => node;\n\nconst trustedTypes = (global as unknown as TrustedTypesWindow).trustedTypes;\n\n/**\n * Our TrustedTypePolicy for HTML which is declared using the html template\n * tag function.\n *\n * That HTML is a developer-authored constant, and is parsed with innerHTML\n * before any untrusted expressions have been mixed in. Therefor it is\n * considered safe by construction.\n */\nconst policy = trustedTypes\n  ? trustedTypes.createPolicy('lit-html', {\n      createHTML: (s) => s,\n    })\n  : undefined;\n\n/**\n * Used to sanitize any value before it is written into the DOM. This can be\n * used to implement a security policy of allowed and disallowed values in\n * order to prevent XSS attacks.\n *\n * One way of using this callback would be to check attributes and properties\n * against a list of high risk fields, and require that values written to such\n * fields be instances of a class which is safe by construction. Closure's Safe\n * HTML Types is one implementation of this technique (\n * https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md).\n * The TrustedTypes polyfill in API-only mode could also be used as a basis\n * for this technique (https://github.com/WICG/trusted-types).\n *\n * @param node The HTML node (usually either a #text node or an Element) that\n *     is being written to. Note that this is just an exemplar node, the write\n *     may take place against another instance of the same class of node.\n * @param name The name of an attribute or property (for example, 'href').\n * @param type Indicates whether the write that's about to be performed will\n *     be to a property or a node.\n * @return A function that will sanitize this class of writes.\n */\nexport type SanitizerFactory = (\n  node: Node,\n  name: string,\n  type: 'property' | 'attribute'\n) => ValueSanitizer;\n\n/**\n * A function which can sanitize values that will be written to a specific kind\n * of DOM sink.\n *\n * See SanitizerFactory.\n *\n * @param value The value to sanitize. Will be the actual value passed into\n *     the lit-html template literal, so this could be of any type.\n * @return The value to write to the DOM. Usually the same as the input value,\n *     unless sanitization is needed.\n */\nexport type ValueSanitizer = (value: unknown) => unknown;\n\nconst identityFunction: ValueSanitizer = (value: unknown) => value;\nconst noopSanitizer: SanitizerFactory = (\n  _node: Node,\n  _name: string,\n  _type: 'property' | 'attribute'\n) => identityFunction;\n\n/** Sets the global sanitizer factory. */\nconst setSanitizer = (newSanitizer: SanitizerFactory) => {\n  if (!ENABLE_EXTRA_SECURITY_HOOKS) {\n    return;\n  }\n  if (sanitizerFactoryInternal !== noopSanitizer) {\n    throw new Error(\n      `Attempted to overwrite existing lit-html security policy.` +\n        ` setSanitizeDOMValueFactory should be called at most once.`\n    );\n  }\n  sanitizerFactoryInternal = newSanitizer;\n};\n\n/**\n * Only used in internal tests, not a part of the public API.\n */\nconst _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => {\n  sanitizerFactoryInternal = noopSanitizer;\n};\n\nconst createSanitizer: SanitizerFactory = (node, name, type) => {\n  return sanitizerFactoryInternal(node, name, type);\n};\n\n// Added to an attribute name to mark the attribute as bound so we can find\n// it easily.\nconst boundAttributeSuffix = '$lit$';\n\n// This marker is used in many syntactic positions in HTML, so it must be\n// a valid element name and attribute name. We don't support dynamic names (yet)\n// but this at least ensures that the parse tree is closer to the template\n// intention.\nconst marker = `lit$${Math.random().toFixed(9).slice(2)}$`;\n\n// String used to tell if a comment is a marker comment\nconst markerMatch = '?' + marker;\n\n// Text used to insert a comment marker node. We use processing instruction\n// syntax because it's slightly smaller, but parses as a comment node.\nconst nodeMarker = `<${markerMatch}>`;\n\nconst d =\n  NODE_MODE && global.document === undefined\n    ? ({\n        createTreeWalker() {\n          return {};\n        },\n      } as unknown as Document)\n    : document;\n\n// Creates a dynamic marker. We never have to search for these in the DOM.\nconst createMarker = () => d.createComment('');\n\n// https://tc39.github.io/ecma262/#sec-typeof-operator\ntype Primitive = null | undefined | boolean | number | string | symbol | bigint;\nconst isPrimitive = (value: unknown): value is Primitive =>\n  value === null || (typeof value != 'object' && typeof value != 'function');\nconst isArray = Array.isArray;\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n  isArray(value) ||\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  typeof (value as any)?.[Symbol.iterator] === 'function';\n\nconst SPACE_CHAR = `[ \\t\\n\\f\\r]`;\nconst ATTR_VALUE_CHAR = `[^ \\t\\n\\f\\r\"'\\`<>=]`;\nconst NAME_CHAR = `[^\\\\s\"'>=/]`;\n\n// These regexes represent the five parsing states that we care about in the\n// Template's HTML scanner. They match the *end* of the state they're named\n// after.\n// Depending on the match, we transition to a new state. If there's no match,\n// we stay in the same state.\n// Note that the regexes are stateful. We utilize lastIndex and sync it\n// across the multiple regexes used. In addition to the five regexes below\n// we also dynamically create a regex to find the matching end tags for raw\n// text elements.\n\n/**\n * End of text is: `<` followed by:\n *   (comment start) or (tag) or (dynamic tag binding)\n */\nconst textEndRegex = /<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g;\nconst COMMENT_START = 1;\nconst TAG_NAME = 2;\nconst DYNAMIC_TAG_NAME = 3;\n\nconst commentEndRegex = /-->/g;\n/**\n * Comments not started with <!--, like </{, can be ended by a single `>`\n */\nconst comment2EndRegex = />/g;\n\n/**\n * The tagEnd regex matches the end of the \"inside an opening\" tag syntax\n * position. It either matches a `>`, an attribute-like sequence, or the end\n * of the string after a space (attribute-name position ending).\n *\n * See attributes in the HTML spec:\n * https://www.w3.org/TR/html5/syntax.html#elements-attributes\n *\n * \" \\t\\n\\f\\r\" are HTML space characters:\n * https://infra.spec.whatwg.org/#ascii-whitespace\n *\n * So an attribute is:\n *  * The name: any character except a whitespace character, (\"), ('), \">\",\n *    \"=\", or \"/\". Note: this is different from the HTML spec which also excludes control characters.\n *  * Followed by zero or more space characters\n *  * Followed by \"=\"\n *  * Followed by zero or more space characters\n *  * Followed by:\n *    * Any character except space, ('), (\"), \"<\", \">\", \"=\", (`), or\n *    * (\") then any non-(\"), or\n *    * (') then any non-(')\n */\nconst tagEndRegex = new RegExp(\n  `>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|(\"|')|))|$)`,\n  'g'\n);\nconst ENTIRE_MATCH = 0;\nconst ATTRIBUTE_NAME = 1;\nconst SPACES_AND_EQUALS = 2;\nconst QUOTE_CHAR = 3;\n\nconst singleQuoteAttrEndRegex = /'/g;\nconst doubleQuoteAttrEndRegex = /\"/g;\n/**\n * Matches the raw text elements.\n *\n * Comments are not parsed within raw text elements, so we need to search their\n * text content for marker strings.\n */\nconst rawTextElement = /^(?:script|style|textarea|title)$/i;\n\n/** TemplateResult types */\nconst HTML_RESULT = 1;\nconst SVG_RESULT = 2;\nconst MATHML_RESULT = 3;\n\ntype ResultType = typeof HTML_RESULT | typeof SVG_RESULT | typeof MATHML_RESULT;\n\n// TemplatePart types\n// IMPORTANT: these must match the values in PartType\nconst ATTRIBUTE_PART = 1;\nconst CHILD_PART = 2;\nconst PROPERTY_PART = 3;\nconst BOOLEAN_ATTRIBUTE_PART = 4;\nconst EVENT_PART = 5;\nconst ELEMENT_PART = 6;\nconst COMMENT_PART = 7;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg} when it hasn't been compiled by @lit-labs/compiler.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n */\nexport type UncompiledTemplateResult<T extends ResultType = ResultType> = {\n  // This property needs to remain unminified.\n  ['_$litType$']: T;\n  strings: TemplateStringsArray;\n  values: unknown[];\n};\n\n/**\n * This is a template result that may be either uncompiled or compiled.\n *\n * In the future, TemplateResult will be this type. If you want to explicitly\n * note that a template result is potentially compiled, you can reference this\n * type and it will continue to behave the same through the next major version\n * of Lit. This can be useful for code that wants to prepare for the next\n * major version of Lit.\n */\nexport type MaybeCompiledTemplateResult<T extends ResultType = ResultType> =\n  | UncompiledTemplateResult<T>\n  | CompiledTemplateResult;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg}.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n * In Lit 4, this type will be an alias of\n * MaybeCompiledTemplateResult, so that code will get type errors if it assumes\n * that Lit templates are not compiled. When deliberately working with only\n * one, use either {@linkcode CompiledTemplateResult} or\n * {@linkcode UncompiledTemplateResult} explicitly.\n */\nexport type TemplateResult<T extends ResultType = ResultType> =\n  UncompiledTemplateResult<T>;\n\nexport type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>;\n\nexport type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>;\n\nexport type MathMLTemplateResult = TemplateResult<typeof MATHML_RESULT>;\n\n/**\n * A TemplateResult that has been compiled by @lit-labs/compiler, skipping the\n * prepare step.\n */\nexport interface CompiledTemplateResult {\n  // This is a factory in order to make template initialization lazy\n  // and allow ShadyRenderOptions scope to be passed in.\n  // This property needs to remain unminified.\n  ['_$litType$']: CompiledTemplate;\n  values: unknown[];\n}\n\nexport interface CompiledTemplate extends Omit<Template, 'el'> {\n  // el is overridden to be optional. We initialize it on first render\n  el?: HTMLTemplateElement;\n\n  // The prepared HTML string to create a template element from.\n  // The type is a TemplateStringsArray to guarantee that the value came from\n  // source code, preventing a JSON injection attack.\n  h: TemplateStringsArray;\n}\n\n/**\n * Generates a template literal tag function that returns a TemplateResult with\n * the given result type.\n */\nconst tag =\n  <T extends ResultType>(type: T) =>\n  (strings: TemplateStringsArray, ...values: unknown[]): TemplateResult<T> => {\n    // Warn against templates octal escape sequences\n    // We do this here rather than in render so that the warning is closer to the\n    // template definition.\n    if (DEV_MODE && strings.some((s) => s === undefined)) {\n      console.warn(\n        'Some template strings are undefined.\\n' +\n          'This is probably caused by illegal octal escape sequences.'\n      );\n    }\n    if (DEV_MODE) {\n      // Import static-html.js results in a circular dependency which g3 doesn't\n      // handle. Instead we know that static values must have the field\n      // `_$litStatic$`.\n      if (\n        values.some((val) => (val as {_$litStatic$: unknown})?.['_$litStatic$'])\n      ) {\n        issueWarning(\n          '',\n          `Static values 'literal' or 'unsafeStatic' cannot be used as values to non-static templates.\\n` +\n            `Please use the static 'html' tag function. See https://lit.dev/docs/templates/expressions/#static-expressions`\n        );\n      }\n    }\n    return {\n      // This property needs to remain unminified.\n      ['_$litType$']: type,\n      strings,\n      values,\n    };\n  };\n\n/**\n * Interprets a template literal as an HTML template that can efficiently\n * render to and update a container.\n *\n * ```ts\n * const header = (title: string) => html`<h1>${title}</h1>`;\n * ```\n *\n * The `html` tag returns a description of the DOM to render as a value. It is\n * lazy, meaning no work is done until the template is rendered. When rendering,\n * if a template comes from the same expression as a previously rendered result,\n * it's efficiently updated instead of replaced.\n */\nexport const html = tag(HTML_RESULT);\n\n/**\n * Interprets a template literal as an SVG fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const rect = svg`<rect width=\"10\" height=\"10\"></rect>`;\n *\n * const myImage = html`\n *   <svg viewBox=\"0 0 10 10\" xmlns=\"http://www.w3.org/2000/svg\">\n *     ${rect}\n *   </svg>`;\n * ```\n *\n * The `svg` *tag function* should only be used for SVG fragments, or elements\n * that would be contained **inside** an `<svg>` HTML element. A common error is\n * placing an `<svg>` *element* in a template tagged with the `svg` tag\n * function. The `<svg>` element is an HTML element and should be used within a\n * template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an SVG fragment from the\n * `render()` method, as the SVG fragment will be contained within the element's\n * shadow root and thus not be properly contained within an `<svg>` HTML\n * element.\n */\nexport const svg = tag(SVG_RESULT);\n\n/**\n * Interprets a template literal as MathML fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const num = mathml`<mn>1</mn>`;\n *\n * const eq = html`\n *   <math>\n *     ${num}\n *   </math>`;\n * ```\n *\n * The `mathml` *tag function* should only be used for MathML fragments, or\n * elements that would be contained **inside** a `<math>` HTML element. A common\n * error is placing a `<math>` *element* in a template tagged with the `mathml`\n * tag function. The `<math>` element is an HTML element and should be used\n * within a template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an MathML fragment from the\n * `render()` method, as the MathML fragment will be contained within the\n * element's shadow root and thus not be properly contained within a `<math>`\n * HTML element.\n */\nexport const mathml = tag(MATHML_RESULT);\n\n/**\n * A sentinel value that signals that a value was handled by a directive and\n * should not be written to the DOM.\n */\nexport const noChange = Symbol.for('lit-noChange');\n\n/**\n * A sentinel value that signals a ChildPart to fully clear its content.\n *\n * ```ts\n * const button = html`${\n *  user.isAdmin\n *    ? html`<button>DELETE</button>`\n *    : nothing\n * }`;\n * ```\n *\n * Prefer using `nothing` over other falsy values as it provides a consistent\n * behavior between various expression binding contexts.\n *\n * In child expressions, `undefined`, `null`, `''`, and `nothing` all behave the\n * same and render no nodes. In attribute expressions, `nothing` _removes_ the\n * attribute, while `undefined` and `null` will render an empty string. In\n * property expressions `nothing` becomes `undefined`.\n */\nexport const nothing = Symbol.for('lit-nothing');\n\n/**\n * The cache of prepared templates, keyed by the tagged TemplateStringsArray\n * and _not_ accounting for the specific template tag used. This means that\n * template tags cannot be dynamic - they must statically be one of html, svg,\n * or attr. This restriction simplifies the cache lookup, which is on the hot\n * path for rendering.\n */\nconst templateCache = new WeakMap<TemplateStringsArray, Template>();\n\n/**\n * Object specifying options for controlling lit-html rendering. Note that\n * while `render` may be called multiple times on the same `container` (and\n * `renderBefore` reference node) to efficiently update the rendered content,\n * only the options passed in during the first render are respected during\n * the lifetime of renders to that unique `container` + `renderBefore`\n * combination.\n */\nexport interface RenderOptions {\n  /**\n   * An object to use as the `this` value for event listeners. It's often\n   * useful to set this to the host component rendering a template.\n   */\n  host?: object;\n  /**\n   * A DOM node before which to render content in the container.\n   */\n  renderBefore?: ChildNode | null;\n  /**\n   * Node used for cloning the template (`importNode` will be called on this\n   * node). This controls the `ownerDocument` of the rendered DOM, along with\n   * any inherited context. Defaults to the global `document`.\n   */\n  creationScope?: {importNode(node: Node, deep?: boolean): Node};\n  /**\n   * The initial connected state for the top-level part being rendered. If no\n   * `isConnected` option is set, `AsyncDirective`s will be connected by\n   * default. Set to `false` if the initial render occurs in a disconnected tree\n   * and `AsyncDirective`s should see `isConnected === false` for their initial\n   * render. The `part.setConnected()` method must be used subsequent to initial\n   * render to change the connected state of the part.\n   */\n  isConnected?: boolean;\n}\n\n/**\n * The root DOM node for rendering.\n */\nexport type RenderRootNode = HTMLElement | SVGElement | DocumentFragment;\n\nconst walker = d.createTreeWalker(\n  d,\n  129 /* NodeFilter.SHOW_{ELEMENT|COMMENT} */\n);\n\nlet sanitizerFactoryInternal: SanitizerFactory = noopSanitizer;\n\n//\n// Classes only below here, const variable declarations only above here...\n//\n// Keeping variable declarations and classes together improves minification.\n// Interfaces and type aliases can be interleaved freely.\n//\n\n// Type for classes that have a `_directive` or `_directives[]` field, used by\n// `resolveDirective`\nexport interface DirectiveParent {\n  _$parent?: DirectiveParent;\n  _$isConnected: boolean;\n  __directive?: Directive;\n  __directives?: Array<Directive | undefined>;\n}\n\nfunction trustFromTemplateString(\n  tsa: TemplateStringsArray,\n  stringFromTSA: string\n): TrustedHTML {\n  // A security check to prevent spoofing of Lit template results.\n  // In the future, we may be able to replace this with Array.isTemplateObject,\n  // though we might need to make that check inside of the html and svg\n  // functions, because precompiled templates don't come in as\n  // TemplateStringArray objects.\n  if (!isArray(tsa) || !tsa.hasOwnProperty('raw')) {\n    let message = 'invalid template strings array';\n    if (DEV_MODE) {\n      message = `\n          Internal Error: expected template strings to be an array\n          with a 'raw' field. Faking a template strings array by\n          calling html or svg like an ordinary function is effectively\n          the same as calling unsafeHtml and can lead to major security\n          issues, e.g. opening your code up to XSS attacks.\n          If you're using the html or svg tagged template functions normally\n          and still seeing this error, please file a bug at\n          https://github.com/lit/lit/issues/new?template=bug_report.md\n          and include information about your build tooling, if any.\n        `\n        .trim()\n        .replace(/\\n */g, '\\n');\n    }\n    throw new Error(message);\n  }\n  return policy !== undefined\n    ? policy.createHTML(stringFromTSA)\n    : (stringFromTSA as unknown as TrustedHTML);\n}\n\n/**\n * Returns an HTML string for the given TemplateStringsArray and result type\n * (HTML or SVG), along with the case-sensitive bound attribute names in\n * template order. The HTML contains comment markers denoting the `ChildPart`s\n * and suffixes on bound attributes denoting the `AttributeParts`.\n *\n * @param strings template strings array\n * @param type HTML or SVG\n * @return Array containing `[html, attrNames]` (array returned for terseness,\n *     to avoid object fields since this code is shared with non-minified SSR\n *     code)\n */\nconst getTemplateHtml = (\n  strings: TemplateStringsArray,\n  type: ResultType\n): [TrustedHTML, Array<string>] => {\n  // Insert makers into the template HTML to represent the position of\n  // bindings. The following code scans the template strings to determine the\n  // syntactic position of the bindings. They can be in text position, where\n  // we insert an HTML comment, attribute value position, where we insert a\n  // sentinel string and re-write the attribute name, or inside a tag where\n  // we insert the sentinel string.\n  const l = strings.length - 1;\n  // Stores the case-sensitive bound attribute names in the order of their\n  // parts. ElementParts are also reflected in this array as undefined\n  // rather than a string, to disambiguate from attribute bindings.\n  const attrNames: Array<string> = [];\n  let html =\n    type === SVG_RESULT ? '<svg>' : type === MATHML_RESULT ? '<math>' : '';\n\n  // When we're inside a raw text tag (not it's text content), the regex\n  // will still be tagRegex so we can find attributes, but will switch to\n  // this regex when the tag ends.\n  let rawTextEndRegex: RegExp | undefined;\n\n  // The current parsing state, represented as a reference to one of the\n  // regexes\n  let regex = textEndRegex;\n\n  for (let i = 0; i < l; i++) {\n    const s = strings[i];\n    // The index of the end of the last attribute name. When this is\n    // positive at end of a string, it means we're in an attribute value\n    // position and need to rewrite the attribute name.\n    // We also use a special value of -2 to indicate that we encountered\n    // the end of a string in attribute name position.\n    let attrNameEndIndex = -1;\n    let attrName: string | undefined;\n    let lastIndex = 0;\n    let match!: RegExpExecArray | null;\n\n    // The conditions in this loop handle the current parse state, and the\n    // assignments to the `regex` variable are the state transitions.\n    while (lastIndex < s.length) {\n      // Make sure we start searching from where we previously left off\n      regex.lastIndex = lastIndex;\n      match = regex.exec(s);\n      if (match === null) {\n        break;\n      }\n      lastIndex = regex.lastIndex;\n      if (regex === textEndRegex) {\n        if (match[COMMENT_START] === '!--') {\n          regex = commentEndRegex;\n        } else if (match[COMMENT_START] !== undefined) {\n          // We started a weird comment, like </{\n          regex = comment2EndRegex;\n        } else if (match[TAG_NAME] !== undefined) {\n          if (rawTextElement.test(match[TAG_NAME])) {\n            // Record if we encounter a raw-text element. We'll switch to\n            // this regex at the end of the tag.\n            rawTextEndRegex = new RegExp(`</${match[TAG_NAME]}`, 'g');\n          }\n          regex = tagEndRegex;\n        } else if (match[DYNAMIC_TAG_NAME] !== undefined) {\n          if (DEV_MODE) {\n            throw new Error(\n              'Bindings in tag names are not supported. Please use static templates instead. ' +\n                'See https://lit.dev/docs/templates/expressions/#static-expressions'\n            );\n          }\n          regex = tagEndRegex;\n        }\n      } else if (regex === tagEndRegex) {\n        if (match[ENTIRE_MATCH] === '>') {\n          // End of a tag. If we had started a raw-text element, use that\n          // regex\n          regex = rawTextEndRegex ?? textEndRegex;\n          // We may be ending an unquoted attribute value, so make sure we\n          // clear any pending attrNameEndIndex\n          attrNameEndIndex = -1;\n        } else if (match[ATTRIBUTE_NAME] === undefined) {\n          // Attribute name position\n          attrNameEndIndex = -2;\n        } else {\n          attrNameEndIndex = regex.lastIndex - match[SPACES_AND_EQUALS].length;\n          attrName = match[ATTRIBUTE_NAME];\n          regex =\n            match[QUOTE_CHAR] === undefined\n              ? tagEndRegex\n              : match[QUOTE_CHAR] === '\"'\n                ? doubleQuoteAttrEndRegex\n                : singleQuoteAttrEndRegex;\n        }\n      } else if (\n        regex === doubleQuoteAttrEndRegex ||\n        regex === singleQuoteAttrEndRegex\n      ) {\n        regex = tagEndRegex;\n      } else if (regex === commentEndRegex || regex === comment2EndRegex) {\n        regex = textEndRegex;\n      } else {\n        // Not one of the five state regexes, so it must be the dynamically\n        // created raw text regex and we're at the close of that element.\n        regex = tagEndRegex;\n        rawTextEndRegex = undefined;\n      }\n    }\n\n    if (DEV_MODE) {\n      // If we have a attrNameEndIndex, which indicates that we should\n      // rewrite the attribute name, assert that we're in a valid attribute\n      // position - either in a tag, or a quoted attribute value.\n      console.assert(\n        attrNameEndIndex === -1 ||\n          regex === tagEndRegex ||\n          regex === singleQuoteAttrEndRegex ||\n          regex === doubleQuoteAttrEndRegex,\n        'unexpected parse state B'\n      );\n    }\n\n    // We have four cases:\n    //  1. We're in text position, and not in a raw text element\n    //     (regex === textEndRegex): insert a comment marker.\n    //  2. We have a non-negative attrNameEndIndex which means we need to\n    //     rewrite the attribute name to add a bound attribute suffix.\n    //  3. We're at the non-first binding in a multi-binding attribute, use a\n    //     plain marker.\n    //  4. We're somewhere else inside the tag. If we're in attribute name\n    //     position (attrNameEndIndex === -2), add a sequential suffix to\n    //     generate a unique attribute name.\n\n    // Detect a binding next to self-closing tag end and insert a space to\n    // separate the marker from the tag end:\n    const end =\n      regex === tagEndRegex && strings[i + 1].startsWith('/>') ? ' ' : '';\n    html +=\n      regex === textEndRegex\n        ? s + nodeMarker\n        : attrNameEndIndex >= 0\n          ? (attrNames.push(attrName!),\n            s.slice(0, attrNameEndIndex) +\n              boundAttributeSuffix +\n              s.slice(attrNameEndIndex)) +\n            marker +\n            end\n          : s + marker + (attrNameEndIndex === -2 ? i : end);\n  }\n\n  const htmlResult: string | TrustedHTML =\n    html +\n    (strings[l] || '<?>') +\n    (type === SVG_RESULT ? '</svg>' : type === MATHML_RESULT ? '</math>' : '');\n\n  // Returned as an array for terseness\n  return [trustFromTemplateString(strings, htmlResult), attrNames];\n};\n\n/** @internal */\nexport type {Template};\nclass Template {\n  /** @internal */\n  el!: HTMLTemplateElement;\n\n  parts: Array<TemplatePart> = [];\n\n  constructor(\n    // This property needs to remain unminified.\n    {strings, ['_$litType$']: type}: UncompiledTemplateResult,\n    options?: RenderOptions\n  ) {\n    let node: Node | null;\n    let nodeIndex = 0;\n    let attrNameIndex = 0;\n    const partCount = strings.length - 1;\n    const parts = this.parts;\n\n    // Create template element\n    const [html, attrNames] = getTemplateHtml(strings, type);\n    this.el = Template.createElement(html, options);\n    walker.currentNode = this.el.content;\n\n    // Re-parent SVG or MathML nodes into template root\n    if (type === SVG_RESULT || type === MATHML_RESULT) {\n      const wrapper = this.el.content.firstChild!;\n      wrapper.replaceWith(...wrapper.childNodes);\n    }\n\n    // Walk the template to find binding markers and create TemplateParts\n    while ((node = walker.nextNode()) !== null && parts.length < partCount) {\n      if (node.nodeType === 1) {\n        if (DEV_MODE) {\n          const tag = (node as Element).localName;\n          // Warn if `textarea` includes an expression and throw if `template`\n          // does since these are not supported. We do this by checking\n          // innerHTML for anything that looks like a marker. This catches\n          // cases like bindings in textarea there markers turn into text nodes.\n          if (\n            /^(?:textarea|template)$/i!.test(tag) &&\n            (node as Element).innerHTML.includes(marker)\n          ) {\n            const m =\n              `Expressions are not supported inside \\`${tag}\\` ` +\n              `elements. See https://lit.dev/msg/expression-in-${tag} for more ` +\n              `information.`;\n            if (tag === 'template') {\n              throw new Error(m);\n            } else issueWarning('', m);\n          }\n        }\n        // TODO (justinfagnani): for attempted dynamic tag names, we don't\n        // increment the bindingIndex, and it'll be off by 1 in the element\n        // and off by two after it.\n        if ((node as Element).hasAttributes()) {\n          for (const name of (node as Element).getAttributeNames()) {\n            if (name.endsWith(boundAttributeSuffix)) {\n              const realName = attrNames[attrNameIndex++];\n              const value = (node as Element).getAttribute(name)!;\n              const statics = value.split(marker);\n              const m = /([.?@])?(.*)/.exec(realName)!;\n              parts.push({\n                type: ATTRIBUTE_PART,\n                index: nodeIndex,\n                name: m[2],\n                strings: statics,\n                ctor:\n                  m[1] === '.'\n                    ? PropertyPart\n                    : m[1] === '?'\n                      ? BooleanAttributePart\n                      : m[1] === '@'\n                        ? EventPart\n                        : AttributePart,\n              });\n              (node as Element).removeAttribute(name);\n            } else if (name.startsWith(marker)) {\n              parts.push({\n                type: ELEMENT_PART,\n                index: nodeIndex,\n              });\n              (node as Element).removeAttribute(name);\n            }\n          }\n        }\n        // TODO (justinfagnani): benchmark the regex against testing for each\n        // of the 3 raw text element names.\n        if (rawTextElement.test((node as Element).tagName)) {\n          // For raw text elements we need to split the text content on\n          // markers, create a Text node for each segment, and create\n          // a TemplatePart for each marker.\n          const strings = (node as Element).textContent!.split(marker);\n          const lastIndex = strings.length - 1;\n          if (lastIndex > 0) {\n            (node as Element).textContent = trustedTypes\n              ? (trustedTypes.emptyScript as unknown as '')\n              : '';\n            // Generate a new text node for each literal section\n            // These nodes are also used as the markers for child parts\n            for (let i = 0; i < lastIndex; i++) {\n              (node as Element).append(strings[i], createMarker());\n              // Walk past the marker node we just added\n              walker.nextNode();\n              parts.push({type: CHILD_PART, index: ++nodeIndex});\n            }\n            // Note because this marker is added after the walker's current\n            // node, it will be walked to in the outer loop (and ignored), so\n            // we don't need to adjust nodeIndex here\n            (node as Element).append(strings[lastIndex], createMarker());\n          }\n        }\n      } else if (node.nodeType === 8) {\n        const data = (node as Comment).data;\n        if (data === markerMatch) {\n          parts.push({type: CHILD_PART, index: nodeIndex});\n        } else {\n          let i = -1;\n          while ((i = (node as Comment).data.indexOf(marker, i + 1)) !== -1) {\n            // Comment node has a binding marker inside, make an inactive part\n            // The binding won't work, but subsequent bindings will\n            parts.push({type: COMMENT_PART, index: nodeIndex});\n            // Move to the end of the match\n            i += marker.length - 1;\n          }\n        }\n      }\n      nodeIndex++;\n    }\n\n    if (DEV_MODE) {\n      // If there was a duplicate attribute on a tag, then when the tag is\n      // parsed into an element the attribute gets de-duplicated. We can detect\n      // this mismatch if we haven't precisely consumed every attribute name\n      // when preparing the template. This works because `attrNames` is built\n      // from the template string and `attrNameIndex` comes from processing the\n      // resulting DOM.\n      if (attrNames.length !== attrNameIndex) {\n        throw new Error(\n          `Detected duplicate attribute bindings. This occurs if your template ` +\n            `has duplicate attributes on an element tag. For example ` +\n            `\"<input ?disabled=\\${true} ?disabled=\\${false}>\" contains a ` +\n            `duplicate \"disabled\" attribute. The error was detected in ` +\n            `the following template: \\n` +\n            '`' +\n            strings.join('${...}') +\n            '`'\n        );\n      }\n    }\n\n    // We could set walker.currentNode to another node here to prevent a memory\n    // leak, but every time we prepare a template, we immediately render it\n    // and re-use the walker in new TemplateInstance._clone().\n    debugLogEvent &&\n      debugLogEvent({\n        kind: 'template prep',\n        template: this,\n        clonableTemplate: this.el,\n        parts: this.parts,\n        strings,\n      });\n  }\n\n  // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n  /** @nocollapse */\n  static createElement(html: TrustedHTML, _options?: RenderOptions) {\n    const el = d.createElement('template');\n    el.innerHTML = html as unknown as string;\n    return el;\n  }\n}\n\nexport interface Disconnectable {\n  _$parent?: Disconnectable;\n  _$disconnectableChildren?: Set<Disconnectable>;\n  // Rather than hold connection state on instances, Disconnectables recursively\n  // fetch the connection state from the RootPart they are connected in via\n  // getters up the Disconnectable tree via _$parent references. This pushes the\n  // cost of tracking the isConnected state to `AsyncDirectives`, and avoids\n  // needing to pass all Disconnectables (parts, template instances, and\n  // directives) their connection state each time it changes, which would be\n  // costly for trees that have no AsyncDirectives.\n  _$isConnected: boolean;\n}\n\nfunction resolveDirective(\n  part: ChildPart | AttributePart | ElementPart,\n  value: unknown,\n  parent: DirectiveParent = part,\n  attributeIndex?: number\n): unknown {\n  // Bail early if the value is explicitly noChange. Note, this means any\n  // nested directive is still attached and is not run.\n  if (value === noChange) {\n    return value;\n  }\n  let currentDirective =\n    attributeIndex !== undefined\n      ? (parent as AttributePart).__directives?.[attributeIndex]\n      : (parent as ChildPart | ElementPart | Directive).__directive;\n  const nextDirectiveConstructor = isPrimitive(value)\n    ? undefined\n    : // This property needs to remain unminified.\n      (value as DirectiveResult)['_$litDirective$'];\n  if (currentDirective?.constructor !== nextDirectiveConstructor) {\n    // This property needs to remain unminified.\n    currentDirective?.['_$notifyDirectiveConnectionChanged']?.(false);\n    if (nextDirectiveConstructor === undefined) {\n      currentDirective = undefined;\n    } else {\n      currentDirective = new nextDirectiveConstructor(part as PartInfo);\n      currentDirective._$initialize(part, parent, attributeIndex);\n    }\n    if (attributeIndex !== undefined) {\n      ((parent as AttributePart).__directives ??= [])[attributeIndex] =\n        currentDirective;\n    } else {\n      (parent as ChildPart | Directive).__directive = currentDirective;\n    }\n  }\n  if (currentDirective !== undefined) {\n    value = resolveDirective(\n      part,\n      currentDirective._$resolve(part, (value as DirectiveResult).values),\n      currentDirective,\n      attributeIndex\n    );\n  }\n  return value;\n}\n\nexport type {TemplateInstance};\n/**\n * An updateable instance of a Template. Holds references to the Parts used to\n * update the template instance.\n */\nclass TemplateInstance implements Disconnectable {\n  _$template: Template;\n  _$parts: Array<Part | undefined> = [];\n\n  /** @internal */\n  _$parent: ChildPart;\n  /** @internal */\n  _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n  constructor(template: Template, parent: ChildPart) {\n    this._$template = template;\n    this._$parent = parent;\n  }\n\n  // Called by ChildPart parentNode getter\n  get parentNode() {\n    return this._$parent.parentNode;\n  }\n\n  // See comment in Disconnectable interface for why this is a getter\n  get _$isConnected() {\n    return this._$parent._$isConnected;\n  }\n\n  // This method is separate from the constructor because we need to return a\n  // DocumentFragment and we don't want to hold onto it with an instance field.\n  _clone(options: RenderOptions | undefined) {\n    const {\n      el: {content},\n      parts: parts,\n    } = this._$template;\n    const fragment = (options?.creationScope ?? d).importNode(content, true);\n    walker.currentNode = fragment;\n\n    let node = walker.nextNode()!;\n    let nodeIndex = 0;\n    let partIndex = 0;\n    let templatePart = parts[0];\n\n    while (templatePart !== undefined) {\n      if (nodeIndex === templatePart.index) {\n        let part: Part | undefined;\n        if (templatePart.type === CHILD_PART) {\n          part = new ChildPart(\n            node as HTMLElement,\n            node.nextSibling,\n            this,\n            options\n          );\n        } else if (templatePart.type === ATTRIBUTE_PART) {\n          part = new templatePart.ctor(\n            node as HTMLElement,\n            templatePart.name,\n            templatePart.strings,\n            this,\n            options\n          );\n        } else if (templatePart.type === ELEMENT_PART) {\n          part = new ElementPart(node as HTMLElement, this, options);\n        }\n        this._$parts.push(part);\n        templatePart = parts[++partIndex];\n      }\n      if (nodeIndex !== templatePart?.index) {\n        node = walker.nextNode()!;\n        nodeIndex++;\n      }\n    }\n    // We need to set the currentNode away from the cloned tree so that we\n    // don't hold onto the tree even if the tree is detached and should be\n    // freed.\n    walker.currentNode = d;\n    return fragment;\n  }\n\n  _update(values: Array<unknown>) {\n    let i = 0;\n    for (const part of this._$parts) {\n      if (part !== undefined) {\n        debugLogEvent &&\n          debugLogEvent({\n            kind: 'set part',\n            part,\n            value: values[i],\n            valueIndex: i,\n            values,\n            templateInstance: this,\n          });\n        if ((part as AttributePart).strings !== undefined) {\n          (part as AttributePart)._$setValue(values, part as AttributePart, i);\n          // The number of values the part consumes is part.strings.length - 1\n          // since values are in between template spans. We increment i by 1\n          // later in the loop, so increment it by part.strings.length - 2 here\n          i += (part as AttributePart).strings!.length - 2;\n        } else {\n          part._$setValue(values[i]);\n        }\n      }\n      i++;\n    }\n  }\n}\n\n/*\n * Parts\n */\ntype AttributeTemplatePart = {\n  readonly type: typeof ATTRIBUTE_PART;\n  readonly index: number;\n  readonly name: string;\n  readonly ctor: typeof AttributePart;\n  readonly strings: ReadonlyArray<string>;\n};\ntype ChildTemplatePart = {\n  readonly type: typeof CHILD_PART;\n  readonly index: number;\n};\ntype ElementTemplatePart = {\n  readonly type: typeof ELEMENT_PART;\n  readonly index: number;\n};\ntype CommentTemplatePart = {\n  readonly type: typeof COMMENT_PART;\n  readonly index: number;\n};\n\n/**\n * A TemplatePart represents a dynamic part in a template, before the template\n * is instantiated. When a template is instantiated Parts are created from\n * TemplateParts.\n */\ntype TemplatePart =\n  | ChildTemplatePart\n  | AttributeTemplatePart\n  | ElementTemplatePart\n  | CommentTemplatePart;\n\nexport type Part =\n  | ChildPart\n  | AttributePart\n  | PropertyPart\n  | BooleanAttributePart\n  | ElementPart\n  | EventPart;\n\nexport type {ChildPart};\nclass ChildPart implements Disconnectable {\n  readonly type = CHILD_PART;\n  readonly options: RenderOptions | undefined;\n  _$committedValue: unknown = nothing;\n  /** @internal */\n  __directive?: Directive;\n  /** @internal */\n  _$startNode: ChildNode;\n  /** @internal */\n  _$endNode: ChildNode | null;\n  private _textSanitizer: ValueSanitizer | undefined;\n  /** @internal */\n  _$parent: Disconnectable | undefined;\n  /**\n   * Connection state for RootParts only (i.e. ChildPart without _$parent\n   * returned from top-level `render`). This field is unused otherwise. The\n   * intention would be clearer if we made `RootPart` a subclass of `ChildPart`\n   * with this field (and a different _$isConnected getter), but the subclass\n   * caused a perf regression, possibly due to making call sites polymorphic.\n   * @internal\n   */\n  __isConnected: boolean;\n\n  // See comment in Disconnectable interface for why this is a getter\n  get _$isConnected() {\n    // ChildParts that are not at the root should always be created with a\n    // parent; only RootChildNode's won't, so they return the local isConnected\n    // state\n    return this._$parent?._$isConnected ?? this.__isConnected;\n  }\n\n  // The following fields will be patched onto ChildParts when required by\n  // AsyncDirective\n  /** @internal */\n  _$disconnectableChildren?: Set<Disconnectable> = undefined;\n  /** @internal */\n  _$notifyConnectionChanged?(\n    isConnected: boolean,\n    removeFromParent?: boolean,\n    from?: number\n  ): void;\n  /** @internal */\n  _$reparentDisconnectables?(parent: Disconnectable): void;\n\n  constructor(\n    startNode: ChildNode,\n    endNode: ChildNode | null,\n    parent: TemplateInstance | ChildPart | undefined,\n    options: RenderOptions | undefined\n  ) {\n    this._$startNode = startNode;\n    this._$endNode = endNode;\n    this._$parent = parent;\n    this.options = options;\n    // Note __isConnected is only ever accessed on RootParts (i.e. when there is\n    // no _$parent); the value on a non-root-part is \"don't care\", but checking\n    // for parent would be more code\n    this.__isConnected = options?.isConnected ?? true;\n    if (ENABLE_EXTRA_SECURITY_HOOKS) {\n      // Explicitly initialize for consistent class shape.\n      this._textSanitizer = undefined;\n    }\n  }\n\n  /**\n   * The parent node into which the part renders its content.\n   *\n   * A ChildPart's content consists of a range of adjacent child nodes of\n   * `.parentNode`, possibly bordered by 'marker nodes' (`.startNode` and\n   * `.endNode`).\n   *\n   * - If both `.startNode` and `.endNode` are non-null, then the part's content\n   * consists of all siblings between `.startNode` and `.endNode`, exclusively.\n   *\n   * - If `.startNode` is non-null but `.endNode` is null, then the part's\n   * content consists of all siblings following `.startNode`, up to and\n   * including the last child of `.parentNode`. If `.endNode` is non-null, then\n   * `.startNode` will always be non-null.\n   *\n   * - If both `.endNode` and `.startNode` are null, then the part's content\n   * consists of all child nodes of `.parentNode`.\n   */\n  get parentNode(): Node {\n    let parentNode: Node = wrap(this._$startNode).parentNode!;\n    const parent = this._$parent;\n    if (\n      parent !== undefined &&\n      parentNode?.nodeType === 11 /* Node.DOCUMENT_FRAGMENT */\n    ) {\n      // If the parentNode is a DocumentFragment, it may be because the DOM is\n      // still in the cloned fragment during initial render; if so, get the real\n      // parentNode the part will be committed into by asking the parent.\n      parentNode = (parent as ChildPart | TemplateInstance).parentNode;\n    }\n    return parentNode;\n  }\n\n  /**\n   * The part's leading marker node, if any. See `.parentNode` for more\n   * information.\n   */\n  get startNode(): Node | null {\n    return this._$startNode;\n  }\n\n  /**\n   * The part's trailing marker node, if any. See `.parentNode` for more\n   * information.\n   */\n  get endNode(): Node | null {\n    return this._$endNode;\n  }\n\n  _$setValue(value: unknown, directiveParent: DirectiveParent = this): void {\n    if (DEV_MODE && this.parentNode === null) {\n      throw new Error(\n        `This \\`ChildPart\\` has no \\`parentNode\\` and therefore cannot accept a value. This likely means the element containing the part was manipulated in an unsupported way outside of Lit's control such that the part's marker nodes were ejected from DOM. For example, setting the element's \\`innerHTML\\` or \\`textContent\\` can do this.`\n      );\n    }\n    value = resolveDirective(this, value, directiveParent);\n    if (isPrimitive(value)) {\n      // Non-rendering child values. It's important that these do not render\n      // empty text nodes to avoid issues with preventing default <slot>\n      // fallback content.\n      if (value === nothing || value == null || value === '') {\n        if (this._$committedValue !== nothing) {\n          debugLogEvent &&\n            debugLogEvent({\n              kind: 'commit nothing to child',\n              start: this._$startNode,\n              end: this._$endNode,\n              parent: this._$parent,\n              options: this.options,\n            });\n          this._$clear();\n        }\n        this._$committedValue = nothing;\n      } else if (value !== this._$committedValue && value !== noChange) {\n        this._commitText(value);\n      }\n      // This property needs to remain unminified.\n    } else if ((value as TemplateResult)['_$litType$'] !== undefined) {\n      this._commitTemplateResult(value as TemplateResult);\n    } else if ((value as Node).nodeType !== undefined) {\n      if (DEV_MODE && this.options?.host === value) {\n        this._commitText(\n          `[probable mistake: rendered a template's host in itself ` +\n            `(commonly caused by writing \\${this} in a template]`\n        );\n        console.warn(\n          `Attempted to render the template host`,\n          value,\n          `inside itself. This is almost always a mistake, and in dev mode `,\n          `we render some warning text. In production however, we'll `,\n          `render it, which will usually result in an error, and sometimes `,\n          `in the element disappearing from the DOM.`\n        );\n        return;\n      }\n      this._commitNode(value as Node);\n    } else if (isIterable(value)) {\n      this._commitIterable(value);\n    } else {\n      // Fallback, will render the string representation\n      this._commitText(value);\n    }\n  }\n\n  private _insert<T extends Node>(node: T) {\n    return wrap(wrap(this._$startNode).parentNode!).insertBefore(\n      node,\n      this._$endNode\n    );\n  }\n\n  private _commitNode(value: Node): void {\n    if (this._$committedValue !== value) {\n      this._$clear();\n      if (\n        ENABLE_EXTRA_SECURITY_HOOKS &&\n        sanitizerFactoryInternal !== noopSanitizer\n      ) {\n        const parentNodeName = this._$startNode.parentNode?.nodeName;\n        if (parentNodeName === 'STYLE' || parentNodeName === 'SCRIPT') {\n          let message = 'Forbidden';\n          if (DEV_MODE) {\n            if (parentNodeName === 'STYLE') {\n              message =\n                `Lit does not support binding inside style nodes. ` +\n                `This is a security risk, as style injection attacks can ` +\n                `exfiltrate data and spoof UIs. ` +\n                `Consider instead using css\\`...\\` literals ` +\n                `to compose styles, and do dynamic styling with ` +\n                `css custom properties, ::parts, <slot>s, ` +\n                `and by mutating the DOM rather than stylesheets.`;\n            } else {\n              message =\n                `Lit does not support binding inside script nodes. ` +\n                `This is a security risk, as it could allow arbitrary ` +\n                `code execution.`;\n            }\n          }\n          throw new Error(message);\n        }\n      }\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'commit node',\n          start: this._$startNode,\n          parent: this._$parent,\n          value: value,\n          options: this.options,\n        });\n      this._$committedValue = this._insert(value);\n    }\n  }\n\n  private _commitText(value: unknown): void {\n    // If the committed value is a primitive it means we called _commitText on\n    // the previous render, and we know that this._$startNode.nextSibling is a\n    // Text node. We can now just replace the text content (.data) of the node.\n    if (\n      this._$committedValue !== nothing &&\n      isPrimitive(this._$committedValue)\n    ) {\n      const node = wrap(this._$startNode).nextSibling as Text;\n      if (ENABLE_EXTRA_SECURITY_HOOKS) {\n        if (this._textSanitizer === undefined) {\n          this._textSanitizer = createSanitizer(node, 'data', 'property');\n        }\n        value = this._textSanitizer(value);\n      }\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'commit text',\n          node,\n          value,\n          options: this.options,\n        });\n      (node as Text).data = value as string;\n    } else {\n      if (ENABLE_EXTRA_SECURITY_HOOKS) {\n        const textNode = d.createTextNode('');\n        this._commitNode(textNode);\n        // When setting text content, for security purposes it matters a lot\n        // what the parent is. For example, <style> and <script> need to be\n        // handled with care, while <span> does not. So first we need to put a\n        // text node into the document, then we can sanitize its content.\n        if (this._textSanitizer === undefined) {\n          this._textSanitizer = createSanitizer(textNode, 'data', 'property');\n        }\n        value = this._textSanitizer(value);\n        debugLogEvent &&\n          debugLogEvent({\n            kind: 'commit text',\n            node: textNode,\n            value,\n            options: this.options,\n          });\n        textNode.data = value as string;\n      } else {\n        this._commitNode(d.createTextNode(value as string));\n        debugLogEvent &&\n          debugLogEvent({\n            kind: 'commit text',\n            node: wrap(this._$startNode).nextSibling as Text,\n            value,\n            options: this.options,\n          });\n      }\n    }\n    this._$committedValue = value;\n  }\n\n  private _commitTemplateResult(\n    result: TemplateResult | CompiledTemplateResult\n  ): void {\n    // This property needs to remain unminified.\n    const {values, ['_$litType$']: type} = result;\n    // If $litType$ is a number, result is a plain TemplateResult and we get\n    // the template from the template cache. If not, result is a\n    // CompiledTemplateResult and _$litType$ is a CompiledTemplate and we need\n    // to create the <template> element the first time we see it.\n    const template: Template | CompiledTemplate =\n      typeof type === 'number'\n        ? this._$getTemplate(result as UncompiledTemplateResult)\n        : (type.el === undefined &&\n            (type.el = Template.createElement(\n              trustFromTemplateString(type.h, type.h[0]),\n              this.options\n            )),\n          type);\n\n    if ((this._$committedValue as TemplateInstance)?._$template === template) {\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'template updating',\n          template,\n          instance: this._$committedValue as TemplateInstance,\n          parts: (this._$committedValue as TemplateInstance)._$parts,\n          options: this.options,\n          values,\n        });\n      (this._$committedValue as TemplateInstance)._update(values);\n    } else {\n      const instance = new TemplateInstance(template as Template, this);\n      const fragment = instance._clone(this.options);\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'template instantiated',\n          template,\n          instance,\n          parts: instance._$parts,\n          options: this.options,\n          fragment,\n          values,\n        });\n      instance._update(values);\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'template instantiated and updated',\n          template,\n          instance,\n          parts: instance._$parts,\n          options: this.options,\n          fragment,\n          values,\n        });\n      this._commitNode(fragment);\n      this._$committedValue = instance;\n    }\n  }\n\n  // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n  /** @internal */\n  _$getTemplate(result: UncompiledTemplateResult) {\n    let template = templateCache.get(result.strings);\n    if (template === undefined) {\n      templateCache.set(result.strings, (template = new Template(result)));\n    }\n    return template;\n  }\n\n  private _commitIterable(value: Iterable<unknown>): void {\n    // For an Iterable, we create a new InstancePart per item, then set its\n    // value to the item. This is a little bit of overhead for every item in\n    // an Iterable, but it lets us recurse easily and efficiently update Arrays\n    // of TemplateResults that will be commonly returned from expressions like:\n    // array.map((i) => html`${i}`), by reusing existing TemplateInstances.\n\n    // If value is an array, then the previous render was of an\n    // iterable and value will contain the ChildParts from the previous\n    // render. If value is not an array, clear this part and make a new\n    // array for ChildParts.\n    if (!isArray(this._$committedValue)) {\n      this._$committedValue = [];\n      this._$clear();\n    }\n\n    // Lets us keep track of how many items we stamped so we can clear leftover\n    // items from a previous render\n    const itemParts = this._$committedValue as ChildPart[];\n    let partIndex = 0;\n    let itemPart: ChildPart | undefined;\n\n    for (const item of value) {\n      if (partIndex === itemParts.length) {\n        // If no existing part, create a new one\n        // TODO (justinfagnani): test perf impact of always creating two parts\n        // instead of sharing parts between nodes\n        // https://github.com/lit/lit/issues/1266\n        itemParts.push(\n          (itemPart = new ChildPart(\n            this._insert(createMarker()),\n            this._insert(createMarker()),\n            this,\n            this.options\n          ))\n        );\n      } else {\n        // Reuse an existing part\n        itemPart = itemParts[partIndex];\n      }\n      itemPart._$setValue(item);\n      partIndex++;\n    }\n\n    if (partIndex < itemParts.length) {\n      // itemParts always have end nodes\n      this._$clear(\n        itemPart && wrap(itemPart._$endNode!).nextSibling,\n        partIndex\n      );\n      // Truncate the parts array so _value reflects the current state\n      itemParts.length = partIndex;\n    }\n  }\n\n  /**\n   * Removes the nodes contained within this Part from the DOM.\n   *\n   * @param start Start node to clear from, for clearing a subset of the part's\n   *     DOM (used when truncating iterables)\n   * @param from  When `start` is specified, the index within the iterable from\n   *     which ChildParts are being removed, used for disconnecting directives\n   *     in those Parts.\n   *\n   * @internal\n   */\n  _$clear(\n    start: ChildNode | null = wrap(this._$startNode).nextSibling,\n    from?: number\n  ) {\n    this._$notifyConnectionChanged?.(false, true, from);\n    while (start !== this._$endNode) {\n      // The non-null assertion is safe because if _$startNode.nextSibling is\n      // null, then _$endNode is also null, and we would not have entered this\n      // loop.\n      const n = wrap(start!).nextSibling;\n      wrap(start!).remove();\n      start = n;\n    }\n  }\n\n  /**\n   * Implementation of RootPart's `isConnected`. Note that this method\n   * should only be called on `RootPart`s (the `ChildPart` returned from a\n   * top-level `render()` call). It has no effect on non-root ChildParts.\n   * @param isConnected Whether to set\n   * @internal\n   */\n  setConnected(isConnected: boolean) {\n    if (this._$parent === undefined) {\n      this.__isConnected = isConnected;\n      this._$notifyConnectionChanged?.(isConnected);\n    } else if (DEV_MODE) {\n      throw new Error(\n        'part.setConnected() may only be called on a ' +\n          'RootPart returned from render().'\n      );\n    }\n  }\n}\n\n/**\n * A top-level `ChildPart` returned from `render` that manages the connected\n * state of `AsyncDirective`s created throughout the tree below it.\n */\nexport interface RootPart extends ChildPart {\n  /**\n   * Sets the connection state for `AsyncDirective`s contained within this root\n   * ChildPart.\n   *\n   * lit-html does not automatically monitor the connectedness of DOM rendered;\n   * as such, it is the responsibility of the caller to `render` to ensure that\n   * `part.setConnected(false)` is called before the part object is potentially\n   * discarded, to ensure that `AsyncDirective`s have a chance to dispose of\n   * any resources being held. If a `RootPart` that was previously\n   * disconnected is subsequently re-connected (and its `AsyncDirective`s should\n   * re-connect), `setConnected(true)` should be called.\n   *\n   * @param isConnected Whether directives within this tree should be connected\n   * or not\n   */\n  setConnected(isConnected: boolean): void;\n}\n\nexport type {AttributePart};\nclass AttributePart implements Disconnectable {\n  readonly type:\n    | typeof ATTRIBUTE_PART\n    | typeof PROPERTY_PART\n    | typeof BOOLEAN_ATTRIBUTE_PART\n    | typeof EVENT_PART = ATTRIBUTE_PART;\n  readonly element: HTMLElement;\n  readonly name: string;\n  readonly options: RenderOptions | undefined;\n\n  /**\n   * If this attribute part represents an interpolation, this contains the\n   * static strings of the interpolation. For single-value, complete bindings,\n   * this is undefined.\n   */\n  readonly strings?: ReadonlyArray<string>;\n  /** @internal */\n  _$committedValue: unknown | Array<unknown> = nothing;\n  /** @internal */\n  __directives?: Array<Directive | undefined>;\n  /** @internal */\n  _$parent: Disconnectable;\n  /** @internal */\n  _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n  protected _sanitizer: ValueSanitizer | undefined;\n\n  get tagName() {\n    return this.element.tagName;\n  }\n\n  // See comment in Disconnectable interface for why this is a getter\n  get _$isConnected() {\n    return this._$parent._$isConnected;\n  }\n\n  constructor(\n    element: HTMLElement,\n    name: string,\n    strings: ReadonlyArray<string>,\n    parent: Disconnectable,\n    options: RenderOptions | undefined\n  ) {\n    this.element = element;\n    this.name = name;\n    this._$parent = parent;\n    this.options = options;\n    if (strings.length > 2 || strings[0] !== '' || strings[1] !== '') {\n      this._$committedValue = new Array(strings.length - 1).fill(new String());\n      this.strings = strings;\n    } else {\n      this._$committedValue = nothing;\n    }\n    if (ENABLE_EXTRA_SECURITY_HOOKS) {\n      this._sanitizer = undefined;\n    }\n  }\n\n  /**\n   * Sets the value of this part by resolving the value from possibly multiple\n   * values and static strings and committing it to the DOM.\n   * If this part is single-valued, `this._strings` will be undefined, and the\n   * method will be called with a single value argument. If this part is\n   * multi-value, `this._strings` will be defined, and the method is called\n   * with the value array of the part's owning TemplateInstance, and an offset\n   * into the value array from which the values should be read.\n   * This method is overloaded this way to eliminate short-lived array slices\n   * of the template instance values, and allow a fast-path for single-valued\n   * parts.\n   *\n   * @param value The part value, or an array of values for multi-valued parts\n   * @param valueIndex the index to start reading values from. `undefined` for\n   *   single-valued parts\n   * @param noCommit causes the part to not commit its value to the DOM. Used\n   *   in hydration to prime attribute parts with their first-rendered value,\n   *   but not set the attribute, and in SSR to no-op the DOM operation and\n   *   capture the value for serialization.\n   *\n   * @internal\n   */\n  _$setValue(\n    value: unknown | Array<unknown>,\n    directiveParent: DirectiveParent = this,\n    valueIndex?: number,\n    noCommit?: boolean\n  ) {\n    const strings = this.strings;\n\n    // Whether any of the values has changed, for dirty-checking\n    let change = false;\n\n    if (strings === undefined) {\n      // Single-value binding case\n      value = resolveDirective(this, value, directiveParent, 0);\n      change =\n        !isPrimitive(value) ||\n        (value !== this._$committedValue && value !== noChange);\n      if (change) {\n        this._$committedValue = value;\n      }\n    } else {\n      // Interpolation case\n      const values = value as Array<unknown>;\n      value = strings[0];\n\n      let i, v;\n      for (i = 0; i < strings.length - 1; i++) {\n        v = resolveDirective(this, values[valueIndex! + i], directiveParent, i);\n\n        if (v === noChange) {\n          // If the user-provided value is `noChange`, use the previous value\n          v = (this._$committedValue as Array<unknown>)[i];\n        }\n        change ||=\n          !isPrimitive(v) || v !== (this._$committedValue as Array<unknown>)[i];\n        if (v === nothing) {\n          value = nothing;\n        } else if (value !== nothing) {\n          value += (v ?? '') + strings[i + 1];\n        }\n        // We always record each value, even if one is `nothing`, for future\n        // change detection.\n        (this._$committedValue as Array<unknown>)[i] = v;\n      }\n    }\n    if (change && !noCommit) {\n      this._commitValue(value);\n    }\n  }\n\n  /** @internal */\n  _commitValue(value: unknown) {\n    if (value === nothing) {\n      (wrap(this.element) as Element).removeAttribute(this.name);\n    } else {\n      if (ENABLE_EXTRA_SECURITY_HOOKS) {\n        if (this._sanitizer === undefined) {\n          this._sanitizer = sanitizerFactoryInternal(\n            this.element,\n            this.name,\n            'attribute'\n          );\n        }\n        value = this._sanitizer(value ?? '');\n      }\n      debugLogEvent &&\n        debugLogEvent({\n          kind: 'commit attribute',\n          element: this.element,\n          name: this.name,\n          value,\n          options: this.options,\n        });\n      (wrap(this.element) as Element).setAttribute(\n        this.name,\n        (value ?? '') as string\n      );\n    }\n  }\n}\n\nexport type {PropertyPart};\nclass PropertyPart extends AttributePart {\n  override readonly type = PROPERTY_PART;\n\n  /** @internal */\n  override _commitValue(value: unknown) {\n    if (ENABLE_EXTRA_SECURITY_HOOKS) {\n      if (this._sanitizer === undefined) {\n        this._sanitizer = sanitizerFactoryInternal(\n          this.element,\n          this.name,\n          'property'\n        );\n      }\n      value = this._sanitizer(value);\n    }\n    debugLogEvent &&\n      debugLogEvent({\n        kind: 'commit property',\n        element: this.element,\n        name: this.name,\n        value,\n        options: this.options,\n      });\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    (this.element as any)[this.name] = value === nothing ? undefined : value;\n  }\n}\n\nexport type {BooleanAttributePart};\nclass BooleanAttributePart extends AttributePart {\n  override readonly type = BOOLEAN_ATTRIBUTE_PART;\n\n  /** @internal */\n  override _commitValue(value: unknown) {\n    debugLogEvent &&\n      debugLogEvent({\n        kind: 'commit boolean attribute',\n        element: this.element,\n        name: this.name,\n        value: !!(value && value !== nothing),\n        options: this.options,\n      });\n    (wrap(this.element) as Element).toggleAttribute(\n      this.name,\n      !!value && value !== nothing\n    );\n  }\n}\n\ntype EventListenerWithOptions = EventListenerOrEventListenerObject &\n  Partial<AddEventListenerOptions>;\n\n/**\n * An AttributePart that manages an event listener via add/removeEventListener.\n *\n * This part works by adding itself as the event listener on an element, then\n * delegating to the value passed to it. This reduces the number of calls to\n * add/removeEventListener if the listener changes frequently, such as when an\n * inline function is used as a listener.\n *\n * Because event options are passed when adding listeners, we must take case\n * to add and remove the part as a listener when the event options change.\n */\nexport type {EventPart};\nclass EventPart extends AttributePart {\n  override readonly type = EVENT_PART;\n\n  constructor(\n    element: HTMLElement,\n    name: string,\n    strings: ReadonlyArray<string>,\n    parent: Disconnectable,\n    options: RenderOptions | undefined\n  ) {\n    super(element, name, strings, parent, options);\n\n    if (DEV_MODE && this.strings !== undefined) {\n      throw new Error(\n        `A \\`<${element.localName}>\\` has a \\`@${name}=...\\` listener with ` +\n          'invalid content. Event listeners in templates must have exactly ' +\n          'one expression and no surrounding text.'\n      );\n    }\n  }\n\n  // EventPart does not use the base _$setValue/_resolveValue implementation\n  // since the dirty checking is more complex\n  /** @internal */\n  override _$setValue(\n    newListener: unknown,\n    directiveParent: DirectiveParent = this\n  ) {\n    newListener =\n      resolveDirective(this, newListener, directiveParent, 0) ?? nothing;\n    if (newListener === noChange) {\n      return;\n    }\n    const oldListener = this._$committedValue;\n\n    // If the new value is nothing or any options change we have to remove the\n    // part as a listener.\n    const shouldRemoveListener =\n      (newListener === nothing && oldListener !== nothing) ||\n      (newListener as EventListenerWithOptions).capture !==\n        (oldListener as EventListenerWithOptions).capture ||\n      (newListener as EventListenerWithOptions).once !==\n        (oldListener as EventListenerWithOptions).once ||\n      (newListener as EventListenerWithOptions).passive !==\n        (oldListener as EventListenerWithOptions).passive;\n\n    // If the new value is not nothing and we removed the listener, we have\n    // to add the part as a listener.\n    const shouldAddListener =\n      newListener !== nothing &&\n      (oldListener === nothing || shouldRemoveListener);\n\n    debugLogEvent &&\n      debugLogEvent({\n        kind: 'commit event listener',\n        element: this.element,\n        name: this.name,\n        value: newListener,\n        options: this.options,\n        removeListener: shouldRemoveListener,\n        addListener: shouldAddListener,\n        oldListener,\n      });\n    if (shouldRemoveListener) {\n      this.element.removeEventListener(\n        this.name,\n        this,\n        oldListener as EventListenerWithOptions\n      );\n    }\n    if (shouldAddListener) {\n      this.element.addEventListener(\n        this.name,\n        this,\n        newListener as EventListenerWithOptions\n      );\n    }\n    this._$committedValue = newListener;\n  }\n\n  handleEvent(event: Event) {\n    if (typeof this._$committedValue === 'function') {\n      this._$committedValue.call(this.options?.host ?? this.element, event);\n    } else {\n      (this._$committedValue as EventListenerObject).handleEvent(event);\n    }\n  }\n}\n\nexport type {ElementPart};\nclass ElementPart implements Disconnectable {\n  readonly type = ELEMENT_PART;\n\n  /** @internal */\n  __directive?: Directive;\n\n  // This is to ensure that every Part has a _$committedValue\n  _$committedValue: undefined;\n\n  /** @internal */\n  _$parent!: Disconnectable;\n\n  /** @internal */\n  _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n  options: RenderOptions | undefined;\n\n  constructor(\n    public element: Element,\n    parent: Disconnectable,\n    options: RenderOptions | undefined\n  ) {\n    this._$parent = parent;\n    this.options = options;\n  }\n\n  // See comment in Disconnectable interface for why this is a getter\n  get _$isConnected() {\n    return this._$parent._$isConnected;\n  }\n\n  _$setValue(value: unknown): void {\n    debugLogEvent &&\n      debugLogEvent({\n        kind: 'commit to element binding',\n        element: this.element,\n        value,\n        options: this.options,\n      });\n    resolveDirective(this, value);\n  }\n}\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports mangled in the\n * client side code, we export a _$LH object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-element, which re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LH = {\n  // Used in lit-ssr\n  _boundAttributeSuffix: boundAttributeSuffix,\n  _marker: marker,\n  _markerMatch: markerMatch,\n  _HTML_RESULT: HTML_RESULT,\n  _getTemplateHtml: getTemplateHtml,\n  // Used in tests and private-ssr-support\n  _TemplateInstance: TemplateInstance,\n  _isIterable: isIterable,\n  _resolveDirective: resolveDirective,\n  _ChildPart: ChildPart,\n  _AttributePart: AttributePart,\n  _BooleanAttributePart: BooleanAttributePart,\n  _EventPart: EventPart,\n  _PropertyPart: PropertyPart,\n  _ElementPart: ElementPart,\n};\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n  ? global.litHtmlPolyfillSupportDevMode\n  : global.litHtmlPolyfillSupport;\npolyfillSupport?.(Template, ChildPart);\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for lit-html usage.\n(global.litHtmlVersions ??= []).push('3.3.3');\nif (DEV_MODE && global.litHtmlVersions.length > 1) {\n  queueMicrotask(() => {\n    issueWarning!(\n      'multiple-versions',\n      `Multiple versions of Lit loaded. ` +\n        `Loading multiple versions is not recommended.`\n    );\n  });\n}\n\n/**\n * Renders a value, usually a lit-html TemplateResult, to the container.\n *\n * This example renders the text \"Hello, Zoe!\" inside a paragraph tag, appending\n * it to the container `document.body`.\n *\n * ```js\n * import {html, render} from 'lit';\n *\n * const name = \"Zoe\";\n * render(html`<p>Hello, ${name}!</p>`, document.body);\n * ```\n *\n * @param value Any [renderable\n *   value](https://lit.dev/docs/templates/expressions/#child-expressions),\n *   typically a {@linkcode TemplateResult} created by evaluating a template tag\n *   like {@linkcode html} or {@linkcode svg}.\n * @param container A DOM container to render to. The first render will append\n *   the rendered value to the container, and subsequent renders will\n *   efficiently update the rendered value if the same result type was\n *   previously rendered there.\n * @param options See {@linkcode RenderOptions} for options documentation.\n * @see\n * {@link https://lit.dev/docs/libraries/standalone-templates/#rendering-lit-html-templates| Rendering Lit HTML Templates}\n */\nexport const render = (\n  value: unknown,\n  container: RenderRootNode,\n  options?: RenderOptions\n): RootPart => {\n  if (DEV_MODE && container == null) {\n    // Give a clearer error message than\n    //     Uncaught TypeError: Cannot read properties of null (reading\n    //     '_$litPart$')\n    // which reads like an internal Lit error.\n    throw new TypeError(`The container to render into may not be ${container}`);\n  }\n  const renderId = DEV_MODE ? debugLogRenderId++ : 0;\n  const partOwnerNode = options?.renderBefore ?? container;\n  // This property needs to remain unminified.\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  let part: ChildPart = (partOwnerNode as any)['_$litPart$'];\n  debugLogEvent &&\n    debugLogEvent({\n      kind: 'begin render',\n      id: renderId,\n      value,\n      container,\n      options,\n      part,\n    });\n  if (part === undefined) {\n    const endNode = options?.renderBefore ?? null;\n    // This property needs to remain unminified.\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    (partOwnerNode as any)['_$litPart$'] = part = new ChildPart(\n      container.insertBefore(createMarker(), endNode),\n      endNode,\n      undefined,\n      options ?? {}\n    );\n  }\n  part._$setValue(value);\n  debugLogEvent &&\n    debugLogEvent({\n      kind: 'end render',\n      id: renderId,\n      value,\n      container,\n      options,\n      part,\n    });\n  return part as RootPart;\n};\n\nif (ENABLE_EXTRA_SECURITY_HOOKS) {\n  render.setSanitizer = setSanitizer;\n  render.createSanitizer = createSanitizer;\n  if (DEV_MODE) {\n    render._testOnlyClearSanitizerFactoryDoNotCallOrElse =\n      _testOnlyClearSanitizerFactoryDoNotCallOrElse;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * The main LitElement module, which defines the {@linkcode LitElement} base\n * class and related APIs.\n *\n * LitElement components can define a template and a set of observed\n * properties. Changing an observed property triggers a re-render of the\n * element.\n *\n * Import {@linkcode LitElement} and {@linkcode html} from this module to\n * create a component:\n *\n *  ```js\n * import {LitElement, html} from 'lit-element';\n *\n * class MyElement extends LitElement {\n *\n *   // Declare observed properties\n *   static get properties() {\n *     return {\n *       adjective: {}\n *     }\n *   }\n *\n *   constructor() {\n *     this.adjective = 'awesome';\n *   }\n *\n *   // Define the element's template\n *   render() {\n *     return html`<p>your ${adjective} template here</p>`;\n *   }\n * }\n *\n * customElements.define('my-element', MyElement);\n * ```\n *\n * `LitElement` extends {@linkcode ReactiveElement} and adds lit-html\n * templating. The `ReactiveElement` class is provided for users that want to\n * build their own custom element base classes that don't use lit-html.\n *\n * @packageDocumentation\n */\nimport {PropertyValues, ReactiveElement} from '@lit/reactive-element';\nimport {render, RenderOptions, noChange, RootPart} from 'lit-html';\nexport * from '@lit/reactive-element';\nexport * from 'lit-html';\n\nimport {LitUnstable} from 'lit-html';\nimport {ReactiveUnstable} from '@lit/reactive-element';\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace Unstable {\n  /**\n   * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n   * we will emit 'lit-debug' events to window, with live details about the update and render\n   * lifecycle. These can be useful for writing debug tooling and visualizations.\n   *\n   * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n   * making certain operations that are normally very cheap (like a no-op render) much slower,\n   * because we must copy data and dispatch events.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-namespace\n  export namespace DebugLog {\n    export type Entry =\n      | LitUnstable.DebugLog.Entry\n      | ReactiveUnstable.DebugLog.Entry;\n  }\n}\n/*\n * When using Closure Compiler, JSCompiler_renameProperty(property, object) is\n * replaced at compile time by the munged name for object[property]. We cannot\n * alias this function, so we have to use a small shim that has the same\n * behavior when not compiling.\n */\n/*@__INLINE__*/\nconst JSCompiler_renameProperty = <P extends PropertyKey>(\n  prop: P,\n  _obj: unknown\n): P => prop;\n\nconst DEV_MODE = true;\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n  // Ensure warnings are issued only 1x, even if multiple versions of Lit\n  // are loaded.\n  global.litIssuedWarnings ??= new Set();\n\n  /**\n   * Issue a warning if we haven't already, based either on `code` or `warning`.\n   * Warnings are disabled automatically only by `warning`; disabling via `code`\n   * can be done by users.\n   */\n  issueWarning = (code: string, warning: string) => {\n    warning += ` See https://lit.dev/msg/${code} for more information.`;\n    if (\n      !global.litIssuedWarnings!.has(warning) &&\n      !global.litIssuedWarnings!.has(code)\n    ) {\n      console.warn(warning);\n      global.litIssuedWarnings!.add(warning);\n    }\n  };\n}\n\n/**\n * Base element class that manages element properties and attributes, and\n * renders a lit-html template.\n *\n * To define a component, subclass `LitElement` and implement a\n * `render` method to provide the component's template. Define properties\n * using the {@linkcode LitElement.properties properties} property or the\n * {@linkcode property} decorator.\n */\nexport class LitElement extends ReactiveElement {\n  // This property needs to remain unminified.\n  static ['_$litElement$'] = true;\n\n  /**\n   * @category rendering\n   */\n  readonly renderOptions: RenderOptions = {host: this};\n\n  private __childPart: RootPart | undefined = undefined;\n\n  /**\n   * @category rendering\n   */\n  protected override createRenderRoot() {\n    const renderRoot = super.createRenderRoot();\n    // When adoptedStyleSheets are shimmed, they are inserted into the\n    // shadowRoot by createRenderRoot. Adjust the renderBefore node so that\n    // any styles in Lit content render before adoptedStyleSheets. This is\n    // important so that adoptedStyleSheets have precedence over styles in\n    // the shadowRoot.\n    this.renderOptions.renderBefore ??= renderRoot!.firstChild as ChildNode;\n    return renderRoot;\n  }\n\n  /**\n   * Updates the element. This method reflects property values to attributes\n   * and calls `render` to render DOM via lit-html. Setting properties inside\n   * this method will *not* trigger another update.\n   * @param changedProperties Map of changed properties with old values\n   * @category updates\n   */\n  protected override update(changedProperties: PropertyValues) {\n    // Setting properties in `render` should not trigger an update. Since\n    // updates are allowed after super.update, it's important to call `render`\n    // before that.\n    const value = this.render();\n    if (!this.hasUpdated) {\n      this.renderOptions.isConnected = this.isConnected;\n    }\n    super.update(changedProperties);\n    this.__childPart = render(value, this.renderRoot, this.renderOptions);\n  }\n\n  /**\n   * Invoked when the component is added to the document's DOM.\n   *\n   * In `connectedCallback()` you should setup tasks that should only occur when\n   * the element is connected to the document. The most common of these is\n   * adding event listeners to nodes external to the element, like a keydown\n   * event handler added to the window.\n   *\n   * ```ts\n   * connectedCallback() {\n   *   super.connectedCallback();\n   *   addEventListener('keydown', this._handleKeydown);\n   * }\n   * ```\n   *\n   * Typically, anything done in `connectedCallback()` should be undone when the\n   * element is disconnected, in `disconnectedCallback()`.\n   *\n   * @category lifecycle\n   */\n  override connectedCallback() {\n    super.connectedCallback();\n    this.__childPart?.setConnected(true);\n  }\n\n  /**\n   * Invoked when the component is removed from the document's DOM.\n   *\n   * This callback is the main signal to the element that it may no longer be\n   * used. `disconnectedCallback()` should ensure that nothing is holding a\n   * reference to the element (such as event listeners added to nodes external\n   * to the element), so that it is free to be garbage collected.\n   *\n   * ```ts\n   * disconnectedCallback() {\n   *   super.disconnectedCallback();\n   *   window.removeEventListener('keydown', this._handleKeydown);\n   * }\n   * ```\n   *\n   * An element may be re-connected after being disconnected.\n   *\n   * @category lifecycle\n   */\n  override disconnectedCallback() {\n    super.disconnectedCallback();\n    this.__childPart?.setConnected(false);\n  }\n\n  /**\n   * Invoked on each update to perform rendering tasks. This method may return\n   * any value renderable by lit-html's `ChildPart` - typically a\n   * `TemplateResult`. Setting properties inside this method will *not* trigger\n   * the element to update.\n   * @category rendering\n   */\n  protected render(): unknown {\n    return noChange;\n  }\n}\n\n/**\n * Ensure this class is marked as `finalized` as an optimization ensuring\n * it will not needlessly try to `finalize`.\n *\n * Note this property name is a string to prevent breaking Closure JS Compiler\n * optimizations. See @lit/reactive-element for more information.\n */\n(LitElement as unknown as Record<string, unknown>)[\n  JSCompiler_renameProperty('finalized', LitElement)\n] = true;\n\n// Install hydration if available\nglobal.litElementHydrateSupport?.({LitElement});\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n  ? global.litElementPolyfillSupportDevMode\n  : global.litElementPolyfillSupport;\npolyfillSupport?.({LitElement});\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports  mangled in the\n * client side code, we export a _$LE object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-html, since this module re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LE = {\n  _$attributeToProperty: (\n    el: LitElement,\n    name: string,\n    value: string | null\n  ) => {\n    // eslint-disable-next-line\n    (el as any)._$attributeToProperty(name, value);\n  },\n  // eslint-disable-next-line\n  _$changedProperties: (el: LitElement) => (el as any)._$changedProperties,\n};\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for LitElement usage.\n(global.litElementVersions ??= []).push('4.2.2');\nif (DEV_MODE && global.litElementVersions.length > 1) {\n  queueMicrotask(() => {\n    issueWarning!(\n      'multiple-versions',\n      `Multiple versions of Lit loaded. Loading multiple versions ` +\n        `is not recommended.`\n    );\n  });\n}\n","import type { IconName } from \"../icons/icon-data\";\n\n/** A row action; icons are rendered only when the consumer explicitly supplies one.\n    Use kind for edit/delete actions whose identifiers are specific to the consumer.\n*/\nexport interface ContextMenuAction {\n  id: string;\n  label?: string;\n  kind?: \"edit\" | \"delete\";\n  icon?: IconName;\n  separatorBefore?: boolean;\n  danger?: boolean;\n  disabled?: boolean;\n}\n\nfunction actionKind(action: ContextMenuAction): ContextMenuAction[\"kind\"] {\n  return action.kind ?? (action.id === \"edit\" || action.id === \"delete\" ? action.id : undefined);\n}\n\nfunction actionRank(action: ContextMenuAction): number {\n  const kind = actionKind(action);\n  return kind === \"edit\" ? 0 : kind === \"delete\" ? 1 : 2;\n}\n\n/** Applies shared menu conventions without mutating the supplied actions.\n    Edit/delete lead the menu with generic labels, and delete is always destructive.\n    Other actions retain their order and group boundaries after one separating rule.\n    Identifiers edit/delete remain supported for callers that do not supply kind.\n*/\nexport function getMenuActions(options: {\n  actions: readonly ContextMenuAction[];\n}): Array<ContextMenuAction & { label: string }> {\n  const ordered = options.actions.toSorted((left, right) => actionRank(left) - actionRank(right));\n  const firstOtherAction = ordered.findIndex(action => !actionKind(action));\n  return ordered.map((action, index) => {\n    const kind = actionKind(action);\n    if (kind === \"edit\")\n      return { ...action, label: \"Bewerken\", separatorBefore: false };\n    if (kind === \"delete\")\n      return { ...action, label: \"Verwijderen\", danger: true, separatorBefore: false };\n    const normalized = { ...action, label: action.label ?? action.id };\n    return index === firstOtherAction && firstOtherAction > 0 ? { ...normalized, separatorBefore: true } : normalized;\n  });\n}\n\nconst STANDARD_ICONS: Partial<Record<NonNullable<ContextMenuAction[\"kind\"]>, IconName>> = { edit: \"edit\", delete: \"trash-can\" };\n\n/** The row actions as inline icon buttons, or null when they belong behind the overflow menu.\n    Carbon data table: fewer than three actions stay inline; an action without an icon can only be a menu item.\n    Edit/delete get the standard icons here only, the menu stays text-only.\n*/\nexport function getInlineRowActions(options: {\n  actions: readonly ContextMenuAction[];\n}): Array<ContextMenuAction & { label: string; icon: IconName }> | null {\n  const menu = getMenuActions(options);\n  if (menu.length > 2)\n    return null;\n  const inline = menu.map(action => {\n    const kind = actionKind(action);\n    return { ...action, icon: action.icon ?? (kind ? STANDARD_ICONS[kind] : undefined) };\n  });\n  return inline.every(action => action.icon) ? inline as Array<ContextMenuAction & { label: string; icon: IconName }> : null;\n}\n\n/** Width of the actions column: one button (or the menu button) fits the standard 48px; a coarse pointer gets 48px buttons. */\nexport function getRowActionsWidth(options: { buttons: number }): number {\n  return Math.max(48, options.buttons * 48);\n}\n\n/** Clamps a measured menu to an eight-pixel viewport margin.\n    When a menu itself exceeds the viewport, its top-left edge remains reachable.\n*/\nexport function getMenuPosition(options: {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n  viewportWidth: number;\n  viewportHeight: number;\n}): { x: number; y: number } {\n  return {\n    x: Math.max(8, Math.min(options.x, options.viewportWidth - options.width - 8)),\n    y: Math.max(8, Math.min(options.y, options.viewportHeight - options.height - 8)),\n  };\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {nothing} from '../lit-html.js';\n\n/**\n * For AttributeParts, sets the attribute if the value is defined and removes\n * the attribute if the value is undefined.\n *\n * For other part types, this directive is a no-op.\n */\nexport const ifDefined = <T>(value: T) => value ?? nothing;\n","// GENERATED FILE, DO NOT EDIT BY HAND.\n// Run scripts/dev/generate-icons.mjs after changing the ICONS list in that script. Geometry comes\n// from @carbon/icons (Apache-2.0).\n//\n// Each entry is a list of [svgTagName, attributes] pairs, rendered by the Icon helper in screen/icon.ts into an\n// <svg viewBox=\"0 0 32 32\" fill=\"currentColor\">.\n\nexport type IconNode = Array<[string, Record<string, string>]>;\n\nexport type IconName =\n  | \"add\"\n  | \"analytics\"\n  | \"arrow--left\"\n  | \"arrow--right\"\n  | \"asleep\"\n  | \"checkmark\"\n  | \"checkmark--filled\"\n  | \"checkmark--outline\"\n  | \"chevron--down\"\n  | \"chevron--left\"\n  | \"chevron--right\"\n  | \"circle--solid\"\n  | \"close\"\n  | \"connect\"\n  | \"copy\"\n  | \"dashboard\"\n  | \"document\"\n  | \"edit\"\n  | \"email\"\n  | \"error--filled\"\n  | \"fit-to-screen\"\n  | \"flag\"\n  | \"flow\"\n  | \"hourglass\"\n  | \"information--filled\"\n  | \"light\"\n  | \"link\"\n  | \"logout\"\n  | \"magic-wand\"\n  | \"menu\"\n  | \"overflow-menu--vertical\"\n  | \"party-popper\"\n  | \"pause--outline\"\n  | \"play--filled--alt\"\n  | \"play--outline\"\n  | \"redo\"\n  | \"renew\"\n  | \"restart\"\n  | \"search\"\n  | \"send\"\n  | \"settings\"\n  | \"settings--adjust\"\n  | \"skip--forward\"\n  | \"stop--filled\"\n  | \"store\"\n  | \"time\"\n  | \"trash-can\"\n  | \"undo\"\n  | \"user--avatar\"\n  | \"user--follow\"\n  | \"zoom--in\"\n  | \"zoom--out\";\n\nexport const ICON_DATA: Record<IconName, IconNode> = {\n  \"add\": [[\"path\",{\"d\":\"M17 15 17 8 15 8 15 15 8 15 8 17 15 17 15 24 17 24 17 17 24 17 24 15z\"}]],\n  \"analytics\": [[\"path\",{\"d\":\"M4,2H2V28a2,2,0,0,0,2,2H30V28H4Z\"}],[\"path\",{\"d\":\"M30,9H23v2h3.59L19,18.59l-4.29-4.3a1,1,0,0,0-1.42,0L6,21.59,7.41,23,14,16.41l4.29,4.3a1,1,0,0,0,1.42,0L28,12.41V16h2Z\"}]],\n  \"arrow--left\": [[\"path\",{\"d\":\"M14 26 15.41 24.59 7.83 17 28 17 28 15 7.83 15 15.41 7.41 14 6 4 16 14 26z\"}]],\n  \"arrow--right\": [[\"path\",{\"d\":\"M18 6 16.57 7.393 24.15 15 4 15 4 17 24.15 17 16.57 24.573 18 26 28 16 18 6z\"}]],\n  \"asleep\": [[\"path\",{\"d\":\"M13.5025,5.4136A15.0755,15.0755,0,0,0,25.096,23.6082a11.1134,11.1134,0,0,1-7.9749,3.3893c-.1385,0-.2782.0051-.4178,0A11.0944,11.0944,0,0,1,13.5025,5.4136M14.98,3a1.0024,1.0024,0,0,0-.1746.0156A13.0959,13.0959,0,0,0,16.63,28.9973c.1641.006.3282,0,.4909,0a13.0724,13.0724,0,0,0,10.702-5.5556,1.0094,1.0094,0,0,0-.7833-1.5644A13.08,13.08,0,0,1,15.8892,4.38,1.0149,1.0149,0,0,0,14.98,3Z\"}]],\n  \"checkmark\": [[\"path\",{\"d\":\"M13 24 4 15 5.414 13.586 13 21.171 26.586 7.586 28 9 13 24z\"}]],\n  \"checkmark--filled\": [[\"path\",{\"d\":\"M16,2A14,14,0,1,0,30,16,14,14,0,0,0,16,2ZM14,21.5908l-5-5L10.5906,15,14,18.4092,21.41,11l1.5957,1.5859Z\"}],[\"path\",{\"fill\":\"none\",\"d\":\"M14 21.591 9 16.591 10.591 15 14 18.409 21.41 11 23.005 12.585 14 21.591z\",\"data-icon-path\":\"inner-path\"}]],\n  \"checkmark--outline\": [[\"path\",{\"d\":\"M14 21.414 9 16.413 10.413 15 14 18.586 21.585 11 23 12.415 14 21.414z\"}],[\"path\",{\"d\":\"M16,2A14,14,0,1,0,30,16,14,14,0,0,0,16,2Zm0,26A12,12,0,1,1,28,16,12,12,0,0,1,16,28Z\"}]],\n  \"chevron--down\": [[\"path\",{\"d\":\"M16 22 6 12 7.4 10.6 16 19.2 24.6 10.6 26 12z\"}]],\n  \"chevron--left\": [[\"path\",{\"d\":\"M10 16 20 6 21.4 7.4 12.8 16 21.4 24.6 20 26z\"}]],\n  \"chevron--right\": [[\"path\",{\"d\":\"M22 16 12 26 10.6 24.6 19.2 16 10.6 7.4 12 6z\"}]],\n  \"circle--solid\": [[\"circle\",{\"cx\":\"16\",\"cy\":\"16\",\"r\":\"14\"}]],\n  \"close\": [[\"path\",{\"d\":\"M17.4141 16 24 9.4141 22.5859 8 16 14.5859 9.4143 8 8 9.4141 14.5859 16 8 22.5859 9.4143 24 16 17.4141 22.5859 24 24 22.5859 17.4141 16z\"}]],\n  \"connect\": [[\"path\",{\"d\":\"M23,16a7,7,0,0,0-4.18,1.39L14.6,13.17A6.86,6.86,0,0,0,16,9a7,7,0,1,0-2.81,5.59l4.21,4.22A7,7,0,1,0,23,16ZM4,9a5,5,0,1,1,5,5A5,5,0,0,1,4,9Z\",\"transform\":\"translate(0 .01)\"}]],\n  \"copy\": [[\"path\",{\"d\":\"M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z\"}],[\"path\",{\"d\":\"M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z\"}]],\n  \"dashboard\": [[\"path\",{\"d\":\"M24 21H26V26H24z\"}],[\"path\",{\"d\":\"M20 16H22V26H20z\"}],[\"path\",{\"d\":\"M11,26a5.0059,5.0059,0,0,1-5-5H8a3,3,0,1,0,3-3V16a5,5,0,0,1,0,10Z\"}],[\"path\",{\"d\":\"M28,2H4A2.002,2.002,0,0,0,2,4V28a2.0023,2.0023,0,0,0,2,2H28a2.0027,2.0027,0,0,0,2-2V4A2.0023,2.0023,0,0,0,28,2Zm0,9H14V4H28ZM12,4v7H4V4ZM4,28V13H28.0007l.0013,15Z\"}]],\n  \"document\": [[\"path\",{\"d\":\"M25.7,9.3l-7-7C18.5,2.1,18.3,2,18,2H8C6.9,2,6,2.9,6,4v24c0,1.1,0.9,2,2,2h16c1.1,0,2-0.9,2-2V10C26,9.7,25.9,9.5,25.7,9.3 z M18,4.4l5.6,5.6H18V4.4z M24,28H8V4h8v6c0,1.1,0.9,2,2,2h6V28z\"}],[\"path\",{\"d\":\"M10 22H22V24H10z\"}],[\"path\",{\"d\":\"M10 16H22V18H10z\"}]],\n  \"edit\": [[\"path\",{\"d\":\"M2 26H30V28H2z\"}],[\"path\",{\"d\":\"M25.4,9c0.8-0.8,0.8-2,0-2.8c0,0,0,0,0,0l-3.6-3.6c-0.8-0.8-2-0.8-2.8,0c0,0,0,0,0,0l-15,15V24h6.4L25.4,9z M20.4,4L24,7.6 l-3,3L17.4,7L20.4,4z M6,22v-3.6l10-10l3.6,3.6l-10,10H6z\"}]],\n  \"email\": [[\"path\",{\"d\":\"M28,6H4A2,2,0,0,0,2,8V24a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V8A2,2,0,0,0,28,6ZM25.8,8,16,14.78,6.2,8ZM4,24V8.91l11.43,7.91a1,1,0,0,0,1.14,0L28,8.91V24Z\"}]],\n  \"error--filled\": [[\"path\",{\"fill\":\"none\",\"d\":\"M14.9 7.2H17.1V24.799H14.9z\",\"data-icon-path\":\"inner-path\",\"transform\":\"rotate(-45 16 16)\"}],[\"path\",{\"d\":\"M16,2A13.914,13.914,0,0,0,2,16,13.914,13.914,0,0,0,16,30,13.914,13.914,0,0,0,30,16,13.914,13.914,0,0,0,16,2Zm5.4449,21L9,10.5557,10.5557,9,23,21.4448Z\"}]],\n  \"fit-to-screen\": [[\"path\",{\"d\":\"M22 16 24 16 24 8 16 8 16 10 22 10 22 16z\"}],[\"path\",{\"d\":\"M8 24 16 24 16 22 10 22 10 16 8 16 8 24z\"}],[\"path\",{\"d\":\"M26,28H6a2.0023,2.0023,0,0,1-2-2V6A2.0023,2.0023,0,0,1,6,4H26a2.0023,2.0023,0,0,1,2,2V26A2.0023,2.0023,0,0,1,26,28ZM6,6V26H26.0012L26,6Z\"}]],\n  \"flag\": [[\"path\",{\"d\":\"M6,30H4V2H28l-5.8,9L28,20H6ZM6,18H24.33L19.8,11l4.53-7H6Z\"}]],\n  \"flow\": [[\"path\",{\"d\":\"M27,22.14V17a2,2,0,0,0-2-2H17V9.86a4,4,0,1,0-2,0V15H7a2,2,0,0,0-2,2v5.14a4,4,0,1,0,2,0V17H25v5.14a4,4,0,1,0,2,0ZM8,26a2,2,0,1,1-2-2A2,2,0,0,1,8,26ZM14,6a2,2,0,1,1,2,2A2,2,0,0,1,14,6ZM26,28a2,2,0,1,1,2-2A2,2,0,0,1,26,28Z\"}]],\n  \"hourglass\": [[\"path\",{\"d\":\"M15 19H17V21H15z\"}],[\"path\",{\"d\":\"M15 23H17V25H15z\"}],[\"path\",{\"d\":\"M23,11.67V4h3V2H6V4H9v7.67a2,2,0,0,0,.4,1.2L11.75,16,9.4,19.13a2,2,0,0,0-.4,1.2V28H6v2H26V28H23V20.33a2,2,0,0,0-.4-1.2L20.25,16l2.35-3.13A2,2,0,0,0,23,11.67ZM21,4v7H11V4Zm0,16.33V28H11V20.33L14.25,16,12,13h8l-2.25,3Z\"}]],\n  \"information--filled\": [[\"path\",{\"fill\":\"none\",\"d\":\"M16,8a1.5,1.5,0,1,1-1.5,1.5A1.5,1.5,0,0,1,16,8Zm4,13.875H17.125v-8H13v2.25h1.875v5.75H12v2.25h8Z\",\"data-icon-path\":\"inner-path\"}],[\"path\",{\"d\":\"M16,2A14,14,0,1,0,30,16,14,14,0,0,0,16,2Zm0,6a1.5,1.5,0,1,1-1.5,1.5A1.5,1.5,0,0,1,16,8Zm4,16.125H12v-2.25h2.875v-5.75H13v-2.25h4.125v8H20Z\"}]],\n  \"light\": [[\"path\",{\"d\":\"M15 2H17V7H15z\"}],[\"path\",{\"d\":\"M21.668 6.854H26.625999999999998V8.854H21.668z\",\"transform\":\"rotate(-45 24.147 7.853)\"}],[\"path\",{\"d\":\"M25 15H30V17H25z\"}],[\"path\",{\"d\":\"M23.147 21.668H25.147V26.625999999999998H23.147z\",\"transform\":\"rotate(-45 24.147 24.146)\"}],[\"path\",{\"d\":\"M15 25H17V30H15z\"}],[\"path\",{\"d\":\"M5.375 23.147H10.333V25.147H5.375z\",\"transform\":\"rotate(-45 7.853 24.146)\"}],[\"path\",{\"d\":\"M2 15H7V17H2z\"}],[\"path\",{\"d\":\"M6.854 5.375H8.854V10.333H6.854z\",\"transform\":\"rotate(-45 7.854 7.853)\"}],[\"path\",{\"d\":\"M16,12a4,4,0,1,1-4,4,4.0045,4.0045,0,0,1,4-4m0-2a6,6,0,1,0,6,6,6,6,0,0,0-6-6Z\"}]],\n  \"link\": [[\"path\",{\"d\":\"M29.25,6.76a6,6,0,0,0-8.5,0l1.42,1.42a4,4,0,1,1,5.67,5.67l-8,8a4,4,0,1,1-5.67-5.66l1.41-1.42-1.41-1.42-1.42,1.42a6,6,0,0,0,0,8.5A6,6,0,0,0,17,25a6,6,0,0,0,4.27-1.76l8-8A6,6,0,0,0,29.25,6.76Z\"}],[\"path\",{\"d\":\"M4.19,24.82a4,4,0,0,1,0-5.67l8-8a4,4,0,0,1,5.67,0A3.94,3.94,0,0,1,19,14a4,4,0,0,1-1.17,2.85L15.71,19l1.42,1.42,2.12-2.12a6,6,0,0,0-8.51-8.51l-8,8a6,6,0,0,0,0,8.51A6,6,0,0,0,7,28a6.07,6.07,0,0,0,4.28-1.76L9.86,24.82A4,4,0,0,1,4.19,24.82Z\"}]],\n  \"logout\": [[\"path\",{\"d\":\"M6,30H18a2.0023,2.0023,0,0,0,2-2V25H18v3H6V4H18V7h2V4a2.0023,2.0023,0,0,0-2-2H6A2.0023,2.0023,0,0,0,4,4V28A2.0023,2.0023,0,0,0,6,30Z\"}],[\"path\",{\"d\":\"M20.586 20.586 24.172 17 10 17 10 15 24.172 15 20.586 11.414 22 10 28 16 22 22 20.586 20.586z\"}]],\n  \"magic-wand\": [[\"path\",{\"d\":\"M29.4141,24,12,6.5859a2.0476,2.0476,0,0,0-2.8281,0l-2.586,2.586a2.0021,2.0021,0,0,0,0,2.8281L23.999,29.4141a2.0024,2.0024,0,0,0,2.8281,0l2.587-2.5865a1.9993,1.9993,0,0,0,0-2.8281ZM8,10.5859,10.5859,8l5,5-2.5866,2.5869-5-5ZM25.4131,28l-11-10.999L17,14.4141l11,11Z\"}],[\"path\",{\"d\":\"M2.586 14.586H5.414V17.414H2.586z\",\"transform\":\"rotate(-45 4 16)\"}],[\"path\",{\"d\":\"M14.586 2.586H17.414V5.414H14.586z\",\"transform\":\"rotate(-45 16 4)\"}],[\"path\",{\"d\":\"M2.586 2.586H5.414V5.414H2.586z\",\"transform\":\"rotate(-45 4 4)\"}]],\n  \"menu\": [[\"path\",{\"d\":\"M4 6H28V8H4z\"}],[\"path\",{\"d\":\"M4 24H28V26H4z\"}],[\"path\",{\"d\":\"M4 12H28V14H4z\"}],[\"path\",{\"d\":\"M4 18H28V20H4z\"}]],\n  \"overflow-menu--vertical\": [[\"circle\",{\"cx\":\"16\",\"cy\":\"8\",\"r\":\"2\"}],[\"circle\",{\"cx\":\"16\",\"cy\":\"16\",\"r\":\"2\"}],[\"circle\",{\"cx\":\"16\",\"cy\":\"24\",\"r\":\"2\"}]],\n  \"party-popper\": [[\"path\",{\"d\":\"M5,28c-.2607,0-.5161-.1016-.707-.293-.2749-.2744-.3657-.6836-.2329-1.0488L12.0601,4.6582c.1172-.3213.3896-.5605.7231-.6343.3335-.0757.6821.0269.9238.269l14,14c.2422.2412.3428.5898.2695.9238-.0742.333-.3135.6064-.6348.7227L5.3418,27.9395c-.1113.041-.2271.0605-.3418.0605ZM9.1367,18.5508l-2.4648,6.7773,6.7773-2.4648-4.3125-4.3125ZM9.8906,16.4766l5.6328,5.6328,3.793-1.3789-8.0464-8.0464-1.3794,3.7925ZM12.0239,10.6099l9.3657,9.3657,3.793-1.3789L13.4033,6.8174l-1.3794,3.7925ZM30,13h-4v-2h4v2ZM25.0127,8.4019l-1.4141-1.4141,3.3926-3.3931,1.4141,1.4141-3.3926,3.3931ZM21,6h-2V2h2v4Z\"}]],\n  \"pause--outline\": [[\"path\",{\"d\":\"M14 10 12 10 12 22 14 22 14 10 14 10z\"}],[\"path\",{\"d\":\"M20 10 18 10 18 22 20 22 20 10 20 10z\"}],[\"path\",{\"d\":\"M16,4A12,12,0,1,1,4,16,12,12,0,0,1,16,4m0-2A14,14,0,1,0,30,16,14,14,0,0,0,16,2Z\"}]],\n  \"play--filled--alt\": [[\"path\",{\"d\":\"M7,28a1,1,0,0,1-1-1V5a1,1,0,0,1,1.4819-.8763l20,11a1,1,0,0,1,0,1.7525l-20,11A1.0005,1.0005,0,0,1,7,28Z\"}]],\n  \"play--outline\": [[\"path\",{\"d\":\"M11,23a1,1,0,0,1-1-1V10a1,1,0,0,1,1.4473-.8945l12,6a1,1,0,0,1,0,1.789l-12,6A1.001,1.001,0,0,1,11,23Zm1-11.3821v8.7642L20.7642,16Z\"}],[\"path\",{\"d\":\"M16,4A12,12,0,1,1,4,16,12,12,0,0,1,16,4m0-2A14,14,0,1,0,30,16,14,14,0,0,0,16,2Z\"}]],\n  \"redo\": [[\"path\",{\"d\":\"M12,10H24.1851L20.5977,6.4141,22,5,28,11,22,17l-1.4023-1.4146L24.1821,12H12a6,6,0,0,0,0,12h8v2H12a8,8,0,0,1,0-16Z\"}]],\n  \"renew\": [[\"path\",{\"d\":\"M12,10H6.78A11,11,0,0,1,27,16h2A13,13,0,0,0,6,7.68V4H4v8h8Z\"}],[\"path\",{\"d\":\"M20,22h5.22A11,11,0,0,1,5,16H3a13,13,0,0,0,23,8.32V28h2V20H20Z\"}]],\n  \"restart\": [[\"path\",{\"d\":\"M26,18A10,10,0,1,1,16,8h6.1821l-3.5844,3.5854L20,13l6-6L20,1,18.5977,2.414,22.1851,6H16A12,12,0,1,0,28,18Z\"}]],\n  \"search\": [[\"path\",{\"d\":\"M29,27.5859l-7.5521-7.5521a11.0177,11.0177,0,1,0-1.4141,1.4141L27.5859,29ZM4,13a9,9,0,1,1,9,9A9.01,9.01,0,0,1,4,13Z\"}]],\n  \"send\": [[\"path\",{\"d\":\"M27.45,15.11l-22-11a1,1,0,0,0-1.08.12,1,1,0,0,0-.33,1L7,16,4,26.74A1,1,0,0,0,5,28a1,1,0,0,0,.45-.11l22-11a1,1,0,0,0,0-1.78Zm-20.9,10L8.76,17H18V15H8.76L6.55,6.89,24.76,16Z\"}]],\n  \"settings\": [[\"path\",{\"d\":\"M27,16.76c0-.25,0-.5,0-.76s0-.51,0-.77l1.92-1.68A2,2,0,0,0,29.3,11L26.94,7a2,2,0,0,0-1.73-1,2,2,0,0,0-.64.1l-2.43.82a11.35,11.35,0,0,0-1.31-.75l-.51-2.52a2,2,0,0,0-2-1.61H13.64a2,2,0,0,0-2,1.61l-.51,2.52a11.48,11.48,0,0,0-1.32.75L7.43,6.06A2,2,0,0,0,6.79,6,2,2,0,0,0,5.06,7L2.7,11a2,2,0,0,0,.41,2.51L5,15.24c0,.25,0,.5,0,.76s0,.51,0,.77L3.11,18.45A2,2,0,0,0,2.7,21L5.06,25a2,2,0,0,0,1.73,1,2,2,0,0,0,.64-.1l2.43-.82a11.35,11.35,0,0,0,1.31.75l.51,2.52a2,2,0,0,0,2,1.61h4.72a2,2,0,0,0,2-1.61l.51-2.52a11.48,11.48,0,0,0,1.32-.75l2.42.82a2,2,0,0,0,.64.1,2,2,0,0,0,1.73-1L29.3,21a2,2,0,0,0-.41-2.51ZM25.21,24l-3.43-1.16a8.86,8.86,0,0,1-2.71,1.57L18.36,28H13.64l-.71-3.55a9.36,9.36,0,0,1-2.7-1.57L6.79,24,4.43,20l2.72-2.4a8.9,8.9,0,0,1,0-3.13L4.43,12,6.79,8l3.43,1.16a8.86,8.86,0,0,1,2.71-1.57L13.64,4h4.72l.71,3.55a9.36,9.36,0,0,1,2.7,1.57L25.21,8,27.57,12l-2.72,2.4a8.9,8.9,0,0,1,0,3.13L27.57,20Z\"}],[\"path\",{\"d\":\"M16,22a6,6,0,1,1,6-6A5.94,5.94,0,0,1,16,22Zm0-10a3.91,3.91,0,0,0-4,4,3.91,3.91,0,0,0,4,4,3.91,3.91,0,0,0,4-4A3.91,3.91,0,0,0,16,12Z\"}]],\n  \"settings--adjust\": [[\"path\",{\"d\":\"M30,8h-4.1c-0.5-2.3-2.5-4-4.9-4s-4.4,1.7-4.9,4H2v2h14.1c0.5,2.3,2.5,4,4.9,4s4.4-1.7,4.9-4H30V8z M21,12c-1.7,0-3-1.3-3-3 s1.3-3,3-3s3,1.3,3,3S22.7,12,21,12z\"}],[\"path\",{\"d\":\"M2,24h4.1c0.5,2.3,2.5,4,4.9,4s4.4-1.7,4.9-4H30v-2H15.9c-0.5-2.3-2.5-4-4.9-4s-4.4,1.7-4.9,4H2V24z M11,20c1.7,0,3,1.3,3,3 s-1.3,3-3,3s-3-1.3-3-3S9.3,20,11,20z\"}]],\n  \"skip--forward\": [[\"path\",{\"d\":\"M5,28a1,1,0,0,1-1-1V5a1,1,0,0,1,.5-.87,1,1,0,0,1,1,0l19,11a1,1,0,0,1,0,1.74l-19,11A1,1,0,0,1,5,28ZM6,6.73V25.27L22,16Z\"}],[\"path\",{\"d\":\"M28 4H30V28H28z\"}]],\n  \"stop--filled\": [[\"path\",{\"d\":\"M16,2A14,14,0,1,0,30,16,14,14,0,0,0,16,2Zm6,18a2,2,0,0,1-2,2H12a2,2,0,0,1-2-2V12a2,2,0,0,1,2-2h8a2,2,0,0,1,2,2Z\"}]],\n  \"store\": [[\"path\",{\"d\":\"M30,10.68l-2-6A1,1,0,0,0,27,4H5a1,1,0,0,0-1,.68l-2,6A1.19,1.19,0,0,0,2,11v6a1,1,0,0,0,1,1H4V28H6V18h6V28H28V18h1a1,1,0,0,0,1-1V11A1.19,1.19,0,0,0,30,10.68ZM26,26H14V18H26Zm2-10H24V12H22v4H17V12H15v4H10V12H8v4H4V11.16L5.72,6H26.28L28,11.16Z\"}]],\n  \"time\": [[\"path\",{\"d\":\"M16,30A14,14,0,1,1,30,16,14,14,0,0,1,16,30ZM16,4A12,12,0,1,0,28,16,12,12,0,0,0,16,4Z\"}],[\"path\",{\"d\":\"M20.59 22 15 16.41 15 7 17 7 17 15.58 22 20.59 20.59 22z\"}]],\n  \"trash-can\": [[\"path\",{\"d\":\"M12 12H14V24H12z\"}],[\"path\",{\"d\":\"M18 12H20V24H18z\"}],[\"path\",{\"d\":\"M4,6V8H6V28a2,2,0,0,0,2,2H24a2,2,0,0,0,2-2V8h2V6ZM8,28V8H24V28Z\"}],[\"path\",{\"d\":\"M12 2H20V4H12z\"}]],\n  \"undo\": [[\"path\",{\"d\":\"M20,10H7.8149l3.5874-3.5859L10,5,4,11,10,17l1.4023-1.4146L7.8179,12H20a6,6,0,0,1,0,12H12v2h8a8,8,0,0,0,0-16Z\"}]],\n  \"user--avatar\": [[\"path\",{\"d\":\"M16,8a5,5,0,1,0,5,5A5,5,0,0,0,16,8Zm0,8a3,3,0,1,1,3-3A3.0034,3.0034,0,0,1,16,16Z\"}],[\"path\",{\"d\":\"M16,2A14,14,0,1,0,30,16,14.0158,14.0158,0,0,0,16,2ZM10,26.3765V25a3.0033,3.0033,0,0,1,3-3h6a3.0033,3.0033,0,0,1,3,3v1.3765a11.8989,11.8989,0,0,1-12,0Zm13.9925-1.4507A5.0016,5.0016,0,0,0,19,20H13a5.0016,5.0016,0,0,0-4.9925,4.9258,12,12,0,1,1,15.985,0Z\"}]],\n  \"user--follow\": [[\"path\",{\"d\":\"M32 14 28 14 28 10 26 10 26 14 22 14 22 16 26 16 26 20 28 20 28 16 32 16 32 14z\"}],[\"path\",{\"d\":\"M12,4A5,5,0,1,1,7,9a5,5,0,0,1,5-5m0-2a7,7,0,1,0,7,7A7,7,0,0,0,12,2Z\"}],[\"path\",{\"d\":\"M22,30H20V25a5,5,0,0,0-5-5H9a5,5,0,0,0-5,5v5H2V25a7,7,0,0,1,7-7h6a7,7,0,0,1,7,7Z\"}]],\n  \"zoom--in\": [[\"path\",{\"d\":\"M18 12 14 12 14 8 12 8 12 12 8 12 8 14 12 14 12 18 14 18 14 14 18 14 18 12z\"}],[\"path\",{\"d\":\"M21.4479,20A10.856,10.856,0,0,0,24,13,11,11,0,1,0,13,24a10.856,10.856,0,0,0,7-2.5521L27.5859,29,29,27.5859ZM13,22a9,9,0,1,1,9-9A9.01,9.01,0,0,1,13,22Z\"}]],\n  \"zoom--out\": [[\"path\",{\"d\":\"M8 12H18V14H8z\"}],[\"path\",{\"d\":\"M21.4479,20A10.856,10.856,0,0,0,24,13,11,11,0,1,0,13,24a10.856,10.856,0,0,0,7-2.5521L27.5859,29,29,27.5859ZM13,22a9,9,0,1,1,9-9A9.01,9.01,0,0,1,13,22Z\"}]],\n};\n","import { svg, html } from \"lit\";\nimport { ifDefined } from \"lit/directives/if-defined.js\";\nimport { ICON_DATA, type IconName } from \"../icons/icon-data\";\n\n/** One Carbon glyph from the generated table (scripts/dev/generate-icons.mjs); decorative only. */\nexport function icon(name: IconName, size = 16) {\n  return html`<svg class=\"companyos-icon\" width=${size} height=${size} viewBox=\"0 0 32 32\" fill=\"currentColor\" aria-hidden=\"true\" focusable=\"false\">${\n    ICON_DATA[name].map(([tag, attrs]) => tag === \"circle\"\n      ? svg`<circle cx=${attrs.cx} cy=${attrs.cy} r=${attrs.r}></circle>`\n      : svg`<path d=${attrs.d} transform=${ifDefined(attrs.transform)} fill=${ifDefined(attrs.fill)}></path>`)}</svg>`;\n}\n","import { render } from \"lit\";\nimport { getMenuPosition } from \"./lib/context-menu\";\nimport { icon } from \"./screen/icon\";\nimport type { IconName } from \"./icons/icon-data\";\nimport \"./menu.scss\";\n\nexport interface MenuItemOptions {\n  id?: string;\n  label: string;\n  icon?: IconName;\n  checked?: boolean;\n  disabled?: boolean;\n  danger?: boolean;\n  onSelect: () => void;\n}\n\n/** A group shares its containing menu's keyboard navigation and lifecycle. */\nexport class CompanyosMenuItems {\n  public readonly element: HTMLElement;\n  #owner?: CompanyosMenu;\n\n  protected constructor(options: { element: HTMLElement; owner?: CompanyosMenu }) {\n    this.element = options.element;\n    this.#owner = options.owner;\n  }\n\n  protected get menu(): CompanyosMenu {\n    return this.#owner!;\n  }\n\n  public addMenuItem(options: MenuItemOptions): HTMLButtonElement {\n    const button = this.#button(options);\n    button.addEventListener(\"click\", () => {\n      this.menu.closeRoot();\n      options.onSelect();\n    });\n    return button;\n  }\n\n  public addSeparator(): void {\n    const separator = document.createElement(\"div\");\n    separator.className = \"companyos-menu__separator\";\n    separator.setAttribute(\"role\", \"separator\");\n    this.element.append(separator);\n  }\n\n  public addGroup(options: { label: string }): CompanyosMenuItems {\n    const element = document.createElement(\"div\");\n    element.setAttribute(\"role\", \"group\");\n    element.setAttribute(\"aria-label\", options.label);\n    this.element.append(element);\n    return new CompanyosMenuItems({ element, owner: this.menu });\n  }\n\n  public addSubmenu(options: { id?: string; label: string }): CompanyosMenu {\n    const trigger = this.#button({ id: options.id ? `${options.id}-trigger` : undefined, label: options.label, icon: \"chevron--right\" });\n    const child = new CompanyosMenu({ label: options.label });\n    if (options.id)\n      child.element.id = options.id;\n    this.element.append(child.element);\n    this.menu.attachSubmenu({ trigger, menu: child });\n    return child;\n  }\n\n  #button(options: Omit<MenuItemOptions, \"onSelect\">): HTMLButtonElement {\n    const button = document.createElement(\"button\");\n    button.type = \"button\";\n    button.className = \"companyos-menu__item\";\n    button.id = options.id ?? \"\";\n    button.tabIndex = -1;\n    button.disabled = options.disabled ?? false;\n    button.setAttribute(\"role\", options.checked === undefined ? \"menuitem\" : \"menuitemradio\");\n    if (options.checked !== undefined)\n      button.setAttribute(\"aria-checked\", String(options.checked));\n    button.classList.toggle(\"companyos-menu__item--danger\", options.danger ?? false);\n    const label = document.createElement(\"span\");\n    label.className = \"companyos-menu__label\";\n    label.textContent = options.label;\n    button.append(label);\n    if (options.checked !== undefined || options.icon) {\n      const glyph = document.createElement(\"span\");\n      glyph.className = \"companyos-menu__icon\";\n      render(icon(options.checked !== undefined ? \"checkmark\" : options.icon!), glyph);\n      button.append(glyph);\n    }\n    this.element.append(button);\n    return button;\n  }\n}\n\nconst MENU_ID = Symbol.for(\"companyos.menu-id\");\nconst menuIds = globalThis as typeof globalThis & { [MENU_ID]?: number };\n\n/** Shared menu for buttons, context menus and submenus. Destroy when its owning screen is removed. */\nexport class CompanyosMenu extends CompanyosMenuItems {\n  #panel: HTMLElement;\n  #trigger?: HTMLElement;\n  #parent?: CompanyosMenu;\n  #children = new Map<HTMLElement, CompanyosMenu>();\n  #activeChild?: CompanyosMenu;\n  #closeTimer?: ReturnType<typeof setTimeout>;\n  #listeners = new AbortController();\n  #openListeners?: AbortController;\n  #open = false;\n  #onClose?: () => void;\n\n  public constructor(options: { label: string; element?: HTMLElement; panel?: HTMLElement; onClose?: () => void }) {\n    super({ element: options.element ?? document.createElement(\"div\") });\n    this.#panel = options.panel ?? this.element;\n    this.#onClose = options.onClose;\n    this.element.id ||= `companyos-menu-${menuIds[MENU_ID] = (menuIds[MENU_ID] ?? 0) + 1}`;\n    this.element.classList.add(\"companyos-menu\");\n    this.element.setAttribute(\"role\", \"menu\");\n    this.element.setAttribute(\"aria-label\", options.label);\n    this.#panel.classList.add(\"companyos-menu-panel\");\n    // Native top-layer positioning, shared dismissal: contextmenu can open before pointer-up light dismiss.\n    this.#panel.popover = \"manual\";\n    this.#panel.hidden = true;\n    const signal = this.#listeners.signal;\n    this.element.addEventListener(\"keydown\", event => this.#onKeydown(event), { signal });\n    this.element.addEventListener(\"pointerover\", event => {\n      if (event.pointerType === \"touch\")\n        return;\n      clearTimeout(this.#closeTimer);\n      const target = (event.target as Element).closest<HTMLElement>(\"[role^=menuitem]\");\n      const child = target ? this.#children.get(target) : undefined;\n      if (child)\n        this.#openSubmenu({ menu: child, focus: false });\n    }, { signal });\n    this.element.addEventListener(\"pointerout\", event => {\n      const child = this.#activeChild;\n      const target = event.relatedTarget as Node | null;\n      if (event.pointerType !== \"touch\" && child && !child.#panel.contains(target) && !child.#trigger!.contains(target)) {\n        // Allow crossing the border and moving diagonally from the trigger into its submenu.\n        clearTimeout(this.#closeTimer);\n        this.#closeTimer = setTimeout(() => child.close({ restoreFocus: child.#panel.contains(document.activeElement) }), 150);\n      }\n    }, { signal });\n  }\n\n  public get isOpen(): boolean {\n    return this.#open;\n  }\n\n  protected override get menu(): CompanyosMenu {\n    return this;\n  }\n\n  public bindTrigger(trigger: HTMLElement): void {\n    this.#setTrigger(trigger);\n    const signal = this.#listeners.signal;\n    trigger.addEventListener(\"click\", () => this.isOpen ? this.close() : this.open({ trigger }), { signal });\n    trigger.addEventListener(\"keydown\", event => {\n      if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n        event.preventDefault();\n        this.open({ trigger, focus: event.key === \"ArrowUp\" ? \"last\" : \"first\" });\n      }\n    }, { signal });\n  }\n\n  public open(options: { trigger: HTMLElement; point?: { x: number; y: number }; focus?: \"first\" | \"last\" | false }): void {\n    this.#setTrigger(options.trigger);\n    this.#panel.hidden = false;\n    this.#panel.showPopover();\n    this.#open = true;\n    this.#trigger!.setAttribute(\"aria-expanded\", \"true\");\n    const anchor = options.trigger.getBoundingClientRect();\n    const parent = this.#parent ? this.#parent.#panel.getBoundingClientRect() : undefined;\n    const width = this.#panel.offsetWidth;\n    const point = options.point ?? (parent\n      ? { x: parent.left >= width + 8 ? parent.left - width : parent.right, y: anchor.top }\n      : { x: anchor.right - width, y: anchor.bottom + 4 });\n    const position = getMenuPosition({ ...point, width, height: this.#panel.offsetHeight, viewportWidth: innerWidth, viewportHeight: innerHeight });\n    this.#panel.style.left = `${position.x}px`;\n    this.#panel.style.top = `${position.y}px`;\n    if (!this.#parent) {\n      this.#openListeners?.abort();\n      this.#openListeners = new AbortController();\n      const signal = this.#openListeners.signal;\n      document.addEventListener(\"pointerdown\", event => {\n        if (!this.#panel.contains(event.target as Node) && !this.#trigger!.contains(event.target as Node))\n          this.close({ restoreFocus: false });\n      }, { signal });\n      document.addEventListener(\"focusin\", event => {\n        if (!this.#panel.contains(event.target as Node) && !this.#trigger!.contains(event.target as Node))\n          this.close({ restoreFocus: false });\n      }, { signal });\n      window.addEventListener(\"resize\", () => this.close(), { signal });\n    }\n    if (options.focus !== false) {\n      const items = this.#items();\n      items[options.focus === \"last\" ? items.length - 1 : 0]?.focus();\n    }\n  }\n\n  public close(options: { restoreFocus?: boolean } = {}): void {\n    clearTimeout(this.#closeTimer);\n    this.#activeChild?.close({ restoreFocus: false });\n    this.#activeChild = undefined;\n    this.#openListeners?.abort();\n    if (!this.#open)\n      return;\n    this.#open = false;\n    this.#panel.hidePopover();\n    this.#panel.hidden = true;\n    this.#trigger?.setAttribute(\"aria-expanded\", \"false\");\n    if (options.restoreFocus !== false && this.#trigger?.isConnected)\n      this.#trigger.focus();\n    this.#onClose?.();\n  }\n\n  public closeRoot(): void {\n    if (this.#parent)\n      this.#parent.closeRoot();\n    else\n      this.close();\n  }\n\n  public destroy(): void {\n    this.close({ restoreFocus: false });\n    this.#listeners.abort();\n    for (const child of this.#children.values())\n      child.destroy();\n    this.#panel.remove();\n  }\n\n  /** Used by addSubmenu; consumers normally use the builder. */\n  public attachSubmenu(options: { trigger: HTMLElement; menu: CompanyosMenu }): void {\n    const { trigger, menu } = options;\n    menu.#parent = this;\n    menu.#setTrigger(trigger);\n    this.#children.set(trigger, menu);\n    trigger.addEventListener(\"click\", () => this.#openSubmenu({ menu, focus: true }), { signal: this.#listeners.signal });\n  }\n\n  #setTrigger(trigger: HTMLElement): void {\n    this.#trigger = trigger;\n    trigger.setAttribute(\"aria-haspopup\", \"menu\");\n    trigger.setAttribute(\"aria-controls\", this.element.id);\n    trigger.setAttribute(\"aria-expanded\", String(this.#open));\n  }\n\n  #items(): HTMLElement[] {\n    return [...this.element.querySelectorAll<HTMLElement>(\"[role^=menuitem]:not(:disabled)\")]\n      .filter(item => item.closest(\"[role=menu]\") === this.element && !item.closest(\"[hidden]\"));\n  }\n\n  #openSubmenu(options: { menu: CompanyosMenu; focus: boolean }): void {\n    clearTimeout(this.#closeTimer);\n    if (this.#activeChild !== options.menu)\n      this.#activeChild?.close({ restoreFocus: false });\n    this.#activeChild = options.menu;\n    options.menu.open({ trigger: options.menu.#trigger!, focus: options.focus ? \"first\" : false });\n  }\n\n  #onKeydown(event: KeyboardEvent): void {\n    if ((event.target as Element).closest(\"[role=menu]\") !== this.element)\n      return;\n    event.stopPropagation();\n    const focused = document.activeElement as HTMLElement;\n    const child = this.#children.get(focused);\n    if (child && [\"ArrowRight\", \"Enter\", \" \"].includes(event.key)) {\n      event.preventDefault();\n      this.#openSubmenu({ menu: child, focus: true });\n      return;\n    }\n    if (event.key === \"Escape\" || (event.key === \"ArrowLeft\" && this.#parent)) {\n      event.preventDefault();\n      if (this.#activeChild?.isOpen)\n        this.#activeChild.close();\n      else\n        this.close();\n      return;\n    }\n    if (event.key === \"Tab\") {\n      this.closeRoot();\n      return;\n    }\n    const items = this.#items();\n    const index = items.indexOf(focused);\n    const next = { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: items.length - 1 }[event.key];\n    if (next !== undefined && items.length) {\n      event.preventDefault();\n      this.#activeChild?.close({ restoreFocus: false });\n      items[(next + items.length) % items.length].focus();\n    }\n  }\n}\n","export type Theme = \"dark\" | \"light\";\n\nexport interface ThemeEnvironment {\n  readStoredTheme: () => Theme | null;\n  writeStoredTheme: (theme: Theme) => void;\n  applyTheme: (theme: Theme) => void;\n}\n\n/** Owns page theme policy without browser globals, so fixed overlays can preserve preferences. */\nexport class ThemeController {\n  readonly #environment: ThemeEnvironment;\n  #theme: Theme = \"dark\";\n  #fixedTheme: Theme | undefined;\n\n  public constructor(environment: ThemeEnvironment) {\n    this.#environment = environment;\n  }\n\n  public get theme(): Theme {\n    return this.#theme;\n  }\n\n  public get canSwitchTheme(): boolean {\n    return this.#fixedTheme === undefined;\n  }\n\n  /** Applies a fixed theme without touching storage, or restores the user's standalone preference. */\n  public initialize(options: { fixedTheme?: Theme } = {}): void {\n    this.#fixedTheme = options.fixedTheme;\n    // Keep this short-circuited: even reading a previous preference is forbidden for fixed overlays.\n    this.#theme = options.fixedTheme ?? this.#environment.readStoredTheme() ?? \"dark\";\n    this.#environment.applyTheme(this.#theme);\n  }\n\n  public setTheme(next: Theme): void {\n    if (!this.canSwitchTheme)\n      return;\n    this.#theme = next;\n    this.#environment.applyTheme(next);\n    this.#environment.writeStoredTheme(next);\n  }\n\n  public toggleTheme(): void {\n    this.setTheme(this.#theme === \"dark\" ? \"light\" : \"dark\");\n  }\n}\n","// The visitor's light/dark choice on page base pages. The head script in shell.witty applied the stored choice before\n// the first paint; this switches it and stores it under the SPA's key (companyos:<brand>:theme), shared by the account\n// menu (account.ts) and the login's toggle below, so a choice made on one page carries over to the other.\nimport { ThemeController, type Theme } from \"./lib/theme\";\n\nexport function createPageTheme({ storageKey, onApply }: { storageKey: string; onApply: (theme: Theme) => void }): ThemeController {\n  const root = document.documentElement;\n  const controller = new ThemeController({\n    readStoredTheme: () => root.classList.contains(\"dark\") ? \"dark\" : \"light\",\n    writeStoredTheme(next) {\n      try {\n        localStorage.setItem(storageKey, next);\n      } catch {\n        // Storage denied: the theme still applies to this page view\n      }\n    },\n    applyTheme(next) {\n      root.classList.toggle(\"dark\", next === \"dark\");\n      onApply(next);\n    },\n  });\n  controller.initialize();\n  return controller;\n}\n\n/** The login's toggle button (shell.witty, loginscreen): pressed is dark. */\nfunction start() {\n  const button = document.querySelector<HTMLButtonElement>(\"[data-companyos-theme-toggle]\");\n  // Two asset packs on one page both import the page base; one setup is enough\n  if (!button || button.dataset.companyosThemeReady !== undefined)\n    return;\n  button.dataset.companyosThemeReady = \"\";\n  const theme = createPageTheme({ storageKey: button.dataset.companyosThemeKey!, onApply: next => button.setAttribute(\"aria-pressed\", String(next === \"dark\")) });\n  button.addEventListener(\"click\", () => theme.toggleTheme());\n}\n\nif (document.readyState === \"loading\")\n  document.addEventListener(\"DOMContentLoaded\", start, { once: true });\nelse\n  start();\n","// The account menu in the shell header (shell.witty): who is logged in, the light or dark theme, and logout.\n// Menu button pattern: Enter, Space and the arrow keys open it, Escape closes it and returns focus to the button,\n// Tab or a click elsewhere closes it. The published HTML holds no visitor data: the name comes from WRDAuth's cached\n// fields (siteprofile `cachefields`), the theme from localStorage, which the head script already applied before paint.\nimport { getUserInfo, isLoggedIn, logout } from \"@webhare/frontend\";\nimport { CompanyosMenu, type CompanyosMenuItems } from \"./menu\";\nimport { createPageTheme } from \"./theme\";\n\ninterface CachedUserInfo {\n  wrd_fullname?: string;\n  wrd_firstname?: string;\n  wrd_lastname?: string;\n  wrd_contact_email?: string;\n}\n\n/** Display name fallbacks: full name, first and last name, e-mail, \"Account\". */\nfunction displayName(info: CachedUserInfo | null): string {\n  const combined = `${info?.wrd_firstname?.trim() ?? \"\"} ${info?.wrd_lastname?.trim() ?? \"\"}`.trim();\n  return info?.wrd_fullname?.trim() || combined || info?.wrd_contact_email?.trim() || \"Account\";\n}\n\n// The same shell can be imported by multiple asset packs; share its extension group on the DOM node.\nconst ACCOUNT_ITEMS = Symbol.for(\"companyos.account-menu-items\");\ntype AccountElement = HTMLElement & { [ACCOUNT_ITEMS]?: CompanyosMenuItems };\n\n/** The extension group between theme and logout, or null without a session. Call after the shell is in the DOM. */\nexport function getAccountMenu(): CompanyosMenuItems | null {\n  start();\n  return document.querySelector<AccountElement>(\"[data-companyos-account]\")?.[ACCOUNT_ITEMS] ?? null;\n}\n\nfunction setupAccount(account: AccountElement): void {\n  account.hidden = !isLoggedIn();\n  if (account.hidden)\n    return;\n  const info = getUserInfo<CachedUserInfo>();\n  for (const name of account.querySelectorAll(\"[data-companyos-account-name]\"))\n    name.textContent = displayName(info);\n  const email = account.querySelector<HTMLElement>(\"[data-companyos-account-email]\")!;\n  email.textContent = info?.wrd_contact_email?.trim() ?? \"\";\n  email.hidden = !email.textContent;\n\n  const button = account.querySelector<HTMLButtonElement>(\"[aria-haspopup=menu]\")!;\n  const panel = account.querySelector<HTMLElement>(\"[data-companyos-account-popover]\")!;\n  const element = panel.querySelector<HTMLElement>(\"[role=menu]\")!;\n  element.replaceChildren();\n  const menu = new CompanyosMenu({ label: \"Account\", element, panel });\n  menu.bindTrigger(button);\n  const themes = menu.addGroup({ label: \"Thema\" });\n  const themeItems = ([{ value: \"light\", label: \"Licht\" }, { value: \"dark\", label: \"Donker\" }] as const).map(option => {\n    const item = themes.addMenuItem({ label: option.label, checked: false, onSelect: () => theme.setTheme(option.value) });\n    item.dataset.companyosTheme = option.value;\n    return item;\n  });\n  const theme = createPageTheme({\n    storageKey: account.dataset.companyosThemeKey!,\n    onApply(next) {\n      for (const item of themeItems)\n        item.setAttribute(\"aria-checked\", String(item.dataset.companyosTheme === next));\n    },\n  });\n  const accountItems = menu.addGroup({ label: \"Extra\" });\n  accountItems.element.dataset.companyosAccountSlot = \"\";\n  account[ACCOUNT_ITEMS] = accountItems;\n  menu.addSeparator();\n  const exit = menu.addMenuItem({ label: \"Uitloggen\", icon: \"logout\", onSelect: () => void logout() });\n  exit.classList.add(\"companyos-page__logout\");\n}\n\nfunction start() {\n  const account = document.querySelector<HTMLElement>(\"[data-companyos-account]\");\n  // Two asset packs on one page both import the page base; one setup is enough\n  if (account && account.dataset.companyosAccountReady === undefined) {\n    account.dataset.companyosAccountReady = \"\";\n    setupAccount(account);\n  }\n}\n\nif (document.readyState === \"loading\")\n  document.addEventListener(\"DOMContentLoaded\", start, { once: true });\nelse\n  start();\n","/** `<cos-page-header heading=\"...\" description=\"...\">`: the page title and its one-line lede. Pages write only this\n    element, never heading markup of their own, so every title stands in the same place. pages.scss reserves the height\n    and shows the attributes until the element is defined (also without JavaScript), so the upgrade moves nothing. */\nexport class CompanyosPageHeader extends HTMLElement {\n  public static readonly observedAttributes = [\"heading\", \"description\"];\n\n  public connectedCallback(): void {\n    this.#render();\n  }\n\n  public attributeChangedCallback(): void {\n    if (this.isConnected)\n      this.#render();\n  }\n\n  #render(): void {\n    const title = document.createElement(\"h1\");\n    title.textContent = this.getAttribute(\"heading\") ?? \"\";\n    const description = this.getAttribute(\"description\");\n    if (!description) {\n      this.replaceChildren(title);\n      return;\n    }\n    const lede = document.createElement(\"p\");\n    lede.textContent = description;\n    this.replaceChildren(title, lede);\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"cos-page-header\": CompanyosPageHeader;\n  }\n}\n\n// Two asset packs on one page both import the page base\nif (!customElements.get(\"cos-page-header\"))\n  customElements.define(\"cos-page-header\", CompanyosPageHeader);\n","/** The heading level for a titled framework element: h2 under the page header, one deeper for every enclosing\n    `<cos-section>`. Pages never choose a level themselves (docs/paginabasis.md, \"Secties\"). */\nexport function headingLevel(element: Element): number {\n  let level = 2;\n  for (let parent = element.parentElement?.closest(\"cos-section\"); parent; parent = parent.parentElement?.closest(\"cos-section\"))\n    level += 1;\n  return Math.min(level, 6);\n}\n\nlet headingIds = 0;\n\n/** `<cos-section heading=\"...\">`: a titled part of a page. Renders its heading as the first child, at the level its\n    nesting gives, and names itself a region by it. A child with `slot=\"actions\"` stands right of the heading; the\n    other children follow below. pages.scss shows the attribute until the element is defined (also without JavaScript),\n    so the upgrade moves nothing. Light DOM: the content stays where WebHare or Lit rendered it. */\nexport class CompanyosSection extends HTMLElement {\n  public static readonly observedAttributes = [\"heading\"];\n  #heading: HTMLHeadingElement | null = null;\n\n  public connectedCallback(): void {\n    this.#render();\n  }\n\n  public attributeChangedCallback(): void {\n    if (this.isConnected)\n      this.#render();\n  }\n\n  #render(): void {\n    const text = this.getAttribute(\"heading\") ?? \"\";\n    if (!text) {\n      this.#heading?.remove();\n      this.#heading = null;\n      this.removeAttribute(\"role\");\n      this.removeAttribute(\"aria-labelledby\");\n      return;\n    }\n    const tag = `h${headingLevel(this)}`;\n    if (this.#heading?.localName !== tag) {\n      const heading = document.createElement(tag) as HTMLHeadingElement;\n      heading.className = \"companyos-section__heading\";\n      heading.id = this.#heading?.id || `${this.id || `cos-section-${++headingIds}`}-heading`;\n      if (this.#heading)\n        this.#heading.replaceWith(heading);\n      else\n        this.prepend(heading);\n      this.#heading = heading;\n    }\n    this.#heading.textContent = text;\n    this.setAttribute(\"role\", \"region\");\n    this.setAttribute(\"aria-labelledby\", this.#heading.id);\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"cos-section\": CompanyosSection;\n  }\n}\n\n// Two asset packs on one page both import the page base\nif (!customElements.get(\"cos-section\"))\n  customElements.define(\"cos-section\", CompanyosSection);\n","/**\n * Asks before a document with unsaved form input is left: links, reload and closing through the browser's own\n * beforeunload dialog, logout through a confirmation before WRDAuth ends the session.\n *\n * Markup contract: `<form data-companyos-unsaved-guard>`, optionally with `[data-companyos-unsaved-scope]` parts that are\n * saved separately (eg one section per submit button). Without scopes the form is one scope. An unsaved scope carries\n * `data-companyos-unsaved`. The form engine stays the only value model: input marks the scope, and only WebHare's\n * `wh:form-submitted` for that scope clears it. A failed submission keeps it, and so does input elsewhere.\n */\n\n/** Present on a scope (or a form without scopes) with input that was not saved yet. */\nexport const UNSAVED_ATTRIBUTE = \"data-companyos-unsaved\";\n\nconst GUARD = \"form[data-companyos-unsaved-guard]\";\nconst SCOPE = \"[data-companyos-unsaved-scope]\";\n\n/** The scope that was submitted last, per form, so its save only clears that scope. */\nconst submittedScopes = new WeakMap<HTMLFormElement, Element>();\n/** Set once leaving was confirmed (logout), so the page does not ask a second time. */\nlet leaving = false;\n\nfunction scopeOf(node: EventTarget | null): Element | null {\n  const form = node instanceof Element ? node.closest<HTMLFormElement>(GUARD) : null;\n  if (!form)\n    return null;\n  const scope = (node as Element).closest(SCOPE);\n  return scope && form.contains(scope) ? scope : form;\n}\n\n/** Whether any guarded form in `root` has unsaved input. */\nexport function hasUnsavedChanges(root: ParentNode = document): boolean {\n  return Boolean(root.querySelector(`${GUARD}[${UNSAVED_ATTRIBUTE}], ${GUARD} [${UNSAVED_ATTRIBUTE}]`));\n}\n\nfunction markUnsaved(event: Event) {\n  scopeOf(event.target)?.setAttribute(UNSAVED_ATTRIBUTE, \"\");\n}\n\n// Two asset packs on one page may both carry this module; a second set of listeners would ask twice.\nconst REGISTERED = Symbol.for(\"companyos:unsaved-guard\");\nif (!(REGISTERED in globalThis)) {\n  Object.assign(globalThis, { [REGISTERED]: true });\n  register();\n}\n\nfunction register() {\n  addEventListener(\"input\", markUnsaved, true);\n  addEventListener(\"change\", markUnsaved, true);\n  addEventListener(\"click\", event => {\n    // Adding or removing an array row changes the value without an input event\n    if (event.target instanceof Element && event.target.closest(\".wh-form__arrayadd, .wh-form__arraydelete\"))\n      markUnsaved(event);\n  }, true);\n\n  addEventListener(\"submit\", event => {\n    const form = event.target;\n    if (!(form instanceof HTMLFormElement) || !form.matches(GUARD))\n      return;\n    // Implicit submission has no submitter; then the field being edited tells which scope is meant\n    const scope = scopeOf(event.submitter ?? document.activeElement);\n    submittedScopes.set(form, scope && form.contains(scope) ? scope : form);\n  }, true);\n\n  // Bubble phase on window: runs after the form's own handlers, which may still write saved values back into fields\n  addEventListener(\"wh:form-submitted\", event => {\n    const form = event.target;\n    if (!(form instanceof HTMLFormElement) || !form.matches(GUARD))\n      return;\n    const scope = submittedScopes.get(form) ?? form;\n    scope.removeAttribute(UNSAVED_ATTRIBUTE);\n    if (scope === form)\n      for (const node of form.querySelectorAll(`[${UNSAVED_ATTRIBUTE}]`))\n        node.removeAttribute(UNSAVED_ATTRIBUTE);\n  });\n\n  addEventListener(\"beforeunload\", event => {\n    if (leaving || !hasUnsavedChanges())\n      return;\n    event.preventDefault();\n    // Older Safari only asks when returnValue is set; the browser shows its own text either way\n    event.returnValue = \"\";\n  });\n\n  // Capture on window runs before WRDAuth's own handler on the link, which ends the session before it navigates\n  addEventListener(\"click\", event => {\n    if (!(event.target instanceof Element) || !event.target.closest(\".wh-wrdauth__logout, .companyos-page__logout\") || !hasUnsavedChanges())\n      return;\n    // eslint-disable-next-line no-alert -- a synchronous question is the only way to stop the click before WRDAuth acts\n    if (confirm(\"Er zijn wijzigingen die nog niet zijn opgeslagen. Toch uitloggen?\")) {\n      leaving = true;\n      return;\n    }\n    event.preventDefault();\n    event.stopImmediatePropagation();\n  }, true);\n}\n","import { LitElement, html } from \"lit\";\nimport { UNSAVED_ATTRIBUTE } from \"./unsaved\";\n\n/**\n * Turns a native in-page section navigation into section buttons that show one section at a time.\n *\n * Markup contract: `<cos-sections for=\"<host id>\"><nav aria-label=\"...\"><a href=\"#<section id>\">...</a></nav></cos-sections>`.\n * Only sections inside the host (default: the parent element) that a link names are touched, so several instances can\n * live on one page. The sections themselves, and every field and handler in them, stay where WebHare rendered them:\n * this element only toggles `hidden`. Without JavaScript the anchors keep working as plain in-page links.\n * A section with unsaved input (see unsaved.ts) gets a marker on its button, and a server error for a field in a hidden\n * section shows that section, so WebHare can focus the field.\n */\nexport class CompanyosSections extends LitElement {\n  #sections: Array<{ section: HTMLElement; label: string }> = [];\n  #label = \"\";\n  #active: HTMLElement | null = null;\n\n  public override createRenderRoot() {\n    return this;\n  }\n\n  public override connectedCallback() {\n    super.connectedCallback();\n    if (this.#sections.length)\n      return; // A reconnect (DOM move) keeps the adopted sections and selection\n    // Defined before the parser reached our children: adopt once they exist\n    if (document.readyState === \"loading\")\n      document.addEventListener(\"DOMContentLoaded\", () => this.#adopt(), { once: true });\n    else\n      this.#adopt();\n  }\n\n  public override render() {\n    return html`<nav aria-label=${this.#label}>${this.#sections.map(({ section, label }) => html`\n      <button type=\"button\" aria-controls=${section.id} aria-current=${section === this.#active ? \"true\" : \"false\"}\n        @click=${() => this.#select({ section, focus: true })}>${label}${isUnsaved(section)\n          ? html`<span class=\"companyos-sections__unsaved\"> (niet opgeslagen)</span>` : \"\"}</button>`)}</nav>`;\n  }\n\n  #adopt() {\n    const nav = this.querySelector(\"nav\");\n    const hostId = this.getAttribute(\"for\");\n    const host = hostId ? document.getElementById(hostId) : this.parentElement;\n    if (!nav || !host || this.#sections.length)\n      return;\n\n    for (const link of nav.querySelectorAll<HTMLAnchorElement>(\"a[href^='#']\")) {\n      const section = host.querySelector<HTMLElement>(`#${CSS.escape(link.getAttribute(\"href\")!.slice(1))}`);\n      if (section)\n        this.#sections.push({ section, label: link.textContent?.trim() ?? \"\" });\n    }\n    if (!this.#sections.length)\n      return; // Nothing we can control: leave the native navigation in place\n\n    this.#label = nav.getAttribute(\"aria-label\") ?? \"\";\n    nav.remove();\n    new MutationObserver(() => this.requestUpdate()).observe(host, { subtree: true, attributeFilter: [UNSAVED_ATTRIBUTE] });\n    // wh:form-response comes before WebHare focuses the first failing field, which only works in a visible section\n    host.addEventListener(\"wh:form-response\", event => this.#revealError({ host, event }));\n    const selected = this.#sections.find(({ section }) => `#${section.id}` === location.hash) ?? this.#sections[0];\n    this.#select({ section: selected.section, focus: false });\n  }\n\n  #revealError({ host, event }: { host: HTMLElement; event: Event }) {\n    const errors = (event as CustomEvent<{ errors?: Array<{ name?: string }> }>).detail?.errors ?? [];\n    const name = errors.find(error => error.name)?.name;\n    const field = name ? host.querySelector(`[name=\"${CSS.escape(name)}\"], [data-wh-form-name=\"${CSS.escape(name)}\"]`) : null;\n    const target = this.#sections.find(({ section }) => section.contains(field));\n    if (target && target.section !== this.#active)\n      this.#select({ section: target.section, focus: false });\n  }\n\n  #select({ section, focus }: { section: HTMLElement; focus: boolean }) {\n    this.#active = section;\n    for (const entry of this.#sections)\n      entry.section.hidden = entry.section !== section;\n    this.requestUpdate();\n    if (focus) {\n      const heading = section.querySelector<HTMLElement>(\"h1, h2, h3, h4, h5, h6\");\n      if (heading) {\n        heading.tabIndex = -1;\n        heading.focus();\n      }\n    }\n  }\n}\n\nfunction isUnsaved(section: HTMLElement) {\n  return section.hasAttribute(UNSAVED_ATTRIBUTE) || Boolean(section.querySelector(`[${UNSAVED_ATTRIBUTE}]`));\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"cos-sections\": CompanyosSections;\n  }\n}\n\n// Two asset packs on one page may both carry this module; the second define would throw.\nif (!customElements.get(\"cos-sections\"))\n  customElements.define(\"cos-sections\", CompanyosSections);\n","// Types and rules of the public screen List (`<cos-table>`), kept free of the DOM so they can be unit tested.\nimport type { ContextMenuAction } from \"./context-menu\";\n\ninterface ListColumnBase<Column extends string> {\n  key: Column;\n  label: string;\n  minWidth: number;\n  defaultWidth: number;\n  flexible?: boolean;\n}\n\n/** A text column (the default kind). `key` doubles as the sort key. */\nexport interface ListTextColumn<Item extends object, Column extends string = string> extends ListColumnBase<Column> {\n  kind?: \"text\";\n  sortable?: boolean;\n  align?: \"left\" | \"center\" | \"right\";\n  emphasis?: boolean;\n  /** Without it the cell shows `item[key]`. */\n  value?: (item: Item) => string | number;\n  /** A native link; keeps browser navigation, modifier clicks and the link context menu. */\n  href?: (item: Item) => string;\n  /** Secondary text color for the cells (not the heading). */\n  tone?: \"secondary\";\n  /** Tabular figures for the cells. */\n  numeric?: boolean;\n  /** A small label after the text, such as \"Vergrendeld\"; `description` completes its accessible name and title. */\n  badge?: (item: Item) => { label: string; description?: string } | undefined;\n}\n\n/** A read-only check per row (role checkbox, aria-readonly): shows a stored boolean, takes no input or focus. */\nexport interface ListCheckColumn<Item extends object, Column extends string = string> extends ListColumnBase<Column> {\n  kind: \"check\";\n  checked: (item: Item) => boolean;\n  /** Accessible name of the check in this row, e.g. \"10.0.0.1: toegang tot CRM\". */\n  checkLabel: (item: Item) => string;\n}\n\n/** A column of a screen List: typed configuration, no cell slots. */\nexport type ListColumn<Item extends object, Column extends string = string> = ListTextColumn<Item, Column> | ListCheckColumn<Item, Column>;\n\nexport interface ListSort<Column extends string = string> {\n  key: Column;\n  direction: \"asc\" | \"desc\";\n}\n\n/** A row menu action; the same shape as the DataTable row actions (edit/delete lead the menu). */\nexport type ListRowAction = ContextMenuAction;\n\n/** Clicking the sorted column reverses its direction; any other column starts ascending. */\nexport function nextListSort<Column extends string>(options: { current: ListSort<Column> | undefined; key: Column }): ListSort<Column> {\n  return { key: options.key, direction: options.current?.key === options.key && options.current.direction === \"asc\" ? \"desc\" : \"asc\" };\n}\n","import type { ListTextColumn } from \"../lib/list\";\n\n/** Declarative text column. In href, {field} inserts a URL-encoded value from the row. */\nexport class CompanyosColumn extends HTMLElement {\n  public get definition(): ListTextColumn<Record<string, unknown>> {\n    const key = this.getAttribute(\"key\") ?? \"\";\n    const align = this.getAttribute(\"align\");\n    const href = this.getAttribute(\"href\");\n    return {\n      key,\n      label: this.getAttribute(\"label\") ?? key,\n      minWidth: this.#width({ attribute: \"min-width\", fallback: 80 }),\n      defaultWidth: this.#width({ attribute: \"width\", fallback: 160 }),\n      flexible: this.hasAttribute(\"flexible\"),\n      sortable: this.hasAttribute(\"sortable\"),\n      emphasis: this.hasAttribute(\"emphasis\"),\n      numeric: this.hasAttribute(\"numeric\"),\n      align: align === \"right\" || align === \"center\" ? align : \"left\",\n      tone: this.getAttribute(\"tone\") === \"secondary\" ? \"secondary\" : undefined,\n      href: href === null ? undefined : item => href.replace(/\\{(\\w+)\\}/g, (_match, field: string) => encodeURIComponent(String(item[field] ?? \"\"))),\n    };\n  }\n\n  #width({ attribute, fallback }: { attribute: string; fallback: number }): number {\n    const value = Number(this.getAttribute(attribute));\n    return Number.isFinite(value) && value > 0 ? value : fallback;\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"cos-column\": CompanyosColumn;\n  }\n}\n\nif (!customElements.get(\"cos-column\"))\n  customElements.define(\"cos-column\", CompanyosColumn);\n","import { LitElement, html, nothing } from \"lit\";\nimport type { CompanyosTable } from \"./list\";\nimport { headingLevel } from \"../section\";\n\n/** A native button or link. Cancel the bubbling action event to handle an href in-place. */\nexport class CompanyosButton extends LitElement {\n  public static override properties = { label: {}, action: {}, href: {}, variant: {}, disabled: { type: Boolean, reflect: true } };\n  declare public label: string;\n  declare public action: string;\n  declare public href: string;\n  declare public variant: string;\n  declare public disabled: boolean;\n\n  public constructor() {\n    super();\n    this.label = \"\";\n    this.action = \"\";\n    this.href = \"\";\n    this.variant = \"\";\n    this.disabled = false;\n  }\n\n  public override createRenderRoot() {\n    this.label ||= this.textContent?.trim() ?? \"\";\n    this.replaceChildren();\n    return this;\n  }\n\n  public override render() {\n    const classes = `companyos-button ${this.variant === \"primary\" || this.variant === \"danger\" ? `companyos-button--${this.variant}` : \"\"}`;\n    return this.href\n      ? html`<a class=${classes} href=${this.href} aria-disabled=${this.disabled ? \"true\" : nothing} tabindex=${this.disabled ? -1 : nothing} @click=${this.#activate}>${this.label}</a>`\n      : html`<button type=\"button\" class=${classes} ?disabled=${this.disabled} @click=${this.#activate}>${this.label}</button>`;\n  }\n\n  #activate = (event: MouseEvent): void => {\n    if (this.disabled) {\n      event.preventDefault();\n      return;\n    }\n    // Keep open-in-new-tab gestures native, even when ordinary clicks open a modal.\n    if (this.href && (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey))\n      return;\n    if (this.action && !this.dispatchEvent(new CustomEvent(\"action\", { detail: { action: this.action }, bubbles: true, cancelable: true })))\n      event.preventDefault();\n  };\n}\n\nexport class CompanyosSearch extends LitElement {\n  public static override properties = { label: {}, value: {}, disabled: { type: Boolean } };\n  declare public label: string;\n  declare public value: string;\n  declare public disabled: boolean;\n\n  public constructor() {\n    super();\n    this.label = \"Zoeken\";\n    this.value = \"\";\n    this.disabled = false;\n  }\n\n  public override createRenderRoot() { return this; }\n\n  public override focus(options?: FocusOptions): void {\n    this.querySelector(\"input\")?.focus(options);\n  }\n\n  public override render() {\n    return html`<label><span class=\"companyos-field__label\">${this.label}</span>\n      <input type=\"search\" .value=${this.value} ?disabled=${this.disabled} spellcheck=\"false\" autocorrect=\"off\" @input=${this.#input}></label>`;\n  }\n\n  #input = (event: Event): void => {\n    this.value = (event.target as HTMLInputElement).value;\n    this.dispatchEvent(new CustomEvent(\"search-change\", { detail: this.value, bubbles: true }));\n  };\n}\n\n/** Options and optgroups are native children in Witty, retained inside the labelled select. */\nexport class CompanyosSelect extends LitElement {\n  public static override properties = { label: {}, value: {}, disabled: { type: Boolean } };\n  declare public label: string;\n  declare public value: string;\n  declare public disabled: boolean;\n  #options: Element[] = [];\n\n  public constructor() {\n    super();\n    this.label = \"\";\n    this.value = \"\";\n    this.disabled = false;\n  }\n\n  public override createRenderRoot() {\n    this.#options = [...this.querySelectorAll(\":scope > option, :scope > optgroup\")];\n    if (!this.hasAttribute(\"value\") && !this.value)\n      this.value = (this.querySelector<HTMLOptionElement>(\"option[selected]\") ?? this.querySelector(\"option\"))?.value ?? \"\";\n    this.replaceChildren();\n    return this;\n  }\n\n  public override render() {\n    return html`<label><span class=\"companyos-field__label\">${this.label}</span>\n      <select ?disabled=${this.disabled} @change=${this.#change}>${this.#options}</select></label>`;\n  }\n\n  protected override updated(): void {\n    this.querySelector(\"select\")!.value = this.value;\n  }\n\n  #change = (event: Event): void => {\n    this.value = (event.target as HTMLSelectElement).value;\n    this.dispatchEvent(new CustomEvent(\"selection-change\", { detail: this.value, bubbles: true }));\n  };\n}\n\nexport class CompanyosEmptyState extends LitElement {\n  public static override properties = { heading: {}, description: {} };\n  declare public heading: string;\n  declare public description: string;\n\n  public constructor() {\n    super();\n    this.heading = \"\";\n    this.description = \"\";\n  }\n\n  public override createRenderRoot() {\n    const copy = document.createElement(\"div\");\n    this.prepend(copy);\n    return copy;\n  }\n\n  public override connectedCallback(): void {\n    super.connectedCallback();\n    this.classList.add(\"companyos-list__empty\");\n    this.setAttribute(\"role\", \"status\");\n  }\n\n  public override render() {\n    // A role instead of an h-tag: Lit cannot vary the tag, and the level follows the enclosing sections (section.ts)\n    return html`${this.heading ? html`<p class=\"companyos-empty-state__heading\" role=\"heading\" aria-level=${headingLevel(this)}>${this.heading}</p>` : nothing}${this.description ? html`<p>${this.description}</p>` : nothing}`;\n  }\n}\n\n/** `for` connects search, focus and buttons with when=\"populated\" to a table by id. */\nexport class CompanyosToolbar extends HTMLElement {\n  public constructor() {\n    super();\n    this.addEventListener(\"search-change\", event => {\n      const table = this.#table();\n      if (table)\n        table.query = (event as CustomEvent<string>).detail;\n    });\n  }\n\n  public connectedCallback(): void {\n    this.classList.add(\"companyos-form\", \"companyos-list-toolbar\");\n    this.ownerDocument.addEventListener(\"table-change\", this.#tableChanged);\n    this.ownerDocument.addEventListener(\"search-request\", this.#focusSearch);\n    queueMicrotask(() => this.#sync());\n  }\n\n  public disconnectedCallback(): void {\n    this.ownerDocument.removeEventListener(\"table-change\", this.#tableChanged);\n    this.ownerDocument.removeEventListener(\"search-request\", this.#focusSearch);\n  }\n\n  #table(): CompanyosTable | null {\n    const target = this.ownerDocument.getElementById(this.getAttribute(\"for\") ?? \"\");\n    return target?.matches(\"cos-table, cos-list\") ? target as CompanyosTable : null;\n  }\n\n  #sync(): void {\n    const table = this.#table();\n    if (!this.isConnected || !table)\n      return;\n    const search = this.querySelector(\"cos-search\");\n    if (search)\n      search.value = table.query;\n    for (const button of this.querySelectorAll<CompanyosButton>(\"cos-button[when=populated]\"))\n      button.hidden = !table.items.length;\n  }\n\n  #tableChanged = (event: Event): void => {\n    if (event.target === this.#table())\n      this.#sync();\n  };\n\n  #focusSearch = (event: Event): void => {\n    if (event.target === this.#table())\n      this.querySelector(\"cos-search\")?.focus();\n  };\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"cos-button\": CompanyosButton;\n    \"cos-search\": CompanyosSearch;\n    \"cos-select\": CompanyosSelect;\n    \"cos-empty-state\": CompanyosEmptyState;\n    \"cos-toolbar\": CompanyosToolbar;\n  }\n}\n\nfor (const [name, constructor] of [\n  [\"cos-button\", CompanyosButton], [\"cos-search\", CompanyosSearch], [\"cos-select\", CompanyosSelect],\n  [\"cos-empty-state\", CompanyosEmptyState], [\"cos-toolbar\", CompanyosToolbar],\n] as const)\n  if (!customElements.get(name))\n    customElements.define(name, constructor);\n","import { LitElement, html, nothing, type PropertyValues } from \"lit\";\nimport { getInlineRowActions, getMenuActions, getRowActionsWidth } from \"../lib/context-menu\";\nimport { nextListSort, type ListColumn, type ListRowAction, type ListSort, type ListTextColumn } from \"../lib/list\";\nimport { icon } from \"./icon\";\nimport { CompanyosMenu } from \"../menu\";\nimport type { CompanyosColumn } from \"./column\";\nimport \"./column\";\nimport \"./controls\";\n\ntype Key = string | number;\ntype Item = object;\n\n/** Cell controls keep their own interaction instead of opening the row (the SPA's DataTable rule). */\nconst CONTROL = \"button, a, input, label, select, textarea, [contenteditable=true], [role=button], [role=checkbox], [role=switch]\";\nconst FIELD = \"input, select, textarea, [contenteditable=true]\";\n\n/**\n * Rows in columns, as the SPA's screen List: `columns` is typed configuration (lib/list.ts), never cell markup.\n * Single selection that follows the arrow keys once something is selected, Enter selects, Home and End jump,\n * double-click fires `open-row` (a double tap only with `doubleTap`), \"/\" outside a field fires `search-request`. The list owns the sort toggle and\n * `aria-sort`; the consumer orders `items` itself on `sort-change`. Row actions (`row-action`): fewer than three, each with an icon\n * (edit and delete have one), are inline icon buttons; otherwise an overflow menu. Right-click opens the same actions as a menu.\n * `selectable = false` is the matrix form: no selection, rows take no focus, keys do nothing, double-click still opens.\n * An empty-state child (`<div class=\"companyos-list__empty\">`) shows only while there are no items.\n * Events, all bubbling CustomEvents: `select-row` (detail: key), `sort-change` (ListSort), `open-row` (item),\n * `row-action` ({ item, actionId }), `search-request`.\n */\nexport class CompanyosTable extends LitElement {\n  public static override properties = {\n    loading: { type: Boolean, reflect: true }, loadingLabel: { attribute: \"loading-label\" },\n    emptyLabel: { attribute: \"empty-label\" }, error: {}, query: {}, noResultsLabel: { attribute: \"no-results-label\" },\n    label: {}, items: { attribute: false }, itemKey: { attribute: false }, itemLabel: { attribute: false },\n    columns: { attribute: false }, rowActions: { attribute: false }, selected: { attribute: false }, sort: { attribute: false },\n    selectable: { type: Boolean }, disabled: { type: Boolean }, doubleTap: { type: Boolean, attribute: \"double-tap\" },\n  };\n  declare public label: string;\n  declare public loading: boolean;\n  declare public loadingLabel: string;\n  declare public emptyLabel: string;\n  declare public error: string;\n  declare public query: string;\n  declare public noResultsLabel: string;\n  declare public items: readonly Item[];\n  declare public itemKey: (item: never) => Key;\n  /** Names a row in its menu button (\"Acties voor ...\"). */\n  declare public itemLabel: (item: never) => string;\n  declare public columns: ReadonlyArray<ListColumn<never>>;\n  declare public rowActions: readonly ListRowAction[] | ((item: never) => readonly ListRowAction[]) | undefined;\n  /** The selected row's key; undefined is no selection. */\n  declare public selected: Key | undefined;\n  declare public sort: ListSort | undefined;\n  declare public selectable: boolean;\n  declare public disabled: boolean;\n  /** A double tap opens a row too. Off by default: on a phone the first tap usually opens the row's details already. */\n  declare public doubleTap: boolean;\n  #viewItems: readonly Item[] = [];\n  #renderColumns: ReadonlyArray<ListColumn<never>> = [];\n  readonly #columnObserver = new MutationObserver(records => {\n    // Ignore the rendered table: only declarative column changes invalidate the configuration.\n    if (records.some(record => record.type === \"attributes\"\n      ? record.target instanceof Element && record.target.matches(\"cos-column\") && record.target.parentElement === this\n      : record.target === this && [...record.addedNodes, ...record.removedNodes].some(node => node instanceof Element && node.matches(\"cos-column\"))))\n      this.requestUpdate();\n  });\n  #cursor: Key | undefined;\n  #menu: { item: Item; menu: CompanyosMenu } | null = null;\n  // dblclick is a MouseEvent without pointerType; the row's last pointerdown tells a tap from a mouse\n  #pointerType = \"\";\n\n  public constructor() {\n    super();\n    this.label = \"\";\n    this.loading = false;\n    this.loadingLabel = \"Gegevens laden…\";\n    this.emptyLabel = \"Geen gegevens.\";\n    this.error = \"\";\n    this.query = \"\";\n    this.noResultsLabel = \"Geen resultaten gevonden\";\n    this.items = [];\n    this.itemKey = item => String(item);\n    this.itemLabel = item => String(item);\n    this.columns = [];\n    this.rowActions = undefined;\n    this.selected = undefined;\n    this.sort = undefined;\n    this.selectable = true;\n    this.disabled = false;\n    this.doubleTap = false;\n  }\n\n  public override connectedCallback(): void {\n    super.connectedCallback();\n    this.#columnObserver.observe(this, { childList: true, attributes: true, subtree: true });\n    this.requestUpdate();\n  }\n\n  // The table goes in its own first child; an empty-state child of the consumer stays after it\n  public override createRenderRoot() {\n    const root = document.createElement(\"div\");\n    root.className = \"companyos-list__scroller\";\n    this.prepend(root);\n    return root;\n  }\n\n  /** Moves keyboard focus to the row with `key`, or to the first row when it is not shown (after a detail panel closes). */\n  public async focusRow(key: Key): Promise<void> {\n    this.#cursor = this.#keys().includes(key) ? key : this.#keys()[0];\n    this.requestUpdate();\n    await this.updateComplete;\n    const row = [...this.renderRoot.querySelectorAll<HTMLElement>(\"tbody > tr\")].find(element => element.dataset.rowKey === String(this.#cursor));\n    row?.focus({ preventScroll: true });\n    row?.scrollIntoView({ block: \"nearest\", inline: \"nearest\" });\n  }\n\n  protected override willUpdate(changed: PropertyValues<this>) {\n    super.willUpdate(changed);\n    this.#renderColumns = this.columns.length ? this.columns : [...this.querySelectorAll<CompanyosColumn>(\":scope > cos-column\")].map(column => column.definition);\n    const query = this.query.trim().toLocaleLowerCase();\n    this.#viewItems = query ? this.items.filter(item => this.#renderColumns.some(column => column.kind !== \"check\"\n      && String(this.#textValue({ item, column })).toLocaleLowerCase().includes(query))) : this.items;\n    const keys = this.#keys();\n    if (this.#cursor === undefined || !keys.includes(this.#cursor))\n      this.#cursor = keys[0];\n    if (this.#menu && (this.disabled || this.loading || Boolean(this.error) || !this.#viewItems.includes(this.#menu.item)))\n      this.#closeMenu();\n  }\n\n  public override render() {\n    if (!this.loading && this.error)\n      return html`<p role=\"alert\">${this.error}</p>`;\n    if (!this.loading && !this.#viewItems.length) {\n      if (this.items.length)\n        return html`<cos-empty-state heading=${this.noResultsLabel} description=\"Gebruik een andere zoekterm of wis de zoekopdracht.\">\n          <cos-button action=\"clear-search\" @action=${this.#clearSearch}>Zoekopdracht wissen</cos-button>\n        </cos-empty-state>`;\n      return this.querySelector(\":scope > cos-empty-state, :scope > .companyos-list__empty\") ? nothing : html`<p role=\"status\">${this.emptyLabel}</p>`;\n    }\n    const actions = Boolean(this.rowActions);\n    const buttons = Math.max(1, ...this.#viewItems.map(item => this.#inlineActions(item)?.length ?? 1));\n    // Rendered rows are never replaced by a skeleton: a reload keeps them until the new ones arrive\n    const skeleton = this.loading && !this.items.length;\n    return html`${this.loading ? html`<p role=\"status\" class=\"companyos-sr-only\">${this.loadingLabel}</p>` : nothing}\n    <table class=\"companyos-list__table\" aria-label=${this.label} aria-busy=${this.disabled || this.loading ? \"true\" : \"false\"} @keydown=${this.#onKeydown}>\n      <colgroup>${this.#renderColumns.map(column => html`<col style=${column.flexible ? `min-width: ${column.minWidth}px` : `width: ${column.defaultWidth}px`}>`)}${actions ? html`<col style=\"width: ${getRowActionsWidth({ buttons })}px\">` : nothing}</colgroup>\n      <thead><tr>${this.#renderColumns.map(column => this.#heading(column))}${actions ? html`<th scope=\"col\" class=\"companyos-list__heading companyos-list__actions\"><span class=\"companyos-sr-only\">Acties</span></th>` : nothing}</tr></thead>\n      <tbody>${skeleton ? Array.from({ length: 5 }, () => html`<tr aria-hidden=\"true\" class=\"companyos-list__skeleton\">\n        ${this.#renderColumns.map(() => html`<td class=\"companyos-list__cell\"><span></span></td>`)}\n        ${actions ? html`<td class=\"companyos-list__cell\"><span></span></td>` : nothing}\n      </tr>`) : this.#viewItems.map(item => this.#row(item))}</tbody>\n    </table>`;\n  }\n\n  protected override updated(changed: PropertyValues<this>) {\n    super.updated(changed);\n    this.toggleAttribute(\"empty\", !this.loading && !this.error && !this.items.length);\n    this.setAttribute(\"aria-busy\", String(this.loading || this.disabled));\n    for (const empty of this.querySelectorAll<HTMLElement>(\":scope > cos-empty-state\"))\n      empty.hidden = this.loading || Boolean(this.error) || Boolean(this.items.length);\n    this.#emit(\"table-change\");\n  }\n\n  public override disconnectedCallback(): void {\n    this.#columnObserver.disconnect();\n    this.#closeMenu();\n    super.disconnectedCallback();\n  }\n\n  #keys(): Key[] {\n    return this.#viewItems.map(item => this.itemKey(item as never));\n  }\n\n  #heading(column: ListColumn<never>) {\n    const sortable = column.kind !== \"check\" && column.sortable;\n    const sorted = sortable && this.sort?.key === column.key ? this.sort.direction : undefined;\n    const align = column.kind === \"check\" ? \"center\" : column.align ?? \"left\";\n    return html`<th scope=\"col\" class=\"companyos-list__heading companyos-list__cell--${align}\" data-column=${column.key}\n        aria-sort=${sortable ? sorted === \"asc\" ? \"ascending\" : sorted === \"desc\" ? \"descending\" : \"none\" : nothing}>${sortable\n      ? html`<button type=\"button\" class=\"companyos-list__sort\" ?disabled=${this.disabled || this.loading} @click=${() => this.#onSort(column.key)}>${column.label}${sorted\n        ? html`<span class=\"companyos-list__sort-icon companyos-list__sort-icon--${sorted}\">${icon(\"chevron--down\", 14)}</span>` : nothing}</button>`\n      : column.label}</th>`;\n  }\n\n  #row(item: Item) {\n    const key = this.itemKey(item as never);\n    const selected = this.selectable && this.selected === key;\n    return html`<tr class=\"companyos-list__row ${this.selectable ? \"companyos-list__row--selectable\" : \"\"}\" data-row-key=${key}\n        tabindex=${this.selectable ? this.#cursor === key ? 0 : -1 : nothing} aria-selected=${this.selectable ? String(selected) : nothing}\n        @focusin=${() => { this.#cursor = key; }} @pointerdown=${(event: PointerEvent) => { this.#pointerType = event.pointerType; }}\n        @click=${(event: MouseEvent) => this.#onRowClick({ event, item })} @dblclick=${(event: MouseEvent) => this.#onDoubleClick({ event, item })}\n        @contextmenu=${(event: MouseEvent) => this.#onContextMenu({ event, item })}>\n      ${this.#renderColumns.map(column => column.kind === \"check\" ? this.#checkCell({ item, column }) : this.#textCell({ item, column }))}\n      ${this.rowActions ? html`<td class=\"companyos-list__cell companyos-list__actions\">${this.#actionsCell(item)}</td>` : nothing}\n    </tr>`;\n  }\n\n  #actions(item: Item) {\n    return getMenuActions({ actions: typeof this.rowActions === \"function\" ? this.rowActions(item as never) : this.rowActions ?? [] });\n  }\n\n  #inlineActions(item: Item) {\n    return this.rowActions ? getInlineRowActions({ actions: this.#actions(item) }) : null;\n  }\n\n  #actionsCell(item: Item) {\n    const inline = this.#inlineActions(item);\n    const name = this.itemLabel(item as never);\n    if (inline)\n      return html`<span class=\"companyos-list__inline-actions\">${inline.map(action => html`<button type=\"button\"\n        class=\"companyos-list__action ${action.danger ? \"companyos-list__action--danger\" : \"\"}\" ?disabled=${this.disabled || action.disabled}\n        aria-label=\"${action.label}: ${name}\" title=${action.label} @click=${() => this.#emit(\"row-action\", { item, actionId: action.id })}>${icon(action.icon, 20)}</button>`)}</span>`;\n    return html`<button type=\"button\" class=\"companyos-list__menu-trigger\" ?disabled=${this.disabled}\n        aria-label=\"Acties voor ${name}\" aria-haspopup=\"menu\" aria-expanded=${this.#menu?.item === item ? \"true\" : \"false\"}\n        @click=${(event: MouseEvent) => this.#openMenu({ item, trigger: event.currentTarget as HTMLElement })}>${icon(\"overflow-menu--vertical\", 20)}</button>`;\n  }\n\n  #textValue({ item, column }: { item: Item; column: ListTextColumn<never> }): string | number {\n    const raw = column.value ? column.value(item as never) : (item as Record<string, unknown>)[column.key];\n    return typeof raw === \"number\" ? raw : String(raw ?? \"\");\n  }\n\n  #clearSearch = (event: Event): void => {\n    event.stopPropagation();\n    this.query = \"\";\n    void this.updateComplete.then(() => this.#emit(\"search-request\"));\n  };\n\n  #textCell({ item, column }: { item: Item; column: ListTextColumn<never> }) {\n    const text = this.#textValue({ item, column });\n    const badge = column.badge?.(item as never);\n    return html`<td class=\"companyos-list__cell companyos-list__cell--${column.align ?? \"left\"} ${column.emphasis ? \"companyos-list__cell--emphasis\" : \"\"}\n        ${column.tone === \"secondary\" ? \"companyos-list__cell--secondary\" : \"\"} ${column.numeric ? \"companyos-list__cell--numeric\" : \"\"}\" data-column=${column.key}>\n      <span class=\"companyos-list__content\">${column.href\n        ? html`<a class=\"companyos-list__text\" href=${column.href(item as never)} title=${text}>${text}</a>`\n        : html`<span class=\"companyos-list__text\" title=${text}>${text}</span>`}${badge ? html`<span class=\"companyos-list__badge\" role=\"img\"\n        aria-label=${badge.description ? `${badge.label}: ${badge.description}` : badge.label} title=${badge.description || badge.label}>${badge.label}</span>` : nothing}</span></td>`;\n  }\n\n  #checkCell({ item, column }: { item: Item; column: Extract<ListColumn<never>, { kind: \"check\" }> }) {\n    const checked = column.checked(item as never);\n    return html`<td class=\"companyos-list__cell companyos-list__cell--center\" data-column=${column.key}>\n      <span class=\"companyos-list__check\" role=\"checkbox\" aria-readonly=\"true\" aria-checked=${String(checked)} aria-label=${column.checkLabel(item as never)}>${checked ? icon(\"checkmark\", 16) : nothing}</span></td>`;\n  }\n\n  #emit(type: string, detail?: unknown): void {\n    this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true }));\n  }\n\n  #select(item: Item): void {\n    if (this.disabled || !this.selectable)\n      return;\n    this.#cursor = this.itemKey(item as never);\n    this.#emit(\"select-row\", this.#cursor);\n  }\n\n  // An action button only acts: on a phone selecting the row replaces the list, and the menu with it\n  #onRowClick({ event, item }: { event: MouseEvent; item: Item }): void {\n    if (!(event.target instanceof Element && event.target.closest(CONTROL)))\n      this.#select(item);\n  }\n\n  #onSort(key: string): void {\n    this.#emit(\"sort-change\", nextListSort({ current: this.sort, key }));\n  }\n\n  #onDoubleClick({ event, item }: { event: MouseEvent; item: Item }): void {\n    if (this.disabled || (event.target instanceof Element && event.target.closest(CONTROL)) || (this.#pointerType === \"touch\" && !this.doubleTap))\n      return;\n    this.#emit(\"open-row\", item);\n  }\n\n  #onContextMenu({ event, item }: { event: MouseEvent; item: Item }): void {\n    if (this.disabled || !this.rowActions || !this.#actions(item).length || (event.target instanceof Element && event.target.closest(\"a\")))\n      return;\n    event.preventDefault();\n    // Inline actions have no menu button: focus returns to the row, or to its first action when rows are not focusable\n    const row = event.currentTarget as HTMLElement;\n    const trigger = row.querySelector<HTMLElement>(\".companyos-list__menu-trigger\") ?? (this.selectable ? row : row.querySelector<HTMLElement>(\".companyos-list__action\") ?? row);\n    this.#openMenu({ item, trigger, point: { x: event.clientX, y: event.clientY } });\n  }\n\n  #onKeydown = (event: KeyboardEvent): void => {\n    if (event.target instanceof Element && event.target.closest(`${FIELD}, .companyos-list__menu`))\n      return;\n    if (event.key === \"/\") {\n      event.preventDefault();\n      this.#emit(\"search-request\");\n      return;\n    }\n    if (this.disabled || !this.selectable || !this.#viewItems.length)\n      return;\n    const keys = this.#keys();\n    const index = keys.indexOf(this.#cursor!);\n    let target: number;\n    switch (event.key) {\n      case \"ArrowDown\": target = index < 0 ? 0 : Math.min(keys.length - 1, index + 1); break;\n      case \"ArrowUp\": target = index < 0 ? 0 : Math.max(0, index - 1); break;\n      case \"Home\": target = 0; break;\n      case \"End\": target = keys.length - 1; break;\n      case \"Enter\":\n        if (event.target instanceof Element && event.target.closest(\"button, a\"))\n          return;\n        event.preventDefault();\n        if (index >= 0)\n          this.#select(this.#viewItems[index]);\n        return;\n      default: return;\n    }\n    event.preventDefault();\n    void this.focusRow(keys[target]);\n    // The cursor moves; the selection only follows once there is one\n    if (this.selected !== undefined)\n      this.#select(this.#viewItems[target]);\n  };\n\n  #openMenu(options: { item: Item; trigger: HTMLElement; point?: { x: number; y: number } }): void {\n    if (this.disabled)\n      return;\n    this.#closeMenu();\n    const menu = new CompanyosMenu({ label: `Acties voor ${this.itemLabel(options.item as never)}`, onClose: () => this.#closeMenu() });\n    menu.element.classList.add(\"companyos-list__menu\");\n    for (const action of this.#actions(options.item)) {\n      if (action.separatorBefore)\n        menu.addSeparator();\n      menu.addMenuItem({ label: action.label, disabled: action.disabled, danger: action.danger,\n        onSelect: () => this.#emit(\"row-action\", { item: options.item, actionId: action.id }) });\n    }\n    this.#menu = { item: options.item, menu };\n    this.append(menu.element);\n    this.requestUpdate();\n    // Open after rendering so updates cannot temporarily detach a visible native popover.\n    void this.updateComplete.then(() => {\n      if (this.#menu?.menu === menu)\n        menu.open({ trigger: options.trigger, point: options.point });\n    });\n  }\n\n  #closeMenu(): void {\n    const current = this.#menu;\n    this.#menu = null;\n    current?.menu.destroy();\n    if (current)\n      this.requestUpdate();\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"cos-table\": CompanyosTable;\n    \"cos-list\": CompanyosTable;\n  }\n}\n\nif (!customElements.get(\"cos-table\"))\n  customElements.define(\"cos-table\", CompanyosTable);\n\n/** @deprecated Use CompanyosTable and <cos-table>. Kept for existing customer modules. */\nexport { CompanyosTable as CompanyosList };\n\n// Custom element names need distinct constructors; both tags use the same implementation.\nif (!customElements.get(\"cos-list\"))\n  customElements.define(\"cos-list\", class extends CompanyosTable {});\n","import { LitElement, html, nothing, type PropertyValues } from \"lit\";\nimport { icon } from \"./icon\";\n\nlet lastId = 0;\n\n/**\n * A modal form dialog on a native `<dialog>`, as the SPA's screen Dialog: focus moves in on open and back to the\n * opener on close, Escape, the backdrop and `requestClose()` are one path (ignored while pending, a discard question\n * when dirty), fields and buttons are disabled while pending, a loading backdrop with a minimum time, the form error\n * and focus on the first invalid field or that error after a failed save. The rest of the page is inert (showModal).\n *\n * Content: the element's own children at first connect. Children with `slot=\"actions\"` become the footer (put a\n * `type=\"submit\"` button there), all others the body. They are moved into the dialog once, together with any template\n * markers of a parent Lit template, so later updates of that template keep working.\n * Events (bubbling CustomEvents): `dialog-submit`, and `dialog-cancel` with detail `{ discard }`.\n * Stays shown while `loadingVisible` after `open` turned false, so the loading minimum is not cut off.\n */\nexport class CompanyosDialog extends LitElement {\n  public static override properties = {\n    externalForm: { type: Boolean, attribute: \"external-form\", reflect: true },\n    open: { type: Boolean }, heading: {}, description: {}, pending: { type: Boolean },\n    loadingVisible: { type: Boolean, attribute: \"loading-visible\" }, dirty: { type: Boolean }, error: {},\n    alert: { type: Boolean }, pendingLabel: { attribute: \"pending-label\" },\n  };\n  /** Host a complete WebHare form without nesting it in the dialog's native form. */\n  declare public externalForm: boolean;\n  declare public open: boolean;\n  declare public heading: string;\n  declare public description: string;\n  declare public pending: boolean;\n  declare public loadingVisible: boolean;\n  declare public dirty: boolean;\n  /** The form-level message; field messages belong to the fields (aria-invalid plus their own text). */\n  declare public error: string;\n  /** Role alertdialog, for a confirmation. */\n  declare public alert: boolean;\n  declare public pendingLabel: string;\n  readonly #id = `companyos-dialog-${++lastId}`;\n  #content: ChildNode[] | null = null;\n  #opener: HTMLElement | null = null;\n  #discardOrigin: HTMLElement | null = null;\n  #confirmingDiscard = false;\n\n  public constructor() {\n    super();\n    this.externalForm = false;\n    this.open = false;\n    this.heading = \"\";\n    this.description = \"\";\n    this.pending = false;\n    this.loadingVisible = false;\n    this.dirty = false;\n    this.error = \"\";\n    this.alert = false;\n    this.pendingLabel = \"Bezig...\";\n  }\n\n  public override createRenderRoot() {\n    return this;\n  }\n\n  public override connectedCallback() {\n    // Before the first render appends the dialog: what is here now is the consumer's content\n    this.#content ??= [...this.childNodes];\n    super.connectedCallback();\n  }\n\n  /** Escape, the backdrop and a cancel button all end here. */\n  public requestClose(): void {\n    if (this.#actionsDisabled())\n      return;\n    if (!this.dirty) {\n      this.dispatchEvent(new CustomEvent(\"dialog-cancel\", { detail: { discard: false }, bubbles: true }));\n      return;\n    }\n    const active = document.activeElement;\n    this.#discardOrigin = active instanceof HTMLElement && this.#dialog()?.contains(active) && active !== this.#dialog() ? active : null;\n    this.#confirmingDiscard = true;\n    this.requestUpdate();\n    void this.updateComplete.then(() => this.querySelector<HTMLButtonElement>(\".companyos-dialog__discard button\")?.focus());\n  }\n\n  public override render() {\n    const disabled = this.#actionsDisabled();\n    return html`<dialog class=\"companyos-dialog\" role=${this.alert ? \"alertdialog\" : \"dialog\"} aria-modal=\"true\" aria-labelledby=\"${this.#id}-title\"\n        aria-describedby=${this.description ? `${this.#id}-description` : nothing} aria-busy=${this.pending ? \"true\" : \"false\"}\n        @cancel=${this.#onCancel} @close=${this.#onClose} @click=${this.#onBackdrop}>\n      <header class=\"companyos-dialog__header\">\n        <h2 id=\"${this.#id}-title\" class=\"companyos-dialog__title\">${this.heading}</h2>\n        ${this.externalForm ? html`<button type=\"button\" class=\"companyos-dialog__close companyos-button\" aria-label=\"Sluiten\"\n          ?disabled=${this.pending} @click=${() => this.requestClose()}>${icon(\"close\", 20)}</button>` : nothing}\n        ${this.description ? html`<p id=\"${this.#id}-description\" class=\"companyos-dialog__description\">${this.description}</p>` : nothing}\n      </header>\n      ${this.externalForm\n        ? html`<div class=\"companyos-dialog__form\">${this.#renderContents(disabled)}</div>`\n        : html`<form class=\"companyos-form companyos-dialog__form\" novalidate @submit=${this.#onSubmit}>${this.#renderContents(disabled)}</form>`}\n    </dialog>`;\n  }\n\n  protected override firstUpdated(changed: PropertyValues<this>) {\n    super.firstUpdated(changed);\n    const fields = this.querySelector(\".companyos-dialog__fields\")!;\n    const actions = this.querySelector(\".companyos-dialog__actions\")!;\n    for (const node of this.#content ?? [])\n      (node instanceof Element && node.getAttribute(\"slot\") === \"actions\" ? actions : fields).append(node);\n    actions.toggleAttribute(\"hidden\", !actions.children.length);\n  }\n\n  protected override updated(changed: PropertyValues<this>) {\n    super.updated(changed);\n    const dialog = this.#dialog()!;\n    if (changed.has(\"open\"))\n      this.#confirmingDiscard = false;\n    const shown = this.open || (dialog.open && this.loadingVisible);\n    if (shown && !dialog.open) {\n      const active = document.activeElement;\n      this.#opener = active instanceof HTMLElement && active !== document.body ? active : null;\n      dialog.showModal();\n    } else if (!shown && dialog.open) {\n      dialog.close();\n      // Chrome restores focus on close by itself (removing this kept the focus check green); not every browser does\n      if (this.#opener?.isConnected)\n        this.#opener.focus();\n      this.#opener = null;\n    }\n    const wasReady = (changed.has(\"pending\") ? changed.get(\"pending\") : this.pending) === false\n      && (changed.has(\"loadingVisible\") ? changed.get(\"loadingVisible\") : this.loadingVisible) === false;\n    if (this.open && !wasReady && this.#ready())\n      this.#focusAfterSave(dialog);\n  }\n\n  #renderContents(disabled: boolean) {\n    return html`\n        <div class=\"companyos-dialog__body\">\n          <div class=\"companyos-dialog__loading\" aria-busy=${this.pending ? \"true\" : \"false\"}>\n            <fieldset class=\"companyos-dialog__fields\" ?disabled=${disabled && !this.externalForm} ?inert=${this.loadingVisible}></fieldset>\n            <span class=\"companyos-sr-only\" role=\"status\" aria-live=\"polite\">${this.pending ? this.pendingLabel : \"\"}</span>\n            ${this.loadingVisible ? html`<div class=\"companyos-dialog__backdrop\" data-pending=${this.pending ? \"true\" : \"false\"}>\n              <div class=\"companyos-dialog__indicator\"><span class=\"companyos-dialog__spinner\" aria-hidden=\"true\"></span><span>${this.pendingLabel}</span></div></div>` : nothing}\n          </div>\n          ${this.error ? html`<p class=\"companyos-dialog__error\" role=\"alert\" tabindex=\"-1\">${this.error}</p>` : nothing}\n          ${this.#confirmingDiscard ? html`<div class=\"companyos-dialog__discard\" role=\"alert\">\n            <p class=\"companyos-dialog__discard-text\">Je wijzigingen zijn nog niet opgeslagen.</p>\n            <div class=\"companyos-buttonbar companyos-buttonbar--start\">\n              <button type=\"button\" class=\"companyos-button\" @click=${this.#keepEditing}>Verder bewerken</button>\n              <button type=\"button\" class=\"companyos-button companyos-button--danger\" @click=${this.#discard}>Sluiten zonder opslaan</button>\n            </div></div>` : nothing}\n        </div>\n        <fieldset class=\"companyos-dialog__actions companyos-buttonbar\" ?disabled=${disabled}></fieldset>`;\n  }\n\n  #dialog(): HTMLDialogElement | null {\n    return this.querySelector(\":scope > dialog\");\n  }\n\n  #actionsDisabled(): boolean {\n    return this.pending || !this.open;\n  }\n\n  #ready(): boolean {\n    return !this.pending && !this.loadingVisible;\n  }\n\n  // The submit button was disabled while pending, which leaves focus on <body>: move it to where the news is\n  #focusAfterSave(dialog: HTMLDialogElement): void {\n    const invalid = dialog.querySelector<HTMLElement>(\"[aria-invalid=true]:not(:disabled)\");\n    if (invalid)\n      invalid.focus();\n    else if (!dialog.contains(document.activeElement))\n      dialog.querySelector<HTMLElement>(\".companyos-dialog__error\")?.focus();\n  }\n\n  #onSubmit = (event: SubmitEvent): void => {\n    event.preventDefault();\n    if (!this.#actionsDisabled())\n      this.dispatchEvent(new CustomEvent(\"dialog-submit\", { bubbles: true }));\n  };\n\n  #onCancel = (event: Event): void => {\n    event.preventDefault();\n    this.requestClose();\n  };\n\n  // A second Escape without user activation closes a dialog without a cancel event (close watcher rules): stay open\n  #onClose = (): void => {\n    const dialog = this.#dialog()!;\n    if (this.open && this.isConnected && !dialog.open) {\n      dialog.showModal();\n      this.requestClose();\n    }\n  };\n\n  // Native dialog sends backdrop clicks to the dialog itself, as well as clicks on its border\n  #onBackdrop = (event: MouseEvent): void => {\n    const dialog = this.#dialog()!;\n    if (this.externalForm || event.target !== dialog)\n      return;\n    const rect = dialog.getBoundingClientRect();\n    if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom)\n      this.requestClose();\n  };\n\n  #keepEditing = (): void => {\n    this.#confirmingDiscard = false;\n    const origin = this.#discardOrigin;\n    this.#discardOrigin = null;\n    this.requestUpdate();\n    // The focused confirmation button is removed with the panel: hand focus back to where it came from\n    void this.updateComplete.then(() => {\n      const target = origin?.isConnected && !origin.matches(\":disabled\") ? origin\n        : this.querySelector<HTMLElement>(\".companyos-dialog__fields :is(input, select, textarea, button):not(:disabled)\");\n      target?.focus({ preventScroll: true });\n    });\n  };\n\n  #discard = (): void => {\n    this.dispatchEvent(new CustomEvent(\"dialog-cancel\", { detail: { discard: true }, bubbles: true }));\n  };\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"cos-dialog\": CompanyosDialog;\n  }\n}\n\nif (!customElements.get(\"cos-dialog\"))\n  customElements.define(\"cos-dialog\", CompanyosDialog);\n","import { LitElement, html } from \"lit\";\nimport \"./signature.scss\";\n\ntype Point = { x: number; y: number };\ntype Stroke = { points: Point[] };\n\n/** Enhances its native textarea; WebHare retains ownership of validation, submission and the stored value. */\nexport class CompanyosSignature extends LitElement {\n  #children: Node[] = [];\n  #field!: HTMLTextAreaElement;\n  #canvas!: HTMLCanvasElement;\n  #observer = new MutationObserver(() => this.requestUpdate());\n  #pointer: number | null = null;\n  #cursor: Point = { x: 0.5, y: 0.5 };\n  #keyboardStroke = false;\n\n  public override createRenderRoot() {\n    this.#children = Array.from(this.childNodes);\n    this.#field = this.querySelector(\"textarea\")!;\n    this.replaceChildren();\n    return this;\n  }\n\n  public override connectedCallback() {\n    super.connectedCallback();\n    if (this.#field)\n      this.#observe();\n  }\n\n  public override disconnectedCallback() {\n    this.#observer.disconnect();\n    super.disconnectedCallback();\n  }\n\n  protected override firstUpdated() {\n    this.#canvas = this.querySelector(\"canvas\")!;\n    this.#field.classList.add(\"companyos-signature__value\");\n    this.#field.tabIndex = -1;\n    this.#field.addEventListener(\"focus\", () => this.#canvas.focus());\n    this.#field.addEventListener(\"input\", () => this.#draw());\n    this.#field.addEventListener(\"change\", () => this.#draw());\n    this.#field.form?.addEventListener(\"reset\", () => { this.#finish(); setTimeout(() => this.#draw()); });\n    this.#observe();\n    this.#draw();\n  }\n\n  protected override updated() {\n    if (this.#canvas)\n      this.#draw();\n  }\n\n  protected override render() {\n    return html`${this.#children}\n      <div class=\"companyos-signature__pad\">\n        <canvas width=\"1024\" height=\"320\" tabindex=\"0\" role=\"img\"\n          aria-label=\"Handtekening tekenen\"\n          aria-description=\"Teken met muis, pen of vinger. Met het toetsenbord: houd Shift vast en teken met de pijltjestoetsen.\"\n          aria-invalid=${this.#field?.getAttribute(\"aria-invalid\") ?? \"false\"}\n          aria-disabled=${String(this.#disabled())}\n          aria-describedby=${this.#field?.getAttribute(\"aria-describedby\") ?? \"\"}\n          @pointerdown=${this.#start} @pointermove=${this.#move} @pointerup=${this.#finish}\n          @pointercancel=${this.#finish} @lostpointercapture=${this.#finish}\n          @keydown=${this.#key} @keyup=${() => { this.#keyboardStroke = false; }}\n          @blur=${() => { this.#keyboardStroke = false; }}></canvas>\n        <button type=\"button\" class=\"companyos-button\" ?disabled=${this.#disabled()} @click=${() => { this.#finish(); this.#write([]); }}>Wissen</button>\n      </div>\n      <p class=\"companyos-signature__help\">Teken met muis, pen of vinger. Toetsenbord: houd Shift vast en gebruik de pijltjestoetsen.</p>`;\n  }\n\n  #observe() {\n    this.#observer.observe(this.#field.form ?? this, { subtree: true, attributes: true, attributeFilter: [\"disabled\", \"readonly\", \"aria-invalid\", \"aria-describedby\"] });\n  }\n\n  #disabled() {\n    return !this.#field || this.#field.matches(\":disabled\") || this.#field.readOnly;\n  }\n\n  #strokes(): Stroke[] {\n    return this.#field.value ? (JSON.parse(this.#field.value) as { strokes: Stroke[] }).strokes : [];\n  }\n\n  #point(event: PointerEvent): Point {\n    const rect = this.#canvas.getBoundingClientRect();\n    return { x: Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width)), y: Math.min(1, Math.max(0, (event.clientY - rect.top) / rect.height)) };\n  }\n\n  #start(event: PointerEvent) {\n    if (this.#disabled() || event.button !== 0 || this.#pointer !== null)\n      return;\n    event.preventDefault();\n    this.#canvas.focus();\n    this.#canvas.setPointerCapture(event.pointerId);\n    this.#keyboardStroke = false;\n    this.#pointer = event.pointerId;\n    this.#cursor = this.#point(event);\n    // A tap is not a signature. Keep the first point only until actual movement arrives.\n  }\n\n  #move(event: PointerEvent) {\n    if (this.#disabled() || this.#pointer !== event.pointerId)\n      return;\n    const point = this.#point(event);\n    this.#append(point);\n  }\n\n  #finish() {\n    this.#pointer = null;\n    this.#keyboardStroke = false;\n  }\n\n  #append(point: Point) {\n    if (point.x === this.#cursor.x && point.y === this.#cursor.y)\n      return;\n    const strokes = this.#strokes();\n    if (strokes.reduce((count, stroke) => count + stroke.points.length, 0) >= 4094)\n      return;\n    if (!this.#keyboardStroke || !strokes.length) {\n      strokes.push({ points: [this.#cursor] });\n      this.#keyboardStroke = true;\n    }\n    strokes[strokes.length - 1].points.push(point);\n    this.#cursor = point;\n    this.#write(strokes);\n  }\n\n  #key(event: KeyboardEvent) {\n    if (this.#disabled() || !event.shiftKey || ![\"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", \"ArrowDown\"].includes(event.key))\n      return;\n    event.preventDefault();\n    this.#append({\n      x: Math.min(1, Math.max(0, this.#cursor.x + (event.key === \"ArrowRight\" ? 0.02 : event.key === \"ArrowLeft\" ? -0.02 : 0))),\n      y: Math.min(1, Math.max(0, this.#cursor.y + (event.key === \"ArrowDown\" ? 0.02 : event.key === \"ArrowUp\" ? -0.02 : 0))),\n    });\n  }\n\n  #write(strokes: Stroke[]) {\n    this.#field.value = strokes.length ? JSON.stringify({ strokes }) : \"\";\n    this.#field.dispatchEvent(new Event(\"input\", { bubbles: true }));\n    this.#field.dispatchEvent(new Event(\"change\", { bubbles: true }));\n    this.#draw();\n  }\n\n  #draw() {\n    const context = this.#canvas.getContext(\"2d\")!;\n    context.clearRect(0, 0, this.#canvas.width, this.#canvas.height);\n    context.lineWidth = 3;\n    context.lineCap = \"round\";\n    context.lineJoin = \"round\";\n    context.strokeStyle = \"#010504\";\n    for (const stroke of this.#strokes()) {\n      context.beginPath();\n      stroke.points.forEach((point, index) => {\n        const x = point.x * this.#canvas.width;\n        const y = point.y * this.#canvas.height;\n        if (index === 0)\n          context.moveTo(x, y);\n        else\n          context.lineTo(x, y);\n      });\n      context.stroke();\n    }\n  }\n}\n\ncustomElements.define(\"cos-signature\", CompanyosSignature);\n","import type { IconName } from \"../icons/icon-data\";\n\nexport type ToastTone = \"success\" | \"info\" | \"error\";\n\n/** Carbon notification: every status shows its filled icon next to its colour. */\nexport const TOAST_ICONS: Record<ToastTone, IconName> = { success: \"checkmark--filled\", info: \"information--filled\", error: \"error--filled\" };\nexport type ToastPauseReason = \"hover\" | \"focus\";\n\nexport interface ToastMessage {\n  id: number;\n  message: string;\n  tone: ToastTone;\n}\n\nexport interface ToastOptions {\n  message: string;\n  tone?: ToastTone;\n}\n\n/** A replaceable clock lets tests verify expiry without real-time delays. */\nexport interface ToastClock {\n  now: () => number;\n  schedule: (options: { callback: () => void; delayMs: number }) => () => void;\n}\n\ninterface ToastEntry {\n  message: ToastMessage;\n  remainingMs: number;\n  startedAt: number;\n  pauses: Set<ToastPauseReason>;\n  cancel?: () => void;\n}\n\nconst browserClock: ToastClock = {\n  now: () => performance.now(),\n  schedule: ({ callback, delayMs }) => {\n    const timer = setTimeout(callback, delayMs);\n    return () => clearTimeout(timer);\n  },\n};\n\n/**\n * Owns one app's transient notifications. Keep at most three, each visible for six seconds\n * of unpaused time. Clear on logout/unmount so messages never leak into another session.\n */\nexport class ToastController {\n  readonly #clock: ToastClock;\n  readonly #onChange: (messages: readonly ToastMessage[]) => void;\n  readonly #entries = new Map<number, ToastEntry>();\n  #nextId = 0;\n\n  public constructor(options: { clock?: ToastClock; onChange?: (messages: readonly ToastMessage[]) => void } = {}) {\n    this.#clock = options.clock ?? browserClock;\n    this.#onChange = options.onChange ?? (() => {});\n  }\n\n  public get messages(): readonly ToastMessage[] {\n    return [...this.#entries.values()].map(entry => entry.message);\n  }\n\n  public show(options: ToastOptions): number {\n    const id = ++this.#nextId;\n    const entry: ToastEntry = {\n      message: { id, message: options.message, tone: options.tone ?? \"info\" },\n      remainingMs: 6000,\n      startedAt: this.#clock.now(),\n      pauses: new Set(),\n    };\n    if (this.#entries.size >= 3) {\n      const oldest = this.messages[0];\n      if (oldest) this.dismiss(oldest.id);\n    }\n    this.#entries.set(id, entry);\n    this.#schedule(entry);\n    this.#publish();\n    return id;\n  }\n\n  public dismiss(id: number): void {\n    this.#entries.get(id)?.cancel?.();\n    this.#entries.delete(id);\n    this.#publish();\n  }\n\n  public pause(options: { id: number; reason: ToastPauseReason }): void {\n    const entry = this.#entries.get(options.id);\n    if (!entry || entry.pauses.has(options.reason)) return;\n    if (!entry.pauses.size) {\n      entry.remainingMs = Math.max(0, entry.remainingMs - (this.#clock.now() - entry.startedAt));\n      entry.cancel?.();\n      entry.cancel = undefined;\n    }\n    entry.pauses.add(options.reason);\n  }\n\n  public resume(options: { id: number; reason: ToastPauseReason }): void {\n    const entry = this.#entries.get(options.id);\n    // Hover and keyboard focus may overlap; neither may resume the other's pause.\n    if (!entry?.pauses.delete(options.reason) || entry.pauses.size) return;\n    this.#schedule(entry);\n  }\n\n  public clear(): void {\n    for (const entry of this.#entries.values()) entry.cancel?.();\n    this.#entries.clear();\n    this.#publish();\n  }\n\n  #schedule(entry: ToastEntry): void {\n    entry.startedAt = this.#clock.now();\n    entry.cancel = this.#clock.schedule({ delayMs: entry.remainingMs, callback: () => this.dismiss(entry.message.id) });\n  }\n\n  #publish(): void {\n    this.#onChange(this.messages);\n  }\n}\n","import { html, render } from \"lit\";\nimport { TOAST_ICONS, ToastController, type ToastMessage, type ToastOptions } from \"../lib/toasts\";\nimport { icon } from \"./icon\";\n\n/** The one live region per page, under <body> outside the page's main content. */\nconst REGION_CLASS = \"companyos-toasts\";\n\nlet controller: ToastController | undefined;\n\n// Created before the first message, so assistive technology hears additions (as ToastHost in the SPA)\nfunction ensure(): ToastController {\n  if (controller)\n    return controller;\n  const region = document.createElement(\"div\");\n  region.className = REGION_CLASS;\n  region.setAttribute(\"role\", \"region\");\n  region.setAttribute(\"aria-label\", \"Meldingen\");\n  region.setAttribute(\"aria-live\", \"polite\");\n  region.setAttribute(\"aria-relevant\", \"additions\");\n  region.setAttribute(\"aria-atomic\", \"false\");\n  document.body.append(region);\n  const created = new ToastController({ onChange: messages => render(messages.toReversed().map(message => toast(created, message)), region) });\n  controller = created;\n  return created;\n}\n\nfunction toast(owner: ToastController, { id, message, tone }: ToastMessage) {\n  return html`<div class=\"companyos-toast companyos-toast--${tone}\"\n      @mouseenter=${() => owner.pause({ id, reason: \"hover\" })} @mouseleave=${() => owner.resume({ id, reason: \"hover\" })}\n      @focusin=${() => owner.pause({ id, reason: \"focus\" })} @focusout=${() => owner.resume({ id, reason: \"focus\" })}>\n    ${icon(TOAST_ICONS[tone], 20)}\n    <p class=\"companyos-toast__message\">${message}</p>\n    <button class=\"companyos-toast__close\" type=\"button\" aria-label=\"Melding sluiten: ${message}\" @click=${() => owner.dismiss(id)}>${icon(\"close\", 20)}</button>\n  </div>`;\n}\n\n/**\n * Shows a short notification in the page's live region (at most three, six seconds each, paused on hover and focus).\n * Returns its id for `dismissToast`. Nothing is persisted: a new document starts without messages.\n */\nexport function showToast(options: ToastOptions): number {\n  return ensure().show(options);\n}\n\nexport function dismissToast(id: number): void {\n  controller?.dismiss(id);\n}\n\n// The region exists from DOM ready on every page that imports the screen entry, before any message\nif (document.readyState === \"loading\")\n  document.addEventListener(\"DOMContentLoaded\", () => ensure(), { once: true });\nelse\n  ensure();\n","export interface TabItem {\n  key: string;\n  label: string;\n  disabled?: boolean;\n  /** Content panels reserve space for a heading; list panels meet their toolbar directly. */\n  panelLayout?: \"content\" | \"list\";\n}\n\n/** Keep a reachable tab when an integration removes or disables the current selection. */\nexport function activeTabKey(options: { items: readonly TabItem[]; selected: string }): string | null {\n  return options.items.find(item => item.key === options.selected && !item.disabled)?.key\n    ?? options.items.find(item => !item.disabled)?.key\n    ?? null;\n}\n\n/** Automatic keyboard activation follows the visible enabled order, including wraparound. */\nexport function nextTabKey(options: { items: readonly TabItem[]; current: string; key: string }): string | null {\n  const enabled = options.items.filter(item => !item.disabled);\n  if (!enabled.length) return null;\n  const index = enabled.findIndex(item => item.key === options.current);\n  switch (options.key) {\n    case \"Home\": return enabled[0].key;\n    case \"End\": return enabled[enabled.length - 1].key;\n    case \"ArrowRight\": return enabled[(index + 1) % enabled.length].key;\n    case \"ArrowLeft\": return enabled[(index < 0 ? 0 : index + enabled.length - 1) % enabled.length].key;\n    default: return null;\n  }\n}\n\n/** IBM Carbon tabs: a tab set has at least two tabs (disabled ones count). Returns the developer message, or null. */\nexport function tabCountIssue(options: { label: string; items: readonly TabItem[] }): string | null {\n  const count = options.items.length;\n  return count >= 2 ? null : `Tabs \"${options.label}\" have ${count} ${count === 1 ? \"tab\" : \"tabs\"}; use at least two (IBM Carbon), or no tabs`;\n}\n","import { LitElement, html, type PropertyValues } from \"lit\";\nimport { activeTabKey, nextTabKey, tabCountIssue, type TabItem } from \"../lib/tabs\";\n\nlet lastId = 0;\n\n/**\n * Tabs over the panels that are its own children: `<cos-tabs label=\"...\"><section data-tab=\"ips\"\n * data-tab-title=\"IP-adressen\">...</section>...</cos-tabs>`. A panel with `data-tab-disabled` is shown in the\n * tablist but cannot be selected. The panels stay where the page or the parent template put them (light DOM); this\n * element only renders the tablist before them and toggles `hidden`, so a panel keeps its state when you switch.\n * Roles, roving tabindex, the keyboard (arrows, Home and End over the enabled tabs with wraparound, automatic\n * activation) and the fallback to the first enabled tab are those of the SPA's screen Tabs (lib/tabs.ts).\n * `selected` is the panel's `data-tab`; a user choice sets it and fires `tab-change` (detail: the value).\n * Fewer than two panels logs a console warning (IBM Carbon: a tab set has at least two tabs).\n * Not `<cos-sections>`: that one switches sections of a server-rendered form with plain buttons.\n */\nexport class CompanyosTabs extends LitElement {\n  public static override properties = { label: {}, selected: {} };\n  declare public label: string;\n  declare public selected: string;\n  readonly #id = `companyos-tabs-${++lastId}`;\n  #observer: MutationObserver | undefined;\n  #reported: string | null = null;\n\n  public constructor() {\n    super();\n    this.label = \"\";\n    this.selected = \"\";\n  }\n\n  // The tablist goes in its own first child, before the panels\n  public override createRenderRoot() {\n    const root = document.createElement(\"div\");\n    root.className = \"companyos-tabs__list\";\n    this.prepend(root);\n    return root;\n  }\n\n  public override connectedCallback() {\n    super.connectedCallback();\n    // Only own panels matter, not every change a panel's content makes\n    this.#observer = new MutationObserver(records => {\n      if (records.some(record => record.target === this || record.target.parentNode === this))\n        this.requestUpdate();\n    });\n    this.#observer.observe(this, { childList: true, attributes: true, subtree: true, attributeFilter: [\"data-tab\", \"data-tab-title\", \"data-tab-disabled\"] });\n  }\n\n  public override disconnectedCallback() {\n    super.disconnectedCallback();\n    this.#observer?.disconnect();\n  }\n\n  public override render() {\n    const items = this.#items();\n    const active = this.#active(items);\n    return html`<div role=\"tablist\" aria-label=${this.label} @keydown=${(event: KeyboardEvent) => this.#onKey({ event, items, active })}>${items.map(item => html`\n      <button type=\"button\" role=\"tab\" id=${this.#tabId(item.key)} aria-controls=${this.#panelId(item.key)} aria-selected=${item.key === active ? \"true\" : \"false\"}\n        tabindex=${item.key === active ? 0 : -1} ?disabled=${item.disabled} @click=${() => this.#select(item.key)}>${item.label}</button>`)}</div>`;\n  }\n\n  protected override updated(changed: PropertyValues<this>) {\n    super.updated(changed);\n    const items = this.#items();\n    // Always, not only in development: these parts stay free of WebHare imports. Once per change, not per render\n    const issue = tabCountIssue({ label: this.label, items });\n    if (issue && issue !== this.#reported)\n      console.warn(issue, this);\n    this.#reported = issue;\n    const active = this.#active(items);\n    for (const panel of this.#panels()) {\n      const value = panel.dataset.tab!;\n      panel.id ||= this.#panelId(value);\n      panel.setAttribute(\"role\", \"tabpanel\");\n      panel.setAttribute(\"aria-labelledby\", this.#tabId(value));\n      panel.tabIndex = 0;\n      panel.hidden = value !== active;\n    }\n    // The model follows the fallback, as in the SPA: after rendering, and only when there is a reachable tab\n    if (active !== null && active !== this.selected)\n      this.#select(active);\n  }\n\n  #panels(): HTMLElement[] {\n    return [...this.children].filter((child): child is HTMLElement => child instanceof HTMLElement && child.dataset.tab !== undefined);\n  }\n\n  #items(): TabItem[] {\n    return this.#panels().map(panel => ({ key: panel.dataset.tab!, label: panel.dataset.tabTitle ?? \"\", disabled: panel.hasAttribute(\"data-tab-disabled\") }));\n  }\n\n  #active(items: TabItem[]): string | null {\n    // No enabled tab: the current one stays shown\n    return activeTabKey({ items, selected: this.selected }) ?? (items.some(item => item.key === this.selected) ? this.selected : null);\n  }\n\n  #panelId(value: string): string {\n    return `${this.#id}-panel-${value}`;\n  }\n\n  #tabId(value: string): string {\n    return `${this.#id}-tab-${value}`;\n  }\n\n  #select(value: string): void {\n    if (value === this.selected)\n      return;\n    this.selected = value;\n    this.dispatchEvent(new CustomEvent(\"tab-change\", { detail: value, bubbles: true }));\n  }\n\n  #onKey({ event, items, active }: { event: KeyboardEvent; items: TabItem[]; active: string | null }): void {\n    const target = nextTabKey({ items, current: active ?? \"\", key: event.key });\n    if (!target)\n      return;\n    event.preventDefault();\n    this.#select(target);\n    void this.updateComplete.then(() => this.renderRoot.querySelector<HTMLButtonElement>(`#${CSS.escape(this.#tabId(target))}`)?.focus());\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"cos-tabs\": CompanyosTabs;\n  }\n}\n\nif (!customElements.get(\"cos-tabs\"))\n  customElements.define(\"cos-tabs\", CompanyosTabs);\n","import { ReactiveElement, html, nothing, render, type PropertyValues } from \"lit\";\nimport { icon } from \"./icon\";\n\ntype Key = string | number;\n\n/** Below this width the detail replaces the master: a 240px list next to a detail narrower than 560px helps no one. */\nconst SPLIT_WIDTH = 800;\nconst TOOLBAR = \"companyos-master-detail__toolbar\";\nconst SKELETON = \"companyos-master-detail__skeleton\";\n\n/**\n * A list with the details of one row, from its own children: `<cos-master-detail .open .keys .selected\n * .shownKey><div data-master>...</div><section data-detail aria-label=\"...\">content</section></cos-master-detail>`.\n * From 800px of its own width master and detail stand side by side; narrower, or expanded, the detail replaces the\n * master. The element adds a toolbar to the detail (previous, next, \"n van m\", expand, close) and owns Escape (expanded\n * first, then close, never while a dialog or row menu is open) and the focus back to the selected row of a\n * `<cos-table>` in the master after closing.\n * `selected` is the key the user asked for, `shownKey` the key whose data the detail shows; while they differ, the\n * detail hides its stale content behind a skeleton: at once when the detail covers the master, otherwise only with\n * `loadingVisible` (the page's delayed loading state), so a quick switch next to the list does not flash.\n * Escape from outside the element reaches it only when the page forwards it with `handleEscape(event)`.\n * Events: `select-row` (detail: key) from previous and next, the same event a `<cos-table>` fires, so one handler\n * on this element serves both; `detail-close` when the user closes the detail.\n */\nexport class CompanyosMasterDetail extends ReactiveElement {\n  public static override properties = {\n    open: { type: Boolean, reflect: true }, expanded: { type: Boolean, reflect: true }, keys: { attribute: false }, selected: { attribute: false },\n    shownKey: { attribute: false }, loadingVisible: { type: Boolean, attribute: \"loading-visible\" }, disabled: { type: Boolean }, itemName: { attribute: \"item-name\" },\n  };\n  declare public open: boolean;\n  declare public expanded: boolean;\n  /** The master's rows in their shown order, for previous, next and the position. */\n  declare public keys: readonly Key[];\n  declare public selected: Key | undefined;\n  declare public shownKey: Key | undefined;\n  declare public loadingVisible: boolean;\n  /** Disables previous and next, for example while the page saves. */\n  declare public disabled: boolean;\n  /** Completes \"Vorige\" and \"Volgende\" (\"naam\": \"Vorige naam\"). */\n  declare public itemName: string;\n  #wide = false;\n  readonly #resize = new ResizeObserver(([entry]) => {\n    const wide = entry.contentRect.width >= SPLIT_WIDTH;\n    if (wide !== this.#wide) {\n      this.#wide = wide;\n      this.requestUpdate();\n    }\n  });\n  // A detail the page renders later still needs its toolbar\n  readonly #children = new MutationObserver(() => this.requestUpdate());\n\n  public constructor() {\n    super();\n    this.open = false;\n    this.expanded = false;\n    this.keys = [];\n    this.selected = undefined;\n    this.shownKey = undefined;\n    this.loadingVisible = false;\n    this.disabled = false;\n    this.itemName = \"\";\n    this.addEventListener(\"keydown\", this.#onKeydown);\n  }\n\n  public override createRenderRoot() {\n    return this;\n  }\n\n  public override connectedCallback() {\n    super.connectedCallback();\n    this.#resize.observe(this);\n    this.#children.observe(this, { childList: true });\n  }\n\n  public override disconnectedCallback() {\n    super.disconnectedCallback();\n    this.#resize.disconnect();\n    this.#children.disconnect();\n  }\n\n  /** Closes the detail as the user would: fires `detail-close` and returns focus to the selected row. */\n  public async close(): Promise<void> {\n    this.open = false;\n    this.expanded = false;\n    this.dispatchEvent(new CustomEvent(\"detail-close\", { bubbles: true }));\n    await this.updateComplete;\n    const list = this.querySelector<HTMLElement & { focusRow(key: Key | undefined): Promise<void> }>(\":scope > [data-master] :is(cos-table, cos-list)\");\n    await list?.focusRow(this.selected);\n  }\n\n  /** Handles an Escape from elsewhere on the page (a header button, the tabs) as one from inside; ignores one already handled. */\n  public handleEscape(event: KeyboardEvent): void {\n    this.#onKeydown(event);\n  }\n\n  protected override updated(changed: PropertyValues<this>) {\n    super.updated(changed);\n    const split = this.open && this.#wide && !this.expanded;\n    this.toggleAttribute(\"split\", split);\n    const detail = this.querySelector<HTMLElement>(\":scope > [data-detail]\");\n    if (!detail)\n      return;\n    // Before the page's own content, outside the template parts its parent renders, so a re-render leaves them alone\n    let skeleton = detail.querySelector<HTMLElement>(`:scope > .${SKELETON}`);\n    if (!skeleton) {\n      skeleton = Object.assign(document.createElement(\"div\"), { className: SKELETON, innerHTML: `<span></span><span></span><span></span><span></span>` });\n      skeleton.setAttribute(\"aria-hidden\", \"true\");\n      detail.prepend(skeleton);\n    }\n    let toolbar = detail.querySelector<HTMLElement>(`:scope > .${TOOLBAR}`);\n    if (!toolbar) {\n      toolbar = Object.assign(document.createElement(\"div\"), { className: TOOLBAR });\n      detail.prepend(toolbar);\n    }\n    render(this.#toolbar(), toolbar);\n    const stale = this.open && this.selected !== undefined && this.shownKey !== this.selected;\n    const covered = stale && (!split || this.loadingVisible);\n    skeleton.hidden = !covered;\n    detail.toggleAttribute(\"data-covered\", covered);\n    for (const child of detail.children)\n      if (child !== toolbar && child !== skeleton)\n        (child as HTMLElement).inert = covered;\n  }\n\n  #toolbar() {\n    const index = this.selected === undefined ? -1 : this.keys.indexOf(this.selected);\n    const name = this.itemName ? ` ${this.itemName}` : \"\";\n    return html`<div class=\"companyos-master-detail__navigation\">\n        ${this.#button({ icon: \"chevron--left\", label: `Vorige${name}`, disabled: this.disabled || index <= 0, onClick: () => this.#step(index - 1) })}\n        ${this.#button({ icon: \"chevron--right\", label: `Volgende${name}`, disabled: this.disabled || !this.keys.length || index === this.keys.length - 1, onClick: () => this.#step(index + 1) })}\n        ${index >= 0 ? html`<span class=\"companyos-master-detail__position\">${index + 1} van ${this.keys.length}</span>` : nothing}\n      </div>\n      <div class=\"companyos-master-detail__controls\">\n        ${this.#wide ? this.#button({ icon: \"fit-to-screen\", label: this.expanded ? \"Detailpaneel verkleinen\" : \"Detailpaneel vergroten\", pressed: this.expanded, onClick: () => { this.expanded = !this.expanded; } }) : nothing}\n        ${this.#button({ icon: \"close\", label: \"Detailpaneel sluiten\", title: \"Sluiten (Escape)\", onClick: () => void this.close() })}\n      </div>`;\n  }\n\n  #button(options: { icon: \"chevron--left\" | \"chevron--right\" | \"fit-to-screen\" | \"close\"; label: string; disabled?: boolean; pressed?: boolean; title?: string; onClick: () => void }) {\n    return html`<button type=\"button\" class=\"companyos-master-detail__button\" aria-label=${options.label} title=${options.title ?? options.label}\n      aria-pressed=${options.pressed === undefined ? nothing : String(options.pressed)} ?disabled=${options.disabled} @click=${options.onClick}>${icon(options.icon, 16)}</button>`;\n  }\n\n  #step(index: number): void {\n    const key = this.keys[index];\n    if (key !== undefined)\n      this.dispatchEvent(new CustomEvent(\"select-row\", { detail: key, bubbles: true }));\n  }\n\n  #onKeydown = (event: KeyboardEvent): void => {\n    // A dialog or row menu handles its own Escape\n    if (event.key !== \"Escape\" || !this.open || event.defaultPrevented || (event.target as Element).closest(\".companyos-list__menu, dialog\") || document.querySelector(\"dialog[open]\"))\n      return;\n    event.preventDefault();\n    if (this.expanded)\n      this.expanded = false;\n    else\n      void this.close();\n  };\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"cos-master-detail\": CompanyosMasterDetail;\n  }\n}\n\nif (!customElements.get(\"cos-master-detail\"))\n  customElements.define(\"cos-master-detail\", CompanyosMasterDetail);\n","/** Posts a login form the server prepared (prepareFrontendLogin): WRDAuth sets the session cookie and goes on to its target. */\nexport function submitLoginForm(instruction: { action: string; vars: ReadonlyArray<{ name: string; value: string }> }): void {\n  const form = document.createElement(\"form\");\n  form.method = \"post\";\n  form.action = instruction.action;\n  form.hidden = true;\n  for (const variable of instruction.vars) {\n    const field = document.createElement(\"input\");\n    field.type = \"hidden\";\n    field.name = variable.name;\n    field.value = variable.value;\n    form.append(field);\n  }\n  document.body.append(form);\n  form.submit();\n}\n","// <locata-login>: the login of a Locata page site, in the panel of the CompanyOS login screen. Emailed code plus\n// single sign-on, answered by locata:pages_login. It follows the markup contract of CompanyOS' own login panel\n// (companyos/webdesigns/pages/login.witty), so that panel's styles apply, and relies on two listeners in CompanyOS'\n// frontend/login.ts: a click on [data-companyos-sso-login] starts the single sign-on, and input in the form hides\n// [data-companyos-login-error]. That error element is therefore set by hand, never through a Lit binding.\nimport { rpc, type OmitRPCContextArgs } from \"@webhare/rpc\";\nimport { LitElement, html, nothing } from \"@mod-companyos/webdesigns/pages/frontend/screen/screen\";\nimport type { PagesLoginRPC } from \"@mod-locata/js/rpc/pages-login\";\nimport { submitLoginForm } from \"../../portal/frontend/lib/login-form\";\n\nconst api = rpc<OmitRPCContextArgs<typeof PagesLoginRPC>>(\"locata:pages_login\", { baseUrl: location.origin });\ntype LoginOptions = Awaited<ReturnType<typeof api.getLoginOptions>>;\n\nconst RESEND_SECONDS = 60;\n// Carbon arrow--right, as in CompanyOS' login.witty\nconst arrow = html`<svg class=\"companyos-login__icon\" viewBox=\"0 0 32 32\" width=\"16\" height=\"16\" fill=\"currentColor\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M18 6 16.57 7.393 24.15 15 4 15 4 17 24.15 17 16.57 24.573 18 26 28 16 18 6z\"/></svg>`;\n\nexport class LocataLogin extends LitElement {\n  public static override properties = {\n    refused: { type: Boolean },\n    step: { state: true },\n    email: { state: true },\n    pending: { state: true },\n    cooldown: { state: true },\n    options: { state: true },\n  };\n\n  /** The page was reached after a refused single sign-on. */\n  declare public refused: boolean;\n  declare public step: \"email\" | \"code\";\n  declare public email: string;\n  declare public pending: boolean;\n  declare public cooldown: number;\n  declare public options: LoginOptions;\n\n  #resendAfter = 0;\n  #timer: ReturnType<typeof setInterval> | undefined;\n  #submit = (event: SubmitEvent): void => {\n    event.preventDefault();\n    void (this.step === \"email\" ? this.#requestCode() : this.#verifyCode());\n  };\n\n  public constructor() {\n    super();\n    this.refused = false;\n    this.step = \"email\";\n    this.email = \"\";\n    this.pending = false;\n    this.cooldown = 0;\n    this.options = {};\n  }\n\n  public override createRenderRoot() {\n    return this;\n  }\n\n  public override connectedCallback(): void {\n    super.connectedCallback();\n    this.#timer = setInterval(() => {\n      this.cooldown = Math.max(0, Math.ceil((this.#resendAfter - Date.now()) / 1000));\n    }, 1000);\n    // The code login stays available when the options cannot be read\n    void api.getLoginOptions().then(options => {\n      this.options = options;\n    }, () => undefined);\n  }\n\n  public override disconnectedCallback(): void {\n    super.disconnectedCallback();\n    clearInterval(this.#timer);\n  }\n\n  public override render() {\n    const { googleProvider, microsoftProvider, moduleProviders = [], testLogins = [] } = this.options;\n    const providers = [\n      ...microsoftProvider ? [{ tag: microsoftProvider, label: \"Microsoft\" }] : [],\n      ...googleProvider ? [{ tag: googleProvider, label: \"Google\" }] : [],\n      ...moduleProviders,\n    ];\n    return html`\n      <section class=\"companyos-login\" aria-labelledby=\"locata-login-title\">\n        <h2 id=\"locata-login-title\" class=\"companyos-login__title\">${this.step === \"email\" ? \"Inloggen\" : \"Controleer je e-mail\"}</h2>\n        ${this.refused ? html`<p class=\"companyos-login__error\" role=\"alert\">Dit account heeft geen toegang tot Locata.</p>` : nothing}\n        <form class=\"companyos-login__form\" novalidate @submit=${this.#submit}>\n          ${this.step === \"email\" ? html`\n            <label class=\"companyos-login__field\">\n              <span class=\"companyos-login__label\">E-mailadres</span>\n              <input class=\"companyos-login__input\" name=\"email\" type=\"email\" autocomplete=\"username\" required .value=${this.email}>\n            </label>` : html`\n            <p>We hebben een code van zes cijfers gestuurd naar ${this.email}.</p>\n            <label class=\"companyos-login__field\">\n              <span class=\"companyos-login__label\">Code</span>\n              <input class=\"companyos-login__input\" name=\"code\" inputmode=\"numeric\" autocomplete=\"one-time-code\" maxlength=\"6\" required>\n            </label>`}\n          <p class=\"companyos-login__error\" role=\"alert\" data-companyos-login-error hidden></p>\n          <button class=\"companyos-login__submit\" type=\"submit\" ?disabled=${this.pending}>\n            <span>${this.step === \"email\" ? \"Stuur inlogcode\" : \"Inloggen\"}</span>${arrow}\n          </button>\n          ${this.step === \"code\" ? html`\n            <button class=\"companyos-button\" type=\"button\" ?disabled=${this.pending || this.cooldown > 0} @click=${() => void this.#requestCode()}>${this.cooldown > 0 ? `Code opnieuw sturen (${this.cooldown} s)` : \"Code opnieuw sturen\"}</button>\n            <button class=\"companyos-button\" type=\"button\" ?disabled=${this.pending} @click=${() => void this.#changeEmail()}>Ander e-mailadres</button>` : nothing}\n        </form>\n        ${this.step === \"email\" ? providers.map(provider => html`\n          <button class=\"companyos-login__submit\" type=\"button\" data-companyos-sso-login=${provider.tag}>\n            <span>Inloggen met ${provider.label}</span>${arrow}\n          </button>`) : nothing}\n        ${this.step === \"email\" && testLogins.length ? html`\n          <section class=\"companyos-login__testlogins\" aria-labelledby=\"locata-login-testlogins-title\" data-companyos-testlogins>\n            <h3 id=\"locata-login-testlogins-title\" class=\"companyos-login__testlogins-title\">Lokale testaccounts</h3>\n            ${testLogins.map(login => html`\n              <button class=\"companyos-login__testlogin\" type=\"button\" ?disabled=${this.pending} @click=${() => void this.#requestCode(login.email)}>\n                <span class=\"companyos-login__testlogin-label\">${login.label}</span>\n                <span class=\"companyos-login__testlogin-email\">${login.email}</span>\n              </button>`)}\n          </section>` : nothing}\n      </section>`;\n  }\n\n  #showError(message: string): void {\n    const error = this.querySelector<HTMLElement>(\"[data-companyos-login-error]\")!;\n    error.textContent = message;\n    error.hidden = !message;\n  }\n\n  /** Requests a code for the typed address, or for a development test login, which then logs in at once. */\n  async #requestCode(testEmail?: string): Promise<void> {\n    if (this.pending || (!testEmail && this.step === \"code\" && this.cooldown > 0))\n      return;\n    if (testEmail) {\n      this.email = testEmail;\n    } else if (this.step === \"email\") {\n      const input = this.querySelector<HTMLInputElement>(\"input[name=email]\")!;\n      if (!input.value.trim() || !input.checkValidity()) {\n        this.#showError(\"Vul een geldig e-mailadres in.\");\n        input.focus();\n        return;\n      }\n      this.email = input.value.trim();\n    }\n    this.#showError(\"\");\n    this.pending = true;\n    let code = \"\";\n    try {\n      const result = await api.requestLoginCode({ email: this.email });\n      if (!result.success) {\n        this.#showError(result.error);\n        return;\n      }\n      if (testEmail && !result.code) {\n        this.#showError(\"Dit testaccount is niet beschikbaar.\");\n        return;\n      }\n      code = result.code ?? \"\";\n      this.step = \"code\";\n      this.#resendAfter = Date.now() + RESEND_SECONDS * 1000;\n      this.cooldown = RESEND_SECONDS;\n    } catch {\n      this.#showError(\"De code kon niet worden verstuurd. Controleer je verbinding en probeer het opnieuw.\");\n      return;\n    } finally {\n      this.pending = false;\n    }\n    await this.updateComplete;\n    const input = this.querySelector<HTMLInputElement>(\"input[name=code]\")!;\n    // Development and @beta.webhare.net accounts get the code back instead of a mail\n    input.value = code;\n    if (testEmail && code)\n      await this.#verifyCode();\n    else\n      input.focus();\n  }\n\n  async #verifyCode(): Promise<void> {\n    if (this.pending)\n      return;\n    const input = this.querySelector<HTMLInputElement>(\"input[name=code]\")!;\n    const code = input.value.trim();\n    if (!/^\\d{6}$/.test(code)) {\n      this.#showError(\"Vul de code van zes cijfers in.\");\n      input.focus();\n      return;\n    }\n    this.#showError(\"\");\n    this.pending = true;\n    try {\n      const result = await api.verifyLoginCode({ email: this.email, code });\n      if (!result.success) {\n        this.pending = false;\n        this.#showError(result.error);\n        input.focus();\n        return;\n      }\n      // WRDAuth sets the session cookie on this post and returns to the site root; pending stays on until the page leaves\n      submitLoginForm(result.form);\n    } catch {\n      this.pending = false;\n      this.#showError(\"Inloggen is niet gelukt. Controleer je verbinding en probeer het opnieuw.\");\n    }\n  }\n\n  async #changeEmail(): Promise<void> {\n    this.step = \"email\";\n    this.#showError(\"\");\n    await this.updateComplete;\n    this.querySelector<HTMLInputElement>(\"input[name=email]\")?.focus();\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"locata-login\": LocataLogin;\n  }\n}\n\n// Two asset packs on one page may both import the page layer\nif (!customElements.get(\"locata-login\"))\n  customElements.define(\"locata-login\", LocataLogin);\n","// The customer switch in the account menu of a Locata page site, for Tech_42 (locata:switchapplications) with more\n// than one environment; customers never see it. The server hands the session over (locata:applications.open) and\n// decides who may: nothing here grants access.\nimport * as dompack from \"dompack\";\nimport { isLoggedIn } from \"@webhare/frontend\";\nimport { rpc, type OmitRPCContextArgs } from \"@webhare/rpc\";\nimport { getAccountMenu } from \"@mod-companyos/webdesigns/pages/frontend/pages\";\nimport { readScreenData, showToast, writeScreenData } from \"@mod-companyos/webdesigns/pages/frontend/screen/screen\";\nimport type { ApplicationsRPC } from \"@mod-locata/js/rpc/applications\";\nimport { submitLoginForm } from \"../../portal/frontend/lib/login-form\";\n\nconst api = rpc<OmitRPCContextArgs<typeof ApplicationsRPC>>(\"locata:applications\", { baseUrl: location.origin });\n\ntype SwitchData = { canSwitch: boolean; applications: Array<{ id: string; title: string; url?: string }> };\nconst SWITCH_DATA = \"locata-switch-v1\";\n\nasync function readSwitch(): Promise<SwitchData> {\n  // shortcut: read once per tab and login, so a customer's pages do not ask on every load; a newly granted right\n  // shows in a new tab. Ask on every load if that ever matters.\n  const cached = readScreenData<SwitchData>(SWITCH_DATA);\n  if (cached)\n    return cached;\n  const { canSwitch, applications } = await api.list();\n  const data = { canSwitch, applications: applications.map(({ id, title, url }) => ({ id, title, url })) };\n  writeScreenData({ name: SWITCH_DATA, data });\n  return data;\n}\n\nasync function fillSwitch(): Promise<void> {\n  const { canSwitch, applications } = await readSwitch();\n  const menu = getAccountMenu();\n  if (!menu || !canSwitch || applications.length < 2)\n    return;\n  menu.addSeparator();\n  const customers = menu.addSubmenu({ id: \"locata-switch-menu\", label: \"Wissel van klant\" });\n  for (const application of applications) {\n    const current = application.url !== undefined && location.href.startsWith(application.url);\n    customers.addMenuItem({\n      id: `locata-switch-${application.id}`,\n      label: application.title,\n      checked: current,\n      onSelect: () => {\n        if (!current)\n          void api.open({ id: application.id }).then(({ form }) => submitLoginForm(form), () => showToast({ message: \"Wisselen is niet gelukt. Probeer het opnieuw.\", tone: \"error\" }));\n      },\n    });\n  }\n}\n\ndompack.register(\"[data-companyos-account]\", () => {\n  if (isLoggedIn())\n    fillSwitch().catch(error => console.error(\"Could not load the customer switch\", error));\n});\n","// Public frontend entry for a customer module's site on the Locata page layer: the CompanyOS page base and screen\n// parts, the Locata login, and the site's WRDAuth. A customer asset pack imports this next to its own page code.\n// No Vue here; the Vue shell lives in webdesigns/portal.\nimport \"@mod-companyos/webdesigns/pages/frontend/pages\";\nimport \"@mod-companyos/webdesigns/pages/frontend/screen/screen\";\nimport \"./login\";\nimport \"./switch\";\nimport { setupWRDAuth } from \"@webhare/frontend\";\n\n// Logout, the account menu and the single sign-on buttons need the site's own WRDAuth.\nsetupWRDAuth();\n","import { rpc, type OmitRPCContextArgs } from \"@webhare/rpc\";\nimport { readScreenData, writeScreenData } from \"@mod-companyos/webdesigns/pages/frontend/screen/screen\";\nimport type { ContainersRPC } from \"../../../js/containers.rpc\";\n\nconst api = rpc<OmitRPCContextArgs<typeof ContainersRPC>>(\"twentemilieu:containers\", { baseUrl: location.origin });\n\nexport type ContainerRow = Awaited<ReturnType<typeof api.list>>[number];\n\n// Change the name when the shape of a row changes: an older cached list would show the new column empty\nconst CONTAINERS_DATA = \"containers-v1\";\n\n/** Last visit's containers of this login, to show at once while the server's answer is on its way. */\nexport function cachedContainers(): ContainerRow[] | undefined {\n  return readScreenData<ContainerRow[]>(CONTAINERS_DATA);\n}\n\nexport async function readContainers(): Promise<ContainerRow[]> {\n  const rows = await api.list();\n  writeScreenData({ name: CONTAINERS_DATA, data: rows });\n  return rows;\n}\n","import * as dompack from \"dompack\";\nimport type { CompanyosTable } from \"@mod-companyos/webdesigns/pages/frontend/screen/screen\";\nimport { cachedContainers, readContainers, type ContainerRow } from \"../inventory\";\n\nasync function showContainers(table: CompanyosTable): Promise<void> {\n  table.itemKey = (row: ContainerRow) => row.guid;\n  table.itemLabel = (row: ContainerRow) => row.title;\n  table.selectable = false;\n  table.error = \"\";\n  // Last visit's containers stand at once; the server's answer replaces them without a loading state\n  const shown = cachedContainers();\n  if (shown)\n    table.items = shown;\n  table.loading = !shown;\n  try {\n    table.items = await readContainers();\n  } catch {\n    // Also clears a cached list: a visitor whose access was withdrawn must not keep reading it\n    table.items = [];\n    table.error = \"De containers konden niet worden geladen. Herlaad de pagina en log zo nodig opnieuw in.\";\n  } finally {\n    table.loading = false;\n  }\n}\n\ndompack.register<CompanyosTable>(\"cos-table.containers\", table => void showContainers(table));\n","// <locata-map>: the points of one or more layers on a map of the Netherlands, for a page on the Locata page layer.\n// The page sets `layers`; Locata draws the pins, the layer switch and the popups. The Vue shell keeps its own\n// components/LocataMap.vue; this element ignores a point's className and a layer's pinSize.\nimport * as L from \"leaflet\";\nimport \"leaflet/dist/leaflet.css\";\nimport \"./map.scss\";\nimport { LitElement, html, nothing, type PropertyValues } from \"@mod-companyos/webdesigns/pages/frontend/screen/screen\";\nimport type { MapLayer } from \"../../portal/frontend/lib/map-layers\";\n\nexport type { MapLayer, MapPoint } from \"../../portal/frontend/lib/map-layers\";\n\nconst FIT_PADDING = 24;\n\nexport class LocataMap extends LitElement {\n  public static override properties = {\n    layers: { attribute: false },\n    loading: { type: Boolean },\n    error: {},\n    label: {},\n    emptyLabel: { attribute: \"empty-label\" },\n  };\n\n  declare public layers: readonly MapLayer[];\n  /** No \"empty\" note while the first answer is on its way. */\n  declare public loading: boolean;\n  declare public error: string;\n  /** Accessible name of the map region. */\n  declare public label: string;\n  declare public emptyLabel: string;\n\n  #map: L.Map | undefined;\n  #control: L.Control.Layers | undefined;\n  #resize: ResizeObserver | undefined;\n  #drawn: L.LayerGroup[] = [];\n  #fitted = false;\n\n  public constructor() {\n    super();\n    this.layers = [];\n    this.loading = false;\n    this.error = \"\";\n    this.label = \"Locaties op de kaart van Nederland\";\n    this.emptyLabel = \"Nog geen locaties.\";\n  }\n\n  public override createRenderRoot() {\n    return this;\n  }\n\n  public override render() {\n    const points = this.layers.flatMap(layer => layer.points);\n    const missing = points.filter(point => !point.coordinates).length;\n    return html`\n      ${this.error ? html`<p class=\"locata-map__note\" role=\"alert\">${this.error}</p>` : nothing}\n      ${!this.error && !this.loading && !points.length ? html`<p class=\"locata-map__note\" role=\"status\">${this.emptyLabel}</p>` : nothing}\n      ${missing ? html`<p class=\"locata-map__note\">${missing} ${missing === 1 ? \"locatie zonder kaartpositie\" : \"locaties zonder kaartpositie\"}.</p>` : nothing}\n      <div class=\"locata-map__canvas\" role=\"region\" aria-label=${this.label}></div>`;\n  }\n\n  public override firstUpdated(): void {\n    const canvas = this.querySelector<HTMLElement>(\".locata-map__canvas\")!;\n    // A fixed centre and zoom, not fitBounds: a map that starts without a size would fit to zoom 19.\n    this.#map = L.map(canvas, { zoomControl: false, center: [52.15, 5.3], zoom: 7 });\n    L.control.zoom({ position: \"bottomleft\" }).addTo(this.#map);\n    L.tileLayer(\"https://tile.openstreetmap.org/{z}/{x}/{y}.png\", {\n      attribution: '&copy; <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a>',\n      maxZoom: 19,\n    }).addTo(this.#map);\n    // A map created before its layout is known caches a zero size and keeps grey tiles until told otherwise.\n    this.#resize = new ResizeObserver(() => {\n      this.#map?.invalidateSize();\n      this.#fit();\n    });\n    this.#resize.observe(canvas);\n    this.#draw();\n  }\n\n  public override updated(changed: PropertyValues): void {\n    if (changed.has(\"layers\") && this.#map)\n      this.#draw();\n  }\n\n  public override disconnectedCallback(): void {\n    super.disconnectedCallback();\n    this.#resize?.disconnect();\n    this.#map?.remove();\n    this.#map = undefined;\n  }\n\n  #draw(): void {\n    const map = this.#map;\n    if (!map)\n      return;\n    for (const group of this.#drawn.splice(0))\n      group.remove();\n    this.#control?.remove();\n    this.#control = undefined;\n    const overlays: Record<string, L.LayerGroup> = {};\n    this.layers.forEach((layer, index) => {\n      const group = L.layerGroup().addTo(map);\n      for (const point of layer.points) {\n        if (!point.coordinates)\n          continue;\n        const label = document.createElement(\"span\");\n        label.textContent = point.title;\n        // Up to four layers get their own colour; the layer switch names them.\n        L.marker(point.coordinates, { title: point.title, alt: point.title, icon: L.divIcon({ className: `locata-pin locata-pin--${index % 4}`, iconSize: [14, 14] }) })\n          .bindPopup(label).addTo(group);\n      }\n      this.#drawn.push(group);\n      overlays[layer.title] = group;\n    });\n    if (this.layers.length > 1)\n      this.#control = L.control.layers(undefined, overlays, { collapsed: false }).addTo(map);\n    this.#fit();\n  }\n\n  /** Zooms in on the points once, as soon as there are any and the map has a usable size. */\n  #fit(): void {\n    const map = this.#map;\n    const points = this.layers.flatMap(layer => layer.points.flatMap(point => point.coordinates ? [point.coordinates] : []));\n    const size = map?.getSize();\n    if (!map || this.#fitted || !points.length || !size || size.x < 4 * FIT_PADDING || size.y < 4 * FIT_PADDING)\n      return;\n    this.#fitted = true;\n    map.fitBounds(L.latLngBounds(points), { padding: [FIT_PADDING, FIT_PADDING] });\n  }\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"locata-map\": LocataMap;\n  }\n}\n\nif (!customElements.get(\"locata-map\"))\n  customElements.define(\"locata-map\", LocataMap);\n","import * as dompack from \"dompack\";\nimport \"@mod-locata/webdesigns/pages/frontend/map\";\nimport type { LocataMap, MapLayer } from \"@mod-locata/webdesigns/pages/frontend/map\";\nimport { cachedContainers, readContainers, type ContainerRow } from \"../inventory\";\n\nfunction layersOf(rows: ContainerRow[]): MapLayer[] {\n  return [{ id: \"containers\", title: \"Ondergrondse containers\", points: rows.map(row => ({ id: row.guid, title: row.title, coordinates: row.coordinates })) }];\n}\n\nasync function showExplorer(map: LocataMap): Promise<void> {\n  // Last visit's containers stand at once; the server's answer replaces them without a loading state\n  const shown = cachedContainers();\n  if (shown)\n    map.layers = layersOf(shown);\n  map.loading = !shown;\n  try {\n    map.layers = layersOf(await readContainers());\n  } catch {\n    // Also clears a cached list: a visitor whose access was withdrawn must not keep reading it\n    map.layers = [];\n    map.error = \"De containers konden niet worden geladen. Herlaad de pagina en log zo nodig opnieuw in.\";\n  } finally {\n    map.loading = false;\n  }\n}\n\ndompack.register<LocataMap>(\"locata-map.explorer\", map => void showExplorer(map));\n","import \"@webhare/frontend/src/init\";import \"/opt/wh/whtree/modules/publisher/js/internal/polyfills/all\";\nimport \"/opt/whdata/installedmodules/twentemilieu.20261124T123655.396Z/webdesigns/app/frontend/frontend\";const aps = globalThis.whAssetPacks ||= {}; aps[\"twentemilieu:app\"]=\"2026-11-24T12:36:57.764Z\";"],"mappings":"6kDAQO,SAASA,EAAOC,EAAM,CAC5B,IAAIC,EAAGC,EAAGC,EAAKC,EAEf,IAAKF,EAAI,EAAGC,EAAM,UAAU,OAAQD,EAAIC,EAAKD,IAAK,CACjDE,EAAM,UAAUF,CAAC,EACjB,IAAKD,KAAKG,EACTJ,EAAKC,CAAC,EAAIG,EAAIH,CAAC,CAElB,CACC,OAAOD,CACR,CAIO,IAAIK,EAAS,OAAO,SAAW,UAAY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AAe,OAAO,aAAcC,EAAS,ECnI/C,SAASuB,GAASC,EAAkC,CAClD,MAAO,CAAC,CAAE,GAAI,aAAc,MAAO,0BAA2B,OAAQA,EAAK,IAAIC,IAAQ,CAAE,GAAIA,EAAI,KAAM,MAAOA,EAAI,MAAO,YAAaA,EAAI,WAAY,EAAE,CAAE,CAAC,CAC7J,CAEA,eAAeC,GAAaC,EAA+B,CAEzD,IAAMC,EAAQC,GAAiB,EAC3BD,IACFD,EAAI,OAASJ,GAASK,CAAK,GAC7BD,EAAI,QAAU,CAACC,EACf,GAAI,CACFD,EAAI,OAASJ,GAAS,MAAMO,GAAe,CAAC,CAC9C,MAAQ,CAENH,EAAI,OAAS,CAAC,EACdA,EAAI,MAAQ,yFACd,QAAE,CACAA,EAAI,QAAU,EAChB,CACF,CAEQI,GAAoB,sBAAuBJ,GAAI,CAAQD,GAAaC,CAAG,EAAC,ECzByB,IAAMK,GAAM,WAAW,eAAiB,CAAC,EAAGA,GAAI,kBAAkB,EAAE","names":["extend","dest","i","j","len","src","create","F","proto","bind","fn","obj","slice","args","lastId","stamp","throttle","time","context","lock","wrapperFn","later","wrapNum","x","range","includeMax","max","min","falseFn","formatNum","num","precision","pow","trim","str","splitWords","setOptions","options","getParamString","existingUrl","uppercase","params","templateRe","template","data","key","value","isArray","indexOf","array","el","emptyImageUrl","getPrefixed","name","lastTime","timeoutDefer","timeToCall","requestFn","cancelFn","id","requestAnimFrame","immediate","cancelAnimFrame","Class","props","NewClass","Util.setOptions","parentProto","Util.create","Util.extend","checkDeprecatedMixinEvents","parentOptions","init","includes","Util.isArray","Events","types","type","Util.splitWords","removeAll","_once","newListener","listeners","Util.falseFn","index","listener","propagate","event","l","_fn","Util.stamp","Evented","Point","y","round","trunc","v","point","toPoint","Bounds","a","b","points","min2","max2","toBounds","bounds","xIntersects","yIntersects","xOverlaps","yOverlaps","bufferRatio","heightBuffer","widthBuffer","LatLngBounds","corner1","corner2","latlngs","sw","ne","sw2","ne2","LatLng","toLatLng","toLatLngBounds","latIntersects","lngIntersects","latOverlaps","lngOverlaps","maxMargin","lat","lng","alt","margin","Util.formatNum","other","Earth","sizeInMeters","latAccuracy","lngAccuracy","c","CRS","latlng","zoom","projectedPoint","scale","untransformedPoint","s","Util.wrapNum","center","newCenter","latShift","lngShift","newSw","newNe","latlng1","latlng2","rad","lat1","lat2","sinDLat","sinDLon","earthRadius","SphericalMercator","d","sin","Transformation","toTransformation","EPSG3857","EPSG900913","svgCreate","pointsToPath","rings","closed","len2","p","Browser","style","ie","ielt9","edge","webkit","userAgentContains","android","android23","webkitVer","androidStock","opera","chrome","gecko","safari","phantom","opera12","win","ie3d","webkit3d","gecko3d","any3d","mobile","mobileWebkit","mobileWebkit3d","msPointer","pointer","touchNative","touch","mobileOpera","mobileGecko","retina","passiveEvents","supportsPassiveOption","opts","canvas","svg","inlineSvg","div","vml","shape","mac","linux","POINTER_DOWN","POINTER_MOVE","POINTER_UP","POINTER_CANCEL","pEvent","handle","_onPointerStart","_handlePointer","_pointers","_pointerDocListener","addPointerListener","handler","_addPointerDocListener","removePointerListener","_globalPointerDown","_globalPointerMove","_globalPointerUp","e","DomEvent.preventDefault","makeDblclick","newEvent","prop","delay","addDoubleTapListener","last","detail","simDblclick","path","DomEvent.getPropagationPath","now","removeDoubleTapListener","handlers","TRANSFORM","testProp","TRANSITION","TRANSITION_END","get","getStyle","css","tagName","className","container","remove","parent","empty","toFront","toBack","hasClass","getClass","addClass","classes","setClass","removeClass","Util.trim","setOpacity","_setOpacityIE","filter","filterName","setTransform","offset","pos","setPosition","getPosition","disableTextSelection","enableTextSelection","_userSelect","DomEvent.on","DomEvent.off","userSelectProperty","disableImageDrag","enableImageDrag","_outlineElement","_outlineStyle","preventOutline","element","restoreOutline","getSizedParentNode","getScale","rect","on","addOne","eventsKey","off","batchRemove","removeOne","Util.indexOf","filterFn","mouseSubst","originalHandler","isExternalTarget","stopPropagation","disableScrollPropagation","disableClickPropagation","preventDefault","stop","getPropagationPath","ev","getMousePosition","wheelPxFactor","getWheelDelta","related","PosAnimation","newPos","duration","easeLinearity","DomUtil.getPosition","Util.requestAnimFrame","elapsed","progress","DomUtil.setPosition","Util.cancelAnimFrame","t","Map","Util.bind","DomUtil.TRANSITION","DomUtil.TRANSITION_END","moved","delta","viewHalf","containerPoint","centerOffset","paddingTL","paddingBR","paddingOffset","swPoint","nePoint","target","DomUtil.addClass","targetCenter","targetZoom","from","to","size","startZoom","w0","w1","u1","rho","rho2","r","s1","s2","t1","b1","sq","log","sinh","n","cosh","tanh","r0","w","u","easeOut","start","S","frame","oldZoom","pixelCenter","pixelPoint","pixelBounds","paddedBounds","paddedSize","oldSize","newSize","oldCenter","onResponse","onError","error","message","HandlerClass","DomUtil.remove","pane","DomUtil.create","inside","padding","nw","se","boundsSize","snap","scalex","scaley","topLeftPoint","toZoom","fromZoom","crs","layerPoint","DomEvent.getMousePosition","DomUtil.get","position","DomUtil.getStyle","panes","noMoveStart","loading","zoomChanged","supressEvent","onOff","targets","isHover","dragging","DomEvent.isExternalTarget","DomUtil.preventOutline","canvasTargets","synth","filtered","isMarker","callback","pixelOrigin","topLeft","latLngBounds","centerPoint","viewBounds","newBounds","pxBounds","maxBounds","projectedMaxBounds","minOffset","maxOffset","dx","dy","left","right","DomUtil.removeClass","proxy","DomUtil.TRANSFORM","transform","DomUtil.setTransform","z","startAnim","noUpdate","createMap","Control","map","corner","control","corners","createCorner","vSide","hSide","Layers","layerA","layerB","nameA","nameB","baseLayers","overlays","layer","acceptableHeight","collapsed","DomEvent.disableClickPropagation","DomEvent.disableScrollPropagation","section","link","overlay","DomUtil.empty","baseLayersPresent","overlaysPresent","baseLayersCount","checked","radioHtml","radioFragment","label","input","holder","inputs","addedLayers","removedLayers","that","layers","Zoom","zoomName","html","title","DomEvent.stop","Scale","maxMeters","meters","maxFeet","maxMiles","miles","feet","text","ratio","pow10","ukrainianFlag","Attribution","prefix","attribs","prefixAndAttribs","attribution","Handler","Mixin","START","Draggable","dragStartTarget","DomUtil.hasClass","DomUtil.disableImageDrag","DomUtil.disableTextSelection","first","sizedParent","DomUtil.getSizedParentNode","DomUtil.getScale","mouseevent","noInertia","DomUtil.enableImageDrag","DomUtil.enableTextSelection","fireDragend","clipPolygon","clippedPoints","edges","k","LineUtil._getBitCode","LineUtil._getEdgeIntersection","polygonCenter","p1","p2","f","area","LineUtil.isFlat","centroidLatLng","areaBounds","centroid","latlngCenter","coords","latSum","lngSum","simplify","tolerance","sqTolerance","_reducePoints","_simplifyDP","pointToSegmentDistance","_sqClosestPointOnSegment","closestPointOnSegment","ArrayConstructor","markers","_simplifyDPStep","newPoints","maxSqDist","sqDist","reducedPoints","prev","_sqDist","_lastCode","clipSegment","useLastCode","codeA","_getBitCode","codeB","codeOut","newCode","_getEdgeIntersection","code","dot","isFlat","_flat","polylineCenter","halfDist","segDist","dist","LonLat","Mercator","tmp","con","ts","phi","dphi","EPSG3395","EPSG4326","Simple","Layer","targetEl","events","method","minZoom","maxZoom","oldZoomSpan","LayerGroup","layerId","methodName","zIndex","layerGroup","FeatureGroup","featureGroup","Icon","oldIcon","img","sizeOption","anchor","icon","IconDefault","strip","re","idx","match","MarkerDrag","marker","speed","iconPos","origin","panBounds","movement","shadow","Marker","latLng","oldLatLng","classToAdd","addIcon","newShadow","addShadow","opt","draggable","opacity","DomUtil.setOpacity","iconOpts","Path","CircleMarker","radius","r2","circleMarker","Circle","legacyOptions","half","latR","top","bottom","lngR","circle","Polyline","minDistance","minPoint","closest","LineUtil._sqClosestPointOnSegment","jLen","LineUtil.polylineCenter","result","flat","projectedBounds","ring","parts","segment","LineUtil.clipSegment","LineUtil.simplify","part","LineUtil.pointToSegmentDistance","polyline","LineUtil._flat","Polygon","PolyUtil.polygonCenter","clipped","PolyUtil.clipPolygon","polygon","GeoJSON","geojson","features","feature","geometryToLayer","asFeature","geometry","pointToLayer","_coordsToLatLng","coordsToLatLng","_pointToLayer","coordsToLatLngs","geoLayer","featureLayer","pointToLayerFn","levelsDeep","latLngToCoords","latLngsToCoords","getFeature","newGeometry","PointToGeoJSON","multi","holes","isGeometryCollection","jsons","json","geoJSON","geoJson","ImageOverlay","url","styleOpts","DomUtil.toFront","DomUtil.toBack","wasElementSupplied","image","errorUrl","imageOverlay","VideoOverlay","vid","sourceElements","sources","source","videoOverlay","video","SVGOverlay","svgOverlay","DivOverlay","content","node","OverlayClass","old","Popup","DomEvent.stopPropagation","wrapper","closeButton","width","height","maxHeight","scrolledClass","marginBottom","containerHeight","containerWidth","layerPos","containerPos","popup","Tooltip","subX","subY","tooltipPoint","direction","tooltipWidth","tooltipHeight","tooltip","DivIcon","bgPos","divIcon","GridLayer","tileZoom","Util.throttle","compare","edgeZIndex","nextFrame","willPrune","tile","fade","level","x2","y2","z2","coords2","animating","noPrune","tileZoomChanged","translate","tileSize","mapZoom","halfSize","tileRange","tileCenter","queue","noPruneRange","fragment","tileBounds","nwPoint","sePoint","bp","tilePos","err","newCoords","gridLayer","TileLayer","noRedraw","done","invertedY","Util.template","zoomReverse","zoomOffset","tilePoint","Util.emptyImageUrl","tileLayer","TileLayerWMS","wmsParams","realRetina","projectionKey","bbox","tileLayerWMS","Renderer","currentCenterPoint","topLeftOffset","Canvas","m","order","next","dashArray","dashValue","ctx","clickedLayer","candidateHoveredLayer","vmlCreate","vmlMixin","stroke","fill","SVG","arc","renderer","Rectangle","rectangle","BoxZoom","DoubleClickZoom","Drag","pxCenter","pxWorldCenter","threshold","limit","worldWidth","halfWidth","newX1","newX2","newX","ease","speedVector","limitedSpeed","limitedSpeedVector","decelerationDuration","Keyboard","body","docEl","panDelta","keys","codes","zoomDelta","newLatLng","ScrollWheelZoom","DomEvent.getWheelDelta","debounce","d2","d3","d4","tapHoldDelay","TapHold","cancelClickPrevent","simulatedEvent","TouchZoom","moveFn","settingschangedcallbacks","globalDebugFlags","localDebugFlags","debugFlagsOverridesCB","DebugFlagsProxyHandler","debugFlagsOverridesCB","localDebugFlags","globalDebugFlags","target","p","record","keys","key","newValue","toModify","runSettingsCallbacks","value","debugFlags","formatForConsoleLogs","cb","settingschangedcallbacks","e","dtapStage","isLive","backendBase","dtapstage","dtapStage","islive","isLive","initEnv","setDtapStage","setBackendBase","dtapStage","isLive","backendBase","dtapstage","islive","getBrowserDebugFlags","varname","flags","urldebugvar","debugcookie","debugcookievalue","flag","sessionDebug","qR","node_or_selector","selector","matches","qSA","isElement","node","isHTMLElement","parseLanguageTag","languageTag","match","getLang","node","tag","getWHType","obj","isCrossRealm","value","isMoney","isTemporalInstant","isTemporalPlainDateTime","isTemporalPlainDate","isTemporalPlainTime","isTemporalZonedDateTime","isDate","isBlob","isFile","stdTypeOf","value","t","isMoney","isBlob","isFile","isDate","isTemporalInstant","isTemporalPlainTime","isTemporalPlainDate","isTemporalPlainDateTime","isTemporalZonedDateTime","stripUnneededDecimals","num","decimals","isneg","toText","amount","decimalpoint","mindecimals","isnegative","astext","splitValue","money","split","sign","joinPrice","parts","adjustDecimals","requiredecimals","toadd","multiplier","idx","__add","lhs","rhs","requiredecimals","adjustDecimals","add","amount1","amount2","joinPrice","splitValue","subtract","amount","tosubtract","__multiply","multiply","cmp","diff","getPercentageOfAmount","perc","result","normalize","__roundIntegerToMultiple","value","roundunit","mode","roundToMultiple","unit","split_value","splitValue","split_unit","requiredecimals","adjustDecimals","result","joinPrice","min","amount","amounts","val","cmp","max","getNonNegativePowerOf10","exp","retval","running_exp","divide","divisor","lhs","rhs","mul10exp","mulfactor","test","lhs","relation","rhs","compareresult","cmp","stripUnneededDecimals","num","decimals","isneg","splitValue","money","split","sign","toText","amount","decimalpoint","mindecimals","thousandpoint","isnegative","astext","beforepoint","afterpoint","Money","_Money","value","intvalue","param","isMoney","left","right","sum","item","add","subtract","roundto","mode","roundToMultiple","lhs","rhs","cmp","relation","test","multiply","percentage","getPercentageOfAmount","numerator","divisor","divide","amounts","min","max","format","nameToSnakeCase","name","c","recodeObject","inp","isDate","isMoney","isBlob","isTemporalInstant","isTemporalPlainDate","isTemporalPlainDateTime","isTemporalZonedDateTime","recursiveToSnakeCase","toSnakeCase","key","value","toSnakeCase","inp","recursiveToSnakeCase","escapeRegExp","text","options","mask","isHTMLUnrepresentableChar","curch","encodeEntities","str","html","s","char","stringify","arg","options","usereplacer","key","value","origvalue","type","stdTypeOf","lhs","rhs","result","encodeEntities","parseTyped","input","Money","omit","value","keys","elt","ret","key","val","unlock","LocalMutex","defer","LocalLock","mutex","config","siteroot","dtapStage","whconfigel","parsedConfig","omit","initEnv","flag","getBrowserDebugFlags","debugFlags","frontendConfig","getLang","getFrontendData","dataObject","allowMissing","retval","resolve","reject","_resolve","_reject","items","callbackfn","retval","idx","item","key","list","IteratorPrototype","ArrayIteratorPrototype","OriginalIteratorPrototype","callback","it","value","next_value","real_value","max_count","values","limit","remaining","index","mapper","mapped","reducer","initial_value","acc","count","string","final","first","iterables","others","it_array","e","finished","partition1","partition2","i","max","min","isObject","t","GetIteratorFlattenable","obj","method","iterator","Iterator","WrappedIterator","#iterator","args","returnMethod","Iterator_from","submitForm","action","values","method","form","item","input","navigateTo","navigation","debugFlags","CustomEvent","dispatchCustomEvent","node","event","params","prop","evt","CustomEvent","defaultaction","stop","event","addDocEventListener","node","type","listener","options","locallocks","modallocked","uiwatcher","installedanticancelhandler","currentbusymodaldialog","currentbusymodaluserdialog","busymodalcontent","mylockmgr","getLockmgr","getParentLockManager","LockManager","anyModalLocks","l","scheduleCheckUIFree","checkUIFree","toggleBusyModal","lockmgr","isDialogElement","el","checkCancelEvent","evt","show","dispatchCustomEvent","dialog","toembed","lock","pos","debugFlags","BusyLock","options","lockmgr","getLockmgr","locallocks","modallocked","toggleBusyModal","debugFlags","lockpos","scheduleCheckUIFree","flagUIBusy","options","BusyLock","getParentLockManager","debugFlags","locallocks","l","lockmgr","getLockmgr","locallockmgr","LockManager","lock","mylockmgr","isDomReady","onDomReady","callback","e","components","map","isNodeCompletelyInDom","node","processRegistration","item","reg","domready","list","applyRegistration","startnode","isDomReady","items","e","register","selector","handler","options","newreg","components","isDomReady","onDomReady","registerMissed","applyRegistration","startnode","item","getCookie","key","value","escapeRegExp","parseUserAgent","ua","UA","platform","name","version","device","browser","getBrowser","parseUserAgent","config","forwardPublisherNavigation","event","isHTMLElement","navaction","desturl","origin","configureForCMS","e","VERTEX","FRAGMENT","hexToRgb","color","i","start","el","gl","compile","type","source","shader","program","position","resolution","time","still","startedAt","frame","draw","now","loop","resize","ratio","onVisibility","visible","canvas","UNKNOWN_FUNCTION","parse","stackString","lines","stack","line","parseResult","parseChrome","parseWinjs","parseGecko","parseNode","parseJSC","chromeRe","chromeEvalRe","parts","isNative","isEval","submatch","winjsRe","geckoRe","geckoEvalRe","javaScriptCoreRe","nodeRe","parseTrace","e","parse","i","formatTrace","trace","e","prependStackTrace","error","stacklines","tracelines","globalseqnr","getDebugAppend","urldebugvar","ControlledCall","client","method","stack","id","options","callurl","fetchoptions","fetchpromise","requestStack","response","retryafter","resolve","exception","jsonresponse","logitem","err","prependStackTrace","RPCClient","url","debugFlags","error","backendBase","params","parseTrace","ServiceProxy","target","prop","receiver","newoptions","createClient","args","servicename","rpcclient","isAbsolute","url","getBaseURL","backendBase","ControlledCall","client","method","stack","options","callurl","fetchoptions","fetchpromise","requestStack","response","exception","retryafter","resolve","jsonresponse","parseTyped","logitem","omit","err","prependStackTrace","RPCClient","debugFlags","error","params","stringify","pathName","parseTrace","ServiceProxy","target","prop","receiver","newoptions","rpc","args","service","servicematch","rpcclient","PublicCookieSuffix","authOptions","getCookieName","getFrontendData","getAuthLocalData","c","parseTyped","getCookie","PublicCookieSuffix","submitLoginForm","node","event","_stack","stop","username","password","site","returnto","persistentlogin","login","lock","__using","flagUIBusy","loginresult","refreshLoginStatus","navigateTo","failLogin","_","_error","_hasError","__callDispose","loggedIn","isLoggedIn","setupWRDAuth","options","register","addDocEventListener","evt","handleLogoutClick","doLogout","logout","onDomReady","message","response","form","evtdetail","dispatchCustomEvent","loginfield","qR","getUserInfo","getLoginTweaks","tweaks","getLang","urlvars","cookieName","result","rpc","getBrowser","startSSOLogin","tag","client","createClient","defer","toSnakeCase","instr","e","postRenderChecks","log","logtext","onDomReady","MESSAGES","event","form","error","input","button","startSSOLogin","register","node","event","PUBLIC_COOKIE_SUFFIX","resolveVisibleAppIds","visibleAppIds","canManageApps","id","publicAuthValue","cookies","cookieName","prefix","cookie","writeCachedAppIds","storage","key","auth","appIds","DEFAULT_SCHEMA","client","rpc","useRpc","readCacheKey","scope","name","readCached","context","key","raw","entry","parseTyped","clearCached","storage","keys","marker","writeCached","data","stringify","pageContext","scope","config","publicAuthValue","readScreenData","name","context","readCached","writeScreenData","data","writeCached","clearScreenData","clearCached","warmOnIntent","selector","warm","warmed","onIntent","event","link","type","APP_ACCESS_DATA","initialAppUser","users","userId","user","warmAppAccess","useRpc","DEFAULT_SCHEMA","selected","writeScreenData","scope","getAppSession","useRpc","DEFAULT_SCHEMA","error","setSettingsAccess","access","items","item","id","group","first","entry","APPS_STATE_ATTRIBUTE","revealApps","root","items","isLoggedIn","clearScreenData","item","storeAppIds","visibleAppIds","canManageApps","userId","getAppSession","setSettingsAccess","warmOnIntent","warmAppAccess","appIds","resolveVisibleAppIds","error","key","auth","publicAuthValue","getFrontendData","writeCachedAppIds","trimSlashes","path","followSpaBookmark","dashboard","wanted","target","link","a","b","start","global","globalThis","supportsAdoptingStyleSheets","ShadowRoot","ShadyCSS","nativeShadow","Document","prototype","CSSStyleSheet","constructionToken","Symbol","cssTagCache","WeakMap","CSSResult","cssText","strings","safeToken","this","Error","_strings","styleSheet","_styleSheet","cacheable","length","get","replaceSync","set","toString","unsafeCSS","value","String","adoptStyles","renderRoot","styles","supportsAdoptingStyleSheets","adoptedStyleSheets","map","s","CSSStyleSheet","styleSheet","style","document","createElement","nonce","global","setAttribute","textContent","cssText","appendChild","getCompatibleStyle","sheet","rule","cssRules","unsafeCSS","is","defineProperty","getOwnPropertyDescriptor","getOwnPropertyNames","getOwnPropertySymbols","getPrototypeOf","Object","global","globalThis","trustedTypes","emptyStringForBooleanAttribute","emptyScript","polyfillSupport","reactiveElementPolyfillSupport","JSCompiler_renameProperty","prop","_obj","defaultConverter","value","type","Boolean","Array","JSON","stringify","fromValue","Number","parse","e","notEqual","old","defaultPropertyDeclaration","attribute","String","converter","reflect","useDefault","hasChanged","Symbol","metadata","litPropertyMetadata","WeakMap","ReactiveElement","HTMLElement","initializer","this","__prepare","_initializers","push","observedAttributes","finalize","__attributeToPropertyMap","keys","name","options","state","prototype","hasOwnProperty","create","wrapped","elementProperties","set","noAccessor","key","descriptor","getPropertyDescriptor","get","v","oldValue","call","requestUpdate","configurable","enumerable","superCtor","Map","finalized","props","properties","propKeys","p","createProperty","attr","__attributeNameForProperty","elementStyles","finalizeStyles","styles","isArray","Set","flat","Infinity","reverse","s","unshift","getCompatibleStyle","toLowerCase","constructor","super","__instanceProperties","isUpdatePending","hasUpdated","__reflectingProperty","__initialize","__updatePromise","Promise","res","enableUpdating","_$changedProperties","__saveInstanceProperties","forEach","i","controller","__controllers","add","renderRoot","isConnected","hostConnected","delete","instanceProperties","size","createRenderRoot","shadowRoot","attachShadow","shadowRootOptions","adoptStyles","connectedCallback","c","_requestedUpdate","disconnectedCallback","hostDisconnected","_old","_$attributeToProperty","attrValue","toAttribute","removeAttribute","setAttribute","ctor","propName","getPropertyOptions","fromAttribute","convertedValue","__defaultValues","useNewValue","newValue","hasAttribute","_$changeProperty","__enqueueUpdate","initializeValue","has","__reflectingProperties","reject","result","scheduleUpdate","performUpdate","shouldUpdate","changedProperties","willUpdate","hostUpdate","update","__markUpdated","_$didUpdate","_changedProperties","hostUpdated","firstUpdated","updated","updateComplete","getUpdateComplete","__propertyToAttribute","mode","reactiveElementVersions","global","globalThis","wrap","node","trustedTypes","policy","createPolicy","createHTML","s","boundAttributeSuffix","marker","Math","random","toFixed","slice","markerMatch","nodeMarker","d","document","createMarker","createComment","isPrimitive","value","isArray","Array","isIterable","Symbol","iterator","SPACE_CHAR","textEndRegex","commentEndRegex","comment2EndRegex","tagEndRegex","RegExp","singleQuoteAttrEndRegex","doubleQuoteAttrEndRegex","rawTextElement","tag","type","strings","values","_$litType$","html","svg","mathml","noChange","for","nothing","templateCache","WeakMap","walker","createTreeWalker","trustFromTemplateString","tsa","stringFromTSA","hasOwnProperty","Error","getTemplateHtml","l","length","attrNames","rawTextEndRegex","regex","i","attrName","match","attrNameEndIndex","lastIndex","exec","test","end","startsWith","push","Template","constructor","options","this","parts","nodeIndex","attrNameIndex","partCount","el","createElement","currentNode","content","wrapper","firstChild","replaceWith","childNodes","nextNode","nodeType","hasAttributes","name","getAttributeNames","endsWith","realName","statics","getAttribute","split","m","index","ctor","PropertyPart","BooleanAttributePart","EventPart","AttributePart","removeAttribute","tagName","textContent","emptyScript","append","data","indexOf","_options","innerHTML","resolveDirective","part","parent","attributeIndex","currentDirective","__directives","__directive","nextDirectiveConstructor","_$initialize","_$resolve","TemplateInstance","template","_$parts","_$disconnectableChildren","_$template","_$parent","parentNode","_$isConnected","fragment","creationScope","importNode","partIndex","templatePart","ChildPart","nextSibling","ElementPart","_$setValue","__isConnected","startNode","endNode","_$committedValue","_$startNode","_$endNode","isConnected","directiveParent","_$clear","_commitText","_commitTemplateResult","_commitNode","_commitIterable","insertBefore","_insert","createTextNode","result","_$getTemplate","h","_update","instance","_clone","get","set","itemParts","itemPart","item","start","from","_$notifyConnectionChanged","n","remove","element","fill","String","valueIndex","noCommit","change","v","_commitValue","setAttribute","toggleAttribute","super","newListener","oldListener","shouldRemoveListener","capture","once","passive","shouldAddListener","removeEventListener","addEventListener","event","call","host","handleEvent","polyfillSupport","global","litHtmlPolyfillSupport","Template","ChildPart","litHtmlVersions","push","render","value","container","options","partOwnerNode","renderBefore","part","endNode","insertBefore","createMarker","_$setValue","global","globalThis","LitElement","ReactiveElement","constructor","this","renderOptions","host","__childPart","createRenderRoot","renderRoot","super","renderBefore","firstChild","changedProperties","value","render","hasUpdated","isConnected","update","connectedCallback","setConnected","disconnectedCallback","noChange","litElementHydrateSupport","polyfillSupport","litElementPolyfillSupport","global","litElementVersions","push","actionKind","action","actionRank","kind","getMenuActions","options","ordered","left","right","firstOtherAction","index","normalized","STANDARD_ICONS","getInlineRowActions","menu","inline","getRowActionsWidth","getMenuPosition","ifDefined","value","nothing","ICON_DATA","icon","name","size","b","ICON_DATA","tag","attrs","w","o","CompanyosMenuItems","_CompanyosMenuItems","#owner","options","button","#button","separator","element","trigger","child","CompanyosMenu","label","glyph","D","icon","MENU_ID","menuIds","#panel","#trigger","#parent","#children","#activeChild","#closeTimer","#listeners","#openListeners","#open","#onClose","signal","event","#onKeydown","target","#openSubmenu","#setTrigger","anchor","parent","width","point","position","getMenuPosition","items","#items","menu","item","focused","index","next","ThemeController","#environment","#theme","#fixedTheme","environment","options","next","createPageTheme","storageKey","onApply","root","controller","ThemeController","next","start","button","theme","displayName","info","combined","ACCOUNT_ITEMS","getAccountMenu","start","setupAccount","account","isLoggedIn","getUserInfo","name","email","button","panel","element","menu","CompanyosMenu","themes","themeItems","option","item","theme","createPageTheme","next","accountItems","logout","CompanyosPageHeader","#render","title","description","lede","headingLevel","element","level","parent","headingIds","CompanyosSection","#heading","#render","text","tag","heading","UNSAVED_ATTRIBUTE","GUARD","SCOPE","submittedScopes","leaving","scopeOf","node","form","scope","hasUnsavedChanges","root","markUnsaved","event","REGISTERED","register","CompanyosSections","i","#sections","#label","#active","#adopt","b","section","label","#select","isUnsaved","nav","hostId","host","link","UNSAVED_ATTRIBUTE","event","#revealError","selected","name","error","field","target","focus","entry","heading","nextListSort","options","CompanyosColumn","key","align","href","#width","item","_match","field","attribute","fallback","value","CompanyosButton","i","classes","b","A","#activate","event","CompanyosSearch","options","#input","CompanyosSelect","#options","#change","CompanyosEmptyState","copy","headingLevel","CompanyosToolbar","table","#table","#tableChanged","#focusSearch","#sync","target","search","button","name","constructor","CONTROL","FIELD","CompanyosTable","i","#viewItems","#renderColumns","#columnObserver","records","record","node","#cursor","#menu","#pointerType","item","root","key","#keys","row","element","changed","column","query","#textValue","keys","#closeMenu","b","#clearSearch","A","actions","buttons","#inlineActions","skeleton","#onKeydown","getRowActionsWidth","#heading","#row","empty","#emit","sortable","sorted","align","#onSort","icon","selected","event","#onRowClick","#onDoubleClick","#onContextMenu","#checkCell","#textCell","#actionsCell","#actions","getMenuActions","getInlineRowActions","inline","name","action","#openMenu","raw","text","badge","checked","type","detail","#select","nextListSort","trigger","index","target","options","menu","CompanyosMenu","current","CompanyosTable","lastId","CompanyosDialog","i","#id","#content","#opener","#discardOrigin","#confirmingDiscard","#actionsDisabled","active","#dialog","disabled","b","A","#onCancel","#onClose","#onBackdrop","icon","#renderContents","#onSubmit","changed","fields","actions","node","dialog","shown","wasReady","#ready","#focusAfterSave","#keepEditing","#discard","invalid","event","rect","origin","CompanyosSignature","i","#children","#field","#canvas","#observer","#pointer","#cursor","#keyboardStroke","#observe","#draw","#finish","b","#disabled","#start","#move","#key","#write","#strokes","#point","event","rect","point","#append","strokes","count","stroke","context","index","x","y","TOAST_ICONS","browserClock","callback","delayMs","timer","ToastController","#clock","#onChange","#entries","#nextId","options","entry","id","oldest","#schedule","#publish","REGION_CLASS","controller","ensure","region","created","ToastController","messages","D","message","toast","owner","id","tone","b","icon","TOAST_ICONS","showToast","options","ensure","activeTabKey","options","item","nextTabKey","enabled","index","tabCountIssue","count","lastId","CompanyosTabs","i","#id","#observer","#reported","root","records","record","items","#items","active","#active","b","event","#onKey","item","#tabId","#panelId","#select","changed","issue","tabCountIssue","panel","#panels","value","child","activeTabKey","target","nextTabKey","SPLIT_WIDTH","TOOLBAR","SKELETON","CompanyosMasterDetail","y","#wide","#resize","entry","wide","#children","#onKeydown","event","changed","split","detail","skeleton","toolbar","D","#toolbar","covered","child","index","name","b","#button","#step","A","options","icon","key","submitLoginForm","instruction","form","variable","field","api","rpc","RESEND_SECONDS","arrow","b","LocataLogin","i","#resendAfter","#timer","#submit","event","#requestCode","#verifyCode","options","googleProvider","microsoftProvider","moduleProviders","testLogins","providers","A","#changeEmail","provider","login","#showError","message","error","testEmail","input","code","result","submitLoginForm","api","rpc","SWITCH_DATA","readSwitch","cached","readScreenData","canSwitch","applications","data","id","title","url","writeScreenData","fillSwitch","menu","getAccountMenu","customers","application","current","form","submitLoginForm","showToast","register","isLoggedIn","error","setupWRDAuth","api","rpc","CONTAINERS_DATA","cachedContainers","readScreenData","readContainers","rows","writeScreenData","showContainers","table","row","shown","cachedContainers","readContainers","register","L","FIT_PADDING","LocataMap","i","#map","#control","#resize","#drawn","#fitted","points","layer","missing","point","b","A","canvas","#fit","#draw","changed","map","group","overlays","index","label","size","layersOf","rows","row","showExplorer","map","shown","cachedContainers","readContainers","register","aps"]}