/******/ var __webpack_modules__ = ({

/***/ 733:
/***/ ((__unused_webpack_module, exports) => {

var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'align-justify';
var width = 448;
var height = 512;
var ligatures = [];
var unicode = 'f039';
var svgPathData = 'M432 416H16a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zm0-128H16a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zm0-128H16a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zm0-128H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16z';

exports.mw = {
  prefix: prefix,
  iconName: iconName,
  icon: [
    width,
    height,
    ligatures,
    unicode,
    svgPathData
  ]};

exports.Ti = exports.mw;
__webpack_unused_export__ = prefix;
__webpack_unused_export__ = iconName;
__webpack_unused_export__ = width;
__webpack_unused_export__ = height;
__webpack_unused_export__ = ligatures;
__webpack_unused_export__ = unicode;
__webpack_unused_export__ = svgPathData;

/***/ }),

/***/ 888:
/***/ ((__unused_webpack_module, exports) => {

var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'check';
var width = 512;
var height = 512;
var ligatures = [];
var unicode = 'f00c';
var svgPathData = 'M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z';

exports.mw = {
  prefix: prefix,
  iconName: iconName,
  icon: [
    width,
    height,
    ligatures,
    unicode,
    svgPathData
  ]};

exports.e6 = exports.mw;
__webpack_unused_export__ = prefix;
__webpack_unused_export__ = iconName;
__webpack_unused_export__ = width;
__webpack_unused_export__ = height;
__webpack_unused_export__ = ligatures;
__webpack_unused_export__ = unicode;
__webpack_unused_export__ = svgPathData;

/***/ }),

/***/ 174:
/***/ ((__unused_webpack_module, exports) => {

var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'edit';
var width = 576;
var height = 512;
var ligatures = [];
var unicode = 'f044';
var svgPathData = 'M402.6 83.2l90.2 90.2c3.8 3.8 3.8 10 0 13.8L274.4 405.6l-92.8 10.3c-12.4 1.4-22.9-9.1-21.5-21.5l10.3-92.8L388.8 83.2c3.8-3.8 10-3.8 13.8 0zm162-22.9l-48.8-48.8c-15.2-15.2-39.9-15.2-55.2 0l-35.4 35.4c-3.8 3.8-3.8 10 0 13.8l90.2 90.2c3.8 3.8 10 3.8 13.8 0l35.4-35.4c15.2-15.3 15.2-40 0-55.2zM384 346.2V448H64V128h229.8c3.2 0 6.2-1.3 8.5-3.5l40-40c7.6-7.6 2.2-20.5-8.5-20.5H48C21.5 64 0 85.5 0 112v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V306.2c0-10.7-12.9-16-20.5-8.5l-40 40c-2.2 2.3-3.5 5.3-3.5 8.5z';

exports.mw = {
  prefix: prefix,
  iconName: iconName,
  icon: [
    width,
    height,
    ligatures,
    unicode,
    svgPathData
  ]};

exports.MT = exports.mw;
__webpack_unused_export__ = prefix;
__webpack_unused_export__ = iconName;
__webpack_unused_export__ = width;
__webpack_unused_export__ = height;
__webpack_unused_export__ = ligatures;
__webpack_unused_export__ = unicode;
__webpack_unused_export__ = svgPathData;

/***/ }),

/***/ 705:
/***/ ((__unused_webpack_module, exports) => {

var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'image';
var width = 512;
var height = 512;
var ligatures = [];
var unicode = 'f03e';
var svgPathData = 'M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48zM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56zM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48z';

exports.mw = {
  prefix: prefix,
  iconName: iconName,
  icon: [
    width,
    height,
    ligatures,
    unicode,
    svgPathData
  ]};

exports.jb = exports.mw;
__webpack_unused_export__ = prefix;
__webpack_unused_export__ = iconName;
__webpack_unused_export__ = width;
__webpack_unused_export__ = height;
__webpack_unused_export__ = ligatures;
__webpack_unused_export__ = unicode;
__webpack_unused_export__ = svgPathData;

/***/ }),

/***/ 718:
/***/ ((__unused_webpack_module, exports) => {

var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'layer-group';
var width = 512;
var height = 512;
var ligatures = [];
var unicode = 'f5fd';
var svgPathData = 'M12.41 148.02l232.94 105.67c6.8 3.09 14.49 3.09 21.29 0l232.94-105.67c16.55-7.51 16.55-32.52 0-40.03L266.65 2.31a25.607 25.607 0 0 0-21.29 0L12.41 107.98c-16.55 7.51-16.55 32.53 0 40.04zm487.18 88.28l-58.09-26.33-161.64 73.27c-7.56 3.43-15.59 5.17-23.86 5.17s-16.29-1.74-23.86-5.17L70.51 209.97l-58.1 26.33c-16.55 7.5-16.55 32.5 0 40l232.94 105.59c6.8 3.08 14.49 3.08 21.29 0L499.59 276.3c16.55-7.5 16.55-32.5 0-40zm0 127.8l-57.87-26.23-161.86 73.37c-7.56 3.43-15.59 5.17-23.86 5.17s-16.29-1.74-23.86-5.17L70.29 337.87 12.41 364.1c-16.55 7.5-16.55 32.5 0 40l232.94 105.59c6.8 3.08 14.49 3.08 21.29 0L499.59 404.1c16.55-7.5 16.55-32.5 0-40z';

exports.mw = {
  prefix: prefix,
  iconName: iconName,
  icon: [
    width,
    height,
    ligatures,
    unicode,
    svgPathData
  ]};

exports.qI = exports.mw;
__webpack_unused_export__ = prefix;
__webpack_unused_export__ = iconName;
__webpack_unused_export__ = width;
__webpack_unused_export__ = height;
__webpack_unused_export__ = ligatures;
__webpack_unused_export__ = unicode;
__webpack_unused_export__ = svgPathData;

/***/ }),

/***/ 801:
/***/ ((__unused_webpack_module, exports) => {

var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'list-ol';
var width = 512;
var height = 512;
var ligatures = [];
var unicode = 'f0cb';
var svgPathData = 'M61.77 401l17.5-20.15a19.92 19.92 0 0 0 5.07-14.19v-3.31C84.34 356 80.5 352 73 352H16a8 8 0 0 0-8 8v16a8 8 0 0 0 8 8h22.83a157.41 157.41 0 0 0-11 12.31l-5.61 7c-4 5.07-5.25 10.13-2.8 14.88l1.05 1.93c3 5.76 6.29 7.88 12.25 7.88h4.73c10.33 0 15.94 2.44 15.94 9.09 0 4.72-4.2 8.22-14.36 8.22a41.54 41.54 0 0 1-15.47-3.12c-6.49-3.88-11.74-3.5-15.6 3.12l-5.59 9.31c-3.72 6.13-3.19 11.72 2.63 15.94 7.71 4.69 20.38 9.44 37 9.44 34.16 0 48.5-22.75 48.5-44.12-.03-14.38-9.12-29.76-28.73-34.88zM496 224H176a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h320a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zm0-160H176a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h320a16 16 0 0 0 16-16V80a16 16 0 0 0-16-16zm0 320H176a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h320a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zM16 160h64a8 8 0 0 0 8-8v-16a8 8 0 0 0-8-8H64V40a8 8 0 0 0-8-8H32a8 8 0 0 0-7.14 4.42l-8 16A8 8 0 0 0 24 64h8v64H16a8 8 0 0 0-8 8v16a8 8 0 0 0 8 8zm-3.91 160H80a8 8 0 0 0 8-8v-16a8 8 0 0 0-8-8H41.32c3.29-10.29 48.34-18.68 48.34-56.44 0-29.06-25-39.56-44.47-39.56-21.36 0-33.8 10-40.46 18.75-4.37 5.59-3 10.84 2.8 15.37l8.58 6.88c5.61 4.56 11 2.47 16.12-2.44a13.44 13.44 0 0 1 9.46-3.84c3.33 0 9.28 1.56 9.28 8.75C51 248.19 0 257.31 0 304.59v4C0 316 5.08 320 12.09 320z';

exports.mw = {
  prefix: prefix,
  iconName: iconName,
  icon: [
    width,
    height,
    ligatures,
    unicode,
    svgPathData
  ]};

exports.Ts = exports.mw;
__webpack_unused_export__ = prefix;
__webpack_unused_export__ = iconName;
__webpack_unused_export__ = width;
__webpack_unused_export__ = height;
__webpack_unused_export__ = ligatures;
__webpack_unused_export__ = unicode;
__webpack_unused_export__ = svgPathData;

/***/ }),

/***/ 430:
/***/ ((__unused_webpack_module, exports) => {

var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'question-circle';
var width = 512;
var height = 512;
var ligatures = [];
var unicode = 'f059';
var svgPathData = 'M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zM262.655 90c-54.497 0-89.255 22.957-116.549 63.758-3.536 5.286-2.353 12.415 2.715 16.258l34.699 26.31c5.205 3.947 12.621 3.008 16.665-2.122 17.864-22.658 30.113-35.797 57.303-35.797 20.429 0 45.698 13.148 45.698 32.958 0 14.976-12.363 22.667-32.534 33.976C247.128 238.528 216 254.941 216 296v4c0 6.627 5.373 12 12 12h56c6.627 0 12-5.373 12-12v-1.333c0-28.462 83.186-29.647 83.186-106.667 0-58.002-60.165-102-116.531-102zM256 338c-25.365 0-46 20.635-46 46 0 25.364 20.635 46 46 46s46-20.636 46-46c0-25.365-20.635-46-46-46z';

exports.mw = {
  prefix: prefix,
  iconName: iconName,
  icon: [
    width,
    height,
    ligatures,
    unicode,
    svgPathData
  ]};

exports.wR = exports.mw;
__webpack_unused_export__ = prefix;
__webpack_unused_export__ = iconName;
__webpack_unused_export__ = width;
__webpack_unused_export__ = height;
__webpack_unused_export__ = ligatures;
__webpack_unused_export__ = unicode;
__webpack_unused_export__ = svgPathData;

/***/ }),

/***/ 184:
/***/ ((__unused_webpack_module, exports) => {

var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'table';
var width = 512;
var height = 512;
var ligatures = [];
var unicode = 'f0ce';
var svgPathData = 'M464 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48 48 48h416c26.51 0 48-21.49 48-48V80c0-26.51-21.49-48-48-48zM224 416H64v-96h160v96zm0-160H64v-96h160v96zm224 160H288v-96h160v96zm0-160H288v-96h160v96z';

exports.mw = {
  prefix: prefix,
  iconName: iconName,
  icon: [
    width,
    height,
    ligatures,
    unicode,
    svgPathData
  ]};

exports.w9 = exports.mw;
__webpack_unused_export__ = prefix;
__webpack_unused_export__ = iconName;
__webpack_unused_export__ = width;
__webpack_unused_export__ = height;
__webpack_unused_export__ = ligatures;
__webpack_unused_export__ = unicode;
__webpack_unused_export__ = svgPathData;

/***/ }),

/***/ 882:
/***/ ((__unused_webpack_module, exports) => {

var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'times';
var width = 352;
var height = 512;
var ligatures = [];
var unicode = 'f00d';
var svgPathData = 'M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z';

exports.mw = {
  prefix: prefix,
  iconName: iconName,
  icon: [
    width,
    height,
    ligatures,
    unicode,
    svgPathData
  ]};

exports.GR = exports.mw;
__webpack_unused_export__ = prefix;
__webpack_unused_export__ = iconName;
__webpack_unused_export__ = width;
__webpack_unused_export__ = height;
__webpack_unused_export__ = ligatures;
__webpack_unused_export__ = unicode;
__webpack_unused_export__ = svgPathData;

/***/ }),

/***/ 792:
/***/ ((module) => {



// do not edit .js files directly - edit src/index.jst



module.exports = function equal(a, b) {
  if (a === b) return true;

  if (a && b && typeof a == 'object' && typeof b == 'object') {
    if (a.constructor !== b.constructor) return false;

    var length, i, keys;
    if (Array.isArray(a)) {
      length = a.length;
      if (length != b.length) return false;
      for (i = length; i-- !== 0;)
        if (!equal(a[i], b[i])) return false;
      return true;
    }



    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();

    keys = Object.keys(a);
    length = keys.length;
    if (length !== Object.keys(b).length) return false;

    for (i = length; i-- !== 0;)
      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;

    for (i = length; i-- !== 0;) {
      var key = keys[i];

      if (!equal(a[key], b[key])) return false;
    }

    return true;
  }

  // true if both NaN, false otherwise
  return a!==a && b!==b;
};


/***/ }),

/***/ 317:
/***/ (function(module) {

/*!
 * html2canvas 1.4.1 <https://html2canvas.hertzen.com>
 * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
 * Released under MIT License
 */
(function (global, factory) {
     true ? module.exports = factory() :
    0;
}(this, (function () { 'use strict';

    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    /* global Reflect, Promise */

    var extendStatics = function(d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };

    function __extends(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }

    var __assign = function() {
        __assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
            }
            return t;
        };
        return __assign.apply(this, arguments);
    };

    function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }

    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (_) try {
                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                if (y = 0, t) op = [op[0] & 2, t.value];
                switch (op[0]) {
                    case 0: case 1: t = op; break;
                    case 4: _.label++; return { value: op[1], done: false };
                    case 5: _.label++; y = op[1]; op = [0]; continue;
                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
                    default:
                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                        if (t[2]) _.ops.pop();
                        _.trys.pop(); continue;
                }
                op = body.call(thisArg, _);
            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
        }
    }

    function __spreadArray(to, from, pack) {
        if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
            if (ar || !(i in from)) {
                if (!ar) ar = Array.prototype.slice.call(from, 0, i);
                ar[i] = from[i];
            }
        }
        return to.concat(ar || from);
    }

    var Bounds = /** @class */ (function () {
        function Bounds(left, top, width, height) {
            this.left = left;
            this.top = top;
            this.width = width;
            this.height = height;
        }
        Bounds.prototype.add = function (x, y, w, h) {
            return new Bounds(this.left + x, this.top + y, this.width + w, this.height + h);
        };
        Bounds.fromClientRect = function (context, clientRect) {
            return new Bounds(clientRect.left + context.windowBounds.left, clientRect.top + context.windowBounds.top, clientRect.width, clientRect.height);
        };
        Bounds.fromDOMRectList = function (context, domRectList) {
            var domRect = Array.from(domRectList).find(function (rect) { return rect.width !== 0; });
            return domRect
                ? new Bounds(domRect.left + context.windowBounds.left, domRect.top + context.windowBounds.top, domRect.width, domRect.height)
                : Bounds.EMPTY;
        };
        Bounds.EMPTY = new Bounds(0, 0, 0, 0);
        return Bounds;
    }());
    var parseBounds = function (context, node) {
        return Bounds.fromClientRect(context, node.getBoundingClientRect());
    };
    var parseDocumentSize = function (document) {
        var body = document.body;
        var documentElement = document.documentElement;
        if (!body || !documentElement) {
            throw new Error("Unable to get document size");
        }
        var width = Math.max(Math.max(body.scrollWidth, documentElement.scrollWidth), Math.max(body.offsetWidth, documentElement.offsetWidth), Math.max(body.clientWidth, documentElement.clientWidth));
        var height = Math.max(Math.max(body.scrollHeight, documentElement.scrollHeight), Math.max(body.offsetHeight, documentElement.offsetHeight), Math.max(body.clientHeight, documentElement.clientHeight));
        return new Bounds(0, 0, width, height);
    };

    /*
     * css-line-break 2.1.0 <https://github.com/niklasvh/css-line-break#readme>
     * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
     * Released under MIT License
     */
    var toCodePoints$1 = function (str) {
        var codePoints = [];
        var i = 0;
        var length = str.length;
        while (i < length) {
            var value = str.charCodeAt(i++);
            if (value >= 0xd800 && value <= 0xdbff && i < length) {
                var extra = str.charCodeAt(i++);
                if ((extra & 0xfc00) === 0xdc00) {
                    codePoints.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
                }
                else {
                    codePoints.push(value);
                    i--;
                }
            }
            else {
                codePoints.push(value);
            }
        }
        return codePoints;
    };
    var fromCodePoint$1 = function () {
        var codePoints = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            codePoints[_i] = arguments[_i];
        }
        if (String.fromCodePoint) {
            return String.fromCodePoint.apply(String, codePoints);
        }
        var length = codePoints.length;
        if (!length) {
            return '';
        }
        var codeUnits = [];
        var index = -1;
        var result = '';
        while (++index < length) {
            var codePoint = codePoints[index];
            if (codePoint <= 0xffff) {
                codeUnits.push(codePoint);
            }
            else {
                codePoint -= 0x10000;
                codeUnits.push((codePoint >> 10) + 0xd800, (codePoint % 0x400) + 0xdc00);
            }
            if (index + 1 === length || codeUnits.length > 0x4000) {
                result += String.fromCharCode.apply(String, codeUnits);
                codeUnits.length = 0;
            }
        }
        return result;
    };
    var chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    // Use a lookup table to find the index.
    var lookup$2 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
    for (var i$2 = 0; i$2 < chars$2.length; i$2++) {
        lookup$2[chars$2.charCodeAt(i$2)] = i$2;
    }

    /*
     * utrie 1.0.2 <https://github.com/niklasvh/utrie>
     * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
     * Released under MIT License
     */
    var chars$1$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    // Use a lookup table to find the index.
    var lookup$1$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
    for (var i$1$1 = 0; i$1$1 < chars$1$1.length; i$1$1++) {
        lookup$1$1[chars$1$1.charCodeAt(i$1$1)] = i$1$1;
    }
    var decode$1 = function (base64) {
        var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
        if (base64[base64.length - 1] === '=') {
            bufferLength--;
            if (base64[base64.length - 2] === '=') {
                bufferLength--;
            }
        }
        var buffer = typeof ArrayBuffer !== 'undefined' &&
            typeof Uint8Array !== 'undefined' &&
            typeof Uint8Array.prototype.slice !== 'undefined'
            ? new ArrayBuffer(bufferLength)
            : new Array(bufferLength);
        var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer);
        for (i = 0; i < len; i += 4) {
            encoded1 = lookup$1$1[base64.charCodeAt(i)];
            encoded2 = lookup$1$1[base64.charCodeAt(i + 1)];
            encoded3 = lookup$1$1[base64.charCodeAt(i + 2)];
            encoded4 = lookup$1$1[base64.charCodeAt(i + 3)];
            bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
            bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
            bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
        }
        return buffer;
    };
    var polyUint16Array$1 = function (buffer) {
        var length = buffer.length;
        var bytes = [];
        for (var i = 0; i < length; i += 2) {
            bytes.push((buffer[i + 1] << 8) | buffer[i]);
        }
        return bytes;
    };
    var polyUint32Array$1 = function (buffer) {
        var length = buffer.length;
        var bytes = [];
        for (var i = 0; i < length; i += 4) {
            bytes.push((buffer[i + 3] << 24) | (buffer[i + 2] << 16) | (buffer[i + 1] << 8) | buffer[i]);
        }
        return bytes;
    };

    /** Shift size for getting the index-2 table offset. */
    var UTRIE2_SHIFT_2$1 = 5;
    /** Shift size for getting the index-1 table offset. */
    var UTRIE2_SHIFT_1$1 = 6 + 5;
    /**
     * Shift size for shifting left the index array values.
     * Increases possible data size with 16-bit index values at the cost
     * of compactability.
     * This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY.
     */
    var UTRIE2_INDEX_SHIFT$1 = 2;
    /**
     * Difference between the two shift sizes,
     * for getting an index-1 offset from an index-2 offset. 6=11-5
     */
    var UTRIE2_SHIFT_1_2$1 = UTRIE2_SHIFT_1$1 - UTRIE2_SHIFT_2$1;
    /**
     * The part of the index-2 table for U+D800..U+DBFF stores values for
     * lead surrogate code _units_ not code _points_.
     * Values for lead surrogate code _points_ are indexed with this portion of the table.
     * Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.)
     */
    var UTRIE2_LSCP_INDEX_2_OFFSET$1 = 0x10000 >> UTRIE2_SHIFT_2$1;
    /** Number of entries in a data block. 32=0x20 */
    var UTRIE2_DATA_BLOCK_LENGTH$1 = 1 << UTRIE2_SHIFT_2$1;
    /** Mask for getting the lower bits for the in-data-block offset. */
    var UTRIE2_DATA_MASK$1 = UTRIE2_DATA_BLOCK_LENGTH$1 - 1;
    var UTRIE2_LSCP_INDEX_2_LENGTH$1 = 0x400 >> UTRIE2_SHIFT_2$1;
    /** Count the lengths of both BMP pieces. 2080=0x820 */
    var UTRIE2_INDEX_2_BMP_LENGTH$1 = UTRIE2_LSCP_INDEX_2_OFFSET$1 + UTRIE2_LSCP_INDEX_2_LENGTH$1;
    /**
     * The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820.
     * Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2.
     */
    var UTRIE2_UTF8_2B_INDEX_2_OFFSET$1 = UTRIE2_INDEX_2_BMP_LENGTH$1;
    var UTRIE2_UTF8_2B_INDEX_2_LENGTH$1 = 0x800 >> 6; /* U+0800 is the first code point after 2-byte UTF-8 */
    /**
     * The index-1 table, only used for supplementary code points, at offset 2112=0x840.
     * Variable length, for code points up to highStart, where the last single-value range starts.
     * Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1.
     * (For 0x100000 supplementary code points U+10000..U+10ffff.)
     *
     * The part of the index-2 table for supplementary code points starts
     * after this index-1 table.
     *
     * Both the index-1 table and the following part of the index-2 table
     * are omitted completely if there is only BMP data.
     */
    var UTRIE2_INDEX_1_OFFSET$1 = UTRIE2_UTF8_2B_INDEX_2_OFFSET$1 + UTRIE2_UTF8_2B_INDEX_2_LENGTH$1;
    /**
     * Number of index-1 entries for the BMP. 32=0x20
     * This part of the index-1 table is omitted from the serialized form.
     */
    var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH$1 = 0x10000 >> UTRIE2_SHIFT_1$1;
    /** Number of entries in an index-2 block. 64=0x40 */
    var UTRIE2_INDEX_2_BLOCK_LENGTH$1 = 1 << UTRIE2_SHIFT_1_2$1;
    /** Mask for getting the lower bits for the in-index-2-block offset. */
    var UTRIE2_INDEX_2_MASK$1 = UTRIE2_INDEX_2_BLOCK_LENGTH$1 - 1;
    var slice16$1 = function (view, start, end) {
        if (view.slice) {
            return view.slice(start, end);
        }
        return new Uint16Array(Array.prototype.slice.call(view, start, end));
    };
    var slice32$1 = function (view, start, end) {
        if (view.slice) {
            return view.slice(start, end);
        }
        return new Uint32Array(Array.prototype.slice.call(view, start, end));
    };
    var createTrieFromBase64$1 = function (base64, _byteLength) {
        var buffer = decode$1(base64);
        var view32 = Array.isArray(buffer) ? polyUint32Array$1(buffer) : new Uint32Array(buffer);
        var view16 = Array.isArray(buffer) ? polyUint16Array$1(buffer) : new Uint16Array(buffer);
        var headerLength = 24;
        var index = slice16$1(view16, headerLength / 2, view32[4] / 2);
        var data = view32[5] === 2
            ? slice16$1(view16, (headerLength + view32[4]) / 2)
            : slice32$1(view32, Math.ceil((headerLength + view32[4]) / 4));
        return new Trie$1(view32[0], view32[1], view32[2], view32[3], index, data);
    };
    var Trie$1 = /** @class */ (function () {
        function Trie(initialValue, errorValue, highStart, highValueIndex, index, data) {
            this.initialValue = initialValue;
            this.errorValue = errorValue;
            this.highStart = highStart;
            this.highValueIndex = highValueIndex;
            this.index = index;
            this.data = data;
        }
        /**
         * Get the value for a code point as stored in the Trie.
         *
         * @param codePoint the code point
         * @return the value
         */
        Trie.prototype.get = function (codePoint) {
            var ix;
            if (codePoint >= 0) {
                if (codePoint < 0x0d800 || (codePoint > 0x0dbff && codePoint <= 0x0ffff)) {
                    // Ordinary BMP code point, excluding leading surrogates.
                    // BMP uses a single level lookup.  BMP index starts at offset 0 in the Trie2 index.
                    // 16 bit data is stored in the index array itself.
                    ix = this.index[codePoint >> UTRIE2_SHIFT_2$1];
                    ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
                    return this.data[ix];
                }
                if (codePoint <= 0xffff) {
                    // Lead Surrogate Code Point.  A Separate index section is stored for
                    // lead surrogate code units and code points.
                    //   The main index has the code unit data.
                    //   For this function, we need the code point data.
                    // Note: this expression could be refactored for slightly improved efficiency, but
                    //       surrogate code points will be so rare in practice that it's not worth it.
                    ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET$1 + ((codePoint - 0xd800) >> UTRIE2_SHIFT_2$1)];
                    ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
                    return this.data[ix];
                }
                if (codePoint < this.highStart) {
                    // Supplemental code point, use two-level lookup.
                    ix = UTRIE2_INDEX_1_OFFSET$1 - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH$1 + (codePoint >> UTRIE2_SHIFT_1$1);
                    ix = this.index[ix];
                    ix += (codePoint >> UTRIE2_SHIFT_2$1) & UTRIE2_INDEX_2_MASK$1;
                    ix = this.index[ix];
                    ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
                    return this.data[ix];
                }
                if (codePoint <= 0x10ffff) {
                    return this.data[this.highValueIndex];
                }
            }
            // Fall through.  The code point is outside of the legal range of 0..0x10ffff.
            return this.errorValue;
        };
        return Trie;
    }());

    /*
     * base64-arraybuffer 1.0.2 <https://github.com/niklasvh/base64-arraybuffer>
     * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
     * Released under MIT License
     */
    var chars$3 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    // Use a lookup table to find the index.
    var lookup$3 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
    for (var i$3 = 0; i$3 < chars$3.length; i$3++) {
        lookup$3[chars$3.charCodeAt(i$3)] = i$3;
    }

    var base64$1 = ' ';

    var LETTER_NUMBER_MODIFIER = 50;
    // Non-tailorable Line Breaking Classes
    var BK = 1; //  Cause a line break (after)
    var CR$1 = 2; //  Cause a line break (after), except between CR and LF
    var LF$1 = 3; //  Cause a line break (after)
    var CM = 4; //  Prohibit a line break between the character and the preceding character
    var NL = 5; //  Cause a line break (after)
    var WJ = 7; //  Prohibit line breaks before and after
    var ZW = 8; //  Provide a break opportunity
    var GL = 9; //  Prohibit line breaks before and after
    var SP = 10; // Enable indirect line breaks
    var ZWJ$1 = 11; // Prohibit line breaks within joiner sequences
    // Break Opportunities
    var B2 = 12; //  Provide a line break opportunity before and after the character
    var BA = 13; //  Generally provide a line break opportunity after the character
    var BB = 14; //  Generally provide a line break opportunity before the character
    var HY = 15; //  Provide a line break opportunity after the character, except in numeric context
    var CB = 16; //   Provide a line break opportunity contingent on additional information
    // Characters Prohibiting Certain Breaks
    var CL = 17; //  Prohibit line breaks before
    var CP = 18; //  Prohibit line breaks before
    var EX = 19; //  Prohibit line breaks before
    var IN = 20; //  Allow only indirect line breaks between pairs
    var NS = 21; //  Allow only indirect line breaks before
    var OP = 22; //  Prohibit line breaks after
    var QU = 23; //  Act like they are both opening and closing
    // Numeric Context
    var IS = 24; //  Prevent breaks after any and before numeric
    var NU = 25; //  Form numeric expressions for line breaking purposes
    var PO = 26; //  Do not break following a numeric expression
    var PR = 27; //  Do not break in front of a numeric expression
    var SY = 28; //  Prevent a break before; and allow a break after
    // Other Characters
    var AI = 29; //  Act like AL when the resolvedEAW is N; otherwise; act as ID
    var AL = 30; //  Are alphabetic characters or symbols that are used with alphabetic characters
    var CJ = 31; //  Treat as NS or ID for strict or normal breaking.
    var EB = 32; //  Do not break from following Emoji Modifier
    var EM = 33; //  Do not break from preceding Emoji Base
    var H2 = 34; //  Form Korean syllable blocks
    var H3 = 35; //  Form Korean syllable blocks
    var HL = 36; //  Do not break around a following hyphen; otherwise act as Alphabetic
    var ID = 37; //  Break before or after; except in some numeric context
    var JL = 38; //  Form Korean syllable blocks
    var JV = 39; //  Form Korean syllable blocks
    var JT = 40; //  Form Korean syllable blocks
    var RI$1 = 41; //  Keep pairs together. For pairs; break before and after other classes
    var SA = 42; //  Provide a line break opportunity contingent on additional, language-specific context analysis
    var XX = 43; //  Have as yet unknown line breaking behavior or unassigned code positions
    var ea_OP = [0x2329, 0xff08];
    var BREAK_MANDATORY = '!';
    var BREAK_NOT_ALLOWED$1 = '×';
    var BREAK_ALLOWED$1 = '÷';
    var UnicodeTrie$1 = createTrieFromBase64$1(base64$1);
    var ALPHABETICS = [AL, HL];
    var HARD_LINE_BREAKS = [BK, CR$1, LF$1, NL];
    var SPACE$1 = [SP, ZW];
    var PREFIX_POSTFIX = [PR, PO];
    var LINE_BREAKS = HARD_LINE_BREAKS.concat(SPACE$1);
    var KOREAN_SYLLABLE_BLOCK = [JL, JV, JT, H2, H3];
    var HYPHEN = [HY, BA];
    var codePointsToCharacterClasses = function (codePoints, lineBreak) {
        if (lineBreak === void 0) { lineBreak = 'strict'; }
        var types = [];
        var indices = [];
        var categories = [];
        codePoints.forEach(function (codePoint, index) {
            var classType = UnicodeTrie$1.get(codePoint);
            if (classType > LETTER_NUMBER_MODIFIER) {
                categories.push(true);
                classType -= LETTER_NUMBER_MODIFIER;
            }
            else {
                categories.push(false);
            }
            if (['normal', 'auto', 'loose'].indexOf(lineBreak) !== -1) {
                // U+2010, – U+2013, 〜 U+301C, ゠ U+30A0
                if ([0x2010, 0x2013, 0x301c, 0x30a0].indexOf(codePoint) !== -1) {
                    indices.push(index);
                    return types.push(CB);
                }
            }
            if (classType === CM || classType === ZWJ$1) {
                // LB10 Treat any remaining combining mark or ZWJ as AL.
                if (index === 0) {
                    indices.push(index);
                    return types.push(AL);
                }
                // LB9 Do not break a combining character sequence; treat it as if it has the line breaking class of
                // the base character in all of the following rules. Treat ZWJ as if it were CM.
                var prev = types[index - 1];
                if (LINE_BREAKS.indexOf(prev) === -1) {
                    indices.push(indices[index - 1]);
                    return types.push(prev);
                }
                indices.push(index);
                return types.push(AL);
            }
            indices.push(index);
            if (classType === CJ) {
                return types.push(lineBreak === 'strict' ? NS : ID);
            }
            if (classType === SA) {
                return types.push(AL);
            }
            if (classType === AI) {
                return types.push(AL);
            }
            // For supplementary characters, a useful default is to treat characters in the range 10000..1FFFD as AL
            // and characters in the ranges 20000..2FFFD and 30000..3FFFD as ID, until the implementation can be revised
            // to take into account the actual line breaking properties for these characters.
            if (classType === XX) {
                if ((codePoint >= 0x20000 && codePoint <= 0x2fffd) || (codePoint >= 0x30000 && codePoint <= 0x3fffd)) {
                    return types.push(ID);
                }
                else {
                    return types.push(AL);
                }
            }
            types.push(classType);
        });
        return [indices, types, categories];
    };
    var isAdjacentWithSpaceIgnored = function (a, b, currentIndex, classTypes) {
        var current = classTypes[currentIndex];
        if (Array.isArray(a) ? a.indexOf(current) !== -1 : a === current) {
            var i = currentIndex;
            while (i <= classTypes.length) {
                i++;
                var next = classTypes[i];
                if (next === b) {
                    return true;
                }
                if (next !== SP) {
                    break;
                }
            }
        }
        if (current === SP) {
            var i = currentIndex;
            while (i > 0) {
                i--;
                var prev = classTypes[i];
                if (Array.isArray(a) ? a.indexOf(prev) !== -1 : a === prev) {
                    var n = currentIndex;
                    while (n <= classTypes.length) {
                        n++;
                        var next = classTypes[n];
                        if (next === b) {
                            return true;
                        }
                        if (next !== SP) {
                            break;
                        }
                    }
                }
                if (prev !== SP) {
                    break;
                }
            }
        }
        return false;
    };
    var previousNonSpaceClassType = function (currentIndex, classTypes) {
        var i = currentIndex;
        while (i >= 0) {
            var type = classTypes[i];
            if (type === SP) {
                i--;
            }
            else {
                return type;
            }
        }
        return 0;
    };
    var _lineBreakAtIndex = function (codePoints, classTypes, indicies, index, forbiddenBreaks) {
        if (indicies[index] === 0) {
            return BREAK_NOT_ALLOWED$1;
        }
        var currentIndex = index - 1;
        if (Array.isArray(forbiddenBreaks) && forbiddenBreaks[currentIndex] === true) {
            return BREAK_NOT_ALLOWED$1;
        }
        var beforeIndex = currentIndex - 1;
        var afterIndex = currentIndex + 1;
        var current = classTypes[currentIndex];
        // LB4 Always break after hard line breaks.
        // LB5 Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks.
        var before = beforeIndex >= 0 ? classTypes[beforeIndex] : 0;
        var next = classTypes[afterIndex];
        if (current === CR$1 && next === LF$1) {
            return BREAK_NOT_ALLOWED$1;
        }
        if (HARD_LINE_BREAKS.indexOf(current) !== -1) {
            return BREAK_MANDATORY;
        }
        // LB6 Do not break before hard line breaks.
        if (HARD_LINE_BREAKS.indexOf(next) !== -1) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB7 Do not break before spaces or zero width space.
        if (SPACE$1.indexOf(next) !== -1) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB8 Break before any character following a zero-width space, even if one or more spaces intervene.
        if (previousNonSpaceClassType(currentIndex, classTypes) === ZW) {
            return BREAK_ALLOWED$1;
        }
        // LB8a Do not break after a zero width joiner.
        if (UnicodeTrie$1.get(codePoints[currentIndex]) === ZWJ$1) {
            return BREAK_NOT_ALLOWED$1;
        }
        // zwj emojis
        if ((current === EB || current === EM) && UnicodeTrie$1.get(codePoints[afterIndex]) === ZWJ$1) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB11 Do not break before or after Word joiner and related characters.
        if (current === WJ || next === WJ) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB12 Do not break after NBSP and related characters.
        if (current === GL) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB12a Do not break before NBSP and related characters, except after spaces and hyphens.
        if ([SP, BA, HY].indexOf(current) === -1 && next === GL) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB13 Do not break before ‘]’ or ‘!’ or ‘;’ or ‘/’, even after spaces.
        if ([CL, CP, EX, IS, SY].indexOf(next) !== -1) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB14 Do not break after ‘[’, even after spaces.
        if (previousNonSpaceClassType(currentIndex, classTypes) === OP) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB15 Do not break within ‘”[’, even with intervening spaces.
        if (isAdjacentWithSpaceIgnored(QU, OP, currentIndex, classTypes)) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB16 Do not break between closing punctuation and a nonstarter (lb=NS), even with intervening spaces.
        if (isAdjacentWithSpaceIgnored([CL, CP], NS, currentIndex, classTypes)) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB17 Do not break within ‘——’, even with intervening spaces.
        if (isAdjacentWithSpaceIgnored(B2, B2, currentIndex, classTypes)) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB18 Break after spaces.
        if (current === SP) {
            return BREAK_ALLOWED$1;
        }
        // LB19 Do not break before or after quotation marks, such as ‘ ” ’.
        if (current === QU || next === QU) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB20 Break before and after unresolved CB.
        if (next === CB || current === CB) {
            return BREAK_ALLOWED$1;
        }
        // LB21 Do not break before hyphen-minus, other hyphens, fixed-width spaces, small kana, and other non-starters, or after acute accents.
        if ([BA, HY, NS].indexOf(next) !== -1 || current === BB) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB21a Don't break after Hebrew + Hyphen.
        if (before === HL && HYPHEN.indexOf(current) !== -1) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB21b Don’t break between Solidus and Hebrew letters.
        if (current === SY && next === HL) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB22 Do not break before ellipsis.
        if (next === IN) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB23 Do not break between digits and letters.
        if ((ALPHABETICS.indexOf(next) !== -1 && current === NU) || (ALPHABETICS.indexOf(current) !== -1 && next === NU)) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB23a Do not break between numeric prefixes and ideographs, or between ideographs and numeric postfixes.
        if ((current === PR && [ID, EB, EM].indexOf(next) !== -1) ||
            ([ID, EB, EM].indexOf(current) !== -1 && next === PO)) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB24 Do not break between numeric prefix/postfix and letters, or between letters and prefix/postfix.
        if ((ALPHABETICS.indexOf(current) !== -1 && PREFIX_POSTFIX.indexOf(next) !== -1) ||
            (PREFIX_POSTFIX.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1)) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB25 Do not break between the following pairs of classes relevant to numbers:
        if (
        // (PR | PO) × ( OP | HY )? NU
        ([PR, PO].indexOf(current) !== -1 &&
            (next === NU || ([OP, HY].indexOf(next) !== -1 && classTypes[afterIndex + 1] === NU))) ||
            // ( OP | HY ) × NU
            ([OP, HY].indexOf(current) !== -1 && next === NU) ||
            // NU ×	(NU | SY | IS)
            (current === NU && [NU, SY, IS].indexOf(next) !== -1)) {
            return BREAK_NOT_ALLOWED$1;
        }
        // NU (NU | SY | IS)* × (NU | SY | IS | CL | CP)
        if ([NU, SY, IS, CL, CP].indexOf(next) !== -1) {
            var prevIndex = currentIndex;
            while (prevIndex >= 0) {
                var type = classTypes[prevIndex];
                if (type === NU) {
                    return BREAK_NOT_ALLOWED$1;
                }
                else if ([SY, IS].indexOf(type) !== -1) {
                    prevIndex--;
                }
                else {
                    break;
                }
            }
        }
        // NU (NU | SY | IS)* (CL | CP)? × (PO | PR))
        if ([PR, PO].indexOf(next) !== -1) {
            var prevIndex = [CL, CP].indexOf(current) !== -1 ? beforeIndex : currentIndex;
            while (prevIndex >= 0) {
                var type = classTypes[prevIndex];
                if (type === NU) {
                    return BREAK_NOT_ALLOWED$1;
                }
                else if ([SY, IS].indexOf(type) !== -1) {
                    prevIndex--;
                }
                else {
                    break;
                }
            }
        }
        // LB26 Do not break a Korean syllable.
        if ((JL === current && [JL, JV, H2, H3].indexOf(next) !== -1) ||
            ([JV, H2].indexOf(current) !== -1 && [JV, JT].indexOf(next) !== -1) ||
            ([JT, H3].indexOf(current) !== -1 && next === JT)) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB27 Treat a Korean Syllable Block the same as ID.
        if ((KOREAN_SYLLABLE_BLOCK.indexOf(current) !== -1 && [IN, PO].indexOf(next) !== -1) ||
            (KOREAN_SYLLABLE_BLOCK.indexOf(next) !== -1 && current === PR)) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB28 Do not break between alphabetics (“at”).
        if (ALPHABETICS.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB29 Do not break between numeric punctuation and alphabetics (“e.g.”).
        if (current === IS && ALPHABETICS.indexOf(next) !== -1) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB30 Do not break between letters, numbers, or ordinary symbols and opening or closing parentheses.
        if ((ALPHABETICS.concat(NU).indexOf(current) !== -1 &&
            next === OP &&
            ea_OP.indexOf(codePoints[afterIndex]) === -1) ||
            (ALPHABETICS.concat(NU).indexOf(next) !== -1 && current === CP)) {
            return BREAK_NOT_ALLOWED$1;
        }
        // LB30a Break between two regional indicator symbols if and only if there are an even number of regional
        // indicators preceding the position of the break.
        if (current === RI$1 && next === RI$1) {
            var i = indicies[currentIndex];
            var count = 1;
            while (i > 0) {
                i--;
                if (classTypes[i] === RI$1) {
                    count++;
                }
                else {
                    break;
                }
            }
            if (count % 2 !== 0) {
                return BREAK_NOT_ALLOWED$1;
            }
        }
        // LB30b Do not break between an emoji base and an emoji modifier.
        if (current === EB && next === EM) {
            return BREAK_NOT_ALLOWED$1;
        }
        return BREAK_ALLOWED$1;
    };
    var cssFormattedClasses = function (codePoints, options) {
        if (!options) {
            options = { lineBreak: 'normal', wordBreak: 'normal' };
        }
        var _a = codePointsToCharacterClasses(codePoints, options.lineBreak), indicies = _a[0], classTypes = _a[1], isLetterNumber = _a[2];
        if (options.wordBreak === 'break-all' || options.wordBreak === 'break-word') {
            classTypes = classTypes.map(function (type) { return ([NU, AL, SA].indexOf(type) !== -1 ? ID : type); });
        }
        var forbiddenBreakpoints = options.wordBreak === 'keep-all'
            ? isLetterNumber.map(function (letterNumber, i) {
                return letterNumber && codePoints[i] >= 0x4e00 && codePoints[i] <= 0x9fff;
            })
            : undefined;
        return [indicies, classTypes, forbiddenBreakpoints];
    };
    var Break = /** @class */ (function () {
        function Break(codePoints, lineBreak, start, end) {
            this.codePoints = codePoints;
            this.required = lineBreak === BREAK_MANDATORY;
            this.start = start;
            this.end = end;
        }
        Break.prototype.slice = function () {
            return fromCodePoint$1.apply(void 0, this.codePoints.slice(this.start, this.end));
        };
        return Break;
    }());
    var LineBreaker = function (str, options) {
        var codePoints = toCodePoints$1(str);
        var _a = cssFormattedClasses(codePoints, options), indicies = _a[0], classTypes = _a[1], forbiddenBreakpoints = _a[2];
        var length = codePoints.length;
        var lastEnd = 0;
        var nextIndex = 0;
        return {
            next: function () {
                if (nextIndex >= length) {
                    return { done: true, value: null };
                }
                var lineBreak = BREAK_NOT_ALLOWED$1;
                while (nextIndex < length &&
                    (lineBreak = _lineBreakAtIndex(codePoints, classTypes, indicies, ++nextIndex, forbiddenBreakpoints)) ===
                        BREAK_NOT_ALLOWED$1) { }
                if (lineBreak !== BREAK_NOT_ALLOWED$1 || nextIndex === length) {
                    var value = new Break(codePoints, lineBreak, lastEnd, nextIndex);
                    lastEnd = nextIndex;
                    return { value: value, done: false };
                }
                return { done: true, value: null };
            },
        };
    };

    // https://www.w3.org/TR/css-syntax-3
    var FLAG_UNRESTRICTED = 1 << 0;
    var FLAG_ID = 1 << 1;
    var FLAG_INTEGER = 1 << 2;
    var FLAG_NUMBER = 1 << 3;
    var LINE_FEED = 0x000a;
    var SOLIDUS = 0x002f;
    var REVERSE_SOLIDUS = 0x005c;
    var CHARACTER_TABULATION = 0x0009;
    var SPACE = 0x0020;
    var QUOTATION_MARK = 0x0022;
    var EQUALS_SIGN = 0x003d;
    var NUMBER_SIGN = 0x0023;
    var DOLLAR_SIGN = 0x0024;
    var PERCENTAGE_SIGN = 0x0025;
    var APOSTROPHE = 0x0027;
    var LEFT_PARENTHESIS = 0x0028;
    var RIGHT_PARENTHESIS = 0x0029;
    var LOW_LINE = 0x005f;
    var HYPHEN_MINUS = 0x002d;
    var EXCLAMATION_MARK = 0x0021;
    var LESS_THAN_SIGN = 0x003c;
    var GREATER_THAN_SIGN = 0x003e;
    var COMMERCIAL_AT = 0x0040;
    var LEFT_SQUARE_BRACKET = 0x005b;
    var RIGHT_SQUARE_BRACKET = 0x005d;
    var CIRCUMFLEX_ACCENT = 0x003d;
    var LEFT_CURLY_BRACKET = 0x007b;
    var QUESTION_MARK = 0x003f;
    var RIGHT_CURLY_BRACKET = 0x007d;
    var VERTICAL_LINE = 0x007c;
    var TILDE = 0x007e;
    var CONTROL = 0x0080;
    var REPLACEMENT_CHARACTER = 0xfffd;
    var ASTERISK = 0x002a;
    var PLUS_SIGN = 0x002b;
    var COMMA = 0x002c;
    var COLON = 0x003a;
    var SEMICOLON = 0x003b;
    var FULL_STOP = 0x002e;
    var NULL = 0x0000;
    var BACKSPACE = 0x0008;
    var LINE_TABULATION = 0x000b;
    var SHIFT_OUT = 0x000e;
    var INFORMATION_SEPARATOR_ONE = 0x001f;
    var DELETE = 0x007f;
    var EOF = -1;
    var ZERO = 0x0030;
    var a = 0x0061;
    var e = 0x0065;
    var f = 0x0066;
    var u = 0x0075;
    var z = 0x007a;
    var A = 0x0041;
    var E = 0x0045;
    var F = 0x0046;
    var U = 0x0055;
    var Z = 0x005a;
    var isDigit = function (codePoint) { return codePoint >= ZERO && codePoint <= 0x0039; };
    var isSurrogateCodePoint = function (codePoint) { return codePoint >= 0xd800 && codePoint <= 0xdfff; };
    var isHex = function (codePoint) {
        return isDigit(codePoint) || (codePoint >= A && codePoint <= F) || (codePoint >= a && codePoint <= f);
    };
    var isLowerCaseLetter = function (codePoint) { return codePoint >= a && codePoint <= z; };
    var isUpperCaseLetter = function (codePoint) { return codePoint >= A && codePoint <= Z; };
    var isLetter = function (codePoint) { return isLowerCaseLetter(codePoint) || isUpperCaseLetter(codePoint); };
    var isNonASCIICodePoint = function (codePoint) { return codePoint >= CONTROL; };
    var isWhiteSpace = function (codePoint) {
        return codePoint === LINE_FEED || codePoint === CHARACTER_TABULATION || codePoint === SPACE;
    };
    var isNameStartCodePoint = function (codePoint) {
        return isLetter(codePoint) || isNonASCIICodePoint(codePoint) || codePoint === LOW_LINE;
    };
    var isNameCodePoint = function (codePoint) {
        return isNameStartCodePoint(codePoint) || isDigit(codePoint) || codePoint === HYPHEN_MINUS;
    };
    var isNonPrintableCodePoint = function (codePoint) {
        return ((codePoint >= NULL && codePoint <= BACKSPACE) ||
            codePoint === LINE_TABULATION ||
            (codePoint >= SHIFT_OUT && codePoint <= INFORMATION_SEPARATOR_ONE) ||
            codePoint === DELETE);
    };
    var isValidEscape = function (c1, c2) {
        if (c1 !== REVERSE_SOLIDUS) {
            return false;
        }
        return c2 !== LINE_FEED;
    };
    var isIdentifierStart = function (c1, c2, c3) {
        if (c1 === HYPHEN_MINUS) {
            return isNameStartCodePoint(c2) || isValidEscape(c2, c3);
        }
        else if (isNameStartCodePoint(c1)) {
            return true;
        }
        else if (c1 === REVERSE_SOLIDUS && isValidEscape(c1, c2)) {
            return true;
        }
        return false;
    };
    var isNumberStart = function (c1, c2, c3) {
        if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) {
            if (isDigit(c2)) {
                return true;
            }
            return c2 === FULL_STOP && isDigit(c3);
        }
        if (c1 === FULL_STOP) {
            return isDigit(c2);
        }
        return isDigit(c1);
    };
    var stringToNumber = function (codePoints) {
        var c = 0;
        var sign = 1;
        if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) {
            if (codePoints[c] === HYPHEN_MINUS) {
                sign = -1;
            }
            c++;
        }
        var integers = [];
        while (isDigit(codePoints[c])) {
            integers.push(codePoints[c++]);
        }
        var int = integers.length ? parseInt(fromCodePoint$1.apply(void 0, integers), 10) : 0;
        if (codePoints[c] === FULL_STOP) {
            c++;
        }
        var fraction = [];
        while (isDigit(codePoints[c])) {
            fraction.push(codePoints[c++]);
        }
        var fracd = fraction.length;
        var frac = fracd ? parseInt(fromCodePoint$1.apply(void 0, fraction), 10) : 0;
        if (codePoints[c] === E || codePoints[c] === e) {
            c++;
        }
        var expsign = 1;
        if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) {
            if (codePoints[c] === HYPHEN_MINUS) {
                expsign = -1;
            }
            c++;
        }
        var exponent = [];
        while (isDigit(codePoints[c])) {
            exponent.push(codePoints[c++]);
        }
        var exp = exponent.length ? parseInt(fromCodePoint$1.apply(void 0, exponent), 10) : 0;
        return sign * (int + frac * Math.pow(10, -fracd)) * Math.pow(10, expsign * exp);
    };
    var LEFT_PARENTHESIS_TOKEN = {
        type: 2 /* LEFT_PARENTHESIS_TOKEN */
    };
    var RIGHT_PARENTHESIS_TOKEN = {
        type: 3 /* RIGHT_PARENTHESIS_TOKEN */
    };
    var COMMA_TOKEN = { type: 4 /* COMMA_TOKEN */ };
    var SUFFIX_MATCH_TOKEN = { type: 13 /* SUFFIX_MATCH_TOKEN */ };
    var PREFIX_MATCH_TOKEN = { type: 8 /* PREFIX_MATCH_TOKEN */ };
    var COLUMN_TOKEN = { type: 21 /* COLUMN_TOKEN */ };
    var DASH_MATCH_TOKEN = { type: 9 /* DASH_MATCH_TOKEN */ };
    var INCLUDE_MATCH_TOKEN = { type: 10 /* INCLUDE_MATCH_TOKEN */ };
    var LEFT_CURLY_BRACKET_TOKEN = {
        type: 11 /* LEFT_CURLY_BRACKET_TOKEN */
    };
    var RIGHT_CURLY_BRACKET_TOKEN = {
        type: 12 /* RIGHT_CURLY_BRACKET_TOKEN */
    };
    var SUBSTRING_MATCH_TOKEN = { type: 14 /* SUBSTRING_MATCH_TOKEN */ };
    var BAD_URL_TOKEN = { type: 23 /* BAD_URL_TOKEN */ };
    var BAD_STRING_TOKEN = { type: 1 /* BAD_STRING_TOKEN */ };
    var CDO_TOKEN = { type: 25 /* CDO_TOKEN */ };
    var CDC_TOKEN = { type: 24 /* CDC_TOKEN */ };
    var COLON_TOKEN = { type: 26 /* COLON_TOKEN */ };
    var SEMICOLON_TOKEN = { type: 27 /* SEMICOLON_TOKEN */ };
    var LEFT_SQUARE_BRACKET_TOKEN = {
        type: 28 /* LEFT_SQUARE_BRACKET_TOKEN */
    };
    var RIGHT_SQUARE_BRACKET_TOKEN = {
        type: 29 /* RIGHT_SQUARE_BRACKET_TOKEN */
    };
    var WHITESPACE_TOKEN = { type: 31 /* WHITESPACE_TOKEN */ };
    var EOF_TOKEN = { type: 32 /* EOF_TOKEN */ };
    var Tokenizer = /** @class */ (function () {
        function Tokenizer() {
            this._value = [];
        }
        Tokenizer.prototype.write = function (chunk) {
            this._value = this._value.concat(toCodePoints$1(chunk));
        };
        Tokenizer.prototype.read = function () {
            var tokens = [];
            var token = this.consumeToken();
            while (token !== EOF_TOKEN) {
                tokens.push(token);
                token = this.consumeToken();
            }
            return tokens;
        };
        Tokenizer.prototype.consumeToken = function () {
            var codePoint = this.consumeCodePoint();
            switch (codePoint) {
                case QUOTATION_MARK:
                    return this.consumeStringToken(QUOTATION_MARK);
                case NUMBER_SIGN:
                    var c1 = this.peekCodePoint(0);
                    var c2 = this.peekCodePoint(1);
                    var c3 = this.peekCodePoint(2);
                    if (isNameCodePoint(c1) || isValidEscape(c2, c3)) {
                        var flags = isIdentifierStart(c1, c2, c3) ? FLAG_ID : FLAG_UNRESTRICTED;
                        var value = this.consumeName();
                        return { type: 5 /* HASH_TOKEN */, value: value, flags: flags };
                    }
                    break;
                case DOLLAR_SIGN:
                    if (this.peekCodePoint(0) === EQUALS_SIGN) {
                        this.consumeCodePoint();
                        return SUFFIX_MATCH_TOKEN;
                    }
                    break;
                case APOSTROPHE:
                    return this.consumeStringToken(APOSTROPHE);
                case LEFT_PARENTHESIS:
                    return LEFT_PARENTHESIS_TOKEN;
                case RIGHT_PARENTHESIS:
                    return RIGHT_PARENTHESIS_TOKEN;
                case ASTERISK:
                    if (this.peekCodePoint(0) === EQUALS_SIGN) {
                        this.consumeCodePoint();
                        return SUBSTRING_MATCH_TOKEN;
                    }
                    break;
                case PLUS_SIGN:
                    if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) {
                        this.reconsumeCodePoint(codePoint);
                        return this.consumeNumericToken();
                    }
                    break;
                case COMMA:
                    return COMMA_TOKEN;
                case HYPHEN_MINUS:
                    var e1 = codePoint;
                    var e2 = this.peekCodePoint(0);
                    var e3 = this.peekCodePoint(1);
                    if (isNumberStart(e1, e2, e3)) {
                        this.reconsumeCodePoint(codePoint);
                        return this.consumeNumericToken();
                    }
                    if (isIdentifierStart(e1, e2, e3)) {
                        this.reconsumeCodePoint(codePoint);
                        return this.consumeIdentLikeToken();
                    }
                    if (e2 === HYPHEN_MINUS && e3 === GREATER_THAN_SIGN) {
                        this.consumeCodePoint();
                        this.consumeCodePoint();
                        return CDC_TOKEN;
                    }
                    break;
                case FULL_STOP:
                    if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) {
                        this.reconsumeCodePoint(codePoint);
                        return this.consumeNumericToken();
                    }
                    break;
                case SOLIDUS:
                    if (this.peekCodePoint(0) === ASTERISK) {
                        this.consumeCodePoint();
                        while (true) {
                            var c = this.consumeCodePoint();
                            if (c === ASTERISK) {
                                c = this.consumeCodePoint();
                                if (c === SOLIDUS) {
                                    return this.consumeToken();
                                }
                            }
                            if (c === EOF) {
                                return this.consumeToken();
                            }
                        }
                    }
                    break;
                case COLON:
                    return COLON_TOKEN;
                case SEMICOLON:
                    return SEMICOLON_TOKEN;
                case LESS_THAN_SIGN:
                    if (this.peekCodePoint(0) === EXCLAMATION_MARK &&
                        this.peekCodePoint(1) === HYPHEN_MINUS &&
                        this.peekCodePoint(2) === HYPHEN_MINUS) {
                        this.consumeCodePoint();
                        this.consumeCodePoint();
                        return CDO_TOKEN;
                    }
                    break;
                case COMMERCIAL_AT:
                    var a1 = this.peekCodePoint(0);
                    var a2 = this.peekCodePoint(1);
                    var a3 = this.peekCodePoint(2);
                    if (isIdentifierStart(a1, a2, a3)) {
                        var value = this.consumeName();
                        return { type: 7 /* AT_KEYWORD_TOKEN */, value: value };
                    }
                    break;
                case LEFT_SQUARE_BRACKET:
                    return LEFT_SQUARE_BRACKET_TOKEN;
                case REVERSE_SOLIDUS:
                    if (isValidEscape(codePoint, this.peekCodePoint(0))) {
                        this.reconsumeCodePoint(codePoint);
                        return this.consumeIdentLikeToken();
                    }
                    break;
                case RIGHT_SQUARE_BRACKET:
                    return RIGHT_SQUARE_BRACKET_TOKEN;
                case CIRCUMFLEX_ACCENT:
                    if (this.peekCodePoint(0) === EQUALS_SIGN) {
                        this.consumeCodePoint();
                        return PREFIX_MATCH_TOKEN;
                    }
                    break;
                case LEFT_CURLY_BRACKET:
                    return LEFT_CURLY_BRACKET_TOKEN;
                case RIGHT_CURLY_BRACKET:
                    return RIGHT_CURLY_BRACKET_TOKEN;
                case u:
                case U:
                    var u1 = this.peekCodePoint(0);
                    var u2 = this.peekCodePoint(1);
                    if (u1 === PLUS_SIGN && (isHex(u2) || u2 === QUESTION_MARK)) {
                        this.consumeCodePoint();
                        this.consumeUnicodeRangeToken();
                    }
                    this.reconsumeCodePoint(codePoint);
                    return this.consumeIdentLikeToken();
                case VERTICAL_LINE:
                    if (this.peekCodePoint(0) === EQUALS_SIGN) {
                        this.consumeCodePoint();
                        return DASH_MATCH_TOKEN;
                    }
                    if (this.peekCodePoint(0) === VERTICAL_LINE) {
                        this.consumeCodePoint();
                        return COLUMN_TOKEN;
                    }
                    break;
                case TILDE:
                    if (this.peekCodePoint(0) === EQUALS_SIGN) {
                        this.consumeCodePoint();
                        return INCLUDE_MATCH_TOKEN;
                    }
                    break;
                case EOF:
                    return EOF_TOKEN;
            }
            if (isWhiteSpace(codePoint)) {
                this.consumeWhiteSpace();
                return WHITESPACE_TOKEN;
            }
            if (isDigit(codePoint)) {
                this.reconsumeCodePoint(codePoint);
                return this.consumeNumericToken();
            }
            if (isNameStartCodePoint(codePoint)) {
                this.reconsumeCodePoint(codePoint);
                return this.consumeIdentLikeToken();
            }
            return { type: 6 /* DELIM_TOKEN */, value: fromCodePoint$1(codePoint) };
        };
        Tokenizer.prototype.consumeCodePoint = function () {
            var value = this._value.shift();
            return typeof value === 'undefined' ? -1 : value;
        };
        Tokenizer.prototype.reconsumeCodePoint = function (codePoint) {
            this._value.unshift(codePoint);
        };
        Tokenizer.prototype.peekCodePoint = function (delta) {
            if (delta >= this._value.length) {
                return -1;
            }
            return this._value[delta];
        };
        Tokenizer.prototype.consumeUnicodeRangeToken = function () {
            var digits = [];
            var codePoint = this.consumeCodePoint();
            while (isHex(codePoint) && digits.length < 6) {
                digits.push(codePoint);
                codePoint = this.consumeCodePoint();
            }
            var questionMarks = false;
            while (codePoint === QUESTION_MARK && digits.length < 6) {
                digits.push(codePoint);
                codePoint = this.consumeCodePoint();
                questionMarks = true;
            }
            if (questionMarks) {
                var start_1 = parseInt(fromCodePoint$1.apply(void 0, digits.map(function (digit) { return (digit === QUESTION_MARK ? ZERO : digit); })), 16);
                var end = parseInt(fromCodePoint$1.apply(void 0, digits.map(function (digit) { return (digit === QUESTION_MARK ? F : digit); })), 16);
                return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start_1, end: end };
            }
            var start = parseInt(fromCodePoint$1.apply(void 0, digits), 16);
            if (this.peekCodePoint(0) === HYPHEN_MINUS && isHex(this.peekCodePoint(1))) {
                this.consumeCodePoint();
                codePoint = this.consumeCodePoint();
                var endDigits = [];
                while (isHex(codePoint) && endDigits.length < 6) {
                    endDigits.push(codePoint);
                    codePoint = this.consumeCodePoint();
                }
                var end = parseInt(fromCodePoint$1.apply(void 0, endDigits), 16);
                return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start, end: end };
            }
            else {
                return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start, end: start };
            }
        };
        Tokenizer.prototype.consumeIdentLikeToken = function () {
            var value = this.consumeName();
            if (value.toLowerCase() === 'url' && this.peekCodePoint(0) === LEFT_PARENTHESIS) {
                this.consumeCodePoint();
                return this.consumeUrlToken();
            }
            else if (this.peekCodePoint(0) === LEFT_PARENTHESIS) {
                this.consumeCodePoint();
                return { type: 19 /* FUNCTION_TOKEN */, value: value };
            }
            return { type: 20 /* IDENT_TOKEN */, value: value };
        };
        Tokenizer.prototype.consumeUrlToken = function () {
            var value = [];
            this.consumeWhiteSpace();
            if (this.peekCodePoint(0) === EOF) {
                return { type: 22 /* URL_TOKEN */, value: '' };
            }
            var next = this.peekCodePoint(0);
            if (next === APOSTROPHE || next === QUOTATION_MARK) {
                var stringToken = this.consumeStringToken(this.consumeCodePoint());
                if (stringToken.type === 0 /* STRING_TOKEN */) {
                    this.consumeWhiteSpace();
                    if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) {
                        this.consumeCodePoint();
                        return { type: 22 /* URL_TOKEN */, value: stringToken.value };
                    }
                }
                this.consumeBadUrlRemnants();
                return BAD_URL_TOKEN;
            }
            while (true) {
                var codePoint = this.consumeCodePoint();
                if (codePoint === EOF || codePoint === RIGHT_PARENTHESIS) {
                    return { type: 22 /* URL_TOKEN */, value: fromCodePoint$1.apply(void 0, value) };
                }
                else if (isWhiteSpace(codePoint)) {
                    this.consumeWhiteSpace();
                    if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) {
                        this.consumeCodePoint();
                        return { type: 22 /* URL_TOKEN */, value: fromCodePoint$1.apply(void 0, value) };
                    }
                    this.consumeBadUrlRemnants();
                    return BAD_URL_TOKEN;
                }
                else if (codePoint === QUOTATION_MARK ||
                    codePoint === APOSTROPHE ||
                    codePoint === LEFT_PARENTHESIS ||
                    isNonPrintableCodePoint(codePoint)) {
                    this.consumeBadUrlRemnants();
                    return BAD_URL_TOKEN;
                }
                else if (codePoint === REVERSE_SOLIDUS) {
                    if (isValidEscape(codePoint, this.peekCodePoint(0))) {
                        value.push(this.consumeEscapedCodePoint());
                    }
                    else {
                        this.consumeBadUrlRemnants();
                        return BAD_URL_TOKEN;
                    }
                }
                else {
                    value.push(codePoint);
                }
            }
        };
        Tokenizer.prototype.consumeWhiteSpace = function () {
            while (isWhiteSpace(this.peekCodePoint(0))) {
                this.consumeCodePoint();
            }
        };
        Tokenizer.prototype.consumeBadUrlRemnants = function () {
            while (true) {
                var codePoint = this.consumeCodePoint();
                if (codePoint === RIGHT_PARENTHESIS || codePoint === EOF) {
                    return;
                }
                if (isValidEscape(codePoint, this.peekCodePoint(0))) {
                    this.consumeEscapedCodePoint();
                }
            }
        };
        Tokenizer.prototype.consumeStringSlice = function (count) {
            var SLICE_STACK_SIZE = 50000;
            var value = '';
            while (count > 0) {
                var amount = Math.min(SLICE_STACK_SIZE, count);
                value += fromCodePoint$1.apply(void 0, this._value.splice(0, amount));
                count -= amount;
            }
            this._value.shift();
            return value;
        };
        Tokenizer.prototype.consumeStringToken = function (endingCodePoint) {
            var value = '';
            var i = 0;
            do {
                var codePoint = this._value[i];
                if (codePoint === EOF || codePoint === undefined || codePoint === endingCodePoint) {
                    value += this.consumeStringSlice(i);
                    return { type: 0 /* STRING_TOKEN */, value: value };
                }
                if (codePoint === LINE_FEED) {
                    this._value.splice(0, i);
                    return BAD_STRING_TOKEN;
                }
                if (codePoint === REVERSE_SOLIDUS) {
                    var next = this._value[i + 1];
                    if (next !== EOF && next !== undefined) {
                        if (next === LINE_FEED) {
                            value += this.consumeStringSlice(i);
                            i = -1;
                            this._value.shift();
                        }
                        else if (isValidEscape(codePoint, next)) {
                            value += this.consumeStringSlice(i);
                            value += fromCodePoint$1(this.consumeEscapedCodePoint());
                            i = -1;
                        }
                    }
                }
                i++;
            } while (true);
        };
        Tokenizer.prototype.consumeNumber = function () {
            var repr = [];
            var type = FLAG_INTEGER;
            var c1 = this.peekCodePoint(0);
            if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) {
                repr.push(this.consumeCodePoint());
            }
            while (isDigit(this.peekCodePoint(0))) {
                repr.push(this.consumeCodePoint());
            }
            c1 = this.peekCodePoint(0);
            var c2 = this.peekCodePoint(1);
            if (c1 === FULL_STOP && isDigit(c2)) {
                repr.push(this.consumeCodePoint(), this.consumeCodePoint());
                type = FLAG_NUMBER;
                while (isDigit(this.peekCodePoint(0))) {
                    repr.push(this.consumeCodePoint());
                }
            }
            c1 = this.peekCodePoint(0);
            c2 = this.peekCodePoint(1);
            var c3 = this.peekCodePoint(2);
            if ((c1 === E || c1 === e) && (((c2 === PLUS_SIGN || c2 === HYPHEN_MINUS) && isDigit(c3)) || isDigit(c2))) {
                repr.push(this.consumeCodePoint(), this.consumeCodePoint());
                type = FLAG_NUMBER;
                while (isDigit(this.peekCodePoint(0))) {
                    repr.push(this.consumeCodePoint());
                }
            }
            return [stringToNumber(repr), type];
        };
        Tokenizer.prototype.consumeNumericToken = function () {
            var _a = this.consumeNumber(), number = _a[0], flags = _a[1];
            var c1 = this.peekCodePoint(0);
            var c2 = this.peekCodePoint(1);
            var c3 = this.peekCodePoint(2);
            if (isIdentifierStart(c1, c2, c3)) {
                var unit = this.consumeName();
                return { type: 15 /* DIMENSION_TOKEN */, number: number, flags: flags, unit: unit };
            }
            if (c1 === PERCENTAGE_SIGN) {
                this.consumeCodePoint();
                return { type: 16 /* PERCENTAGE_TOKEN */, number: number, flags: flags };
            }
            return { type: 17 /* NUMBER_TOKEN */, number: number, flags: flags };
        };
        Tokenizer.prototype.consumeEscapedCodePoint = function () {
            var codePoint = this.consumeCodePoint();
            if (isHex(codePoint)) {
                var hex = fromCodePoint$1(codePoint);
                while (isHex(this.peekCodePoint(0)) && hex.length < 6) {
                    hex += fromCodePoint$1(this.consumeCodePoint());
                }
                if (isWhiteSpace(this.peekCodePoint(0))) {
                    this.consumeCodePoint();
                }
                var hexCodePoint = parseInt(hex, 16);
                if (hexCodePoint === 0 || isSurrogateCodePoint(hexCodePoint) || hexCodePoint > 0x10ffff) {
                    return REPLACEMENT_CHARACTER;
                }
                return hexCodePoint;
            }
            if (codePoint === EOF) {
                return REPLACEMENT_CHARACTER;
            }
            return codePoint;
        };
        Tokenizer.prototype.consumeName = function () {
            var result = '';
            while (true) {
                var codePoint = this.consumeCodePoint();
                if (isNameCodePoint(codePoint)) {
                    result += fromCodePoint$1(codePoint);
                }
                else if (isValidEscape(codePoint, this.peekCodePoint(0))) {
                    result += fromCodePoint$1(this.consumeEscapedCodePoint());
                }
                else {
                    this.reconsumeCodePoint(codePoint);
                    return result;
                }
            }
        };
        return Tokenizer;
    }());

    var Parser = /** @class */ (function () {
        function Parser(tokens) {
            this._tokens = tokens;
        }
        Parser.create = function (value) {
            var tokenizer = new Tokenizer();
            tokenizer.write(value);
            return new Parser(tokenizer.read());
        };
        Parser.parseValue = function (value) {
            return Parser.create(value).parseComponentValue();
        };
        Parser.parseValues = function (value) {
            return Parser.create(value).parseComponentValues();
        };
        Parser.prototype.parseComponentValue = function () {
            var token = this.consumeToken();
            while (token.type === 31 /* WHITESPACE_TOKEN */) {
                token = this.consumeToken();
            }
            if (token.type === 32 /* EOF_TOKEN */) {
                throw new SyntaxError("Error parsing CSS component value, unexpected EOF");
            }
            this.reconsumeToken(token);
            var value = this.consumeComponentValue();
            do {
                token = this.consumeToken();
            } while (token.type === 31 /* WHITESPACE_TOKEN */);
            if (token.type === 32 /* EOF_TOKEN */) {
                return value;
            }
            throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one");
        };
        Parser.prototype.parseComponentValues = function () {
            var values = [];
            while (true) {
                var value = this.consumeComponentValue();
                if (value.type === 32 /* EOF_TOKEN */) {
                    return values;
                }
                values.push(value);
                values.push();
            }
        };
        Parser.prototype.consumeComponentValue = function () {
            var token = this.consumeToken();
            switch (token.type) {
                case 11 /* LEFT_CURLY_BRACKET_TOKEN */:
                case 28 /* LEFT_SQUARE_BRACKET_TOKEN */:
                case 2 /* LEFT_PARENTHESIS_TOKEN */:
                    return this.consumeSimpleBlock(token.type);
                case 19 /* FUNCTION_TOKEN */:
                    return this.consumeFunction(token);
            }
            return token;
        };
        Parser.prototype.consumeSimpleBlock = function (type) {
            var block = { type: type, values: [] };
            var token = this.consumeToken();
            while (true) {
                if (token.type === 32 /* EOF_TOKEN */ || isEndingTokenFor(token, type)) {
                    return block;
                }
                this.reconsumeToken(token);
                block.values.push(this.consumeComponentValue());
                token = this.consumeToken();
            }
        };
        Parser.prototype.consumeFunction = function (functionToken) {
            var cssFunction = {
                name: functionToken.value,
                values: [],
                type: 18 /* FUNCTION */
            };
            while (true) {
                var token = this.consumeToken();
                if (token.type === 32 /* EOF_TOKEN */ || token.type === 3 /* RIGHT_PARENTHESIS_TOKEN */) {
                    return cssFunction;
                }
                this.reconsumeToken(token);
                cssFunction.values.push(this.consumeComponentValue());
            }
        };
        Parser.prototype.consumeToken = function () {
            var token = this._tokens.shift();
            return typeof token === 'undefined' ? EOF_TOKEN : token;
        };
        Parser.prototype.reconsumeToken = function (token) {
            this._tokens.unshift(token);
        };
        return Parser;
    }());
    var isDimensionToken = function (token) { return token.type === 15 /* DIMENSION_TOKEN */; };
    var isNumberToken = function (token) { return token.type === 17 /* NUMBER_TOKEN */; };
    var isIdentToken = function (token) { return token.type === 20 /* IDENT_TOKEN */; };
    var isStringToken = function (token) { return token.type === 0 /* STRING_TOKEN */; };
    var isIdentWithValue = function (token, value) {
        return isIdentToken(token) && token.value === value;
    };
    var nonWhiteSpace = function (token) { return token.type !== 31 /* WHITESPACE_TOKEN */; };
    var nonFunctionArgSeparator = function (token) {
        return token.type !== 31 /* WHITESPACE_TOKEN */ && token.type !== 4 /* COMMA_TOKEN */;
    };
    var parseFunctionArgs = function (tokens) {
        var args = [];
        var arg = [];
        tokens.forEach(function (token) {
            if (token.type === 4 /* COMMA_TOKEN */) {
                if (arg.length === 0) {
                    throw new Error("Error parsing function args, zero tokens for arg");
                }
                args.push(arg);
                arg = [];
                return;
            }
            if (token.type !== 31 /* WHITESPACE_TOKEN */) {
                arg.push(token);
            }
        });
        if (arg.length) {
            args.push(arg);
        }
        return args;
    };
    var isEndingTokenFor = function (token, type) {
        if (type === 11 /* LEFT_CURLY_BRACKET_TOKEN */ && token.type === 12 /* RIGHT_CURLY_BRACKET_TOKEN */) {
            return true;
        }
        if (type === 28 /* LEFT_SQUARE_BRACKET_TOKEN */ && token.type === 29 /* RIGHT_SQUARE_BRACKET_TOKEN */) {
            return true;
        }
        return type === 2 /* LEFT_PARENTHESIS_TOKEN */ && token.type === 3 /* RIGHT_PARENTHESIS_TOKEN */;
    };

    var isLength = function (token) {
        return token.type === 17 /* NUMBER_TOKEN */ || token.type === 15 /* DIMENSION_TOKEN */;
    };

    var isLengthPercentage = function (token) {
        return token.type === 16 /* PERCENTAGE_TOKEN */ || isLength(token);
    };
    var parseLengthPercentageTuple = function (tokens) {
        return tokens.length > 1 ? [tokens[0], tokens[1]] : [tokens[0]];
    };
    var ZERO_LENGTH = {
        type: 17 /* NUMBER_TOKEN */,
        number: 0,
        flags: FLAG_INTEGER
    };
    var FIFTY_PERCENT = {
        type: 16 /* PERCENTAGE_TOKEN */,
        number: 50,
        flags: FLAG_INTEGER
    };
    var HUNDRED_PERCENT = {
        type: 16 /* PERCENTAGE_TOKEN */,
        number: 100,
        flags: FLAG_INTEGER
    };
    var getAbsoluteValueForTuple = function (tuple, width, height) {
        var x = tuple[0], y = tuple[1];
        return [getAbsoluteValue(x, width), getAbsoluteValue(typeof y !== 'undefined' ? y : x, height)];
    };
    var getAbsoluteValue = function (token, parent) {
        if (token.type === 16 /* PERCENTAGE_TOKEN */) {
            return (token.number / 100) * parent;
        }
        if (isDimensionToken(token)) {
            switch (token.unit) {
                case 'rem':
                case 'em':
                    return 16 * token.number; // TODO use correct font-size
                case 'px':
                default:
                    return token.number;
            }
        }
        return token.number;
    };

    var DEG = 'deg';
    var GRAD = 'grad';
    var RAD = 'rad';
    var TURN = 'turn';
    var angle = {
        name: 'angle',
        parse: function (_context, value) {
            if (value.type === 15 /* DIMENSION_TOKEN */) {
                switch (value.unit) {
                    case DEG:
                        return (Math.PI * value.number) / 180;
                    case GRAD:
                        return (Math.PI / 200) * value.number;
                    case RAD:
                        return value.number;
                    case TURN:
                        return Math.PI * 2 * value.number;
                }
            }
            throw new Error("Unsupported angle type");
        }
    };
    var isAngle = function (value) {
        if (value.type === 15 /* DIMENSION_TOKEN */) {
            if (value.unit === DEG || value.unit === GRAD || value.unit === RAD || value.unit === TURN) {
                return true;
            }
        }
        return false;
    };
    var parseNamedSide = function (tokens) {
        var sideOrCorner = tokens
            .filter(isIdentToken)
            .map(function (ident) { return ident.value; })
            .join(' ');
        switch (sideOrCorner) {
            case 'to bottom right':
            case 'to right bottom':
            case 'left top':
            case 'top left':
                return [ZERO_LENGTH, ZERO_LENGTH];
            case 'to top':
            case 'bottom':
                return deg(0);
            case 'to bottom left':
            case 'to left bottom':
            case 'right top':
            case 'top right':
                return [ZERO_LENGTH, HUNDRED_PERCENT];
            case 'to right':
            case 'left':
                return deg(90);
            case 'to top left':
            case 'to left top':
            case 'right bottom':
            case 'bottom right':
                return [HUNDRED_PERCENT, HUNDRED_PERCENT];
            case 'to bottom':
            case 'top':
                return deg(180);
            case 'to top right':
            case 'to right top':
            case 'left bottom':
            case 'bottom left':
                return [HUNDRED_PERCENT, ZERO_LENGTH];
            case 'to left':
            case 'right':
                return deg(270);
        }
        return 0;
    };
    var deg = function (deg) { return (Math.PI * deg) / 180; };

    var color$1 = {
        name: 'color',
        parse: function (context, value) {
            if (value.type === 18 /* FUNCTION */) {
                var colorFunction = SUPPORTED_COLOR_FUNCTIONS[value.name];
                if (typeof colorFunction === 'undefined') {
                    throw new Error("Attempting to parse an unsupported color function \"" + value.name + "\"");
                }
                return colorFunction(context, value.values);
            }
            if (value.type === 5 /* HASH_TOKEN */) {
                if (value.value.length === 3) {
                    var r = value.value.substring(0, 1);
                    var g = value.value.substring(1, 2);
                    var b = value.value.substring(2, 3);
                    return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), 1);
                }
                if (value.value.length === 4) {
                    var r = value.value.substring(0, 1);
                    var g = value.value.substring(1, 2);
                    var b = value.value.substring(2, 3);
                    var a = value.value.substring(3, 4);
                    return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), parseInt(a + a, 16) / 255);
                }
                if (value.value.length === 6) {
                    var r = value.value.substring(0, 2);
                    var g = value.value.substring(2, 4);
                    var b = value.value.substring(4, 6);
                    return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), 1);
                }
                if (value.value.length === 8) {
                    var r = value.value.substring(0, 2);
                    var g = value.value.substring(2, 4);
                    var b = value.value.substring(4, 6);
                    var a = value.value.substring(6, 8);
                    return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), parseInt(a, 16) / 255);
                }
            }
            if (value.type === 20 /* IDENT_TOKEN */) {
                var namedColor = COLORS[value.value.toUpperCase()];
                if (typeof namedColor !== 'undefined') {
                    return namedColor;
                }
            }
            return COLORS.TRANSPARENT;
        }
    };
    var isTransparent = function (color) { return (0xff & color) === 0; };
    var asString = function (color) {
        var alpha = 0xff & color;
        var blue = 0xff & (color >> 8);
        var green = 0xff & (color >> 16);
        var red = 0xff & (color >> 24);
        return alpha < 255 ? "rgba(" + red + "," + green + "," + blue + "," + alpha / 255 + ")" : "rgb(" + red + "," + green + "," + blue + ")";
    };
    var pack = function (r, g, b, a) {
        return ((r << 24) | (g << 16) | (b << 8) | (Math.round(a * 255) << 0)) >>> 0;
    };
    var getTokenColorValue = function (token, i) {
        if (token.type === 17 /* NUMBER_TOKEN */) {
            return token.number;
        }
        if (token.type === 16 /* PERCENTAGE_TOKEN */) {
            var max = i === 3 ? 1 : 255;
            return i === 3 ? (token.number / 100) * max : Math.round((token.number / 100) * max);
        }
        return 0;
    };
    var rgb = function (_context, args) {
        var tokens = args.filter(nonFunctionArgSeparator);
        if (tokens.length === 3) {
            var _a = tokens.map(getTokenColorValue), r = _a[0], g = _a[1], b = _a[2];
            return pack(r, g, b, 1);
        }
        if (tokens.length === 4) {
            var _b = tokens.map(getTokenColorValue), r = _b[0], g = _b[1], b = _b[2], a = _b[3];
            return pack(r, g, b, a);
        }
        return 0;
    };
    function hue2rgb(t1, t2, hue) {
        if (hue < 0) {
            hue += 1;
        }
        if (hue >= 1) {
            hue -= 1;
        }
        if (hue < 1 / 6) {
            return (t2 - t1) * hue * 6 + t1;
        }
        else if (hue < 1 / 2) {
            return t2;
        }
        else if (hue < 2 / 3) {
            return (t2 - t1) * 6 * (2 / 3 - hue) + t1;
        }
        else {
            return t1;
        }
    }
    var hsl = function (context, args) {
        var tokens = args.filter(nonFunctionArgSeparator);
        var hue = tokens[0], saturation = tokens[1], lightness = tokens[2], alpha = tokens[3];
        var h = (hue.type === 17 /* NUMBER_TOKEN */ ? deg(hue.number) : angle.parse(context, hue)) / (Math.PI * 2);
        var s = isLengthPercentage(saturation) ? saturation.number / 100 : 0;
        var l = isLengthPercentage(lightness) ? lightness.number / 100 : 0;
        var a = typeof alpha !== 'undefined' && isLengthPercentage(alpha) ? getAbsoluteValue(alpha, 1) : 1;
        if (s === 0) {
            return pack(l * 255, l * 255, l * 255, 1);
        }
        var t2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
        var t1 = l * 2 - t2;
        var r = hue2rgb(t1, t2, h + 1 / 3);
        var g = hue2rgb(t1, t2, h);
        var b = hue2rgb(t1, t2, h - 1 / 3);
        return pack(r * 255, g * 255, b * 255, a);
    };
    var SUPPORTED_COLOR_FUNCTIONS = {
        hsl: hsl,
        hsla: hsl,
        rgb: rgb,
        rgba: rgb
    };
    var parseColor = function (context, value) {
        return color$1.parse(context, Parser.create(value).parseComponentValue());
    };
    var COLORS = {
        ALICEBLUE: 0xf0f8ffff,
        ANTIQUEWHITE: 0xfaebd7ff,
        AQUA: 0x00ffffff,
        AQUAMARINE: 0x7fffd4ff,
        AZURE: 0xf0ffffff,
        BEIGE: 0xf5f5dcff,
        BISQUE: 0xffe4c4ff,
        BLACK: 0x000000ff,
        BLANCHEDALMOND: 0xffebcdff,
        BLUE: 0x0000ffff,
        BLUEVIOLET: 0x8a2be2ff,
        BROWN: 0xa52a2aff,
        BURLYWOOD: 0xdeb887ff,
        CADETBLUE: 0x5f9ea0ff,
        CHARTREUSE: 0x7fff00ff,
        CHOCOLATE: 0xd2691eff,
        CORAL: 0xff7f50ff,
        CORNFLOWERBLUE: 0x6495edff,
        CORNSILK: 0xfff8dcff,
        CRIMSON: 0xdc143cff,
        CYAN: 0x00ffffff,
        DARKBLUE: 0x00008bff,
        DARKCYAN: 0x008b8bff,
        DARKGOLDENROD: 0xb886bbff,
        DARKGRAY: 0xa9a9a9ff,
        DARKGREEN: 0x006400ff,
        DARKGREY: 0xa9a9a9ff,
        DARKKHAKI: 0xbdb76bff,
        DARKMAGENTA: 0x8b008bff,
        DARKOLIVEGREEN: 0x556b2fff,
        DARKORANGE: 0xff8c00ff,
        DARKORCHID: 0x9932ccff,
        DARKRED: 0x8b0000ff,
        DARKSALMON: 0xe9967aff,
        DARKSEAGREEN: 0x8fbc8fff,
        DARKSLATEBLUE: 0x483d8bff,
        DARKSLATEGRAY: 0x2f4f4fff,
        DARKSLATEGREY: 0x2f4f4fff,
        DARKTURQUOISE: 0x00ced1ff,
        DARKVIOLET: 0x9400d3ff,
        DEEPPINK: 0xff1493ff,
        DEEPSKYBLUE: 0x00bfffff,
        DIMGRAY: 0x696969ff,
        DIMGREY: 0x696969ff,
        DODGERBLUE: 0x1e90ffff,
        FIREBRICK: 0xb22222ff,
        FLORALWHITE: 0xfffaf0ff,
        FORESTGREEN: 0x228b22ff,
        FUCHSIA: 0xff00ffff,
        GAINSBORO: 0xdcdcdcff,
        GHOSTWHITE: 0xf8f8ffff,
        GOLD: 0xffd700ff,
        GOLDENROD: 0xdaa520ff,
        GRAY: 0x808080ff,
        GREEN: 0x008000ff,
        GREENYELLOW: 0xadff2fff,
        GREY: 0x808080ff,
        HONEYDEW: 0xf0fff0ff,
        HOTPINK: 0xff69b4ff,
        INDIANRED: 0xcd5c5cff,
        INDIGO: 0x4b0082ff,
        IVORY: 0xfffff0ff,
        KHAKI: 0xf0e68cff,
        LAVENDER: 0xe6e6faff,
        LAVENDERBLUSH: 0xfff0f5ff,
        LAWNGREEN: 0x7cfc00ff,
        LEMONCHIFFON: 0xfffacdff,
        LIGHTBLUE: 0xadd8e6ff,
        LIGHTCORAL: 0xf08080ff,
        LIGHTCYAN: 0xe0ffffff,
        LIGHTGOLDENRODYELLOW: 0xfafad2ff,
        LIGHTGRAY: 0xd3d3d3ff,
        LIGHTGREEN: 0x90ee90ff,
        LIGHTGREY: 0xd3d3d3ff,
        LIGHTPINK: 0xffb6c1ff,
        LIGHTSALMON: 0xffa07aff,
        LIGHTSEAGREEN: 0x20b2aaff,
        LIGHTSKYBLUE: 0x87cefaff,
        LIGHTSLATEGRAY: 0x778899ff,
        LIGHTSLATEGREY: 0x778899ff,
        LIGHTSTEELBLUE: 0xb0c4deff,
        LIGHTYELLOW: 0xffffe0ff,
        LIME: 0x00ff00ff,
        LIMEGREEN: 0x32cd32ff,
        LINEN: 0xfaf0e6ff,
        MAGENTA: 0xff00ffff,
        MAROON: 0x800000ff,
        MEDIUMAQUAMARINE: 0x66cdaaff,
        MEDIUMBLUE: 0x0000cdff,
        MEDIUMORCHID: 0xba55d3ff,
        MEDIUMPURPLE: 0x9370dbff,
        MEDIUMSEAGREEN: 0x3cb371ff,
        MEDIUMSLATEBLUE: 0x7b68eeff,
        MEDIUMSPRINGGREEN: 0x00fa9aff,
        MEDIUMTURQUOISE: 0x48d1ccff,
        MEDIUMVIOLETRED: 0xc71585ff,
        MIDNIGHTBLUE: 0x191970ff,
        MINTCREAM: 0xf5fffaff,
        MISTYROSE: 0xffe4e1ff,
        MOCCASIN: 0xffe4b5ff,
        NAVAJOWHITE: 0xffdeadff,
        NAVY: 0x000080ff,
        OLDLACE: 0xfdf5e6ff,
        OLIVE: 0x808000ff,
        OLIVEDRAB: 0x6b8e23ff,
        ORANGE: 0xffa500ff,
        ORANGERED: 0xff4500ff,
        ORCHID: 0xda70d6ff,
        PALEGOLDENROD: 0xeee8aaff,
        PALEGREEN: 0x98fb98ff,
        PALETURQUOISE: 0xafeeeeff,
        PALEVIOLETRED: 0xdb7093ff,
        PAPAYAWHIP: 0xffefd5ff,
        PEACHPUFF: 0xffdab9ff,
        PERU: 0xcd853fff,
        PINK: 0xffc0cbff,
        PLUM: 0xdda0ddff,
        POWDERBLUE: 0xb0e0e6ff,
        PURPLE: 0x800080ff,
        REBECCAPURPLE: 0x663399ff,
        RED: 0xff0000ff,
        ROSYBROWN: 0xbc8f8fff,
        ROYALBLUE: 0x4169e1ff,
        SADDLEBROWN: 0x8b4513ff,
        SALMON: 0xfa8072ff,
        SANDYBROWN: 0xf4a460ff,
        SEAGREEN: 0x2e8b57ff,
        SEASHELL: 0xfff5eeff,
        SIENNA: 0xa0522dff,
        SILVER: 0xc0c0c0ff,
        SKYBLUE: 0x87ceebff,
        SLATEBLUE: 0x6a5acdff,
        SLATEGRAY: 0x708090ff,
        SLATEGREY: 0x708090ff,
        SNOW: 0xfffafaff,
        SPRINGGREEN: 0x00ff7fff,
        STEELBLUE: 0x4682b4ff,
        TAN: 0xd2b48cff,
        TEAL: 0x008080ff,
        THISTLE: 0xd8bfd8ff,
        TOMATO: 0xff6347ff,
        TRANSPARENT: 0x00000000,
        TURQUOISE: 0x40e0d0ff,
        VIOLET: 0xee82eeff,
        WHEAT: 0xf5deb3ff,
        WHITE: 0xffffffff,
        WHITESMOKE: 0xf5f5f5ff,
        YELLOW: 0xffff00ff,
        YELLOWGREEN: 0x9acd32ff
    };

    var backgroundClip = {
        name: 'background-clip',
        initialValue: 'border-box',
        prefix: false,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            return tokens.map(function (token) {
                if (isIdentToken(token)) {
                    switch (token.value) {
                        case 'padding-box':
                            return 1 /* PADDING_BOX */;
                        case 'content-box':
                            return 2 /* CONTENT_BOX */;
                    }
                }
                return 0 /* BORDER_BOX */;
            });
        }
    };

    var backgroundColor = {
        name: "background-color",
        initialValue: 'transparent',
        prefix: false,
        type: 3 /* TYPE_VALUE */,
        format: 'color'
    };

    var parseColorStop = function (context, args) {
        var color = color$1.parse(context, args[0]);
        var stop = args[1];
        return stop && isLengthPercentage(stop) ? { color: color, stop: stop } : { color: color, stop: null };
    };
    var processColorStops = function (stops, lineLength) {
        var first = stops[0];
        var last = stops[stops.length - 1];
        if (first.stop === null) {
            first.stop = ZERO_LENGTH;
        }
        if (last.stop === null) {
            last.stop = HUNDRED_PERCENT;
        }
        var processStops = [];
        var previous = 0;
        for (var i = 0; i < stops.length; i++) {
            var stop_1 = stops[i].stop;
            if (stop_1 !== null) {
                var absoluteValue = getAbsoluteValue(stop_1, lineLength);
                if (absoluteValue > previous) {
                    processStops.push(absoluteValue);
                }
                else {
                    processStops.push(previous);
                }
                previous = absoluteValue;
            }
            else {
                processStops.push(null);
            }
        }
        var gapBegin = null;
        for (var i = 0; i < processStops.length; i++) {
            var stop_2 = processStops[i];
            if (stop_2 === null) {
                if (gapBegin === null) {
                    gapBegin = i;
                }
            }
            else if (gapBegin !== null) {
                var gapLength = i - gapBegin;
                var beforeGap = processStops[gapBegin - 1];
                var gapValue = (stop_2 - beforeGap) / (gapLength + 1);
                for (var g = 1; g <= gapLength; g++) {
                    processStops[gapBegin + g - 1] = gapValue * g;
                }
                gapBegin = null;
            }
        }
        return stops.map(function (_a, i) {
            var color = _a.color;
            return { color: color, stop: Math.max(Math.min(1, processStops[i] / lineLength), 0) };
        });
    };
    var getAngleFromCorner = function (corner, width, height) {
        var centerX = width / 2;
        var centerY = height / 2;
        var x = getAbsoluteValue(corner[0], width) - centerX;
        var y = centerY - getAbsoluteValue(corner[1], height);
        return (Math.atan2(y, x) + Math.PI * 2) % (Math.PI * 2);
    };
    var calculateGradientDirection = function (angle, width, height) {
        var radian = typeof angle === 'number' ? angle : getAngleFromCorner(angle, width, height);
        var lineLength = Math.abs(width * Math.sin(radian)) + Math.abs(height * Math.cos(radian));
        var halfWidth = width / 2;
        var halfHeight = height / 2;
        var halfLineLength = lineLength / 2;
        var yDiff = Math.sin(radian - Math.PI / 2) * halfLineLength;
        var xDiff = Math.cos(radian - Math.PI / 2) * halfLineLength;
        return [lineLength, halfWidth - xDiff, halfWidth + xDiff, halfHeight - yDiff, halfHeight + yDiff];
    };
    var distance = function (a, b) { return Math.sqrt(a * a + b * b); };
    var findCorner = function (width, height, x, y, closest) {
        var corners = [
            [0, 0],
            [0, height],
            [width, 0],
            [width, height]
        ];
        return corners.reduce(function (stat, corner) {
            var cx = corner[0], cy = corner[1];
            var d = distance(x - cx, y - cy);
            if (closest ? d < stat.optimumDistance : d > stat.optimumDistance) {
                return {
                    optimumCorner: corner,
                    optimumDistance: d
                };
            }
            return stat;
        }, {
            optimumDistance: closest ? Infinity : -Infinity,
            optimumCorner: null
        }).optimumCorner;
    };
    var calculateRadius = function (gradient, x, y, width, height) {
        var rx = 0;
        var ry = 0;
        switch (gradient.size) {
            case 0 /* CLOSEST_SIDE */:
                // The ending shape is sized so that that it exactly meets the side of the gradient box closest to the gradient’s center.
                // If the shape is an ellipse, it exactly meets the closest side in each dimension.
                if (gradient.shape === 0 /* CIRCLE */) {
                    rx = ry = Math.min(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height));
                }
                else if (gradient.shape === 1 /* ELLIPSE */) {
                    rx = Math.min(Math.abs(x), Math.abs(x - width));
                    ry = Math.min(Math.abs(y), Math.abs(y - height));
                }
                break;
            case 2 /* CLOSEST_CORNER */:
                // The ending shape is sized so that that it passes through the corner of the gradient box closest to the gradient’s center.
                // If the shape is an ellipse, the ending shape is given the same aspect-ratio it would have if closest-side were specified.
                if (gradient.shape === 0 /* CIRCLE */) {
                    rx = ry = Math.min(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height));
                }
                else if (gradient.shape === 1 /* ELLIPSE */) {
                    // Compute the ratio ry/rx (which is to be the same as for "closest-side")
                    var c = Math.min(Math.abs(y), Math.abs(y - height)) / Math.min(Math.abs(x), Math.abs(x - width));
                    var _a = findCorner(width, height, x, y, true), cx = _a[0], cy = _a[1];
                    rx = distance(cx - x, (cy - y) / c);
                    ry = c * rx;
                }
                break;
            case 1 /* FARTHEST_SIDE */:
                // Same as closest-side, except the ending shape is sized based on the farthest side(s)
                if (gradient.shape === 0 /* CIRCLE */) {
                    rx = ry = Math.max(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height));
                }
                else if (gradient.shape === 1 /* ELLIPSE */) {
                    rx = Math.max(Math.abs(x), Math.abs(x - width));
                    ry = Math.max(Math.abs(y), Math.abs(y - height));
                }
                break;
            case 3 /* FARTHEST_CORNER */:
                // Same as closest-corner, except the ending shape is sized based on the farthest corner.
                // If the shape is an ellipse, the ending shape is given the same aspect ratio it would have if farthest-side were specified.
                if (gradient.shape === 0 /* CIRCLE */) {
                    rx = ry = Math.max(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height));
                }
                else if (gradient.shape === 1 /* ELLIPSE */) {
                    // Compute the ratio ry/rx (which is to be the same as for "farthest-side")
                    var c = Math.max(Math.abs(y), Math.abs(y - height)) / Math.max(Math.abs(x), Math.abs(x - width));
                    var _b = findCorner(width, height, x, y, false), cx = _b[0], cy = _b[1];
                    rx = distance(cx - x, (cy - y) / c);
                    ry = c * rx;
                }
                break;
        }
        if (Array.isArray(gradient.size)) {
            rx = getAbsoluteValue(gradient.size[0], width);
            ry = gradient.size.length === 2 ? getAbsoluteValue(gradient.size[1], height) : rx;
        }
        return [rx, ry];
    };

    var linearGradient = function (context, tokens) {
        var angle$1 = deg(180);
        var stops = [];
        parseFunctionArgs(tokens).forEach(function (arg, i) {
            if (i === 0) {
                var firstToken = arg[0];
                if (firstToken.type === 20 /* IDENT_TOKEN */ && firstToken.value === 'to') {
                    angle$1 = parseNamedSide(arg);
                    return;
                }
                else if (isAngle(firstToken)) {
                    angle$1 = angle.parse(context, firstToken);
                    return;
                }
            }
            var colorStop = parseColorStop(context, arg);
            stops.push(colorStop);
        });
        return { angle: angle$1, stops: stops, type: 1 /* LINEAR_GRADIENT */ };
    };

    var prefixLinearGradient = function (context, tokens) {
        var angle$1 = deg(180);
        var stops = [];
        parseFunctionArgs(tokens).forEach(function (arg, i) {
            if (i === 0) {
                var firstToken = arg[0];
                if (firstToken.type === 20 /* IDENT_TOKEN */ &&
                    ['top', 'left', 'right', 'bottom'].indexOf(firstToken.value) !== -1) {
                    angle$1 = parseNamedSide(arg);
                    return;
                }
                else if (isAngle(firstToken)) {
                    angle$1 = (angle.parse(context, firstToken) + deg(270)) % deg(360);
                    return;
                }
            }
            var colorStop = parseColorStop(context, arg);
            stops.push(colorStop);
        });
        return {
            angle: angle$1,
            stops: stops,
            type: 1 /* LINEAR_GRADIENT */
        };
    };

    var webkitGradient = function (context, tokens) {
        var angle = deg(180);
        var stops = [];
        var type = 1 /* LINEAR_GRADIENT */;
        var shape = 0 /* CIRCLE */;
        var size = 3 /* FARTHEST_CORNER */;
        var position = [];
        parseFunctionArgs(tokens).forEach(function (arg, i) {
            var firstToken = arg[0];
            if (i === 0) {
                if (isIdentToken(firstToken) && firstToken.value === 'linear') {
                    type = 1 /* LINEAR_GRADIENT */;
                    return;
                }
                else if (isIdentToken(firstToken) && firstToken.value === 'radial') {
                    type = 2 /* RADIAL_GRADIENT */;
                    return;
                }
            }
            if (firstToken.type === 18 /* FUNCTION */) {
                if (firstToken.name === 'from') {
                    var color = color$1.parse(context, firstToken.values[0]);
                    stops.push({ stop: ZERO_LENGTH, color: color });
                }
                else if (firstToken.name === 'to') {
                    var color = color$1.parse(context, firstToken.values[0]);
                    stops.push({ stop: HUNDRED_PERCENT, color: color });
                }
                else if (firstToken.name === 'color-stop') {
                    var values = firstToken.values.filter(nonFunctionArgSeparator);
                    if (values.length === 2) {
                        var color = color$1.parse(context, values[1]);
                        var stop_1 = values[0];
                        if (isNumberToken(stop_1)) {
                            stops.push({
                                stop: { type: 16 /* PERCENTAGE_TOKEN */, number: stop_1.number * 100, flags: stop_1.flags },
                                color: color
                            });
                        }
                    }
                }
            }
        });
        return type === 1 /* LINEAR_GRADIENT */
            ? {
                angle: (angle + deg(180)) % deg(360),
                stops: stops,
                type: type
            }
            : { size: size, shape: shape, stops: stops, position: position, type: type };
    };

    var CLOSEST_SIDE = 'closest-side';
    var FARTHEST_SIDE = 'farthest-side';
    var CLOSEST_CORNER = 'closest-corner';
    var FARTHEST_CORNER = 'farthest-corner';
    var CIRCLE = 'circle';
    var ELLIPSE = 'ellipse';
    var COVER = 'cover';
    var CONTAIN = 'contain';
    var radialGradient = function (context, tokens) {
        var shape = 0 /* CIRCLE */;
        var size = 3 /* FARTHEST_CORNER */;
        var stops = [];
        var position = [];
        parseFunctionArgs(tokens).forEach(function (arg, i) {
            var isColorStop = true;
            if (i === 0) {
                var isAtPosition_1 = false;
                isColorStop = arg.reduce(function (acc, token) {
                    if (isAtPosition_1) {
                        if (isIdentToken(token)) {
                            switch (token.value) {
                                case 'center':
                                    position.push(FIFTY_PERCENT);
                                    return acc;
                                case 'top':
                                case 'left':
                                    position.push(ZERO_LENGTH);
                                    return acc;
                                case 'right':
                                case 'bottom':
                                    position.push(HUNDRED_PERCENT);
                                    return acc;
                            }
                        }
                        else if (isLengthPercentage(token) || isLength(token)) {
                            position.push(token);
                        }
                    }
                    else if (isIdentToken(token)) {
                        switch (token.value) {
                            case CIRCLE:
                                shape = 0 /* CIRCLE */;
                                return false;
                            case ELLIPSE:
                                shape = 1 /* ELLIPSE */;
                                return false;
                            case 'at':
                                isAtPosition_1 = true;
                                return false;
                            case CLOSEST_SIDE:
                                size = 0 /* CLOSEST_SIDE */;
                                return false;
                            case COVER:
                            case FARTHEST_SIDE:
                                size = 1 /* FARTHEST_SIDE */;
                                return false;
                            case CONTAIN:
                            case CLOSEST_CORNER:
                                size = 2 /* CLOSEST_CORNER */;
                                return false;
                            case FARTHEST_CORNER:
                                size = 3 /* FARTHEST_CORNER */;
                                return false;
                        }
                    }
                    else if (isLength(token) || isLengthPercentage(token)) {
                        if (!Array.isArray(size)) {
                            size = [];
                        }
                        size.push(token);
                        return false;
                    }
                    return acc;
                }, isColorStop);
            }
            if (isColorStop) {
                var colorStop = parseColorStop(context, arg);
                stops.push(colorStop);
            }
        });
        return { size: size, shape: shape, stops: stops, position: position, type: 2 /* RADIAL_GRADIENT */ };
    };

    var prefixRadialGradient = function (context, tokens) {
        var shape = 0 /* CIRCLE */;
        var size = 3 /* FARTHEST_CORNER */;
        var stops = [];
        var position = [];
        parseFunctionArgs(tokens).forEach(function (arg, i) {
            var isColorStop = true;
            if (i === 0) {
                isColorStop = arg.reduce(function (acc, token) {
                    if (isIdentToken(token)) {
                        switch (token.value) {
                            case 'center':
                                position.push(FIFTY_PERCENT);
                                return false;
                            case 'top':
                            case 'left':
                                position.push(ZERO_LENGTH);
                                return false;
                            case 'right':
                            case 'bottom':
                                position.push(HUNDRED_PERCENT);
                                return false;
                        }
                    }
                    else if (isLengthPercentage(token) || isLength(token)) {
                        position.push(token);
                        return false;
                    }
                    return acc;
                }, isColorStop);
            }
            else if (i === 1) {
                isColorStop = arg.reduce(function (acc, token) {
                    if (isIdentToken(token)) {
                        switch (token.value) {
                            case CIRCLE:
                                shape = 0 /* CIRCLE */;
                                return false;
                            case ELLIPSE:
                                shape = 1 /* ELLIPSE */;
                                return false;
                            case CONTAIN:
                            case CLOSEST_SIDE:
                                size = 0 /* CLOSEST_SIDE */;
                                return false;
                            case FARTHEST_SIDE:
                                size = 1 /* FARTHEST_SIDE */;
                                return false;
                            case CLOSEST_CORNER:
                                size = 2 /* CLOSEST_CORNER */;
                                return false;
                            case COVER:
                            case FARTHEST_CORNER:
                                size = 3 /* FARTHEST_CORNER */;
                                return false;
                        }
                    }
                    else if (isLength(token) || isLengthPercentage(token)) {
                        if (!Array.isArray(size)) {
                            size = [];
                        }
                        size.push(token);
                        return false;
                    }
                    return acc;
                }, isColorStop);
            }
            if (isColorStop) {
                var colorStop = parseColorStop(context, arg);
                stops.push(colorStop);
            }
        });
        return { size: size, shape: shape, stops: stops, position: position, type: 2 /* RADIAL_GRADIENT */ };
    };

    var isLinearGradient = function (background) {
        return background.type === 1 /* LINEAR_GRADIENT */;
    };
    var isRadialGradient = function (background) {
        return background.type === 2 /* RADIAL_GRADIENT */;
    };
    var image = {
        name: 'image',
        parse: function (context, value) {
            if (value.type === 22 /* URL_TOKEN */) {
                var image_1 = { url: value.value, type: 0 /* URL */ };
                context.cache.addImage(value.value);
                return image_1;
            }
            if (value.type === 18 /* FUNCTION */) {
                var imageFunction = SUPPORTED_IMAGE_FUNCTIONS[value.name];
                if (typeof imageFunction === 'undefined') {
                    throw new Error("Attempting to parse an unsupported image function \"" + value.name + "\"");
                }
                return imageFunction(context, value.values);
            }
            throw new Error("Unsupported image type " + value.type);
        }
    };
    function isSupportedImage(value) {
        return (!(value.type === 20 /* IDENT_TOKEN */ && value.value === 'none') &&
            (value.type !== 18 /* FUNCTION */ || !!SUPPORTED_IMAGE_FUNCTIONS[value.name]));
    }
    var SUPPORTED_IMAGE_FUNCTIONS = {
        'linear-gradient': linearGradient,
        '-moz-linear-gradient': prefixLinearGradient,
        '-ms-linear-gradient': prefixLinearGradient,
        '-o-linear-gradient': prefixLinearGradient,
        '-webkit-linear-gradient': prefixLinearGradient,
        'radial-gradient': radialGradient,
        '-moz-radial-gradient': prefixRadialGradient,
        '-ms-radial-gradient': prefixRadialGradient,
        '-o-radial-gradient': prefixRadialGradient,
        '-webkit-radial-gradient': prefixRadialGradient,
        '-webkit-gradient': webkitGradient
    };

    var backgroundImage = {
        name: 'background-image',
        initialValue: 'none',
        type: 1 /* LIST */,
        prefix: false,
        parse: function (context, tokens) {
            if (tokens.length === 0) {
                return [];
            }
            var first = tokens[0];
            if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
                return [];
            }
            return tokens
                .filter(function (value) { return nonFunctionArgSeparator(value) && isSupportedImage(value); })
                .map(function (value) { return image.parse(context, value); });
        }
    };

    var backgroundOrigin = {
        name: 'background-origin',
        initialValue: 'border-box',
        prefix: false,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            return tokens.map(function (token) {
                if (isIdentToken(token)) {
                    switch (token.value) {
                        case 'padding-box':
                            return 1 /* PADDING_BOX */;
                        case 'content-box':
                            return 2 /* CONTENT_BOX */;
                    }
                }
                return 0 /* BORDER_BOX */;
            });
        }
    };

    var backgroundPosition = {
        name: 'background-position',
        initialValue: '0% 0%',
        type: 1 /* LIST */,
        prefix: false,
        parse: function (_context, tokens) {
            return parseFunctionArgs(tokens)
                .map(function (values) { return values.filter(isLengthPercentage); })
                .map(parseLengthPercentageTuple);
        }
    };

    var backgroundRepeat = {
        name: 'background-repeat',
        initialValue: 'repeat',
        prefix: false,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            return parseFunctionArgs(tokens)
                .map(function (values) {
                return values
                    .filter(isIdentToken)
                    .map(function (token) { return token.value; })
                    .join(' ');
            })
                .map(parseBackgroundRepeat);
        }
    };
    var parseBackgroundRepeat = function (value) {
        switch (value) {
            case 'no-repeat':
                return 1 /* NO_REPEAT */;
            case 'repeat-x':
            case 'repeat no-repeat':
                return 2 /* REPEAT_X */;
            case 'repeat-y':
            case 'no-repeat repeat':
                return 3 /* REPEAT_Y */;
            case 'repeat':
            default:
                return 0 /* REPEAT */;
        }
    };

    var BACKGROUND_SIZE;
    (function (BACKGROUND_SIZE) {
        BACKGROUND_SIZE["AUTO"] = "auto";
        BACKGROUND_SIZE["CONTAIN"] = "contain";
        BACKGROUND_SIZE["COVER"] = "cover";
    })(BACKGROUND_SIZE || (BACKGROUND_SIZE = {}));
    var backgroundSize = {
        name: 'background-size',
        initialValue: '0',
        prefix: false,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            return parseFunctionArgs(tokens).map(function (values) { return values.filter(isBackgroundSizeInfoToken); });
        }
    };
    var isBackgroundSizeInfoToken = function (value) {
        return isIdentToken(value) || isLengthPercentage(value);
    };

    var borderColorForSide = function (side) { return ({
        name: "border-" + side + "-color",
        initialValue: 'transparent',
        prefix: false,
        type: 3 /* TYPE_VALUE */,
        format: 'color'
    }); };
    var borderTopColor = borderColorForSide('top');
    var borderRightColor = borderColorForSide('right');
    var borderBottomColor = borderColorForSide('bottom');
    var borderLeftColor = borderColorForSide('left');

    var borderRadiusForSide = function (side) { return ({
        name: "border-radius-" + side,
        initialValue: '0 0',
        prefix: false,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            return parseLengthPercentageTuple(tokens.filter(isLengthPercentage));
        }
    }); };
    var borderTopLeftRadius = borderRadiusForSide('top-left');
    var borderTopRightRadius = borderRadiusForSide('top-right');
    var borderBottomRightRadius = borderRadiusForSide('bottom-right');
    var borderBottomLeftRadius = borderRadiusForSide('bottom-left');

    var borderStyleForSide = function (side) { return ({
        name: "border-" + side + "-style",
        initialValue: 'solid',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, style) {
            switch (style) {
                case 'none':
                    return 0 /* NONE */;
                case 'dashed':
                    return 2 /* DASHED */;
                case 'dotted':
                    return 3 /* DOTTED */;
                case 'double':
                    return 4 /* DOUBLE */;
            }
            return 1 /* SOLID */;
        }
    }); };
    var borderTopStyle = borderStyleForSide('top');
    var borderRightStyle = borderStyleForSide('right');
    var borderBottomStyle = borderStyleForSide('bottom');
    var borderLeftStyle = borderStyleForSide('left');

    var borderWidthForSide = function (side) { return ({
        name: "border-" + side + "-width",
        initialValue: '0',
        type: 0 /* VALUE */,
        prefix: false,
        parse: function (_context, token) {
            if (isDimensionToken(token)) {
                return token.number;
            }
            return 0;
        }
    }); };
    var borderTopWidth = borderWidthForSide('top');
    var borderRightWidth = borderWidthForSide('right');
    var borderBottomWidth = borderWidthForSide('bottom');
    var borderLeftWidth = borderWidthForSide('left');

    var color = {
        name: "color",
        initialValue: 'transparent',
        prefix: false,
        type: 3 /* TYPE_VALUE */,
        format: 'color'
    };

    var direction = {
        name: 'direction',
        initialValue: 'ltr',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, direction) {
            switch (direction) {
                case 'rtl':
                    return 1 /* RTL */;
                case 'ltr':
                default:
                    return 0 /* LTR */;
            }
        }
    };

    var display = {
        name: 'display',
        initialValue: 'inline-block',
        prefix: false,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            return tokens.filter(isIdentToken).reduce(function (bit, token) {
                return bit | parseDisplayValue(token.value);
            }, 0 /* NONE */);
        }
    };
    var parseDisplayValue = function (display) {
        switch (display) {
            case 'block':
            case '-webkit-box':
                return 2 /* BLOCK */;
            case 'inline':
                return 4 /* INLINE */;
            case 'run-in':
                return 8 /* RUN_IN */;
            case 'flow':
                return 16 /* FLOW */;
            case 'flow-root':
                return 32 /* FLOW_ROOT */;
            case 'table':
                return 64 /* TABLE */;
            case 'flex':
            case '-webkit-flex':
                return 128 /* FLEX */;
            case 'grid':
            case '-ms-grid':
                return 256 /* GRID */;
            case 'ruby':
                return 512 /* RUBY */;
            case 'subgrid':
                return 1024 /* SUBGRID */;
            case 'list-item':
                return 2048 /* LIST_ITEM */;
            case 'table-row-group':
                return 4096 /* TABLE_ROW_GROUP */;
            case 'table-header-group':
                return 8192 /* TABLE_HEADER_GROUP */;
            case 'table-footer-group':
                return 16384 /* TABLE_FOOTER_GROUP */;
            case 'table-row':
                return 32768 /* TABLE_ROW */;
            case 'table-cell':
                return 65536 /* TABLE_CELL */;
            case 'table-column-group':
                return 131072 /* TABLE_COLUMN_GROUP */;
            case 'table-column':
                return 262144 /* TABLE_COLUMN */;
            case 'table-caption':
                return 524288 /* TABLE_CAPTION */;
            case 'ruby-base':
                return 1048576 /* RUBY_BASE */;
            case 'ruby-text':
                return 2097152 /* RUBY_TEXT */;
            case 'ruby-base-container':
                return 4194304 /* RUBY_BASE_CONTAINER */;
            case 'ruby-text-container':
                return 8388608 /* RUBY_TEXT_CONTAINER */;
            case 'contents':
                return 16777216 /* CONTENTS */;
            case 'inline-block':
                return 33554432 /* INLINE_BLOCK */;
            case 'inline-list-item':
                return 67108864 /* INLINE_LIST_ITEM */;
            case 'inline-table':
                return 134217728 /* INLINE_TABLE */;
            case 'inline-flex':
                return 268435456 /* INLINE_FLEX */;
            case 'inline-grid':
                return 536870912 /* INLINE_GRID */;
        }
        return 0 /* NONE */;
    };

    var float = {
        name: 'float',
        initialValue: 'none',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, float) {
            switch (float) {
                case 'left':
                    return 1 /* LEFT */;
                case 'right':
                    return 2 /* RIGHT */;
                case 'inline-start':
                    return 3 /* INLINE_START */;
                case 'inline-end':
                    return 4 /* INLINE_END */;
            }
            return 0 /* NONE */;
        }
    };

    var letterSpacing = {
        name: 'letter-spacing',
        initialValue: '0',
        prefix: false,
        type: 0 /* VALUE */,
        parse: function (_context, token) {
            if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'normal') {
                return 0;
            }
            if (token.type === 17 /* NUMBER_TOKEN */) {
                return token.number;
            }
            if (token.type === 15 /* DIMENSION_TOKEN */) {
                return token.number;
            }
            return 0;
        }
    };

    var LINE_BREAK;
    (function (LINE_BREAK) {
        LINE_BREAK["NORMAL"] = "normal";
        LINE_BREAK["STRICT"] = "strict";
    })(LINE_BREAK || (LINE_BREAK = {}));
    var lineBreak = {
        name: 'line-break',
        initialValue: 'normal',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, lineBreak) {
            switch (lineBreak) {
                case 'strict':
                    return LINE_BREAK.STRICT;
                case 'normal':
                default:
                    return LINE_BREAK.NORMAL;
            }
        }
    };

    var lineHeight = {
        name: 'line-height',
        initialValue: 'normal',
        prefix: false,
        type: 4 /* TOKEN_VALUE */
    };
    var computeLineHeight = function (token, fontSize) {
        if (isIdentToken(token) && token.value === 'normal') {
            return 1.2 * fontSize;
        }
        else if (token.type === 17 /* NUMBER_TOKEN */) {
            return fontSize * token.number;
        }
        else if (isLengthPercentage(token)) {
            return getAbsoluteValue(token, fontSize);
        }
        return fontSize;
    };

    var listStyleImage = {
        name: 'list-style-image',
        initialValue: 'none',
        type: 0 /* VALUE */,
        prefix: false,
        parse: function (context, token) {
            if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'none') {
                return null;
            }
            return image.parse(context, token);
        }
    };

    var listStylePosition = {
        name: 'list-style-position',
        initialValue: 'outside',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, position) {
            switch (position) {
                case 'inside':
                    return 0 /* INSIDE */;
                case 'outside':
                default:
                    return 1 /* OUTSIDE */;
            }
        }
    };

    var listStyleType = {
        name: 'list-style-type',
        initialValue: 'none',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, type) {
            switch (type) {
                case 'disc':
                    return 0 /* DISC */;
                case 'circle':
                    return 1 /* CIRCLE */;
                case 'square':
                    return 2 /* SQUARE */;
                case 'decimal':
                    return 3 /* DECIMAL */;
                case 'cjk-decimal':
                    return 4 /* CJK_DECIMAL */;
                case 'decimal-leading-zero':
                    return 5 /* DECIMAL_LEADING_ZERO */;
                case 'lower-roman':
                    return 6 /* LOWER_ROMAN */;
                case 'upper-roman':
                    return 7 /* UPPER_ROMAN */;
                case 'lower-greek':
                    return 8 /* LOWER_GREEK */;
                case 'lower-alpha':
                    return 9 /* LOWER_ALPHA */;
                case 'upper-alpha':
                    return 10 /* UPPER_ALPHA */;
                case 'arabic-indic':
                    return 11 /* ARABIC_INDIC */;
                case 'armenian':
                    return 12 /* ARMENIAN */;
                case 'bengali':
                    return 13 /* BENGALI */;
                case 'cambodian':
                    return 14 /* CAMBODIAN */;
                case 'cjk-earthly-branch':
                    return 15 /* CJK_EARTHLY_BRANCH */;
                case 'cjk-heavenly-stem':
                    return 16 /* CJK_HEAVENLY_STEM */;
                case 'cjk-ideographic':
                    return 17 /* CJK_IDEOGRAPHIC */;
                case 'devanagari':
                    return 18 /* DEVANAGARI */;
                case 'ethiopic-numeric':
                    return 19 /* ETHIOPIC_NUMERIC */;
                case 'georgian':
                    return 20 /* GEORGIAN */;
                case 'gujarati':
                    return 21 /* GUJARATI */;
                case 'gurmukhi':
                    return 22 /* GURMUKHI */;
                case 'hebrew':
                    return 22 /* HEBREW */;
                case 'hiragana':
                    return 23 /* HIRAGANA */;
                case 'hiragana-iroha':
                    return 24 /* HIRAGANA_IROHA */;
                case 'japanese-formal':
                    return 25 /* JAPANESE_FORMAL */;
                case 'japanese-informal':
                    return 26 /* JAPANESE_INFORMAL */;
                case 'kannada':
                    return 27 /* KANNADA */;
                case 'katakana':
                    return 28 /* KATAKANA */;
                case 'katakana-iroha':
                    return 29 /* KATAKANA_IROHA */;
                case 'khmer':
                    return 30 /* KHMER */;
                case 'korean-hangul-formal':
                    return 31 /* KOREAN_HANGUL_FORMAL */;
                case 'korean-hanja-formal':
                    return 32 /* KOREAN_HANJA_FORMAL */;
                case 'korean-hanja-informal':
                    return 33 /* KOREAN_HANJA_INFORMAL */;
                case 'lao':
                    return 34 /* LAO */;
                case 'lower-armenian':
                    return 35 /* LOWER_ARMENIAN */;
                case 'malayalam':
                    return 36 /* MALAYALAM */;
                case 'mongolian':
                    return 37 /* MONGOLIAN */;
                case 'myanmar':
                    return 38 /* MYANMAR */;
                case 'oriya':
                    return 39 /* ORIYA */;
                case 'persian':
                    return 40 /* PERSIAN */;
                case 'simp-chinese-formal':
                    return 41 /* SIMP_CHINESE_FORMAL */;
                case 'simp-chinese-informal':
                    return 42 /* SIMP_CHINESE_INFORMAL */;
                case 'tamil':
                    return 43 /* TAMIL */;
                case 'telugu':
                    return 44 /* TELUGU */;
                case 'thai':
                    return 45 /* THAI */;
                case 'tibetan':
                    return 46 /* TIBETAN */;
                case 'trad-chinese-formal':
                    return 47 /* TRAD_CHINESE_FORMAL */;
                case 'trad-chinese-informal':
                    return 48 /* TRAD_CHINESE_INFORMAL */;
                case 'upper-armenian':
                    return 49 /* UPPER_ARMENIAN */;
                case 'disclosure-open':
                    return 50 /* DISCLOSURE_OPEN */;
                case 'disclosure-closed':
                    return 51 /* DISCLOSURE_CLOSED */;
                case 'none':
                default:
                    return -1 /* NONE */;
            }
        }
    };

    var marginForSide = function (side) { return ({
        name: "margin-" + side,
        initialValue: '0',
        prefix: false,
        type: 4 /* TOKEN_VALUE */
    }); };
    var marginTop = marginForSide('top');
    var marginRight = marginForSide('right');
    var marginBottom = marginForSide('bottom');
    var marginLeft = marginForSide('left');

    var overflow = {
        name: 'overflow',
        initialValue: 'visible',
        prefix: false,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            return tokens.filter(isIdentToken).map(function (overflow) {
                switch (overflow.value) {
                    case 'hidden':
                        return 1 /* HIDDEN */;
                    case 'scroll':
                        return 2 /* SCROLL */;
                    case 'clip':
                        return 3 /* CLIP */;
                    case 'auto':
                        return 4 /* AUTO */;
                    case 'visible':
                    default:
                        return 0 /* VISIBLE */;
                }
            });
        }
    };

    var overflowWrap = {
        name: 'overflow-wrap',
        initialValue: 'normal',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, overflow) {
            switch (overflow) {
                case 'break-word':
                    return "break-word" /* BREAK_WORD */;
                case 'normal':
                default:
                    return "normal" /* NORMAL */;
            }
        }
    };

    var paddingForSide = function (side) { return ({
        name: "padding-" + side,
        initialValue: '0',
        prefix: false,
        type: 3 /* TYPE_VALUE */,
        format: 'length-percentage'
    }); };
    var paddingTop = paddingForSide('top');
    var paddingRight = paddingForSide('right');
    var paddingBottom = paddingForSide('bottom');
    var paddingLeft = paddingForSide('left');

    var textAlign = {
        name: 'text-align',
        initialValue: 'left',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, textAlign) {
            switch (textAlign) {
                case 'right':
                    return 2 /* RIGHT */;
                case 'center':
                case 'justify':
                    return 1 /* CENTER */;
                case 'left':
                default:
                    return 0 /* LEFT */;
            }
        }
    };

    var position = {
        name: 'position',
        initialValue: 'static',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, position) {
            switch (position) {
                case 'relative':
                    return 1 /* RELATIVE */;
                case 'absolute':
                    return 2 /* ABSOLUTE */;
                case 'fixed':
                    return 3 /* FIXED */;
                case 'sticky':
                    return 4 /* STICKY */;
            }
            return 0 /* STATIC */;
        }
    };

    var textShadow = {
        name: 'text-shadow',
        initialValue: 'none',
        type: 1 /* LIST */,
        prefix: false,
        parse: function (context, tokens) {
            if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) {
                return [];
            }
            return parseFunctionArgs(tokens).map(function (values) {
                var shadow = {
                    color: COLORS.TRANSPARENT,
                    offsetX: ZERO_LENGTH,
                    offsetY: ZERO_LENGTH,
                    blur: ZERO_LENGTH
                };
                var c = 0;
                for (var i = 0; i < values.length; i++) {
                    var token = values[i];
                    if (isLength(token)) {
                        if (c === 0) {
                            shadow.offsetX = token;
                        }
                        else if (c === 1) {
                            shadow.offsetY = token;
                        }
                        else {
                            shadow.blur = token;
                        }
                        c++;
                    }
                    else {
                        shadow.color = color$1.parse(context, token);
                    }
                }
                return shadow;
            });
        }
    };

    var textTransform = {
        name: 'text-transform',
        initialValue: 'none',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, textTransform) {
            switch (textTransform) {
                case 'uppercase':
                    return 2 /* UPPERCASE */;
                case 'lowercase':
                    return 1 /* LOWERCASE */;
                case 'capitalize':
                    return 3 /* CAPITALIZE */;
            }
            return 0 /* NONE */;
        }
    };

    var transform$1 = {
        name: 'transform',
        initialValue: 'none',
        prefix: true,
        type: 0 /* VALUE */,
        parse: function (_context, token) {
            if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'none') {
                return null;
            }
            if (token.type === 18 /* FUNCTION */) {
                var transformFunction = SUPPORTED_TRANSFORM_FUNCTIONS[token.name];
                if (typeof transformFunction === 'undefined') {
                    throw new Error("Attempting to parse an unsupported transform function \"" + token.name + "\"");
                }
                return transformFunction(token.values);
            }
            return null;
        }
    };
    var matrix = function (args) {
        var values = args.filter(function (arg) { return arg.type === 17 /* NUMBER_TOKEN */; }).map(function (arg) { return arg.number; });
        return values.length === 6 ? values : null;
    };
    // doesn't support 3D transforms at the moment
    var matrix3d = function (args) {
        var values = args.filter(function (arg) { return arg.type === 17 /* NUMBER_TOKEN */; }).map(function (arg) { return arg.number; });
        var a1 = values[0], b1 = values[1]; values[2]; values[3]; var a2 = values[4], b2 = values[5]; values[6]; values[7]; values[8]; values[9]; values[10]; values[11]; var a4 = values[12], b4 = values[13]; values[14]; values[15];
        return values.length === 16 ? [a1, b1, a2, b2, a4, b4] : null;
    };
    var SUPPORTED_TRANSFORM_FUNCTIONS = {
        matrix: matrix,
        matrix3d: matrix3d
    };

    var DEFAULT_VALUE = {
        type: 16 /* PERCENTAGE_TOKEN */,
        number: 50,
        flags: FLAG_INTEGER
    };
    var DEFAULT = [DEFAULT_VALUE, DEFAULT_VALUE];
    var transformOrigin = {
        name: 'transform-origin',
        initialValue: '50% 50%',
        prefix: true,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            var origins = tokens.filter(isLengthPercentage);
            if (origins.length !== 2) {
                return DEFAULT;
            }
            return [origins[0], origins[1]];
        }
    };

    var visibility = {
        name: 'visible',
        initialValue: 'none',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, visibility) {
            switch (visibility) {
                case 'hidden':
                    return 1 /* HIDDEN */;
                case 'collapse':
                    return 2 /* COLLAPSE */;
                case 'visible':
                default:
                    return 0 /* VISIBLE */;
            }
        }
    };

    var WORD_BREAK;
    (function (WORD_BREAK) {
        WORD_BREAK["NORMAL"] = "normal";
        WORD_BREAK["BREAK_ALL"] = "break-all";
        WORD_BREAK["KEEP_ALL"] = "keep-all";
    })(WORD_BREAK || (WORD_BREAK = {}));
    var wordBreak = {
        name: 'word-break',
        initialValue: 'normal',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, wordBreak) {
            switch (wordBreak) {
                case 'break-all':
                    return WORD_BREAK.BREAK_ALL;
                case 'keep-all':
                    return WORD_BREAK.KEEP_ALL;
                case 'normal':
                default:
                    return WORD_BREAK.NORMAL;
            }
        }
    };

    var zIndex = {
        name: 'z-index',
        initialValue: 'auto',
        prefix: false,
        type: 0 /* VALUE */,
        parse: function (_context, token) {
            if (token.type === 20 /* IDENT_TOKEN */) {
                return { auto: true, order: 0 };
            }
            if (isNumberToken(token)) {
                return { auto: false, order: token.number };
            }
            throw new Error("Invalid z-index number parsed");
        }
    };

    var time = {
        name: 'time',
        parse: function (_context, value) {
            if (value.type === 15 /* DIMENSION_TOKEN */) {
                switch (value.unit.toLowerCase()) {
                    case 's':
                        return 1000 * value.number;
                    case 'ms':
                        return value.number;
                }
            }
            throw new Error("Unsupported time type");
        }
    };

    var opacity = {
        name: 'opacity',
        initialValue: '1',
        type: 0 /* VALUE */,
        prefix: false,
        parse: function (_context, token) {
            if (isNumberToken(token)) {
                return token.number;
            }
            return 1;
        }
    };

    var textDecorationColor = {
        name: "text-decoration-color",
        initialValue: 'transparent',
        prefix: false,
        type: 3 /* TYPE_VALUE */,
        format: 'color'
    };

    var textDecorationLine = {
        name: 'text-decoration-line',
        initialValue: 'none',
        prefix: false,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            return tokens
                .filter(isIdentToken)
                .map(function (token) {
                switch (token.value) {
                    case 'underline':
                        return 1 /* UNDERLINE */;
                    case 'overline':
                        return 2 /* OVERLINE */;
                    case 'line-through':
                        return 3 /* LINE_THROUGH */;
                    case 'none':
                        return 4 /* BLINK */;
                }
                return 0 /* NONE */;
            })
                .filter(function (line) { return line !== 0 /* NONE */; });
        }
    };

    var fontFamily = {
        name: "font-family",
        initialValue: '',
        prefix: false,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            var accumulator = [];
            var results = [];
            tokens.forEach(function (token) {
                switch (token.type) {
                    case 20 /* IDENT_TOKEN */:
                    case 0 /* STRING_TOKEN */:
                        accumulator.push(token.value);
                        break;
                    case 17 /* NUMBER_TOKEN */:
                        accumulator.push(token.number.toString());
                        break;
                    case 4 /* COMMA_TOKEN */:
                        results.push(accumulator.join(' '));
                        accumulator.length = 0;
                        break;
                }
            });
            if (accumulator.length) {
                results.push(accumulator.join(' '));
            }
            return results.map(function (result) { return (result.indexOf(' ') === -1 ? result : "'" + result + "'"); });
        }
    };

    var fontSize = {
        name: "font-size",
        initialValue: '0',
        prefix: false,
        type: 3 /* TYPE_VALUE */,
        format: 'length'
    };

    var fontWeight = {
        name: 'font-weight',
        initialValue: 'normal',
        type: 0 /* VALUE */,
        prefix: false,
        parse: function (_context, token) {
            if (isNumberToken(token)) {
                return token.number;
            }
            if (isIdentToken(token)) {
                switch (token.value) {
                    case 'bold':
                        return 700;
                    case 'normal':
                    default:
                        return 400;
                }
            }
            return 400;
        }
    };

    var fontVariant = {
        name: 'font-variant',
        initialValue: 'none',
        type: 1 /* LIST */,
        prefix: false,
        parse: function (_context, tokens) {
            return tokens.filter(isIdentToken).map(function (token) { return token.value; });
        }
    };

    var fontStyle = {
        name: 'font-style',
        initialValue: 'normal',
        prefix: false,
        type: 2 /* IDENT_VALUE */,
        parse: function (_context, overflow) {
            switch (overflow) {
                case 'oblique':
                    return "oblique" /* OBLIQUE */;
                case 'italic':
                    return "italic" /* ITALIC */;
                case 'normal':
                default:
                    return "normal" /* NORMAL */;
            }
        }
    };

    var contains = function (bit, value) { return (bit & value) !== 0; };

    var content = {
        name: 'content',
        initialValue: 'none',
        type: 1 /* LIST */,
        prefix: false,
        parse: function (_context, tokens) {
            if (tokens.length === 0) {
                return [];
            }
            var first = tokens[0];
            if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
                return [];
            }
            return tokens;
        }
    };

    var counterIncrement = {
        name: 'counter-increment',
        initialValue: 'none',
        prefix: true,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            if (tokens.length === 0) {
                return null;
            }
            var first = tokens[0];
            if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
                return null;
            }
            var increments = [];
            var filtered = tokens.filter(nonWhiteSpace);
            for (var i = 0; i < filtered.length; i++) {
                var counter = filtered[i];
                var next = filtered[i + 1];
                if (counter.type === 20 /* IDENT_TOKEN */) {
                    var increment = next && isNumberToken(next) ? next.number : 1;
                    increments.push({ counter: counter.value, increment: increment });
                }
            }
            return increments;
        }
    };

    var counterReset = {
        name: 'counter-reset',
        initialValue: 'none',
        prefix: true,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            if (tokens.length === 0) {
                return [];
            }
            var resets = [];
            var filtered = tokens.filter(nonWhiteSpace);
            for (var i = 0; i < filtered.length; i++) {
                var counter = filtered[i];
                var next = filtered[i + 1];
                if (isIdentToken(counter) && counter.value !== 'none') {
                    var reset = next && isNumberToken(next) ? next.number : 0;
                    resets.push({ counter: counter.value, reset: reset });
                }
            }
            return resets;
        }
    };

    var duration = {
        name: 'duration',
        initialValue: '0s',
        prefix: false,
        type: 1 /* LIST */,
        parse: function (context, tokens) {
            return tokens.filter(isDimensionToken).map(function (token) { return time.parse(context, token); });
        }
    };

    var quotes = {
        name: 'quotes',
        initialValue: 'none',
        prefix: true,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            if (tokens.length === 0) {
                return null;
            }
            var first = tokens[0];
            if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
                return null;
            }
            var quotes = [];
            var filtered = tokens.filter(isStringToken);
            if (filtered.length % 2 !== 0) {
                return null;
            }
            for (var i = 0; i < filtered.length; i += 2) {
                var open_1 = filtered[i].value;
                var close_1 = filtered[i + 1].value;
                quotes.push({ open: open_1, close: close_1 });
            }
            return quotes;
        }
    };
    var getQuote = function (quotes, depth, open) {
        if (!quotes) {
            return '';
        }
        var quote = quotes[Math.min(depth, quotes.length - 1)];
        if (!quote) {
            return '';
        }
        return open ? quote.open : quote.close;
    };

    var boxShadow = {
        name: 'box-shadow',
        initialValue: 'none',
        type: 1 /* LIST */,
        prefix: false,
        parse: function (context, tokens) {
            if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) {
                return [];
            }
            return parseFunctionArgs(tokens).map(function (values) {
                var shadow = {
                    color: 0x000000ff,
                    offsetX: ZERO_LENGTH,
                    offsetY: ZERO_LENGTH,
                    blur: ZERO_LENGTH,
                    spread: ZERO_LENGTH,
                    inset: false
                };
                var c = 0;
                for (var i = 0; i < values.length; i++) {
                    var token = values[i];
                    if (isIdentWithValue(token, 'inset')) {
                        shadow.inset = true;
                    }
                    else if (isLength(token)) {
                        if (c === 0) {
                            shadow.offsetX = token;
                        }
                        else if (c === 1) {
                            shadow.offsetY = token;
                        }
                        else if (c === 2) {
                            shadow.blur = token;
                        }
                        else {
                            shadow.spread = token;
                        }
                        c++;
                    }
                    else {
                        shadow.color = color$1.parse(context, token);
                    }
                }
                return shadow;
            });
        }
    };

    var paintOrder = {
        name: 'paint-order',
        initialValue: 'normal',
        prefix: false,
        type: 1 /* LIST */,
        parse: function (_context, tokens) {
            var DEFAULT_VALUE = [0 /* FILL */, 1 /* STROKE */, 2 /* MARKERS */];
            var layers = [];
            tokens.filter(isIdentToken).forEach(function (token) {
                switch (token.value) {
                    case 'stroke':
                        layers.push(1 /* STROKE */);
                        break;
                    case 'fill':
                        layers.push(0 /* FILL */);
                        break;
                    case 'markers':
                        layers.push(2 /* MARKERS */);
                        break;
                }
            });
            DEFAULT_VALUE.forEach(function (value) {
                if (layers.indexOf(value) === -1) {
                    layers.push(value);
                }
            });
            return layers;
        }
    };

    var webkitTextStrokeColor = {
        name: "-webkit-text-stroke-color",
        initialValue: 'currentcolor',
        prefix: false,
        type: 3 /* TYPE_VALUE */,
        format: 'color'
    };

    var webkitTextStrokeWidth = {
        name: "-webkit-text-stroke-width",
        initialValue: '0',
        type: 0 /* VALUE */,
        prefix: false,
        parse: function (_context, token) {
            if (isDimensionToken(token)) {
                return token.number;
            }
            return 0;
        }
    };

    var CSSParsedDeclaration = /** @class */ (function () {
        function CSSParsedDeclaration(context, declaration) {
            var _a, _b;
            this.animationDuration = parse(context, duration, declaration.animationDuration);
            this.backgroundClip = parse(context, backgroundClip, declaration.backgroundClip);
            this.backgroundColor = parse(context, backgroundColor, declaration.backgroundColor);
            this.backgroundImage = parse(context, backgroundImage, declaration.backgroundImage);
            this.backgroundOrigin = parse(context, backgroundOrigin, declaration.backgroundOrigin);
            this.backgroundPosition = parse(context, backgroundPosition, declaration.backgroundPosition);
            this.backgroundRepeat = parse(context, backgroundRepeat, declaration.backgroundRepeat);
            this.backgroundSize = parse(context, backgroundSize, declaration.backgroundSize);
            this.borderTopColor = parse(context, borderTopColor, declaration.borderTopColor);
            this.borderRightColor = parse(context, borderRightColor, declaration.borderRightColor);
            this.borderBottomColor = parse(context, borderBottomColor, declaration.borderBottomColor);
            this.borderLeftColor = parse(context, borderLeftColor, declaration.borderLeftColor);
            this.borderTopLeftRadius = parse(context, borderTopLeftRadius, declaration.borderTopLeftRadius);
            this.borderTopRightRadius = parse(context, borderTopRightRadius, declaration.borderTopRightRadius);
            this.borderBottomRightRadius = parse(context, borderBottomRightRadius, declaration.borderBottomRightRadius);
            this.borderBottomLeftRadius = parse(context, borderBottomLeftRadius, declaration.borderBottomLeftRadius);
            this.borderTopStyle = parse(context, borderTopStyle, declaration.borderTopStyle);
            this.borderRightStyle = parse(context, borderRightStyle, declaration.borderRightStyle);
            this.borderBottomStyle = parse(context, borderBottomStyle, declaration.borderBottomStyle);
            this.borderLeftStyle = parse(context, borderLeftStyle, declaration.borderLeftStyle);
            this.borderTopWidth = parse(context, borderTopWidth, declaration.borderTopWidth);
            this.borderRightWidth = parse(context, borderRightWidth, declaration.borderRightWidth);
            this.borderBottomWidth = parse(context, borderBottomWidth, declaration.borderBottomWidth);
            this.borderLeftWidth = parse(context, borderLeftWidth, declaration.borderLeftWidth);
            this.boxShadow = parse(context, boxShadow, declaration.boxShadow);
            this.color = parse(context, color, declaration.color);
            this.direction = parse(context, direction, declaration.direction);
            this.display = parse(context, display, declaration.display);
            this.float = parse(context, float, declaration.cssFloat);
            this.fontFamily = parse(context, fontFamily, declaration.fontFamily);
            this.fontSize = parse(context, fontSize, declaration.fontSize);
            this.fontStyle = parse(context, fontStyle, declaration.fontStyle);
            this.fontVariant = parse(context, fontVariant, declaration.fontVariant);
            this.fontWeight = parse(context, fontWeight, declaration.fontWeight);
            this.letterSpacing = parse(context, letterSpacing, declaration.letterSpacing);
            this.lineBreak = parse(context, lineBreak, declaration.lineBreak);
            this.lineHeight = parse(context, lineHeight, declaration.lineHeight);
            this.listStyleImage = parse(context, listStyleImage, declaration.listStyleImage);
            this.listStylePosition = parse(context, listStylePosition, declaration.listStylePosition);
            this.listStyleType = parse(context, listStyleType, declaration.listStyleType);
            this.marginTop = parse(context, marginTop, declaration.marginTop);
            this.marginRight = parse(context, marginRight, declaration.marginRight);
            this.marginBottom = parse(context, marginBottom, declaration.marginBottom);
            this.marginLeft = parse(context, marginLeft, declaration.marginLeft);
            this.opacity = parse(context, opacity, declaration.opacity);
            var overflowTuple = parse(context, overflow, declaration.overflow);
            this.overflowX = overflowTuple[0];
            this.overflowY = overflowTuple[overflowTuple.length > 1 ? 1 : 0];
            this.overflowWrap = parse(context, overflowWrap, declaration.overflowWrap);
            this.paddingTop = parse(context, paddingTop, declaration.paddingTop);
            this.paddingRight = parse(context, paddingRight, declaration.paddingRight);
            this.paddingBottom = parse(context, paddingBottom, declaration.paddingBottom);
            this.paddingLeft = parse(context, paddingLeft, declaration.paddingLeft);
            this.paintOrder = parse(context, paintOrder, declaration.paintOrder);
            this.position = parse(context, position, declaration.position);
            this.textAlign = parse(context, textAlign, declaration.textAlign);
            this.textDecorationColor = parse(context, textDecorationColor, (_a = declaration.textDecorationColor) !== null && _a !== void 0 ? _a : declaration.color);
            this.textDecorationLine = parse(context, textDecorationLine, (_b = declaration.textDecorationLine) !== null && _b !== void 0 ? _b : declaration.textDecoration);
            this.textShadow = parse(context, textShadow, declaration.textShadow);
            this.textTransform = parse(context, textTransform, declaration.textTransform);
            this.transform = parse(context, transform$1, declaration.transform);
            this.transformOrigin = parse(context, transformOrigin, declaration.transformOrigin);
            this.visibility = parse(context, visibility, declaration.visibility);
            this.webkitTextStrokeColor = parse(context, webkitTextStrokeColor, declaration.webkitTextStrokeColor);
            this.webkitTextStrokeWidth = parse(context, webkitTextStrokeWidth, declaration.webkitTextStrokeWidth);
            this.wordBreak = parse(context, wordBreak, declaration.wordBreak);
            this.zIndex = parse(context, zIndex, declaration.zIndex);
        }
        CSSParsedDeclaration.prototype.isVisible = function () {
            return this.display > 0 && this.opacity > 0 && this.visibility === 0 /* VISIBLE */;
        };
        CSSParsedDeclaration.prototype.isTransparent = function () {
            return isTransparent(this.backgroundColor);
        };
        CSSParsedDeclaration.prototype.isTransformed = function () {
            return this.transform !== null;
        };
        CSSParsedDeclaration.prototype.isPositioned = function () {
            return this.position !== 0 /* STATIC */;
        };
        CSSParsedDeclaration.prototype.isPositionedWithZIndex = function () {
            return this.isPositioned() && !this.zIndex.auto;
        };
        CSSParsedDeclaration.prototype.isFloating = function () {
            return this.float !== 0 /* NONE */;
        };
        CSSParsedDeclaration.prototype.isInlineLevel = function () {
            return (contains(this.display, 4 /* INLINE */) ||
                contains(this.display, 33554432 /* INLINE_BLOCK */) ||
                contains(this.display, 268435456 /* INLINE_FLEX */) ||
                contains(this.display, 536870912 /* INLINE_GRID */) ||
                contains(this.display, 67108864 /* INLINE_LIST_ITEM */) ||
                contains(this.display, 134217728 /* INLINE_TABLE */));
        };
        return CSSParsedDeclaration;
    }());
    var CSSParsedPseudoDeclaration = /** @class */ (function () {
        function CSSParsedPseudoDeclaration(context, declaration) {
            this.content = parse(context, content, declaration.content);
            this.quotes = parse(context, quotes, declaration.quotes);
        }
        return CSSParsedPseudoDeclaration;
    }());
    var CSSParsedCounterDeclaration = /** @class */ (function () {
        function CSSParsedCounterDeclaration(context, declaration) {
            this.counterIncrement = parse(context, counterIncrement, declaration.counterIncrement);
            this.counterReset = parse(context, counterReset, declaration.counterReset);
        }
        return CSSParsedCounterDeclaration;
    }());
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    var parse = function (context, descriptor, style) {
        var tokenizer = new Tokenizer();
        var value = style !== null && typeof style !== 'undefined' ? style.toString() : descriptor.initialValue;
        tokenizer.write(value);
        var parser = new Parser(tokenizer.read());
        switch (descriptor.type) {
            case 2 /* IDENT_VALUE */:
                var token = parser.parseComponentValue();
                return descriptor.parse(context, isIdentToken(token) ? token.value : descriptor.initialValue);
            case 0 /* VALUE */:
                return descriptor.parse(context, parser.parseComponentValue());
            case 1 /* LIST */:
                return descriptor.parse(context, parser.parseComponentValues());
            case 4 /* TOKEN_VALUE */:
                return parser.parseComponentValue();
            case 3 /* TYPE_VALUE */:
                switch (descriptor.format) {
                    case 'angle':
                        return angle.parse(context, parser.parseComponentValue());
                    case 'color':
                        return color$1.parse(context, parser.parseComponentValue());
                    case 'image':
                        return image.parse(context, parser.parseComponentValue());
                    case 'length':
                        var length_1 = parser.parseComponentValue();
                        return isLength(length_1) ? length_1 : ZERO_LENGTH;
                    case 'length-percentage':
                        var value_1 = parser.parseComponentValue();
                        return isLengthPercentage(value_1) ? value_1 : ZERO_LENGTH;
                    case 'time':
                        return time.parse(context, parser.parseComponentValue());
                }
                break;
        }
    };

    var elementDebuggerAttribute = 'data-html2canvas-debug';
    var getElementDebugType = function (element) {
        var attribute = element.getAttribute(elementDebuggerAttribute);
        switch (attribute) {
            case 'all':
                return 1 /* ALL */;
            case 'clone':
                return 2 /* CLONE */;
            case 'parse':
                return 3 /* PARSE */;
            case 'render':
                return 4 /* RENDER */;
            default:
                return 0 /* NONE */;
        }
    };
    var isDebugging = function (element, type) {
        var elementType = getElementDebugType(element);
        return elementType === 1 /* ALL */ || type === elementType;
    };

    var ElementContainer = /** @class */ (function () {
        function ElementContainer(context, element) {
            this.context = context;
            this.textNodes = [];
            this.elements = [];
            this.flags = 0;
            if (isDebugging(element, 3 /* PARSE */)) {
                debugger;
            }
            this.styles = new CSSParsedDeclaration(context, window.getComputedStyle(element, null));
            if (isHTMLElementNode(element)) {
                if (this.styles.animationDuration.some(function (duration) { return duration > 0; })) {
                    element.style.animationDuration = '0s';
                }
                if (this.styles.transform !== null) {
                    // getBoundingClientRect takes transforms into account
                    element.style.transform = 'none';
                }
            }
            this.bounds = parseBounds(this.context, element);
            if (isDebugging(element, 4 /* RENDER */)) {
                this.flags |= 16 /* DEBUG_RENDER */;
            }
        }
        return ElementContainer;
    }());

    /*
     * text-segmentation 1.0.3 <https://github.com/niklasvh/text-segmentation>
     * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
     * Released under MIT License
     */
    var base64 = ' ';

    /*
     * utrie 1.0.2 <https://github.com/niklasvh/utrie>
     * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
     * Released under MIT License
     */
    var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    // Use a lookup table to find the index.
    var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
    for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
        lookup$1[chars$1.charCodeAt(i$1)] = i$1;
    }
    var decode = function (base64) {
        var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
        if (base64[base64.length - 1] === '=') {
            bufferLength--;
            if (base64[base64.length - 2] === '=') {
                bufferLength--;
            }
        }
        var buffer = typeof ArrayBuffer !== 'undefined' &&
            typeof Uint8Array !== 'undefined' &&
            typeof Uint8Array.prototype.slice !== 'undefined'
            ? new ArrayBuffer(bufferLength)
            : new Array(bufferLength);
        var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer);
        for (i = 0; i < len; i += 4) {
            encoded1 = lookup$1[base64.charCodeAt(i)];
            encoded2 = lookup$1[base64.charCodeAt(i + 1)];
            encoded3 = lookup$1[base64.charCodeAt(i + 2)];
            encoded4 = lookup$1[base64.charCodeAt(i + 3)];
            bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
            bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
            bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
        }
        return buffer;
    };
    var polyUint16Array = function (buffer) {
        var length = buffer.length;
        var bytes = [];
        for (var i = 0; i < length; i += 2) {
            bytes.push((buffer[i + 1] << 8) | buffer[i]);
        }
        return bytes;
    };
    var polyUint32Array = function (buffer) {
        var length = buffer.length;
        var bytes = [];
        for (var i = 0; i < length; i += 4) {
            bytes.push((buffer[i + 3] << 24) | (buffer[i + 2] << 16) | (buffer[i + 1] << 8) | buffer[i]);
        }
        return bytes;
    };

    /** Shift size for getting the index-2 table offset. */
    var UTRIE2_SHIFT_2 = 5;
    /** Shift size for getting the index-1 table offset. */
    var UTRIE2_SHIFT_1 = 6 + 5;
    /**
     * Shift size for shifting left the index array values.
     * Increases possible data size with 16-bit index values at the cost
     * of compactability.
     * This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY.
     */
    var UTRIE2_INDEX_SHIFT = 2;
    /**
     * Difference between the two shift sizes,
     * for getting an index-1 offset from an index-2 offset. 6=11-5
     */
    var UTRIE2_SHIFT_1_2 = UTRIE2_SHIFT_1 - UTRIE2_SHIFT_2;
    /**
     * The part of the index-2 table for U+D800..U+DBFF stores values for
     * lead surrogate code _units_ not code _points_.
     * Values for lead surrogate code _points_ are indexed with this portion of the table.
     * Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.)
     */
    var UTRIE2_LSCP_INDEX_2_OFFSET = 0x10000 >> UTRIE2_SHIFT_2;
    /** Number of entries in a data block. 32=0x20 */
    var UTRIE2_DATA_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_2;
    /** Mask for getting the lower bits for the in-data-block offset. */
    var UTRIE2_DATA_MASK = UTRIE2_DATA_BLOCK_LENGTH - 1;
    var UTRIE2_LSCP_INDEX_2_LENGTH = 0x400 >> UTRIE2_SHIFT_2;
    /** Count the lengths of both BMP pieces. 2080=0x820 */
    var UTRIE2_INDEX_2_BMP_LENGTH = UTRIE2_LSCP_INDEX_2_OFFSET + UTRIE2_LSCP_INDEX_2_LENGTH;
    /**
     * The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820.
     * Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2.
     */
    var UTRIE2_UTF8_2B_INDEX_2_OFFSET = UTRIE2_INDEX_2_BMP_LENGTH;
    var UTRIE2_UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6; /* U+0800 is the first code point after 2-byte UTF-8 */
    /**
     * The index-1 table, only used for supplementary code points, at offset 2112=0x840.
     * Variable length, for code points up to highStart, where the last single-value range starts.
     * Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1.
     * (For 0x100000 supplementary code points U+10000..U+10ffff.)
     *
     * The part of the index-2 table for supplementary code points starts
     * after this index-1 table.
     *
     * Both the index-1 table and the following part of the index-2 table
     * are omitted completely if there is only BMP data.
     */
    var UTRIE2_INDEX_1_OFFSET = UTRIE2_UTF8_2B_INDEX_2_OFFSET + UTRIE2_UTF8_2B_INDEX_2_LENGTH;
    /**
     * Number of index-1 entries for the BMP. 32=0x20
     * This part of the index-1 table is omitted from the serialized form.
     */
    var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> UTRIE2_SHIFT_1;
    /** Number of entries in an index-2 block. 64=0x40 */
    var UTRIE2_INDEX_2_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_1_2;
    /** Mask for getting the lower bits for the in-index-2-block offset. */
    var UTRIE2_INDEX_2_MASK = UTRIE2_INDEX_2_BLOCK_LENGTH - 1;
    var slice16 = function (view, start, end) {
        if (view.slice) {
            return view.slice(start, end);
        }
        return new Uint16Array(Array.prototype.slice.call(view, start, end));
    };
    var slice32 = function (view, start, end) {
        if (view.slice) {
            return view.slice(start, end);
        }
        return new Uint32Array(Array.prototype.slice.call(view, start, end));
    };
    var createTrieFromBase64 = function (base64, _byteLength) {
        var buffer = decode(base64);
        var view32 = Array.isArray(buffer) ? polyUint32Array(buffer) : new Uint32Array(buffer);
        var view16 = Array.isArray(buffer) ? polyUint16Array(buffer) : new Uint16Array(buffer);
        var headerLength = 24;
        var index = slice16(view16, headerLength / 2, view32[4] / 2);
        var data = view32[5] === 2
            ? slice16(view16, (headerLength + view32[4]) / 2)
            : slice32(view32, Math.ceil((headerLength + view32[4]) / 4));
        return new Trie(view32[0], view32[1], view32[2], view32[3], index, data);
    };
    var Trie = /** @class */ (function () {
        function Trie(initialValue, errorValue, highStart, highValueIndex, index, data) {
            this.initialValue = initialValue;
            this.errorValue = errorValue;
            this.highStart = highStart;
            this.highValueIndex = highValueIndex;
            this.index = index;
            this.data = data;
        }
        /**
         * Get the value for a code point as stored in the Trie.
         *
         * @param codePoint the code point
         * @return the value
         */
        Trie.prototype.get = function (codePoint) {
            var ix;
            if (codePoint >= 0) {
                if (codePoint < 0x0d800 || (codePoint > 0x0dbff && codePoint <= 0x0ffff)) {
                    // Ordinary BMP code point, excluding leading surrogates.
                    // BMP uses a single level lookup.  BMP index starts at offset 0 in the Trie2 index.
                    // 16 bit data is stored in the index array itself.
                    ix = this.index[codePoint >> UTRIE2_SHIFT_2];
                    ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
                    return this.data[ix];
                }
                if (codePoint <= 0xffff) {
                    // Lead Surrogate Code Point.  A Separate index section is stored for
                    // lead surrogate code units and code points.
                    //   The main index has the code unit data.
                    //   For this function, we need the code point data.
                    // Note: this expression could be refactored for slightly improved efficiency, but
                    //       surrogate code points will be so rare in practice that it's not worth it.
                    ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET + ((codePoint - 0xd800) >> UTRIE2_SHIFT_2)];
                    ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
                    return this.data[ix];
                }
                if (codePoint < this.highStart) {
                    // Supplemental code point, use two-level lookup.
                    ix = UTRIE2_INDEX_1_OFFSET - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH + (codePoint >> UTRIE2_SHIFT_1);
                    ix = this.index[ix];
                    ix += (codePoint >> UTRIE2_SHIFT_2) & UTRIE2_INDEX_2_MASK;
                    ix = this.index[ix];
                    ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
                    return this.data[ix];
                }
                if (codePoint <= 0x10ffff) {
                    return this.data[this.highValueIndex];
                }
            }
            // Fall through.  The code point is outside of the legal range of 0..0x10ffff.
            return this.errorValue;
        };
        return Trie;
    }());

    /*
     * base64-arraybuffer 1.0.2 <https://github.com/niklasvh/base64-arraybuffer>
     * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
     * Released under MIT License
     */
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    // Use a lookup table to find the index.
    var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
    for (var i = 0; i < chars.length; i++) {
        lookup[chars.charCodeAt(i)] = i;
    }

    var Prepend = 1;
    var CR = 2;
    var LF = 3;
    var Control = 4;
    var Extend = 5;
    var SpacingMark = 7;
    var L = 8;
    var V = 9;
    var T = 10;
    var LV = 11;
    var LVT = 12;
    var ZWJ = 13;
    var Extended_Pictographic = 14;
    var RI = 15;
    var toCodePoints = function (str) {
        var codePoints = [];
        var i = 0;
        var length = str.length;
        while (i < length) {
            var value = str.charCodeAt(i++);
            if (value >= 0xd800 && value <= 0xdbff && i < length) {
                var extra = str.charCodeAt(i++);
                if ((extra & 0xfc00) === 0xdc00) {
                    codePoints.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
                }
                else {
                    codePoints.push(value);
                    i--;
                }
            }
            else {
                codePoints.push(value);
            }
        }
        return codePoints;
    };
    var fromCodePoint = function () {
        var codePoints = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            codePoints[_i] = arguments[_i];
        }
        if (String.fromCodePoint) {
            return String.fromCodePoint.apply(String, codePoints);
        }
        var length = codePoints.length;
        if (!length) {
            return '';
        }
        var codeUnits = [];
        var index = -1;
        var result = '';
        while (++index < length) {
            var codePoint = codePoints[index];
            if (codePoint <= 0xffff) {
                codeUnits.push(codePoint);
            }
            else {
                codePoint -= 0x10000;
                codeUnits.push((codePoint >> 10) + 0xd800, (codePoint % 0x400) + 0xdc00);
            }
            if (index + 1 === length || codeUnits.length > 0x4000) {
                result += String.fromCharCode.apply(String, codeUnits);
                codeUnits.length = 0;
            }
        }
        return result;
    };
    var UnicodeTrie = createTrieFromBase64(base64);
    var BREAK_NOT_ALLOWED = '×';
    var BREAK_ALLOWED = '÷';
    var codePointToClass = function (codePoint) { return UnicodeTrie.get(codePoint); };
    var _graphemeBreakAtIndex = function (_codePoints, classTypes, index) {
        var prevIndex = index - 2;
        var prev = classTypes[prevIndex];
        var current = classTypes[index - 1];
        var next = classTypes[index];
        // GB3 Do not break between a CR and LF
        if (current === CR && next === LF) {
            return BREAK_NOT_ALLOWED;
        }
        // GB4 Otherwise, break before and after controls.
        if (current === CR || current === LF || current === Control) {
            return BREAK_ALLOWED;
        }
        // GB5
        if (next === CR || next === LF || next === Control) {
            return BREAK_ALLOWED;
        }
        // Do not break Hangul syllable sequences.
        // GB6
        if (current === L && [L, V, LV, LVT].indexOf(next) !== -1) {
            return BREAK_NOT_ALLOWED;
        }
        // GB7
        if ((current === LV || current === V) && (next === V || next === T)) {
            return BREAK_NOT_ALLOWED;
        }
        // GB8
        if ((current === LVT || current === T) && next === T) {
            return BREAK_NOT_ALLOWED;
        }
        // GB9 Do not break before extending characters or ZWJ.
        if (next === ZWJ || next === Extend) {
            return BREAK_NOT_ALLOWED;
        }
        // Do not break before SpacingMarks, or after Prepend characters.
        // GB9a
        if (next === SpacingMark) {
            return BREAK_NOT_ALLOWED;
        }
        // GB9a
        if (current === Prepend) {
            return BREAK_NOT_ALLOWED;
        }
        // GB11 Do not break within emoji modifier sequences or emoji zwj sequences.
        if (current === ZWJ && next === Extended_Pictographic) {
            while (prev === Extend) {
                prev = classTypes[--prevIndex];
            }
            if (prev === Extended_Pictographic) {
                return BREAK_NOT_ALLOWED;
            }
        }
        // GB12 Do not break within emoji flag sequences.
        // That is, do not break between regional indicator (RI) symbols
        // if there is an odd number of RI characters before the break point.
        if (current === RI && next === RI) {
            var countRI = 0;
            while (prev === RI) {
                countRI++;
                prev = classTypes[--prevIndex];
            }
            if (countRI % 2 === 0) {
                return BREAK_NOT_ALLOWED;
            }
        }
        return BREAK_ALLOWED;
    };
    var GraphemeBreaker = function (str) {
        var codePoints = toCodePoints(str);
        var length = codePoints.length;
        var index = 0;
        var lastEnd = 0;
        var classTypes = codePoints.map(codePointToClass);
        return {
            next: function () {
                if (index >= length) {
                    return { done: true, value: null };
                }
                var graphemeBreak = BREAK_NOT_ALLOWED;
                while (index < length &&
                    (graphemeBreak = _graphemeBreakAtIndex(codePoints, classTypes, ++index)) === BREAK_NOT_ALLOWED) { }
                if (graphemeBreak !== BREAK_NOT_ALLOWED || index === length) {
                    var value = fromCodePoint.apply(null, codePoints.slice(lastEnd, index));
                    lastEnd = index;
                    return { value: value, done: false };
                }
                return { done: true, value: null };
            },
        };
    };
    var splitGraphemes = function (str) {
        var breaker = GraphemeBreaker(str);
        var graphemes = [];
        var bk;
        while (!(bk = breaker.next()).done) {
            if (bk.value) {
                graphemes.push(bk.value.slice());
            }
        }
        return graphemes;
    };

    var testRangeBounds = function (document) {
        var TEST_HEIGHT = 123;
        if (document.createRange) {
            var range = document.createRange();
            if (range.getBoundingClientRect) {
                var testElement = document.createElement('boundtest');
                testElement.style.height = TEST_HEIGHT + "px";
                testElement.style.display = 'block';
                document.body.appendChild(testElement);
                range.selectNode(testElement);
                var rangeBounds = range.getBoundingClientRect();
                var rangeHeight = Math.round(rangeBounds.height);
                document.body.removeChild(testElement);
                if (rangeHeight === TEST_HEIGHT) {
                    return true;
                }
            }
        }
        return false;
    };
    var testIOSLineBreak = function (document) {
        var testElement = document.createElement('boundtest');
        testElement.style.width = '50px';
        testElement.style.display = 'block';
        testElement.style.fontSize = '12px';
        testElement.style.letterSpacing = '0px';
        testElement.style.wordSpacing = '0px';
        document.body.appendChild(testElement);
        var range = document.createRange();
        testElement.innerHTML = typeof ''.repeat === 'function' ? '&#128104;'.repeat(10) : '';
        var node = testElement.firstChild;
        var textList = toCodePoints$1(node.data).map(function (i) { return fromCodePoint$1(i); });
        var offset = 0;
        var prev = {};
        // ios 13 does not handle range getBoundingClientRect line changes correctly #2177
        var supports = textList.every(function (text, i) {
            range.setStart(node, offset);
            range.setEnd(node, offset + text.length);
            var rect = range.getBoundingClientRect();
            offset += text.length;
            var boundAhead = rect.x > prev.x || rect.y > prev.y;
            prev = rect;
            if (i === 0) {
                return true;
            }
            return boundAhead;
        });
        document.body.removeChild(testElement);
        return supports;
    };
    var testCORS = function () { return typeof new Image().crossOrigin !== 'undefined'; };
    var testResponseType = function () { return typeof new XMLHttpRequest().responseType === 'string'; };
    var testSVG = function (document) {
        var img = new Image();
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        if (!ctx) {
            return false;
        }
        img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
        try {
            ctx.drawImage(img, 0, 0);
            canvas.toDataURL();
        }
        catch (e) {
            return false;
        }
        return true;
    };
    var isGreenPixel = function (data) {
        return data[0] === 0 && data[1] === 255 && data[2] === 0 && data[3] === 255;
    };
    var testForeignObject = function (document) {
        var canvas = document.createElement('canvas');
        var size = 100;
        canvas.width = size;
        canvas.height = size;
        var ctx = canvas.getContext('2d');
        if (!ctx) {
            return Promise.reject(false);
        }
        ctx.fillStyle = 'rgb(0, 255, 0)';
        ctx.fillRect(0, 0, size, size);
        var img = new Image();
        var greenImageSrc = canvas.toDataURL();
        img.src = greenImageSrc;
        var svg = createForeignObjectSVG(size, size, 0, 0, img);
        ctx.fillStyle = 'red';
        ctx.fillRect(0, 0, size, size);
        return loadSerializedSVG$1(svg)
            .then(function (img) {
            ctx.drawImage(img, 0, 0);
            var data = ctx.getImageData(0, 0, size, size).data;
            ctx.fillStyle = 'red';
            ctx.fillRect(0, 0, size, size);
            var node = document.createElement('div');
            node.style.backgroundImage = "url(" + greenImageSrc + ")";
            node.style.height = size + "px";
            // Firefox 55 does not render inline <img /> tags
            return isGreenPixel(data)
                ? loadSerializedSVG$1(createForeignObjectSVG(size, size, 0, 0, node))
                : Promise.reject(false);
        })
            .then(function (img) {
            ctx.drawImage(img, 0, 0);
            // Edge does not render background-images
            return isGreenPixel(ctx.getImageData(0, 0, size, size).data);
        })
            .catch(function () { return false; });
    };
    var createForeignObjectSVG = function (width, height, x, y, node) {
        var xmlns = 'http://www.w3.org/2000/svg';
        var svg = document.createElementNS(xmlns, 'svg');
        var foreignObject = document.createElementNS(xmlns, 'foreignObject');
        svg.setAttributeNS(null, 'width', width.toString());
        svg.setAttributeNS(null, 'height', height.toString());
        foreignObject.setAttributeNS(null, 'width', '100%');
        foreignObject.setAttributeNS(null, 'height', '100%');
        foreignObject.setAttributeNS(null, 'x', x.toString());
        foreignObject.setAttributeNS(null, 'y', y.toString());
        foreignObject.setAttributeNS(null, 'externalResourcesRequired', 'true');
        svg.appendChild(foreignObject);
        foreignObject.appendChild(node);
        return svg;
    };
    var loadSerializedSVG$1 = function (svg) {
        return new Promise(function (resolve, reject) {
            var img = new Image();
            img.onload = function () { return resolve(img); };
            img.onerror = reject;
            img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg));
        });
    };
    var FEATURES = {
        get SUPPORT_RANGE_BOUNDS() {
            var value = testRangeBounds(document);
            Object.defineProperty(FEATURES, 'SUPPORT_RANGE_BOUNDS', { value: value });
            return value;
        },
        get SUPPORT_WORD_BREAKING() {
            var value = FEATURES.SUPPORT_RANGE_BOUNDS && testIOSLineBreak(document);
            Object.defineProperty(FEATURES, 'SUPPORT_WORD_BREAKING', { value: value });
            return value;
        },
        get SUPPORT_SVG_DRAWING() {
            var value = testSVG(document);
            Object.defineProperty(FEATURES, 'SUPPORT_SVG_DRAWING', { value: value });
            return value;
        },
        get SUPPORT_FOREIGNOBJECT_DRAWING() {
            var value = typeof Array.from === 'function' && typeof window.fetch === 'function'
                ? testForeignObject(document)
                : Promise.resolve(false);
            Object.defineProperty(FEATURES, 'SUPPORT_FOREIGNOBJECT_DRAWING', { value: value });
            return value;
        },
        get SUPPORT_CORS_IMAGES() {
            var value = testCORS();
            Object.defineProperty(FEATURES, 'SUPPORT_CORS_IMAGES', { value: value });
            return value;
        },
        get SUPPORT_RESPONSE_TYPE() {
            var value = testResponseType();
            Object.defineProperty(FEATURES, 'SUPPORT_RESPONSE_TYPE', { value: value });
            return value;
        },
        get SUPPORT_CORS_XHR() {
            var value = 'withCredentials' in new XMLHttpRequest();
            Object.defineProperty(FEATURES, 'SUPPORT_CORS_XHR', { value: value });
            return value;
        },
        get SUPPORT_NATIVE_TEXT_SEGMENTATION() {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            var value = !!(typeof Intl !== 'undefined' && Intl.Segmenter);
            Object.defineProperty(FEATURES, 'SUPPORT_NATIVE_TEXT_SEGMENTATION', { value: value });
            return value;
        }
    };

    var TextBounds = /** @class */ (function () {
        function TextBounds(text, bounds) {
            this.text = text;
            this.bounds = bounds;
        }
        return TextBounds;
    }());
    var parseTextBounds = function (context, value, styles, node) {
        var textList = breakText(value, styles);
        var textBounds = [];
        var offset = 0;
        textList.forEach(function (text) {
            if (styles.textDecorationLine.length || text.trim().length > 0) {
                if (FEATURES.SUPPORT_RANGE_BOUNDS) {
                    var clientRects = createRange(node, offset, text.length).getClientRects();
                    if (clientRects.length > 1) {
                        var subSegments = segmentGraphemes(text);
                        var subOffset_1 = 0;
                        subSegments.forEach(function (subSegment) {
                            textBounds.push(new TextBounds(subSegment, Bounds.fromDOMRectList(context, createRange(node, subOffset_1 + offset, subSegment.length).getClientRects())));
                            subOffset_1 += subSegment.length;
                        });
                    }
                    else {
                        textBounds.push(new TextBounds(text, Bounds.fromDOMRectList(context, clientRects)));
                    }
                }
                else {
                    var replacementNode = node.splitText(text.length);
                    textBounds.push(new TextBounds(text, getWrapperBounds(context, node)));
                    node = replacementNode;
                }
            }
            else if (!FEATURES.SUPPORT_RANGE_BOUNDS) {
                node = node.splitText(text.length);
            }
            offset += text.length;
        });
        return textBounds;
    };
    var getWrapperBounds = function (context, node) {
        var ownerDocument = node.ownerDocument;
        if (ownerDocument) {
            var wrapper = ownerDocument.createElement('html2canvaswrapper');
            wrapper.appendChild(node.cloneNode(true));
            var parentNode = node.parentNode;
            if (parentNode) {
                parentNode.replaceChild(wrapper, node);
                var bounds = parseBounds(context, wrapper);
                if (wrapper.firstChild) {
                    parentNode.replaceChild(wrapper.firstChild, wrapper);
                }
                return bounds;
            }
        }
        return Bounds.EMPTY;
    };
    var createRange = function (node, offset, length) {
        var ownerDocument = node.ownerDocument;
        if (!ownerDocument) {
            throw new Error('Node has no owner document');
        }
        var range = ownerDocument.createRange();
        range.setStart(node, offset);
        range.setEnd(node, offset + length);
        return range;
    };
    var segmentGraphemes = function (value) {
        if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            var segmenter = new Intl.Segmenter(void 0, { granularity: 'grapheme' });
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            return Array.from(segmenter.segment(value)).map(function (segment) { return segment.segment; });
        }
        return splitGraphemes(value);
    };
    var segmentWords = function (value, styles) {
        if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            var segmenter = new Intl.Segmenter(void 0, {
                granularity: 'word'
            });
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            return Array.from(segmenter.segment(value)).map(function (segment) { return segment.segment; });
        }
        return breakWords(value, styles);
    };
    var breakText = function (value, styles) {
        return styles.letterSpacing !== 0 ? segmentGraphemes(value) : segmentWords(value, styles);
    };
    // https://drafts.csswg.org/css-text/#word-separator
    var wordSeparators = [0x0020, 0x00a0, 0x1361, 0x10100, 0x10101, 0x1039, 0x1091];
    var breakWords = function (str, styles) {
        var breaker = LineBreaker(str, {
            lineBreak: styles.lineBreak,
            wordBreak: styles.overflowWrap === "break-word" /* BREAK_WORD */ ? 'break-word' : styles.wordBreak
        });
        var words = [];
        var bk;
        var _loop_1 = function () {
            if (bk.value) {
                var value = bk.value.slice();
                var codePoints = toCodePoints$1(value);
                var word_1 = '';
                codePoints.forEach(function (codePoint) {
                    if (wordSeparators.indexOf(codePoint) === -1) {
                        word_1 += fromCodePoint$1(codePoint);
                    }
                    else {
                        if (word_1.length) {
                            words.push(word_1);
                        }
                        words.push(fromCodePoint$1(codePoint));
                        word_1 = '';
                    }
                });
                if (word_1.length) {
                    words.push(word_1);
                }
            }
        };
        while (!(bk = breaker.next()).done) {
            _loop_1();
        }
        return words;
    };

    var TextContainer = /** @class */ (function () {
        function TextContainer(context, node, styles) {
            this.text = transform(node.data, styles.textTransform);
            this.textBounds = parseTextBounds(context, this.text, styles, node);
        }
        return TextContainer;
    }());
    var transform = function (text, transform) {
        switch (transform) {
            case 1 /* LOWERCASE */:
                return text.toLowerCase();
            case 3 /* CAPITALIZE */:
                return text.replace(CAPITALIZE, capitalize);
            case 2 /* UPPERCASE */:
                return text.toUpperCase();
            default:
                return text;
        }
    };
    var CAPITALIZE = /(^|\s|:|-|\(|\))([a-z])/g;
    var capitalize = function (m, p1, p2) {
        if (m.length > 0) {
            return p1 + p2.toUpperCase();
        }
        return m;
    };

    var ImageElementContainer = /** @class */ (function (_super) {
        __extends(ImageElementContainer, _super);
        function ImageElementContainer(context, img) {
            var _this = _super.call(this, context, img) || this;
            _this.src = img.currentSrc || img.src;
            _this.intrinsicWidth = img.naturalWidth;
            _this.intrinsicHeight = img.naturalHeight;
            _this.context.cache.addImage(_this.src);
            return _this;
        }
        return ImageElementContainer;
    }(ElementContainer));

    var CanvasElementContainer = /** @class */ (function (_super) {
        __extends(CanvasElementContainer, _super);
        function CanvasElementContainer(context, canvas) {
            var _this = _super.call(this, context, canvas) || this;
            _this.canvas = canvas;
            _this.intrinsicWidth = canvas.width;
            _this.intrinsicHeight = canvas.height;
            return _this;
        }
        return CanvasElementContainer;
    }(ElementContainer));

    var SVGElementContainer = /** @class */ (function (_super) {
        __extends(SVGElementContainer, _super);
        function SVGElementContainer(context, img) {
            var _this = _super.call(this, context, img) || this;
            var s = new XMLSerializer();
            var bounds = parseBounds(context, img);
            img.setAttribute('width', bounds.width + "px");
            img.setAttribute('height', bounds.height + "px");
            _this.svg = "data:image/svg+xml," + encodeURIComponent(s.serializeToString(img));
            _this.intrinsicWidth = img.width.baseVal.value;
            _this.intrinsicHeight = img.height.baseVal.value;
            _this.context.cache.addImage(_this.svg);
            return _this;
        }
        return SVGElementContainer;
    }(ElementContainer));

    var LIElementContainer = /** @class */ (function (_super) {
        __extends(LIElementContainer, _super);
        function LIElementContainer(context, element) {
            var _this = _super.call(this, context, element) || this;
            _this.value = element.value;
            return _this;
        }
        return LIElementContainer;
    }(ElementContainer));

    var OLElementContainer = /** @class */ (function (_super) {
        __extends(OLElementContainer, _super);
        function OLElementContainer(context, element) {
            var _this = _super.call(this, context, element) || this;
            _this.start = element.start;
            _this.reversed = typeof element.reversed === 'boolean' && element.reversed === true;
            return _this;
        }
        return OLElementContainer;
    }(ElementContainer));

    var CHECKBOX_BORDER_RADIUS = [
        {
            type: 15 /* DIMENSION_TOKEN */,
            flags: 0,
            unit: 'px',
            number: 3
        }
    ];
    var RADIO_BORDER_RADIUS = [
        {
            type: 16 /* PERCENTAGE_TOKEN */,
            flags: 0,
            number: 50
        }
    ];
    var reformatInputBounds = function (bounds) {
        if (bounds.width > bounds.height) {
            return new Bounds(bounds.left + (bounds.width - bounds.height) / 2, bounds.top, bounds.height, bounds.height);
        }
        else if (bounds.width < bounds.height) {
            return new Bounds(bounds.left, bounds.top + (bounds.height - bounds.width) / 2, bounds.width, bounds.width);
        }
        return bounds;
    };
    var getInputValue = function (node) {
        var value = node.type === PASSWORD ? new Array(node.value.length + 1).join('\u2022') : node.value;
        return value.length === 0 ? node.placeholder || '' : value;
    };
    var CHECKBOX = 'checkbox';
    var RADIO = 'radio';
    var PASSWORD = 'password';
    var INPUT_COLOR = 0x2a2a2aff;
    var InputElementContainer = /** @class */ (function (_super) {
        __extends(InputElementContainer, _super);
        function InputElementContainer(context, input) {
            var _this = _super.call(this, context, input) || this;
            _this.type = input.type.toLowerCase();
            _this.checked = input.checked;
            _this.value = getInputValue(input);
            if (_this.type === CHECKBOX || _this.type === RADIO) {
                _this.styles.backgroundColor = 0xdededeff;
                _this.styles.borderTopColor =
                    _this.styles.borderRightColor =
                        _this.styles.borderBottomColor =
                            _this.styles.borderLeftColor =
                                0xa5a5a5ff;
                _this.styles.borderTopWidth =
                    _this.styles.borderRightWidth =
                        _this.styles.borderBottomWidth =
                            _this.styles.borderLeftWidth =
                                1;
                _this.styles.borderTopStyle =
                    _this.styles.borderRightStyle =
                        _this.styles.borderBottomStyle =
                            _this.styles.borderLeftStyle =
                                1 /* SOLID */;
                _this.styles.backgroundClip = [0 /* BORDER_BOX */];
                _this.styles.backgroundOrigin = [0 /* BORDER_BOX */];
                _this.bounds = reformatInputBounds(_this.bounds);
            }
            switch (_this.type) {
                case CHECKBOX:
                    _this.styles.borderTopRightRadius =
                        _this.styles.borderTopLeftRadius =
                            _this.styles.borderBottomRightRadius =
                                _this.styles.borderBottomLeftRadius =
                                    CHECKBOX_BORDER_RADIUS;
                    break;
                case RADIO:
                    _this.styles.borderTopRightRadius =
                        _this.styles.borderTopLeftRadius =
                            _this.styles.borderBottomRightRadius =
                                _this.styles.borderBottomLeftRadius =
                                    RADIO_BORDER_RADIUS;
                    break;
            }
            return _this;
        }
        return InputElementContainer;
    }(ElementContainer));

    var SelectElementContainer = /** @class */ (function (_super) {
        __extends(SelectElementContainer, _super);
        function SelectElementContainer(context, element) {
            var _this = _super.call(this, context, element) || this;
            var option = element.options[element.selectedIndex || 0];
            _this.value = option ? option.text || '' : '';
            return _this;
        }
        return SelectElementContainer;
    }(ElementContainer));

    var TextareaElementContainer = /** @class */ (function (_super) {
        __extends(TextareaElementContainer, _super);
        function TextareaElementContainer(context, element) {
            var _this = _super.call(this, context, element) || this;
            _this.value = element.value;
            return _this;
        }
        return TextareaElementContainer;
    }(ElementContainer));

    var IFrameElementContainer = /** @class */ (function (_super) {
        __extends(IFrameElementContainer, _super);
        function IFrameElementContainer(context, iframe) {
            var _this = _super.call(this, context, iframe) || this;
            _this.src = iframe.src;
            _this.width = parseInt(iframe.width, 10) || 0;
            _this.height = parseInt(iframe.height, 10) || 0;
            _this.backgroundColor = _this.styles.backgroundColor;
            try {
                if (iframe.contentWindow &&
                    iframe.contentWindow.document &&
                    iframe.contentWindow.document.documentElement) {
                    _this.tree = parseTree(context, iframe.contentWindow.document.documentElement);
                    // http://www.w3.org/TR/css3-background/#special-backgrounds
                    var documentBackgroundColor = iframe.contentWindow.document.documentElement
                        ? parseColor(context, getComputedStyle(iframe.contentWindow.document.documentElement).backgroundColor)
                        : COLORS.TRANSPARENT;
                    var bodyBackgroundColor = iframe.contentWindow.document.body
                        ? parseColor(context, getComputedStyle(iframe.contentWindow.document.body).backgroundColor)
                        : COLORS.TRANSPARENT;
                    _this.backgroundColor = isTransparent(documentBackgroundColor)
                        ? isTransparent(bodyBackgroundColor)
                            ? _this.styles.backgroundColor
                            : bodyBackgroundColor
                        : documentBackgroundColor;
                }
            }
            catch (e) { }
            return _this;
        }
        return IFrameElementContainer;
    }(ElementContainer));

    var LIST_OWNERS = ['OL', 'UL', 'MENU'];
    var parseNodeTree = function (context, node, parent, root) {
        for (var childNode = node.firstChild, nextNode = void 0; childNode; childNode = nextNode) {
            nextNode = childNode.nextSibling;
            if (isTextNode(childNode) && childNode.data.trim().length > 0) {
                parent.textNodes.push(new TextContainer(context, childNode, parent.styles));
            }
            else if (isElementNode(childNode)) {
                if (isSlotElement(childNode) && childNode.assignedNodes) {
                    childNode.assignedNodes().forEach(function (childNode) { return parseNodeTree(context, childNode, parent, root); });
                }
                else {
                    var container = createContainer(context, childNode);
                    if (container.styles.isVisible()) {
                        if (createsRealStackingContext(childNode, container, root)) {
                            container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */;
                        }
                        else if (createsStackingContext(container.styles)) {
                            container.flags |= 2 /* CREATES_STACKING_CONTEXT */;
                        }
                        if (LIST_OWNERS.indexOf(childNode.tagName) !== -1) {
                            container.flags |= 8 /* IS_LIST_OWNER */;
                        }
                        parent.elements.push(container);
                        childNode.slot;
                        if (childNode.shadowRoot) {
                            parseNodeTree(context, childNode.shadowRoot, container, root);
                        }
                        else if (!isTextareaElement(childNode) &&
                            !isSVGElement(childNode) &&
                            !isSelectElement(childNode)) {
                            parseNodeTree(context, childNode, container, root);
                        }
                    }
                }
            }
        }
    };
    var createContainer = function (context, element) {
        if (isImageElement(element)) {
            return new ImageElementContainer(context, element);
        }
        if (isCanvasElement(element)) {
            return new CanvasElementContainer(context, element);
        }
        if (isSVGElement(element)) {
            return new SVGElementContainer(context, element);
        }
        if (isLIElement(element)) {
            return new LIElementContainer(context, element);
        }
        if (isOLElement(element)) {
            return new OLElementContainer(context, element);
        }
        if (isInputElement(element)) {
            return new InputElementContainer(context, element);
        }
        if (isSelectElement(element)) {
            return new SelectElementContainer(context, element);
        }
        if (isTextareaElement(element)) {
            return new TextareaElementContainer(context, element);
        }
        if (isIFrameElement(element)) {
            return new IFrameElementContainer(context, element);
        }
        return new ElementContainer(context, element);
    };
    var parseTree = function (context, element) {
        var container = createContainer(context, element);
        container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */;
        parseNodeTree(context, element, container, container);
        return container;
    };
    var createsRealStackingContext = function (node, container, root) {
        return (container.styles.isPositionedWithZIndex() ||
            container.styles.opacity < 1 ||
            container.styles.isTransformed() ||
            (isBodyElement(node) && root.styles.isTransparent()));
    };
    var createsStackingContext = function (styles) { return styles.isPositioned() || styles.isFloating(); };
    var isTextNode = function (node) { return node.nodeType === Node.TEXT_NODE; };
    var isElementNode = function (node) { return node.nodeType === Node.ELEMENT_NODE; };
    var isHTMLElementNode = function (node) {
        return isElementNode(node) && typeof node.style !== 'undefined' && !isSVGElementNode(node);
    };
    var isSVGElementNode = function (element) {
        return typeof element.className === 'object';
    };
    var isLIElement = function (node) { return node.tagName === 'LI'; };
    var isOLElement = function (node) { return node.tagName === 'OL'; };
    var isInputElement = function (node) { return node.tagName === 'INPUT'; };
    var isHTMLElement = function (node) { return node.tagName === 'HTML'; };
    var isSVGElement = function (node) { return node.tagName === 'svg'; };
    var isBodyElement = function (node) { return node.tagName === 'BODY'; };
    var isCanvasElement = function (node) { return node.tagName === 'CANVAS'; };
    var isVideoElement = function (node) { return node.tagName === 'VIDEO'; };
    var isImageElement = function (node) { return node.tagName === 'IMG'; };
    var isIFrameElement = function (node) { return node.tagName === 'IFRAME'; };
    var isStyleElement = function (node) { return node.tagName === 'STYLE'; };
    var isScriptElement = function (node) { return node.tagName === 'SCRIPT'; };
    var isTextareaElement = function (node) { return node.tagName === 'TEXTAREA'; };
    var isSelectElement = function (node) { return node.tagName === 'SELECT'; };
    var isSlotElement = function (node) { return node.tagName === 'SLOT'; };
    // https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name
    var isCustomElement = function (node) { return node.tagName.indexOf('-') > 0; };

    var CounterState = /** @class */ (function () {
        function CounterState() {
            this.counters = {};
        }
        CounterState.prototype.getCounterValue = function (name) {
            var counter = this.counters[name];
            if (counter && counter.length) {
                return counter[counter.length - 1];
            }
            return 1;
        };
        CounterState.prototype.getCounterValues = function (name) {
            var counter = this.counters[name];
            return counter ? counter : [];
        };
        CounterState.prototype.pop = function (counters) {
            var _this = this;
            counters.forEach(function (counter) { return _this.counters[counter].pop(); });
        };
        CounterState.prototype.parse = function (style) {
            var _this = this;
            var counterIncrement = style.counterIncrement;
            var counterReset = style.counterReset;
            var canReset = true;
            if (counterIncrement !== null) {
                counterIncrement.forEach(function (entry) {
                    var counter = _this.counters[entry.counter];
                    if (counter && entry.increment !== 0) {
                        canReset = false;
                        if (!counter.length) {
                            counter.push(1);
                        }
                        counter[Math.max(0, counter.length - 1)] += entry.increment;
                    }
                });
            }
            var counterNames = [];
            if (canReset) {
                counterReset.forEach(function (entry) {
                    var counter = _this.counters[entry.counter];
                    counterNames.push(entry.counter);
                    if (!counter) {
                        counter = _this.counters[entry.counter] = [];
                    }
                    counter.push(entry.reset);
                });
            }
            return counterNames;
        };
        return CounterState;
    }());
    var ROMAN_UPPER = {
        integers: [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
        values: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
    };
    var ARMENIAN = {
        integers: [
            9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70,
            60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
        ],
        values: [
            'Ք',
            'Փ',
            'Ւ',
            'Ց',
            'Ր',
            'Տ',
            'Վ',
            'Ս',
            'Ռ',
            'Ջ',
            'Պ',
            'Չ',
            'Ո',
            'Շ',
            'Ն',
            'Յ',
            'Մ',
            'Ճ',
            'Ղ',
            'Ձ',
            'Հ',
            'Կ',
            'Ծ',
            'Խ',
            'Լ',
            'Ի',
            'Ժ',
            'Թ',
            'Ը',
            'Է',
            'Զ',
            'Ե',
            'Դ',
            'Գ',
            'Բ',
            'Ա'
        ]
    };
    var HEBREW = {
        integers: [
            10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20,
            19, 18, 17, 16, 15, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
        ],
        values: [
            'י׳',
            'ט׳',
            'ח׳',
            'ז׳',
            'ו׳',
            'ה׳',
            'ד׳',
            'ג׳',
            'ב׳',
            'א׳',
            'ת',
            'ש',
            'ר',
            'ק',
            'צ',
            'פ',
            'ע',
            'ס',
            'נ',
            'מ',
            'ל',
            'כ',
            'יט',
            'יח',
            'יז',
            'טז',
            'טו',
            'י',
            'ט',
            'ח',
            'ז',
            'ו',
            'ה',
            'ד',
            'ג',
            'ב',
            'א'
        ]
    };
    var GEORGIAN = {
        integers: [
            10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90,
            80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
        ],
        values: [
            'ჵ',
            'ჰ',
            'ჯ',
            'ჴ',
            'ხ',
            'ჭ',
            'წ',
            'ძ',
            'ც',
            'ჩ',
            'შ',
            'ყ',
            'ღ',
            'ქ',
            'ფ',
            'ჳ',
            'ტ',
            'ს',
            'რ',
            'ჟ',
            'პ',
            'ო',
            'ჲ',
            'ნ',
            'მ',
            'ლ',
            'კ',
            'ი',
            'თ',
            'ჱ',
            'ზ',
            'ვ',
            'ე',
            'დ',
            'გ',
            'ბ',
            'ა'
        ]
    };
    var createAdditiveCounter = function (value, min, max, symbols, fallback, suffix) {
        if (value < min || value > max) {
            return createCounterText(value, fallback, suffix.length > 0);
        }
        return (symbols.integers.reduce(function (string, integer, index) {
            while (value >= integer) {
                value -= integer;
                string += symbols.values[index];
            }
            return string;
        }, '') + suffix);
    };
    var createCounterStyleWithSymbolResolver = function (value, codePointRangeLength, isNumeric, resolver) {
        var string = '';
        do {
            if (!isNumeric) {
                value--;
            }
            string = resolver(value) + string;
            value /= codePointRangeLength;
        } while (value * codePointRangeLength >= codePointRangeLength);
        return string;
    };
    var createCounterStyleFromRange = function (value, codePointRangeStart, codePointRangeEnd, isNumeric, suffix) {
        var codePointRangeLength = codePointRangeEnd - codePointRangeStart + 1;
        return ((value < 0 ? '-' : '') +
            (createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, isNumeric, function (codePoint) {
                return fromCodePoint$1(Math.floor(codePoint % codePointRangeLength) + codePointRangeStart);
            }) +
                suffix));
    };
    var createCounterStyleFromSymbols = function (value, symbols, suffix) {
        if (suffix === void 0) { suffix = '. '; }
        var codePointRangeLength = symbols.length;
        return (createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, false, function (codePoint) { return symbols[Math.floor(codePoint % codePointRangeLength)]; }) + suffix);
    };
    var CJK_ZEROS = 1 << 0;
    var CJK_TEN_COEFFICIENTS = 1 << 1;
    var CJK_TEN_HIGH_COEFFICIENTS = 1 << 2;
    var CJK_HUNDRED_COEFFICIENTS = 1 << 3;
    var createCJKCounter = function (value, numbers, multipliers, negativeSign, suffix, flags) {
        if (value < -9999 || value > 9999) {
            return createCounterText(value, 4 /* CJK_DECIMAL */, suffix.length > 0);
        }
        var tmp = Math.abs(value);
        var string = suffix;
        if (tmp === 0) {
            return numbers[0] + string;
        }
        for (var digit = 0; tmp > 0 && digit <= 4; digit++) {
            var coefficient = tmp % 10;
            if (coefficient === 0 && contains(flags, CJK_ZEROS) && string !== '') {
                string = numbers[coefficient] + string;
            }
            else if (coefficient > 1 ||
                (coefficient === 1 && digit === 0) ||
                (coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_COEFFICIENTS)) ||
                (coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_HIGH_COEFFICIENTS) && value > 100) ||
                (coefficient === 1 && digit > 1 && contains(flags, CJK_HUNDRED_COEFFICIENTS))) {
                string = numbers[coefficient] + (digit > 0 ? multipliers[digit - 1] : '') + string;
            }
            else if (coefficient === 1 && digit > 0) {
                string = multipliers[digit - 1] + string;
            }
            tmp = Math.floor(tmp / 10);
        }
        return (value < 0 ? negativeSign : '') + string;
    };
    var CHINESE_INFORMAL_MULTIPLIERS = '十百千萬';
    var CHINESE_FORMAL_MULTIPLIERS = '拾佰仟萬';
    var JAPANESE_NEGATIVE = 'マイナス';
    var KOREAN_NEGATIVE = '마이너스';
    var createCounterText = function (value, type, appendSuffix) {
        var defaultSuffix = appendSuffix ? '. ' : '';
        var cjkSuffix = appendSuffix ? '、' : '';
        var koreanSuffix = appendSuffix ? ', ' : '';
        var spaceSuffix = appendSuffix ? ' ' : '';
        switch (type) {
            case 0 /* DISC */:
                return '•' + spaceSuffix;
            case 1 /* CIRCLE */:
                return '◦' + spaceSuffix;
            case 2 /* SQUARE */:
                return '◾' + spaceSuffix;
            case 5 /* DECIMAL_LEADING_ZERO */:
                var string = createCounterStyleFromRange(value, 48, 57, true, defaultSuffix);
                return string.length < 4 ? "0" + string : string;
            case 4 /* CJK_DECIMAL */:
                return createCounterStyleFromSymbols(value, '〇一二三四五六七八九', cjkSuffix);
            case 6 /* LOWER_ROMAN */:
                return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, 3 /* DECIMAL */, defaultSuffix).toLowerCase();
            case 7 /* UPPER_ROMAN */:
                return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, 3 /* DECIMAL */, defaultSuffix);
            case 8 /* LOWER_GREEK */:
                return createCounterStyleFromRange(value, 945, 969, false, defaultSuffix);
            case 9 /* LOWER_ALPHA */:
                return createCounterStyleFromRange(value, 97, 122, false, defaultSuffix);
            case 10 /* UPPER_ALPHA */:
                return createCounterStyleFromRange(value, 65, 90, false, defaultSuffix);
            case 11 /* ARABIC_INDIC */:
                return createCounterStyleFromRange(value, 1632, 1641, true, defaultSuffix);
            case 12 /* ARMENIAN */:
            case 49 /* UPPER_ARMENIAN */:
                return createAdditiveCounter(value, 1, 9999, ARMENIAN, 3 /* DECIMAL */, defaultSuffix);
            case 35 /* LOWER_ARMENIAN */:
                return createAdditiveCounter(value, 1, 9999, ARMENIAN, 3 /* DECIMAL */, defaultSuffix).toLowerCase();
            case 13 /* BENGALI */:
                return createCounterStyleFromRange(value, 2534, 2543, true, defaultSuffix);
            case 14 /* CAMBODIAN */:
            case 30 /* KHMER */:
                return createCounterStyleFromRange(value, 6112, 6121, true, defaultSuffix);
            case 15 /* CJK_EARTHLY_BRANCH */:
                return createCounterStyleFromSymbols(value, '子丑寅卯辰巳午未申酉戌亥', cjkSuffix);
            case 16 /* CJK_HEAVENLY_STEM */:
                return createCounterStyleFromSymbols(value, '甲乙丙丁戊己庚辛壬癸', cjkSuffix);
            case 17 /* CJK_IDEOGRAPHIC */:
            case 48 /* TRAD_CHINESE_INFORMAL */:
                return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
            case 47 /* TRAD_CHINESE_FORMAL */:
                return createCJKCounter(value, '零壹貳參肆伍陸柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
            case 42 /* SIMP_CHINESE_INFORMAL */:
                return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
            case 41 /* SIMP_CHINESE_FORMAL */:
                return createCJKCounter(value, '零壹贰叁肆伍陆柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
            case 26 /* JAPANESE_INFORMAL */:
                return createCJKCounter(value, '〇一二三四五六七八九', '十百千万', JAPANESE_NEGATIVE, cjkSuffix, 0);
            case 25 /* JAPANESE_FORMAL */:
                return createCJKCounter(value, '零壱弐参四伍六七八九', '拾百千万', JAPANESE_NEGATIVE, cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
            case 31 /* KOREAN_HANGUL_FORMAL */:
                return createCJKCounter(value, '영일이삼사오육칠팔구', '십백천만', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
            case 33 /* KOREAN_HANJA_INFORMAL */:
                return createCJKCounter(value, '零一二三四五六七八九', '十百千萬', KOREAN_NEGATIVE, koreanSuffix, 0);
            case 32 /* KOREAN_HANJA_FORMAL */:
                return createCJKCounter(value, '零壹貳參四五六七八九', '拾百千', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
            case 18 /* DEVANAGARI */:
                return createCounterStyleFromRange(value, 0x966, 0x96f, true, defaultSuffix);
            case 20 /* GEORGIAN */:
                return createAdditiveCounter(value, 1, 19999, GEORGIAN, 3 /* DECIMAL */, defaultSuffix);
            case 21 /* GUJARATI */:
                return createCounterStyleFromRange(value, 0xae6, 0xaef, true, defaultSuffix);
            case 22 /* GURMUKHI */:
                return createCounterStyleFromRange(value, 0xa66, 0xa6f, true, defaultSuffix);
            case 22 /* HEBREW */:
                return createAdditiveCounter(value, 1, 10999, HEBREW, 3 /* DECIMAL */, defaultSuffix);
            case 23 /* HIRAGANA */:
                return createCounterStyleFromSymbols(value, 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん');
            case 24 /* HIRAGANA_IROHA */:
                return createCounterStyleFromSymbols(value, 'いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす');
            case 27 /* KANNADA */:
                return createCounterStyleFromRange(value, 0xce6, 0xcef, true, defaultSuffix);
            case 28 /* KATAKANA */:
                return createCounterStyleFromSymbols(value, 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン', cjkSuffix);
            case 29 /* KATAKANA_IROHA */:
                return createCounterStyleFromSymbols(value, 'イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス', cjkSuffix);
            case 34 /* LAO */:
                return createCounterStyleFromRange(value, 0xed0, 0xed9, true, defaultSuffix);
            case 37 /* MONGOLIAN */:
                return createCounterStyleFromRange(value, 0x1810, 0x1819, true, defaultSuffix);
            case 38 /* MYANMAR */:
                return createCounterStyleFromRange(value, 0x1040, 0x1049, true, defaultSuffix);
            case 39 /* ORIYA */:
                return createCounterStyleFromRange(value, 0xb66, 0xb6f, true, defaultSuffix);
            case 40 /* PERSIAN */:
                return createCounterStyleFromRange(value, 0x6f0, 0x6f9, true, defaultSuffix);
            case 43 /* TAMIL */:
                return createCounterStyleFromRange(value, 0xbe6, 0xbef, true, defaultSuffix);
            case 44 /* TELUGU */:
                return createCounterStyleFromRange(value, 0xc66, 0xc6f, true, defaultSuffix);
            case 45 /* THAI */:
                return createCounterStyleFromRange(value, 0xe50, 0xe59, true, defaultSuffix);
            case 46 /* TIBETAN */:
                return createCounterStyleFromRange(value, 0xf20, 0xf29, true, defaultSuffix);
            case 3 /* DECIMAL */:
            default:
                return createCounterStyleFromRange(value, 48, 57, true, defaultSuffix);
        }
    };

    var IGNORE_ATTRIBUTE = 'data-html2canvas-ignore';
    var DocumentCloner = /** @class */ (function () {
        function DocumentCloner(context, element, options) {
            this.context = context;
            this.options = options;
            this.scrolledElements = [];
            this.referenceElement = element;
            this.counters = new CounterState();
            this.quoteDepth = 0;
            if (!element.ownerDocument) {
                throw new Error('Cloned element does not have an owner document');
            }
            this.documentElement = this.cloneNode(element.ownerDocument.documentElement, false);
        }
        DocumentCloner.prototype.toIFrame = function (ownerDocument, windowSize) {
            var _this = this;
            var iframe = createIFrameContainer(ownerDocument, windowSize);
            if (!iframe.contentWindow) {
                return Promise.reject("Unable to find iframe window");
            }
            var scrollX = ownerDocument.defaultView.pageXOffset;
            var scrollY = ownerDocument.defaultView.pageYOffset;
            var cloneWindow = iframe.contentWindow;
            var documentClone = cloneWindow.document;
            /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
             if window url is about:blank, we can assign the url to current by writing onto the document
             */
            var iframeLoad = iframeLoader(iframe).then(function () { return __awaiter(_this, void 0, void 0, function () {
                var onclone, referenceElement;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.scrolledElements.forEach(restoreNodeScroll);
                            if (cloneWindow) {
                                cloneWindow.scrollTo(windowSize.left, windowSize.top);
                                if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent) &&
                                    (cloneWindow.scrollY !== windowSize.top || cloneWindow.scrollX !== windowSize.left)) {
                                    this.context.logger.warn('Unable to restore scroll position for cloned document');
                                    this.context.windowBounds = this.context.windowBounds.add(cloneWindow.scrollX - windowSize.left, cloneWindow.scrollY - windowSize.top, 0, 0);
                                }
                            }
                            onclone = this.options.onclone;
                            referenceElement = this.clonedReferenceElement;
                            if (typeof referenceElement === 'undefined') {
                                return [2 /*return*/, Promise.reject("Error finding the " + this.referenceElement.nodeName + " in the cloned document")];
                            }
                            if (!(documentClone.fonts && documentClone.fonts.ready)) return [3 /*break*/, 2];
                            return [4 /*yield*/, documentClone.fonts.ready];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2:
                            if (!/(AppleWebKit)/g.test(navigator.userAgent)) return [3 /*break*/, 4];
                            return [4 /*yield*/, imagesReady(documentClone)];
                        case 3:
                            _a.sent();
                            _a.label = 4;
                        case 4:
                            if (typeof onclone === 'function') {
                                return [2 /*return*/, Promise.resolve()
                                        .then(function () { return onclone(documentClone, referenceElement); })
                                        .then(function () { return iframe; })];
                            }
                            return [2 /*return*/, iframe];
                    }
                });
            }); });
            documentClone.open();
            documentClone.write(serializeDoctype(document.doctype) + "<html></html>");
            // Chrome scrolls the parent document for some reason after the write to the cloned window???
            restoreOwnerScroll(this.referenceElement.ownerDocument, scrollX, scrollY);
            documentClone.replaceChild(documentClone.adoptNode(this.documentElement), documentClone.documentElement);
            documentClone.close();
            return iframeLoad;
        };
        DocumentCloner.prototype.createElementClone = function (node) {
            if (isDebugging(node, 2 /* CLONE */)) {
                debugger;
            }
            if (isCanvasElement(node)) {
                return this.createCanvasClone(node);
            }
            if (isVideoElement(node)) {
                return this.createVideoClone(node);
            }
            if (isStyleElement(node)) {
                return this.createStyleClone(node);
            }
            var clone = node.cloneNode(false);
            if (isImageElement(clone)) {
                if (isImageElement(node) && node.currentSrc && node.currentSrc !== node.src) {
                    clone.src = node.currentSrc;
                    clone.srcset = '';
                }
                if (clone.loading === 'lazy') {
                    clone.loading = 'eager';
                }
            }
            if (isCustomElement(clone)) {
                return this.createCustomElementClone(clone);
            }
            return clone;
        };
        DocumentCloner.prototype.createCustomElementClone = function (node) {
            var clone = document.createElement('html2canvascustomelement');
            copyCSSStyles(node.style, clone);
            return clone;
        };
        DocumentCloner.prototype.createStyleClone = function (node) {
            try {
                var sheet = node.sheet;
                if (sheet && sheet.cssRules) {
                    var css = [].slice.call(sheet.cssRules, 0).reduce(function (css, rule) {
                        if (rule && typeof rule.cssText === 'string') {
                            return css + rule.cssText;
                        }
                        return css;
                    }, '');
                    var style = node.cloneNode(false);
                    style.textContent = css;
                    return style;
                }
            }
            catch (e) {
                // accessing node.sheet.cssRules throws a DOMException
                this.context.logger.error('Unable to access cssRules property', e);
                if (e.name !== 'SecurityError') {
                    throw e;
                }
            }
            return node.cloneNode(false);
        };
        DocumentCloner.prototype.createCanvasClone = function (canvas) {
            var _a;
            if (this.options.inlineImages && canvas.ownerDocument) {
                var img = canvas.ownerDocument.createElement('img');
                try {
                    img.src = canvas.toDataURL();
                    return img;
                }
                catch (e) {
                    this.context.logger.info("Unable to inline canvas contents, canvas is tainted", canvas);
                }
            }
            var clonedCanvas = canvas.cloneNode(false);
            try {
                clonedCanvas.width = canvas.width;
                clonedCanvas.height = canvas.height;
                var ctx = canvas.getContext('2d');
                var clonedCtx = clonedCanvas.getContext('2d');
                if (clonedCtx) {
                    if (!this.options.allowTaint && ctx) {
                        clonedCtx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
                    }
                    else {
                        var gl = (_a = canvas.getContext('webgl2')) !== null && _a !== void 0 ? _a : canvas.getContext('webgl');
                        if (gl) {
                            var attribs = gl.getContextAttributes();
                            if ((attribs === null || attribs === void 0 ? void 0 : attribs.preserveDrawingBuffer) === false) {
                                this.context.logger.warn('Unable to clone WebGL context as it has preserveDrawingBuffer=false', canvas);
                            }
                        }
                        clonedCtx.drawImage(canvas, 0, 0);
                    }
                }
                return clonedCanvas;
            }
            catch (e) {
                this.context.logger.info("Unable to clone canvas as it is tainted", canvas);
            }
            return clonedCanvas;
        };
        DocumentCloner.prototype.createVideoClone = function (video) {
            var canvas = video.ownerDocument.createElement('canvas');
            canvas.width = video.offsetWidth;
            canvas.height = video.offsetHeight;
            var ctx = canvas.getContext('2d');
            try {
                if (ctx) {
                    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                    if (!this.options.allowTaint) {
                        ctx.getImageData(0, 0, canvas.width, canvas.height);
                    }
                }
                return canvas;
            }
            catch (e) {
                this.context.logger.info("Unable to clone video as it is tainted", video);
            }
            var blankCanvas = video.ownerDocument.createElement('canvas');
            blankCanvas.width = video.offsetWidth;
            blankCanvas.height = video.offsetHeight;
            return blankCanvas;
        };
        DocumentCloner.prototype.appendChildNode = function (clone, child, copyStyles) {
            if (!isElementNode(child) ||
                (!isScriptElement(child) &&
                    !child.hasAttribute(IGNORE_ATTRIBUTE) &&
                    (typeof this.options.ignoreElements !== 'function' || !this.options.ignoreElements(child)))) {
                if (!this.options.copyStyles || !isElementNode(child) || !isStyleElement(child)) {
                    clone.appendChild(this.cloneNode(child, copyStyles));
                }
            }
        };
        DocumentCloner.prototype.cloneChildNodes = function (node, clone, copyStyles) {
            var _this = this;
            for (var child = node.shadowRoot ? node.shadowRoot.firstChild : node.firstChild; child; child = child.nextSibling) {
                if (isElementNode(child) && isSlotElement(child) && typeof child.assignedNodes === 'function') {
                    var assignedNodes = child.assignedNodes();
                    if (assignedNodes.length) {
                        assignedNodes.forEach(function (assignedNode) { return _this.appendChildNode(clone, assignedNode, copyStyles); });
                    }
                }
                else {
                    this.appendChildNode(clone, child, copyStyles);
                }
            }
        };
        DocumentCloner.prototype.cloneNode = function (node, copyStyles) {
            if (isTextNode(node)) {
                return document.createTextNode(node.data);
            }
            if (!node.ownerDocument) {
                return node.cloneNode(false);
            }
            var window = node.ownerDocument.defaultView;
            if (window && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) {
                var clone = this.createElementClone(node);
                clone.style.transitionProperty = 'none';
                var style = window.getComputedStyle(node);
                var styleBefore = window.getComputedStyle(node, ':before');
                var styleAfter = window.getComputedStyle(node, ':after');
                if (this.referenceElement === node && isHTMLElementNode(clone)) {
                    this.clonedReferenceElement = clone;
                }
                if (isBodyElement(clone)) {
                    createPseudoHideStyles(clone);
                }
                var counters = this.counters.parse(new CSSParsedCounterDeclaration(this.context, style));
                var before = this.resolvePseudoContent(node, clone, styleBefore, PseudoElementType.BEFORE);
                if (isCustomElement(node)) {
                    copyStyles = true;
                }
                if (!isVideoElement(node)) {
                    this.cloneChildNodes(node, clone, copyStyles);
                }
                if (before) {
                    clone.insertBefore(before, clone.firstChild);
                }
                var after = this.resolvePseudoContent(node, clone, styleAfter, PseudoElementType.AFTER);
                if (after) {
                    clone.appendChild(after);
                }
                this.counters.pop(counters);
                if ((style && (this.options.copyStyles || isSVGElementNode(node)) && !isIFrameElement(node)) ||
                    copyStyles) {
                    copyCSSStyles(style, clone);
                }
                if (node.scrollTop !== 0 || node.scrollLeft !== 0) {
                    this.scrolledElements.push([clone, node.scrollLeft, node.scrollTop]);
                }
                if ((isTextareaElement(node) || isSelectElement(node)) &&
                    (isTextareaElement(clone) || isSelectElement(clone))) {
                    clone.value = node.value;
                }
                return clone;
            }
            return node.cloneNode(false);
        };
        DocumentCloner.prototype.resolvePseudoContent = function (node, clone, style, pseudoElt) {
            var _this = this;
            if (!style) {
                return;
            }
            var value = style.content;
            var document = clone.ownerDocument;
            if (!document || !value || value === 'none' || value === '-moz-alt-content' || style.display === 'none') {
                return;
            }
            this.counters.parse(new CSSParsedCounterDeclaration(this.context, style));
            var declaration = new CSSParsedPseudoDeclaration(this.context, style);
            var anonymousReplacedElement = document.createElement('html2canvaspseudoelement');
            copyCSSStyles(style, anonymousReplacedElement);
            declaration.content.forEach(function (token) {
                if (token.type === 0 /* STRING_TOKEN */) {
                    anonymousReplacedElement.appendChild(document.createTextNode(token.value));
                }
                else if (token.type === 22 /* URL_TOKEN */) {
                    var img = document.createElement('img');
                    img.src = token.value;
                    img.style.opacity = '1';
                    anonymousReplacedElement.appendChild(img);
                }
                else if (token.type === 18 /* FUNCTION */) {
                    if (token.name === 'attr') {
                        var attr = token.values.filter(isIdentToken);
                        if (attr.length) {
                            anonymousReplacedElement.appendChild(document.createTextNode(node.getAttribute(attr[0].value) || ''));
                        }
                    }
                    else if (token.name === 'counter') {
                        var _a = token.values.filter(nonFunctionArgSeparator), counter = _a[0], counterStyle = _a[1];
                        if (counter && isIdentToken(counter)) {
                            var counterState = _this.counters.getCounterValue(counter.value);
                            var counterType = counterStyle && isIdentToken(counterStyle)
                                ? listStyleType.parse(_this.context, counterStyle.value)
                                : 3 /* DECIMAL */;
                            anonymousReplacedElement.appendChild(document.createTextNode(createCounterText(counterState, counterType, false)));
                        }
                    }
                    else if (token.name === 'counters') {
                        var _b = token.values.filter(nonFunctionArgSeparator), counter = _b[0], delim = _b[1], counterStyle = _b[2];
                        if (counter && isIdentToken(counter)) {
                            var counterStates = _this.counters.getCounterValues(counter.value);
                            var counterType_1 = counterStyle && isIdentToken(counterStyle)
                                ? listStyleType.parse(_this.context, counterStyle.value)
                                : 3 /* DECIMAL */;
                            var separator = delim && delim.type === 0 /* STRING_TOKEN */ ? delim.value : '';
                            var text = counterStates
                                .map(function (value) { return createCounterText(value, counterType_1, false); })
                                .join(separator);
                            anonymousReplacedElement.appendChild(document.createTextNode(text));
                        }
                    }
                    else ;
                }
                else if (token.type === 20 /* IDENT_TOKEN */) {
                    switch (token.value) {
                        case 'open-quote':
                            anonymousReplacedElement.appendChild(document.createTextNode(getQuote(declaration.quotes, _this.quoteDepth++, true)));
                            break;
                        case 'close-quote':
                            anonymousReplacedElement.appendChild(document.createTextNode(getQuote(declaration.quotes, --_this.quoteDepth, false)));
                            break;
                        default:
                            // safari doesn't parse string tokens correctly because of lack of quotes
                            anonymousReplacedElement.appendChild(document.createTextNode(token.value));
                    }
                }
            });
            anonymousReplacedElement.className = PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
            var newClassName = pseudoElt === PseudoElementType.BEFORE
                ? " " + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE
                : " " + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
            if (isSVGElementNode(clone)) {
                clone.className.baseValue += newClassName;
            }
            else {
                clone.className += newClassName;
            }
            return anonymousReplacedElement;
        };
        DocumentCloner.destroy = function (container) {
            if (container.parentNode) {
                container.parentNode.removeChild(container);
                return true;
            }
            return false;
        };
        return DocumentCloner;
    }());
    var PseudoElementType;
    (function (PseudoElementType) {
        PseudoElementType[PseudoElementType["BEFORE"] = 0] = "BEFORE";
        PseudoElementType[PseudoElementType["AFTER"] = 1] = "AFTER";
    })(PseudoElementType || (PseudoElementType = {}));
    var createIFrameContainer = function (ownerDocument, bounds) {
        var cloneIframeContainer = ownerDocument.createElement('iframe');
        cloneIframeContainer.className = 'html2canvas-container';
        cloneIframeContainer.style.visibility = 'hidden';
        cloneIframeContainer.style.position = 'fixed';
        cloneIframeContainer.style.left = '-10000px';
        cloneIframeContainer.style.top = '0px';
        cloneIframeContainer.style.border = '0';
        cloneIframeContainer.width = bounds.width.toString();
        cloneIframeContainer.height = bounds.height.toString();
        cloneIframeContainer.scrolling = 'no'; // ios won't scroll without it
        cloneIframeContainer.setAttribute(IGNORE_ATTRIBUTE, 'true');
        ownerDocument.body.appendChild(cloneIframeContainer);
        return cloneIframeContainer;
    };
    var imageReady = function (img) {
        return new Promise(function (resolve) {
            if (img.complete) {
                resolve();
                return;
            }
            if (!img.src) {
                resolve();
                return;
            }
            img.onload = resolve;
            img.onerror = resolve;
        });
    };
    var imagesReady = function (document) {
        return Promise.all([].slice.call(document.images, 0).map(imageReady));
    };
    var iframeLoader = function (iframe) {
        return new Promise(function (resolve, reject) {
            var cloneWindow = iframe.contentWindow;
            if (!cloneWindow) {
                return reject("No window assigned for iframe");
            }
            var documentClone = cloneWindow.document;
            cloneWindow.onload = iframe.onload = function () {
                cloneWindow.onload = iframe.onload = null;
                var interval = setInterval(function () {
                    if (documentClone.body.childNodes.length > 0 && documentClone.readyState === 'complete') {
                        clearInterval(interval);
                        resolve(iframe);
                    }
                }, 50);
            };
        });
    };
    var ignoredStyleProperties = [
        'all',
        'd',
        'content' // Safari shows pseudoelements if content is set
    ];
    var copyCSSStyles = function (style, target) {
        // Edge does not provide value for cssText
        for (var i = style.length - 1; i >= 0; i--) {
            var property = style.item(i);
            if (ignoredStyleProperties.indexOf(property) === -1) {
                target.style.setProperty(property, style.getPropertyValue(property));
            }
        }
        return target;
    };
    var serializeDoctype = function (doctype) {
        var str = '';
        if (doctype) {
            str += '<!DOCTYPE ';
            if (doctype.name) {
                str += doctype.name;
            }
            if (doctype.internalSubset) {
                str += doctype.internalSubset;
            }
            if (doctype.publicId) {
                str += "\"" + doctype.publicId + "\"";
            }
            if (doctype.systemId) {
                str += "\"" + doctype.systemId + "\"";
            }
            str += '>';
        }
        return str;
    };
    var restoreOwnerScroll = function (ownerDocument, x, y) {
        if (ownerDocument &&
            ownerDocument.defaultView &&
            (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
            ownerDocument.defaultView.scrollTo(x, y);
        }
    };
    var restoreNodeScroll = function (_a) {
        var element = _a[0], x = _a[1], y = _a[2];
        element.scrollLeft = x;
        element.scrollTop = y;
    };
    var PSEUDO_BEFORE = ':before';
    var PSEUDO_AFTER = ':after';
    var PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = '___html2canvas___pseudoelement_before';
    var PSEUDO_HIDE_ELEMENT_CLASS_AFTER = '___html2canvas___pseudoelement_after';
    var PSEUDO_HIDE_ELEMENT_STYLE = "{\n    content: \"\" !important;\n    display: none !important;\n}";
    var createPseudoHideStyles = function (body) {
        createStyles(body, "." + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + PSEUDO_BEFORE + PSEUDO_HIDE_ELEMENT_STYLE + "\n         ." + PSEUDO_HIDE_ELEMENT_CLASS_AFTER + PSEUDO_AFTER + PSEUDO_HIDE_ELEMENT_STYLE);
    };
    var createStyles = function (body, styles) {
        var document = body.ownerDocument;
        if (document) {
            var style = document.createElement('style');
            style.textContent = styles;
            body.appendChild(style);
        }
    };

    var CacheStorage = /** @class */ (function () {
        function CacheStorage() {
        }
        CacheStorage.getOrigin = function (url) {
            var link = CacheStorage._link;
            if (!link) {
                return 'about:blank';
            }
            link.href = url;
            link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
            return link.protocol + link.hostname + link.port;
        };
        CacheStorage.isSameOrigin = function (src) {
            return CacheStorage.getOrigin(src) === CacheStorage._origin;
        };
        CacheStorage.setContext = function (window) {
            CacheStorage._link = window.document.createElement('a');
            CacheStorage._origin = CacheStorage.getOrigin(window.location.href);
        };
        CacheStorage._origin = 'about:blank';
        return CacheStorage;
    }());
    var Cache = /** @class */ (function () {
        function Cache(context, _options) {
            this.context = context;
            this._options = _options;
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            this._cache = {};
        }
        Cache.prototype.addImage = function (src) {
            var result = Promise.resolve();
            if (this.has(src)) {
                return result;
            }
            if (isBlobImage(src) || isRenderable(src)) {
                (this._cache[src] = this.loadImage(src)).catch(function () {
                    // prevent unhandled rejection
                });
                return result;
            }
            return result;
        };
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        Cache.prototype.match = function (src) {
            return this._cache[src];
        };
        Cache.prototype.loadImage = function (key) {
            return __awaiter(this, void 0, void 0, function () {
                var isSameOrigin, useCORS, useProxy, src;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            isSameOrigin = CacheStorage.isSameOrigin(key);
                            useCORS = !isInlineImage(key) && this._options.useCORS === true && FEATURES.SUPPORT_CORS_IMAGES && !isSameOrigin;
                            useProxy = !isInlineImage(key) &&
                                !isSameOrigin &&
                                !isBlobImage(key) &&
                                typeof this._options.proxy === 'string' &&
                                FEATURES.SUPPORT_CORS_XHR &&
                                !useCORS;
                            if (!isSameOrigin &&
                                this._options.allowTaint === false &&
                                !isInlineImage(key) &&
                                !isBlobImage(key) &&
                                !useProxy &&
                                !useCORS) {
                                return [2 /*return*/];
                            }
                            src = key;
                            if (!useProxy) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.proxy(src)];
                        case 1:
                            src = _a.sent();
                            _a.label = 2;
                        case 2:
                            this.context.logger.debug("Added image " + key.substring(0, 256));
                            return [4 /*yield*/, new Promise(function (resolve, reject) {
                                    var img = new Image();
                                    img.onload = function () { return resolve(img); };
                                    img.onerror = reject;
                                    //ios safari 10.3 taints canvas with data urls unless crossOrigin is set to anonymous
                                    if (isInlineBase64Image(src) || useCORS) {
                                        img.crossOrigin = 'anonymous';
                                    }
                                    img.src = src;
                                    if (img.complete === true) {
                                        // Inline XML images may fail to parse, throwing an Error later on
                                        setTimeout(function () { return resolve(img); }, 500);
                                    }
                                    if (_this._options.imageTimeout > 0) {
                                        setTimeout(function () { return reject("Timed out (" + _this._options.imageTimeout + "ms) loading image"); }, _this._options.imageTimeout);
                                    }
                                })];
                        case 3: return [2 /*return*/, _a.sent()];
                    }
                });
            });
        };
        Cache.prototype.has = function (key) {
            return typeof this._cache[key] !== 'undefined';
        };
        Cache.prototype.keys = function () {
            return Promise.resolve(Object.keys(this._cache));
        };
        Cache.prototype.proxy = function (src) {
            var _this = this;
            var proxy = this._options.proxy;
            if (!proxy) {
                throw new Error('No proxy defined');
            }
            var key = src.substring(0, 256);
            return new Promise(function (resolve, reject) {
                var responseType = FEATURES.SUPPORT_RESPONSE_TYPE ? 'blob' : 'text';
                var xhr = new XMLHttpRequest();
                xhr.onload = function () {
                    if (xhr.status === 200) {
                        if (responseType === 'text') {
                            resolve(xhr.response);
                        }
                        else {
                            var reader_1 = new FileReader();
                            reader_1.addEventListener('load', function () { return resolve(reader_1.result); }, false);
                            reader_1.addEventListener('error', function (e) { return reject(e); }, false);
                            reader_1.readAsDataURL(xhr.response);
                        }
                    }
                    else {
                        reject("Failed to proxy resource " + key + " with status code " + xhr.status);
                    }
                };
                xhr.onerror = reject;
                var queryString = proxy.indexOf('?') > -1 ? '&' : '?';
                xhr.open('GET', "" + proxy + queryString + "url=" + encodeURIComponent(src) + "&responseType=" + responseType);
                if (responseType !== 'text' && xhr instanceof XMLHttpRequest) {
                    xhr.responseType = responseType;
                }
                if (_this._options.imageTimeout) {
                    var timeout_1 = _this._options.imageTimeout;
                    xhr.timeout = timeout_1;
                    xhr.ontimeout = function () { return reject("Timed out (" + timeout_1 + "ms) proxying " + key); };
                }
                xhr.send();
            });
        };
        return Cache;
    }());
    var INLINE_SVG = /^data:image\/svg\+xml/i;
    var INLINE_BASE64 = /^data:image\/.*;base64,/i;
    var INLINE_IMG = /^data:image\/.*/i;
    var isRenderable = function (src) { return FEATURES.SUPPORT_SVG_DRAWING || !isSVG(src); };
    var isInlineImage = function (src) { return INLINE_IMG.test(src); };
    var isInlineBase64Image = function (src) { return INLINE_BASE64.test(src); };
    var isBlobImage = function (src) { return src.substr(0, 4) === 'blob'; };
    var isSVG = function (src) { return src.substr(-3).toLowerCase() === 'svg' || INLINE_SVG.test(src); };

    var Vector = /** @class */ (function () {
        function Vector(x, y) {
            this.type = 0 /* VECTOR */;
            this.x = x;
            this.y = y;
        }
        Vector.prototype.add = function (deltaX, deltaY) {
            return new Vector(this.x + deltaX, this.y + deltaY);
        };
        return Vector;
    }());

    var lerp = function (a, b, t) {
        return new Vector(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
    };
    var BezierCurve = /** @class */ (function () {
        function BezierCurve(start, startControl, endControl, end) {
            this.type = 1 /* BEZIER_CURVE */;
            this.start = start;
            this.startControl = startControl;
            this.endControl = endControl;
            this.end = end;
        }
        BezierCurve.prototype.subdivide = function (t, firstHalf) {
            var ab = lerp(this.start, this.startControl, t);
            var bc = lerp(this.startControl, this.endControl, t);
            var cd = lerp(this.endControl, this.end, t);
            var abbc = lerp(ab, bc, t);
            var bccd = lerp(bc, cd, t);
            var dest = lerp(abbc, bccd, t);
            return firstHalf ? new BezierCurve(this.start, ab, abbc, dest) : new BezierCurve(dest, bccd, cd, this.end);
        };
        BezierCurve.prototype.add = function (deltaX, deltaY) {
            return new BezierCurve(this.start.add(deltaX, deltaY), this.startControl.add(deltaX, deltaY), this.endControl.add(deltaX, deltaY), this.end.add(deltaX, deltaY));
        };
        BezierCurve.prototype.reverse = function () {
            return new BezierCurve(this.end, this.endControl, this.startControl, this.start);
        };
        return BezierCurve;
    }());
    var isBezierCurve = function (path) { return path.type === 1 /* BEZIER_CURVE */; };

    var BoundCurves = /** @class */ (function () {
        function BoundCurves(element) {
            var styles = element.styles;
            var bounds = element.bounds;
            var _a = getAbsoluteValueForTuple(styles.borderTopLeftRadius, bounds.width, bounds.height), tlh = _a[0], tlv = _a[1];
            var _b = getAbsoluteValueForTuple(styles.borderTopRightRadius, bounds.width, bounds.height), trh = _b[0], trv = _b[1];
            var _c = getAbsoluteValueForTuple(styles.borderBottomRightRadius, bounds.width, bounds.height), brh = _c[0], brv = _c[1];
            var _d = getAbsoluteValueForTuple(styles.borderBottomLeftRadius, bounds.width, bounds.height), blh = _d[0], blv = _d[1];
            var factors = [];
            factors.push((tlh + trh) / bounds.width);
            factors.push((blh + brh) / bounds.width);
            factors.push((tlv + blv) / bounds.height);
            factors.push((trv + brv) / bounds.height);
            var maxFactor = Math.max.apply(Math, factors);
            if (maxFactor > 1) {
                tlh /= maxFactor;
                tlv /= maxFactor;
                trh /= maxFactor;
                trv /= maxFactor;
                brh /= maxFactor;
                brv /= maxFactor;
                blh /= maxFactor;
                blv /= maxFactor;
            }
            var topWidth = bounds.width - trh;
            var rightHeight = bounds.height - brv;
            var bottomWidth = bounds.width - brh;
            var leftHeight = bounds.height - blv;
            var borderTopWidth = styles.borderTopWidth;
            var borderRightWidth = styles.borderRightWidth;
            var borderBottomWidth = styles.borderBottomWidth;
            var borderLeftWidth = styles.borderLeftWidth;
            var paddingTop = getAbsoluteValue(styles.paddingTop, element.bounds.width);
            var paddingRight = getAbsoluteValue(styles.paddingRight, element.bounds.width);
            var paddingBottom = getAbsoluteValue(styles.paddingBottom, element.bounds.width);
            var paddingLeft = getAbsoluteValue(styles.paddingLeft, element.bounds.width);
            this.topLeftBorderDoubleOuterBox =
                tlh > 0 || tlv > 0
                    ? getCurvePoints(bounds.left + borderLeftWidth / 3, bounds.top + borderTopWidth / 3, tlh - borderLeftWidth / 3, tlv - borderTopWidth / 3, CORNER.TOP_LEFT)
                    : new Vector(bounds.left + borderLeftWidth / 3, bounds.top + borderTopWidth / 3);
            this.topRightBorderDoubleOuterBox =
                tlh > 0 || tlv > 0
                    ? getCurvePoints(bounds.left + topWidth, bounds.top + borderTopWidth / 3, trh - borderRightWidth / 3, trv - borderTopWidth / 3, CORNER.TOP_RIGHT)
                    : new Vector(bounds.left + bounds.width - borderRightWidth / 3, bounds.top + borderTopWidth / 3);
            this.bottomRightBorderDoubleOuterBox =
                brh > 0 || brv > 0
                    ? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh - borderRightWidth / 3, brv - borderBottomWidth / 3, CORNER.BOTTOM_RIGHT)
                    : new Vector(bounds.left + bounds.width - borderRightWidth / 3, bounds.top + bounds.height - borderBottomWidth / 3);
            this.bottomLeftBorderDoubleOuterBox =
                blh > 0 || blv > 0
                    ? getCurvePoints(bounds.left + borderLeftWidth / 3, bounds.top + leftHeight, blh - borderLeftWidth / 3, blv - borderBottomWidth / 3, CORNER.BOTTOM_LEFT)
                    : new Vector(bounds.left + borderLeftWidth / 3, bounds.top + bounds.height - borderBottomWidth / 3);
            this.topLeftBorderDoubleInnerBox =
                tlh > 0 || tlv > 0
                    ? getCurvePoints(bounds.left + (borderLeftWidth * 2) / 3, bounds.top + (borderTopWidth * 2) / 3, tlh - (borderLeftWidth * 2) / 3, tlv - (borderTopWidth * 2) / 3, CORNER.TOP_LEFT)
                    : new Vector(bounds.left + (borderLeftWidth * 2) / 3, bounds.top + (borderTopWidth * 2) / 3);
            this.topRightBorderDoubleInnerBox =
                tlh > 0 || tlv > 0
                    ? getCurvePoints(bounds.left + topWidth, bounds.top + (borderTopWidth * 2) / 3, trh - (borderRightWidth * 2) / 3, trv - (borderTopWidth * 2) / 3, CORNER.TOP_RIGHT)
                    : new Vector(bounds.left + bounds.width - (borderRightWidth * 2) / 3, bounds.top + (borderTopWidth * 2) / 3);
            this.bottomRightBorderDoubleInnerBox =
                brh > 0 || brv > 0
                    ? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh - (borderRightWidth * 2) / 3, brv - (borderBottomWidth * 2) / 3, CORNER.BOTTOM_RIGHT)
                    : new Vector(bounds.left + bounds.width - (borderRightWidth * 2) / 3, bounds.top + bounds.height - (borderBottomWidth * 2) / 3);
            this.bottomLeftBorderDoubleInnerBox =
                blh > 0 || blv > 0
                    ? getCurvePoints(bounds.left + (borderLeftWidth * 2) / 3, bounds.top + leftHeight, blh - (borderLeftWidth * 2) / 3, blv - (borderBottomWidth * 2) / 3, CORNER.BOTTOM_LEFT)
                    : new Vector(bounds.left + (borderLeftWidth * 2) / 3, bounds.top + bounds.height - (borderBottomWidth * 2) / 3);
            this.topLeftBorderStroke =
                tlh > 0 || tlv > 0
                    ? getCurvePoints(bounds.left + borderLeftWidth / 2, bounds.top + borderTopWidth / 2, tlh - borderLeftWidth / 2, tlv - borderTopWidth / 2, CORNER.TOP_LEFT)
                    : new Vector(bounds.left + borderLeftWidth / 2, bounds.top + borderTopWidth / 2);
            this.topRightBorderStroke =
                tlh > 0 || tlv > 0
                    ? getCurvePoints(bounds.left + topWidth, bounds.top + borderTopWidth / 2, trh - borderRightWidth / 2, trv - borderTopWidth / 2, CORNER.TOP_RIGHT)
                    : new Vector(bounds.left + bounds.width - borderRightWidth / 2, bounds.top + borderTopWidth / 2);
            this.bottomRightBorderStroke =
                brh > 0 || brv > 0
                    ? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh - borderRightWidth / 2, brv - borderBottomWidth / 2, CORNER.BOTTOM_RIGHT)
                    : new Vector(bounds.left + bounds.width - borderRightWidth / 2, bounds.top + bounds.height - borderBottomWidth / 2);
            this.bottomLeftBorderStroke =
                blh > 0 || blv > 0
                    ? getCurvePoints(bounds.left + borderLeftWidth / 2, bounds.top + leftHeight, blh - borderLeftWidth / 2, blv - borderBottomWidth / 2, CORNER.BOTTOM_LEFT)
                    : new Vector(bounds.left + borderLeftWidth / 2, bounds.top + bounds.height - borderBottomWidth / 2);
            this.topLeftBorderBox =
                tlh > 0 || tlv > 0
                    ? getCurvePoints(bounds.left, bounds.top, tlh, tlv, CORNER.TOP_LEFT)
                    : new Vector(bounds.left, bounds.top);
            this.topRightBorderBox =
                trh > 0 || trv > 0
                    ? getCurvePoints(bounds.left + topWidth, bounds.top, trh, trv, CORNER.TOP_RIGHT)
                    : new Vector(bounds.left + bounds.width, bounds.top);
            this.bottomRightBorderBox =
                brh > 0 || brv > 0
                    ? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh, brv, CORNER.BOTTOM_RIGHT)
                    : new Vector(bounds.left + bounds.width, bounds.top + bounds.height);
            this.bottomLeftBorderBox =
                blh > 0 || blv > 0
                    ? getCurvePoints(bounds.left, bounds.top + leftHeight, blh, blv, CORNER.BOTTOM_LEFT)
                    : new Vector(bounds.left, bounds.top + bounds.height);
            this.topLeftPaddingBox =
                tlh > 0 || tlv > 0
                    ? getCurvePoints(bounds.left + borderLeftWidth, bounds.top + borderTopWidth, Math.max(0, tlh - borderLeftWidth), Math.max(0, tlv - borderTopWidth), CORNER.TOP_LEFT)
                    : new Vector(bounds.left + borderLeftWidth, bounds.top + borderTopWidth);
            this.topRightPaddingBox =
                trh > 0 || trv > 0
                    ? getCurvePoints(bounds.left + Math.min(topWidth, bounds.width - borderRightWidth), bounds.top + borderTopWidth, topWidth > bounds.width + borderRightWidth ? 0 : Math.max(0, trh - borderRightWidth), Math.max(0, trv - borderTopWidth), CORNER.TOP_RIGHT)
                    : new Vector(bounds.left + bounds.width - borderRightWidth, bounds.top + borderTopWidth);
            this.bottomRightPaddingBox =
                brh > 0 || brv > 0
                    ? getCurvePoints(bounds.left + Math.min(bottomWidth, bounds.width - borderLeftWidth), bounds.top + Math.min(rightHeight, bounds.height - borderBottomWidth), Math.max(0, brh - borderRightWidth), Math.max(0, brv - borderBottomWidth), CORNER.BOTTOM_RIGHT)
                    : new Vector(bounds.left + bounds.width - borderRightWidth, bounds.top + bounds.height - borderBottomWidth);
            this.bottomLeftPaddingBox =
                blh > 0 || blv > 0
                    ? getCurvePoints(bounds.left + borderLeftWidth, bounds.top + Math.min(leftHeight, bounds.height - borderBottomWidth), Math.max(0, blh - borderLeftWidth), Math.max(0, blv - borderBottomWidth), CORNER.BOTTOM_LEFT)
                    : new Vector(bounds.left + borderLeftWidth, bounds.top + bounds.height - borderBottomWidth);
            this.topLeftContentBox =
                tlh > 0 || tlv > 0
                    ? getCurvePoints(bounds.left + borderLeftWidth + paddingLeft, bounds.top + borderTopWidth + paddingTop, Math.max(0, tlh - (borderLeftWidth + paddingLeft)), Math.max(0, tlv - (borderTopWidth + paddingTop)), CORNER.TOP_LEFT)
                    : new Vector(bounds.left + borderLeftWidth + paddingLeft, bounds.top + borderTopWidth + paddingTop);
            this.topRightContentBox =
                trh > 0 || trv > 0
                    ? getCurvePoints(bounds.left + Math.min(topWidth, bounds.width + borderLeftWidth + paddingLeft), bounds.top + borderTopWidth + paddingTop, topWidth > bounds.width + borderLeftWidth + paddingLeft ? 0 : trh - borderLeftWidth + paddingLeft, trv - (borderTopWidth + paddingTop), CORNER.TOP_RIGHT)
                    : new Vector(bounds.left + bounds.width - (borderRightWidth + paddingRight), bounds.top + borderTopWidth + paddingTop);
            this.bottomRightContentBox =
                brh > 0 || brv > 0
                    ? getCurvePoints(bounds.left + Math.min(bottomWidth, bounds.width - (borderLeftWidth + paddingLeft)), bounds.top + Math.min(rightHeight, bounds.height + borderTopWidth + paddingTop), Math.max(0, brh - (borderRightWidth + paddingRight)), brv - (borderBottomWidth + paddingBottom), CORNER.BOTTOM_RIGHT)
                    : new Vector(bounds.left + bounds.width - (borderRightWidth + paddingRight), bounds.top + bounds.height - (borderBottomWidth + paddingBottom));
            this.bottomLeftContentBox =
                blh > 0 || blv > 0
                    ? getCurvePoints(bounds.left + borderLeftWidth + paddingLeft, bounds.top + leftHeight, Math.max(0, blh - (borderLeftWidth + paddingLeft)), blv - (borderBottomWidth + paddingBottom), CORNER.BOTTOM_LEFT)
                    : new Vector(bounds.left + borderLeftWidth + paddingLeft, bounds.top + bounds.height - (borderBottomWidth + paddingBottom));
        }
        return BoundCurves;
    }());
    var CORNER;
    (function (CORNER) {
        CORNER[CORNER["TOP_LEFT"] = 0] = "TOP_LEFT";
        CORNER[CORNER["TOP_RIGHT"] = 1] = "TOP_RIGHT";
        CORNER[CORNER["BOTTOM_RIGHT"] = 2] = "BOTTOM_RIGHT";
        CORNER[CORNER["BOTTOM_LEFT"] = 3] = "BOTTOM_LEFT";
    })(CORNER || (CORNER = {}));
    var getCurvePoints = function (x, y, r1, r2, position) {
        var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
        var ox = r1 * kappa; // control point offset horizontal
        var oy = r2 * kappa; // control point offset vertical
        var xm = x + r1; // x-middle
        var ym = y + r2; // y-middle
        switch (position) {
            case CORNER.TOP_LEFT:
                return new BezierCurve(new Vector(x, ym), new Vector(x, ym - oy), new Vector(xm - ox, y), new Vector(xm, y));
            case CORNER.TOP_RIGHT:
                return new BezierCurve(new Vector(x, y), new Vector(x + ox, y), new Vector(xm, ym - oy), new Vector(xm, ym));
            case CORNER.BOTTOM_RIGHT:
                return new BezierCurve(new Vector(xm, y), new Vector(xm, y + oy), new Vector(x + ox, ym), new Vector(x, ym));
            case CORNER.BOTTOM_LEFT:
            default:
                return new BezierCurve(new Vector(xm, ym), new Vector(xm - ox, ym), new Vector(x, y + oy), new Vector(x, y));
        }
    };
    var calculateBorderBoxPath = function (curves) {
        return [curves.topLeftBorderBox, curves.topRightBorderBox, curves.bottomRightBorderBox, curves.bottomLeftBorderBox];
    };
    var calculateContentBoxPath = function (curves) {
        return [
            curves.topLeftContentBox,
            curves.topRightContentBox,
            curves.bottomRightContentBox,
            curves.bottomLeftContentBox
        ];
    };
    var calculatePaddingBoxPath = function (curves) {
        return [
            curves.topLeftPaddingBox,
            curves.topRightPaddingBox,
            curves.bottomRightPaddingBox,
            curves.bottomLeftPaddingBox
        ];
    };

    var TransformEffect = /** @class */ (function () {
        function TransformEffect(offsetX, offsetY, matrix) {
            this.offsetX = offsetX;
            this.offsetY = offsetY;
            this.matrix = matrix;
            this.type = 0 /* TRANSFORM */;
            this.target = 2 /* BACKGROUND_BORDERS */ | 4 /* CONTENT */;
        }
        return TransformEffect;
    }());
    var ClipEffect = /** @class */ (function () {
        function ClipEffect(path, target) {
            this.path = path;
            this.target = target;
            this.type = 1 /* CLIP */;
        }
        return ClipEffect;
    }());
    var OpacityEffect = /** @class */ (function () {
        function OpacityEffect(opacity) {
            this.opacity = opacity;
            this.type = 2 /* OPACITY */;
            this.target = 2 /* BACKGROUND_BORDERS */ | 4 /* CONTENT */;
        }
        return OpacityEffect;
    }());
    var isTransformEffect = function (effect) {
        return effect.type === 0 /* TRANSFORM */;
    };
    var isClipEffect = function (effect) { return effect.type === 1 /* CLIP */; };
    var isOpacityEffect = function (effect) { return effect.type === 2 /* OPACITY */; };

    var equalPath = function (a, b) {
        if (a.length === b.length) {
            return a.some(function (v, i) { return v === b[i]; });
        }
        return false;
    };
    var transformPath = function (path, deltaX, deltaY, deltaW, deltaH) {
        return path.map(function (point, index) {
            switch (index) {
                case 0:
                    return point.add(deltaX, deltaY);
                case 1:
                    return point.add(deltaX + deltaW, deltaY);
                case 2:
                    return point.add(deltaX + deltaW, deltaY + deltaH);
                case 3:
                    return point.add(deltaX, deltaY + deltaH);
            }
            return point;
        });
    };

    var StackingContext = /** @class */ (function () {
        function StackingContext(container) {
            this.element = container;
            this.inlineLevel = [];
            this.nonInlineLevel = [];
            this.negativeZIndex = [];
            this.zeroOrAutoZIndexOrTransformedOrOpacity = [];
            this.positiveZIndex = [];
            this.nonPositionedFloats = [];
            this.nonPositionedInlineLevel = [];
        }
        return StackingContext;
    }());
    var ElementPaint = /** @class */ (function () {
        function ElementPaint(container, parent) {
            this.container = container;
            this.parent = parent;
            this.effects = [];
            this.curves = new BoundCurves(this.container);
            if (this.container.styles.opacity < 1) {
                this.effects.push(new OpacityEffect(this.container.styles.opacity));
            }
            if (this.container.styles.transform !== null) {
                var offsetX = this.container.bounds.left + this.container.styles.transformOrigin[0].number;
                var offsetY = this.container.bounds.top + this.container.styles.transformOrigin[1].number;
                var matrix = this.container.styles.transform;
                this.effects.push(new TransformEffect(offsetX, offsetY, matrix));
            }
            if (this.container.styles.overflowX !== 0 /* VISIBLE */) {
                var borderBox = calculateBorderBoxPath(this.curves);
                var paddingBox = calculatePaddingBoxPath(this.curves);
                if (equalPath(borderBox, paddingBox)) {
                    this.effects.push(new ClipEffect(borderBox, 2 /* BACKGROUND_BORDERS */ | 4 /* CONTENT */));
                }
                else {
                    this.effects.push(new ClipEffect(borderBox, 2 /* BACKGROUND_BORDERS */));
                    this.effects.push(new ClipEffect(paddingBox, 4 /* CONTENT */));
                }
            }
        }
        ElementPaint.prototype.getEffects = function (target) {
            var inFlow = [2 /* ABSOLUTE */, 3 /* FIXED */].indexOf(this.container.styles.position) === -1;
            var parent = this.parent;
            var effects = this.effects.slice(0);
            while (parent) {
                var croplessEffects = parent.effects.filter(function (effect) { return !isClipEffect(effect); });
                if (inFlow || parent.container.styles.position !== 0 /* STATIC */ || !parent.parent) {
                    effects.unshift.apply(effects, croplessEffects);
                    inFlow = [2 /* ABSOLUTE */, 3 /* FIXED */].indexOf(parent.container.styles.position) === -1;
                    if (parent.container.styles.overflowX !== 0 /* VISIBLE */) {
                        var borderBox = calculateBorderBoxPath(parent.curves);
                        var paddingBox = calculatePaddingBoxPath(parent.curves);
                        if (!equalPath(borderBox, paddingBox)) {
                            effects.unshift(new ClipEffect(paddingBox, 2 /* BACKGROUND_BORDERS */ | 4 /* CONTENT */));
                        }
                    }
                }
                else {
                    effects.unshift.apply(effects, croplessEffects);
                }
                parent = parent.parent;
            }
            return effects.filter(function (effect) { return contains(effect.target, target); });
        };
        return ElementPaint;
    }());
    var parseStackTree = function (parent, stackingContext, realStackingContext, listItems) {
        parent.container.elements.forEach(function (child) {
            var treatAsRealStackingContext = contains(child.flags, 4 /* CREATES_REAL_STACKING_CONTEXT */);
            var createsStackingContext = contains(child.flags, 2 /* CREATES_STACKING_CONTEXT */);
            var paintContainer = new ElementPaint(child, parent);
            if (contains(child.styles.display, 2048 /* LIST_ITEM */)) {
                listItems.push(paintContainer);
            }
            var listOwnerItems = contains(child.flags, 8 /* IS_LIST_OWNER */) ? [] : listItems;
            if (treatAsRealStackingContext || createsStackingContext) {
                var parentStack = treatAsRealStackingContext || child.styles.isPositioned() ? realStackingContext : stackingContext;
                var stack = new StackingContext(paintContainer);
                if (child.styles.isPositioned() || child.styles.opacity < 1 || child.styles.isTransformed()) {
                    var order_1 = child.styles.zIndex.order;
                    if (order_1 < 0) {
                        var index_1 = 0;
                        parentStack.negativeZIndex.some(function (current, i) {
                            if (order_1 > current.element.container.styles.zIndex.order) {
                                index_1 = i;
                                return false;
                            }
                            else if (index_1 > 0) {
                                return true;
                            }
                            return false;
                        });
                        parentStack.negativeZIndex.splice(index_1, 0, stack);
                    }
                    else if (order_1 > 0) {
                        var index_2 = 0;
                        parentStack.positiveZIndex.some(function (current, i) {
                            if (order_1 >= current.element.container.styles.zIndex.order) {
                                index_2 = i + 1;
                                return false;
                            }
                            else if (index_2 > 0) {
                                return true;
                            }
                            return false;
                        });
                        parentStack.positiveZIndex.splice(index_2, 0, stack);
                    }
                    else {
                        parentStack.zeroOrAutoZIndexOrTransformedOrOpacity.push(stack);
                    }
                }
                else {
                    if (child.styles.isFloating()) {
                        parentStack.nonPositionedFloats.push(stack);
                    }
                    else {
                        parentStack.nonPositionedInlineLevel.push(stack);
                    }
                }
                parseStackTree(paintContainer, stack, treatAsRealStackingContext ? stack : realStackingContext, listOwnerItems);
            }
            else {
                if (child.styles.isInlineLevel()) {
                    stackingContext.inlineLevel.push(paintContainer);
                }
                else {
                    stackingContext.nonInlineLevel.push(paintContainer);
                }
                parseStackTree(paintContainer, stackingContext, realStackingContext, listOwnerItems);
            }
            if (contains(child.flags, 8 /* IS_LIST_OWNER */)) {
                processListItems(child, listOwnerItems);
            }
        });
    };
    var processListItems = function (owner, elements) {
        var numbering = owner instanceof OLElementContainer ? owner.start : 1;
        var reversed = owner instanceof OLElementContainer ? owner.reversed : false;
        for (var i = 0; i < elements.length; i++) {
            var item = elements[i];
            if (item.container instanceof LIElementContainer &&
                typeof item.container.value === 'number' &&
                item.container.value !== 0) {
                numbering = item.container.value;
            }
            item.listValue = createCounterText(numbering, item.container.styles.listStyleType, true);
            numbering += reversed ? -1 : 1;
        }
    };
    var parseStackingContexts = function (container) {
        var paintContainer = new ElementPaint(container, null);
        var root = new StackingContext(paintContainer);
        var listItems = [];
        parseStackTree(paintContainer, root, root, listItems);
        processListItems(paintContainer.container, listItems);
        return root;
    };

    var parsePathForBorder = function (curves, borderSide) {
        switch (borderSide) {
            case 0:
                return createPathFromCurves(curves.topLeftBorderBox, curves.topLeftPaddingBox, curves.topRightBorderBox, curves.topRightPaddingBox);
            case 1:
                return createPathFromCurves(curves.topRightBorderBox, curves.topRightPaddingBox, curves.bottomRightBorderBox, curves.bottomRightPaddingBox);
            case 2:
                return createPathFromCurves(curves.bottomRightBorderBox, curves.bottomRightPaddingBox, curves.bottomLeftBorderBox, curves.bottomLeftPaddingBox);
            case 3:
            default:
                return createPathFromCurves(curves.bottomLeftBorderBox, curves.bottomLeftPaddingBox, curves.topLeftBorderBox, curves.topLeftPaddingBox);
        }
    };
    var parsePathForBorderDoubleOuter = function (curves, borderSide) {
        switch (borderSide) {
            case 0:
                return createPathFromCurves(curves.topLeftBorderBox, curves.topLeftBorderDoubleOuterBox, curves.topRightBorderBox, curves.topRightBorderDoubleOuterBox);
            case 1:
                return createPathFromCurves(curves.topRightBorderBox, curves.topRightBorderDoubleOuterBox, curves.bottomRightBorderBox, curves.bottomRightBorderDoubleOuterBox);
            case 2:
                return createPathFromCurves(curves.bottomRightBorderBox, curves.bottomRightBorderDoubleOuterBox, curves.bottomLeftBorderBox, curves.bottomLeftBorderDoubleOuterBox);
            case 3:
            default:
                return createPathFromCurves(curves.bottomLeftBorderBox, curves.bottomLeftBorderDoubleOuterBox, curves.topLeftBorderBox, curves.topLeftBorderDoubleOuterBox);
        }
    };
    var parsePathForBorderDoubleInner = function (curves, borderSide) {
        switch (borderSide) {
            case 0:
                return createPathFromCurves(curves.topLeftBorderDoubleInnerBox, curves.topLeftPaddingBox, curves.topRightBorderDoubleInnerBox, curves.topRightPaddingBox);
            case 1:
                return createPathFromCurves(curves.topRightBorderDoubleInnerBox, curves.topRightPaddingBox, curves.bottomRightBorderDoubleInnerBox, curves.bottomRightPaddingBox);
            case 2:
                return createPathFromCurves(curves.bottomRightBorderDoubleInnerBox, curves.bottomRightPaddingBox, curves.bottomLeftBorderDoubleInnerBox, curves.bottomLeftPaddingBox);
            case 3:
            default:
                return createPathFromCurves(curves.bottomLeftBorderDoubleInnerBox, curves.bottomLeftPaddingBox, curves.topLeftBorderDoubleInnerBox, curves.topLeftPaddingBox);
        }
    };
    var parsePathForBorderStroke = function (curves, borderSide) {
        switch (borderSide) {
            case 0:
                return createStrokePathFromCurves(curves.topLeftBorderStroke, curves.topRightBorderStroke);
            case 1:
                return createStrokePathFromCurves(curves.topRightBorderStroke, curves.bottomRightBorderStroke);
            case 2:
                return createStrokePathFromCurves(curves.bottomRightBorderStroke, curves.bottomLeftBorderStroke);
            case 3:
            default:
                return createStrokePathFromCurves(curves.bottomLeftBorderStroke, curves.topLeftBorderStroke);
        }
    };
    var createStrokePathFromCurves = function (outer1, outer2) {
        var path = [];
        if (isBezierCurve(outer1)) {
            path.push(outer1.subdivide(0.5, false));
        }
        else {
            path.push(outer1);
        }
        if (isBezierCurve(outer2)) {
            path.push(outer2.subdivide(0.5, true));
        }
        else {
            path.push(outer2);
        }
        return path;
    };
    var createPathFromCurves = function (outer1, inner1, outer2, inner2) {
        var path = [];
        if (isBezierCurve(outer1)) {
            path.push(outer1.subdivide(0.5, false));
        }
        else {
            path.push(outer1);
        }
        if (isBezierCurve(outer2)) {
            path.push(outer2.subdivide(0.5, true));
        }
        else {
            path.push(outer2);
        }
        if (isBezierCurve(inner2)) {
            path.push(inner2.subdivide(0.5, true).reverse());
        }
        else {
            path.push(inner2);
        }
        if (isBezierCurve(inner1)) {
            path.push(inner1.subdivide(0.5, false).reverse());
        }
        else {
            path.push(inner1);
        }
        return path;
    };

    var paddingBox = function (element) {
        var bounds = element.bounds;
        var styles = element.styles;
        return bounds.add(styles.borderLeftWidth, styles.borderTopWidth, -(styles.borderRightWidth + styles.borderLeftWidth), -(styles.borderTopWidth + styles.borderBottomWidth));
    };
    var contentBox = function (element) {
        var styles = element.styles;
        var bounds = element.bounds;
        var paddingLeft = getAbsoluteValue(styles.paddingLeft, bounds.width);
        var paddingRight = getAbsoluteValue(styles.paddingRight, bounds.width);
        var paddingTop = getAbsoluteValue(styles.paddingTop, bounds.width);
        var paddingBottom = getAbsoluteValue(styles.paddingBottom, bounds.width);
        return bounds.add(paddingLeft + styles.borderLeftWidth, paddingTop + styles.borderTopWidth, -(styles.borderRightWidth + styles.borderLeftWidth + paddingLeft + paddingRight), -(styles.borderTopWidth + styles.borderBottomWidth + paddingTop + paddingBottom));
    };

    var calculateBackgroundPositioningArea = function (backgroundOrigin, element) {
        if (backgroundOrigin === 0 /* BORDER_BOX */) {
            return element.bounds;
        }
        if (backgroundOrigin === 2 /* CONTENT_BOX */) {
            return contentBox(element);
        }
        return paddingBox(element);
    };
    var calculateBackgroundPaintingArea = function (backgroundClip, element) {
        if (backgroundClip === 0 /* BORDER_BOX */) {
            return element.bounds;
        }
        if (backgroundClip === 2 /* CONTENT_BOX */) {
            return contentBox(element);
        }
        return paddingBox(element);
    };
    var calculateBackgroundRendering = function (container, index, intrinsicSize) {
        var backgroundPositioningArea = calculateBackgroundPositioningArea(getBackgroundValueForIndex(container.styles.backgroundOrigin, index), container);
        var backgroundPaintingArea = calculateBackgroundPaintingArea(getBackgroundValueForIndex(container.styles.backgroundClip, index), container);
        var backgroundImageSize = calculateBackgroundSize(getBackgroundValueForIndex(container.styles.backgroundSize, index), intrinsicSize, backgroundPositioningArea);
        var sizeWidth = backgroundImageSize[0], sizeHeight = backgroundImageSize[1];
        var position = getAbsoluteValueForTuple(getBackgroundValueForIndex(container.styles.backgroundPosition, index), backgroundPositioningArea.width - sizeWidth, backgroundPositioningArea.height - sizeHeight);
        var path = calculateBackgroundRepeatPath(getBackgroundValueForIndex(container.styles.backgroundRepeat, index), position, backgroundImageSize, backgroundPositioningArea, backgroundPaintingArea);
        var offsetX = Math.round(backgroundPositioningArea.left + position[0]);
        var offsetY = Math.round(backgroundPositioningArea.top + position[1]);
        return [path, offsetX, offsetY, sizeWidth, sizeHeight];
    };
    var isAuto = function (token) { return isIdentToken(token) && token.value === BACKGROUND_SIZE.AUTO; };
    var hasIntrinsicValue = function (value) { return typeof value === 'number'; };
    var calculateBackgroundSize = function (size, _a, bounds) {
        var intrinsicWidth = _a[0], intrinsicHeight = _a[1], intrinsicProportion = _a[2];
        var first = size[0], second = size[1];
        if (!first) {
            return [0, 0];
        }
        if (isLengthPercentage(first) && second && isLengthPercentage(second)) {
            return [getAbsoluteValue(first, bounds.width), getAbsoluteValue(second, bounds.height)];
        }
        var hasIntrinsicProportion = hasIntrinsicValue(intrinsicProportion);
        if (isIdentToken(first) && (first.value === BACKGROUND_SIZE.CONTAIN || first.value === BACKGROUND_SIZE.COVER)) {
            if (hasIntrinsicValue(intrinsicProportion)) {
                var targetRatio = bounds.width / bounds.height;
                return targetRatio < intrinsicProportion !== (first.value === BACKGROUND_SIZE.COVER)
                    ? [bounds.width, bounds.width / intrinsicProportion]
                    : [bounds.height * intrinsicProportion, bounds.height];
            }
            return [bounds.width, bounds.height];
        }
        var hasIntrinsicWidth = hasIntrinsicValue(intrinsicWidth);
        var hasIntrinsicHeight = hasIntrinsicValue(intrinsicHeight);
        var hasIntrinsicDimensions = hasIntrinsicWidth || hasIntrinsicHeight;
        // If the background-size is auto or auto auto:
        if (isAuto(first) && (!second || isAuto(second))) {
            // If the image has both horizontal and vertical intrinsic dimensions, it's rendered at that size.
            if (hasIntrinsicWidth && hasIntrinsicHeight) {
                return [intrinsicWidth, intrinsicHeight];
            }
            // If the image has no intrinsic dimensions and has no intrinsic proportions,
            // it's rendered at the size of the background positioning area.
            if (!hasIntrinsicProportion && !hasIntrinsicDimensions) {
                return [bounds.width, bounds.height];
            }
            // TODO If the image has no intrinsic dimensions but has intrinsic proportions, it's rendered as if contain had been specified instead.
            // If the image has only one intrinsic dimension and has intrinsic proportions, it's rendered at the size corresponding to that one dimension.
            // The other dimension is computed using the specified dimension and the intrinsic proportions.
            if (hasIntrinsicDimensions && hasIntrinsicProportion) {
                var width_1 = hasIntrinsicWidth
                    ? intrinsicWidth
                    : intrinsicHeight * intrinsicProportion;
                var height_1 = hasIntrinsicHeight
                    ? intrinsicHeight
                    : intrinsicWidth / intrinsicProportion;
                return [width_1, height_1];
            }
            // If the image has only one intrinsic dimension but has no intrinsic proportions,
            // it's rendered using the specified dimension and the other dimension of the background positioning area.
            var width_2 = hasIntrinsicWidth ? intrinsicWidth : bounds.width;
            var height_2 = hasIntrinsicHeight ? intrinsicHeight : bounds.height;
            return [width_2, height_2];
        }
        // If the image has intrinsic proportions, it's stretched to the specified dimension.
        // The unspecified dimension is computed using the specified dimension and the intrinsic proportions.
        if (hasIntrinsicProportion) {
            var width_3 = 0;
            var height_3 = 0;
            if (isLengthPercentage(first)) {
                width_3 = getAbsoluteValue(first, bounds.width);
            }
            else if (isLengthPercentage(second)) {
                height_3 = getAbsoluteValue(second, bounds.height);
            }
            if (isAuto(first)) {
                width_3 = height_3 * intrinsicProportion;
            }
            else if (!second || isAuto(second)) {
                height_3 = width_3 / intrinsicProportion;
            }
            return [width_3, height_3];
        }
        // If the image has no intrinsic proportions, it's stretched to the specified dimension.
        // The unspecified dimension is computed using the image's corresponding intrinsic dimension,
        // if there is one. If there is no such intrinsic dimension,
        // it becomes the corresponding dimension of the background positioning area.
        var width = null;
        var height = null;
        if (isLengthPercentage(first)) {
            width = getAbsoluteValue(first, bounds.width);
        }
        else if (second && isLengthPercentage(second)) {
            height = getAbsoluteValue(second, bounds.height);
        }
        if (width !== null && (!second || isAuto(second))) {
            height =
                hasIntrinsicWidth && hasIntrinsicHeight
                    ? (width / intrinsicWidth) * intrinsicHeight
                    : bounds.height;
        }
        if (height !== null && isAuto(first)) {
            width =
                hasIntrinsicWidth && hasIntrinsicHeight
                    ? (height / intrinsicHeight) * intrinsicWidth
                    : bounds.width;
        }
        if (width !== null && height !== null) {
            return [width, height];
        }
        throw new Error("Unable to calculate background-size for element");
    };
    var getBackgroundValueForIndex = function (values, index) {
        var value = values[index];
        if (typeof value === 'undefined') {
            return values[0];
        }
        return value;
    };
    var calculateBackgroundRepeatPath = function (repeat, _a, _b, backgroundPositioningArea, backgroundPaintingArea) {
        var x = _a[0], y = _a[1];
        var width = _b[0], height = _b[1];
        switch (repeat) {
            case 2 /* REPEAT_X */:
                return [
                    new Vector(Math.round(backgroundPositioningArea.left), Math.round(backgroundPositioningArea.top + y)),
                    new Vector(Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width), Math.round(backgroundPositioningArea.top + y)),
                    new Vector(Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width), Math.round(height + backgroundPositioningArea.top + y)),
                    new Vector(Math.round(backgroundPositioningArea.left), Math.round(height + backgroundPositioningArea.top + y))
                ];
            case 3 /* REPEAT_Y */:
                return [
                    new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top)),
                    new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top)),
                    new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top)),
                    new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top))
                ];
            case 1 /* NO_REPEAT */:
                return [
                    new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top + y)),
                    new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top + y)),
                    new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top + y + height)),
                    new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top + y + height))
                ];
            default:
                return [
                    new Vector(Math.round(backgroundPaintingArea.left), Math.round(backgroundPaintingArea.top)),
                    new Vector(Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width), Math.round(backgroundPaintingArea.top)),
                    new Vector(Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width), Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top)),
                    new Vector(Math.round(backgroundPaintingArea.left), Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top))
                ];
        }
    };

    var SMALL_IMAGE = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';

    var SAMPLE_TEXT = 'Hidden Text';
    var FontMetrics = /** @class */ (function () {
        function FontMetrics(document) {
            this._data = {};
            this._document = document;
        }
        FontMetrics.prototype.parseMetrics = function (fontFamily, fontSize) {
            var container = this._document.createElement('div');
            var img = this._document.createElement('img');
            var span = this._document.createElement('span');
            var body = this._document.body;
            container.style.visibility = 'hidden';
            container.style.fontFamily = fontFamily;
            container.style.fontSize = fontSize;
            container.style.margin = '0';
            container.style.padding = '0';
            container.style.whiteSpace = 'nowrap';
            body.appendChild(container);
            img.src = SMALL_IMAGE;
            img.width = 1;
            img.height = 1;
            img.style.margin = '0';
            img.style.padding = '0';
            img.style.verticalAlign = 'baseline';
            span.style.fontFamily = fontFamily;
            span.style.fontSize = fontSize;
            span.style.margin = '0';
            span.style.padding = '0';
            span.appendChild(this._document.createTextNode(SAMPLE_TEXT));
            container.appendChild(span);
            container.appendChild(img);
            var baseline = img.offsetTop - span.offsetTop + 2;
            container.removeChild(span);
            container.appendChild(this._document.createTextNode(SAMPLE_TEXT));
            container.style.lineHeight = 'normal';
            img.style.verticalAlign = 'super';
            var middle = img.offsetTop - container.offsetTop + 2;
            body.removeChild(container);
            return { baseline: baseline, middle: middle };
        };
        FontMetrics.prototype.getMetrics = function (fontFamily, fontSize) {
            var key = fontFamily + " " + fontSize;
            if (typeof this._data[key] === 'undefined') {
                this._data[key] = this.parseMetrics(fontFamily, fontSize);
            }
            return this._data[key];
        };
        return FontMetrics;
    }());

    var Renderer = /** @class */ (function () {
        function Renderer(context, options) {
            this.context = context;
            this.options = options;
        }
        return Renderer;
    }());

    var MASK_OFFSET = 10000;
    var CanvasRenderer = /** @class */ (function (_super) {
        __extends(CanvasRenderer, _super);
        function CanvasRenderer(context, options) {
            var _this = _super.call(this, context, options) || this;
            _this._activeEffects = [];
            _this.canvas = options.canvas ? options.canvas : document.createElement('canvas');
            _this.ctx = _this.canvas.getContext('2d');
            if (!options.canvas) {
                _this.canvas.width = Math.floor(options.width * options.scale);
                _this.canvas.height = Math.floor(options.height * options.scale);
                _this.canvas.style.width = options.width + "px";
                _this.canvas.style.height = options.height + "px";
            }
            _this.fontMetrics = new FontMetrics(document);
            _this.ctx.scale(_this.options.scale, _this.options.scale);
            _this.ctx.translate(-options.x, -options.y);
            _this.ctx.textBaseline = 'bottom';
            _this._activeEffects = [];
            _this.context.logger.debug("Canvas renderer initialized (" + options.width + "x" + options.height + ") with scale " + options.scale);
            return _this;
        }
        CanvasRenderer.prototype.applyEffects = function (effects) {
            var _this = this;
            while (this._activeEffects.length) {
                this.popEffect();
            }
            effects.forEach(function (effect) { return _this.applyEffect(effect); });
        };
        CanvasRenderer.prototype.applyEffect = function (effect) {
            this.ctx.save();
            if (isOpacityEffect(effect)) {
                this.ctx.globalAlpha = effect.opacity;
            }
            if (isTransformEffect(effect)) {
                this.ctx.translate(effect.offsetX, effect.offsetY);
                this.ctx.transform(effect.matrix[0], effect.matrix[1], effect.matrix[2], effect.matrix[3], effect.matrix[4], effect.matrix[5]);
                this.ctx.translate(-effect.offsetX, -effect.offsetY);
            }
            if (isClipEffect(effect)) {
                this.path(effect.path);
                this.ctx.clip();
            }
            this._activeEffects.push(effect);
        };
        CanvasRenderer.prototype.popEffect = function () {
            this._activeEffects.pop();
            this.ctx.restore();
        };
        CanvasRenderer.prototype.renderStack = function (stack) {
            return __awaiter(this, void 0, void 0, function () {
                var styles;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            styles = stack.element.container.styles;
                            if (!styles.isVisible()) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.renderStackContent(stack)];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2 /*return*/];
                    }
                });
            });
        };
        CanvasRenderer.prototype.renderNode = function (paint) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (contains(paint.container.flags, 16 /* DEBUG_RENDER */)) {
                                debugger;
                            }
                            if (!paint.container.styles.isVisible()) return [3 /*break*/, 3];
                            return [4 /*yield*/, this.renderNodeBackgroundAndBorders(paint)];
                        case 1:
                            _a.sent();
                            return [4 /*yield*/, this.renderNodeContent(paint)];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
        CanvasRenderer.prototype.renderTextWithLetterSpacing = function (text, letterSpacing, baseline) {
            var _this = this;
            if (letterSpacing === 0) {
                this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + baseline);
            }
            else {
                var letters = segmentGraphemes(text.text);
                letters.reduce(function (left, letter) {
                    _this.ctx.fillText(letter, left, text.bounds.top + baseline);
                    return left + _this.ctx.measureText(letter).width;
                }, text.bounds.left);
            }
        };
        CanvasRenderer.prototype.createFontStyle = function (styles) {
            var fontVariant = styles.fontVariant
                .filter(function (variant) { return variant === 'normal' || variant === 'small-caps'; })
                .join('');
            var fontFamily = fixIOSSystemFonts(styles.fontFamily).join(', ');
            var fontSize = isDimensionToken(styles.fontSize)
                ? "" + styles.fontSize.number + styles.fontSize.unit
                : styles.fontSize.number + "px";
            return [
                [styles.fontStyle, fontVariant, styles.fontWeight, fontSize, fontFamily].join(' '),
                fontFamily,
                fontSize
            ];
        };
        CanvasRenderer.prototype.renderTextNode = function (text, styles) {
            return __awaiter(this, void 0, void 0, function () {
                var _a, font, fontFamily, fontSize, _b, baseline, middle, paintOrder;
                var _this = this;
                return __generator(this, function (_c) {
                    _a = this.createFontStyle(styles), font = _a[0], fontFamily = _a[1], fontSize = _a[2];
                    this.ctx.font = font;
                    this.ctx.direction = styles.direction === 1 /* RTL */ ? 'rtl' : 'ltr';
                    this.ctx.textAlign = 'left';
                    this.ctx.textBaseline = 'alphabetic';
                    _b = this.fontMetrics.getMetrics(fontFamily, fontSize), baseline = _b.baseline, middle = _b.middle;
                    paintOrder = styles.paintOrder;
                    text.textBounds.forEach(function (text) {
                        paintOrder.forEach(function (paintOrderLayer) {
                            switch (paintOrderLayer) {
                                case 0 /* FILL */:
                                    _this.ctx.fillStyle = asString(styles.color);
                                    _this.renderTextWithLetterSpacing(text, styles.letterSpacing, baseline);
                                    var textShadows = styles.textShadow;
                                    if (textShadows.length && text.text.trim().length) {
                                        textShadows
                                            .slice(0)
                                            .reverse()
                                            .forEach(function (textShadow) {
                                            _this.ctx.shadowColor = asString(textShadow.color);
                                            _this.ctx.shadowOffsetX = textShadow.offsetX.number * _this.options.scale;
                                            _this.ctx.shadowOffsetY = textShadow.offsetY.number * _this.options.scale;
                                            _this.ctx.shadowBlur = textShadow.blur.number;
                                            _this.renderTextWithLetterSpacing(text, styles.letterSpacing, baseline);
                                        });
                                        _this.ctx.shadowColor = '';
                                        _this.ctx.shadowOffsetX = 0;
                                        _this.ctx.shadowOffsetY = 0;
                                        _this.ctx.shadowBlur = 0;
                                    }
                                    if (styles.textDecorationLine.length) {
                                        _this.ctx.fillStyle = asString(styles.textDecorationColor || styles.color);
                                        styles.textDecorationLine.forEach(function (textDecorationLine) {
                                            switch (textDecorationLine) {
                                                case 1 /* UNDERLINE */:
                                                    // Draws a line at the baseline of the font
                                                    // TODO As some browsers display the line as more than 1px if the font-size is big,
                                                    // need to take that into account both in position and size
                                                    _this.ctx.fillRect(text.bounds.left, Math.round(text.bounds.top + baseline), text.bounds.width, 1);
                                                    break;
                                                case 2 /* OVERLINE */:
                                                    _this.ctx.fillRect(text.bounds.left, Math.round(text.bounds.top), text.bounds.width, 1);
                                                    break;
                                                case 3 /* LINE_THROUGH */:
                                                    // TODO try and find exact position for line-through
                                                    _this.ctx.fillRect(text.bounds.left, Math.ceil(text.bounds.top + middle), text.bounds.width, 1);
                                                    break;
                                            }
                                        });
                                    }
                                    break;
                                case 1 /* STROKE */:
                                    if (styles.webkitTextStrokeWidth && text.text.trim().length) {
                                        _this.ctx.strokeStyle = asString(styles.webkitTextStrokeColor);
                                        _this.ctx.lineWidth = styles.webkitTextStrokeWidth;
                                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                        _this.ctx.lineJoin = !!window.chrome ? 'miter' : 'round';
                                        _this.ctx.strokeText(text.text, text.bounds.left, text.bounds.top + baseline);
                                    }
                                    _this.ctx.strokeStyle = '';
                                    _this.ctx.lineWidth = 0;
                                    _this.ctx.lineJoin = 'miter';
                                    break;
                            }
                        });
                    });
                    return [2 /*return*/];
                });
            });
        };
        CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image) {
            if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
                var box = contentBox(container);
                var path = calculatePaddingBoxPath(curves);
                this.path(path);
                this.ctx.save();
                this.ctx.clip();
                this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, box.left, box.top, box.width, box.height);
                this.ctx.restore();
            }
        };
        CanvasRenderer.prototype.renderNodeContent = function (paint) {
            return __awaiter(this, void 0, void 0, function () {
                var container, curves, styles, _i, _a, child, image, image, iframeRenderer, canvas, size, _b, fontFamily, fontSize, baseline, bounds, x, textBounds, img, image, url, fontFamily, bounds;
                return __generator(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            this.applyEffects(paint.getEffects(4 /* CONTENT */));
                            container = paint.container;
                            curves = paint.curves;
                            styles = container.styles;
                            _i = 0, _a = container.textNodes;
                            _c.label = 1;
                        case 1:
                            if (!(_i < _a.length)) return [3 /*break*/, 4];
                            child = _a[_i];
                            return [4 /*yield*/, this.renderTextNode(child, styles)];
                        case 2:
                            _c.sent();
                            _c.label = 3;
                        case 3:
                            _i++;
                            return [3 /*break*/, 1];
                        case 4:
                            if (!(container instanceof ImageElementContainer)) return [3 /*break*/, 8];
                            _c.label = 5;
                        case 5:
                            _c.trys.push([5, 7, , 8]);
                            return [4 /*yield*/, this.context.cache.match(container.src)];
                        case 6:
                            image = _c.sent();
                            this.renderReplacedElement(container, curves, image);
                            return [3 /*break*/, 8];
                        case 7:
                            _c.sent();
                            this.context.logger.error("Error loading image " + container.src);
                            return [3 /*break*/, 8];
                        case 8:
                            if (container instanceof CanvasElementContainer) {
                                this.renderReplacedElement(container, curves, container.canvas);
                            }
                            if (!(container instanceof SVGElementContainer)) return [3 /*break*/, 12];
                            _c.label = 9;
                        case 9:
                            _c.trys.push([9, 11, , 12]);
                            return [4 /*yield*/, this.context.cache.match(container.svg)];
                        case 10:
                            image = _c.sent();
                            this.renderReplacedElement(container, curves, image);
                            return [3 /*break*/, 12];
                        case 11:
                            _c.sent();
                            this.context.logger.error("Error loading svg " + container.svg.substring(0, 255));
                            return [3 /*break*/, 12];
                        case 12:
                            if (!(container instanceof IFrameElementContainer && container.tree)) return [3 /*break*/, 14];
                            iframeRenderer = new CanvasRenderer(this.context, {
                                scale: this.options.scale,
                                backgroundColor: container.backgroundColor,
                                x: 0,
                                y: 0,
                                width: container.width,
                                height: container.height
                            });
                            return [4 /*yield*/, iframeRenderer.render(container.tree)];
                        case 13:
                            canvas = _c.sent();
                            if (container.width && container.height) {
                                this.ctx.drawImage(canvas, 0, 0, container.width, container.height, container.bounds.left, container.bounds.top, container.bounds.width, container.bounds.height);
                            }
                            _c.label = 14;
                        case 14:
                            if (container instanceof InputElementContainer) {
                                size = Math.min(container.bounds.width, container.bounds.height);
                                if (container.type === CHECKBOX) {
                                    if (container.checked) {
                                        this.ctx.save();
                                        this.path([
                                            new Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79),
                                            new Vector(container.bounds.left + size * 0.16, container.bounds.top + size * 0.5549),
                                            new Vector(container.bounds.left + size * 0.27347, container.bounds.top + size * 0.44071),
                                            new Vector(container.bounds.left + size * 0.39694, container.bounds.top + size * 0.5649),
                                            new Vector(container.bounds.left + size * 0.72983, container.bounds.top + size * 0.23),
                                            new Vector(container.bounds.left + size * 0.84, container.bounds.top + size * 0.34085),
                                            new Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79)
                                        ]);
                                        this.ctx.fillStyle = asString(INPUT_COLOR);
                                        this.ctx.fill();
                                        this.ctx.restore();
                                    }
                                }
                                else if (container.type === RADIO) {
                                    if (container.checked) {
                                        this.ctx.save();
                                        this.ctx.beginPath();
                                        this.ctx.arc(container.bounds.left + size / 2, container.bounds.top + size / 2, size / 4, 0, Math.PI * 2, true);
                                        this.ctx.fillStyle = asString(INPUT_COLOR);
                                        this.ctx.fill();
                                        this.ctx.restore();
                                    }
                                }
                            }
                            if (isTextInputElement(container) && container.value.length) {
                                _b = this.createFontStyle(styles), fontFamily = _b[0], fontSize = _b[1];
                                baseline = this.fontMetrics.getMetrics(fontFamily, fontSize).baseline;
                                this.ctx.font = fontFamily;
                                this.ctx.fillStyle = asString(styles.color);
                                this.ctx.textBaseline = 'alphabetic';
                                this.ctx.textAlign = canvasTextAlign(container.styles.textAlign);
                                bounds = contentBox(container);
                                x = 0;
                                switch (container.styles.textAlign) {
                                    case 1 /* CENTER */:
                                        x += bounds.width / 2;
                                        break;
                                    case 2 /* RIGHT */:
                                        x += bounds.width;
                                        break;
                                }
                                textBounds = bounds.add(x, 0, 0, -bounds.height / 2 + 1);
                                this.ctx.save();
                                this.path([
                                    new Vector(bounds.left, bounds.top),
                                    new Vector(bounds.left + bounds.width, bounds.top),
                                    new Vector(bounds.left + bounds.width, bounds.top + bounds.height),
                                    new Vector(bounds.left, bounds.top + bounds.height)
                                ]);
                                this.ctx.clip();
                                this.renderTextWithLetterSpacing(new TextBounds(container.value, textBounds), styles.letterSpacing, baseline);
                                this.ctx.restore();
                                this.ctx.textBaseline = 'alphabetic';
                                this.ctx.textAlign = 'left';
                            }
                            if (!contains(container.styles.display, 2048 /* LIST_ITEM */)) return [3 /*break*/, 20];
                            if (!(container.styles.listStyleImage !== null)) return [3 /*break*/, 19];
                            img = container.styles.listStyleImage;
                            if (!(img.type === 0 /* URL */)) return [3 /*break*/, 18];
                            image = void 0;
                            url = img.url;
                            _c.label = 15;
                        case 15:
                            _c.trys.push([15, 17, , 18]);
                            return [4 /*yield*/, this.context.cache.match(url)];
                        case 16:
                            image = _c.sent();
                            this.ctx.drawImage(image, container.bounds.left - (image.width + 10), container.bounds.top);
                            return [3 /*break*/, 18];
                        case 17:
                            _c.sent();
                            this.context.logger.error("Error loading list-style-image " + url);
                            return [3 /*break*/, 18];
                        case 18: return [3 /*break*/, 20];
                        case 19:
                            if (paint.listValue && container.styles.listStyleType !== -1 /* NONE */) {
                                fontFamily = this.createFontStyle(styles)[0];
                                this.ctx.font = fontFamily;
                                this.ctx.fillStyle = asString(styles.color);
                                this.ctx.textBaseline = 'middle';
                                this.ctx.textAlign = 'right';
                                bounds = new Bounds(container.bounds.left, container.bounds.top + getAbsoluteValue(container.styles.paddingTop, container.bounds.width), container.bounds.width, computeLineHeight(styles.lineHeight, styles.fontSize.number) / 2 + 1);
                                this.renderTextWithLetterSpacing(new TextBounds(paint.listValue, bounds), styles.letterSpacing, computeLineHeight(styles.lineHeight, styles.fontSize.number) / 2 + 2);
                                this.ctx.textBaseline = 'bottom';
                                this.ctx.textAlign = 'left';
                            }
                            _c.label = 20;
                        case 20: return [2 /*return*/];
                    }
                });
            });
        };
        CanvasRenderer.prototype.renderStackContent = function (stack) {
            return __awaiter(this, void 0, void 0, function () {
                var _i, _a, child, _b, _c, child, _d, _e, child, _f, _g, child, _h, _j, child, _k, _l, child, _m, _o, child;
                return __generator(this, function (_p) {
                    switch (_p.label) {
                        case 0:
                            if (contains(stack.element.container.flags, 16 /* DEBUG_RENDER */)) {
                                debugger;
                            }
                            // https://www.w3.org/TR/css-position-3/#painting-order
                            // 1. the background and borders of the element forming the stacking context.
                            return [4 /*yield*/, this.renderNodeBackgroundAndBorders(stack.element)];
                        case 1:
                            // https://www.w3.org/TR/css-position-3/#painting-order
                            // 1. the background and borders of the element forming the stacking context.
                            _p.sent();
                            _i = 0, _a = stack.negativeZIndex;
                            _p.label = 2;
                        case 2:
                            if (!(_i < _a.length)) return [3 /*break*/, 5];
                            child = _a[_i];
                            return [4 /*yield*/, this.renderStack(child)];
                        case 3:
                            _p.sent();
                            _p.label = 4;
                        case 4:
                            _i++;
                            return [3 /*break*/, 2];
                        case 5: 
                        // 3. For all its in-flow, non-positioned, block-level descendants in tree order:
                        return [4 /*yield*/, this.renderNodeContent(stack.element)];
                        case 6:
                            // 3. For all its in-flow, non-positioned, block-level descendants in tree order:
                            _p.sent();
                            _b = 0, _c = stack.nonInlineLevel;
                            _p.label = 7;
                        case 7:
                            if (!(_b < _c.length)) return [3 /*break*/, 10];
                            child = _c[_b];
                            return [4 /*yield*/, this.renderNode(child)];
                        case 8:
                            _p.sent();
                            _p.label = 9;
                        case 9:
                            _b++;
                            return [3 /*break*/, 7];
                        case 10:
                            _d = 0, _e = stack.nonPositionedFloats;
                            _p.label = 11;
                        case 11:
                            if (!(_d < _e.length)) return [3 /*break*/, 14];
                            child = _e[_d];
                            return [4 /*yield*/, this.renderStack(child)];
                        case 12:
                            _p.sent();
                            _p.label = 13;
                        case 13:
                            _d++;
                            return [3 /*break*/, 11];
                        case 14:
                            _f = 0, _g = stack.nonPositionedInlineLevel;
                            _p.label = 15;
                        case 15:
                            if (!(_f < _g.length)) return [3 /*break*/, 18];
                            child = _g[_f];
                            return [4 /*yield*/, this.renderStack(child)];
                        case 16:
                            _p.sent();
                            _p.label = 17;
                        case 17:
                            _f++;
                            return [3 /*break*/, 15];
                        case 18:
                            _h = 0, _j = stack.inlineLevel;
                            _p.label = 19;
                        case 19:
                            if (!(_h < _j.length)) return [3 /*break*/, 22];
                            child = _j[_h];
                            return [4 /*yield*/, this.renderNode(child)];
                        case 20:
                            _p.sent();
                            _p.label = 21;
                        case 21:
                            _h++;
                            return [3 /*break*/, 19];
                        case 22:
                            _k = 0, _l = stack.zeroOrAutoZIndexOrTransformedOrOpacity;
                            _p.label = 23;
                        case 23:
                            if (!(_k < _l.length)) return [3 /*break*/, 26];
                            child = _l[_k];
                            return [4 /*yield*/, this.renderStack(child)];
                        case 24:
                            _p.sent();
                            _p.label = 25;
                        case 25:
                            _k++;
                            return [3 /*break*/, 23];
                        case 26:
                            _m = 0, _o = stack.positiveZIndex;
                            _p.label = 27;
                        case 27:
                            if (!(_m < _o.length)) return [3 /*break*/, 30];
                            child = _o[_m];
                            return [4 /*yield*/, this.renderStack(child)];
                        case 28:
                            _p.sent();
                            _p.label = 29;
                        case 29:
                            _m++;
                            return [3 /*break*/, 27];
                        case 30: return [2 /*return*/];
                    }
                });
            });
        };
        CanvasRenderer.prototype.mask = function (paths) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, 0);
            this.ctx.lineTo(this.canvas.width, 0);
            this.ctx.lineTo(this.canvas.width, this.canvas.height);
            this.ctx.lineTo(0, this.canvas.height);
            this.ctx.lineTo(0, 0);
            this.formatPath(paths.slice(0).reverse());
            this.ctx.closePath();
        };
        CanvasRenderer.prototype.path = function (paths) {
            this.ctx.beginPath();
            this.formatPath(paths);
            this.ctx.closePath();
        };
        CanvasRenderer.prototype.formatPath = function (paths) {
            var _this = this;
            paths.forEach(function (point, index) {
                var start = isBezierCurve(point) ? point.start : point;
                if (index === 0) {
                    _this.ctx.moveTo(start.x, start.y);
                }
                else {
                    _this.ctx.lineTo(start.x, start.y);
                }
                if (isBezierCurve(point)) {
                    _this.ctx.bezierCurveTo(point.startControl.x, point.startControl.y, point.endControl.x, point.endControl.y, point.end.x, point.end.y);
                }
            });
        };
        CanvasRenderer.prototype.renderRepeat = function (path, pattern, offsetX, offsetY) {
            this.path(path);
            this.ctx.fillStyle = pattern;
            this.ctx.translate(offsetX, offsetY);
            this.ctx.fill();
            this.ctx.translate(-offsetX, -offsetY);
        };
        CanvasRenderer.prototype.resizeImage = function (image, width, height) {
            var _a;
            if (image.width === width && image.height === height) {
                return image;
            }
            var ownerDocument = (_a = this.canvas.ownerDocument) !== null && _a !== void 0 ? _a : document;
            var canvas = ownerDocument.createElement('canvas');
            canvas.width = Math.max(1, width);
            canvas.height = Math.max(1, height);
            var ctx = canvas.getContext('2d');
            ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, width, height);
            return canvas;
        };
        CanvasRenderer.prototype.renderBackgroundImage = function (container) {
            return __awaiter(this, void 0, void 0, function () {
                var index, _loop_1, this_1, _i, _a, backgroundImage;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            index = container.styles.backgroundImage.length - 1;
                            _loop_1 = function (backgroundImage) {
                                var image, url, _c, path, x, y, width, height, pattern, _d, path, x, y, width, height, _e, lineLength, x0, x1, y0, y1, canvas, ctx, gradient_1, pattern, _f, path, left, top_1, width, height, position, x, y, _g, rx, ry, radialGradient_1, midX, midY, f, invF;
                                return __generator(this, function (_h) {
                                    switch (_h.label) {
                                        case 0:
                                            if (!(backgroundImage.type === 0 /* URL */)) return [3 /*break*/, 5];
                                            image = void 0;
                                            url = backgroundImage.url;
                                            _h.label = 1;
                                        case 1:
                                            _h.trys.push([1, 3, , 4]);
                                            return [4 /*yield*/, this_1.context.cache.match(url)];
                                        case 2:
                                            image = _h.sent();
                                            return [3 /*break*/, 4];
                                        case 3:
                                            _h.sent();
                                            this_1.context.logger.error("Error loading background-image " + url);
                                            return [3 /*break*/, 4];
                                        case 4:
                                            if (image) {
                                                _c = calculateBackgroundRendering(container, index, [
                                                    image.width,
                                                    image.height,
                                                    image.width / image.height
                                                ]), path = _c[0], x = _c[1], y = _c[2], width = _c[3], height = _c[4];
                                                pattern = this_1.ctx.createPattern(this_1.resizeImage(image, width, height), 'repeat');
                                                this_1.renderRepeat(path, pattern, x, y);
                                            }
                                            return [3 /*break*/, 6];
                                        case 5:
                                            if (isLinearGradient(backgroundImage)) {
                                                _d = calculateBackgroundRendering(container, index, [null, null, null]), path = _d[0], x = _d[1], y = _d[2], width = _d[3], height = _d[4];
                                                _e = calculateGradientDirection(backgroundImage.angle, width, height), lineLength = _e[0], x0 = _e[1], x1 = _e[2], y0 = _e[3], y1 = _e[4];
                                                canvas = document.createElement('canvas');
                                                canvas.width = width;
                                                canvas.height = height;
                                                ctx = canvas.getContext('2d');
                                                gradient_1 = ctx.createLinearGradient(x0, y0, x1, y1);
                                                processColorStops(backgroundImage.stops, lineLength).forEach(function (colorStop) {
                                                    return gradient_1.addColorStop(colorStop.stop, asString(colorStop.color));
                                                });
                                                ctx.fillStyle = gradient_1;
                                                ctx.fillRect(0, 0, width, height);
                                                if (width > 0 && height > 0) {
                                                    pattern = this_1.ctx.createPattern(canvas, 'repeat');
                                                    this_1.renderRepeat(path, pattern, x, y);
                                                }
                                            }
                                            else if (isRadialGradient(backgroundImage)) {
                                                _f = calculateBackgroundRendering(container, index, [
                                                    null,
                                                    null,
                                                    null
                                                ]), path = _f[0], left = _f[1], top_1 = _f[2], width = _f[3], height = _f[4];
                                                position = backgroundImage.position.length === 0 ? [FIFTY_PERCENT] : backgroundImage.position;
                                                x = getAbsoluteValue(position[0], width);
                                                y = getAbsoluteValue(position[position.length - 1], height);
                                                _g = calculateRadius(backgroundImage, x, y, width, height), rx = _g[0], ry = _g[1];
                                                if (rx > 0 && ry > 0) {
                                                    radialGradient_1 = this_1.ctx.createRadialGradient(left + x, top_1 + y, 0, left + x, top_1 + y, rx);
                                                    processColorStops(backgroundImage.stops, rx * 2).forEach(function (colorStop) {
                                                        return radialGradient_1.addColorStop(colorStop.stop, asString(colorStop.color));
                                                    });
                                                    this_1.path(path);
                                                    this_1.ctx.fillStyle = radialGradient_1;
                                                    if (rx !== ry) {
                                                        midX = container.bounds.left + 0.5 * container.bounds.width;
                                                        midY = container.bounds.top + 0.5 * container.bounds.height;
                                                        f = ry / rx;
                                                        invF = 1 / f;
                                                        this_1.ctx.save();
                                                        this_1.ctx.translate(midX, midY);
                                                        this_1.ctx.transform(1, 0, 0, f, 0, 0);
                                                        this_1.ctx.translate(-midX, -midY);
                                                        this_1.ctx.fillRect(left, invF * (top_1 - midY) + midY, width, height * invF);
                                                        this_1.ctx.restore();
                                                    }
                                                    else {
                                                        this_1.ctx.fill();
                                                    }
                                                }
                                            }
                                            _h.label = 6;
                                        case 6:
                                            index--;
                                            return [2 /*return*/];
                                    }
                                });
                            };
                            this_1 = this;
                            _i = 0, _a = container.styles.backgroundImage.slice(0).reverse();
                            _b.label = 1;
                        case 1:
                            if (!(_i < _a.length)) return [3 /*break*/, 4];
                            backgroundImage = _a[_i];
                            return [5 /*yield**/, _loop_1(backgroundImage)];
                        case 2:
                            _b.sent();
                            _b.label = 3;
                        case 3:
                            _i++;
                            return [3 /*break*/, 1];
                        case 4: return [2 /*return*/];
                    }
                });
            });
        };
        CanvasRenderer.prototype.renderSolidBorder = function (color, side, curvePoints) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    this.path(parsePathForBorder(curvePoints, side));
                    this.ctx.fillStyle = asString(color);
                    this.ctx.fill();
                    return [2 /*return*/];
                });
            });
        };
        CanvasRenderer.prototype.renderDoubleBorder = function (color, width, side, curvePoints) {
            return __awaiter(this, void 0, void 0, function () {
                var outerPaths, innerPaths;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(width < 3)) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.renderSolidBorder(color, side, curvePoints)];
                        case 1:
                            _a.sent();
                            return [2 /*return*/];
                        case 2:
                            outerPaths = parsePathForBorderDoubleOuter(curvePoints, side);
                            this.path(outerPaths);
                            this.ctx.fillStyle = asString(color);
                            this.ctx.fill();
                            innerPaths = parsePathForBorderDoubleInner(curvePoints, side);
                            this.path(innerPaths);
                            this.ctx.fill();
                            return [2 /*return*/];
                    }
                });
            });
        };
        CanvasRenderer.prototype.renderNodeBackgroundAndBorders = function (paint) {
            return __awaiter(this, void 0, void 0, function () {
                var styles, hasBackground, borders, backgroundPaintingArea, side, _i, borders_1, border;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.applyEffects(paint.getEffects(2 /* BACKGROUND_BORDERS */));
                            styles = paint.container.styles;
                            hasBackground = !isTransparent(styles.backgroundColor) || styles.backgroundImage.length;
                            borders = [
                                { style: styles.borderTopStyle, color: styles.borderTopColor, width: styles.borderTopWidth },
                                { style: styles.borderRightStyle, color: styles.borderRightColor, width: styles.borderRightWidth },
                                { style: styles.borderBottomStyle, color: styles.borderBottomColor, width: styles.borderBottomWidth },
                                { style: styles.borderLeftStyle, color: styles.borderLeftColor, width: styles.borderLeftWidth }
                            ];
                            backgroundPaintingArea = calculateBackgroundCurvedPaintingArea(getBackgroundValueForIndex(styles.backgroundClip, 0), paint.curves);
                            if (!(hasBackground || styles.boxShadow.length)) return [3 /*break*/, 2];
                            this.ctx.save();
                            this.path(backgroundPaintingArea);
                            this.ctx.clip();
                            if (!isTransparent(styles.backgroundColor)) {
                                this.ctx.fillStyle = asString(styles.backgroundColor);
                                this.ctx.fill();
                            }
                            return [4 /*yield*/, this.renderBackgroundImage(paint.container)];
                        case 1:
                            _a.sent();
                            this.ctx.restore();
                            styles.boxShadow
                                .slice(0)
                                .reverse()
                                .forEach(function (shadow) {
                                _this.ctx.save();
                                var borderBoxArea = calculateBorderBoxPath(paint.curves);
                                var maskOffset = shadow.inset ? 0 : MASK_OFFSET;
                                var shadowPaintingArea = transformPath(borderBoxArea, -maskOffset + (shadow.inset ? 1 : -1) * shadow.spread.number, (shadow.inset ? 1 : -1) * shadow.spread.number, shadow.spread.number * (shadow.inset ? -2 : 2), shadow.spread.number * (shadow.inset ? -2 : 2));
                                if (shadow.inset) {
                                    _this.path(borderBoxArea);
                                    _this.ctx.clip();
                                    _this.mask(shadowPaintingArea);
                                }
                                else {
                                    _this.mask(borderBoxArea);
                                    _this.ctx.clip();
                                    _this.path(shadowPaintingArea);
                                }
                                _this.ctx.shadowOffsetX = shadow.offsetX.number + maskOffset;
                                _this.ctx.shadowOffsetY = shadow.offsetY.number;
                                _this.ctx.shadowColor = asString(shadow.color);
                                _this.ctx.shadowBlur = shadow.blur.number;
                                _this.ctx.fillStyle = shadow.inset ? asString(shadow.color) : 'rgba(0,0,0,1)';
                                _this.ctx.fill();
                                _this.ctx.restore();
                            });
                            _a.label = 2;
                        case 2:
                            side = 0;
                            _i = 0, borders_1 = borders;
                            _a.label = 3;
                        case 3:
                            if (!(_i < borders_1.length)) return [3 /*break*/, 13];
                            border = borders_1[_i];
                            if (!(border.style !== 0 /* NONE */ && !isTransparent(border.color) && border.width > 0)) return [3 /*break*/, 11];
                            if (!(border.style === 2 /* DASHED */)) return [3 /*break*/, 5];
                            return [4 /*yield*/, this.renderDashedDottedBorder(border.color, border.width, side, paint.curves, 2 /* DASHED */)];
                        case 4:
                            _a.sent();
                            return [3 /*break*/, 11];
                        case 5:
                            if (!(border.style === 3 /* DOTTED */)) return [3 /*break*/, 7];
                            return [4 /*yield*/, this.renderDashedDottedBorder(border.color, border.width, side, paint.curves, 3 /* DOTTED */)];
                        case 6:
                            _a.sent();
                            return [3 /*break*/, 11];
                        case 7:
                            if (!(border.style === 4 /* DOUBLE */)) return [3 /*break*/, 9];
                            return [4 /*yield*/, this.renderDoubleBorder(border.color, border.width, side, paint.curves)];
                        case 8:
                            _a.sent();
                            return [3 /*break*/, 11];
                        case 9: return [4 /*yield*/, this.renderSolidBorder(border.color, side, paint.curves)];
                        case 10:
                            _a.sent();
                            _a.label = 11;
                        case 11:
                            side++;
                            _a.label = 12;
                        case 12:
                            _i++;
                            return [3 /*break*/, 3];
                        case 13: return [2 /*return*/];
                    }
                });
            });
        };
        CanvasRenderer.prototype.renderDashedDottedBorder = function (color, width, side, curvePoints, style) {
            return __awaiter(this, void 0, void 0, function () {
                var strokePaths, boxPaths, startX, startY, endX, endY, length, dashLength, spaceLength, useLineDash, multiplier, numberOfDashes, minSpace, maxSpace, path1, path2, path1, path2;
                return __generator(this, function (_a) {
                    this.ctx.save();
                    strokePaths = parsePathForBorderStroke(curvePoints, side);
                    boxPaths = parsePathForBorder(curvePoints, side);
                    if (style === 2 /* DASHED */) {
                        this.path(boxPaths);
                        this.ctx.clip();
                    }
                    if (isBezierCurve(boxPaths[0])) {
                        startX = boxPaths[0].start.x;
                        startY = boxPaths[0].start.y;
                    }
                    else {
                        startX = boxPaths[0].x;
                        startY = boxPaths[0].y;
                    }
                    if (isBezierCurve(boxPaths[1])) {
                        endX = boxPaths[1].end.x;
                        endY = boxPaths[1].end.y;
                    }
                    else {
                        endX = boxPaths[1].x;
                        endY = boxPaths[1].y;
                    }
                    if (side === 0 || side === 2) {
                        length = Math.abs(startX - endX);
                    }
                    else {
                        length = Math.abs(startY - endY);
                    }
                    this.ctx.beginPath();
                    if (style === 3 /* DOTTED */) {
                        this.formatPath(strokePaths);
                    }
                    else {
                        this.formatPath(boxPaths.slice(0, 2));
                    }
                    dashLength = width < 3 ? width * 3 : width * 2;
                    spaceLength = width < 3 ? width * 2 : width;
                    if (style === 3 /* DOTTED */) {
                        dashLength = width;
                        spaceLength = width;
                    }
                    useLineDash = true;
                    if (length <= dashLength * 2) {
                        useLineDash = false;
                    }
                    else if (length <= dashLength * 2 + spaceLength) {
                        multiplier = length / (2 * dashLength + spaceLength);
                        dashLength *= multiplier;
                        spaceLength *= multiplier;
                    }
                    else {
                        numberOfDashes = Math.floor((length + spaceLength) / (dashLength + spaceLength));
                        minSpace = (length - numberOfDashes * dashLength) / (numberOfDashes - 1);
                        maxSpace = (length - (numberOfDashes + 1) * dashLength) / numberOfDashes;
                        spaceLength =
                            maxSpace <= 0 || Math.abs(spaceLength - minSpace) < Math.abs(spaceLength - maxSpace)
                                ? minSpace
                                : maxSpace;
                    }
                    if (useLineDash) {
                        if (style === 3 /* DOTTED */) {
                            this.ctx.setLineDash([0, dashLength + spaceLength]);
                        }
                        else {
                            this.ctx.setLineDash([dashLength, spaceLength]);
                        }
                    }
                    if (style === 3 /* DOTTED */) {
                        this.ctx.lineCap = 'round';
                        this.ctx.lineWidth = width;
                    }
                    else {
                        this.ctx.lineWidth = width * 2 + 1.1;
                    }
                    this.ctx.strokeStyle = asString(color);
                    this.ctx.stroke();
                    this.ctx.setLineDash([]);
                    // dashed round edge gap
                    if (style === 2 /* DASHED */) {
                        if (isBezierCurve(boxPaths[0])) {
                            path1 = boxPaths[3];
                            path2 = boxPaths[0];
                            this.ctx.beginPath();
                            this.formatPath([new Vector(path1.end.x, path1.end.y), new Vector(path2.start.x, path2.start.y)]);
                            this.ctx.stroke();
                        }
                        if (isBezierCurve(boxPaths[1])) {
                            path1 = boxPaths[1];
                            path2 = boxPaths[2];
                            this.ctx.beginPath();
                            this.formatPath([new Vector(path1.end.x, path1.end.y), new Vector(path2.start.x, path2.start.y)]);
                            this.ctx.stroke();
                        }
                    }
                    this.ctx.restore();
                    return [2 /*return*/];
                });
            });
        };
        CanvasRenderer.prototype.render = function (element) {
            return __awaiter(this, void 0, void 0, function () {
                var stack;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (this.options.backgroundColor) {
                                this.ctx.fillStyle = asString(this.options.backgroundColor);
                                this.ctx.fillRect(this.options.x, this.options.y, this.options.width, this.options.height);
                            }
                            stack = parseStackingContexts(element);
                            return [4 /*yield*/, this.renderStack(stack)];
                        case 1:
                            _a.sent();
                            this.applyEffects([]);
                            return [2 /*return*/, this.canvas];
                    }
                });
            });
        };
        return CanvasRenderer;
    }(Renderer));
    var isTextInputElement = function (container) {
        if (container instanceof TextareaElementContainer) {
            return true;
        }
        else if (container instanceof SelectElementContainer) {
            return true;
        }
        else if (container instanceof InputElementContainer && container.type !== RADIO && container.type !== CHECKBOX) {
            return true;
        }
        return false;
    };
    var calculateBackgroundCurvedPaintingArea = function (clip, curves) {
        switch (clip) {
            case 0 /* BORDER_BOX */:
                return calculateBorderBoxPath(curves);
            case 2 /* CONTENT_BOX */:
                return calculateContentBoxPath(curves);
            case 1 /* PADDING_BOX */:
            default:
                return calculatePaddingBoxPath(curves);
        }
    };
    var canvasTextAlign = function (textAlign) {
        switch (textAlign) {
            case 1 /* CENTER */:
                return 'center';
            case 2 /* RIGHT */:
                return 'right';
            case 0 /* LEFT */:
            default:
                return 'left';
        }
    };
    // see https://github.com/niklasvh/html2canvas/pull/2645
    var iOSBrokenFonts = ['-apple-system', 'system-ui'];
    var fixIOSSystemFonts = function (fontFamilies) {
        return /iPhone OS 15_(0|1)/.test(window.navigator.userAgent)
            ? fontFamilies.filter(function (fontFamily) { return iOSBrokenFonts.indexOf(fontFamily) === -1; })
            : fontFamilies;
    };

    var ForeignObjectRenderer = /** @class */ (function (_super) {
        __extends(ForeignObjectRenderer, _super);
        function ForeignObjectRenderer(context, options) {
            var _this = _super.call(this, context, options) || this;
            _this.canvas = options.canvas ? options.canvas : document.createElement('canvas');
            _this.ctx = _this.canvas.getContext('2d');
            _this.options = options;
            _this.canvas.width = Math.floor(options.width * options.scale);
            _this.canvas.height = Math.floor(options.height * options.scale);
            _this.canvas.style.width = options.width + "px";
            _this.canvas.style.height = options.height + "px";
            _this.ctx.scale(_this.options.scale, _this.options.scale);
            _this.ctx.translate(-options.x, -options.y);
            _this.context.logger.debug("EXPERIMENTAL ForeignObject renderer initialized (" + options.width + "x" + options.height + " at " + options.x + "," + options.y + ") with scale " + options.scale);
            return _this;
        }
        ForeignObjectRenderer.prototype.render = function (element) {
            return __awaiter(this, void 0, void 0, function () {
                var svg, img;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            svg = createForeignObjectSVG(this.options.width * this.options.scale, this.options.height * this.options.scale, this.options.scale, this.options.scale, element);
                            return [4 /*yield*/, loadSerializedSVG(svg)];
                        case 1:
                            img = _a.sent();
                            if (this.options.backgroundColor) {
                                this.ctx.fillStyle = asString(this.options.backgroundColor);
                                this.ctx.fillRect(0, 0, this.options.width * this.options.scale, this.options.height * this.options.scale);
                            }
                            this.ctx.drawImage(img, -this.options.x * this.options.scale, -this.options.y * this.options.scale);
                            return [2 /*return*/, this.canvas];
                    }
                });
            });
        };
        return ForeignObjectRenderer;
    }(Renderer));
    var loadSerializedSVG = function (svg) {
        return new Promise(function (resolve, reject) {
            var img = new Image();
            img.onload = function () {
                resolve(img);
            };
            img.onerror = reject;
            img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg));
        });
    };

    var Logger = /** @class */ (function () {
        function Logger(_a) {
            var id = _a.id, enabled = _a.enabled;
            this.id = id;
            this.enabled = enabled;
            this.start = Date.now();
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        Logger.prototype.debug = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            if (this.enabled) {
                // eslint-disable-next-line no-console
                if (typeof window !== 'undefined' && window.console && typeof console.debug === 'function') {
                    // eslint-disable-next-line no-console
                    console.debug.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
                }
                else {
                    this.info.apply(this, args);
                }
            }
        };
        Logger.prototype.getTime = function () {
            return Date.now() - this.start;
        };
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        Logger.prototype.info = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            if (this.enabled) {
                // eslint-disable-next-line no-console
                if (typeof window !== 'undefined' && window.console && typeof console.info === 'function') {
                    // eslint-disable-next-line no-console
                    console.info.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
                }
            }
        };
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        Logger.prototype.warn = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            if (this.enabled) {
                // eslint-disable-next-line no-console
                if (typeof window !== 'undefined' && window.console && typeof console.warn === 'function') {
                    // eslint-disable-next-line no-console
                    console.warn.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
                }
                else {
                    this.info.apply(this, args);
                }
            }
        };
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        Logger.prototype.error = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            if (this.enabled) {
                // eslint-disable-next-line no-console
                if (typeof window !== 'undefined' && window.console && typeof console.error === 'function') {
                    // eslint-disable-next-line no-console
                    console.error.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
                }
                else {
                    this.info.apply(this, args);
                }
            }
        };
        Logger.instances = {};
        return Logger;
    }());

    var Context = /** @class */ (function () {
        function Context(options, windowBounds) {
            var _a;
            this.windowBounds = windowBounds;
            this.instanceName = "#" + Context.instanceCount++;
            this.logger = new Logger({ id: this.instanceName, enabled: options.logging });
            this.cache = (_a = options.cache) !== null && _a !== void 0 ? _a : new Cache(this, options);
        }
        Context.instanceCount = 1;
        return Context;
    }());

    var html2canvas = function (element, options) {
        if (options === void 0) { options = {}; }
        return renderElement(element, options);
    };
    if (typeof window !== 'undefined') {
        CacheStorage.setContext(window);
    }
    var renderElement = function (element, opts) { return __awaiter(void 0, void 0, void 0, function () {
        var ownerDocument, defaultView, resourceOptions, contextOptions, windowOptions, windowBounds, context, foreignObjectRendering, cloneOptions, documentCloner, clonedElement, container, _a, width, height, left, top, backgroundColor, renderOptions, canvas, renderer, root, renderer;
        var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
        return __generator(this, function (_u) {
            switch (_u.label) {
                case 0:
                    if (!element || typeof element !== 'object') {
                        return [2 /*return*/, Promise.reject('Invalid element provided as first argument')];
                    }
                    ownerDocument = element.ownerDocument;
                    if (!ownerDocument) {
                        throw new Error("Element is not attached to a Document");
                    }
                    defaultView = ownerDocument.defaultView;
                    if (!defaultView) {
                        throw new Error("Document is not attached to a Window");
                    }
                    resourceOptions = {
                        allowTaint: (_b = opts.allowTaint) !== null && _b !== void 0 ? _b : false,
                        imageTimeout: (_c = opts.imageTimeout) !== null && _c !== void 0 ? _c : 15000,
                        proxy: opts.proxy,
                        useCORS: (_d = opts.useCORS) !== null && _d !== void 0 ? _d : false
                    };
                    contextOptions = __assign({ logging: (_e = opts.logging) !== null && _e !== void 0 ? _e : true, cache: opts.cache }, resourceOptions);
                    windowOptions = {
                        windowWidth: (_f = opts.windowWidth) !== null && _f !== void 0 ? _f : defaultView.innerWidth,
                        windowHeight: (_g = opts.windowHeight) !== null && _g !== void 0 ? _g : defaultView.innerHeight,
                        scrollX: (_h = opts.scrollX) !== null && _h !== void 0 ? _h : defaultView.pageXOffset,
                        scrollY: (_j = opts.scrollY) !== null && _j !== void 0 ? _j : defaultView.pageYOffset
                    };
                    windowBounds = new Bounds(windowOptions.scrollX, windowOptions.scrollY, windowOptions.windowWidth, windowOptions.windowHeight);
                    context = new Context(contextOptions, windowBounds);
                    foreignObjectRendering = (_k = opts.foreignObjectRendering) !== null && _k !== void 0 ? _k : false;
                    cloneOptions = {
                        allowTaint: (_l = opts.allowTaint) !== null && _l !== void 0 ? _l : false,
                        onclone: opts.onclone,
                        ignoreElements: opts.ignoreElements,
                        inlineImages: foreignObjectRendering,
                        copyStyles: foreignObjectRendering
                    };
                    context.logger.debug("Starting document clone with size " + windowBounds.width + "x" + windowBounds.height + " scrolled to " + -windowBounds.left + "," + -windowBounds.top);
                    documentCloner = new DocumentCloner(context, element, cloneOptions);
                    clonedElement = documentCloner.clonedReferenceElement;
                    if (!clonedElement) {
                        return [2 /*return*/, Promise.reject("Unable to find element in cloned iframe")];
                    }
                    return [4 /*yield*/, documentCloner.toIFrame(ownerDocument, windowBounds)];
                case 1:
                    container = _u.sent();
                    _a = isBodyElement(clonedElement) || isHTMLElement(clonedElement)
                        ? parseDocumentSize(clonedElement.ownerDocument)
                        : parseBounds(context, clonedElement), width = _a.width, height = _a.height, left = _a.left, top = _a.top;
                    backgroundColor = parseBackgroundColor(context, clonedElement, opts.backgroundColor);
                    renderOptions = {
                        canvas: opts.canvas,
                        backgroundColor: backgroundColor,
                        scale: (_o = (_m = opts.scale) !== null && _m !== void 0 ? _m : defaultView.devicePixelRatio) !== null && _o !== void 0 ? _o : 1,
                        x: ((_p = opts.x) !== null && _p !== void 0 ? _p : 0) + left,
                        y: ((_q = opts.y) !== null && _q !== void 0 ? _q : 0) + top,
                        width: (_r = opts.width) !== null && _r !== void 0 ? _r : Math.ceil(width),
                        height: (_s = opts.height) !== null && _s !== void 0 ? _s : Math.ceil(height)
                    };
                    if (!foreignObjectRendering) return [3 /*break*/, 3];
                    context.logger.debug("Document cloned, using foreign object rendering");
                    renderer = new ForeignObjectRenderer(context, renderOptions);
                    return [4 /*yield*/, renderer.render(clonedElement)];
                case 2:
                    canvas = _u.sent();
                    return [3 /*break*/, 5];
                case 3:
                    context.logger.debug("Document cloned, element located at " + left + "," + top + " with size " + width + "x" + height + " using computed rendering");
                    context.logger.debug("Starting DOM parsing");
                    root = parseTree(context, clonedElement);
                    if (backgroundColor === root.styles.backgroundColor) {
                        root.styles.backgroundColor = COLORS.TRANSPARENT;
                    }
                    context.logger.debug("Starting renderer for element at " + renderOptions.x + "," + renderOptions.y + " with size " + renderOptions.width + "x" + renderOptions.height);
                    renderer = new CanvasRenderer(context, renderOptions);
                    return [4 /*yield*/, renderer.render(root)];
                case 4:
                    canvas = _u.sent();
                    _u.label = 5;
                case 5:
                    if ((_t = opts.removeContainer) !== null && _t !== void 0 ? _t : true) {
                        if (!DocumentCloner.destroy(container)) {
                            context.logger.error("Cannot detach cloned iframe as it is not in the DOM anymore");
                        }
                    }
                    context.logger.debug("Finished rendering");
                    return [2 /*return*/, canvas];
            }
        });
    }); };
    var parseBackgroundColor = function (context, element, backgroundColorOverride) {
        var ownerDocument = element.ownerDocument;
        // http://www.w3.org/TR/css3-background/#special-backgrounds
        var documentBackgroundColor = ownerDocument.documentElement
            ? parseColor(context, getComputedStyle(ownerDocument.documentElement).backgroundColor)
            : COLORS.TRANSPARENT;
        var bodyBackgroundColor = ownerDocument.body
            ? parseColor(context, getComputedStyle(ownerDocument.body).backgroundColor)
            : COLORS.TRANSPARENT;
        var defaultBackgroundColor = typeof backgroundColorOverride === 'string'
            ? parseColor(context, backgroundColorOverride)
            : backgroundColorOverride === null
                ? COLORS.TRANSPARENT
                : 0xffffffff;
        return element === ownerDocument.documentElement
            ? isTransparent(documentBackgroundColor)
                ? isTransparent(bodyBackgroundColor)
                    ? defaultBackgroundColor
                    : bodyBackgroundColor
                : documentBackgroundColor
            : defaultBackgroundColor;
    };

    return html2canvas;

})));
//# sourceMappingURL=html2canvas.js.map


/***/ })

/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/ 
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ 	// Check if module is in cache
/******/ 	var cachedModule = __webpack_module_cache__[moduleId];
/******/ 	if (cachedModule !== undefined) {
/******/ 		return cachedModule.exports;
/******/ 	}
/******/ 	// Create a new module (and put it into the cache)
/******/ 	var module = __webpack_module_cache__[moduleId] = {
/******/ 		// no module.id needed
/******/ 		// no module.loaded needed
/******/ 		exports: {}
/******/ 	};
/******/ 
/******/ 	// Execute the module function
/******/ 	__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 
/******/ 	// Return the exports of the module
/******/ 	return module.exports;
/******/ }
/******/ 
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ (() => {
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = (module) => {
/******/ 		var getter = module && module.__esModule ?
/******/ 			() => (module['default']) :
/******/ 			() => (module);
/******/ 		__webpack_require__.d(getter, { a: getter });
/******/ 		return getter;
/******/ 	};
/******/ })();
/******/ 
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ 	// define getter functions for harmony exports
/******/ 	__webpack_require__.d = (exports, definition) => {
/******/ 		for(var key in definition) {
/******/ 			if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 				Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 			}
/******/ 		}
/******/ 	};
/******/ })();
/******/ 
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ 	__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/ 
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = (exports) => {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/ })();
/******/ 
/************************************************************************/
var __webpack_exports__ = {};

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  z: () => (/* reexport */ standalone_CanvasSummary_svelte)
});

// NAMESPACE OBJECT: ../../node_modules/vega-transforms/build/vega-transforms.module.js
var standalone_vega_transforms_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_transforms_module_namespaceObject);
__webpack_require__.d(standalone_vega_transforms_module_namespaceObject, {
  aggregate: () => (standalone_Aggregate),
  bin: () => (standalone_Bin),
  collect: () => (standalone_Collect),
  compare: () => (standalone_Compare),
  countpattern: () => (standalone_CountPattern),
  cross: () => (standalone_Cross),
  density: () => (standalone_Density),
  dotbin: () => (standalone_DotBin),
  expression: () => (standalone_Expression),
  extent: () => (standalone_Extent),
  facet: () => (standalone_Facet),
  field: () => (standalone_Field),
  filter: () => (standalone_Filter),
  flatten: () => (standalone_Flatten),
  fold: () => (standalone_Fold),
  formula: () => (standalone_Formula),
  generate: () => (standalone_Generate),
  impute: () => (standalone_Impute),
  joinaggregate: () => (standalone_JoinAggregate),
  kde: () => (standalone_KDE),
  key: () => (standalone_Key),
  load: () => (standalone_Load),
  lookup: () => (standalone_Lookup),
  multiextent: () => (standalone_MultiExtent),
  multivalues: () => (standalone_MultiValues),
  params: () => (standalone_Params),
  pivot: () => (standalone_Pivot),
  prefacet: () => (standalone_PreFacet),
  project: () => (standalone_Project),
  proxy: () => (standalone_vega_transforms_module_Proxy),
  quantile: () => (standalone_Quantile),
  relay: () => (standalone_Relay),
  sample: () => (standalone_Sample),
  sequence: () => (standalone_Sequence),
  sieve: () => (standalone_Sieve),
  subflow: () => (standalone_Subflow),
  timeunit: () => (standalone_TimeUnit),
  tupleindex: () => (standalone_TupleIndex),
  values: () => (standalone_Values),
  window: () => (standalone_Window)
});

// NAMESPACE OBJECT: ../../node_modules/d3-interpolate/src/index.js
var standalone_d3_interpolate_src_namespaceObject = {};
__webpack_require__.r(standalone_d3_interpolate_src_namespaceObject);
__webpack_require__.d(standalone_d3_interpolate_src_namespaceObject, {
  interpolate: () => (standalone_value),
  interpolateArray: () => (standalone_d3_interpolate_src_array),
  interpolateBasis: () => (standalone_src_basis),
  interpolateBasisClosed: () => (standalone_src_basisClosed),
  interpolateCubehelix: () => (standalone_src_cubehelix),
  interpolateCubehelixLong: () => (standalone_cubehelixLong),
  interpolateDate: () => (standalone_date),
  interpolateDiscrete: () => (standalone_discrete),
  interpolateHcl: () => (standalone_src_hcl),
  interpolateHclLong: () => (standalone_hclLong),
  interpolateHsl: () => (standalone_src_hsl),
  interpolateHslLong: () => (standalone_hslLong),
  interpolateHue: () => (standalone_src_hue),
  interpolateLab: () => (standalone_lab_lab),
  interpolateNumber: () => (standalone_src_number),
  interpolateNumberArray: () => (standalone_numberArray),
  interpolateObject: () => (standalone_src_object),
  interpolateRgb: () => (standalone_rgb),
  interpolateRgbBasis: () => (standalone_rgbBasis),
  interpolateRgbBasisClosed: () => (standalone_rgbBasisClosed),
  interpolateRound: () => (standalone_src_round),
  interpolateString: () => (standalone_string),
  interpolateTransformCss: () => (standalone_interpolateTransformCss),
  interpolateTransformSvg: () => (standalone_interpolateTransformSvg),
  interpolateZoom: () => (standalone_src_zoom),
  piecewise: () => (standalone_piecewise),
  quantize: () => (standalone_src_quantize)
});

// NAMESPACE OBJECT: ../../node_modules/vega-view-transforms/build/vega-view-transforms.module.js
var standalone_vega_view_transforms_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_view_transforms_module_namespaceObject);
__webpack_require__.d(standalone_vega_view_transforms_module_namespaceObject, {
  bound: () => (standalone_Bound),
  identifier: () => (standalone_Identifier),
  mark: () => (standalone_Mark),
  overlap: () => (standalone_Overlap),
  render: () => (standalone_Render),
  viewlayout: () => (standalone_ViewLayout)
});

// NAMESPACE OBJECT: ../../node_modules/vega-encode/build/vega-encode.module.js
var standalone_vega_encode_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_encode_module_namespaceObject);
__webpack_require__.d(standalone_vega_encode_module_namespaceObject, {
  axisticks: () => (standalone_AxisTicks),
  datajoin: () => (standalone_DataJoin),
  encode: () => (standalone_Encode),
  legendentries: () => (standalone_LegendEntries),
  linkpath: () => (standalone_LinkPath),
  pie: () => (standalone_Pie),
  scale: () => (standalone_Scale),
  sortitems: () => (standalone_SortItems),
  stack: () => (standalone_Stack)
});

// NAMESPACE OBJECT: ../../node_modules/vega-geo/build/vega-geo.module.js
var standalone_vega_geo_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_geo_module_namespaceObject);
__webpack_require__.d(standalone_vega_geo_module_namespaceObject, {
  contour: () => (standalone_Contour),
  geojson: () => (standalone_GeoJSON),
  geopath: () => (standalone_GeoPath),
  geopoint: () => (standalone_GeoPoint),
  geoshape: () => (standalone_GeoShape),
  graticule: () => (standalone_Graticule),
  heatmap: () => (standalone_Heatmap),
  isocontour: () => (standalone_Isocontour),
  kde2d: () => (standalone_KDE2D),
  projection: () => (standalone_Projection)
});

// NAMESPACE OBJECT: ../../node_modules/vega-force/build/vega-force.module.js
var standalone_vega_force_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_force_module_namespaceObject);
__webpack_require__.d(standalone_vega_force_module_namespaceObject, {
  force: () => (standalone_Force)
});

// NAMESPACE OBJECT: ../../node_modules/vega-hierarchy/build/vega-hierarchy.module.js
var standalone_vega_hierarchy_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_hierarchy_module_namespaceObject);
__webpack_require__.d(standalone_vega_hierarchy_module_namespaceObject, {
  nest: () => (standalone_Nest),
  pack: () => (standalone_Pack),
  partition: () => (standalone_Partition),
  stratify: () => (standalone_Stratify),
  tree: () => (standalone_Tree),
  treelinks: () => (standalone_TreeLinks),
  treemap: () => (standalone_Treemap)
});

// NAMESPACE OBJECT: ../../node_modules/vega-label/build/vega-label.module.js
var standalone_vega_label_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_label_module_namespaceObject);
__webpack_require__.d(standalone_vega_label_module_namespaceObject, {
  label: () => (standalone_Label)
});

// NAMESPACE OBJECT: ../../node_modules/vega-regression/build/vega-regression.module.js
var standalone_vega_regression_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_regression_module_namespaceObject);
__webpack_require__.d(standalone_vega_regression_module_namespaceObject, {
  loess: () => (standalone_Loess),
  regression: () => (standalone_Regression)
});

// NAMESPACE OBJECT: ../../node_modules/vega-voronoi/build/vega-voronoi.module.js
var standalone_vega_voronoi_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_voronoi_module_namespaceObject);
__webpack_require__.d(standalone_vega_voronoi_module_namespaceObject, {
  voronoi: () => (standalone_vega_voronoi_module_Voronoi)
});

// NAMESPACE OBJECT: ../../node_modules/vega-wordcloud/build/vega-wordcloud.module.js
var standalone_vega_wordcloud_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_wordcloud_module_namespaceObject);
__webpack_require__.d(standalone_vega_wordcloud_module_namespaceObject, {
  wordcloud: () => (standalone_Wordcloud)
});

// NAMESPACE OBJECT: ../../node_modules/vega-crossfilter/build/vega-crossfilter.module.js
var standalone_vega_crossfilter_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_crossfilter_module_namespaceObject);
__webpack_require__.d(standalone_vega_crossfilter_module_namespaceObject, {
  crossfilter: () => (standalone_CrossFilter),
  resolvefilter: () => (standalone_ResolveFilter)
});

// NAMESPACE OBJECT: ../../node_modules/vega/build/vega.module.js
var standalone_vega_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_module_namespaceObject);
__webpack_require__.d(standalone_vega_module_namespaceObject, {
  Bounds: () => (standalone_Bounds),
  CanvasHandler: () => (standalone_CanvasHandler),
  CanvasRenderer: () => (standalone_CanvasRenderer),
  DATE: () => (standalone_DATE),
  DAY: () => (standalone_DAY),
  DAYOFYEAR: () => (standalone_DAYOFYEAR),
  Dataflow: () => (standalone_Dataflow),
  Debug: () => (standalone_vega_util_module_Debug),
  Error: () => (standalone_Error$1),
  EventStream: () => (standalone_EventStream),
  Gradient: () => (standalone_Gradient),
  GroupItem: () => (standalone_GroupItem),
  HOURS: () => (standalone_HOURS),
  Handler: () => (standalone_Handler),
  HybridHandler: () => (standalone_HybridHandler),
  HybridRenderer: () => (standalone_HybridRenderer),
  Info: () => (standalone_vega_util_module_Info),
  Item: () => (standalone_Item),
  MILLISECONDS: () => (standalone_MILLISECONDS),
  MINUTES: () => (standalone_MINUTES),
  MONTH: () => (standalone_MONTH),
  Marks: () => (standalone_Marks),
  MultiPulse: () => (standalone_MultiPulse),
  None: () => (standalone_None),
  Operator: () => (standalone_Operator),
  Parameters: () => (standalone_Parameters),
  Pulse: () => (standalone_Pulse),
  QUARTER: () => (standalone_QUARTER),
  RenderType: () => (standalone_RenderType),
  Renderer: () => (standalone_Renderer),
  ResourceLoader: () => (standalone_ResourceLoader),
  SECONDS: () => (standalone_SECONDS),
  SVGHandler: () => (standalone_SVGHandler),
  SVGRenderer: () => (standalone_SVGRenderer),
  SVGStringRenderer: () => (standalone_SVGStringRenderer),
  Scenegraph: () => (standalone_Scenegraph),
  TIME_UNITS: () => (standalone_TIME_UNITS),
  Transform: () => (standalone_Transform),
  View: () => (standalone_View),
  WEEK: () => (standalone_WEEK),
  Warn: () => (standalone_vega_util_module_Warn),
  YEAR: () => (standalone_YEAR),
  accessor: () => (standalone_accessor),
  accessorFields: () => (standalone_accessorFields),
  accessorName: () => (standalone_accessorName),
  array: () => (standalone_array),
  ascending: () => (standalone_ascending),
  bandwidthNRD: () => (standalone_estimateBandwidth),
  bin: () => (standalone_vega_statistics_module_bin),
  bootstrapCI: () => (standalone_bootstrapCI),
  boundClip: () => (standalone_boundClip),
  boundContext: () => (standalone_boundContext),
  boundItem: () => (standalone_boundItem),
  boundMark: () => (standalone_boundMark),
  boundStroke: () => (standalone_boundStroke),
  changeset: () => (standalone_changeset),
  clampRange: () => (standalone_clampRange),
  codegenExpression: () => (standalone_codegen),
  compare: () => (standalone_compare),
  constant: () => (standalone_vega_util_module_constant),
  cumulativeLogNormal: () => (standalone_cumulativeLogNormal),
  cumulativeNormal: () => (standalone_cumulativeNormal),
  cumulativeUniform: () => (standalone_cumulativeUniform),
  dayofyear: () => (standalone_dayofyear),
  debounce: () => (standalone_debounce),
  defaultLocale: () => (standalone_vega_format_module_defaultLocale),
  definition: () => (standalone_definition),
  densityLogNormal: () => (standalone_densityLogNormal),
  densityNormal: () => (standalone_densityNormal),
  densityUniform: () => (standalone_densityUniform),
  domChild: () => (standalone_domChild),
  domClear: () => (standalone_domClear),
  domCreate: () => (standalone_domCreate),
  domFind: () => (standalone_domFind),
  dotbin: () => (standalone_dotbin),
  error: () => (standalone_vega_util_module_error),
  expressionFunction: () => (standalone_expressionFunction),
  extend: () => (standalone_extend),
  extent: () => (standalone_extent),
  extentIndex: () => (standalone_extentIndex),
  falsy: () => (standalone_falsy),
  fastmap: () => (standalone_fastmap),
  field: () => (standalone_field),
  flush: () => (standalone_vega_util_module_flush),
  font: () => (standalone_font),
  fontFamily: () => (standalone_fontFamily),
  fontSize: () => (standalone_fontSize),
  format: () => (standalone_vega_loader_browser_module_format),
  formatLocale: () => (standalone_numberFormatDefaultLocale),
  formats: () => (standalone_formats),
  hasOwnProperty: () => (standalone_vega_util_module_has),
  id: () => (standalone_id),
  identity: () => (standalone_vega_util_module_identity),
  inferType: () => (standalone_inferType),
  inferTypes: () => (standalone_inferTypes),
  ingest: () => (standalone_ingest$1),
  inherits: () => (standalone_inherits),
  inrange: () => (standalone_inrange),
  interpolate: () => (standalone_interpolate),
  interpolateColors: () => (standalone_interpolateColors),
  interpolateRange: () => (standalone_interpolateRange),
  intersect: () => (standalone_vega_scenegraph_module_intersect),
  intersectBoxLine: () => (standalone_intersectBoxLine),
  intersectPath: () => (standalone_intersectPath),
  intersectPoint: () => (standalone_intersectPoint),
  intersectRule: () => (standalone_intersectRule),
  isArray: () => (standalone_vega_util_module_isArray),
  isBoolean: () => (standalone_isBoolean),
  isDate: () => (standalone_isDate),
  isFunction: () => (standalone_vega_util_module_isFunction),
  isIterable: () => (standalone_isIterable),
  isNumber: () => (standalone_isNumber),
  isObject: () => (standalone_vega_util_module_isObject),
  isRegExp: () => (standalone_isRegExp),
  isString: () => (standalone_vega_util_module_isString),
  isTuple: () => (standalone_isTuple),
  key: () => (standalone_key),
  lerp: () => (standalone_lerp),
  lineHeight: () => (standalone_lineHeight),
  loader: () => (standalone_loader),
  locale: () => (standalone_vega_format_module_locale),
  logger: () => (standalone_logger),
  lruCache: () => (standalone_lruCache),
  markup: () => (standalone_markup),
  merge: () => (standalone_merge),
  mergeConfig: () => (standalone_mergeConfig),
  multiLineOffset: () => (standalone_multiLineOffset),
  one: () => (standalone_one),
  pad: () => (standalone_pad),
  panLinear: () => (standalone_panLinear),
  panLog: () => (standalone_panLog),
  panPow: () => (standalone_panPow),
  panSymlog: () => (standalone_panSymlog),
  parse: () => (standalone_vega_parser_module_parse),
  parseExpression: () => (standalone_parser),
  parseSelector: () => (standalone_eventSelector),
  path: () => (standalone_path),
  pathCurves: () => (standalone_curves),
  pathEqual: () => (standalone_pathEqual),
  pathParse: () => (standalone_vega_scenegraph_module_parse),
  pathRectangle: () => (standalone_vg_rect),
  pathRender: () => (standalone_pathRender),
  pathSymbols: () => (standalone_vega_scenegraph_module_symbols),
  pathTrail: () => (standalone_vg_trail),
  peek: () => (standalone_peek),
  point: () => (standalone_vega_scenegraph_module_point),
  projection: () => (standalone_vega_projection_module_projection),
  quantileLogNormal: () => (standalone_quantileLogNormal),
  quantileNormal: () => (standalone_quantileNormal),
  quantileUniform: () => (standalone_quantileUniform),
  quantiles: () => (standalone_quantiles),
  quantizeInterpolator: () => (standalone_quantizeInterpolator),
  quarter: () => (standalone_quarter),
  quartiles: () => (standalone_quartiles),
  random: () => (standalone_random),
  randomInteger: () => (standalone_integer),
  randomKDE: () => (standalone_kde),
  randomLCG: () => (standalone_vega_statistics_module_lcg),
  randomLogNormal: () => (standalone_lognormal),
  randomMixture: () => (standalone_mixture),
  randomNormal: () => (standalone_gaussian),
  randomUniform: () => (standalone_uniform),
  read: () => (standalone_read),
  regressionConstant: () => (standalone_vega_statistics_module_constant),
  regressionExp: () => (standalone_vega_statistics_module_exp),
  regressionLinear: () => (standalone_linear),
  regressionLoess: () => (standalone_loess),
  regressionLog: () => (standalone_vega_statistics_module_log),
  regressionPoly: () => (standalone_poly),
  regressionPow: () => (standalone_vega_statistics_module_pow),
  regressionQuad: () => (standalone_quad),
  renderModule: () => (standalone_renderModule),
  repeat: () => (standalone_vega_util_module_repeat),
  resetDefaultLocale: () => (standalone_resetDefaultLocale),
  resetSVGClipId: () => (standalone_resetSVGClipId),
  resetSVGDefIds: () => (standalone_resetSVGDefIds),
  responseType: () => (standalone_responseType),
  runtimeContext: () => (standalone_vega_runtime_module_context),
  sampleCurve: () => (standalone_sampleCurve),
  sampleLogNormal: () => (standalone_sampleLogNormal),
  sampleNormal: () => (standalone_sampleNormal),
  sampleUniform: () => (standalone_sampleUniform),
  scale: () => (standalone_vega_scale_module_scale),
  sceneEqual: () => (standalone_sceneEqual),
  sceneFromJSON: () => (standalone_sceneFromJSON),
  scenePickVisit: () => (standalone_pickVisit),
  sceneToJSON: () => (standalone_sceneToJSON),
  sceneVisit: () => (standalone_visit),
  sceneZOrder: () => (standalone_zorder),
  scheme: () => (standalone_scheme),
  serializeXML: () => (standalone_serializeXML),
  setHybridRendererOptions: () => (standalone_setHybridRendererOptions),
  setRandom: () => (standalone_setRandom),
  span: () => (standalone_span),
  splitAccessPath: () => (standalone_splitAccessPath),
  stringValue: () => (standalone_$),
  textMetrics: () => (standalone_textMetrics),
  timeBin: () => (standalone_bin),
  timeFloor: () => (standalone_timeFloor),
  timeFormatLocale: () => (standalone_timeFormatDefaultLocale),
  timeInterval: () => (standalone_vega_time_module_timeInterval),
  timeOffset: () => (standalone_timeOffset),
  timeSequence: () => (standalone_timeSequence),
  timeUnitSpecifier: () => (standalone_timeUnitSpecifier),
  timeUnits: () => (standalone_timeUnits),
  toBoolean: () => (standalone_toBoolean),
  toDate: () => (standalone_toDate),
  toNumber: () => (standalone_toNumber),
  toSet: () => (standalone_toSet),
  toString: () => (standalone_vega_util_module_toString),
  transform: () => (standalone_vega_dataflow_module_transform),
  transforms: () => (standalone_transforms),
  truncate: () => (standalone_truncate),
  truthy: () => (standalone_truthy),
  tupleid: () => (standalone_tupleid),
  typeParsers: () => (standalone_typeParsers),
  utcFloor: () => (standalone_utcFloor),
  utcInterval: () => (standalone_utcInterval),
  utcOffset: () => (standalone_utcOffset),
  utcSequence: () => (standalone_utcSequence),
  utcdayofyear: () => (standalone_utcdayofyear),
  utcquarter: () => (standalone_utcquarter),
  utcweek: () => (standalone_utcweek),
  version: () => (standalone_version),
  visitArray: () => (standalone_visitArray),
  week: () => (standalone_week),
  writeConfig: () => (standalone_writeConfig),
  zero: () => (standalone_zero),
  zoomLinear: () => (standalone_zoomLinear),
  zoomLog: () => (standalone_zoomLog),
  zoomPow: () => (standalone_zoomPow),
  zoomSymlog: () => (standalone_zoomSymlog)
});

// NAMESPACE OBJECT: ../../node_modules/vega-lite/build/src/index.js
var standalone_build_src_namespaceObject = {};
__webpack_require__.r(standalone_build_src_namespaceObject);
__webpack_require__.d(standalone_build_src_namespaceObject, {
  accessPathDepth: () => (standalone_accessPathDepth),
  accessPathWithDatum: () => (standalone_accessPathWithDatum),
  accessWithDatumToUnescapedPath: () => (standalone_accessWithDatumToUnescapedPath),
  compile: () => (standalone_compile),
  contains: () => (standalone_util_contains),
  deepEqual: () => (standalone_deepEqual),
  deleteNestedProperty: () => (standalone_deleteNestedProperty),
  duplicate: () => (standalone_duplicate),
  entries: () => (standalone_entries),
  every: () => (standalone_every),
  fieldIntersection: () => (standalone_fieldIntersection),
  flatAccessWithDatum: () => (standalone_flatAccessWithDatum),
  getFirstDefined: () => (standalone_getFirstDefined),
  hasIntersection: () => (standalone_hasIntersection),
  hasProperty: () => (standalone_util_hasProperty),
  hash: () => (standalone_util_hash),
  internalField: () => (standalone_internalField),
  isBoolean: () => (standalone_util_isBoolean),
  isEmpty: () => (standalone_isEmpty),
  isEqual: () => (standalone_isEqual),
  isInternalField: () => (standalone_isInternalField),
  isNullOrFalse: () => (standalone_isNullOrFalse),
  isNumeric: () => (standalone_isNumeric),
  keys: () => (standalone_util_keys),
  logicalExpr: () => (standalone_logicalExpr),
  mergeDeep: () => (standalone_mergeDeep),
  never: () => (standalone_never),
  normalize: () => (standalone_normalize_normalize),
  normalizeAngle: () => (standalone_normalizeAngle),
  omit: () => (standalone_omit),
  pick: () => (standalone_util_pick),
  prefixGenerator: () => (standalone_prefixGenerator),
  removePathFromField: () => (standalone_removePathFromField),
  replaceAll: () => (standalone_replaceAll),
  replacePathInField: () => (standalone_replacePathInField),
  resetIdCounter: () => (standalone_resetIdCounter),
  setEqual: () => (standalone_setEqual),
  some: () => (standalone_some),
  stringify: () => (standalone_util_stringify),
  titleCase: () => (standalone_titleCase),
  unique: () => (standalone_unique),
  uniqueId: () => (standalone_uniqueId),
  vals: () => (standalone_vals),
  varName: () => (standalone_varName),
  version: () => (standalone_src_version)
});

// NAMESPACE OBJECT: ../../node_modules/vega-themes/build/vega-themes.module.js
var standalone_vega_themes_module_namespaceObject = {};
__webpack_require__.r(standalone_vega_themes_module_namespaceObject);
__webpack_require__.d(standalone_vega_themes_module_namespaceObject, {
  carbong10: () => (standalone_carbong10),
  carbong100: () => (standalone_carbong100),
  carbong90: () => (standalone_carbong90),
  carbonwhite: () => (standalone_carbonwhite),
  dark: () => (standalone_darkTheme),
  excel: () => (standalone_excelTheme),
  fivethirtyeight: () => (standalone_fiveThirtyEightTheme),
  ggplot2: () => (standalone_ggplot2Theme),
  googlecharts: () => (standalone_googlechartsTheme),
  latimes: () => (standalone_latimesTheme),
  powerbi: () => (standalone_powerbiTheme),
  quartz: () => (standalone_quartzTheme),
  urbaninstitute: () => (standalone_urbanInstituteTheme),
  version: () => (standalone_vega_themes_module_version),
  vox: () => (standalone_voxTheme)
});

// NAMESPACE OBJECT: ../../node_modules/apache-arrow/util/buffer.mjs
var standalone_util_buffer_namespaceObject = {};
__webpack_require__.r(standalone_util_buffer_namespaceObject);
__webpack_require__.d(standalone_util_buffer_namespaceObject, {
  compareArrayLike: () => (standalone_compareArrayLike),
  joinUint8Arrays: () => (standalone_joinUint8Arrays),
  memcpy: () => (standalone_memcpy),
  rebaseValueOffsets: () => (standalone_rebaseValueOffsets),
  toArrayBufferView: () => (standalone_toArrayBufferView),
  toArrayBufferViewAsyncIterator: () => (standalone_toArrayBufferViewAsyncIterator),
  toArrayBufferViewIterator: () => (standalone_toArrayBufferViewIterator),
  toBigInt64Array: () => (standalone_toBigInt64Array),
  toBigUint64Array: () => (standalone_toBigUint64Array),
  toFloat32Array: () => (standalone_toFloat32Array),
  toFloat32ArrayAsyncIterator: () => (standalone_toFloat32ArrayAsyncIterator),
  toFloat32ArrayIterator: () => (standalone_toFloat32ArrayIterator),
  toFloat64Array: () => (standalone_toFloat64Array),
  toFloat64ArrayAsyncIterator: () => (standalone_toFloat64ArrayAsyncIterator),
  toFloat64ArrayIterator: () => (standalone_toFloat64ArrayIterator),
  toInt16Array: () => (standalone_toInt16Array),
  toInt16ArrayAsyncIterator: () => (standalone_toInt16ArrayAsyncIterator),
  toInt16ArrayIterator: () => (standalone_toInt16ArrayIterator),
  toInt32Array: () => (standalone_toInt32Array),
  toInt32ArrayAsyncIterator: () => (standalone_toInt32ArrayAsyncIterator),
  toInt32ArrayIterator: () => (standalone_toInt32ArrayIterator),
  toInt8Array: () => (standalone_toInt8Array),
  toInt8ArrayAsyncIterator: () => (standalone_toInt8ArrayAsyncIterator),
  toInt8ArrayIterator: () => (standalone_toInt8ArrayIterator),
  toUint16Array: () => (standalone_toUint16Array),
  toUint16ArrayAsyncIterator: () => (standalone_toUint16ArrayAsyncIterator),
  toUint16ArrayIterator: () => (standalone_toUint16ArrayIterator),
  toUint32Array: () => (standalone_toUint32Array),
  toUint32ArrayAsyncIterator: () => (standalone_toUint32ArrayAsyncIterator),
  toUint32ArrayIterator: () => (standalone_toUint32ArrayIterator),
  toUint8Array: () => (standalone_toUint8Array),
  toUint8ArrayAsyncIterator: () => (standalone_toUint8ArrayAsyncIterator),
  toUint8ArrayIterator: () => (standalone_toUint8ArrayIterator),
  toUint8ClampedArray: () => (standalone_toUint8ClampedArray),
  toUint8ClampedArrayAsyncIterator: () => (standalone_toUint8ClampedArrayAsyncIterator),
  toUint8ClampedArrayIterator: () => (standalone_toUint8ClampedArrayIterator)
});

// NAMESPACE OBJECT: ../../node_modules/apache-arrow/util/bit.mjs
var standalone_bit_namespaceObject = {};
__webpack_require__.r(standalone_bit_namespaceObject);
__webpack_require__.d(standalone_bit_namespaceObject, {
  getBit: () => (standalone_getBit),
  getBool: () => (standalone_getBool),
  iterateBits: () => (standalone_iterateBits),
  packBools: () => (standalone_packBools),
  popcnt_array: () => (standalone_popcnt_array),
  popcnt_bit_range: () => (standalone_popcnt_bit_range),
  popcnt_uint32: () => (standalone_popcnt_uint32),
  setBool: () => (standalone_setBool),
  truncateBitmap: () => (standalone_truncateBitmap)
});

// NAMESPACE OBJECT: ../../node_modules/apache-arrow/util/math.mjs
var standalone_util_math_namespaceObject = {};
__webpack_require__.r(standalone_util_math_namespaceObject);
__webpack_require__.d(standalone_util_math_namespaceObject, {
  float64ToUint16: () => (standalone_float64ToUint16),
  uint16ToFloat64: () => (standalone_uint16ToFloat64)
});

// NAMESPACE OBJECT: ../../node_modules/apache-arrow/util/bn.mjs
var standalone_bn_namespaceObject = {};
__webpack_require__.r(standalone_bn_namespaceObject);
__webpack_require__.d(standalone_bn_namespaceObject, {
  BN: () => (standalone_BN),
  bignumToBigInt: () => (standalone_bignumToBigInt),
  bignumToString: () => (standalone_bignumToString),
  isArrowBigNumSymbol: () => (standalone_isArrowBigNumSymbol)
});

// NAMESPACE OBJECT: ../../node_modules/apache-arrow/util/vector.mjs
var standalone_util_vector_namespaceObject = {};
__webpack_require__.r(standalone_util_vector_namespaceObject);
__webpack_require__.d(standalone_util_vector_namespaceObject, {
  clampIndex: () => (standalone_clampIndex),
  clampRange: () => (standalone_vector_clampRange),
  createElementComparator: () => (standalone_createElementComparator)
});

// NAMESPACE OBJECT: ../../node_modules/apache-arrow/util/int.mjs
var standalone_util_int_namespaceObject = {};
__webpack_require__.r(standalone_util_int_namespaceObject);
__webpack_require__.d(standalone_util_int_namespaceObject, {
  BaseInt64: () => (standalone_BaseInt64),
  Int128: () => (standalone_Int128),
  Int64: () => (standalone_int_Int64),
  Uint64: () => (standalone_int_Uint64)
});

;// ../../node_modules/svelte/internal/index.mjs
function standalone_noop() { }
const standalone_internal_identity = x => x;
function standalone_internal_assign(tar, src) {
    // @ts-ignore
    for (const k in src)
        tar[k] = src[k];
    return tar;
}
// Adapted from https://github.com/then/is-promise/blob/master/index.js
// Distributed under MIT License https://github.com/then/is-promise/blob/master/LICENSE
function standalone_is_promise(value) {
    return !!value && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function';
}
function standalone_add_location(element, file, line, column, char) {
    element.__svelte_meta = {
        loc: { file, line, column, char }
    };
}
function standalone_run(fn) {
    return fn();
}
function standalone_blank_object() {
    return Object.create(null);
}
function standalone_run_all(fns) {
    fns.forEach(standalone_run);
}
function standalone_internal_is_function(thing) {
    return typeof thing === 'function';
}
function standalone_safe_not_equal(a, b) {
    return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}
let standalone_src_url_equal_anchor;
function standalone_src_url_equal(element_src, url) {
    if (!standalone_src_url_equal_anchor) {
        standalone_src_url_equal_anchor = document.createElement('a');
    }
    standalone_src_url_equal_anchor.href = url;
    return element_src === standalone_src_url_equal_anchor.href;
}
function standalone_not_equal(a, b) {
    return a != a ? b == b : a !== b;
}
function standalone_is_empty(obj) {
    return Object.keys(obj).length === 0;
}
function standalone_validate_store(store, name) {
    if (store != null && typeof store.subscribe !== 'function') {
        throw new Error(`'${name}' is not a store with a 'subscribe' method`);
    }
}
function standalone_subscribe(store, ...callbacks) {
    if (store == null) {
        return standalone_noop;
    }
    const unsub = store.subscribe(...callbacks);
    return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
function standalone_get_store_value(store) {
    let value;
    standalone_subscribe(store, _ => value = _)();
    return value;
}
function standalone_component_subscribe(component, store, callback) {
    component.$$.on_destroy.push(standalone_subscribe(store, callback));
}
function standalone_create_slot(definition, ctx, $$scope, fn) {
    if (definition) {
        const slot_ctx = standalone_get_slot_context(definition, ctx, $$scope, fn);
        return definition[0](slot_ctx);
    }
}
function standalone_get_slot_context(definition, ctx, $$scope, fn) {
    return definition[1] && fn
        ? standalone_internal_assign($$scope.ctx.slice(), definition[1](fn(ctx)))
        : $$scope.ctx;
}
function standalone_get_slot_changes(definition, $$scope, dirty, fn) {
    if (definition[2] && fn) {
        const lets = definition[2](fn(dirty));
        if ($$scope.dirty === undefined) {
            return lets;
        }
        if (typeof lets === 'object') {
            const merged = [];
            const len = Math.max($$scope.dirty.length, lets.length);
            for (let i = 0; i < len; i += 1) {
                merged[i] = $$scope.dirty[i] | lets[i];
            }
            return merged;
        }
        return $$scope.dirty | lets;
    }
    return $$scope.dirty;
}
function standalone_update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
    if (slot_changes) {
        const slot_context = standalone_get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
        slot.p(slot_context, slot_changes);
    }
}
function standalone_update_slot(slot, slot_definition, ctx, $$scope, dirty, get_slot_changes_fn, get_slot_context_fn) {
    const slot_changes = standalone_get_slot_changes(slot_definition, $$scope, dirty, get_slot_changes_fn);
    standalone_update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn);
}
function standalone_get_all_dirty_from_scope($$scope) {
    if ($$scope.ctx.length > 32) {
        const dirty = [];
        const length = $$scope.ctx.length / 32;
        for (let i = 0; i < length; i++) {
            dirty[i] = -1;
        }
        return dirty;
    }
    return -1;
}
function standalone_exclude_internal_props(props) {
    const result = {};
    for (const k in props)
        if (k[0] !== '$')
            result[k] = props[k];
    return result;
}
function standalone_compute_rest_props(props, keys) {
    const rest = {};
    keys = new Set(keys);
    for (const k in props)
        if (!keys.has(k) && k[0] !== '$')
            rest[k] = props[k];
    return rest;
}
function standalone_compute_slots(slots) {
    const result = {};
    for (const key in slots) {
        result[key] = true;
    }
    return result;
}
function standalone_once(fn) {
    let ran = false;
    return function (...args) {
        if (ran)
            return;
        ran = true;
        fn.call(this, ...args);
    };
}
function standalone_null_to_empty(value) {
    return value == null ? '' : value;
}
function standalone_set_store_value(store, ret, value) {
    store.set(value);
    return ret;
}
const standalone_has_prop = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
function standalone_action_destroyer(action_result) {
    return action_result && standalone_internal_is_function(action_result.destroy) ? action_result.destroy : standalone_noop;
}
function standalone_internal_split_css_unit(value) {
    const split = typeof value === 'string' && value.match(/^\s*(-?[\d.]+)([^\s]*)\s*$/);
    return split ? [parseFloat(split[1]), split[2] || 'px'] : [value, 'px'];
}
const standalone_contenteditable_truthy_values = (/* unused pure expression or super */ null && (['', true, 1, 'true', 'contenteditable']));

const standalone_is_client = typeof window !== 'undefined';
let standalone_now = standalone_is_client
    ? () => window.performance.now()
    : () => Date.now();
let standalone_raf = standalone_is_client ? cb => requestAnimationFrame(cb) : standalone_noop;
// used internally for testing
function standalone_set_now(fn) {
    standalone_now = fn;
}
function standalone_set_raf(fn) {
    standalone_raf = fn;
}

const standalone_tasks = new Set();
function standalone_run_tasks(now) {
    standalone_tasks.forEach(task => {
        if (!task.c(now)) {
            standalone_tasks.delete(task);
            task.f();
        }
    });
    if (standalone_tasks.size !== 0)
        standalone_raf(standalone_run_tasks);
}
/**
 * For testing purposes only!
 */
function standalone_clear_loops() {
    standalone_tasks.clear();
}
/**
 * Creates a new task that runs on each raf frame
 * until it returns a falsy value or is aborted
 */
function standalone_loop(callback) {
    let task;
    if (standalone_tasks.size === 0)
        standalone_raf(standalone_run_tasks);
    return {
        promise: new Promise(fulfill => {
            standalone_tasks.add(task = { c: callback, f: fulfill });
        }),
        abort() {
            standalone_tasks.delete(task);
        }
    };
}

const standalone_globals = (typeof window !== 'undefined'
    ? window
    : typeof globalThis !== 'undefined'
        ? globalThis
        : global);

/**
 * Resize observer singleton.
 * One listener per element only!
 * https://groups.google.com/a/chromium.org/g/blink-dev/c/z6ienONUb5A/m/F5-VcUZtBAAJ
 */
class standalone_ResizeObserverSingleton {
    constructor(options) {
        this.options = options;
        this._listeners = 'WeakMap' in standalone_globals ? new WeakMap() : undefined;
    }
    observe(element, listener) {
        this._listeners.set(element, listener);
        this._getObserver().observe(element, this.options);
        return () => {
            this._listeners.delete(element);
            this._observer.unobserve(element); // this line can probably be removed
        };
    }
    _getObserver() {
        var _a;
        return (_a = this._observer) !== null && _a !== void 0 ? _a : (this._observer = new ResizeObserver((entries) => {
            var _a;
            for (const entry of entries) {
                standalone_ResizeObserverSingleton.entries.set(entry.target, entry);
                (_a = this._listeners.get(entry.target)) === null || _a === void 0 ? void 0 : _a(entry);
            }
        }));
    }
}
// Needs to be written like this to pass the tree-shake-test
standalone_ResizeObserverSingleton.entries = 'WeakMap' in standalone_globals ? new WeakMap() : undefined;

// Track which nodes are claimed during hydration. Unclaimed nodes can then be removed from the DOM
// at the end of hydration without touching the remaining nodes.
let standalone_is_hydrating = false;
function standalone_start_hydrating() {
    standalone_is_hydrating = true;
}
function standalone_end_hydrating() {
    standalone_is_hydrating = false;
}
function standalone_upper_bound(low, high, key, value) {
    // Return first index of value larger than input value in the range [low, high)
    while (low < high) {
        const mid = low + ((high - low) >> 1);
        if (key(mid) <= value) {
            low = mid + 1;
        }
        else {
            high = mid;
        }
    }
    return low;
}
function standalone_init_hydrate(target) {
    if (target.hydrate_init)
        return;
    target.hydrate_init = true;
    // We know that all children have claim_order values since the unclaimed have been detached if target is not <head>
    let children = target.childNodes;
    // If target is <head>, there may be children without claim_order
    if (target.nodeName === 'HEAD') {
        const myChildren = [];
        for (let i = 0; i < children.length; i++) {
            const node = children[i];
            if (node.claim_order !== undefined) {
                myChildren.push(node);
            }
        }
        children = myChildren;
    }
    /*
    * Reorder claimed children optimally.
    * We can reorder claimed children optimally by finding the longest subsequence of
    * nodes that are already claimed in order and only moving the rest. The longest
    * subsequence of nodes that are claimed in order can be found by
    * computing the longest increasing subsequence of .claim_order values.
    *
    * This algorithm is optimal in generating the least amount of reorder operations
    * possible.
    *
    * Proof:
    * We know that, given a set of reordering operations, the nodes that do not move
    * always form an increasing subsequence, since they do not move among each other
    * meaning that they must be already ordered among each other. Thus, the maximal
    * set of nodes that do not move form a longest increasing subsequence.
    */
    // Compute longest increasing subsequence
    // m: subsequence length j => index k of smallest value that ends an increasing subsequence of length j
    const m = new Int32Array(children.length + 1);
    // Predecessor indices + 1
    const p = new Int32Array(children.length);
    m[0] = -1;
    let longest = 0;
    for (let i = 0; i < children.length; i++) {
        const current = children[i].claim_order;
        // Find the largest subsequence length such that it ends in a value less than our current value
        // upper_bound returns first greater value, so we subtract one
        // with fast path for when we are on the current longest subsequence
        const seqLen = ((longest > 0 && children[m[longest]].claim_order <= current) ? longest + 1 : standalone_upper_bound(1, longest, idx => children[m[idx]].claim_order, current)) - 1;
        p[i] = m[seqLen] + 1;
        const newLen = seqLen + 1;
        // We can guarantee that current is the smallest value. Otherwise, we would have generated a longer sequence.
        m[newLen] = i;
        longest = Math.max(newLen, longest);
    }
    // The longest increasing subsequence of nodes (initially reversed)
    const lis = [];
    // The rest of the nodes, nodes that will be moved
    const toMove = [];
    let last = children.length - 1;
    for (let cur = m[longest] + 1; cur != 0; cur = p[cur - 1]) {
        lis.push(children[cur - 1]);
        for (; last >= cur; last--) {
            toMove.push(children[last]);
        }
        last--;
    }
    for (; last >= 0; last--) {
        toMove.push(children[last]);
    }
    lis.reverse();
    // We sort the nodes being moved to guarantee that their insertion order matches the claim order
    toMove.sort((a, b) => a.claim_order - b.claim_order);
    // Finally, we move the nodes
    for (let i = 0, j = 0; i < toMove.length; i++) {
        while (j < lis.length && toMove[i].claim_order >= lis[j].claim_order) {
            j++;
        }
        const anchor = j < lis.length ? lis[j] : null;
        target.insertBefore(toMove[i], anchor);
    }
}
function standalone_append(target, node) {
    target.appendChild(node);
}
function standalone_append_styles(target, style_sheet_id, styles) {
    const append_styles_to = standalone_get_root_for_style(target);
    if (!append_styles_to.getElementById(style_sheet_id)) {
        const style = standalone_internal_element('style');
        style.id = style_sheet_id;
        style.textContent = styles;
        standalone_append_stylesheet(append_styles_to, style);
    }
}
function standalone_get_root_for_style(node) {
    if (!node)
        return document;
    const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
    if (root && root.host) {
        return root;
    }
    return node.ownerDocument;
}
function standalone_append_empty_stylesheet(node) {
    const style_element = standalone_internal_element('style');
    standalone_append_stylesheet(standalone_get_root_for_style(node), style_element);
    return style_element.sheet;
}
function standalone_append_stylesheet(node, style) {
    standalone_append(node.head || node, style);
    return style.sheet;
}
function standalone_append_hydration(target, node) {
    if (standalone_is_hydrating) {
        standalone_init_hydrate(target);
        if ((target.actual_end_child === undefined) || ((target.actual_end_child !== null) && (target.actual_end_child.parentNode !== target))) {
            target.actual_end_child = target.firstChild;
        }
        // Skip nodes of undefined ordering
        while ((target.actual_end_child !== null) && (target.actual_end_child.claim_order === undefined)) {
            target.actual_end_child = target.actual_end_child.nextSibling;
        }
        if (node !== target.actual_end_child) {
            // We only insert if the ordering of this node should be modified or the parent node is not target
            if (node.claim_order !== undefined || node.parentNode !== target) {
                target.insertBefore(node, target.actual_end_child);
            }
        }
        else {
            target.actual_end_child = node.nextSibling;
        }
    }
    else if (node.parentNode !== target || node.nextSibling !== null) {
        target.appendChild(node);
    }
}
function standalone_insert(target, node, anchor) {
    target.insertBefore(node, anchor || null);
}
function standalone_insert_hydration(target, node, anchor) {
    if (standalone_is_hydrating && !anchor) {
        standalone_append_hydration(target, node);
    }
    else if (node.parentNode !== target || node.nextSibling != anchor) {
        target.insertBefore(node, anchor || null);
    }
}
function standalone_detach(node) {
    if (node.parentNode) {
        node.parentNode.removeChild(node);
    }
}
function standalone_destroy_each(iterations, detaching) {
    for (let i = 0; i < iterations.length; i += 1) {
        if (iterations[i])
            iterations[i].d(detaching);
    }
}
function standalone_internal_element(name) {
    return document.createElement(name);
}
function standalone_element_is(name, is) {
    return document.createElement(name, { is });
}
function standalone_object_without_properties(obj, exclude) {
    const target = {};
    for (const k in obj) {
        if (standalone_has_prop(obj, k)
            // @ts-ignore
            && exclude.indexOf(k) === -1) {
            // @ts-ignore
            target[k] = obj[k];
        }
    }
    return target;
}
function standalone_svg_element(name) {
    return document.createElementNS('http://www.w3.org/2000/svg', name);
}
function standalone_internal_text(data) {
    return document.createTextNode(data);
}
function standalone_space() {
    return standalone_internal_text(' ');
}
function standalone_empty() {
    return standalone_internal_text('');
}
function standalone_comment(content) {
    return document.createComment(content);
}
function standalone_listen(node, event, handler, options) {
    node.addEventListener(event, handler, options);
    return () => node.removeEventListener(event, handler, options);
}
function standalone_prevent_default(fn) {
    return function (event) {
        event.preventDefault();
        // @ts-ignore
        return fn.call(this, event);
    };
}
function standalone_stop_propagation(fn) {
    return function (event) {
        event.stopPropagation();
        // @ts-ignore
        return fn.call(this, event);
    };
}
function standalone_stop_immediate_propagation(fn) {
    return function (event) {
        event.stopImmediatePropagation();
        // @ts-ignore
        return fn.call(this, event);
    };
}
function standalone_internal_self(fn) {
    return function (event) {
        // @ts-ignore
        if (event.target === this)
            fn.call(this, event);
    };
}
function standalone_trusted(fn) {
    return function (event) {
        // @ts-ignore
        if (event.isTrusted)
            fn.call(this, event);
    };
}
function standalone_attr(node, attribute, value) {
    if (value == null)
        node.removeAttribute(attribute);
    else if (node.getAttribute(attribute) !== value)
        node.setAttribute(attribute, value);
}
/**
 * List of attributes that should always be set through the attr method,
 * because updating them through the property setter doesn't work reliably.
 * In the example of `width`/`height`, the problem is that the setter only
 * accepts numeric values, but the attribute can also be set to a string like `50%`.
 * If this list becomes too big, rethink this approach.
 */
const standalone_always_set_through_set_attribute = (/* unused pure expression or super */ null && (['width', 'height']));
function standalone_set_attributes(node, attributes) {
    // @ts-ignore
    const descriptors = Object.getOwnPropertyDescriptors(node.__proto__);
    for (const key in attributes) {
        if (attributes[key] == null) {
            node.removeAttribute(key);
        }
        else if (key === 'style') {
            node.style.cssText = attributes[key];
        }
        else if (key === '__value') {
            node.value = node[key] = attributes[key];
        }
        else if (descriptors[key] && descriptors[key].set && standalone_always_set_through_set_attribute.indexOf(key) === -1) {
            node[key] = attributes[key];
        }
        else {
            standalone_attr(node, key, attributes[key]);
        }
    }
}
function standalone_set_svg_attributes(node, attributes) {
    for (const key in attributes) {
        standalone_attr(node, key, attributes[key]);
    }
}
function standalone_set_custom_element_data_map(node, data_map) {
    Object.keys(data_map).forEach((key) => {
        standalone_set_custom_element_data(node, key, data_map[key]);
    });
}
function standalone_set_custom_element_data(node, prop, value) {
    if (prop in node) {
        node[prop] = typeof node[prop] === 'boolean' && value === '' ? true : value;
    }
    else {
        standalone_attr(node, prop, value);
    }
}
function standalone_set_dynamic_element_data(tag) {
    return (/-/.test(tag)) ? standalone_set_custom_element_data_map : standalone_set_attributes;
}
function standalone_xlink_attr(node, attribute, value) {
    node.setAttributeNS('http://www.w3.org/1999/xlink', attribute, value);
}
function standalone_get_binding_group_value(group, __value, checked) {
    const value = new Set();
    for (let i = 0; i < group.length; i += 1) {
        if (group[i].checked)
            value.add(group[i].__value);
    }
    if (!checked) {
        value.delete(__value);
    }
    return Array.from(value);
}
function standalone_init_binding_group(group) {
    let _inputs;
    return {
        /* push */ p(...inputs) {
            _inputs = inputs;
            _inputs.forEach(input => group.push(input));
        },
        /* remove */ r() {
            _inputs.forEach(input => group.splice(group.indexOf(input), 1));
        }
    };
}
function standalone_init_binding_group_dynamic(group, indexes) {
    let _group = get_binding_group(group);
    let _inputs;
    function get_binding_group(group) {
        for (let i = 0; i < indexes.length; i++) {
            group = group[indexes[i]] = group[indexes[i]] || [];
        }
        return group;
    }
    function push() {
        _inputs.forEach(input => _group.push(input));
    }
    function remove() {
        _inputs.forEach(input => _group.splice(_group.indexOf(input), 1));
    }
    return {
        /* update */ u(new_indexes) {
            indexes = new_indexes;
            const new_group = get_binding_group(group);
            if (new_group !== _group) {
                remove();
                _group = new_group;
                push();
            }
        },
        /* push */ p(...inputs) {
            _inputs = inputs;
            push();
        },
        /* remove */ r: remove
    };
}
function standalone_to_number(value) {
    return value === '' ? null : +value;
}
function standalone_time_ranges_to_array(ranges) {
    const array = [];
    for (let i = 0; i < ranges.length; i += 1) {
        array.push({ start: ranges.start(i), end: ranges.end(i) });
    }
    return array;
}
function standalone_children(element) {
    return Array.from(element.childNodes);
}
function standalone_init_claim_info(nodes) {
    if (nodes.claim_info === undefined) {
        nodes.claim_info = { last_index: 0, total_claimed: 0 };
    }
}
function standalone_claim_node(nodes, predicate, processNode, createNode, dontUpdateLastIndex = false) {
    // Try to find nodes in an order such that we lengthen the longest increasing subsequence
    standalone_init_claim_info(nodes);
    const resultNode = (() => {
        // We first try to find an element after the previous one
        for (let i = nodes.claim_info.last_index; i < nodes.length; i++) {
            const node = nodes[i];
            if (predicate(node)) {
                const replacement = processNode(node);
                if (replacement === undefined) {
                    nodes.splice(i, 1);
                }
                else {
                    nodes[i] = replacement;
                }
                if (!dontUpdateLastIndex) {
                    nodes.claim_info.last_index = i;
                }
                return node;
            }
        }
        // Otherwise, we try to find one before
        // We iterate in reverse so that we don't go too far back
        for (let i = nodes.claim_info.last_index - 1; i >= 0; i--) {
            const node = nodes[i];
            if (predicate(node)) {
                const replacement = processNode(node);
                if (replacement === undefined) {
                    nodes.splice(i, 1);
                }
                else {
                    nodes[i] = replacement;
                }
                if (!dontUpdateLastIndex) {
                    nodes.claim_info.last_index = i;
                }
                else if (replacement === undefined) {
                    // Since we spliced before the last_index, we decrease it
                    nodes.claim_info.last_index--;
                }
                return node;
            }
        }
        // If we can't find any matching node, we create a new one
        return createNode();
    })();
    resultNode.claim_order = nodes.claim_info.total_claimed;
    nodes.claim_info.total_claimed += 1;
    return resultNode;
}
function standalone_claim_element_base(nodes, name, attributes, create_element) {
    return standalone_claim_node(nodes, (node) => node.nodeName === name, (node) => {
        const remove = [];
        for (let j = 0; j < node.attributes.length; j++) {
            const attribute = node.attributes[j];
            if (!attributes[attribute.name]) {
                remove.push(attribute.name);
            }
        }
        remove.forEach(v => node.removeAttribute(v));
        return undefined;
    }, () => create_element(name));
}
function standalone_claim_element(nodes, name, attributes) {
    return standalone_claim_element_base(nodes, name, attributes, standalone_internal_element);
}
function standalone_claim_svg_element(nodes, name, attributes) {
    return standalone_claim_element_base(nodes, name, attributes, standalone_svg_element);
}
function standalone_claim_text(nodes, data) {
    return standalone_claim_node(nodes, (node) => node.nodeType === 3, (node) => {
        const dataStr = '' + data;
        if (node.data.startsWith(dataStr)) {
            if (node.data.length !== dataStr.length) {
                return node.splitText(dataStr.length);
            }
        }
        else {
            node.data = dataStr;
        }
    }, () => standalone_internal_text(data), true // Text nodes should not update last index since it is likely not worth it to eliminate an increasing subsequence of actual elements
    );
}
function standalone_claim_space(nodes) {
    return standalone_claim_text(nodes, ' ');
}
function standalone_claim_comment(nodes, data) {
    return standalone_claim_node(nodes, (node) => node.nodeType === 8, (node) => {
        node.data = '' + data;
        return undefined;
    }, () => standalone_comment(data), true);
}
function standalone_find_comment(nodes, text, start) {
    for (let i = start; i < nodes.length; i += 1) {
        const node = nodes[i];
        if (node.nodeType === 8 /* comment node */ && node.textContent.trim() === text) {
            return i;
        }
    }
    return nodes.length;
}
function standalone_claim_html_tag(nodes, is_svg) {
    // find html opening tag
    const start_index = standalone_find_comment(nodes, 'HTML_TAG_START', 0);
    const end_index = standalone_find_comment(nodes, 'HTML_TAG_END', start_index);
    if (start_index === end_index) {
        return new standalone_HtmlTagHydration(undefined, is_svg);
    }
    standalone_init_claim_info(nodes);
    const html_tag_nodes = nodes.splice(start_index, end_index - start_index + 1);
    standalone_detach(html_tag_nodes[0]);
    standalone_detach(html_tag_nodes[html_tag_nodes.length - 1]);
    const claimed_nodes = html_tag_nodes.slice(1, html_tag_nodes.length - 1);
    for (const n of claimed_nodes) {
        n.claim_order = nodes.claim_info.total_claimed;
        nodes.claim_info.total_claimed += 1;
    }
    return new standalone_HtmlTagHydration(claimed_nodes, is_svg);
}
function standalone_set_data(text, data) {
    data = '' + data;
    if (text.data === data)
        return;
    text.data = data;
}
function standalone_set_data_contenteditable(text, data) {
    data = '' + data;
    if (text.wholeText === data)
        return;
    text.data = data;
}
function standalone_set_data_maybe_contenteditable(text, data, attr_value) {
    if (~standalone_contenteditable_truthy_values.indexOf(attr_value)) {
        standalone_set_data_contenteditable(text, data);
    }
    else {
        standalone_set_data(text, data);
    }
}
function standalone_set_input_value(input, value) {
    input.value = value == null ? '' : value;
}
function standalone_set_input_type(input, type) {
    try {
        input.type = type;
    }
    catch (e) {
        // do nothing
    }
}
function standalone_set_style(node, key, value, important) {
    if (value == null) {
        node.style.removeProperty(key);
    }
    else {
        node.style.setProperty(key, value, important ? 'important' : '');
    }
}
function standalone_select_option(select, value, mounting) {
    for (let i = 0; i < select.options.length; i += 1) {
        const option = select.options[i];
        if (option.__value === value) {
            option.selected = true;
            return;
        }
    }
    if (!mounting || value !== undefined) {
        select.selectedIndex = -1; // no option should be selected
    }
}
function standalone_select_options(select, value) {
    for (let i = 0; i < select.options.length; i += 1) {
        const option = select.options[i];
        option.selected = ~value.indexOf(option.__value);
    }
}
function standalone_select_value(select) {
    const selected_option = select.querySelector(':checked');
    return selected_option && selected_option.__value;
}
function standalone_select_multiple_value(select) {
    return [].map.call(select.querySelectorAll(':checked'), option => option.__value);
}
// unfortunately this can't be a constant as that wouldn't be tree-shakeable
// so we cache the result instead
let standalone_crossorigin;
function standalone_is_crossorigin() {
    if (standalone_crossorigin === undefined) {
        standalone_crossorigin = false;
        try {
            if (typeof window !== 'undefined' && window.parent) {
                void window.parent.document;
            }
        }
        catch (error) {
            standalone_crossorigin = true;
        }
    }
    return standalone_crossorigin;
}
function standalone_add_iframe_resize_listener(node, fn) {
    const computed_style = getComputedStyle(node);
    if (computed_style.position === 'static') {
        node.style.position = 'relative';
    }
    const iframe = standalone_internal_element('iframe');
    iframe.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; ' +
        'overflow: hidden; border: 0; opacity: 0; pointer-events: none; z-index: -1;');
    iframe.setAttribute('aria-hidden', 'true');
    iframe.tabIndex = -1;
    const crossorigin = standalone_is_crossorigin();
    let unsubscribe;
    if (crossorigin) {
        iframe.src = "data:text/html,<script>onresize=function(){parent.postMessage(0,'*')}</script>";
        unsubscribe = standalone_listen(window, 'message', (event) => {
            if (event.source === iframe.contentWindow)
                fn();
        });
    }
    else {
        iframe.src = 'about:blank';
        iframe.onload = () => {
            unsubscribe = standalone_listen(iframe.contentWindow, 'resize', fn);
            // make sure an initial resize event is fired _after_ the iframe is loaded (which is asynchronous)
            // see https://github.com/sveltejs/svelte/issues/4233
            fn();
        };
    }
    standalone_append(node, iframe);
    return () => {
        if (crossorigin) {
            unsubscribe();
        }
        else if (unsubscribe && iframe.contentWindow) {
            unsubscribe();
        }
        standalone_detach(iframe);
    };
}
const standalone_resize_observer_content_box = /* @__PURE__ */ new standalone_ResizeObserverSingleton({ box: 'content-box' });
const standalone_resize_observer_border_box = /* @__PURE__ */ new standalone_ResizeObserverSingleton({ box: 'border-box' });
const standalone_resize_observer_device_pixel_content_box = /* @__PURE__ */ new standalone_ResizeObserverSingleton({ box: 'device-pixel-content-box' });
function standalone_toggle_class(element, name, toggle) {
    element.classList[toggle ? 'add' : 'remove'](name);
}
function standalone_custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
    const e = document.createEvent('CustomEvent');
    e.initCustomEvent(type, bubbles, cancelable, detail);
    return e;
}
function standalone_query_selector_all(selector, parent = document.body) {
    return Array.from(parent.querySelectorAll(selector));
}
function standalone_head_selector(nodeId, head) {
    const result = [];
    let started = 0;
    for (const node of head.childNodes) {
        if (node.nodeType === 8 /* comment node */) {
            const comment = node.textContent.trim();
            if (comment === `HEAD_${nodeId}_END`) {
                started -= 1;
                result.push(node);
            }
            else if (comment === `HEAD_${nodeId}_START`) {
                started += 1;
                result.push(node);
            }
        }
        else if (started > 0) {
            result.push(node);
        }
    }
    return result;
}
class standalone_HtmlTag {
    constructor(is_svg = false) {
        this.is_svg = false;
        this.is_svg = is_svg;
        this.e = this.n = null;
    }
    c(html) {
        this.h(html);
    }
    m(html, target, anchor = null) {
        if (!this.e) {
            if (this.is_svg)
                this.e = standalone_svg_element(target.nodeName);
            /** #7364  target for <template> may be provided as #document-fragment(11) */
            else
                this.e = standalone_internal_element((target.nodeType === 11 ? 'TEMPLATE' : target.nodeName));
            this.t = target.tagName !== 'TEMPLATE' ? target : target.content;
            this.c(html);
        }
        this.i(anchor);
    }
    h(html) {
        this.e.innerHTML = html;
        this.n = Array.from(this.e.nodeName === 'TEMPLATE' ? this.e.content.childNodes : this.e.childNodes);
    }
    i(anchor) {
        for (let i = 0; i < this.n.length; i += 1) {
            standalone_insert(this.t, this.n[i], anchor);
        }
    }
    p(html) {
        this.d();
        this.h(html);
        this.i(this.a);
    }
    d() {
        this.n.forEach(standalone_detach);
    }
}
class standalone_HtmlTagHydration extends standalone_HtmlTag {
    constructor(claimed_nodes, is_svg = false) {
        super(is_svg);
        this.e = this.n = null;
        this.l = claimed_nodes;
    }
    c(html) {
        if (this.l) {
            this.n = this.l;
        }
        else {
            super.c(html);
        }
    }
    i(anchor) {
        for (let i = 0; i < this.n.length; i += 1) {
            standalone_insert_hydration(this.t, this.n[i], anchor);
        }
    }
}
function standalone_attribute_to_object(attributes) {
    const result = {};
    for (const attribute of attributes) {
        result[attribute.name] = attribute.value;
    }
    return result;
}
function standalone_get_custom_elements_slots(element) {
    const result = {};
    element.childNodes.forEach((node) => {
        result[node.slot || 'default'] = true;
    });
    return result;
}
function standalone_construct_svelte_component(component, props) {
    return new component(props);
}

// we need to store the information for multiple documents because a Svelte application could also contain iframes
// https://github.com/sveltejs/svelte/issues/3624
const standalone_managed_styles = new Map();
let standalone_active = 0;
// https://github.com/darkskyapp/string-hash/blob/master/index.js
function standalone_hash(str) {
    let hash = 5381;
    let i = str.length;
    while (i--)
        hash = ((hash << 5) - hash) ^ str.charCodeAt(i);
    return hash >>> 0;
}
function standalone_create_style_information(doc, node) {
    const info = { stylesheet: standalone_append_empty_stylesheet(node), rules: {} };
    standalone_managed_styles.set(doc, info);
    return info;
}
function standalone_create_rule(node, a, b, duration, delay, ease, fn, uid = 0) {
    const step = 16.666 / duration;
    let keyframes = '{\n';
    for (let p = 0; p <= 1; p += step) {
        const t = a + (b - a) * ease(p);
        keyframes += p * 100 + `%{${fn(t, 1 - t)}}\n`;
    }
    const rule = keyframes + `100% {${fn(b, 1 - b)}}\n}`;
    const name = `__svelte_${standalone_hash(rule)}_${uid}`;
    const doc = standalone_get_root_for_style(node);
    const { stylesheet, rules } = standalone_managed_styles.get(doc) || standalone_create_style_information(doc, node);
    if (!rules[name]) {
        rules[name] = true;
        stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length);
    }
    const animation = node.style.animation || '';
    node.style.animation = `${animation ? `${animation}, ` : ''}${name} ${duration}ms linear ${delay}ms 1 both`;
    standalone_active += 1;
    return name;
}
function standalone_delete_rule(node, name) {
    const previous = (node.style.animation || '').split(', ');
    const next = previous.filter(name
        ? anim => anim.indexOf(name) < 0 // remove specific animation
        : anim => anim.indexOf('__svelte') === -1 // remove all Svelte animations
    );
    const deleted = previous.length - next.length;
    if (deleted) {
        node.style.animation = next.join(', ');
        standalone_active -= deleted;
        if (!standalone_active)
            standalone_clear_rules();
    }
}
function standalone_clear_rules() {
    standalone_raf(() => {
        if (standalone_active)
            return;
        standalone_managed_styles.forEach(info => {
            const { ownerNode } = info.stylesheet;
            // there is no ownerNode if it runs on jsdom.
            if (ownerNode)
                standalone_detach(ownerNode);
        });
        standalone_managed_styles.clear();
    });
}

function standalone_create_animation(node, from, fn, params) {
    if (!from)
        return standalone_noop;
    const to = node.getBoundingClientRect();
    if (from.left === to.left && from.right === to.right && from.top === to.top && from.bottom === to.bottom)
        return standalone_noop;
    const { delay = 0, duration = 300, easing = standalone_internal_identity, 
    // @ts-ignore todo: should this be separated from destructuring? Or start/end added to public api and documentation?
    start: start_time = standalone_now() + delay, 
    // @ts-ignore todo:
    end = start_time + duration, tick = standalone_noop, css } = fn(node, { from, to }, params);
    let running = true;
    let started = false;
    let name;
    function start() {
        if (css) {
            name = standalone_create_rule(node, 0, 1, duration, delay, easing, css);
        }
        if (!delay) {
            started = true;
        }
    }
    function stop() {
        if (css)
            standalone_delete_rule(node, name);
        running = false;
    }
    standalone_loop(now => {
        if (!started && now >= start_time) {
            started = true;
        }
        if (started && now >= end) {
            tick(1, 0);
            stop();
        }
        if (!running) {
            return false;
        }
        if (started) {
            const p = now - start_time;
            const t = 0 + 1 * easing(p / duration);
            tick(t, 1 - t);
        }
        return true;
    });
    start();
    tick(0, 1);
    return stop;
}
function standalone_fix_position(node) {
    const style = getComputedStyle(node);
    if (style.position !== 'absolute' && style.position !== 'fixed') {
        const { width, height } = style;
        const a = node.getBoundingClientRect();
        node.style.position = 'absolute';
        node.style.width = width;
        node.style.height = height;
        standalone_add_transform(node, a);
    }
}
function standalone_add_transform(node, a) {
    const b = node.getBoundingClientRect();
    if (a.left !== b.left || a.top !== b.top) {
        const style = getComputedStyle(node);
        const transform = style.transform === 'none' ? '' : style.transform;
        node.style.transform = `${transform} translate(${a.left - b.left}px, ${a.top - b.top}px)`;
    }
}

let standalone_current_component;
function standalone_set_current_component(component) {
    standalone_current_component = component;
}
function standalone_get_current_component() {
    if (!standalone_current_component)
        throw new Error('Function called outside component initialization');
    return standalone_current_component;
}
/**
 * Schedules a callback to run immediately before the component is updated after any state change.
 *
 * The first time the callback runs will be before the initial `onMount`
 *
 * https://svelte.dev/docs#run-time-svelte-beforeupdate
 */
function standalone_beforeUpdate(fn) {
    standalone_get_current_component().$$.before_update.push(fn);
}
/**
 * The `onMount` function schedules a callback to run as soon as the component has been mounted to the DOM.
 * It must be called during the component's initialisation (but doesn't need to live *inside* the component;
 * it can be called from an external module).
 *
 * `onMount` does not run inside a [server-side component](/docs#run-time-server-side-component-api).
 *
 * https://svelte.dev/docs#run-time-svelte-onmount
 */
function standalone_onMount(fn) {
    standalone_get_current_component().$$.on_mount.push(fn);
}
/**
 * Schedules a callback to run immediately after the component has been updated.
 *
 * The first time the callback runs will be after the initial `onMount`
 */
function standalone_afterUpdate(fn) {
    standalone_get_current_component().$$.after_update.push(fn);
}
/**
 * Schedules a callback to run immediately before the component is unmounted.
 *
 * Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the
 * only one that runs inside a server-side component.
 *
 * https://svelte.dev/docs#run-time-svelte-ondestroy
 */
function standalone_onDestroy(fn) {
    standalone_get_current_component().$$.on_destroy.push(fn);
}
/**
 * Creates an event dispatcher that can be used to dispatch [component events](/docs#template-syntax-component-directives-on-eventname).
 * Event dispatchers are functions that can take two arguments: `name` and `detail`.
 *
 * Component events created with `createEventDispatcher` create a
 * [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent).
 * These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture).
 * The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail)
 * property and can contain any type of data.
 *
 * https://svelte.dev/docs#run-time-svelte-createeventdispatcher
 */
function standalone_createEventDispatcher() {
    const component = standalone_get_current_component();
    return (type, detail, { cancelable = false } = {}) => {
        const callbacks = component.$$.callbacks[type];
        if (callbacks) {
            // TODO are there situations where events could be dispatched
            // in a server (non-DOM) environment?
            const event = standalone_custom_event(type, detail, { cancelable });
            callbacks.slice().forEach(fn => {
                fn.call(component, event);
            });
            return !event.defaultPrevented;
        }
        return true;
    };
}
/**
 * Associates an arbitrary `context` object with the current component and the specified `key`
 * and returns that object. The context is then available to children of the component
 * (including slotted content) with `getContext`.
 *
 * Like lifecycle functions, this must be called during component initialisation.
 *
 * https://svelte.dev/docs#run-time-svelte-setcontext
 */
function standalone_setContext(key, context) {
    standalone_get_current_component().$$.context.set(key, context);
    return context;
}
/**
 * Retrieves the context that belongs to the closest parent component with the specified `key`.
 * Must be called during component initialisation.
 *
 * https://svelte.dev/docs#run-time-svelte-getcontext
 */
function standalone_getContext(key) {
    return standalone_get_current_component().$$.context.get(key);
}
/**
 * Retrieves the whole context map that belongs to the closest parent component.
 * Must be called during component initialisation. Useful, for example, if you
 * programmatically create a component and want to pass the existing context to it.
 *
 * https://svelte.dev/docs#run-time-svelte-getallcontexts
 */
function standalone_getAllContexts() {
    return standalone_get_current_component().$$.context;
}
/**
 * Checks whether a given `key` has been set in the context of a parent component.
 * Must be called during component initialisation.
 *
 * https://svelte.dev/docs#run-time-svelte-hascontext
 */
function standalone_hasContext(key) {
    return standalone_get_current_component().$$.context.has(key);
}
// TODO figure out if we still want to support
// shorthand events, or if we want to implement
// a real bubbling mechanism
function standalone_bubble(component, event) {
    const callbacks = component.$$.callbacks[event.type];
    if (callbacks) {
        // @ts-ignore
        callbacks.slice().forEach(fn => fn.call(this, event));
    }
}

const standalone_dirty_components = [];
const standalone_intros = { enabled: false };
const standalone_binding_callbacks = [];
let standalone_render_callbacks = [];
const standalone_flush_callbacks = [];
const standalone_resolved_promise = /* @__PURE__ */ Promise.resolve();
let standalone_update_scheduled = false;
function standalone_schedule_update() {
    if (!standalone_update_scheduled) {
        standalone_update_scheduled = true;
        standalone_resolved_promise.then(standalone_flush);
    }
}
function standalone_tick() {
    standalone_schedule_update();
    return standalone_resolved_promise;
}
function standalone_add_render_callback(fn) {
    standalone_render_callbacks.push(fn);
}
function standalone_add_flush_callback(fn) {
    standalone_flush_callbacks.push(fn);
}
// flush() calls callbacks in this order:
// 1. All beforeUpdate callbacks, in order: parents before children
// 2. All bind:this callbacks, in reverse order: children before parents.
// 3. All afterUpdate callbacks, in order: parents before children. EXCEPT
//    for afterUpdates called during the initial onMount, which are called in
//    reverse order: children before parents.
// Since callbacks might update component values, which could trigger another
// call to flush(), the following steps guard against this:
// 1. During beforeUpdate, any updated components will be added to the
//    dirty_components array and will cause a reentrant call to flush(). Because
//    the flush index is kept outside the function, the reentrant call will pick
//    up where the earlier call left off and go through all dirty components. The
//    current_component value is saved and restored so that the reentrant call will
//    not interfere with the "parent" flush() call.
// 2. bind:this callbacks cannot trigger new flush() calls.
// 3. During afterUpdate, any updated components will NOT have their afterUpdate
//    callback called a second time; the seen_callbacks set, outside the flush()
//    function, guarantees this behavior.
const standalone_seen_callbacks = new Set();
let standalone_flushidx = 0; // Do *not* move this inside the flush() function
function standalone_flush() {
    // Do not reenter flush while dirty components are updated, as this can
    // result in an infinite loop. Instead, let the inner flush handle it.
    // Reentrancy is ok afterwards for bindings etc.
    if (standalone_flushidx !== 0) {
        return;
    }
    const saved_component = standalone_current_component;
    do {
        // first, call beforeUpdate functions
        // and update components
        try {
            while (standalone_flushidx < standalone_dirty_components.length) {
                const component = standalone_dirty_components[standalone_flushidx];
                standalone_flushidx++;
                standalone_set_current_component(component);
                standalone_update(component.$$);
            }
        }
        catch (e) {
            // reset dirty state to not end up in a deadlocked state and then rethrow
            standalone_dirty_components.length = 0;
            standalone_flushidx = 0;
            throw e;
        }
        standalone_set_current_component(null);
        standalone_dirty_components.length = 0;
        standalone_flushidx = 0;
        while (standalone_binding_callbacks.length)
            standalone_binding_callbacks.pop()();
        // then, once components are updated, call
        // afterUpdate functions. This may cause
        // subsequent updates...
        for (let i = 0; i < standalone_render_callbacks.length; i += 1) {
            const callback = standalone_render_callbacks[i];
            if (!standalone_seen_callbacks.has(callback)) {
                // ...so guard against infinite loops
                standalone_seen_callbacks.add(callback);
                callback();
            }
        }
        standalone_render_callbacks.length = 0;
    } while (standalone_dirty_components.length);
    while (standalone_flush_callbacks.length) {
        standalone_flush_callbacks.pop()();
    }
    standalone_update_scheduled = false;
    standalone_seen_callbacks.clear();
    standalone_set_current_component(saved_component);
}
function standalone_update($$) {
    if ($$.fragment !== null) {
        $$.update();
        standalone_run_all($$.before_update);
        const dirty = $$.dirty;
        $$.dirty = [-1];
        $$.fragment && $$.fragment.p($$.ctx, dirty);
        $$.after_update.forEach(standalone_add_render_callback);
    }
}
/**
 * Useful for example to execute remaining `afterUpdate` callbacks before executing `destroy`.
 */
function standalone_flush_render_callbacks(fns) {
    const filtered = [];
    const targets = [];
    standalone_render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c));
    targets.forEach((c) => c());
    standalone_render_callbacks = filtered;
}

let standalone_promise;
function standalone_wait() {
    if (!standalone_promise) {
        standalone_promise = Promise.resolve();
        standalone_promise.then(() => {
            standalone_promise = null;
        });
    }
    return standalone_promise;
}
function standalone_dispatch(node, direction, kind) {
    node.dispatchEvent(standalone_custom_event(`${direction ? 'intro' : 'outro'}${kind}`));
}
const standalone_outroing = new Set();
let standalone_outros;
function standalone_group_outros() {
    standalone_outros = {
        r: 0,
        c: [],
        p: standalone_outros // parent group
    };
}
function standalone_check_outros() {
    if (!standalone_outros.r) {
        standalone_run_all(standalone_outros.c);
    }
    standalone_outros = standalone_outros.p;
}
function standalone_transition_in(block, local) {
    if (block && block.i) {
        standalone_outroing.delete(block);
        block.i(local);
    }
}
function standalone_transition_out(block, local, detach, callback) {
    if (block && block.o) {
        if (standalone_outroing.has(block))
            return;
        standalone_outroing.add(block);
        standalone_outros.c.push(() => {
            standalone_outroing.delete(block);
            if (callback) {
                if (detach)
                    block.d(1);
                callback();
            }
        });
        block.o(local);
    }
    else if (callback) {
        callback();
    }
}
const standalone_null_transition = { duration: 0 };
function standalone_create_in_transition(node, fn, params) {
    const options = { direction: 'in' };
    let config = fn(node, params, options);
    let running = false;
    let animation_name;
    let task;
    let uid = 0;
    function cleanup() {
        if (animation_name)
            standalone_delete_rule(node, animation_name);
    }
    function go() {
        const { delay = 0, duration = 300, easing = standalone_internal_identity, tick = standalone_noop, css } = config || standalone_null_transition;
        if (css)
            animation_name = standalone_create_rule(node, 0, 1, duration, delay, easing, css, uid++);
        tick(0, 1);
        const start_time = standalone_now() + delay;
        const end_time = start_time + duration;
        if (task)
            task.abort();
        running = true;
        standalone_add_render_callback(() => standalone_dispatch(node, true, 'start'));
        task = standalone_loop(now => {
            if (running) {
                if (now >= end_time) {
                    tick(1, 0);
                    standalone_dispatch(node, true, 'end');
                    cleanup();
                    return running = false;
                }
                if (now >= start_time) {
                    const t = easing((now - start_time) / duration);
                    tick(t, 1 - t);
                }
            }
            return running;
        });
    }
    let started = false;
    return {
        start() {
            if (started)
                return;
            started = true;
            standalone_delete_rule(node);
            if (standalone_internal_is_function(config)) {
                config = config(options);
                standalone_wait().then(go);
            }
            else {
                go();
            }
        },
        invalidate() {
            started = false;
        },
        end() {
            if (running) {
                cleanup();
                running = false;
            }
        }
    };
}
function standalone_create_out_transition(node, fn, params) {
    const options = { direction: 'out' };
    let config = fn(node, params, options);
    let running = true;
    let animation_name;
    const group = standalone_outros;
    group.r += 1;
    function go() {
        const { delay = 0, duration = 300, easing = standalone_internal_identity, tick = standalone_noop, css } = config || standalone_null_transition;
        if (css)
            animation_name = standalone_create_rule(node, 1, 0, duration, delay, easing, css);
        const start_time = standalone_now() + delay;
        const end_time = start_time + duration;
        standalone_add_render_callback(() => standalone_dispatch(node, false, 'start'));
        standalone_loop(now => {
            if (running) {
                if (now >= end_time) {
                    tick(0, 1);
                    standalone_dispatch(node, false, 'end');
                    if (!--group.r) {
                        // this will result in `end()` being called,
                        // so we don't need to clean up here
                        standalone_run_all(group.c);
                    }
                    return false;
                }
                if (now >= start_time) {
                    const t = easing((now - start_time) / duration);
                    tick(1 - t, t);
                }
            }
            return running;
        });
    }
    if (standalone_internal_is_function(config)) {
        standalone_wait().then(() => {
            // @ts-ignore
            config = config(options);
            go();
        });
    }
    else {
        go();
    }
    return {
        end(reset) {
            if (reset && config.tick) {
                config.tick(1, 0);
            }
            if (running) {
                if (animation_name)
                    standalone_delete_rule(node, animation_name);
                running = false;
            }
        }
    };
}
function standalone_create_bidirectional_transition(node, fn, params, intro) {
    const options = { direction: 'both' };
    let config = fn(node, params, options);
    let t = intro ? 0 : 1;
    let running_program = null;
    let pending_program = null;
    let animation_name = null;
    function clear_animation() {
        if (animation_name)
            standalone_delete_rule(node, animation_name);
    }
    function init(program, duration) {
        const d = (program.b - t);
        duration *= Math.abs(d);
        return {
            a: t,
            b: program.b,
            d,
            duration,
            start: program.start,
            end: program.start + duration,
            group: program.group
        };
    }
    function go(b) {
        const { delay = 0, duration = 300, easing = standalone_internal_identity, tick = standalone_noop, css } = config || standalone_null_transition;
        const program = {
            start: standalone_now() + delay,
            b
        };
        if (!b) {
            // @ts-ignore todo: improve typings
            program.group = standalone_outros;
            standalone_outros.r += 1;
        }
        if (running_program || pending_program) {
            pending_program = program;
        }
        else {
            // if this is an intro, and there's a delay, we need to do
            // an initial tick and/or apply CSS animation immediately
            if (css) {
                clear_animation();
                animation_name = standalone_create_rule(node, t, b, duration, delay, easing, css);
            }
            if (b)
                tick(0, 1);
            running_program = init(program, duration);
            standalone_add_render_callback(() => standalone_dispatch(node, b, 'start'));
            standalone_loop(now => {
                if (pending_program && now > pending_program.start) {
                    running_program = init(pending_program, duration);
                    pending_program = null;
                    standalone_dispatch(node, running_program.b, 'start');
                    if (css) {
                        clear_animation();
                        animation_name = standalone_create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css);
                    }
                }
                if (running_program) {
                    if (now >= running_program.end) {
                        tick(t = running_program.b, 1 - t);
                        standalone_dispatch(node, running_program.b, 'end');
                        if (!pending_program) {
                            // we're done
                            if (running_program.b) {
                                // intro — we can tidy up immediately
                                clear_animation();
                            }
                            else {
                                // outro — needs to be coordinated
                                if (!--running_program.group.r)
                                    standalone_run_all(running_program.group.c);
                            }
                        }
                        running_program = null;
                    }
                    else if (now >= running_program.start) {
                        const p = now - running_program.start;
                        t = running_program.a + running_program.d * easing(p / running_program.duration);
                        tick(t, 1 - t);
                    }
                }
                return !!(running_program || pending_program);
            });
        }
    }
    return {
        run(b) {
            if (standalone_internal_is_function(config)) {
                standalone_wait().then(() => {
                    // @ts-ignore
                    config = config(options);
                    go(b);
                });
            }
            else {
                go(b);
            }
        },
        end() {
            clear_animation();
            running_program = pending_program = null;
        }
    };
}

function standalone_handle_promise(promise, info) {
    const token = info.token = {};
    function update(type, index, key, value) {
        if (info.token !== token)
            return;
        info.resolved = value;
        let child_ctx = info.ctx;
        if (key !== undefined) {
            child_ctx = child_ctx.slice();
            child_ctx[key] = value;
        }
        const block = type && (info.current = type)(child_ctx);
        let needs_flush = false;
        if (info.block) {
            if (info.blocks) {
                info.blocks.forEach((block, i) => {
                    if (i !== index && block) {
                        standalone_group_outros();
                        standalone_transition_out(block, 1, 1, () => {
                            if (info.blocks[i] === block) {
                                info.blocks[i] = null;
                            }
                        });
                        standalone_check_outros();
                    }
                });
            }
            else {
                info.block.d(1);
            }
            block.c();
            standalone_transition_in(block, 1);
            block.m(info.mount(), info.anchor);
            needs_flush = true;
        }
        info.block = block;
        if (info.blocks)
            info.blocks[index] = block;
        if (needs_flush) {
            standalone_flush();
        }
    }
    if (standalone_is_promise(promise)) {
        const current_component = standalone_get_current_component();
        promise.then(value => {
            standalone_set_current_component(current_component);
            update(info.then, 1, info.value, value);
            standalone_set_current_component(null);
        }, error => {
            standalone_set_current_component(current_component);
            update(info.catch, 2, info.error, error);
            standalone_set_current_component(null);
            if (!info.hasCatch) {
                throw error;
            }
        });
        // if we previously had a then/catch block, destroy it
        if (info.current !== info.pending) {
            update(info.pending, 0);
            return true;
        }
    }
    else {
        if (info.current !== info.then) {
            update(info.then, 1, info.value, promise);
            return true;
        }
        info.resolved = promise;
    }
}
function standalone_update_await_block_branch(info, ctx, dirty) {
    const child_ctx = ctx.slice();
    const { resolved } = info;
    if (info.current === info.then) {
        child_ctx[info.value] = resolved;
    }
    if (info.current === info.catch) {
        child_ctx[info.error] = resolved;
    }
    info.block.p(child_ctx, dirty);
}

function standalone_destroy_block(block, lookup) {
    block.d(1);
    lookup.delete(block.key);
}
function standalone_outro_and_destroy_block(block, lookup) {
    standalone_transition_out(block, 1, 1, () => {
        lookup.delete(block.key);
    });
}
function standalone_fix_and_destroy_block(block, lookup) {
    block.f();
    standalone_destroy_block(block, lookup);
}
function standalone_fix_and_outro_and_destroy_block(block, lookup) {
    block.f();
    standalone_outro_and_destroy_block(block, lookup);
}
function standalone_update_keyed_each(old_blocks, dirty, get_key, dynamic, ctx, list, lookup, node, destroy, create_each_block, next, get_context) {
    let o = old_blocks.length;
    let n = list.length;
    let i = o;
    const old_indexes = {};
    while (i--)
        old_indexes[old_blocks[i].key] = i;
    const new_blocks = [];
    const new_lookup = new Map();
    const deltas = new Map();
    const updates = [];
    i = n;
    while (i--) {
        const child_ctx = get_context(ctx, list, i);
        const key = get_key(child_ctx);
        let block = lookup.get(key);
        if (!block) {
            block = create_each_block(key, child_ctx);
            block.c();
        }
        else if (dynamic) {
            // defer updates until all the DOM shuffling is done
            updates.push(() => block.p(child_ctx, dirty));
        }
        new_lookup.set(key, new_blocks[i] = block);
        if (key in old_indexes)
            deltas.set(key, Math.abs(i - old_indexes[key]));
    }
    const will_move = new Set();
    const did_move = new Set();
    function insert(block) {
        standalone_transition_in(block, 1);
        block.m(node, next);
        lookup.set(block.key, block);
        next = block.first;
        n--;
    }
    while (o && n) {
        const new_block = new_blocks[n - 1];
        const old_block = old_blocks[o - 1];
        const new_key = new_block.key;
        const old_key = old_block.key;
        if (new_block === old_block) {
            // do nothing
            next = new_block.first;
            o--;
            n--;
        }
        else if (!new_lookup.has(old_key)) {
            // remove old block
            destroy(old_block, lookup);
            o--;
        }
        else if (!lookup.has(new_key) || will_move.has(new_key)) {
            insert(new_block);
        }
        else if (did_move.has(old_key)) {
            o--;
        }
        else if (deltas.get(new_key) > deltas.get(old_key)) {
            did_move.add(new_key);
            insert(new_block);
        }
        else {
            will_move.add(old_key);
            o--;
        }
    }
    while (o--) {
        const old_block = old_blocks[o];
        if (!new_lookup.has(old_block.key))
            destroy(old_block, lookup);
    }
    while (n)
        insert(new_blocks[n - 1]);
    standalone_run_all(updates);
    return new_blocks;
}
function standalone_validate_each_keys(ctx, list, get_context, get_key) {
    const keys = new Set();
    for (let i = 0; i < list.length; i++) {
        const key = get_key(get_context(ctx, list, i));
        if (keys.has(key)) {
            throw new Error('Cannot have duplicate keys in a keyed each');
        }
        keys.add(key);
    }
}

function standalone_get_spread_update(levels, updates) {
    const update = {};
    const to_null_out = {};
    const accounted_for = { $$scope: 1 };
    let i = levels.length;
    while (i--) {
        const o = levels[i];
        const n = updates[i];
        if (n) {
            for (const key in o) {
                if (!(key in n))
                    to_null_out[key] = 1;
            }
            for (const key in n) {
                if (!accounted_for[key]) {
                    update[key] = n[key];
                    accounted_for[key] = 1;
                }
            }
            levels[i] = n;
        }
        else {
            for (const key in o) {
                accounted_for[key] = 1;
            }
        }
    }
    for (const key in to_null_out) {
        if (!(key in update))
            update[key] = undefined;
    }
    return update;
}
function standalone_get_spread_object(spread_props) {
    return typeof spread_props === 'object' && spread_props !== null ? spread_props : {};
}

const standalone_boolean_attributes = [
    'allowfullscreen',
    'allowpaymentrequest',
    'async',
    'autofocus',
    'autoplay',
    'checked',
    'controls',
    'default',
    'defer',
    'disabled',
    'formnovalidate',
    'hidden',
    'inert',
    'ismap',
    'loop',
    'multiple',
    'muted',
    'nomodule',
    'novalidate',
    'open',
    'playsinline',
    'readonly',
    'required',
    'reversed',
    'selected'
];
/**
 * List of HTML boolean attributes (e.g. `<input disabled>`).
 * Source: https://html.spec.whatwg.org/multipage/indices.html
 */
const src_standalone_boolean_attributes = new Set([...standalone_boolean_attributes]);

/** regex of all html void element names */
const standalone_void_element_names = /^(?:area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/;
function standalone_is_void(name) {
    return standalone_void_element_names.test(name) || name.toLowerCase() === '!doctype';
}

const standalone_invalid_attribute_name_character = /[\s'">/=\u{FDD0}-\u{FDEF}\u{FFFE}\u{FFFF}\u{1FFFE}\u{1FFFF}\u{2FFFE}\u{2FFFF}\u{3FFFE}\u{3FFFF}\u{4FFFE}\u{4FFFF}\u{5FFFE}\u{5FFFF}\u{6FFFE}\u{6FFFF}\u{7FFFE}\u{7FFFF}\u{8FFFE}\u{8FFFF}\u{9FFFE}\u{9FFFF}\u{AFFFE}\u{AFFFF}\u{BFFFE}\u{BFFFF}\u{CFFFE}\u{CFFFF}\u{DFFFE}\u{DFFFF}\u{EFFFE}\u{EFFFF}\u{FFFFE}\u{FFFFF}\u{10FFFE}\u{10FFFF}]/u;
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
// https://infra.spec.whatwg.org/#noncharacter
function standalone_spread(args, attrs_to_add) {
    const attributes = Object.assign({}, ...args);
    if (attrs_to_add) {
        const classes_to_add = attrs_to_add.classes;
        const styles_to_add = attrs_to_add.styles;
        if (classes_to_add) {
            if (attributes.class == null) {
                attributes.class = classes_to_add;
            }
            else {
                attributes.class += ' ' + classes_to_add;
            }
        }
        if (styles_to_add) {
            if (attributes.style == null) {
                attributes.style = standalone_style_object_to_string(styles_to_add);
            }
            else {
                attributes.style = standalone_style_object_to_string(standalone_merge_ssr_styles(attributes.style, styles_to_add));
            }
        }
    }
    let str = '';
    Object.keys(attributes).forEach(name => {
        if (standalone_invalid_attribute_name_character.test(name))
            return;
        const value = attributes[name];
        if (value === true)
            str += ' ' + name;
        else if (src_standalone_boolean_attributes.has(name.toLowerCase())) {
            if (value)
                str += ' ' + name;
        }
        else if (value != null) {
            str += ` ${name}="${value}"`;
        }
    });
    return str;
}
function standalone_merge_ssr_styles(style_attribute, style_directive) {
    const style_object = {};
    for (const individual_style of style_attribute.split(';')) {
        const colon_index = individual_style.indexOf(':');
        const name = individual_style.slice(0, colon_index).trim();
        const value = individual_style.slice(colon_index + 1).trim();
        if (!name)
            continue;
        style_object[name] = value;
    }
    for (const name in style_directive) {
        const value = style_directive[name];
        if (value) {
            style_object[name] = value;
        }
        else {
            delete style_object[name];
        }
    }
    return style_object;
}
const standalone_ATTR_REGEX = /[&"]/g;
const standalone_CONTENT_REGEX = /[&<]/g;
/**
 * Note: this method is performance sensitive and has been optimized
 * https://github.com/sveltejs/svelte/pull/5701
 */
function standalone_internal_escape(value, is_attr = false) {
    const str = String(value);
    const pattern = is_attr ? standalone_ATTR_REGEX : standalone_CONTENT_REGEX;
    pattern.lastIndex = 0;
    let escaped = '';
    let last = 0;
    while (pattern.test(str)) {
        const i = pattern.lastIndex - 1;
        const ch = str[i];
        escaped += str.substring(last, i) + (ch === '&' ? '&amp;' : (ch === '"' ? '&quot;' : '&lt;'));
        last = i + 1;
    }
    return escaped + str.substring(last);
}
function standalone_escape_attribute_value(value) {
    // keep booleans, null, and undefined for the sake of `spread`
    const should_escape = typeof value === 'string' || (value && typeof value === 'object');
    return should_escape ? standalone_internal_escape(value, true) : value;
}
function standalone_escape_object(obj) {
    const result = {};
    for (const key in obj) {
        result[key] = standalone_escape_attribute_value(obj[key]);
    }
    return result;
}
function standalone_each(items, fn) {
    let str = '';
    for (let i = 0; i < items.length; i += 1) {
        str += fn(items[i], i);
    }
    return str;
}
const standalone_missing_component = {
    $$render: () => ''
};
function standalone_validate_component(component, name) {
    if (!component || !component.$$render) {
        if (name === 'svelte:component')
            name += ' this={...}';
        throw new Error(`<${name}> is not a valid SSR component. You may need to review your build config to ensure that dependencies are compiled, rather than imported as pre-compiled modules. Otherwise you may need to fix a <${name}>.`);
    }
    return component;
}
function standalone_debug(file, line, column, values) {
    console.log(`{@debug} ${file ? file + ' ' : ''}(${line}:${column})`); // eslint-disable-line no-console
    console.log(values); // eslint-disable-line no-console
    return '';
}
let standalone_on_destroy;
function standalone_create_ssr_component(fn) {
    function $$render(result, props, bindings, slots, context) {
        const parent_component = standalone_current_component;
        const $$ = {
            on_destroy: standalone_on_destroy,
            context: new Map(context || (parent_component ? parent_component.$$.context : [])),
            // these will be immediately discarded
            on_mount: [],
            before_update: [],
            after_update: [],
            callbacks: standalone_blank_object()
        };
        standalone_set_current_component({ $$ });
        const html = fn(result, props, bindings, slots);
        standalone_set_current_component(parent_component);
        return html;
    }
    return {
        render: (props = {}, { $$slots = {}, context = new Map() } = {}) => {
            standalone_on_destroy = [];
            const result = { title: '', head: '', css: new Set() };
            const html = $$render(result, props, {}, $$slots, context);
            standalone_run_all(standalone_on_destroy);
            return {
                html,
                css: {
                    code: Array.from(result.css).map(css => css.code).join('\n'),
                    map: null // TODO
                },
                head: result.title + result.head
            };
        },
        $$render
    };
}
function standalone_add_attribute(name, value, boolean) {
    if (value == null || (boolean && !value))
        return '';
    const assignment = (boolean && value === true) ? '' : `="${standalone_internal_escape(value, true)}"`;
    return ` ${name}${assignment}`;
}
function standalone_add_classes(classes) {
    return classes ? ` class="${classes}"` : '';
}
function standalone_style_object_to_string(style_object) {
    return Object.keys(style_object)
        .filter(key => style_object[key])
        .map(key => `${key}: ${standalone_escape_attribute_value(style_object[key])};`)
        .join(' ');
}
function standalone_add_styles(style_object) {
    const styles = standalone_style_object_to_string(style_object);
    return styles ? ` style="${styles}"` : '';
}

function standalone_bind(component, name, callback) {
    const index = component.$$.props[name];
    if (index !== undefined) {
        component.$$.bound[index] = callback;
        callback(component.$$.ctx[index]);
    }
}
function standalone_create_component(block) {
    block && block.c();
}
function standalone_claim_component(block, parent_nodes) {
    block && block.l(parent_nodes);
}
function standalone_mount_component(component, target, anchor, customElement) {
    const { fragment, after_update } = component.$$;
    fragment && fragment.m(target, anchor);
    if (!customElement) {
        // onMount happens before the initial afterUpdate
        standalone_add_render_callback(() => {
            const new_on_destroy = component.$$.on_mount.map(standalone_run).filter(standalone_internal_is_function);
            // if the component was destroyed immediately
            // it will update the `$$.on_destroy` reference to `null`.
            // the destructured on_destroy may still reference to the old array
            if (component.$$.on_destroy) {
                component.$$.on_destroy.push(...new_on_destroy);
            }
            else {
                // Edge case - component was destroyed immediately,
                // most likely as a result of a binding initialising
                standalone_run_all(new_on_destroy);
            }
            component.$$.on_mount = [];
        });
    }
    after_update.forEach(standalone_add_render_callback);
}
function standalone_destroy_component(component, detaching) {
    const $$ = component.$$;
    if ($$.fragment !== null) {
        standalone_flush_render_callbacks($$.after_update);
        standalone_run_all($$.on_destroy);
        $$.fragment && $$.fragment.d(detaching);
        // TODO null out other refs, including component.$$ (but need to
        // preserve final state?)
        $$.on_destroy = $$.fragment = null;
        $$.ctx = [];
    }
}
function standalone_make_dirty(component, i) {
    if (component.$$.dirty[0] === -1) {
        standalone_dirty_components.push(component);
        standalone_schedule_update();
        component.$$.dirty.fill(0);
    }
    component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
}
function standalone_init(component, options, instance, create_fragment, not_equal, props, append_styles, dirty = [-1]) {
    const parent_component = standalone_current_component;
    standalone_set_current_component(component);
    const $$ = component.$$ = {
        fragment: null,
        ctx: [],
        // state
        props,
        update: standalone_noop,
        not_equal,
        bound: standalone_blank_object(),
        // lifecycle
        on_mount: [],
        on_destroy: [],
        on_disconnect: [],
        before_update: [],
        after_update: [],
        context: new Map(options.context || (parent_component ? parent_component.$$.context : [])),
        // everything else
        callbacks: standalone_blank_object(),
        dirty,
        skip_bound: false,
        root: options.target || parent_component.$$.root
    };
    append_styles && append_styles($$.root);
    let ready = false;
    $$.ctx = instance
        ? instance(component, options.props || {}, (i, ret, ...rest) => {
            const value = rest.length ? rest[0] : ret;
            if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
                if (!$$.skip_bound && $$.bound[i])
                    $$.bound[i](value);
                if (ready)
                    standalone_make_dirty(component, i);
            }
            return ret;
        })
        : [];
    $$.update();
    ready = true;
    standalone_run_all($$.before_update);
    // `false` as a special case of no DOM component
    $$.fragment = create_fragment ? create_fragment($$.ctx) : false;
    if (options.target) {
        if (options.hydrate) {
            standalone_start_hydrating();
            const nodes = standalone_children(options.target);
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            $$.fragment && $$.fragment.l(nodes);
            nodes.forEach(standalone_detach);
        }
        else {
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            $$.fragment && $$.fragment.c();
        }
        if (options.intro)
            standalone_transition_in(component.$$.fragment);
        standalone_mount_component(component, options.target, options.anchor, options.customElement);
        standalone_end_hydrating();
        standalone_flush();
    }
    standalone_set_current_component(parent_component);
}
let standalone_SvelteElement;
if (typeof HTMLElement === 'function') {
    standalone_SvelteElement = class extends HTMLElement {
        constructor() {
            super();
            this.attachShadow({ mode: 'open' });
        }
        connectedCallback() {
            const { on_mount } = this.$$;
            this.$$.on_disconnect = on_mount.map(standalone_run).filter(standalone_internal_is_function);
            // @ts-ignore todo: improve typings
            for (const key in this.$$.slotted) {
                // @ts-ignore todo: improve typings
                this.appendChild(this.$$.slotted[key]);
            }
        }
        attributeChangedCallback(attr, _oldValue, newValue) {
            this[attr] = newValue;
        }
        disconnectedCallback() {
            standalone_run_all(this.$$.on_disconnect);
        }
        $destroy() {
            standalone_destroy_component(this, 1);
            this.$destroy = standalone_noop;
        }
        $on(type, callback) {
            // TODO should this delegate to addEventListener?
            if (!standalone_internal_is_function(callback)) {
                return standalone_noop;
            }
            const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
            callbacks.push(callback);
            return () => {
                const index = callbacks.indexOf(callback);
                if (index !== -1)
                    callbacks.splice(index, 1);
            };
        }
        $set($$props) {
            if (this.$$set && !standalone_is_empty($$props)) {
                this.$$.skip_bound = true;
                this.$$set($$props);
                this.$$.skip_bound = false;
            }
        }
    };
}
/**
 * Base class for Svelte components. Used when dev=false.
 */
class standalone_SvelteComponent {
    $destroy() {
        standalone_destroy_component(this, 1);
        this.$destroy = standalone_noop;
    }
    $on(type, callback) {
        if (!standalone_internal_is_function(callback)) {
            return standalone_noop;
        }
        const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
        callbacks.push(callback);
        return () => {
            const index = callbacks.indexOf(callback);
            if (index !== -1)
                callbacks.splice(index, 1);
        };
    }
    $set($$props) {
        if (this.$$set && !standalone_is_empty($$props)) {
            this.$$.skip_bound = true;
            this.$$set($$props);
            this.$$.skip_bound = false;
        }
    }
}

function standalone_dispatch_dev(type, detail) {
    document.dispatchEvent(standalone_custom_event(type, Object.assign({ version: '3.59.2' }, detail), { bubbles: true }));
}
function standalone_append_dev(target, node) {
    standalone_dispatch_dev('SvelteDOMInsert', { target, node });
    standalone_append(target, node);
}
function standalone_append_hydration_dev(target, node) {
    standalone_dispatch_dev('SvelteDOMInsert', { target, node });
    standalone_append_hydration(target, node);
}
function standalone_insert_dev(target, node, anchor) {
    standalone_dispatch_dev('SvelteDOMInsert', { target, node, anchor });
    standalone_insert(target, node, anchor);
}
function standalone_insert_hydration_dev(target, node, anchor) {
    standalone_dispatch_dev('SvelteDOMInsert', { target, node, anchor });
    standalone_insert_hydration(target, node, anchor);
}
function standalone_detach_dev(node) {
    standalone_dispatch_dev('SvelteDOMRemove', { node });
    standalone_detach(node);
}
function standalone_detach_between_dev(before, after) {
    while (before.nextSibling && before.nextSibling !== after) {
        standalone_detach_dev(before.nextSibling);
    }
}
function standalone_detach_before_dev(after) {
    while (after.previousSibling) {
        standalone_detach_dev(after.previousSibling);
    }
}
function standalone_detach_after_dev(before) {
    while (before.nextSibling) {
        standalone_detach_dev(before.nextSibling);
    }
}
function standalone_listen_dev(node, event, handler, options, has_prevent_default, has_stop_propagation, has_stop_immediate_propagation) {
    const modifiers = options === true ? ['capture'] : options ? Array.from(Object.keys(options)) : [];
    if (has_prevent_default)
        modifiers.push('preventDefault');
    if (has_stop_propagation)
        modifiers.push('stopPropagation');
    if (has_stop_immediate_propagation)
        modifiers.push('stopImmediatePropagation');
    standalone_dispatch_dev('SvelteDOMAddEventListener', { node, event, handler, modifiers });
    const dispose = standalone_listen(node, event, handler, options);
    return () => {
        standalone_dispatch_dev('SvelteDOMRemoveEventListener', { node, event, handler, modifiers });
        dispose();
    };
}
function standalone_attr_dev(node, attribute, value) {
    standalone_attr(node, attribute, value);
    if (value == null)
        standalone_dispatch_dev('SvelteDOMRemoveAttribute', { node, attribute });
    else
        standalone_dispatch_dev('SvelteDOMSetAttribute', { node, attribute, value });
}
function standalone_prop_dev(node, property, value) {
    node[property] = value;
    standalone_dispatch_dev('SvelteDOMSetProperty', { node, property, value });
}
function standalone_dataset_dev(node, property, value) {
    node.dataset[property] = value;
    standalone_dispatch_dev('SvelteDOMSetDataset', { node, property, value });
}
function standalone_set_data_dev(text, data) {
    data = '' + data;
    if (text.data === data)
        return;
    standalone_dispatch_dev('SvelteDOMSetData', { node: text, data });
    text.data = data;
}
function standalone_set_data_contenteditable_dev(text, data) {
    data = '' + data;
    if (text.wholeText === data)
        return;
    standalone_dispatch_dev('SvelteDOMSetData', { node: text, data });
    text.data = data;
}
function standalone_set_data_maybe_contenteditable_dev(text, data, attr_value) {
    if (~standalone_contenteditable_truthy_values.indexOf(attr_value)) {
        standalone_set_data_contenteditable_dev(text, data);
    }
    else {
        standalone_set_data_dev(text, data);
    }
}
function standalone_validate_each_argument(arg) {
    if (typeof arg !== 'string' && !(arg && typeof arg === 'object' && 'length' in arg)) {
        let msg = '{#each} only iterates over array-like objects.';
        if (typeof Symbol === 'function' && arg && Symbol.iterator in arg) {
            msg += ' You can use a spread to convert this iterable into an array.';
        }
        throw new Error(msg);
    }
}
function standalone_validate_slots(name, slot, keys) {
    for (const slot_key of Object.keys(slot)) {
        if (!~keys.indexOf(slot_key)) {
            console.warn(`<${name}> received an unexpected slot "${slot_key}".`);
        }
    }
}
function standalone_validate_dynamic_element(tag) {
    const is_string = typeof tag === 'string';
    if (tag && !is_string) {
        throw new Error('<svelte:element> expects "this" attribute to be a string.');
    }
}
function standalone_validate_void_dynamic_element(tag) {
    if (tag && standalone_is_void(tag)) {
        console.warn(`<svelte:element this="${tag}"> is self-closing and cannot have content.`);
    }
}
function standalone_construct_svelte_component_dev(component, props) {
    const error_message = 'this={...} of <svelte:component> should specify a Svelte component.';
    try {
        const instance = new component(props);
        if (!instance.$$ || !instance.$set || !instance.$on || !instance.$destroy) {
            throw new Error(error_message);
        }
        return instance;
    }
    catch (err) {
        const { message } = err;
        if (typeof message === 'string' && message.indexOf('is not a constructor') !== -1) {
            throw new Error(error_message);
        }
        else {
            throw err;
        }
    }
}
/**
 * Base class for Svelte components with some minor dev-enhancements. Used when dev=true.
 */
class standalone_SvelteComponentDev extends standalone_SvelteComponent {
    constructor(options) {
        if (!options || (!options.target && !options.$$inline)) {
            throw new Error("'target' is a required option");
        }
        super();
    }
    $destroy() {
        super.$destroy();
        this.$destroy = () => {
            console.warn('Component was already destroyed'); // eslint-disable-line no-console
        };
    }
    $capture_state() { }
    $inject_state() { }
}
/**
 * Base class to create strongly typed Svelte components.
 * This only exists for typing purposes and should be used in `.d.ts` files.
 *
 * ### Example:
 *
 * You have component library on npm called `component-library`, from which
 * you export a component called `MyComponent`. For Svelte+TypeScript users,
 * you want to provide typings. Therefore you create a `index.d.ts`:
 * ```ts
 * import { SvelteComponentTyped } from "svelte";
 * export class MyComponent extends SvelteComponentTyped<{foo: string}> {}
 * ```
 * Typing this makes it possible for IDEs like VS Code with the Svelte extension
 * to provide intellisense and to use the component like this in a Svelte file
 * with TypeScript:
 * ```svelte
 * <script lang="ts">
 * 	import { MyComponent } from "component-library";
 * </script>
 * <MyComponent foo={'bar'} />
 * ```
 *
 * #### Why not make this part of `SvelteComponent(Dev)`?
 * Because
 * ```ts
 * class ASubclassOfSvelteComponent extends SvelteComponent<{foo: string}> {}
 * const component: typeof SvelteComponent = ASubclassOfSvelteComponent;
 * ```
 * will throw a type error, so we need to separate the more strictly typed class.
 */
class standalone_SvelteComponentTyped extends standalone_SvelteComponentDev {
    constructor(options) {
        super(options);
    }
}
function standalone_loop_guard(timeout) {
    const start = Date.now();
    return () => {
        if (Date.now() - start > timeout) {
            throw new Error('Infinite loop detected');
        }
    };
}



;// ../../node_modules/svelte-fa/src/utils.js
const standalone_parseNumber = parseFloat;

function standalone_joinCss(obj, separator = ';') {
  let texts;
  if (Array.isArray(obj)) {
    texts = obj.filter((text) => text);
  } else {
    texts = [];
    for (const prop in obj) {
      if (obj[prop]) {
        texts.push(`${prop}:${obj[prop]}`);
      }
    }
  }
  return texts.join(separator);
}

function standalone_getStyles(style, size, pull, fw) {
  let float;
  let width;
  const height = '1em';
  let lineHeight;
  let fontSize;
  let textAlign;
  let verticalAlign = '-.125em';
  const overflow = 'visible';

  if (fw) {
    textAlign = 'center';
    width = '1.25em';
  }

  if (pull) {
    float = pull;
  }

  if (size) {
    if (size == 'lg') {
      fontSize = '1.33333em';
      lineHeight = '.75em';
      verticalAlign = '-.225em';
    } else if (size == 'xs') {
      fontSize = '.75em';
    } else if (size == 'sm') {
      fontSize = '.875em';
    } else {
      fontSize = size.replace('x', 'em');
    }
  }

  return standalone_joinCss([
    standalone_joinCss({
      float,
      width,
      height,
      'line-height': lineHeight,
      'font-size': fontSize,
      'text-align': textAlign,
      'vertical-align': verticalAlign,
      'transform-origin': 'center',
      overflow,
    }),
    style,
  ]);
}

function standalone_getTransform(
  scale,
  translateX,
  translateY,
  rotate,
  flip,
  translateTimes = 1,
  translateUnit = '',
  rotateUnit = '',
) {
  let flipX = 1;
  let flipY = 1;

  if (flip) {
    if (flip == 'horizontal') {
      flipX = -1;
    } else if (flip == 'vertical') {
      flipY = -1;
    } else {
      flipX = flipY = -1;
    }
  }

  return standalone_joinCss(
    [
      `translate(${standalone_parseNumber(translateX) * translateTimes}${translateUnit},${standalone_parseNumber(translateY) * translateTimes}${translateUnit})`,
      `scale(${flipX * standalone_parseNumber(scale)},${flipY * standalone_parseNumber(scale)})`,
      rotate && `rotate(${rotate}${rotateUnit})`,
    ],
    ' ',
  );
}

;// ../../node_modules/svelte-fa/src/fa.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/node_modules/svelte-fa/src/fa.svelte generated by Svelte v3.59.2 */




function standalone_add_css(target) {
	standalone_append_styles(target, "svelte-q6amlk", ".spin.svelte-q6amlk{-webkit-animation:svelte-q6amlk-spin 2s 0s infinite linear;animation:svelte-q6amlk-spin 2s 0s infinite linear}.pulse.svelte-q6amlk{-webkit-animation:svelte-q6amlk-spin 1s infinite steps(8);animation:svelte-q6amlk-spin 1s infinite steps(8)}@-webkit-keyframes svelte-q6amlk-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes svelte-q6amlk-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}");
}

// (93:0) {#if i[4]}
function standalone_create_if_block(ctx) {
	let svg;
	let g1;
	let g0;
	let g1_transform_value;
	let g1_transform_origin_value;
	let svg_class_value;
	let svg_viewBox_value;

	function select_block_type(ctx, dirty) {
		if (typeof /*i*/ ctx[7][4] == 'string') return standalone_create_if_block_1;
		return standalone_create_else_block;
	}

	let current_block_type = select_block_type(ctx, -1);
	let if_block = current_block_type(ctx);

	return {
		c() {
			svg = standalone_svg_element("svg");
			g1 = standalone_svg_element("g");
			g0 = standalone_svg_element("g");
			if_block.c();
			standalone_attr(g0, "transform", /*transform*/ ctx[10]);
			standalone_attr(g1, "transform", g1_transform_value = `translate(${/*i*/ ctx[7][0] / 2} ${/*i*/ ctx[7][1] / 2})`);
			standalone_attr(g1, "transform-origin", g1_transform_origin_value = `${/*i*/ ctx[7][0] / 4} 0`);
			standalone_attr(svg, "id", /*id*/ ctx[0]);
			standalone_attr(svg, "class", svg_class_value = "" + (standalone_null_to_empty(/*c*/ ctx[8]) + " svelte-q6amlk"));
			standalone_attr(svg, "style", /*s*/ ctx[9]);
			standalone_attr(svg, "viewBox", svg_viewBox_value = `0 0 ${/*i*/ ctx[7][0]} ${/*i*/ ctx[7][1]}`);
			standalone_attr(svg, "aria-hidden", "true");
			standalone_attr(svg, "role", "img");
			standalone_attr(svg, "xmlns", "http://www.w3.org/2000/svg");
		},
		m(target, anchor) {
			standalone_insert(target, svg, anchor);
			standalone_append(svg, g1);
			standalone_append(g1, g0);
			if_block.m(g0, null);
		},
		p(ctx, dirty) {
			if (current_block_type === (current_block_type = select_block_type(ctx, dirty)) && if_block) {
				if_block.p(ctx, dirty);
			} else {
				if_block.d(1);
				if_block = current_block_type(ctx);

				if (if_block) {
					if_block.c();
					if_block.m(g0, null);
				}
			}

			if (dirty & /*transform*/ 1024) {
				standalone_attr(g0, "transform", /*transform*/ ctx[10]);
			}

			if (dirty & /*i*/ 128 && g1_transform_value !== (g1_transform_value = `translate(${/*i*/ ctx[7][0] / 2} ${/*i*/ ctx[7][1] / 2})`)) {
				standalone_attr(g1, "transform", g1_transform_value);
			}

			if (dirty & /*i*/ 128 && g1_transform_origin_value !== (g1_transform_origin_value = `${/*i*/ ctx[7][0] / 4} 0`)) {
				standalone_attr(g1, "transform-origin", g1_transform_origin_value);
			}

			if (dirty & /*id*/ 1) {
				standalone_attr(svg, "id", /*id*/ ctx[0]);
			}

			if (dirty & /*c*/ 256 && svg_class_value !== (svg_class_value = "" + (standalone_null_to_empty(/*c*/ ctx[8]) + " svelte-q6amlk"))) {
				standalone_attr(svg, "class", svg_class_value);
			}

			if (dirty & /*s*/ 512) {
				standalone_attr(svg, "style", /*s*/ ctx[9]);
			}

			if (dirty & /*i*/ 128 && svg_viewBox_value !== (svg_viewBox_value = `0 0 ${/*i*/ ctx[7][0]} ${/*i*/ ctx[7][1]}`)) {
				standalone_attr(svg, "viewBox", svg_viewBox_value);
			}
		},
		d(detaching) {
			if (detaching) standalone_detach(svg);
			if_block.d();
		}
	};
}

// (114:8) {:else}
function standalone_create_else_block(ctx) {
	let path0;
	let path0_d_value;
	let path0_fill_value;
	let path0_fill_opacity_value;
	let path0_transform_value;
	let path1;
	let path1_d_value;
	let path1_fill_value;
	let path1_fill_opacity_value;
	let path1_transform_value;

	return {
		c() {
			path0 = standalone_svg_element("path");
			path1 = standalone_svg_element("path");
			standalone_attr(path0, "d", path0_d_value = /*i*/ ctx[7][4][0]);
			standalone_attr(path0, "fill", path0_fill_value = /*secondaryColor*/ ctx[3] || /*color*/ ctx[1] || 'currentColor');

			standalone_attr(path0, "fill-opacity", path0_fill_opacity_value = /*swapOpacity*/ ctx[6] != false
			? /*primaryOpacity*/ ctx[4]
			: /*secondaryOpacity*/ ctx[5]);

			standalone_attr(path0, "transform", path0_transform_value = `translate(${/*i*/ ctx[7][0] / -2} ${/*i*/ ctx[7][1] / -2})`);
			standalone_attr(path1, "d", path1_d_value = /*i*/ ctx[7][4][1]);
			standalone_attr(path1, "fill", path1_fill_value = /*primaryColor*/ ctx[2] || /*color*/ ctx[1] || 'currentColor');

			standalone_attr(path1, "fill-opacity", path1_fill_opacity_value = /*swapOpacity*/ ctx[6] != false
			? /*secondaryOpacity*/ ctx[5]
			: /*primaryOpacity*/ ctx[4]);

			standalone_attr(path1, "transform", path1_transform_value = `translate(${/*i*/ ctx[7][0] / -2} ${/*i*/ ctx[7][1] / -2})`);
		},
		m(target, anchor) {
			standalone_insert(target, path0, anchor);
			standalone_insert(target, path1, anchor);
		},
		p(ctx, dirty) {
			if (dirty & /*i*/ 128 && path0_d_value !== (path0_d_value = /*i*/ ctx[7][4][0])) {
				standalone_attr(path0, "d", path0_d_value);
			}

			if (dirty & /*secondaryColor, color*/ 10 && path0_fill_value !== (path0_fill_value = /*secondaryColor*/ ctx[3] || /*color*/ ctx[1] || 'currentColor')) {
				standalone_attr(path0, "fill", path0_fill_value);
			}

			if (dirty & /*swapOpacity, primaryOpacity, secondaryOpacity*/ 112 && path0_fill_opacity_value !== (path0_fill_opacity_value = /*swapOpacity*/ ctx[6] != false
			? /*primaryOpacity*/ ctx[4]
			: /*secondaryOpacity*/ ctx[5])) {
				standalone_attr(path0, "fill-opacity", path0_fill_opacity_value);
			}

			if (dirty & /*i*/ 128 && path0_transform_value !== (path0_transform_value = `translate(${/*i*/ ctx[7][0] / -2} ${/*i*/ ctx[7][1] / -2})`)) {
				standalone_attr(path0, "transform", path0_transform_value);
			}

			if (dirty & /*i*/ 128 && path1_d_value !== (path1_d_value = /*i*/ ctx[7][4][1])) {
				standalone_attr(path1, "d", path1_d_value);
			}

			if (dirty & /*primaryColor, color*/ 6 && path1_fill_value !== (path1_fill_value = /*primaryColor*/ ctx[2] || /*color*/ ctx[1] || 'currentColor')) {
				standalone_attr(path1, "fill", path1_fill_value);
			}

			if (dirty & /*swapOpacity, secondaryOpacity, primaryOpacity*/ 112 && path1_fill_opacity_value !== (path1_fill_opacity_value = /*swapOpacity*/ ctx[6] != false
			? /*secondaryOpacity*/ ctx[5]
			: /*primaryOpacity*/ ctx[4])) {
				standalone_attr(path1, "fill-opacity", path1_fill_opacity_value);
			}

			if (dirty & /*i*/ 128 && path1_transform_value !== (path1_transform_value = `translate(${/*i*/ ctx[7][0] / -2} ${/*i*/ ctx[7][1] / -2})`)) {
				standalone_attr(path1, "transform", path1_transform_value);
			}
		},
		d(detaching) {
			if (detaching) standalone_detach(path0);
			if (detaching) standalone_detach(path1);
		}
	};
}

// (108:8) {#if typeof i[4] == 'string'}
function standalone_create_if_block_1(ctx) {
	let path;
	let path_d_value;
	let path_fill_value;
	let path_transform_value;

	return {
		c() {
			path = standalone_svg_element("path");
			standalone_attr(path, "d", path_d_value = /*i*/ ctx[7][4]);
			standalone_attr(path, "fill", path_fill_value = /*color*/ ctx[1] || /*primaryColor*/ ctx[2] || 'currentColor');
			standalone_attr(path, "transform", path_transform_value = `translate(${/*i*/ ctx[7][0] / -2} ${/*i*/ ctx[7][1] / -2})`);
		},
		m(target, anchor) {
			standalone_insert(target, path, anchor);
		},
		p(ctx, dirty) {
			if (dirty & /*i*/ 128 && path_d_value !== (path_d_value = /*i*/ ctx[7][4])) {
				standalone_attr(path, "d", path_d_value);
			}

			if (dirty & /*color, primaryColor*/ 6 && path_fill_value !== (path_fill_value = /*color*/ ctx[1] || /*primaryColor*/ ctx[2] || 'currentColor')) {
				standalone_attr(path, "fill", path_fill_value);
			}

			if (dirty & /*i*/ 128 && path_transform_value !== (path_transform_value = `translate(${/*i*/ ctx[7][0] / -2} ${/*i*/ ctx[7][1] / -2})`)) {
				standalone_attr(path, "transform", path_transform_value);
			}
		},
		d(detaching) {
			if (detaching) standalone_detach(path);
		}
	};
}

function standalone_create_fragment(ctx) {
	let if_block_anchor;
	let if_block = /*i*/ ctx[7][4] && standalone_create_if_block(ctx);

	return {
		c() {
			if (if_block) if_block.c();
			if_block_anchor = standalone_empty();
		},
		m(target, anchor) {
			if (if_block) if_block.m(target, anchor);
			standalone_insert(target, if_block_anchor, anchor);
		},
		p(ctx, [dirty]) {
			if (/*i*/ ctx[7][4]) {
				if (if_block) {
					if_block.p(ctx, dirty);
				} else {
					if_block = standalone_create_if_block(ctx);
					if_block.c();
					if_block.m(if_block_anchor.parentNode, if_block_anchor);
				}
			} else if (if_block) {
				if_block.d(1);
				if_block = null;
			}
		},
		i: standalone_noop,
		o: standalone_noop,
		d(detaching) {
			if (if_block) if_block.d(detaching);
			if (detaching) standalone_detach(if_block_anchor);
		}
	};
}

function standalone_instance($$self, $$props, $$invalidate) {
	let { class: clazz = '' } = $$props;
	let { id = '' } = $$props;
	let { style = '' } = $$props;
	let { icon } = $$props;
	let { size = '' } = $$props;
	let { color = '' } = $$props;
	let { fw = false } = $$props;
	let { pull = '' } = $$props;
	let { scale = 1 } = $$props;
	let { translateX = 0 } = $$props;
	let { translateY = 0 } = $$props;
	let { rotate = '' } = $$props;
	let { flip = false } = $$props;
	let { spin = false } = $$props;
	let { pulse = false } = $$props;
	let { primaryColor = '' } = $$props;
	let { secondaryColor = '' } = $$props;
	let { primaryOpacity = 1 } = $$props;
	let { secondaryOpacity = 0.4 } = $$props;
	let { swapOpacity = false } = $$props;
	let i;
	let c;
	let s;
	let transform;

	$$self.$$set = $$props => {
		if ('class' in $$props) $$invalidate(11, clazz = $$props.class);
		if ('id' in $$props) $$invalidate(0, id = $$props.id);
		if ('style' in $$props) $$invalidate(12, style = $$props.style);
		if ('icon' in $$props) $$invalidate(13, icon = $$props.icon);
		if ('size' in $$props) $$invalidate(14, size = $$props.size);
		if ('color' in $$props) $$invalidate(1, color = $$props.color);
		if ('fw' in $$props) $$invalidate(15, fw = $$props.fw);
		if ('pull' in $$props) $$invalidate(16, pull = $$props.pull);
		if ('scale' in $$props) $$invalidate(17, scale = $$props.scale);
		if ('translateX' in $$props) $$invalidate(18, translateX = $$props.translateX);
		if ('translateY' in $$props) $$invalidate(19, translateY = $$props.translateY);
		if ('rotate' in $$props) $$invalidate(20, rotate = $$props.rotate);
		if ('flip' in $$props) $$invalidate(21, flip = $$props.flip);
		if ('spin' in $$props) $$invalidate(22, spin = $$props.spin);
		if ('pulse' in $$props) $$invalidate(23, pulse = $$props.pulse);
		if ('primaryColor' in $$props) $$invalidate(2, primaryColor = $$props.primaryColor);
		if ('secondaryColor' in $$props) $$invalidate(3, secondaryColor = $$props.secondaryColor);
		if ('primaryOpacity' in $$props) $$invalidate(4, primaryOpacity = $$props.primaryOpacity);
		if ('secondaryOpacity' in $$props) $$invalidate(5, secondaryOpacity = $$props.secondaryOpacity);
		if ('swapOpacity' in $$props) $$invalidate(6, swapOpacity = $$props.swapOpacity);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*icon*/ 8192) {
			$: $$invalidate(7, i = icon && icon.icon || [0, 0, '', [], '']);
		}

		if ($$self.$$.dirty & /*clazz, spin, pulse*/ 12584960) {
			$: $$invalidate(8, c = standalone_joinCss([clazz, 'svelte-fa', spin && 'spin', pulse && 'pulse'], ' '));
		}

		if ($$self.$$.dirty & /*style, size, pull, fw*/ 118784) {
			$: $$invalidate(9, s = standalone_getStyles(style, size, pull, fw));
		}

		if ($$self.$$.dirty & /*scale, translateX, translateY, rotate, flip*/ 4063232) {
			$: $$invalidate(10, transform = standalone_getTransform(scale, translateX, translateY, rotate, flip, 512));
		}
	};

	return [
		id,
		color,
		primaryColor,
		secondaryColor,
		primaryOpacity,
		secondaryOpacity,
		swapOpacity,
		i,
		c,
		s,
		transform,
		clazz,
		style,
		icon,
		size,
		fw,
		pull,
		scale,
		translateX,
		translateY,
		rotate,
		flip,
		spin,
		pulse
	];
}

class standalone_Fa extends standalone_SvelteComponent {
	constructor(options) {
		super();

		standalone_init(
			this,
			options,
			standalone_instance,
			standalone_create_fragment,
			standalone_safe_not_equal,
			{
				class: 11,
				id: 0,
				style: 12,
				icon: 13,
				size: 14,
				color: 1,
				fw: 15,
				pull: 16,
				scale: 17,
				translateX: 18,
				translateY: 19,
				rotate: 20,
				flip: 21,
				spin: 22,
				pulse: 23,
				primaryColor: 2,
				secondaryColor: 3,
				primaryOpacity: 4,
				secondaryOpacity: 5,
				swapOpacity: 6
			},
			standalone_add_css
		);
	}
}

/* harmony default export */ const standalone_fa_svelte = (standalone_Fa);
;// ../../node_modules/svelte/index.mjs


// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faEdit.js
var standalone_faEdit = __webpack_require__(174);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faCheck.js
var standalone_faCheck = __webpack_require__(888);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faTimes.js
var standalone_faTimes = __webpack_require__(882);
;// ../../canvas_viz/dist/elements/IconButton.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/canvas_viz/dist/elements/IconButton.svelte generated by Svelte v3.59.2 */


const standalone_get_text_slot_changes = dirty => ({});
const standalone_get_text_slot_context = ctx => ({});
const standalone_get_icon_slot_changes = dirty => ({});
const standalone_get_icon_slot_context = ctx => ({});

// (26:4) {#if $$slots.icon}
function standalone_IconButton_svelte_create_if_block(ctx) {
	let div;
	let div_class_value;
	let current;
	const icon_slot_template = /*#slots*/ ctx[3].icon;
	const icon_slot = standalone_create_slot(icon_slot_template, ctx, /*$$scope*/ ctx[2], standalone_get_icon_slot_context);

	return {
		c() {
			div = standalone_internal_element("div");
			if (icon_slot) icon_slot.c();
			standalone_attr(div, "class", div_class_value = /*$$slots*/ ctx[1].text ? "pr-2 flex" : "flex");
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);

			if (icon_slot) {
				icon_slot.m(div, null);
			}

			current = true;
		},
		p(ctx, dirty) {
			if (icon_slot) {
				if (icon_slot.p && (!current || dirty & /*$$scope*/ 4)) {
					standalone_update_slot_base(
						icon_slot,
						icon_slot_template,
						ctx,
						/*$$scope*/ ctx[2],
						!current
						? standalone_get_all_dirty_from_scope(/*$$scope*/ ctx[2])
						: standalone_get_slot_changes(icon_slot_template, /*$$scope*/ ctx[2], dirty, standalone_get_icon_slot_changes),
						standalone_get_icon_slot_context
					);
				}
			}

			if (!current || dirty & /*$$slots*/ 2 && div_class_value !== (div_class_value = /*$$slots*/ ctx[1].text ? "pr-2 flex" : "flex")) {
				standalone_attr(div, "class", div_class_value);
			}
		},
		i(local) {
			if (current) return;
			standalone_transition_in(icon_slot, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(icon_slot, local);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div);
			if (icon_slot) icon_slot.d(detaching);
		}
	};
}

function standalone_IconButton_svelte_create_fragment(ctx) {
	let button;
	let div;
	let t;
	let button_class_value;
	let current;
	let mounted;
	let dispose;
	let if_block = /*$$slots*/ ctx[1].icon && standalone_IconButton_svelte_create_if_block(ctx);
	const text_slot_template = /*#slots*/ ctx[3].text;
	const text_slot = standalone_create_slot(text_slot_template, ctx, /*$$scope*/ ctx[2], standalone_get_text_slot_context);

	return {
		c() {
			button = standalone_internal_element("button");
			div = standalone_internal_element("div");
			if (if_block) if_block.c();
			t = standalone_space();
			if (text_slot) text_slot.c();
			standalone_attr(div, "class", "flex items-center");

			standalone_attr(button, "class", button_class_value = "" + ((/*filled*/ ctx[0]
			? 'bg-button hover:bg-button_hover text-text-dark'
			: 'bg-white text-button border border-button hover:bg-button hover:text-white') + " rounded-md py-1 px-2 transition"));
		},
		m(target, anchor) {
			standalone_insert(target, button, anchor);
			standalone_append(button, div);
			if (if_block) if_block.m(div, null);
			standalone_append(div, t);

			if (text_slot) {
				text_slot.m(div, null);
			}

			current = true;

			if (!mounted) {
				dispose = [
					standalone_listen(button, "click", /*click_handler*/ ctx[4]),
					standalone_listen(button, "mouseleave", /*mouseleave_handler*/ ctx[5])
				];

				mounted = true;
			}
		},
		p(ctx, [dirty]) {
			if (/*$$slots*/ ctx[1].icon) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*$$slots*/ 2) {
						standalone_transition_in(if_block, 1);
					}
				} else {
					if_block = standalone_IconButton_svelte_create_if_block(ctx);
					if_block.c();
					standalone_transition_in(if_block, 1);
					if_block.m(div, t);
				}
			} else if (if_block) {
				standalone_group_outros();

				standalone_transition_out(if_block, 1, 1, () => {
					if_block = null;
				});

				standalone_check_outros();
			}

			if (text_slot) {
				if (text_slot.p && (!current || dirty & /*$$scope*/ 4)) {
					standalone_update_slot_base(
						text_slot,
						text_slot_template,
						ctx,
						/*$$scope*/ ctx[2],
						!current
						? standalone_get_all_dirty_from_scope(/*$$scope*/ ctx[2])
						: standalone_get_slot_changes(text_slot_template, /*$$scope*/ ctx[2], dirty, standalone_get_text_slot_changes),
						standalone_get_text_slot_context
					);
				}
			}

			if (!current || dirty & /*filled*/ 1 && button_class_value !== (button_class_value = "" + ((/*filled*/ ctx[0]
			? 'bg-button hover:bg-button_hover text-text-dark'
			: 'bg-white text-button border border-button hover:bg-button hover:text-white') + " rounded-md py-1 px-2 transition"))) {
				standalone_attr(button, "class", button_class_value);
			}
		},
		i(local) {
			if (current) return;
			standalone_transition_in(if_block);
			standalone_transition_in(text_slot, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(if_block);
			standalone_transition_out(text_slot, local);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(button);
			if (if_block) if_block.d();
			if (text_slot) text_slot.d(detaching);
			mounted = false;
			standalone_run_all(dispose);
		}
	};
}

function standalone_IconButton_svelte_instance($$self, $$props, $$invalidate) {
	let { $$slots: slots = {}, $$scope } = $$props;
	const $$slots = standalone_compute_slots(slots);
	let { filled = false } = $$props;

	function click_handler(event) {
		standalone_bubble.call(this, $$self, event);
	}

	function mouseleave_handler(event) {
		standalone_bubble.call(this, $$self, event);
	}

	$$self.$$set = $$props => {
		if ('filled' in $$props) $$invalidate(0, filled = $$props.filled);
		if ('$$scope' in $$props) $$invalidate(2, $$scope = $$props.$$scope);
	};

	return [filled, $$slots, $$scope, slots, click_handler, mouseleave_handler];
}

class standalone_IconButton extends standalone_SvelteComponent {
	constructor(options) {
		super();
		standalone_init(this, options, standalone_IconButton_svelte_instance, standalone_IconButton_svelte_create_fragment, standalone_safe_not_equal, { filled: 0 });
	}
}

/* harmony default export */ const standalone_IconButton_svelte = (standalone_IconButton);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faQuestionCircle.js
var standalone_faQuestionCircle = __webpack_require__(430);
;// ../../canvas_viz/dist/elements/Tooltip.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/canvas_viz/dist/elements/Tooltip.svelte generated by Svelte v3.59.2 */






function standalone_Tooltip_svelte_add_css(target) {
	standalone_append_styles(target, "svelte-49ae0e", "[data-tooltip].svelte-49ae0e{position:relative;z-index:2;display:block}[data-tooltip].svelte-49ae0e:before,[data-tooltip].svelte-49ae0e:after{visibility:hidden;opacity:0;pointer-events:none;transition:0.2s ease-out;transform:translate(-50%, 5px)}[data-tooltip].svelte-49ae0e:before{position:absolute;top:100%;left:50%;margin-bottom:5px;padding:7px;width:100%;min-width:300px;max-width:400px;border-radius:3px;background-color:#000;background-color:hsla(0, 0%, 20%, 0.9);color:#fff;content:attr(data-tooltip);text-align:center;font-size:14px;line-height:1.2;transition:0.2s ease-out}[data-tooltip].svelte-49ae0e:hover:before,[data-tooltip].svelte-49ae0e:hover:after{visibility:visible;opacity:1;transform:translate(-50%, 0)}[data-tooltip=\"false\"].svelte-49ae0e:hover:before,[data-tooltip=\"false\"].svelte-49ae0e:hover:after{visibility:hidden;opacity:0}");
}

function standalone_Tooltip_svelte_create_fragment(ctx) {
	let div;
	let fa;
	let current;
	fa = new standalone_fa_svelte({ props: { icon: standalone_faQuestionCircle/* faQuestionCircle */.wR } });

	return {
		c() {
			div = standalone_internal_element("div");
			standalone_create_component(fa.$$.fragment);
			standalone_attr(div, "class", "w-max svelte-49ae0e");
			standalone_attr(div, "data-tooltip", /*text*/ ctx[0]);
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);
			standalone_mount_component(fa, div, null);
			current = true;
		},
		p(ctx, [dirty]) {
			if (!current || dirty & /*text*/ 1) {
				standalone_attr(div, "data-tooltip", /*text*/ ctx[0]);
			}
		},
		i(local) {
			if (current) return;
			standalone_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div);
			standalone_destroy_component(fa);
		}
	};
}

function standalone_Tooltip_svelte_instance($$self, $$props, $$invalidate) {
	let { text } = $$props;

	$$self.$$set = $$props => {
		if ('text' in $$props) $$invalidate(0, text = $$props.text);
	};

	return [text];
}

class standalone_Tooltip extends standalone_SvelteComponent {
	constructor(options) {
		super();
		standalone_init(this, options, standalone_Tooltip_svelte_instance, standalone_Tooltip_svelte_create_fragment, standalone_safe_not_equal, { text: 0 }, standalone_Tooltip_svelte_add_css);
	}
}

/* harmony default export */ const standalone_Tooltip_svelte = (standalone_Tooltip);
;// ../../canvas_viz/dist/elements/Heading.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/canvas_viz/dist/elements/Heading.svelte generated by Svelte v3.59.2 */




function standalone_Heading_svelte_create_fragment(ctx) {
	let div1;
	let div0;
	let h2;
	let t0;
	let t1;
	let tooltip;
	let current;
	tooltip = new standalone_Tooltip_svelte({ props: { text: /*description*/ ctx[1] } });

	return {
		c() {
			div1 = standalone_internal_element("div");
			div0 = standalone_internal_element("div");
			h2 = standalone_internal_element("h2");
			t0 = standalone_internal_text(/*heading*/ ctx[0]);
			t1 = standalone_space();
			standalone_create_component(tooltip.$$.fragment);
			standalone_attr(h2, "class", "text-2xl font-bold leading-7 text-gray-900 pr-2");
			standalone_attr(div0, "class", "flex items-center");
			standalone_attr(div1, "class", "flex items-center justify-between pb-3 pr-4");
		},
		m(target, anchor) {
			standalone_insert(target, div1, anchor);
			standalone_append(div1, div0);
			standalone_append(div0, h2);
			standalone_append(h2, t0);
			standalone_append(div0, t1);
			standalone_mount_component(tooltip, div0, null);
			current = true;
		},
		p(ctx, [dirty]) {
			if (!current || dirty & /*heading*/ 1) standalone_set_data(t0, /*heading*/ ctx[0]);
			const tooltip_changes = {};
			if (dirty & /*description*/ 2) tooltip_changes.text = /*description*/ ctx[1];
			tooltip.$set(tooltip_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(tooltip.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(tooltip.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div1);
			standalone_destroy_component(tooltip);
		}
	};
}

let standalone_hover = false;
let standalone_offsetX = 0;

function standalone_Heading_svelte_instance($$self, $$props, $$invalidate) {
	let { heading } = $$props;
	let { description } = $$props;

	$$self.$$set = $$props => {
		if ('heading' in $$props) $$invalidate(0, heading = $$props.heading);
		if ('description' in $$props) $$invalidate(1, description = $$props.description);
	};

	return [heading, description];
}

class standalone_Heading extends standalone_SvelteComponent {
	constructor(options) {
		super();
		standalone_init(this, options, standalone_Heading_svelte_instance, standalone_Heading_svelte_create_fragment, standalone_safe_not_equal, { heading: 0, description: 1 });
	}
}

/* harmony default export */ const standalone_Heading_svelte = (standalone_Heading);
// EXTERNAL MODULE: ../../node_modules/html2canvas/dist/html2canvas.js
var standalone_html2canvas = __webpack_require__(317);
var standalone_html2canvas_default = /*#__PURE__*/__webpack_require__.n(standalone_html2canvas);
;// ../../canvas_viz/dist/helpers/export.js
/**
 * Copyright 2024 BetterWithData
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function standalone_exportView(container, name) {
    standalone_html2canvas_default()(container).then((canvas) => {
        const a = document.createElement("a");
        a.href = canvas
            .toDataURL("image/jpeg")
            .replace("image/jpeg", "image/octet-stream");
        a.download = `${name}.jpg`;
        a.click();
    });
}

// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faImage.js
var standalone_faImage = __webpack_require__(705);
;// ../../canvas_viz/dist/elements/ComponentHeader.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/canvas_viz/dist/elements/ComponentHeader.svelte generated by Svelte v3.59.2 */








function standalone_create_icon_slot(ctx) {
	let fa;
	let current;
	fa = new standalone_fa_svelte({ props: { icon: standalone_faImage/* faImage */.jb, slot: "icon" } });

	return {
		c() {
			standalone_create_component(fa.$$.fragment);
		},
		m(target, anchor) {
			standalone_mount_component(fa, target, anchor);
			current = true;
		},
		p: standalone_noop,
		i(local) {
			if (current) return;
			standalone_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			standalone_destroy_component(fa, detaching);
		}
	};
}

// (35:6) 
function standalone_create_text_slot(ctx) {
	let span;

	return {
		c() {
			span = standalone_internal_element("span");
			span.textContent = "Download";
			standalone_attr(span, "slot", "text");
		},
		m(target, anchor) {
			standalone_insert(target, span, anchor);
		},
		p: standalone_noop,
		d(detaching) {
			if (detaching) standalone_detach(span);
		}
	};
}

function standalone_ComponentHeader_svelte_create_fragment(ctx) {
	let div3;
	let div1;
	let heading;
	let t0;
	let div0;
	let t1;
	let div2;
	let iconbutton;
	let current;

	heading = new standalone_Heading_svelte({
			props: {
				heading: /*title*/ ctx[0],
				description: /*description*/ ctx[1]
			}
		});

	const default_slot_template = /*#slots*/ ctx[3].default;
	const default_slot = standalone_create_slot(default_slot_template, ctx, /*$$scope*/ ctx[5], null);

	iconbutton = new standalone_IconButton_svelte({
			props: {
				$$slots: {
					text: [standalone_create_text_slot],
					icon: [standalone_create_icon_slot]
				},
				$$scope: { ctx }
			}
		});

	iconbutton.$on("click", /*click_handler*/ ctx[4]);

	return {
		c() {
			div3 = standalone_internal_element("div");
			div1 = standalone_internal_element("div");
			standalone_create_component(heading.$$.fragment);
			t0 = standalone_space();
			div0 = standalone_internal_element("div");
			if (default_slot) default_slot.c();
			t1 = standalone_space();
			div2 = standalone_internal_element("div");
			standalone_create_component(iconbutton.$$.fragment);
			standalone_attr(div0, "class", "flex flex-wrap");
			standalone_attr(div1, "class", "flex flex-wrap");
			standalone_attr(div2, "class", "pb-3 pl-3");
			standalone_attr(div3, "class", "flex items-top justify-between");
		},
		m(target, anchor) {
			standalone_insert(target, div3, anchor);
			standalone_append(div3, div1);
			standalone_mount_component(heading, div1, null);
			standalone_append(div1, t0);
			standalone_append(div1, div0);

			if (default_slot) {
				default_slot.m(div0, null);
			}

			standalone_append(div3, t1);
			standalone_append(div3, div2);
			standalone_mount_component(iconbutton, div2, null);
			current = true;
		},
		p(ctx, [dirty]) {
			const heading_changes = {};
			if (dirty & /*title*/ 1) heading_changes.heading = /*title*/ ctx[0];
			if (dirty & /*description*/ 2) heading_changes.description = /*description*/ ctx[1];
			heading.$set(heading_changes);

			if (default_slot) {
				if (default_slot.p && (!current || dirty & /*$$scope*/ 32)) {
					standalone_update_slot_base(
						default_slot,
						default_slot_template,
						ctx,
						/*$$scope*/ ctx[5],
						!current
						? standalone_get_all_dirty_from_scope(/*$$scope*/ ctx[5])
						: standalone_get_slot_changes(default_slot_template, /*$$scope*/ ctx[5], dirty, null),
						null
					);
				}
			}

			const iconbutton_changes = {};

			if (dirty & /*$$scope*/ 32) {
				iconbutton_changes.$$scope = { dirty, ctx };
			}

			iconbutton.$set(iconbutton_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(heading.$$.fragment, local);
			standalone_transition_in(default_slot, local);
			standalone_transition_in(iconbutton.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(heading.$$.fragment, local);
			standalone_transition_out(default_slot, local);
			standalone_transition_out(iconbutton.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div3);
			standalone_destroy_component(heading);
			if (default_slot) default_slot.d(detaching);
			standalone_destroy_component(iconbutton);
		}
	};
}

function standalone_ComponentHeader_svelte_instance($$self, $$props, $$invalidate) {
	let { $$slots: slots = {}, $$scope } = $$props;
	let { title } = $$props;
	let { description } = $$props;
	let { container } = $$props;
	const click_handler = () => standalone_exportView(container, "Scatterplot");

	$$self.$$set = $$props => {
		if ('title' in $$props) $$invalidate(0, title = $$props.title);
		if ('description' in $$props) $$invalidate(1, description = $$props.description);
		if ('container' in $$props) $$invalidate(2, container = $$props.container);
		if ('$$scope' in $$props) $$invalidate(5, $$scope = $$props.$$scope);
	};

	return [title, description, container, slots, click_handler, $$scope];
}

class standalone_ComponentHeader extends standalone_SvelteComponent {
	constructor(options) {
		super();
		standalone_init(this, options, standalone_ComponentHeader_svelte_instance, standalone_ComponentHeader_svelte_create_fragment, standalone_safe_not_equal, { title: 0, description: 1, container: 2 });
	}
}

/* harmony default export */ const standalone_ComponentHeader_svelte = (standalone_ComponentHeader);
;// ../../canvas_viz/dist/helpers/dimensions.js
/**
 * Copyright 2024 BetterWithData
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function standalone_mapWidth(width) {
    switch (width) {
        case 'XS':
            return 'col-span-1';
        case 'S':
            return 'col-span-2';
        case 'M':
            return 'col-span-3';
        case 'L':
            return 'col-span-4';
        case 'XL':
            return 'col-span-5';
        case 'XXL':
            return 'col-span-6';
        default:
            return 'col-span-2';
    }
}
function standalone_mapHeight(height, grid = false) {
    switch (height) {
        case 'XS':
            return grid ? 'row-span-1' : 'max-h-XS';
        case 'S':
            return grid ? 'row-span-2' : 'max-h-S';
        case 'M':
            return grid ? 'row-span-3' : 'max-h-M';
        case 'L':
            return grid ? 'row-span-4' : 'max-h-L';
        case 'XL':
            return grid ? 'row-span-5' : 'max-h-XL';
        case 'XXL':
            return grid ? 'row-span-6' : 'max-h-XXL';
        default:
            return grid ? 'row-span-2' : 'max-h-S';
    }
}
function standalone_mapHeightFixed(height, grid = false) {
    switch (height) {
        case 'XS':
            return grid ? 'row-span-1' : 'h-XS';
        case 'S':
            return grid ? 'row-span-2' : 'h-S';
        case 'M':
            return grid ? 'row-span-3' : 'h-M';
        case 'L':
            return grid ? 'row-span-4' : 'h-L';
        case 'XL':
            return grid ? 'row-span-5' : 'h-XL';
        case 'XXL':
            return grid ? 'row-span-6' : 'h-XXL';
        default:
            return grid ? 'row-span-2' : 'h-S';
    }
}

;// ../../canvas_viz/dist/types.js
/**
 * Copyright 2024 BetterWithData
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var standalone_CanvasDataType;
(function (CanvasDataType) {
    CanvasDataType[CanvasDataType["TABULAR"] = 1] = "TABULAR";
    CanvasDataType[CanvasDataType["IMAGE"] = 2] = "IMAGE";
    CanvasDataType[CanvasDataType["AUDIO"] = 3] = "AUDIO";
})(standalone_CanvasDataType || (standalone_CanvasDataType = {}));
var standalone_ResolverType;
(function (ResolverType) {
    ResolverType[ResolverType["BINNED_STRING"] = 0] = "BINNED_STRING";
    ResolverType[ResolverType["NUMBER"] = 1] = "NUMBER";
})(standalone_ResolverType || (standalone_ResolverType = {}));

;// ../../canvas_viz/dist/helpers/table.js
/**
 * Copyright 2024 BetterWithData
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const standalone_UNIQUE_COLS_PCTG = 0.1;
function standalone_getColumnType(table, columnName) {
    const col = table.column(columnName);
    if (col === undefined) {
        return undefined;
    }
    const firstValue = col.get(0);
    if (firstValue.constructor.name === "SignedBigNum") {
        return "number";
    }
    if (typeof firstValue === "object") {
        const objectClass = firstValue.constructor.name;
        if (objectClass.includes("Array")) {
            return "array";
        }
    }
    return typeof firstValue;
}
function standalone_getBinnableStringColumns(table) {
    const colNames = table.columnNames();
    const binnnableStringColumns = [];
    for (const colName of colNames) {
        const columnType = standalone_getColumnType(table, colName);
        if (columnType === "string") {
            if (standalone_isStringColumnBinnable(colName, table)) {
                binnnableStringColumns.push(colName);
            }
        }
    }
    return binnnableStringColumns;
}
function standalone_isStringColumnBinnable(columnName, table) {
    /** If more than UNIQUE_COLS_PCTG percent of the column are unique strings, likely an ID, don't bin. */
    const unique = table.groupby(columnName).count().numRows();
    if (unique < standalone_UNIQUE_COLS_PCTG * table.numRows()) {
        return true;
    }
    return false;
}
const standalone_cartesian = (...a) => a.reduce((a, b) => a.flatMap((d) => b.map((e) => [d, e].reduce((acc, val) => acc.concat(val), []))));

// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faAlignJustify.js
var standalone_faAlignJustify = __webpack_require__(733);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faListOl.js
var standalone_faListOl = __webpack_require__(801);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faTable.js
var standalone_faTable = __webpack_require__(184);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faLayerGroup.js
var standalone_faLayerGroup = __webpack_require__(718);
;// ./src/summarySpecs.ts
/**
 * Copyright 2024 BetterWithData
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */






function standalone_extractColumnElements(table) {
    const summaryElements = [];
    summaryElements.push({
        name: '# of Instances',
        data: table.numRows(),
    });
    const colNames = table.columnNames();
    for (const colName of colNames) {
        const columnType = standalone_getColumnType(table, colName);
        if (columnType === 'number') {
            if (colName.startsWith('duplicates_')) {
                summaryElements.push(standalone_getTotalNonNegativeElements(colName, table));
            }
            else if (!colName.startsWith('projection_')) {
                summaryElements.push({
                    name: colName,
                    data: {
                        spec: standalone_getNumberColumnSpec(colName),
                        data: { values: 'arrow_table' },
                        resolver: {
                            type: standalone_ResolverType.NUMBER,
                            columnName: colName,
                        },
                    },
                });
            }
        }
        else if (columnType === 'string') {
            if (standalone_isStringColumnBinnable(colName, table)) {
                summaryElements.unshift({
                    name: colName,
                    data: {
                        spec: standalone_getBinnedStringColumnSpec(colName),
                        data: { values: 'arrow_table' },
                        resolver: {
                            type: standalone_ResolverType.BINNED_STRING,
                            columnName: colName,
                        },
                    },
                });
            }
        }
    }
    return summaryElements;
}
function standalone_getQueryTree(table) {
    return {
        name: 'init',
        next: [standalone_tableQueryElement, ...standalone_getQueryElementsFromTable(table)],
    };
}
function standalone_getNumberColumnSpec(columnName) {
    return {
        $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
        title: `${columnName} binned`,
        data: { values: 'values' },
        mark: { type: 'bar', tooltip: true },
        encoding: {
            x: {
                field: 'bin_0',
                title: 'value',
            },
            y: { field: 'count', type: 'quantitative', title: 'instances' },
        },
    };
}
function standalone_getBinnedStringColumnSpec(columnName) {
    return {
        $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
        title: `${columnName} distribution`,
        data: { name: 'values' },
        mark: { type: 'bar', tooltip: true, cursor: 'pointer' },
        encoding: {
            y: { field: columnName, type: 'nominal', sort: '-x' },
            x: {
                field: 'count',
                type: 'quantitative',
                title: 'instances',
            },
        },
    };
}
function standalone_getQueryElementsFromTable(table) {
    const elements = [];
    for (const columnName of table.columnNames()) {
        const type = standalone_getColumnType(table, columnName);
        switch (type) {
            case 'number':
                elements.push(standalone_getNumberQueryElement(table, columnName));
                break;
            case 'string':
                if (standalone_isStringColumnBinnable(columnName, table)) {
                    elements.push(standalone_getStringQueryElement(table, columnName));
                }
                break;
            case 'array':
                if (standalone_getBinnableStringColumns(table).length > 0) {
                    elements.push(standalone_getArrayQueryElement(table, columnName));
                }
                break;
            default:
                break;
        }
    }
    return elements;
}
const standalone_tableQueryElement = {
    name: 'table',
    icon: standalone_faTable/* faTable */.w9,
    next: [
        {
            name: 'numRows',
            next: (names, table) => {
                return { name: '# of Instances', data: table.numRows() };
            },
        },
    ],
};
function standalone_getNumberQueryElement(table, columnName) {
    return {
        name: columnName,
        icon: standalone_faListOl/* faListOl */.Ts,
        next: [
            {
                name: 'histogram',
                next: (names, table) => {
                    return {
                        name: columnName,
                        data: {
                            spec: standalone_getNumberColumnSpec(columnName),
                            data: { values: 'arrow_table' },
                            resolver: {
                                type: standalone_ResolverType.NUMBER,
                                columnName: columnName,
                            },
                        },
                    };
                },
            },
            {
                name: 'non-negative',
                next: standalone_getNonNegativeNumberQueryElements(table),
            },
        ],
    };
}
function standalone_getNonNegativeNumberQueryElements(table) {
    const elements = [];
    elements.push({
        name: 'total',
        next: (names, table) => standalone_getTotalNonNegativeElements(names[0], table),
    });
    for (const column of standalone_getBinnableStringColumns(table)) {
        elements.push({
            name: `by ${column}`,
            next: (names, table) => {
                return {
                    name: 'Nonempty List',
                    data: {
                        spec: {
                            $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
                            title: `${names[0]} per ${column}`,
                            description: `Bar chart visualizing the distribution of ${names[0]} per ${column}.`,
                            transform: [
                                {
                                    filter: `datum.${names[0]} >= 0`,
                                },
                            ],
                            data: { name: 'values' },
                            mark: { type: 'bar', tooltip: true },
                            encoding: {
                                y: { field: column, type: 'nominal', title: column },
                                x: {
                                    aggregate: 'count',
                                    type: 'quantitative',
                                    title: names[0],
                                },
                            },
                        },
                        data: {
                            values: 'arrow_table',
                        },
                    },
                };
            },
        });
    }
    return elements;
}
function standalone_getTotalNonNegativeElements(columnName, table) {
    const column = table.array(columnName);
    let nonNegativeElements = 0;
    column.forEach((element) => {
        if (element >= 0) {
            nonNegativeElements++;
        }
    });
    return {
        name: columnName,
        data: nonNegativeElements,
    };
}
function standalone_getStringQueryElement(table, columnName) {
    return {
        name: columnName,
        icon: standalone_faAlignJustify/* faAlignJustify */.Ti,
        next: [
            {
                name: 'histogram',
                next: (names, table) => {
                    return {
                        name: columnName,
                        data: {
                            spec: standalone_getBinnedStringColumnSpec(columnName),
                            data: { values: 'arrow_table' },
                            resolver: {
                                type: standalone_ResolverType.BINNED_STRING,
                                columnName: columnName,
                            },
                        },
                    };
                },
            },
        ],
    };
}
function standalone_getArrayQueryElement(table, columnName) {
    return {
        name: columnName,
        icon: standalone_faLayerGroup/* faLayerGroup */.qI,
        next: [
            {
                name: 'not empty',
                next: standalone_getArrayBinQueryElements(table),
            },
        ],
    };
}
function standalone_getArrayBinQueryElements(table) {
    const elements = [];
    for (const column of standalone_getBinnableStringColumns(table)) {
        elements.push({
            name: `bin by ${column}`,
            next: (names, table) => {
                return {
                    name: 'Nonempty List',
                    data: {
                        spec: {
                            $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
                            title: `${names[0]} per ${column}`,
                            description: `Bar chart visualizing the distribution of ${names[0]} per ${column}.`,
                            transform: [
                                {
                                    filter: `length(datum.${names[0]}) > 0`,
                                },
                            ],
                            data: { name: 'values' },
                            mark: { type: 'bar', tooltip: true },
                            encoding: {
                                y: { field: column, type: 'nominal', title: column },
                                x: {
                                    aggregate: 'count',
                                    type: 'quantitative',
                                    title: names[0],
                                },
                            },
                        },
                        data: {
                            values: 'arrow_table',
                        },
                    },
                };
            },
        });
    }
    return elements;
}

;// ../../canvas_viz/dist/elements/TextField.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/canvas_viz/dist/elements/TextField.svelte generated by Svelte v3.59.2 */


function standalone_TextField_svelte_create_fragment(ctx) {
	let input;
	let mounted;
	let dispose;

	return {
		c() {
			input = standalone_internal_element("input");
			standalone_attr(input, "class", "border border-midgrey rounded w-full");
			standalone_attr(input, "type", "text");
			standalone_attr(input, "placeholder", /*placeholder*/ ctx[1]);
		},
		m(target, anchor) {
			standalone_insert(target, input, anchor);
			standalone_set_input_value(input, /*value*/ ctx[0]);

			if (!mounted) {
				dispose = standalone_listen(input, "input", /*input_input_handler*/ ctx[2]);
				mounted = true;
			}
		},
		p(ctx, [dirty]) {
			if (dirty & /*placeholder*/ 2) {
				standalone_attr(input, "placeholder", /*placeholder*/ ctx[1]);
			}

			if (dirty & /*value*/ 1 && input.value !== /*value*/ ctx[0]) {
				standalone_set_input_value(input, /*value*/ ctx[0]);
			}
		},
		i: standalone_noop,
		o: standalone_noop,
		d(detaching) {
			if (detaching) standalone_detach(input);
			mounted = false;
			dispose();
		}
	};
}

function standalone_TextField_svelte_instance($$self, $$props, $$invalidate) {
	let { value } = $$props;
	let { placeholder = "" } = $$props;

	function input_input_handler() {
		value = this.value;
		$$invalidate(0, value);
	}

	$$self.$$set = $$props => {
		if ('value' in $$props) $$invalidate(0, value = $$props.value);
		if ('placeholder' in $$props) $$invalidate(1, placeholder = $$props.placeholder);
	};

	return [value, placeholder, input_input_handler];
}

class standalone_TextField extends standalone_SvelteComponent {
	constructor(options) {
		super();
		standalone_init(this, options, standalone_TextField_svelte_instance, standalone_TextField_svelte_create_fragment, standalone_safe_not_equal, { value: 0, placeholder: 1 });
	}
}

/* harmony default export */ const standalone_TextField_svelte = (standalone_TextField);
;// ../../node_modules/json-stringify-pretty-compact/index.js
// Note: This regex matches even invalid JSON strings, but since we’re
// working on the output of `JSON.stringify` we know that only valid strings
// are present (unless the user supplied a weird `options.indent` but in
// that case we don’t care since the output would be invalid anyway).
const standalone_stringOrChar = /("(?:[^\\"]|\\.)*")|[:,]/g;

function standalone_stringify(passedObj, options = {}) {
  const indent = JSON.stringify(
    [1],
    undefined,
    options.indent === undefined ? 2 : options.indent
  ).slice(2, -3);

  const maxLength =
    indent === ""
      ? Infinity
      : options.maxLength === undefined
      ? 80
      : options.maxLength;

  let { replacer } = options;

  return (function _stringify(obj, currentIndent, reserved) {
    if (obj && typeof obj.toJSON === "function") {
      obj = obj.toJSON();
    }

    const string = JSON.stringify(obj, replacer);

    if (string === undefined) {
      return string;
    }

    const length = maxLength - currentIndent.length - reserved;

    if (string.length <= length) {
      const prettified = string.replace(
        standalone_stringOrChar,
        (match, stringLiteral) => {
          return stringLiteral || `${match} `;
        }
      );
      if (prettified.length <= length) {
        return prettified;
      }
    }

    if (replacer != null) {
      obj = JSON.parse(string);
      replacer = undefined;
    }

    if (typeof obj === "object" && obj !== null) {
      const nextIndent = currentIndent + indent;
      const items = [];
      let index = 0;
      let start;
      let end;

      if (Array.isArray(obj)) {
        start = "[";
        end = "]";
        const { length } = obj;
        for (; index < length; index++) {
          items.push(
            _stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) ||
              "null"
          );
        }
      } else {
        start = "{";
        end = "}";
        const keys = Object.keys(obj);
        const { length } = keys;
        for (; index < length; index++) {
          const key = keys[index];
          const keyPart = `${JSON.stringify(key)}: `;
          const value = _stringify(
            obj[key],
            nextIndent,
            keyPart.length + (index === length - 1 ? 0 : 1)
          );
          if (value !== undefined) {
            items.push(keyPart + value);
          }
        }
      }

      if (items.length > 0) {
        return [start, indent + items.join(`,\n${nextIndent}`), end].join(
          `\n${currentIndent}`
        );
      }
    }

    return string;
  })(passedObj, "", 0);
}

;// ../../node_modules/vega-util/build/vega-util.module.js
function standalone_accessor (fn, fields, name) {
  fn.fields = fields || [];
  fn.fname = name;
  return fn;
}
function standalone_accessorName(fn) {
  return fn == null ? null : fn.fname;
}
function standalone_accessorFields(fn) {
  return fn == null ? null : fn.fields;
}

function standalone_getter (path) {
  return path.length === 1 ? standalone_get1(path[0]) : standalone_getN(path);
}
const standalone_get1 = field => function (obj) {
  return obj[field];
};
const standalone_getN = path => {
  const len = path.length;
  return function (obj) {
    for (let i = 0; i < len; ++i) {
      obj = obj[path[i]];
    }
    return obj;
  };
};

function standalone_vega_util_module_error (message) {
  throw Error(message);
}

function standalone_splitAccessPath (p) {
  const path = [],
    n = p.length;
  let q = null,
    b = 0,
    s = '',
    i,
    j,
    c;
  p = p + '';
  function push() {
    path.push(s + p.substring(i, j));
    s = '';
    i = j + 1;
  }
  for (i = j = 0; j < n; ++j) {
    c = p[j];
    if (c === '\\') {
      s += p.substring(i, j++);
      i = j;
    } else if (c === q) {
      push();
      q = null;
      b = -1;
    } else if (q) {
      continue;
    } else if (i === b && c === '"') {
      i = j + 1;
      q = c;
    } else if (i === b && c === "'") {
      i = j + 1;
      q = c;
    } else if (c === '.' && !b) {
      if (j > i) {
        push();
      } else {
        i = j + 1;
      }
    } else if (c === '[') {
      if (j > i) push();
      b = i = j + 1;
    } else if (c === ']') {
      if (!b) standalone_vega_util_module_error('Access path missing open bracket: ' + p);
      if (b > 0) push();
      b = 0;
      i = j + 1;
    }
  }
  if (b) standalone_vega_util_module_error('Access path missing closing bracket: ' + p);
  if (q) standalone_vega_util_module_error('Access path missing closing quote: ' + p);
  if (j > i) {
    j++;
    push();
  }
  return path;
}

function standalone_field (field, name, opt) {
  const path = standalone_splitAccessPath(field);
  field = path.length === 1 ? path[0] : field;
  return standalone_accessor((opt && opt.get || standalone_getter)(path), [field], name || field);
}

const standalone_id = standalone_field('id');
const standalone_vega_util_module_identity = standalone_accessor(_ => _, [], 'identity');
const standalone_zero = standalone_accessor(() => 0, [], 'zero');
const standalone_one = standalone_accessor(() => 1, [], 'one');
const standalone_truthy = standalone_accessor(() => true, [], 'true');
const standalone_falsy = standalone_accessor(() => false, [], 'false');

function standalone_log$1(method, level, input) {
  const args = [level].concat([].slice.call(input));
  console[method].apply(console, args); // eslint-disable-line no-console
}

const standalone_None = 0;
const standalone_Error$1 = 1;
const standalone_vega_util_module_Warn = 2;
const standalone_vega_util_module_Info = 3;
const standalone_vega_util_module_Debug = 4;
function standalone_logger (_, method) {
  let handler = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : standalone_log$1;
  let level = _ || standalone_None;
  return {
    level(_) {
      if (arguments.length) {
        level = +_;
        return this;
      } else {
        return level;
      }
    },
    error() {
      if (level >= standalone_Error$1) handler(method || 'error', 'ERROR', arguments);
      return this;
    },
    warn() {
      if (level >= standalone_vega_util_module_Warn) handler(method || 'warn', 'WARN', arguments);
      return this;
    },
    info() {
      if (level >= standalone_vega_util_module_Info) handler(method || 'log', 'INFO', arguments);
      return this;
    },
    debug() {
      if (level >= standalone_vega_util_module_Debug) handler(method || 'log', 'DEBUG', arguments);
      return this;
    }
  };
}

var standalone_vega_util_module_isArray = Array.isArray;

function standalone_vega_util_module_isObject (_) {
  return _ === Object(_);
}

const standalone_isLegalKey = key => key !== '__proto__';
function standalone_mergeConfig() {
  for (var _len = arguments.length, configs = new Array(_len), _key = 0; _key < _len; _key++) {
    configs[_key] = arguments[_key];
  }
  return configs.reduce((out, source) => {
    for (const key in source) {
      if (key === 'signals') {
        // for signals, we merge the signals arrays
        // source signals take precedence over
        // existing signals with the same name
        out.signals = standalone_mergeNamed(out.signals, source.signals);
      } else {
        // otherwise, merge objects subject to recursion constraints
        // for legend block, recurse for the layout entry only
        // for style block, recurse for all properties
        // otherwise, no recursion: objects overwrite, no merging
        const r = key === 'legend' ? {
          layout: 1
        } : key === 'style' ? true : null;
        standalone_writeConfig(out, key, source[key], r);
      }
    }
    return out;
  }, {});
}
function standalone_writeConfig(output, key, value, recurse) {
  if (!standalone_isLegalKey(key)) return;
  let k, o;
  if (standalone_vega_util_module_isObject(value) && !standalone_vega_util_module_isArray(value)) {
    o = standalone_vega_util_module_isObject(output[key]) ? output[key] : output[key] = {};
    for (k in value) {
      if (recurse && (recurse === true || recurse[k])) {
        standalone_writeConfig(o, k, value[k]);
      } else if (standalone_isLegalKey(k)) {
        o[k] = value[k];
      }
    }
  } else {
    output[key] = value;
  }
}
function standalone_mergeNamed(a, b) {
  if (a == null) return b;
  const map = {},
    out = [];
  function add(_) {
    if (!map[_.name]) {
      map[_.name] = 1;
      out.push(_);
    }
  }
  b.forEach(add);
  a.forEach(add);
  return out;
}

function standalone_peek (array) {
  return array[array.length - 1];
}

function standalone_toNumber (_) {
  return _ == null || _ === '' ? null : +_;
}

const standalone_exp = sign => x => sign * Math.exp(x);
const standalone_log = sign => x => Math.log(sign * x);
const standalone_symlog = c => x => Math.sign(x) * Math.log1p(Math.abs(x / c));
const standalone_symexp = c => x => Math.sign(x) * Math.expm1(Math.abs(x)) * c;
const standalone_pow = exponent => x => x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
function standalone_pan(domain, delta, lift, ground) {
  const d0 = lift(domain[0]),
    d1 = lift(standalone_peek(domain)),
    dd = (d1 - d0) * delta;
  return [ground(d0 - dd), ground(d1 - dd)];
}
function standalone_panLinear(domain, delta) {
  return standalone_pan(domain, delta, standalone_toNumber, standalone_vega_util_module_identity);
}
function standalone_panLog(domain, delta) {
  var sign = Math.sign(domain[0]);
  return standalone_pan(domain, delta, standalone_log(sign), standalone_exp(sign));
}
function standalone_panPow(domain, delta, exponent) {
  return standalone_pan(domain, delta, standalone_pow(exponent), standalone_pow(1 / exponent));
}
function standalone_panSymlog(domain, delta, constant) {
  return standalone_pan(domain, delta, standalone_symlog(constant), standalone_symexp(constant));
}
function standalone_zoom(domain, anchor, scale, lift, ground) {
  const d0 = lift(domain[0]),
    d1 = lift(standalone_peek(domain)),
    da = anchor != null ? lift(anchor) : (d0 + d1) / 2;
  return [ground(da + (d0 - da) * scale), ground(da + (d1 - da) * scale)];
}
function standalone_zoomLinear(domain, anchor, scale) {
  return standalone_zoom(domain, anchor, scale, standalone_toNumber, standalone_vega_util_module_identity);
}
function standalone_zoomLog(domain, anchor, scale) {
  const sign = Math.sign(domain[0]);
  return standalone_zoom(domain, anchor, scale, standalone_log(sign), standalone_exp(sign));
}
function standalone_zoomPow(domain, anchor, scale, exponent) {
  return standalone_zoom(domain, anchor, scale, standalone_pow(exponent), standalone_pow(1 / exponent));
}
function standalone_zoomSymlog(domain, anchor, scale, constant) {
  return standalone_zoom(domain, anchor, scale, standalone_symlog(constant), standalone_symexp(constant));
}

function standalone_quarter(date) {
  return 1 + ~~(new Date(date).getMonth() / 3);
}
function standalone_utcquarter(date) {
  return 1 + ~~(new Date(date).getUTCMonth() / 3);
}

function standalone_array (_) {
  return _ != null ? standalone_vega_util_module_isArray(_) ? _ : [_] : [];
}

/**
 * Span-preserving range clamp. If the span of the input range is less
 * than (max - min) and an endpoint exceeds either the min or max value,
 * the range is translated such that the span is preserved and one
 * endpoint touches the boundary of the min/max range.
 * If the span exceeds (max - min), the range [min, max] is returned.
 */
function standalone_clampRange (range, min, max) {
  let lo = range[0],
    hi = range[1],
    span;
  if (hi < lo) {
    span = hi;
    hi = lo;
    lo = span;
  }
  span = hi - lo;
  return span >= max - min ? [min, max] : [lo = Math.min(Math.max(lo, min), max - span), lo + span];
}

function standalone_vega_util_module_isFunction (_) {
  return typeof _ === 'function';
}

const standalone_DESCENDING = 'descending';
function standalone_compare (fields, orders, opt) {
  opt = opt || {};
  orders = standalone_array(orders) || [];
  const ord = [],
    get = [],
    fmap = {},
    gen = opt.comparator || standalone_comparator;
  standalone_array(fields).forEach((f, i) => {
    if (f == null) return;
    ord.push(orders[i] === standalone_DESCENDING ? -1 : 1);
    get.push(f = standalone_vega_util_module_isFunction(f) ? f : standalone_field(f, null, opt));
    (standalone_accessorFields(f) || []).forEach(_ => fmap[_] = 1);
  });
  return get.length === 0 ? null : standalone_accessor(gen(get, ord), Object.keys(fmap));
}
const standalone_ascending = (u, v) => (u < v || u == null) && v != null ? -1 : (u > v || v == null) && u != null ? 1 : (v = v instanceof Date ? +v : v, u = u instanceof Date ? +u : u) !== u && v === v ? -1 : v !== v && u === u ? 1 : 0;
const standalone_comparator = (fields, orders) => fields.length === 1 ? standalone_compare1(fields[0], orders[0]) : standalone_compareN(fields, orders, fields.length);
const standalone_compare1 = (field, order) => function (a, b) {
  return standalone_ascending(field(a), field(b)) * order;
};
const standalone_compareN = (fields, orders, n) => {
  orders.push(0); // pad zero for convenient lookup
  return function (a, b) {
    let f,
      c = 0,
      i = -1;
    while (c === 0 && ++i < n) {
      f = fields[i];
      c = standalone_ascending(f(a), f(b));
    }
    return c * orders[i];
  };
};

function standalone_vega_util_module_constant (_) {
  return standalone_vega_util_module_isFunction(_) ? _ : () => _;
}

function standalone_debounce (delay, handler) {
  let tid;
  return e => {
    if (tid) clearTimeout(tid);
    tid = setTimeout(() => (handler(e), tid = null), delay);
  };
}

function standalone_extend (_) {
  for (let x, k, i = 1, len = arguments.length; i < len; ++i) {
    x = arguments[i];
    for (k in x) {
      _[k] = x[k];
    }
  }
  return _;
}

/**
 * Return an array with minimum and maximum values, in the
 * form [min, max]. Ignores null, undefined, and NaN values.
 */
function standalone_extent (array, f) {
  let i = 0,
    n,
    v,
    min,
    max;
  if (array && (n = array.length)) {
    if (f == null) {
      // find first valid value
      for (v = array[i]; i < n && (v == null || v !== v); v = array[++i]);
      min = max = v;

      // visit all other values
      for (; i < n; ++i) {
        v = array[i];
        // skip null/undefined; NaN will fail all comparisons
        if (v != null) {
          if (v < min) min = v;
          if (v > max) max = v;
        }
      }
    } else {
      // find first valid value
      for (v = f(array[i]); i < n && (v == null || v !== v); v = f(array[++i]));
      min = max = v;

      // visit all other values
      for (; i < n; ++i) {
        v = f(array[i]);
        // skip null/undefined; NaN will fail all comparisons
        if (v != null) {
          if (v < min) min = v;
          if (v > max) max = v;
        }
      }
    }
  }
  return [min, max];
}

function standalone_extentIndex (array, f) {
  const n = array.length;
  let i = -1,
    a,
    b,
    c,
    u,
    v;
  if (f == null) {
    while (++i < n) {
      b = array[i];
      if (b != null && b >= b) {
        a = c = b;
        break;
      }
    }
    if (i === n) return [-1, -1];
    u = v = i;
    while (++i < n) {
      b = array[i];
      if (b != null) {
        if (a > b) {
          a = b;
          u = i;
        }
        if (c < b) {
          c = b;
          v = i;
        }
      }
    }
  } else {
    while (++i < n) {
      b = f(array[i], i, array);
      if (b != null && b >= b) {
        a = c = b;
        break;
      }
    }
    if (i === n) return [-1, -1];
    u = v = i;
    while (++i < n) {
      b = f(array[i], i, array);
      if (b != null) {
        if (a > b) {
          a = b;
          u = i;
        }
        if (c < b) {
          c = b;
          v = i;
        }
      }
    }
  }
  return [u, v];
}

const standalone_hop = Object.prototype.hasOwnProperty;
function standalone_vega_util_module_has (object, property) {
  return standalone_hop.call(object, property);
}

const standalone_NULL = {};
function standalone_fastmap (input) {
  let obj = {},
    test;
  function has$1(key) {
    return standalone_vega_util_module_has(obj, key) && obj[key] !== standalone_NULL;
  }
  const map = {
    size: 0,
    empty: 0,
    object: obj,
    has: has$1,
    get(key) {
      return has$1(key) ? obj[key] : undefined;
    },
    set(key, value) {
      if (!has$1(key)) {
        ++map.size;
        if (obj[key] === standalone_NULL) --map.empty;
      }
      obj[key] = value;
      return this;
    },
    delete(key) {
      if (has$1(key)) {
        --map.size;
        ++map.empty;
        obj[key] = standalone_NULL;
      }
      return this;
    },
    clear() {
      map.size = map.empty = 0;
      map.object = obj = {};
    },
    test(_) {
      if (arguments.length) {
        test = _;
        return map;
      } else {
        return test;
      }
    },
    clean() {
      const next = {};
      let size = 0;
      for (const key in obj) {
        const value = obj[key];
        if (value !== standalone_NULL && (!test || !test(value))) {
          next[key] = value;
          ++size;
        }
      }
      map.size = size;
      map.empty = 0;
      map.object = obj = next;
    }
  };
  if (input) Object.keys(input).forEach(key => {
    map.set(key, input[key]);
  });
  return map;
}

function standalone_vega_util_module_flush (range, value, threshold, left, right, center) {
  if (!threshold && threshold !== 0) return center;
  const t = +threshold;
  let a = range[0],
    b = standalone_peek(range),
    l;

  // swap endpoints if range is reversed
  if (b < a) {
    l = a;
    a = b;
    b = l;
  }

  // compare value to endpoints
  l = Math.abs(value - a);
  const r = Math.abs(b - value);

  // adjust if value is within threshold distance of endpoint
  return l < r && l <= t ? left : r <= t ? right : center;
}

function standalone_inherits (child, parent, members) {
  const proto = child.prototype = Object.create(parent.prototype);
  Object.defineProperty(proto, 'constructor', {
    value: child,
    writable: true,
    enumerable: true,
    configurable: true
  });
  return standalone_extend(proto, members);
}

/**
 * Predicate that returns true if the value lies within the span
 * of the given range. The left and right flags control the use
 * of inclusive (true) or exclusive (false) comparisons.
 */
function standalone_inrange (value, range, left, right) {
  let r0 = range[0],
    r1 = range[range.length - 1],
    t;
  if (r0 > r1) {
    t = r0;
    r0 = r1;
    r1 = t;
  }
  left = left === undefined || left;
  right = right === undefined || right;
  return (left ? r0 <= value : r0 < value) && (right ? value <= r1 : value < r1);
}

function standalone_isBoolean (_) {
  return typeof _ === 'boolean';
}

function standalone_isDate (_) {
  return Object.prototype.toString.call(_) === '[object Date]';
}

function standalone_isIterable (_) {
  return _ && standalone_vega_util_module_isFunction(_[Symbol.iterator]);
}

function standalone_isNumber (_) {
  return typeof _ === 'number';
}

function standalone_isRegExp (_) {
  return Object.prototype.toString.call(_) === '[object RegExp]';
}

function standalone_vega_util_module_isString (_) {
  return typeof _ === 'string';
}

function standalone_key (fields, flat, opt) {
  if (fields) {
    fields = flat ? standalone_array(fields).map(f => f.replace(/\\(.)/g, '$1')) : standalone_array(fields);
  }
  const len = fields && fields.length,
    gen = opt && opt.get || standalone_getter,
    map = f => gen(flat ? [f] : standalone_splitAccessPath(f));
  let fn;
  if (!len) {
    fn = function () {
      return '';
    };
  } else if (len === 1) {
    const get = map(fields[0]);
    fn = function (_) {
      return '' + get(_);
    };
  } else {
    const get = fields.map(map);
    fn = function (_) {
      let s = '' + get[0](_),
        i = 0;
      while (++i < len) s += '|' + get[i](_);
      return s;
    };
  }
  return standalone_accessor(fn, fields, 'key');
}

function standalone_lerp (array, frac) {
  const lo = array[0],
    hi = standalone_peek(array),
    f = +frac;
  return !f ? lo : f === 1 ? hi : lo + f * (hi - lo);
}

const standalone_DEFAULT_MAX_SIZE = 10000;

// adapted from https://github.com/dominictarr/hashlru/ (MIT License)
function standalone_lruCache (maxsize) {
  maxsize = +maxsize || standalone_DEFAULT_MAX_SIZE;
  let curr, prev, size;
  const clear = () => {
    curr = {};
    prev = {};
    size = 0;
  };
  const update = (key, value) => {
    if (++size > maxsize) {
      prev = curr;
      curr = {};
      size = 1;
    }
    return curr[key] = value;
  };
  clear();
  return {
    clear,
    has: key => standalone_vega_util_module_has(curr, key) || standalone_vega_util_module_has(prev, key),
    get: key => standalone_vega_util_module_has(curr, key) ? curr[key] : standalone_vega_util_module_has(prev, key) ? update(key, prev[key]) : undefined,
    set: (key, value) => standalone_vega_util_module_has(curr, key) ? curr[key] = value : update(key, value)
  };
}

function standalone_merge (compare, array0, array1, output) {
  const n0 = array0.length,
    n1 = array1.length;
  if (!n1) return array0;
  if (!n0) return array1;
  const merged = output || new array0.constructor(n0 + n1);
  let i0 = 0,
    i1 = 0,
    i = 0;
  for (; i0 < n0 && i1 < n1; ++i) {
    merged[i] = compare(array0[i0], array1[i1]) > 0 ? array1[i1++] : array0[i0++];
  }
  for (; i0 < n0; ++i0, ++i) {
    merged[i] = array0[i0];
  }
  for (; i1 < n1; ++i1, ++i) {
    merged[i] = array1[i1];
  }
  return merged;
}

function standalone_vega_util_module_repeat (str, reps) {
  let s = '';
  while (--reps >= 0) s += str;
  return s;
}

function standalone_pad (str, length, padchar, align) {
  const c = padchar || ' ',
    s = str + '',
    n = length - s.length;
  return n <= 0 ? s : align === 'left' ? standalone_vega_util_module_repeat(c, n) + s : align === 'center' ? standalone_vega_util_module_repeat(c, ~~(n / 2)) + s + standalone_vega_util_module_repeat(c, Math.ceil(n / 2)) : s + standalone_vega_util_module_repeat(c, n);
}

/**
 * Return the numerical span of an array: the difference between
 * the last and first values.
 */
function standalone_span (array) {
  return array && standalone_peek(array) - array[0] || 0;
}

function standalone_$(x) {
  return standalone_vega_util_module_isArray(x) ? '[' + x.map(standalone_$) + ']' : standalone_vega_util_module_isObject(x) || standalone_vega_util_module_isString(x) ?
  // Output valid JSON and JS source strings.
  // See http://timelessrepo.com/json-isnt-a-javascript-subset
  JSON.stringify(x).replace('\u2028', '\\u2028').replace('\u2029', '\\u2029') : x;
}

function standalone_toBoolean (_) {
  return _ == null || _ === '' ? null : !_ || _ === 'false' || _ === '0' ? false : !!_;
}

const standalone_defaultParser = _ => standalone_isNumber(_) ? _ : standalone_isDate(_) ? _ : Date.parse(_);
function standalone_toDate (_, parser) {
  parser = parser || standalone_defaultParser;
  return _ == null || _ === '' ? null : parser(_);
}

function standalone_vega_util_module_toString (_) {
  return _ == null || _ === '' ? null : _ + '';
}

function standalone_toSet (_) {
  const s = {},
    n = _.length;
  for (let i = 0; i < n; ++i) s[_[i]] = true;
  return s;
}

function standalone_truncate (str, length, align, ellipsis) {
  const e = ellipsis != null ? ellipsis : '\u2026',
    s = str + '',
    n = s.length,
    l = Math.max(0, length - e.length);
  return n <= length ? s : align === 'left' ? e + s.slice(n - l) : align === 'center' ? s.slice(0, Math.ceil(l / 2)) + e + s.slice(n - ~~(l / 2)) : s.slice(0, l) + e;
}

function standalone_visitArray (array, filter, visitor) {
  if (array) {
    if (filter) {
      const n = array.length;
      for (let i = 0; i < n; ++i) {
        const t = filter(array[i]);
        if (t) visitor(t, i, array);
      }
    } else {
      array.forEach(visitor);
    }
  }
}



;// ../../node_modules/d3-dsv/src/dsv.js
var standalone_dsv_EOL = {},
    standalone_dsv_EOF = {},
    standalone_dsv_QUOTE = 34,
    standalone_dsv_NEWLINE = 10,
    standalone_dsv_RETURN = 13;

function standalone_objectConverter(columns) {
  return new Function("d", "return {" + columns.map(function(name, i) {
    return JSON.stringify(name) + ": d[" + i + "] || \"\"";
  }).join(",") + "}");
}

function standalone_customConverter(columns, f) {
  var object = standalone_objectConverter(columns);
  return function(row, i) {
    return f(object(row), i, columns);
  };
}

// Compute unique columns in order of discovery.
function standalone_inferColumns(rows) {
  var columnSet = Object.create(null),
      columns = [];

  rows.forEach(function(row) {
    for (var column in row) {
      if (!(column in columnSet)) {
        columns.push(columnSet[column] = column);
      }
    }
  });

  return columns;
}

function standalone_dsv_pad(value, width) {
  var s = value + "", length = s.length;
  return length < width ? new Array(width - length + 1).join(0) + s : s;
}

function standalone_formatYear(year) {
  return year < 0 ? "-" + standalone_dsv_pad(-year, 6)
    : year > 9999 ? "+" + standalone_dsv_pad(year, 6)
    : standalone_dsv_pad(year, 4);
}

function standalone_formatDate(date) {
  var hours = date.getUTCHours(),
      minutes = date.getUTCMinutes(),
      seconds = date.getUTCSeconds(),
      milliseconds = date.getUTCMilliseconds();
  return isNaN(date) ? "Invalid Date"
      : standalone_formatYear(date.getUTCFullYear(), 4) + "-" + standalone_dsv_pad(date.getUTCMonth() + 1, 2) + "-" + standalone_dsv_pad(date.getUTCDate(), 2)
      + (milliseconds ? "T" + standalone_dsv_pad(hours, 2) + ":" + standalone_dsv_pad(minutes, 2) + ":" + standalone_dsv_pad(seconds, 2) + "." + standalone_dsv_pad(milliseconds, 3) + "Z"
      : seconds ? "T" + standalone_dsv_pad(hours, 2) + ":" + standalone_dsv_pad(minutes, 2) + ":" + standalone_dsv_pad(seconds, 2) + "Z"
      : minutes || hours ? "T" + standalone_dsv_pad(hours, 2) + ":" + standalone_dsv_pad(minutes, 2) + "Z"
      : "");
}

/* harmony default export */ function standalone_dsv(delimiter) {
  var reFormat = new RegExp("[\"" + delimiter + "\n\r]"),
      DELIMITER = delimiter.charCodeAt(0);

  function parse(text, f) {
    var convert, columns, rows = parseRows(text, function(row, i) {
      if (convert) return convert(row, i - 1);
      columns = row, convert = f ? standalone_customConverter(row, f) : standalone_objectConverter(row);
    });
    rows.columns = columns || [];
    return rows;
  }

  function parseRows(text, f) {
    var rows = [], // output rows
        N = text.length,
        I = 0, // current character index
        n = 0, // current line number
        t, // current token
        eof = N <= 0, // current token followed by EOF?
        eol = false; // current token followed by EOL?

    // Strip the trailing newline.
    if (text.charCodeAt(N - 1) === standalone_dsv_NEWLINE) --N;
    if (text.charCodeAt(N - 1) === standalone_dsv_RETURN) --N;

    function token() {
      if (eof) return standalone_dsv_EOF;
      if (eol) return eol = false, standalone_dsv_EOL;

      // Unescape quotes.
      var i, j = I, c;
      if (text.charCodeAt(j) === standalone_dsv_QUOTE) {
        while (I++ < N && text.charCodeAt(I) !== standalone_dsv_QUOTE || text.charCodeAt(++I) === standalone_dsv_QUOTE);
        if ((i = I) >= N) eof = true;
        else if ((c = text.charCodeAt(I++)) === standalone_dsv_NEWLINE) eol = true;
        else if (c === standalone_dsv_RETURN) { eol = true; if (text.charCodeAt(I) === standalone_dsv_NEWLINE) ++I; }
        return text.slice(j + 1, i - 1).replace(/""/g, "\"");
      }

      // Find next delimiter or newline.
      while (I < N) {
        if ((c = text.charCodeAt(i = I++)) === standalone_dsv_NEWLINE) eol = true;
        else if (c === standalone_dsv_RETURN) { eol = true; if (text.charCodeAt(I) === standalone_dsv_NEWLINE) ++I; }
        else if (c !== DELIMITER) continue;
        return text.slice(j, i);
      }

      // Return last token before EOF.
      return eof = true, text.slice(j, N);
    }

    while ((t = token()) !== standalone_dsv_EOF) {
      var row = [];
      while (t !== standalone_dsv_EOL && t !== standalone_dsv_EOF) row.push(t), t = token();
      if (f && (row = f(row, n++)) == null) continue;
      rows.push(row);
    }

    return rows;
  }

  function preformatBody(rows, columns) {
    return rows.map(function(row) {
      return columns.map(function(column) {
        return formatValue(row[column]);
      }).join(delimiter);
    });
  }

  function format(rows, columns) {
    if (columns == null) columns = standalone_inferColumns(rows);
    return [columns.map(formatValue).join(delimiter)].concat(preformatBody(rows, columns)).join("\n");
  }

  function formatBody(rows, columns) {
    if (columns == null) columns = standalone_inferColumns(rows);
    return preformatBody(rows, columns).join("\n");
  }

  function formatRows(rows) {
    return rows.map(formatRow).join("\n");
  }

  function formatRow(row) {
    return row.map(formatValue).join(delimiter);
  }

  function formatValue(value) {
    return value == null ? ""
        : value instanceof Date ? standalone_formatDate(value)
        : reFormat.test(value += "") ? "\"" + value.replace(/"/g, "\"\"") + "\""
        : value;
  }

  return {
    parse: parse,
    parseRows: parseRows,
    format: format,
    formatBody: formatBody,
    formatRows: formatRows,
    formatRow: formatRow,
    formatValue: formatValue
  };
}

;// ../../node_modules/topojson-client/src/reverse.js
/* harmony default export */ function standalone_reverse(array, n) {
  var t, j = array.length, i = j - n;
  while (i < --j) t = array[i], array[i++] = array[j], array[j] = t;
}

;// ../../node_modules/topojson-client/src/identity.js
/* harmony default export */ function standalone_src_identity(x) {
  return x;
}

;// ../../node_modules/topojson-client/src/transform.js


/* harmony default export */ function standalone_transform(transform) {
  if (transform == null) return standalone_src_identity;
  var x0,
      y0,
      kx = transform.scale[0],
      ky = transform.scale[1],
      dx = transform.translate[0],
      dy = transform.translate[1];
  return function(input, i) {
    if (!i) x0 = y0 = 0;
    var j = 2, n = input.length, output = new Array(n);
    output[0] = (x0 += input[0]) * kx + dx;
    output[1] = (y0 += input[1]) * ky + dy;
    while (j < n) output[j] = input[j], ++j;
    return output;
  };
}

;// ../../node_modules/topojson-client/src/feature.js



/* harmony default export */ function standalone_feature(topology, o) {
  if (typeof o === "string") o = topology.objects[o];
  return o.type === "GeometryCollection"
      ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return standalone_feature_feature(topology, o); })}
      : standalone_feature_feature(topology, o);
}

function standalone_feature_feature(topology, o) {
  var id = o.id,
      bbox = o.bbox,
      properties = o.properties == null ? {} : o.properties,
      geometry = standalone_object(topology, o);
  return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry}
      : bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry}
      : {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry};
}

function standalone_object(topology, o) {
  var transformPoint = standalone_transform(topology.transform),
      arcs = topology.arcs;

  function arc(i, points) {
    if (points.length) points.pop();
    for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) {
      points.push(transformPoint(a[k], k));
    }
    if (i < 0) standalone_reverse(points, n);
  }

  function point(p) {
    return transformPoint(p);
  }

  function line(arcs) {
    var points = [];
    for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points);
    if (points.length < 2) points.push(points[0]); // This should never happen per the specification.
    return points;
  }

  function ring(arcs) {
    var points = line(arcs);
    while (points.length < 4) points.push(points[0]); // This may happen if an arc has only two points.
    return points;
  }

  function polygon(arcs) {
    return arcs.map(ring);
  }

  function geometry(o) {
    var type = o.type, coordinates;
    switch (type) {
      case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)};
      case "Point": coordinates = point(o.coordinates); break;
      case "MultiPoint": coordinates = o.coordinates.map(point); break;
      case "LineString": coordinates = line(o.arcs); break;
      case "MultiLineString": coordinates = o.arcs.map(line); break;
      case "Polygon": coordinates = polygon(o.arcs); break;
      case "MultiPolygon": coordinates = o.arcs.map(polygon); break;
      default: return null;
    }
    return {type: type, coordinates: coordinates};
  }

  return geometry(o);
}

;// ../../node_modules/topojson-client/src/stitch.js
/* harmony default export */ function standalone_stitch(topology, arcs) {
  var stitchedArcs = {},
      fragmentByStart = {},
      fragmentByEnd = {},
      fragments = [],
      emptyIndex = -1;

  // Stitch empty arcs first, since they may be subsumed by other arcs.
  arcs.forEach(function(i, j) {
    var arc = topology.arcs[i < 0 ? ~i : i], t;
    if (arc.length < 3 && !arc[1][0] && !arc[1][1]) {
      t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t;
    }
  });

  arcs.forEach(function(i) {
    var e = ends(i),
        start = e[0],
        end = e[1],
        f, g;

    if (f = fragmentByEnd[start]) {
      delete fragmentByEnd[f.end];
      f.push(i);
      f.end = end;
      if (g = fragmentByStart[end]) {
        delete fragmentByStart[g.start];
        var fg = g === f ? f : f.concat(g);
        fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
      } else {
        fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
      }
    } else if (f = fragmentByStart[end]) {
      delete fragmentByStart[f.start];
      f.unshift(i);
      f.start = start;
      if (g = fragmentByEnd[start]) {
        delete fragmentByEnd[g.end];
        var gf = g === f ? f : g.concat(f);
        fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
      } else {
        fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
      }
    } else {
      f = [i];
      fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f;
    }
  });

  function ends(i) {
    var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1;
    if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; });
    else p1 = arc[arc.length - 1];
    return i < 0 ? [p1, p0] : [p0, p1];
  }

  function flush(fragmentByEnd, fragmentByStart) {
    for (var k in fragmentByEnd) {
      var f = fragmentByEnd[k];
      delete fragmentByStart[f.start];
      delete f.start;
      delete f.end;
      f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; });
      fragments.push(f);
    }
  }

  flush(fragmentByEnd, fragmentByStart);
  flush(fragmentByStart, fragmentByEnd);
  arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); });

  return fragments;
}

;// ../../node_modules/topojson-client/src/mesh.js



/* harmony default export */ function standalone_mesh(topology) {
  return standalone_object(topology, standalone_meshArcs.apply(this, arguments));
}

function standalone_meshArcs(topology, object, filter) {
  var arcs, i, n;
  if (arguments.length > 1) arcs = standalone_extractArcs(topology, object, filter);
  else for (i = 0, arcs = new Array(n = topology.arcs.length); i < n; ++i) arcs[i] = i;
  return {type: "MultiLineString", arcs: standalone_stitch(topology, arcs)};
}

function standalone_extractArcs(topology, object, filter) {
  var arcs = [],
      geomsByArc = [],
      geom;

  function extract0(i) {
    var j = i < 0 ? ~i : i;
    (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom});
  }

  function extract1(arcs) {
    arcs.forEach(extract0);
  }

  function extract2(arcs) {
    arcs.forEach(extract1);
  }

  function extract3(arcs) {
    arcs.forEach(extract2);
  }

  function geometry(o) {
    switch (geom = o, o.type) {
      case "GeometryCollection": o.geometries.forEach(geometry); break;
      case "LineString": extract1(o.arcs); break;
      case "MultiLineString": case "Polygon": extract2(o.arcs); break;
      case "MultiPolygon": extract3(o.arcs); break;
    }
  }

  geometry(object);

  geomsByArc.forEach(filter == null
      ? function(geoms) { arcs.push(geoms[0].i); }
      : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); });

  return arcs;
}

;// ../../node_modules/d3-array/src/ticks.js
const standalone_e10 = Math.sqrt(50),
    standalone_e5 = Math.sqrt(10),
    standalone_e2 = Math.sqrt(2);

function standalone_tickSpec(start, stop, count) {
  const step = (stop - start) / Math.max(0, count),
      power = Math.floor(Math.log10(step)),
      error = step / Math.pow(10, power),
      factor = error >= standalone_e10 ? 10 : error >= standalone_e5 ? 5 : error >= standalone_e2 ? 2 : 1;
  let i1, i2, inc;
  if (power < 0) {
    inc = Math.pow(10, -power) / factor;
    i1 = Math.round(start * inc);
    i2 = Math.round(stop * inc);
    if (i1 / inc < start) ++i1;
    if (i2 / inc > stop) --i2;
    inc = -inc;
  } else {
    inc = Math.pow(10, power) * factor;
    i1 = Math.round(start / inc);
    i2 = Math.round(stop / inc);
    if (i1 * inc < start) ++i1;
    if (i2 * inc > stop) --i2;
  }
  if (i2 < i1 && 0.5 <= count && count < 2) return standalone_tickSpec(start, stop, count * 2);
  return [i1, i2, inc];
}

function standalone_ticks(start, stop, count) {
  stop = +stop, start = +start, count = +count;
  if (!(count > 0)) return [];
  if (start === stop) return [start];
  const reverse = stop < start, [i1, i2, inc] = reverse ? standalone_tickSpec(stop, start, count) : standalone_tickSpec(start, stop, count);
  if (!(i2 >= i1)) return [];
  const n = i2 - i1 + 1, ticks = new Array(n);
  if (reverse) {
    if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) / -inc;
    else for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) * inc;
  } else {
    if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) / -inc;
    else for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) * inc;
  }
  return ticks;
}

function standalone_tickIncrement(start, stop, count) {
  stop = +stop, start = +start, count = +count;
  return standalone_tickSpec(start, stop, count)[2];
}

function standalone_tickStep(start, stop, count) {
  stop = +stop, start = +start, count = +count;
  const reverse = stop < start, inc = reverse ? standalone_tickIncrement(stop, start, count) : standalone_tickIncrement(start, stop, count);
  return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);
}

;// ../../node_modules/d3-format/src/formatSpecifier.js
// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
var standalone_re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;

function standalone_formatSpecifier(specifier) {
  if (!(match = standalone_re.exec(specifier))) throw new Error("invalid format: " + specifier);
  var match;
  return new standalone_FormatSpecifier({
    fill: match[1],
    align: match[2],
    sign: match[3],
    symbol: match[4],
    zero: match[5],
    width: match[6],
    comma: match[7],
    precision: match[8] && match[8].slice(1),
    trim: match[9],
    type: match[10]
  });
}

standalone_formatSpecifier.prototype = standalone_FormatSpecifier.prototype; // instanceof

function standalone_FormatSpecifier(specifier) {
  this.fill = specifier.fill === undefined ? " " : specifier.fill + "";
  this.align = specifier.align === undefined ? ">" : specifier.align + "";
  this.sign = specifier.sign === undefined ? "-" : specifier.sign + "";
  this.symbol = specifier.symbol === undefined ? "" : specifier.symbol + "";
  this.zero = !!specifier.zero;
  this.width = specifier.width === undefined ? undefined : +specifier.width;
  this.comma = !!specifier.comma;
  this.precision = specifier.precision === undefined ? undefined : +specifier.precision;
  this.trim = !!specifier.trim;
  this.type = specifier.type === undefined ? "" : specifier.type + "";
}

standalone_FormatSpecifier.prototype.toString = function() {
  return this.fill
      + this.align
      + this.sign
      + this.symbol
      + (this.zero ? "0" : "")
      + (this.width === undefined ? "" : Math.max(1, this.width | 0))
      + (this.comma ? "," : "")
      + (this.precision === undefined ? "" : "." + Math.max(0, this.precision | 0))
      + (this.trim ? "~" : "")
      + this.type;
};

;// ../../node_modules/d3-format/src/formatDecimal.js
/* harmony default export */ function standalone_formatDecimal(x) {
  return Math.abs(x = Math.round(x)) >= 1e21
      ? x.toLocaleString("en").replace(/,/g, "")
      : x.toString(10);
}

// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimalParts(1.23) returns ["123", 0].
function standalone_formatDecimalParts(x, p) {
  if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
  var i, coefficient = x.slice(0, i);

  // The string returned by toExponential either has the form \d\.\d+e[-+]\d+
  // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x.slice(i + 1)
  ];
}

;// ../../node_modules/d3-format/src/exponent.js


/* harmony default export */ function standalone_exponent(x) {
  return x = standalone_formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;
}

;// ../../node_modules/d3-format/src/precisionPrefix.js


/* harmony default export */ function standalone_precisionPrefix(step, value) {
  return Math.max(0, Math.max(-8, Math.min(8, Math.floor(standalone_exponent(value) / 3))) * 3 - standalone_exponent(Math.abs(step)));
}

;// ../../node_modules/d3-format/src/precisionRound.js


/* harmony default export */ function standalone_precisionRound(step, max) {
  step = Math.abs(step), max = Math.abs(max) - step;
  return Math.max(0, standalone_exponent(max) - standalone_exponent(step)) + 1;
}

;// ../../node_modules/d3-format/src/precisionFixed.js


/* harmony default export */ function standalone_precisionFixed(step) {
  return Math.max(0, -standalone_exponent(Math.abs(step)));
}

;// ../../node_modules/d3-format/src/formatGroup.js
/* harmony default export */ function standalone_formatGroup(grouping, thousands) {
  return function(value, width) {
    var i = value.length,
        t = [],
        j = 0,
        g = grouping[0],
        length = 0;

    while (i > 0 && g > 0) {
      if (length + g + 1 > width) g = Math.max(1, width - length);
      t.push(value.substring(i -= g, i + g));
      if ((length += g + 1) > width) break;
      g = grouping[j = (j + 1) % grouping.length];
    }

    return t.reverse().join(thousands);
  };
}

;// ../../node_modules/d3-format/src/formatNumerals.js
/* harmony default export */ function standalone_formatNumerals(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i) {
      return numerals[+i];
    });
  };
}

;// ../../node_modules/d3-format/src/formatTrim.js
// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
/* harmony default export */ function standalone_formatTrim(s) {
  out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
    switch (s[i]) {
      case ".": i0 = i1 = i; break;
      case "0": if (i0 === 0) i0 = i; i1 = i; break;
      default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;
    }
  }
  return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
}

;// ../../node_modules/d3-format/src/formatPrefixAuto.js


var standalone_prefixExponent;

/* harmony default export */ function standalone_formatPrefixAuto(x, p) {
  var d = standalone_formatDecimalParts(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1],
      i = exponent - (standalone_prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
      n = coefficient.length;
  return i === n ? coefficient
      : i > n ? coefficient + new Array(i - n + 1).join("0")
      : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
      : "0." + new Array(1 - i).join("0") + standalone_formatDecimalParts(x, Math.max(0, p + i - 1))[0]; // less than 1y!
}

;// ../../node_modules/d3-format/src/formatRounded.js


/* harmony default export */ function standalone_formatRounded(x, p) {
  var d = standalone_formatDecimalParts(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1];
  return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
      : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
      : coefficient + new Array(exponent - coefficient.length + 2).join("0");
}

;// ../../node_modules/d3-format/src/formatTypes.js




/* harmony default export */ const standalone_formatTypes = ({
  "%": (x, p) => (x * 100).toFixed(p),
  "b": (x) => Math.round(x).toString(2),
  "c": (x) => x + "",
  "d": standalone_formatDecimal,
  "e": (x, p) => x.toExponential(p),
  "f": (x, p) => x.toFixed(p),
  "g": (x, p) => x.toPrecision(p),
  "o": (x) => Math.round(x).toString(8),
  "p": (x, p) => standalone_formatRounded(x * 100, p),
  "r": standalone_formatRounded,
  "s": standalone_formatPrefixAuto,
  "X": (x) => Math.round(x).toString(16).toUpperCase(),
  "x": (x) => Math.round(x).toString(16)
});

;// ../../node_modules/d3-format/src/identity.js
/* harmony default export */ function standalone_d3_format_src_identity(x) {
  return x;
}

;// ../../node_modules/d3-format/src/locale.js









var standalone_map = Array.prototype.map,
    standalone_prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];

/* harmony default export */ function standalone_locale(locale) {
  var group = locale.grouping === undefined || locale.thousands === undefined ? standalone_d3_format_src_identity : standalone_formatGroup(standalone_map.call(locale.grouping, Number), locale.thousands + ""),
      currencyPrefix = locale.currency === undefined ? "" : locale.currency[0] + "",
      currencySuffix = locale.currency === undefined ? "" : locale.currency[1] + "",
      decimal = locale.decimal === undefined ? "." : locale.decimal + "",
      numerals = locale.numerals === undefined ? standalone_d3_format_src_identity : standalone_formatNumerals(standalone_map.call(locale.numerals, String)),
      percent = locale.percent === undefined ? "%" : locale.percent + "",
      minus = locale.minus === undefined ? "−" : locale.minus + "",
      nan = locale.nan === undefined ? "NaN" : locale.nan + "";

  function newFormat(specifier) {
    specifier = standalone_formatSpecifier(specifier);

    var fill = specifier.fill,
        align = specifier.align,
        sign = specifier.sign,
        symbol = specifier.symbol,
        zero = specifier.zero,
        width = specifier.width,
        comma = specifier.comma,
        precision = specifier.precision,
        trim = specifier.trim,
        type = specifier.type;

    // The "n" type is an alias for ",g".
    if (type === "n") comma = true, type = "g";

    // The "" type, and any invalid type, is an alias for ".12~g".
    else if (!standalone_formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = "g";

    // If zero fill is specified, padding goes after sign and before digits.
    if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";

    // Compute the prefix and suffix.
    // For SI-prefix, the suffix is lazily computed.
    var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
        suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";

    // What format function should we use?
    // Is this an integer type?
    // Can this type generate exponential notation?
    var formatType = standalone_formatTypes[type],
        maybeSuffix = /[defgprs%]/.test(type);

    // Set the default precision if not specified,
    // or clamp the specified precision to the supported range.
    // For significant precision, it must be in [1, 21].
    // For fixed precision, it must be in [0, 20].
    precision = precision === undefined ? 6
        : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
        : Math.max(0, Math.min(20, precision));

    function format(value) {
      var valuePrefix = prefix,
          valueSuffix = suffix,
          i, n, c;

      if (type === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;

        // Determine the sign. -0 is not less than 0, but 1 / -0 is!
        var valueNegative = value < 0 || 1 / value < 0;

        // Perform the initial formatting.
        value = isNaN(value) ? nan : formatType(Math.abs(value), precision);

        // Trim insignificant zeros.
        if (trim) value = standalone_formatTrim(value);

        // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.
        if (valueNegative && +value === 0 && sign !== "+") valueNegative = false;

        // Compute the prefix and suffix.
        valuePrefix = (valueNegative ? (sign === "(" ? sign : minus) : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
        valueSuffix = (type === "s" ? standalone_prefixes[8 + standalone_prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");

        // Break the formatted value into the integer “value” part that can be
        // grouped, and fractional or exponential “suffix” part that is not.
        if (maybeSuffix) {
          i = -1, n = value.length;
          while (++i < n) {
            if (c = value.charCodeAt(i), 48 > c || c > 57) {
              valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
              value = value.slice(0, i);
              break;
            }
          }
        }
      }

      // If the fill character is not "0", grouping is applied before padding.
      if (comma && !zero) value = group(value, Infinity);

      // Compute the padding.
      var length = valuePrefix.length + value.length + valueSuffix.length,
          padding = length < width ? new Array(width - length + 1).join(fill) : "";

      // If the fill character is "0", grouping is applied after padding.
      if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";

      // Reconstruct the final output based on the desired alignment.
      switch (align) {
        case "<": value = valuePrefix + value + valueSuffix + padding; break;
        case "=": value = valuePrefix + padding + value + valueSuffix; break;
        case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
        default: value = padding + valuePrefix + value + valueSuffix; break;
      }

      return numerals(value);
    }

    format.toString = function() {
      return specifier + "";
    };

    return format;
  }

  function formatPrefix(specifier, value) {
    var f = newFormat((specifier = standalone_formatSpecifier(specifier), specifier.type = "f", specifier)),
        e = Math.max(-8, Math.min(8, Math.floor(standalone_exponent(value) / 3))) * 3,
        k = Math.pow(10, -e),
        prefix = standalone_prefixes[8 + e / 3];
    return function(value) {
      return f(k * value) + prefix;
    };
  }

  return {
    format: newFormat,
    formatPrefix: formatPrefix
  };
}

;// ../../node_modules/d3-format/src/defaultLocale.js


var standalone_defaultLocale_locale;
var standalone_format;
var standalone_formatPrefix;

standalone_defaultLocale({
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});

function standalone_defaultLocale(definition) {
  standalone_defaultLocale_locale = standalone_locale(definition);
  standalone_format = standalone_defaultLocale_locale.format;
  standalone_formatPrefix = standalone_defaultLocale_locale.formatPrefix;
  return standalone_defaultLocale_locale;
}

;// ../../node_modules/d3-time/src/interval.js
const standalone_t0 = new Date, standalone_t1 = new Date;

function standalone_timeInterval(floori, offseti, count, field) {

  function interval(date) {
    return floori(date = arguments.length === 0 ? new Date : new Date(+date)), date;
  }

  interval.floor = (date) => {
    return floori(date = new Date(+date)), date;
  };

  interval.ceil = (date) => {
    return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;
  };

  interval.round = (date) => {
    const d0 = interval(date), d1 = interval.ceil(date);
    return date - d0 < d1 - date ? d0 : d1;
  };

  interval.offset = (date, step) => {
    return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;
  };

  interval.range = (start, stop, step) => {
    const range = [];
    start = interval.ceil(start);
    step = step == null ? 1 : Math.floor(step);
    if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date
    let previous;
    do range.push(previous = new Date(+start)), offseti(start, step), floori(start);
    while (previous < start && start < stop);
    return range;
  };

  interval.filter = (test) => {
    return standalone_timeInterval((date) => {
      if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);
    }, (date, step) => {
      if (date >= date) {
        if (step < 0) while (++step <= 0) {
          while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty
        } else while (--step >= 0) {
          while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty
        }
      }
    });
  };

  if (count) {
    interval.count = (start, end) => {
      standalone_t0.setTime(+start), standalone_t1.setTime(+end);
      floori(standalone_t0), floori(standalone_t1);
      return Math.floor(count(standalone_t0, standalone_t1));
    };

    interval.every = (step) => {
      step = Math.floor(step);
      return !isFinite(step) || !(step > 0) ? null
          : !(step > 1) ? interval
          : interval.filter(field
              ? (d) => field(d) % step === 0
              : (d) => interval.count(0, d) % step === 0);
    };
  }

  return interval;
}

;// ../../node_modules/d3-time/src/duration.js
const standalone_durationSecond = 1000;
const standalone_durationMinute = standalone_durationSecond * 60;
const standalone_durationHour = standalone_durationMinute * 60;
const standalone_durationDay = standalone_durationHour * 24;
const standalone_durationWeek = standalone_durationDay * 7;
const standalone_durationMonth = standalone_durationDay * 30;
const standalone_durationYear = standalone_durationDay * 365;

;// ../../node_modules/d3-time/src/day.js



const standalone_timeDay = standalone_timeInterval(
  date => date.setHours(0, 0, 0, 0),
  (date, step) => date.setDate(date.getDate() + step),
  (start, end) => (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * standalone_durationMinute) / standalone_durationDay,
  date => date.getDate() - 1
);

const standalone_timeDays = standalone_timeDay.range;

const standalone_utcDay = standalone_timeInterval((date) => {
  date.setUTCHours(0, 0, 0, 0);
}, (date, step) => {
  date.setUTCDate(date.getUTCDate() + step);
}, (start, end) => {
  return (end - start) / standalone_durationDay;
}, (date) => {
  return date.getUTCDate() - 1;
});

const standalone_utcDays = standalone_utcDay.range;

const standalone_unixDay = standalone_timeInterval((date) => {
  date.setUTCHours(0, 0, 0, 0);
}, (date, step) => {
  date.setUTCDate(date.getUTCDate() + step);
}, (start, end) => {
  return (end - start) / standalone_durationDay;
}, (date) => {
  return Math.floor(date / standalone_durationDay);
});

const standalone_unixDays = standalone_unixDay.range;

;// ../../node_modules/d3-time/src/week.js



function standalone_timeWeekday(i) {
  return standalone_timeInterval((date) => {
    date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);
    date.setHours(0, 0, 0, 0);
  }, (date, step) => {
    date.setDate(date.getDate() + step * 7);
  }, (start, end) => {
    return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * standalone_durationMinute) / standalone_durationWeek;
  });
}

const standalone_timeSunday = standalone_timeWeekday(0);
const standalone_timeMonday = standalone_timeWeekday(1);
const standalone_timeTuesday = standalone_timeWeekday(2);
const standalone_timeWednesday = standalone_timeWeekday(3);
const standalone_timeThursday = standalone_timeWeekday(4);
const standalone_timeFriday = standalone_timeWeekday(5);
const standalone_timeSaturday = standalone_timeWeekday(6);

const standalone_timeSundays = standalone_timeSunday.range;
const standalone_timeMondays = standalone_timeMonday.range;
const standalone_timeTuesdays = standalone_timeTuesday.range;
const standalone_timeWednesdays = standalone_timeWednesday.range;
const standalone_timeThursdays = standalone_timeThursday.range;
const standalone_timeFridays = standalone_timeFriday.range;
const standalone_timeSaturdays = standalone_timeSaturday.range;

function standalone_utcWeekday(i) {
  return standalone_timeInterval((date) => {
    date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);
    date.setUTCHours(0, 0, 0, 0);
  }, (date, step) => {
    date.setUTCDate(date.getUTCDate() + step * 7);
  }, (start, end) => {
    return (end - start) / standalone_durationWeek;
  });
}

const standalone_utcSunday = standalone_utcWeekday(0);
const standalone_utcMonday = standalone_utcWeekday(1);
const standalone_utcTuesday = standalone_utcWeekday(2);
const standalone_utcWednesday = standalone_utcWeekday(3);
const standalone_utcThursday = standalone_utcWeekday(4);
const standalone_utcFriday = standalone_utcWeekday(5);
const standalone_utcSaturday = standalone_utcWeekday(6);

const standalone_utcSundays = standalone_utcSunday.range;
const standalone_utcMondays = standalone_utcMonday.range;
const standalone_utcTuesdays = standalone_utcTuesday.range;
const standalone_utcWednesdays = standalone_utcWednesday.range;
const standalone_utcThursdays = standalone_utcThursday.range;
const standalone_utcFridays = standalone_utcFriday.range;
const standalone_utcSaturdays = standalone_utcSaturday.range;

;// ../../node_modules/d3-time/src/year.js


const standalone_timeYear = standalone_timeInterval((date) => {
  date.setMonth(0, 1);
  date.setHours(0, 0, 0, 0);
}, (date, step) => {
  date.setFullYear(date.getFullYear() + step);
}, (start, end) => {
  return end.getFullYear() - start.getFullYear();
}, (date) => {
  return date.getFullYear();
});

// An optimized implementation for this simple case.
standalone_timeYear.every = (k) => {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : standalone_timeInterval((date) => {
    date.setFullYear(Math.floor(date.getFullYear() / k) * k);
    date.setMonth(0, 1);
    date.setHours(0, 0, 0, 0);
  }, (date, step) => {
    date.setFullYear(date.getFullYear() + step * k);
  });
};

const standalone_timeYears = standalone_timeYear.range;

const standalone_utcYear = standalone_timeInterval((date) => {
  date.setUTCMonth(0, 1);
  date.setUTCHours(0, 0, 0, 0);
}, (date, step) => {
  date.setUTCFullYear(date.getUTCFullYear() + step);
}, (start, end) => {
  return end.getUTCFullYear() - start.getUTCFullYear();
}, (date) => {
  return date.getUTCFullYear();
});

// An optimized implementation for this simple case.
standalone_utcYear.every = (k) => {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : standalone_timeInterval((date) => {
    date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);
    date.setUTCMonth(0, 1);
    date.setUTCHours(0, 0, 0, 0);
  }, (date, step) => {
    date.setUTCFullYear(date.getUTCFullYear() + step * k);
  });
};

const standalone_utcYears = standalone_utcYear.range;

;// ../../node_modules/d3-time/src/month.js


const standalone_timeMonth = standalone_timeInterval((date) => {
  date.setDate(1);
  date.setHours(0, 0, 0, 0);
}, (date, step) => {
  date.setMonth(date.getMonth() + step);
}, (start, end) => {
  return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
}, (date) => {
  return date.getMonth();
});

const standalone_timeMonths = standalone_timeMonth.range;

const standalone_utcMonth = standalone_timeInterval((date) => {
  date.setUTCDate(1);
  date.setUTCHours(0, 0, 0, 0);
}, (date, step) => {
  date.setUTCMonth(date.getUTCMonth() + step);
}, (start, end) => {
  return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
}, (date) => {
  return date.getUTCMonth();
});

const standalone_utcMonths = standalone_utcMonth.range;

;// ../../node_modules/d3-time/src/hour.js



const standalone_timeHour = standalone_timeInterval((date) => {
  date.setTime(date - date.getMilliseconds() - date.getSeconds() * standalone_durationSecond - date.getMinutes() * standalone_durationMinute);
}, (date, step) => {
  date.setTime(+date + step * standalone_durationHour);
}, (start, end) => {
  return (end - start) / standalone_durationHour;
}, (date) => {
  return date.getHours();
});

const standalone_timeHours = standalone_timeHour.range;

const standalone_utcHour = standalone_timeInterval((date) => {
  date.setUTCMinutes(0, 0, 0);
}, (date, step) => {
  date.setTime(+date + step * standalone_durationHour);
}, (start, end) => {
  return (end - start) / standalone_durationHour;
}, (date) => {
  return date.getUTCHours();
});

const standalone_utcHours = standalone_utcHour.range;

;// ../../node_modules/d3-time/src/minute.js



const standalone_timeMinute = standalone_timeInterval((date) => {
  date.setTime(date - date.getMilliseconds() - date.getSeconds() * standalone_durationSecond);
}, (date, step) => {
  date.setTime(+date + step * standalone_durationMinute);
}, (start, end) => {
  return (end - start) / standalone_durationMinute;
}, (date) => {
  return date.getMinutes();
});

const standalone_timeMinutes = standalone_timeMinute.range;

const standalone_utcMinute = standalone_timeInterval((date) => {
  date.setUTCSeconds(0, 0);
}, (date, step) => {
  date.setTime(+date + step * standalone_durationMinute);
}, (start, end) => {
  return (end - start) / standalone_durationMinute;
}, (date) => {
  return date.getUTCMinutes();
});

const standalone_utcMinutes = standalone_utcMinute.range;

;// ../../node_modules/d3-time/src/second.js



const standalone_second = standalone_timeInterval((date) => {
  date.setTime(date - date.getMilliseconds());
}, (date, step) => {
  date.setTime(+date + step * standalone_durationSecond);
}, (start, end) => {
  return (end - start) / standalone_durationSecond;
}, (date) => {
  return date.getUTCSeconds();
});

const standalone_seconds = standalone_second.range;

;// ../../node_modules/d3-time/src/millisecond.js


const standalone_millisecond = standalone_timeInterval(() => {
  // noop
}, (date, step) => {
  date.setTime(+date + step);
}, (start, end) => {
  return end - start;
});

// An optimized implementation for this simple case.
standalone_millisecond.every = (k) => {
  k = Math.floor(k);
  if (!isFinite(k) || !(k > 0)) return null;
  if (!(k > 1)) return standalone_millisecond;
  return standalone_timeInterval((date) => {
    date.setTime(Math.floor(date / k) * k);
  }, (date, step) => {
    date.setTime(+date + step * k);
  }, (start, end) => {
    return (end - start) / k;
  });
};

const standalone_milliseconds = standalone_millisecond.range;

;// ../../node_modules/d3-array/src/ascending.js
function standalone_ascending_ascending(a, b) {
  return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

;// ../../node_modules/d3-array/src/descending.js
function standalone_descending(a, b) {
  return a == null || b == null ? NaN
    : b < a ? -1
    : b > a ? 1
    : b >= a ? 0
    : NaN;
}

;// ../../node_modules/d3-array/src/bisector.js



function standalone_bisector(f) {
  let compare1, compare2, delta;

  // If an accessor is specified, promote it to a comparator. In this case we
  // can test whether the search value is (self-) comparable. We can’t do this
  // for a comparator (except for specific, known comparators) because we can’t
  // tell if the comparator is symmetric, and an asymmetric comparator can’t be
  // used to test whether a single value is comparable.
  if (f.length !== 2) {
    compare1 = standalone_ascending_ascending;
    compare2 = (d, x) => standalone_ascending_ascending(f(d), x);
    delta = (d, x) => f(d) - x;
  } else {
    compare1 = f === standalone_ascending_ascending || f === standalone_descending ? f : standalone_bisector_zero;
    compare2 = f;
    delta = f;
  }

  function left(a, x, lo = 0, hi = a.length) {
    if (lo < hi) {
      if (compare1(x, x) !== 0) return hi;
      do {
        const mid = (lo + hi) >>> 1;
        if (compare2(a[mid], x) < 0) lo = mid + 1;
        else hi = mid;
      } while (lo < hi);
    }
    return lo;
  }

  function right(a, x, lo = 0, hi = a.length) {
    if (lo < hi) {
      if (compare1(x, x) !== 0) return hi;
      do {
        const mid = (lo + hi) >>> 1;
        if (compare2(a[mid], x) <= 0) lo = mid + 1;
        else hi = mid;
      } while (lo < hi);
    }
    return lo;
  }

  function center(a, x, lo = 0, hi = a.length) {
    const i = left(a, x, lo, hi - 1);
    return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;
  }

  return {left, center, right};
}

function standalone_bisector_zero() {
  return 0;
}

;// ../../node_modules/vega-time/build/vega-time.module.js




const standalone_YEAR = 'year';
const standalone_QUARTER = 'quarter';
const standalone_MONTH = 'month';
const standalone_WEEK = 'week';
const standalone_DATE = 'date';
const standalone_DAY = 'day';
const standalone_DAYOFYEAR = 'dayofyear';
const standalone_HOURS = 'hours';
const standalone_MINUTES = 'minutes';
const standalone_SECONDS = 'seconds';
const standalone_MILLISECONDS = 'milliseconds';
const standalone_TIME_UNITS = [standalone_YEAR, standalone_QUARTER, standalone_MONTH, standalone_WEEK, standalone_DATE, standalone_DAY, standalone_DAYOFYEAR, standalone_HOURS, standalone_MINUTES, standalone_SECONDS, standalone_MILLISECONDS];
const standalone_UNITS = standalone_TIME_UNITS.reduce((o, u, i) => (o[u] = 1 + i, o), {});
function standalone_timeUnits(units) {
  const u = standalone_array(units).slice(),
    m = {};

  // check validity
  if (!u.length) standalone_vega_util_module_error('Missing time unit.');
  u.forEach(unit => {
    if (standalone_vega_util_module_has(standalone_UNITS, unit)) {
      m[unit] = 1;
    } else {
      standalone_vega_util_module_error(`Invalid time unit: ${unit}.`);
    }
  });
  const numTypes = (m[standalone_WEEK] || m[standalone_DAY] ? 1 : 0) + (m[standalone_QUARTER] || m[standalone_MONTH] || m[standalone_DATE] ? 1 : 0) + (m[standalone_DAYOFYEAR] ? 1 : 0);
  if (numTypes > 1) {
    standalone_vega_util_module_error(`Incompatible time units: ${units}`);
  }

  // ensure proper sort order
  u.sort((a, b) => standalone_UNITS[a] - standalone_UNITS[b]);
  return u;
}
const standalone_defaultSpecifiers = {
  [standalone_YEAR]: '%Y ',
  [standalone_QUARTER]: 'Q%q ',
  [standalone_MONTH]: '%b ',
  [standalone_DATE]: '%d ',
  [standalone_WEEK]: 'W%U ',
  [standalone_DAY]: '%a ',
  [standalone_DAYOFYEAR]: '%j ',
  [standalone_HOURS]: '%H:00',
  [standalone_MINUTES]: '00:%M',
  [standalone_SECONDS]: ':%S',
  [standalone_MILLISECONDS]: '.%L',
  [`${standalone_YEAR}-${standalone_MONTH}`]: '%Y-%m ',
  [`${standalone_YEAR}-${standalone_MONTH}-${standalone_DATE}`]: '%Y-%m-%d ',
  [`${standalone_HOURS}-${standalone_MINUTES}`]: '%H:%M'
};
function standalone_timeUnitSpecifier(units, specifiers) {
  const s = standalone_extend({}, standalone_defaultSpecifiers, specifiers),
    u = standalone_timeUnits(units),
    n = u.length;
  let fmt = '',
    start = 0,
    end,
    key;
  for (start = 0; start < n;) {
    for (end = u.length; end > start; --end) {
      key = u.slice(start, end).join('-');
      if (s[key] != null) {
        fmt += s[key];
        start = end;
        break;
      }
    }
  }
  return fmt.trim();
}

const standalone_vega_time_module_t0 = new Date();
function standalone_localYear(y) {
  standalone_vega_time_module_t0.setFullYear(y);
  standalone_vega_time_module_t0.setMonth(0);
  standalone_vega_time_module_t0.setDate(1);
  standalone_vega_time_module_t0.setHours(0, 0, 0, 0);
  return standalone_vega_time_module_t0;
}
function standalone_dayofyear(d) {
  return standalone_localDayOfYear(new Date(d));
}
function standalone_week(d) {
  return standalone_localWeekNum(new Date(d));
}
function standalone_localDayOfYear(d) {
  return standalone_timeDay.count(standalone_localYear(d.getFullYear()) - 1, d);
}
function standalone_localWeekNum(d) {
  return standalone_timeSunday.count(standalone_localYear(d.getFullYear()) - 1, d);
}
function standalone_localFirst(y) {
  return standalone_localYear(y).getDay();
}
function standalone_localDate(y, m, d, H, M, S, L) {
  if (0 <= y && y < 100) {
    const date = new Date(-1, m, d, H, M, S, L);
    date.setFullYear(y);
    return date;
  }
  return new Date(y, m, d, H, M, S, L);
}
function standalone_utcdayofyear(d) {
  return standalone_utcDayOfYear(new Date(d));
}
function standalone_utcweek(d) {
  return standalone_utcWeekNum(new Date(d));
}
function standalone_utcDayOfYear(d) {
  const y = Date.UTC(d.getUTCFullYear(), 0, 1);
  return standalone_utcDay.count(y - 1, d);
}
function standalone_utcWeekNum(d) {
  const y = Date.UTC(d.getUTCFullYear(), 0, 1);
  return standalone_utcSunday.count(y - 1, d);
}
function standalone_utcFirst(y) {
  standalone_vega_time_module_t0.setTime(Date.UTC(y, 0, 1));
  return standalone_vega_time_module_t0.getUTCDay();
}
function standalone_utcDate(y, m, d, H, M, S, L) {
  if (0 <= y && y < 100) {
    const date = new Date(Date.UTC(-1, m, d, H, M, S, L));
    date.setUTCFullYear(d.y);
    return date;
  }
  return new Date(Date.UTC(y, m, d, H, M, S, L));
}

function standalone_floor(units, step, get, inv, newDate) {
  const s = step || 1,
    b = standalone_peek(units),
    _ = (unit, p, key) => {
      key = key || unit;
      return standalone_getUnit(get[key], inv[key], unit === b && s, p);
    };
  const t = new Date(),
    u = standalone_toSet(units),
    y = u[standalone_YEAR] ? _(standalone_YEAR) : standalone_vega_util_module_constant(2012),
    m = u[standalone_MONTH] ? _(standalone_MONTH) : u[standalone_QUARTER] ? _(standalone_QUARTER) : standalone_zero,
    d = u[standalone_WEEK] && u[standalone_DAY] ? _(standalone_DAY, 1, standalone_WEEK + standalone_DAY) : u[standalone_WEEK] ? _(standalone_WEEK, 1) : u[standalone_DAY] ? _(standalone_DAY, 1) : u[standalone_DATE] ? _(standalone_DATE, 1) : u[standalone_DAYOFYEAR] ? _(standalone_DAYOFYEAR, 1) : standalone_one,
    H = u[standalone_HOURS] ? _(standalone_HOURS) : standalone_zero,
    M = u[standalone_MINUTES] ? _(standalone_MINUTES) : standalone_zero,
    S = u[standalone_SECONDS] ? _(standalone_SECONDS) : standalone_zero,
    L = u[standalone_MILLISECONDS] ? _(standalone_MILLISECONDS) : standalone_zero;
  return function (v) {
    t.setTime(+v);
    const year = y(t);
    return newDate(year, m(t), d(t, year), H(t), M(t), S(t), L(t));
  };
}
function standalone_getUnit(f, inv, step, phase) {
  const u = step <= 1 ? f : phase ? (d, y) => phase + step * Math.floor((f(d, y) - phase) / step) : (d, y) => step * Math.floor(f(d, y) / step);
  return inv ? (d, y) => inv(u(d, y), y) : u;
}

// returns the day of the year based on week number, day of week,
// and the day of the week for the first day of the year
function standalone_weekday(week, day, firstDay) {
  return day + week * 7 - (firstDay + 6) % 7;
}

// -- LOCAL TIME --

const standalone_localGet = {
  [standalone_YEAR]: d => d.getFullYear(),
  [standalone_QUARTER]: d => Math.floor(d.getMonth() / 3),
  [standalone_MONTH]: d => d.getMonth(),
  [standalone_DATE]: d => d.getDate(),
  [standalone_HOURS]: d => d.getHours(),
  [standalone_MINUTES]: d => d.getMinutes(),
  [standalone_SECONDS]: d => d.getSeconds(),
  [standalone_MILLISECONDS]: d => d.getMilliseconds(),
  [standalone_DAYOFYEAR]: d => standalone_localDayOfYear(d),
  [standalone_WEEK]: d => standalone_localWeekNum(d),
  [standalone_WEEK + standalone_DAY]: (d, y) => standalone_weekday(standalone_localWeekNum(d), d.getDay(), standalone_localFirst(y)),
  [standalone_DAY]: (d, y) => standalone_weekday(1, d.getDay(), standalone_localFirst(y))
};
const standalone_localInv = {
  [standalone_QUARTER]: q => 3 * q,
  [standalone_WEEK]: (w, y) => standalone_weekday(w, 0, standalone_localFirst(y))
};
function standalone_timeFloor(units, step) {
  return standalone_floor(units, step || 1, standalone_localGet, standalone_localInv, standalone_localDate);
}

// -- UTC TIME --

const standalone_utcGet = {
  [standalone_YEAR]: d => d.getUTCFullYear(),
  [standalone_QUARTER]: d => Math.floor(d.getUTCMonth() / 3),
  [standalone_MONTH]: d => d.getUTCMonth(),
  [standalone_DATE]: d => d.getUTCDate(),
  [standalone_HOURS]: d => d.getUTCHours(),
  [standalone_MINUTES]: d => d.getUTCMinutes(),
  [standalone_SECONDS]: d => d.getUTCSeconds(),
  [standalone_MILLISECONDS]: d => d.getUTCMilliseconds(),
  [standalone_DAYOFYEAR]: d => standalone_utcDayOfYear(d),
  [standalone_WEEK]: d => standalone_utcWeekNum(d),
  [standalone_DAY]: (d, y) => standalone_weekday(1, d.getUTCDay(), standalone_utcFirst(y)),
  [standalone_WEEK + standalone_DAY]: (d, y) => standalone_weekday(standalone_utcWeekNum(d), d.getUTCDay(), standalone_utcFirst(y))
};
const standalone_utcInv = {
  [standalone_QUARTER]: q => 3 * q,
  [standalone_WEEK]: (w, y) => standalone_weekday(w, 0, standalone_utcFirst(y))
};
function standalone_utcFloor(units, step) {
  return standalone_floor(units, step || 1, standalone_utcGet, standalone_utcInv, standalone_utcDate);
}

const standalone_timeIntervals = {
  [standalone_YEAR]: standalone_timeYear,
  [standalone_QUARTER]: standalone_timeMonth.every(3),
  [standalone_MONTH]: standalone_timeMonth,
  [standalone_WEEK]: standalone_timeSunday,
  [standalone_DATE]: standalone_timeDay,
  [standalone_DAY]: standalone_timeDay,
  [standalone_DAYOFYEAR]: standalone_timeDay,
  [standalone_HOURS]: standalone_timeHour,
  [standalone_MINUTES]: standalone_timeMinute,
  [standalone_SECONDS]: standalone_second,
  [standalone_MILLISECONDS]: standalone_millisecond
};
const standalone_utcIntervals = {
  [standalone_YEAR]: standalone_utcYear,
  [standalone_QUARTER]: standalone_utcMonth.every(3),
  [standalone_MONTH]: standalone_utcMonth,
  [standalone_WEEK]: standalone_utcSunday,
  [standalone_DATE]: standalone_utcDay,
  [standalone_DAY]: standalone_utcDay,
  [standalone_DAYOFYEAR]: standalone_utcDay,
  [standalone_HOURS]: standalone_utcHour,
  [standalone_MINUTES]: standalone_utcMinute,
  [standalone_SECONDS]: standalone_second,
  [standalone_MILLISECONDS]: standalone_millisecond
};
function standalone_vega_time_module_timeInterval(unit) {
  return standalone_timeIntervals[unit];
}
function standalone_utcInterval(unit) {
  return standalone_utcIntervals[unit];
}
function standalone_offset(ival, date, step) {
  return ival ? ival.offset(date, step) : undefined;
}
function standalone_timeOffset(unit, date, step) {
  return standalone_offset(standalone_vega_time_module_timeInterval(unit), date, step);
}
function standalone_utcOffset(unit, date, step) {
  return standalone_offset(standalone_utcInterval(unit), date, step);
}
function standalone_sequence(ival, start, stop, step) {
  return ival ? ival.range(start, stop, step) : undefined;
}
function standalone_timeSequence(unit, start, stop, step) {
  return standalone_sequence(standalone_vega_time_module_timeInterval(unit), start, stop, step);
}
function standalone_utcSequence(unit, start, stop, step) {
  return standalone_sequence(standalone_utcInterval(unit), start, stop, step);
}

const standalone_vega_time_module_durationSecond = 1000,
  standalone_vega_time_module_durationMinute = standalone_vega_time_module_durationSecond * 60,
  standalone_vega_time_module_durationHour = standalone_vega_time_module_durationMinute * 60,
  standalone_vega_time_module_durationDay = standalone_vega_time_module_durationHour * 24,
  standalone_vega_time_module_durationWeek = standalone_vega_time_module_durationDay * 7,
  standalone_vega_time_module_durationMonth = standalone_vega_time_module_durationDay * 30,
  standalone_vega_time_module_durationYear = standalone_vega_time_module_durationDay * 365;
const standalone_Milli = [standalone_YEAR, standalone_MONTH, standalone_DATE, standalone_HOURS, standalone_MINUTES, standalone_SECONDS, standalone_MILLISECONDS],
  standalone_Seconds = standalone_Milli.slice(0, -1),
  standalone_Minutes = standalone_Seconds.slice(0, -1),
  standalone_Hours = standalone_Minutes.slice(0, -1),
  standalone_Day = standalone_Hours.slice(0, -1),
  standalone_Week = [standalone_YEAR, standalone_WEEK],
  standalone_Month = [standalone_YEAR, standalone_MONTH],
  standalone_Year = [standalone_YEAR];
const standalone_intervals = [[standalone_Seconds, 1, standalone_vega_time_module_durationSecond], [standalone_Seconds, 5, 5 * standalone_vega_time_module_durationSecond], [standalone_Seconds, 15, 15 * standalone_vega_time_module_durationSecond], [standalone_Seconds, 30, 30 * standalone_vega_time_module_durationSecond], [standalone_Minutes, 1, standalone_vega_time_module_durationMinute], [standalone_Minutes, 5, 5 * standalone_vega_time_module_durationMinute], [standalone_Minutes, 15, 15 * standalone_vega_time_module_durationMinute], [standalone_Minutes, 30, 30 * standalone_vega_time_module_durationMinute], [standalone_Hours, 1, standalone_vega_time_module_durationHour], [standalone_Hours, 3, 3 * standalone_vega_time_module_durationHour], [standalone_Hours, 6, 6 * standalone_vega_time_module_durationHour], [standalone_Hours, 12, 12 * standalone_vega_time_module_durationHour], [standalone_Day, 1, standalone_vega_time_module_durationDay], [standalone_Week, 1, standalone_vega_time_module_durationWeek], [standalone_Month, 1, standalone_vega_time_module_durationMonth], [standalone_Month, 3, 3 * standalone_vega_time_module_durationMonth], [standalone_Year, 1, standalone_vega_time_module_durationYear]];
function standalone_bin (opt) {
  const ext = opt.extent,
    max = opt.maxbins || 40,
    target = Math.abs(standalone_span(ext)) / max;
  let i = standalone_bisector(i => i[2]).right(standalone_intervals, target),
    units,
    step;
  if (i === standalone_intervals.length) {
    units = standalone_Year, step = standalone_tickStep(ext[0] / standalone_vega_time_module_durationYear, ext[1] / standalone_vega_time_module_durationYear, max);
  } else if (i) {
    i = standalone_intervals[target / standalone_intervals[i - 1][2] < standalone_intervals[i][2] / target ? i - 1 : i];
    units = i[0];
    step = i[1];
  } else {
    units = standalone_Milli;
    step = Math.max(standalone_tickStep(ext[0], ext[1], max), 1);
  }
  return {
    units,
    step
  };
}



;// ../../node_modules/d3-time-format/src/locale.js


function standalone_locale_localDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
    date.setFullYear(d.y);
    return date;
  }
  return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}

function standalone_locale_utcDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
    date.setUTCFullYear(d.y);
    return date;
  }
  return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}

function standalone_newDate(y, m, d) {
  return {y: y, m: m, d: d, H: 0, M: 0, S: 0, L: 0};
}

function standalone_formatLocale(locale) {
  var locale_dateTime = locale.dateTime,
      locale_date = locale.date,
      locale_time = locale.time,
      locale_periods = locale.periods,
      locale_weekdays = locale.days,
      locale_shortWeekdays = locale.shortDays,
      locale_months = locale.months,
      locale_shortMonths = locale.shortMonths;

  var periodRe = standalone_formatRe(locale_periods),
      periodLookup = standalone_formatLookup(locale_periods),
      weekdayRe = standalone_formatRe(locale_weekdays),
      weekdayLookup = standalone_formatLookup(locale_weekdays),
      shortWeekdayRe = standalone_formatRe(locale_shortWeekdays),
      shortWeekdayLookup = standalone_formatLookup(locale_shortWeekdays),
      monthRe = standalone_formatRe(locale_months),
      monthLookup = standalone_formatLookup(locale_months),
      shortMonthRe = standalone_formatRe(locale_shortMonths),
      shortMonthLookup = standalone_formatLookup(locale_shortMonths);

  var formats = {
    "a": formatShortWeekday,
    "A": formatWeekday,
    "b": formatShortMonth,
    "B": formatMonth,
    "c": null,
    "d": standalone_formatDayOfMonth,
    "e": standalone_formatDayOfMonth,
    "f": standalone_formatMicroseconds,
    "g": standalone_formatYearISO,
    "G": standalone_formatFullYearISO,
    "H": standalone_formatHour24,
    "I": standalone_formatHour12,
    "j": standalone_formatDayOfYear,
    "L": standalone_formatMilliseconds,
    "m": standalone_formatMonthNumber,
    "M": standalone_formatMinutes,
    "p": formatPeriod,
    "q": formatQuarter,
    "Q": standalone_formatUnixTimestamp,
    "s": standalone_formatUnixTimestampSeconds,
    "S": standalone_formatSeconds,
    "u": standalone_formatWeekdayNumberMonday,
    "U": standalone_formatWeekNumberSunday,
    "V": standalone_formatWeekNumberISO,
    "w": standalone_formatWeekdayNumberSunday,
    "W": standalone_formatWeekNumberMonday,
    "x": null,
    "X": null,
    "y": standalone_locale_formatYear,
    "Y": standalone_formatFullYear,
    "Z": standalone_formatZone,
    "%": standalone_formatLiteralPercent
  };

  var utcFormats = {
    "a": formatUTCShortWeekday,
    "A": formatUTCWeekday,
    "b": formatUTCShortMonth,
    "B": formatUTCMonth,
    "c": null,
    "d": standalone_formatUTCDayOfMonth,
    "e": standalone_formatUTCDayOfMonth,
    "f": standalone_formatUTCMicroseconds,
    "g": standalone_formatUTCYearISO,
    "G": standalone_formatUTCFullYearISO,
    "H": standalone_formatUTCHour24,
    "I": standalone_formatUTCHour12,
    "j": standalone_formatUTCDayOfYear,
    "L": standalone_formatUTCMilliseconds,
    "m": standalone_formatUTCMonthNumber,
    "M": standalone_formatUTCMinutes,
    "p": formatUTCPeriod,
    "q": formatUTCQuarter,
    "Q": standalone_formatUnixTimestamp,
    "s": standalone_formatUnixTimestampSeconds,
    "S": standalone_formatUTCSeconds,
    "u": standalone_formatUTCWeekdayNumberMonday,
    "U": standalone_formatUTCWeekNumberSunday,
    "V": standalone_formatUTCWeekNumberISO,
    "w": standalone_formatUTCWeekdayNumberSunday,
    "W": standalone_formatUTCWeekNumberMonday,
    "x": null,
    "X": null,
    "y": standalone_formatUTCYear,
    "Y": standalone_formatUTCFullYear,
    "Z": standalone_formatUTCZone,
    "%": standalone_formatLiteralPercent
  };

  var parses = {
    "a": parseShortWeekday,
    "A": parseWeekday,
    "b": parseShortMonth,
    "B": parseMonth,
    "c": parseLocaleDateTime,
    "d": standalone_parseDayOfMonth,
    "e": standalone_parseDayOfMonth,
    "f": standalone_parseMicroseconds,
    "g": standalone_parseYear,
    "G": standalone_parseFullYear,
    "H": standalone_parseHour24,
    "I": standalone_parseHour24,
    "j": standalone_parseDayOfYear,
    "L": standalone_parseMilliseconds,
    "m": standalone_parseMonthNumber,
    "M": standalone_parseMinutes,
    "p": parsePeriod,
    "q": standalone_parseQuarter,
    "Q": standalone_parseUnixTimestamp,
    "s": standalone_parseUnixTimestampSeconds,
    "S": standalone_parseSeconds,
    "u": standalone_parseWeekdayNumberMonday,
    "U": standalone_parseWeekNumberSunday,
    "V": standalone_parseWeekNumberISO,
    "w": standalone_parseWeekdayNumberSunday,
    "W": standalone_parseWeekNumberMonday,
    "x": parseLocaleDate,
    "X": parseLocaleTime,
    "y": standalone_parseYear,
    "Y": standalone_parseFullYear,
    "Z": standalone_parseZone,
    "%": standalone_parseLiteralPercent
  };

  // These recursive directive definitions must be deferred.
  formats.x = newFormat(locale_date, formats);
  formats.X = newFormat(locale_time, formats);
  formats.c = newFormat(locale_dateTime, formats);
  utcFormats.x = newFormat(locale_date, utcFormats);
  utcFormats.X = newFormat(locale_time, utcFormats);
  utcFormats.c = newFormat(locale_dateTime, utcFormats);

  function newFormat(specifier, formats) {
    return function(date) {
      var string = [],
          i = -1,
          j = 0,
          n = specifier.length,
          c,
          pad,
          format;

      if (!(date instanceof Date)) date = new Date(+date);

      while (++i < n) {
        if (specifier.charCodeAt(i) === 37) {
          string.push(specifier.slice(j, i));
          if ((pad = standalone_pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);
          else pad = c === "e" ? " " : "0";
          if (format = formats[c]) c = format(date, pad);
          string.push(c);
          j = i + 1;
        }
      }

      string.push(specifier.slice(j, i));
      return string.join("");
    };
  }

  function newParse(specifier, Z) {
    return function(string) {
      var d = standalone_newDate(1900, undefined, 1),
          i = parseSpecifier(d, specifier, string += "", 0),
          week, day;
      if (i != string.length) return null;

      // If a UNIX timestamp is specified, return it.
      if ("Q" in d) return new Date(d.Q);
      if ("s" in d) return new Date(d.s * 1000 + ("L" in d ? d.L : 0));

      // If this is utcParse, never use the local timezone.
      if (Z && !("Z" in d)) d.Z = 0;

      // The am-pm flag is 0 for AM, and 1 for PM.
      if ("p" in d) d.H = d.H % 12 + d.p * 12;

      // If the month was not specified, inherit from the quarter.
      if (d.m === undefined) d.m = "q" in d ? d.q : 0;

      // Convert day-of-week and week-of-year to day-of-year.
      if ("V" in d) {
        if (d.V < 1 || d.V > 53) return null;
        if (!("w" in d)) d.w = 1;
        if ("Z" in d) {
          week = standalone_locale_utcDate(standalone_newDate(d.y, 0, 1)), day = week.getUTCDay();
          week = day > 4 || day === 0 ? standalone_utcMonday.ceil(week) : standalone_utcMonday(week);
          week = standalone_utcDay.offset(week, (d.V - 1) * 7);
          d.y = week.getUTCFullYear();
          d.m = week.getUTCMonth();
          d.d = week.getUTCDate() + (d.w + 6) % 7;
        } else {
          week = standalone_locale_localDate(standalone_newDate(d.y, 0, 1)), day = week.getDay();
          week = day > 4 || day === 0 ? standalone_timeMonday.ceil(week) : standalone_timeMonday(week);
          week = standalone_timeDay.offset(week, (d.V - 1) * 7);
          d.y = week.getFullYear();
          d.m = week.getMonth();
          d.d = week.getDate() + (d.w + 6) % 7;
        }
      } else if ("W" in d || "U" in d) {
        if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
        day = "Z" in d ? standalone_locale_utcDate(standalone_newDate(d.y, 0, 1)).getUTCDay() : standalone_locale_localDate(standalone_newDate(d.y, 0, 1)).getDay();
        d.m = 0;
        d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;
      }

      // If a time zone is specified, all fields are interpreted as UTC and then
      // offset according to the specified time zone.
      if ("Z" in d) {
        d.H += d.Z / 100 | 0;
        d.M += d.Z % 100;
        return standalone_locale_utcDate(d);
      }

      // Otherwise, all fields are in local time.
      return standalone_locale_localDate(d);
    };
  }

  function parseSpecifier(d, specifier, string, j) {
    var i = 0,
        n = specifier.length,
        m = string.length,
        c,
        parse;

    while (i < n) {
      if (j >= m) return -1;
      c = specifier.charCodeAt(i++);
      if (c === 37) {
        c = specifier.charAt(i++);
        parse = parses[c in standalone_pads ? specifier.charAt(i++) : c];
        if (!parse || ((j = parse(d, string, j)) < 0)) return -1;
      } else if (c != string.charCodeAt(j++)) {
        return -1;
      }
    }

    return j;
  }

  function parsePeriod(d, string, i) {
    var n = periodRe.exec(string.slice(i));
    return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }

  function parseShortWeekday(d, string, i) {
    var n = shortWeekdayRe.exec(string.slice(i));
    return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }

  function parseWeekday(d, string, i) {
    var n = weekdayRe.exec(string.slice(i));
    return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }

  function parseShortMonth(d, string, i) {
    var n = shortMonthRe.exec(string.slice(i));
    return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }

  function parseMonth(d, string, i) {
    var n = monthRe.exec(string.slice(i));
    return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }

  function parseLocaleDateTime(d, string, i) {
    return parseSpecifier(d, locale_dateTime, string, i);
  }

  function parseLocaleDate(d, string, i) {
    return parseSpecifier(d, locale_date, string, i);
  }

  function parseLocaleTime(d, string, i) {
    return parseSpecifier(d, locale_time, string, i);
  }

  function formatShortWeekday(d) {
    return locale_shortWeekdays[d.getDay()];
  }

  function formatWeekday(d) {
    return locale_weekdays[d.getDay()];
  }

  function formatShortMonth(d) {
    return locale_shortMonths[d.getMonth()];
  }

  function formatMonth(d) {
    return locale_months[d.getMonth()];
  }

  function formatPeriod(d) {
    return locale_periods[+(d.getHours() >= 12)];
  }

  function formatQuarter(d) {
    return 1 + ~~(d.getMonth() / 3);
  }

  function formatUTCShortWeekday(d) {
    return locale_shortWeekdays[d.getUTCDay()];
  }

  function formatUTCWeekday(d) {
    return locale_weekdays[d.getUTCDay()];
  }

  function formatUTCShortMonth(d) {
    return locale_shortMonths[d.getUTCMonth()];
  }

  function formatUTCMonth(d) {
    return locale_months[d.getUTCMonth()];
  }

  function formatUTCPeriod(d) {
    return locale_periods[+(d.getUTCHours() >= 12)];
  }

  function formatUTCQuarter(d) {
    return 1 + ~~(d.getUTCMonth() / 3);
  }

  return {
    format: function(specifier) {
      var f = newFormat(specifier += "", formats);
      f.toString = function() { return specifier; };
      return f;
    },
    parse: function(specifier) {
      var p = newParse(specifier += "", false);
      p.toString = function() { return specifier; };
      return p;
    },
    utcFormat: function(specifier) {
      var f = newFormat(specifier += "", utcFormats);
      f.toString = function() { return specifier; };
      return f;
    },
    utcParse: function(specifier) {
      var p = newParse(specifier += "", true);
      p.toString = function() { return specifier; };
      return p;
    }
  };
}

var standalone_pads = {"-": "", "_": " ", "0": "0"},
    standalone_numberRe = /^\s*\d+/, // note: ignores next directive
    standalone_percentRe = /^%/,
    standalone_requoteRe = /[\\^$*+?|[\]().{}]/g;

function standalone_locale_pad(value, fill, width) {
  var sign = value < 0 ? "-" : "",
      string = (sign ? -value : value) + "",
      length = string.length;
  return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
}

function standalone_requote(s) {
  return s.replace(standalone_requoteRe, "\\$&");
}

function standalone_formatRe(names) {
  return new RegExp("^(?:" + names.map(standalone_requote).join("|") + ")", "i");
}

function standalone_formatLookup(names) {
  return new Map(names.map((name, i) => [name.toLowerCase(), i]));
}

function standalone_parseWeekdayNumberSunday(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 1));
  return n ? (d.w = +n[0], i + n[0].length) : -1;
}

function standalone_parseWeekdayNumberMonday(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 1));
  return n ? (d.u = +n[0], i + n[0].length) : -1;
}

function standalone_parseWeekNumberSunday(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 2));
  return n ? (d.U = +n[0], i + n[0].length) : -1;
}

function standalone_parseWeekNumberISO(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 2));
  return n ? (d.V = +n[0], i + n[0].length) : -1;
}

function standalone_parseWeekNumberMonday(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 2));
  return n ? (d.W = +n[0], i + n[0].length) : -1;
}

function standalone_parseFullYear(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 4));
  return n ? (d.y = +n[0], i + n[0].length) : -1;
}

function standalone_parseYear(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 2));
  return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;
}

function standalone_parseZone(d, string, i) {
  var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6));
  return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}

function standalone_parseQuarter(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 1));
  return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;
}

function standalone_parseMonthNumber(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 2));
  return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}

function standalone_parseDayOfMonth(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 2));
  return n ? (d.d = +n[0], i + n[0].length) : -1;
}

function standalone_parseDayOfYear(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 3));
  return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}

function standalone_parseHour24(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 2));
  return n ? (d.H = +n[0], i + n[0].length) : -1;
}

function standalone_parseMinutes(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 2));
  return n ? (d.M = +n[0], i + n[0].length) : -1;
}

function standalone_parseSeconds(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 2));
  return n ? (d.S = +n[0], i + n[0].length) : -1;
}

function standalone_parseMilliseconds(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 3));
  return n ? (d.L = +n[0], i + n[0].length) : -1;
}

function standalone_parseMicroseconds(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i, i + 6));
  return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;
}

function standalone_parseLiteralPercent(d, string, i) {
  var n = standalone_percentRe.exec(string.slice(i, i + 1));
  return n ? i + n[0].length : -1;
}

function standalone_parseUnixTimestamp(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i));
  return n ? (d.Q = +n[0], i + n[0].length) : -1;
}

function standalone_parseUnixTimestampSeconds(d, string, i) {
  var n = standalone_numberRe.exec(string.slice(i));
  return n ? (d.s = +n[0], i + n[0].length) : -1;
}

function standalone_formatDayOfMonth(d, p) {
  return standalone_locale_pad(d.getDate(), p, 2);
}

function standalone_formatHour24(d, p) {
  return standalone_locale_pad(d.getHours(), p, 2);
}

function standalone_formatHour12(d, p) {
  return standalone_locale_pad(d.getHours() % 12 || 12, p, 2);
}

function standalone_formatDayOfYear(d, p) {
  return standalone_locale_pad(1 + standalone_timeDay.count(standalone_timeYear(d), d), p, 3);
}

function standalone_formatMilliseconds(d, p) {
  return standalone_locale_pad(d.getMilliseconds(), p, 3);
}

function standalone_formatMicroseconds(d, p) {
  return standalone_formatMilliseconds(d, p) + "000";
}

function standalone_formatMonthNumber(d, p) {
  return standalone_locale_pad(d.getMonth() + 1, p, 2);
}

function standalone_formatMinutes(d, p) {
  return standalone_locale_pad(d.getMinutes(), p, 2);
}

function standalone_formatSeconds(d, p) {
  return standalone_locale_pad(d.getSeconds(), p, 2);
}

function standalone_formatWeekdayNumberMonday(d) {
  var day = d.getDay();
  return day === 0 ? 7 : day;
}

function standalone_formatWeekNumberSunday(d, p) {
  return standalone_locale_pad(standalone_timeSunday.count(standalone_timeYear(d) - 1, d), p, 2);
}

function standalone_dISO(d) {
  var day = d.getDay();
  return (day >= 4 || day === 0) ? standalone_timeThursday(d) : standalone_timeThursday.ceil(d);
}

function standalone_formatWeekNumberISO(d, p) {
  d = standalone_dISO(d);
  return standalone_locale_pad(standalone_timeThursday.count(standalone_timeYear(d), d) + (standalone_timeYear(d).getDay() === 4), p, 2);
}

function standalone_formatWeekdayNumberSunday(d) {
  return d.getDay();
}

function standalone_formatWeekNumberMonday(d, p) {
  return standalone_locale_pad(standalone_timeMonday.count(standalone_timeYear(d) - 1, d), p, 2);
}

function standalone_locale_formatYear(d, p) {
  return standalone_locale_pad(d.getFullYear() % 100, p, 2);
}

function standalone_formatYearISO(d, p) {
  d = standalone_dISO(d);
  return standalone_locale_pad(d.getFullYear() % 100, p, 2);
}

function standalone_formatFullYear(d, p) {
  return standalone_locale_pad(d.getFullYear() % 10000, p, 4);
}

function standalone_formatFullYearISO(d, p) {
  var day = d.getDay();
  d = (day >= 4 || day === 0) ? standalone_timeThursday(d) : standalone_timeThursday.ceil(d);
  return standalone_locale_pad(d.getFullYear() % 10000, p, 4);
}

function standalone_formatZone(d) {
  var z = d.getTimezoneOffset();
  return (z > 0 ? "-" : (z *= -1, "+"))
      + standalone_locale_pad(z / 60 | 0, "0", 2)
      + standalone_locale_pad(z % 60, "0", 2);
}

function standalone_formatUTCDayOfMonth(d, p) {
  return standalone_locale_pad(d.getUTCDate(), p, 2);
}

function standalone_formatUTCHour24(d, p) {
  return standalone_locale_pad(d.getUTCHours(), p, 2);
}

function standalone_formatUTCHour12(d, p) {
  return standalone_locale_pad(d.getUTCHours() % 12 || 12, p, 2);
}

function standalone_formatUTCDayOfYear(d, p) {
  return standalone_locale_pad(1 + standalone_utcDay.count(standalone_utcYear(d), d), p, 3);
}

function standalone_formatUTCMilliseconds(d, p) {
  return standalone_locale_pad(d.getUTCMilliseconds(), p, 3);
}

function standalone_formatUTCMicroseconds(d, p) {
  return standalone_formatUTCMilliseconds(d, p) + "000";
}

function standalone_formatUTCMonthNumber(d, p) {
  return standalone_locale_pad(d.getUTCMonth() + 1, p, 2);
}

function standalone_formatUTCMinutes(d, p) {
  return standalone_locale_pad(d.getUTCMinutes(), p, 2);
}

function standalone_formatUTCSeconds(d, p) {
  return standalone_locale_pad(d.getUTCSeconds(), p, 2);
}

function standalone_formatUTCWeekdayNumberMonday(d) {
  var dow = d.getUTCDay();
  return dow === 0 ? 7 : dow;
}

function standalone_formatUTCWeekNumberSunday(d, p) {
  return standalone_locale_pad(standalone_utcSunday.count(standalone_utcYear(d) - 1, d), p, 2);
}

function standalone_UTCdISO(d) {
  var day = d.getUTCDay();
  return (day >= 4 || day === 0) ? standalone_utcThursday(d) : standalone_utcThursday.ceil(d);
}

function standalone_formatUTCWeekNumberISO(d, p) {
  d = standalone_UTCdISO(d);
  return standalone_locale_pad(standalone_utcThursday.count(standalone_utcYear(d), d) + (standalone_utcYear(d).getUTCDay() === 4), p, 2);
}

function standalone_formatUTCWeekdayNumberSunday(d) {
  return d.getUTCDay();
}

function standalone_formatUTCWeekNumberMonday(d, p) {
  return standalone_locale_pad(standalone_utcMonday.count(standalone_utcYear(d) - 1, d), p, 2);
}

function standalone_formatUTCYear(d, p) {
  return standalone_locale_pad(d.getUTCFullYear() % 100, p, 2);
}

function standalone_formatUTCYearISO(d, p) {
  d = standalone_UTCdISO(d);
  return standalone_locale_pad(d.getUTCFullYear() % 100, p, 2);
}

function standalone_formatUTCFullYear(d, p) {
  return standalone_locale_pad(d.getUTCFullYear() % 10000, p, 4);
}

function standalone_formatUTCFullYearISO(d, p) {
  var day = d.getUTCDay();
  d = (day >= 4 || day === 0) ? standalone_utcThursday(d) : standalone_utcThursday.ceil(d);
  return standalone_locale_pad(d.getUTCFullYear() % 10000, p, 4);
}

function standalone_formatUTCZone() {
  return "+0000";
}

function standalone_formatLiteralPercent() {
  return "%";
}

function standalone_formatUnixTimestamp(d) {
  return +d;
}

function standalone_formatUnixTimestampSeconds(d) {
  return Math.floor(+d / 1000);
}

;// ../../node_modules/d3-time-format/src/defaultLocale.js


var standalone_src_defaultLocale_locale;
var standalone_timeFormat;
var standalone_timeParse;
var standalone_utcFormat;
var standalone_utcParse;

standalone_defaultLocale_defaultLocale({
  dateTime: "%x, %X",
  date: "%-m/%-d/%Y",
  time: "%-I:%M:%S %p",
  periods: ["AM", "PM"],
  days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});

function standalone_defaultLocale_defaultLocale(definition) {
  standalone_src_defaultLocale_locale = standalone_formatLocale(definition);
  standalone_timeFormat = standalone_src_defaultLocale_locale.format;
  standalone_timeParse = standalone_src_defaultLocale_locale.parse;
  standalone_utcFormat = standalone_src_defaultLocale_locale.utcFormat;
  standalone_utcParse = standalone_src_defaultLocale_locale.utcParse;
  return standalone_src_defaultLocale_locale;
}

;// ../../node_modules/vega-format/build/vega-format.module.js






function standalone_memoize (method) {
  const cache = {};
  return spec => cache[spec] || (cache[spec] = method(spec));
}

function standalone_trimZeroes(numberFormat, decimalChar) {
  return x => {
    const str = numberFormat(x),
      dec = str.indexOf(decimalChar);
    if (dec < 0) return str;
    let idx = standalone_rightmostDigit(str, dec);
    const end = idx < str.length ? str.slice(idx) : '';
    while (--idx > dec) if (str[idx] !== '0') {
      ++idx;
      break;
    }
    return str.slice(0, idx) + end;
  };
}
function standalone_rightmostDigit(str, dec) {
  let i = str.lastIndexOf('e'),
    c;
  if (i > 0) return i;
  for (i = str.length; --i > dec;) {
    c = str.charCodeAt(i);
    if (c >= 48 && c <= 57) return i + 1; // is digit
  }
}
function standalone_numberLocale(locale) {
  const format = standalone_memoize(locale.format),
    formatPrefix = locale.formatPrefix;
  return {
    format,
    formatPrefix,
    formatFloat(spec) {
      const s = standalone_formatSpecifier(spec || ',');
      if (s.precision == null) {
        s.precision = 12;
        switch (s.type) {
          case '%':
            s.precision -= 2;
            break;
          case 'e':
            s.precision -= 1;
            break;
        }
        return standalone_trimZeroes(format(s),
        // number format
        format('.1f')(1)[1] // decimal point character
        );
      } else {
        return format(s);
      }
    },
    formatSpan(start, stop, count, specifier) {
      specifier = standalone_formatSpecifier(specifier == null ? ',f' : specifier);
      const step = standalone_tickStep(start, stop, count),
        value = Math.max(Math.abs(start), Math.abs(stop));
      let precision;
      if (specifier.precision == null) {
        switch (specifier.type) {
          case 's':
            {
              if (!isNaN(precision = standalone_precisionPrefix(step, value))) {
                specifier.precision = precision;
              }
              return formatPrefix(specifier, value);
            }
          case '':
          case 'e':
          case 'g':
          case 'p':
          case 'r':
            {
              if (!isNaN(precision = standalone_precisionRound(step, value))) {
                specifier.precision = precision - (specifier.type === 'e');
              }
              break;
            }
          case 'f':
          case '%':
            {
              if (!isNaN(precision = standalone_precisionFixed(step))) {
                specifier.precision = precision - (specifier.type === '%') * 2;
              }
              break;
            }
        }
      }
      return format(specifier);
    }
  };
}
let standalone_defaultNumberLocale;
standalone_resetNumberFormatDefaultLocale();
function standalone_resetNumberFormatDefaultLocale() {
  return standalone_defaultNumberLocale = standalone_numberLocale({
    format: standalone_format,
    formatPrefix: standalone_formatPrefix
  });
}
function standalone_numberFormatLocale(definition) {
  return standalone_numberLocale(standalone_locale(definition));
}
function standalone_numberFormatDefaultLocale(definition) {
  return arguments.length ? standalone_defaultNumberLocale = standalone_numberFormatLocale(definition) : standalone_defaultNumberLocale;
}

function standalone_timeMultiFormat(format, interval, spec) {
  spec = spec || {};
  if (!standalone_vega_util_module_isObject(spec)) {
    standalone_vega_util_module_error(`Invalid time multi-format specifier: ${spec}`);
  }
  const second = interval(standalone_SECONDS),
    minute = interval(standalone_MINUTES),
    hour = interval(standalone_HOURS),
    day = interval(standalone_DATE),
    week = interval(standalone_WEEK),
    month = interval(standalone_MONTH),
    quarter = interval(standalone_QUARTER),
    year = interval(standalone_YEAR),
    L = format(spec[standalone_MILLISECONDS] || '.%L'),
    S = format(spec[standalone_SECONDS] || ':%S'),
    M = format(spec[standalone_MINUTES] || '%I:%M'),
    H = format(spec[standalone_HOURS] || '%I %p'),
    d = format(spec[standalone_DATE] || spec[standalone_DAY] || '%a %d'),
    w = format(spec[standalone_WEEK] || '%b %d'),
    m = format(spec[standalone_MONTH] || '%B'),
    q = format(spec[standalone_QUARTER] || '%B'),
    y = format(spec[standalone_YEAR] || '%Y');
  return date => (second(date) < date ? L : minute(date) < date ? S : hour(date) < date ? M : day(date) < date ? H : month(date) < date ? week(date) < date ? d : w : year(date) < date ? quarter(date) < date ? m : q : y)(date);
}
function standalone_timeLocale(locale) {
  const timeFormat = standalone_memoize(locale.format),
    utcFormat = standalone_memoize(locale.utcFormat);
  return {
    timeFormat: spec => standalone_vega_util_module_isString(spec) ? timeFormat(spec) : standalone_timeMultiFormat(timeFormat, standalone_vega_time_module_timeInterval, spec),
    utcFormat: spec => standalone_vega_util_module_isString(spec) ? utcFormat(spec) : standalone_timeMultiFormat(utcFormat, standalone_utcInterval, spec),
    timeParse: standalone_memoize(locale.parse),
    utcParse: standalone_memoize(locale.utcParse)
  };
}
let standalone_defaultTimeLocale;
standalone_resetTimeFormatDefaultLocale();
function standalone_resetTimeFormatDefaultLocale() {
  return standalone_defaultTimeLocale = standalone_timeLocale({
    format: standalone_timeFormat,
    parse: standalone_timeParse,
    utcFormat: standalone_utcFormat,
    utcParse: standalone_utcParse
  });
}
function standalone_timeFormatLocale(definition) {
  return standalone_timeLocale(standalone_formatLocale(definition));
}
function standalone_timeFormatDefaultLocale(definition) {
  return arguments.length ? standalone_defaultTimeLocale = standalone_timeFormatLocale(definition) : standalone_defaultTimeLocale;
}

const standalone_createLocale = (number, time) => standalone_extend({}, number, time);
function standalone_vega_format_module_locale(numberSpec, timeSpec) {
  const number = numberSpec ? standalone_numberFormatLocale(numberSpec) : standalone_numberFormatDefaultLocale();
  const time = timeSpec ? standalone_timeFormatLocale(timeSpec) : standalone_timeFormatDefaultLocale();
  return standalone_createLocale(number, time);
}
function standalone_vega_format_module_defaultLocale(numberSpec, timeSpec) {
  const args = arguments.length;
  if (args && args !== 2) {
    standalone_vega_util_module_error('defaultLocale expects either zero or two arguments.');
  }
  return args ? standalone_createLocale(standalone_numberFormatDefaultLocale(numberSpec), standalone_timeFormatDefaultLocale(timeSpec)) : standalone_createLocale(standalone_numberFormatDefaultLocale(), standalone_timeFormatDefaultLocale());
}
function standalone_resetDefaultLocale() {
  standalone_resetNumberFormatDefaultLocale();
  standalone_resetTimeFormatDefaultLocale();
  return standalone_vega_format_module_defaultLocale();
}



;// ../../node_modules/vega-loader/build/vega-loader.browser.module.js





// Matches absolute URLs with optional protocol
//   https://...    file://...    //...
const standalone_protocol_re = /^(data:|([A-Za-z]+:)?\/\/)/;

// Matches allowed URIs. From https://github.com/cure53/DOMPurify/blob/master/src/regexp.js with added file://
const standalone_allowed_re = /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|file|data):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i; // eslint-disable-line no-useless-escape
const standalone_whitespace_re = /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g; // eslint-disable-line no-control-regex

// Special treatment in node.js for the file: protocol
const standalone_fileProtocol = 'file://';

/**
 * Factory for a loader constructor that provides methods for requesting
 * files from either the network or disk, and for sanitizing request URIs.
 * @param {function} fetch - The Fetch API for HTTP network requests.
 *   If null or undefined, HTTP loading will be disabled.
 * @param {object} fs - The file system interface for file loading.
 *   If null or undefined, local file loading will be disabled.
 * @return {function} A loader constructor with the following signature:
 *   param {object} [options] - Optional default loading options to use.
 *   return {object} - A new loader instance.
 */
function standalone_loaderFactory (fetch, fs) {
  return options => ({
    options: options || {},
    sanitize: standalone_sanitize,
    load: standalone_load,
    fileAccess: !!fs,
    file: standalone_fileLoader(fs),
    http: standalone_httpLoader(fetch)
  });
}

/**
 * Load an external resource, typically either from the web or from the local
 * filesystem. This function uses {@link sanitize} to first sanitize the uri,
 * then calls either {@link http} (for web requests) or {@link file} (for
 * filesystem loading).
 * @param {string} uri - The resource indicator (e.g., URL or filename).
 * @param {object} [options] - Optional loading options. These options will
 *   override any existing default options.
 * @return {Promise} - A promise that resolves to the loaded content.
 */
async function standalone_load(uri, options) {
  const opt = await this.sanitize(uri, options),
    url = opt.href;
  return opt.localFile ? this.file(url) : this.http(url, options);
}

/**
 * URI sanitizer function.
 * @param {string} uri - The uri (url or filename) to check.
 * @param {object} options - An options hash.
 * @return {Promise} - A promise that resolves to an object containing
 *  sanitized uri data, or rejects it the input uri is deemed invalid.
 *  The properties of the resolved object are assumed to be
 *  valid attributes for an HTML 'a' tag. The sanitized uri *must* be
 *  provided by the 'href' property of the returned object.
 */
async function standalone_sanitize(uri, options) {
  options = standalone_extend({}, this.options, options);
  const fileAccess = this.fileAccess,
    result = {
      href: null
    };
  let isFile, loadFile, base;
  const isAllowed = standalone_allowed_re.test(uri.replace(standalone_whitespace_re, ''));
  if (uri == null || typeof uri !== 'string' || !isAllowed) {
    standalone_vega_util_module_error('Sanitize failure, invalid URI: ' + standalone_$(uri));
  }
  const hasProtocol = standalone_protocol_re.test(uri);

  // if relative url (no protocol/host), prepend baseURL
  if ((base = options.baseURL) && !hasProtocol) {
    // Ensure that there is a slash between the baseURL (e.g. hostname) and url
    if (!uri.startsWith('/') && !base.endsWith('/')) {
      uri = '/' + uri;
    }
    uri = base + uri;
  }

  // should we load from file system?
  loadFile = (isFile = uri.startsWith(standalone_fileProtocol)) || options.mode === 'file' || options.mode !== 'http' && !hasProtocol && fileAccess;
  if (isFile) {
    // strip file protocol
    uri = uri.slice(standalone_fileProtocol.length);
  } else if (uri.startsWith('//')) {
    if (options.defaultProtocol === 'file') {
      // if is file, strip protocol and set loadFile flag
      uri = uri.slice(2);
      loadFile = true;
    } else {
      // if relative protocol (starts with '//'), prepend default protocol
      uri = (options.defaultProtocol || 'http') + ':' + uri;
    }
  }

  // set non-enumerable mode flag to indicate local file load
  Object.defineProperty(result, 'localFile', {
    value: !!loadFile
  });

  // set uri
  result.href = uri;

  // set default result target, if specified
  if (options.target) {
    result.target = options.target + '';
  }

  // set default result rel, if specified (#1542)
  if (options.rel) {
    result.rel = options.rel + '';
  }

  // provide control over cross-origin image handling (#2238)
  // https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image
  if (options.context === 'image' && options.crossOrigin) {
    result.crossOrigin = options.crossOrigin + '';
  }

  // return
  return result;
}

/**
 * File system loader factory.
 * @param {object} fs - The file system interface.
 * @return {function} - A file loader with the following signature:
 *   param {string} filename - The file system path to load.
 *   param {string} filename - The file system path to load.
 *   return {Promise} A promise that resolves to the file contents.
 */
function standalone_fileLoader(fs) {
  return fs ? filename => new Promise((accept, reject) => {
    fs.readFile(filename, (error, data) => {
      if (error) reject(error);else accept(data);
    });
  }) : standalone_fileReject;
}

/**
 * Default file system loader that simply rejects.
 */
async function standalone_fileReject() {
  standalone_vega_util_module_error('No file system access.');
}

/**
 * HTTP request handler factory.
 * @param {function} fetch - The Fetch API method.
 * @return {function} - An http loader with the following signature:
 *   param {string} url - The url to request.
 *   param {object} options - An options hash.
 *   return {Promise} - A promise that resolves to the file contents.
 */
function standalone_httpLoader(fetch) {
  return fetch ? async function (url, options) {
    const opt = standalone_extend({}, this.options.http, options),
      type = options && options.response,
      response = await fetch(url, opt);
    return !response.ok ? standalone_vega_util_module_error(response.status + '' + response.statusText) : standalone_vega_util_module_isFunction(response[type]) ? response[type]() : response.text();
  } : standalone_httpReject;
}

/**
 * Default http request handler that simply rejects.
 */
async function standalone_httpReject() {
  standalone_vega_util_module_error('No HTTP fetch method available.');
}

const standalone_vega_loader_browser_module_isValid = _ => _ != null && _ === _;
const standalone_vega_loader_browser_module_isBoolean = _ => _ === 'true' || _ === 'false' || _ === true || _ === false;
const standalone_vega_loader_browser_module_isDate = _ => !Number.isNaN(Date.parse(_));
const standalone_vega_loader_browser_module_isNumber = _ => !Number.isNaN(+_) && !(_ instanceof Date);
const standalone_isInteger = _ => standalone_vega_loader_browser_module_isNumber(_) && Number.isInteger(+_);
const standalone_typeParsers = {
  boolean: standalone_toBoolean,
  integer: standalone_toNumber,
  number: standalone_toNumber,
  date: standalone_toDate,
  string: standalone_vega_util_module_toString,
  unknown: standalone_vega_util_module_identity
};
const standalone_typeTests = [standalone_vega_loader_browser_module_isBoolean, standalone_isInteger, standalone_vega_loader_browser_module_isNumber, standalone_vega_loader_browser_module_isDate];
const standalone_typeList = ['boolean', 'integer', 'number', 'date'];
function standalone_inferType(values, field) {
  if (!values || !values.length) return 'unknown';
  const n = values.length,
    m = standalone_typeTests.length,
    a = standalone_typeTests.map((_, i) => i + 1);
  for (let i = 0, t = 0, j, value; i < n; ++i) {
    value = field ? values[i][field] : values[i];
    for (j = 0; j < m; ++j) {
      if (a[j] && standalone_vega_loader_browser_module_isValid(value) && !standalone_typeTests[j](value)) {
        a[j] = 0;
        ++t;
        if (t === standalone_typeTests.length) return 'string';
      }
    }
  }
  return standalone_typeList[a.reduce((u, v) => u === 0 ? v : u, 0) - 1];
}
function standalone_inferTypes(data, fields) {
  return fields.reduce((types, field) => {
    types[field] = standalone_inferType(data, field);
    return types;
  }, {});
}

function standalone_delimitedFormat(delimiter) {
  const parse = function (data, format) {
    const delim = {
      delimiter: delimiter
    };
    return standalone_vega_loader_browser_module_dsv(data, format ? standalone_extend(format, delim) : delim);
  };
  parse.responseType = 'text';
  return parse;
}
function standalone_vega_loader_browser_module_dsv(data, format) {
  if (format.header) {
    data = format.header.map(standalone_$).join(format.delimiter) + '\n' + data;
  }
  return standalone_dsv(format.delimiter).parse(data + '');
}
standalone_vega_loader_browser_module_dsv.responseType = 'text';

function standalone_isBuffer(_) {
  return typeof Buffer === 'function' && standalone_vega_util_module_isFunction(Buffer.isBuffer) ? Buffer.isBuffer(_) : false;
}
function standalone_json(data, format) {
  const prop = format && format.property ? standalone_field(format.property) : standalone_vega_util_module_identity;
  return standalone_vega_util_module_isObject(data) && !standalone_isBuffer(data) ? standalone_parseJSON(prop(data), format) : prop(JSON.parse(data));
}
standalone_json.responseType = 'json';
function standalone_parseJSON(data, format) {
  if (!standalone_vega_util_module_isArray(data) && standalone_isIterable(data)) {
    data = [...data];
  }
  return format && format.copy ? JSON.parse(JSON.stringify(data)) : data;
}

const standalone_filters = {
  interior: (a, b) => a !== b,
  exterior: (a, b) => a === b
};
function standalone_topojson(data, format) {
  let method, object, property, filter;
  data = standalone_json(data, format);
  if (format && format.feature) {
    method = standalone_feature;
    property = format.feature;
  } else if (format && format.mesh) {
    method = standalone_mesh;
    property = format.mesh;
    filter = standalone_filters[format.filter];
  } else {
    standalone_vega_util_module_error('Missing TopoJSON feature or mesh parameter.');
  }
  object = (object = data.objects[property]) ? method(data, object, filter) : standalone_vega_util_module_error('Invalid TopoJSON object: ' + property);
  return object && object.features || [object];
}
standalone_topojson.responseType = 'json';

const standalone_vega_loader_browser_module_format = {
  dsv: standalone_vega_loader_browser_module_dsv,
  csv: standalone_delimitedFormat(','),
  tsv: standalone_delimitedFormat('\t'),
  json: standalone_json,
  topojson: standalone_topojson
};
function standalone_formats(name, reader) {
  if (arguments.length > 1) {
    standalone_vega_loader_browser_module_format[name] = reader;
    return this;
  } else {
    return standalone_vega_util_module_has(standalone_vega_loader_browser_module_format, name) ? standalone_vega_loader_browser_module_format[name] : null;
  }
}
function standalone_responseType(type) {
  const f = standalone_formats(type);
  return f && f.responseType || 'text';
}

function standalone_read (data, schema, timeParser, utcParser) {
  schema = schema || {};
  const reader = standalone_formats(schema.type || 'json');
  if (!reader) standalone_vega_util_module_error('Unknown data format type: ' + schema.type);
  data = reader(data, schema);
  if (schema.parse) standalone_parse(data, schema.parse, timeParser, utcParser);
  if (standalone_vega_util_module_has(data, 'columns')) delete data.columns;
  return data;
}
function standalone_parse(data, types, timeParser, utcParser) {
  if (!data.length) return; // early exit for empty data

  const locale = standalone_timeFormatDefaultLocale();
  timeParser = timeParser || locale.timeParse;
  utcParser = utcParser || locale.utcParse;
  let fields = data.columns || Object.keys(data[0]),
    datum,
    field,
    i,
    j,
    n,
    m;
  if (types === 'auto') types = standalone_inferTypes(data, fields);
  fields = Object.keys(types);
  const parsers = fields.map(field => {
    const type = types[field];
    let parts, pattern;
    if (type && (type.startsWith('date:') || type.startsWith('utc:'))) {
      parts = type.split(/:(.+)?/, 2); // split on first :
      pattern = parts[1];
      if (pattern[0] === '\'' && pattern[pattern.length - 1] === '\'' || pattern[0] === '"' && pattern[pattern.length - 1] === '"') {
        pattern = pattern.slice(1, -1);
      }
      const parse = parts[0] === 'utc' ? utcParser : timeParser;
      return parse(pattern);
    }
    if (!standalone_typeParsers[type]) {
      throw Error('Illegal format pattern: ' + field + ':' + type);
    }
    return standalone_typeParsers[type];
  });
  for (i = 0, n = data.length, m = fields.length; i < n; ++i) {
    datum = data[i];
    for (j = 0; j < m; ++j) {
      field = fields[j];
      datum[field] = parsers[j](datum[field]);
    }
  }
}

const standalone_loader = standalone_loaderFactory(typeof fetch !== 'undefined' && fetch,
// use built-in fetch API
null // no file system access
);



;// ../../node_modules/vega-dataflow/build/vega-dataflow.module.js




function standalone_UniqueList(idFunc) {
  const $ = idFunc || standalone_vega_util_module_identity,
    list = [],
    ids = {};
  list.add = _ => {
    const id = $(_);
    if (!ids[id]) {
      ids[id] = 1;
      list.push(_);
    }
    return list;
  };
  list.remove = _ => {
    const id = $(_);
    if (ids[id]) {
      ids[id] = 0;
      const idx = list.indexOf(_);
      if (idx >= 0) list.splice(idx, 1);
    }
    return list;
  };
  return list;
}

/**
 * Invoke and await a potentially async callback function. If
 * an error occurs, trap it and route to Dataflow.error.
 * @param {Dataflow} df - The dataflow instance
 * @param {function} callback - A callback function to invoke
 *   and then await. The dataflow will be passed as the single
 *   argument to the function.
 */
async function standalone_asyncCallback (df, callback) {
  try {
    await callback(df);
  } catch (err) {
    df.error(err);
  }
}

const standalone_TUPLE_ID_KEY = Symbol('vega_id');
let standalone_TUPLE_ID = 1;

/**
 * Checks if an input value is a registered tuple.
 * @param {*} t - The value to check.
 * @return {boolean} True if the input is a tuple, false otherwise.
 */
function standalone_isTuple(t) {
  return !!(t && standalone_tupleid(t));
}

/**
 * Returns the id of a tuple.
 * @param {object} t - The input tuple.
 * @return {*} the tuple id.
 */
function standalone_tupleid(t) {
  return t[standalone_TUPLE_ID_KEY];
}

/**
 * Sets the id of a tuple.
 * @param {object} t - The input tuple.
 * @param {*} id - The id value to set.
 * @return {object} the input tuple.
 */
function standalone_setid(t, id) {
  t[standalone_TUPLE_ID_KEY] = id;
  return t;
}

/**
 * Ingest an object or value as a data tuple.
 * If the input value is an object, an id field will be added to it. For
 * efficiency, the input object is modified directly. A copy is not made.
 * If the input value is a literal, it will be wrapped in a new object
 * instance, with the value accessible as the 'data' property.
 * @param datum - The value to ingest.
 * @return {object} The ingested data tuple.
 */
function standalone_ingest$1(datum) {
  const t = datum === Object(datum) ? datum : {
    data: datum
  };
  return standalone_tupleid(t) ? t : standalone_setid(t, standalone_TUPLE_ID++);
}

/**
 * Given a source tuple, return a derived copy.
 * @param {object} t - The source tuple.
 * @return {object} The derived tuple.
 */
function standalone_derive(t) {
  return standalone_rederive(t, standalone_ingest$1({}));
}

/**
 * Rederive a derived tuple by copying values from the source tuple.
 * @param {object} t - The source tuple.
 * @param {object} d - The derived tuple.
 * @return {object} The derived tuple.
 */
function standalone_rederive(t, d) {
  for (const k in t) d[k] = t[k];
  return d;
}

/**
 * Replace an existing tuple with a new tuple.
 * @param {object} t - The existing data tuple.
 * @param {object} d - The new tuple that replaces the old.
 * @return {object} The new tuple.
 */
function standalone_replace(t, d) {
  return standalone_setid(d, standalone_tupleid(t));
}

/**
 * Generate an augmented comparator function that provides stable
 * sorting by tuple id when the given comparator produces ties.
 * @param {function} cmp - The comparator to augment.
 * @param {function} [f] - Optional tuple accessor function.
 * @return {function} An augmented comparator function.
 */
function standalone_stableCompare(cmp, f) {
  return !cmp ? null : f ? (a, b) => cmp(a, b) || standalone_tupleid(f(a)) - standalone_tupleid(f(b)) : (a, b) => cmp(a, b) || standalone_tupleid(a) - standalone_tupleid(b);
}

function standalone_isChangeSet(v) {
  return v && v.constructor === standalone_changeset;
}
function standalone_changeset() {
  const add = [],
    // insert tuples
    rem = [],
    // remove tuples
    mod = [],
    // modify tuples
    remp = [],
    // remove by predicate
    modp = []; // modify by predicate
  let clean = null,
    reflow = false;
  return {
    constructor: standalone_changeset,
    insert(t) {
      const d = standalone_array(t),
        n = d.length;
      for (let i = 0; i < n; ++i) add.push(d[i]);
      return this;
    },
    remove(t) {
      const a = standalone_vega_util_module_isFunction(t) ? remp : rem,
        d = standalone_array(t),
        n = d.length;
      for (let i = 0; i < n; ++i) a.push(d[i]);
      return this;
    },
    modify(t, field, value) {
      const m = {
        field: field,
        value: standalone_vega_util_module_constant(value)
      };
      if (standalone_vega_util_module_isFunction(t)) {
        m.filter = t;
        modp.push(m);
      } else {
        m.tuple = t;
        mod.push(m);
      }
      return this;
    },
    encode(t, set) {
      if (standalone_vega_util_module_isFunction(t)) modp.push({
        filter: t,
        field: set
      });else mod.push({
        tuple: t,
        field: set
      });
      return this;
    },
    clean(value) {
      clean = value;
      return this;
    },
    reflow() {
      reflow = true;
      return this;
    },
    pulse(pulse, tuples) {
      const cur = {},
        out = {};
      let i, n, m, f, t, id;

      // build lookup table of current tuples
      for (i = 0, n = tuples.length; i < n; ++i) {
        cur[standalone_tupleid(tuples[i])] = 1;
      }

      // process individual tuples to remove
      for (i = 0, n = rem.length; i < n; ++i) {
        t = rem[i];
        cur[standalone_tupleid(t)] = -1;
      }

      // process predicate-based removals
      for (i = 0, n = remp.length; i < n; ++i) {
        f = remp[i];
        tuples.forEach(t => {
          if (f(t)) cur[standalone_tupleid(t)] = -1;
        });
      }

      // process all add tuples
      for (i = 0, n = add.length; i < n; ++i) {
        t = add[i];
        id = standalone_tupleid(t);
        if (cur[id]) {
          // tuple already resides in dataset
          // if flagged for both add and remove, cancel
          cur[id] = 1;
        } else {
          // tuple does not reside in dataset, add
          pulse.add.push(standalone_ingest$1(add[i]));
        }
      }

      // populate pulse rem list
      for (i = 0, n = tuples.length; i < n; ++i) {
        t = tuples[i];
        if (cur[standalone_tupleid(t)] < 0) pulse.rem.push(t);
      }

      // modify helper method
      function modify(t, f, v) {
        if (v) {
          t[f] = v(t);
        } else {
          pulse.encode = f;
        }
        if (!reflow) out[standalone_tupleid(t)] = t;
      }

      // process individual tuples to modify
      for (i = 0, n = mod.length; i < n; ++i) {
        m = mod[i];
        t = m.tuple;
        f = m.field;
        id = cur[standalone_tupleid(t)];
        if (id > 0) {
          modify(t, f, m.value);
          pulse.modifies(f);
        }
      }

      // process predicate-based modifications
      for (i = 0, n = modp.length; i < n; ++i) {
        m = modp[i];
        f = m.filter;
        tuples.forEach(t => {
          if (f(t) && cur[standalone_tupleid(t)] > 0) {
            modify(t, m.field, m.value);
          }
        });
        pulse.modifies(m.field);
      }

      // upon reflow request, populate mod with all non-removed tuples
      // otherwise, populate mod with modified tuples only
      if (reflow) {
        pulse.mod = rem.length || remp.length ? tuples.filter(t => cur[standalone_tupleid(t)] > 0) : tuples.slice();
      } else {
        for (id in out) pulse.mod.push(out[id]);
      }

      // set pulse garbage collection request
      if (clean || clean == null && (rem.length || remp.length)) {
        pulse.clean(true);
      }
      return pulse;
    }
  };
}

const standalone_CACHE = '_:mod:_';

/**
 * Hash that tracks modifications to assigned values.
 * Callers *must* use the set method to update values.
 */
function standalone_Parameters() {
  Object.defineProperty(this, standalone_CACHE, {
    writable: true,
    value: {}
  });
}
standalone_Parameters.prototype = {
  /**
   * Set a parameter value. If the parameter value changes, the parameter
   * will be recorded as modified.
   * @param {string} name - The parameter name.
   * @param {number} index - The index into an array-value parameter. Ignored if
   *   the argument is undefined, null or less than zero.
   * @param {*} value - The parameter value to set.
   * @param {boolean} [force=false] - If true, records the parameter as modified
   *   even if the value is unchanged.
   * @return {Parameters} - This parameter object.
   */
  set(name, index, value, force) {
    const o = this,
      v = o[name],
      mod = o[standalone_CACHE];
    if (index != null && index >= 0) {
      if (v[index] !== value || force) {
        v[index] = value;
        mod[index + ':' + name] = -1;
        mod[name] = -1;
      }
    } else if (v !== value || force) {
      o[name] = value;
      mod[name] = standalone_vega_util_module_isArray(value) ? 1 + value.length : -1;
    }
    return o;
  },
  /**
   * Tests if one or more parameters has been modified. If invoked with no
   * arguments, returns true if any parameter value has changed. If the first
   * argument is array, returns trues if any parameter name in the array has
   * changed. Otherwise, tests if the given name and optional array index has
   * changed.
   * @param {string} name - The parameter name to test.
   * @param {number} [index=undefined] - The parameter array index to test.
   * @return {boolean} - Returns true if a queried parameter was modified.
   */
  modified(name, index) {
    const mod = this[standalone_CACHE];
    if (!arguments.length) {
      for (const k in mod) {
        if (mod[k]) return true;
      }
      return false;
    } else if (standalone_vega_util_module_isArray(name)) {
      for (let k = 0; k < name.length; ++k) {
        if (mod[name[k]]) return true;
      }
      return false;
    }
    return index != null && index >= 0 ? index + 1 < mod[name] || !!mod[index + ':' + name] : !!mod[name];
  },
  /**
   * Clears the modification records. After calling this method,
   * all parameters are considered unmodified.
   */
  clear() {
    this[standalone_CACHE] = {};
    return this;
  }
};

let standalone_OP_ID = 0;
const standalone_PULSE = 'pulse',
  standalone_NO_PARAMS = new standalone_Parameters();

// Boolean Flags
const standalone_SKIP$1 = 1,
  standalone_MODIFIED = 2;

/**
 * An Operator is a processing node in a dataflow graph.
 * Each operator stores a value and an optional value update function.
 * Operators can accept a hash of named parameters. Parameter values can
 * either be direct (JavaScript literals, arrays, objects) or indirect
 * (other operators whose values will be pulled dynamically). Operators
 * included as parameters will have this operator added as a dependency.
 * @constructor
 * @param {*} [init] - The initial value for this operator.
 * @param {function(object, Pulse)} [update] - An update function. Upon
 *   evaluation of this operator, the update function will be invoked and the
 *   return value will be used as the new value of this operator.
 * @param {object} [params] - The parameters for this operator.
 * @param {boolean} [react=true] - Flag indicating if this operator should
 *   listen for changes to upstream operators included as parameters.
 * @see parameters
 */
function standalone_Operator(init, update, params, react) {
  this.id = ++standalone_OP_ID;
  this.value = init;
  this.stamp = -1;
  this.rank = -1;
  this.qrank = -1;
  this.flags = 0;
  if (update) {
    this._update = update;
  }
  if (params) this.parameters(params, react);
}
function standalone_flag(bit) {
  return function (state) {
    const f = this.flags;
    if (arguments.length === 0) return !!(f & bit);
    this.flags = state ? f | bit : f & ~bit;
    return this;
  };
}
standalone_Operator.prototype = {
  /**
   * Returns a list of target operators dependent on this operator.
   * If this list does not exist, it is created and then returned.
   * @return {UniqueList}
   */
  targets() {
    return this._targets || (this._targets = standalone_UniqueList(standalone_id));
  },
  /**
   * Sets the value of this operator.
   * @param {*} value - the value to set.
   * @return {Number} Returns 1 if the operator value has changed
   *   according to strict equality, returns 0 otherwise.
   */
  set(value) {
    if (this.value !== value) {
      this.value = value;
      return 1;
    } else {
      return 0;
    }
  },
  /**
   * Indicates that operator evaluation should be skipped on the next pulse.
   * This operator will still propagate incoming pulses, but its update function
   * will not be invoked. The skip flag is reset after every pulse, so calling
   * this method will affect processing of the next pulse only.
   */
  skip: standalone_flag(standalone_SKIP$1),
  /**
   * Indicates that this operator's value has been modified on its most recent
   * pulse. Normally modification is checked via strict equality; however, in
   * some cases it is more efficient to update the internal state of an object.
   * In those cases, the modified flag can be used to trigger propagation. Once
   * set, the modification flag persists across pulses until unset. The flag can
   * be used with the last timestamp to test if a modification is recent.
   */
  modified: standalone_flag(standalone_MODIFIED),
  /**
   * Sets the parameters for this operator. The parameter values are analyzed for
   * operator instances. If found, this operator will be added as a dependency
   * of the parameterizing operator. Operator values are dynamically marshalled
   * from each operator parameter prior to evaluation. If a parameter value is
   * an array, the array will also be searched for Operator instances. However,
   * the search does not recurse into sub-arrays or object properties.
   * @param {object} params - A hash of operator parameters.
   * @param {boolean} [react=true] - A flag indicating if this operator should
   *   automatically update (react) when parameter values change. In other words,
   *   this flag determines if the operator registers itself as a listener on
   *   any upstream operators included in the parameters.
   * @param {boolean} [initonly=false] - A flag indicating if this operator
   *   should calculate an update only upon its initial evaluation, then
   *   deregister dependencies and suppress all future update invocations.
   * @return {Operator[]} - An array of upstream dependencies.
   */
  parameters(params, react, initonly) {
    react = react !== false;
    const argval = this._argval = this._argval || new standalone_Parameters(),
      argops = this._argops = this._argops || [],
      deps = [];
    let name, value, n, i;
    const add = (name, index, value) => {
      if (value instanceof standalone_Operator) {
        if (value !== this) {
          if (react) value.targets().add(this);
          deps.push(value);
        }
        argops.push({
          op: value,
          name: name,
          index: index
        });
      } else {
        argval.set(name, index, value);
      }
    };
    for (name in params) {
      value = params[name];
      if (name === standalone_PULSE) {
        standalone_array(value).forEach(op => {
          if (!(op instanceof standalone_Operator)) {
            standalone_vega_util_module_error('Pulse parameters must be operator instances.');
          } else if (op !== this) {
            op.targets().add(this);
            deps.push(op);
          }
        });
        this.source = value;
      } else if (standalone_vega_util_module_isArray(value)) {
        argval.set(name, -1, Array(n = value.length));
        for (i = 0; i < n; ++i) add(name, i, value[i]);
      } else {
        add(name, -1, value);
      }
    }
    this.marshall().clear(); // initialize values
    if (initonly) argops.initonly = true;
    return deps;
  },
  /**
   * Internal method for marshalling parameter values.
   * Visits each operator dependency to pull the latest value.
   * @return {Parameters} A Parameters object to pass to the update function.
   */
  marshall(stamp) {
    const argval = this._argval || standalone_NO_PARAMS,
      argops = this._argops;
    let item, i, op, mod;
    if (argops) {
      const n = argops.length;
      for (i = 0; i < n; ++i) {
        item = argops[i];
        op = item.op;
        mod = op.modified() && op.stamp === stamp;
        argval.set(item.name, item.index, op.value, mod);
      }
      if (argops.initonly) {
        for (i = 0; i < n; ++i) {
          item = argops[i];
          item.op.targets().remove(this);
        }
        this._argops = null;
        this._update = null;
      }
    }
    return argval;
  },
  /**
   * Detach this operator from the dataflow.
   * Unregisters listeners on upstream dependencies.
   */
  detach() {
    const argops = this._argops;
    let i, n, item, op;
    if (argops) {
      for (i = 0, n = argops.length; i < n; ++i) {
        item = argops[i];
        op = item.op;
        if (op._targets) {
          op._targets.remove(this);
        }
      }
    }

    // remove references to the source and pulse object,
    // if present, to prevent memory leaks of old data.
    this.pulse = null;
    this.source = null;
  },
  /**
   * Delegate method to perform operator processing.
   * Subclasses can override this method to perform custom processing.
   * By default, it marshalls parameters and calls the update function
   * if that function is defined. If the update function does not
   * change the operator value then StopPropagation is returned.
   * If no update function is defined, this method does nothing.
   * @param {Pulse} pulse - the current dataflow pulse.
   * @return The output pulse or StopPropagation. A falsy return value
   *   (including undefined) will let the input pulse pass through.
   */
  evaluate(pulse) {
    const update = this._update;
    if (update) {
      const params = this.marshall(pulse.stamp),
        v = update.call(this, params, pulse);
      params.clear();
      if (v !== this.value) {
        this.value = v;
      } else if (!this.modified()) {
        return pulse.StopPropagation;
      }
    }
  },
  /**
   * Run this operator for the current pulse. If this operator has already
   * been run at (or after) the pulse timestamp, returns StopPropagation.
   * Internally, this method calls {@link evaluate} to perform processing.
   * If {@link evaluate} returns a falsy value, the input pulse is returned.
   * This method should NOT be overridden, instead overrride {@link evaluate}.
   * @param {Pulse} pulse - the current dataflow pulse.
   * @return the output pulse for this operator (or StopPropagation)
   */
  run(pulse) {
    if (pulse.stamp < this.stamp) return pulse.StopPropagation;
    let rv;
    if (this.skip()) {
      this.skip(false);
      rv = 0;
    } else {
      rv = this.evaluate(pulse);
    }
    return this.pulse = rv || pulse;
  }
};

/**
 * Add an operator to the dataflow graph. This function accepts a
 * variety of input argument types. The basic signature supports an
 * initial value, update function and parameters. If the first parameter
 * is an Operator instance, it will be added directly. If it is a
 * constructor for an Operator subclass, a new instance will be instantiated.
 * Otherwise, if the first parameter is a function instance, it will be used
 * as the update function and a null initial value is assumed.
 * @param {*} init - One of: the operator to add, the initial value of
 *   the operator, an operator class to instantiate, or an update function.
 * @param {function} [update] - The operator update function.
 * @param {object} [params] - The operator parameters.
 * @param {boolean} [react=true] - Flag indicating if this operator should
 *   listen for changes to upstream operators included as parameters.
 * @return {Operator} - The added operator.
 */
function standalone_add (init, update, params, react) {
  let shift = 1,
    op;
  if (init instanceof standalone_Operator) {
    op = init;
  } else if (init && init.prototype instanceof standalone_Operator) {
    op = new init();
  } else if (standalone_vega_util_module_isFunction(init)) {
    op = new standalone_Operator(null, init);
  } else {
    shift = 0;
    op = new standalone_Operator(init, update);
  }
  this.rank(op);
  if (shift) {
    react = params;
    params = update;
  }
  if (params) this.connect(op, op.parameters(params, react));
  this.touch(op);
  return op;
}

/**
 * Connect a target operator as a dependent of source operators.
 * If necessary, this method will rerank the target operator and its
 * dependents to ensure propagation proceeds in a topologically sorted order.
 * @param {Operator} target - The target operator.
 * @param {Array<Operator>} - The source operators that should propagate
 *   to the target operator.
 */
function standalone_connect (target, sources) {
  const targetRank = target.rank,
    n = sources.length;
  for (let i = 0; i < n; ++i) {
    if (targetRank < sources[i].rank) {
      this.rerank(target);
      return;
    }
  }
}

let standalone_STREAM_ID = 0;

/**
 * Models an event stream.
 * @constructor
 * @param {function(Object, number): boolean} [filter] - Filter predicate.
 *   Events pass through when truthy, events are suppressed when falsy.
 * @param {function(Object): *} [apply] - Applied to input events to produce
 *   new event values.
 * @param {function(Object)} [receive] - Event callback function to invoke
 *   upon receipt of a new event. Use to override standard event processing.
 */
function standalone_EventStream(filter, apply, receive) {
  this.id = ++standalone_STREAM_ID;
  this.value = null;
  if (receive) this.receive = receive;
  if (filter) this._filter = filter;
  if (apply) this._apply = apply;
}

/**
 * Creates a new event stream instance with the provided
 * (optional) filter, apply and receive functions.
 * @param {function(Object, number): boolean} [filter] - Filter predicate.
 *   Events pass through when truthy, events are suppressed when falsy.
 * @param {function(Object): *} [apply] - Applied to input events to produce
 *   new event values.
 * @see EventStream
 */
function standalone_stream(filter, apply, receive) {
  return new standalone_EventStream(filter, apply, receive);
}
standalone_EventStream.prototype = {
  _filter: standalone_truthy,
  _apply: standalone_vega_util_module_identity,
  targets() {
    return this._targets || (this._targets = standalone_UniqueList(standalone_id));
  },
  consume(_) {
    if (!arguments.length) return !!this._consume;
    this._consume = !!_;
    return this;
  },
  receive(evt) {
    if (this._filter(evt)) {
      const val = this.value = this._apply(evt),
        trg = this._targets,
        n = trg ? trg.length : 0;
      for (let i = 0; i < n; ++i) trg[i].receive(val);
      if (this._consume) {
        evt.preventDefault();
        evt.stopPropagation();
      }
    }
  },
  filter(filter) {
    const s = standalone_stream(filter);
    this.targets().add(s);
    return s;
  },
  apply(apply) {
    const s = standalone_stream(null, apply);
    this.targets().add(s);
    return s;
  },
  merge() {
    const s = standalone_stream();
    this.targets().add(s);
    for (let i = 0, n = arguments.length; i < n; ++i) {
      arguments[i].targets().add(s);
    }
    return s;
  },
  throttle(pause) {
    let t = -1;
    return this.filter(() => {
      const now = Date.now();
      if (now - t > pause) {
        t = now;
        return 1;
      } else {
        return 0;
      }
    });
  },
  debounce(delay) {
    const s = standalone_stream();
    this.targets().add(standalone_stream(null, null, standalone_debounce(delay, e => {
      const df = e.dataflow;
      s.receive(e);
      if (df && df.run) df.run();
    })));
    return s;
  },
  between(a, b) {
    let active = false;
    a.targets().add(standalone_stream(null, null, () => active = true));
    b.targets().add(standalone_stream(null, null, () => active = false));
    return this.filter(() => active);
  },
  detach() {
    // ensures compatibility with operators (#2753)
    // remove references to other streams and filter functions that may
    // be bound to subcontexts that need to be garbage collected.
    this._filter = standalone_truthy;
    this._targets = null;
  }
};

/**
 * Create a new event stream from an event source.
 * @param {object} source - The event source to monitor. The input must
 *  support the addEventListener method.
 * @param {string} type - The event type.
 * @param {function(object): boolean} [filter] - Event filter function.
 * @param {function(object): *} [apply] - Event application function.
 *   If provided, this function will be invoked and the result will be
 *   used as the downstream event value.
 * @return {EventStream}
 */
function standalone_events (source, type, filter, apply) {
  const df = this,
    s = standalone_stream(filter, apply),
    send = function (e) {
      e.dataflow = df;
      try {
        s.receive(e);
      } catch (error) {
        df.error(error);
      } finally {
        df.run();
      }
    };
  let sources;
  if (typeof source === 'string' && typeof document !== 'undefined') {
    sources = document.querySelectorAll(source);
  } else {
    sources = standalone_array(source);
  }
  const n = sources.length;
  for (let i = 0; i < n; ++i) {
    sources[i].addEventListener(type, send);
  }
  return s;
}

function standalone_vega_dataflow_module_parse(data, format) {
  const locale = this.locale();
  return standalone_read(data, format, locale.timeParse, locale.utcParse);
}

/**
 * Ingests new data into the dataflow. First parses the data using the
 * vega-loader read method, then pulses a changeset to the target operator.
 * @param {Operator} target - The Operator to target with ingested data,
 *   typically a Collect transform instance.
 * @param {*} data - The input data, prior to parsing. For JSON this may
 *   be a string or an object. For CSV, TSV, etc should be a string.
 * @param {object} format - The data format description for parsing
 *   loaded data. This object is passed to the vega-loader read method.
 * @returns {Dataflow}
 */
function standalone_ingest(target, data, format) {
  data = this.parse(data, format);
  return this.pulse(target, this.changeset().insert(data));
}

/**
 * Request data from an external source, parse it, and return a Promise.
 * @param {string} url - The URL from which to load the data. This string
 *   is passed to the vega-loader load method.
 * @param {object} [format] - The data format description for parsing
 *   loaded data. This object is passed to the vega-loader read method.
 * @return {Promise} A Promise that resolves upon completion of the request.
 *   The resolved object contains the following properties:
 *   - data: an array of parsed data (or null upon error)
 *   - status: a code for success (0), load fail (-1), or parse fail (-2)
 */
async function standalone_request(url, format) {
  const df = this;
  let status = 0,
    data;
  try {
    data = await df.loader().load(url, {
      context: 'dataflow',
      response: standalone_responseType(format && format.type)
    });
    try {
      data = df.parse(data, format);
    } catch (err) {
      status = -2;
      df.warn('Data ingestion failed', url, err);
    }
  } catch (err) {
    status = -1;
    df.warn('Loading failed', url, err);
  }
  return {
    data,
    status
  };
}
async function standalone_preload(target, url, format) {
  const df = this,
    pending = df._pending || standalone_loadPending(df);
  pending.requests += 1;
  const res = await df.request(url, format);
  df.pulse(target, df.changeset().remove(standalone_truthy).insert(res.data || []));
  pending.done();
  return res;
}
function standalone_loadPending(df) {
  let accept;
  const pending = new Promise(a => accept = a);
  pending.requests = 0;
  pending.done = () => {
    if (--pending.requests === 0) {
      df._pending = null;
      accept(df);
    }
  };
  return df._pending = pending;
}

const standalone_SKIP = {
  skip: true
};

/**
 * Perform operator updates in response to events. Applies an
 * update function to compute a new operator value. If the update function
 * returns a {@link ChangeSet}, the operator will be pulsed with those tuple
 * changes. Otherwise, the operator value will be updated to the return value.
 * @param {EventStream|Operator} source - The event source to react to.
 *   This argument can be either an EventStream or an Operator.
 * @param {Operator|function(object):Operator} target - The operator to update.
 *   This argument can either be an Operator instance or (if the source
 *   argument is an EventStream), a function that accepts an event object as
 *   input and returns an Operator to target.
 * @param {function(Parameters,Event): *} [update] - Optional update function
 *   to compute the new operator value, or a literal value to set. Update
 *   functions expect to receive a parameter object and event as arguments.
 *   This function can either return a new operator value or (if the source
 *   argument is an EventStream) a {@link ChangeSet} instance to pulse
 *   the target operator with tuple changes.
 * @param {object} [params] - The update function parameters.
 * @param {object} [options] - Additional options hash. If not overridden,
 *   updated operators will be skipped by default.
 * @param {boolean} [options.skip] - If true, the operator will
 *  be skipped: it will not be evaluated, but its dependents will be.
 * @param {boolean} [options.force] - If true, the operator will
 *   be re-evaluated even if its value has not changed.
 * @return {Dataflow}
 */
function standalone_on (source, target, update, params, options) {
  const fn = source instanceof standalone_Operator ? standalone_onOperator : standalone_onStream;
  fn(this, source, target, update, params, options);
  return this;
}
function standalone_onStream(df, stream, target, update, params, options) {
  const opt = standalone_extend({}, options, standalone_SKIP);
  let func, op;
  if (!standalone_vega_util_module_isFunction(target)) target = standalone_vega_util_module_constant(target);
  if (update === undefined) {
    func = e => df.touch(target(e));
  } else if (standalone_vega_util_module_isFunction(update)) {
    op = new standalone_Operator(null, update, params, false);
    func = e => {
      op.evaluate(e);
      const t = target(e),
        v = op.value;
      standalone_isChangeSet(v) ? df.pulse(t, v, options) : df.update(t, v, opt);
    };
  } else {
    func = e => df.update(target(e), update, opt);
  }
  stream.apply(func);
}
function standalone_onOperator(df, source, target, update, params, options) {
  if (update === undefined) {
    source.targets().add(target);
  } else {
    const opt = options || {},
      op = new standalone_Operator(null, standalone_updater(target, update), params, false);
    op.modified(opt.force);
    op.rank = source.rank; // immediately follow source
    source.targets().add(op); // add dependency

    if (target) {
      op.skip(true); // skip first invocation
      op.value = target.value; // initialize value
      op.targets().add(target); // chain dependencies
      df.connect(target, [op]); // rerank as needed, #1672
    }
  }
}
function standalone_updater(target, update) {
  update = standalone_vega_util_module_isFunction(update) ? update : standalone_vega_util_module_constant(update);
  return target ? function (_, pulse) {
    const value = update(_, pulse);
    if (!target.skip()) {
      target.skip(value !== this.value).value = value;
    }
    return value;
  } : update;
}

/**
 * Assigns a rank to an operator. Ranks are assigned in increasing order
 * by incrementing an internal rank counter.
 * @param {Operator} op - The operator to assign a rank.
 */
function standalone_rank(op) {
  op.rank = ++this._rank;
}

/**
 * Re-ranks an operator and all downstream target dependencies. This
 * is necessary when upstream dependencies of higher rank are added to
 * a target operator.
 * @param {Operator} op - The operator to re-rank.
 */
function standalone_rerank(op) {
  const queue = [op];
  let cur, list, i;
  while (queue.length) {
    this.rank(cur = queue.pop());
    if (list = cur._targets) {
      for (i = list.length; --i >= 0;) {
        queue.push(cur = list[i]);
        if (cur === op) standalone_vega_util_module_error('Cycle detected in dataflow graph.');
      }
    }
  }
}

/**
 * Sentinel value indicating pulse propagation should stop.
 */
const standalone_StopPropagation = {};

// Pulse visit type flags
const standalone_ADD = 1 << 0,
  standalone_REM = 1 << 1,
  standalone_MOD = 1 << 2,
  standalone_ADD_REM = standalone_ADD | standalone_REM,
  standalone_ADD_MOD = standalone_ADD | standalone_MOD,
  standalone_ALL = standalone_ADD | standalone_REM | standalone_MOD,
  standalone_REFLOW = 1 << 3,
  standalone_SOURCE = 1 << 4,
  standalone_NO_SOURCE = 1 << 5,
  standalone_NO_FIELDS = 1 << 6;

/**
 * A Pulse enables inter-operator communication during a run of the
 * dataflow graph. In addition to the current timestamp, a pulse may also
 * contain a change-set of added, removed or modified data tuples, as well as
 * a pointer to a full backing data source. Tuple change sets may not
 * be fully materialized; for example, to prevent needless array creation
 * a change set may include larger arrays and corresponding filter functions.
 * The pulse provides a {@link visit} method to enable proper and efficient
 * iteration over requested data tuples.
 *
 * In addition, each pulse can track modification flags for data tuple fields.
 * Responsible transform operators should call the {@link modifies} method to
 * indicate changes to data fields. The {@link modified} method enables
 * querying of this modification state.
 *
 * @constructor
 * @param {Dataflow} dataflow - The backing dataflow instance.
 * @param {number} stamp - The current propagation timestamp.
 * @param {string} [encode] - An optional encoding set name, which is then
 *   accessible as Pulse.encode. Operators can respond to (or ignore) this
 *   setting as appropriate. This parameter can be used in conjunction with
 *   the Encode transform in the vega-encode module.
 */
function standalone_Pulse(dataflow, stamp, encode) {
  this.dataflow = dataflow;
  this.stamp = stamp == null ? -1 : stamp;
  this.add = [];
  this.rem = [];
  this.mod = [];
  this.fields = null;
  this.encode = encode || null;
}
function standalone_materialize(data, filter) {
  const out = [];
  standalone_visitArray(data, filter, _ => out.push(_));
  return out;
}
function standalone_vega_dataflow_module_filter(pulse, flags) {
  const map = {};
  pulse.visit(flags, t => {
    map[standalone_tupleid(t)] = 1;
  });
  return t => map[standalone_tupleid(t)] ? null : t;
}
function standalone_addFilter(a, b) {
  return a ? (t, i) => a(t, i) && b(t, i) : b;
}
standalone_Pulse.prototype = {
  /**
   * Sentinel value indicating pulse propagation should stop.
   */
  StopPropagation: standalone_StopPropagation,
  /**
   * Boolean flag indicating ADD (added) tuples.
   */
  ADD: standalone_ADD,
  /**
   * Boolean flag indicating REM (removed) tuples.
   */
  REM: standalone_REM,
  /**
   * Boolean flag indicating MOD (modified) tuples.
   */
  MOD: standalone_MOD,
  /**
   * Boolean flag indicating ADD (added) and REM (removed) tuples.
   */
  ADD_REM: standalone_ADD_REM,
  /**
   * Boolean flag indicating ADD (added) and MOD (modified) tuples.
   */
  ADD_MOD: standalone_ADD_MOD,
  /**
   * Boolean flag indicating ADD, REM and MOD tuples.
   */
  ALL: standalone_ALL,
  /**
   * Boolean flag indicating all tuples in a data source
   * except for the ADD, REM and MOD tuples.
   */
  REFLOW: standalone_REFLOW,
  /**
   * Boolean flag indicating a 'pass-through' to a
   * backing data source, ignoring ADD, REM and MOD tuples.
   */
  SOURCE: standalone_SOURCE,
  /**
   * Boolean flag indicating that source data should be
   * suppressed when creating a forked pulse.
   */
  NO_SOURCE: standalone_NO_SOURCE,
  /**
   * Boolean flag indicating that field modifications should be
   * suppressed when creating a forked pulse.
   */
  NO_FIELDS: standalone_NO_FIELDS,
  /**
   * Creates a new pulse based on the values of this pulse.
   * The dataflow, time stamp and field modification values are copied over.
   * By default, new empty ADD, REM and MOD arrays are created.
   * @param {number} flags - Integer of boolean flags indicating which (if any)
   *   tuple arrays should be copied to the new pulse. The supported flag values
   *   are ADD, REM and MOD. Array references are copied directly: new array
   *   instances are not created.
   * @return {Pulse} - The forked pulse instance.
   * @see init
   */
  fork(flags) {
    return new standalone_Pulse(this.dataflow).init(this, flags);
  },
  /**
   * Creates a copy of this pulse with new materialized array
   * instances for the ADD, REM, MOD, and SOURCE arrays.
   * The dataflow, time stamp and field modification values are copied over.
   * @return {Pulse} - The cloned pulse instance.
   * @see init
   */
  clone() {
    const p = this.fork(standalone_ALL);
    p.add = p.add.slice();
    p.rem = p.rem.slice();
    p.mod = p.mod.slice();
    if (p.source) p.source = p.source.slice();
    return p.materialize(standalone_ALL | standalone_SOURCE);
  },
  /**
   * Returns a pulse that adds all tuples from a backing source. This is
   * useful for cases where operators are added to a dataflow after an
   * upstream data pipeline has already been processed, ensuring that
   * new operators can observe all tuples within a stream.
   * @return {Pulse} - A pulse instance with all source tuples included
   *   in the add array. If the current pulse already has all source
   *   tuples in its add array, it is returned directly. If the current
   *   pulse does not have a backing source, it is returned directly.
   */
  addAll() {
    let p = this;
    const reuse = !p.source || p.add === p.rem // special case for indexed set (e.g., crossfilter)
    || !p.rem.length && p.source.length === p.add.length;
    if (reuse) {
      return p;
    } else {
      p = new standalone_Pulse(this.dataflow).init(this);
      p.add = p.source;
      p.rem = []; // new operators can ignore rem #2769
      return p;
    }
  },
  /**
   * Initialize this pulse based on the values of another pulse. This method
   * is used internally by {@link fork} to initialize a new forked tuple.
   * The dataflow, time stamp and field modification values are copied over.
   * By default, new empty ADD, REM and MOD arrays are created.
   * @param {Pulse} src - The source pulse to copy from.
   * @param {number} flags - Integer of boolean flags indicating which (if any)
   *   tuple arrays should be copied to the new pulse. The supported flag values
   *   are ADD, REM and MOD. Array references are copied directly: new array
   *   instances are not created. By default, source data arrays are copied
   *   to the new pulse. Use the NO_SOURCE flag to enforce a null source.
   * @return {Pulse} - Returns this Pulse instance.
   */
  init(src, flags) {
    const p = this;
    p.stamp = src.stamp;
    p.encode = src.encode;
    if (src.fields && !(flags & standalone_NO_FIELDS)) {
      p.fields = src.fields;
    }
    if (flags & standalone_ADD) {
      p.addF = src.addF;
      p.add = src.add;
    } else {
      p.addF = null;
      p.add = [];
    }
    if (flags & standalone_REM) {
      p.remF = src.remF;
      p.rem = src.rem;
    } else {
      p.remF = null;
      p.rem = [];
    }
    if (flags & standalone_MOD) {
      p.modF = src.modF;
      p.mod = src.mod;
    } else {
      p.modF = null;
      p.mod = [];
    }
    if (flags & standalone_NO_SOURCE) {
      p.srcF = null;
      p.source = null;
    } else {
      p.srcF = src.srcF;
      p.source = src.source;
      if (src.cleans) p.cleans = src.cleans;
    }
    return p;
  },
  /**
   * Schedules a function to run after pulse propagation completes.
   * @param {function} func - The function to run.
   */
  runAfter(func) {
    this.dataflow.runAfter(func);
  },
  /**
   * Indicates if tuples have been added, removed or modified.
   * @param {number} [flags] - The tuple types (ADD, REM or MOD) to query.
   *   Defaults to ALL, returning true if any tuple type has changed.
   * @return {boolean} - Returns true if one or more queried tuple types have
   *   changed, false otherwise.
   */
  changed(flags) {
    const f = flags || standalone_ALL;
    return f & standalone_ADD && this.add.length || f & standalone_REM && this.rem.length || f & standalone_MOD && this.mod.length;
  },
  /**
   * Forces a "reflow" of tuple values, such that all tuples in the backing
   * source are added to the MOD set, unless already present in the ADD set.
   * @param {boolean} [fork=false] - If true, returns a forked copy of this
   *   pulse, and invokes reflow on that derived pulse.
   * @return {Pulse} - The reflowed pulse instance.
   */
  reflow(fork) {
    if (fork) return this.fork(standalone_ALL).reflow();
    const len = this.add.length,
      src = this.source && this.source.length;
    if (src && src !== len) {
      this.mod = this.source;
      if (len) this.filter(standalone_MOD, standalone_vega_dataflow_module_filter(this, standalone_ADD));
    }
    return this;
  },
  /**
   * Get/set metadata to pulse requesting garbage collection
   * to reclaim currently unused resources.
   */
  clean(value) {
    if (arguments.length) {
      this.cleans = !!value;
      return this;
    } else {
      return this.cleans;
    }
  },
  /**
   * Marks one or more data field names as modified to assist dependency
   * tracking and incremental processing by transform operators.
   * @param {string|Array<string>} _ - The field(s) to mark as modified.
   * @return {Pulse} - This pulse instance.
   */
  modifies(_) {
    const hash = this.fields || (this.fields = {});
    if (standalone_vega_util_module_isArray(_)) {
      _.forEach(f => hash[f] = true);
    } else {
      hash[_] = true;
    }
    return this;
  },
  /**
   * Checks if one or more data fields have been modified during this pulse
   * propagation timestamp.
   * @param {string|Array<string>} _ - The field(s) to check for modified.
   * @param {boolean} nomod - If true, will check the modified flag even if
   *   no mod tuples exist. If false (default), mod tuples must be present.
   * @return {boolean} - Returns true if any of the provided fields has been
   *   marked as modified, false otherwise.
   */
  modified(_, nomod) {
    const fields = this.fields;
    return !((nomod || this.mod.length) && fields) ? false : !arguments.length ? !!fields : standalone_vega_util_module_isArray(_) ? _.some(f => fields[f]) : fields[_];
  },
  /**
   * Adds a filter function to one more tuple sets. Filters are applied to
   * backing tuple arrays, to determine the actual set of tuples considered
   * added, removed or modified. They can be used to delay materialization of
   * a tuple set in order to avoid expensive array copies. In addition, the
   * filter functions can serve as value transformers: unlike standard predicate
   * function (which return boolean values), Pulse filters should return the
   * actual tuple value to process. If a tuple set is already filtered, the
   * new filter function will be appended into a conjuntive ('and') query.
   * @param {number} flags - Flags indicating the tuple set(s) to filter.
   * @param {function(*):object} filter - Filter function that will be applied
   *   to the tuple set array, and should return a data tuple if the value
   *   should be included in the tuple set, and falsy (or null) otherwise.
   * @return {Pulse} - Returns this pulse instance.
   */
  filter(flags, filter) {
    const p = this;
    if (flags & standalone_ADD) p.addF = standalone_addFilter(p.addF, filter);
    if (flags & standalone_REM) p.remF = standalone_addFilter(p.remF, filter);
    if (flags & standalone_MOD) p.modF = standalone_addFilter(p.modF, filter);
    if (flags & standalone_SOURCE) p.srcF = standalone_addFilter(p.srcF, filter);
    return p;
  },
  /**
   * Materialize one or more tuple sets in this pulse. If the tuple set(s) have
   * a registered filter function, it will be applied and the tuple set(s) will
   * be replaced with materialized tuple arrays.
   * @param {number} flags - Flags indicating the tuple set(s) to materialize.
   * @return {Pulse} - Returns this pulse instance.
   */
  materialize(flags) {
    flags = flags || standalone_ALL;
    const p = this;
    if (flags & standalone_ADD && p.addF) {
      p.add = standalone_materialize(p.add, p.addF);
      p.addF = null;
    }
    if (flags & standalone_REM && p.remF) {
      p.rem = standalone_materialize(p.rem, p.remF);
      p.remF = null;
    }
    if (flags & standalone_MOD && p.modF) {
      p.mod = standalone_materialize(p.mod, p.modF);
      p.modF = null;
    }
    if (flags & standalone_SOURCE && p.srcF) {
      p.source = p.source.filter(p.srcF);
      p.srcF = null;
    }
    return p;
  },
  /**
   * Visit one or more tuple sets in this pulse.
   * @param {number} flags - Flags indicating the tuple set(s) to visit.
   *   Legal values are ADD, REM, MOD and SOURCE (if a backing data source
   *   has been set).
   * @param {function(object):*} - Visitor function invoked per-tuple.
   * @return {Pulse} - Returns this pulse instance.
   */
  visit(flags, visitor) {
    const p = this,
      v = visitor;
    if (flags & standalone_SOURCE) {
      standalone_visitArray(p.source, p.srcF, v);
      return p;
    }
    if (flags & standalone_ADD) standalone_visitArray(p.add, p.addF, v);
    if (flags & standalone_REM) standalone_visitArray(p.rem, p.remF, v);
    if (flags & standalone_MOD) standalone_visitArray(p.mod, p.modF, v);
    const src = p.source;
    if (flags & standalone_REFLOW && src) {
      const sum = p.add.length + p.mod.length;
      if (sum === src.length) ; else if (sum) {
        standalone_visitArray(src, standalone_vega_dataflow_module_filter(p, standalone_ADD_MOD), v);
      } else {
        // if no add/rem/mod tuples, visit source
        standalone_visitArray(src, p.srcF, v);
      }
    }
    return p;
  }
};

/**
 * Represents a set of multiple pulses. Used as input for operators
 * that accept multiple pulses at a time. Contained pulses are
 * accessible via the public "pulses" array property. This pulse doe
 * not carry added, removed or modified tuples directly. However,
 * the visit method can be used to traverse all such tuples contained
 * in sub-pulses with a timestamp matching this parent multi-pulse.
 * @constructor
 * @param {Dataflow} dataflow - The backing dataflow instance.
 * @param {number} stamp - The timestamp.
 * @param {Array<Pulse>} pulses - The sub-pulses for this multi-pulse.
 */
function standalone_MultiPulse(dataflow, stamp, pulses, encode) {
  const p = this;
  let c = 0;
  this.dataflow = dataflow;
  this.stamp = stamp;
  this.fields = null;
  this.encode = encode || null;
  this.pulses = pulses;
  for (const pulse of pulses) {
    if (pulse.stamp !== stamp) continue;
    if (pulse.fields) {
      const hash = p.fields || (p.fields = {});
      for (const f in pulse.fields) {
        hash[f] = 1;
      }
    }
    if (pulse.changed(p.ADD)) c |= p.ADD;
    if (pulse.changed(p.REM)) c |= p.REM;
    if (pulse.changed(p.MOD)) c |= p.MOD;
  }
  this.changes = c;
}
standalone_inherits(standalone_MultiPulse, standalone_Pulse, {
  /**
   * Creates a new pulse based on the values of this pulse.
   * The dataflow, time stamp and field modification values are copied over.
   * @return {Pulse}
   */
  fork(flags) {
    const p = new standalone_Pulse(this.dataflow).init(this, flags & this.NO_FIELDS);
    if (flags !== undefined) {
      if (flags & p.ADD) this.visit(p.ADD, t => p.add.push(t));
      if (flags & p.REM) this.visit(p.REM, t => p.rem.push(t));
      if (flags & p.MOD) this.visit(p.MOD, t => p.mod.push(t));
    }
    return p;
  },
  changed(flags) {
    return this.changes & flags;
  },
  modified(_) {
    const p = this,
      fields = p.fields;
    return !(fields && p.changes & p.MOD) ? 0 : standalone_vega_util_module_isArray(_) ? _.some(f => fields[f]) : fields[_];
  },
  filter() {
    standalone_vega_util_module_error('MultiPulse does not support filtering.');
  },
  materialize() {
    standalone_vega_util_module_error('MultiPulse does not support materialization.');
  },
  visit(flags, visitor) {
    const p = this,
      pulses = p.pulses,
      n = pulses.length;
    let i = 0;
    if (flags & p.SOURCE) {
      for (; i < n; ++i) {
        pulses[i].visit(flags, visitor);
      }
    } else {
      for (; i < n; ++i) {
        if (pulses[i].stamp === p.stamp) {
          pulses[i].visit(flags, visitor);
        }
      }
    }
    return p;
  }
});

/* eslint-disable require-atomic-updates */

/**
 * Evaluates the dataflow and returns a Promise that resolves when pulse
 * propagation completes. This method will increment the current timestamp
 * and process all updated, pulsed and touched operators. When invoked for
 * the first time, all registered operators will be processed. This method
 * should not be invoked by third-party clients, use {@link runAsync} or
 * {@link run} instead.
 * @param {string} [encode] - The name of an encoding set to invoke during
 *   propagation. This value is added to generated Pulse instances;
 *   operators can then respond to (or ignore) this setting as appropriate.
 *   This parameter can be used in conjunction with the Encode transform in
 *   the vega-encode package.
 * @param {function} [prerun] - An optional callback function to invoke
 *   immediately before dataflow evaluation commences.
 * @param {function} [postrun] - An optional callback function to invoke
 *   after dataflow evaluation completes. The callback will be invoked
 *   after those registered via {@link runAfter}.
 * @return {Promise} - A promise that resolves to this dataflow after
 *   evaluation completes.
 */
async function standalone_evaluate(encode, prerun, postrun) {
  const df = this,
    async = [];

  // if the pulse value is set, this is a re-entrant call
  if (df._pulse) return standalone_reentrant(df);

  // wait for pending datasets to load
  if (df._pending) await df._pending;

  // invoke prerun function, if provided
  if (prerun) await standalone_asyncCallback(df, prerun);

  // exit early if there are no updates
  if (!df._touched.length) {
    df.debug('Dataflow invoked, but nothing to do.');
    return df;
  }

  // increment timestamp clock
  const stamp = ++df._clock;

  // set the current pulse
  df._pulse = new standalone_Pulse(df, stamp, encode);

  // initialize priority queue, reset touched operators
  df._touched.forEach(op => df._enqueue(op, true));
  df._touched = standalone_UniqueList(standalone_id);
  let count = 0,
    op,
    next,
    error;
  try {
    while (df._heap.size() > 0) {
      // dequeue operator with highest priority
      op = df._heap.pop();

      // re-queue if rank changed
      if (op.rank !== op.qrank) {
        df._enqueue(op, true);
        continue;
      }

      // otherwise, evaluate the operator
      next = op.run(df._getPulse(op, encode));
      if (next.then) {
        // await if operator returns a promise directly
        next = await next;
      } else if (next.async) {
        // queue parallel asynchronous execution
        async.push(next.async);
        next = standalone_StopPropagation;
      }

      // propagate evaluation, enqueue dependent operators
      if (next !== standalone_StopPropagation) {
        if (op._targets) op._targets.forEach(op => df._enqueue(op));
      }

      // increment visit counter
      ++count;
    }
  } catch (err) {
    df._heap.clear();
    error = err;
  }

  // reset pulse map
  df._input = {};
  df._pulse = null;
  df.debug(`Pulse ${stamp}: ${count} operators`);
  if (error) {
    df._postrun = [];
    df.error(error);
  }

  // invoke callbacks queued via runAfter
  if (df._postrun.length) {
    const pr = df._postrun.sort((a, b) => b.priority - a.priority);
    df._postrun = [];
    for (let i = 0; i < pr.length; ++i) {
      await standalone_asyncCallback(df, pr[i].callback);
    }
  }

  // invoke postrun function, if provided
  if (postrun) await standalone_asyncCallback(df, postrun);

  // handle non-blocking asynchronous callbacks
  if (async.length) {
    Promise.all(async).then(cb => df.runAsync(null, () => {
      cb.forEach(f => {
        try {
          f(df);
        } catch (err) {
          df.error(err);
        }
      });
    }));
  }
  return df;
}

/**
 * Queues dataflow evaluation to run once any other queued evaluations have
 * completed and returns a Promise that resolves when the queued pulse
 * propagation completes. If provided, a callback function will be invoked
 * immediately before evaluation commences. This method will ensure a
 * separate evaluation is invoked for each time it is called.
 * @param {string} [encode] - The name of an encoding set to invoke during
 *   propagation. This value is added to generated Pulse instances;
 *   operators can then respond to (or ignore) this setting as appropriate.
 *   This parameter can be used in conjunction with the Encode transform in
 *   the vega-encode package.
 * @param {function} [prerun] - An optional callback function to invoke
 *   immediately before dataflow evaluation commences.
 * @param {function} [postrun] - An optional callback function to invoke
 *   after dataflow evaluation completes. The callback will be invoked
 *   after those registered via {@link runAfter}.
 * @return {Promise} - A promise that resolves to this dataflow after
 *   evaluation completes.
 */
async function standalone_runAsync(encode, prerun, postrun) {
  // await previously queued functions
  while (this._running) await this._running;

  // run dataflow, manage running promise
  const clear = () => this._running = null;
  (this._running = this.evaluate(encode, prerun, postrun)).then(clear, clear);
  return this._running;
}

/**
 * Requests dataflow evaluation and the immediately returns this dataflow
 * instance. If there are pending data loading or other asynchronous
 * operations, the dataflow will evaluate asynchronously after this method
 * has been invoked. To track when dataflow evaluation completes, use the
 * {@link runAsync} method instead. This method will raise an error if
 * invoked while the dataflow is already in the midst of evaluation.
 * @param {string} [encode] - The name of an encoding set to invoke during
 *   propagation. This value is added to generated Pulse instances;
 *   operators can then respond to (or ignore) this setting as appropriate.
 *   This parameter can be used in conjunction with the Encode transform in
 *   the vega-encode module.
 * @param {function} [prerun] - An optional callback function to invoke
 *   immediately before dataflow evaluation commences.
 * @param {function} [postrun] - An optional callback function to invoke
 *   after dataflow evaluation completes. The callback will be invoked
 *   after those registered via {@link runAfter}.
 * @return {Dataflow} - This dataflow instance.
 */
function standalone_vega_dataflow_module_run(encode, prerun, postrun) {
  return this._pulse ? standalone_reentrant(this) : (this.evaluate(encode, prerun, postrun), this);
}

/**
 * Schedules a callback function to be invoked after the current pulse
 * propagation completes. If no propagation is currently occurring,
 * the function is invoked immediately. Callbacks scheduled via runAfter
 * are invoked immediately upon completion of the current cycle, before
 * any request queued via runAsync. This method is primarily intended for
 * internal use. Third-party callers using runAfter to schedule a callback
 * that invokes {@link run} or {@link runAsync} should not use this method,
 * but instead use {@link runAsync} with prerun or postrun arguments.
 * @param {function(Dataflow)} callback - The callback function to run.
 *   The callback will be invoked with this Dataflow instance as its
 *   sole argument.
 * @param {boolean} enqueue - A boolean flag indicating that the
 *   callback should be queued up to run after the next propagation
 *   cycle, suppressing immediate invocation when propagation is not
 *   currently occurring.
 * @param {number} [priority] - A priority value used to sort registered
 *   callbacks to determine execution order. This argument is intended
 *   for internal Vega use only.
 */
function standalone_runAfter(callback, enqueue, priority) {
  if (this._pulse || enqueue) {
    // pulse propagation is currently running, queue to run after
    this._postrun.push({
      priority: priority || 0,
      callback: callback
    });
  } else {
    // pulse propagation already complete, invoke immediately
    try {
      callback(this);
    } catch (err) {
      this.error(err);
    }
  }
}

/**
 * Raise an error for re-entrant dataflow evaluation.
 */
function standalone_reentrant(df) {
  df.error('Dataflow already running. Use runAsync() to chain invocations.');
  return df;
}

/**
 * Enqueue an operator into the priority queue for evaluation. The operator
 * will be enqueued if it has no registered pulse for the current cycle, or if
 * the force argument is true. Upon enqueue, this method also sets the
 * operator's qrank to the current rank value.
 * @param {Operator} op - The operator to enqueue.
 * @param {boolean} [force] - A flag indicating if the operator should be
 *   forceably added to the queue, even if it has already been previously
 *   enqueued during the current pulse propagation. This is useful when the
 *   dataflow graph is dynamically modified and the operator rank changes.
 */
function standalone_enqueue(op, force) {
  const q = op.stamp < this._clock;
  if (q) op.stamp = this._clock;
  if (q || force) {
    op.qrank = op.rank;
    this._heap.push(op);
  }
}

/**
 * Provide a correct pulse for evaluating an operator. If the operator has an
 * explicit source operator, we will try to pull the pulse(s) from it.
 * If there is an array of source operators, we build a multi-pulse.
 * Otherwise, we return a current pulse with correct source data.
 * If the pulse is the pulse map has an explicit target set, we use that.
 * Else if the pulse on the upstream source operator is current, we use that.
 * Else we use the pulse from the pulse map, but copy the source tuple array.
 * @param {Operator} op - The operator for which to get an input pulse.
 * @param {string} [encode] - An (optional) encoding set name with which to
 *   annotate the returned pulse. See {@link run} for more information.
 */
function standalone_getPulse(op, encode) {
  const s = op.source,
    stamp = this._clock;
  return s && standalone_vega_util_module_isArray(s) ? new standalone_MultiPulse(this, stamp, s.map(_ => _.pulse), encode) : this._input[op.id] || standalone_singlePulse(this._pulse, s && s.pulse);
}
function standalone_singlePulse(p, s) {
  if (s && s.stamp === p.stamp) {
    return s;
  }
  p = p.fork();
  if (s && s !== standalone_StopPropagation) {
    p.source = s.source;
  }
  return p;
}

const standalone_NO_OPT = {
  skip: false,
  force: false
};

/**
 * Touches an operator, scheduling it to be evaluated. If invoked outside of
 * a pulse propagation, the operator will be evaluated the next time this
 * dataflow is run. If invoked in the midst of pulse propagation, the operator
 * will be queued for evaluation if and only if the operator has not yet been
 * evaluated on the current propagation timestamp.
 * @param {Operator} op - The operator to touch.
 * @param {object} [options] - Additional options hash.
 * @param {boolean} [options.skip] - If true, the operator will
 *   be skipped: it will not be evaluated, but its dependents will be.
 * @return {Dataflow}
 */
function standalone_touch(op, options) {
  const opt = options || standalone_NO_OPT;
  if (this._pulse) {
    // if in midst of propagation, add to priority queue
    this._enqueue(op);
  } else {
    // otherwise, queue for next propagation
    this._touched.add(op);
  }
  if (opt.skip) op.skip(true);
  return this;
}

/**
 * Updates the value of the given operator.
 * @param {Operator} op - The operator to update.
 * @param {*} value - The value to set.
 * @param {object} [options] - Additional options hash.
 * @param {boolean} [options.force] - If true, the operator will
 *   be re-evaluated even if its value has not changed.
 * @param {boolean} [options.skip] - If true, the operator will
 *   be skipped: it will not be evaluated, but its dependents will be.
 * @return {Dataflow}
 */
function standalone_vega_dataflow_module_update(op, value, options) {
  const opt = options || standalone_NO_OPT;
  if (op.set(value) || opt.force) {
    this.touch(op, opt);
  }
  return this;
}

/**
 * Pulses an operator with a changeset of tuples. If invoked outside of
 * a pulse propagation, the pulse will be applied the next time this
 * dataflow is run. If invoked in the midst of pulse propagation, the pulse
 * will be added to the set of active pulses and will be applied if and
 * only if the target operator has not yet been evaluated on the current
 * propagation timestamp.
 * @param {Operator} op - The operator to pulse.
 * @param {ChangeSet} value - The tuple changeset to apply.
 * @param {object} [options] - Additional options hash.
 * @param {boolean} [options.skip] - If true, the operator will
 *   be skipped: it will not be evaluated, but its dependents will be.
 * @return {Dataflow}
 */
function standalone_pulse(op, changeset, options) {
  this.touch(op, options || standalone_NO_OPT);
  const p = new standalone_Pulse(this, this._clock + (this._pulse ? 0 : 1)),
    t = op.pulse && op.pulse.source || [];
  p.target = op;
  this._input[op.id] = changeset.pulse(p, t);
  return this;
}

function standalone_Heap(cmp) {
  let nodes = [];
  return {
    clear: () => nodes = [],
    size: () => nodes.length,
    peek: () => nodes[0],
    push: x => {
      nodes.push(x);
      return standalone_siftdown(nodes, 0, nodes.length - 1, cmp);
    },
    pop: () => {
      const last = nodes.pop();
      let item;
      if (nodes.length) {
        item = nodes[0];
        nodes[0] = last;
        standalone_siftup(nodes, 0, cmp);
      } else {
        item = last;
      }
      return item;
    }
  };
}
function standalone_siftdown(array, start, idx, cmp) {
  let parent, pidx;
  const item = array[idx];
  while (idx > start) {
    pidx = idx - 1 >> 1;
    parent = array[pidx];
    if (cmp(item, parent) < 0) {
      array[idx] = parent;
      idx = pidx;
      continue;
    }
    break;
  }
  return array[idx] = item;
}
function standalone_siftup(array, idx, cmp) {
  const start = idx,
    end = array.length,
    item = array[idx];
  let cidx = (idx << 1) + 1,
    ridx;
  while (cidx < end) {
    ridx = cidx + 1;
    if (ridx < end && cmp(array[cidx], array[ridx]) >= 0) {
      cidx = ridx;
    }
    array[idx] = array[cidx];
    idx = cidx;
    cidx = (idx << 1) + 1;
  }
  array[idx] = item;
  return standalone_siftdown(array, start, idx, cmp);
}

/**
 * A dataflow graph for reactive processing of data streams.
 * @constructor
 */
function standalone_Dataflow() {
  this.logger(standalone_logger());
  this.logLevel(standalone_Error$1);
  this._clock = 0;
  this._rank = 0;
  this._locale = standalone_vega_format_module_defaultLocale();
  try {
    this._loader = standalone_loader();
  } catch (e) {
    // do nothing if loader module is unavailable
  }
  this._touched = standalone_UniqueList(standalone_id);
  this._input = {};
  this._pulse = null;
  this._heap = standalone_Heap((a, b) => a.qrank - b.qrank);
  this._postrun = [];
}
function standalone_logMethod(method) {
  return function () {
    return this._log[method].apply(this, arguments);
  };
}
standalone_Dataflow.prototype = {
  /**
   * The current timestamp of this dataflow. This value reflects the
   * timestamp of the previous dataflow run. The dataflow is initialized
   * with a stamp value of 0. The initial run of the dataflow will have
   * a timestap of 1, and so on. This value will match the
   * {@link Pulse.stamp} property.
   * @return {number} - The current timestamp value.
   */
  stamp() {
    return this._clock;
  },
  /**
   * Gets or sets the loader instance to use for data file loading. A
   * loader object must provide a "load" method for loading files and a
   * "sanitize" method for checking URL/filename validity. Both methods
   * should accept a URI and options hash as arguments, and return a Promise
   * that resolves to the loaded file contents (load) or a hash containing
   * sanitized URI data with the sanitized url assigned to the "href" property
   * (sanitize).
   * @param {object} _ - The loader instance to use.
   * @return {object|Dataflow} - If no arguments are provided, returns
   *   the current loader instance. Otherwise returns this Dataflow instance.
   */
  loader(_) {
    if (arguments.length) {
      this._loader = _;
      return this;
    } else {
      return this._loader;
    }
  },
  /**
   * Gets or sets the locale instance to use for formatting and parsing
   * string values. The locale object should be provided by the
   * vega-format library, and include methods such as format, timeFormat,
   * utcFormat, timeParse, and utcParse.
   * @param {object} _ - The locale instance to use.
   * @return {object|Dataflow} - If no arguments are provided, returns
   *   the current locale instance. Otherwise returns this Dataflow instance.
   */
  locale(_) {
    if (arguments.length) {
      this._locale = _;
      return this;
    } else {
      return this._locale;
    }
  },
  /**
   * Get or set the logger instance used to log messages. If no arguments are
   * provided, returns the current logger instance. Otherwise, sets the logger
   * and return this Dataflow instance. Provided loggers must support the full
   * API of logger objects generated by the vega-util logger method. Note that
   * by default the log level of the new logger will be used; use the logLevel
   * method to adjust the log level as needed.
   */
  logger(logger) {
    if (arguments.length) {
      this._log = logger;
      return this;
    } else {
      return this._log;
    }
  },
  /**
   * Logs an error message. By default, logged messages are written to console
   * output. The message will only be logged if the current log level is high
   * enough to permit error messages.
   */
  error: standalone_logMethod('error'),
  /**
   * Logs a warning message. By default, logged messages are written to console
   * output. The message will only be logged if the current log level is high
   * enough to permit warning messages.
   */
  warn: standalone_logMethod('warn'),
  /**
   * Logs a information message. By default, logged messages are written to
   * console output. The message will only be logged if the current log level is
   * high enough to permit information messages.
   */
  info: standalone_logMethod('info'),
  /**
   * Logs a debug message. By default, logged messages are written to console
   * output. The message will only be logged if the current log level is high
   * enough to permit debug messages.
   */
  debug: standalone_logMethod('debug'),
  /**
   * Get or set the current log level. If an argument is provided, it
   * will be used as the new log level.
   * @param {number} [level] - Should be one of None, Warn, Info
   * @return {number} - The current log level.
   */
  logLevel: standalone_logMethod('level'),
  /**
   * Empty entry threshold for garbage cleaning. Map data structures will
   * perform cleaning once the number of empty entries exceeds this value.
   */
  cleanThreshold: 1e4,
  // OPERATOR REGISTRATION
  add: standalone_add,
  connect: standalone_connect,
  rank: standalone_rank,
  rerank: standalone_rerank,
  // OPERATOR UPDATES
  pulse: standalone_pulse,
  touch: standalone_touch,
  update: standalone_vega_dataflow_module_update,
  changeset: standalone_changeset,
  // DATA LOADING
  ingest: standalone_ingest,
  parse: standalone_vega_dataflow_module_parse,
  preload: standalone_preload,
  request: standalone_request,
  // EVENT HANDLING
  events: standalone_events,
  on: standalone_on,
  // PULSE PROPAGATION
  evaluate: standalone_evaluate,
  run: standalone_vega_dataflow_module_run,
  runAsync: standalone_runAsync,
  runAfter: standalone_runAfter,
  _enqueue: standalone_enqueue,
  _getPulse: standalone_getPulse
};

/**
 * Abstract class for operators that process data tuples.
 * Subclasses must provide a {@link transform} method for operator processing.
 * @constructor
 * @param {*} [init] - The initial value for this operator.
 * @param {object} [params] - The parameters for this operator.
 * @param {Operator} [source] - The operator from which to receive pulses.
 */
function standalone_Transform(init, params) {
  standalone_Operator.call(this, init, null, params);
}
standalone_inherits(standalone_Transform, standalone_Operator, {
  /**
   * Overrides {@link Operator.evaluate} for transform operators.
   * Internally, this method calls {@link evaluate} to perform processing.
   * If {@link evaluate} returns a falsy value, the input pulse is returned.
   * This method should NOT be overridden, instead overrride {@link evaluate}.
   * @param {Pulse} pulse - the current dataflow pulse.
   * @return the output pulse for this operator (or StopPropagation)
   */
  run(pulse) {
    if (pulse.stamp < this.stamp) return pulse.StopPropagation;
    let rv;
    if (this.skip()) {
      this.skip(false);
    } else {
      rv = this.evaluate(pulse);
    }
    rv = rv || pulse;
    if (rv.then) {
      rv = rv.then(_ => this.pulse = _);
    } else if (rv !== pulse.StopPropagation) {
      this.pulse = rv;
    }
    return rv;
  },
  /**
   * Overrides {@link Operator.evaluate} for transform operators.
   * Marshalls parameter values and then invokes {@link transform}.
   * @param {Pulse} pulse - the current dataflow pulse.
   * @return {Pulse} The output pulse (or StopPropagation). A falsy return
       value (including undefined) will let the input pulse pass through.
  */
  evaluate(pulse) {
    const params = this.marshall(pulse.stamp),
      out = this.transform(params, pulse);
    params.clear();
    return out;
  },
  /**
   * Process incoming pulses.
   * Subclasses should override this method to implement transforms.
   * @param {Parameters} _ - The operator parameter values.
   * @param {Pulse} pulse - The current dataflow pulse.
   * @return {Pulse} The output pulse (or StopPropagation). A falsy return
   *   value (including undefined) will let the input pulse pass through.
   */
  transform() {}
});

const standalone_transforms = {};
function standalone_definition(type) {
  const t = standalone_vega_dataflow_module_transform(type);
  return t && t.Definition || null;
}
function standalone_vega_dataflow_module_transform(type) {
  type = type && type.toLowerCase();
  return standalone_vega_util_module_has(standalone_transforms, type) ? standalone_transforms[type] : null;
}



;// ../../node_modules/d3-array/src/max.js
function standalone_max(values, valueof) {
  let max;
  if (valueof === undefined) {
    for (const value of values) {
      if (value != null
          && (max < value || (max === undefined && value >= value))) {
        max = value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null
          && (max < value || (max === undefined && value >= value))) {
        max = value;
      }
    }
  }
  return max;
}

;// ../../node_modules/d3-array/src/min.js
function standalone_min(values, valueof) {
  let min;
  if (valueof === undefined) {
    for (const value of values) {
      if (value != null
          && (min > value || (min === undefined && value >= value))) {
        min = value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null
          && (min > value || (min === undefined && value >= value))) {
        min = value;
      }
    }
  }
  return min;
}

;// ../../node_modules/d3-array/src/sort.js



function standalone_sort(values, ...F) {
  if (typeof values[Symbol.iterator] !== "function") throw new TypeError("values is not iterable");
  values = Array.from(values);
  let [f] = F;
  if ((f && f.length !== 2) || F.length > 1) {
    const index = Uint32Array.from(values, (d, i) => i);
    if (F.length > 1) {
      F = F.map(f => values.map(f));
      index.sort((i, j) => {
        for (const f of F) {
          const c = standalone_sort_ascendingDefined(f[i], f[j]);
          if (c) return c;
        }
      });
    } else {
      f = values.map(f);
      index.sort((i, j) => standalone_sort_ascendingDefined(f[i], f[j]));
    }
    return permute(values, index);
  }
  return values.sort(standalone_compareDefined(f));
}

function standalone_compareDefined(compare = standalone_ascending_ascending) {
  if (compare === standalone_ascending_ascending) return standalone_sort_ascendingDefined;
  if (typeof compare !== "function") throw new TypeError("compare is not a function");
  return (a, b) => {
    const x = compare(a, b);
    if (x || x === 0) return x;
    return (compare(b, b) === 0) - (compare(a, a) === 0);
  };
}

function standalone_sort_ascendingDefined(a, b) {
  return (a == null || !(a >= a)) - (b == null || !(b >= b)) || (a < b ? -1 : a > b ? 1 : 0);
}

;// ../../node_modules/d3-array/src/quickselect.js


// Based on https://github.com/mourner/quickselect
// ISC license, Copyright 2018 Vladimir Agafonkin.
function standalone_quickselect_quickselect(array, k, left = 0, right = Infinity, compare) {
  k = Math.floor(k);
  left = Math.floor(Math.max(0, left));
  right = Math.floor(Math.min(array.length - 1, right));

  if (!(left <= k && k <= right)) return array;

  compare = compare === undefined ? standalone_sort_ascendingDefined : standalone_compareDefined(compare);

  while (right > left) {
    if (right - left > 600) {
      const n = right - left + 1;
      const m = k - left + 1;
      const z = Math.log(n);
      const s = 0.5 * Math.exp(2 * z / 3);
      const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
      const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
      const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
      standalone_quickselect_quickselect(array, k, newLeft, newRight, compare);
    }

    const t = array[k];
    let i = left;
    let j = right;

    standalone_swap(array, left, k);
    if (compare(array[right], t) > 0) standalone_swap(array, left, right);

    while (i < j) {
      standalone_swap(array, i, j), ++i, --j;
      while (compare(array[i], t) < 0) ++i;
      while (compare(array[j], t) > 0) --j;
    }

    if (compare(array[left], t) === 0) standalone_swap(array, left, j);
    else ++j, standalone_swap(array, j, right);

    if (j <= k) left = j + 1;
    if (k <= j) right = j - 1;
  }

  return array;
}

function standalone_swap(array, i, j) {
  const t = array[i];
  array[i] = array[j];
  array[j] = t;
}

;// ../../node_modules/d3-array/src/number.js
function standalone_number_number(x) {
  return x === null ? NaN : +x;
}

function* standalone_numbers(values, valueof) {
  if (valueof === undefined) {
    for (let value of values) {
      if (value != null && (value = +value) >= value) {
        yield value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {
        yield value;
      }
    }
  }
}

;// ../../node_modules/d3-array/src/quantile.js









function standalone_quantile(values, p, valueof) {
  values = Float64Array.from(standalone_numbers(values, valueof));
  if (!(n = values.length) || isNaN(p = +p)) return;
  if (p <= 0 || n < 2) return standalone_min(values);
  if (p >= 1) return standalone_max(values);
  var n,
      i = (n - 1) * p,
      i0 = Math.floor(i),
      value0 = standalone_max(standalone_quickselect_quickselect(values, i0).subarray(0, i0 + 1)),
      value1 = standalone_min(values.subarray(i0 + 1));
  return value0 + (value1 - value0) * (i - i0);
}

function standalone_quantileSorted(values, p, valueof = standalone_number_number) {
  if (!(n = values.length) || isNaN(p = +p)) return;
  if (p <= 0 || n < 2) return +valueof(values[0], 0, values);
  if (p >= 1) return +valueof(values[n - 1], n - 1, values);
  var n,
      i = (n - 1) * p,
      i0 = Math.floor(i),
      value0 = +valueof(values[i0], i0, values),
      value1 = +valueof(values[i0 + 1], i0 + 1, values);
  return value0 + (value1 - value0) * (i - i0);
}

function standalone_quantile_quantileIndex(values, p, valueof = number) {
  if (isNaN(p = +p)) return;
  numbers = Float64Array.from(values, (_, i) => number(valueof(values[i], i, values)));
  if (p <= 0) return minIndex(numbers);
  if (p >= 1) return maxIndex(numbers);
  var numbers,
      index = Uint32Array.from(values, (_, i) => i),
      j = numbers.length - 1,
      i = Math.floor(j * p);
  quickselect(index, i, 0, j, (i, j) => ascendingDefined(numbers[i], numbers[j]));
  i = greatest(index.subarray(0, i + 1), (i) => numbers[i]);
  return i >= 0 ? i : -1;
}

;// ../../node_modules/d3-array/src/variance.js
function standalone_variance(values, valueof) {
  let count = 0;
  let delta;
  let mean = 0;
  let sum = 0;
  if (valueof === undefined) {
    for (let value of values) {
      if (value != null && (value = +value) >= value) {
        delta = value - mean;
        mean += delta / ++count;
        sum += delta * (value - mean);
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {
        delta = value - mean;
        mean += delta / ++count;
        sum += delta * (value - mean);
      }
    }
  }
  if (count > 1) return sum / (count - 1);
}

;// ../../node_modules/d3-array/src/deviation.js


function standalone_deviation(values, valueof) {
  const v = standalone_variance(values, valueof);
  return v ? Math.sqrt(v) : v;
}

;// ../../node_modules/d3-array/src/median.js


function standalone_median(values, valueof) {
  return standalone_quantile(values, 0.5, valueof);
}

function standalone_medianIndex(values, valueof) {
  return quantileIndex(values, 0.5, valueof);
}

;// ../../node_modules/vega-statistics/build/vega-statistics.module.js


function* standalone_vega_statistics_module_numbers (values, valueof) {
  if (valueof == null) {
    for (let value of values) {
      if (value != null && value !== '' && (value = +value) >= value) {
        yield value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      value = valueof(value, ++index, values);
      if (value != null && value !== '' && (value = +value) >= value) {
        yield value;
      }
    }
  }
}

function standalone_quantiles (array, p, f) {
  const values = Float64Array.from(standalone_vega_statistics_module_numbers(array, f));

  // don't depend on return value from typed array sort call
  // protects against undefined sort results in Safari (vega/vega-lite#4964)
  values.sort(standalone_ascending_ascending);
  return p.map(_ => standalone_quantileSorted(values, _));
}

function standalone_quartiles (array, f) {
  return standalone_quantiles(array, [0.25, 0.50, 0.75], f);
}

// Scott, D. W. (1992) Multivariate Density Estimation:
// Theory, Practice, and Visualization. Wiley.
function standalone_estimateBandwidth (array, f) {
  const n = array.length,
    d = standalone_deviation(array, f),
    q = standalone_quartiles(array, f),
    h = (q[2] - q[0]) / 1.34,
    v = Math.min(d, h) || d || Math.abs(q[0]) || 1;
  return 1.06 * v * Math.pow(n, -0.2);
}

function standalone_vega_statistics_module_bin (_) {
  // determine range
  const maxb = _.maxbins || 20,
    base = _.base || 10,
    logb = Math.log(base),
    div = _.divide || [5, 2];
  let min = _.extent[0],
    max = _.extent[1],
    step,
    level,
    minstep,
    v,
    i,
    n;
  const span = _.span || max - min || Math.abs(min) || 1;
  if (_.step) {
    // if step size is explicitly given, use that
    step = _.step;
  } else if (_.steps) {
    // if provided, limit choice to acceptable step sizes
    v = span / maxb;
    for (i = 0, n = _.steps.length; i < n && _.steps[i] < v; ++i);
    step = _.steps[Math.max(0, i - 1)];
  } else {
    // else use span to determine step size
    level = Math.ceil(Math.log(maxb) / logb);
    minstep = _.minstep || 0;
    step = Math.max(minstep, Math.pow(base, Math.round(Math.log(span) / logb) - level));

    // increase step size if too many bins
    while (Math.ceil(span / step) > maxb) {
      step *= base;
    }

    // decrease step size if allowed
    for (i = 0, n = div.length; i < n; ++i) {
      v = step / div[i];
      if (v >= minstep && span / v <= maxb) step = v;
    }
  }

  // update precision, min and max
  v = Math.log(step);
  const precision = v >= 0 ? 0 : ~~(-v / logb) + 1,
    eps = Math.pow(base, -precision - 1);
  if (_.nice || _.nice === undefined) {
    v = Math.floor(min / step + eps) * step;
    min = min < v ? v - step : v;
    max = Math.ceil(max / step) * step;
  }
  return {
    start: min,
    stop: max === min ? min + step : max,
    step: step
  };
}

var standalone_random = Math.random;
function standalone_setRandom(r) {
  standalone_random = r;
}

function standalone_bootstrapCI (array, samples, alpha, f) {
  if (!array.length) return [undefined, undefined];
  const values = Float64Array.from(standalone_vega_statistics_module_numbers(array, f)),
    n = values.length,
    m = samples;
  let a, i, j, mu;
  for (j = 0, mu = Array(m); j < m; ++j) {
    for (a = 0, i = 0; i < n; ++i) {
      a += values[~~(standalone_random() * n)];
    }
    mu[j] = a / n;
  }
  mu.sort(standalone_ascending_ascending);
  return [standalone_quantile(mu, alpha / 2), standalone_quantile(mu, 1 - alpha / 2)];
}

// Dot density binning for dot plot construction.
// Based on Leland Wilkinson, Dot Plots, The American Statistician, 1999.
// https://www.cs.uic.edu/~wilkinson/Publications/dotplots.pdf
function standalone_dotbin (array, step, smooth, f) {
  f = f || (_ => _);
  const n = array.length,
    v = new Float64Array(n);
  let i = 0,
    j = 1,
    a = f(array[0]),
    b = a,
    w = a + step,
    x;
  for (; j < n; ++j) {
    x = f(array[j]);
    if (x >= w) {
      b = (a + b) / 2;
      for (; i < j; ++i) v[i] = b;
      w = x + step;
      a = x;
    }
    b = x;
  }
  b = (a + b) / 2;
  for (; i < j; ++i) v[i] = b;
  return smooth ? standalone_smoothing(v, step + step / 4) : v;
}

// perform smoothing to reduce variance
// swap points between "adjacent" stacks
// Wilkinson defines adjacent as within step/4 units
function standalone_smoothing(v, thresh) {
  const n = v.length;
  let a = 0,
    b = 1,
    c,
    d;

  // get left stack
  while (v[a] === v[b]) ++b;
  while (b < n) {
    // get right stack
    c = b + 1;
    while (v[b] === v[c]) ++c;

    // are stacks adjacent?
    // if so, compare sizes and swap as needed
    if (v[b] - v[b - 1] < thresh) {
      d = b + (a + c - b - b >> 1);
      while (d < b) v[d++] = v[b];
      while (d > b) v[d--] = v[a];
    }

    // update left stack indices
    a = b;
    b = c;
  }
  return v;
}

function standalone_vega_statistics_module_lcg (seed) {
  // Random numbers using a Linear Congruential Generator with seed value
  // Uses glibc values from https://en.wikipedia.org/wiki/Linear_congruential_generator
  return function () {
    seed = (1103515245 * seed + 12345) % 2147483647;
    return seed / 2147483647;
  };
}

function standalone_integer (min, max) {
  if (max == null) {
    max = min;
    min = 0;
  }
  let a, b, d;
  const dist = {
    min(_) {
      if (arguments.length) {
        a = _ || 0;
        d = b - a;
        return dist;
      } else {
        return a;
      }
    },
    max(_) {
      if (arguments.length) {
        b = _ || 0;
        d = b - a;
        return dist;
      } else {
        return b;
      }
    },
    sample() {
      return a + Math.floor(d * standalone_random());
    },
    pdf(x) {
      return x === Math.floor(x) && x >= a && x < b ? 1 / d : 0;
    },
    cdf(x) {
      const v = Math.floor(x);
      return v < a ? 0 : v >= b ? 1 : (v - a + 1) / d;
    },
    icdf(p) {
      return p >= 0 && p <= 1 ? a - 1 + Math.floor(p * d) : NaN;
    }
  };
  return dist.min(min).max(max);
}

const standalone_SQRT2PI = Math.sqrt(2 * Math.PI);
const standalone_SQRT2 = Math.SQRT2;

let standalone_nextSample = NaN;
function standalone_sampleNormal(mean, stdev) {
  mean = mean || 0;
  stdev = stdev == null ? 1 : stdev;
  let x = 0,
    y = 0,
    rds,
    c;
  if (standalone_nextSample === standalone_nextSample) {
    x = standalone_nextSample;
    standalone_nextSample = NaN;
  } else {
    do {
      x = standalone_random() * 2 - 1;
      y = standalone_random() * 2 - 1;
      rds = x * x + y * y;
    } while (rds === 0 || rds > 1);
    c = Math.sqrt(-2 * Math.log(rds) / rds); // Box-Muller transform
    x *= c;
    standalone_nextSample = y * c;
  }
  return mean + x * stdev;
}
function standalone_densityNormal(value, mean, stdev) {
  stdev = stdev == null ? 1 : stdev;
  const z = (value - (mean || 0)) / stdev;
  return Math.exp(-0.5 * z * z) / (stdev * standalone_SQRT2PI);
}

// Approximation from West (2009)
// Better Approximations to Cumulative Normal Functions
function standalone_cumulativeNormal(value, mean, stdev) {
  mean = mean || 0;
  stdev = stdev == null ? 1 : stdev;
  const z = (value - mean) / stdev,
    Z = Math.abs(z);
  let cd;
  if (Z > 37) {
    cd = 0;
  } else {
    const exp = Math.exp(-Z * Z / 2);
    let sum;
    if (Z < 7.07106781186547) {
      sum = 3.52624965998911e-02 * Z + 0.700383064443688;
      sum = sum * Z + 6.37396220353165;
      sum = sum * Z + 33.912866078383;
      sum = sum * Z + 112.079291497871;
      sum = sum * Z + 221.213596169931;
      sum = sum * Z + 220.206867912376;
      cd = exp * sum;
      sum = 8.83883476483184e-02 * Z + 1.75566716318264;
      sum = sum * Z + 16.064177579207;
      sum = sum * Z + 86.7807322029461;
      sum = sum * Z + 296.564248779674;
      sum = sum * Z + 637.333633378831;
      sum = sum * Z + 793.826512519948;
      sum = sum * Z + 440.413735824752;
      cd = cd / sum;
    } else {
      sum = Z + 0.65;
      sum = Z + 4 / sum;
      sum = Z + 3 / sum;
      sum = Z + 2 / sum;
      sum = Z + 1 / sum;
      cd = exp / sum / 2.506628274631;
    }
  }
  return z > 0 ? 1 - cd : cd;
}

// Approximation of Probit function using inverse error function.
function standalone_quantileNormal(p, mean, stdev) {
  if (p < 0 || p > 1) return NaN;
  return (mean || 0) + (stdev == null ? 1 : stdev) * standalone_SQRT2 * standalone_erfinv(2 * p - 1);
}

// Approximate inverse error function. Implementation from "Approximating
// the erfinv function" by Mike Giles, GPU Computing Gems, volume 2, 2010.
// Ported from Apache Commons Math, http://www.apache.org/licenses/LICENSE-2.0
function standalone_erfinv(x) {
  // beware that the logarithm argument must be
  // commputed as (1.0 - x) * (1.0 + x),
  // it must NOT be simplified as 1.0 - x * x as this
  // would induce rounding errors near the boundaries +/-1
  let w = -Math.log((1 - x) * (1 + x)),
    p;
  if (w < 6.25) {
    w -= 3.125;
    p = -3.6444120640178196996e-21;
    p = -1.685059138182016589e-19 + p * w;
    p = 1.2858480715256400167e-18 + p * w;
    p = 1.115787767802518096e-17 + p * w;
    p = -1.333171662854620906e-16 + p * w;
    p = 2.0972767875968561637e-17 + p * w;
    p = 6.6376381343583238325e-15 + p * w;
    p = -4.0545662729752068639e-14 + p * w;
    p = -8.1519341976054721522e-14 + p * w;
    p = 2.6335093153082322977e-12 + p * w;
    p = -1.2975133253453532498e-11 + p * w;
    p = -5.4154120542946279317e-11 + p * w;
    p = 1.051212273321532285e-09 + p * w;
    p = -4.1126339803469836976e-09 + p * w;
    p = -2.9070369957882005086e-08 + p * w;
    p = 4.2347877827932403518e-07 + p * w;
    p = -1.3654692000834678645e-06 + p * w;
    p = -1.3882523362786468719e-05 + p * w;
    p = 0.0001867342080340571352 + p * w;
    p = -0.00074070253416626697512 + p * w;
    p = -0.0060336708714301490533 + p * w;
    p = 0.24015818242558961693 + p * w;
    p = 1.6536545626831027356 + p * w;
  } else if (w < 16.0) {
    w = Math.sqrt(w) - 3.25;
    p = 2.2137376921775787049e-09;
    p = 9.0756561938885390979e-08 + p * w;
    p = -2.7517406297064545428e-07 + p * w;
    p = 1.8239629214389227755e-08 + p * w;
    p = 1.5027403968909827627e-06 + p * w;
    p = -4.013867526981545969e-06 + p * w;
    p = 2.9234449089955446044e-06 + p * w;
    p = 1.2475304481671778723e-05 + p * w;
    p = -4.7318229009055733981e-05 + p * w;
    p = 6.8284851459573175448e-05 + p * w;
    p = 2.4031110387097893999e-05 + p * w;
    p = -0.0003550375203628474796 + p * w;
    p = 0.00095328937973738049703 + p * w;
    p = -0.0016882755560235047313 + p * w;
    p = 0.0024914420961078508066 + p * w;
    p = -0.0037512085075692412107 + p * w;
    p = 0.005370914553590063617 + p * w;
    p = 1.0052589676941592334 + p * w;
    p = 3.0838856104922207635 + p * w;
  } else if (Number.isFinite(w)) {
    w = Math.sqrt(w) - 5.0;
    p = -2.7109920616438573243e-11;
    p = -2.5556418169965252055e-10 + p * w;
    p = 1.5076572693500548083e-09 + p * w;
    p = -3.7894654401267369937e-09 + p * w;
    p = 7.6157012080783393804e-09 + p * w;
    p = -1.4960026627149240478e-08 + p * w;
    p = 2.9147953450901080826e-08 + p * w;
    p = -6.7711997758452339498e-08 + p * w;
    p = 2.2900482228026654717e-07 + p * w;
    p = -9.9298272942317002539e-07 + p * w;
    p = 4.5260625972231537039e-06 + p * w;
    p = -1.9681778105531670567e-05 + p * w;
    p = 7.5995277030017761139e-05 + p * w;
    p = -0.00021503011930044477347 + p * w;
    p = -0.00013871931833623122026 + p * w;
    p = 1.0103004648645343977 + p * w;
    p = 4.8499064014085844221 + p * w;
  } else {
    p = Infinity;
  }
  return p * x;
}
function standalone_gaussian (mean, stdev) {
  let mu, sigma;
  const dist = {
    mean(_) {
      if (arguments.length) {
        mu = _ || 0;
        return dist;
      } else {
        return mu;
      }
    },
    stdev(_) {
      if (arguments.length) {
        sigma = _ == null ? 1 : _;
        return dist;
      } else {
        return sigma;
      }
    },
    sample: () => standalone_sampleNormal(mu, sigma),
    pdf: value => standalone_densityNormal(value, mu, sigma),
    cdf: value => standalone_cumulativeNormal(value, mu, sigma),
    icdf: p => standalone_quantileNormal(p, mu, sigma)
  };
  return dist.mean(mean).stdev(stdev);
}

function standalone_kde (support, bandwidth) {
  const kernel = standalone_gaussian();
  let n = 0;
  const dist = {
    data(_) {
      if (arguments.length) {
        support = _;
        n = _ ? _.length : 0;
        return dist.bandwidth(bandwidth);
      } else {
        return support;
      }
    },
    bandwidth(_) {
      if (!arguments.length) return bandwidth;
      bandwidth = _;
      if (!bandwidth && support) bandwidth = standalone_estimateBandwidth(support);
      return dist;
    },
    sample() {
      return support[~~(standalone_random() * n)] + bandwidth * kernel.sample();
    },
    pdf(x) {
      let y = 0,
        i = 0;
      for (; i < n; ++i) {
        y += kernel.pdf((x - support[i]) / bandwidth);
      }
      return y / bandwidth / n;
    },
    cdf(x) {
      let y = 0,
        i = 0;
      for (; i < n; ++i) {
        y += kernel.cdf((x - support[i]) / bandwidth);
      }
      return y / n;
    },
    icdf() {
      throw Error('KDE icdf not supported.');
    }
  };
  return dist.data(support);
}

function standalone_sampleLogNormal(mean, stdev) {
  mean = mean || 0;
  stdev = stdev == null ? 1 : stdev;
  return Math.exp(mean + standalone_sampleNormal() * stdev);
}
function standalone_densityLogNormal(value, mean, stdev) {
  if (value <= 0) return 0;
  mean = mean || 0;
  stdev = stdev == null ? 1 : stdev;
  const z = (Math.log(value) - mean) / stdev;
  return Math.exp(-0.5 * z * z) / (stdev * standalone_SQRT2PI * value);
}
function standalone_cumulativeLogNormal(value, mean, stdev) {
  return standalone_cumulativeNormal(Math.log(value), mean, stdev);
}
function standalone_quantileLogNormal(p, mean, stdev) {
  return Math.exp(standalone_quantileNormal(p, mean, stdev));
}
function standalone_lognormal (mean, stdev) {
  let mu, sigma;
  const dist = {
    mean(_) {
      if (arguments.length) {
        mu = _ || 0;
        return dist;
      } else {
        return mu;
      }
    },
    stdev(_) {
      if (arguments.length) {
        sigma = _ == null ? 1 : _;
        return dist;
      } else {
        return sigma;
      }
    },
    sample: () => standalone_sampleLogNormal(mu, sigma),
    pdf: value => standalone_densityLogNormal(value, mu, sigma),
    cdf: value => standalone_cumulativeLogNormal(value, mu, sigma),
    icdf: p => standalone_quantileLogNormal(p, mu, sigma)
  };
  return dist.mean(mean).stdev(stdev);
}

function standalone_mixture (dists, weights) {
  let m = 0,
    w;
  function normalize(x) {
    const w = [];
    let sum = 0,
      i;
    for (i = 0; i < m; ++i) {
      sum += w[i] = x[i] == null ? 1 : +x[i];
    }
    for (i = 0; i < m; ++i) {
      w[i] /= sum;
    }
    return w;
  }
  const dist = {
    weights(_) {
      if (arguments.length) {
        w = normalize(weights = _ || []);
        return dist;
      }
      return weights;
    },
    distributions(_) {
      if (arguments.length) {
        if (_) {
          m = _.length;
          dists = _;
        } else {
          m = 0;
          dists = [];
        }
        return dist.weights(weights);
      }
      return dists;
    },
    sample() {
      const r = standalone_random();
      let d = dists[m - 1],
        v = w[0],
        i = 0;

      // first select distribution
      for (; i < m - 1; v += w[++i]) {
        if (r < v) {
          d = dists[i];
          break;
        }
      }
      // then sample from it
      return d.sample();
    },
    pdf(x) {
      let p = 0,
        i = 0;
      for (; i < m; ++i) {
        p += w[i] * dists[i].pdf(x);
      }
      return p;
    },
    cdf(x) {
      let p = 0,
        i = 0;
      for (; i < m; ++i) {
        p += w[i] * dists[i].cdf(x);
      }
      return p;
    },
    icdf() {
      throw Error('Mixture icdf not supported.');
    }
  };
  return dist.distributions(dists).weights(weights);
}

function standalone_sampleUniform(min, max) {
  if (max == null) {
    max = min == null ? 1 : min;
    min = 0;
  }
  return min + (max - min) * standalone_random();
}
function standalone_densityUniform(value, min, max) {
  if (max == null) {
    max = min == null ? 1 : min;
    min = 0;
  }
  return value >= min && value <= max ? 1 / (max - min) : 0;
}
function standalone_cumulativeUniform(value, min, max) {
  if (max == null) {
    max = min == null ? 1 : min;
    min = 0;
  }
  return value < min ? 0 : value > max ? 1 : (value - min) / (max - min);
}
function standalone_quantileUniform(p, min, max) {
  if (max == null) {
    max = min == null ? 1 : min;
    min = 0;
  }
  return p >= 0 && p <= 1 ? min + p * (max - min) : NaN;
}
function standalone_uniform (min, max) {
  let a, b;
  const dist = {
    min(_) {
      if (arguments.length) {
        a = _ || 0;
        return dist;
      } else {
        return a;
      }
    },
    max(_) {
      if (arguments.length) {
        b = _ == null ? 1 : _;
        return dist;
      } else {
        return b;
      }
    },
    sample: () => standalone_sampleUniform(a, b),
    pdf: value => standalone_densityUniform(value, a, b),
    cdf: value => standalone_cumulativeUniform(value, a, b),
    icdf: p => standalone_quantileUniform(p, a, b)
  };
  if (max == null) {
    max = min == null ? 1 : min;
    min = 0;
  }
  return dist.min(min).max(max);
}

function standalone_vega_statistics_module_constant (data, x, y) {
  let mean = 0,
    n = 0;
  for (const d of data) {
    const val = y(d);
    if (x(d) == null || val == null || isNaN(val)) continue;
    mean += (val - mean) / ++n;
  }
  return {
    coef: [mean],
    predict: () => mean,
    rSquared: 0
  };
}

// Ordinary Least Squares
function standalone_ols (uX, uY, uXY, uX2) {
  const delta = uX2 - uX * uX,
    slope = Math.abs(delta) < 1e-24 ? 0 : (uXY - uX * uY) / delta,
    intercept = uY - slope * uX;
  return [intercept, slope];
}

function standalone_points(data, x, y, sort) {
  data = data.filter(d => {
    let u = x(d),
      v = y(d);
    return u != null && (u = +u) >= u && v != null && (v = +v) >= v;
  });
  if (sort) {
    data.sort((a, b) => x(a) - x(b));
  }
  const n = data.length,
    X = new Float64Array(n),
    Y = new Float64Array(n);

  // extract values, calculate means
  let i = 0,
    ux = 0,
    uy = 0,
    xv,
    yv,
    d;
  for (d of data) {
    X[i] = xv = +x(d);
    Y[i] = yv = +y(d);
    ++i;
    ux += (xv - ux) / i;
    uy += (yv - uy) / i;
  }

  // mean center the data
  for (i = 0; i < n; ++i) {
    X[i] -= ux;
    Y[i] -= uy;
  }
  return [X, Y, ux, uy];
}
function standalone_visitPoints(data, x, y, callback) {
  let i = -1,
    u,
    v;
  for (const d of data) {
    u = x(d);
    v = y(d);
    if (u != null && (u = +u) >= u && v != null && (v = +v) >= v) {
      callback(u, v, ++i);
    }
  }
}

// Adapted from d3-regression by Harry Stevens
// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE
function standalone_rSquared (data, x, y, uY, predict) {
  let SSE = 0,
    SST = 0;
  standalone_visitPoints(data, x, y, (dx, dy) => {
    const sse = dy - predict(dx),
      sst = dy - uY;
    SSE += sse * sse;
    SST += sst * sst;
  });
  return 1 - SSE / SST;
}

// Adapted from d3-regression by Harry Stevens
// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE
function standalone_linear (data, x, y) {
  let X = 0,
    Y = 0,
    XY = 0,
    X2 = 0,
    n = 0;
  standalone_visitPoints(data, x, y, (dx, dy) => {
    ++n;
    X += (dx - X) / n;
    Y += (dy - Y) / n;
    XY += (dx * dy - XY) / n;
    X2 += (dx * dx - X2) / n;
  });
  const coef = standalone_ols(X, Y, XY, X2),
    predict = x => coef[0] + coef[1] * x;
  return {
    coef: coef,
    predict: predict,
    rSquared: standalone_rSquared(data, x, y, Y, predict)
  };
}

// Adapted from d3-regression by Harry Stevens
// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE
function standalone_vega_statistics_module_log (data, x, y) {
  let X = 0,
    Y = 0,
    XY = 0,
    X2 = 0,
    n = 0;
  standalone_visitPoints(data, x, y, (dx, dy) => {
    ++n;
    dx = Math.log(dx);
    X += (dx - X) / n;
    Y += (dy - Y) / n;
    XY += (dx * dy - XY) / n;
    X2 += (dx * dx - X2) / n;
  });
  const coef = standalone_ols(X, Y, XY, X2),
    predict = x => coef[0] + coef[1] * Math.log(x);
  return {
    coef: coef,
    predict: predict,
    rSquared: standalone_rSquared(data, x, y, Y, predict)
  };
}

function standalone_vega_statistics_module_exp (data, x, y) {
  // eslint-disable-next-line no-unused-vars
  const [xv, yv, ux, uy] = standalone_points(data, x, y);
  let YL = 0,
    XY = 0,
    XYL = 0,
    X2Y = 0,
    n = 0,
    dx,
    ly,
    xy;
  standalone_visitPoints(data, x, y, (_, dy) => {
    dx = xv[n++];
    ly = Math.log(dy);
    xy = dx * dy;
    YL += (dy * ly - YL) / n;
    XY += (xy - XY) / n;
    XYL += (xy * ly - XYL) / n;
    X2Y += (dx * xy - X2Y) / n;
  });
  const [c0, c1] = standalone_ols(XY / uy, YL / uy, XYL / uy, X2Y / uy),
    predict = x => Math.exp(c0 + c1 * (x - ux));
  return {
    coef: [Math.exp(c0 - c1 * ux), c1],
    predict: predict,
    rSquared: standalone_rSquared(data, x, y, uy, predict)
  };
}

// Adapted from d3-regression by Harry Stevens
// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE
function standalone_vega_statistics_module_pow (data, x, y) {
  let X = 0,
    Y = 0,
    XY = 0,
    X2 = 0,
    YS = 0,
    n = 0;
  standalone_visitPoints(data, x, y, (dx, dy) => {
    const lx = Math.log(dx),
      ly = Math.log(dy);
    ++n;
    X += (lx - X) / n;
    Y += (ly - Y) / n;
    XY += (lx * ly - XY) / n;
    X2 += (lx * lx - X2) / n;
    YS += (dy - YS) / n;
  });
  const coef = standalone_ols(X, Y, XY, X2),
    predict = x => coef[0] * Math.pow(x, coef[1]);
  coef[0] = Math.exp(coef[0]);
  return {
    coef: coef,
    predict: predict,
    rSquared: standalone_rSquared(data, x, y, YS, predict)
  };
}

function standalone_quad (data, x, y) {
  const [xv, yv, ux, uy] = standalone_points(data, x, y),
    n = xv.length;
  let X2 = 0,
    X3 = 0,
    X4 = 0,
    XY = 0,
    X2Y = 0,
    i,
    dx,
    dy,
    x2;
  for (i = 0; i < n;) {
    dx = xv[i];
    dy = yv[i++];
    x2 = dx * dx;
    X2 += (x2 - X2) / i;
    X3 += (x2 * dx - X3) / i;
    X4 += (x2 * x2 - X4) / i;
    XY += (dx * dy - XY) / i;
    X2Y += (x2 * dy - X2Y) / i;
  }
  const X2X2 = X4 - X2 * X2,
    d = X2 * X2X2 - X3 * X3,
    a = (X2Y * X2 - XY * X3) / d,
    b = (XY * X2X2 - X2Y * X3) / d,
    c = -a * X2,
    predict = x => {
      x = x - ux;
      return a * x * x + b * x + c + uy;
    };

  // transform coefficients back from mean-centered space
  return {
    coef: [c - b * ux + a * ux * ux + uy, b - 2 * a * ux, a],
    predict: predict,
    rSquared: standalone_rSquared(data, x, y, uy, predict)
  };
}

// Adapted from d3-regression by Harry Stevens
// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE
// ... which was adapted from regression-js by Tom Alexander
// Source: https://github.com/Tom-Alexander/regression-js/blob/master/src/regression.js#L246
// License: https://github.com/Tom-Alexander/regression-js/blob/master/LICENSE
function standalone_poly (data, x, y, order) {
  // use more efficient methods for lower orders
  if (order === 0) return standalone_vega_statistics_module_constant(data, x, y);
  if (order === 1) return standalone_linear(data, x, y);
  if (order === 2) return standalone_quad(data, x, y);
  const [xv, yv, ux, uy] = standalone_points(data, x, y),
    n = xv.length,
    lhs = [],
    rhs = [],
    k = order + 1;
  let i, j, l, v, c;
  for (i = 0; i < k; ++i) {
    for (l = 0, v = 0; l < n; ++l) {
      v += Math.pow(xv[l], i) * yv[l];
    }
    lhs.push(v);
    c = new Float64Array(k);
    for (j = 0; j < k; ++j) {
      for (l = 0, v = 0; l < n; ++l) {
        v += Math.pow(xv[l], i + j);
      }
      c[j] = v;
    }
    rhs.push(c);
  }
  rhs.push(lhs);
  const coef = standalone_gaussianElimination(rhs),
    predict = x => {
      x -= ux;
      let y = uy + coef[0] + coef[1] * x + coef[2] * x * x;
      for (i = 3; i < k; ++i) y += coef[i] * Math.pow(x, i);
      return y;
    };
  return {
    coef: standalone_uncenter(k, coef, -ux, uy),
    predict: predict,
    rSquared: standalone_rSquared(data, x, y, uy, predict)
  };
}
function standalone_uncenter(k, a, x, y) {
  const z = Array(k);
  let i, j, v, c;

  // initialize to zero
  for (i = 0; i < k; ++i) z[i] = 0;

  // polynomial expansion
  for (i = k - 1; i >= 0; --i) {
    v = a[i];
    c = 1;
    z[i] += v;
    for (j = 1; j <= i; ++j) {
      c *= (i + 1 - j) / j; // binomial coefficent
      z[i - j] += v * Math.pow(x, j) * c;
    }
  }

  // bias term
  z[0] += y;
  return z;
}

// Given an array for a two-dimensional matrix and the polynomial order,
// solve A * x = b using Gaussian elimination.
function standalone_gaussianElimination(matrix) {
  const n = matrix.length - 1,
    coef = [];
  let i, j, k, r, t;
  for (i = 0; i < n; ++i) {
    r = i; // max row
    for (j = i + 1; j < n; ++j) {
      if (Math.abs(matrix[i][j]) > Math.abs(matrix[i][r])) {
        r = j;
      }
    }
    for (k = i; k < n + 1; ++k) {
      t = matrix[k][i];
      matrix[k][i] = matrix[k][r];
      matrix[k][r] = t;
    }
    for (j = i + 1; j < n; ++j) {
      for (k = n; k >= i; k--) {
        matrix[k][j] -= matrix[k][i] * matrix[i][j] / matrix[i][i];
      }
    }
  }
  for (j = n - 1; j >= 0; --j) {
    t = 0;
    for (k = j + 1; k < n; ++k) {
      t += matrix[k][j] * coef[k];
    }
    coef[j] = (matrix[n][j] - t) / matrix[j][j];
  }
  return coef;
}

const standalone_maxiters = 2,
  standalone_epsilon = 1e-12;

// Adapted from science.js by Jason Davies
// Source: https://github.com/jasondavies/science.js/blob/master/src/stats/loess.js
// License: https://github.com/jasondavies/science.js/blob/master/LICENSE
function standalone_loess (data, x, y, bandwidth) {
  const [xv, yv, ux, uy] = standalone_points(data, x, y, true),
    n = xv.length,
    bw = Math.max(2, ~~(bandwidth * n)),
    // # nearest neighbors
    yhat = new Float64Array(n),
    residuals = new Float64Array(n),
    robustWeights = new Float64Array(n).fill(1);
  for (let iter = -1; ++iter <= standalone_maxiters;) {
    const interval = [0, bw - 1];
    for (let i = 0; i < n; ++i) {
      const dx = xv[i],
        i0 = interval[0],
        i1 = interval[1],
        edge = dx - xv[i0] > xv[i1] - dx ? i0 : i1;
      let W = 0,
        X = 0,
        Y = 0,
        XY = 0,
        X2 = 0;
      const denom = 1 / Math.abs(xv[edge] - dx || 1); // avoid singularity!

      for (let k = i0; k <= i1; ++k) {
        const xk = xv[k],
          yk = yv[k],
          w = standalone_tricube(Math.abs(dx - xk) * denom) * robustWeights[k],
          xkw = xk * w;
        W += w;
        X += xkw;
        Y += yk * w;
        XY += yk * xkw;
        X2 += xk * xkw;
      }

      // linear regression fit
      const [a, b] = standalone_ols(X / W, Y / W, XY / W, X2 / W);
      yhat[i] = a + b * dx;
      residuals[i] = Math.abs(yv[i] - yhat[i]);
      standalone_updateInterval(xv, i + 1, interval);
    }
    if (iter === standalone_maxiters) {
      break;
    }
    const medianResidual = standalone_median(residuals);
    if (Math.abs(medianResidual) < standalone_epsilon) break;
    for (let i = 0, arg, w; i < n; ++i) {
      arg = residuals[i] / (6 * medianResidual);
      // default to epsilon (rather than zero) for large deviations
      // keeping weights tiny but non-zero prevents singularites
      robustWeights[i] = arg >= 1 ? standalone_epsilon : (w = 1 - arg * arg) * w;
    }
  }
  return standalone_output(xv, yhat, ux, uy);
}

// weighting kernel for local regression
function standalone_tricube(x) {
  return (x = 1 - x * x * x) * x * x;
}

// advance sliding window interval of nearest neighbors
function standalone_updateInterval(xv, i, interval) {
  const val = xv[i];
  let left = interval[0],
    right = interval[1] + 1;
  if (right >= xv.length) return;

  // step right if distance to new right edge is <= distance to old left edge
  // step when distance is equal to ensure movement over duplicate x values
  while (i > left && xv[right] - val <= val - xv[left]) {
    interval[0] = ++left;
    interval[1] = right;
    ++right;
  }
}

// generate smoothed output points
// average points with repeated x values
function standalone_output(xv, yhat, ux, uy) {
  const n = xv.length,
    out = [];
  let i = 0,
    cnt = 0,
    prev = [],
    v;
  for (; i < n; ++i) {
    v = xv[i] + ux;
    if (prev[0] === v) {
      // average output values via online update
      prev[1] += (yhat[i] - prev[1]) / ++cnt;
    } else {
      // add new output point
      cnt = 0;
      prev[1] += uy;
      prev = [v, yhat[i]];
      out.push(prev);
    }
  }
  prev[1] += uy;
  return out;
}

// subdivide up to accuracy of 0.5 degrees
const standalone_MIN_RADIANS = 0.5 * Math.PI / 180;

// Adaptively sample an interpolated function over a domain extent
function standalone_sampleCurve (f, extent, minSteps, maxSteps) {
  minSteps = minSteps || 25;
  maxSteps = Math.max(minSteps, maxSteps || 200);
  const point = x => [x, f(x)],
    minX = extent[0],
    maxX = extent[1],
    span = maxX - minX,
    stop = span / maxSteps,
    prev = [point(minX)],
    next = [];
  if (minSteps === maxSteps) {
    // no adaptation, sample uniform grid directly and return
    for (let i = 1; i < maxSteps; ++i) {
      prev.push(point(minX + i / minSteps * span));
    }
    prev.push(point(maxX));
    return prev;
  } else {
    // sample minimum points on uniform grid
    // then move on to perform adaptive refinement
    next.push(point(maxX));
    for (let i = minSteps; --i > 0;) {
      next.push(point(minX + i / minSteps * span));
    }
  }
  let p0 = prev[0];
  let p1 = next[next.length - 1];
  const sx = 1 / span;
  const sy = standalone_scaleY(p0[1], next);
  while (p1) {
    // midpoint for potential curve subdivision
    const pm = point((p0[0] + p1[0]) / 2);
    const dx = pm[0] - p0[0] >= stop;
    if (dx && standalone_angleDelta(p0, pm, p1, sx, sy) > standalone_MIN_RADIANS) {
      // maximum resolution has not yet been met, and
      // subdivision midpoint is sufficiently different from endpoint
      // save subdivision, push midpoint onto the visitation stack
      next.push(pm);
    } else {
      // subdivision midpoint sufficiently similar to endpoint
      // skip subdivision, store endpoint, move to next point on the stack
      p0 = p1;
      prev.push(p1);
      next.pop();
    }
    p1 = next[next.length - 1];
  }
  return prev;
}
function standalone_scaleY(init, points) {
  let ymin = init;
  let ymax = init;
  const n = points.length;
  for (let i = 0; i < n; ++i) {
    const y = points[i][1];
    if (y < ymin) ymin = y;
    if (y > ymax) ymax = y;
  }
  return 1 / (ymax - ymin);
}
function standalone_angleDelta(p, q, r, sx, sy) {
  const a0 = Math.atan2(sy * (r[1] - p[1]), sx * (r[0] - p[0])),
    a1 = Math.atan2(sy * (q[1] - p[1]), sx * (q[0] - p[0]));
  return Math.abs(a0 - a1);
}



;// ../../node_modules/d3-array/src/mean.js
function standalone_mean(values, valueof) {
  let count = 0;
  let sum = 0;
  if (valueof === undefined) {
    for (let value of values) {
      if (value != null && (value = +value) >= value) {
        ++count, sum += value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {
        ++count, sum += value;
      }
    }
  }
  if (count) return sum / count;
}

;// ../../node_modules/d3-array/src/range.js
function standalone_range(start, stop, step) {
  start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;

  var i = -1,
      n = Math.max(0, Math.ceil((stop - start) / step)) | 0,
      range = new Array(n);

  while (++i < n) {
    range[i] = start + i * step;
  }

  return range;
}

;// ../../node_modules/vega-transforms/build/vega-transforms.module.js






function standalone_multikey(f) {
  return x => {
    const n = f.length;
    let i = 1,
      k = String(f[0](x));
    for (; i < n; ++i) {
      k += '|' + f[i](x);
    }
    return k;
  };
}
function standalone_groupkey(fields) {
  return !fields || !fields.length ? function () {
    return '';
  } : fields.length === 1 ? fields[0] : standalone_multikey(fields);
}

function standalone_measureName(op, field, as) {
  return as || op + (!field ? '' : '_' + field);
}
const standalone_vega_transforms_module_noop = () => {};
const standalone_base_op = {
  init: standalone_vega_transforms_module_noop,
  add: standalone_vega_transforms_module_noop,
  rem: standalone_vega_transforms_module_noop,
  idx: 0
};
const standalone_AggregateOps = {
  values: {
    init: m => m.cell.store = true,
    value: m => m.cell.data.values(),
    idx: -1
  },
  count: {
    value: m => m.cell.num
  },
  __count__: {
    value: m => m.missing + m.valid
  },
  missing: {
    value: m => m.missing
  },
  valid: {
    value: m => m.valid
  },
  sum: {
    init: m => m.sum = 0,
    value: m => m.valid ? m.sum : undefined,
    add: (m, v) => m.sum += +v,
    rem: (m, v) => m.sum -= v
  },
  product: {
    init: m => m.product = 1,
    value: m => m.valid ? m.product : undefined,
    add: (m, v) => m.product *= v,
    rem: (m, v) => m.product /= v
  },
  mean: {
    init: m => m.mean = 0,
    value: m => m.valid ? m.mean : undefined,
    add: (m, v) => (m.mean_d = v - m.mean, m.mean += m.mean_d / m.valid),
    rem: (m, v) => (m.mean_d = v - m.mean, m.mean -= m.valid ? m.mean_d / m.valid : m.mean)
  },
  average: {
    value: m => m.valid ? m.mean : undefined,
    req: ['mean'],
    idx: 1
  },
  variance: {
    init: m => m.dev = 0,
    value: m => m.valid > 1 ? m.dev / (m.valid - 1) : undefined,
    add: (m, v) => m.dev += m.mean_d * (v - m.mean),
    rem: (m, v) => m.dev -= m.mean_d * (v - m.mean),
    req: ['mean'],
    idx: 1
  },
  variancep: {
    value: m => m.valid > 1 ? m.dev / m.valid : undefined,
    req: ['variance'],
    idx: 2
  },
  stdev: {
    value: m => m.valid > 1 ? Math.sqrt(m.dev / (m.valid - 1)) : undefined,
    req: ['variance'],
    idx: 2
  },
  stdevp: {
    value: m => m.valid > 1 ? Math.sqrt(m.dev / m.valid) : undefined,
    req: ['variance'],
    idx: 2
  },
  stderr: {
    value: m => m.valid > 1 ? Math.sqrt(m.dev / (m.valid * (m.valid - 1))) : undefined,
    req: ['variance'],
    idx: 2
  },
  distinct: {
    value: m => m.cell.data.distinct(m.get),
    req: ['values'],
    idx: 3
  },
  ci0: {
    value: m => m.cell.data.ci0(m.get),
    req: ['values'],
    idx: 3
  },
  ci1: {
    value: m => m.cell.data.ci1(m.get),
    req: ['values'],
    idx: 3
  },
  median: {
    value: m => m.cell.data.q2(m.get),
    req: ['values'],
    idx: 3
  },
  q1: {
    value: m => m.cell.data.q1(m.get),
    req: ['values'],
    idx: 3
  },
  q3: {
    value: m => m.cell.data.q3(m.get),
    req: ['values'],
    idx: 3
  },
  min: {
    init: m => m.min = undefined,
    value: m => m.min = Number.isNaN(m.min) ? m.cell.data.min(m.get) : m.min,
    add: (m, v) => {
      if (v < m.min || m.min === undefined) m.min = v;
    },
    rem: (m, v) => {
      if (v <= m.min) m.min = NaN;
    },
    req: ['values'],
    idx: 4
  },
  max: {
    init: m => m.max = undefined,
    value: m => m.max = Number.isNaN(m.max) ? m.cell.data.max(m.get) : m.max,
    add: (m, v) => {
      if (v > m.max || m.max === undefined) m.max = v;
    },
    rem: (m, v) => {
      if (v >= m.max) m.max = NaN;
    },
    req: ['values'],
    idx: 4
  },
  argmin: {
    init: m => m.argmin = undefined,
    value: m => m.argmin || m.cell.data.argmin(m.get),
    add: (m, v, t) => {
      if (v < m.min) m.argmin = t;
    },
    rem: (m, v) => {
      if (v <= m.min) m.argmin = undefined;
    },
    req: ['min', 'values'],
    idx: 3
  },
  argmax: {
    init: m => m.argmax = undefined,
    value: m => m.argmax || m.cell.data.argmax(m.get),
    add: (m, v, t) => {
      if (v > m.max) m.argmax = t;
    },
    rem: (m, v) => {
      if (v >= m.max) m.argmax = undefined;
    },
    req: ['max', 'values'],
    idx: 3
  },
  exponential: {
    init: (m, r) => {
      m.exp = 0;
      m.exp_r = r;
    },
    value: m => m.valid ? m.exp * (1 - m.exp_r) / (1 - m.exp_r ** m.valid) : undefined,
    add: (m, v) => m.exp = m.exp_r * m.exp + v,
    rem: (m, v) => m.exp = (m.exp - v / m.exp_r ** (m.valid - 1)) / m.exp_r
  },
  exponentialb: {
    value: m => m.valid ? m.exp * (1 - m.exp_r) : undefined,
    req: ['exponential'],
    idx: 1
  }
};
const standalone_ValidAggregateOps = Object.keys(standalone_AggregateOps).filter(d => d !== '__count__');
function standalone_measure(key, value) {
  return (out, aggregate_param) => standalone_extend({
    name: key,
    aggregate_param: aggregate_param,
    out: out || key
  }, standalone_base_op, value);
}
[...standalone_ValidAggregateOps, '__count__'].forEach(key => {
  standalone_AggregateOps[key] = standalone_measure(key, standalone_AggregateOps[key]);
});
function standalone_createMeasure(op, param, name) {
  return standalone_AggregateOps[op](name, param);
}
function standalone_compareIndex(a, b) {
  return a.idx - b.idx;
}
function standalone_vega_transforms_module_resolve(agg) {
  const map = {};
  agg.forEach(a => map[a.name] = a);
  const getreqs = a => {
    if (!a.req) return;
    a.req.forEach(key => {
      if (!map[key]) getreqs(map[key] = standalone_AggregateOps[key]());
    });
  };
  agg.forEach(getreqs);
  return Object.values(map).sort(standalone_compareIndex);
}
function standalone_vega_transforms_module_init() {
  this.valid = 0;
  this.missing = 0;
  this._ops.forEach(op => op.aggregate_param == null ? op.init(this) : op.init(this, op.aggregate_param));
}
function standalone_vega_transforms_module_add(v, t) {
  if (v == null || v === '') {
    ++this.missing;
    return;
  }
  if (v !== v) return;
  ++this.valid;
  this._ops.forEach(op => op.add(this, v, t));
}
function standalone_rem(v, t) {
  if (v == null || v === '') {
    --this.missing;
    return;
  }
  if (v !== v) return;
  --this.valid;
  this._ops.forEach(op => op.rem(this, v, t));
}
function standalone_set(t) {
  this._out.forEach(op => t[op.out] = op.value(this));
  return t;
}
function standalone_compileMeasures(agg, field) {
  const get = field || standalone_vega_util_module_identity,
    ops = standalone_vega_transforms_module_resolve(agg),
    out = agg.slice().sort(standalone_compareIndex);
  function ctr(cell) {
    this._ops = ops;
    this._out = out;
    this.cell = cell;
    this.init();
  }
  ctr.prototype.init = standalone_vega_transforms_module_init;
  ctr.prototype.add = standalone_vega_transforms_module_add;
  ctr.prototype.rem = standalone_rem;
  ctr.prototype.set = standalone_set;
  ctr.prototype.get = get;
  ctr.fields = agg.map(op => op.out);
  return ctr;
}

function standalone_TupleStore(key) {
  this._key = key ? standalone_field(key) : standalone_tupleid;
  this.reset();
}
const standalone_prototype$1 = standalone_TupleStore.prototype;
standalone_prototype$1.reset = function () {
  this._add = [];
  this._rem = [];
  this._ext = null;
  this._get = null;
  this._q = null;
};
standalone_prototype$1.add = function (v) {
  this._add.push(v);
};
standalone_prototype$1.rem = function (v) {
  this._rem.push(v);
};
standalone_prototype$1.values = function () {
  this._get = null;
  if (this._rem.length === 0) return this._add;
  const a = this._add,
    r = this._rem,
    k = this._key,
    n = a.length,
    m = r.length,
    x = Array(n - m),
    map = {};
  let i, j, v;

  // use unique key field to clear removed values
  for (i = 0; i < m; ++i) {
    map[k(r[i])] = 1;
  }
  for (i = 0, j = 0; i < n; ++i) {
    if (map[k(v = a[i])]) {
      map[k(v)] = 0;
    } else {
      x[j++] = v;
    }
  }
  this._rem = [];
  return this._add = x;
};

// memoizing statistics methods

standalone_prototype$1.distinct = function (get) {
  const v = this.values(),
    map = {};
  let n = v.length,
    count = 0,
    s;
  while (--n >= 0) {
    s = get(v[n]) + '';
    if (!standalone_vega_util_module_has(map, s)) {
      map[s] = 1;
      ++count;
    }
  }
  return count;
};
standalone_prototype$1.extent = function (get) {
  if (this._get !== get || !this._ext) {
    const v = this.values(),
      i = standalone_extentIndex(v, get);
    this._ext = [v[i[0]], v[i[1]]];
    this._get = get;
  }
  return this._ext;
};
standalone_prototype$1.argmin = function (get) {
  return this.extent(get)[0] || {};
};
standalone_prototype$1.argmax = function (get) {
  return this.extent(get)[1] || {};
};
standalone_prototype$1.min = function (get) {
  const m = this.extent(get)[0];
  return m != null ? get(m) : undefined;
};
standalone_prototype$1.max = function (get) {
  const m = this.extent(get)[1];
  return m != null ? get(m) : undefined;
};
standalone_prototype$1.quartile = function (get) {
  if (this._get !== get || !this._q) {
    this._q = standalone_quartiles(this.values(), get);
    this._get = get;
  }
  return this._q;
};
standalone_prototype$1.q1 = function (get) {
  return this.quartile(get)[0];
};
standalone_prototype$1.q2 = function (get) {
  return this.quartile(get)[1];
};
standalone_prototype$1.q3 = function (get) {
  return this.quartile(get)[2];
};
standalone_prototype$1.ci = function (get) {
  if (this._get !== get || !this._ci) {
    this._ci = standalone_bootstrapCI(this.values(), 1000, 0.05, get);
    this._get = get;
  }
  return this._ci;
};
standalone_prototype$1.ci0 = function (get) {
  return this.ci(get)[0];
};
standalone_prototype$1.ci1 = function (get) {
  return this.ci(get)[1];
};

/**
 * Group-by aggregation operator.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby.
 * @param {Array<function(object): *>} [params.fields] - An array of accessors to aggregate.
 * @param {Array<string>} [params.ops] - An array of strings indicating aggregation operations.
 * @param {Array<number>} [params.aggregate_params] - An optional array of parameters for aggregation operations.
 * @param {Array<string>} [params.as] - An array of output field names for aggregated values.
 * @param {boolean} [params.cross=false] - A flag indicating that the full
 *   cross-product of groupby values should be generated, including empty cells.
 *   If true, the drop parameter is ignored and empty cells are retained.
 * @param {boolean} [params.drop=true] - A flag indicating if empty cells should be removed.
 */
function standalone_Aggregate(params) {
  standalone_Transform.call(this, null, params);
  this._adds = []; // array of added output tuples
  this._mods = []; // array of modified output tuples
  this._alen = 0; // number of active added tuples
  this._mlen = 0; // number of active modified tuples
  this._drop = true; // should empty aggregation cells be removed
  this._cross = false; // produce full cross-product of group-by values

  this._dims = []; // group-by dimension accessors
  this._dnames = []; // group-by dimension names

  this._measures = []; // collection of aggregation monoids
  this._countOnly = false; // flag indicating only count aggregation
  this._counts = null; // collection of count fields
  this._prev = null; // previous aggregation cells

  this._inputs = null; // array of dependent input tuple field names
  this._outputs = null; // array of output tuple field names
}
standalone_Aggregate.Definition = {
  'type': 'Aggregate',
  'metadata': {
    'generates': true,
    'changes': true
  },
  'params': [{
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'ops',
    'type': 'enum',
    'array': true,
    'values': standalone_ValidAggregateOps
  }, {
    'name': 'aggregate_params',
    'type': 'number',
    'null': true,
    'array': true
  }, {
    'name': 'fields',
    'type': 'field',
    'null': true,
    'array': true
  }, {
    'name': 'as',
    'type': 'string',
    'null': true,
    'array': true
  }, {
    'name': 'drop',
    'type': 'boolean',
    'default': true
  }, {
    'name': 'cross',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'key',
    'type': 'field'
  }]
};
standalone_inherits(standalone_Aggregate, standalone_Transform, {
  transform(_, pulse) {
    const aggr = this,
      out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
      mod = _.modified();
    aggr.stamp = out.stamp;
    if (aggr.value && (mod || pulse.modified(aggr._inputs, true))) {
      aggr._prev = aggr.value;
      aggr.value = mod ? aggr.init(_) : Object.create(null);
      pulse.visit(pulse.SOURCE, t => aggr.add(t));
    } else {
      aggr.value = aggr.value || aggr.init(_);
      pulse.visit(pulse.REM, t => aggr.rem(t));
      pulse.visit(pulse.ADD, t => aggr.add(t));
    }

    // Indicate output fields and return aggregate tuples.
    out.modifies(aggr._outputs);

    // Should empty cells be dropped?
    aggr._drop = _.drop !== false;

    // If domain cross-product requested, generate empty cells as needed
    // and ensure that empty cells are not dropped
    if (_.cross && aggr._dims.length > 1) {
      aggr._drop = false;
      aggr.cross();
    }
    if (pulse.clean() && aggr._drop) {
      out.clean(true).runAfter(() => this.clean());
    }
    return aggr.changes(out);
  },
  cross() {
    const aggr = this,
      curr = aggr.value,
      dims = aggr._dnames,
      vals = dims.map(() => ({})),
      n = dims.length;

    // collect all group-by domain values
    function collect(cells) {
      let key, i, t, v;
      for (key in cells) {
        t = cells[key].tuple;
        for (i = 0; i < n; ++i) {
          vals[i][v = t[dims[i]]] = v;
        }
      }
    }
    collect(aggr._prev);
    collect(curr);

    // iterate over key cross-product, create cells as needed
    function generate(base, tuple, index) {
      const name = dims[index],
        v = vals[index++];
      for (const k in v) {
        const key = base ? base + '|' + k : k;
        tuple[name] = v[k];
        if (index < n) generate(key, tuple, index);else if (!curr[key]) aggr.cell(key, tuple);
      }
    }
    generate('', {}, 0);
  },
  init(_) {
    // initialize input and output fields
    const inputs = this._inputs = [],
      outputs = this._outputs = [],
      inputMap = {};
    function inputVisit(get) {
      const fields = standalone_array(standalone_accessorFields(get)),
        n = fields.length;
      let i = 0,
        f;
      for (; i < n; ++i) {
        if (!inputMap[f = fields[i]]) {
          inputMap[f] = 1;
          inputs.push(f);
        }
      }
    }

    // initialize group-by dimensions
    this._dims = standalone_array(_.groupby);
    this._dnames = this._dims.map(d => {
      const dname = standalone_accessorName(d);
      inputVisit(d);
      outputs.push(dname);
      return dname;
    });
    this.cellkey = _.key ? _.key : standalone_groupkey(this._dims);

    // initialize aggregate measures
    this._countOnly = true;
    this._counts = [];
    this._measures = [];
    const fields = _.fields || [null],
      ops = _.ops || ['count'],
      aggregate_params = _.aggregate_params || [null],
      as = _.as || [],
      n = fields.length,
      map = {};
    let field, op, aggregate_param, m, mname, outname, i;
    if (n !== ops.length) {
      standalone_vega_util_module_error('Unmatched number of fields and aggregate ops.');
    }
    for (i = 0; i < n; ++i) {
      field = fields[i];
      op = ops[i];
      aggregate_param = aggregate_params[i] || null;
      if (field == null && op !== 'count') {
        standalone_vega_util_module_error('Null aggregate field specified.');
      }
      mname = standalone_accessorName(field);
      outname = standalone_measureName(op, mname, as[i]);
      outputs.push(outname);
      if (op === 'count') {
        this._counts.push(outname);
        continue;
      }
      m = map[mname];
      if (!m) {
        inputVisit(field);
        m = map[mname] = [];
        m.field = field;
        this._measures.push(m);
      }
      if (op !== 'count') this._countOnly = false;
      m.push(standalone_createMeasure(op, aggregate_param, outname));
    }
    this._measures = this._measures.map(m => standalone_compileMeasures(m, m.field));
    return Object.create(null); // aggregation cells (this.value)
  },
  // -- Cell Management -----

  cellkey: standalone_groupkey(),
  cell(key, t) {
    let cell = this.value[key];
    if (!cell) {
      cell = this.value[key] = this.newcell(key, t);
      this._adds[this._alen++] = cell;
    } else if (cell.num === 0 && this._drop && cell.stamp < this.stamp) {
      cell.stamp = this.stamp;
      this._adds[this._alen++] = cell;
    } else if (cell.stamp < this.stamp) {
      cell.stamp = this.stamp;
      this._mods[this._mlen++] = cell;
    }
    return cell;
  },
  newcell(key, t) {
    const cell = {
      key: key,
      num: 0,
      agg: null,
      tuple: this.newtuple(t, this._prev && this._prev[key]),
      stamp: this.stamp,
      store: false
    };
    if (!this._countOnly) {
      const measures = this._measures,
        n = measures.length;
      cell.agg = Array(n);
      for (let i = 0; i < n; ++i) {
        cell.agg[i] = new measures[i](cell);
      }
    }
    if (cell.store) {
      cell.data = new standalone_TupleStore();
    }
    return cell;
  },
  newtuple(t, p) {
    const names = this._dnames,
      dims = this._dims,
      n = dims.length,
      x = {};
    for (let i = 0; i < n; ++i) {
      x[names[i]] = dims[i](t);
    }
    return p ? standalone_replace(p.tuple, x) : standalone_ingest$1(x);
  },
  clean() {
    const cells = this.value;
    for (const key in cells) {
      if (cells[key].num === 0) {
        delete cells[key];
      }
    }
  },
  // -- Process Tuples -----

  add(t) {
    const key = this.cellkey(t),
      cell = this.cell(key, t);
    cell.num += 1;
    if (this._countOnly) return;
    if (cell.store) cell.data.add(t);
    const agg = cell.agg;
    for (let i = 0, n = agg.length; i < n; ++i) {
      agg[i].add(agg[i].get(t), t);
    }
  },
  rem(t) {
    const key = this.cellkey(t),
      cell = this.cell(key, t);
    cell.num -= 1;
    if (this._countOnly) return;
    if (cell.store) cell.data.rem(t);
    const agg = cell.agg;
    for (let i = 0, n = agg.length; i < n; ++i) {
      agg[i].rem(agg[i].get(t), t);
    }
  },
  celltuple(cell) {
    const tuple = cell.tuple,
      counts = this._counts;

    // consolidate stored values
    if (cell.store) {
      cell.data.values();
    }

    // update tuple properties
    for (let i = 0, n = counts.length; i < n; ++i) {
      tuple[counts[i]] = cell.num;
    }
    if (!this._countOnly) {
      const agg = cell.agg;
      for (let i = 0, n = agg.length; i < n; ++i) {
        agg[i].set(tuple);
      }
    }
    return tuple;
  },
  changes(out) {
    const adds = this._adds,
      mods = this._mods,
      prev = this._prev,
      drop = this._drop,
      add = out.add,
      rem = out.rem,
      mod = out.mod;
    let cell, key, i, n;
    if (prev) for (key in prev) {
      cell = prev[key];
      if (!drop || cell.num) rem.push(cell.tuple);
    }
    for (i = 0, n = this._alen; i < n; ++i) {
      add.push(this.celltuple(adds[i]));
      adds[i] = null; // for garbage collection
    }
    for (i = 0, n = this._mlen; i < n; ++i) {
      cell = mods[i];
      (cell.num === 0 && drop ? rem : mod).push(this.celltuple(cell));
      mods[i] = null; // for garbage collection
    }
    this._alen = this._mlen = 0; // reset list of active cells
    this._prev = null;
    return out;
  }
});

// epsilon bias to offset floating point error (#1737)
const standalone_EPSILON$1 = 1e-14;

/**
 * Generates a binning function for discretizing data.
 * @constructor
 * @param {object} params - The parameters for this operator. The
 *   provided values should be valid options for the {@link bin} function.
 * @param {function(object): *} params.field - The data field to bin.
 */
function standalone_Bin(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Bin.Definition = {
  'type': 'Bin',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'field',
    'type': 'field',
    'required': true
  }, {
    'name': 'interval',
    'type': 'boolean',
    'default': true
  }, {
    'name': 'anchor',
    'type': 'number'
  }, {
    'name': 'maxbins',
    'type': 'number',
    'default': 20
  }, {
    'name': 'base',
    'type': 'number',
    'default': 10
  }, {
    'name': 'divide',
    'type': 'number',
    'array': true,
    'default': [5, 2]
  }, {
    'name': 'extent',
    'type': 'number',
    'array': true,
    'length': 2,
    'required': true
  }, {
    'name': 'span',
    'type': 'number'
  }, {
    'name': 'step',
    'type': 'number'
  }, {
    'name': 'steps',
    'type': 'number',
    'array': true
  }, {
    'name': 'minstep',
    'type': 'number',
    'default': 0
  }, {
    'name': 'nice',
    'type': 'boolean',
    'default': true
  }, {
    'name': 'name',
    'type': 'string'
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': 2,
    'default': ['bin0', 'bin1']
  }]
};
standalone_inherits(standalone_Bin, standalone_Transform, {
  transform(_, pulse) {
    const band = _.interval !== false,
      bins = this._bins(_),
      start = bins.start,
      step = bins.step,
      as = _.as || ['bin0', 'bin1'],
      b0 = as[0],
      b1 = as[1];
    let flag;
    if (_.modified()) {
      pulse = pulse.reflow(true);
      flag = pulse.SOURCE;
    } else {
      flag = pulse.modified(standalone_accessorFields(_.field)) ? pulse.ADD_MOD : pulse.ADD;
    }
    pulse.visit(flag, band ? t => {
      const v = bins(t);
      // minimum bin value (inclusive)
      t[b0] = v;
      // maximum bin value (exclusive)
      // use convoluted math for better floating point agreement
      // see https://github.com/vega/vega/issues/830
      // infinite values propagate through this formula! #2227
      t[b1] = v == null ? null : start + step * (1 + (v - start) / step);
    } : t => t[b0] = bins(t));
    return pulse.modifies(band ? as : b0);
  },
  _bins(_) {
    if (this.value && !_.modified()) {
      return this.value;
    }
    const field = _.field,
      bins = standalone_vega_statistics_module_bin(_),
      step = bins.step;
    let start = bins.start,
      stop = start + Math.ceil((bins.stop - start) / step) * step,
      a,
      d;
    if ((a = _.anchor) != null) {
      d = a - (start + step * Math.floor((a - start) / step));
      start += d;
      stop += d;
    }
    const f = function (t) {
      let v = standalone_toNumber(field(t));
      return v == null ? null : v < start ? -Infinity : v > stop ? +Infinity : (v = Math.max(start, Math.min(v, stop - step)), start + step * Math.floor(standalone_EPSILON$1 + (v - start) / step));
    };
    f.start = start;
    f.stop = bins.stop;
    f.step = step;
    return this.value = standalone_accessor(f, standalone_accessorFields(field), _.name || 'bin_' + standalone_accessorName(field));
  }
});

function standalone_SortedList (idFunc, source, input) {
  const $ = idFunc;
  let data = source || [],
    add = input || [],
    rem = {},
    cnt = 0;
  return {
    add: t => add.push(t),
    remove: t => rem[$(t)] = ++cnt,
    size: () => data.length,
    data: (compare, resort) => {
      if (cnt) {
        data = data.filter(t => !rem[$(t)]);
        rem = {};
        cnt = 0;
      }
      if (resort && compare) {
        data.sort(compare);
      }
      if (add.length) {
        data = compare ? standalone_merge(compare, data, add.sort(compare)) : data.concat(add);
        add = [];
      }
      return data;
    }
  };
}

/**
 * Collects all data tuples that pass through this operator.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(*,*): number} [params.sort] - An optional
 *   comparator function for additionally sorting the collected tuples.
 */
function standalone_Collect(params) {
  standalone_Transform.call(this, [], params);
}
standalone_Collect.Definition = {
  'type': 'Collect',
  'metadata': {
    'source': true
  },
  'params': [{
    'name': 'sort',
    'type': 'compare'
  }]
};
standalone_inherits(standalone_Collect, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.ALL),
      list = standalone_SortedList(standalone_tupleid, this.value, out.materialize(out.ADD).add),
      sort = _.sort,
      mod = pulse.changed() || sort && (_.modified('sort') || pulse.modified(sort.fields));
    out.visit(out.REM, list.remove);
    this.modified(mod);
    this.value = out.source = list.data(standalone_stableCompare(sort), mod);

    // propagate tree root if defined
    if (pulse.source && pulse.source.root) {
      this.value.root = pulse.source.root;
    }
    return out;
  }
});

/**
 * Generates a comparator function.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<string|function>} params.fields - The fields to compare.
 * @param {Array<string>} [params.orders] - The sort orders.
 *   Each entry should be one of "ascending" (default) or "descending".
 */
function standalone_Compare(params) {
  standalone_Operator.call(this, null, standalone_update$5, params);
}
standalone_inherits(standalone_Compare, standalone_Operator);
function standalone_update$5(_) {
  return this.value && !_.modified() ? this.value : standalone_compare(_.fields, _.orders);
}

/**
 * Count regexp-defined pattern occurrences in a text field.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - An accessor for the text field.
 * @param {string} [params.pattern] - RegExp string defining the text pattern.
 * @param {string} [params.case] - One of 'lower', 'upper' or null (mixed) case.
 * @param {string} [params.stopwords] - RegExp string of words to ignore.
 */
function standalone_CountPattern(params) {
  standalone_Transform.call(this, null, params);
}
standalone_CountPattern.Definition = {
  'type': 'CountPattern',
  'metadata': {
    'generates': true,
    'changes': true
  },
  'params': [{
    'name': 'field',
    'type': 'field',
    'required': true
  }, {
    'name': 'case',
    'type': 'enum',
    'values': ['upper', 'lower', 'mixed'],
    'default': 'mixed'
  }, {
    'name': 'pattern',
    'type': 'string',
    'default': '[\\w"]+'
  }, {
    'name': 'stopwords',
    'type': 'string',
    'default': ''
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': 2,
    'default': ['text', 'count']
  }]
};
function standalone_tokenize(text, tcase, match) {
  switch (tcase) {
    case 'upper':
      text = text.toUpperCase();
      break;
    case 'lower':
      text = text.toLowerCase();
      break;
  }
  return text.match(match);
}
standalone_inherits(standalone_CountPattern, standalone_Transform, {
  transform(_, pulse) {
    const process = update => tuple => {
      var tokens = standalone_tokenize(get(tuple), _.case, match) || [],
        t;
      for (var i = 0, n = tokens.length; i < n; ++i) {
        if (!stop.test(t = tokens[i])) update(t);
      }
    };
    const init = this._parameterCheck(_, pulse),
      counts = this._counts,
      match = this._match,
      stop = this._stop,
      get = _.field,
      as = _.as || ['text', 'count'],
      add = process(t => counts[t] = 1 + (counts[t] || 0)),
      rem = process(t => counts[t] -= 1);
    if (init) {
      pulse.visit(pulse.SOURCE, add);
    } else {
      pulse.visit(pulse.ADD, add);
      pulse.visit(pulse.REM, rem);
    }
    return this._finish(pulse, as); // generate output tuples
  },
  _parameterCheck(_, pulse) {
    let init = false;
    if (_.modified('stopwords') || !this._stop) {
      this._stop = new RegExp('^' + (_.stopwords || '') + '$', 'i');
      init = true;
    }
    if (_.modified('pattern') || !this._match) {
      this._match = new RegExp(_.pattern || '[\\w\']+', 'g');
      init = true;
    }
    if (_.modified('field') || pulse.modified(_.field.fields)) {
      init = true;
    }
    if (init) this._counts = {};
    return init;
  },
  _finish(pulse, as) {
    const counts = this._counts,
      tuples = this._tuples || (this._tuples = {}),
      text = as[0],
      count = as[1],
      out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
    let w, t, c;
    for (w in counts) {
      t = tuples[w];
      c = counts[w] || 0;
      if (!t && c) {
        tuples[w] = t = standalone_ingest$1({});
        t[text] = w;
        t[count] = c;
        out.add.push(t);
      } else if (c === 0) {
        if (t) out.rem.push(t);
        counts[w] = null;
        tuples[w] = null;
      } else if (t[count] !== c) {
        t[count] = c;
        out.mod.push(t);
      }
    }
    return out.modifies(as);
  }
});

/**
 * Perform a cross-product of a tuple stream with itself.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object):boolean} [params.filter] - An optional filter
 *   function for selectively including tuples in the cross product.
 * @param {Array<string>} [params.as] - The names of the output fields.
 */
function standalone_Cross(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Cross.Definition = {
  'type': 'Cross',
  'metadata': {
    'generates': true
  },
  'params': [{
    'name': 'filter',
    'type': 'expr'
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': 2,
    'default': ['a', 'b']
  }]
};
standalone_inherits(standalone_Cross, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.NO_SOURCE),
      as = _.as || ['a', 'b'],
      a = as[0],
      b = as[1],
      reset = !this.value || pulse.changed(pulse.ADD_REM) || _.modified('as') || _.modified('filter');
    let data = this.value;
    if (reset) {
      if (data) out.rem = data;
      data = pulse.materialize(pulse.SOURCE).source;
      out.add = this.value = standalone_cross(data, a, b, _.filter || standalone_truthy);
    } else {
      out.mod = data;
    }
    out.source = this.value;
    return out.modifies(as);
  }
});
function standalone_cross(input, a, b, filter) {
  var data = [],
    t = {},
    n = input.length,
    i = 0,
    j,
    left;
  for (; i < n; ++i) {
    t[a] = left = input[i];
    for (j = 0; j < n; ++j) {
      t[b] = input[j];
      if (filter(t)) {
        data.push(standalone_ingest$1(t));
        t = {};
        t[a] = left;
      }
    }
  }
  return data;
}

const standalone_Distributions = {
  kde: standalone_kde,
  mixture: standalone_mixture,
  normal: standalone_gaussian,
  lognormal: standalone_lognormal,
  uniform: standalone_uniform
};
const standalone_DISTRIBUTIONS = 'distributions',
  standalone_FUNCTION = 'function',
  standalone_FIELD = 'field';

/**
 * Parse a parameter object for a probability distribution.
 * @param {object} def - The distribution parameter object.
 * @param {function():Array<object>} - A method for requesting
 *   source data. Used for distributions (such as KDE) that
 *   require sample data points. This method will only be
 *   invoked if the 'from' parameter for a target data source
 *   is not provided. Typically this method returns backing
 *   source data for a Pulse object.
 * @return {object} - The output distribution object.
 */
function standalone_vega_transforms_module_parse(def, data) {
  const func = def[standalone_FUNCTION];
  if (!standalone_vega_util_module_has(standalone_Distributions, func)) {
    standalone_vega_util_module_error('Unknown distribution function: ' + func);
  }
  const d = standalone_Distributions[func]();
  for (const name in def) {
    // if data field, extract values
    if (name === standalone_FIELD) {
      d.data((def.from || data()).map(def[name]));
    }

    // if distribution mixture, recurse to parse each definition
    else if (name === standalone_DISTRIBUTIONS) {
      d[name](def[name].map(_ => standalone_vega_transforms_module_parse(_, data)));
    }

    // otherwise, simply set the parameter
    else if (typeof d[name] === standalone_FUNCTION) {
      d[name](def[name]);
    }
  }
  return d;
}

/**
 * Grid sample points for a probability density. Given a distribution and
 * a sampling extent, will generate points suitable for plotting either
 * PDF (probability density function) or CDF (cumulative distribution
 * function) curves.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {object} params.distribution - The probability distribution. This
 *   is an object parameter dependent on the distribution type.
 * @param {string} [params.method='pdf'] - The distribution method to sample.
 *   One of 'pdf' or 'cdf'.
 * @param {Array<number>} [params.extent] - The [min, max] extent over which
 *   to sample the distribution. This argument is required in most cases, but
 *   can be omitted if the distribution (e.g., 'kde') supports a 'data' method
 *   that returns numerical sample points from which the extent can be deduced.
 * @param {number} [params.minsteps=25] - The minimum number of curve samples
 *   for plotting the density.
 * @param {number} [params.maxsteps=200] - The maximum number of curve samples
 *   for plotting the density.
 * @param {number} [params.steps] - The exact number of curve samples for
 *   plotting the density. If specified, overrides both minsteps and maxsteps
 *   to set an exact number of uniform samples. Useful in conjunction with
 *   a fixed extent to ensure consistent sample points for stacked densities.
 */
function standalone_Density(params) {
  standalone_Transform.call(this, null, params);
}
const standalone_distributions = [{
  'key': {
    'function': 'normal'
  },
  'params': [{
    'name': 'mean',
    'type': 'number',
    'default': 0
  }, {
    'name': 'stdev',
    'type': 'number',
    'default': 1
  }]
}, {
  'key': {
    'function': 'lognormal'
  },
  'params': [{
    'name': 'mean',
    'type': 'number',
    'default': 0
  }, {
    'name': 'stdev',
    'type': 'number',
    'default': 1
  }]
}, {
  'key': {
    'function': 'uniform'
  },
  'params': [{
    'name': 'min',
    'type': 'number',
    'default': 0
  }, {
    'name': 'max',
    'type': 'number',
    'default': 1
  }]
}, {
  'key': {
    'function': 'kde'
  },
  'params': [{
    'name': 'field',
    'type': 'field',
    'required': true
  }, {
    'name': 'from',
    'type': 'data'
  }, {
    'name': 'bandwidth',
    'type': 'number',
    'default': 0
  }]
}];
const standalone_vega_transforms_module_mixture = {
  'key': {
    'function': 'mixture'
  },
  'params': [{
    'name': 'distributions',
    'type': 'param',
    'array': true,
    'params': standalone_distributions
  }, {
    'name': 'weights',
    'type': 'number',
    'array': true
  }]
};
standalone_Density.Definition = {
  'type': 'Density',
  'metadata': {
    'generates': true
  },
  'params': [{
    'name': 'extent',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'steps',
    'type': 'number'
  }, {
    'name': 'minsteps',
    'type': 'number',
    'default': 25
  }, {
    'name': 'maxsteps',
    'type': 'number',
    'default': 200
  }, {
    'name': 'method',
    'type': 'string',
    'default': 'pdf',
    'values': ['pdf', 'cdf']
  }, {
    'name': 'distribution',
    'type': 'param',
    'params': standalone_distributions.concat(standalone_vega_transforms_module_mixture)
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'default': ['value', 'density']
  }]
};
standalone_inherits(standalone_Density, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
    if (!this.value || pulse.changed() || _.modified()) {
      const dist = standalone_vega_transforms_module_parse(_.distribution, standalone_source(pulse)),
        minsteps = _.steps || _.minsteps || 25,
        maxsteps = _.steps || _.maxsteps || 200;
      let method = _.method || 'pdf';
      if (method !== 'pdf' && method !== 'cdf') {
        standalone_vega_util_module_error('Invalid density method: ' + method);
      }
      if (!_.extent && !dist.data) {
        standalone_vega_util_module_error('Missing density extent parameter.');
      }
      method = dist[method];
      const as = _.as || ['value', 'density'],
        domain = _.extent || standalone_extent(dist.data()),
        values = standalone_sampleCurve(method, domain, minsteps, maxsteps).map(v => {
          const tuple = {};
          tuple[as[0]] = v[0];
          tuple[as[1]] = v[1];
          return standalone_ingest$1(tuple);
        });
      if (this.value) out.rem = this.value;
      this.value = out.add = out.source = values;
    }
    return out;
  }
});
function standalone_source(pulse) {
  return () => pulse.materialize(pulse.SOURCE).source;
}

// use either provided alias or accessor field name
function standalone_fieldNames(fields, as) {
  if (!fields) return null;
  return fields.map((f, i) => as[i] || standalone_accessorName(f));
}
function standalone_partition$1(data, groupby, field) {
  const groups = [],
    get = f => f(t);
  let map, i, n, t, k, g;

  // partition data points into groups
  if (groupby == null) {
    groups.push(data.map(field));
  } else {
    for (map = {}, i = 0, n = data.length; i < n; ++i) {
      t = data[i];
      k = groupby.map(get);
      g = map[k];
      if (!g) {
        map[k] = g = [];
        g.dims = k;
        groups.push(g);
      }
      g.push(field(t));
    }
  }
  return groups;
}

const standalone_Output = 'bin';

/**
 * Dot density binning for dot plot construction.
 * Based on Leland Wilkinson, Dot Plots, The American Statistician, 1999.
 * https://www.cs.uic.edu/~wilkinson/Publications/dotplots.pdf
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The value field to bin.
 * @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby.
 * @param {number} [params.step] - The step size (bin width) within which dots should be
 *   stacked. Defaults to 1/30 of the extent of the data *field*.
 * @param {boolean} [params.smooth=false] - A boolean flag indicating if dot density
 *   stacks should be smoothed to reduce variance.
 */
function standalone_DotBin(params) {
  standalone_Transform.call(this, null, params);
}
standalone_DotBin.Definition = {
  'type': 'DotBin',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'field',
    'type': 'field',
    'required': true
  }, {
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'step',
    'type': 'number'
  }, {
    'name': 'smooth',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'as',
    'type': 'string',
    'default': standalone_Output
  }]
};
const standalone_autostep = (data, field) => standalone_span(standalone_extent(data, field)) / 30;
standalone_inherits(standalone_DotBin, standalone_Transform, {
  transform(_, pulse) {
    if (this.value && !(_.modified() || pulse.changed())) {
      return pulse; // early exit
    }
    const source = pulse.materialize(pulse.SOURCE).source,
      groups = standalone_partition$1(pulse.source, _.groupby, standalone_vega_util_module_identity),
      smooth = _.smooth || false,
      field = _.field,
      step = _.step || standalone_autostep(source, field),
      sort = standalone_stableCompare((a, b) => field(a) - field(b)),
      as = _.as || standalone_Output,
      n = groups.length;

    // compute dotplot bins per group
    let min = Infinity,
      max = -Infinity,
      i = 0,
      j;
    for (; i < n; ++i) {
      const g = groups[i].sort(sort);
      j = -1;
      for (const v of standalone_dotbin(g, step, smooth, field)) {
        if (v < min) min = v;
        if (v > max) max = v;
        g[++j][as] = v;
      }
    }
    this.value = {
      start: min,
      stop: max,
      step: step
    };
    return pulse.reflow(true).modifies(as);
  }
});

/**
 * Wraps an expression function with access to external parameters.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function} params.expr - The expression function. The
 *  function should accept both a datum and a parameter object.
 *  This operator's value will be a new function that wraps the
 *  expression function with access to this operator's parameters.
 */
function standalone_Expression(params) {
  standalone_Operator.call(this, null, standalone_update$4, params);
  this.modified(true);
}
standalone_inherits(standalone_Expression, standalone_Operator);
function standalone_update$4(_) {
  const expr = _.expr;
  return this.value && !_.modified('expr') ? this.value : standalone_accessor(datum => expr(datum, _), standalone_accessorFields(expr), standalone_accessorName(expr));
}

/**
 * Computes extents (min/max) for a data field.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The field over which to compute extends.
 */
function standalone_Extent(params) {
  standalone_Transform.call(this, [undefined, undefined], params);
}
standalone_Extent.Definition = {
  'type': 'Extent',
  'metadata': {},
  'params': [{
    'name': 'field',
    'type': 'field',
    'required': true
  }]
};
standalone_inherits(standalone_Extent, standalone_Transform, {
  transform(_, pulse) {
    const extent = this.value,
      field = _.field,
      mod = pulse.changed() || pulse.modified(field.fields) || _.modified('field');
    let min = extent[0],
      max = extent[1];
    if (mod || min == null) {
      min = +Infinity;
      max = -Infinity;
    }
    pulse.visit(mod ? pulse.SOURCE : pulse.ADD, t => {
      const v = standalone_toNumber(field(t));
      if (v != null) {
        // NaNs will fail all comparisons!
        if (v < min) min = v;
        if (v > max) max = v;
      }
    });
    if (!Number.isFinite(min) || !Number.isFinite(max)) {
      let name = standalone_accessorName(field);
      if (name) name = ` for field "${name}"`;
      pulse.dataflow.warn(`Infinite extent${name}: [${min}, ${max}]`);
      min = max = undefined;
    }
    this.value = [min, max];
  }
});

/**
 * Provides a bridge between a parent transform and a target subflow that
 * consumes only a subset of the tuples that pass through the parent.
 * @constructor
 * @param {Pulse} pulse - A pulse to use as the value of this operator.
 * @param {Transform} parent - The parent transform (typically a Facet instance).
 */
function standalone_Subflow(pulse, parent) {
  standalone_Operator.call(this, pulse);
  this.parent = parent;
  this.count = 0;
}
standalone_inherits(standalone_Subflow, standalone_Operator, {
  /**
   * Routes pulses from this subflow to a target transform.
   * @param {Transform} target - A transform that receives the subflow of tuples.
   */
  connect(target) {
    this.detachSubflow = target.detachSubflow;
    this.targets().add(target);
    return target.source = this;
  },
  /**
   * Add an 'add' tuple to the subflow pulse.
   * @param {Tuple} t - The tuple being added.
   */
  add(t) {
    this.count += 1;
    this.value.add.push(t);
  },
  /**
   * Add a 'rem' tuple to the subflow pulse.
   * @param {Tuple} t - The tuple being removed.
   */
  rem(t) {
    this.count -= 1;
    this.value.rem.push(t);
  },
  /**
   * Add a 'mod' tuple to the subflow pulse.
   * @param {Tuple} t - The tuple being modified.
   */
  mod(t) {
    this.value.mod.push(t);
  },
  /**
   * Re-initialize this operator's pulse value.
   * @param {Pulse} pulse - The pulse to copy from.
   * @see Pulse.init
   */
  init(pulse) {
    this.value.init(pulse, pulse.NO_SOURCE);
  },
  /**
   * Evaluate this operator. This method overrides the
   * default behavior to simply return the contained pulse value.
   * @return {Pulse}
   */
  evaluate() {
    // assert: this.value.stamp === pulse.stamp
    return this.value;
  }
});

/**
 * Facets a dataflow into a set of subflows based on a key.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(Dataflow, string): Operator} params.subflow - A function
 *   that generates a subflow of operators and returns its root operator.
 * @param {function(object): *} params.key - The key field to facet by.
 */
function standalone_Facet(params) {
  standalone_Transform.call(this, {}, params);
  this._keys = standalone_fastmap(); // cache previously calculated key values

  // keep track of active subflows, use as targets array for listeners
  // this allows us to limit propagation to only updated subflows
  const a = this._targets = [];
  a.active = 0;
  a.forEach = f => {
    for (let i = 0, n = a.active; i < n; ++i) {
      f(a[i], i, a);
    }
  };
}
standalone_inherits(standalone_Facet, standalone_Transform, {
  activate(flow) {
    this._targets[this._targets.active++] = flow;
  },
  // parent argument provided by PreFacet subclass
  subflow(key, flow, pulse, parent) {
    const flows = this.value;
    let sf = standalone_vega_util_module_has(flows, key) && flows[key],
      df,
      p;
    if (!sf) {
      p = parent || (p = this._group[key]) && p.tuple;
      df = pulse.dataflow;
      sf = new standalone_Subflow(pulse.fork(pulse.NO_SOURCE), this);
      df.add(sf).connect(flow(df, key, p));
      flows[key] = sf;
      this.activate(sf);
    } else if (sf.value.stamp < pulse.stamp) {
      sf.init(pulse);
      this.activate(sf);
    }
    return sf;
  },
  clean() {
    const flows = this.value;
    let detached = 0;
    for (const key in flows) {
      if (flows[key].count === 0) {
        const detach = flows[key].detachSubflow;
        if (detach) detach();
        delete flows[key];
        ++detached;
      }
    }

    // remove inactive targets from the active targets array
    if (detached) {
      const active = this._targets.filter(sf => sf && sf.count > 0);
      this.initTargets(active);
    }
  },
  initTargets(act) {
    const a = this._targets,
      n = a.length,
      m = act ? act.length : 0;
    let i = 0;
    for (; i < m; ++i) {
      a[i] = act[i];
    }
    for (; i < n && a[i] != null; ++i) {
      a[i] = null; // ensure old flows can be garbage collected
    }
    a.active = m;
  },
  transform(_, pulse) {
    const df = pulse.dataflow,
      key = _.key,
      flow = _.subflow,
      cache = this._keys,
      rekey = _.modified('key'),
      subflow = key => this.subflow(key, flow, pulse);
    this._group = _.group || {};
    this.initTargets(); // reset list of active subflows

    pulse.visit(pulse.REM, t => {
      const id = standalone_tupleid(t),
        k = cache.get(id);
      if (k !== undefined) {
        cache.delete(id);
        subflow(k).rem(t);
      }
    });
    pulse.visit(pulse.ADD, t => {
      const k = key(t);
      cache.set(standalone_tupleid(t), k);
      subflow(k).add(t);
    });
    if (rekey || pulse.modified(key.fields)) {
      pulse.visit(pulse.MOD, t => {
        const id = standalone_tupleid(t),
          k0 = cache.get(id),
          k1 = key(t);
        if (k0 === k1) {
          subflow(k1).mod(t);
        } else {
          cache.set(id, k1);
          subflow(k0).rem(t);
          subflow(k1).add(t);
        }
      });
    } else if (pulse.changed(pulse.MOD)) {
      pulse.visit(pulse.MOD, t => {
        subflow(cache.get(standalone_tupleid(t))).mod(t);
      });
    }
    if (rekey) {
      pulse.visit(pulse.REFLOW, t => {
        const id = standalone_tupleid(t),
          k0 = cache.get(id),
          k1 = key(t);
        if (k0 !== k1) {
          cache.set(id, k1);
          subflow(k0).rem(t);
          subflow(k1).add(t);
        }
      });
    }
    if (pulse.clean()) {
      df.runAfter(() => {
        this.clean();
        cache.clean();
      });
    } else if (cache.empty > df.cleanThreshold) {
      df.runAfter(cache.clean);
    }
    return pulse;
  }
});

/**
 * Generates one or more field accessor functions.
 * If the 'name' parameter is an array, an array of field accessors
 * will be created and the 'as' parameter will be ignored.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {string} params.name - The field name(s) to access.
 * @param {string} params.as - The accessor function name.
 */
function standalone_Field(params) {
  standalone_Operator.call(this, null, standalone_update$3, params);
}
standalone_inherits(standalone_Field, standalone_Operator);
function standalone_update$3(_) {
  return this.value && !_.modified() ? this.value : standalone_vega_util_module_isArray(_.name) ? standalone_array(_.name).map(f => standalone_field(f)) : standalone_field(_.name, _.as);
}

/**
 * Filters data tuples according to a predicate function.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.expr - The predicate expression function
 *   that determines a tuple's filter status. Truthy values pass the filter.
 */
function standalone_Filter(params) {
  standalone_Transform.call(this, standalone_fastmap(), params);
}
standalone_Filter.Definition = {
  'type': 'Filter',
  'metadata': {
    'changes': true
  },
  'params': [{
    'name': 'expr',
    'type': 'expr',
    'required': true
  }]
};
standalone_inherits(standalone_Filter, standalone_Transform, {
  transform(_, pulse) {
    const df = pulse.dataflow,
      cache = this.value,
      // cache ids of filtered tuples
      output = pulse.fork(),
      add = output.add,
      rem = output.rem,
      mod = output.mod,
      test = _.expr;
    let isMod = true;
    pulse.visit(pulse.REM, t => {
      const id = standalone_tupleid(t);
      if (!cache.has(id)) rem.push(t);else cache.delete(id);
    });
    pulse.visit(pulse.ADD, t => {
      if (test(t, _)) add.push(t);else cache.set(standalone_tupleid(t), 1);
    });
    function revisit(t) {
      const id = standalone_tupleid(t),
        b = test(t, _),
        s = cache.get(id);
      if (b && s) {
        cache.delete(id);
        add.push(t);
      } else if (!b && !s) {
        cache.set(id, 1);
        rem.push(t);
      } else if (isMod && b && !s) {
        mod.push(t);
      }
    }
    pulse.visit(pulse.MOD, revisit);
    if (_.modified()) {
      isMod = false;
      pulse.visit(pulse.REFLOW, revisit);
    }
    if (cache.empty > df.cleanThreshold) df.runAfter(cache.clean);
    return output;
  }
});

/**
 * Flattens array-typed field values into new data objects.
 * If multiple fields are specified, they are treated as parallel arrays,
 * with output values included for each matching index (or null if missing).
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<function(object): *>} params.fields - An array of field
 *   accessors for the tuple fields that should be flattened.
 * @param {string} [params.index] - Optional output field name for index
 *   value. If unspecified, no index field is included in the output.
 * @param {Array<string>} [params.as] - Output field names for flattened
 *   array fields. Any unspecified fields will use the field name provided
 *   by the fields accessors.
 */
function standalone_Flatten(params) {
  standalone_Transform.call(this, [], params);
}
standalone_Flatten.Definition = {
  'type': 'Flatten',
  'metadata': {
    'generates': true
  },
  'params': [{
    'name': 'fields',
    'type': 'field',
    'array': true,
    'required': true
  }, {
    'name': 'index',
    'type': 'string'
  }, {
    'name': 'as',
    'type': 'string',
    'array': true
  }]
};
standalone_inherits(standalone_Flatten, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.NO_SOURCE),
      fields = _.fields,
      as = standalone_fieldNames(fields, _.as || []),
      index = _.index || null,
      m = as.length;

    // remove any previous results
    out.rem = this.value;

    // generate flattened tuples
    pulse.visit(pulse.SOURCE, t => {
      const arrays = fields.map(f => f(t)),
        maxlen = arrays.reduce((l, a) => Math.max(l, a.length), 0);
      let i = 0,
        j,
        d,
        v;
      for (; i < maxlen; ++i) {
        d = standalone_derive(t);
        for (j = 0; j < m; ++j) {
          d[as[j]] = (v = arrays[j][i]) == null ? null : v;
        }
        if (index) {
          d[index] = i;
        }
        out.add.push(d);
      }
    });
    this.value = out.source = out.add;
    if (index) out.modifies(index);
    return out.modifies(as);
  }
});

/**
 * Folds one more tuple fields into multiple tuples in which the field
 * name and values are available under new 'key' and 'value' fields.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.fields - An array of field accessors
 *   for the tuple fields that should be folded.
 * @param {Array<string>} [params.as] - Output field names for folded key
 *   and value fields, defaults to ['key', 'value'].
 */
function standalone_Fold(params) {
  standalone_Transform.call(this, [], params);
}
standalone_Fold.Definition = {
  'type': 'Fold',
  'metadata': {
    'generates': true
  },
  'params': [{
    'name': 'fields',
    'type': 'field',
    'array': true,
    'required': true
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': 2,
    'default': ['key', 'value']
  }]
};
standalone_inherits(standalone_Fold, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.NO_SOURCE),
      fields = _.fields,
      fnames = fields.map(standalone_accessorName),
      as = _.as || ['key', 'value'],
      k = as[0],
      v = as[1],
      n = fields.length;
    out.rem = this.value;
    pulse.visit(pulse.SOURCE, t => {
      for (let i = 0, d; i < n; ++i) {
        d = standalone_derive(t);
        d[k] = fnames[i];
        d[v] = fields[i](t);
        out.add.push(d);
      }
    });
    this.value = out.source = out.add;
    return out.modifies(as);
  }
});

/**
 * Invokes a function for each data tuple and saves the results as a new field.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.expr - The formula function to invoke for each tuple.
 * @param {string} params.as - The field name under which to save the result.
 * @param {boolean} [params.initonly=false] - If true, the formula is applied to
 *   added tuples only, and does not update in response to modifications.
 */
function standalone_Formula(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Formula.Definition = {
  'type': 'Formula',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'expr',
    'type': 'expr',
    'required': true
  }, {
    'name': 'as',
    'type': 'string',
    'required': true
  }, {
    'name': 'initonly',
    'type': 'boolean'
  }]
};
standalone_inherits(standalone_Formula, standalone_Transform, {
  transform(_, pulse) {
    const func = _.expr,
      as = _.as,
      mod = _.modified(),
      flag = _.initonly ? pulse.ADD : mod ? pulse.SOURCE : pulse.modified(func.fields) || pulse.modified(as) ? pulse.ADD_MOD : pulse.ADD;
    if (mod) {
      // parameters updated, need to reflow
      pulse = pulse.materialize().reflow(true);
    }
    if (!_.initonly) {
      pulse.modifies(as);
    }
    return pulse.visit(flag, t => t[as] = func(t, _));
  }
});

/**
 * Generates data tuples using a provided generator function.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(Parameters): object} params.generator - A tuple generator
 *   function. This function is given the operator parameters as input.
 *   Changes to any additional parameters will not trigger re-calculation
 *   of previously generated tuples. Only future tuples are affected.
 * @param {number} params.size - The number of tuples to produce.
 */
function standalone_Generate(params) {
  standalone_Transform.call(this, [], params);
}
standalone_inherits(standalone_Generate, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.ALL),
      gen = _.generator;
    let data = this.value,
      num = _.size - data.length,
      add,
      rem,
      t;
    if (num > 0) {
      // need more tuples, generate and add
      for (add = []; --num >= 0;) {
        add.push(t = standalone_ingest$1(gen(_)));
        data.push(t);
      }
      out.add = out.add.length ? out.materialize(out.ADD).add.concat(add) : add;
    } else {
      // need fewer tuples, remove
      rem = data.slice(0, -num);
      out.rem = out.rem.length ? out.materialize(out.REM).rem.concat(rem) : rem;
      data = data.slice(-num);
    }
    out.source = this.value = data;
    return out;
  }
});

const standalone_Methods = {
  value: 'value',
  median: standalone_median,
  mean: standalone_mean,
  min: standalone_min,
  max: standalone_max
};
const standalone_Empty = [];

/**
 * Impute missing values.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The value field to impute.
 * @param {Array<function(object): *>} [params.groupby] - An array of
 *   accessors to determine series within which to perform imputation.
 * @param {function(object): *} params.key - An accessor for a key value.
 *   Each key value should be unique within a group. New tuples will be
 *   imputed for any key values that are not found within a group.
 * @param {Array<*>} [params.keyvals] - Optional array of required key
 *   values. New tuples will be imputed for any key values that are not
 *   found within a group. In addition, these values will be automatically
 *   augmented with the key values observed in the input data.
 * @param {string} [method='value'] - The imputation method to use. One of
 *   'value', 'mean', 'median', 'max', 'min'.
 * @param {*} [value=0] - The constant value to use for imputation
 *   when using method 'value'.
 */
function standalone_Impute(params) {
  standalone_Transform.call(this, [], params);
}
standalone_Impute.Definition = {
  'type': 'Impute',
  'metadata': {
    'changes': true
  },
  'params': [{
    'name': 'field',
    'type': 'field',
    'required': true
  }, {
    'name': 'key',
    'type': 'field',
    'required': true
  }, {
    'name': 'keyvals',
    'array': true
  }, {
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'method',
    'type': 'enum',
    'default': 'value',
    'values': ['value', 'mean', 'median', 'max', 'min']
  }, {
    'name': 'value',
    'default': 0
  }]
};
function standalone_getValue(_) {
  var m = _.method || standalone_Methods.value,
    v;
  if (standalone_Methods[m] == null) {
    standalone_vega_util_module_error('Unrecognized imputation method: ' + m);
  } else if (m === standalone_Methods.value) {
    v = _.value !== undefined ? _.value : 0;
    return () => v;
  } else {
    return standalone_Methods[m];
  }
}
function standalone_getField(_) {
  const f = _.field;
  return t => t ? f(t) : NaN;
}
standalone_inherits(standalone_Impute, standalone_Transform, {
  transform(_, pulse) {
    var out = pulse.fork(pulse.ALL),
      impute = standalone_getValue(_),
      field = standalone_getField(_),
      fName = standalone_accessorName(_.field),
      kName = standalone_accessorName(_.key),
      gNames = (_.groupby || []).map(standalone_accessorName),
      groups = standalone_partition(pulse.source, _.groupby, _.key, _.keyvals),
      curr = [],
      prev = this.value,
      m = groups.domain.length,
      group,
      value,
      gVals,
      kVal,
      g,
      i,
      j,
      l,
      n,
      t;
    for (g = 0, l = groups.length; g < l; ++g) {
      group = groups[g];
      gVals = group.values;
      value = NaN;

      // add tuples for missing values
      for (j = 0; j < m; ++j) {
        if (group[j] != null) continue;
        kVal = groups.domain[j];
        t = {
          _impute: true
        };
        for (i = 0, n = gVals.length; i < n; ++i) t[gNames[i]] = gVals[i];
        t[kName] = kVal;
        t[fName] = Number.isNaN(value) ? value = impute(group, field) : value;
        curr.push(standalone_ingest$1(t));
      }
    }

    // update pulse with imputed tuples
    if (curr.length) out.add = out.materialize(out.ADD).add.concat(curr);
    if (prev.length) out.rem = out.materialize(out.REM).rem.concat(prev);
    this.value = curr;
    return out;
  }
});
function standalone_partition(data, groupby, key, keyvals) {
  var get = f => f(t),
    groups = [],
    domain = keyvals ? keyvals.slice() : [],
    kMap = {},
    gMap = {},
    gVals,
    gKey,
    group,
    i,
    j,
    k,
    n,
    t;
  domain.forEach((k, i) => kMap[k] = i + 1);
  for (i = 0, n = data.length; i < n; ++i) {
    t = data[i];
    k = key(t);
    j = kMap[k] || (kMap[k] = domain.push(k));
    gKey = (gVals = groupby ? groupby.map(get) : standalone_Empty) + '';
    if (!(group = gMap[gKey])) {
      group = gMap[gKey] = [];
      groups.push(group);
      group.values = gVals;
    }
    group[j - 1] = t;
  }
  groups.domain = domain;
  return groups;
}

/**
 * Extend input tuples with aggregate values.
 * Calcuates aggregate values and joins them with the input stream.
 * @constructor
 */
function standalone_JoinAggregate(params) {
  standalone_Aggregate.call(this, params);
}
standalone_JoinAggregate.Definition = {
  'type': 'JoinAggregate',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'fields',
    'type': 'field',
    'null': true,
    'array': true
  }, {
    'name': 'ops',
    'type': 'enum',
    'array': true,
    'values': standalone_ValidAggregateOps
  }, {
    'name': 'as',
    'type': 'string',
    'null': true,
    'array': true
  }, {
    'name': 'key',
    'type': 'field'
  }]
};
standalone_inherits(standalone_JoinAggregate, standalone_Aggregate, {
  transform(_, pulse) {
    const aggr = this,
      mod = _.modified();
    let cells;

    // process all input tuples to calculate aggregates
    if (aggr.value && (mod || pulse.modified(aggr._inputs, true))) {
      cells = aggr.value = mod ? aggr.init(_) : {};
      pulse.visit(pulse.SOURCE, t => aggr.add(t));
    } else {
      cells = aggr.value = aggr.value || this.init(_);
      pulse.visit(pulse.REM, t => aggr.rem(t));
      pulse.visit(pulse.ADD, t => aggr.add(t));
    }

    // update aggregation cells
    aggr.changes();

    // write aggregate values to input tuples
    pulse.visit(pulse.SOURCE, t => {
      standalone_extend(t, cells[aggr.cellkey(t)].tuple);
    });
    return pulse.reflow(mod).modifies(this._outputs);
  },
  changes() {
    const adds = this._adds,
      mods = this._mods;
    let i, n;
    for (i = 0, n = this._alen; i < n; ++i) {
      this.celltuple(adds[i]);
      adds[i] = null; // for garbage collection
    }
    for (i = 0, n = this._mlen; i < n; ++i) {
      this.celltuple(mods[i]);
      mods[i] = null; // for garbage collection
    }
    this._alen = this._mlen = 0; // reset list of active cells
  }
});

/**
 * Compute kernel density estimates (KDE) for one or more data groups.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<function(object): *>} [params.groupby] - An array of accessors
 *   to groupby.
 * @param {function(object): *} params.field - An accessor for the data field
 *   to estimate.
 * @param {number} [params.bandwidth=0] - The KDE kernel bandwidth.
 *   If zero or unspecified, the bandwidth is automatically determined.
 * @param {boolean} [params.counts=false] - A boolean flag indicating if the
 *   output values should be probability estimates (false, default) or
 *   smoothed counts (true).
 * @param {string} [params.cumulative=false] - A boolean flag indicating if a
 *   density (false) or cumulative distribution (true) should be generated.
 * @param {Array<number>} [params.extent] - The domain extent over which to
 *   plot the density. If unspecified, the [min, max] data extent is used.
 * @param {string} [params.resolve='independent'] - Indicates how parameters for
 *   multiple densities should be resolved. If "independent" (the default), each
 *   density may have its own domain extent and dynamic number of curve sample
 *   steps. If "shared", the KDE transform will ensure that all densities are
 *   defined over a shared domain and curve steps, enabling stacking.
 * @param {number} [params.minsteps=25] - The minimum number of curve samples
 *   for plotting the density.
 * @param {number} [params.maxsteps=200] - The maximum number of curve samples
 *   for plotting the density.
 * @param {number} [params.steps] - The exact number of curve samples for
 *   plotting the density. If specified, overrides both minsteps and maxsteps
 *   to set an exact number of uniform samples. Useful in conjunction with
 *   a fixed extent to ensure consistent sample points for stacked densities.
 */
function standalone_KDE(params) {
  standalone_Transform.call(this, null, params);
}
standalone_KDE.Definition = {
  'type': 'KDE',
  'metadata': {
    'generates': true
  },
  'params': [{
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'field',
    'type': 'field',
    'required': true
  }, {
    'name': 'cumulative',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'counts',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'bandwidth',
    'type': 'number',
    'default': 0
  }, {
    'name': 'extent',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'resolve',
    'type': 'enum',
    'values': ['shared', 'independent'],
    'default': 'independent'
  }, {
    'name': 'steps',
    'type': 'number'
  }, {
    'name': 'minsteps',
    'type': 'number',
    'default': 25
  }, {
    'name': 'maxsteps',
    'type': 'number',
    'default': 200
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'default': ['value', 'density']
  }]
};
standalone_inherits(standalone_KDE, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
    if (!this.value || pulse.changed() || _.modified()) {
      const source = pulse.materialize(pulse.SOURCE).source,
        groups = standalone_partition$1(source, _.groupby, _.field),
        names = (_.groupby || []).map(standalone_accessorName),
        bandwidth = _.bandwidth,
        method = _.cumulative ? 'cdf' : 'pdf',
        as = _.as || ['value', 'density'],
        values = [];
      let domain = _.extent,
        minsteps = _.steps || _.minsteps || 25,
        maxsteps = _.steps || _.maxsteps || 200;
      if (method !== 'pdf' && method !== 'cdf') {
        standalone_vega_util_module_error('Invalid density method: ' + method);
      }
      if (_.resolve === 'shared') {
        if (!domain) domain = standalone_extent(source, _.field);
        minsteps = maxsteps = _.steps || maxsteps;
      }
      groups.forEach(g => {
        const density = standalone_kde(g, bandwidth)[method],
          scale = _.counts ? g.length : 1,
          local = domain || standalone_extent(g);
        standalone_sampleCurve(density, local, minsteps, maxsteps).forEach(v => {
          const t = {};
          for (let i = 0; i < names.length; ++i) {
            t[names[i]] = g.dims[i];
          }
          t[as[0]] = v[0];
          t[as[1]] = v[1] * scale;
          values.push(standalone_ingest$1(t));
        });
      });
      if (this.value) out.rem = this.value;
      this.value = out.add = out.source = values;
    }
    return out;
  }
});

/**
 * Generates a key function.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<string>} params.fields - The field name(s) for the key function.
 * @param {boolean} params.flat - A boolean flag indicating if the field names
 *  should be treated as flat property names, side-stepping nested field
 *  lookups normally indicated by dot or bracket notation.
 */
function standalone_Key(params) {
  standalone_Operator.call(this, null, standalone_update$2, params);
}
standalone_inherits(standalone_Key, standalone_Operator);
function standalone_update$2(_) {
  return this.value && !_.modified() ? this.value : standalone_key(_.fields, _.flat);
}

/**
 * Load and parse data from an external source. Marshalls parameter
 * values and then invokes the Dataflow request method.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {string} params.url - The URL to load from.
 * @param {object} params.format - The data format options.
 */
function standalone_Load(params) {
  standalone_Transform.call(this, [], params);
  this._pending = null;
}
standalone_inherits(standalone_Load, standalone_Transform, {
  transform(_, pulse) {
    const df = pulse.dataflow;
    if (this._pending) {
      // update state and return pulse
      return standalone_vega_transforms_module_output(this, pulse, this._pending);
    }
    if (standalone_stop(_)) return pulse.StopPropagation;
    if (_.values) {
      // parse and ingest values, return output pulse
      return standalone_vega_transforms_module_output(this, pulse, df.parse(_.values, _.format));
    } else if (_.async) {
      // return promise for non-blocking async loading
      const p = df.request(_.url, _.format).then(res => {
        this._pending = standalone_array(res.data);
        return df => df.touch(this);
      });
      return {
        async: p
      };
    } else {
      // return promise for synchronous loading
      return df.request(_.url, _.format).then(res => standalone_vega_transforms_module_output(this, pulse, standalone_array(res.data)));
    }
  }
});
function standalone_stop(_) {
  return _.modified('async') && !(_.modified('values') || _.modified('url') || _.modified('format'));
}
function standalone_vega_transforms_module_output(op, pulse, data) {
  data.forEach(standalone_ingest$1);
  const out = pulse.fork(pulse.NO_FIELDS & pulse.NO_SOURCE);
  out.rem = op.value;
  op.value = out.source = out.add = data;
  op._pending = null;
  if (out.rem.length) out.clean(true);
  return out;
}

/**
 * Extend tuples by joining them with values from a lookup table.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Map} params.index - The lookup table map.
 * @param {Array<function(object): *} params.fields - The fields to lookup.
 * @param {Array<string>} params.as - Output field names for each lookup value.
 * @param {*} [params.default] - A default value to use if lookup fails.
 */
function standalone_Lookup(params) {
  standalone_Transform.call(this, {}, params);
}
standalone_Lookup.Definition = {
  'type': 'Lookup',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'index',
    'type': 'index',
    'params': [{
      'name': 'from',
      'type': 'data',
      'required': true
    }, {
      'name': 'key',
      'type': 'field',
      'required': true
    }]
  }, {
    'name': 'values',
    'type': 'field',
    'array': true
  }, {
    'name': 'fields',
    'type': 'field',
    'array': true,
    'required': true
  }, {
    'name': 'as',
    'type': 'string',
    'array': true
  }, {
    'name': 'default',
    'default': null
  }]
};
standalone_inherits(standalone_Lookup, standalone_Transform, {
  transform(_, pulse) {
    const keys = _.fields,
      index = _.index,
      values = _.values,
      defaultValue = _.default == null ? null : _.default,
      reset = _.modified(),
      n = keys.length;
    let flag = reset ? pulse.SOURCE : pulse.ADD,
      out = pulse,
      as = _.as,
      set,
      m,
      mods;
    if (values) {
      m = values.length;
      if (n > 1 && !as) {
        standalone_vega_util_module_error('Multi-field lookup requires explicit "as" parameter.');
      }
      if (as && as.length !== n * m) {
        standalone_vega_util_module_error('The "as" parameter has too few output field names.');
      }
      as = as || values.map(standalone_accessorName);
      set = function (t) {
        for (var i = 0, k = 0, j, v; i < n; ++i) {
          v = index.get(keys[i](t));
          if (v == null) for (j = 0; j < m; ++j, ++k) t[as[k]] = defaultValue;else for (j = 0; j < m; ++j, ++k) t[as[k]] = values[j](v);
        }
      };
    } else {
      if (!as) {
        standalone_vega_util_module_error('Missing output field names.');
      }
      set = function (t) {
        for (var i = 0, v; i < n; ++i) {
          v = index.get(keys[i](t));
          t[as[i]] = v == null ? defaultValue : v;
        }
      };
    }
    if (reset) {
      out = pulse.reflow(true);
    } else {
      mods = keys.some(k => pulse.modified(k.fields));
      flag |= mods ? pulse.MOD : 0;
    }
    pulse.visit(flag, set);
    return out.modifies(as);
  }
});

/**
 * Computes global min/max extents over a collection of extents.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<Array<number>>} params.extents - The input extents.
 */
function standalone_MultiExtent(params) {
  standalone_Operator.call(this, null, standalone_update$1, params);
}
standalone_inherits(standalone_MultiExtent, standalone_Operator);
function standalone_update$1(_) {
  if (this.value && !_.modified()) {
    return this.value;
  }
  const ext = _.extents,
    n = ext.length;
  let min = +Infinity,
    max = -Infinity,
    i,
    e;
  for (i = 0; i < n; ++i) {
    e = ext[i];
    if (e[0] < min) min = e[0];
    if (e[1] > max) max = e[1];
  }
  return [min, max];
}

/**
 * Merge a collection of value arrays.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<Array<*>>} params.values - The input value arrrays.
 */
function standalone_MultiValues(params) {
  standalone_Operator.call(this, null, standalone_vega_transforms_module_update, params);
}
standalone_inherits(standalone_MultiValues, standalone_Operator);
function standalone_vega_transforms_module_update(_) {
  return this.value && !_.modified() ? this.value : _.values.reduce((data, _) => data.concat(_), []);
}

/**
 * Operator whose value is simply its parameter hash. This operator is
 * useful for enabling reactive updates to values of nested objects.
 * @constructor
 * @param {object} params - The parameters for this operator.
 */
function standalone_Params(params) {
  standalone_Transform.call(this, null, params);
}
standalone_inherits(standalone_Params, standalone_Transform, {
  transform(_, pulse) {
    this.modified(_.modified());
    this.value = _;
    return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS); // do not pass tuples
  }
});

/**
 * Aggregate and pivot selected field values to become new fields.
 * This operator is useful to construction cross-tabulations.
 * @constructor
 * @param {Array<function(object): *>} [params.groupby] - An array of accessors
 *  to groupby. These fields act just like groupby fields of an Aggregate transform.
 * @param {function(object): *} params.field - The field to pivot on. The unique
 *  values of this field become new field names in the output stream.
 * @param {function(object): *} params.value - The field to populate pivoted fields.
 *  The aggregate values of this field become the values of the new pivoted fields.
 * @param {string} [params.op] - The aggregation operation for the value field,
 *  applied per cell in the output stream. The default is "sum".
 * @param {number} [params.limit] - An optional parameter indicating the maximum
 *  number of pivoted fields to generate. The pivoted field names are sorted in
 *  ascending order prior to enforcing the limit.
 */
function standalone_Pivot(params) {
  standalone_Aggregate.call(this, params);
}
standalone_Pivot.Definition = {
  'type': 'Pivot',
  'metadata': {
    'generates': true,
    'changes': true
  },
  'params': [{
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'field',
    'type': 'field',
    'required': true
  }, {
    'name': 'value',
    'type': 'field',
    'required': true
  }, {
    'name': 'op',
    'type': 'enum',
    'values': standalone_ValidAggregateOps,
    'default': 'sum'
  }, {
    'name': 'limit',
    'type': 'number',
    'default': 0
  }, {
    'name': 'key',
    'type': 'field'
  }]
};
standalone_inherits(standalone_Pivot, standalone_Aggregate, {
  _transform: standalone_Aggregate.prototype.transform,
  transform(_, pulse) {
    return this._transform(standalone_aggregateParams(_, pulse), pulse);
  }
});

// Shoehorn a pivot transform into an aggregate transform!
// First collect all unique pivot field values.
// Then generate aggregate fields for each output pivot field.
function standalone_aggregateParams(_, pulse) {
  const key = _.field,
    value = _.value,
    op = (_.op === 'count' ? '__count__' : _.op) || 'sum',
    fields = standalone_accessorFields(key).concat(standalone_accessorFields(value)),
    keys = standalone_pivotKeys(key, _.limit || 0, pulse);

  // if data stream content changes, pivot fields may change
  // flag parameter modification to ensure re-initialization
  if (pulse.changed()) _.set('__pivot__', null, null, true);
  return {
    key: _.key,
    groupby: _.groupby,
    ops: keys.map(() => op),
    fields: keys.map(k => standalone_get(k, key, value, fields)),
    as: keys.map(k => k + ''),
    modified: _.modified.bind(_)
  };
}

// Generate aggregate field accessor.
// Output NaN for non-existent values; aggregator will ignore!
function standalone_get(k, key, value, fields) {
  return standalone_accessor(d => key(d) === k ? value(d) : NaN, fields, k + '');
}

// Collect (and optionally limit) all unique pivot values.
function standalone_pivotKeys(key, limit, pulse) {
  const map = {},
    list = [];
  pulse.visit(pulse.SOURCE, t => {
    const k = key(t);
    if (!map[k]) {
      map[k] = 1;
      list.push(k);
    }
  });
  list.sort(standalone_ascending);
  return limit ? list.slice(0, limit) : list;
}

/**
 * Partitions pre-faceted data into tuple subflows.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(Dataflow, string): Operator} params.subflow - A function
 *   that generates a subflow of operators and returns its root operator.
 * @param {function(object): Array<object>} params.field - The field
 *   accessor for an array of subflow tuple objects.
 */
function standalone_PreFacet(params) {
  standalone_Facet.call(this, params);
}
standalone_inherits(standalone_PreFacet, standalone_Facet, {
  transform(_, pulse) {
    const flow = _.subflow,
      field = _.field,
      subflow = t => this.subflow(standalone_tupleid(t), flow, pulse, t);
    if (_.modified('field') || field && pulse.modified(standalone_accessorFields(field))) {
      standalone_vega_util_module_error('PreFacet does not support field modification.');
    }
    this.initTargets(); // reset list of active subflows

    if (field) {
      pulse.visit(pulse.MOD, t => {
        const sf = subflow(t);
        field(t).forEach(_ => sf.mod(_));
      });
      pulse.visit(pulse.ADD, t => {
        const sf = subflow(t);
        field(t).forEach(_ => sf.add(standalone_ingest$1(_)));
      });
      pulse.visit(pulse.REM, t => {
        const sf = subflow(t);
        field(t).forEach(_ => sf.rem(_));
      });
    } else {
      pulse.visit(pulse.MOD, t => subflow(t).mod(t));
      pulse.visit(pulse.ADD, t => subflow(t).add(t));
      pulse.visit(pulse.REM, t => subflow(t).rem(t));
    }
    if (pulse.clean()) {
      pulse.runAfter(() => this.clean());
    }
    return pulse;
  }
});

/**
 * Performs a relational projection, copying selected fields from source
 * tuples to a new set of derived tuples.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<function(object): *} params.fields - The fields to project,
 *   as an array of field accessors. If unspecified, all fields will be
 *   copied with names unchanged.
 * @param {Array<string>} [params.as] - Output field names for each projected
 *   field. Any unspecified fields will use the field name provided by
 *   the field accessor.
 */
function standalone_Project(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Project.Definition = {
  'type': 'Project',
  'metadata': {
    'generates': true,
    'changes': true
  },
  'params': [{
    'name': 'fields',
    'type': 'field',
    'array': true
  }, {
    'name': 'as',
    'type': 'string',
    'null': true,
    'array': true
  }]
};
standalone_inherits(standalone_Project, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.NO_SOURCE),
      fields = _.fields,
      as = standalone_fieldNames(_.fields, _.as || []),
      derive = fields ? (s, t) => standalone_project(s, t, fields, as) : standalone_rederive;
    let lut;
    if (this.value) {
      lut = this.value;
    } else {
      pulse = pulse.addAll();
      lut = this.value = {};
    }
    pulse.visit(pulse.REM, t => {
      const id = standalone_tupleid(t);
      out.rem.push(lut[id]);
      lut[id] = null;
    });
    pulse.visit(pulse.ADD, t => {
      const dt = derive(t, standalone_ingest$1({}));
      lut[standalone_tupleid(t)] = dt;
      out.add.push(dt);
    });
    pulse.visit(pulse.MOD, t => {
      out.mod.push(derive(t, lut[standalone_tupleid(t)]));
    });
    return out;
  }
});
function standalone_project(s, t, fields, as) {
  for (let i = 0, n = fields.length; i < n; ++i) {
    t[as[i]] = fields[i](s);
  }
  return t;
}

/**
 * Proxy the value of another operator as a pure signal value.
 * Ensures no tuples are propagated.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {*} params.value - The value to proxy, becomes the value of this operator.
 */
function standalone_vega_transforms_module_Proxy(params) {
  standalone_Transform.call(this, null, params);
}
standalone_inherits(standalone_vega_transforms_module_Proxy, standalone_Transform, {
  transform(_, pulse) {
    this.value = _.value;
    return _.modified('value') ? pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS) : pulse.StopPropagation;
  }
});

/**
 * Generates sample quantile values from an input data stream.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - An accessor for the data field
 *   over which to calculate quantile values.
 * @param {Array<function(object): *>} [params.groupby] - An array of accessors
 *   to groupby.
 * @param {Array<number>} [params.probs] - An array of probabilities in
 *   the range (0, 1) for which to compute quantile values. If not specified,
 *   the *step* parameter will be used.
 * @param {Array<number>} [params.step=0.01] - A probability step size for
 *   sampling quantile values. All values from one-half the step size up to
 *   1 (exclusive) will be sampled. This parameter is only used if the
 *   *quantiles* parameter is not provided.
 */
function standalone_Quantile(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Quantile.Definition = {
  'type': 'Quantile',
  'metadata': {
    'generates': true,
    'changes': true
  },
  'params': [{
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'field',
    'type': 'field',
    'required': true
  }, {
    'name': 'probs',
    'type': 'number',
    'array': true
  }, {
    'name': 'step',
    'type': 'number',
    'default': 0.01
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'default': ['prob', 'value']
  }]
};
const standalone_EPSILON = 1e-14;
standalone_inherits(standalone_Quantile, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
      as = _.as || ['prob', 'value'];
    if (this.value && !_.modified() && !pulse.changed()) {
      out.source = this.value;
      return out;
    }
    const source = pulse.materialize(pulse.SOURCE).source,
      groups = standalone_partition$1(source, _.groupby, _.field),
      names = (_.groupby || []).map(standalone_accessorName),
      values = [],
      step = _.step || 0.01,
      p = _.probs || standalone_range(step / 2, 1 - standalone_EPSILON, step),
      n = p.length;
    groups.forEach(g => {
      const q = standalone_quantiles(g, p);
      for (let i = 0; i < n; ++i) {
        const t = {};
        for (let i = 0; i < names.length; ++i) {
          t[names[i]] = g.dims[i];
        }
        t[as[0]] = p[i];
        t[as[1]] = q[i];
        values.push(standalone_ingest$1(t));
      }
    });
    if (this.value) out.rem = this.value;
    this.value = out.add = out.source = values;
    return out;
  }
});

/**
 * Relays a data stream between data processing pipelines.
 * If the derive parameter is set, this transform will create derived
 * copies of observed tuples. This provides derived data streams in which
 * modifications to the tuples do not pollute an upstream data source.
 * @param {object} params - The parameters for this operator.
 * @param {number} [params.derive=false] - Boolean flag indicating if
 *   the transform should make derived copies of incoming tuples.
 * @constructor
 */
function standalone_Relay(params) {
  standalone_Transform.call(this, null, params);
}
standalone_inherits(standalone_Relay, standalone_Transform, {
  transform(_, pulse) {
    let out, lut;
    if (this.value) {
      lut = this.value;
    } else {
      out = pulse = pulse.addAll();
      lut = this.value = {};
    }
    if (_.derive) {
      out = pulse.fork(pulse.NO_SOURCE);
      pulse.visit(pulse.REM, t => {
        const id = standalone_tupleid(t);
        out.rem.push(lut[id]);
        lut[id] = null;
      });
      pulse.visit(pulse.ADD, t => {
        const dt = standalone_derive(t);
        lut[standalone_tupleid(t)] = dt;
        out.add.push(dt);
      });
      pulse.visit(pulse.MOD, t => {
        const dt = lut[standalone_tupleid(t)];
        for (const k in t) {
          dt[k] = t[k];
          // down stream writes may overwrite re-derived tuples
          // conservatively mark all source fields as modified
          out.modifies(k);
        }
        out.mod.push(dt);
      });
    }
    return out;
  }
});

/**
 * Samples tuples passing through this operator.
 * Uses reservoir sampling to maintain a representative sample.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {number} [params.size=1000] - The maximum number of samples.
 */
function standalone_Sample(params) {
  standalone_Transform.call(this, [], params);
  this.count = 0;
}
standalone_Sample.Definition = {
  'type': 'Sample',
  'metadata': {},
  'params': [{
    'name': 'size',
    'type': 'number',
    'default': 1000
  }]
};
standalone_inherits(standalone_Sample, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.NO_SOURCE),
      mod = _.modified('size'),
      num = _.size,
      map = this.value.reduce((m, t) => (m[standalone_tupleid(t)] = 1, m), {});
    let res = this.value,
      cnt = this.count,
      cap = 0;

    // sample reservoir update function
    function update(t) {
      let p, idx;
      if (res.length < num) {
        res.push(t);
      } else {
        idx = ~~((cnt + 1) * standalone_random());
        if (idx < res.length && idx >= cap) {
          p = res[idx];
          if (map[standalone_tupleid(p)]) out.rem.push(p); // eviction
          res[idx] = t;
        }
      }
      ++cnt;
    }
    if (pulse.rem.length) {
      // find all tuples that should be removed, add to output
      pulse.visit(pulse.REM, t => {
        const id = standalone_tupleid(t);
        if (map[id]) {
          map[id] = -1;
          out.rem.push(t);
        }
        --cnt;
      });

      // filter removed tuples out of the sample reservoir
      res = res.filter(t => map[standalone_tupleid(t)] !== -1);
    }
    if ((pulse.rem.length || mod) && res.length < num && pulse.source) {
      // replenish sample if backing data source is available
      cap = cnt = res.length;
      pulse.visit(pulse.SOURCE, t => {
        // update, but skip previously sampled tuples
        if (!map[standalone_tupleid(t)]) update(t);
      });
      cap = -1;
    }
    if (mod && res.length > num) {
      const n = res.length - num;
      for (let i = 0; i < n; ++i) {
        map[standalone_tupleid(res[i])] = -1;
        out.rem.push(res[i]);
      }
      res = res.slice(n);
    }
    if (pulse.mod.length) {
      // propagate modified tuples in the sample reservoir
      pulse.visit(pulse.MOD, t => {
        if (map[standalone_tupleid(t)]) out.mod.push(t);
      });
    }
    if (pulse.add.length) {
      // update sample reservoir
      pulse.visit(pulse.ADD, update);
    }
    if (pulse.add.length || cap < 0) {
      // output newly added tuples
      out.add = res.filter(t => !map[standalone_tupleid(t)]);
    }
    this.count = cnt;
    this.value = out.source = res;
    return out;
  }
});

/**
 * Generates data tuples for a specified sequence range of numbers.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {number} params.start - The first number in the sequence.
 * @param {number} params.stop - The last number (exclusive) in the sequence.
 * @param {number} [params.step=1] - The step size between numbers in the sequence.
 */
function standalone_Sequence(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Sequence.Definition = {
  'type': 'Sequence',
  'metadata': {
    'generates': true,
    'changes': true
  },
  'params': [{
    'name': 'start',
    'type': 'number',
    'required': true
  }, {
    'name': 'stop',
    'type': 'number',
    'required': true
  }, {
    'name': 'step',
    'type': 'number',
    'default': 1
  }, {
    'name': 'as',
    'type': 'string',
    'default': 'data'
  }]
};
standalone_inherits(standalone_Sequence, standalone_Transform, {
  transform(_, pulse) {
    if (this.value && !_.modified()) return;
    const out = pulse.materialize().fork(pulse.MOD),
      as = _.as || 'data';
    out.rem = this.value ? pulse.rem.concat(this.value) : pulse.rem;
    this.value = standalone_range(_.start, _.stop, _.step || 1).map(v => {
      const t = {};
      t[as] = v;
      return standalone_ingest$1(t);
    });
    out.add = pulse.add.concat(this.value);
    return out;
  }
});

/**
 * Propagates a new pulse without any tuples so long as the input
 * pulse contains some added, removed or modified tuples.
 * @param {object} params - The parameters for this operator.
 * @constructor
 */
function standalone_Sieve(params) {
  standalone_Transform.call(this, null, params);
  this.modified(true); // always treat as modified
}
standalone_inherits(standalone_Sieve, standalone_Transform, {
  transform(_, pulse) {
    this.value = pulse.source;
    return pulse.changed() ? pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS) : pulse.StopPropagation;
  }
});

/**
 * Discretize dates to specific time units.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The data field containing date/time values.
 */
function standalone_TimeUnit(params) {
  standalone_Transform.call(this, null, params);
}
const standalone_OUTPUT = ['unit0', 'unit1'];
standalone_TimeUnit.Definition = {
  'type': 'TimeUnit',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'field',
    'type': 'field',
    'required': true
  }, {
    'name': 'interval',
    'type': 'boolean',
    'default': true
  }, {
    'name': 'units',
    'type': 'enum',
    'values': standalone_TIME_UNITS,
    'array': true
  }, {
    'name': 'step',
    'type': 'number',
    'default': 1
  }, {
    'name': 'maxbins',
    'type': 'number',
    'default': 40
  }, {
    'name': 'extent',
    'type': 'date',
    'array': true
  }, {
    'name': 'timezone',
    'type': 'enum',
    'default': 'local',
    'values': ['local', 'utc']
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': 2,
    'default': standalone_OUTPUT
  }]
};
standalone_inherits(standalone_TimeUnit, standalone_Transform, {
  transform(_, pulse) {
    const field = _.field,
      band = _.interval !== false,
      utc = _.timezone === 'utc',
      floor = this._floor(_, pulse),
      offset = (utc ? standalone_utcInterval : standalone_vega_time_module_timeInterval)(floor.unit).offset,
      as = _.as || standalone_OUTPUT,
      u0 = as[0],
      u1 = as[1],
      step = floor.step;
    let min = floor.start || Infinity,
      max = floor.stop || -Infinity,
      flag = pulse.ADD;
    if (_.modified() || pulse.changed(pulse.REM) || pulse.modified(standalone_accessorFields(field))) {
      pulse = pulse.reflow(true);
      flag = pulse.SOURCE;
      min = Infinity;
      max = -Infinity;
    }
    pulse.visit(flag, t => {
      const v = field(t);
      let a, b;
      if (v == null) {
        t[u0] = null;
        if (band) t[u1] = null;
      } else {
        t[u0] = a = b = floor(v);
        if (band) t[u1] = b = offset(a, step);
        if (a < min) min = a;
        if (b > max) max = b;
      }
    });
    floor.start = min;
    floor.stop = max;
    return pulse.modifies(band ? as : u0);
  },
  _floor(_, pulse) {
    const utc = _.timezone === 'utc';

    // get parameters
    const {
      units,
      step
    } = _.units ? {
      units: _.units,
      step: _.step || 1
    } : standalone_bin({
      extent: _.extent || standalone_extent(pulse.materialize(pulse.SOURCE).source, _.field),
      maxbins: _.maxbins
    });

    // check / standardize time units
    const tunits = standalone_timeUnits(units),
      prev = this.value || {},
      floor = (utc ? standalone_utcFloor : standalone_timeFloor)(tunits, step);
    floor.unit = standalone_peek(tunits);
    floor.units = tunits;
    floor.step = step;
    floor.start = prev.start;
    floor.stop = prev.stop;
    return this.value = floor;
  }
});

/**
 * An index that maps from unique, string-coerced, field values to tuples.
 * Assumes that the field serves as a unique key with no duplicate values.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The field accessor to index.
 */
function standalone_TupleIndex(params) {
  standalone_Transform.call(this, standalone_fastmap(), params);
}
standalone_inherits(standalone_TupleIndex, standalone_Transform, {
  transform(_, pulse) {
    const df = pulse.dataflow,
      field = _.field,
      index = this.value,
      set = t => index.set(field(t), t);
    let mod = true;
    if (_.modified('field') || pulse.modified(field.fields)) {
      index.clear();
      pulse.visit(pulse.SOURCE, set);
    } else if (pulse.changed()) {
      pulse.visit(pulse.REM, t => index.delete(field(t)));
      pulse.visit(pulse.ADD, set);
    } else {
      mod = false;
    }
    this.modified(mod);
    if (index.empty > df.cleanThreshold) df.runAfter(index.clean);
    return pulse.fork();
  }
});

/**
 * Extracts an array of values. Assumes the source data has already been
 * reduced as needed (e.g., by an upstream Aggregate transform).
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The domain field to extract.
 * @param {function(*,*): number} [params.sort] - An optional
 *   comparator function for sorting the values. The comparator will be
 *   applied to backing tuples prior to value extraction.
 */
function standalone_Values(params) {
  standalone_Transform.call(this, null, params);
}
standalone_inherits(standalone_Values, standalone_Transform, {
  transform(_, pulse) {
    const run = !this.value || _.modified('field') || _.modified('sort') || pulse.changed() || _.sort && pulse.modified(_.sort.fields);
    if (run) {
      this.value = (_.sort ? pulse.source.slice().sort(standalone_stableCompare(_.sort)) : pulse.source).map(_.field);
    }
  }
});

function standalone_WindowOp(op, field, param, as) {
  const fn = standalone_WindowOps[op](field, param);
  return {
    init: fn.init || standalone_zero,
    update: function (w, t) {
      t[as] = fn.next(w);
    }
  };
}
const standalone_WindowOps = {
  row_number: function () {
    return {
      next: w => w.index + 1
    };
  },
  rank: function () {
    let rank;
    return {
      init: () => rank = 1,
      next: w => {
        const i = w.index,
          data = w.data;
        return i && w.compare(data[i - 1], data[i]) ? rank = i + 1 : rank;
      }
    };
  },
  dense_rank: function () {
    let drank;
    return {
      init: () => drank = 1,
      next: w => {
        const i = w.index,
          d = w.data;
        return i && w.compare(d[i - 1], d[i]) ? ++drank : drank;
      }
    };
  },
  percent_rank: function () {
    const rank = standalone_WindowOps.rank(),
      next = rank.next;
    return {
      init: rank.init,
      next: w => (next(w) - 1) / (w.data.length - 1)
    };
  },
  cume_dist: function () {
    let cume;
    return {
      init: () => cume = 0,
      next: w => {
        const d = w.data,
          c = w.compare;
        let i = w.index;
        if (cume < i) {
          while (i + 1 < d.length && !c(d[i], d[i + 1])) ++i;
          cume = i;
        }
        return (1 + cume) / d.length;
      }
    };
  },
  ntile: function (field, num) {
    num = +num;
    if (!(num > 0)) standalone_vega_util_module_error('ntile num must be greater than zero.');
    const cume = standalone_WindowOps.cume_dist(),
      next = cume.next;
    return {
      init: cume.init,
      next: w => Math.ceil(num * next(w))
    };
  },
  lag: function (field, offset) {
    offset = +offset || 1;
    return {
      next: w => {
        const i = w.index - offset;
        return i >= 0 ? field(w.data[i]) : null;
      }
    };
  },
  lead: function (field, offset) {
    offset = +offset || 1;
    return {
      next: w => {
        const i = w.index + offset,
          d = w.data;
        return i < d.length ? field(d[i]) : null;
      }
    };
  },
  first_value: function (field) {
    return {
      next: w => field(w.data[w.i0])
    };
  },
  last_value: function (field) {
    return {
      next: w => field(w.data[w.i1 - 1])
    };
  },
  nth_value: function (field, nth) {
    nth = +nth;
    if (!(nth > 0)) standalone_vega_util_module_error('nth_value nth must be greater than zero.');
    return {
      next: w => {
        const i = w.i0 + (nth - 1);
        return i < w.i1 ? field(w.data[i]) : null;
      }
    };
  },
  prev_value: function (field) {
    let prev;
    return {
      init: () => prev = null,
      next: w => {
        const v = field(w.data[w.index]);
        return v != null ? prev = v : prev;
      }
    };
  },
  next_value: function (field) {
    let v, i;
    return {
      init: () => (v = null, i = -1),
      next: w => {
        const d = w.data;
        return w.index <= i ? v : (i = standalone_find(field, d, w.index)) < 0 ? (i = d.length, v = null) : v = field(d[i]);
      }
    };
  }
};
function standalone_find(field, data, index) {
  for (let n = data.length; index < n; ++index) {
    const v = field(data[index]);
    if (v != null) return index;
  }
  return -1;
}
const standalone_ValidWindowOps = Object.keys(standalone_WindowOps);

function standalone_WindowState(_) {
  const ops = standalone_array(_.ops),
    fields = standalone_array(_.fields),
    params = standalone_array(_.params),
    aggregate_params = standalone_array(_.aggregate_params),
    as = standalone_array(_.as),
    outputs = this.outputs = [],
    windows = this.windows = [],
    inputs = {},
    map = {},
    counts = [],
    measures = [];
  let countOnly = true;
  function visitInputs(f) {
    standalone_array(standalone_accessorFields(f)).forEach(_ => inputs[_] = 1);
  }
  visitInputs(_.sort);
  ops.forEach((op, i) => {
    const field = fields[i],
      param = params[i],
      aggregate_param = aggregate_params[i] || null,
      mname = standalone_accessorName(field),
      name = standalone_measureName(op, mname, as[i]);
    visitInputs(field);
    outputs.push(name);

    // Window operation
    if (standalone_vega_util_module_has(standalone_WindowOps, op)) {
      windows.push(standalone_WindowOp(op, field, param, name));
    }

    // Aggregate operation
    else {
      if (field == null && op !== 'count') {
        standalone_vega_util_module_error('Null aggregate field specified.');
      }
      if (op === 'count') {
        counts.push(name);
        return;
      }
      countOnly = false;
      let m = map[mname];
      if (!m) {
        m = map[mname] = [];
        m.field = field;
        measures.push(m);
      }
      m.push(standalone_createMeasure(op, aggregate_param, name));
    }
  });
  if (counts.length || measures.length) {
    this.cell = standalone_cell(measures, counts, countOnly);
  }
  this.inputs = Object.keys(inputs);
}
const standalone_vega_transforms_module_prototype = standalone_WindowState.prototype;
standalone_vega_transforms_module_prototype.init = function () {
  this.windows.forEach(_ => _.init());
  if (this.cell) this.cell.init();
};
standalone_vega_transforms_module_prototype.update = function (w, t) {
  const cell = this.cell,
    wind = this.windows,
    data = w.data,
    m = wind && wind.length;
  let j;
  if (cell) {
    for (j = w.p0; j < w.i0; ++j) cell.rem(data[j]);
    for (j = w.p1; j < w.i1; ++j) cell.add(data[j]);
    cell.set(t);
  }
  for (j = 0; j < m; ++j) wind[j].update(w, t);
};
function standalone_cell(measures, counts, countOnly) {
  measures = measures.map(m => standalone_compileMeasures(m, m.field));
  const cell = {
    num: 0,
    agg: null,
    store: false,
    count: counts
  };
  if (!countOnly) {
    var n = measures.length,
      a = cell.agg = Array(n),
      i = 0;
    for (; i < n; ++i) a[i] = new measures[i](cell);
  }
  if (cell.store) {
    var store = cell.data = new standalone_TupleStore();
  }
  cell.add = function (t) {
    cell.num += 1;
    if (countOnly) return;
    if (store) store.add(t);
    for (let i = 0; i < n; ++i) {
      a[i].add(a[i].get(t), t);
    }
  };
  cell.rem = function (t) {
    cell.num -= 1;
    if (countOnly) return;
    if (store) store.rem(t);
    for (let i = 0; i < n; ++i) {
      a[i].rem(a[i].get(t), t);
    }
  };
  cell.set = function (t) {
    let i, n;

    // consolidate stored values
    if (store) store.values();

    // update tuple properties
    for (i = 0, n = counts.length; i < n; ++i) t[counts[i]] = cell.num;
    if (!countOnly) for (i = 0, n = a.length; i < n; ++i) a[i].set(t);
  };
  cell.init = function () {
    cell.num = 0;
    if (store) store.reset();
    for (let i = 0; i < n; ++i) a[i].init();
  };
  return cell;
}

/**
 * Perform window calculations and write results to the input stream.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(*,*): number} [params.sort] - A comparator function for sorting tuples within a window.
 * @param {Array<function(object): *>} [params.groupby] - An array of accessors by which to partition tuples into separate windows.
 * @param {Array<string>} params.ops - An array of strings indicating window operations to perform.
 * @param {Array<function(object): *>} [params.fields] - An array of accessors
 *   for data fields to use as inputs to window operations.
 * @param {Array<*>} [params.params] - An array of parameter values for window operations.
 * @param {Array<number>} [params.aggregate_params] - An optional array of parameter values for aggregation operations.
 * @param {Array<string>} [params.as] - An array of output field names for window operations.
 * @param {Array<number>} [params.frame] - Window frame definition as two-element array.
 * @param {boolean} [params.ignorePeers=false] - If true, base window frame boundaries on row
 *   number alone, ignoring peers with identical sort values. If false (default),
 *   the window boundaries will be adjusted to include peer values.
 */
function standalone_Window(params) {
  standalone_Transform.call(this, {}, params);
  this._mlen = 0;
  this._mods = [];
}
standalone_Window.Definition = {
  'type': 'Window',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'sort',
    'type': 'compare'
  }, {
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'ops',
    'type': 'enum',
    'array': true,
    'values': standalone_ValidWindowOps.concat(standalone_ValidAggregateOps)
  }, {
    'name': 'params',
    'type': 'number',
    'null': true,
    'array': true
  }, {
    'name': 'aggregate_params',
    'type': 'number',
    'null': true,
    'array': true
  }, {
    'name': 'fields',
    'type': 'field',
    'null': true,
    'array': true
  }, {
    'name': 'as',
    'type': 'string',
    'null': true,
    'array': true
  }, {
    'name': 'frame',
    'type': 'number',
    'null': true,
    'array': true,
    'length': 2,
    'default': [null, 0]
  }, {
    'name': 'ignorePeers',
    'type': 'boolean',
    'default': false
  }]
};
standalone_inherits(standalone_Window, standalone_Transform, {
  transform(_, pulse) {
    this.stamp = pulse.stamp;
    const mod = _.modified(),
      cmp = standalone_stableCompare(_.sort),
      key = standalone_groupkey(_.groupby),
      group = t => this.group(key(t));

    // initialize window state
    let state = this.state;
    if (!state || mod) {
      state = this.state = new standalone_WindowState(_);
    }

    // partition input tuples
    if (mod || pulse.modified(state.inputs)) {
      this.value = {};
      pulse.visit(pulse.SOURCE, t => group(t).add(t));
    } else {
      pulse.visit(pulse.REM, t => group(t).remove(t));
      pulse.visit(pulse.ADD, t => group(t).add(t));
    }

    // perform window calculations for each modified partition
    for (let i = 0, n = this._mlen; i < n; ++i) {
      standalone_processPartition(this._mods[i], state, cmp, _);
    }
    this._mlen = 0;
    this._mods = [];

    // TODO don't reflow everything?
    return pulse.reflow(mod).modifies(state.outputs);
  },
  group(key) {
    let group = this.value[key];
    if (!group) {
      group = this.value[key] = standalone_SortedList(standalone_tupleid);
      group.stamp = -1;
    }
    if (group.stamp < this.stamp) {
      group.stamp = this.stamp;
      this._mods[this._mlen++] = group;
    }
    return group;
  }
});
function standalone_processPartition(list, state, cmp, _) {
  const sort = _.sort,
    range = sort && !_.ignorePeers,
    frame = _.frame || [null, 0],
    data = list.data(cmp),
    // use cmp for stable sort
    n = data.length,
    b = range ? standalone_bisector(sort) : null,
    w = {
      i0: 0,
      i1: 0,
      p0: 0,
      p1: 0,
      index: 0,
      data: data,
      compare: sort || standalone_vega_util_module_constant(-1)
    };
  state.init();
  for (let i = 0; i < n; ++i) {
    standalone_setWindow(w, frame, i, n);
    if (range) standalone_adjustRange(w, b);
    state.update(w, data[i]);
  }
}
function standalone_setWindow(w, f, i, n) {
  w.p0 = w.i0;
  w.p1 = w.i1;
  w.i0 = f[0] == null ? 0 : Math.max(0, i - Math.abs(f[0]));
  w.i1 = f[1] == null ? n : Math.min(n, i + Math.abs(f[1]) + 1);
  w.index = i;
}

// if frame type is 'range', adjust window for peer values
function standalone_adjustRange(w, bisect) {
  const r0 = w.i0,
    r1 = w.i1 - 1,
    c = w.compare,
    d = w.data,
    n = d.length - 1;
  if (r0 > 0 && !c(d[r0], d[r0 - 1])) w.i0 = bisect.left(d, d[r0]);
  if (r1 < n && !c(d[r1], d[r1 + 1])) w.i1 = bisect.right(d, d[r1]);
}



;// ../../node_modules/d3-shape/src/curve/basis.js
function standalone_point(that, x, y) {
  that._context.bezierCurveTo(
    (2 * that._x0 + that._x1) / 3,
    (2 * that._y0 + that._y1) / 3,
    (that._x0 + 2 * that._x1) / 3,
    (that._y0 + 2 * that._y1) / 3,
    (that._x0 + 4 * that._x1 + x) / 6,
    (that._y0 + 4 * that._y1 + y) / 6
  );
}

function standalone_Basis(context) {
  this._context = context;
}

standalone_Basis.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 =
    this._y0 = this._y1 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 3: standalone_point(this, this._x1, this._y1); // falls through
      case 2: this._context.lineTo(this._x1, this._y1); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6); // falls through
      default: standalone_point(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = x;
    this._y0 = this._y1, this._y1 = y;
  }
};

/* harmony default export */ function standalone_basis(context) {
  return new standalone_Basis(context);
}

;// ../../node_modules/d3-shape/src/noop.js
/* harmony default export */ function standalone_src_noop() {}

;// ../../node_modules/d3-shape/src/curve/basisClosed.js



function standalone_BasisClosed(context) {
  this._context = context;
}

standalone_BasisClosed.prototype = {
  areaStart: standalone_src_noop,
  areaEnd: standalone_src_noop,
  lineStart: function() {
    this._x0 = this._x1 = this._x2 = this._x3 = this._x4 =
    this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 1: {
        this._context.moveTo(this._x2, this._y2);
        this._context.closePath();
        break;
      }
      case 2: {
        this._context.moveTo((this._x2 + 2 * this._x3) / 3, (this._y2 + 2 * this._y3) / 3);
        this._context.lineTo((this._x3 + 2 * this._x2) / 3, (this._y3 + 2 * this._y2) / 3);
        this._context.closePath();
        break;
      }
      case 3: {
        this.point(this._x2, this._y2);
        this.point(this._x3, this._y3);
        this.point(this._x4, this._y4);
        break;
      }
    }
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._x2 = x, this._y2 = y; break;
      case 1: this._point = 2; this._x3 = x, this._y3 = y; break;
      case 2: this._point = 3; this._x4 = x, this._y4 = y; this._context.moveTo((this._x0 + 4 * this._x1 + x) / 6, (this._y0 + 4 * this._y1 + y) / 6); break;
      default: standalone_point(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = x;
    this._y0 = this._y1, this._y1 = y;
  }
};

/* harmony default export */ function standalone_basisClosed(context) {
  return new standalone_BasisClosed(context);
}

;// ../../node_modules/d3-shape/src/curve/basisOpen.js


function standalone_BasisOpen(context) {
  this._context = context;
}

standalone_BasisOpen.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 =
    this._y0 = this._y1 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; var x0 = (this._x0 + 4 * this._x1 + x) / 6, y0 = (this._y0 + 4 * this._y1 + y) / 6; this._line ? this._context.lineTo(x0, y0) : this._context.moveTo(x0, y0); break;
      case 3: this._point = 4; // falls through
      default: standalone_point(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = x;
    this._y0 = this._y1, this._y1 = y;
  }
};

/* harmony default export */ function standalone_basisOpen(context) {
  return new standalone_BasisOpen(context);
}

;// ../../node_modules/d3-shape/src/curve/bundle.js


function standalone_Bundle(context, beta) {
  this._basis = new standalone_Basis(context);
  this._beta = beta;
}

standalone_Bundle.prototype = {
  lineStart: function() {
    this._x = [];
    this._y = [];
    this._basis.lineStart();
  },
  lineEnd: function() {
    var x = this._x,
        y = this._y,
        j = x.length - 1;

    if (j > 0) {
      var x0 = x[0],
          y0 = y[0],
          dx = x[j] - x0,
          dy = y[j] - y0,
          i = -1,
          t;

      while (++i <= j) {
        t = i / j;
        this._basis.point(
          this._beta * x[i] + (1 - this._beta) * (x0 + t * dx),
          this._beta * y[i] + (1 - this._beta) * (y0 + t * dy)
        );
      }
    }

    this._x = this._y = null;
    this._basis.lineEnd();
  },
  point: function(x, y) {
    this._x.push(+x);
    this._y.push(+y);
  }
};

/* harmony default export */ const standalone_bundle = ((function custom(beta) {

  function bundle(context) {
    return beta === 1 ? new standalone_Basis(context) : new standalone_Bundle(context, beta);
  }

  bundle.beta = function(beta) {
    return custom(+beta);
  };

  return bundle;
})(0.85));

;// ../../node_modules/d3-shape/src/curve/cardinal.js
function standalone_cardinal_point(that, x, y) {
  that._context.bezierCurveTo(
    that._x1 + that._k * (that._x2 - that._x0),
    that._y1 + that._k * (that._y2 - that._y0),
    that._x2 + that._k * (that._x1 - x),
    that._y2 + that._k * (that._y1 - y),
    that._x2,
    that._y2
  );
}

function standalone_Cardinal(context, tension) {
  this._context = context;
  this._k = (1 - tension) / 6;
}

standalone_Cardinal.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 =
    this._y0 = this._y1 = this._y2 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2: this._context.lineTo(this._x2, this._y2); break;
      case 3: standalone_cardinal_point(this, this._x1, this._y1); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; this._x1 = x, this._y1 = y; break;
      case 2: this._point = 3; // falls through
      default: standalone_cardinal_point(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

/* harmony default export */ const standalone_cardinal = ((function custom(tension) {

  function cardinal(context) {
    return new standalone_Cardinal(context, tension);
  }

  cardinal.tension = function(tension) {
    return custom(+tension);
  };

  return cardinal;
})(0));

;// ../../node_modules/d3-shape/src/curve/cardinalOpen.js


function standalone_CardinalOpen(context, tension) {
  this._context = context;
  this._k = (1 - tension) / 6;
}

standalone_CardinalOpen.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 =
    this._y0 = this._y1 = this._y2 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;
      case 3: this._point = 4; // falls through
      default: standalone_cardinal_point(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

/* harmony default export */ const standalone_cardinalOpen = ((function custom(tension) {

  function cardinal(context) {
    return new standalone_CardinalOpen(context, tension);
  }

  cardinal.tension = function(tension) {
    return custom(+tension);
  };

  return cardinal;
})(0));

;// ../../node_modules/d3-shape/src/curve/cardinalClosed.js



function standalone_CardinalClosed(context, tension) {
  this._context = context;
  this._k = (1 - tension) / 6;
}

standalone_CardinalClosed.prototype = {
  areaStart: standalone_src_noop,
  areaEnd: standalone_src_noop,
  lineStart: function() {
    this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =
    this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 1: {
        this._context.moveTo(this._x3, this._y3);
        this._context.closePath();
        break;
      }
      case 2: {
        this._context.lineTo(this._x3, this._y3);
        this._context.closePath();
        break;
      }
      case 3: {
        this.point(this._x3, this._y3);
        this.point(this._x4, this._y4);
        this.point(this._x5, this._y5);
        break;
      }
    }
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._x3 = x, this._y3 = y; break;
      case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;
      case 2: this._point = 3; this._x5 = x, this._y5 = y; break;
      default: standalone_cardinal_point(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

/* harmony default export */ const standalone_cardinalClosed = ((function custom(tension) {

  function cardinal(context) {
    return new standalone_CardinalClosed(context, tension);
  }

  cardinal.tension = function(tension) {
    return custom(+tension);
  };

  return cardinal;
})(0));

;// ../../node_modules/d3-shape/src/math.js
const standalone_abs = Math.abs;
const standalone_atan2 = Math.atan2;
const standalone_cos = Math.cos;
const standalone_math_max = Math.max;
const standalone_math_min = Math.min;
const standalone_sin = Math.sin;
const standalone_sqrt = Math.sqrt;

const standalone_math_epsilon = 1e-12;
const standalone_pi = Math.PI;
const standalone_halfPi = standalone_pi / 2;
const standalone_tau = 2 * standalone_pi;

function standalone_acos(x) {
  return x > 1 ? 0 : x < -1 ? standalone_pi : Math.acos(x);
}

function standalone_asin(x) {
  return x >= 1 ? standalone_halfPi : x <= -1 ? -standalone_halfPi : Math.asin(x);
}

;// ../../node_modules/d3-shape/src/curve/catmullRom.js



function standalone_catmullRom_point(that, x, y) {
  var x1 = that._x1,
      y1 = that._y1,
      x2 = that._x2,
      y2 = that._y2;

  if (that._l01_a > standalone_math_epsilon) {
    var a = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a,
        n = 3 * that._l01_a * (that._l01_a + that._l12_a);
    x1 = (x1 * a - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n;
    y1 = (y1 * a - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n;
  }

  if (that._l23_a > standalone_math_epsilon) {
    var b = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a,
        m = 3 * that._l23_a * (that._l23_a + that._l12_a);
    x2 = (x2 * b + that._x1 * that._l23_2a - x * that._l12_2a) / m;
    y2 = (y2 * b + that._y1 * that._l23_2a - y * that._l12_2a) / m;
  }

  that._context.bezierCurveTo(x1, y1, x2, y2, that._x2, that._y2);
}

function standalone_CatmullRom(context, alpha) {
  this._context = context;
  this._alpha = alpha;
}

standalone_CatmullRom.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 =
    this._y0 = this._y1 = this._y2 = NaN;
    this._l01_a = this._l12_a = this._l23_a =
    this._l01_2a = this._l12_2a = this._l23_2a =
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2: this._context.lineTo(this._x2, this._y2); break;
      case 3: this.point(this._x2, this._y2); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;

    if (this._point) {
      var x23 = this._x2 - x,
          y23 = this._y2 - y;
      this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
    }

    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; // falls through
      default: standalone_catmullRom_point(this, x, y); break;
    }

    this._l01_a = this._l12_a, this._l12_a = this._l23_a;
    this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

/* harmony default export */ const standalone_catmullRom = ((function custom(alpha) {

  function catmullRom(context) {
    return alpha ? new standalone_CatmullRom(context, alpha) : new standalone_Cardinal(context, 0);
  }

  catmullRom.alpha = function(alpha) {
    return custom(+alpha);
  };

  return catmullRom;
})(0.5));

;// ../../node_modules/d3-shape/src/curve/catmullRomClosed.js




function standalone_CatmullRomClosed(context, alpha) {
  this._context = context;
  this._alpha = alpha;
}

standalone_CatmullRomClosed.prototype = {
  areaStart: standalone_src_noop,
  areaEnd: standalone_src_noop,
  lineStart: function() {
    this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =
    this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
    this._l01_a = this._l12_a = this._l23_a =
    this._l01_2a = this._l12_2a = this._l23_2a =
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 1: {
        this._context.moveTo(this._x3, this._y3);
        this._context.closePath();
        break;
      }
      case 2: {
        this._context.lineTo(this._x3, this._y3);
        this._context.closePath();
        break;
      }
      case 3: {
        this.point(this._x3, this._y3);
        this.point(this._x4, this._y4);
        this.point(this._x5, this._y5);
        break;
      }
    }
  },
  point: function(x, y) {
    x = +x, y = +y;

    if (this._point) {
      var x23 = this._x2 - x,
          y23 = this._y2 - y;
      this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
    }

    switch (this._point) {
      case 0: this._point = 1; this._x3 = x, this._y3 = y; break;
      case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;
      case 2: this._point = 3; this._x5 = x, this._y5 = y; break;
      default: standalone_catmullRom_point(this, x, y); break;
    }

    this._l01_a = this._l12_a, this._l12_a = this._l23_a;
    this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

/* harmony default export */ const standalone_catmullRomClosed = ((function custom(alpha) {

  function catmullRom(context) {
    return alpha ? new standalone_CatmullRomClosed(context, alpha) : new standalone_CardinalClosed(context, 0);
  }

  catmullRom.alpha = function(alpha) {
    return custom(+alpha);
  };

  return catmullRom;
})(0.5));

;// ../../node_modules/d3-shape/src/curve/catmullRomOpen.js



function standalone_CatmullRomOpen(context, alpha) {
  this._context = context;
  this._alpha = alpha;
}

standalone_CatmullRomOpen.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 =
    this._y0 = this._y1 = this._y2 = NaN;
    this._l01_a = this._l12_a = this._l23_a =
    this._l01_2a = this._l12_2a = this._l23_2a =
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;

    if (this._point) {
      var x23 = this._x2 - x,
          y23 = this._y2 - y;
      this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
    }

    switch (this._point) {
      case 0: this._point = 1; break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;
      case 3: this._point = 4; // falls through
      default: standalone_catmullRom_point(this, x, y); break;
    }

    this._l01_a = this._l12_a, this._l12_a = this._l23_a;
    this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

/* harmony default export */ const standalone_catmullRomOpen = ((function custom(alpha) {

  function catmullRom(context) {
    return alpha ? new standalone_CatmullRomOpen(context, alpha) : new standalone_CardinalOpen(context, 0);
  }

  catmullRom.alpha = function(alpha) {
    return custom(+alpha);
  };

  return catmullRom;
})(0.5));

;// ../../node_modules/d3-shape/src/curve/linear.js
function standalone_Linear(context) {
  this._context = context;
}

standalone_Linear.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; // falls through
      default: this._context.lineTo(x, y); break;
    }
  }
};

/* harmony default export */ function standalone_curve_linear(context) {
  return new standalone_Linear(context);
}

;// ../../node_modules/d3-shape/src/curve/linearClosed.js


function standalone_LinearClosed(context) {
  this._context = context;
}

standalone_LinearClosed.prototype = {
  areaStart: standalone_src_noop,
  areaEnd: standalone_src_noop,
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._point) this._context.closePath();
  },
  point: function(x, y) {
    x = +x, y = +y;
    if (this._point) this._context.lineTo(x, y);
    else this._point = 1, this._context.moveTo(x, y);
  }
};

/* harmony default export */ function standalone_linearClosed(context) {
  return new standalone_LinearClosed(context);
}

;// ../../node_modules/d3-shape/src/curve/monotone.js
function standalone_sign(x) {
  return x < 0 ? -1 : 1;
}

// Calculate the slopes of the tangents (Hermite-type interpolation) based on
// the following paper: Steffen, M. 1990. A Simple Method for Monotonic
// Interpolation in One Dimension. Astronomy and Astrophysics, Vol. 239, NO.
// NOV(II), P. 443, 1990.
function standalone_slope3(that, x2, y2) {
  var h0 = that._x1 - that._x0,
      h1 = x2 - that._x1,
      s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0),
      s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0),
      p = (s0 * h1 + s1 * h0) / (h0 + h1);
  return (standalone_sign(s0) + standalone_sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
}

// Calculate a one-sided slope.
function standalone_slope2(that, t) {
  var h = that._x1 - that._x0;
  return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
}

// According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations
// "you can express cubic Hermite interpolation in terms of cubic Bézier curves
// with respect to the four values p0, p0 + m0 / 3, p1 - m1 / 3, p1".
function standalone_monotone_point(that, t0, t1) {
  var x0 = that._x0,
      y0 = that._y0,
      x1 = that._x1,
      y1 = that._y1,
      dx = (x1 - x0) / 3;
  that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1);
}

function standalone_MonotoneX(context) {
  this._context = context;
}

standalone_MonotoneX.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 =
    this._y0 = this._y1 =
    this._t0 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2: this._context.lineTo(this._x1, this._y1); break;
      case 3: standalone_monotone_point(this, this._t0, standalone_slope2(this, this._t0)); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    var t1 = NaN;

    x = +x, y = +y;
    if (x === this._x1 && y === this._y1) return; // Ignore coincident points.
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; standalone_monotone_point(this, standalone_slope2(this, t1 = standalone_slope3(this, x, y)), t1); break;
      default: standalone_monotone_point(this, this._t0, t1 = standalone_slope3(this, x, y)); break;
    }

    this._x0 = this._x1, this._x1 = x;
    this._y0 = this._y1, this._y1 = y;
    this._t0 = t1;
  }
}

function standalone_MonotoneY(context) {
  this._context = new standalone_ReflectContext(context);
}

(standalone_MonotoneY.prototype = Object.create(standalone_MonotoneX.prototype)).point = function(x, y) {
  standalone_MonotoneX.prototype.point.call(this, y, x);
};

function standalone_ReflectContext(context) {
  this._context = context;
}

standalone_ReflectContext.prototype = {
  moveTo: function(x, y) { this._context.moveTo(y, x); },
  closePath: function() { this._context.closePath(); },
  lineTo: function(x, y) { this._context.lineTo(y, x); },
  bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._context.bezierCurveTo(y1, x1, y2, x2, y, x); }
};

function standalone_monotoneX(context) {
  return new standalone_MonotoneX(context);
}

function standalone_monotoneY(context) {
  return new standalone_MonotoneY(context);
}

;// ../../node_modules/d3-shape/src/curve/natural.js
function standalone_Natural(context) {
  this._context = context;
}

standalone_Natural.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x = [];
    this._y = [];
  },
  lineEnd: function() {
    var x = this._x,
        y = this._y,
        n = x.length;

    if (n) {
      this._line ? this._context.lineTo(x[0], y[0]) : this._context.moveTo(x[0], y[0]);
      if (n === 2) {
        this._context.lineTo(x[1], y[1]);
      } else {
        var px = standalone_controlPoints(x),
            py = standalone_controlPoints(y);
        for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {
          this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x[i1], y[i1]);
        }
      }
    }

    if (this._line || (this._line !== 0 && n === 1)) this._context.closePath();
    this._line = 1 - this._line;
    this._x = this._y = null;
  },
  point: function(x, y) {
    this._x.push(+x);
    this._y.push(+y);
  }
};

// See https://www.particleincell.com/2012/bezier-splines/ for derivation.
function standalone_controlPoints(x) {
  var i,
      n = x.length - 1,
      m,
      a = new Array(n),
      b = new Array(n),
      r = new Array(n);
  a[0] = 0, b[0] = 2, r[0] = x[0] + 2 * x[1];
  for (i = 1; i < n - 1; ++i) a[i] = 1, b[i] = 4, r[i] = 4 * x[i] + 2 * x[i + 1];
  a[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x[n - 1] + x[n];
  for (i = 1; i < n; ++i) m = a[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];
  a[n - 1] = r[n - 1] / b[n - 1];
  for (i = n - 2; i >= 0; --i) a[i] = (r[i] - a[i + 1]) / b[i];
  b[n - 1] = (x[n] + a[n - 1]) / 2;
  for (i = 0; i < n - 1; ++i) b[i] = 2 * x[i + 1] - a[i + 1];
  return [a, b];
}

/* harmony default export */ function standalone_natural(context) {
  return new standalone_Natural(context);
}

;// ../../node_modules/d3-shape/src/curve/step.js
function standalone_Step(context, t) {
  this._context = context;
  this._t = t;
}

standalone_Step.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x = this._y = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; // falls through
      default: {
        if (this._t <= 0) {
          this._context.lineTo(this._x, y);
          this._context.lineTo(x, y);
        } else {
          var x1 = this._x * (1 - this._t) + x * this._t;
          this._context.lineTo(x1, this._y);
          this._context.lineTo(x1, y);
        }
        break;
      }
    }
    this._x = x, this._y = y;
  }
};

/* harmony default export */ function standalone_step(context) {
  return new standalone_Step(context, 0.5);
}

function standalone_stepBefore(context) {
  return new standalone_Step(context, 0);
}

function standalone_stepAfter(context) {
  return new standalone_Step(context, 1);
}

;// ../../node_modules/d3-shape/src/constant.js
/* harmony default export */ function standalone_src_constant(x) {
  return function constant() {
    return x;
  };
}

;// ../../node_modules/d3-path/src/path.js
const standalone_path_pi = Math.PI,
    standalone_path_tau = 2 * standalone_path_pi,
    standalone_path_epsilon = 1e-6,
    standalone_tauEpsilon = standalone_path_tau - standalone_path_epsilon;

function standalone_path_append(strings) {
  this._ += strings[0];
  for (let i = 1, n = strings.length; i < n; ++i) {
    this._ += arguments[i] + strings[i];
  }
}

function standalone_appendRound(digits) {
  let d = Math.floor(digits);
  if (!(d >= 0)) throw new Error(`invalid digits: ${digits}`);
  if (d > 15) return standalone_path_append;
  const k = 10 ** d;
  return function(strings) {
    this._ += strings[0];
    for (let i = 1, n = strings.length; i < n; ++i) {
      this._ += Math.round(arguments[i] * k) / k + strings[i];
    }
  };
}

class standalone_Path {
  constructor(digits) {
    this._x0 = this._y0 = // start of current subpath
    this._x1 = this._y1 = null; // end of current subpath
    this._ = "";
    this._append = digits == null ? standalone_path_append : standalone_appendRound(digits);
  }
  moveTo(x, y) {
    this._append`M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}`;
  }
  closePath() {
    if (this._x1 !== null) {
      this._x1 = this._x0, this._y1 = this._y0;
      this._append`Z`;
    }
  }
  lineTo(x, y) {
    this._append`L${this._x1 = +x},${this._y1 = +y}`;
  }
  quadraticCurveTo(x1, y1, x, y) {
    this._append`Q${+x1},${+y1},${this._x1 = +x},${this._y1 = +y}`;
  }
  bezierCurveTo(x1, y1, x2, y2, x, y) {
    this._append`C${+x1},${+y1},${+x2},${+y2},${this._x1 = +x},${this._y1 = +y}`;
  }
  arcTo(x1, y1, x2, y2, r) {
    x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;

    // Is the radius negative? Error.
    if (r < 0) throw new Error(`negative radius: ${r}`);

    let x0 = this._x1,
        y0 = this._y1,
        x21 = x2 - x1,
        y21 = y2 - y1,
        x01 = x0 - x1,
        y01 = y0 - y1,
        l01_2 = x01 * x01 + y01 * y01;

    // Is this path empty? Move to (x1,y1).
    if (this._x1 === null) {
      this._append`M${this._x1 = x1},${this._y1 = y1}`;
    }

    // Or, is (x1,y1) coincident with (x0,y0)? Do nothing.
    else if (!(l01_2 > standalone_path_epsilon));

    // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?
    // Equivalently, is (x1,y1) coincident with (x2,y2)?
    // Or, is the radius zero? Line to (x1,y1).
    else if (!(Math.abs(y01 * x21 - y21 * x01) > standalone_path_epsilon) || !r) {
      this._append`L${this._x1 = x1},${this._y1 = y1}`;
    }

    // Otherwise, draw an arc!
    else {
      let x20 = x2 - x0,
          y20 = y2 - y0,
          l21_2 = x21 * x21 + y21 * y21,
          l20_2 = x20 * x20 + y20 * y20,
          l21 = Math.sqrt(l21_2),
          l01 = Math.sqrt(l01_2),
          l = r * Math.tan((standalone_path_pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),
          t01 = l / l01,
          t21 = l / l21;

      // If the start tangent is not coincident with (x0,y0), line to.
      if (Math.abs(t01 - 1) > standalone_path_epsilon) {
        this._append`L${x1 + t01 * x01},${y1 + t01 * y01}`;
      }

      this._append`A${r},${r},0,0,${+(y01 * x20 > x01 * y20)},${this._x1 = x1 + t21 * x21},${this._y1 = y1 + t21 * y21}`;
    }
  }
  arc(x, y, r, a0, a1, ccw) {
    x = +x, y = +y, r = +r, ccw = !!ccw;

    // Is the radius negative? Error.
    if (r < 0) throw new Error(`negative radius: ${r}`);

    let dx = r * Math.cos(a0),
        dy = r * Math.sin(a0),
        x0 = x + dx,
        y0 = y + dy,
        cw = 1 ^ ccw,
        da = ccw ? a0 - a1 : a1 - a0;

    // Is this path empty? Move to (x0,y0).
    if (this._x1 === null) {
      this._append`M${x0},${y0}`;
    }

    // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).
    else if (Math.abs(this._x1 - x0) > standalone_path_epsilon || Math.abs(this._y1 - y0) > standalone_path_epsilon) {
      this._append`L${x0},${y0}`;
    }

    // Is this arc empty? We’re done.
    if (!r) return;

    // Does the angle go the wrong way? Flip the direction.
    if (da < 0) da = da % standalone_path_tau + standalone_path_tau;

    // Is this a complete circle? Draw two arcs to complete the circle.
    if (da > standalone_tauEpsilon) {
      this._append`A${r},${r},0,1,${cw},${x - dx},${y - dy}A${r},${r},0,1,${cw},${this._x1 = x0},${this._y1 = y0}`;
    }

    // Is this arc non-empty? Draw an arc!
    else if (da > standalone_path_epsilon) {
      this._append`A${r},${r},0,${+(da >= standalone_path_pi)},${cw},${this._x1 = x + r * Math.cos(a1)},${this._y1 = y + r * Math.sin(a1)}`;
    }
  }
  rect(x, y, w, h) {
    this._append`M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}h${w = +w}v${+h}h${-w}Z`;
  }
  toString() {
    return this._;
  }
}

function standalone_path() {
  return new standalone_Path;
}

// Allow instanceof d3.path
standalone_path.prototype = standalone_Path.prototype;

function standalone_pathRound(digits = 3) {
  return new standalone_Path(+digits);
}

;// ../../node_modules/d3-shape/src/path.js


function standalone_withPath(shape) {
  let digits = 3;

  shape.digits = function(_) {
    if (!arguments.length) return digits;
    if (_ == null) {
      digits = null;
    } else {
      const d = Math.floor(_);
      if (!(d >= 0)) throw new RangeError(`invalid digits: ${_}`);
      digits = d;
    }
    return shape;
  };

  return () => new standalone_Path(digits);
}

;// ../../node_modules/d3-shape/src/arc.js




function standalone_arcInnerRadius(d) {
  return d.innerRadius;
}

function standalone_arcOuterRadius(d) {
  return d.outerRadius;
}

function standalone_arcStartAngle(d) {
  return d.startAngle;
}

function standalone_arcEndAngle(d) {
  return d.endAngle;
}

function standalone_arcPadAngle(d) {
  return d && d.padAngle; // Note: optional!
}

function standalone_intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  var x10 = x1 - x0, y10 = y1 - y0,
      x32 = x3 - x2, y32 = y3 - y2,
      t = y32 * x10 - x32 * y10;
  if (t * t < standalone_math_epsilon) return;
  t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
  return [x0 + t * x10, y0 + t * y10];
}

// Compute perpendicular offset line of length rc.
// http://mathworld.wolfram.com/Circle-LineIntersection.html
function standalone_cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
  var x01 = x0 - x1,
      y01 = y0 - y1,
      lo = (cw ? rc : -rc) / standalone_sqrt(x01 * x01 + y01 * y01),
      ox = lo * y01,
      oy = -lo * x01,
      x11 = x0 + ox,
      y11 = y0 + oy,
      x10 = x1 + ox,
      y10 = y1 + oy,
      x00 = (x11 + x10) / 2,
      y00 = (y11 + y10) / 2,
      dx = x10 - x11,
      dy = y10 - y11,
      d2 = dx * dx + dy * dy,
      r = r1 - rc,
      D = x11 * y10 - x10 * y11,
      d = (dy < 0 ? -1 : 1) * standalone_sqrt(standalone_math_max(0, r * r * d2 - D * D)),
      cx0 = (D * dy - dx * d) / d2,
      cy0 = (-D * dx - dy * d) / d2,
      cx1 = (D * dy + dx * d) / d2,
      cy1 = (-D * dx + dy * d) / d2,
      dx0 = cx0 - x00,
      dy0 = cy0 - y00,
      dx1 = cx1 - x00,
      dy1 = cy1 - y00;

  // Pick the closer of the two intersection points.
  // TODO Is there a faster way to determine which intersection to use?
  if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;

  return {
    cx: cx0,
    cy: cy0,
    x01: -ox,
    y01: -oy,
    x11: cx0 * (r1 / r - 1),
    y11: cy0 * (r1 / r - 1)
  };
}

/* harmony default export */ function standalone_arc() {
  var innerRadius = standalone_arcInnerRadius,
      outerRadius = standalone_arcOuterRadius,
      cornerRadius = standalone_src_constant(0),
      padRadius = null,
      startAngle = standalone_arcStartAngle,
      endAngle = standalone_arcEndAngle,
      padAngle = standalone_arcPadAngle,
      context = null,
      path = standalone_withPath(arc);

  function arc() {
    var buffer,
        r,
        r0 = +innerRadius.apply(this, arguments),
        r1 = +outerRadius.apply(this, arguments),
        a0 = startAngle.apply(this, arguments) - standalone_halfPi,
        a1 = endAngle.apply(this, arguments) - standalone_halfPi,
        da = standalone_abs(a1 - a0),
        cw = a1 > a0;

    if (!context) context = buffer = path();

    // Ensure that the outer radius is always larger than the inner radius.
    if (r1 < r0) r = r1, r1 = r0, r0 = r;

    // Is it a point?
    if (!(r1 > standalone_math_epsilon)) context.moveTo(0, 0);

    // Or is it a circle or annulus?
    else if (da > standalone_tau - standalone_math_epsilon) {
      context.moveTo(r1 * standalone_cos(a0), r1 * standalone_sin(a0));
      context.arc(0, 0, r1, a0, a1, !cw);
      if (r0 > standalone_math_epsilon) {
        context.moveTo(r0 * standalone_cos(a1), r0 * standalone_sin(a1));
        context.arc(0, 0, r0, a1, a0, cw);
      }
    }

    // Or is it a circular or annular sector?
    else {
      var a01 = a0,
          a11 = a1,
          a00 = a0,
          a10 = a1,
          da0 = da,
          da1 = da,
          ap = padAngle.apply(this, arguments) / 2,
          rp = (ap > standalone_math_epsilon) && (padRadius ? +padRadius.apply(this, arguments) : standalone_sqrt(r0 * r0 + r1 * r1)),
          rc = standalone_math_min(standalone_abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)),
          rc0 = rc,
          rc1 = rc,
          t0,
          t1;

      // Apply padding? Note that since r1 ≥ r0, da1 ≥ da0.
      if (rp > standalone_math_epsilon) {
        var p0 = standalone_asin(rp / r0 * standalone_sin(ap)),
            p1 = standalone_asin(rp / r1 * standalone_sin(ap));
        if ((da0 -= p0 * 2) > standalone_math_epsilon) p0 *= (cw ? 1 : -1), a00 += p0, a10 -= p0;
        else da0 = 0, a00 = a10 = (a0 + a1) / 2;
        if ((da1 -= p1 * 2) > standalone_math_epsilon) p1 *= (cw ? 1 : -1), a01 += p1, a11 -= p1;
        else da1 = 0, a01 = a11 = (a0 + a1) / 2;
      }

      var x01 = r1 * standalone_cos(a01),
          y01 = r1 * standalone_sin(a01),
          x10 = r0 * standalone_cos(a10),
          y10 = r0 * standalone_sin(a10);

      // Apply rounded corners?
      if (rc > standalone_math_epsilon) {
        var x11 = r1 * standalone_cos(a11),
            y11 = r1 * standalone_sin(a11),
            x00 = r0 * standalone_cos(a00),
            y00 = r0 * standalone_sin(a00),
            oc;

        // Restrict the corner radius according to the sector angle. If this
        // intersection fails, it’s probably because the arc is too small, so
        // disable the corner radius entirely.
        if (da < standalone_pi) {
          if (oc = standalone_intersect(x01, y01, x00, y00, x11, y11, x10, y10)) {
            var ax = x01 - oc[0],
                ay = y01 - oc[1],
                bx = x11 - oc[0],
                by = y11 - oc[1],
                kc = 1 / standalone_sin(standalone_acos((ax * bx + ay * by) / (standalone_sqrt(ax * ax + ay * ay) * standalone_sqrt(bx * bx + by * by))) / 2),
                lc = standalone_sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
            rc0 = standalone_math_min(rc, (r0 - lc) / (kc - 1));
            rc1 = standalone_math_min(rc, (r1 - lc) / (kc + 1));
          } else {
            rc0 = rc1 = 0;
          }
        }
      }

      // Is the sector collapsed to a line?
      if (!(da1 > standalone_math_epsilon)) context.moveTo(x01, y01);

      // Does the sector’s outer ring have rounded corners?
      else if (rc1 > standalone_math_epsilon) {
        t0 = standalone_cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
        t1 = standalone_cornerTangents(x11, y11, x10, y10, r1, rc1, cw);

        context.moveTo(t0.cx + t0.x01, t0.cy + t0.y01);

        // Have the corners merged?
        if (rc1 < rc) context.arc(t0.cx, t0.cy, rc1, standalone_atan2(t0.y01, t0.x01), standalone_atan2(t1.y01, t1.x01), !cw);

        // Otherwise, draw the two corners and the ring.
        else {
          context.arc(t0.cx, t0.cy, rc1, standalone_atan2(t0.y01, t0.x01), standalone_atan2(t0.y11, t0.x11), !cw);
          context.arc(0, 0, r1, standalone_atan2(t0.cy + t0.y11, t0.cx + t0.x11), standalone_atan2(t1.cy + t1.y11, t1.cx + t1.x11), !cw);
          context.arc(t1.cx, t1.cy, rc1, standalone_atan2(t1.y11, t1.x11), standalone_atan2(t1.y01, t1.x01), !cw);
        }
      }

      // Or is the outer ring just a circular arc?
      else context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);

      // Is there no inner ring, and it’s a circular sector?
      // Or perhaps it’s an annular sector collapsed due to padding?
      if (!(r0 > standalone_math_epsilon) || !(da0 > standalone_math_epsilon)) context.lineTo(x10, y10);

      // Does the sector’s inner ring (or point) have rounded corners?
      else if (rc0 > standalone_math_epsilon) {
        t0 = standalone_cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
        t1 = standalone_cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);

        context.lineTo(t0.cx + t0.x01, t0.cy + t0.y01);

        // Have the corners merged?
        if (rc0 < rc) context.arc(t0.cx, t0.cy, rc0, standalone_atan2(t0.y01, t0.x01), standalone_atan2(t1.y01, t1.x01), !cw);

        // Otherwise, draw the two corners and the ring.
        else {
          context.arc(t0.cx, t0.cy, rc0, standalone_atan2(t0.y01, t0.x01), standalone_atan2(t0.y11, t0.x11), !cw);
          context.arc(0, 0, r0, standalone_atan2(t0.cy + t0.y11, t0.cx + t0.x11), standalone_atan2(t1.cy + t1.y11, t1.cx + t1.x11), cw);
          context.arc(t1.cx, t1.cy, rc0, standalone_atan2(t1.y11, t1.x11), standalone_atan2(t1.y01, t1.x01), !cw);
        }
      }

      // Or is the inner ring just a circular arc?
      else context.arc(0, 0, r0, a10, a00, cw);
    }

    context.closePath();

    if (buffer) return context = null, buffer + "" || null;
  }

  arc.centroid = function() {
    var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2,
        a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - standalone_pi / 2;
    return [standalone_cos(a) * r, standalone_sin(a) * r];
  };

  arc.innerRadius = function(_) {
    return arguments.length ? (innerRadius = typeof _ === "function" ? _ : standalone_src_constant(+_), arc) : innerRadius;
  };

  arc.outerRadius = function(_) {
    return arguments.length ? (outerRadius = typeof _ === "function" ? _ : standalone_src_constant(+_), arc) : outerRadius;
  };

  arc.cornerRadius = function(_) {
    return arguments.length ? (cornerRadius = typeof _ === "function" ? _ : standalone_src_constant(+_), arc) : cornerRadius;
  };

  arc.padRadius = function(_) {
    return arguments.length ? (padRadius = _ == null ? null : typeof _ === "function" ? _ : standalone_src_constant(+_), arc) : padRadius;
  };

  arc.startAngle = function(_) {
    return arguments.length ? (startAngle = typeof _ === "function" ? _ : standalone_src_constant(+_), arc) : startAngle;
  };

  arc.endAngle = function(_) {
    return arguments.length ? (endAngle = typeof _ === "function" ? _ : standalone_src_constant(+_), arc) : endAngle;
  };

  arc.padAngle = function(_) {
    return arguments.length ? (padAngle = typeof _ === "function" ? _ : standalone_src_constant(+_), arc) : padAngle;
  };

  arc.context = function(_) {
    return arguments.length ? ((context = _ == null ? null : _), arc) : context;
  };

  return arc;
}

;// ../../node_modules/d3-shape/src/array.js
var standalone_slice = Array.prototype.slice;

/* harmony default export */ function standalone_src_array(x) {
  return typeof x === "object" && "length" in x
    ? x // Array, TypedArray, NodeList, array-like
    : Array.from(x); // Map, Set, iterable, string, or anything else
}

;// ../../node_modules/d3-shape/src/point.js
function standalone_point_x(p) {
  return p[0];
}

function standalone_point_y(p) {
  return p[1];
}

;// ../../node_modules/d3-shape/src/line.js






/* harmony default export */ function standalone_line(x, y) {
  var defined = standalone_src_constant(true),
      context = null,
      curve = standalone_curve_linear,
      output = null,
      path = standalone_withPath(line);

  x = typeof x === "function" ? x : (x === undefined) ? standalone_point_x : standalone_src_constant(x);
  y = typeof y === "function" ? y : (y === undefined) ? standalone_point_y : standalone_src_constant(y);

  function line(data) {
    var i,
        n = (data = standalone_src_array(data)).length,
        d,
        defined0 = false,
        buffer;

    if (context == null) output = curve(buffer = path());

    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) output.lineStart();
        else output.lineEnd();
      }
      if (defined0) output.point(+x(d, i, data), +y(d, i, data));
    }

    if (buffer) return output = null, buffer + "" || null;
  }

  line.x = function(_) {
    return arguments.length ? (x = typeof _ === "function" ? _ : standalone_src_constant(+_), line) : x;
  };

  line.y = function(_) {
    return arguments.length ? (y = typeof _ === "function" ? _ : standalone_src_constant(+_), line) : y;
  };

  line.defined = function(_) {
    return arguments.length ? (defined = typeof _ === "function" ? _ : standalone_src_constant(!!_), line) : defined;
  };

  line.curve = function(_) {
    return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;
  };

  line.context = function(_) {
    return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;
  };

  return line;
}

;// ../../node_modules/d3-shape/src/area.js







/* harmony default export */ function standalone_src_area(x0, y0, y1) {
  var x1 = null,
      defined = standalone_src_constant(true),
      context = null,
      curve = standalone_curve_linear,
      output = null,
      path = standalone_withPath(area);

  x0 = typeof x0 === "function" ? x0 : (x0 === undefined) ? standalone_point_x : standalone_src_constant(+x0);
  y0 = typeof y0 === "function" ? y0 : (y0 === undefined) ? standalone_src_constant(0) : standalone_src_constant(+y0);
  y1 = typeof y1 === "function" ? y1 : (y1 === undefined) ? standalone_point_y : standalone_src_constant(+y1);

  function area(data) {
    var i,
        j,
        k,
        n = (data = standalone_src_array(data)).length,
        d,
        defined0 = false,
        buffer,
        x0z = new Array(n),
        y0z = new Array(n);

    if (context == null) output = curve(buffer = path());

    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) {
          j = i;
          output.areaStart();
          output.lineStart();
        } else {
          output.lineEnd();
          output.lineStart();
          for (k = i - 1; k >= j; --k) {
            output.point(x0z[k], y0z[k]);
          }
          output.lineEnd();
          output.areaEnd();
        }
      }
      if (defined0) {
        x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);
        output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);
      }
    }

    if (buffer) return output = null, buffer + "" || null;
  }

  function arealine() {
    return standalone_line().defined(defined).curve(curve).context(context);
  }

  area.x = function(_) {
    return arguments.length ? (x0 = typeof _ === "function" ? _ : standalone_src_constant(+_), x1 = null, area) : x0;
  };

  area.x0 = function(_) {
    return arguments.length ? (x0 = typeof _ === "function" ? _ : standalone_src_constant(+_), area) : x0;
  };

  area.x1 = function(_) {
    return arguments.length ? (x1 = _ == null ? null : typeof _ === "function" ? _ : standalone_src_constant(+_), area) : x1;
  };

  area.y = function(_) {
    return arguments.length ? (y0 = typeof _ === "function" ? _ : standalone_src_constant(+_), y1 = null, area) : y0;
  };

  area.y0 = function(_) {
    return arguments.length ? (y0 = typeof _ === "function" ? _ : standalone_src_constant(+_), area) : y0;
  };

  area.y1 = function(_) {
    return arguments.length ? (y1 = _ == null ? null : typeof _ === "function" ? _ : standalone_src_constant(+_), area) : y1;
  };

  area.lineX0 =
  area.lineY0 = function() {
    return arealine().x(x0).y(y0);
  };

  area.lineY1 = function() {
    return arealine().x(x0).y(y1);
  };

  area.lineX1 = function() {
    return arealine().x(x1).y(y0);
  };

  area.defined = function(_) {
    return arguments.length ? (defined = typeof _ === "function" ? _ : standalone_src_constant(!!_), area) : defined;
  };

  area.curve = function(_) {
    return arguments.length ? (curve = _, context != null && (output = curve(context)), area) : curve;
  };

  area.context = function(_) {
    return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area) : context;
  };

  return area;
}

;// ../../node_modules/d3-shape/src/symbol/asterisk.js


const standalone_sqrt3 = standalone_sqrt(3);

/* harmony default export */ const standalone_asterisk = ({
  draw(context, size) {
    const r = standalone_sqrt(size + standalone_math_min(size / 28, 0.75)) * 0.59436;
    const t = r / 2;
    const u = t * standalone_sqrt3;
    context.moveTo(0, r);
    context.lineTo(0, -r);
    context.moveTo(-u, -t);
    context.lineTo(u, t);
    context.moveTo(-u, t);
    context.lineTo(u, -t);
  }
});

;// ../../node_modules/d3-shape/src/symbol/circle.js


/* harmony default export */ const standalone_circle = ({
  draw(context, size) {
    const r = standalone_sqrt(size / standalone_pi);
    context.moveTo(r, 0);
    context.arc(0, 0, r, 0, standalone_tau);
  }
});

;// ../../node_modules/d3-shape/src/symbol/cross.js


/* harmony default export */ const standalone_symbol_cross = ({
  draw(context, size) {
    const r = standalone_sqrt(size / 5) / 2;
    context.moveTo(-3 * r, -r);
    context.lineTo(-r, -r);
    context.lineTo(-r, -3 * r);
    context.lineTo(r, -3 * r);
    context.lineTo(r, -r);
    context.lineTo(3 * r, -r);
    context.lineTo(3 * r, r);
    context.lineTo(r, r);
    context.lineTo(r, 3 * r);
    context.lineTo(-r, 3 * r);
    context.lineTo(-r, r);
    context.lineTo(-3 * r, r);
    context.closePath();
  }
});

;// ../../node_modules/d3-shape/src/symbol/diamond.js


const standalone_tan30 = standalone_sqrt(1 / 3);
const standalone_tan30_2 = standalone_tan30 * 2;

/* harmony default export */ const standalone_diamond = ({
  draw(context, size) {
    const y = standalone_sqrt(size / standalone_tan30_2);
    const x = y * standalone_tan30;
    context.moveTo(0, -y);
    context.lineTo(x, 0);
    context.lineTo(0, y);
    context.lineTo(-x, 0);
    context.closePath();
  }
});

;// ../../node_modules/d3-shape/src/symbol/diamond2.js


/* harmony default export */ const standalone_diamond2 = ({
  draw(context, size) {
    const r = standalone_sqrt(size) * 0.62625;
    context.moveTo(0, -r);
    context.lineTo(r, 0);
    context.lineTo(0, r);
    context.lineTo(-r, 0);
    context.closePath();
  }
});

;// ../../node_modules/d3-shape/src/symbol/plus.js


/* harmony default export */ const standalone_plus = ({
  draw(context, size) {
    const r = standalone_sqrt(size - standalone_math_min(size / 7, 2)) * 0.87559;
    context.moveTo(-r, 0);
    context.lineTo(r, 0);
    context.moveTo(0, r);
    context.lineTo(0, -r);
  }
});

;// ../../node_modules/d3-shape/src/symbol/square.js


/* harmony default export */ const standalone_square = ({
  draw(context, size) {
    const w = standalone_sqrt(size);
    const x = -w / 2;
    context.rect(x, x, w, w);
  }
});

;// ../../node_modules/d3-shape/src/symbol/square2.js


/* harmony default export */ const standalone_square2 = ({
  draw(context, size) {
    const r = standalone_sqrt(size) * 0.4431;
    context.moveTo(r, r);
    context.lineTo(r, -r);
    context.lineTo(-r, -r);
    context.lineTo(-r, r);
    context.closePath();
  }
});

;// ../../node_modules/d3-shape/src/symbol/star.js


const standalone_ka = 0.89081309152928522810;
const standalone_kr = standalone_sin(standalone_pi / 10) / standalone_sin(7 * standalone_pi / 10);
const standalone_kx = standalone_sin(standalone_tau / 10) * standalone_kr;
const standalone_ky = -standalone_cos(standalone_tau / 10) * standalone_kr;

/* harmony default export */ const standalone_star = ({
  draw(context, size) {
    const r = standalone_sqrt(size * standalone_ka);
    const x = standalone_kx * r;
    const y = standalone_ky * r;
    context.moveTo(0, -r);
    context.lineTo(x, y);
    for (let i = 1; i < 5; ++i) {
      const a = standalone_tau * i / 5;
      const c = standalone_cos(a);
      const s = standalone_sin(a);
      context.lineTo(s * r, -c * r);
      context.lineTo(c * x - s * y, s * x + c * y);
    }
    context.closePath();
  }
});

;// ../../node_modules/d3-shape/src/symbol/triangle.js


const standalone_triangle_sqrt3 = standalone_sqrt(3);

/* harmony default export */ const standalone_triangle = ({
  draw(context, size) {
    const y = -standalone_sqrt(size / (standalone_triangle_sqrt3 * 3));
    context.moveTo(0, y * 2);
    context.lineTo(-standalone_triangle_sqrt3 * y, -y);
    context.lineTo(standalone_triangle_sqrt3 * y, -y);
    context.closePath();
  }
});

;// ../../node_modules/d3-shape/src/symbol/triangle2.js


const standalone_triangle2_sqrt3 = standalone_sqrt(3);

/* harmony default export */ const standalone_triangle2 = ({
  draw(context, size) {
    const s = standalone_sqrt(size) * 0.6824;
    const t = s  / 2;
    const u = (s * standalone_triangle2_sqrt3) / 2; // cos(Math.PI / 6)
    context.moveTo(0, -s);
    context.lineTo(u, t);
    context.lineTo(-u, t);
    context.closePath();
  }
});

;// ../../node_modules/d3-shape/src/symbol/wye.js


const standalone_c = -0.5;
const standalone_s = standalone_sqrt(3) / 2;
const standalone_k = 1 / standalone_sqrt(12);
const standalone_a = (standalone_k / 2 + 1) * 3;

/* harmony default export */ const standalone_wye = ({
  draw(context, size) {
    const r = standalone_sqrt(size / standalone_a);
    const x0 = r / 2, y0 = r * standalone_k;
    const x1 = x0, y1 = r * standalone_k + r;
    const x2 = -x1, y2 = y1;
    context.moveTo(x0, y0);
    context.lineTo(x1, y1);
    context.lineTo(x2, y2);
    context.lineTo(standalone_c * x0 - standalone_s * y0, standalone_s * x0 + standalone_c * y0);
    context.lineTo(standalone_c * x1 - standalone_s * y1, standalone_s * x1 + standalone_c * y1);
    context.lineTo(standalone_c * x2 - standalone_s * y2, standalone_s * x2 + standalone_c * y2);
    context.lineTo(standalone_c * x0 + standalone_s * y0, standalone_c * y0 - standalone_s * x0);
    context.lineTo(standalone_c * x1 + standalone_s * y1, standalone_c * y1 - standalone_s * x1);
    context.lineTo(standalone_c * x2 + standalone_s * y2, standalone_c * y2 - standalone_s * x2);
    context.closePath();
  }
});

;// ../../node_modules/d3-shape/src/symbol/times.js


/* harmony default export */ const standalone_times = ({
  draw(context, size) {
    const r = standalone_sqrt(size - standalone_math_min(size / 6, 1.7)) * 0.6189;
    context.moveTo(-r, -r);
    context.lineTo(r, r);
    context.moveTo(-r, r);
    context.lineTo(r, -r);
  }
});

;// ../../node_modules/d3-shape/src/symbol.js
















// These symbols are designed to be filled.
const standalone_symbolsFill = [
  standalone_circle,
  standalone_symbol_cross,
  standalone_diamond,
  standalone_square,
  standalone_star,
  standalone_triangle,
  standalone_wye
];

// These symbols are designed to be stroked (with a width of 1.5px and round caps).
const standalone_symbolsStroke = [
  standalone_circle,
  standalone_plus,
  standalone_times,
  standalone_triangle2,
  standalone_asterisk,
  standalone_square2,
  standalone_diamond2
];

function standalone_symbol_Symbol(type, size) {
  let context = null,
      path = standalone_withPath(symbol);

  type = typeof type === "function" ? type : standalone_src_constant(type || standalone_circle);
  size = typeof size === "function" ? size : standalone_src_constant(size === undefined ? 64 : +size);

  function symbol() {
    let buffer;
    if (!context) context = buffer = path();
    type.apply(this, arguments).draw(context, +size.apply(this, arguments));
    if (buffer) return context = null, buffer + "" || null;
  }

  symbol.type = function(_) {
    return arguments.length ? (type = typeof _ === "function" ? _ : standalone_src_constant(_), symbol) : type;
  };

  symbol.size = function(_) {
    return arguments.length ? (size = typeof _ === "function" ? _ : standalone_src_constant(+_), symbol) : size;
  };

  symbol.context = function(_) {
    return arguments.length ? (context = _ == null ? null : _, symbol) : context;
  };

  return symbol;
}

;// ../../node_modules/vega-canvas/build/vega-canvas.browser.module.js
function standalone_domCanvas(w, h) {
  if (typeof document !== 'undefined' && document.createElement) {
    const c = document.createElement('canvas');
    if (c && c.getContext) {
      c.width = w;
      c.height = h;
      return c;
    }
  }
  return null;
}
const standalone_domImage = () => typeof Image !== 'undefined' ? Image : null;



;// ../../node_modules/d3-array/src/bisect.js




const standalone_ascendingBisect = standalone_bisector(standalone_ascending_ascending);
const standalone_bisectRight = standalone_ascendingBisect.right;
const standalone_bisectLeft = standalone_ascendingBisect.left;
const standalone_bisectCenter = standalone_bisector(standalone_number_number).center;
/* harmony default export */ const standalone_bisect = (standalone_bisectRight);

;// ../../node_modules/d3-color/src/define.js
/* harmony default export */ function standalone_src_define(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}

function standalone_define_extend(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key in definition) prototype[key] = definition[key];
  return prototype;
}

;// ../../node_modules/d3-color/src/color.js


function standalone_Color() {}

var standalone_darker = 0.7;
var standalone_brighter = 1 / standalone_darker;

var standalone_reI = "\\s*([+-]?\\d+)\\s*",
    standalone_reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",
    standalone_reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
    standalone_reHex = /^#([0-9a-f]{3,8})$/,
    standalone_reRgbInteger = new RegExp(`^rgb\\(${standalone_reI},${standalone_reI},${standalone_reI}\\)$`),
    standalone_reRgbPercent = new RegExp(`^rgb\\(${standalone_reP},${standalone_reP},${standalone_reP}\\)$`),
    standalone_reRgbaInteger = new RegExp(`^rgba\\(${standalone_reI},${standalone_reI},${standalone_reI},${standalone_reN}\\)$`),
    standalone_reRgbaPercent = new RegExp(`^rgba\\(${standalone_reP},${standalone_reP},${standalone_reP},${standalone_reN}\\)$`),
    standalone_reHslPercent = new RegExp(`^hsl\\(${standalone_reN},${standalone_reP},${standalone_reP}\\)$`),
    standalone_reHslaPercent = new RegExp(`^hsla\\(${standalone_reN},${standalone_reP},${standalone_reP},${standalone_reN}\\)$`);

var standalone_named = {
  aliceblue: 0xf0f8ff,
  antiquewhite: 0xfaebd7,
  aqua: 0x00ffff,
  aquamarine: 0x7fffd4,
  azure: 0xf0ffff,
  beige: 0xf5f5dc,
  bisque: 0xffe4c4,
  black: 0x000000,
  blanchedalmond: 0xffebcd,
  blue: 0x0000ff,
  blueviolet: 0x8a2be2,
  brown: 0xa52a2a,
  burlywood: 0xdeb887,
  cadetblue: 0x5f9ea0,
  chartreuse: 0x7fff00,
  chocolate: 0xd2691e,
  coral: 0xff7f50,
  cornflowerblue: 0x6495ed,
  cornsilk: 0xfff8dc,
  crimson: 0xdc143c,
  cyan: 0x00ffff,
  darkblue: 0x00008b,
  darkcyan: 0x008b8b,
  darkgoldenrod: 0xb8860b,
  darkgray: 0xa9a9a9,
  darkgreen: 0x006400,
  darkgrey: 0xa9a9a9,
  darkkhaki: 0xbdb76b,
  darkmagenta: 0x8b008b,
  darkolivegreen: 0x556b2f,
  darkorange: 0xff8c00,
  darkorchid: 0x9932cc,
  darkred: 0x8b0000,
  darksalmon: 0xe9967a,
  darkseagreen: 0x8fbc8f,
  darkslateblue: 0x483d8b,
  darkslategray: 0x2f4f4f,
  darkslategrey: 0x2f4f4f,
  darkturquoise: 0x00ced1,
  darkviolet: 0x9400d3,
  deeppink: 0xff1493,
  deepskyblue: 0x00bfff,
  dimgray: 0x696969,
  dimgrey: 0x696969,
  dodgerblue: 0x1e90ff,
  firebrick: 0xb22222,
  floralwhite: 0xfffaf0,
  forestgreen: 0x228b22,
  fuchsia: 0xff00ff,
  gainsboro: 0xdcdcdc,
  ghostwhite: 0xf8f8ff,
  gold: 0xffd700,
  goldenrod: 0xdaa520,
  gray: 0x808080,
  green: 0x008000,
  greenyellow: 0xadff2f,
  grey: 0x808080,
  honeydew: 0xf0fff0,
  hotpink: 0xff69b4,
  indianred: 0xcd5c5c,
  indigo: 0x4b0082,
  ivory: 0xfffff0,
  khaki: 0xf0e68c,
  lavender: 0xe6e6fa,
  lavenderblush: 0xfff0f5,
  lawngreen: 0x7cfc00,
  lemonchiffon: 0xfffacd,
  lightblue: 0xadd8e6,
  lightcoral: 0xf08080,
  lightcyan: 0xe0ffff,
  lightgoldenrodyellow: 0xfafad2,
  lightgray: 0xd3d3d3,
  lightgreen: 0x90ee90,
  lightgrey: 0xd3d3d3,
  lightpink: 0xffb6c1,
  lightsalmon: 0xffa07a,
  lightseagreen: 0x20b2aa,
  lightskyblue: 0x87cefa,
  lightslategray: 0x778899,
  lightslategrey: 0x778899,
  lightsteelblue: 0xb0c4de,
  lightyellow: 0xffffe0,
  lime: 0x00ff00,
  limegreen: 0x32cd32,
  linen: 0xfaf0e6,
  magenta: 0xff00ff,
  maroon: 0x800000,
  mediumaquamarine: 0x66cdaa,
  mediumblue: 0x0000cd,
  mediumorchid: 0xba55d3,
  mediumpurple: 0x9370db,
  mediumseagreen: 0x3cb371,
  mediumslateblue: 0x7b68ee,
  mediumspringgreen: 0x00fa9a,
  mediumturquoise: 0x48d1cc,
  mediumvioletred: 0xc71585,
  midnightblue: 0x191970,
  mintcream: 0xf5fffa,
  mistyrose: 0xffe4e1,
  moccasin: 0xffe4b5,
  navajowhite: 0xffdead,
  navy: 0x000080,
  oldlace: 0xfdf5e6,
  olive: 0x808000,
  olivedrab: 0x6b8e23,
  orange: 0xffa500,
  orangered: 0xff4500,
  orchid: 0xda70d6,
  palegoldenrod: 0xeee8aa,
  palegreen: 0x98fb98,
  paleturquoise: 0xafeeee,
  palevioletred: 0xdb7093,
  papayawhip: 0xffefd5,
  peachpuff: 0xffdab9,
  peru: 0xcd853f,
  pink: 0xffc0cb,
  plum: 0xdda0dd,
  powderblue: 0xb0e0e6,
  purple: 0x800080,
  rebeccapurple: 0x663399,
  red: 0xff0000,
  rosybrown: 0xbc8f8f,
  royalblue: 0x4169e1,
  saddlebrown: 0x8b4513,
  salmon: 0xfa8072,
  sandybrown: 0xf4a460,
  seagreen: 0x2e8b57,
  seashell: 0xfff5ee,
  sienna: 0xa0522d,
  silver: 0xc0c0c0,
  skyblue: 0x87ceeb,
  slateblue: 0x6a5acd,
  slategray: 0x708090,
  slategrey: 0x708090,
  snow: 0xfffafa,
  springgreen: 0x00ff7f,
  steelblue: 0x4682b4,
  tan: 0xd2b48c,
  teal: 0x008080,
  thistle: 0xd8bfd8,
  tomato: 0xff6347,
  turquoise: 0x40e0d0,
  violet: 0xee82ee,
  wheat: 0xf5deb3,
  white: 0xffffff,
  whitesmoke: 0xf5f5f5,
  yellow: 0xffff00,
  yellowgreen: 0x9acd32
};

standalone_src_define(standalone_Color, standalone_color, {
  copy(channels) {
    return Object.assign(new this.constructor, this, channels);
  },
  displayable() {
    return this.rgb().displayable();
  },
  hex: standalone_color_formatHex, // Deprecated! Use color.formatHex.
  formatHex: standalone_color_formatHex,
  formatHex8: standalone_color_formatHex8,
  formatHsl: standalone_color_formatHsl,
  formatRgb: standalone_color_formatRgb,
  toString: standalone_color_formatRgb
});

function standalone_color_formatHex() {
  return this.rgb().formatHex();
}

function standalone_color_formatHex8() {
  return this.rgb().formatHex8();
}

function standalone_color_formatHsl() {
  return standalone_hslConvert(this).formatHsl();
}

function standalone_color_formatRgb() {
  return this.rgb().formatRgb();
}

function standalone_color(format) {
  var m, l;
  format = (format + "").trim().toLowerCase();
  return (m = standalone_reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? standalone_rgbn(m) // #ff0000
      : l === 3 ? new standalone_Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00
      : l === 8 ? standalone_rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
      : l === 4 ? standalone_rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000
      : null) // invalid hex
      : (m = standalone_reRgbInteger.exec(format)) ? new standalone_Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
      : (m = standalone_reRgbPercent.exec(format)) ? new standalone_Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
      : (m = standalone_reRgbaInteger.exec(format)) ? standalone_rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
      : (m = standalone_reRgbaPercent.exec(format)) ? standalone_rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
      : (m = standalone_reHslPercent.exec(format)) ? standalone_hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
      : (m = standalone_reHslaPercent.exec(format)) ? standalone_hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
      : standalone_named.hasOwnProperty(format) ? standalone_rgbn(standalone_named[format]) // eslint-disable-line no-prototype-builtins
      : format === "transparent" ? new standalone_Rgb(NaN, NaN, NaN, 0)
      : null;
}

function standalone_rgbn(n) {
  return new standalone_Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
}

function standalone_rgba(r, g, b, a) {
  if (a <= 0) r = g = b = NaN;
  return new standalone_Rgb(r, g, b, a);
}

function standalone_rgbConvert(o) {
  if (!(o instanceof standalone_Color)) o = standalone_color(o);
  if (!o) return new standalone_Rgb;
  o = o.rgb();
  return new standalone_Rgb(o.r, o.g, o.b, o.opacity);
}

function standalone_color_rgb(r, g, b, opacity) {
  return arguments.length === 1 ? standalone_rgbConvert(r) : new standalone_Rgb(r, g, b, opacity == null ? 1 : opacity);
}

function standalone_Rgb(r, g, b, opacity) {
  this.r = +r;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}

standalone_src_define(standalone_Rgb, standalone_color_rgb, standalone_define_extend(standalone_Color, {
  brighter(k) {
    k = k == null ? standalone_brighter : Math.pow(standalone_brighter, k);
    return new standalone_Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker(k) {
    k = k == null ? standalone_darker : Math.pow(standalone_darker, k);
    return new standalone_Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb() {
    return this;
  },
  clamp() {
    return new standalone_Rgb(standalone_clampi(this.r), standalone_clampi(this.g), standalone_clampi(this.b), standalone_clampa(this.opacity));
  },
  displayable() {
    return (-0.5 <= this.r && this.r < 255.5)
        && (-0.5 <= this.g && this.g < 255.5)
        && (-0.5 <= this.b && this.b < 255.5)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: standalone_rgb_formatHex, // Deprecated! Use color.formatHex.
  formatHex: standalone_rgb_formatHex,
  formatHex8: standalone_rgb_formatHex8,
  formatRgb: standalone_rgb_formatRgb,
  toString: standalone_rgb_formatRgb
}));

function standalone_rgb_formatHex() {
  return `#${standalone_hex(this.r)}${standalone_hex(this.g)}${standalone_hex(this.b)}`;
}

function standalone_rgb_formatHex8() {
  return `#${standalone_hex(this.r)}${standalone_hex(this.g)}${standalone_hex(this.b)}${standalone_hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
}

function standalone_rgb_formatRgb() {
  const a = standalone_clampa(this.opacity);
  return `${a === 1 ? "rgb(" : "rgba("}${standalone_clampi(this.r)}, ${standalone_clampi(this.g)}, ${standalone_clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
}

function standalone_clampa(opacity) {
  return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
}

function standalone_clampi(value) {
  return Math.max(0, Math.min(255, Math.round(value) || 0));
}

function standalone_hex(value) {
  value = standalone_clampi(value);
  return (value < 16 ? "0" : "") + value.toString(16);
}

function standalone_hsla(h, s, l, a) {
  if (a <= 0) h = s = l = NaN;
  else if (l <= 0 || l >= 1) h = s = NaN;
  else if (s <= 0) h = NaN;
  return new standalone_Hsl(h, s, l, a);
}

function standalone_hslConvert(o) {
  if (o instanceof standalone_Hsl) return new standalone_Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof standalone_Color)) o = standalone_color(o);
  if (!o) return new standalone_Hsl;
  if (o instanceof standalone_Hsl) return o;
  o = o.rgb();
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      min = Math.min(r, g, b),
      max = Math.max(r, g, b),
      h = NaN,
      s = max - min,
      l = (max + min) / 2;
  if (s) {
    if (r === max) h = (g - b) / s + (g < b) * 6;
    else if (g === max) h = (b - r) / s + 2;
    else h = (r - g) / s + 4;
    s /= l < 0.5 ? max + min : 2 - max - min;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new standalone_Hsl(h, s, l, o.opacity);
}

function standalone_hsl(h, s, l, opacity) {
  return arguments.length === 1 ? standalone_hslConvert(h) : new standalone_Hsl(h, s, l, opacity == null ? 1 : opacity);
}

function standalone_Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

standalone_src_define(standalone_Hsl, standalone_hsl, standalone_define_extend(standalone_Color, {
  brighter(k) {
    k = k == null ? standalone_brighter : Math.pow(standalone_brighter, k);
    return new standalone_Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker(k) {
    k = k == null ? standalone_darker : Math.pow(standalone_darker, k);
    return new standalone_Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb() {
    var h = this.h % 360 + (this.h < 0) * 360,
        s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
        l = this.l,
        m2 = l + (l < 0.5 ? l : 1 - l) * s,
        m1 = 2 * l - m2;
    return new standalone_Rgb(
      standalone_hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      standalone_hsl2rgb(h, m1, m2),
      standalone_hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  clamp() {
    return new standalone_Hsl(standalone_clamph(this.h), standalone_clampt(this.s), standalone_clampt(this.l), standalone_clampa(this.opacity));
  },
  displayable() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s))
        && (0 <= this.l && this.l <= 1)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  formatHsl() {
    const a = standalone_clampa(this.opacity);
    return `${a === 1 ? "hsl(" : "hsla("}${standalone_clamph(this.h)}, ${standalone_clampt(this.s) * 100}%, ${standalone_clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
  }
}));

function standalone_clamph(value) {
  value = (value || 0) % 360;
  return value < 0 ? value + 360 : value;
}

function standalone_clampt(value) {
  return Math.max(0, Math.min(1, value || 0));
}

/* From FvD 13.37, CSS Color Module Level 3 */
function standalone_hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60
      : h < 180 ? m2
      : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
      : m1) * 255;
}

;// ../../node_modules/d3-interpolate/src/basis.js
function standalone_basis_basis(t1, v0, v1, v2, v3) {
  var t2 = t1 * t1, t3 = t2 * t1;
  return ((1 - 3 * t1 + 3 * t2 - t3) * v0
      + (4 - 6 * t2 + 3 * t3) * v1
      + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
      + t3 * v3) / 6;
}

/* harmony default export */ function standalone_src_basis(values) {
  var n = values.length - 1;
  return function(t) {
    var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),
        v1 = values[i],
        v2 = values[i + 1],
        v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,
        v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
    return standalone_basis_basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

;// ../../node_modules/d3-interpolate/src/basisClosed.js


/* harmony default export */ function standalone_src_basisClosed(values) {
  var n = values.length;
  return function(t) {
    var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),
        v0 = values[(i + n - 1) % n],
        v1 = values[i % n],
        v2 = values[(i + 1) % n],
        v3 = values[(i + 2) % n];
    return standalone_basis_basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

;// ../../node_modules/d3-interpolate/src/constant.js
/* harmony default export */ const standalone_d3_interpolate_src_constant = (x => () => x);

;// ../../node_modules/d3-interpolate/src/color.js


function standalone_color_linear(a, d) {
  return function(t) {
    return a + t * d;
  };
}

function standalone_exponential(a, b, y) {
  return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
    return Math.pow(a + t * b, y);
  };
}

function standalone_hue(a, b) {
  var d = b - a;
  return d ? standalone_color_linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : standalone_d3_interpolate_src_constant(isNaN(a) ? b : a);
}

function standalone_gamma(y) {
  return (y = +y) === 1 ? standalone_nogamma : function(a, b) {
    return b - a ? standalone_exponential(a, b, y) : standalone_d3_interpolate_src_constant(isNaN(a) ? b : a);
  };
}

function standalone_nogamma(a, b) {
  var d = b - a;
  return d ? standalone_color_linear(a, d) : standalone_d3_interpolate_src_constant(isNaN(a) ? b : a);
}

;// ../../node_modules/d3-interpolate/src/rgb.js





/* harmony default export */ const standalone_rgb = ((function rgbGamma(y) {
  var color = standalone_gamma(y);

  function rgb(start, end) {
    var r = color((start = standalone_color_rgb(start)).r, (end = standalone_color_rgb(end)).r),
        g = color(start.g, end.g),
        b = color(start.b, end.b),
        opacity = standalone_nogamma(start.opacity, end.opacity);
    return function(t) {
      start.r = r(t);
      start.g = g(t);
      start.b = b(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }

  rgb.gamma = rgbGamma;

  return rgb;
})(1));

function standalone_rgbSpline(spline) {
  return function(colors) {
    var n = colors.length,
        r = new Array(n),
        g = new Array(n),
        b = new Array(n),
        i, color;
    for (i = 0; i < n; ++i) {
      color = standalone_color_rgb(colors[i]);
      r[i] = color.r || 0;
      g[i] = color.g || 0;
      b[i] = color.b || 0;
    }
    r = spline(r);
    g = spline(g);
    b = spline(b);
    color.opacity = 1;
    return function(t) {
      color.r = r(t);
      color.g = g(t);
      color.b = b(t);
      return color + "";
    };
  };
}

var standalone_rgbBasis = standalone_rgbSpline(standalone_src_basis);
var standalone_rgbBasisClosed = standalone_rgbSpline(standalone_src_basisClosed);

;// ../../node_modules/d3-interpolate/src/numberArray.js
/* harmony default export */ function standalone_numberArray(a, b) {
  if (!b) b = [];
  var n = a ? Math.min(b.length, a.length) : 0,
      c = b.slice(),
      i;
  return function(t) {
    for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;
    return c;
  };
}

function standalone_isNumberArray(x) {
  return ArrayBuffer.isView(x) && !(x instanceof DataView);
}

;// ../../node_modules/d3-interpolate/src/array.js



/* harmony default export */ function standalone_d3_interpolate_src_array(a, b) {
  return (standalone_isNumberArray(b) ? standalone_numberArray : standalone_genericArray)(a, b);
}

function standalone_genericArray(a, b) {
  var nb = b ? b.length : 0,
      na = a ? Math.min(nb, a.length) : 0,
      x = new Array(na),
      c = new Array(nb),
      i;

  for (i = 0; i < na; ++i) x[i] = standalone_value(a[i], b[i]);
  for (; i < nb; ++i) c[i] = b[i];

  return function(t) {
    for (i = 0; i < na; ++i) c[i] = x[i](t);
    return c;
  };
}

;// ../../node_modules/d3-interpolate/src/date.js
/* harmony default export */ function standalone_date(a, b) {
  var d = new Date;
  return a = +a, b = +b, function(t) {
    return d.setTime(a * (1 - t) + b * t), d;
  };
}

;// ../../node_modules/d3-interpolate/src/number.js
/* harmony default export */ function standalone_src_number(a, b) {
  return a = +a, b = +b, function(t) {
    return a * (1 - t) + b * t;
  };
}

;// ../../node_modules/d3-interpolate/src/object.js


/* harmony default export */ function standalone_src_object(a, b) {
  var i = {},
      c = {},
      k;

  if (a === null || typeof a !== "object") a = {};
  if (b === null || typeof b !== "object") b = {};

  for (k in b) {
    if (k in a) {
      i[k] = standalone_value(a[k], b[k]);
    } else {
      c[k] = b[k];
    }
  }

  return function(t) {
    for (k in i) c[k] = i[k](t);
    return c;
  };
}

;// ../../node_modules/d3-interpolate/src/string.js


var standalone_reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,
    standalone_reB = new RegExp(standalone_reA.source, "g");

function standalone_string_zero(b) {
  return function() {
    return b;
  };
}

function standalone_string_one(b) {
  return function(t) {
    return b(t) + "";
  };
}

/* harmony default export */ function standalone_string(a, b) {
  var bi = standalone_reA.lastIndex = standalone_reB.lastIndex = 0, // scan index for next number in b
      am, // current match in a
      bm, // current match in b
      bs, // string preceding current number in b, if any
      i = -1, // index in s
      s = [], // string constants and placeholders
      q = []; // number interpolators

  // Coerce inputs to strings.
  a = a + "", b = b + "";

  // Interpolate pairs of numbers in a & b.
  while ((am = standalone_reA.exec(a))
      && (bm = standalone_reB.exec(b))) {
    if ((bs = bm.index) > bi) { // a string precedes the next number in b
      bs = b.slice(bi, bs);
      if (s[i]) s[i] += bs; // coalesce with previous string
      else s[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
      if (s[i]) s[i] += bm; // coalesce with previous string
      else s[++i] = bm;
    } else { // interpolate non-matching numbers
      s[++i] = null;
      q.push({i: i, x: standalone_src_number(am, bm)});
    }
    bi = standalone_reB.lastIndex;
  }

  // Add remains of b.
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s[i]) s[i] += bs; // coalesce with previous string
    else s[++i] = bs;
  }

  // Special optimization for only a single match.
  // Otherwise, interpolate each of the numbers and rejoin the string.
  return s.length < 2 ? (q[0]
      ? standalone_string_one(q[0].x)
      : standalone_string_zero(b))
      : (b = q.length, function(t) {
          for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
          return s.join("");
        });
}

;// ../../node_modules/d3-interpolate/src/value.js










/* harmony default export */ function standalone_value(a, b) {
  var t = typeof b, c;
  return b == null || t === "boolean" ? standalone_d3_interpolate_src_constant(b)
      : (t === "number" ? standalone_src_number
      : t === "string" ? ((c = standalone_color(b)) ? (b = c, standalone_rgb) : standalone_string)
      : b instanceof standalone_color ? standalone_rgb
      : b instanceof Date ? standalone_date
      : standalone_isNumberArray(b) ? standalone_numberArray
      : Array.isArray(b) ? standalone_genericArray
      : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? standalone_src_object
      : standalone_src_number)(a, b);
}

;// ../../node_modules/d3-interpolate/src/round.js
/* harmony default export */ function standalone_src_round(a, b) {
  return a = +a, b = +b, function(t) {
    return Math.round(a * (1 - t) + b * t);
  };
}

;// ../../node_modules/d3-scale/src/constant.js
function standalone_constants(x) {
  return function() {
    return x;
  };
}

;// ../../node_modules/d3-scale/src/number.js
function standalone_src_number_number(x) {
  return +x;
}

;// ../../node_modules/d3-scale/src/continuous.js





var standalone_unit = [0, 1];

function standalone_continuous_identity(x) {
  return x;
}

function standalone_normalize(a, b) {
  return (b -= (a = +a))
      ? function(x) { return (x - a) / b; }
      : standalone_constants(isNaN(b) ? NaN : 0.5);
}

function standalone_clamper(a, b) {
  var t;
  if (a > b) t = a, a = b, b = t;
  return function(x) { return Math.max(a, Math.min(b, x)); };
}

// normalize(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].
// interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value x in [a,b].
function standalone_bimap(domain, range, interpolate) {
  var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];
  if (d1 < d0) d0 = standalone_normalize(d1, d0), r0 = interpolate(r1, r0);
  else d0 = standalone_normalize(d0, d1), r0 = interpolate(r0, r1);
  return function(x) { return r0(d0(x)); };
}

function standalone_polymap(domain, range, interpolate) {
  var j = Math.min(domain.length, range.length) - 1,
      d = new Array(j),
      r = new Array(j),
      i = -1;

  // Reverse descending domains.
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range = range.slice().reverse();
  }

  while (++i < j) {
    d[i] = standalone_normalize(domain[i], domain[i + 1]);
    r[i] = interpolate(range[i], range[i + 1]);
  }

  return function(x) {
    var i = standalone_bisect(domain, x, 1, j) - 1;
    return r[i](d[i](x));
  };
}

function standalone_copy(source, target) {
  return target
      .domain(source.domain())
      .range(source.range())
      .interpolate(source.interpolate())
      .clamp(source.clamp())
      .unknown(source.unknown());
}

function standalone_transformer() {
  var domain = standalone_unit,
      range = standalone_unit,
      interpolate = standalone_value,
      transform,
      untransform,
      unknown,
      clamp = standalone_continuous_identity,
      piecewise,
      output,
      input;

  function rescale() {
    var n = Math.min(domain.length, range.length);
    if (clamp !== standalone_continuous_identity) clamp = standalone_clamper(domain[0], domain[n - 1]);
    piecewise = n > 2 ? standalone_polymap : standalone_bimap;
    output = input = null;
    return scale;
  }

  function scale(x) {
    return x == null || isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range, interpolate)))(transform(clamp(x)));
  }

  scale.invert = function(y) {
    return clamp(untransform((input || (input = piecewise(range, domain.map(transform), standalone_src_number)))(y)));
  };

  scale.domain = function(_) {
    return arguments.length ? (domain = Array.from(_, standalone_src_number_number), rescale()) : domain.slice();
  };

  scale.range = function(_) {
    return arguments.length ? (range = Array.from(_), rescale()) : range.slice();
  };

  scale.rangeRound = function(_) {
    return range = Array.from(_), interpolate = standalone_src_round, rescale();
  };

  scale.clamp = function(_) {
    return arguments.length ? (clamp = _ ? true : standalone_continuous_identity, rescale()) : clamp !== standalone_continuous_identity;
  };

  scale.interpolate = function(_) {
    return arguments.length ? (interpolate = _, rescale()) : interpolate;
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  return function(t, u) {
    transform = t, untransform = u;
    return rescale();
  };
}

function standalone_continuous() {
  return standalone_transformer()(standalone_continuous_identity, standalone_continuous_identity);
}

;// ../../node_modules/d3-scale/src/init.js
function standalone_initRange(domain, range) {
  switch (arguments.length) {
    case 0: break;
    case 1: this.range(domain); break;
    default: this.range(range).domain(domain); break;
  }
  return this;
}

function standalone_initInterpolator(domain, interpolator) {
  switch (arguments.length) {
    case 0: break;
    case 1: {
      if (typeof domain === "function") this.interpolator(domain);
      else this.range(domain);
      break;
    }
    default: {
      this.domain(domain);
      if (typeof interpolator === "function") this.interpolator(interpolator);
      else this.range(interpolator);
      break;
    }
  }
  return this;
}

;// ../../node_modules/d3-scale/src/tickFormat.js



function standalone_tickFormat(start, stop, count, specifier) {
  var step = standalone_tickStep(start, stop, count),
      precision;
  specifier = standalone_formatSpecifier(specifier == null ? ",f" : specifier);
  switch (specifier.type) {
    case "s": {
      var value = Math.max(Math.abs(start), Math.abs(stop));
      if (specifier.precision == null && !isNaN(precision = standalone_precisionPrefix(step, value))) specifier.precision = precision;
      return standalone_formatPrefix(specifier, value);
    }
    case "":
    case "e":
    case "g":
    case "p":
    case "r": {
      if (specifier.precision == null && !isNaN(precision = standalone_precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e");
      break;
    }
    case "f":
    case "%": {
      if (specifier.precision == null && !isNaN(precision = standalone_precisionFixed(step))) specifier.precision = precision - (specifier.type === "%") * 2;
      break;
    }
  }
  return standalone_format(specifier);
}

;// ../../node_modules/d3-scale/src/linear.js





function standalone_linearish(scale) {
  var domain = scale.domain;

  scale.ticks = function(count) {
    var d = domain();
    return standalone_ticks(d[0], d[d.length - 1], count == null ? 10 : count);
  };

  scale.tickFormat = function(count, specifier) {
    var d = domain();
    return standalone_tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);
  };

  scale.nice = function(count) {
    if (count == null) count = 10;

    var d = domain();
    var i0 = 0;
    var i1 = d.length - 1;
    var start = d[i0];
    var stop = d[i1];
    var prestep;
    var step;
    var maxIter = 10;

    if (stop < start) {
      step = start, start = stop, stop = step;
      step = i0, i0 = i1, i1 = step;
    }
    
    while (maxIter-- > 0) {
      step = standalone_tickIncrement(start, stop, count);
      if (step === prestep) {
        d[i0] = start
        d[i1] = stop
        return domain(d);
      } else if (step > 0) {
        start = Math.floor(start / step) * step;
        stop = Math.ceil(stop / step) * step;
      } else if (step < 0) {
        start = Math.ceil(start * step) / step;
        stop = Math.floor(stop * step) / step;
      } else {
        break;
      }
      prestep = step;
    }

    return scale;
  };

  return scale;
}

function standalone_linear_linear() {
  var scale = standalone_continuous();

  scale.copy = function() {
    return standalone_copy(scale, standalone_linear_linear());
  };

  standalone_initRange.apply(scale, arguments);

  return standalone_linearish(scale);
}

;// ../../node_modules/d3-scale/src/identity.js



function standalone_identity_identity(domain) {
  var unknown;

  function scale(x) {
    return x == null || isNaN(x = +x) ? unknown : x;
  }

  scale.invert = scale;

  scale.domain = scale.range = function(_) {
    return arguments.length ? (domain = Array.from(_, standalone_src_number_number), scale) : domain.slice();
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  scale.copy = function() {
    return standalone_identity_identity(domain).unknown(unknown);
  };

  domain = arguments.length ? Array.from(domain, standalone_src_number_number) : [0, 1];

  return standalone_linearish(scale);
}

;// ../../node_modules/d3-scale/src/nice.js
function standalone_nice(domain, interval) {
  domain = domain.slice();

  var i0 = 0,
      i1 = domain.length - 1,
      x0 = domain[i0],
      x1 = domain[i1],
      t;

  if (x1 < x0) {
    t = i0, i0 = i1, i1 = t;
    t = x0, x0 = x1, x1 = t;
  }

  domain[i0] = interval.floor(x0);
  domain[i1] = interval.ceil(x1);
  return domain;
}

;// ../../node_modules/d3-scale/src/log.js






function standalone_transformLog(x) {
  return Math.log(x);
}

function standalone_transformExp(x) {
  return Math.exp(x);
}

function standalone_transformLogn(x) {
  return -Math.log(-x);
}

function standalone_transformExpn(x) {
  return -Math.exp(-x);
}

function standalone_pow10(x) {
  return isFinite(x) ? +("1e" + x) : x < 0 ? 0 : x;
}

function standalone_powp(base) {
  return base === 10 ? standalone_pow10
      : base === Math.E ? Math.exp
      : x => Math.pow(base, x);
}

function standalone_logp(base) {
  return base === Math.E ? Math.log
      : base === 10 && Math.log10
      || base === 2 && Math.log2
      || (base = Math.log(base), x => Math.log(x) / base);
}

function standalone_reflect(f) {
  return (x, k) => -f(-x, k);
}

function standalone_loggish(transform) {
  const scale = transform(standalone_transformLog, standalone_transformExp);
  const domain = scale.domain;
  let base = 10;
  let logs;
  let pows;

  function rescale() {
    logs = standalone_logp(base), pows = standalone_powp(base);
    if (domain()[0] < 0) {
      logs = standalone_reflect(logs), pows = standalone_reflect(pows);
      transform(standalone_transformLogn, standalone_transformExpn);
    } else {
      transform(standalone_transformLog, standalone_transformExp);
    }
    return scale;
  }

  scale.base = function(_) {
    return arguments.length ? (base = +_, rescale()) : base;
  };

  scale.domain = function(_) {
    return arguments.length ? (domain(_), rescale()) : domain();
  };

  scale.ticks = count => {
    const d = domain();
    let u = d[0];
    let v = d[d.length - 1];
    const r = v < u;

    if (r) ([u, v] = [v, u]);

    let i = logs(u);
    let j = logs(v);
    let k;
    let t;
    const n = count == null ? 10 : +count;
    let z = [];

    if (!(base % 1) && j - i < n) {
      i = Math.floor(i), j = Math.ceil(j);
      if (u > 0) for (; i <= j; ++i) {
        for (k = 1; k < base; ++k) {
          t = i < 0 ? k / pows(-i) : k * pows(i);
          if (t < u) continue;
          if (t > v) break;
          z.push(t);
        }
      } else for (; i <= j; ++i) {
        for (k = base - 1; k >= 1; --k) {
          t = i > 0 ? k / pows(-i) : k * pows(i);
          if (t < u) continue;
          if (t > v) break;
          z.push(t);
        }
      }
      if (z.length * 2 < n) z = standalone_ticks(u, v, n);
    } else {
      z = standalone_ticks(i, j, Math.min(j - i, n)).map(pows);
    }
    return r ? z.reverse() : z;
  };

  scale.tickFormat = (count, specifier) => {
    if (count == null) count = 10;
    if (specifier == null) specifier = base === 10 ? "s" : ",";
    if (typeof specifier !== "function") {
      if (!(base % 1) && (specifier = standalone_formatSpecifier(specifier)).precision == null) specifier.trim = true;
      specifier = standalone_format(specifier);
    }
    if (count === Infinity) return specifier;
    const k = Math.max(1, base * count / scale.ticks().length); // TODO fast estimate?
    return d => {
      let i = d / pows(Math.round(logs(d)));
      if (i * base < base - 0.5) i *= base;
      return i <= k ? specifier(d) : "";
    };
  };

  scale.nice = () => {
    return domain(standalone_nice(domain(), {
      floor: x => pows(Math.floor(logs(x))),
      ceil: x => pows(Math.ceil(logs(x)))
    }));
  };

  return scale;
}

function standalone_log_log() {
  const scale = standalone_loggish(standalone_transformer()).domain([1, 10]);
  scale.copy = () => standalone_copy(scale, standalone_log_log()).base(scale.base());
  standalone_initRange.apply(scale, arguments);
  return scale;
}

;// ../../node_modules/d3-scale/src/pow.js




function standalone_transformPow(exponent) {
  return function(x) {
    return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
  };
}

function standalone_transformSqrt(x) {
  return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x);
}

function standalone_transformSquare(x) {
  return x < 0 ? -x * x : x * x;
}

function standalone_powish(transform) {
  var scale = transform(standalone_continuous_identity, standalone_continuous_identity),
      exponent = 1;

  function rescale() {
    return exponent === 1 ? transform(standalone_continuous_identity, standalone_continuous_identity)
        : exponent === 0.5 ? transform(standalone_transformSqrt, standalone_transformSquare)
        : transform(standalone_transformPow(exponent), standalone_transformPow(1 / exponent));
  }

  scale.exponent = function(_) {
    return arguments.length ? (exponent = +_, rescale()) : exponent;
  };

  return standalone_linearish(scale);
}

function standalone_pow_pow() {
  var scale = standalone_powish(standalone_transformer());

  scale.copy = function() {
    return standalone_copy(scale, standalone_pow_pow()).exponent(scale.exponent());
  };

  standalone_initRange.apply(scale, arguments);

  return scale;
}

function standalone_pow_sqrt() {
  return standalone_pow_pow.apply(null, arguments).exponent(0.5);
}

;// ../../node_modules/d3-scale/src/symlog.js




function standalone_transformSymlog(c) {
  return function(x) {
    return Math.sign(x) * Math.log1p(Math.abs(x / c));
  };
}

function standalone_transformSymexp(c) {
  return function(x) {
    return Math.sign(x) * Math.expm1(Math.abs(x)) * c;
  };
}

function standalone_symlogish(transform) {
  var c = 1, scale = transform(standalone_transformSymlog(c), standalone_transformSymexp(c));

  scale.constant = function(_) {
    return arguments.length ? transform(standalone_transformSymlog(c = +_), standalone_transformSymexp(c)) : c;
  };

  return standalone_linearish(scale);
}

function standalone_symlog_symlog() {
  var scale = standalone_symlogish(standalone_transformer());

  scale.copy = function() {
    return standalone_copy(scale, standalone_symlog_symlog()).constant(scale.constant());
  };

  return standalone_initRange.apply(scale, arguments);
}

;// ../../node_modules/d3-time/src/ticks.js











function standalone_ticker(year, month, week, day, hour, minute) {

  const tickIntervals = [
    [standalone_second,  1,      standalone_durationSecond],
    [standalone_second,  5,  5 * standalone_durationSecond],
    [standalone_second, 15, 15 * standalone_durationSecond],
    [standalone_second, 30, 30 * standalone_durationSecond],
    [minute,  1,      standalone_durationMinute],
    [minute,  5,  5 * standalone_durationMinute],
    [minute, 15, 15 * standalone_durationMinute],
    [minute, 30, 30 * standalone_durationMinute],
    [  hour,  1,      standalone_durationHour  ],
    [  hour,  3,  3 * standalone_durationHour  ],
    [  hour,  6,  6 * standalone_durationHour  ],
    [  hour, 12, 12 * standalone_durationHour  ],
    [   day,  1,      standalone_durationDay   ],
    [   day,  2,  2 * standalone_durationDay   ],
    [  week,  1,      standalone_durationWeek  ],
    [ month,  1,      standalone_durationMonth ],
    [ month,  3,  3 * standalone_durationMonth ],
    [  year,  1,      standalone_durationYear  ]
  ];

  function ticks(start, stop, count) {
    const reverse = stop < start;
    if (reverse) [start, stop] = [stop, start];
    const interval = count && typeof count.range === "function" ? count : tickInterval(start, stop, count);
    const ticks = interval ? interval.range(start, +stop + 1) : []; // inclusive stop
    return reverse ? ticks.reverse() : ticks;
  }

  function tickInterval(start, stop, count) {
    const target = Math.abs(stop - start) / count;
    const i = standalone_bisector(([,, step]) => step).right(tickIntervals, target);
    if (i === tickIntervals.length) return year.every(standalone_tickStep(start / standalone_durationYear, stop / standalone_durationYear, count));
    if (i === 0) return standalone_millisecond.every(Math.max(standalone_tickStep(start, stop, count), 1));
    const [t, step] = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];
    return t.every(step);
  }

  return [ticks, tickInterval];
}

const [standalone_utcTicks, standalone_utcTickInterval] = standalone_ticker(standalone_utcYear, standalone_utcMonth, standalone_utcSunday, standalone_unixDay, standalone_utcHour, standalone_utcMinute);
const [standalone_timeTicks, standalone_timeTickInterval] = standalone_ticker(standalone_timeYear, standalone_timeMonth, standalone_timeSunday, standalone_timeDay, standalone_timeHour, standalone_timeMinute);



;// ../../node_modules/d3-scale/src/time.js






function standalone_time_date(t) {
  return new Date(t);
}

function standalone_time_number(t) {
  return t instanceof Date ? +t : +new Date(+t);
}

function standalone_calendar(ticks, tickInterval, year, month, week, day, hour, minute, second, format) {
  var scale = standalone_continuous(),
      invert = scale.invert,
      domain = scale.domain;

  var formatMillisecond = format(".%L"),
      formatSecond = format(":%S"),
      formatMinute = format("%I:%M"),
      formatHour = format("%I %p"),
      formatDay = format("%a %d"),
      formatWeek = format("%b %d"),
      formatMonth = format("%B"),
      formatYear = format("%Y");

  function tickFormat(date) {
    return (second(date) < date ? formatMillisecond
        : minute(date) < date ? formatSecond
        : hour(date) < date ? formatMinute
        : day(date) < date ? formatHour
        : month(date) < date ? (week(date) < date ? formatDay : formatWeek)
        : year(date) < date ? formatMonth
        : formatYear)(date);
  }

  scale.invert = function(y) {
    return new Date(invert(y));
  };

  scale.domain = function(_) {
    return arguments.length ? domain(Array.from(_, standalone_time_number)) : domain().map(standalone_time_date);
  };

  scale.ticks = function(interval) {
    var d = domain();
    return ticks(d[0], d[d.length - 1], interval == null ? 10 : interval);
  };

  scale.tickFormat = function(count, specifier) {
    return specifier == null ? tickFormat : format(specifier);
  };

  scale.nice = function(interval) {
    var d = domain();
    if (!interval || typeof interval.range !== "function") interval = tickInterval(d[0], d[d.length - 1], interval == null ? 10 : interval);
    return interval ? domain(standalone_nice(d, interval)) : scale;
  };

  scale.copy = function() {
    return standalone_copy(scale, standalone_calendar(ticks, tickInterval, year, month, week, day, hour, minute, second, format));
  };

  return scale;
}

function standalone_time() {
  return standalone_initRange.apply(standalone_calendar(standalone_timeTicks, standalone_timeTickInterval, standalone_timeYear, standalone_timeMonth, standalone_timeSunday, standalone_timeDay, standalone_timeHour, standalone_timeMinute, standalone_second, standalone_timeFormat).domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]), arguments);
}

;// ../../node_modules/d3-scale/src/utcTime.js





function standalone_utcTime() {
  return standalone_initRange.apply(standalone_calendar(standalone_utcTicks, standalone_utcTickInterval, standalone_utcYear, standalone_utcMonth, standalone_utcSunday, standalone_utcDay, standalone_utcHour, standalone_utcMinute, standalone_second, standalone_utcFormat).domain([Date.UTC(2000, 0, 1), Date.UTC(2000, 0, 2)]), arguments);
}

;// ../../node_modules/d3-scale/src/sequential.js








function standalone_sequential_transformer() {
  var x0 = 0,
      x1 = 1,
      t0,
      t1,
      k10,
      transform,
      interpolator = standalone_continuous_identity,
      clamp = false,
      unknown;

  function scale(x) {
    return x == null || isNaN(x = +x) ? unknown : interpolator(k10 === 0 ? 0.5 : (x = (transform(x) - t0) * k10, clamp ? Math.max(0, Math.min(1, x)) : x));
  }

  scale.domain = function(_) {
    return arguments.length ? ([x0, x1] = _, t0 = transform(x0 = +x0), t1 = transform(x1 = +x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0), scale) : [x0, x1];
  };

  scale.clamp = function(_) {
    return arguments.length ? (clamp = !!_, scale) : clamp;
  };

  scale.interpolator = function(_) {
    return arguments.length ? (interpolator = _, scale) : interpolator;
  };

  function range(interpolate) {
    return function(_) {
      var r0, r1;
      return arguments.length ? ([r0, r1] = _, interpolator = interpolate(r0, r1), scale) : [interpolator(0), interpolator(1)];
    };
  }

  scale.range = range(standalone_value);

  scale.rangeRound = range(standalone_src_round);

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  return function(t) {
    transform = t, t0 = t(x0), t1 = t(x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0);
    return scale;
  };
}

function standalone_sequential_copy(source, target) {
  return target
      .domain(source.domain())
      .interpolator(source.interpolator())
      .clamp(source.clamp())
      .unknown(source.unknown());
}

function standalone_sequential() {
  var scale = standalone_linearish(standalone_sequential_transformer()(standalone_continuous_identity));

  scale.copy = function() {
    return standalone_sequential_copy(scale, standalone_sequential());
  };

  return standalone_initInterpolator.apply(scale, arguments);
}

function standalone_sequentialLog() {
  var scale = standalone_loggish(standalone_sequential_transformer()).domain([1, 10]);

  scale.copy = function() {
    return standalone_sequential_copy(scale, standalone_sequentialLog()).base(scale.base());
  };

  return standalone_initInterpolator.apply(scale, arguments);
}

function standalone_sequentialSymlog() {
  var scale = standalone_symlogish(standalone_sequential_transformer());

  scale.copy = function() {
    return standalone_sequential_copy(scale, standalone_sequentialSymlog()).constant(scale.constant());
  };

  return standalone_initInterpolator.apply(scale, arguments);
}

function standalone_sequentialPow() {
  var scale = standalone_powish(standalone_sequential_transformer());

  scale.copy = function() {
    return standalone_sequential_copy(scale, standalone_sequentialPow()).exponent(scale.exponent());
  };

  return standalone_initInterpolator.apply(scale, arguments);
}

function standalone_sequentialSqrt() {
  return standalone_sequentialPow.apply(null, arguments).exponent(0.5);
}

;// ../../node_modules/d3-interpolate/src/piecewise.js


function standalone_piecewise(interpolate, values) {
  if (values === undefined) values = interpolate, interpolate = standalone_value;
  var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n);
  while (i < n) I[i] = interpolate(v, v = values[++i]);
  return function(t) {
    var i = Math.max(0, Math.min(n - 1, Math.floor(t *= n)));
    return I[i](t - i);
  };
}

;// ../../node_modules/d3-scale/src/diverging.js









function standalone_diverging_transformer() {
  var x0 = 0,
      x1 = 0.5,
      x2 = 1,
      s = 1,
      t0,
      t1,
      t2,
      k10,
      k21,
      interpolator = standalone_continuous_identity,
      transform,
      clamp = false,
      unknown;

  function scale(x) {
    return isNaN(x = +x) ? unknown : (x = 0.5 + ((x = +transform(x)) - t1) * (s * x < s * t1 ? k10 : k21), interpolator(clamp ? Math.max(0, Math.min(1, x)) : x));
  }

  scale.domain = function(_) {
    return arguments.length ? ([x0, x1, x2] = _, t0 = transform(x0 = +x0), t1 = transform(x1 = +x1), t2 = transform(x2 = +x2), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1), s = t1 < t0 ? -1 : 1, scale) : [x0, x1, x2];
  };

  scale.clamp = function(_) {
    return arguments.length ? (clamp = !!_, scale) : clamp;
  };

  scale.interpolator = function(_) {
    return arguments.length ? (interpolator = _, scale) : interpolator;
  };

  function range(interpolate) {
    return function(_) {
      var r0, r1, r2;
      return arguments.length ? ([r0, r1, r2] = _, interpolator = standalone_piecewise(interpolate, [r0, r1, r2]), scale) : [interpolator(0), interpolator(0.5), interpolator(1)];
    };
  }

  scale.range = range(standalone_value);

  scale.rangeRound = range(standalone_src_round);

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  return function(t) {
    transform = t, t0 = t(x0), t1 = t(x1), t2 = t(x2), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1), s = t1 < t0 ? -1 : 1;
    return scale;
  };
}

function standalone_diverging() {
  var scale = standalone_linearish(standalone_diverging_transformer()(standalone_continuous_identity));

  scale.copy = function() {
    return standalone_sequential_copy(scale, standalone_diverging());
  };

  return standalone_initInterpolator.apply(scale, arguments);
}

function standalone_divergingLog() {
  var scale = standalone_loggish(standalone_diverging_transformer()).domain([0.1, 1, 10]);

  scale.copy = function() {
    return standalone_sequential_copy(scale, standalone_divergingLog()).base(scale.base());
  };

  return standalone_initInterpolator.apply(scale, arguments);
}

function standalone_divergingSymlog() {
  var scale = standalone_symlogish(standalone_diverging_transformer());

  scale.copy = function() {
    return standalone_sequential_copy(scale, standalone_divergingSymlog()).constant(scale.constant());
  };

  return standalone_initInterpolator.apply(scale, arguments);
}

function standalone_divergingPow() {
  var scale = standalone_powish(standalone_diverging_transformer());

  scale.copy = function() {
    return standalone_sequential_copy(scale, standalone_divergingPow()).exponent(scale.exponent());
  };

  return standalone_initInterpolator.apply(scale, arguments);
}

function standalone_divergingSqrt() {
  return standalone_divergingPow.apply(null, arguments).exponent(0.5);
}

;// ../../node_modules/d3-scale/src/quantile.js



function standalone_quantile_quantile() {
  var domain = [],
      range = [],
      thresholds = [],
      unknown;

  function rescale() {
    var i = 0, n = Math.max(1, range.length);
    thresholds = new Array(n - 1);
    while (++i < n) thresholds[i - 1] = standalone_quantileSorted(domain, i / n);
    return scale;
  }

  function scale(x) {
    return x == null || isNaN(x = +x) ? unknown : range[standalone_bisect(thresholds, x)];
  }

  scale.invertExtent = function(y) {
    var i = range.indexOf(y);
    return i < 0 ? [NaN, NaN] : [
      i > 0 ? thresholds[i - 1] : domain[0],
      i < thresholds.length ? thresholds[i] : domain[domain.length - 1]
    ];
  };

  scale.domain = function(_) {
    if (!arguments.length) return domain.slice();
    domain = [];
    for (let d of _) if (d != null && !isNaN(d = +d)) domain.push(d);
    domain.sort(standalone_ascending_ascending);
    return rescale();
  };

  scale.range = function(_) {
    return arguments.length ? (range = Array.from(_), rescale()) : range.slice();
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  scale.quantiles = function() {
    return thresholds.slice();
  };

  scale.copy = function() {
    return standalone_quantile_quantile()
        .domain(domain)
        .range(range)
        .unknown(unknown);
  };

  return standalone_initRange.apply(scale, arguments);
}

;// ../../node_modules/d3-scale/src/quantize.js




function standalone_quantize() {
  var x0 = 0,
      x1 = 1,
      n = 1,
      domain = [0.5],
      range = [0, 1],
      unknown;

  function scale(x) {
    return x != null && x <= x ? range[standalone_bisect(domain, x, 0, n)] : unknown;
  }

  function rescale() {
    var i = -1;
    domain = new Array(n);
    while (++i < n) domain[i] = ((i + 1) * x1 - (i - n) * x0) / (n + 1);
    return scale;
  }

  scale.domain = function(_) {
    return arguments.length ? ([x0, x1] = _, x0 = +x0, x1 = +x1, rescale()) : [x0, x1];
  };

  scale.range = function(_) {
    return arguments.length ? (n = (range = Array.from(_)).length - 1, rescale()) : range.slice();
  };

  scale.invertExtent = function(y) {
    var i = range.indexOf(y);
    return i < 0 ? [NaN, NaN]
        : i < 1 ? [x0, domain[0]]
        : i >= n ? [domain[n - 1], x1]
        : [domain[i - 1], domain[i]];
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : scale;
  };

  scale.thresholds = function() {
    return domain.slice();
  };

  scale.copy = function() {
    return standalone_quantize()
        .domain([x0, x1])
        .range(range)
        .unknown(unknown);
  };

  return standalone_initRange.apply(standalone_linearish(scale), arguments);
}

;// ../../node_modules/d3-scale/src/threshold.js



function standalone_threshold() {
  var domain = [0.5],
      range = [0, 1],
      unknown,
      n = 1;

  function scale(x) {
    return x != null && x <= x ? range[standalone_bisect(domain, x, 0, n)] : unknown;
  }

  scale.domain = function(_) {
    return arguments.length ? (domain = Array.from(_), n = Math.min(domain.length, range.length - 1), scale) : domain.slice();
  };

  scale.range = function(_) {
    return arguments.length ? (range = Array.from(_), n = Math.min(domain.length, range.length - 1), scale) : range.slice();
  };

  scale.invertExtent = function(y) {
    var i = range.indexOf(y);
    return [domain[i - 1], domain[i]];
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  scale.copy = function() {
    return standalone_threshold()
        .domain(domain)
        .range(range)
        .unknown(unknown);
  };

  return standalone_initRange.apply(scale, arguments);
}

;// ../../node_modules/internmap/src/index.js
class standalone_InternMap extends Map {
  constructor(entries, key = standalone_keyof) {
    super();
    Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});
    if (entries != null) for (const [key, value] of entries) this.set(key, value);
  }
  get(key) {
    return super.get(standalone_intern_get(this, key));
  }
  has(key) {
    return super.has(standalone_intern_get(this, key));
  }
  set(key, value) {
    return super.set(standalone_intern_set(this, key), value);
  }
  delete(key) {
    return super.delete(standalone_intern_delete(this, key));
  }
}

class standalone_InternSet extends Set {
  constructor(values, key = standalone_keyof) {
    super();
    Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});
    if (values != null) for (const value of values) this.add(value);
  }
  has(value) {
    return super.has(standalone_intern_get(this, value));
  }
  add(value) {
    return super.add(standalone_intern_set(this, value));
  }
  delete(value) {
    return super.delete(standalone_intern_delete(this, value));
  }
}

function standalone_intern_get({_intern, _key}, value) {
  const key = _key(value);
  return _intern.has(key) ? _intern.get(key) : value;
}

function standalone_intern_set({_intern, _key}, value) {
  const key = _key(value);
  if (_intern.has(key)) return _intern.get(key);
  _intern.set(key, value);
  return value;
}

function standalone_intern_delete({_intern, _key}, value) {
  const key = _key(value);
  if (_intern.has(key)) {
    value = _intern.get(key);
    _intern.delete(key);
  }
  return value;
}

function standalone_keyof(value) {
  return value !== null && typeof value === "object" ? value.valueOf() : value;
}

;// ../../node_modules/d3-scale/src/ordinal.js



const standalone_implicit = Symbol("implicit");

function standalone_ordinal() {
  var index = new standalone_InternMap(),
      domain = [],
      range = [],
      unknown = standalone_implicit;

  function scale(d) {
    let i = index.get(d);
    if (i === undefined) {
      if (unknown !== standalone_implicit) return unknown;
      index.set(d, i = domain.push(d) - 1);
    }
    return range[i % range.length];
  }

  scale.domain = function(_) {
    if (!arguments.length) return domain.slice();
    domain = [], index = new standalone_InternMap();
    for (const value of _) {
      if (index.has(value)) continue;
      index.set(value, domain.push(value) - 1);
    }
    return scale;
  };

  scale.range = function(_) {
    return arguments.length ? (range = Array.from(_), scale) : range.slice();
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  scale.copy = function() {
    return standalone_ordinal(domain, range).unknown(unknown);
  };

  standalone_initRange.apply(scale, arguments);

  return scale;
}

;// ../../node_modules/d3-interpolate/src/discrete.js
/* harmony default export */ function standalone_discrete(range) {
  var n = range.length;
  return function(t) {
    return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
  };
}

;// ../../node_modules/d3-interpolate/src/hue.js


/* harmony default export */ function standalone_src_hue(a, b) {
  var i = standalone_hue(+a, +b);
  return function(t) {
    var x = i(t);
    return x - 360 * Math.floor(x / 360);
  };
}

;// ../../node_modules/d3-interpolate/src/transform/decompose.js
var standalone_decompose_degrees = 180 / Math.PI;

var standalone_decompose_identity = {
  translateX: 0,
  translateY: 0,
  rotate: 0,
  skewX: 0,
  scaleX: 1,
  scaleY: 1
};

/* harmony default export */ function standalone_decompose(a, b, c, d, e, f) {
  var scaleX, scaleY, skewX;
  if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX;
  if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX;
  if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY;
  if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX;
  return {
    translateX: e,
    translateY: f,
    rotate: Math.atan2(b, a) * standalone_decompose_degrees,
    skewX: Math.atan(skewX) * standalone_decompose_degrees,
    scaleX: scaleX,
    scaleY: scaleY
  };
}

;// ../../node_modules/d3-interpolate/src/transform/parse.js


var standalone_svgNode;

/* eslint-disable no-undef */
function standalone_parseCss(value) {
  const m = new (typeof DOMMatrix === "function" ? DOMMatrix : WebKitCSSMatrix)(value + "");
  return m.isIdentity ? standalone_decompose_identity : standalone_decompose(m.a, m.b, m.c, m.d, m.e, m.f);
}

function standalone_parseSvg(value) {
  if (value == null) return standalone_decompose_identity;
  if (!standalone_svgNode) standalone_svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g");
  standalone_svgNode.setAttribute("transform", value);
  if (!(value = standalone_svgNode.transform.baseVal.consolidate())) return standalone_decompose_identity;
  value = value.matrix;
  return standalone_decompose(value.a, value.b, value.c, value.d, value.e, value.f);
}

;// ../../node_modules/d3-interpolate/src/transform/index.js



function standalone_interpolateTransform(parse, pxComma, pxParen, degParen) {

  function pop(s) {
    return s.length ? s.pop() + " " : "";
  }

  function translate(xa, ya, xb, yb, s, q) {
    if (xa !== xb || ya !== yb) {
      var i = s.push("translate(", null, pxComma, null, pxParen);
      q.push({i: i - 4, x: standalone_src_number(xa, xb)}, {i: i - 2, x: standalone_src_number(ya, yb)});
    } else if (xb || yb) {
      s.push("translate(" + xb + pxComma + yb + pxParen);
    }
  }

  function rotate(a, b, s, q) {
    if (a !== b) {
      if (a - b > 180) b += 360; else if (b - a > 180) a += 360; // shortest path
      q.push({i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: standalone_src_number(a, b)});
    } else if (b) {
      s.push(pop(s) + "rotate(" + b + degParen);
    }
  }

  function skewX(a, b, s, q) {
    if (a !== b) {
      q.push({i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: standalone_src_number(a, b)});
    } else if (b) {
      s.push(pop(s) + "skewX(" + b + degParen);
    }
  }

  function scale(xa, ya, xb, yb, s, q) {
    if (xa !== xb || ya !== yb) {
      var i = s.push(pop(s) + "scale(", null, ",", null, ")");
      q.push({i: i - 4, x: standalone_src_number(xa, xb)}, {i: i - 2, x: standalone_src_number(ya, yb)});
    } else if (xb !== 1 || yb !== 1) {
      s.push(pop(s) + "scale(" + xb + "," + yb + ")");
    }
  }

  return function(a, b) {
    var s = [], // string constants and placeholders
        q = []; // number interpolators
    a = parse(a), b = parse(b);
    translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q);
    rotate(a.rotate, b.rotate, s, q);
    skewX(a.skewX, b.skewX, s, q);
    scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q);
    a = b = null; // gc
    return function(t) {
      var i = -1, n = q.length, o;
      while (++i < n) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    };
  };
}

var standalone_interpolateTransformCss = standalone_interpolateTransform(standalone_parseCss, "px, ", "px)", "deg)");
var standalone_interpolateTransformSvg = standalone_interpolateTransform(standalone_parseSvg, ", ", ")", ")");

;// ../../node_modules/d3-interpolate/src/zoom.js
var standalone_epsilon2 = 1e-12;

function standalone_cosh(x) {
  return ((x = Math.exp(x)) + 1 / x) / 2;
}

function standalone_sinh(x) {
  return ((x = Math.exp(x)) - 1 / x) / 2;
}

function standalone_tanh(x) {
  return ((x = Math.exp(2 * x)) - 1) / (x + 1);
}

/* harmony default export */ const standalone_src_zoom = ((function zoomRho(rho, rho2, rho4) {

  // p0 = [ux0, uy0, w0]
  // p1 = [ux1, uy1, w1]
  function zoom(p0, p1) {
    var ux0 = p0[0], uy0 = p0[1], w0 = p0[2],
        ux1 = p1[0], uy1 = p1[1], w1 = p1[2],
        dx = ux1 - ux0,
        dy = uy1 - uy0,
        d2 = dx * dx + dy * dy,
        i,
        S;

    // Special case for u0 ≅ u1.
    if (d2 < standalone_epsilon2) {
      S = Math.log(w1 / w0) / rho;
      i = function(t) {
        return [
          ux0 + t * dx,
          uy0 + t * dy,
          w0 * Math.exp(rho * t * S)
        ];
      }
    }

    // General case.
    else {
      var d1 = Math.sqrt(d2),
          b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1),
          b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1),
          r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0),
          r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
      S = (r1 - r0) / rho;
      i = function(t) {
        var s = t * S,
            coshr0 = standalone_cosh(r0),
            u = w0 / (rho2 * d1) * (coshr0 * standalone_tanh(rho * s + r0) - standalone_sinh(r0));
        return [
          ux0 + u * dx,
          uy0 + u * dy,
          w0 * coshr0 / standalone_cosh(rho * s + r0)
        ];
      }
    }

    i.duration = S * 1000 * rho / Math.SQRT2;

    return i;
  }

  zoom.rho = function(_) {
    var _1 = Math.max(1e-3, +_), _2 = _1 * _1, _4 = _2 * _2;
    return zoomRho(_1, _2, _4);
  };

  return zoom;
})(Math.SQRT2, 2, 4));

;// ../../node_modules/d3-interpolate/src/hsl.js



function standalone_hsl_hsl(hue) {
  return function(start, end) {
    var h = hue((start = standalone_hsl(start)).h, (end = standalone_hsl(end)).h),
        s = standalone_nogamma(start.s, end.s),
        l = standalone_nogamma(start.l, end.l),
        opacity = standalone_nogamma(start.opacity, end.opacity);
    return function(t) {
      start.h = h(t);
      start.s = s(t);
      start.l = l(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
}

/* harmony default export */ const standalone_src_hsl = (standalone_hsl_hsl(standalone_hue));
var standalone_hslLong = standalone_hsl_hsl(standalone_nogamma);

;// ../../node_modules/d3-color/src/math.js
const standalone_math_radians = Math.PI / 180;
const standalone_math_degrees = 180 / Math.PI;

;// ../../node_modules/d3-color/src/lab.js




// https://observablehq.com/@mbostock/lab-and-rgb
const standalone_K = 18,
    standalone_Xn = 0.96422,
    standalone_Yn = 1,
    standalone_Zn = 0.82521,
    standalone_lab_t0 = 4 / 29,
    standalone_lab_t1 = 6 / 29,
    standalone_t2 = 3 * standalone_lab_t1 * standalone_lab_t1,
    standalone_t3 = standalone_lab_t1 * standalone_lab_t1 * standalone_lab_t1;

function standalone_labConvert(o) {
  if (o instanceof standalone_Lab) return new standalone_Lab(o.l, o.a, o.b, o.opacity);
  if (o instanceof standalone_Hcl) return standalone_hcl2lab(o);
  if (!(o instanceof standalone_Rgb)) o = standalone_rgbConvert(o);
  var r = standalone_rgb2lrgb(o.r),
      g = standalone_rgb2lrgb(o.g),
      b = standalone_rgb2lrgb(o.b),
      y = standalone_xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / standalone_Yn), x, z;
  if (r === g && g === b) x = z = y; else {
    x = standalone_xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / standalone_Xn);
    z = standalone_xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / standalone_Zn);
  }
  return new standalone_Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
}

function standalone_gray(l, opacity) {
  return new standalone_Lab(l, 0, 0, opacity == null ? 1 : opacity);
}

function standalone_lab(l, a, b, opacity) {
  return arguments.length === 1 ? standalone_labConvert(l) : new standalone_Lab(l, a, b, opacity == null ? 1 : opacity);
}

function standalone_Lab(l, a, b, opacity) {
  this.l = +l;
  this.a = +a;
  this.b = +b;
  this.opacity = +opacity;
}

standalone_src_define(standalone_Lab, standalone_lab, standalone_define_extend(standalone_Color, {
  brighter(k) {
    return new standalone_Lab(this.l + standalone_K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  darker(k) {
    return new standalone_Lab(this.l - standalone_K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  rgb() {
    var y = (this.l + 16) / 116,
        x = isNaN(this.a) ? y : y + this.a / 500,
        z = isNaN(this.b) ? y : y - this.b / 200;
    x = standalone_Xn * standalone_lab2xyz(x);
    y = standalone_Yn * standalone_lab2xyz(y);
    z = standalone_Zn * standalone_lab2xyz(z);
    return new standalone_Rgb(
      standalone_lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),
      standalone_lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),
      standalone_lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),
      this.opacity
    );
  }
}));

function standalone_xyz2lab(t) {
  return t > standalone_t3 ? Math.pow(t, 1 / 3) : t / standalone_t2 + standalone_lab_t0;
}

function standalone_lab2xyz(t) {
  return t > standalone_lab_t1 ? t * t * t : standalone_t2 * (t - standalone_lab_t0);
}

function standalone_lrgb2rgb(x) {
  return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}

function standalone_rgb2lrgb(x) {
  return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}

function standalone_hclConvert(o) {
  if (o instanceof standalone_Hcl) return new standalone_Hcl(o.h, o.c, o.l, o.opacity);
  if (!(o instanceof standalone_Lab)) o = standalone_labConvert(o);
  if (o.a === 0 && o.b === 0) return new standalone_Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);
  var h = Math.atan2(o.b, o.a) * standalone_math_degrees;
  return new standalone_Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}

function standalone_lch(l, c, h, opacity) {
  return arguments.length === 1 ? standalone_hclConvert(l) : new standalone_Hcl(h, c, l, opacity == null ? 1 : opacity);
}

function standalone_hcl(h, c, l, opacity) {
  return arguments.length === 1 ? standalone_hclConvert(h) : new standalone_Hcl(h, c, l, opacity == null ? 1 : opacity);
}

function standalone_Hcl(h, c, l, opacity) {
  this.h = +h;
  this.c = +c;
  this.l = +l;
  this.opacity = +opacity;
}

function standalone_hcl2lab(o) {
  if (isNaN(o.h)) return new standalone_Lab(o.l, 0, 0, o.opacity);
  var h = o.h * standalone_math_radians;
  return new standalone_Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
}

standalone_src_define(standalone_Hcl, standalone_hcl, standalone_define_extend(standalone_Color, {
  brighter(k) {
    return new standalone_Hcl(this.h, this.c, this.l + standalone_K * (k == null ? 1 : k), this.opacity);
  },
  darker(k) {
    return new standalone_Hcl(this.h, this.c, this.l - standalone_K * (k == null ? 1 : k), this.opacity);
  },
  rgb() {
    return standalone_hcl2lab(this).rgb();
  }
}));

;// ../../node_modules/d3-interpolate/src/lab.js



function standalone_lab_lab(start, end) {
  var l = standalone_nogamma((start = standalone_lab(start)).l, (end = standalone_lab(end)).l),
      a = standalone_nogamma(start.a, end.a),
      b = standalone_nogamma(start.b, end.b),
      opacity = standalone_nogamma(start.opacity, end.opacity);
  return function(t) {
    start.l = l(t);
    start.a = a(t);
    start.b = b(t);
    start.opacity = opacity(t);
    return start + "";
  };
}

;// ../../node_modules/d3-interpolate/src/hcl.js



function standalone_hcl_hcl(hue) {
  return function(start, end) {
    var h = hue((start = standalone_hcl(start)).h, (end = standalone_hcl(end)).h),
        c = standalone_nogamma(start.c, end.c),
        l = standalone_nogamma(start.l, end.l),
        opacity = standalone_nogamma(start.opacity, end.opacity);
    return function(t) {
      start.h = h(t);
      start.c = c(t);
      start.l = l(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
}

/* harmony default export */ const standalone_src_hcl = (standalone_hcl_hcl(standalone_hue));
var standalone_hclLong = standalone_hcl_hcl(standalone_nogamma);

;// ../../node_modules/d3-color/src/cubehelix.js




var standalone_A = -0.14861,
    standalone_B = +1.78277,
    standalone_C = -0.29227,
    standalone_D = -0.90649,
    standalone_E = +1.97294,
    standalone_ED = standalone_E * standalone_D,
    standalone_EB = standalone_E * standalone_B,
    standalone_BC_DA = standalone_B * standalone_C - standalone_D * standalone_A;

function standalone_cubehelixConvert(o) {
  if (o instanceof standalone_Cubehelix) return new standalone_Cubehelix(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof standalone_Rgb)) o = standalone_rgbConvert(o);
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      l = (standalone_BC_DA * b + standalone_ED * r - standalone_EB * g) / (standalone_BC_DA + standalone_ED - standalone_EB),
      bl = b - l,
      k = (standalone_E * (g - l) - standalone_C * bl) / standalone_D,
      s = Math.sqrt(k * k + bl * bl) / (standalone_E * l * (1 - l)), // NaN if l=0 or l=1
      h = s ? Math.atan2(k, bl) * standalone_math_degrees - 120 : NaN;
  return new standalone_Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}

function standalone_cubehelix_cubehelix(h, s, l, opacity) {
  return arguments.length === 1 ? standalone_cubehelixConvert(h) : new standalone_Cubehelix(h, s, l, opacity == null ? 1 : opacity);
}

function standalone_Cubehelix(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

standalone_src_define(standalone_Cubehelix, standalone_cubehelix_cubehelix, standalone_define_extend(standalone_Color, {
  brighter(k) {
    k = k == null ? standalone_brighter : Math.pow(standalone_brighter, k);
    return new standalone_Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  darker(k) {
    k = k == null ? standalone_darker : Math.pow(standalone_darker, k);
    return new standalone_Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  rgb() {
    var h = isNaN(this.h) ? 0 : (this.h + 120) * standalone_math_radians,
        l = +this.l,
        a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
        cosh = Math.cos(h),
        sinh = Math.sin(h);
    return new standalone_Rgb(
      255 * (l + a * (standalone_A * cosh + standalone_B * sinh)),
      255 * (l + a * (standalone_C * cosh + standalone_D * sinh)),
      255 * (l + a * (standalone_E * cosh)),
      this.opacity
    );
  }
}));

;// ../../node_modules/d3-interpolate/src/cubehelix.js



function standalone_cubehelix(hue) {
  return (function cubehelixGamma(y) {
    y = +y;

    function cubehelix(start, end) {
      var h = hue((start = standalone_cubehelix_cubehelix(start)).h, (end = standalone_cubehelix_cubehelix(end)).h),
          s = standalone_nogamma(start.s, end.s),
          l = standalone_nogamma(start.l, end.l),
          opacity = standalone_nogamma(start.opacity, end.opacity);
      return function(t) {
        start.h = h(t);
        start.s = s(t);
        start.l = l(Math.pow(t, y));
        start.opacity = opacity(t);
        return start + "";
      };
    }

    cubehelix.gamma = cubehelixGamma;

    return cubehelix;
  })(1);
}

/* harmony default export */ const standalone_src_cubehelix = (standalone_cubehelix(standalone_hue));
var standalone_cubehelixLong = standalone_cubehelix(standalone_nogamma);

;// ../../node_modules/d3-interpolate/src/quantize.js
/* harmony default export */ function standalone_src_quantize(interpolator, n) {
  var samples = new Array(n);
  for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1));
  return samples;
}

;// ../../node_modules/d3-interpolate/src/index.js






















;// ../../node_modules/d3-scale-chromatic/src/colors.js
/* harmony default export */ function standalone_colors(specifier) {
  var n = specifier.length / 6 | 0, colors = new Array(n), i = 0;
  while (i < n) colors[i] = "#" + specifier.slice(i * 6, ++i * 6);
  return colors;
}

;// ../../node_modules/d3-scale-chromatic/src/categorical/Accent.js


/* harmony default export */ const standalone_Accent = (standalone_colors("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"));

;// ../../node_modules/d3-scale-chromatic/src/categorical/category10.js


/* harmony default export */ const standalone_category10 = (standalone_colors("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"));

;// ../../node_modules/d3-scale-chromatic/src/categorical/Dark2.js


/* harmony default export */ const standalone_Dark2 = (standalone_colors("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"));

;// ../../node_modules/d3-scale-chromatic/src/categorical/observable10.js


/* harmony default export */ const standalone_observable10 = (standalone_colors("4269d0efb118ff725c6cc5b03ca951ff8ab7a463f297bbf59c6b4e9498a0"));

;// ../../node_modules/d3-scale-chromatic/src/categorical/Paired.js


/* harmony default export */ const standalone_Paired = (standalone_colors("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928"));

;// ../../node_modules/d3-scale-chromatic/src/categorical/Pastel1.js


/* harmony default export */ const standalone_Pastel1 = (standalone_colors("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"));

;// ../../node_modules/d3-scale-chromatic/src/categorical/Pastel2.js


/* harmony default export */ const standalone_Pastel2 = (standalone_colors("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"));

;// ../../node_modules/d3-scale-chromatic/src/categorical/Set1.js


/* harmony default export */ const standalone_Set1 = (standalone_colors("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"));

;// ../../node_modules/d3-scale-chromatic/src/categorical/Set2.js


/* harmony default export */ const standalone_Set2 = (standalone_colors("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"));

;// ../../node_modules/d3-scale-chromatic/src/categorical/Set3.js


/* harmony default export */ const standalone_Set3 = (standalone_colors("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"));

;// ../../node_modules/vega-scale/build/vega-scale.module.js









function standalone_bandSpace (count, paddingInner, paddingOuter) {
  const space = count - paddingInner + paddingOuter * 2;
  return count ? space > 0 ? space : 1 : 0;
}

const standalone_Identity = 'identity';
const standalone_vega_scale_module_Linear = 'linear';
const standalone_Log = 'log';
const standalone_Pow = 'pow';
const standalone_Sqrt = 'sqrt';
const standalone_Symlog = 'symlog';
const standalone_Time = 'time';
const standalone_UTC = 'utc';
const standalone_Sequential = 'sequential';
const standalone_Diverging = 'diverging';
const standalone_vega_scale_module_Quantile = 'quantile';
const standalone_Quantize = 'quantize';
const standalone_Threshold = 'threshold';
const standalone_Ordinal = 'ordinal';
const standalone_Point = 'point';
const standalone_Band = 'band';
const standalone_BinOrdinal = 'bin-ordinal';

// categories
const standalone_Continuous = 'continuous';
const standalone_Discrete = 'discrete';
const standalone_Discretizing = 'discretizing';
const standalone_Interpolating = 'interpolating';
const standalone_Temporal = 'temporal';

function standalone_invertRange (scale) {
  return function (_) {
    let lo = _[0],
      hi = _[1],
      t;
    if (hi < lo) {
      t = lo;
      lo = hi;
      hi = t;
    }
    return [scale.invert(lo), scale.invert(hi)];
  };
}

function standalone_invertRangeExtent (scale) {
  return function (_) {
    const range = scale.range();
    let lo = _[0],
      hi = _[1],
      min = -1,
      max,
      t,
      i,
      n;
    if (hi < lo) {
      t = lo;
      lo = hi;
      hi = t;
    }
    for (i = 0, n = range.length; i < n; ++i) {
      if (range[i] >= lo && range[i] <= hi) {
        if (min < 0) min = i;
        max = i;
      }
    }
    if (min < 0) return undefined;
    lo = scale.invertExtent(range[min]);
    hi = scale.invertExtent(range[max]);
    return [lo[0] === undefined ? lo[1] : lo[0], hi[1] === undefined ? hi[0] : hi[1]];
  };
}

function standalone_band() {
  const scale = standalone_ordinal().unknown(undefined),
    domain = scale.domain,
    ordinalRange = scale.range;
  let range$1 = [0, 1],
    step,
    bandwidth,
    round = false,
    paddingInner = 0,
    paddingOuter = 0,
    align = 0.5;
  delete scale.unknown;
  function rescale() {
    const n = domain().length,
      reverse = range$1[1] < range$1[0],
      stop = range$1[1 - reverse],
      space = standalone_bandSpace(n, paddingInner, paddingOuter);
    let start = range$1[reverse - 0];
    step = (stop - start) / (space || 1);
    if (round) {
      step = Math.floor(step);
    }
    start += (stop - start - step * (n - paddingInner)) * align;
    bandwidth = step * (1 - paddingInner);
    if (round) {
      start = Math.round(start);
      bandwidth = Math.round(bandwidth);
    }
    const values = standalone_range(n).map(i => start + step * i);
    return ordinalRange(reverse ? values.reverse() : values);
  }
  scale.domain = function (_) {
    if (arguments.length) {
      domain(_);
      return rescale();
    } else {
      return domain();
    }
  };
  scale.range = function (_) {
    if (arguments.length) {
      range$1 = [+_[0], +_[1]];
      return rescale();
    } else {
      return range$1.slice();
    }
  };
  scale.rangeRound = function (_) {
    range$1 = [+_[0], +_[1]];
    round = true;
    return rescale();
  };
  scale.bandwidth = function () {
    return bandwidth;
  };
  scale.step = function () {
    return step;
  };
  scale.round = function (_) {
    if (arguments.length) {
      round = !!_;
      return rescale();
    } else {
      return round;
    }
  };
  scale.padding = function (_) {
    if (arguments.length) {
      paddingOuter = Math.max(0, Math.min(1, _));
      paddingInner = paddingOuter;
      return rescale();
    } else {
      return paddingInner;
    }
  };
  scale.paddingInner = function (_) {
    if (arguments.length) {
      paddingInner = Math.max(0, Math.min(1, _));
      return rescale();
    } else {
      return paddingInner;
    }
  };
  scale.paddingOuter = function (_) {
    if (arguments.length) {
      paddingOuter = Math.max(0, Math.min(1, _));
      return rescale();
    } else {
      return paddingOuter;
    }
  };
  scale.align = function (_) {
    if (arguments.length) {
      align = Math.max(0, Math.min(1, _));
      return rescale();
    } else {
      return align;
    }
  };
  scale.invertRange = function (_) {
    // bail if range has null or undefined values
    if (_[0] == null || _[1] == null) return;
    const reverse = range$1[1] < range$1[0],
      values = reverse ? ordinalRange().reverse() : ordinalRange(),
      n = values.length - 1;
    let lo = +_[0],
      hi = +_[1],
      a,
      b,
      t;

    // bail if either range endpoint is invalid
    if (lo !== lo || hi !== hi) return;

    // order range inputs, bail if outside of scale range
    if (hi < lo) {
      t = lo;
      lo = hi;
      hi = t;
    }
    if (hi < values[0] || lo > range$1[1 - reverse]) return;

    // binary search to index into scale range
    a = Math.max(0, standalone_bisectRight(values, lo) - 1);
    b = lo === hi ? a : standalone_bisectRight(values, hi) - 1;

    // increment index a if lo is within padding gap
    if (lo - values[a] > bandwidth + 1e-10) ++a;
    if (reverse) {
      // map + swap
      t = a;
      a = n - b;
      b = n - t;
    }
    return a > b ? undefined : domain().slice(a, b + 1);
  };
  scale.invert = function (_) {
    const value = scale.invertRange([_, _]);
    return value ? value[0] : value;
  };
  scale.copy = function () {
    return standalone_band().domain(domain()).range(range$1).round(round).paddingInner(paddingInner).paddingOuter(paddingOuter).align(align);
  };
  return rescale();
}
function standalone_pointish(scale) {
  const copy = scale.copy;
  scale.padding = scale.paddingOuter;
  delete scale.paddingInner;
  scale.copy = function () {
    return standalone_pointish(copy());
  };
  return scale;
}
function standalone_vega_scale_module_point() {
  return standalone_pointish(standalone_band().paddingInner(1));
}

var standalone_vega_scale_module_map = Array.prototype.map;
function standalone_vega_scale_module_numbers(_) {
  return standalone_vega_scale_module_map.call(_, standalone_toNumber);
}

const standalone_vega_scale_module_slice = Array.prototype.slice;

function standalone_scaleBinOrdinal() {
  let domain = [],
    range = [];
  function scale(x) {
    return x == null || x !== x ? undefined : range[(standalone_bisect(domain, x) - 1) % range.length];
  }
  scale.domain = function (_) {
    if (arguments.length) {
      domain = standalone_vega_scale_module_numbers(_);
      return scale;
    } else {
      return domain.slice();
    }
  };
  scale.range = function (_) {
    if (arguments.length) {
      range = standalone_vega_scale_module_slice.call(_);
      return scale;
    } else {
      return range.slice();
    }
  };
  scale.tickFormat = function (count, specifier) {
    return standalone_tickFormat(domain[0], standalone_peek(domain), count == null ? 10 : count, specifier);
  };
  scale.copy = function () {
    return standalone_scaleBinOrdinal().domain(scale.domain()).range(scale.range());
  };
  return scale;
}

/** Private scale registry: should not be exported */
const standalone_scales = new Map();
const standalone_VEGA_SCALE = Symbol('vega_scale');
function standalone_registerScale(scale) {
  scale[standalone_VEGA_SCALE] = true;
  return scale;
}

/**
 * Return true if object was created by a constructor from the vega-scale `scale` function.
 */
function standalone_isRegisteredScale(scale) {
  return scale && scale[standalone_VEGA_SCALE] === true;
}

/**
 * Augment scales with their type and needed inverse methods.
 */
function standalone_create(type, constructor, metadata) {
  const ctr = function scale() {
    const s = constructor();
    if (!s.invertRange) {
      s.invertRange = s.invert ? standalone_invertRange(s) : s.invertExtent ? standalone_invertRangeExtent(s) : undefined;
    }
    s.type = type;
    return standalone_registerScale(s);
  };
  ctr.metadata = standalone_toSet(standalone_array(metadata));
  return ctr;
}

/**
 * Registry function for adding and accessing scale constructor functions.
 * The *type* argument is a String indicating the name of the scale type.
 *
 * If the *scale* argument is not specified, this method returns the matching scale constructor in the registry, or `null` if not found.
 * If the *scale* argument is provided, it must be a scale constructor function to add to the registry under the given *type* name.
 * The *metadata* argument provides additional information to guide appropriate use of scales within Vega.
 *
 *  *metadata* can be either a string or string array. The valid string values are:
 * - `"continuous"` - the scale is defined over a continuous-valued domain.
 * - `"discrete"` - the scale is defined over a discrete domain and range.
 * - `"discretizing"` - the scale discretizes a continuous domain to a discrete range.
 * - `"interpolating"` - the scale range is defined using a color interpolator.
 * - `"log"` - the scale performs a logarithmic transform of the continuous domain.
 * - `"temporal"` - the scale domain is defined over date-time values.
 */
function standalone_vega_scale_module_scale(type, scale, metadata) {
  if (arguments.length > 1) {
    standalone_scales.set(type, standalone_create(type, scale, metadata));
    return this;
  } else {
    return standalone_isValidScaleType(type) ? standalone_scales.get(type) : undefined;
  }
}

// identity scale
standalone_vega_scale_module_scale(standalone_Identity, standalone_identity_identity);

// continuous scales
standalone_vega_scale_module_scale(standalone_vega_scale_module_Linear, standalone_linear_linear, standalone_Continuous);
standalone_vega_scale_module_scale(standalone_Log, standalone_log_log, [standalone_Continuous, standalone_Log]);
standalone_vega_scale_module_scale(standalone_Pow, standalone_pow_pow, standalone_Continuous);
standalone_vega_scale_module_scale(standalone_Sqrt, standalone_pow_sqrt, standalone_Continuous);
standalone_vega_scale_module_scale(standalone_Symlog, standalone_symlog_symlog, standalone_Continuous);
standalone_vega_scale_module_scale(standalone_Time, standalone_time, [standalone_Continuous, standalone_Temporal]);
standalone_vega_scale_module_scale(standalone_UTC, standalone_utcTime, [standalone_Continuous, standalone_Temporal]);

// sequential scales
standalone_vega_scale_module_scale(standalone_Sequential, standalone_sequential, [standalone_Continuous, standalone_Interpolating]); // backwards compat
standalone_vega_scale_module_scale(`${standalone_Sequential}-${standalone_vega_scale_module_Linear}`, standalone_sequential, [standalone_Continuous, standalone_Interpolating]);
standalone_vega_scale_module_scale(`${standalone_Sequential}-${standalone_Log}`, standalone_sequentialLog, [standalone_Continuous, standalone_Interpolating, standalone_Log]);
standalone_vega_scale_module_scale(`${standalone_Sequential}-${standalone_Pow}`, standalone_sequentialPow, [standalone_Continuous, standalone_Interpolating]);
standalone_vega_scale_module_scale(`${standalone_Sequential}-${standalone_Sqrt}`, standalone_sequentialSqrt, [standalone_Continuous, standalone_Interpolating]);
standalone_vega_scale_module_scale(`${standalone_Sequential}-${standalone_Symlog}`, standalone_sequentialSymlog, [standalone_Continuous, standalone_Interpolating]);

// diverging scales
standalone_vega_scale_module_scale(`${standalone_Diverging}-${standalone_vega_scale_module_Linear}`, standalone_diverging, [standalone_Continuous, standalone_Interpolating]);
standalone_vega_scale_module_scale(`${standalone_Diverging}-${standalone_Log}`, standalone_divergingLog, [standalone_Continuous, standalone_Interpolating, standalone_Log]);
standalone_vega_scale_module_scale(`${standalone_Diverging}-${standalone_Pow}`, standalone_divergingPow, [standalone_Continuous, standalone_Interpolating]);
standalone_vega_scale_module_scale(`${standalone_Diverging}-${standalone_Sqrt}`, standalone_divergingSqrt, [standalone_Continuous, standalone_Interpolating]);
standalone_vega_scale_module_scale(`${standalone_Diverging}-${standalone_Symlog}`, standalone_divergingSymlog, [standalone_Continuous, standalone_Interpolating]);

// discretizing scales
standalone_vega_scale_module_scale(standalone_vega_scale_module_Quantile, standalone_quantile_quantile, [standalone_Discretizing, standalone_vega_scale_module_Quantile]);
standalone_vega_scale_module_scale(standalone_Quantize, standalone_quantize, standalone_Discretizing);
standalone_vega_scale_module_scale(standalone_Threshold, standalone_threshold, standalone_Discretizing);

// discrete scales
standalone_vega_scale_module_scale(standalone_BinOrdinal, standalone_scaleBinOrdinal, [standalone_Discrete, standalone_Discretizing]);
standalone_vega_scale_module_scale(standalone_Ordinal, standalone_ordinal, standalone_Discrete);
standalone_vega_scale_module_scale(standalone_Band, standalone_band, standalone_Discrete);
standalone_vega_scale_module_scale(standalone_Point, standalone_vega_scale_module_point, standalone_Discrete);
function standalone_isValidScaleType(type) {
  return standalone_scales.has(type);
}
function standalone_hasType(key, type) {
  const s = standalone_scales.get(key);
  return s && s.metadata[type];
}
function standalone_isContinuous(key) {
  return standalone_hasType(key, standalone_Continuous);
}
function standalone_isDiscrete(key) {
  return standalone_hasType(key, standalone_Discrete);
}
function standalone_isDiscretizing(key) {
  return standalone_hasType(key, standalone_Discretizing);
}
function standalone_isLogarithmic(key) {
  return standalone_hasType(key, standalone_Log);
}
function standalone_isTemporal(key) {
  return standalone_hasType(key, standalone_Temporal);
}
function standalone_isInterpolating(key) {
  return standalone_hasType(key, standalone_Interpolating);
}
function standalone_isQuantile(key) {
  return standalone_hasType(key, standalone_vega_scale_module_Quantile);
}

const standalone_scaleProps = ['clamp', 'base', 'constant', 'exponent'];
function standalone_interpolateRange(interpolator, range) {
  const start = range[0],
    span = standalone_peek(range) - start;
  return function (i) {
    return interpolator(start + i * span);
  };
}
function standalone_interpolateColors(colors, type, gamma) {
  return standalone_piecewise(standalone_interpolate(type || 'rgb', gamma), colors);
}
function standalone_quantizeInterpolator(interpolator, count) {
  const samples = new Array(count),
    n = count + 1;
  for (let i = 0; i < count;) samples[i] = interpolator(++i / n);
  return samples;
}
function standalone_scaleCopy(scale) {
  const t = scale.type,
    s = scale.copy();
  s.type = t;
  return s;
}
function standalone_scaleFraction(scale$1, min, max) {
  const delta = max - min;
  let i, t, s;
  if (!delta || !Number.isFinite(delta)) {
    return standalone_vega_util_module_constant(0.5);
  } else {
    i = (t = scale$1.type).indexOf('-');
    t = i < 0 ? t : t.slice(i + 1);
    s = standalone_vega_scale_module_scale(t)().domain([min, max]).range([0, 1]);
    standalone_scaleProps.forEach(m => scale$1[m] ? s[m](scale$1[m]()) : 0);
    return s;
  }
}
function standalone_interpolate(type, gamma) {
  const interp = standalone_d3_interpolate_src_namespaceObject[standalone_method(type)];
  return gamma != null && interp && interp.gamma ? interp.gamma(gamma) : interp;
}
function standalone_method(type) {
  return 'interpolate' + type.toLowerCase().split('-').map(s => s[0].toUpperCase() + s.slice(1)).join('');
}

const standalone_vega_scale_module_continuous = {
  blues: 'cfe1f2bed8eca8cee58fc1de74b2d75ba3cf4592c63181bd206fb2125ca40a4a90',
  greens: 'd3eecdc0e6baabdda594d3917bc77d60ba6c46ab5e329a512089430e7735036429',
  greys: 'e2e2e2d4d4d4c4c4c4b1b1b19d9d9d8888887575756262624d4d4d3535351e1e1e',
  oranges: 'fdd8b3fdc998fdb87bfda55efc9244f87f2cf06b18e4580bd14904b93d029f3303',
  purples: 'e2e1efd4d4e8c4c5e0b4b3d6a3a0cc928ec3827cb97566ae684ea25c3696501f8c',
  reds: 'fdc9b4fcb49afc9e80fc8767fa7051f6573fec3f2fdc2a25c81b1db21218970b13',
  blueGreen: 'd5efedc1e8e0a7ddd18bd2be70c6a958ba9144ad77319c5d2089460e7736036429',
  bluePurple: 'ccddecbad0e4a8c2dd9ab0d4919cc98d85be8b6db28a55a6873c99822287730f71',
  greenBlue: 'd3eecec5e8c3b1e1bb9bd8bb82cec269c2ca51b2cd3c9fc7288abd1675b10b60a1',
  orangeRed: 'fddcaffdcf9bfdc18afdad77fb9562f67d53ee6545e24932d32d1ebf130da70403',
  purpleBlue: 'dbdaebc8cee4b1c3de97b7d87bacd15b9fc93a90c01e7fb70b70ab056199045281',
  purpleBlueGreen: 'dbd8eac8cee4b0c3de93b7d872acd1549fc83892bb1c88a3097f8702736b016353',
  purpleRed: 'dcc9e2d3b3d7ce9eccd186c0da6bb2e14da0e23189d91e6fc61159ab07498f023a',
  redPurple: 'fccfccfcbec0faa9b8f98faff571a5ec539ddb3695c41b8aa908808d0179700174',
  yellowGreen: 'e4f4acd1eca0b9e2949ed68880c97c62bb6e47aa5e3297502083440e723b036034',
  yellowOrangeBrown: 'feeaa1fedd84fecc63feb746fca031f68921eb7215db5e0bc54c05ab3d038f3204',
  yellowOrangeRed: 'fee087fed16ffebd59fea849fd903efc7335f9522bee3423de1b20ca0b22af0225',
  blueOrange: '134b852f78b35da2cb9dcae1d2e5eff2f0ebfce0bafbbf74e8932fc5690d994a07',
  brownBlueGreen: '704108a0651ac79548e3c78af3e6c6eef1eac9e9e48ed1c74da79e187a72025147',
  purpleGreen: '5b1667834792a67fb6c9aed3e6d6e8eff0efd9efd5aedda971bb75368e490e5e29',
  purpleOrange: '4114696647968f83b7b9b4d6dadbebf3eeeafce0bafbbf74e8932fc5690d994a07',
  redBlue: '8c0d25bf363adf745ef4ae91fbdbc9f2efeed2e5ef9dcae15da2cb2f78b3134b85',
  redGrey: '8c0d25bf363adf745ef4ae91fcdccbfaf4f1e2e2e2c0c0c0969696646464343434',
  yellowGreenBlue: 'eff9bddbf1b4bde5b594d5b969c5be45b4c22c9ec02182b82163aa23479c1c3185',
  redYellowBlue: 'a50026d4322cf16e43fcac64fedd90faf8c1dcf1ecabd6e875abd04a74b4313695',
  redYellowGreen: 'a50026d4322cf16e43fcac63fedd8df9f7aed7ee8ea4d86e64bc6122964f006837',
  pinkYellowGreen: '8e0152c0267edd72adf0b3d6faddedf5f3efe1f2cab6de8780bb474f9125276419',
  spectral: '9e0142d13c4bf0704afcac63fedd8dfbf8b0e0f3a1a9dda269bda94288b55e4fa2',
  viridis: '440154470e61481a6c482575472f7d443a834144873d4e8a39568c35608d31688e2d708e2a788e27818e23888e21918d1f988b1fa08822a8842ab07f35b77943bf7154c56866cc5d7ad1518fd744a5db36bcdf27d2e21be9e51afde725',
  magma: '0000040404130b0924150e3720114b2c11603b0f704a107957157e651a80721f817f24828c29819a2e80a8327db6377ac43c75d1426fde4968e95462f1605df76f5cfa7f5efc8f65fe9f6dfeaf78febf84fece91fddea0fcedaffcfdbf',
  inferno: '0000040403130c0826170c3b240c4f330a5f420a68500d6c5d126e6b176e781c6d86216b932667a12b62ae305cbb3755c73e4cd24644dd513ae65c30ed6925f3771af8850ffb9506fca50afcb519fac62df6d645f2e661f3f484fcffa4',
  plasma: '0d088723069033059742039d5002a25d01a66a00a87801a88405a7900da49c179ea72198b12a90ba3488c33d80cb4779d35171da5a69e16462e76e5bed7953f2834cf68f44fa9a3dfca636fdb32ffec029fcce25f9dc24f5ea27f0f921',
  cividis: '00205100235800265d002961012b65042e670831690d346b11366c16396d1c3c6e213f6e26426e2c456e31476e374a6e3c4d6e42506e47536d4c566d51586e555b6e5a5e6e5e616e62646f66676f6a6a706e6d717270717573727976737c79747f7c75827f758682768985778c8877908b78938e789691789a94789e9778a19b78a59e77a9a177aea575b2a874b6ab73bbaf71c0b26fc5b66dc9b96acebd68d3c065d8c462ddc85fe2cb5ce7cf58ebd355f0d652f3da4ff7de4cfae249fce647',
  rainbow: '6e40aa883eb1a43db3bf3cafd83fa4ee4395fe4b83ff576eff6659ff7847ff8c38f3a130e2b72fcfcc36bee044aff05b8ff4576ff65b52f6673af27828ea8d1ddfa319d0b81cbecb23abd82f96e03d82e14c6edb5a5dd0664dbf6e40aa',
  sinebow: 'ff4040fc582af47218e78d0bd5a703bfbf00a7d5038de70b72f41858fc2a40ff402afc5818f4720be78d03d5a700bfbf03a7d50b8de71872f42a58fc4040ff582afc7218f48d0be7a703d5bf00bfd503a7e70b8df41872fc2a58ff4040',
  turbo: '23171b32204a3e2a71453493493eae4b49c54a53d7485ee44569ee4074f53c7ff8378af93295f72e9ff42ba9ef28b3e926bce125c5d925cdcf27d5c629dcbc2de3b232e9a738ee9d3ff39347f68950f9805afc7765fd6e70fe667cfd5e88fc5795fb51a1f84badf545b9f140c5ec3cd0e637dae034e4d931ecd12ef4c92bfac029ffb626ffad24ffa223ff9821ff8d1fff821dff771cfd6c1af76118f05616e84b14df4111d5380fcb2f0dc0260ab61f07ac1805a313029b0f00950c00910b00',
  browns: 'eedbbdecca96e9b97ae4a865dc9856d18954c7784cc0673fb85536ad44339f3632',
  tealBlues: 'bce4d89dd3d181c3cb65b3c245a2b9368fae347da0306a932c5985',
  teals: 'bbdfdfa2d4d58ac9c975bcbb61b0af4da5a43799982b8b8c1e7f7f127273006667',
  warmGreys: 'dcd4d0cec5c1c0b8b4b3aaa7a59c9998908c8b827f7e7673726866665c5a59504e',
  goldGreen: 'f4d166d5ca60b6c35c98bb597cb25760a6564b9c533f8f4f33834a257740146c36',
  goldOrange: 'f4d166f8be5cf8aa4cf5983bf3852aef701be2621fd65322c54923b142239e3a26',
  goldRed: 'f4d166f6be59f9aa51fc964ef6834bee734ae56249db5247cf4244c43141b71d3e',
  lightGreyRed: 'efe9e6e1dad7d5cbc8c8bdb9bbaea9cd967ddc7b43e15f19df4011dc000b',
  lightGreyTeal: 'e4eaead6dcddc8ced2b7c2c7a6b4bc64b0bf22a6c32295c11f85be1876bc',
  lightMulti: 'e0f1f2c4e9d0b0de9fd0e181f6e072f6c053f3993ef77440ef4a3c',
  lightOrange: 'f2e7daf7d5baf9c499fab184fa9c73f68967ef7860e8645bde515bd43d5b',
  lightTealBlue: 'e3e9e0c0dccf9aceca7abfc859afc0389fb9328dad2f7ca0276b95255988',
  darkBlue: '3232322d46681a5c930074af008cbf05a7ce25c0dd38daed50f3faffffff',
  darkGold: '3c3c3c584b37725e348c7631ae8b2bcfa424ecc31ef9de30fff184ffffff',
  darkGreen: '3a3a3a215748006f4d048942489e4276b340a6c63dd2d836ffeb2cffffaa',
  darkMulti: '3737371f5287197d8c29a86995ce3fffe800ffffff',
  darkRed: '3434347036339e3c38cc4037e75d1eec8620eeab29f0ce32ffeb2c'
};
const standalone_vega_scale_module_discrete = {
  accent: standalone_Accent,
  category10: standalone_category10,
  category20: '1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5',
  category20b: '393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6',
  category20c: '3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9',
  dark2: standalone_Dark2,
  observable10: standalone_observable10,
  paired: standalone_Paired,
  pastel1: standalone_Pastel1,
  pastel2: standalone_Pastel2,
  set1: standalone_Set1,
  set2: standalone_Set2,
  set3: standalone_Set3,
  tableau10: '4c78a8f58518e4575672b7b254a24beeca3bb279a2ff9da69d755dbab0ac',
  tableau20: '4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5'
};

function standalone_vega_scale_module_colors(palette) {
  if (standalone_vega_util_module_isArray(palette)) return palette;
  const n = palette.length / 6 | 0,
    c = new Array(n);
  for (let i = 0; i < n;) {
    c[i] = '#' + palette.slice(i * 6, ++i * 6);
  }
  return c;
}
function standalone_apply(_, f) {
  for (const k in _) standalone_scheme(k, f(_[k]));
}
const standalone_schemes = {};
standalone_apply(standalone_vega_scale_module_discrete, standalone_vega_scale_module_colors);
standalone_apply(standalone_vega_scale_module_continuous, _ => standalone_interpolateColors(standalone_vega_scale_module_colors(_)));
function standalone_scheme(name, scheme) {
  name = name && name.toLowerCase();
  if (arguments.length > 1) {
    standalone_schemes[name] = scheme;
    return this;
  } else {
    return standalone_schemes[name];
  }
}

const standalone_SymbolLegend = 'symbol';
const standalone_DiscreteLegend = 'discrete';
const standalone_GradientLegend = 'gradient';

const standalone_defaultFormatter = value => standalone_vega_util_module_isArray(value) ? value.map(v => String(v)) : String(value);
const standalone_vega_scale_module_ascending = (a, b) => a[1] - b[1];
const standalone_vega_scale_module_descending = (a, b) => b[1] - a[1];

/**
 * Determine the tick count or interval function.
 * @param {Scale} scale - The scale for which to generate tick values.
 * @param {*} count - The desired tick count or interval specifier.
 * @param {number} minStep - The desired minimum step between tick values.
 * @return {*} - The tick count or interval function.
 */
function standalone_tickCount(scale, count, minStep) {
  let step;
  if (standalone_isNumber(count)) {
    if (scale.bins) {
      count = Math.max(count, scale.bins.length);
    }
    if (minStep != null) {
      count = Math.min(count, Math.floor(standalone_span(scale.domain()) / minStep || 1) + 1);
    }
  }
  if (standalone_vega_util_module_isObject(count)) {
    step = count.step;
    count = count.interval;
  }
  if (standalone_vega_util_module_isString(count)) {
    count = scale.type === standalone_Time ? standalone_vega_time_module_timeInterval(count) : scale.type == standalone_UTC ? standalone_utcInterval(count) : standalone_vega_util_module_error('Only time and utc scales accept interval strings.');
    if (step) count = count.every(step);
  }
  return count;
}

/**
 * Filter a set of candidate tick values, ensuring that only tick values
 * that lie within the scale range are included.
 * @param {Scale} scale - The scale for which to generate tick values.
 * @param {Array<*>} ticks - The candidate tick values.
 * @param {*} count - The tick count or interval function.
 * @return {Array<*>} - The filtered tick values.
 */
function standalone_validTicks(scale, ticks, count) {
  let range = scale.range(),
    lo = range[0],
    hi = standalone_peek(range),
    cmp = standalone_vega_scale_module_ascending;
  if (lo > hi) {
    range = hi;
    hi = lo;
    lo = range;
    cmp = standalone_vega_scale_module_descending;
  }
  lo = Math.floor(lo);
  hi = Math.ceil(hi);

  // filter ticks to valid values within the range
  // additionally sort ticks in range order (#2579)
  ticks = ticks.map(v => [v, scale(v)]).filter(_ => lo <= _[1] && _[1] <= hi).sort(cmp).map(_ => _[0]);
  if (count > 0 && ticks.length > 1) {
    const endpoints = [ticks[0], standalone_peek(ticks)];
    while (ticks.length > count && ticks.length >= 3) {
      ticks = ticks.filter((_, i) => !(i % 2));
    }
    if (ticks.length < 3) {
      ticks = endpoints;
    }
  }
  return ticks;
}

/**
 * Generate tick values for the given scale and approximate tick count or
 * interval value. If the scale has a 'ticks' method, it will be used to
 * generate the ticks, with the count argument passed as a parameter. If the
 * scale lacks a 'ticks' method, the full scale domain will be returned.
 * @param {Scale} scale - The scale for which to generate tick values.
 * @param {*} [count] - The approximate number of desired ticks.
 * @return {Array<*>} - The generated tick values.
 */
function standalone_tickValues(scale, count) {
  return scale.bins ? standalone_validTicks(scale, scale.bins, count) : scale.ticks ? scale.ticks(count) : scale.domain();
}

/**
 * Generate a label format function for a scale. If the scale has a
 * 'tickFormat' method, it will be used to generate the formatter, with the
 * count and specifier arguments passed as parameters. If the scale lacks a
 * 'tickFormat' method, the returned formatter performs simple string coercion.
 * If the input scale is a logarithmic scale and the format specifier does not
 * indicate a desired decimal precision, a special variable precision formatter
 * that automatically trims trailing zeroes will be generated.
 * @param {Scale} scale - The scale for which to generate the label formatter.
 * @param {*} [count] - The approximate number of desired ticks.
 * @param {string} [specifier] - The format specifier. Must be a legal d3
 *   specifier string (see https://github.com/d3/d3-format#formatSpecifier) or
 *   time multi-format specifier object.
 * @return {function(*):string} - The generated label formatter.
 */
function standalone_vega_scale_module_tickFormat(locale, scale, count, specifier, formatType, noSkip) {
  const type = scale.type;
  let format = standalone_defaultFormatter;
  if (type === standalone_Time || formatType === standalone_Time) {
    format = locale.timeFormat(specifier);
  } else if (type === standalone_UTC || formatType === standalone_UTC) {
    format = locale.utcFormat(specifier);
  } else if (standalone_isLogarithmic(type)) {
    const varfmt = locale.formatFloat(specifier);
    if (noSkip || scale.bins) {
      format = varfmt;
    } else {
      const test = standalone_tickLog(scale, count, false);
      format = _ => test(_) ? varfmt(_) : '';
    }
  } else if (scale.tickFormat) {
    // if d3 scale has tickFormat, it must be continuous
    const d = scale.domain();
    format = locale.formatSpan(d[0], d[d.length - 1], count, specifier);
  } else if (specifier) {
    format = locale.format(specifier);
  }
  return format;
}
function standalone_tickLog(scale, count, values) {
  const ticks = standalone_tickValues(scale, count),
    base = scale.base(),
    logb = Math.log(base),
    k = Math.max(1, base * count / ticks.length);

  // apply d3-scale's log format filter criteria
  const test = d => {
    let i = d / Math.pow(base, Math.round(Math.log(d) / logb));
    if (i * base < base - 0.5) i *= base;
    return i <= k;
  };
  return values ? ticks.filter(test) : test;
}

const standalone_symbols = {
  [standalone_vega_scale_module_Quantile]: 'quantiles',
  [standalone_Quantize]: 'thresholds',
  [standalone_Threshold]: 'domain'
};
const standalone_vega_scale_module_formats = {
  [standalone_vega_scale_module_Quantile]: 'quantiles',
  [standalone_Quantize]: 'domain'
};
function standalone_labelValues(scale, count) {
  return scale.bins ? standalone_binValues(scale.bins) : scale.type === standalone_Log ? standalone_tickLog(scale, count, true) : standalone_symbols[scale.type] ? standalone_thresholdValues(scale[standalone_symbols[scale.type]]()) : standalone_tickValues(scale, count);
}
function standalone_thresholdFormat(locale, scale, specifier) {
  const _ = scale[standalone_vega_scale_module_formats[scale.type]](),
    n = _.length;
  let d = n > 1 ? _[1] - _[0] : _[0],
    i;
  for (i = 1; i < n; ++i) {
    d = Math.min(d, _[i] - _[i - 1]);
  }

  // tickCount = 3 ticks times 10 for increased resolution
  return locale.formatSpan(0, d, 3 * 10, specifier);
}
function standalone_thresholdValues(thresholds) {
  const values = [-Infinity].concat(thresholds);
  values.max = +Infinity;
  return values;
}
function standalone_binValues(bins) {
  const values = bins.slice(0, -1);
  values.max = standalone_peek(bins);
  return values;
}
const standalone_isDiscreteRange = scale => standalone_symbols[scale.type] || scale.bins;
function standalone_labelFormat(locale, scale, count, type, specifier, formatType, noSkip) {
  const format = standalone_vega_scale_module_formats[scale.type] && formatType !== standalone_Time && formatType !== standalone_UTC ? standalone_thresholdFormat(locale, scale, specifier) : standalone_vega_scale_module_tickFormat(locale, scale, count, specifier, formatType, noSkip);
  return type === standalone_SymbolLegend && standalone_isDiscreteRange(scale) ? standalone_formatRange(format) : type === standalone_DiscreteLegend ? standalone_formatDiscrete(format) : standalone_formatPoint(format);
}
const standalone_formatRange = format => (value, index, array) => {
  const limit = standalone_vega_scale_module_get(array[index + 1], standalone_vega_scale_module_get(array.max, +Infinity)),
    lo = standalone_formatValue(value, format),
    hi = standalone_formatValue(limit, format);
  return lo && hi ? lo + ' \u2013 ' + hi : hi ? '< ' + hi : '\u2265 ' + lo;
};
const standalone_vega_scale_module_get = (value, dflt) => value != null ? value : dflt;
const standalone_formatDiscrete = format => (value, index) => index ? format(value) : null;
const standalone_formatPoint = format => value => format(value);
const standalone_formatValue = (value, format) => Number.isFinite(value) ? format(value) : null;
function standalone_labelFraction(scale) {
  const domain = scale.domain(),
    count = domain.length - 1;
  let lo = +domain[0],
    hi = +standalone_peek(domain),
    span = hi - lo;
  if (scale.type === standalone_Threshold) {
    const adjust = count ? span / count : 0.1;
    lo -= adjust;
    hi += adjust;
    span = hi - lo;
  }
  return value => (value - lo) / span;
}

function standalone_vega_scale_module_format(locale, scale, specifier, formatType) {
  const type = formatType || scale.type;

  // replace abbreviated time specifiers to improve screen reader experience
  if (standalone_vega_util_module_isString(specifier) && standalone_isTemporal(type)) {
    specifier = specifier.replace(/%a/g, '%A').replace(/%b/g, '%B');
  }
  return !specifier && type === standalone_Time ? locale.timeFormat('%A, %d %B %Y, %X') : !specifier && type === standalone_UTC ? locale.utcFormat('%A, %d %B %Y, %X UTC') : standalone_labelFormat(locale, scale, 5, null, specifier, formatType, true);
}
function standalone_domainCaption(locale, scale, opt) {
  opt = opt || {};
  const max = Math.max(3, opt.maxlen || 7),
    fmt = standalone_vega_scale_module_format(locale, scale, opt.format, opt.formatType);

  // if scale breaks domain into bins, describe boundaries
  if (standalone_isDiscretizing(scale.type)) {
    const v = standalone_labelValues(scale).slice(1).map(fmt),
      n = v.length;
    return `${n} boundar${n === 1 ? 'y' : 'ies'}: ${v.join(', ')}`;
  }

  // if scale domain is discrete, list values
  else if (standalone_isDiscrete(scale.type)) {
    const d = scale.domain(),
      n = d.length,
      v = n > max ? d.slice(0, max - 2).map(fmt).join(', ') + ', ending with ' + d.slice(-1).map(fmt) : d.map(fmt).join(', ');
    return `${n} value${n === 1 ? '' : 's'}: ${v}`;
  }

  // if scale domain is continuous, describe value range
  else {
    const d = scale.domain();
    return `values from ${fmt(d[0])} to ${fmt(standalone_peek(d))}`;
  }
}



;// ../../node_modules/vega-scenegraph/build/vega-scenegraph.module.js








let standalone_gradient_id = 0;
function standalone_resetSVGGradientId() {
  standalone_gradient_id = 0;
}
const standalone_patternPrefix = 'p_';
function standalone_isGradient(value) {
  return value && value.gradient;
}
function standalone_gradientRef(g, defs, base) {
  const type = g.gradient;
  let id = g.id,
    prefix = type === 'radial' ? standalone_patternPrefix : '';

  // check id, assign default values as needed
  if (!id) {
    id = g.id = 'gradient_' + standalone_gradient_id++;
    if (type === 'radial') {
      g.x1 = standalone_vega_scenegraph_module_get(g.x1, 0.5);
      g.y1 = standalone_vega_scenegraph_module_get(g.y1, 0.5);
      g.r1 = standalone_vega_scenegraph_module_get(g.r1, 0);
      g.x2 = standalone_vega_scenegraph_module_get(g.x2, 0.5);
      g.y2 = standalone_vega_scenegraph_module_get(g.y2, 0.5);
      g.r2 = standalone_vega_scenegraph_module_get(g.r2, 0.5);
      prefix = standalone_patternPrefix;
    } else {
      g.x1 = standalone_vega_scenegraph_module_get(g.x1, 0);
      g.y1 = standalone_vega_scenegraph_module_get(g.y1, 0);
      g.x2 = standalone_vega_scenegraph_module_get(g.x2, 1);
      g.y2 = standalone_vega_scenegraph_module_get(g.y2, 0);
    }
  }

  // register definition
  defs[id] = g;

  // return url reference
  return 'url(' + (base || '') + '#' + prefix + id + ')';
}
function standalone_vega_scenegraph_module_get(val, def) {
  return val != null ? val : def;
}
function standalone_Gradient (p0, p1) {
  var stops = [],
    gradient;
  return gradient = {
    gradient: 'linear',
    x1: p0 ? p0[0] : 0,
    y1: p0 ? p0[1] : 0,
    x2: p1 ? p1[0] : 1,
    y2: p1 ? p1[1] : 0,
    stops: stops,
    stop: function (offset, color) {
      stops.push({
        offset: offset,
        color: color
      });
      return gradient;
    }
  };
}

const standalone_lookup = {
  'basis': {
    curve: standalone_basis
  },
  'basis-closed': {
    curve: standalone_basisClosed
  },
  'basis-open': {
    curve: standalone_basisOpen
  },
  'bundle': {
    curve: standalone_bundle,
    tension: 'beta',
    value: 0.85
  },
  'cardinal': {
    curve: standalone_cardinal,
    tension: 'tension',
    value: 0
  },
  'cardinal-open': {
    curve: standalone_cardinalOpen,
    tension: 'tension',
    value: 0
  },
  'cardinal-closed': {
    curve: standalone_cardinalClosed,
    tension: 'tension',
    value: 0
  },
  'catmull-rom': {
    curve: standalone_catmullRom,
    tension: 'alpha',
    value: 0.5
  },
  'catmull-rom-closed': {
    curve: standalone_catmullRomClosed,
    tension: 'alpha',
    value: 0.5
  },
  'catmull-rom-open': {
    curve: standalone_catmullRomOpen,
    tension: 'alpha',
    value: 0.5
  },
  'linear': {
    curve: standalone_curve_linear
  },
  'linear-closed': {
    curve: standalone_linearClosed
  },
  'monotone': {
    horizontal: standalone_monotoneY,
    vertical: standalone_monotoneX
  },
  'natural': {
    curve: standalone_natural
  },
  'step': {
    curve: standalone_step
  },
  'step-after': {
    curve: standalone_stepAfter
  },
  'step-before': {
    curve: standalone_stepBefore
  }
};
function standalone_curves(type, orientation, tension) {
  var entry = standalone_vega_util_module_has(standalone_lookup, type) && standalone_lookup[type],
    curve = null;
  if (entry) {
    curve = entry.curve || entry[orientation || 'vertical'];
    if (entry.tension && tension != null) {
      curve = curve[entry.tension](tension);
    }
  }
  return curve;
}

const standalone_paramCounts = {
  m: 2,
  l: 2,
  h: 1,
  v: 1,
  z: 0,
  c: 6,
  s: 4,
  q: 4,
  t: 2,
  a: 7
};
const standalone_commandPattern = /[mlhvzcsqta]([^mlhvzcsqta]+|$)/gi;
const standalone_numberPattern = /^[+-]?(([0-9]*\.[0-9]+)|([0-9]+\.)|([0-9]+))([eE][+-]?[0-9]+)?/;
const standalone_spacePattern = /^((\s+,?\s*)|(,\s*))/;
const standalone_flagPattern = /^[01]/;
function standalone_vega_scenegraph_module_parse(path) {
  const commands = [];
  const matches = path.match(standalone_commandPattern) || [];
  matches.forEach(str => {
    let cmd = str[0];
    const type = cmd.toLowerCase();

    // parse parameters
    const paramCount = standalone_paramCounts[type];
    const params = standalone_parseParams(type, paramCount, str.slice(1).trim());
    const count = params.length;

    // error checking based on parameter count
    if (count < paramCount || count && count % paramCount !== 0) {
      throw Error('Invalid SVG path, incorrect parameter count');
    }

    // register the command
    commands.push([cmd, ...params.slice(0, paramCount)]);

    // exit now if we're done, also handles zero-param 'z'
    if (count === paramCount) {
      return;
    }

    // handle implicit line-to
    if (type === 'm') {
      cmd = cmd === 'M' ? 'L' : 'l';
    }

    // repeat command when given extended param list
    for (let i = paramCount; i < count; i += paramCount) {
      commands.push([cmd, ...params.slice(i, i + paramCount)]);
    }
  });
  return commands;
}
function standalone_parseParams(type, paramCount, segment) {
  const params = [];
  for (let index = 0; paramCount && index < segment.length;) {
    for (let i = 0; i < paramCount; ++i) {
      const pattern = type === 'a' && (i === 3 || i === 4) ? standalone_flagPattern : standalone_numberPattern;
      const match = segment.slice(index).match(pattern);
      if (match === null) {
        throw Error('Invalid SVG path, incorrect parameter type');
      }
      index += match[0].length;
      params.push(+match[0]);
      const ws = segment.slice(index).match(standalone_spacePattern);
      if (ws !== null) {
        index += ws[0].length;
      }
    }
  }
  return params;
}

const standalone_DegToRad = Math.PI / 180;
const standalone_Epsilon = 1e-14;
const standalone_HalfPi = Math.PI / 2;
const standalone_Tau = Math.PI * 2;
const standalone_HalfSqrt3 = Math.sqrt(3) / 2;

var standalone_segmentCache = {};
var standalone_bezierCache = {};
var standalone_join = [].join;

// Copied from Inkscape svgtopdf, thanks!
function standalone_segments(x, y, rx, ry, large, sweep, rotateX, ox, oy) {
  const key = standalone_join.call(arguments);
  if (standalone_segmentCache[key]) {
    return standalone_segmentCache[key];
  }
  const th = rotateX * standalone_DegToRad;
  const sin_th = Math.sin(th);
  const cos_th = Math.cos(th);
  rx = Math.abs(rx);
  ry = Math.abs(ry);
  const px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5;
  const py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5;
  let pl = px * px / (rx * rx) + py * py / (ry * ry);
  if (pl > 1) {
    pl = Math.sqrt(pl);
    rx *= pl;
    ry *= pl;
  }
  const a00 = cos_th / rx;
  const a01 = sin_th / rx;
  const a10 = -sin_th / ry;
  const a11 = cos_th / ry;
  const x0 = a00 * ox + a01 * oy;
  const y0 = a10 * ox + a11 * oy;
  const x1 = a00 * x + a01 * y;
  const y1 = a10 * x + a11 * y;
  const d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
  let sfactor_sq = 1 / d - 0.25;
  if (sfactor_sq < 0) sfactor_sq = 0;
  let sfactor = Math.sqrt(sfactor_sq);
  if (sweep == large) sfactor = -sfactor;
  const xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);
  const yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);
  const th0 = Math.atan2(y0 - yc, x0 - xc);
  const th1 = Math.atan2(y1 - yc, x1 - xc);
  let th_arc = th1 - th0;
  if (th_arc < 0 && sweep === 1) {
    th_arc += standalone_Tau;
  } else if (th_arc > 0 && sweep === 0) {
    th_arc -= standalone_Tau;
  }
  const segs = Math.ceil(Math.abs(th_arc / (standalone_HalfPi + 0.001)));
  const result = [];
  for (let i = 0; i < segs; ++i) {
    const th2 = th0 + i * th_arc / segs;
    const th3 = th0 + (i + 1) * th_arc / segs;
    result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th];
  }
  return standalone_segmentCache[key] = result;
}
function standalone_bezier(params) {
  const key = standalone_join.call(params);
  if (standalone_bezierCache[key]) {
    return standalone_bezierCache[key];
  }
  var cx = params[0],
    cy = params[1],
    th0 = params[2],
    th1 = params[3],
    rx = params[4],
    ry = params[5],
    sin_th = params[6],
    cos_th = params[7];
  const a00 = cos_th * rx;
  const a01 = -sin_th * ry;
  const a10 = sin_th * rx;
  const a11 = cos_th * ry;
  const cos_th0 = Math.cos(th0);
  const sin_th0 = Math.sin(th0);
  const cos_th1 = Math.cos(th1);
  const sin_th1 = Math.sin(th1);
  const th_half = 0.5 * (th1 - th0);
  const sin_th_h2 = Math.sin(th_half * 0.5);
  const t = 8 / 3 * sin_th_h2 * sin_th_h2 / Math.sin(th_half);
  const x1 = cx + cos_th0 - t * sin_th0;
  const y1 = cy + sin_th0 + t * cos_th0;
  const x3 = cx + cos_th1;
  const y3 = cy + sin_th1;
  const x2 = x3 + t * sin_th1;
  const y2 = y3 - t * cos_th1;
  return standalone_bezierCache[key] = [a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3];
}

const standalone_temp = ['l', 0, 0, 0, 0, 0, 0, 0];
function standalone_scale$1(current, sX, sY) {
  const c = standalone_temp[0] = current[0];
  if (c === 'a' || c === 'A') {
    standalone_temp[1] = sX * current[1];
    standalone_temp[2] = sY * current[2];
    standalone_temp[3] = current[3];
    standalone_temp[4] = current[4];
    standalone_temp[5] = current[5];
    standalone_temp[6] = sX * current[6];
    standalone_temp[7] = sY * current[7];
  } else if (c === 'h' || c === 'H') {
    standalone_temp[1] = sX * current[1];
  } else if (c === 'v' || c === 'V') {
    standalone_temp[1] = sY * current[1];
  } else {
    for (var i = 1, n = current.length; i < n; ++i) {
      standalone_temp[i] = (i % 2 == 1 ? sX : sY) * current[i];
    }
  }
  return standalone_temp;
}
function standalone_pathRender (context, path, l, t, sX, sY) {
  var current,
    // current instruction
    previous = null,
    x = 0,
    // current x
    y = 0,
    // current y
    controlX = 0,
    // current control point x
    controlY = 0,
    // current control point y
    tempX,
    tempY,
    tempControlX,
    tempControlY,
    anchorX = 0,
    anchorY = 0;
  if (l == null) l = 0;
  if (t == null) t = 0;
  if (sX == null) sX = 1;
  if (sY == null) sY = sX;
  if (context.beginPath) context.beginPath();
  for (var i = 0, len = path.length; i < len; ++i) {
    current = path[i];
    if (sX !== 1 || sY !== 1) {
      current = standalone_scale$1(current, sX, sY);
    }
    switch (current[0]) {
      // first letter

      case 'l':
        // lineto, relative
        x += current[1];
        y += current[2];
        context.lineTo(x + l, y + t);
        break;
      case 'L':
        // lineto, absolute
        x = current[1];
        y = current[2];
        context.lineTo(x + l, y + t);
        break;
      case 'h':
        // horizontal lineto, relative
        x += current[1];
        context.lineTo(x + l, y + t);
        break;
      case 'H':
        // horizontal lineto, absolute
        x = current[1];
        context.lineTo(x + l, y + t);
        break;
      case 'v':
        // vertical lineto, relative
        y += current[1];
        context.lineTo(x + l, y + t);
        break;
      case 'V':
        // verical lineto, absolute
        y = current[1];
        context.lineTo(x + l, y + t);
        break;
      case 'm':
        // moveTo, relative
        x += current[1];
        y += current[2];
        anchorX = x;
        anchorY = y;
        context.moveTo(x + l, y + t);
        break;
      case 'M':
        // moveTo, absolute
        x = current[1];
        y = current[2];
        anchorX = x;
        anchorY = y;
        context.moveTo(x + l, y + t);
        break;
      case 'c':
        // bezierCurveTo, relative
        tempX = x + current[5];
        tempY = y + current[6];
        controlX = x + current[3];
        controlY = y + current[4];
        context.bezierCurveTo(x + current[1] + l,
        // x1
        y + current[2] + t,
        // y1
        controlX + l,
        // x2
        controlY + t,
        // y2
        tempX + l, tempY + t);
        x = tempX;
        y = tempY;
        break;
      case 'C':
        // bezierCurveTo, absolute
        x = current[5];
        y = current[6];
        controlX = current[3];
        controlY = current[4];
        context.bezierCurveTo(current[1] + l, current[2] + t, controlX + l, controlY + t, x + l, y + t);
        break;
      case 's':
        // shorthand cubic bezierCurveTo, relative
        // transform to absolute x,y
        tempX = x + current[3];
        tempY = y + current[4];
        // calculate reflection of previous control points
        controlX = 2 * x - controlX;
        controlY = 2 * y - controlY;
        context.bezierCurveTo(controlX + l, controlY + t, x + current[1] + l, y + current[2] + t, tempX + l, tempY + t);

        // set control point to 2nd one of this command
        // the first control point is assumed to be the reflection of
        // the second control point on the previous command relative
        // to the current point.
        controlX = x + current[1];
        controlY = y + current[2];
        x = tempX;
        y = tempY;
        break;
      case 'S':
        // shorthand cubic bezierCurveTo, absolute
        tempX = current[3];
        tempY = current[4];
        // calculate reflection of previous control points
        controlX = 2 * x - controlX;
        controlY = 2 * y - controlY;
        context.bezierCurveTo(controlX + l, controlY + t, current[1] + l, current[2] + t, tempX + l, tempY + t);
        x = tempX;
        y = tempY;
        // set control point to 2nd one of this command
        // the first control point is assumed to be the reflection of
        // the second control point on the previous command relative
        // to the current point.
        controlX = current[1];
        controlY = current[2];
        break;
      case 'q':
        // quadraticCurveTo, relative
        // transform to absolute x,y
        tempX = x + current[3];
        tempY = y + current[4];
        controlX = x + current[1];
        controlY = y + current[2];
        context.quadraticCurveTo(controlX + l, controlY + t, tempX + l, tempY + t);
        x = tempX;
        y = tempY;
        break;
      case 'Q':
        // quadraticCurveTo, absolute
        tempX = current[3];
        tempY = current[4];
        context.quadraticCurveTo(current[1] + l, current[2] + t, tempX + l, tempY + t);
        x = tempX;
        y = tempY;
        controlX = current[1];
        controlY = current[2];
        break;
      case 't':
        // shorthand quadraticCurveTo, relative

        // transform to absolute x,y
        tempX = x + current[1];
        tempY = y + current[2];
        if (previous[0].match(/[QqTt]/) === null) {
          // If there is no previous command or if the previous command was not a Q, q, T or t,
          // assume the control point is coincident with the current point
          controlX = x;
          controlY = y;
        } else if (previous[0] === 't') {
          // calculate reflection of previous control points for t
          controlX = 2 * x - tempControlX;
          controlY = 2 * y - tempControlY;
        } else if (previous[0] === 'q') {
          // calculate reflection of previous control points for q
          controlX = 2 * x - controlX;
          controlY = 2 * y - controlY;
        }
        tempControlX = controlX;
        tempControlY = controlY;
        context.quadraticCurveTo(controlX + l, controlY + t, tempX + l, tempY + t);
        x = tempX;
        y = tempY;
        controlX = x + current[1];
        controlY = y + current[2];
        break;
      case 'T':
        tempX = current[1];
        tempY = current[2];

        // calculate reflection of previous control points
        controlX = 2 * x - controlX;
        controlY = 2 * y - controlY;
        context.quadraticCurveTo(controlX + l, controlY + t, tempX + l, tempY + t);
        x = tempX;
        y = tempY;
        break;
      case 'a':
        standalone_drawArc(context, x + l, y + t, [current[1], current[2], current[3], current[4], current[5], current[6] + x + l, current[7] + y + t]);
        x += current[6];
        y += current[7];
        break;
      case 'A':
        standalone_drawArc(context, x + l, y + t, [current[1], current[2], current[3], current[4], current[5], current[6] + l, current[7] + t]);
        x = current[6];
        y = current[7];
        break;
      case 'z':
      case 'Z':
        x = anchorX;
        y = anchorY;
        context.closePath();
        break;
    }
    previous = current;
  }
}
function standalone_drawArc(context, x, y, coords) {
  const seg = standalone_segments(coords[5],
  // end x
  coords[6],
  // end y
  coords[0],
  // radius x
  coords[1],
  // radius y
  coords[3],
  // large flag
  coords[4],
  // sweep flag
  coords[2],
  // rotation
  x, y);
  for (let i = 0; i < seg.length; ++i) {
    const bez = standalone_bezier(seg[i]);
    context.bezierCurveTo(bez[0], bez[1], bez[2], bez[3], bez[4], bez[5]);
  }
}

const standalone_Tan30 = 0.5773502691896257;
const standalone_builtins = {
  'circle': {
    draw: function (context, size) {
      const r = Math.sqrt(size) / 2;
      context.moveTo(r, 0);
      context.arc(0, 0, r, 0, standalone_Tau);
    }
  },
  'cross': {
    draw: function (context, size) {
      var r = Math.sqrt(size) / 2,
        s = r / 2.5;
      context.moveTo(-r, -s);
      context.lineTo(-r, s);
      context.lineTo(-s, s);
      context.lineTo(-s, r);
      context.lineTo(s, r);
      context.lineTo(s, s);
      context.lineTo(r, s);
      context.lineTo(r, -s);
      context.lineTo(s, -s);
      context.lineTo(s, -r);
      context.lineTo(-s, -r);
      context.lineTo(-s, -s);
      context.closePath();
    }
  },
  'diamond': {
    draw: function (context, size) {
      const r = Math.sqrt(size) / 2;
      context.moveTo(-r, 0);
      context.lineTo(0, -r);
      context.lineTo(r, 0);
      context.lineTo(0, r);
      context.closePath();
    }
  },
  'square': {
    draw: function (context, size) {
      var w = Math.sqrt(size),
        x = -w / 2;
      context.rect(x, x, w, w);
    }
  },
  'arrow': {
    draw: function (context, size) {
      var r = Math.sqrt(size) / 2,
        s = r / 7,
        t = r / 2.5,
        v = r / 8;
      context.moveTo(-s, r);
      context.lineTo(s, r);
      context.lineTo(s, -v);
      context.lineTo(t, -v);
      context.lineTo(0, -r);
      context.lineTo(-t, -v);
      context.lineTo(-s, -v);
      context.closePath();
    }
  },
  'wedge': {
    draw: function (context, size) {
      var r = Math.sqrt(size) / 2,
        h = standalone_HalfSqrt3 * r,
        o = h - r * standalone_Tan30,
        b = r / 4;
      context.moveTo(0, -h - o);
      context.lineTo(-b, h - o);
      context.lineTo(b, h - o);
      context.closePath();
    }
  },
  'triangle': {
    draw: function (context, size) {
      var r = Math.sqrt(size) / 2,
        h = standalone_HalfSqrt3 * r,
        o = h - r * standalone_Tan30;
      context.moveTo(0, -h - o);
      context.lineTo(-r, h - o);
      context.lineTo(r, h - o);
      context.closePath();
    }
  },
  'triangle-up': {
    draw: function (context, size) {
      var r = Math.sqrt(size) / 2,
        h = standalone_HalfSqrt3 * r;
      context.moveTo(0, -h);
      context.lineTo(-r, h);
      context.lineTo(r, h);
      context.closePath();
    }
  },
  'triangle-down': {
    draw: function (context, size) {
      var r = Math.sqrt(size) / 2,
        h = standalone_HalfSqrt3 * r;
      context.moveTo(0, h);
      context.lineTo(-r, -h);
      context.lineTo(r, -h);
      context.closePath();
    }
  },
  'triangle-right': {
    draw: function (context, size) {
      var r = Math.sqrt(size) / 2,
        h = standalone_HalfSqrt3 * r;
      context.moveTo(h, 0);
      context.lineTo(-h, -r);
      context.lineTo(-h, r);
      context.closePath();
    }
  },
  'triangle-left': {
    draw: function (context, size) {
      var r = Math.sqrt(size) / 2,
        h = standalone_HalfSqrt3 * r;
      context.moveTo(-h, 0);
      context.lineTo(h, -r);
      context.lineTo(h, r);
      context.closePath();
    }
  },
  'stroke': {
    draw: function (context, size) {
      const r = Math.sqrt(size) / 2;
      context.moveTo(-r, 0);
      context.lineTo(r, 0);
    }
  }
};
function standalone_vega_scenegraph_module_symbols(_) {
  return standalone_vega_util_module_has(standalone_builtins, _) ? standalone_builtins[_] : standalone_customSymbol(_);
}
var standalone_custom = {};
function standalone_customSymbol(path) {
  if (!standalone_vega_util_module_has(standalone_custom, path)) {
    const parsed = standalone_vega_scenegraph_module_parse(path);
    standalone_custom[path] = {
      draw: function (context, size) {
        standalone_pathRender(context, parsed, 0, 0, Math.sqrt(size) / 2);
      }
    };
  }
  return standalone_custom[path];
}

// See http://spencermortensen.com/articles/bezier-circle/
const standalone_vega_scenegraph_module_C = 0.448084975506; // C = 1 - c

function standalone_rectangleX(d) {
  return d.x;
}
function standalone_rectangleY(d) {
  return d.y;
}
function standalone_rectangleWidth(d) {
  return d.width;
}
function standalone_rectangleHeight(d) {
  return d.height;
}
function standalone_vega_scenegraph_module_number(_) {
  return typeof _ === 'function' ? _ : () => +_;
}
function standalone_clamp(value, min, max) {
  return Math.max(min, Math.min(value, max));
}
function standalone_vg_rect () {
  var x = standalone_rectangleX,
    y = standalone_rectangleY,
    width = standalone_rectangleWidth,
    height = standalone_rectangleHeight,
    crTL = standalone_vega_scenegraph_module_number(0),
    crTR = crTL,
    crBL = crTL,
    crBR = crTL,
    context = null;
  function rectangle(_, x0, y0) {
    var buffer,
      x1 = x0 != null ? x0 : +x.call(this, _),
      y1 = y0 != null ? y0 : +y.call(this, _),
      w = +width.call(this, _),
      h = +height.call(this, _),
      s = Math.min(w, h) / 2,
      tl = standalone_clamp(+crTL.call(this, _), 0, s),
      tr = standalone_clamp(+crTR.call(this, _), 0, s),
      bl = standalone_clamp(+crBL.call(this, _), 0, s),
      br = standalone_clamp(+crBR.call(this, _), 0, s);
    if (!context) context = buffer = standalone_path();
    if (tl <= 0 && tr <= 0 && bl <= 0 && br <= 0) {
      context.rect(x1, y1, w, h);
    } else {
      var x2 = x1 + w,
        y2 = y1 + h;
      context.moveTo(x1 + tl, y1);
      context.lineTo(x2 - tr, y1);
      context.bezierCurveTo(x2 - standalone_vega_scenegraph_module_C * tr, y1, x2, y1 + standalone_vega_scenegraph_module_C * tr, x2, y1 + tr);
      context.lineTo(x2, y2 - br);
      context.bezierCurveTo(x2, y2 - standalone_vega_scenegraph_module_C * br, x2 - standalone_vega_scenegraph_module_C * br, y2, x2 - br, y2);
      context.lineTo(x1 + bl, y2);
      context.bezierCurveTo(x1 + standalone_vega_scenegraph_module_C * bl, y2, x1, y2 - standalone_vega_scenegraph_module_C * bl, x1, y2 - bl);
      context.lineTo(x1, y1 + tl);
      context.bezierCurveTo(x1, y1 + standalone_vega_scenegraph_module_C * tl, x1 + standalone_vega_scenegraph_module_C * tl, y1, x1 + tl, y1);
      context.closePath();
    }
    if (buffer) {
      context = null;
      return buffer + '' || null;
    }
  }
  rectangle.x = function (_) {
    if (arguments.length) {
      x = standalone_vega_scenegraph_module_number(_);
      return rectangle;
    } else {
      return x;
    }
  };
  rectangle.y = function (_) {
    if (arguments.length) {
      y = standalone_vega_scenegraph_module_number(_);
      return rectangle;
    } else {
      return y;
    }
  };
  rectangle.width = function (_) {
    if (arguments.length) {
      width = standalone_vega_scenegraph_module_number(_);
      return rectangle;
    } else {
      return width;
    }
  };
  rectangle.height = function (_) {
    if (arguments.length) {
      height = standalone_vega_scenegraph_module_number(_);
      return rectangle;
    } else {
      return height;
    }
  };
  rectangle.cornerRadius = function (tl, tr, br, bl) {
    if (arguments.length) {
      crTL = standalone_vega_scenegraph_module_number(tl);
      crTR = tr != null ? standalone_vega_scenegraph_module_number(tr) : crTL;
      crBR = br != null ? standalone_vega_scenegraph_module_number(br) : crTL;
      crBL = bl != null ? standalone_vega_scenegraph_module_number(bl) : crTR;
      return rectangle;
    } else {
      return crTL;
    }
  };
  rectangle.context = function (_) {
    if (arguments.length) {
      context = _ == null ? null : _;
      return rectangle;
    } else {
      return context;
    }
  };
  return rectangle;
}

function standalone_vg_trail () {
  var x,
    y,
    size,
    defined,
    context = null,
    ready,
    x1,
    y1,
    r1;
  function point(x2, y2, w2) {
    const r2 = w2 / 2;
    if (ready) {
      var ux = y1 - y2,
        uy = x2 - x1;
      if (ux || uy) {
        // get normal vector
        var ud = Math.hypot(ux, uy),
          rx = (ux /= ud) * r1,
          ry = (uy /= ud) * r1,
          t = Math.atan2(uy, ux);

        // draw segment
        context.moveTo(x1 - rx, y1 - ry);
        context.lineTo(x2 - ux * r2, y2 - uy * r2);
        context.arc(x2, y2, r2, t - Math.PI, t);
        context.lineTo(x1 + rx, y1 + ry);
        context.arc(x1, y1, r1, t, t + Math.PI);
      } else {
        context.arc(x2, y2, r2, 0, standalone_Tau);
      }
      context.closePath();
    } else {
      ready = 1;
    }
    x1 = x2;
    y1 = y2;
    r1 = r2;
  }
  function trail(data) {
    var i,
      n = data.length,
      d,
      defined0 = false,
      buffer;
    if (context == null) context = buffer = standalone_path();
    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) ready = 0;
      }
      if (defined0) point(+x(d, i, data), +y(d, i, data), +size(d, i, data));
    }
    if (buffer) {
      context = null;
      return buffer + '' || null;
    }
  }
  trail.x = function (_) {
    if (arguments.length) {
      x = _;
      return trail;
    } else {
      return x;
    }
  };
  trail.y = function (_) {
    if (arguments.length) {
      y = _;
      return trail;
    } else {
      return y;
    }
  };
  trail.size = function (_) {
    if (arguments.length) {
      size = _;
      return trail;
    } else {
      return size;
    }
  };
  trail.defined = function (_) {
    if (arguments.length) {
      defined = _;
      return trail;
    } else {
      return defined;
    }
  };
  trail.context = function (_) {
    if (arguments.length) {
      if (_ == null) {
        context = null;
      } else {
        context = _;
      }
      return trail;
    } else {
      return context;
    }
  };
  return trail;
}

function standalone_value$1(a, b) {
  return a != null ? a : b;
}
const standalone_x = item => item.x || 0,
  standalone_y = item => item.y || 0,
  standalone_w = item => item.width || 0,
  standalone_h = item => item.height || 0,
  standalone_xw = item => (item.x || 0) + (item.width || 0),
  standalone_yh = item => (item.y || 0) + (item.height || 0),
  standalone_sa = item => item.startAngle || 0,
  standalone_ea = item => item.endAngle || 0,
  standalone_pa = item => item.padAngle || 0,
  standalone_ir = item => item.innerRadius || 0,
  standalone_or = item => item.outerRadius || 0,
  standalone_cr = item => item.cornerRadius || 0,
  standalone_tl = item => standalone_value$1(item.cornerRadiusTopLeft, item.cornerRadius) || 0,
  standalone_tr = item => standalone_value$1(item.cornerRadiusTopRight, item.cornerRadius) || 0,
  standalone_br = item => standalone_value$1(item.cornerRadiusBottomRight, item.cornerRadius) || 0,
  standalone_bl = item => standalone_value$1(item.cornerRadiusBottomLeft, item.cornerRadius) || 0,
  standalone_sz = item => standalone_value$1(item.size, 64),
  standalone_ts = item => item.size || 1,
  standalone_def = item => !(item.defined === false),
  standalone_type = item => standalone_vega_scenegraph_module_symbols(item.shape || 'circle');
const standalone_arcShape = standalone_arc().startAngle(standalone_sa).endAngle(standalone_ea).padAngle(standalone_pa).innerRadius(standalone_ir).outerRadius(standalone_or).cornerRadius(standalone_cr),
  standalone_areavShape = standalone_src_area().x(standalone_x).y1(standalone_y).y0(standalone_yh).defined(standalone_def),
  standalone_areahShape = standalone_src_area().y(standalone_y).x1(standalone_x).x0(standalone_xw).defined(standalone_def),
  standalone_lineShape = standalone_line().x(standalone_x).y(standalone_y).defined(standalone_def),
  standalone_rectShape = standalone_vg_rect().x(standalone_x).y(standalone_y).width(standalone_w).height(standalone_h).cornerRadius(standalone_tl, standalone_tr, standalone_br, standalone_bl),
  standalone_symbolShape = standalone_symbol_Symbol().type(standalone_type).size(standalone_sz),
  standalone_trailShape = standalone_vg_trail().x(standalone_x).y(standalone_y).defined(standalone_def).size(standalone_ts);
function standalone_hasCornerRadius(item) {
  return item.cornerRadius || item.cornerRadiusTopLeft || item.cornerRadiusTopRight || item.cornerRadiusBottomRight || item.cornerRadiusBottomLeft;
}
function standalone_arc$1(context, item) {
  return standalone_arcShape.context(context)(item);
}
function standalone_area$1(context, items) {
  const item = items[0],
    interp = item.interpolate || 'linear';
  return (item.orient === 'horizontal' ? standalone_areahShape : standalone_areavShape).curve(standalone_curves(interp, item.orient, item.tension)).context(context)(items);
}
function standalone_line$1(context, items) {
  const item = items[0],
    interp = item.interpolate || 'linear';
  return standalone_lineShape.curve(standalone_curves(interp, item.orient, item.tension)).context(context)(items);
}
function standalone_rectangle(context, item, x, y) {
  return standalone_rectShape.context(context)(item, x, y);
}
function standalone_shape$1(context, item) {
  return (item.mark.shape || item.shape).context(context)(item);
}
function standalone_symbol$1(context, item) {
  return standalone_symbolShape.context(context)(item);
}
function standalone_trail$1(context, items) {
  return standalone_trailShape.context(context)(items);
}

var standalone_clip_id = 1;
function standalone_resetSVGClipId() {
  standalone_clip_id = 1;
}
function standalone_clip$1 (renderer, item, size) {
  var clip = item.clip,
    defs = renderer._defs,
    id = item.clip_id || (item.clip_id = 'clip' + standalone_clip_id++),
    c = defs.clipping[id] || (defs.clipping[id] = {
      id: id
    });
  if (standalone_vega_util_module_isFunction(clip)) {
    c.path = clip(null);
  } else if (standalone_hasCornerRadius(size)) {
    c.path = standalone_rectangle(null, size, 0, 0);
  } else {
    c.width = size.width || 0;
    c.height = size.height || 0;
  }
  return 'url(#' + id + ')';
}

function standalone_Bounds(b) {
  this.clear();
  if (b) this.union(b);
}
standalone_Bounds.prototype = {
  clone() {
    return new standalone_Bounds(this);
  },
  clear() {
    this.x1 = +Number.MAX_VALUE;
    this.y1 = +Number.MAX_VALUE;
    this.x2 = -Number.MAX_VALUE;
    this.y2 = -Number.MAX_VALUE;
    return this;
  },
  empty() {
    return this.x1 === +Number.MAX_VALUE && this.y1 === +Number.MAX_VALUE && this.x2 === -Number.MAX_VALUE && this.y2 === -Number.MAX_VALUE;
  },
  equals(b) {
    return this.x1 === b.x1 && this.y1 === b.y1 && this.x2 === b.x2 && this.y2 === b.y2;
  },
  set(x1, y1, x2, y2) {
    if (x2 < x1) {
      this.x2 = x1;
      this.x1 = x2;
    } else {
      this.x1 = x1;
      this.x2 = x2;
    }
    if (y2 < y1) {
      this.y2 = y1;
      this.y1 = y2;
    } else {
      this.y1 = y1;
      this.y2 = y2;
    }
    return this;
  },
  add(x, y) {
    if (x < this.x1) this.x1 = x;
    if (y < this.y1) this.y1 = y;
    if (x > this.x2) this.x2 = x;
    if (y > this.y2) this.y2 = y;
    return this;
  },
  expand(d) {
    this.x1 -= d;
    this.y1 -= d;
    this.x2 += d;
    this.y2 += d;
    return this;
  },
  round() {
    this.x1 = Math.floor(this.x1);
    this.y1 = Math.floor(this.y1);
    this.x2 = Math.ceil(this.x2);
    this.y2 = Math.ceil(this.y2);
    return this;
  },
  scale(s) {
    this.x1 *= s;
    this.y1 *= s;
    this.x2 *= s;
    this.y2 *= s;
    return this;
  },
  translate(dx, dy) {
    this.x1 += dx;
    this.x2 += dx;
    this.y1 += dy;
    this.y2 += dy;
    return this;
  },
  rotate(angle, x, y) {
    const p = this.rotatedPoints(angle, x, y);
    return this.clear().add(p[0], p[1]).add(p[2], p[3]).add(p[4], p[5]).add(p[6], p[7]);
  },
  rotatedPoints(angle, x, y) {
    var {
        x1,
        y1,
        x2,
        y2
      } = this,
      cos = Math.cos(angle),
      sin = Math.sin(angle),
      cx = x - x * cos + y * sin,
      cy = y - x * sin - y * cos;
    return [cos * x1 - sin * y1 + cx, sin * x1 + cos * y1 + cy, cos * x1 - sin * y2 + cx, sin * x1 + cos * y2 + cy, cos * x2 - sin * y1 + cx, sin * x2 + cos * y1 + cy, cos * x2 - sin * y2 + cx, sin * x2 + cos * y2 + cy];
  },
  union(b) {
    if (b.x1 < this.x1) this.x1 = b.x1;
    if (b.y1 < this.y1) this.y1 = b.y1;
    if (b.x2 > this.x2) this.x2 = b.x2;
    if (b.y2 > this.y2) this.y2 = b.y2;
    return this;
  },
  intersect(b) {
    if (b.x1 > this.x1) this.x1 = b.x1;
    if (b.y1 > this.y1) this.y1 = b.y1;
    if (b.x2 < this.x2) this.x2 = b.x2;
    if (b.y2 < this.y2) this.y2 = b.y2;
    return this;
  },
  encloses(b) {
    return b && this.x1 <= b.x1 && this.x2 >= b.x2 && this.y1 <= b.y1 && this.y2 >= b.y2;
  },
  alignsWith(b) {
    return b && (this.x1 == b.x1 || this.x2 == b.x2 || this.y1 == b.y1 || this.y2 == b.y2);
  },
  intersects(b) {
    return b && !(this.x2 < b.x1 || this.x1 > b.x2 || this.y2 < b.y1 || this.y1 > b.y2);
  },
  contains(x, y) {
    return !(x < this.x1 || x > this.x2 || y < this.y1 || y > this.y2);
  },
  width() {
    return this.x2 - this.x1;
  },
  height() {
    return this.y2 - this.y1;
  }
};

function standalone_Item(mark) {
  this.mark = mark;
  this.bounds = this.bounds || new standalone_Bounds();
}

function standalone_GroupItem(mark) {
  standalone_Item.call(this, mark);
  this.items = this.items || [];
}
standalone_inherits(standalone_GroupItem, standalone_Item);

class standalone_ResourceLoader {
  constructor(customLoader) {
    this._pending = 0;
    this._loader = customLoader || standalone_loader();
  }
  pending() {
    return this._pending;
  }
  sanitizeURL(uri) {
    const loader = this;
    standalone_increment(loader);
    return loader._loader.sanitize(uri, {
      context: 'href'
    }).then(opt => {
      standalone_decrement(loader);
      return opt;
    }).catch(() => {
      standalone_decrement(loader);
      return null;
    });
  }
  loadImage(uri) {
    const loader = this,
      Image = standalone_domImage();
    standalone_increment(loader);
    return loader._loader.sanitize(uri, {
      context: 'image'
    }).then(opt => {
      const url = opt.href;
      if (!url || !Image) throw {
        url: url
      };
      const img = new Image();

      // set crossOrigin only if cors is defined; empty string sets anonymous mode
      // https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/crossOrigin
      const cors = standalone_vega_util_module_has(opt, 'crossOrigin') ? opt.crossOrigin : 'anonymous';
      if (cors != null) img.crossOrigin = cors;

      // attempt to load image resource
      img.onload = () => standalone_decrement(loader);
      img.onerror = () => standalone_decrement(loader);
      img.src = url;
      return img;
    }).catch(e => {
      standalone_decrement(loader);
      return {
        complete: false,
        width: 0,
        height: 0,
        src: e && e.url || ''
      };
    });
  }
  ready() {
    const loader = this;
    return new Promise(accept => {
      function poll(value) {
        if (!loader.pending()) accept(value);else setTimeout(() => {
          poll(true);
        }, 10);
      }
      poll(false);
    });
  }
}
function standalone_increment(loader) {
  loader._pending += 1;
}
function standalone_decrement(loader) {
  loader._pending -= 1;
}

function standalone_boundStroke (bounds, item, miter) {
  if (item.stroke && item.opacity !== 0 && item.strokeOpacity !== 0) {
    const sw = item.strokeWidth != null ? +item.strokeWidth : 1;
    bounds.expand(sw + (miter ? standalone_miterAdjustment(item, sw) : 0));
  }
  return bounds;
}
function standalone_miterAdjustment(item, strokeWidth) {
  // TODO: more sophisticated adjustment? Or miter support in boundContext?
  return item.strokeJoin && item.strokeJoin !== 'miter' ? 0 : strokeWidth;
}

const standalone_circleThreshold = standalone_Tau - 1e-8;
let standalone_bounds, standalone_lx, standalone_ly, standalone_rot, standalone_ma, standalone_mb, standalone_mc, standalone_md;
const standalone_vega_scenegraph_module_add = (x, y) => standalone_bounds.add(x, y);
const standalone_addL = (x, y) => standalone_vega_scenegraph_module_add(standalone_lx = x, standalone_ly = y);
const standalone_addX = x => standalone_vega_scenegraph_module_add(x, standalone_bounds.y1);
const standalone_addY = y => standalone_vega_scenegraph_module_add(standalone_bounds.x1, y);
const standalone_px = (x, y) => standalone_ma * x + standalone_mc * y;
const standalone_py = (x, y) => standalone_mb * x + standalone_md * y;
const standalone_addp = (x, y) => standalone_vega_scenegraph_module_add(standalone_px(x, y), standalone_py(x, y));
const standalone_addpL = (x, y) => standalone_addL(standalone_px(x, y), standalone_py(x, y));
function standalone_boundContext (_, deg) {
  standalone_bounds = _;
  if (deg) {
    standalone_rot = deg * standalone_DegToRad;
    standalone_ma = standalone_md = Math.cos(standalone_rot);
    standalone_mb = Math.sin(standalone_rot);
    standalone_mc = -standalone_mb;
  } else {
    standalone_ma = standalone_md = 1;
    standalone_rot = standalone_mb = standalone_mc = 0;
  }
  return standalone_context$1;
}
const standalone_context$1 = {
  beginPath() {},
  closePath() {},
  moveTo: standalone_addpL,
  lineTo: standalone_addpL,
  rect(x, y, w, h) {
    if (standalone_rot) {
      standalone_addp(x + w, y);
      standalone_addp(x + w, y + h);
      standalone_addp(x, y + h);
      standalone_addpL(x, y);
    } else {
      standalone_vega_scenegraph_module_add(x + w, y + h);
      standalone_addL(x, y);
    }
  },
  quadraticCurveTo(x1, y1, x2, y2) {
    const px1 = standalone_px(x1, y1),
      py1 = standalone_py(x1, y1),
      px2 = standalone_px(x2, y2),
      py2 = standalone_py(x2, y2);
    standalone_quadExtrema(standalone_lx, px1, px2, standalone_addX);
    standalone_quadExtrema(standalone_ly, py1, py2, standalone_addY);
    standalone_addL(px2, py2);
  },
  bezierCurveTo(x1, y1, x2, y2, x3, y3) {
    const px1 = standalone_px(x1, y1),
      py1 = standalone_py(x1, y1),
      px2 = standalone_px(x2, y2),
      py2 = standalone_py(x2, y2),
      px3 = standalone_px(x3, y3),
      py3 = standalone_py(x3, y3);
    standalone_cubicExtrema(standalone_lx, px1, px2, px3, standalone_addX);
    standalone_cubicExtrema(standalone_ly, py1, py2, py3, standalone_addY);
    standalone_addL(px3, py3);
  },
  arc(cx, cy, r, sa, ea, ccw) {
    sa += standalone_rot;
    ea += standalone_rot;

    // store last point on path
    standalone_lx = r * Math.cos(ea) + cx;
    standalone_ly = r * Math.sin(ea) + cy;
    if (Math.abs(ea - sa) > standalone_circleThreshold) {
      // treat as full circle
      standalone_vega_scenegraph_module_add(cx - r, cy - r);
      standalone_vega_scenegraph_module_add(cx + r, cy + r);
    } else {
      const update = a => standalone_vega_scenegraph_module_add(r * Math.cos(a) + cx, r * Math.sin(a) + cy);
      let s, i;

      // sample end points
      update(sa);
      update(ea);

      // sample interior points aligned with 90 degrees
      if (ea !== sa) {
        sa = sa % standalone_Tau;
        if (sa < 0) sa += standalone_Tau;
        ea = ea % standalone_Tau;
        if (ea < 0) ea += standalone_Tau;
        if (ea < sa) {
          ccw = !ccw; // flip direction
          s = sa;
          sa = ea;
          ea = s; // swap end-points
        }
        if (ccw) {
          ea -= standalone_Tau;
          s = sa - sa % standalone_HalfPi;
          for (i = 0; i < 4 && s > ea; ++i, s -= standalone_HalfPi) update(s);
        } else {
          s = sa - sa % standalone_HalfPi + standalone_HalfPi;
          for (i = 0; i < 4 && s < ea; ++i, s = s + standalone_HalfPi) update(s);
        }
      }
    }
  }
};
function standalone_quadExtrema(x0, x1, x2, cb) {
  const t = (x0 - x1) / (x0 + x2 - 2 * x1);
  if (0 < t && t < 1) cb(x0 + (x1 - x0) * t);
}
function standalone_cubicExtrema(x0, x1, x2, x3, cb) {
  const a = x3 - x0 + 3 * x1 - 3 * x2,
    b = x0 + x2 - 2 * x1,
    c = x0 - x1;
  let t0 = 0,
    t1 = 0,
    r;

  // solve for parameter t
  if (Math.abs(a) > standalone_Epsilon) {
    // quadratic equation
    r = b * b + c * a;
    if (r >= 0) {
      r = Math.sqrt(r);
      t0 = (-b + r) / a;
      t1 = (-b - r) / a;
    }
  } else {
    // linear equation
    t0 = 0.5 * c / b;
  }

  // calculate position
  if (0 < t0 && t0 < 1) cb(standalone_cubic(t0, x0, x1, x2, x3));
  if (0 < t1 && t1 < 1) cb(standalone_cubic(t1, x0, x1, x2, x3));
}
function standalone_cubic(t, x0, x1, x2, x3) {
  const s = 1 - t,
    s2 = s * s,
    t2 = t * t;
  return s2 * s * x0 + 3 * s2 * t * x1 + 3 * s * t2 * x2 + t2 * t * x3;
}

var standalone_context = (standalone_context = standalone_domCanvas(1, 1)) ? standalone_context.getContext('2d') : null;

const standalone_b = new standalone_Bounds();
function standalone_intersectPath(draw) {
  return function (item, brush) {
    // rely on (inaccurate) bounds intersection if no context
    if (!standalone_context) return true;

    // add path to offscreen graphics context
    draw(standalone_context, item);

    // get bounds intersection region
    standalone_b.clear().union(item.bounds).intersect(brush).round();
    const {
      x1,
      y1,
      x2,
      y2
    } = standalone_b;

    // iterate over intersection region
    // perform fine grained inclusion test
    for (let y = y1; y <= y2; ++y) {
      for (let x = x1; x <= x2; ++x) {
        if (standalone_context.isPointInPath(x, y)) {
          return true;
        }
      }
    }

    // false if no hits in intersection region
    return false;
  };
}
function standalone_intersectPoint(item, box) {
  return box.contains(item.x || 0, item.y || 0);
}
function standalone_intersectRect(item, box) {
  const x = item.x || 0,
    y = item.y || 0,
    w = item.width || 0,
    h = item.height || 0;
  return box.intersects(standalone_b.set(x, y, x + w, y + h));
}
function standalone_intersectRule(item, box) {
  const x = item.x || 0,
    y = item.y || 0,
    x2 = item.x2 != null ? item.x2 : x,
    y2 = item.y2 != null ? item.y2 : y;
  return standalone_intersectBoxLine(box, x, y, x2, y2);
}
function standalone_intersectBoxLine(box, x, y, u, v) {
  const {
      x1,
      y1,
      x2,
      y2
    } = box,
    dx = u - x,
    dy = v - y;
  let t0 = 0,
    t1 = 1,
    p,
    q,
    r,
    e;
  for (e = 0; e < 4; ++e) {
    if (e === 0) {
      p = -dx;
      q = -(x1 - x);
    }
    if (e === 1) {
      p = dx;
      q = x2 - x;
    }
    if (e === 2) {
      p = -dy;
      q = -(y1 - y);
    }
    if (e === 3) {
      p = dy;
      q = y2 - y;
    }
    if (Math.abs(p) < 1e-10 && q < 0) return false;
    r = q / p;
    if (p < 0) {
      if (r > t1) return false;else if (r > t0) t0 = r;
    } else if (p > 0) {
      if (r < t0) return false;else if (r < t1) t1 = r;
    }
  }
  return true;
}

function standalone_blend (context, item) {
  context.globalCompositeOperation = item.blend || 'source-over';
}

function standalone_vega_scenegraph_module_value (value, dflt) {
  return value == null ? dflt : value;
}

function standalone_addStops(gradient, stops) {
  const n = stops.length;
  for (let i = 0; i < n; ++i) {
    gradient.addColorStop(stops[i].offset, stops[i].color);
  }
  return gradient;
}
function standalone_gradient (context, spec, bounds) {
  const w = bounds.width(),
    h = bounds.height();
  let gradient;
  if (spec.gradient === 'radial') {
    gradient = context.createRadialGradient(bounds.x1 + standalone_vega_scenegraph_module_value(spec.x1, 0.5) * w, bounds.y1 + standalone_vega_scenegraph_module_value(spec.y1, 0.5) * h, Math.max(w, h) * standalone_vega_scenegraph_module_value(spec.r1, 0), bounds.x1 + standalone_vega_scenegraph_module_value(spec.x2, 0.5) * w, bounds.y1 + standalone_vega_scenegraph_module_value(spec.y2, 0.5) * h, Math.max(w, h) * standalone_vega_scenegraph_module_value(spec.r2, 0.5));
  } else {
    // linear gradient
    const x1 = standalone_vega_scenegraph_module_value(spec.x1, 0),
      y1 = standalone_vega_scenegraph_module_value(spec.y1, 0),
      x2 = standalone_vega_scenegraph_module_value(spec.x2, 1),
      y2 = standalone_vega_scenegraph_module_value(spec.y2, 0);
    if (x1 === x2 || y1 === y2 || w === h) {
      // axis aligned: use normal gradient
      gradient = context.createLinearGradient(bounds.x1 + x1 * w, bounds.y1 + y1 * h, bounds.x1 + x2 * w, bounds.y1 + y2 * h);
    } else {
      // not axis aligned: render gradient into a pattern (#2365)
      // this allows us to use normalized bounding box coordinates
      const image = standalone_domCanvas(Math.ceil(w), Math.ceil(h)),
        ictx = image.getContext('2d');
      ictx.scale(w, h);
      ictx.fillStyle = standalone_addStops(ictx.createLinearGradient(x1, y1, x2, y2), spec.stops);
      ictx.fillRect(0, 0, w, h);
      return context.createPattern(image, 'no-repeat');
    }
  }
  return standalone_addStops(gradient, spec.stops);
}

function standalone_vega_scenegraph_module_color (context, item, value) {
  return standalone_isGradient(value) ? standalone_gradient(context, value, item.bounds) : value;
}

function standalone_fill (context, item, opacity) {
  opacity *= item.fillOpacity == null ? 1 : item.fillOpacity;
  if (opacity > 0) {
    context.globalAlpha = opacity;
    context.fillStyle = standalone_vega_scenegraph_module_color(context, item, item.fill);
    return true;
  } else {
    return false;
  }
}

var standalone_vega_scenegraph_module_Empty = [];
function standalone_stroke (context, item, opacity) {
  var lw = (lw = item.strokeWidth) != null ? lw : 1;
  if (lw <= 0) return false;
  opacity *= item.strokeOpacity == null ? 1 : item.strokeOpacity;
  if (opacity > 0) {
    context.globalAlpha = opacity;
    context.strokeStyle = standalone_vega_scenegraph_module_color(context, item, item.stroke);
    context.lineWidth = lw;
    context.lineCap = item.strokeCap || 'butt';
    context.lineJoin = item.strokeJoin || 'miter';
    context.miterLimit = item.strokeMiterLimit || 10;
    if (context.setLineDash) {
      context.setLineDash(item.strokeDash || standalone_vega_scenegraph_module_Empty);
      context.lineDashOffset = item.strokeDashOffset || 0;
    }
    return true;
  } else {
    return false;
  }
}

function standalone_vega_scenegraph_module_compare(a, b) {
  return a.zindex - b.zindex || a.index - b.index;
}
function standalone_zorder(scene) {
  if (!scene.zdirty) return scene.zitems;
  var items = scene.items,
    output = [],
    item,
    i,
    n;
  for (i = 0, n = items.length; i < n; ++i) {
    item = items[i];
    item.index = i;
    if (item.zindex) output.push(item);
  }
  scene.zdirty = false;
  return scene.zitems = output.sort(standalone_vega_scenegraph_module_compare);
}
function standalone_visit(scene, visitor) {
  var items = scene.items,
    i,
    n;
  if (!items || !items.length) return;
  const zitems = standalone_zorder(scene);
  if (zitems && zitems.length) {
    for (i = 0, n = items.length; i < n; ++i) {
      if (!items[i].zindex) visitor(items[i]);
    }
    items = zitems;
  }
  for (i = 0, n = items.length; i < n; ++i) {
    visitor(items[i]);
  }
}
function standalone_pickVisit(scene, visitor) {
  var items = scene.items,
    hit,
    i;
  if (!items || !items.length) return null;
  const zitems = standalone_zorder(scene);
  if (zitems && zitems.length) items = zitems;
  for (i = items.length; --i >= 0;) {
    if (hit = visitor(items[i])) return hit;
  }
  if (items === zitems) {
    for (items = scene.items, i = items.length; --i >= 0;) {
      if (!items[i].zindex) {
        if (hit = visitor(items[i])) return hit;
      }
    }
  }
  return null;
}

function standalone_drawAll(path) {
  return function (context, scene, bounds) {
    standalone_visit(scene, item => {
      if (!bounds || bounds.intersects(item.bounds)) {
        standalone_drawPath(path, context, item, item);
      }
    });
  };
}
function standalone_drawOne(path) {
  return function (context, scene, bounds) {
    if (scene.items.length && (!bounds || bounds.intersects(scene.bounds))) {
      standalone_drawPath(path, context, scene.items[0], scene.items);
    }
  };
}
function standalone_drawPath(path, context, item, items) {
  var opacity = item.opacity == null ? 1 : item.opacity;
  if (opacity === 0) return;
  if (path(context, items)) return;
  standalone_blend(context, item);
  if (item.fill && standalone_fill(context, item, opacity)) {
    context.fill();
  }
  if (item.stroke && standalone_stroke(context, item, opacity)) {
    context.stroke();
  }
}

function standalone_pick$1(test) {
  test = test || standalone_truthy;
  return function (context, scene, x, y, gx, gy) {
    x *= context.pixelRatio;
    y *= context.pixelRatio;
    return standalone_pickVisit(scene, item => {
      const b = item.bounds;
      // first hit test against bounding box
      if (b && !b.contains(gx, gy) || !b) return;
      // if in bounding box, perform more careful test
      if (test(context, item, x, y, gx, gy)) return item;
    });
  };
}
function standalone_hitPath(path, filled) {
  return function (context, o, x, y) {
    var item = Array.isArray(o) ? o[0] : o,
      fill = filled == null ? item.fill : filled,
      stroke = item.stroke && context.isPointInStroke,
      lw,
      lc;
    if (stroke) {
      lw = item.strokeWidth;
      lc = item.strokeCap;
      context.lineWidth = lw != null ? lw : 1;
      context.lineCap = lc != null ? lc : 'butt';
    }
    return path(context, o) ? false : fill && context.isPointInPath(x, y) || stroke && context.isPointInStroke(x, y);
  };
}
function standalone_pickPath(path) {
  return standalone_pick$1(standalone_hitPath(path));
}

function standalone_translate(x, y) {
  return 'translate(' + x + ',' + y + ')';
}
function standalone_rotate(a) {
  return 'rotate(' + a + ')';
}
function standalone_vega_scenegraph_module_scale(scaleX, scaleY) {
  return 'scale(' + scaleX + ',' + scaleY + ')';
}
function standalone_translateItem(item) {
  return standalone_translate(item.x || 0, item.y || 0);
}
function standalone_rotateItem(item) {
  return standalone_translate(item.x || 0, item.y || 0) + (item.angle ? ' ' + standalone_rotate(item.angle) : '');
}
function standalone_transformItem(item) {
  return standalone_translate(item.x || 0, item.y || 0) + (item.angle ? ' ' + standalone_rotate(item.angle) : '') + (item.scaleX || item.scaleY ? ' ' + standalone_vega_scenegraph_module_scale(item.scaleX || 1, item.scaleY || 1) : '');
}

function standalone_markItemPath (type, shape, isect) {
  function attr(emit, item) {
    emit('transform', standalone_rotateItem(item));
    emit('d', shape(null, item));
  }
  function bound(bounds, item) {
    shape(standalone_boundContext(bounds, item.angle), item);
    return standalone_boundStroke(bounds, item).translate(item.x || 0, item.y || 0);
  }
  function draw(context, item) {
    var x = item.x || 0,
      y = item.y || 0,
      a = item.angle || 0;
    context.translate(x, y);
    if (a) context.rotate(a *= standalone_DegToRad);
    context.beginPath();
    shape(context, item);
    if (a) context.rotate(-a);
    context.translate(-x, -y);
  }
  return {
    type: type,
    tag: 'path',
    nested: false,
    attr: attr,
    bound: bound,
    draw: standalone_drawAll(draw),
    pick: standalone_pickPath(draw),
    isect: isect || standalone_intersectPath(draw)
  };
}

var standalone_vega_scenegraph_module_arc = standalone_markItemPath('arc', standalone_arc$1);

function standalone_pickArea(a, p) {
  var v = a[0].orient === 'horizontal' ? p[1] : p[0],
    z = a[0].orient === 'horizontal' ? 'y' : 'x',
    i = a.length,
    min = +Infinity,
    hit,
    d;
  while (--i >= 0) {
    if (a[i].defined === false) continue;
    d = Math.abs(a[i][z] - v);
    if (d < min) {
      min = d;
      hit = a[i];
    }
  }
  return hit;
}
function standalone_pickLine(a, p) {
  var t = Math.pow(a[0].strokeWidth || 1, 2),
    i = a.length,
    dx,
    dy,
    dd;
  while (--i >= 0) {
    if (a[i].defined === false) continue;
    dx = a[i].x - p[0];
    dy = a[i].y - p[1];
    dd = dx * dx + dy * dy;
    if (dd < t) return a[i];
  }
  return null;
}
function standalone_pickTrail(a, p) {
  var i = a.length,
    dx,
    dy,
    dd;
  while (--i >= 0) {
    if (a[i].defined === false) continue;
    dx = a[i].x - p[0];
    dy = a[i].y - p[1];
    dd = dx * dx + dy * dy;
    dx = a[i].size || 1;
    if (dd < dx * dx) return a[i];
  }
  return null;
}

function standalone_markMultiItemPath (type, shape, tip) {
  function attr(emit, item) {
    var items = item.mark.items;
    if (items.length) emit('d', shape(null, items));
  }
  function bound(bounds, mark) {
    var items = mark.items;
    if (items.length === 0) {
      return bounds;
    } else {
      shape(standalone_boundContext(bounds), items);
      return standalone_boundStroke(bounds, items[0]);
    }
  }
  function draw(context, items) {
    context.beginPath();
    shape(context, items);
  }
  const hit = standalone_hitPath(draw);
  function pick(context, scene, x, y, gx, gy) {
    var items = scene.items,
      b = scene.bounds;
    if (!items || !items.length || b && !b.contains(gx, gy)) {
      return null;
    }
    x *= context.pixelRatio;
    y *= context.pixelRatio;
    return hit(context, items, x, y) ? items[0] : null;
  }
  return {
    type: type,
    tag: 'path',
    nested: true,
    attr: attr,
    bound: bound,
    draw: standalone_drawOne(draw),
    pick: pick,
    isect: standalone_intersectPoint,
    tip: tip
  };
}

var standalone_vega_scenegraph_module_area = standalone_markMultiItemPath('area', standalone_area$1, standalone_pickArea);

function standalone_clip (context, scene) {
  var clip = scene.clip;
  context.save();
  if (standalone_vega_util_module_isFunction(clip)) {
    context.beginPath();
    clip(context);
    context.clip();
  } else {
    standalone_clipGroup(context, scene.group);
  }
}
function standalone_clipGroup(context, group) {
  context.beginPath();
  standalone_hasCornerRadius(group) ? standalone_rectangle(context, group, 0, 0) : context.rect(0, 0, group.width || 0, group.height || 0);
  context.clip();
}

function standalone_offset$1(item) {
  const sw = standalone_vega_scenegraph_module_value(item.strokeWidth, 1);
  return item.strokeOffset != null ? item.strokeOffset : item.stroke && sw > 0.5 && sw < 1.5 ? 0.5 - Math.abs(sw - 1) : 0;
}
function standalone_attr$5(emit, item) {
  emit('transform', standalone_translateItem(item));
}
function standalone_emitRectangle(emit, item) {
  const off = standalone_offset$1(item);
  emit('d', standalone_rectangle(null, item, off, off));
}
function standalone_background(emit, item) {
  emit('class', 'background');
  emit('aria-hidden', true);
  standalone_emitRectangle(emit, item);
}
function standalone_foreground(emit, item) {
  emit('class', 'foreground');
  emit('aria-hidden', true);
  if (item.strokeForeground) {
    standalone_emitRectangle(emit, item);
  } else {
    emit('d', '');
  }
}
function standalone_content(emit, item, renderer) {
  const url = item.clip ? standalone_clip$1(renderer, item, item) : null;
  emit('clip-path', url);
}
function standalone_bound$5(bounds, group) {
  if (!group.clip && group.items) {
    const items = group.items,
      m = items.length;
    for (let j = 0; j < m; ++j) {
      bounds.union(items[j].bounds);
    }
  }
  if ((group.clip || group.width || group.height) && !group.noBound) {
    bounds.add(0, 0).add(group.width || 0, group.height || 0);
  }
  standalone_boundStroke(bounds, group);
  return bounds.translate(group.x || 0, group.y || 0);
}
function standalone_rectanglePath(context, group, x, y) {
  const off = standalone_offset$1(group);
  context.beginPath();
  standalone_rectangle(context, group, (x || 0) + off, (y || 0) + off);
}
const standalone_hitBackground = standalone_hitPath(standalone_rectanglePath);
const standalone_hitForeground = standalone_hitPath(standalone_rectanglePath, false);
const standalone_hitCorner = standalone_hitPath(standalone_rectanglePath, true);
function standalone_draw$4(context, scene, bounds, markTypes) {
  standalone_visit(scene, group => {
    const gx = group.x || 0,
      gy = group.y || 0,
      fore = group.strokeForeground,
      opacity = group.opacity == null ? 1 : group.opacity;

    // draw group background
    if ((group.stroke || group.fill) && opacity) {
      standalone_rectanglePath(context, group, gx, gy);
      standalone_blend(context, group);
      if (group.fill && standalone_fill(context, group, opacity)) {
        context.fill();
      }
      if (group.stroke && !fore && standalone_stroke(context, group, opacity)) {
        context.stroke();
      }
    }

    // setup graphics context, set clip and bounds
    context.save();
    context.translate(gx, gy);
    if (group.clip) standalone_clipGroup(context, group);
    if (bounds) bounds.translate(-gx, -gy);

    // draw group contents
    standalone_visit(group, item => {
      if (item.marktype === 'group' || markTypes == null || markTypes.includes(item.marktype)) {
        this.draw(context, item, bounds, markTypes);
      }
    });

    // restore graphics context
    if (bounds) bounds.translate(gx, gy);
    context.restore();

    // draw group foreground
    if (fore && group.stroke && opacity) {
      standalone_rectanglePath(context, group, gx, gy);
      standalone_blend(context, group);
      if (standalone_stroke(context, group, opacity)) {
        context.stroke();
      }
    }
  });
}
function standalone_pick(context, scene, x, y, gx, gy) {
  if (scene.bounds && !scene.bounds.contains(gx, gy) || !scene.items) {
    return null;
  }
  const cx = x * context.pixelRatio,
    cy = y * context.pixelRatio;
  return standalone_pickVisit(scene, group => {
    let hit, dx, dy;

    // first hit test bounding box
    const b = group.bounds;
    if (b && !b.contains(gx, gy)) return;

    // passed bounds check, test rectangular clip
    dx = group.x || 0;
    dy = group.y || 0;
    const dw = dx + (group.width || 0),
      dh = dy + (group.height || 0),
      c = group.clip;
    if (c && (gx < dx || gx > dw || gy < dy || gy > dh)) return;

    // adjust coordinate system
    context.save();
    context.translate(dx, dy);
    dx = gx - dx;
    dy = gy - dy;

    // test background for rounded corner clip
    if (c && standalone_hasCornerRadius(group) && !standalone_hitCorner(context, group, cx, cy)) {
      context.restore();
      return null;
    }
    const fore = group.strokeForeground,
      ix = scene.interactive !== false;

    // hit test against group foreground
    if (ix && fore && group.stroke && standalone_hitForeground(context, group, cx, cy)) {
      context.restore();
      return group;
    }

    // hit test against contained marks
    hit = standalone_pickVisit(group, mark => standalone_pickMark(mark, dx, dy) ? this.pick(mark, x, y, dx, dy) : null);

    // hit test against group background
    if (!hit && ix && (group.fill || !fore && group.stroke) && standalone_hitBackground(context, group, cx, cy)) {
      hit = group;
    }

    // restore state and return
    context.restore();
    return hit || null;
  });
}
function standalone_pickMark(mark, x, y) {
  return (mark.interactive !== false || mark.marktype === 'group') && mark.bounds && mark.bounds.contains(x, y);
}
var standalone_group = {
  type: 'group',
  tag: 'g',
  nested: false,
  attr: standalone_attr$5,
  bound: standalone_bound$5,
  draw: standalone_draw$4,
  pick: standalone_pick,
  isect: standalone_intersectRect,
  content: standalone_content,
  background: standalone_background,
  foreground: standalone_foreground
};

var standalone_metadata = {
  'xmlns': 'http://www.w3.org/2000/svg',
  'xmlns:xlink': 'http://www.w3.org/1999/xlink',
  'version': '1.1'
};

function standalone_getImage(item, renderer) {
  var image = item.image;
  if (!image || item.url && item.url !== image.url) {
    image = {
      complete: false,
      width: 0,
      height: 0
    };
    renderer.loadImage(item.url).then(image => {
      item.image = image;
      item.image.url = item.url;
    });
  }
  return image;
}
function standalone_imageWidth(item, image) {
  return item.width != null ? item.width : !image || !image.width ? 0 : item.aspect !== false && item.height ? item.height * image.width / image.height : image.width;
}
function standalone_imageHeight(item, image) {
  return item.height != null ? item.height : !image || !image.height ? 0 : item.aspect !== false && item.width ? item.width * image.height / image.width : image.height;
}
function standalone_imageXOffset(align, w) {
  return align === 'center' ? w / 2 : align === 'right' ? w : 0;
}
function standalone_imageYOffset(baseline, h) {
  return baseline === 'middle' ? h / 2 : baseline === 'bottom' ? h : 0;
}
function standalone_attr$4(emit, item, renderer) {
  const img = standalone_getImage(item, renderer),
    w = standalone_imageWidth(item, img),
    h = standalone_imageHeight(item, img),
    x = (item.x || 0) - standalone_imageXOffset(item.align, w),
    y = (item.y || 0) - standalone_imageYOffset(item.baseline, h),
    i = !img.src && img.toDataURL ? img.toDataURL() : img.src || '';
  emit('href', i, standalone_metadata['xmlns:xlink'], 'xlink:href');
  emit('transform', standalone_translate(x, y));
  emit('width', w);
  emit('height', h);
  emit('preserveAspectRatio', item.aspect === false ? 'none' : 'xMidYMid');
}
function standalone_bound$4(bounds, item) {
  const img = item.image,
    w = standalone_imageWidth(item, img),
    h = standalone_imageHeight(item, img),
    x = (item.x || 0) - standalone_imageXOffset(item.align, w),
    y = (item.y || 0) - standalone_imageYOffset(item.baseline, h);
  return bounds.set(x, y, x + w, y + h);
}
function standalone_draw$3(context, scene, bounds) {
  standalone_visit(scene, item => {
    if (bounds && !bounds.intersects(item.bounds)) return; // bounds check

    const img = standalone_getImage(item, this);
    let w = standalone_imageWidth(item, img);
    let h = standalone_imageHeight(item, img);
    if (w === 0 || h === 0) return; // early exit

    let x = (item.x || 0) - standalone_imageXOffset(item.align, w),
      y = (item.y || 0) - standalone_imageYOffset(item.baseline, h),
      opacity,
      ar0,
      ar1,
      t;
    if (item.aspect !== false) {
      ar0 = img.width / img.height;
      ar1 = item.width / item.height;
      if (ar0 === ar0 && ar1 === ar1 && ar0 !== ar1) {
        if (ar1 < ar0) {
          t = w / ar0;
          y += (h - t) / 2;
          h = t;
        } else {
          t = h * ar0;
          x += (w - t) / 2;
          w = t;
        }
      }
    }
    if (img.complete || img.toDataURL) {
      standalone_blend(context, item);
      context.globalAlpha = (opacity = item.opacity) != null ? opacity : 1;
      context.imageSmoothingEnabled = item.smooth !== false;
      context.drawImage(img, x, y, w, h);
    }
  });
}
var standalone_vega_scenegraph_module_image = {
  type: 'image',
  tag: 'image',
  nested: false,
  attr: standalone_attr$4,
  bound: standalone_bound$4,
  draw: standalone_draw$3,
  pick: standalone_pick$1(),
  isect: standalone_truthy,
  // bounds check is sufficient
  get: standalone_getImage,
  xOffset: standalone_imageXOffset,
  yOffset: standalone_imageYOffset
};

var standalone_vega_scenegraph_module_line = standalone_markMultiItemPath('line', standalone_line$1, standalone_pickLine);

function standalone_attr$3(emit, item) {
  var sx = item.scaleX || 1,
    sy = item.scaleY || 1;
  if (sx !== 1 || sy !== 1) {
    emit('vector-effect', 'non-scaling-stroke');
  }
  emit('transform', standalone_transformItem(item));
  emit('d', item.path);
}
function standalone_path$1(context, item) {
  var path = item.path;
  if (path == null) return true;
  var x = item.x || 0,
    y = item.y || 0,
    sx = item.scaleX || 1,
    sy = item.scaleY || 1,
    a = (item.angle || 0) * standalone_DegToRad,
    cache = item.pathCache;
  if (!cache || cache.path !== path) {
    (item.pathCache = cache = standalone_vega_scenegraph_module_parse(path)).path = path;
  }
  if (a && context.rotate && context.translate) {
    context.translate(x, y);
    context.rotate(a);
    standalone_pathRender(context, cache, 0, 0, sx, sy);
    context.rotate(-a);
    context.translate(-x, -y);
  } else {
    standalone_pathRender(context, cache, x, y, sx, sy);
  }
}
function standalone_bound$3(bounds, item) {
  return standalone_path$1(standalone_boundContext(bounds, item.angle), item) ? bounds.set(0, 0, 0, 0) : standalone_boundStroke(bounds, item, true);
}
var standalone_path$2 = {
  type: 'path',
  tag: 'path',
  nested: false,
  attr: standalone_attr$3,
  bound: standalone_bound$3,
  draw: standalone_drawAll(standalone_path$1),
  pick: standalone_pickPath(standalone_path$1),
  isect: standalone_intersectPath(standalone_path$1)
};

function standalone_attr$2(emit, item) {
  emit('d', standalone_rectangle(null, item));
}
function standalone_bound$2(bounds, item) {
  var x, y;
  return standalone_boundStroke(bounds.set(x = item.x || 0, y = item.y || 0, x + item.width || 0, y + item.height || 0), item);
}
function standalone_draw$2(context, item) {
  context.beginPath();
  standalone_rectangle(context, item);
}
var standalone_rect = {
  type: 'rect',
  tag: 'path',
  nested: false,
  attr: standalone_attr$2,
  bound: standalone_bound$2,
  draw: standalone_drawAll(standalone_draw$2),
  pick: standalone_pickPath(standalone_draw$2),
  isect: standalone_intersectRect
};

function standalone_attr$1(emit, item) {
  emit('transform', standalone_translateItem(item));
  emit('x2', item.x2 != null ? item.x2 - (item.x || 0) : 0);
  emit('y2', item.y2 != null ? item.y2 - (item.y || 0) : 0);
}
function standalone_bound$1(bounds, item) {
  var x1, y1;
  return standalone_boundStroke(bounds.set(x1 = item.x || 0, y1 = item.y || 0, item.x2 != null ? item.x2 : x1, item.y2 != null ? item.y2 : y1), item);
}
function standalone_vega_scenegraph_module_path(context, item, opacity) {
  var x1, y1, x2, y2;
  if (item.stroke && standalone_stroke(context, item, opacity)) {
    x1 = item.x || 0;
    y1 = item.y || 0;
    x2 = item.x2 != null ? item.x2 : x1;
    y2 = item.y2 != null ? item.y2 : y1;
    context.beginPath();
    context.moveTo(x1, y1);
    context.lineTo(x2, y2);
    return true;
  }
  return false;
}
function standalone_draw$1(context, scene, bounds) {
  standalone_visit(scene, item => {
    if (bounds && !bounds.intersects(item.bounds)) return; // bounds check
    var opacity = item.opacity == null ? 1 : item.opacity;
    if (opacity && standalone_vega_scenegraph_module_path(context, item, opacity)) {
      standalone_blend(context, item);
      context.stroke();
    }
  });
}
function standalone_hit$1(context, item, x, y) {
  if (!context.isPointInStroke) return false;
  return standalone_vega_scenegraph_module_path(context, item, 1) && context.isPointInStroke(x, y);
}
var standalone_rule = {
  type: 'rule',
  tag: 'line',
  nested: false,
  attr: standalone_attr$1,
  bound: standalone_bound$1,
  draw: standalone_draw$1,
  pick: standalone_pick$1(standalone_hit$1),
  isect: standalone_intersectRule
};

var standalone_shape = standalone_markItemPath('shape', standalone_shape$1);

var standalone_symbol = standalone_markItemPath('symbol', standalone_symbol$1, standalone_intersectPoint);

// memoize text width measurement
const standalone_widthCache = standalone_lruCache();
var standalone_textMetrics = {
  height: standalone_fontSize,
  measureWidth: standalone_measureWidth,
  estimateWidth: standalone_estimateWidth,
  width: standalone_estimateWidth,
  canvas: standalone_useCanvas
};
standalone_useCanvas(true);
function standalone_useCanvas(use) {
  standalone_textMetrics.width = use && standalone_context ? standalone_measureWidth : standalone_estimateWidth;
}

// make simple estimate if no canvas is available
function standalone_estimateWidth(item, text) {
  return src_standalone_estimateWidth(standalone_textValue(item, text), standalone_fontSize(item));
}
function src_standalone_estimateWidth(text, currentFontHeight) {
  return ~~(0.8 * text.length * currentFontHeight);
}

// measure text width if canvas is available
function standalone_measureWidth(item, text) {
  return standalone_fontSize(item) <= 0 || !(text = standalone_textValue(item, text)) ? 0 : src_standalone_measureWidth(text, standalone_font(item));
}
function src_standalone_measureWidth(text, currentFont) {
  const key = `(${currentFont}) ${text}`;
  let width = standalone_widthCache.get(key);
  if (width === undefined) {
    standalone_context.font = currentFont;
    width = standalone_context.measureText(text).width;
    standalone_widthCache.set(key, width);
  }
  return width;
}
function standalone_fontSize(item) {
  return item.fontSize != null ? +item.fontSize || 0 : 11;
}
function standalone_lineHeight(item) {
  return item.lineHeight != null ? item.lineHeight : standalone_fontSize(item) + 2;
}
function standalone_lineArray(_) {
  return standalone_vega_util_module_isArray(_) ? _.length > 1 ? _ : _[0] : _;
}
function standalone_textLines(item) {
  return standalone_lineArray(item.lineBreak && item.text && !standalone_vega_util_module_isArray(item.text) ? item.text.split(item.lineBreak) : item.text);
}
function standalone_multiLineOffset(item) {
  const tl = standalone_textLines(item);
  return (standalone_vega_util_module_isArray(tl) ? tl.length - 1 : 0) * standalone_lineHeight(item);
}
function standalone_textValue(item, line) {
  const text = line == null ? '' : (line + '').trim();
  return item.limit > 0 && text.length ? standalone_vega_scenegraph_module_truncate(item, text) : text;
}
function standalone_widthGetter(item) {
  if (standalone_textMetrics.width === standalone_measureWidth) {
    // we are using canvas
    const currentFont = standalone_font(item);
    return text => src_standalone_measureWidth(text, currentFont);
  } else if (standalone_textMetrics.width === standalone_estimateWidth) {
    // we are relying on estimates
    const currentFontHeight = standalone_fontSize(item);
    return text => src_standalone_estimateWidth(text, currentFontHeight);
  } else {
    // User defined textMetrics.width function in use (e.g. vl-convert)
    return text => standalone_textMetrics.width(item, text);
  }
}
function standalone_vega_scenegraph_module_truncate(item, text) {
  var limit = +item.limit,
    width = standalone_widthGetter(item);
  if (width(text) < limit) return text;
  var ellipsis = item.ellipsis || '\u2026',
    rtl = item.dir === 'rtl',
    lo = 0,
    hi = text.length,
    mid;
  limit -= width(ellipsis);
  if (rtl) {
    while (lo < hi) {
      mid = lo + hi >>> 1;
      if (width(text.slice(mid)) > limit) lo = mid + 1;else hi = mid;
    }
    return ellipsis + text.slice(lo);
  } else {
    while (lo < hi) {
      mid = 1 + (lo + hi >>> 1);
      if (width(text.slice(0, mid)) < limit) lo = mid;else hi = mid - 1;
    }
    return text.slice(0, lo) + ellipsis;
  }
}
function standalone_fontFamily(item, quote) {
  var font = item.font;
  return (quote && font ? String(font).replace(/"/g, '\'') : font) || 'sans-serif';
}
function standalone_font(item, quote) {
  return '' + (item.fontStyle ? item.fontStyle + ' ' : '') + (item.fontVariant ? item.fontVariant + ' ' : '') + (item.fontWeight ? item.fontWeight + ' ' : '') + standalone_fontSize(item) + 'px ' + standalone_fontFamily(item, quote);
}
function standalone_vega_scenegraph_module_offset(item) {
  // perform our own font baseline calculation
  // why? not all browsers support SVG 1.1 'alignment-baseline' :(
  // this also ensures consistent layout across renderers
  var baseline = item.baseline,
    h = standalone_fontSize(item);
  return Math.round(baseline === 'top' ? 0.79 * h : baseline === 'middle' ? 0.30 * h : baseline === 'bottom' ? -0.21 * h : baseline === 'line-top' ? 0.29 * h + 0.5 * standalone_lineHeight(item) : baseline === 'line-bottom' ? 0.29 * h - 0.5 * standalone_lineHeight(item) : 0);
}

const standalone_textAlign = {
  'left': 'start',
  'center': 'middle',
  'right': 'end'
};
const standalone_tempBounds = new standalone_Bounds();
function standalone_anchorPoint(item) {
  var x = item.x || 0,
    y = item.y || 0,
    r = item.radius || 0,
    t;
  if (r) {
    t = (item.theta || 0) - standalone_HalfPi;
    x += r * Math.cos(t);
    y += r * Math.sin(t);
  }
  standalone_tempBounds.x1 = x;
  standalone_tempBounds.y1 = y;
  return standalone_tempBounds;
}
function standalone_vega_scenegraph_module_attr(emit, item) {
  var dx = item.dx || 0,
    dy = (item.dy || 0) + standalone_vega_scenegraph_module_offset(item),
    p = standalone_anchorPoint(item),
    x = p.x1,
    y = p.y1,
    a = item.angle || 0,
    t;
  emit('text-anchor', standalone_textAlign[item.align] || 'start');
  if (a) {
    t = standalone_translate(x, y) + ' ' + standalone_rotate(a);
    if (dx || dy) t += ' ' + standalone_translate(dx, dy);
  } else {
    t = standalone_translate(x + dx, y + dy);
  }
  emit('transform', t);
}
function standalone_bound(bounds, item, mode) {
  var h = standalone_textMetrics.height(item),
    a = item.align,
    p = standalone_anchorPoint(item),
    x = p.x1,
    y = p.y1,
    dx = item.dx || 0,
    dy = (item.dy || 0) + standalone_vega_scenegraph_module_offset(item) - Math.round(0.8 * h),
    // use 4/5 offset
    tl = standalone_textLines(item),
    w;

  // get dimensions
  if (standalone_vega_util_module_isArray(tl)) {
    // multi-line text
    h += standalone_lineHeight(item) * (tl.length - 1);
    w = tl.reduce((w, t) => Math.max(w, standalone_textMetrics.width(item, t)), 0);
  } else {
    // single-line text
    w = standalone_textMetrics.width(item, tl);
  }

  // horizontal alignment
  if (a === 'center') {
    dx -= w / 2;
  } else if (a === 'right') {
    dx -= w;
  } else ;
  bounds.set(dx += x, dy += y, dx + w, dy + h);
  if (item.angle && !mode) {
    bounds.rotate(item.angle * standalone_DegToRad, x, y);
  } else if (mode === 2) {
    return bounds.rotatedPoints(item.angle * standalone_DegToRad, x, y);
  }
  return bounds;
}
function standalone_draw(context, scene, bounds) {
  standalone_visit(scene, item => {
    var opacity = item.opacity == null ? 1 : item.opacity,
      p,
      x,
      y,
      i,
      lh,
      tl,
      str;
    if (bounds && !bounds.intersects(item.bounds) ||
    // bounds check
    opacity === 0 || item.fontSize <= 0 || item.text == null || item.text.length === 0) return;
    context.font = standalone_font(item);
    context.textAlign = item.align || 'left';
    p = standalone_anchorPoint(item);
    x = p.x1, y = p.y1;
    if (item.angle) {
      context.save();
      context.translate(x, y);
      context.rotate(item.angle * standalone_DegToRad);
      x = y = 0; // reset x, y
    }
    x += item.dx || 0;
    y += (item.dy || 0) + standalone_vega_scenegraph_module_offset(item);
    tl = standalone_textLines(item);
    standalone_blend(context, item);
    if (standalone_vega_util_module_isArray(tl)) {
      lh = standalone_lineHeight(item);
      for (i = 0; i < tl.length; ++i) {
        str = standalone_textValue(item, tl[i]);
        if (item.fill && standalone_fill(context, item, opacity)) {
          context.fillText(str, x, y);
        }
        if (item.stroke && standalone_stroke(context, item, opacity)) {
          context.strokeText(str, x, y);
        }
        y += lh;
      }
    } else {
      str = standalone_textValue(item, tl);
      if (item.fill && standalone_fill(context, item, opacity)) {
        context.fillText(str, x, y);
      }
      if (item.stroke && standalone_stroke(context, item, opacity)) {
        context.strokeText(str, x, y);
      }
    }
    if (item.angle) context.restore();
  });
}
function standalone_hit(context, item, x, y, gx, gy) {
  if (item.fontSize <= 0) return false;
  if (!item.angle) return true; // bounds sufficient if no rotation

  // project point into space of unrotated bounds
  var p = standalone_anchorPoint(item),
    ax = p.x1,
    ay = p.y1,
    b = standalone_bound(standalone_tempBounds, item, 1),
    a = -item.angle * standalone_DegToRad,
    cos = Math.cos(a),
    sin = Math.sin(a),
    px = cos * gx - sin * gy + (ax - cos * ax + sin * ay),
    py = sin * gx + cos * gy + (ay - sin * ax - cos * ay);
  return b.contains(px, py);
}
function standalone_intersectText(item, box) {
  const p = standalone_bound(standalone_tempBounds, item, 2);
  return standalone_intersectBoxLine(box, p[0], p[1], p[2], p[3]) || standalone_intersectBoxLine(box, p[0], p[1], p[4], p[5]) || standalone_intersectBoxLine(box, p[4], p[5], p[6], p[7]) || standalone_intersectBoxLine(box, p[2], p[3], p[6], p[7]);
}
var standalone_vega_scenegraph_module_text = {
  type: 'text',
  tag: 'text',
  nested: false,
  attr: standalone_vega_scenegraph_module_attr,
  bound: standalone_bound,
  draw: standalone_draw,
  pick: standalone_pick$1(standalone_hit),
  isect: standalone_intersectText
};

var standalone_trail = standalone_markMultiItemPath('trail', standalone_trail$1, standalone_pickTrail);

var standalone_Marks = {
  arc: standalone_vega_scenegraph_module_arc,
  area: standalone_vega_scenegraph_module_area,
  group: standalone_group,
  image: standalone_vega_scenegraph_module_image,
  line: standalone_vega_scenegraph_module_line,
  path: standalone_path$2,
  rect: standalone_rect,
  rule: standalone_rule,
  shape: standalone_shape,
  symbol: standalone_symbol,
  text: standalone_vega_scenegraph_module_text,
  trail: standalone_trail
};

function standalone_boundItem (item, func, opt) {
  var type = standalone_Marks[item.mark.marktype],
    bound = func || type.bound;
  if (type.nested) item = item.mark;
  return bound(item.bounds || (item.bounds = new standalone_Bounds()), item, opt);
}

var standalone_DUMMY = {
  mark: null
};
function standalone_boundMark (mark, bounds, opt) {
  var type = standalone_Marks[mark.marktype],
    bound = type.bound,
    items = mark.items,
    hasItems = items && items.length,
    i,
    n,
    item,
    b;
  if (type.nested) {
    if (hasItems) {
      item = items[0];
    } else {
      // no items, fake it
      standalone_DUMMY.mark = mark;
      item = standalone_DUMMY;
    }
    b = standalone_boundItem(item, bound, opt);
    bounds = bounds && bounds.union(b) || b;
    return bounds;
  }
  bounds = bounds || mark.bounds && mark.bounds.clear() || new standalone_Bounds();
  if (hasItems) {
    for (i = 0, n = items.length; i < n; ++i) {
      bounds.union(standalone_boundItem(items[i], bound, opt));
    }
  }
  return mark.bounds = bounds;
}

const standalone_keys = ['marktype', 'name', 'role', 'interactive', 'clip', 'items', 'zindex', 'x', 'y', 'width', 'height', 'align', 'baseline',
// layout
'fill', 'fillOpacity', 'opacity', 'blend',
// fill
'stroke', 'strokeOpacity', 'strokeWidth', 'strokeCap',
// stroke
'strokeDash', 'strokeDashOffset',
// stroke dash
'strokeForeground', 'strokeOffset',
// group
'startAngle', 'endAngle', 'innerRadius', 'outerRadius',
// arc
'cornerRadius', 'padAngle',
// arc, rect
'cornerRadiusTopLeft', 'cornerRadiusTopRight',
// rect, group
'cornerRadiusBottomLeft', 'cornerRadiusBottomRight', 'interpolate', 'tension', 'orient', 'defined',
// area, line
'url', 'aspect', 'smooth',
// image
'path', 'scaleX', 'scaleY',
// path
'x2', 'y2',
// rule
'size', 'shape',
// symbol
'text', 'angle', 'theta', 'radius', 'dir', 'dx', 'dy',
// text
'ellipsis', 'limit', 'lineBreak', 'lineHeight', 'font', 'fontSize', 'fontWeight', 'fontStyle', 'fontVariant',
// font
'description', 'aria', 'ariaRole', 'ariaRoleDescription' // aria
];
function standalone_sceneToJSON(scene, indent) {
  return JSON.stringify(scene, standalone_keys, indent);
}
function standalone_sceneFromJSON(json) {
  const scene = typeof json === 'string' ? JSON.parse(json) : json;
  return standalone_initialize(scene);
}
function standalone_initialize(scene) {
  var type = scene.marktype,
    items = scene.items,
    parent,
    i,
    n;
  if (items) {
    for (i = 0, n = items.length; i < n; ++i) {
      parent = type ? 'mark' : 'group';
      items[i][parent] = scene;
      if (items[i].zindex) items[i][parent].zdirty = true;
      if ('group' === (type || parent)) standalone_initialize(items[i]);
    }
  }
  if (type) standalone_boundMark(scene);
  return scene;
}

class standalone_Scenegraph {
  constructor(scene) {
    if (arguments.length) {
      this.root = standalone_sceneFromJSON(scene);
    } else {
      this.root = standalone_createMark({
        marktype: 'group',
        name: 'root',
        role: 'frame'
      });
      this.root.items = [new standalone_GroupItem(this.root)];
    }
  }
  toJSON(indent) {
    return standalone_sceneToJSON(this.root, indent || 0);
  }
  mark(markdef, group, index) {
    group = group || this.root.items[0];
    const mark = standalone_createMark(markdef, group);
    group.items[index] = mark;
    if (mark.zindex) mark.group.zdirty = true;
    return mark;
  }
}
function standalone_createMark(def, group) {
  const mark = {
    bounds: new standalone_Bounds(),
    clip: !!def.clip,
    group: group,
    interactive: def.interactive === false ? false : true,
    items: [],
    marktype: def.marktype,
    name: def.name || undefined,
    role: def.role || undefined,
    zindex: def.zindex || 0
  };

  // add accessibility properties if defined
  if (def.aria != null) {
    mark.aria = def.aria;
  }
  if (def.description) {
    mark.description = def.description;
  }
  return mark;
}

// create a new DOM element
function standalone_domCreate(doc, tag, ns) {
  if (!doc && typeof document !== 'undefined' && document.createElement) {
    doc = document;
  }
  return doc ? ns ? doc.createElementNS(ns, tag) : doc.createElement(tag) : null;
}

// find first child element with matching tag
function standalone_domFind(el, tag) {
  tag = tag.toLowerCase();
  var nodes = el.childNodes,
    i = 0,
    n = nodes.length;
  for (; i < n; ++i) if (nodes[i].tagName.toLowerCase() === tag) {
    return nodes[i];
  }
}

// retrieve child element at given index
// create & insert if doesn't exist or if tags do not match
function standalone_domChild(el, index, tag, ns) {
  var a = el.childNodes[index],
    b;
  if (!a || a.tagName.toLowerCase() !== tag.toLowerCase()) {
    b = a || null;
    a = standalone_domCreate(el.ownerDocument, tag, ns);
    el.insertBefore(a, b);
  }
  return a;
}

// remove all child elements at or above the given index
function standalone_domClear(el, index) {
  var nodes = el.childNodes,
    curr = nodes.length;
  while (curr > index) el.removeChild(nodes[--curr]);
  return el;
}

// generate css class name for mark
function standalone_cssClass(mark) {
  return 'mark-' + mark.marktype + (mark.role ? ' role-' + mark.role : '') + (mark.name ? ' ' + mark.name : '');
}

function standalone_vega_scenegraph_module_point (event, el) {
  const rect = el.getBoundingClientRect();
  return [event.clientX - rect.left - (el.clientLeft || 0), event.clientY - rect.top - (el.clientTop || 0)];
}

function standalone_resolveItem (item, event, el, origin) {
  var mark = item && item.mark,
    mdef,
    p;
  if (mark && (mdef = standalone_Marks[mark.marktype]).tip) {
    p = standalone_vega_scenegraph_module_point(event, el);
    p[0] -= origin[0];
    p[1] -= origin[1];
    while (item = item.mark.group) {
      p[0] -= item.x || 0;
      p[1] -= item.y || 0;
    }
    item = mdef.tip(mark.items, p);
  }
  return item;
}

class standalone_Handler {
  /**
   * Create a new Handler instance.
   * @param {object} [customLoader] - Optional loader instance for
   *   href URL sanitization. If not specified, a standard loader
   *   instance will be generated.
   * @param {function} [customTooltip] - Optional tooltip handler
   *   function for custom tooltip display.
   * @constructor
   */
  constructor(customLoader, customTooltip) {
    this._active = null;
    this._handlers = {};
    this._loader = customLoader || standalone_loader();
    this._tooltip = customTooltip || standalone_defaultTooltip;
  }

  /**
   * Initialize a new Handler instance.
   * @param {DOMElement} el - The containing DOM element for the display.
   * @param {Array<number>} origin - The origin of the display, in pixels.
   *   The coordinate system will be translated to this point.
   * @param {object} [obj] - Optional context object that should serve as
   *   the "this" context for event callbacks.
   * @return {Handler} - This handler instance.
   */
  initialize(el, origin, obj) {
    this._el = el;
    this._obj = obj || null;
    return this.origin(origin);
  }

  /**
   * Returns the parent container element for a visualization.
   * @return {DOMElement} - The containing DOM element.
   */
  element() {
    return this._el;
  }

  /**
   * Returns the scene element (e.g., canvas or SVG) of the visualization
   * Subclasses must override if the first child is not the scene element.
   * @return {DOMElement} - The scene (e.g., canvas or SVG) element.
   */
  canvas() {
    return this._el && this._el.firstChild;
  }

  /**
   * Get / set the origin coordinates of the visualization.
   */
  origin(origin) {
    if (arguments.length) {
      this._origin = origin || [0, 0];
      return this;
    } else {
      return this._origin.slice();
    }
  }

  /**
   * Get / set the scenegraph root.
   */
  scene(scene) {
    if (!arguments.length) return this._scene;
    this._scene = scene;
    return this;
  }

  /**
   * Add an event handler. Subclasses should override this method.
   */
  on( /*type, handler*/) {}

  /**
   * Remove an event handler. Subclasses should override this method.
   */
  off( /*type, handler*/) {}

  /**
   * Utility method for finding the array index of an event handler.
   * @param {Array} h - An array of registered event handlers.
   * @param {string} type - The event type.
   * @param {function} handler - The event handler instance to find.
   * @return {number} - The handler's array index or -1 if not registered.
   */
  _handlerIndex(h, type, handler) {
    for (let i = h ? h.length : 0; --i >= 0;) {
      if (h[i].type === type && (!handler || h[i].handler === handler)) {
        return i;
      }
    }
    return -1;
  }

  /**
   * Returns an array with registered event handlers.
   * @param {string} [type] - The event type to query. Any annotations
   *   are ignored; for example, for the argument "click.foo", ".foo" will
   *   be ignored and the method returns all "click" handlers. If type is
   *   null or unspecified, this method returns handlers for all types.
   * @return {Array} - A new array containing all registered event handlers.
   */
  handlers(type) {
    const h = this._handlers,
      a = [];
    if (type) {
      a.push(...h[this.eventName(type)]);
    } else {
      for (const k in h) {
        a.push(...h[k]);
      }
    }
    return a;
  }

  /**
   * Parses an event name string to return the specific event type.
   * For example, given "click.foo" returns "click"
   * @param {string} name - The input event type string.
   * @return {string} - A string with the event type only.
   */
  eventName(name) {
    const i = name.indexOf('.');
    return i < 0 ? name : name.slice(0, i);
  }

  /**
   * Handle hyperlink navigation in response to an item.href value.
   * @param {Event} event - The event triggering hyperlink navigation.
   * @param {Item} item - The scenegraph item.
   * @param {string} href - The URL to navigate to.
   */
  handleHref(event, item, href) {
    this._loader.sanitize(href, {
      context: 'href'
    }).then(opt => {
      const e = new MouseEvent(event.type, event),
        a = standalone_domCreate(null, 'a');
      for (const name in opt) a.setAttribute(name, opt[name]);
      a.dispatchEvent(e);
    }).catch(() => {});
  }

  /**
   * Handle tooltip display in response to an item.tooltip value.
   * @param {Event} event - The event triggering tooltip display.
   * @param {Item} item - The scenegraph item.
   * @param {boolean} show - A boolean flag indicating whether
   *   to show or hide a tooltip for the given item.
   */
  handleTooltip(event, item, show) {
    if (item && item.tooltip != null) {
      item = standalone_resolveItem(item, event, this.canvas(), this._origin);
      const value = show && item && item.tooltip || null;
      this._tooltip.call(this._obj, this, event, item, value);
    }
  }

  /**
   * Returns the size of a scenegraph item and its position relative
   * to the viewport.
   * @param {Item} item - The scenegraph item.
   * @return {object} - A bounding box object (compatible with the
   *   DOMRect type) consisting of x, y, width, heigh, top, left,
   *   right, and bottom properties.
   */
  getItemBoundingClientRect(item) {
    const el = this.canvas();
    if (!el) return;
    const rect = el.getBoundingClientRect(),
      origin = this._origin,
      bounds = item.bounds,
      width = bounds.width(),
      height = bounds.height();
    let x = bounds.x1 + origin[0] + rect.left,
      y = bounds.y1 + origin[1] + rect.top;

    // translate coordinate for each parent group
    while (item.mark && (item = item.mark.group)) {
      x += item.x || 0;
      y += item.y || 0;
    }

    // return DOMRect-compatible bounding box
    return {
      x,
      y,
      width,
      height,
      left: x,
      top: y,
      right: x + width,
      bottom: y + height
    };
  }
}

// The default tooltip display handler.
// Sets the HTML title attribute on the visualization container.
function standalone_defaultTooltip(handler, event, item, value) {
  handler.element().setAttribute('title', value || '');
}

class standalone_Renderer {
  /**
   * Create a new Renderer instance.
   * @param {object} [loader] - Optional loader instance for
   *   image and href URL sanitization. If not specified, a
   *   standard loader instance will be generated.
   * @constructor
   */
  constructor(loader) {
    this._el = null;
    this._bgcolor = null;
    this._loader = new standalone_ResourceLoader(loader);
  }

  /**
   * Initialize a new Renderer instance.
   * @param {DOMElement} el - The containing DOM element for the display.
   * @param {number} width - The coordinate width of the display, in pixels.
   * @param {number} height - The coordinate height of the display, in pixels.
   * @param {Array<number>} origin - The origin of the display, in pixels.
   *   The coordinate system will be translated to this point.
   * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
   *   the width and height to determine the final pixel size.
   * @return {Renderer} - This renderer instance.
   */
  initialize(el, width, height, origin, scaleFactor) {
    this._el = el;
    return this.resize(width, height, origin, scaleFactor);
  }

  /**
   * Returns the parent container element for a visualization.
   * @return {DOMElement} - The containing DOM element.
   */
  element() {
    return this._el;
  }

  /**
   * Returns the scene element (e.g., canvas or SVG) of the visualization
   * Subclasses must override if the first child is not the scene element.
   * @return {DOMElement} - The scene (e.g., canvas or SVG) element.
   */
  canvas() {
    return this._el && this._el.firstChild;
  }

  /**
   * Get / set the background color.
   */
  background(bgcolor) {
    if (arguments.length === 0) return this._bgcolor;
    this._bgcolor = bgcolor;
    return this;
  }

  /**
   * Resize the display.
   * @param {number} width - The new coordinate width of the display, in pixels.
   * @param {number} height - The new coordinate height of the display, in pixels.
   * @param {Array<number>} origin - The new origin of the display, in pixels.
   *   The coordinate system will be translated to this point.
   * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
   *   the width and height to determine the final pixel size.
   * @return {Renderer} - This renderer instance;
   */
  resize(width, height, origin, scaleFactor) {
    this._width = width;
    this._height = height;
    this._origin = origin || [0, 0];
    this._scale = scaleFactor || 1;
    return this;
  }

  /**
   * Report a dirty item whose bounds should be redrawn.
   * This base class method does nothing. Subclasses that perform
   * incremental should implement this method.
   * @param {Item} item - The dirty item whose bounds should be redrawn.
   */
  dirty( /*item*/) {}

  /**
   * Render an input scenegraph, potentially with a set of dirty items.
   * This method will perform an immediate rendering with available resources.
   * The renderer may also need to perform image loading to perform a complete
   * render. This process can lead to asynchronous re-rendering of the scene
   * after this method returns. To receive notification when rendering is
   * complete, use the renderAsync method instead.
   * @param {object} scene - The root mark of a scenegraph to render.
   * @param {Array} markTypes - Array of the mark types to render.
   *                            If undefined, render all mark types
   * @return {Renderer} - This renderer instance.
   */
  render(scene, markTypes) {
    const r = this;

    // bind arguments into a render call, and cache it
    // this function may be subsequently called for async redraw
    r._call = function () {
      r._render(scene, markTypes);
    };

    // invoke the renderer
    r._call();

    // clear the cached call for garbage collection
    // async redraws will stash their own copy
    r._call = null;
    return r;
  }

  /**
   * Internal rendering method. Renderer subclasses should override this
   * method to actually perform rendering.
   * @param {object} scene - The root mark of a scenegraph to render.
   * @param {Array} markTypes - Array of the mark types to render.
   *                            If undefined, render all mark types
   */
  _render( /*scene, markTypes*/
  ) {
    // subclasses to override
  }

  /**
   * Asynchronous rendering method. Similar to render, but returns a Promise
   * that resolves when all rendering is completed. Sometimes a renderer must
   * perform image loading to get a complete rendering. The returned
   * Promise will not resolve until this process completes.
   * @param {object} scene - The root mark of a scenegraph to render.
   * @param {Array} markTypes - Array of the mark types to render.
   *                            If undefined, render all mark types
   * @return {Promise} - A Promise that resolves when rendering is complete.
   */
  renderAsync(scene, markTypes) {
    const r = this.render(scene, markTypes);
    return this._ready ? this._ready.then(() => r) : Promise.resolve(r);
  }

  /**
   * Internal method for asynchronous resource loading.
   * Proxies method calls to the ImageLoader, and tracks loading
   * progress to invoke a re-render once complete.
   * @param {string} method - The method name to invoke on the ImageLoader.
   * @param {string} uri - The URI for the requested resource.
   * @return {Promise} - A Promise that resolves to the requested resource.
   */
  _load(method, uri) {
    var r = this,
      p = r._loader[method](uri);
    if (!r._ready) {
      // re-render the scene when loading completes
      const call = r._call;
      r._ready = r._loader.ready().then(redraw => {
        if (redraw) call();
        r._ready = null;
      });
    }
    return p;
  }

  /**
   * Sanitize a URL to include as a hyperlink in the rendered scene.
   * This method proxies a call to ImageLoader.sanitizeURL, but also tracks
   * image loading progress and invokes a re-render once complete.
   * @param {string} uri - The URI string to sanitize.
   * @return {Promise} - A Promise that resolves to the sanitized URL.
   */
  sanitizeURL(uri) {
    return this._load('sanitizeURL', uri);
  }

  /**
   * Requests an image to include in the rendered scene.
   * This method proxies a call to ImageLoader.loadImage, but also tracks
   * image loading progress and invokes a re-render once complete.
   * @param {string} uri - The URI string of the image.
   * @return {Promise} - A Promise that resolves to the loaded Image.
   */
  loadImage(uri) {
    return this._load('loadImage', uri);
  }
}

const standalone_KeyDownEvent = 'keydown';
const standalone_KeyPressEvent = 'keypress';
const standalone_KeyUpEvent = 'keyup';
const standalone_DragEnterEvent = 'dragenter';
const standalone_DragLeaveEvent = 'dragleave';
const standalone_DragOverEvent = 'dragover';
const standalone_PointerDownEvent = 'pointerdown';
const standalone_PointerUpEvent = 'pointerup';
const standalone_PointerMoveEvent = 'pointermove';
const standalone_PointerOutEvent = 'pointerout';
const standalone_PointerOverEvent = 'pointerover';
const standalone_MouseDownEvent = 'mousedown';
const standalone_MouseUpEvent = 'mouseup';
const standalone_MouseMoveEvent = 'mousemove';
const standalone_MouseOutEvent = 'mouseout';
const standalone_MouseOverEvent = 'mouseover';
const standalone_ClickEvent = 'click';
const standalone_DoubleClickEvent = 'dblclick';
const standalone_WheelEvent = 'wheel';
const standalone_MouseWheelEvent = 'mousewheel';
const standalone_TouchStartEvent = 'touchstart';
const standalone_TouchMoveEvent = 'touchmove';
const standalone_TouchEndEvent = 'touchend';
const standalone_Events = [standalone_KeyDownEvent, standalone_KeyPressEvent, standalone_KeyUpEvent, standalone_DragEnterEvent, standalone_DragLeaveEvent, standalone_DragOverEvent, standalone_PointerDownEvent, standalone_PointerUpEvent, standalone_PointerMoveEvent, standalone_PointerOutEvent, standalone_PointerOverEvent, standalone_MouseDownEvent, standalone_MouseUpEvent, standalone_MouseMoveEvent, standalone_MouseOutEvent, standalone_MouseOverEvent, standalone_ClickEvent, standalone_DoubleClickEvent, standalone_WheelEvent, standalone_MouseWheelEvent, standalone_TouchStartEvent, standalone_TouchMoveEvent, standalone_TouchEndEvent];
const standalone_TooltipShowEvent = standalone_PointerMoveEvent;
const standalone_TooltipHideEvent = standalone_MouseOutEvent;
const standalone_HrefEvent = standalone_ClickEvent;

class standalone_CanvasHandler extends standalone_Handler {
  constructor(loader, tooltip) {
    super(loader, tooltip);
    this._down = null;
    this._touch = null;
    this._first = true;
    this._events = {};

    // supported events
    this.events = standalone_Events;
    this.pointermove = standalone_move([standalone_PointerMoveEvent, standalone_MouseMoveEvent], [standalone_PointerOverEvent, standalone_MouseOverEvent], [standalone_PointerOutEvent, standalone_MouseOutEvent]);
    this.dragover = standalone_move([standalone_DragOverEvent], [standalone_DragEnterEvent], [standalone_DragLeaveEvent]), this.pointerout = standalone_inactive([standalone_PointerOutEvent, standalone_MouseOutEvent]);
    this.dragleave = standalone_inactive([standalone_DragLeaveEvent]);
  }
  initialize(el, origin, obj) {
    this._canvas = el && standalone_domFind(el, 'canvas');

    // add minimal events required for proper state management
    [standalone_ClickEvent, standalone_MouseDownEvent, standalone_PointerDownEvent, standalone_PointerMoveEvent, standalone_PointerOutEvent, standalone_DragLeaveEvent].forEach(type => standalone_eventListenerCheck(this, type));
    return super.initialize(el, origin, obj);
  }

  // return the backing canvas instance
  canvas() {
    return this._canvas;
  }

  // retrieve the current canvas context
  context() {
    return this._canvas.getContext('2d');
  }

  // to keep old versions of firefox happy
  DOMMouseScroll(evt) {
    this.fire(standalone_MouseWheelEvent, evt);
  }
  pointerdown(evt) {
    this._down = this._active;
    this.fire(standalone_PointerDownEvent, evt);
  }
  mousedown(evt) {
    this._down = this._active;
    this.fire(standalone_MouseDownEvent, evt);
  }
  click(evt) {
    if (this._down === this._active) {
      this.fire(standalone_ClickEvent, evt);
      this._down = null;
    }
  }
  touchstart(evt) {
    this._touch = this.pickEvent(evt.changedTouches[0]);
    if (this._first) {
      this._active = this._touch;
      this._first = false;
    }
    this.fire(standalone_TouchStartEvent, evt, true);
  }
  touchmove(evt) {
    this.fire(standalone_TouchMoveEvent, evt, true);
  }
  touchend(evt) {
    this.fire(standalone_TouchEndEvent, evt, true);
    this._touch = null;
  }

  // fire an event
  fire(type, evt, touch) {
    const a = touch ? this._touch : this._active,
      h = this._handlers[type];

    // set event type relative to scenegraph items
    evt.vegaType = type;

    // handle hyperlinks and tooltips first
    if (type === standalone_HrefEvent && a && a.href) {
      this.handleHref(evt, a, a.href);
    } else if (type === standalone_TooltipShowEvent || type === standalone_TooltipHideEvent) {
      this.handleTooltip(evt, a, type !== standalone_TooltipHideEvent);
    }

    // invoke all registered handlers
    if (h) {
      for (let i = 0, len = h.length; i < len; ++i) {
        h[i].handler.call(this._obj, evt, a);
      }
    }
  }

  // add an event handler
  on(type, handler) {
    const name = this.eventName(type),
      h = this._handlers,
      i = this._handlerIndex(h[name], type, handler);
    if (i < 0) {
      standalone_eventListenerCheck(this, type);
      (h[name] || (h[name] = [])).push({
        type: type,
        handler: handler
      });
    }
    return this;
  }

  // remove an event handler
  off(type, handler) {
    const name = this.eventName(type),
      h = this._handlers[name],
      i = this._handlerIndex(h, type, handler);
    if (i >= 0) {
      h.splice(i, 1);
    }
    return this;
  }
  pickEvent(evt) {
    const p = standalone_vega_scenegraph_module_point(evt, this._canvas),
      o = this._origin;
    return this.pick(this._scene, p[0], p[1], p[0] - o[0], p[1] - o[1]);
  }

  // find the scenegraph item at the current pointer position
  // x, y -- the absolute x, y pointer coordinates on the canvas element
  // gx, gy -- the relative coordinates within the current group
  pick(scene, x, y, gx, gy) {
    const g = this.context(),
      mark = standalone_Marks[scene.marktype];
    return mark.pick.call(this, g, scene, x, y, gx, gy);
  }
}
const standalone_eventBundle = type => type === standalone_TouchStartEvent || type === standalone_TouchMoveEvent || type === standalone_TouchEndEvent ? [standalone_TouchStartEvent, standalone_TouchMoveEvent, standalone_TouchEndEvent] : [type];

// lazily add listeners to the canvas as needed
function standalone_eventListenerCheck(handler, type) {
  standalone_eventBundle(type).forEach(_ => standalone_addEventListener(handler, _));
}
function standalone_addEventListener(handler, type) {
  const canvas = handler.canvas();
  if (canvas && !handler._events[type]) {
    handler._events[type] = 1;
    canvas.addEventListener(type, handler[type] ? evt => handler[type](evt) : evt => handler.fire(type, evt));
  }
}
function standalone_fireAll(handler, types, event) {
  types.forEach(type => handler.fire(type, event));
}
function standalone_move(moveEvents, overEvents, outEvents) {
  return function (evt) {
    const a = this._active,
      p = this.pickEvent(evt);
    if (p === a) {
      // active item and picked item are the same
      standalone_fireAll(this, moveEvents, evt); // fire move
    } else {
      // active item and picked item are different
      if (!a || !a.exit) {
        // fire out for prior active item
        // suppress if active item was removed from scene
        standalone_fireAll(this, outEvents, evt);
      }
      this._active = p; // set new active item
      standalone_fireAll(this, overEvents, evt); // fire over for new active item
      standalone_fireAll(this, moveEvents, evt); // fire move for new active item
    }
  };
}
function standalone_inactive(types) {
  return function (evt) {
    standalone_fireAll(this, types, evt);
    this._active = null;
  };
}

function standalone_devicePixelRatio() {
  return typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
}
function standalone_resize (canvas, width, height, origin, scaleFactor, opt) {
  const inDOM = typeof HTMLElement !== 'undefined' && canvas instanceof HTMLElement && canvas.parentNode != null,
    context = canvas.getContext('2d'),
    ratio = inDOM ? standalone_devicePixelRatio() : scaleFactor;
  canvas.width = width * ratio;
  canvas.height = height * ratio;
  for (const key in opt) {
    context[key] = opt[key];
  }
  if (inDOM && ratio !== 1) {
    canvas.style.width = width + 'px';
    canvas.style.height = height + 'px';
  }
  context.pixelRatio = ratio;
  context.setTransform(ratio, 0, 0, ratio, ratio * origin[0], ratio * origin[1]);
  return canvas;
}

class standalone_CanvasRenderer extends standalone_Renderer {
  constructor(loader) {
    super(loader);
    this._options = {};
    this._redraw = false;
    this._dirty = new standalone_Bounds();
    this._tempb = new standalone_Bounds();
  }
  initialize(el, width, height, origin, scaleFactor, options) {
    this._options = options || {};
    this._canvas = this._options.externalContext ? null : standalone_domCanvas(1, 1, this._options.type); // instantiate a small canvas

    if (el && this._canvas) {
      standalone_domClear(el, 0).appendChild(this._canvas);
      this._canvas.setAttribute('class', 'marks');
    }

    // this method will invoke resize to size the canvas appropriately
    return super.initialize(el, width, height, origin, scaleFactor);
  }
  resize(width, height, origin, scaleFactor) {
    super.resize(width, height, origin, scaleFactor);
    if (this._canvas) {
      // configure canvas size and transform
      standalone_resize(this._canvas, this._width, this._height, this._origin, this._scale, this._options.context);
    } else {
      // external context needs to be scaled and positioned to origin
      const ctx = this._options.externalContext;
      if (!ctx) standalone_vega_util_module_error('CanvasRenderer is missing a valid canvas or context');
      ctx.scale(this._scale, this._scale);
      ctx.translate(this._origin[0], this._origin[1]);
    }
    this._redraw = true;
    return this;
  }
  canvas() {
    return this._canvas;
  }
  context() {
    return this._options.externalContext || (this._canvas ? this._canvas.getContext('2d') : null);
  }
  dirty(item) {
    const b = this._tempb.clear().union(item.bounds);
    let g = item.mark.group;
    while (g) {
      b.translate(g.x || 0, g.y || 0);
      g = g.mark.group;
    }
    this._dirty.union(b);
  }
  _render(scene, markTypes) {
    const g = this.context(),
      o = this._origin,
      w = this._width,
      h = this._height,
      db = this._dirty,
      vb = standalone_viewBounds(o, w, h);

    // setup
    g.save();
    const b = this._redraw || db.empty() ? (this._redraw = false, vb.expand(1)) : standalone_clipToBounds(g, vb.intersect(db), o);
    this.clear(-o[0], -o[1], w, h);

    // render
    this.draw(g, scene, b, markTypes);

    // takedown
    g.restore();
    db.clear();
    return this;
  }
  draw(ctx, scene, bounds, markTypes) {
    if (scene.marktype !== 'group' && markTypes != null && !markTypes.includes(scene.marktype)) {
      return;
    }
    const mark = standalone_Marks[scene.marktype];
    if (scene.clip) standalone_clip(ctx, scene);
    mark.draw.call(this, ctx, scene, bounds, markTypes);
    if (scene.clip) ctx.restore();
  }
  clear(x, y, w, h) {
    const opt = this._options,
      g = this.context();
    if (opt.type !== 'pdf' && !opt.externalContext) {
      // calling clear rect voids vector output in pdf mode
      // and could remove external context content (#2615)
      g.clearRect(x, y, w, h);
    }
    if (this._bgcolor != null) {
      g.fillStyle = this._bgcolor;
      g.fillRect(x, y, w, h);
    }
  }
}
const standalone_viewBounds = (origin, width, height) => new standalone_Bounds().set(0, 0, width, height).translate(-origin[0], -origin[1]);
function standalone_clipToBounds(g, b, origin) {
  // expand bounds by 1 pixel, then round to pixel boundaries
  b.expand(1).round();

  // align to base pixel grid in case of non-integer scaling (#2425)
  if (g.pixelRatio % 1) {
    b.scale(g.pixelRatio).round().scale(1 / g.pixelRatio);
  }

  // to avoid artifacts translate if origin has fractional pixels
  b.translate(-(origin[0] % 1), -(origin[1] % 1));

  // set clip path
  g.beginPath();
  g.rect(b.x1, b.y1, b.width(), b.height());
  g.clip();
  return b;
}

class standalone_SVGHandler extends standalone_Handler {
  constructor(loader, tooltip) {
    super(loader, tooltip);
    const h = this;
    h._hrefHandler = standalone_listener(h, (evt, item) => {
      if (item && item.href) h.handleHref(evt, item, item.href);
    });
    h._tooltipHandler = standalone_listener(h, (evt, item) => {
      h.handleTooltip(evt, item, evt.type !== standalone_TooltipHideEvent);
    });
  }
  initialize(el, origin, obj) {
    let svg = this._svg;
    if (svg) {
      svg.removeEventListener(standalone_HrefEvent, this._hrefHandler);
      svg.removeEventListener(standalone_TooltipShowEvent, this._tooltipHandler);
      svg.removeEventListener(standalone_TooltipHideEvent, this._tooltipHandler);
    }
    this._svg = svg = el && standalone_domFind(el, 'svg');
    if (svg) {
      svg.addEventListener(standalone_HrefEvent, this._hrefHandler);
      svg.addEventListener(standalone_TooltipShowEvent, this._tooltipHandler);
      svg.addEventListener(standalone_TooltipHideEvent, this._tooltipHandler);
    }
    return super.initialize(el, origin, obj);
  }
  canvas() {
    return this._svg;
  }

  // add an event handler
  on(type, handler) {
    const name = this.eventName(type),
      h = this._handlers,
      i = this._handlerIndex(h[name], type, handler);
    if (i < 0) {
      const x = {
        type,
        handler,
        listener: standalone_listener(this, handler)
      };
      (h[name] || (h[name] = [])).push(x);
      if (this._svg) {
        this._svg.addEventListener(name, x.listener);
      }
    }
    return this;
  }

  // remove an event handler
  off(type, handler) {
    const name = this.eventName(type),
      h = this._handlers[name],
      i = this._handlerIndex(h, type, handler);
    if (i >= 0) {
      if (this._svg) {
        this._svg.removeEventListener(name, h[i].listener);
      }
      h.splice(i, 1);
    }
    return this;
  }
}

// wrap an event listener for the SVG DOM
const standalone_listener = (context, handler) => evt => {
  let item = evt.target.__data__;
  item = Array.isArray(item) ? item[0] : item;
  evt.vegaType = evt.type;
  handler.call(context._obj, evt, item);
};

const standalone_ARIA_HIDDEN = 'aria-hidden';
const standalone_ARIA_LABEL = 'aria-label';
const standalone_ARIA_ROLE = 'role';
const standalone_ARIA_ROLEDESCRIPTION = 'aria-roledescription';
const standalone_GRAPHICS_OBJECT = 'graphics-object';
const standalone_GRAPHICS_SYMBOL = 'graphics-symbol';
const standalone_vega_scenegraph_module_bundle = (role, roledesc, label) => ({
  [standalone_ARIA_ROLE]: role,
  [standalone_ARIA_ROLEDESCRIPTION]: roledesc,
  [standalone_ARIA_LABEL]: label || undefined
});

// these roles are covered by related roles
// we can ignore them, no need to generate attributes
const standalone_AriaIgnore = standalone_toSet(['axis-domain', 'axis-grid', 'axis-label', 'axis-tick', 'axis-title', 'legend-band', 'legend-entry', 'legend-gradient', 'legend-label', 'legend-title', 'legend-symbol', 'title']);

// aria attribute generators for guide roles
const standalone_AriaGuides = {
  'axis': {
    desc: 'axis',
    caption: standalone_axisCaption
  },
  'legend': {
    desc: 'legend',
    caption: standalone_legendCaption
  },
  'title-text': {
    desc: 'title',
    caption: item => `Title text '${standalone_titleCaption(item)}'`
  },
  'title-subtitle': {
    desc: 'subtitle',
    caption: item => `Subtitle text '${standalone_titleCaption(item)}'`
  }
};

// aria properties generated for mark item encoding channels
const standalone_AriaEncode = {
  ariaRole: standalone_ARIA_ROLE,
  ariaRoleDescription: standalone_ARIA_ROLEDESCRIPTION,
  description: standalone_ARIA_LABEL
};
function standalone_ariaItemAttributes(emit, item) {
  const hide = item.aria === false;
  emit(standalone_ARIA_HIDDEN, hide || undefined);
  if (hide || item.description == null) {
    for (const prop in standalone_AriaEncode) {
      emit(standalone_AriaEncode[prop], undefined);
    }
  } else {
    const type = item.mark.marktype;
    emit(standalone_ARIA_LABEL, item.description);
    emit(standalone_ARIA_ROLE, item.ariaRole || (type === 'group' ? standalone_GRAPHICS_OBJECT : standalone_GRAPHICS_SYMBOL));
    emit(standalone_ARIA_ROLEDESCRIPTION, item.ariaRoleDescription || `${type} mark`);
  }
}
function standalone_ariaMarkAttributes(mark) {
  return mark.aria === false ? {
    [standalone_ARIA_HIDDEN]: true
  } : standalone_AriaIgnore[mark.role] ? null : standalone_AriaGuides[mark.role] ? standalone_ariaGuide(mark, standalone_AriaGuides[mark.role]) : standalone_ariaMark(mark);
}
function standalone_ariaMark(mark) {
  const type = mark.marktype;
  const recurse = type === 'group' || type === 'text' || mark.items.some(_ => _.description != null && _.aria !== false);
  return standalone_vega_scenegraph_module_bundle(recurse ? standalone_GRAPHICS_OBJECT : standalone_GRAPHICS_SYMBOL, `${type} mark container`, mark.description);
}
function standalone_ariaGuide(mark, opt) {
  try {
    const item = mark.items[0],
      caption = opt.caption || (() => '');
    return standalone_vega_scenegraph_module_bundle(opt.role || standalone_GRAPHICS_SYMBOL, opt.desc, item.description || caption(item));
  } catch (err) {
    return null;
  }
}
function standalone_titleCaption(item) {
  return standalone_array(item.text).join(' ');
}
function standalone_axisCaption(item) {
  const datum = item.datum,
    orient = item.orient,
    title = datum.title ? standalone_extractTitle(item) : null,
    ctx = item.context,
    scale = ctx.scales[datum.scale].value,
    locale = ctx.dataflow.locale(),
    type = scale.type,
    xy = orient === 'left' || orient === 'right' ? 'Y' : 'X';
  return `${xy}-axis` + (title ? ` titled '${title}'` : '') + ` for a ${standalone_isDiscrete(type) ? 'discrete' : type} scale` + ` with ${standalone_domainCaption(locale, scale, item)}`;
}
function standalone_legendCaption(item) {
  const datum = item.datum,
    title = datum.title ? standalone_extractTitle(item) : null,
    type = `${datum.type || ''} legend`.trim(),
    scales = datum.scales,
    props = Object.keys(scales),
    ctx = item.context,
    scale = ctx.scales[scales[props[0]]].value,
    locale = ctx.dataflow.locale();
  return standalone_capitalize(type) + (title ? ` titled '${title}'` : '') + ` for ${standalone_channelCaption(props)}` + ` with ${standalone_domainCaption(locale, scale, item)}`;
}
function standalone_extractTitle(item) {
  try {
    return standalone_array(standalone_peek(item.items).items[0].text).join(' ');
  } catch (err) {
    return null;
  }
}
function standalone_channelCaption(props) {
  props = props.map(p => p + (p === 'fill' || p === 'stroke' ? ' color' : ''));
  return props.length < 2 ? props[0] : props.slice(0, -1).join(', ') + ' and ' + standalone_peek(props);
}
function standalone_capitalize(s) {
  return s.length ? s[0].toUpperCase() + s.slice(1) : s;
}

const standalone_innerText = val => (val + '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const standalone_attrText = val => standalone_innerText(val).replace(/"/g, '&quot;').replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;').replace(/\r/g, '&#xD;');
function standalone_markup() {
  let buf = '',
    outer = '',
    inner = '';
  const stack = [],
    clear = () => outer = inner = '',
    push = tag => {
      if (outer) {
        buf += `${outer}>${inner}`;
        clear();
      }
      stack.push(tag);
    },
    attr = (name, value) => {
      if (value != null) outer += ` ${name}="${standalone_attrText(value)}"`;
      return m;
    },
    m = {
      open(tag) {
        push(tag);
        outer = '<' + tag;
        for (var _len = arguments.length, attrs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          attrs[_key - 1] = arguments[_key];
        }
        for (const set of attrs) {
          for (const key in set) attr(key, set[key]);
        }
        return m;
      },
      close() {
        const tag = stack.pop();
        if (outer) {
          buf += outer + (inner ? `>${inner}</${tag}>` : '/>');
        } else {
          buf += `</${tag}>`;
        }
        clear();
        return m;
      },
      attr,
      text: t => (inner += standalone_innerText(t), m),
      toString: () => buf
    };
  return m;
}
const standalone_serializeXML = node => standalone_serialize(standalone_markup(), node) + '';
function standalone_serialize(m, node) {
  m.open(node.tagName);
  if (node.hasAttributes()) {
    const attrs = node.attributes,
      n = attrs.length;
    for (let i = 0; i < n; ++i) {
      m.attr(attrs[i].name, attrs[i].value);
    }
  }
  if (node.hasChildNodes()) {
    const children = node.childNodes;
    for (const child of children) {
      child.nodeType === 3 // text node
      ? m.text(child.nodeValue) : standalone_serialize(m, child);
    }
  }
  return m.close();
}

const standalone_stylesAttr = {
  fill: 'fill',
  fillOpacity: 'fill-opacity',
  stroke: 'stroke',
  strokeOpacity: 'stroke-opacity',
  strokeWidth: 'stroke-width',
  strokeCap: 'stroke-linecap',
  strokeJoin: 'stroke-linejoin',
  strokeDash: 'stroke-dasharray',
  strokeDashOffset: 'stroke-dashoffset',
  strokeMiterLimit: 'stroke-miterlimit',
  opacity: 'opacity'
};
const standalone_stylesCss = {
  blend: 'mix-blend-mode'
};

// ensure miter limit default is consistent with canvas (#2498)
const standalone_rootAttributes = {
  'fill': 'none',
  'stroke-miterlimit': 10
};

const standalone_RootIndex = 0,
  standalone_xmlns = 'http://www.w3.org/2000/xmlns/',
  standalone_svgns = standalone_metadata.xmlns;
class standalone_SVGRenderer extends standalone_Renderer {
  constructor(loader) {
    super(loader);
    this._dirtyID = 0;
    this._dirty = [];
    this._svg = null;
    this._root = null;
    this._defs = null;
  }

  /**
   * Initialize a new SVGRenderer instance.
   * @param {DOMElement} el - The containing DOM element for the display.
   * @param {number} width - The coordinate width of the display, in pixels.
   * @param {number} height - The coordinate height of the display, in pixels.
   * @param {Array<number>} origin - The origin of the display, in pixels.
   *   The coordinate system will be translated to this point.
   * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
   *   the width and height to determine the final pixel size.
   * @return {SVGRenderer} - This renderer instance.
   */
  initialize(el, width, height, origin, scaleFactor) {
    // create the svg definitions cache
    this._defs = {};
    this._clearDefs();
    if (el) {
      this._svg = standalone_domChild(el, 0, 'svg', standalone_svgns);
      this._svg.setAttributeNS(standalone_xmlns, 'xmlns', standalone_svgns);
      this._svg.setAttributeNS(standalone_xmlns, 'xmlns:xlink', standalone_metadata['xmlns:xlink']);
      this._svg.setAttribute('version', standalone_metadata['version']);
      this._svg.setAttribute('class', 'marks');
      standalone_domClear(el, 1);

      // set the svg root group
      this._root = standalone_domChild(this._svg, standalone_RootIndex, 'g', standalone_svgns);
      standalone_setAttributes(this._root, standalone_rootAttributes);

      // ensure no additional child elements
      standalone_domClear(this._svg, standalone_RootIndex + 1);
    }

    // set background color if defined
    this.background(this._bgcolor);
    return super.initialize(el, width, height, origin, scaleFactor);
  }

  /**
   * Get / set the background color.
   */
  background(bgcolor) {
    if (arguments.length && this._svg) {
      this._svg.style.setProperty('background-color', bgcolor);
    }
    return super.background(...arguments);
  }

  /**
   * Resize the display.
   * @param {number} width - The new coordinate width of the display, in pixels.
   * @param {number} height - The new coordinate height of the display, in pixels.
   * @param {Array<number>} origin - The new origin of the display, in pixels.
   *   The coordinate system will be translated to this point.
   * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
   *   the width and height to determine the final pixel size.
   * @return {SVGRenderer} - This renderer instance;
   */
  resize(width, height, origin, scaleFactor) {
    super.resize(width, height, origin, scaleFactor);
    if (this._svg) {
      standalone_setAttributes(this._svg, {
        width: this._width * this._scale,
        height: this._height * this._scale,
        viewBox: `0 0 ${this._width} ${this._height}`
      });
      this._root.setAttribute('transform', `translate(${this._origin})`);
    }
    this._dirty = [];
    return this;
  }

  /**
   * Returns the SVG element of the visualization.
   * @return {DOMElement} - The SVG element.
   */
  canvas() {
    return this._svg;
  }

  /**
   * Returns an SVG text string for the rendered content,
   * or null if this renderer is currently headless.
   */
  svg() {
    const svg = this._svg,
      bg = this._bgcolor;
    if (!svg) return null;
    let node;
    if (bg) {
      svg.removeAttribute('style');
      node = standalone_domChild(svg, standalone_RootIndex, 'rect', standalone_svgns);
      standalone_setAttributes(node, {
        width: this._width,
        height: this._height,
        fill: bg
      });
    }
    const text = standalone_serializeXML(svg);
    if (bg) {
      svg.removeChild(node);
      this._svg.style.setProperty('background-color', bg);
    }
    return text;
  }

  /**
   * Internal rendering method.
   * @param {object} scene - The root mark of a scenegraph to render.
   * @param {Array} markTypes - Array of the mark types to render.
   *                            If undefined, render all mark types
   */
  _render(scene, markTypes) {
    // perform spot updates and re-render markup
    if (this._dirtyCheck()) {
      if (this._dirtyAll) this._clearDefs();
      this.mark(this._root, scene, undefined, markTypes);
      standalone_domClear(this._root, 1);
    }
    this.defs();
    this._dirty = [];
    ++this._dirtyID;
    return this;
  }

  // -- Manage rendering of items marked as dirty --

  /**
   * Flag a mark item as dirty.
   * @param {Item} item - The mark item.
   */
  dirty(item) {
    if (item.dirty !== this._dirtyID) {
      item.dirty = this._dirtyID;
      this._dirty.push(item);
    }
  }

  /**
   * Check if a mark item is considered dirty.
   * @param {Item} item - The mark item.
   */
  isDirty(item) {
    return this._dirtyAll || !item._svg || !item._svg.ownerSVGElement || item.dirty === this._dirtyID;
  }

  /**
   * Internal method to check dirty status and, if possible,
   * make targetted updates without a full rendering pass.
   */
  _dirtyCheck() {
    this._dirtyAll = true;
    const items = this._dirty;
    if (!items.length || !this._dirtyID) return true;
    const id = ++this._dirtyID;
    let item, mark, type, mdef, i, n, o;
    for (i = 0, n = items.length; i < n; ++i) {
      item = items[i];
      mark = item.mark;
      if (mark.marktype !== type) {
        // memoize mark instance lookup
        type = mark.marktype;
        mdef = standalone_Marks[type];
      }
      if (mark.zdirty && mark.dirty !== id) {
        this._dirtyAll = false;
        standalone_dirtyParents(item, id);
        mark.items.forEach(i => {
          i.dirty = id;
        });
      }
      if (mark.zdirty) continue; // handle in standard drawing pass

      if (item.exit) {
        // EXIT
        if (mdef.nested && mark.items.length) {
          // if nested mark with remaining points, update instead
          o = mark.items[0];
          if (o._svg) this._update(mdef, o._svg, o);
        } else if (item._svg) {
          // otherwise remove from DOM
          o = item._svg.parentNode;
          if (o) o.removeChild(item._svg);
        }
        item._svg = null;
        continue;
      }
      item = mdef.nested ? mark.items[0] : item;
      if (item._update === id) continue; // already visited

      if (!item._svg || !item._svg.ownerSVGElement) {
        // ENTER
        this._dirtyAll = false;
        standalone_dirtyParents(item, id);
      } else {
        // IN-PLACE UPDATE
        this._update(mdef, item._svg, item);
      }
      item._update = id;
    }
    return !this._dirtyAll;
  }

  // -- Construct & maintain scenegraph to SVG mapping ---

  /**
   * Render a set of mark items.
   * @param {SVGElement} el - The parent element in the SVG tree.
   * @param {object} scene - The mark parent to render.
   * @param {SVGElement} prev - The previous sibling in the SVG tree.
   * @param {Array} markTypes - Array of the mark types to render.
   *                            If undefined, render all mark types
   */
  mark(el, scene, prev, markTypes) {
    if (!this.isDirty(scene)) {
      return scene._svg;
    }
    const svg = this._svg,
      markType = scene.marktype,
      mdef = standalone_Marks[markType],
      events = scene.interactive === false ? 'none' : null,
      isGroup = mdef.tag === 'g';
    const parent = standalone_vega_scenegraph_module_bind(scene, el, prev, 'g', svg);
    if (markType !== 'group' && markTypes != null && !markTypes.includes(markType)) {
      standalone_domClear(parent, 0);
      return scene._svg;
    }
    parent.setAttribute('class', standalone_cssClass(scene));

    // apply aria attributes to parent container element
    const aria = standalone_ariaMarkAttributes(scene);
    for (const key in aria) standalone_setAttribute(parent, key, aria[key]);
    if (!isGroup) {
      standalone_setAttribute(parent, 'pointer-events', events);
    }
    standalone_setAttribute(parent, 'clip-path', scene.clip ? standalone_clip$1(this, scene, scene.group) : null);
    let sibling = null,
      i = 0;
    const process = item => {
      const dirty = this.isDirty(item),
        node = standalone_vega_scenegraph_module_bind(item, parent, sibling, mdef.tag, svg);
      if (dirty) {
        this._update(mdef, node, item);
        if (isGroup) standalone_recurse(this, node, item, markTypes);
      }
      sibling = node;
      ++i;
    };
    if (mdef.nested) {
      if (scene.items.length) process(scene.items[0]);
    } else {
      standalone_visit(scene, process);
    }
    standalone_domClear(parent, i);
    return parent;
  }

  /**
   * Update the attributes of an SVG element for a mark item.
   * @param {object} mdef - The mark definition object
   * @param {SVGElement} el - The SVG element.
   * @param {Item} item - The mark item.
   */
  _update(mdef, el, item) {
    // set dom element and values cache
    // provides access to emit method
    standalone_vega_scenegraph_module_element = el;
    standalone_values = el.__values__;

    // apply aria-specific properties
    standalone_ariaItemAttributes(standalone_emit, item);

    // apply svg attributes
    mdef.attr(standalone_emit, item, this);

    // some marks need special treatment
    const extra = standalone_mark_extras[mdef.type];
    if (extra) extra.call(this, mdef, el, item);

    // apply svg style attributes
    // note: element state may have been modified by 'extra' method
    if (standalone_vega_scenegraph_module_element) this.style(standalone_vega_scenegraph_module_element, item);
  }

  /**
   * Update the presentation attributes of an SVG element for a mark item.
   * @param {SVGElement} el - The SVG element.
   * @param {Item} item - The mark item.
   */
  style(el, item) {
    if (item == null) return;
    for (const prop in standalone_stylesAttr) {
      let value = prop === 'font' ? standalone_fontFamily(item) : item[prop];
      if (value === standalone_values[prop]) continue;
      const name = standalone_stylesAttr[prop];
      if (value == null) {
        el.removeAttribute(name);
      } else {
        if (standalone_isGradient(value)) {
          value = standalone_gradientRef(value, this._defs.gradient, standalone_href());
        }
        el.setAttribute(name, value + '');
      }
      standalone_values[prop] = value;
    }
    for (const prop in standalone_stylesCss) {
      standalone_setStyle(el, standalone_stylesCss[prop], item[prop]);
    }
  }

  /**
   * Render SVG defs, as needed.
   * Must be called *after* marks have been processed to ensure the
   * collected state is current and accurate.
   */
  defs() {
    const svg = this._svg,
      defs = this._defs;
    let el = defs.el,
      index = 0;
    for (const id in defs.gradient) {
      if (!el) defs.el = el = standalone_domChild(svg, standalone_RootIndex + 1, 'defs', standalone_svgns);
      index = standalone_updateGradient(el, defs.gradient[id], index);
    }
    for (const id in defs.clipping) {
      if (!el) defs.el = el = standalone_domChild(svg, standalone_RootIndex + 1, 'defs', standalone_svgns);
      index = standalone_updateClipping(el, defs.clipping[id], index);
    }

    // clean-up
    if (el) {
      index === 0 ? (svg.removeChild(el), defs.el = null) : standalone_domClear(el, index);
    }
  }

  /**
   * Clear defs caches.
   */
  _clearDefs() {
    const def = this._defs;
    def.gradient = {};
    def.clipping = {};
  }
}

// mark ancestor chain with a dirty id
function standalone_dirtyParents(item, id) {
  for (; item && item.dirty !== id; item = item.mark.group) {
    item.dirty = id;
    if (item.mark && item.mark.dirty !== id) {
      item.mark.dirty = id;
    } else return;
  }
}

// update gradient definitions
function standalone_updateGradient(el, grad, index) {
  let i, n, stop;
  if (grad.gradient === 'radial') {
    // SVG radial gradients automatically transform to normalized bbox
    // coordinates, in a way that is cumbersome to replicate in canvas.
    // We wrap the radial gradient in a pattern element, allowing us to
    // maintain a circular gradient that matches what canvas provides.
    let pt = standalone_domChild(el, index++, 'pattern', standalone_svgns);
    standalone_setAttributes(pt, {
      id: standalone_patternPrefix + grad.id,
      viewBox: '0,0,1,1',
      width: '100%',
      height: '100%',
      preserveAspectRatio: 'xMidYMid slice'
    });
    pt = standalone_domChild(pt, 0, 'rect', standalone_svgns);
    standalone_setAttributes(pt, {
      width: 1,
      height: 1,
      fill: `url(${standalone_href()}#${grad.id})`
    });
    el = standalone_domChild(el, index++, 'radialGradient', standalone_svgns);
    standalone_setAttributes(el, {
      id: grad.id,
      fx: grad.x1,
      fy: grad.y1,
      fr: grad.r1,
      cx: grad.x2,
      cy: grad.y2,
      r: grad.r2
    });
  } else {
    el = standalone_domChild(el, index++, 'linearGradient', standalone_svgns);
    standalone_setAttributes(el, {
      id: grad.id,
      x1: grad.x1,
      x2: grad.x2,
      y1: grad.y1,
      y2: grad.y2
    });
  }
  for (i = 0, n = grad.stops.length; i < n; ++i) {
    stop = standalone_domChild(el, i, 'stop', standalone_svgns);
    stop.setAttribute('offset', grad.stops[i].offset);
    stop.setAttribute('stop-color', grad.stops[i].color);
  }
  standalone_domClear(el, i);
  return index;
}

// update clipping path definitions
function standalone_updateClipping(el, clip, index) {
  let mask;
  el = standalone_domChild(el, index, 'clipPath', standalone_svgns);
  el.setAttribute('id', clip.id);
  if (clip.path) {
    mask = standalone_domChild(el, 0, 'path', standalone_svgns);
    mask.setAttribute('d', clip.path);
  } else {
    mask = standalone_domChild(el, 0, 'rect', standalone_svgns);
    standalone_setAttributes(mask, {
      x: 0,
      y: 0,
      width: clip.width,
      height: clip.height
    });
  }
  standalone_domClear(el, 1);
  return index + 1;
}

// Recursively process group contents.
function standalone_recurse(renderer, el, group, markTypes) {
  // child 'g' element is second to last among children (path, g, path)
  // other children here are foreground and background path elements
  el = el.lastChild.previousSibling;
  let prev,
    idx = 0;
  standalone_visit(group, item => {
    prev = renderer.mark(el, item, prev, markTypes);
    ++idx;
  });

  // remove any extraneous DOM elements
  standalone_domClear(el, 1 + idx);
}

// Bind a scenegraph item to an SVG DOM element.
// Create new SVG elements as needed.
function standalone_vega_scenegraph_module_bind(item, el, sibling, tag, svg) {
  let node = item._svg,
    doc;

  // create a new dom node if needed
  if (!node) {
    doc = el.ownerDocument;
    node = standalone_domCreate(doc, tag, standalone_svgns);
    item._svg = node;
    if (item.mark) {
      node.__data__ = item;
      node.__values__ = {
        fill: 'default'
      };

      // if group, create background, content, and foreground elements
      if (tag === 'g') {
        const bg = standalone_domCreate(doc, 'path', standalone_svgns);
        node.appendChild(bg);
        bg.__data__ = item;
        const cg = standalone_domCreate(doc, 'g', standalone_svgns);
        node.appendChild(cg);
        cg.__data__ = item;
        const fg = standalone_domCreate(doc, 'path', standalone_svgns);
        node.appendChild(fg);
        fg.__data__ = item;
        fg.__values__ = {
          fill: 'default'
        };
      }
    }
  }

  // (re-)insert if (a) not contained in SVG or (b) sibling order has changed
  if (node.ownerSVGElement !== svg || standalone_siblingCheck(node, sibling)) {
    el.insertBefore(node, sibling ? sibling.nextSibling : el.firstChild);
  }
  return node;
}

// check if two nodes are ordered siblings
function standalone_siblingCheck(node, sibling) {
  return node.parentNode && node.parentNode.childNodes.length > 1 && node.previousSibling != sibling; // treat null/undefined the same
}

// -- Set attributes & styles on SVG elements ---

let standalone_vega_scenegraph_module_element = null,
  // temp var for current SVG element
  standalone_values = null; // temp var for current values hash

// Extra configuration for certain mark types
const standalone_mark_extras = {
  group(mdef, el, item) {
    const fg = standalone_vega_scenegraph_module_element = el.childNodes[2];
    standalone_values = fg.__values__;
    mdef.foreground(standalone_emit, item, this);
    standalone_values = el.__values__; // use parent's values hash
    standalone_vega_scenegraph_module_element = el.childNodes[1];
    mdef.content(standalone_emit, item, this);
    const bg = standalone_vega_scenegraph_module_element = el.childNodes[0];
    mdef.background(standalone_emit, item, this);
    const value = item.mark.interactive === false ? 'none' : null;
    if (value !== standalone_values.events) {
      standalone_setAttribute(fg, 'pointer-events', value);
      standalone_setAttribute(bg, 'pointer-events', value);
      standalone_values.events = value;
    }
    if (item.strokeForeground && item.stroke) {
      const fill = item.fill;
      standalone_setAttribute(fg, 'display', null);

      // set style of background
      this.style(bg, item);
      standalone_setAttribute(bg, 'stroke', null);

      // set style of foreground
      if (fill) item.fill = null;
      standalone_values = fg.__values__;
      this.style(fg, item);
      if (fill) item.fill = fill;

      // leave element null to prevent downstream styling
      standalone_vega_scenegraph_module_element = null;
    } else {
      // ensure foreground is ignored
      standalone_setAttribute(fg, 'display', 'none');
    }
  },
  image(mdef, el, item) {
    if (item.smooth === false) {
      standalone_setStyle(el, 'image-rendering', 'optimizeSpeed');
      standalone_setStyle(el, 'image-rendering', 'pixelated');
    } else {
      standalone_setStyle(el, 'image-rendering', null);
    }
  },
  text(mdef, el, item) {
    const tl = standalone_textLines(item);
    let key, value, doc, lh;
    if (standalone_vega_util_module_isArray(tl)) {
      // multi-line text
      value = tl.map(_ => standalone_textValue(item, _));
      key = value.join('\n'); // content cache key

      if (key !== standalone_values.text) {
        standalone_domClear(el, 0);
        doc = el.ownerDocument;
        lh = standalone_lineHeight(item);
        value.forEach((t, i) => {
          const ts = standalone_domCreate(doc, 'tspan', standalone_svgns);
          ts.__data__ = item; // data binding
          ts.textContent = t;
          if (i) {
            ts.setAttribute('x', 0);
            ts.setAttribute('dy', lh);
          }
          el.appendChild(ts);
        });
        standalone_values.text = key;
      }
    } else {
      // single-line text
      value = standalone_textValue(item, tl);
      if (value !== standalone_values.text) {
        el.textContent = value;
        standalone_values.text = value;
      }
    }
    standalone_setAttribute(el, 'font-family', standalone_fontFamily(item));
    standalone_setAttribute(el, 'font-size', standalone_fontSize(item) + 'px');
    standalone_setAttribute(el, 'font-style', item.fontStyle);
    standalone_setAttribute(el, 'font-variant', item.fontVariant);
    standalone_setAttribute(el, 'font-weight', item.fontWeight);
  }
};
function standalone_emit(name, value, ns) {
  // early exit if value is unchanged
  if (value === standalone_values[name]) return;

  // use appropriate method given namespace (ns)
  if (ns) {
    standalone_setAttributeNS(standalone_vega_scenegraph_module_element, name, value, ns);
  } else {
    standalone_setAttribute(standalone_vega_scenegraph_module_element, name, value);
  }

  // note current value for future comparison
  standalone_values[name] = value;
}
function standalone_setStyle(el, name, value) {
  if (value !== standalone_values[name]) {
    if (value == null) {
      el.style.removeProperty(name);
    } else {
      el.style.setProperty(name, value + '');
    }
    standalone_values[name] = value;
  }
}
function standalone_setAttributes(el, attrs) {
  for (const key in attrs) {
    standalone_setAttribute(el, key, attrs[key]);
  }
}
function standalone_setAttribute(el, name, value) {
  if (value != null) {
    // if value is provided, update DOM attribute
    el.setAttribute(name, value);
  } else {
    // else remove DOM attribute
    el.removeAttribute(name);
  }
}
function standalone_setAttributeNS(el, name, value, ns) {
  if (value != null) {
    // if value is provided, update DOM attribute
    el.setAttributeNS(ns, name, value);
  } else {
    // else remove DOM attribute
    el.removeAttributeNS(ns, name);
  }
}
function standalone_href() {
  let loc;
  return typeof window === 'undefined' ? '' : (loc = window.location).hash ? loc.href.slice(0, -loc.hash.length) : loc.href;
}

class standalone_SVGStringRenderer extends standalone_Renderer {
  constructor(loader) {
    super(loader);
    this._text = null;
    this._defs = {
      gradient: {},
      clipping: {}
    };
  }

  /**
   * Returns the rendered SVG text string,
   * or null if rendering has not yet occurred.
   */
  svg() {
    return this._text;
  }

  /**
   * Internal rendering method.
   * @param {object} scene - The root mark of a scenegraph to render.
   */
  _render(scene) {
    const m = standalone_markup();

    // svg tag
    m.open('svg', standalone_extend({}, standalone_metadata, {
      class: 'marks',
      width: this._width * this._scale,
      height: this._height * this._scale,
      viewBox: `0 0 ${this._width} ${this._height}`
    }));

    // background, if defined
    const bg = this._bgcolor;
    if (bg && bg !== 'transparent' && bg !== 'none') {
      m.open('rect', {
        width: this._width,
        height: this._height,
        fill: bg
      }).close();
    }

    // root content group
    m.open('g', standalone_rootAttributes, {
      transform: 'translate(' + this._origin + ')'
    });
    this.mark(m, scene);
    m.close(); // </g>

    // defs
    this.defs(m);

    // get SVG text string
    this._text = m.close() + '';
    return this;
  }

  /**
   * Render a set of mark items.
   * @param {object} m - The markup context.
   * @param {object} scene - The mark parent to render.
   */
  mark(m, scene) {
    const mdef = standalone_Marks[scene.marktype],
      tag = mdef.tag,
      attrList = [standalone_ariaItemAttributes, mdef.attr];

    // render opening group tag
    m.open('g', {
      'class': standalone_cssClass(scene),
      'clip-path': scene.clip ? standalone_clip$1(this, scene, scene.group) : null
    }, standalone_ariaMarkAttributes(scene), {
      'pointer-events': tag !== 'g' && scene.interactive === false ? 'none' : null
    });

    // render contained elements
    const process = item => {
      const href = this.href(item);
      if (href) m.open('a', href);
      m.open(tag, this.attr(scene, item, attrList, tag !== 'g' ? tag : null));
      if (tag === 'text') {
        const tl = standalone_textLines(item);
        if (standalone_vega_util_module_isArray(tl)) {
          // multi-line text
          const attrs = {
            x: 0,
            dy: standalone_lineHeight(item)
          };
          for (let i = 0; i < tl.length; ++i) {
            m.open('tspan', i ? attrs : null).text(standalone_textValue(item, tl[i])).close();
          }
        } else {
          // single-line text
          m.text(standalone_textValue(item, tl));
        }
      } else if (tag === 'g') {
        const fore = item.strokeForeground,
          fill = item.fill,
          stroke = item.stroke;
        if (fore && stroke) {
          item.stroke = null;
        }
        m.open('path', this.attr(scene, item, mdef.background, 'bgrect')).close();

        // recurse for group content
        m.open('g', this.attr(scene, item, mdef.content));
        standalone_visit(item, scene => this.mark(m, scene));
        m.close();
        if (fore && stroke) {
          if (fill) item.fill = null;
          item.stroke = stroke;
          m.open('path', this.attr(scene, item, mdef.foreground, 'bgrect')).close();
          if (fill) item.fill = fill;
        } else {
          m.open('path', this.attr(scene, item, mdef.foreground, 'bgfore')).close();
        }
      }
      m.close(); // </tag>
      if (href) m.close(); // </a>
    };
    if (mdef.nested) {
      if (scene.items && scene.items.length) process(scene.items[0]);
    } else {
      standalone_visit(scene, process);
    }

    // render closing group tag
    return m.close(); // </g>
  }

  /**
   * Get href attributes for a hyperlinked mark item.
   * @param {Item} item - The mark item.
   */
  href(item) {
    const href = item.href;
    let attr;
    if (href) {
      if (attr = this._hrefs && this._hrefs[href]) {
        return attr;
      } else {
        this.sanitizeURL(href).then(attr => {
          // rewrite to use xlink namespace
          attr['xlink:href'] = attr.href;
          attr.href = null;
          (this._hrefs || (this._hrefs = {}))[href] = attr;
        });
      }
    }
    return null;
  }

  /**
   * Get an object of SVG attributes for a mark item.
   * @param {object} scene - The mark parent.
   * @param {Item} item - The mark item.
   * @param {array|function} attrs - One or more attribute emitters.
   * @param {string} tag - The tag being rendered.
   */
  attr(scene, item, attrs, tag) {
    const object = {},
      emit = (name, value, ns, prefixed) => {
        object[prefixed || name] = value;
      };

    // apply mark specific attributes
    if (Array.isArray(attrs)) {
      attrs.forEach(fn => fn(emit, item, this));
    } else {
      attrs(emit, item, this);
    }

    // apply style attributes
    if (tag) {
      standalone_style(object, item, scene, tag, this._defs);
    }
    return object;
  }

  /**
   * Render SVG defs, as needed.
   * Must be called *after* marks have been processed to ensure the
   * collected state is current and accurate.
   * @param {object} m - The markup context.
   */
  defs(m) {
    const gradient = this._defs.gradient,
      clipping = this._defs.clipping,
      count = Object.keys(gradient).length + Object.keys(clipping).length;
    if (count === 0) return; // nothing to do

    m.open('defs');
    for (const id in gradient) {
      const def = gradient[id],
        stops = def.stops;
      if (def.gradient === 'radial') {
        // SVG radial gradients automatically transform to normalized bbox
        // coordinates, in a way that is cumbersome to replicate in canvas.
        // We wrap the radial gradient in a pattern element, allowing us to
        // maintain a circular gradient that matches what canvas provides.

        m.open('pattern', {
          id: standalone_patternPrefix + id,
          viewBox: '0,0,1,1',
          width: '100%',
          height: '100%',
          preserveAspectRatio: 'xMidYMid slice'
        });
        m.open('rect', {
          width: '1',
          height: '1',
          fill: 'url(#' + id + ')'
        }).close();
        m.close(); // </pattern>

        m.open('radialGradient', {
          id: id,
          fx: def.x1,
          fy: def.y1,
          fr: def.r1,
          cx: def.x2,
          cy: def.y2,
          r: def.r2
        });
      } else {
        m.open('linearGradient', {
          id: id,
          x1: def.x1,
          x2: def.x2,
          y1: def.y1,
          y2: def.y2
        });
      }
      for (let i = 0; i < stops.length; ++i) {
        m.open('stop', {
          offset: stops[i].offset,
          'stop-color': stops[i].color
        }).close();
      }
      m.close();
    }
    for (const id in clipping) {
      const def = clipping[id];
      m.open('clipPath', {
        id: id
      });
      if (def.path) {
        m.open('path', {
          d: def.path
        }).close();
      } else {
        m.open('rect', {
          x: 0,
          y: 0,
          width: def.width,
          height: def.height
        }).close();
      }
      m.close();
    }
    m.close();
  }
}

// Helper function for attr for style presentation attributes
function standalone_style(s, item, scene, tag, defs) {
  let styleList;
  if (item == null) return s;
  if (tag === 'bgrect' && scene.interactive === false) {
    s['pointer-events'] = 'none';
  }
  if (tag === 'bgfore') {
    if (scene.interactive === false) {
      s['pointer-events'] = 'none';
    }
    s.display = 'none';
    if (item.fill !== null) return s;
  }
  if (tag === 'image' && item.smooth === false) {
    styleList = ['image-rendering: optimizeSpeed;', 'image-rendering: pixelated;'];
  }
  if (tag === 'text') {
    s['font-family'] = standalone_fontFamily(item);
    s['font-size'] = standalone_fontSize(item) + 'px';
    s['font-style'] = item.fontStyle;
    s['font-variant'] = item.fontVariant;
    s['font-weight'] = item.fontWeight;
  }
  for (const prop in standalone_stylesAttr) {
    let value = item[prop];
    const name = standalone_stylesAttr[prop];
    if (value === 'transparent' && (name === 'fill' || name === 'stroke')) ; else if (value != null) {
      if (standalone_isGradient(value)) {
        value = standalone_gradientRef(value, defs.gradient, '');
      }
      s[name] = value;
    }
  }
  for (const prop in standalone_stylesCss) {
    const value = item[prop];
    if (value != null) {
      styleList = styleList || [];
      styleList.push(`${standalone_stylesCss[prop]}: ${value};`);
    }
  }
  if (styleList) {
    s.style = styleList.join(' ');
  }
  return s;
}

/**
 * @typedef {Object} HybridRendererOptions
 *
 * @property {string[]} [svgMarkTypes=['text']] - An array of SVG mark types to render
 *                                                in the SVG layer. All other mark types
 *                                                will be rendered in the Canvas layer.
 * @property {boolean} [svgOnTop=true] - Flag to determine if SVG should be rendered on top.
 * @property {boolean} [debug=false] - Flag to enable or disable debugging mode. When true,
 *                                     the top layer will be stacked below the bottom layer
 *                                     rather than overlaid on top.
 */

/** @type {HybridRendererOptions} */
const standalone_OPTS = {
  svgMarkTypes: ['text'],
  svgOnTop: true,
  debug: false
};

/**
 * Configure the HybridRenderer
 *
 * @param {HybridRendererOptions} options - HybridRenderer configuration options.
 */
function standalone_setHybridRendererOptions(options) {
  standalone_OPTS['svgMarkTypes'] = options.svgMarkTypes ?? ['text'];
  standalone_OPTS['svgOnTop'] = options.svgOnTop ?? true;
  standalone_OPTS['debug'] = options.debug ?? false;
}
class standalone_HybridRenderer extends standalone_Renderer {
  constructor(loader) {
    super(loader);
    this._svgRenderer = new standalone_SVGRenderer(loader);
    this._canvasRenderer = new standalone_CanvasRenderer(loader);
  }

  /**
   * Initialize a new HybridRenderer instance.
   * @param {DOMElement} el - The containing DOM element for the display.
   * @param {number} width - The coordinate width of the display, in pixels.
   * @param {number} height - The coordinate height of the display, in pixels.
   * @param {Array<number>} origin - The origin of the display, in pixels.
   *   The coordinate system will be translated to this point.
   * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
   *   the width and height to determine the final pixel size.
   * @return {HybridRenderer} - This renderer instance.
   */
  initialize(el, width, height, origin, scaleFactor) {
    this._root_el = standalone_domChild(el, 0, 'div');
    const bottomEl = standalone_domChild(this._root_el, 0, 'div');
    const topEl = standalone_domChild(this._root_el, 1, 'div');
    this._root_el.style.position = 'relative';

    // Set position absolute to overlay svg on top of canvas
    if (!standalone_OPTS.debug) {
      bottomEl.style.height = '100%';
      topEl.style.position = 'absolute';
      topEl.style.top = '0';
      topEl.style.left = '0';
      topEl.style.height = '100%';
      topEl.style.width = '100%';
    }
    this._svgEl = standalone_OPTS.svgOnTop ? topEl : bottomEl;
    this._canvasEl = standalone_OPTS.svgOnTop ? bottomEl : topEl;

    // pointer-events to none on SVG layer so that canvas gets all events
    this._svgEl.style.pointerEvents = 'none';
    this._canvasRenderer.initialize(this._canvasEl, width, height, origin, scaleFactor);
    this._svgRenderer.initialize(this._svgEl, width, height, origin, scaleFactor);
    return super.initialize(el, width, height, origin, scaleFactor);
  }

  /**
   * Flag a mark item as dirty.
   * @param {Item} item - The mark item.
   */
  dirty(item) {
    if (standalone_OPTS.svgMarkTypes.includes(item.mark.marktype)) {
      this._svgRenderer.dirty(item);
    } else {
      this._canvasRenderer.dirty(item);
    }
    return this;
  }

  /**
   * Internal rendering method.
   * @param {object} scene - The root mark of a scenegraph to render.
   * @param {Array} markTypes - Array of the mark types to render.
   *                            If undefined, render all mark types
   */
  _render(scene, markTypes) {
    const allMarkTypes = markTypes ?? ['arc', 'area', 'image', 'line', 'path', 'rect', 'rule', 'shape', 'symbol', 'text', 'trail'];
    const canvasMarkTypes = allMarkTypes.filter(m => !standalone_OPTS.svgMarkTypes.includes(m));
    this._svgRenderer.render(scene, standalone_OPTS.svgMarkTypes);
    this._canvasRenderer.render(scene, canvasMarkTypes);
  }

  /**
   * Resize the display.
   * @param {number} width - The new coordinate width of the display, in pixels.
   * @param {number} height - The new coordinate height of the display, in pixels.
   * @param {Array<number>} origin - The new origin of the display, in pixels.
   *   The coordinate system will be translated to this point.
   * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
   *   the width and height to determine the final pixel size.
   * @return {SVGRenderer} - This renderer instance;
   */
  resize(width, height, origin, scaleFactor) {
    super.resize(width, height, origin, scaleFactor);
    this._svgRenderer.resize(width, height, origin, scaleFactor);
    this._canvasRenderer.resize(width, height, origin, scaleFactor);
    return this;
  }
  background(bgcolor) {
    // Propagate background color to lower canvas renderer
    if (standalone_OPTS.svgOnTop) {
      this._canvasRenderer.background(bgcolor);
    } else {
      this._svgRenderer.background(bgcolor);
    }
    return this;
  }
}

class standalone_HybridHandler extends standalone_CanvasHandler {
  constructor(loader, tooltip) {
    super(loader, tooltip);
  }
  initialize(el, origin, obj) {
    const canvas = standalone_domChild(standalone_domChild(el, 0, 'div'), standalone_OPTS.svgOnTop ? 0 : 1, 'div');
    return super.initialize(canvas, origin, obj);
  }
}

const standalone_Canvas = 'canvas';
const standalone_Hybrid = 'hybrid';
const standalone_PNG = 'png';
const standalone_SVG = 'svg';
const standalone_vega_scenegraph_module_None = 'none';
const standalone_RenderType = {
  Canvas: standalone_Canvas,
  PNG: standalone_PNG,
  SVG: standalone_SVG,
  Hybrid: standalone_Hybrid,
  None: standalone_vega_scenegraph_module_None
};
const standalone_modules = {};
standalone_modules[standalone_Canvas] = standalone_modules[standalone_PNG] = {
  renderer: standalone_CanvasRenderer,
  headless: standalone_CanvasRenderer,
  handler: standalone_CanvasHandler
};
standalone_modules[standalone_SVG] = {
  renderer: standalone_SVGRenderer,
  headless: standalone_SVGStringRenderer,
  handler: standalone_SVGHandler
};
standalone_modules[standalone_Hybrid] = {
  renderer: standalone_HybridRenderer,
  headless: standalone_HybridRenderer,
  handler: standalone_HybridHandler
};
standalone_modules[standalone_vega_scenegraph_module_None] = {};
function standalone_renderModule(name, _) {
  name = String(name || '').toLowerCase();
  if (arguments.length > 1) {
    standalone_modules[name] = _;
    return this;
  } else {
    return standalone_modules[name];
  }
}

function standalone_vega_scenegraph_module_intersect(scene, bounds, filter) {
  const hits = [],
    // intersection results
    box = new standalone_Bounds().union(bounds),
    // defensive copy
    type = scene.marktype;
  return type ? standalone_intersectMark(scene, box, filter, hits) : type === 'group' ? standalone_intersectGroup(scene, box, filter, hits) : standalone_vega_util_module_error('Intersect scene must be mark node or group item.');
}
function standalone_intersectMark(mark, box, filter, hits) {
  if (standalone_visitMark(mark, box, filter)) {
    const items = mark.items,
      type = mark.marktype,
      n = items.length;
    let i = 0;
    if (type === 'group') {
      for (; i < n; ++i) {
        standalone_intersectGroup(items[i], box, filter, hits);
      }
    } else {
      for (const test = standalone_Marks[type].isect; i < n; ++i) {
        const item = items[i];
        if (standalone_intersectItem(item, box, test)) hits.push(item);
      }
    }
  }
  return hits;
}
function standalone_visitMark(mark, box, filter) {
  // process if bounds intersect and if
  // (1) mark is a group mark (so we must recurse), or
  // (2) mark is interactive and passes filter
  return mark.bounds && box.intersects(mark.bounds) && (mark.marktype === 'group' || mark.interactive !== false && (!filter || filter(mark)));
}
function standalone_intersectGroup(group, box, filter, hits) {
  // test intersect against group
  // skip groups by default unless filter says otherwise
  if (filter && filter(group.mark) && standalone_intersectItem(group, box, standalone_Marks.group.isect)) {
    hits.push(group);
  }

  // recursively test children marks
  // translate box to group coordinate space
  const marks = group.items,
    n = marks && marks.length;
  if (n) {
    const x = group.x || 0,
      y = group.y || 0;
    box.translate(-x, -y);
    for (let i = 0; i < n; ++i) {
      standalone_intersectMark(marks[i], box, filter, hits);
    }
    box.translate(x, y);
  }
  return hits;
}
function standalone_intersectItem(item, box, test) {
  // test bounds enclosure, bounds intersection, then detailed test
  const bounds = item.bounds;
  return box.encloses(bounds) || box.intersects(bounds) && test(item, box);
}

const standalone_clipBounds = new standalone_Bounds();
function standalone_boundClip (mark) {
  const clip = mark.clip;
  if (standalone_vega_util_module_isFunction(clip)) {
    clip(standalone_boundContext(standalone_clipBounds.clear()));
  } else if (clip) {
    standalone_clipBounds.set(0, 0, mark.group.width, mark.group.height);
  } else return;
  mark.bounds.intersect(standalone_clipBounds);
}

const standalone_TOLERANCE = 1e-9;
function standalone_sceneEqual(a, b, key) {
  return a === b ? true : key === 'path' ? standalone_pathEqual(a, b) : a instanceof Date && b instanceof Date ? +a === +b : standalone_isNumber(a) && standalone_isNumber(b) ? Math.abs(a - b) <= standalone_TOLERANCE : !a || !b || !standalone_vega_util_module_isObject(a) && !standalone_vega_util_module_isObject(b) ? a == b : standalone_objectEqual(a, b);
}
function standalone_pathEqual(a, b) {
  return standalone_sceneEqual(standalone_vega_scenegraph_module_parse(a), standalone_vega_scenegraph_module_parse(b));
}
function standalone_objectEqual(a, b) {
  var ka = Object.keys(a),
    kb = Object.keys(b),
    key,
    i;
  if (ka.length !== kb.length) return false;
  ka.sort();
  kb.sort();
  for (i = ka.length - 1; i >= 0; i--) {
    if (ka[i] != kb[i]) return false;
  }
  for (i = ka.length - 1; i >= 0; i--) {
    key = ka[i];
    if (!standalone_sceneEqual(a[key], b[key], key)) return false;
  }
  return typeof a === typeof b;
}

function standalone_resetSVGDefIds() {
  standalone_resetSVGClipId();
  standalone_resetSVGGradientId();
}



;// ../../node_modules/vega-view-transforms/build/vega-view-transforms.module.js




const standalone_Top = 'top';
const standalone_Left = 'left';
const standalone_Right = 'right';
const standalone_Bottom = 'bottom';
const standalone_TopLeft = 'top-left';
const standalone_TopRight = 'top-right';
const standalone_BottomLeft = 'bottom-left';
const standalone_BottomRight = 'bottom-right';
const standalone_Start = 'start';
const standalone_Middle = 'middle';
const standalone_End = 'end';
const standalone_X = 'x';
const standalone_Y = 'y';
const standalone_Group = 'group';
const standalone_AxisRole = 'axis';
const standalone_TitleRole = 'title';
const standalone_FrameRole = 'frame';
const standalone_ScopeRole = 'scope';
const standalone_LegendRole = 'legend';
const standalone_RowHeader = 'row-header';
const standalone_RowFooter = 'row-footer';
const standalone_RowTitle = 'row-title';
const standalone_ColHeader = 'column-header';
const standalone_ColFooter = 'column-footer';
const standalone_ColTitle = 'column-title';
const standalone_Padding = 'padding';
const standalone_Symbols = 'symbol';
const standalone_Fit = 'fit';
const standalone_FitX = 'fit-x';
const standalone_FitY = 'fit-y';
const standalone_Pad = 'pad';
const standalone_vega_view_transforms_module_None = 'none';
const standalone_All = 'all';
const standalone_Each = 'each';
const standalone_Flush = 'flush';
const standalone_Column = 'column';
const standalone_Row = 'row';

/**
 * Calculate bounding boxes for scenegraph items.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {object} params.mark - The scenegraph mark instance to bound.
 */
function standalone_Bound(params) {
  standalone_Transform.call(this, null, params);
}
standalone_inherits(standalone_Bound, standalone_Transform, {
  transform(_, pulse) {
    const view = pulse.dataflow,
      mark = _.mark,
      type = mark.marktype,
      entry = standalone_Marks[type],
      bound = entry.bound;
    let markBounds = mark.bounds,
      rebound;
    if (entry.nested) {
      // multi-item marks have a single bounds instance
      if (mark.items.length) view.dirty(mark.items[0]);
      markBounds = standalone_vega_view_transforms_module_boundItem(mark, bound);
      mark.items.forEach(item => {
        item.bounds.clear().union(markBounds);
      });
    } else if (type === standalone_Group || _.modified()) {
      // operator parameters modified -> re-bound all items
      // updates group bounds in response to modified group content
      pulse.visit(pulse.MOD, item => view.dirty(item));
      markBounds.clear();
      mark.items.forEach(item => markBounds.union(standalone_vega_view_transforms_module_boundItem(item, bound)));

      // force reflow for axes/legends/titles to propagate any layout changes
      switch (mark.role) {
        case standalone_AxisRole:
        case standalone_LegendRole:
        case standalone_TitleRole:
          pulse.reflow();
      }
    } else {
      // incrementally update bounds, re-bound mark as needed
      rebound = pulse.changed(pulse.REM);
      pulse.visit(pulse.ADD, item => {
        markBounds.union(standalone_vega_view_transforms_module_boundItem(item, bound));
      });
      pulse.visit(pulse.MOD, item => {
        rebound = rebound || markBounds.alignsWith(item.bounds);
        view.dirty(item);
        markBounds.union(standalone_vega_view_transforms_module_boundItem(item, bound));
      });
      if (rebound) {
        markBounds.clear();
        mark.items.forEach(item => markBounds.union(item.bounds));
      }
    }

    // ensure mark bounds do not exceed any clipping region
    standalone_boundClip(mark);
    return pulse.modifies('bounds');
  }
});
function standalone_vega_view_transforms_module_boundItem(item, bound, opt) {
  return bound(item.bounds.clear(), item, opt);
}

const standalone_COUNTER_NAME = ':vega_identifier:';

/**
 * Adds a unique identifier to all added tuples.
 * This transform creates a new signal that serves as an id counter.
 * As a result, the id counter is shared across all instances of this
 * transform, generating unique ids across multiple data streams. In
 * addition, this signal value can be included in a snapshot of the
 * dataflow state, enabling correct resumption of id allocation.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {string} params.as - The field name for the generated identifier.
 */
function standalone_Identifier(params) {
  standalone_Transform.call(this, 0, params);
}
standalone_Identifier.Definition = {
  'type': 'Identifier',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'as',
    'type': 'string',
    'required': true
  }]
};
standalone_inherits(standalone_Identifier, standalone_Transform, {
  transform(_, pulse) {
    const counter = standalone_getCounter(pulse.dataflow),
      as = _.as;
    let id = counter.value;
    pulse.visit(pulse.ADD, t => t[as] = t[as] || ++id);
    counter.set(this.value = id);
    return pulse;
  }
});
function standalone_getCounter(view) {
  return view._signals[standalone_COUNTER_NAME] || (view._signals[standalone_COUNTER_NAME] = view.add(0));
}

/**
 * Bind scenegraph items to a scenegraph mark instance.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {object} params.markdef - The mark definition for creating the mark.
 *   This is an object of legal scenegraph mark properties which *must* include
 *   the 'marktype' property.
 */
function standalone_Mark(params) {
  standalone_Transform.call(this, null, params);
}
standalone_inherits(standalone_Mark, standalone_Transform, {
  transform(_, pulse) {
    let mark = this.value;

    // acquire mark on first invocation, bind context and group
    if (!mark) {
      mark = pulse.dataflow.scenegraph().mark(_.markdef, standalone_lookup$1(_), _.index);
      mark.group.context = _.context;
      if (!_.context.group) _.context.group = mark.group;
      mark.source = this.source; // point to upstream collector
      mark.clip = _.clip;
      mark.interactive = _.interactive;
      this.value = mark;
    }

    // initialize entering items
    const Init = mark.marktype === standalone_Group ? standalone_GroupItem : standalone_Item;
    pulse.visit(pulse.ADD, item => Init.call(item, mark));

    // update clipping and/or interactive status
    if (_.modified('clip') || _.modified('interactive')) {
      mark.clip = _.clip;
      mark.interactive = !!_.interactive;
      mark.zdirty = true; // force scenegraph re-eval
      pulse.reflow();
    }

    // bind items array to scenegraph mark
    mark.items = pulse.source;
    return pulse;
  }
});
function standalone_lookup$1(_) {
  const g = _.groups,
    p = _.parent;
  return g && g.size === 1 ? g.get(Object.keys(g.object)[0]) : g && p ? g.lookup(p) : null;
}

/**
 * Analyze items for overlap, changing opacity to hide items with
 * overlapping bounding boxes. This transform will preserve at least
 * two items (e.g., first and last) even if overlap persists.
 * @param {object} params - The parameters for this operator.
 * @param {function(*,*): number} [params.sort] - A comparator
 *   function for sorting items.
 * @param {object} [params.method] - The overlap removal method to apply.
 *   One of 'parity' (default, hide every other item until there is no
 *   more overlap) or 'greedy' (sequentially scan and hide and items that
 *   overlap with the last visible item).
 * @param {object} [params.boundScale] - A scale whose range should be used
 *   to bound the items. Items exceeding the bounds of the scale range
 *   will be treated as overlapping. If null or undefined, no bounds check
 *   will be applied.
 * @param {object} [params.boundOrient] - The orientation of the scale
 *   (top, bottom, left, or right) used to bound items. This parameter is
 *   ignored if boundScale is null or undefined.
 * @param {object} [params.boundTolerance] - The tolerance in pixels for
 *   bound inclusion testing (default 1). This specifies by how many pixels
 *   an item's bounds may exceed the scale range bounds and not be culled.
 * @constructor
 */
function standalone_Overlap(params) {
  standalone_Transform.call(this, null, params);
}
const standalone_methods = {
  parity: items => items.filter((item, i) => i % 2 ? item.opacity = 0 : 1),
  greedy: (items, sep) => {
    let a;
    return items.filter((b, i) => !i || !standalone_vega_view_transforms_module_intersect(a.bounds, b.bounds, sep) ? (a = b, 1) : b.opacity = 0);
  }
};

// compute bounding box intersection
// including padding pixels of separation
const standalone_vega_view_transforms_module_intersect = (a, b, sep) => sep > Math.max(b.x1 - a.x2, a.x1 - b.x2, b.y1 - a.y2, a.y1 - b.y2);
const standalone_hasOverlap = (items, pad) => {
  for (var i = 1, n = items.length, a = items[0].bounds, b; i < n; a = b, ++i) {
    if (standalone_vega_view_transforms_module_intersect(a, b = items[i].bounds, pad)) return true;
  }
};
const standalone_hasBounds = item => {
  const b = item.bounds;
  return b.width() > 1 && b.height() > 1;
};
const standalone_boundTest = (scale, orient, tolerance) => {
  var range = scale.range(),
    b = new standalone_Bounds();
  if (orient === standalone_Top || orient === standalone_Bottom) {
    b.set(range[0], -Infinity, range[1], +Infinity);
  } else {
    b.set(-Infinity, range[0], +Infinity, range[1]);
  }
  b.expand(tolerance || 1);
  return item => b.encloses(item.bounds);
};

// reset all items to be fully opaque
const standalone_vega_view_transforms_module_reset = source => {
  source.forEach(item => item.opacity = 1);
  return source;
};

// add all tuples to mod, fork pulse if parameters were modified
// fork prevents cross-stream tuple pollution (e.g., pulse from scale)
const standalone_reflow = (pulse, _) => pulse.reflow(_.modified()).modifies('opacity');
standalone_inherits(standalone_Overlap, standalone_Transform, {
  transform(_, pulse) {
    const reduce = standalone_methods[_.method] || standalone_methods.parity,
      sep = _.separation || 0;
    let source = pulse.materialize(pulse.SOURCE).source,
      items,
      test;
    if (!source || !source.length) return;
    if (!_.method) {
      // early exit if method is falsy
      if (_.modified('method')) {
        standalone_vega_view_transforms_module_reset(source);
        pulse = standalone_reflow(pulse, _);
      }
      return pulse;
    }

    // skip labels with no content
    source = source.filter(standalone_hasBounds);

    // early exit, nothing to do
    if (!source.length) return;
    if (_.sort) {
      source = source.slice().sort(_.sort);
    }
    items = standalone_vega_view_transforms_module_reset(source);
    pulse = standalone_reflow(pulse, _);
    if (items.length >= 3 && standalone_hasOverlap(items, sep)) {
      do {
        items = reduce(items, sep);
      } while (items.length >= 3 && standalone_hasOverlap(items, sep));
      if (items.length < 3 && !standalone_peek(source).opacity) {
        if (items.length > 1) standalone_peek(items).opacity = 0;
        standalone_peek(source).opacity = 1;
      }
    }
    if (_.boundScale && _.boundTolerance >= 0) {
      test = standalone_boundTest(_.boundScale, _.boundOrient, +_.boundTolerance);
      source.forEach(item => {
        if (!test(item)) item.opacity = 0;
      });
    }

    // re-calculate mark bounds
    const bounds = items[0].mark.bounds.clear();
    source.forEach(item => {
      if (item.opacity) bounds.union(item.bounds);
    });
    return pulse;
  }
});

/**
 * Queue modified scenegraph items for rendering.
 * @constructor
 */
function standalone_Render(params) {
  standalone_Transform.call(this, null, params);
}
standalone_inherits(standalone_Render, standalone_Transform, {
  transform(_, pulse) {
    const view = pulse.dataflow;
    pulse.visit(pulse.ALL, item => view.dirty(item));

    // set z-index dirty flag as needed
    if (pulse.fields && pulse.fields['zindex']) {
      const item = pulse.source && pulse.source[0];
      if (item) item.mark.zdirty = true;
    }
  }
});

const standalone_vega_view_transforms_module_tempBounds = new standalone_Bounds();
function standalone_vega_view_transforms_module_set(item, property, value) {
  return item[property] === value ? 0 : (item[property] = value, 1);
}

function standalone_isYAxis(mark) {
  var orient = mark.items[0].orient;
  return orient === standalone_Left || orient === standalone_Right;
}
function standalone_axisIndices(datum) {
  let index = +datum.grid;
  return [datum.ticks ? index++ : -1,
  // ticks index
  datum.labels ? index++ : -1,
  // labels index
  index + +datum.domain // title index
  ];
}
function standalone_axisLayout(view, axis, width, height) {
  var item = axis.items[0],
    datum = item.datum,
    delta = item.translate != null ? item.translate : 0.5,
    orient = item.orient,
    indices = standalone_axisIndices(datum),
    range = item.range,
    offset = item.offset,
    position = item.position,
    minExtent = item.minExtent,
    maxExtent = item.maxExtent,
    title = datum.title && item.items[indices[2]].items[0],
    titlePadding = item.titlePadding,
    bounds = item.bounds,
    dl = title && standalone_multiLineOffset(title),
    x = 0,
    y = 0,
    i,
    s;
  standalone_vega_view_transforms_module_tempBounds.clear().union(bounds);
  bounds.clear();
  if ((i = indices[0]) > -1) bounds.union(item.items[i].bounds);
  if ((i = indices[1]) > -1) bounds.union(item.items[i].bounds);

  // position axis group and title
  switch (orient) {
    case standalone_Top:
      x = position || 0;
      y = -offset;
      s = Math.max(minExtent, Math.min(maxExtent, -bounds.y1));
      bounds.add(0, -s).add(range, 0);
      if (title) standalone_axisTitleLayout(view, title, s, titlePadding, dl, 0, -1, bounds);
      break;
    case standalone_Left:
      x = -offset;
      y = position || 0;
      s = Math.max(minExtent, Math.min(maxExtent, -bounds.x1));
      bounds.add(-s, 0).add(0, range);
      if (title) standalone_axisTitleLayout(view, title, s, titlePadding, dl, 1, -1, bounds);
      break;
    case standalone_Right:
      x = width + offset;
      y = position || 0;
      s = Math.max(minExtent, Math.min(maxExtent, bounds.x2));
      bounds.add(0, 0).add(s, range);
      if (title) standalone_axisTitleLayout(view, title, s, titlePadding, dl, 1, 1, bounds);
      break;
    case standalone_Bottom:
      x = position || 0;
      y = height + offset;
      s = Math.max(minExtent, Math.min(maxExtent, bounds.y2));
      bounds.add(0, 0).add(range, s);
      if (title) standalone_axisTitleLayout(view, title, s, titlePadding, 0, 0, 1, bounds);
      break;
    default:
      x = item.x;
      y = item.y;
  }

  // update bounds
  standalone_boundStroke(bounds.translate(x, y), item);
  if (standalone_vega_view_transforms_module_set(item, 'x', x + delta) | standalone_vega_view_transforms_module_set(item, 'y', y + delta)) {
    item.bounds = standalone_vega_view_transforms_module_tempBounds;
    view.dirty(item);
    item.bounds = bounds;
    view.dirty(item);
  }
  return item.mark.bounds.clear().union(bounds);
}
function standalone_axisTitleLayout(view, title, offset, pad, dl, isYAxis, sign, bounds) {
  const b = title.bounds;
  if (title.auto) {
    const v = sign * (offset + dl + pad);
    let dx = 0,
      dy = 0;
    view.dirty(title);
    isYAxis ? dx = (title.x || 0) - (title.x = v) : dy = (title.y || 0) - (title.y = v);
    title.mark.bounds.clear().union(b.translate(-dx, -dy));
    view.dirty(title);
  }
  bounds.union(b);
}

// aggregation functions for grid margin determination
const standalone_vega_view_transforms_module_min = (a, b) => Math.floor(Math.min(a, b));
const standalone_vega_view_transforms_module_max = (a, b) => Math.ceil(Math.max(a, b));
function standalone_gridLayoutGroups(group) {
  var groups = group.items,
    n = groups.length,
    i = 0,
    mark,
    items;
  const views = {
    marks: [],
    rowheaders: [],
    rowfooters: [],
    colheaders: [],
    colfooters: [],
    rowtitle: null,
    coltitle: null
  };

  // layout axes, gather legends, collect bounds
  for (; i < n; ++i) {
    mark = groups[i];
    items = mark.items;
    if (mark.marktype === standalone_Group) {
      switch (mark.role) {
        case standalone_AxisRole:
        case standalone_LegendRole:
        case standalone_TitleRole:
          break;
        case standalone_RowHeader:
          views.rowheaders.push(...items);
          break;
        case standalone_RowFooter:
          views.rowfooters.push(...items);
          break;
        case standalone_ColHeader:
          views.colheaders.push(...items);
          break;
        case standalone_ColFooter:
          views.colfooters.push(...items);
          break;
        case standalone_RowTitle:
          views.rowtitle = items[0];
          break;
        case standalone_ColTitle:
          views.coltitle = items[0];
          break;
        default:
          views.marks.push(...items);
      }
    }
  }
  return views;
}
function standalone_bboxFlush(item) {
  return new standalone_Bounds().set(0, 0, item.width || 0, item.height || 0);
}
function standalone_bboxFull(item) {
  const b = item.bounds.clone();
  return b.empty() ? b.set(0, 0, 0, 0) : b.translate(-(item.x || 0), -(item.y || 0));
}
function standalone_vega_view_transforms_module_get(opt, key, d) {
  const v = standalone_vega_util_module_isObject(opt) ? opt[key] : opt;
  return v != null ? v : d !== undefined ? d : 0;
}
function standalone_offsetValue(v) {
  return v < 0 ? Math.ceil(-v) : 0;
}
function standalone_gridLayout(view, groups, opt) {
  var dirty = !opt.nodirty,
    bbox = opt.bounds === standalone_Flush ? standalone_bboxFlush : standalone_bboxFull,
    bounds = standalone_vega_view_transforms_module_tempBounds.set(0, 0, 0, 0),
    alignCol = standalone_vega_view_transforms_module_get(opt.align, standalone_Column),
    alignRow = standalone_vega_view_transforms_module_get(opt.align, standalone_Row),
    padCol = standalone_vega_view_transforms_module_get(opt.padding, standalone_Column),
    padRow = standalone_vega_view_transforms_module_get(opt.padding, standalone_Row),
    ncols = opt.columns || groups.length,
    nrows = ncols <= 0 ? 1 : Math.ceil(groups.length / ncols),
    n = groups.length,
    xOffset = Array(n),
    xExtent = Array(ncols),
    xMax = 0,
    yOffset = Array(n),
    yExtent = Array(nrows),
    yMax = 0,
    dx = Array(n),
    dy = Array(n),
    boxes = Array(n),
    m,
    i,
    c,
    r,
    b,
    g,
    px,
    py,
    x,
    y,
    offset;
  for (i = 0; i < ncols; ++i) xExtent[i] = 0;
  for (i = 0; i < nrows; ++i) yExtent[i] = 0;

  // determine offsets for each group
  for (i = 0; i < n; ++i) {
    g = groups[i];
    b = boxes[i] = bbox(g);
    g.x = g.x || 0;
    dx[i] = 0;
    g.y = g.y || 0;
    dy[i] = 0;
    c = i % ncols;
    r = ~~(i / ncols);
    xMax = Math.max(xMax, px = Math.ceil(b.x2));
    yMax = Math.max(yMax, py = Math.ceil(b.y2));
    xExtent[c] = Math.max(xExtent[c], px);
    yExtent[r] = Math.max(yExtent[r], py);
    xOffset[i] = padCol + standalone_offsetValue(b.x1);
    yOffset[i] = padRow + standalone_offsetValue(b.y1);
    if (dirty) view.dirty(groups[i]);
  }

  // set initial alignment offsets
  for (i = 0; i < n; ++i) {
    if (i % ncols === 0) xOffset[i] = 0;
    if (i < ncols) yOffset[i] = 0;
  }

  // enforce column alignment constraints
  if (alignCol === standalone_Each) {
    for (c = 1; c < ncols; ++c) {
      for (offset = 0, i = c; i < n; i += ncols) {
        if (offset < xOffset[i]) offset = xOffset[i];
      }
      for (i = c; i < n; i += ncols) {
        xOffset[i] = offset + xExtent[c - 1];
      }
    }
  } else if (alignCol === standalone_All) {
    for (offset = 0, i = 0; i < n; ++i) {
      if (i % ncols && offset < xOffset[i]) offset = xOffset[i];
    }
    for (i = 0; i < n; ++i) {
      if (i % ncols) xOffset[i] = offset + xMax;
    }
  } else {
    for (alignCol = false, c = 1; c < ncols; ++c) {
      for (i = c; i < n; i += ncols) {
        xOffset[i] += xExtent[c - 1];
      }
    }
  }

  // enforce row alignment constraints
  if (alignRow === standalone_Each) {
    for (r = 1; r < nrows; ++r) {
      for (offset = 0, i = r * ncols, m = i + ncols; i < m; ++i) {
        if (offset < yOffset[i]) offset = yOffset[i];
      }
      for (i = r * ncols; i < m; ++i) {
        yOffset[i] = offset + yExtent[r - 1];
      }
    }
  } else if (alignRow === standalone_All) {
    for (offset = 0, i = ncols; i < n; ++i) {
      if (offset < yOffset[i]) offset = yOffset[i];
    }
    for (i = ncols; i < n; ++i) {
      yOffset[i] = offset + yMax;
    }
  } else {
    for (alignRow = false, r = 1; r < nrows; ++r) {
      for (i = r * ncols, m = i + ncols; i < m; ++i) {
        yOffset[i] += yExtent[r - 1];
      }
    }
  }

  // perform horizontal grid layout
  for (x = 0, i = 0; i < n; ++i) {
    x = xOffset[i] + (i % ncols ? x : 0);
    dx[i] += x - groups[i].x;
  }

  // perform vertical grid layout
  for (c = 0; c < ncols; ++c) {
    for (y = 0, i = c; i < n; i += ncols) {
      y += yOffset[i];
      dy[i] += y - groups[i].y;
    }
  }

  // perform horizontal centering
  if (alignCol && standalone_vega_view_transforms_module_get(opt.center, standalone_Column) && nrows > 1) {
    for (i = 0; i < n; ++i) {
      b = alignCol === standalone_All ? xMax : xExtent[i % ncols];
      x = b - boxes[i].x2 - groups[i].x - dx[i];
      if (x > 0) dx[i] += x / 2;
    }
  }

  // perform vertical centering
  if (alignRow && standalone_vega_view_transforms_module_get(opt.center, standalone_Row) && ncols !== 1) {
    for (i = 0; i < n; ++i) {
      b = alignRow === standalone_All ? yMax : yExtent[~~(i / ncols)];
      y = b - boxes[i].y2 - groups[i].y - dy[i];
      if (y > 0) dy[i] += y / 2;
    }
  }

  // position grid relative to anchor
  for (i = 0; i < n; ++i) {
    bounds.union(boxes[i].translate(dx[i], dy[i]));
  }
  x = standalone_vega_view_transforms_module_get(opt.anchor, standalone_X);
  y = standalone_vega_view_transforms_module_get(opt.anchor, standalone_Y);
  switch (standalone_vega_view_transforms_module_get(opt.anchor, standalone_Column)) {
    case standalone_End:
      x -= bounds.width();
      break;
    case standalone_Middle:
      x -= bounds.width() / 2;
  }
  switch (standalone_vega_view_transforms_module_get(opt.anchor, standalone_Row)) {
    case standalone_End:
      y -= bounds.height();
      break;
    case standalone_Middle:
      y -= bounds.height() / 2;
  }
  x = Math.round(x);
  y = Math.round(y);

  // update mark positions, bounds, dirty
  bounds.clear();
  for (i = 0; i < n; ++i) {
    groups[i].mark.bounds.clear();
  }
  for (i = 0; i < n; ++i) {
    g = groups[i];
    g.x += dx[i] += x;
    g.y += dy[i] += y;
    bounds.union(g.mark.bounds.union(g.bounds.translate(dx[i], dy[i])));
    if (dirty) view.dirty(g);
  }
  return bounds;
}
function standalone_trellisLayout(view, group, opt) {
  var views = standalone_gridLayoutGroups(group),
    groups = views.marks,
    bbox = opt.bounds === standalone_Flush ? standalone_boundFlush : standalone_boundFull,
    off = opt.offset,
    ncols = opt.columns || groups.length,
    nrows = ncols <= 0 ? 1 : Math.ceil(groups.length / ncols),
    cells = nrows * ncols,
    x,
    y,
    x2,
    y2,
    anchor,
    band,
    offset;

  // -- initial grid layout
  const bounds = standalone_gridLayout(view, groups, opt);
  if (bounds.empty()) bounds.set(0, 0, 0, 0); // empty grid

  // -- layout grid headers and footers --

  // perform row header layout
  if (views.rowheaders) {
    band = standalone_vega_view_transforms_module_get(opt.headerBand, standalone_Row, null);
    x = standalone_layoutHeaders(view, views.rowheaders, groups, ncols, nrows, -standalone_vega_view_transforms_module_get(off, 'rowHeader'), standalone_vega_view_transforms_module_min, 0, bbox, 'x1', 0, ncols, 1, band);
  }

  // perform column header layout
  if (views.colheaders) {
    band = standalone_vega_view_transforms_module_get(opt.headerBand, standalone_Column, null);
    y = standalone_layoutHeaders(view, views.colheaders, groups, ncols, ncols, -standalone_vega_view_transforms_module_get(off, 'columnHeader'), standalone_vega_view_transforms_module_min, 1, bbox, 'y1', 0, 1, ncols, band);
  }

  // perform row footer layout
  if (views.rowfooters) {
    band = standalone_vega_view_transforms_module_get(opt.footerBand, standalone_Row, null);
    x2 = standalone_layoutHeaders(view, views.rowfooters, groups, ncols, nrows, standalone_vega_view_transforms_module_get(off, 'rowFooter'), standalone_vega_view_transforms_module_max, 0, bbox, 'x2', ncols - 1, ncols, 1, band);
  }

  // perform column footer layout
  if (views.colfooters) {
    band = standalone_vega_view_transforms_module_get(opt.footerBand, standalone_Column, null);
    y2 = standalone_layoutHeaders(view, views.colfooters, groups, ncols, ncols, standalone_vega_view_transforms_module_get(off, 'columnFooter'), standalone_vega_view_transforms_module_max, 1, bbox, 'y2', cells - ncols, 1, ncols, band);
  }

  // perform row title layout
  if (views.rowtitle) {
    anchor = standalone_vega_view_transforms_module_get(opt.titleAnchor, standalone_Row);
    offset = standalone_vega_view_transforms_module_get(off, 'rowTitle');
    offset = anchor === standalone_End ? x2 + offset : x - offset;
    band = standalone_vega_view_transforms_module_get(opt.titleBand, standalone_Row, 0.5);
    standalone_layoutTitle(view, views.rowtitle, offset, 0, bounds, band);
  }

  // perform column title layout
  if (views.coltitle) {
    anchor = standalone_vega_view_transforms_module_get(opt.titleAnchor, standalone_Column);
    offset = standalone_vega_view_transforms_module_get(off, 'columnTitle');
    offset = anchor === standalone_End ? y2 + offset : y - offset;
    band = standalone_vega_view_transforms_module_get(opt.titleBand, standalone_Column, 0.5);
    standalone_layoutTitle(view, views.coltitle, offset, 1, bounds, band);
  }
}
function standalone_boundFlush(item, field) {
  return field === 'x1' ? item.x || 0 : field === 'y1' ? item.y || 0 : field === 'x2' ? (item.x || 0) + (item.width || 0) : field === 'y2' ? (item.y || 0) + (item.height || 0) : undefined;
}
function standalone_boundFull(item, field) {
  return item.bounds[field];
}
function standalone_layoutHeaders(view, headers, groups, ncols, limit, offset, agg, isX, bound, bf, start, stride, back, band) {
  var n = groups.length,
    init = 0,
    edge = 0,
    i,
    j,
    k,
    m,
    b,
    h,
    g,
    x,
    y;

  // if no groups, early exit and return 0
  if (!n) return init;

  // compute margin
  for (i = start; i < n; i += stride) {
    if (groups[i]) init = agg(init, bound(groups[i], bf));
  }

  // if no headers, return margin calculation
  if (!headers.length) return init;

  // check if number of headers exceeds number of rows or columns
  if (headers.length > limit) {
    view.warn('Grid headers exceed limit: ' + limit);
    headers = headers.slice(0, limit);
  }

  // apply offset
  init += offset;

  // clear mark bounds for all headers
  for (j = 0, m = headers.length; j < m; ++j) {
    view.dirty(headers[j]);
    headers[j].mark.bounds.clear();
  }

  // layout each header
  for (i = start, j = 0, m = headers.length; j < m; ++j, i += stride) {
    h = headers[j];
    b = h.mark.bounds;

    // search for nearest group to align to
    // necessary if table has empty cells
    for (k = i; k >= 0 && (g = groups[k]) == null; k -= back);

    // assign coordinates and update bounds
    if (isX) {
      x = band == null ? g.x : Math.round(g.bounds.x1 + band * g.bounds.width());
      y = init;
    } else {
      x = init;
      y = band == null ? g.y : Math.round(g.bounds.y1 + band * g.bounds.height());
    }
    b.union(h.bounds.translate(x - (h.x || 0), y - (h.y || 0)));
    h.x = x;
    h.y = y;
    view.dirty(h);

    // update current edge of layout bounds
    edge = agg(edge, b[bf]);
  }
  return edge;
}
function standalone_layoutTitle(view, g, offset, isX, bounds, band) {
  if (!g) return;
  view.dirty(g);

  // compute title coordinates
  var x = offset,
    y = offset;
  isX ? x = Math.round(bounds.x1 + band * bounds.width()) : y = Math.round(bounds.y1 + band * bounds.height());

  // assign coordinates and update bounds
  g.bounds.translate(x - (g.x || 0), y - (g.y || 0));
  g.mark.bounds.clear().union(g.bounds);
  g.x = x;
  g.y = y;

  // queue title for redraw
  view.dirty(g);
}

// utility for looking up legend layout configuration
function standalone_vega_view_transforms_module_lookup(config, orient) {
  const opt = config[orient] || {};
  return (key, d) => opt[key] != null ? opt[key] : config[key] != null ? config[key] : d;
}

// if legends specify offset directly, use the maximum specified value
function standalone_offsets(legends, value) {
  let max = -Infinity;
  legends.forEach(item => {
    if (item.offset != null) max = Math.max(max, item.offset);
  });
  return max > -Infinity ? max : value;
}
function standalone_legendParams(g, orient, config, xb, yb, w, h) {
  const _ = standalone_vega_view_transforms_module_lookup(config, orient),
    offset = standalone_offsets(g, _('offset', 0)),
    anchor = _('anchor', standalone_Start),
    mult = anchor === standalone_End ? 1 : anchor === standalone_Middle ? 0.5 : 0;
  const p = {
    align: standalone_Each,
    bounds: _('bounds', standalone_Flush),
    columns: _('direction') === 'vertical' ? 1 : g.length,
    padding: _('margin', 8),
    center: _('center'),
    nodirty: true
  };
  switch (orient) {
    case standalone_Left:
      p.anchor = {
        x: Math.floor(xb.x1) - offset,
        column: standalone_End,
        y: mult * (h || xb.height() + 2 * xb.y1),
        row: anchor
      };
      break;
    case standalone_Right:
      p.anchor = {
        x: Math.ceil(xb.x2) + offset,
        y: mult * (h || xb.height() + 2 * xb.y1),
        row: anchor
      };
      break;
    case standalone_Top:
      p.anchor = {
        y: Math.floor(yb.y1) - offset,
        row: standalone_End,
        x: mult * (w || yb.width() + 2 * yb.x1),
        column: anchor
      };
      break;
    case standalone_Bottom:
      p.anchor = {
        y: Math.ceil(yb.y2) + offset,
        x: mult * (w || yb.width() + 2 * yb.x1),
        column: anchor
      };
      break;
    case standalone_TopLeft:
      p.anchor = {
        x: offset,
        y: offset
      };
      break;
    case standalone_TopRight:
      p.anchor = {
        x: w - offset,
        y: offset,
        column: standalone_End
      };
      break;
    case standalone_BottomLeft:
      p.anchor = {
        x: offset,
        y: h - offset,
        row: standalone_End
      };
      break;
    case standalone_BottomRight:
      p.anchor = {
        x: w - offset,
        y: h - offset,
        column: standalone_End,
        row: standalone_End
      };
      break;
  }
  return p;
}
function standalone_legendLayout(view, legend) {
  var item = legend.items[0],
    datum = item.datum,
    orient = item.orient,
    bounds = item.bounds,
    x = item.x,
    y = item.y,
    w,
    h;

  // cache current bounds for later comparison
  item._bounds ? item._bounds.clear().union(bounds) : item._bounds = bounds.clone();
  bounds.clear();

  // adjust legend to accommodate padding and title
  standalone_legendGroupLayout(view, item, item.items[0].items[0]);

  // aggregate bounds to determine size, and include origin
  bounds = standalone_legendBounds(item, bounds);
  w = 2 * item.padding;
  h = 2 * item.padding;
  if (!bounds.empty()) {
    w = Math.ceil(bounds.width() + w);
    h = Math.ceil(bounds.height() + h);
  }
  if (datum.type === standalone_Symbols) {
    standalone_legendEntryLayout(item.items[0].items[0].items[0].items);
  }
  if (orient !== standalone_vega_view_transforms_module_None) {
    item.x = x = 0;
    item.y = y = 0;
  }
  item.width = w;
  item.height = h;
  standalone_boundStroke(bounds.set(x, y, x + w, y + h), item);
  item.mark.bounds.clear().union(bounds);
  return item;
}
function standalone_legendBounds(item, b) {
  // aggregate item bounds
  item.items.forEach(_ => b.union(_.bounds));

  // anchor to legend origin
  b.x1 = item.padding;
  b.y1 = item.padding;
  return b;
}
function standalone_legendGroupLayout(view, item, entry) {
  var pad = item.padding,
    ex = pad - entry.x,
    ey = pad - entry.y;
  if (!item.datum.title) {
    if (ex || ey) standalone_vega_view_transforms_module_translate(view, entry, ex, ey);
  } else {
    var title = item.items[1].items[0],
      anchor = title.anchor,
      tpad = item.titlePadding || 0,
      tx = pad - title.x,
      ty = pad - title.y;
    switch (title.orient) {
      case standalone_Left:
        ex += Math.ceil(title.bounds.width()) + tpad;
        break;
      case standalone_Right:
      case standalone_Bottom:
        break;
      default:
        ey += title.bounds.height() + tpad;
    }
    if (ex || ey) standalone_vega_view_transforms_module_translate(view, entry, ex, ey);
    switch (title.orient) {
      case standalone_Left:
        ty += standalone_legendTitleOffset(item, entry, title, anchor, 1, 1);
        break;
      case standalone_Right:
        tx += standalone_legendTitleOffset(item, entry, title, standalone_End, 0, 0) + tpad;
        ty += standalone_legendTitleOffset(item, entry, title, anchor, 1, 1);
        break;
      case standalone_Bottom:
        tx += standalone_legendTitleOffset(item, entry, title, anchor, 0, 0);
        ty += standalone_legendTitleOffset(item, entry, title, standalone_End, -1, 0, 1) + tpad;
        break;
      default:
        tx += standalone_legendTitleOffset(item, entry, title, anchor, 0, 0);
    }
    if (tx || ty) standalone_vega_view_transforms_module_translate(view, title, tx, ty);

    // translate legend if title pushes into negative coordinates
    if ((tx = Math.round(title.bounds.x1 - pad)) < 0) {
      standalone_vega_view_transforms_module_translate(view, entry, -tx, 0);
      standalone_vega_view_transforms_module_translate(view, title, -tx, 0);
    }
  }
}
function standalone_legendTitleOffset(item, entry, title, anchor, y, lr, noBar) {
  const grad = item.datum.type !== 'symbol',
    vgrad = title.datum.vgrad,
    e = grad && (lr || !vgrad) && !noBar ? entry.items[0] : entry,
    s = e.bounds[y ? 'y2' : 'x2'] - item.padding,
    u = vgrad && lr ? s : 0,
    v = vgrad && lr ? 0 : s,
    o = y <= 0 ? 0 : standalone_multiLineOffset(title);
  return Math.round(anchor === standalone_Start ? u : anchor === standalone_End ? v - o : 0.5 * (s - o));
}
function standalone_vega_view_transforms_module_translate(view, item, dx, dy) {
  item.x += dx;
  item.y += dy;
  item.bounds.translate(dx, dy);
  item.mark.bounds.translate(dx, dy);
  view.dirty(item);
}
function standalone_legendEntryLayout(entries) {
  // get max widths for each column
  const widths = entries.reduce((w, g) => {
    w[g.column] = Math.max(g.bounds.x2 - g.x, w[g.column] || 0);
    return w;
  }, {});

  // set dimensions of legend entry groups
  entries.forEach(g => {
    g.width = widths[g.column];
    g.height = g.bounds.y2 - g.y;
  });
}

function standalone_titleLayout(view, mark, width, height, viewBounds) {
  var group = mark.items[0],
    frame = group.frame,
    orient = group.orient,
    anchor = group.anchor,
    offset = group.offset,
    padding = group.padding,
    title = group.items[0].items[0],
    subtitle = group.items[1] && group.items[1].items[0],
    end = orient === standalone_Left || orient === standalone_Right ? height : width,
    start = 0,
    x = 0,
    y = 0,
    sx = 0,
    sy = 0,
    pos;
  if (frame !== standalone_Group) {
    orient === standalone_Left ? (start = viewBounds.y2, end = viewBounds.y1) : orient === standalone_Right ? (start = viewBounds.y1, end = viewBounds.y2) : (start = viewBounds.x1, end = viewBounds.x2);
  } else if (orient === standalone_Left) {
    start = height, end = 0;
  }
  pos = anchor === standalone_Start ? start : anchor === standalone_End ? end : (start + end) / 2;
  if (subtitle && subtitle.text) {
    // position subtitle
    switch (orient) {
      case standalone_Top:
      case standalone_Bottom:
        sy = title.bounds.height() + padding;
        break;
      case standalone_Left:
        sx = title.bounds.width() + padding;
        break;
      case standalone_Right:
        sx = -title.bounds.width() - padding;
        break;
    }
    standalone_vega_view_transforms_module_tempBounds.clear().union(subtitle.bounds);
    standalone_vega_view_transforms_module_tempBounds.translate(sx - (subtitle.x || 0), sy - (subtitle.y || 0));
    if (standalone_vega_view_transforms_module_set(subtitle, 'x', sx) | standalone_vega_view_transforms_module_set(subtitle, 'y', sy)) {
      view.dirty(subtitle);
      subtitle.bounds.clear().union(standalone_vega_view_transforms_module_tempBounds);
      subtitle.mark.bounds.clear().union(standalone_vega_view_transforms_module_tempBounds);
      view.dirty(subtitle);
    }
    standalone_vega_view_transforms_module_tempBounds.clear().union(subtitle.bounds);
  } else {
    standalone_vega_view_transforms_module_tempBounds.clear();
  }
  standalone_vega_view_transforms_module_tempBounds.union(title.bounds);

  // position title group
  switch (orient) {
    case standalone_Top:
      x = pos;
      y = viewBounds.y1 - standalone_vega_view_transforms_module_tempBounds.height() - offset;
      break;
    case standalone_Left:
      x = viewBounds.x1 - standalone_vega_view_transforms_module_tempBounds.width() - offset;
      y = pos;
      break;
    case standalone_Right:
      x = viewBounds.x2 + standalone_vega_view_transforms_module_tempBounds.width() + offset;
      y = pos;
      break;
    case standalone_Bottom:
      x = pos;
      y = viewBounds.y2 + offset;
      break;
    default:
      x = group.x;
      y = group.y;
  }
  if (standalone_vega_view_transforms_module_set(group, 'x', x) | standalone_vega_view_transforms_module_set(group, 'y', y)) {
    standalone_vega_view_transforms_module_tempBounds.translate(x, y);
    view.dirty(group);
    group.bounds.clear().union(standalone_vega_view_transforms_module_tempBounds);
    mark.bounds.clear().union(standalone_vega_view_transforms_module_tempBounds);
    view.dirty(group);
  }
  return group.bounds;
}

/**
 * Layout view elements such as axes and legends.
 * Also performs size adjustments.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {object} params.mark - Scenegraph mark of groups to layout.
 */
function standalone_ViewLayout(params) {
  standalone_Transform.call(this, null, params);
}
standalone_inherits(standalone_ViewLayout, standalone_Transform, {
  transform(_, pulse) {
    const view = pulse.dataflow;
    _.mark.items.forEach(group => {
      if (_.layout) standalone_trellisLayout(view, group, _.layout);
      standalone_layoutGroup(view, group, _);
    });
    return standalone_shouldReflow(_.mark.group) ? pulse.reflow() : pulse;
  }
});
function standalone_shouldReflow(group) {
  // We typically should reflow if layout is invoked (#2568), as child items
  // may have resized and reflow ensures group bounds are re-calculated.
  // However, legend entries have a special exception to avoid instability.
  // For example, if a selected legend symbol gains a stroke on hover,
  // we don't want to re-position subsequent elements in the legend.
  return group && group.mark.role !== 'legend-entry';
}
function standalone_layoutGroup(view, group, _) {
  var items = group.items,
    width = Math.max(0, group.width || 0),
    height = Math.max(0, group.height || 0),
    viewBounds = new standalone_Bounds().set(0, 0, width, height),
    xBounds = viewBounds.clone(),
    yBounds = viewBounds.clone(),
    legends = [],
    title,
    mark,
    orient,
    b,
    i,
    n;

  // layout axes, gather legends, collect bounds
  for (i = 0, n = items.length; i < n; ++i) {
    mark = items[i];
    switch (mark.role) {
      case standalone_AxisRole:
        b = standalone_isYAxis(mark) ? xBounds : yBounds;
        b.union(standalone_axisLayout(view, mark, width, height));
        break;
      case standalone_TitleRole:
        title = mark;
        break;
      case standalone_LegendRole:
        legends.push(standalone_legendLayout(view, mark));
        break;
      case standalone_FrameRole:
      case standalone_ScopeRole:
      case standalone_RowHeader:
      case standalone_RowFooter:
      case standalone_RowTitle:
      case standalone_ColHeader:
      case standalone_ColFooter:
      case standalone_ColTitle:
        xBounds.union(mark.bounds);
        yBounds.union(mark.bounds);
        break;
      default:
        viewBounds.union(mark.bounds);
    }
  }

  // layout legends, adjust viewBounds
  if (legends.length) {
    // group legends by orient
    const l = {};
    legends.forEach(item => {
      orient = item.orient || standalone_Right;
      if (orient !== standalone_vega_view_transforms_module_None) (l[orient] || (l[orient] = [])).push(item);
    });

    // perform grid layout for each orient group
    for (const orient in l) {
      const g = l[orient];
      standalone_gridLayout(view, g, standalone_legendParams(g, orient, _.legends, xBounds, yBounds, width, height));
    }

    // update view bounds
    legends.forEach(item => {
      const b = item.bounds;
      if (!b.equals(item._bounds)) {
        item.bounds = item._bounds;
        view.dirty(item); // dirty previous location
        item.bounds = b;
        view.dirty(item);
      }
      if (_.autosize && (_.autosize.type === standalone_Fit || _.autosize.type === standalone_FitX || _.autosize.type === standalone_FitY)) {
        // For autosize fit, incorporate the orthogonal dimension only.
        // Legends that overrun the chart area will then be clipped;
        // otherwise the chart area gets reduced to nothing!
        switch (item.orient) {
          case standalone_Left:
          case standalone_Right:
            viewBounds.add(b.x1, 0).add(b.x2, 0);
            break;
          case standalone_Top:
          case standalone_Bottom:
            viewBounds.add(0, b.y1).add(0, b.y2);
        }
      } else {
        viewBounds.union(b);
      }
    });
  }

  // combine bounding boxes
  viewBounds.union(xBounds).union(yBounds);

  // layout title, adjust bounds
  if (title) {
    viewBounds.union(standalone_titleLayout(view, title, width, height, viewBounds));
  }

  // override aggregated view bounds if content is clipped
  if (group.clip) {
    viewBounds.set(0, 0, group.width || 0, group.height || 0);
  }

  // perform size adjustment
  standalone_viewSizeLayout(view, group, viewBounds, _);
}
function standalone_viewSizeLayout(view, group, viewBounds, _) {
  const auto = _.autosize || {},
    type = auto.type;
  if (view._autosize < 1 || !type) return;
  let viewWidth = view._width,
    viewHeight = view._height,
    width = Math.max(0, group.width || 0),
    left = Math.max(0, Math.ceil(-viewBounds.x1)),
    height = Math.max(0, group.height || 0),
    top = Math.max(0, Math.ceil(-viewBounds.y1));
  const right = Math.max(0, Math.ceil(viewBounds.x2 - width)),
    bottom = Math.max(0, Math.ceil(viewBounds.y2 - height));
  if (auto.contains === standalone_Padding) {
    const padding = view.padding();
    viewWidth -= padding.left + padding.right;
    viewHeight -= padding.top + padding.bottom;
  }
  if (type === standalone_vega_view_transforms_module_None) {
    left = 0;
    top = 0;
    width = viewWidth;
    height = viewHeight;
  } else if (type === standalone_Fit) {
    width = Math.max(0, viewWidth - left - right);
    height = Math.max(0, viewHeight - top - bottom);
  } else if (type === standalone_FitX) {
    width = Math.max(0, viewWidth - left - right);
    viewHeight = height + top + bottom;
  } else if (type === standalone_FitY) {
    viewWidth = width + left + right;
    height = Math.max(0, viewHeight - top - bottom);
  } else if (type === standalone_Pad) {
    viewWidth = width + left + right;
    viewHeight = height + top + bottom;
  }
  view._resizeView(viewWidth, viewHeight, width, height, [left, top], auto.resize);
}



;// ../../node_modules/d3-array/src/sum.js
function standalone_sum_sum(values, valueof) {
  let sum = 0;
  if (valueof === undefined) {
    for (let value of values) {
      if (value = +value) {
        sum += value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if (value = +valueof(value, ++index, values)) {
        sum += value;
      }
    }
  }
  return sum;
}

;// ../../node_modules/vega-encode/build/vega-encode.module.js






/**
 * Generates axis ticks for visualizing a spatial scale.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Scale} params.scale - The scale to generate ticks for.
 * @param {*} [params.count=10] - The approximate number of ticks, or
 *   desired tick interval, to use.
 * @param {Array<*>} [params.values] - The exact tick values to use.
 *   These must be legal domain values for the provided scale.
 *   If provided, the count argument is ignored.
 * @param {function(*):string} [params.formatSpecifier] - A format specifier
 *   to use in conjunction with scale.tickFormat. Legal values are
 *   any valid d3 4.0 format specifier.
 * @param {function(*):string} [params.format] - The format function to use.
 *   If provided, the formatSpecifier argument is ignored.
 */
function standalone_AxisTicks(params) {
  standalone_Transform.call(this, null, params);
}
standalone_inherits(standalone_AxisTicks, standalone_Transform, {
  transform(_, pulse) {
    if (this.value && !_.modified()) {
      return pulse.StopPropagation;
    }
    var locale = pulse.dataflow.locale(),
      out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
      ticks = this.value,
      scale = _.scale,
      tally = _.count == null ? _.values ? _.values.length : 10 : _.count,
      count = standalone_tickCount(scale, tally, _.minstep),
      format = _.format || standalone_vega_scale_module_tickFormat(locale, scale, count, _.formatSpecifier, _.formatType, !!_.values),
      values = _.values ? standalone_validTicks(scale, _.values, count) : standalone_tickValues(scale, count);
    if (ticks) out.rem = ticks;
    ticks = values.map((value, i) => standalone_ingest$1({
      index: i / (values.length - 1 || 1),
      value: value,
      label: format(value)
    }));
    if (_.extra && ticks.length) {
      // add an extra tick pegged to the initial domain value
      // this is used to generate axes with 'binned' domains
      ticks.push(standalone_ingest$1({
        index: -1,
        extra: {
          value: ticks[0].value
        },
        label: ''
      }));
    }
    out.source = ticks;
    out.add = ticks;
    this.value = ticks;
    return out;
  }
});

/**
 * Joins a set of data elements against a set of visual items.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): object} [params.item] - An item generator function.
 * @param {function(object): *} [params.key] - The key field associating data and visual items.
 */
function standalone_DataJoin(params) {
  standalone_Transform.call(this, null, params);
}
function standalone_defaultItemCreate() {
  return standalone_ingest$1({});
}
function standalone_newMap(key) {
  const map = standalone_fastmap().test(t => t.exit);
  map.lookup = t => map.get(key(t));
  return map;
}
standalone_inherits(standalone_DataJoin, standalone_Transform, {
  transform(_, pulse) {
    var df = pulse.dataflow,
      out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
      item = _.item || standalone_defaultItemCreate,
      key = _.key || standalone_tupleid,
      map = this.value;

    // prevent transient (e.g., hover) requests from
    // cascading across marks derived from marks
    if (standalone_vega_util_module_isArray(out.encode)) {
      out.encode = null;
    }
    if (map && (_.modified('key') || pulse.modified(key))) {
      standalone_vega_util_module_error('DataJoin does not support modified key function or fields.');
    }
    if (!map) {
      pulse = pulse.addAll();
      this.value = map = standalone_newMap(key);
    }
    pulse.visit(pulse.ADD, t => {
      const k = key(t);
      let x = map.get(k);
      if (x) {
        if (x.exit) {
          map.empty--;
          out.add.push(x);
        } else {
          out.mod.push(x);
        }
      } else {
        x = item(t);
        map.set(k, x);
        out.add.push(x);
      }
      x.datum = t;
      x.exit = false;
    });
    pulse.visit(pulse.MOD, t => {
      const k = key(t),
        x = map.get(k);
      if (x) {
        x.datum = t;
        out.mod.push(x);
      }
    });
    pulse.visit(pulse.REM, t => {
      const k = key(t),
        x = map.get(k);
      if (t === x.datum && !x.exit) {
        out.rem.push(x);
        x.exit = true;
        ++map.empty;
      }
    });
    if (pulse.changed(pulse.ADD_MOD)) out.modifies('datum');
    if (pulse.clean() || _.clean && map.empty > df.cleanThreshold) {
      df.runAfter(map.clean);
    }
    return out;
  }
});

/**
 * Invokes encoding functions for visual items.
 * @constructor
 * @param {object} params - The parameters to the encoding functions. This
 *   parameter object will be passed through to all invoked encoding functions.
 * @param {object} [params.mod=false] - Flag indicating if tuples in the input
 *   mod set that are unmodified by encoders should be included in the output.
 * @param {object} param.encoders - The encoding functions
 * @param {function(object, object): boolean} [param.encoders.update] - Update encoding set
 * @param {function(object, object): boolean} [param.encoders.enter] - Enter encoding set
 * @param {function(object, object): boolean} [param.encoders.exit] - Exit encoding set
 */
function standalone_Encode(params) {
  standalone_Transform.call(this, null, params);
}
standalone_inherits(standalone_Encode, standalone_Transform, {
  transform(_, pulse) {
    var out = pulse.fork(pulse.ADD_REM),
      fmod = _.mod || false,
      encoders = _.encoders,
      encode = pulse.encode;

    // if an array, the encode directive includes additional sets
    // that must be defined in order for the primary set to be invoked
    // e.g., only run the update set if the hover set is defined
    if (standalone_vega_util_module_isArray(encode)) {
      if (out.changed() || encode.every(e => encoders[e])) {
        encode = encode[0];
        out.encode = null; // consume targeted encode directive
      } else {
        return pulse.StopPropagation;
      }
    }

    // marshall encoder functions
    var reenter = encode === 'enter',
      update = encoders.update || standalone_falsy,
      enter = encoders.enter || standalone_falsy,
      exit = encoders.exit || standalone_falsy,
      set = (encode && !reenter ? encoders[encode] : update) || standalone_falsy;
    if (pulse.changed(pulse.ADD)) {
      pulse.visit(pulse.ADD, t => {
        enter(t, _);
        update(t, _);
      });
      out.modifies(enter.output);
      out.modifies(update.output);
      if (set !== standalone_falsy && set !== update) {
        pulse.visit(pulse.ADD, t => {
          set(t, _);
        });
        out.modifies(set.output);
      }
    }
    if (pulse.changed(pulse.REM) && exit !== standalone_falsy) {
      pulse.visit(pulse.REM, t => {
        exit(t, _);
      });
      out.modifies(exit.output);
    }
    if (reenter || set !== standalone_falsy) {
      const flag = pulse.MOD | (_.modified() ? pulse.REFLOW : 0);
      if (reenter) {
        pulse.visit(flag, t => {
          const mod = enter(t, _) || fmod;
          if (set(t, _) || mod) out.mod.push(t);
        });
        if (out.mod.length) out.modifies(enter.output);
      } else {
        pulse.visit(flag, t => {
          if (set(t, _) || fmod) out.mod.push(t);
        });
      }
      if (out.mod.length) out.modifies(set.output);
    }
    return out.changed() ? out : pulse.StopPropagation;
  }
});

/**
 * Generates legend entries for visualizing a scale.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Scale} params.scale - The scale to generate items for.
 * @param {*} [params.count=5] - The approximate number of items, or
 *   desired tick interval, to use.
 * @param {*} [params.limit] - The maximum number of entries to
 *   include in a symbol legend.
 * @param {Array<*>} [params.values] - The exact tick values to use.
 *   These must be legal domain values for the provided scale.
 *   If provided, the count argument is ignored.
 * @param {string} [params.formatSpecifier] - A format specifier
 *   to use in conjunction with scale.tickFormat. Legal values are
 *   any valid D3 format specifier string.
 * @param {function(*):string} [params.format] - The format function to use.
 *   If provided, the formatSpecifier argument is ignored.
 */
function standalone_LegendEntries(params) {
  standalone_Transform.call(this, [], params);
}
standalone_inherits(standalone_LegendEntries, standalone_Transform, {
  transform(_, pulse) {
    if (this.value != null && !_.modified()) {
      return pulse.StopPropagation;
    }
    var locale = pulse.dataflow.locale(),
      out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
      items = this.value,
      type = _.type || standalone_SymbolLegend,
      scale = _.scale,
      limit = +_.limit,
      count = standalone_tickCount(scale, _.count == null ? 5 : _.count, _.minstep),
      lskip = !!_.values || type === standalone_SymbolLegend,
      format = _.format || standalone_labelFormat(locale, scale, count, type, _.formatSpecifier, _.formatType, lskip),
      values = _.values || standalone_labelValues(scale, count),
      domain,
      fraction,
      size,
      offset,
      ellipsis;
    if (items) out.rem = items;
    if (type === standalone_SymbolLegend) {
      if (limit && values.length > limit) {
        pulse.dataflow.warn('Symbol legend count exceeds limit, filtering items.');
        items = values.slice(0, limit - 1);
        ellipsis = true;
      } else {
        items = values;
      }
      if (standalone_vega_util_module_isFunction(size = _.size)) {
        // if first value maps to size zero, remove from list (vega#717)
        if (!_.values && scale(items[0]) === 0) {
          items = items.slice(1);
        }
        // compute size offset for legend entries
        offset = items.reduce((max, value) => Math.max(max, size(value, _)), 0);
      } else {
        size = standalone_vega_util_module_constant(offset = size || 8);
      }
      items = items.map((value, index) => standalone_ingest$1({
        index: index,
        label: format(value, index, items),
        value: value,
        offset: offset,
        size: size(value, _)
      }));
      if (ellipsis) {
        ellipsis = values[items.length];
        items.push(standalone_ingest$1({
          index: items.length,
          label: `\u2026${values.length - items.length} entries`,
          value: ellipsis,
          offset: offset,
          size: size(ellipsis, _)
        }));
      }
    } else if (type === standalone_GradientLegend) {
      domain = scale.domain(), fraction = standalone_scaleFraction(scale, domain[0], standalone_peek(domain));

      // if automatic label generation produces 2 or fewer values,
      // use the domain end points instead (fixes vega/vega#1364)
      if (values.length < 3 && !_.values && domain[0] !== standalone_peek(domain)) {
        values = [domain[0], standalone_peek(domain)];
      }
      items = values.map((value, index) => standalone_ingest$1({
        index: index,
        label: format(value, index, values),
        value: value,
        perc: fraction(value)
      }));
    } else {
      size = values.length - 1;
      fraction = standalone_labelFraction(scale);
      items = values.map((value, index) => standalone_ingest$1({
        index: index,
        label: format(value, index, values),
        value: value,
        perc: index ? fraction(value) : 0,
        perc2: index === size ? 1 : fraction(values[index + 1])
      }));
    }
    out.source = items;
    out.add = items;
    this.value = items;
    return out;
  }
});

const standalone_sourceX = t => t.source.x;
const standalone_sourceY = t => t.source.y;
const standalone_targetX = t => t.target.x;
const standalone_targetY = t => t.target.y;

/**
 * Layout paths linking source and target elements.
 * @constructor
 * @param {object} params - The parameters for this operator.
 */
function standalone_LinkPath(params) {
  standalone_Transform.call(this, {}, params);
}
standalone_LinkPath.Definition = {
  'type': 'LinkPath',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'sourceX',
    'type': 'field',
    'default': 'source.x'
  }, {
    'name': 'sourceY',
    'type': 'field',
    'default': 'source.y'
  }, {
    'name': 'targetX',
    'type': 'field',
    'default': 'target.x'
  }, {
    'name': 'targetY',
    'type': 'field',
    'default': 'target.y'
  }, {
    'name': 'orient',
    'type': 'enum',
    'default': 'vertical',
    'values': ['horizontal', 'vertical', 'radial']
  }, {
    'name': 'shape',
    'type': 'enum',
    'default': 'line',
    'values': ['line', 'arc', 'curve', 'diagonal', 'orthogonal']
  }, {
    'name': 'require',
    'type': 'signal'
  }, {
    'name': 'as',
    'type': 'string',
    'default': 'path'
  }]
};
standalone_inherits(standalone_LinkPath, standalone_Transform, {
  transform(_, pulse) {
    var sx = _.sourceX || standalone_sourceX,
      sy = _.sourceY || standalone_sourceY,
      tx = _.targetX || standalone_targetX,
      ty = _.targetY || standalone_targetY,
      as = _.as || 'path',
      orient = _.orient || 'vertical',
      shape = _.shape || 'line',
      path = standalone_Paths.get(shape + '-' + orient) || standalone_Paths.get(shape);
    if (!path) {
      standalone_vega_util_module_error('LinkPath unsupported type: ' + _.shape + (_.orient ? '-' + _.orient : ''));
    }
    pulse.visit(pulse.SOURCE, t => {
      t[as] = path(sx(t), sy(t), tx(t), ty(t));
    });
    return pulse.reflow(_.modified()).modifies(as);
  }
});
const standalone_vega_encode_module_line = (sx, sy, tx, ty) => 'M' + sx + ',' + sy + 'L' + tx + ',' + ty;
const standalone_lineR = (sa, sr, ta, tr) => standalone_vega_encode_module_line(sr * Math.cos(sa), sr * Math.sin(sa), tr * Math.cos(ta), tr * Math.sin(ta));
const standalone_vega_encode_module_arc = (sx, sy, tx, ty) => {
  var dx = tx - sx,
    dy = ty - sy,
    rr = Math.hypot(dx, dy) / 2,
    ra = 180 * Math.atan2(dy, dx) / Math.PI;
  return 'M' + sx + ',' + sy + 'A' + rr + ',' + rr + ' ' + ra + ' 0 1' + ' ' + tx + ',' + ty;
};
const standalone_arcR = (sa, sr, ta, tr) => standalone_vega_encode_module_arc(sr * Math.cos(sa), sr * Math.sin(sa), tr * Math.cos(ta), tr * Math.sin(ta));
const standalone_curve = (sx, sy, tx, ty) => {
  const dx = tx - sx,
    dy = ty - sy,
    ix = 0.2 * (dx + dy),
    iy = 0.2 * (dy - dx);
  return 'M' + sx + ',' + sy + 'C' + (sx + ix) + ',' + (sy + iy) + ' ' + (tx + iy) + ',' + (ty - ix) + ' ' + tx + ',' + ty;
};
const standalone_curveR = (sa, sr, ta, tr) => standalone_curve(sr * Math.cos(sa), sr * Math.sin(sa), tr * Math.cos(ta), tr * Math.sin(ta));
const standalone_orthoX = (sx, sy, tx, ty) => 'M' + sx + ',' + sy + 'V' + ty + 'H' + tx;
const standalone_orthoY = (sx, sy, tx, ty) => 'M' + sx + ',' + sy + 'H' + tx + 'V' + ty;
const standalone_orthoR = (sa, sr, ta, tr) => {
  const sc = Math.cos(sa),
    ss = Math.sin(sa),
    tc = Math.cos(ta),
    ts = Math.sin(ta),
    sf = Math.abs(ta - sa) > Math.PI ? ta <= sa : ta > sa;
  return 'M' + sr * sc + ',' + sr * ss + 'A' + sr + ',' + sr + ' 0 0,' + (sf ? 1 : 0) + ' ' + sr * tc + ',' + sr * ts + 'L' + tr * tc + ',' + tr * ts;
};
const standalone_diagonalX = (sx, sy, tx, ty) => {
  const m = (sx + tx) / 2;
  return 'M' + sx + ',' + sy + 'C' + m + ',' + sy + ' ' + m + ',' + ty + ' ' + tx + ',' + ty;
};
const standalone_diagonalY = (sx, sy, tx, ty) => {
  const m = (sy + ty) / 2;
  return 'M' + sx + ',' + sy + 'C' + sx + ',' + m + ' ' + tx + ',' + m + ' ' + tx + ',' + ty;
};
const standalone_diagonalR = (sa, sr, ta, tr) => {
  const sc = Math.cos(sa),
    ss = Math.sin(sa),
    tc = Math.cos(ta),
    ts = Math.sin(ta),
    mr = (sr + tr) / 2;
  return 'M' + sr * sc + ',' + sr * ss + 'C' + mr * sc + ',' + mr * ss + ' ' + mr * tc + ',' + mr * ts + ' ' + tr * tc + ',' + tr * ts;
};
const standalone_Paths = standalone_fastmap({
  'line': standalone_vega_encode_module_line,
  'line-radial': standalone_lineR,
  'arc': standalone_vega_encode_module_arc,
  'arc-radial': standalone_arcR,
  'curve': standalone_curve,
  'curve-radial': standalone_curveR,
  'orthogonal-horizontal': standalone_orthoX,
  'orthogonal-vertical': standalone_orthoY,
  'orthogonal-radial': standalone_orthoR,
  'diagonal-horizontal': standalone_diagonalX,
  'diagonal-vertical': standalone_diagonalY,
  'diagonal-radial': standalone_diagonalR
});

/**
 * Pie and donut chart layout.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The value field to size pie segments.
 * @param {number} [params.startAngle=0] - The start angle (in radians) of the layout.
 * @param {number} [params.endAngle=2π] - The end angle (in radians) of the layout.
 * @param {boolean} [params.sort] - Boolean flag for sorting sectors by value.
 */
function standalone_Pie(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Pie.Definition = {
  'type': 'Pie',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'field',
    'type': 'field'
  }, {
    'name': 'startAngle',
    'type': 'number',
    'default': 0
  }, {
    'name': 'endAngle',
    'type': 'number',
    'default': 6.283185307179586
  }, {
    'name': 'sort',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': 2,
    'default': ['startAngle', 'endAngle']
  }]
};
standalone_inherits(standalone_Pie, standalone_Transform, {
  transform(_, pulse) {
    var as = _.as || ['startAngle', 'endAngle'],
      startAngle = as[0],
      endAngle = as[1],
      field = _.field || standalone_one,
      start = _.startAngle || 0,
      stop = _.endAngle != null ? _.endAngle : 2 * Math.PI,
      data = pulse.source,
      values = data.map(field),
      n = values.length,
      a = start,
      k = (stop - start) / standalone_sum_sum(values),
      index = standalone_range(n),
      i,
      t,
      v;
    if (_.sort) {
      index.sort((a, b) => values[a] - values[b]);
    }
    for (i = 0; i < n; ++i) {
      v = values[index[i]];
      t = data[index[i]];
      t[startAngle] = a;
      t[endAngle] = a += v * k;
    }
    this.value = values;
    return pulse.reflow(_.modified()).modifies(as);
  }
});

const standalone_DEFAULT_COUNT = 5;
function standalone_includeZero(scale) {
  const type = scale.type;
  return !scale.bins && (type === standalone_vega_scale_module_Linear || type === standalone_Pow || type === standalone_Sqrt);
}
function standalone_includePad(type) {
  return standalone_isContinuous(type) && type !== standalone_Sequential;
}
const standalone_vega_encode_module_SKIP = standalone_toSet(['set', 'modified', 'clear', 'type', 'scheme', 'schemeExtent', 'schemeCount', 'domain', 'domainMin', 'domainMid', 'domainMax', 'domainRaw', 'domainImplicit', 'nice', 'zero', 'bins', 'range', 'rangeStep', 'round', 'reverse', 'interpolate', 'interpolateGamma']);

/**
 * Maintains a scale function mapping data values to visual channels.
 * @constructor
 * @param {object} params - The parameters for this operator.
 */
function standalone_Scale(params) {
  standalone_Transform.call(this, null, params);
  this.modified(true); // always treat as modified
}
standalone_inherits(standalone_Scale, standalone_Transform, {
  transform(_, pulse) {
    var df = pulse.dataflow,
      scale$1 = this.value,
      key = standalone_scaleKey(_);
    if (!scale$1 || key !== scale$1.type) {
      this.value = scale$1 = standalone_vega_scale_module_scale(key)();
    }
    for (key in _) if (!standalone_vega_encode_module_SKIP[key]) {
      // padding is a scale property for band/point but not others
      if (key === 'padding' && standalone_includePad(scale$1.type)) continue;
      // invoke scale property setter, raise warning if not found
      standalone_vega_util_module_isFunction(scale$1[key]) ? scale$1[key](_[key]) : df.warn('Unsupported scale property: ' + key);
    }
    standalone_configureRange(scale$1, _, standalone_configureBins(scale$1, _, standalone_configureDomain(scale$1, _, df)));
    return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
  }
});
function standalone_scaleKey(_) {
  var t = _.type,
    d = '',
    n;

  // backwards compatibility pre Vega 5.
  if (t === standalone_Sequential) return standalone_Sequential + '-' + standalone_vega_scale_module_Linear;
  if (standalone_isContinuousColor(_)) {
    n = _.rawDomain ? _.rawDomain.length : _.domain ? _.domain.length + +(_.domainMid != null) : 0;
    d = n === 2 ? standalone_Sequential + '-' : n === 3 ? standalone_Diverging + '-' : '';
  }
  return (d + t || standalone_vega_scale_module_Linear).toLowerCase();
}
function standalone_isContinuousColor(_) {
  const t = _.type;
  return standalone_isContinuous(t) && t !== standalone_Time && t !== standalone_UTC && (_.scheme || _.range && _.range.length && _.range.every(standalone_vega_util_module_isString));
}
function standalone_configureDomain(scale, _, df) {
  // check raw domain, if provided use that and exit early
  const raw = standalone_rawDomain(scale, _.domainRaw, df);
  if (raw > -1) return raw;
  var domain = _.domain,
    type = scale.type,
    zero = _.zero || _.zero === undefined && standalone_includeZero(scale),
    n,
    mid;
  if (!domain) return 0;

  // adjust domain based on zero, min, max settings
  if (zero || _.domainMin != null || _.domainMax != null || _.domainMid != null) {
    n = (domain = domain.slice()).length - 1 || 1;
    if (zero) {
      if (domain[0] > 0) domain[0] = 0;
      if (domain[n] < 0) domain[n] = 0;
    }
    if (_.domainMin != null) domain[0] = _.domainMin;
    if (_.domainMax != null) domain[n] = _.domainMax;
    if (_.domainMid != null) {
      mid = _.domainMid;
      const i = mid > domain[n] ? n + 1 : mid < domain[0] ? 0 : n;
      if (i !== n) df.warn('Scale domainMid exceeds domain min or max.', mid);
      domain.splice(i, 0, mid);
    }
  }

  // adjust continuous domain for minimum pixel padding
  if (standalone_includePad(type) && _.padding && domain[0] !== standalone_peek(domain)) {
    domain = standalone_padDomain(type, domain, _.range, _.padding, _.exponent, _.constant);
  }

  // set the scale domain
  scale.domain(standalone_domainCheck(type, domain, df));

  // if ordinal scale domain is defined, prevent implicit
  // domain construction as side-effect of scale lookup
  if (type === standalone_Ordinal) {
    scale.unknown(_.domainImplicit ? standalone_implicit : undefined);
  }

  // perform 'nice' adjustment as requested
  if (_.nice && scale.nice) {
    scale.nice(_.nice !== true && standalone_tickCount(scale, _.nice) || null);
  }

  // return the cardinality of the domain
  return domain.length;
}
function standalone_rawDomain(scale, raw, df) {
  if (raw) {
    scale.domain(standalone_domainCheck(scale.type, raw, df));
    return raw.length;
  } else {
    return -1;
  }
}
function standalone_padDomain(type, domain, range, pad, exponent, constant) {
  var span = Math.abs(standalone_peek(range) - range[0]),
    frac = span / (span - 2 * pad),
    d = type === standalone_Log ? standalone_zoomLog(domain, null, frac) : type === standalone_Sqrt ? standalone_zoomPow(domain, null, frac, 0.5) : type === standalone_Pow ? standalone_zoomPow(domain, null, frac, exponent || 1) : type === standalone_Symlog ? standalone_zoomSymlog(domain, null, frac, constant || 1) : standalone_zoomLinear(domain, null, frac);
  domain = domain.slice();
  domain[0] = d[0];
  domain[domain.length - 1] = d[1];
  return domain;
}
function standalone_domainCheck(type, domain, df) {
  if (standalone_isLogarithmic(type)) {
    // sum signs of domain values
    // if all pos or all neg, abs(sum) === domain.length
    var s = Math.abs(domain.reduce((s, v) => s + (v < 0 ? -1 : v > 0 ? 1 : 0), 0));
    if (s !== domain.length) {
      df.warn('Log scale domain includes zero: ' + standalone_$(domain));
    }
  }
  return domain;
}
function standalone_configureBins(scale, _, count) {
  let bins = _.bins;
  if (bins && !standalone_vega_util_module_isArray(bins)) {
    // generate bin boundary array
    const domain = scale.domain(),
      lo = domain[0],
      hi = standalone_peek(domain),
      step = bins.step;
    let start = bins.start == null ? lo : bins.start,
      stop = bins.stop == null ? hi : bins.stop;
    if (!step) standalone_vega_util_module_error('Scale bins parameter missing step property.');
    if (start < lo) start = step * Math.ceil(lo / step);
    if (stop > hi) stop = step * Math.floor(hi / step);
    bins = standalone_range(start, stop + step / 2, step);
  }
  if (bins) {
    // assign bin boundaries to scale instance
    scale.bins = bins;
  } else if (scale.bins) {
    // no current bins, remove bins if previously set
    delete scale.bins;
  }

  // special handling for bin-ordinal scales
  if (scale.type === standalone_BinOrdinal) {
    if (!bins) {
      // the domain specifies the bins
      scale.bins = scale.domain();
    } else if (!_.domain && !_.domainRaw) {
      // the bins specify the domain
      scale.domain(bins);
      count = bins.length;
    }
  }

  // return domain cardinality
  return count;
}
function standalone_configureRange(scale, _, count) {
  var type = scale.type,
    round = _.round || false,
    range = _.range;

  // if range step specified, calculate full range extent
  if (_.rangeStep != null) {
    range = standalone_configureRangeStep(type, _, count);
  }

  // else if a range scheme is defined, use that
  else if (_.scheme) {
    range = standalone_configureScheme(type, _, count);
    if (standalone_vega_util_module_isFunction(range)) {
      if (scale.interpolator) {
        return scale.interpolator(range);
      } else {
        standalone_vega_util_module_error(`Scale type ${type} does not support interpolating color schemes.`);
      }
    }
  }

  // given a range array for an interpolating scale, convert to interpolator
  if (range && standalone_isInterpolating(type)) {
    return scale.interpolator(standalone_interpolateColors(standalone_flip(range, _.reverse), _.interpolate, _.interpolateGamma));
  }

  // configure rounding / interpolation
  if (range && _.interpolate && scale.interpolate) {
    scale.interpolate(standalone_interpolate(_.interpolate, _.interpolateGamma));
  } else if (standalone_vega_util_module_isFunction(scale.round)) {
    scale.round(round);
  } else if (standalone_vega_util_module_isFunction(scale.rangeRound)) {
    scale.interpolate(round ? standalone_src_round : standalone_value);
  }
  if (range) scale.range(standalone_flip(range, _.reverse));
}
function standalone_configureRangeStep(type, _, count) {
  if (type !== standalone_Band && type !== standalone_Point) {
    standalone_vega_util_module_error('Only band and point scales support rangeStep.');
  }

  // calculate full range based on requested step size and padding
  var outer = (_.paddingOuter != null ? _.paddingOuter : _.padding) || 0,
    inner = type === standalone_Point ? 1 : (_.paddingInner != null ? _.paddingInner : _.padding) || 0;
  return [0, _.rangeStep * standalone_bandSpace(count, inner, outer)];
}
function standalone_configureScheme(type, _, count) {
  var extent = _.schemeExtent,
    name,
    scheme$1;
  if (standalone_vega_util_module_isArray(_.scheme)) {
    scheme$1 = standalone_interpolateColors(_.scheme, _.interpolate, _.interpolateGamma);
  } else {
    name = _.scheme.toLowerCase();
    scheme$1 = standalone_scheme(name);
    if (!scheme$1) standalone_vega_util_module_error(`Unrecognized scheme name: ${_.scheme}`);
  }

  // determine size for potential discrete range
  count = type === standalone_Threshold ? count + 1 : type === standalone_BinOrdinal ? count - 1 : type === standalone_vega_scale_module_Quantile || type === standalone_Quantize ? +_.schemeCount || standalone_DEFAULT_COUNT : count;

  // adjust and/or quantize scheme as appropriate
  return standalone_isInterpolating(type) ? standalone_adjustScheme(scheme$1, extent, _.reverse) : standalone_vega_util_module_isFunction(scheme$1) ? standalone_quantizeInterpolator(standalone_adjustScheme(scheme$1, extent), count) : type === standalone_Ordinal ? scheme$1 : scheme$1.slice(0, count);
}
function standalone_adjustScheme(scheme, extent, reverse) {
  return standalone_vega_util_module_isFunction(scheme) && (extent || reverse) ? standalone_interpolateRange(scheme, standalone_flip(extent || [0, 1], reverse)) : scheme;
}
function standalone_flip(array, reverse) {
  return reverse ? array.slice().reverse() : array;
}

/**
 * Sorts scenegraph items in the pulse source array.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(*,*): number} [params.sort] - A comparator
 *   function for sorting tuples.
 */
function standalone_SortItems(params) {
  standalone_Transform.call(this, null, params);
}
standalone_inherits(standalone_SortItems, standalone_Transform, {
  transform(_, pulse) {
    const mod = _.modified('sort') || pulse.changed(pulse.ADD) || pulse.modified(_.sort.fields) || pulse.modified('datum');
    if (mod) pulse.source.sort(standalone_stableCompare(_.sort));
    this.modified(mod);
    return pulse;
  }
});

const standalone_Zero = 'zero',
  standalone_Center = 'center',
  standalone_Normalize = 'normalize',
  standalone_DefOutput = ['y0', 'y1'];

/**
 * Stack layout for visualization elements.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The value field to stack.
 * @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby.
 * @param {function(object,object): number} [params.sort] - A comparator for stack sorting.
 * @param {string} [offset='zero'] - Stack baseline offset. One of 'zero', 'center', 'normalize'.
 */
function standalone_Stack(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Stack.Definition = {
  'type': 'Stack',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'field',
    'type': 'field'
  }, {
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'sort',
    'type': 'compare'
  }, {
    'name': 'offset',
    'type': 'enum',
    'default': standalone_Zero,
    'values': [standalone_Zero, standalone_Center, standalone_Normalize]
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': 2,
    'default': standalone_DefOutput
  }]
};
standalone_inherits(standalone_Stack, standalone_Transform, {
  transform(_, pulse) {
    var as = _.as || standalone_DefOutput,
      y0 = as[0],
      y1 = as[1],
      sort = standalone_stableCompare(_.sort),
      field = _.field || standalone_one,
      stack = _.offset === standalone_Center ? standalone_stackCenter : _.offset === standalone_Normalize ? standalone_stackNormalize : standalone_stackZero,
      groups,
      i,
      n,
      max;

    // partition, sum, and sort the stack groups
    groups = standalone_vega_encode_module_partition(pulse.source, _.groupby, sort, field);

    // compute stack layouts per group
    for (i = 0, n = groups.length, max = groups.max; i < n; ++i) {
      stack(groups[i], max, field, y0, y1);
    }
    return pulse.reflow(_.modified()).modifies(as);
  }
});
function standalone_stackCenter(group, max, field, y0, y1) {
  var last = (max - group.sum) / 2,
    m = group.length,
    j = 0,
    t;
  for (; j < m; ++j) {
    t = group[j];
    t[y0] = last;
    t[y1] = last += Math.abs(field(t));
  }
}
function standalone_stackNormalize(group, max, field, y0, y1) {
  var scale = 1 / group.sum,
    last = 0,
    m = group.length,
    j = 0,
    v = 0,
    t;
  for (; j < m; ++j) {
    t = group[j];
    t[y0] = last;
    t[y1] = last = scale * (v += Math.abs(field(t)));
  }
}
function standalone_stackZero(group, max, field, y0, y1) {
  var lastPos = 0,
    lastNeg = 0,
    m = group.length,
    j = 0,
    v,
    t;
  for (; j < m; ++j) {
    t = group[j];
    v = +field(t);
    if (v < 0) {
      t[y0] = lastNeg;
      t[y1] = lastNeg += v;
    } else {
      t[y0] = lastPos;
      t[y1] = lastPos += v;
    }
  }
}
function standalone_vega_encode_module_partition(data, groupby, sort, field) {
  var groups = [],
    get = f => f(t),
    map,
    i,
    n,
    m,
    t,
    k,
    g,
    s,
    max;

  // partition data points into stack groups
  if (groupby == null) {
    groups.push(data.slice());
  } else {
    for (map = {}, i = 0, n = data.length; i < n; ++i) {
      t = data[i];
      k = groupby.map(get);
      g = map[k];
      if (!g) {
        map[k] = g = [];
        groups.push(g);
      }
      g.push(t);
    }
  }

  // compute sums of groups, sort groups as needed
  for (k = 0, max = 0, m = groups.length; k < m; ++k) {
    g = groups[k];
    for (i = 0, s = 0, n = g.length; i < n; ++i) {
      s += Math.abs(field(g[i]));
    }
    g.sum = s;
    if (s > max) max = s;
    if (sort) g.sort(sort);
  }
  groups.max = max;
  return groups;
}



;// ../../node_modules/d3-geo/src/identity.js
/* harmony default export */ const standalone_d3_geo_src_identity = (x => x);

;// ../../node_modules/d3-geo/src/stream.js
function standalone_streamGeometry(geometry, stream) {
  if (geometry && standalone_streamGeometryType.hasOwnProperty(geometry.type)) {
    standalone_streamGeometryType[geometry.type](geometry, stream);
  }
}

var standalone_streamObjectType = {
  Feature: function(object, stream) {
    standalone_streamGeometry(object.geometry, stream);
  },
  FeatureCollection: function(object, stream) {
    var features = object.features, i = -1, n = features.length;
    while (++i < n) standalone_streamGeometry(features[i].geometry, stream);
  }
};

var standalone_streamGeometryType = {
  Sphere: function(object, stream) {
    stream.sphere();
  },
  Point: function(object, stream) {
    object = object.coordinates;
    stream.point(object[0], object[1], object[2]);
  },
  MultiPoint: function(object, stream) {
    var coordinates = object.coordinates, i = -1, n = coordinates.length;
    while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]);
  },
  LineString: function(object, stream) {
    standalone_streamLine(object.coordinates, stream, 0);
  },
  MultiLineString: function(object, stream) {
    var coordinates = object.coordinates, i = -1, n = coordinates.length;
    while (++i < n) standalone_streamLine(coordinates[i], stream, 0);
  },
  Polygon: function(object, stream) {
    standalone_streamPolygon(object.coordinates, stream);
  },
  MultiPolygon: function(object, stream) {
    var coordinates = object.coordinates, i = -1, n = coordinates.length;
    while (++i < n) standalone_streamPolygon(coordinates[i], stream);
  },
  GeometryCollection: function(object, stream) {
    var geometries = object.geometries, i = -1, n = geometries.length;
    while (++i < n) standalone_streamGeometry(geometries[i], stream);
  }
};

function standalone_streamLine(coordinates, stream, closed) {
  var i = -1, n = coordinates.length - closed, coordinate;
  stream.lineStart();
  while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);
  stream.lineEnd();
}

function standalone_streamPolygon(coordinates, stream) {
  var i = -1, n = coordinates.length;
  stream.polygonStart();
  while (++i < n) standalone_streamLine(coordinates[i], stream, 1);
  stream.polygonEnd();
}

/* harmony default export */ function standalone_src_stream(object, stream) {
  if (object && standalone_streamObjectType.hasOwnProperty(object.type)) {
    standalone_streamObjectType[object.type](object, stream);
  } else {
    standalone_streamGeometry(object, stream);
  }
}

;// ../../node_modules/d3-array/src/fsum.js
// https://github.com/python/cpython/blob/a74eea238f5baba15797e2e8b570d153bc8690a7/Modules/mathmodule.c#L1423
class standalone_Adder {
  constructor() {
    this._partials = new Float64Array(32);
    this._n = 0;
  }
  add(x) {
    const p = this._partials;
    let i = 0;
    for (let j = 0; j < this._n && j < 32; j++) {
      const y = p[j],
        hi = x + y,
        lo = Math.abs(x) < Math.abs(y) ? x - (hi - y) : y - (hi - x);
      if (lo) p[i++] = lo;
      x = hi;
    }
    p[i] = x;
    this._n = i + 1;
    return this;
  }
  valueOf() {
    const p = this._partials;
    let n = this._n, x, y, lo, hi = 0;
    if (n > 0) {
      hi = p[--n];
      while (n > 0) {
        x = hi;
        y = p[--n];
        hi = x + y;
        lo = y - (hi - x);
        if (lo) break;
      }
      if (n > 0 && ((lo < 0 && p[n - 1] < 0) || (lo > 0 && p[n - 1] > 0))) {
        y = lo * 2;
        x = hi + y;
        if (y == x - hi) hi = x;
      }
    }
    return hi;
  }
}

function standalone_fsum(values, valueof) {
  const adder = new standalone_Adder();
  if (valueof === undefined) {
    for (let value of values) {
      if (value = +value) {
        adder.add(value);
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if (value = +valueof(value, ++index, values)) {
        adder.add(value);
      }
    }
  }
  return +adder;
}

function standalone_fcumsum(values, valueof) {
  const adder = new standalone_Adder();
  let index = -1;
  return Float64Array.from(values, valueof === undefined
      ? v => adder.add(+v || 0)
      : v => adder.add(+valueof(v, ++index, values) || 0)
  );
}

;// ../../node_modules/d3-geo/src/math.js
var standalone_src_math_epsilon = 1e-6;
var standalone_math_epsilon2 = 1e-12;
var standalone_math_pi = Math.PI;
var standalone_math_halfPi = standalone_math_pi / 2;
var standalone_quarterPi = standalone_math_pi / 4;
var standalone_math_tau = standalone_math_pi * 2;

var standalone_src_math_degrees = 180 / standalone_math_pi;
var standalone_src_math_radians = standalone_math_pi / 180;

var standalone_math_abs = Math.abs;
var standalone_atan = Math.atan;
var standalone_math_atan2 = Math.atan2;
var standalone_math_cos = Math.cos;
var standalone_ceil = Math.ceil;
var standalone_math_exp = Math.exp;
var standalone_math_floor = Math.floor;
var standalone_hypot = Math.hypot;
var standalone_math_log = Math.log;
var standalone_math_pow = Math.pow;
var standalone_math_sin = Math.sin;
var standalone_math_sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };
var standalone_math_sqrt = Math.sqrt;
var standalone_tan = Math.tan;

function standalone_math_acos(x) {
  return x > 1 ? 0 : x < -1 ? standalone_math_pi : Math.acos(x);
}

function standalone_math_asin(x) {
  return x > 1 ? standalone_math_halfPi : x < -1 ? -standalone_math_halfPi : Math.asin(x);
}

function standalone_haversin(x) {
  return (x = standalone_math_sin(x / 2)) * x;
}

;// ../../node_modules/d3-geo/src/noop.js
function standalone_noop_noop() {}

;// ../../node_modules/d3-geo/src/path/area.js




var standalone_areaSum = new standalone_Adder(),
    standalone_areaRingSum = new standalone_Adder(),
    standalone_x00,
    standalone_y00,
    standalone_x0,
    standalone_y0;

var standalone_areaStream = {
  point: standalone_noop_noop,
  lineStart: standalone_noop_noop,
  lineEnd: standalone_noop_noop,
  polygonStart: function() {
    standalone_areaStream.lineStart = standalone_areaRingStart;
    standalone_areaStream.lineEnd = standalone_areaRingEnd;
  },
  polygonEnd: function() {
    standalone_areaStream.lineStart = standalone_areaStream.lineEnd = standalone_areaStream.point = standalone_noop_noop;
    standalone_areaSum.add(standalone_math_abs(standalone_areaRingSum));
    standalone_areaRingSum = new standalone_Adder();
  },
  result: function() {
    var area = standalone_areaSum / 2;
    standalone_areaSum = new standalone_Adder();
    return area;
  }
};

function standalone_areaRingStart() {
  standalone_areaStream.point = standalone_areaPointFirst;
}

function standalone_areaPointFirst(x, y) {
  standalone_areaStream.point = standalone_areaPoint;
  standalone_x00 = standalone_x0 = x, standalone_y00 = standalone_y0 = y;
}

function standalone_areaPoint(x, y) {
  standalone_areaRingSum.add(standalone_y0 * x - standalone_x0 * y);
  standalone_x0 = x, standalone_y0 = y;
}

function standalone_areaRingEnd() {
  standalone_areaPoint(standalone_x00, standalone_y00);
}

/* harmony default export */ const standalone_path_area = (standalone_areaStream);

;// ../../node_modules/d3-geo/src/path/bounds.js


var standalone_bounds_x0 = Infinity,
    standalone_bounds_y0 = standalone_bounds_x0,
    standalone_x1 = -standalone_bounds_x0,
    standalone_y1 = standalone_x1;

var standalone_boundsStream = {
  point: standalone_boundsPoint,
  lineStart: standalone_noop_noop,
  lineEnd: standalone_noop_noop,
  polygonStart: standalone_noop_noop,
  polygonEnd: standalone_noop_noop,
  result: function() {
    var bounds = [[standalone_bounds_x0, standalone_bounds_y0], [standalone_x1, standalone_y1]];
    standalone_x1 = standalone_y1 = -(standalone_bounds_y0 = standalone_bounds_x0 = Infinity);
    return bounds;
  }
};

function standalone_boundsPoint(x, y) {
  if (x < standalone_bounds_x0) standalone_bounds_x0 = x;
  if (x > standalone_x1) standalone_x1 = x;
  if (y < standalone_bounds_y0) standalone_bounds_y0 = y;
  if (y > standalone_y1) standalone_y1 = y;
}

/* harmony default export */ const standalone_path_bounds = (standalone_boundsStream);

;// ../../node_modules/d3-geo/src/path/centroid.js


// TODO Enforce positive area for exterior, negative area for interior?

var standalone_X0 = 0,
    standalone_Y0 = 0,
    standalone_Z0 = 0,
    standalone_X1 = 0,
    standalone_Y1 = 0,
    standalone_Z1 = 0,
    standalone_X2 = 0,
    standalone_Y2 = 0,
    standalone_Z2 = 0,
    standalone_centroid_x00,
    standalone_centroid_y00,
    standalone_centroid_x0,
    standalone_centroid_y0;

var standalone_centroidStream = {
  point: standalone_centroidPoint,
  lineStart: standalone_centroidLineStart,
  lineEnd: standalone_centroidLineEnd,
  polygonStart: function() {
    standalone_centroidStream.lineStart = standalone_centroidRingStart;
    standalone_centroidStream.lineEnd = standalone_centroidRingEnd;
  },
  polygonEnd: function() {
    standalone_centroidStream.point = standalone_centroidPoint;
    standalone_centroidStream.lineStart = standalone_centroidLineStart;
    standalone_centroidStream.lineEnd = standalone_centroidLineEnd;
  },
  result: function() {
    var centroid = standalone_Z2 ? [standalone_X2 / standalone_Z2, standalone_Y2 / standalone_Z2]
        : standalone_Z1 ? [standalone_X1 / standalone_Z1, standalone_Y1 / standalone_Z1]
        : standalone_Z0 ? [standalone_X0 / standalone_Z0, standalone_Y0 / standalone_Z0]
        : [NaN, NaN];
    standalone_X0 = standalone_Y0 = standalone_Z0 =
    standalone_X1 = standalone_Y1 = standalone_Z1 =
    standalone_X2 = standalone_Y2 = standalone_Z2 = 0;
    return centroid;
  }
};

function standalone_centroidPoint(x, y) {
  standalone_X0 += x;
  standalone_Y0 += y;
  ++standalone_Z0;
}

function standalone_centroidLineStart() {
  standalone_centroidStream.point = standalone_centroidPointFirstLine;
}

function standalone_centroidPointFirstLine(x, y) {
  standalone_centroidStream.point = standalone_centroidPointLine;
  standalone_centroidPoint(standalone_centroid_x0 = x, standalone_centroid_y0 = y);
}

function standalone_centroidPointLine(x, y) {
  var dx = x - standalone_centroid_x0, dy = y - standalone_centroid_y0, z = standalone_math_sqrt(dx * dx + dy * dy);
  standalone_X1 += z * (standalone_centroid_x0 + x) / 2;
  standalone_Y1 += z * (standalone_centroid_y0 + y) / 2;
  standalone_Z1 += z;
  standalone_centroidPoint(standalone_centroid_x0 = x, standalone_centroid_y0 = y);
}

function standalone_centroidLineEnd() {
  standalone_centroidStream.point = standalone_centroidPoint;
}

function standalone_centroidRingStart() {
  standalone_centroidStream.point = standalone_centroidPointFirstRing;
}

function standalone_centroidRingEnd() {
  standalone_centroidPointRing(standalone_centroid_x00, standalone_centroid_y00);
}

function standalone_centroidPointFirstRing(x, y) {
  standalone_centroidStream.point = standalone_centroidPointRing;
  standalone_centroidPoint(standalone_centroid_x00 = standalone_centroid_x0 = x, standalone_centroid_y00 = standalone_centroid_y0 = y);
}

function standalone_centroidPointRing(x, y) {
  var dx = x - standalone_centroid_x0,
      dy = y - standalone_centroid_y0,
      z = standalone_math_sqrt(dx * dx + dy * dy);

  standalone_X1 += z * (standalone_centroid_x0 + x) / 2;
  standalone_Y1 += z * (standalone_centroid_y0 + y) / 2;
  standalone_Z1 += z;

  z = standalone_centroid_y0 * x - standalone_centroid_x0 * y;
  standalone_X2 += z * (standalone_centroid_x0 + x);
  standalone_Y2 += z * (standalone_centroid_y0 + y);
  standalone_Z2 += z * 3;
  standalone_centroidPoint(standalone_centroid_x0 = x, standalone_centroid_y0 = y);
}

/* harmony default export */ const standalone_centroid = (standalone_centroidStream);

;// ../../node_modules/d3-geo/src/path/context.js



function standalone_PathContext(context) {
  this._context = context;
}

standalone_PathContext.prototype = {
  _radius: 4.5,
  pointRadius: function(_) {
    return this._radius = _, this;
  },
  polygonStart: function() {
    this._line = 0;
  },
  polygonEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line === 0) this._context.closePath();
    this._point = NaN;
  },
  point: function(x, y) {
    switch (this._point) {
      case 0: {
        this._context.moveTo(x, y);
        this._point = 1;
        break;
      }
      case 1: {
        this._context.lineTo(x, y);
        break;
      }
      default: {
        this._context.moveTo(x + this._radius, y);
        this._context.arc(x, y, this._radius, 0, standalone_math_tau);
        break;
      }
    }
  },
  result: standalone_noop_noop
};

;// ../../node_modules/d3-geo/src/path/measure.js




var standalone_lengthSum = new standalone_Adder(),
    standalone_lengthRing,
    standalone_measure_x00,
    standalone_measure_y00,
    standalone_measure_x0,
    standalone_measure_y0;

var standalone_lengthStream = {
  point: standalone_noop_noop,
  lineStart: function() {
    standalone_lengthStream.point = standalone_lengthPointFirst;
  },
  lineEnd: function() {
    if (standalone_lengthRing) standalone_lengthPoint(standalone_measure_x00, standalone_measure_y00);
    standalone_lengthStream.point = standalone_noop_noop;
  },
  polygonStart: function() {
    standalone_lengthRing = true;
  },
  polygonEnd: function() {
    standalone_lengthRing = null;
  },
  result: function() {
    var length = +standalone_lengthSum;
    standalone_lengthSum = new standalone_Adder();
    return length;
  }
};

function standalone_lengthPointFirst(x, y) {
  standalone_lengthStream.point = standalone_lengthPoint;
  standalone_measure_x00 = standalone_measure_x0 = x, standalone_measure_y00 = standalone_measure_y0 = y;
}

function standalone_lengthPoint(x, y) {
  standalone_measure_x0 -= x, standalone_measure_y0 -= y;
  standalone_lengthSum.add(standalone_math_sqrt(standalone_measure_x0 * standalone_measure_x0 + standalone_measure_y0 * standalone_measure_y0));
  standalone_measure_x0 = x, standalone_measure_y0 = y;
}

/* harmony default export */ const standalone_path_measure = (standalone_lengthStream);

;// ../../node_modules/d3-geo/src/path/string.js
// Simple caching for constant-radius points.
let standalone_cacheDigits, standalone_cacheAppend, standalone_cacheRadius, standalone_cacheCircle;

class standalone_PathString {
  constructor(digits) {
    this._append = digits == null ? standalone_string_append : standalone_string_appendRound(digits);
    this._radius = 4.5;
    this._ = "";
  }
  pointRadius(_) {
    this._radius = +_;
    return this;
  }
  polygonStart() {
    this._line = 0;
  }
  polygonEnd() {
    this._line = NaN;
  }
  lineStart() {
    this._point = 0;
  }
  lineEnd() {
    if (this._line === 0) this._ += "Z";
    this._point = NaN;
  }
  point(x, y) {
    switch (this._point) {
      case 0: {
        this._append`M${x},${y}`;
        this._point = 1;
        break;
      }
      case 1: {
        this._append`L${x},${y}`;
        break;
      }
      default: {
        this._append`M${x},${y}`;
        if (this._radius !== standalone_cacheRadius || this._append !== standalone_cacheAppend) {
          const r = this._radius;
          const s = this._;
          this._ = ""; // stash the old string so we can cache the circle path fragment
          this._append`m0,${r}a${r},${r} 0 1,1 0,${-2 * r}a${r},${r} 0 1,1 0,${2 * r}z`;
          standalone_cacheRadius = r;
          standalone_cacheAppend = this._append;
          standalone_cacheCircle = this._;
          this._ = s;
        }
        this._ += standalone_cacheCircle;
        break;
      }
    }
  }
  result() {
    const result = this._;
    this._ = "";
    return result.length ? result : null;
  }
}

function standalone_string_append(strings) {
  let i = 1;
  this._ += strings[0];
  for (const j = strings.length; i < j; ++i) {
    this._ += arguments[i] + strings[i];
  }
}

function standalone_string_appendRound(digits) {
  const d = Math.floor(digits);
  if (!(d >= 0)) throw new RangeError(`invalid digits: ${digits}`);
  if (d > 15) return standalone_string_append;
  if (d !== standalone_cacheDigits) {
    const k = 10 ** d;
    standalone_cacheDigits = d;
    standalone_cacheAppend = function append(strings) {
      let i = 1;
      this._ += strings[0];
      for (const j = strings.length; i < j; ++i) {
        this._ += Math.round(arguments[i] * k) / k + strings[i];
      }
    };
  }
  return standalone_cacheAppend;
}

;// ../../node_modules/d3-geo/src/path/index.js









/* harmony default export */ function standalone_src_path(projection, context) {
  let digits = 3,
      pointRadius = 4.5,
      projectionStream,
      contextStream;

  function path(object) {
    if (object) {
      if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
      standalone_src_stream(object, projectionStream(contextStream));
    }
    return contextStream.result();
  }

  path.area = function(object) {
    standalone_src_stream(object, projectionStream(standalone_path_area));
    return standalone_path_area.result();
  };

  path.measure = function(object) {
    standalone_src_stream(object, projectionStream(standalone_path_measure));
    return standalone_path_measure.result();
  };

  path.bounds = function(object) {
    standalone_src_stream(object, projectionStream(standalone_path_bounds));
    return standalone_path_bounds.result();
  };

  path.centroid = function(object) {
    standalone_src_stream(object, projectionStream(standalone_centroid));
    return standalone_centroid.result();
  };

  path.projection = function(_) {
    if (!arguments.length) return projection;
    projectionStream = _ == null ? (projection = null, standalone_d3_geo_src_identity) : (projection = _).stream;
    return path;
  };

  path.context = function(_) {
    if (!arguments.length) return context;
    contextStream = _ == null ? (context = null, new standalone_PathString(digits)) : new standalone_PathContext(context = _);
    if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
    return path;
  };

  path.pointRadius = function(_) {
    if (!arguments.length) return pointRadius;
    pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
    return path;
  };

  path.digits = function(_) {
    if (!arguments.length) return digits;
    if (_ == null) digits = null;
    else {
      const d = Math.floor(_);
      if (!(d >= 0)) throw new RangeError(`invalid digits: ${_}`);
      digits = d;
    }
    if (context === null) contextStream = new standalone_PathString(digits);
    return path;
  };

  return path.projection(projection).digits(digits).context(context);
}

;// ../../node_modules/d3-geo/src/clip/buffer.js


/* harmony default export */ function standalone_buffer() {
  var lines = [],
      line;
  return {
    point: function(x, y, m) {
      line.push([x, y, m]);
    },
    lineStart: function() {
      lines.push(line = []);
    },
    lineEnd: standalone_noop_noop,
    rejoin: function() {
      if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
    },
    result: function() {
      var result = lines;
      lines = [];
      line = null;
      return result;
    }
  };
}

;// ../../node_modules/d3-geo/src/pointEqual.js


/* harmony default export */ function standalone_pointEqual(a, b) {
  return standalone_math_abs(a[0] - b[0]) < standalone_src_math_epsilon && standalone_math_abs(a[1] - b[1]) < standalone_src_math_epsilon;
}

;// ../../node_modules/d3-geo/src/clip/rejoin.js



function standalone_Intersection(point, points, other, entry) {
  this.x = point;
  this.z = points;
  this.o = other; // another intersection
  this.e = entry; // is an entry?
  this.v = false; // visited
  this.n = this.p = null; // next & previous
}

// A generalized polygon clipping algorithm: given a polygon that has been cut
// into its visible line segments, and rejoins the segments by interpolating
// along the clip edge.
/* harmony default export */ function standalone_rejoin(segments, compareIntersection, startInside, interpolate, stream) {
  var subject = [],
      clip = [],
      i,
      n;

  segments.forEach(function(segment) {
    if ((n = segment.length - 1) <= 0) return;
    var n, p0 = segment[0], p1 = segment[n], x;

    if (standalone_pointEqual(p0, p1)) {
      if (!p0[2] && !p1[2]) {
        stream.lineStart();
        for (i = 0; i < n; ++i) stream.point((p0 = segment[i])[0], p0[1]);
        stream.lineEnd();
        return;
      }
      // handle degenerate cases by moving the point
      p1[0] += 2 * standalone_src_math_epsilon;
    }

    subject.push(x = new standalone_Intersection(p0, segment, null, true));
    clip.push(x.o = new standalone_Intersection(p0, null, x, false));
    subject.push(x = new standalone_Intersection(p1, segment, null, false));
    clip.push(x.o = new standalone_Intersection(p1, null, x, true));
  });

  if (!subject.length) return;

  clip.sort(compareIntersection);
  standalone_rejoin_link(subject);
  standalone_rejoin_link(clip);

  for (i = 0, n = clip.length; i < n; ++i) {
    clip[i].e = startInside = !startInside;
  }

  var start = subject[0],
      points,
      point;

  while (1) {
    // Find first unvisited intersection.
    var current = start,
        isSubject = true;
    while (current.v) if ((current = current.n) === start) return;
    points = current.z;
    stream.lineStart();
    do {
      current.v = current.o.v = true;
      if (current.e) {
        if (isSubject) {
          for (i = 0, n = points.length; i < n; ++i) stream.point((point = points[i])[0], point[1]);
        } else {
          interpolate(current.x, current.n.x, 1, stream);
        }
        current = current.n;
      } else {
        if (isSubject) {
          points = current.p.z;
          for (i = points.length - 1; i >= 0; --i) stream.point((point = points[i])[0], point[1]);
        } else {
          interpolate(current.x, current.p.x, -1, stream);
        }
        current = current.p;
      }
      current = current.o;
      points = current.z;
      isSubject = !isSubject;
    } while (!current.v);
    stream.lineEnd();
  }
}

function standalone_rejoin_link(array) {
  if (!(n = array.length)) return;
  var n,
      i = 0,
      a = array[0],
      b;
  while (++i < n) {
    a.n = b = array[i];
    b.p = a;
    a = b;
  }
  a.n = b = array[0];
  b.p = a;
}

;// ../../node_modules/d3-geo/src/cartesian.js


function standalone_spherical(cartesian) {
  return [standalone_math_atan2(cartesian[1], cartesian[0]), standalone_math_asin(cartesian[2])];
}

function standalone_cartesian_cartesian(spherical) {
  var lambda = spherical[0], phi = spherical[1], cosPhi = standalone_math_cos(phi);
  return [cosPhi * standalone_math_cos(lambda), cosPhi * standalone_math_sin(lambda), standalone_math_sin(phi)];
}

function standalone_cartesianDot(a, b) {
  return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}

function standalone_cartesianCross(a, b) {
  return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
}

// TODO return a
function standalone_cartesianAddInPlace(a, b) {
  a[0] += b[0], a[1] += b[1], a[2] += b[2];
}

function standalone_cartesianScale(vector, k) {
  return [vector[0] * k, vector[1] * k, vector[2] * k];
}

// TODO return d
function standalone_cartesianNormalizeInPlace(d) {
  var l = standalone_math_sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
  d[0] /= l, d[1] /= l, d[2] /= l;
}

;// ../../node_modules/d3-geo/src/polygonContains.js




function standalone_longitude(point) {
  return standalone_math_abs(point[0]) <= standalone_math_pi ? point[0] : standalone_math_sign(point[0]) * ((standalone_math_abs(point[0]) + standalone_math_pi) % standalone_math_tau - standalone_math_pi);
}

/* harmony default export */ function standalone_polygonContains(polygon, point) {
  var lambda = standalone_longitude(point),
      phi = point[1],
      sinPhi = standalone_math_sin(phi),
      normal = [standalone_math_sin(lambda), -standalone_math_cos(lambda), 0],
      angle = 0,
      winding = 0;

  var sum = new standalone_Adder();

  if (sinPhi === 1) phi = standalone_math_halfPi + standalone_src_math_epsilon;
  else if (sinPhi === -1) phi = -standalone_math_halfPi - standalone_src_math_epsilon;

  for (var i = 0, n = polygon.length; i < n; ++i) {
    if (!(m = (ring = polygon[i]).length)) continue;
    var ring,
        m,
        point0 = ring[m - 1],
        lambda0 = standalone_longitude(point0),
        phi0 = point0[1] / 2 + standalone_quarterPi,
        sinPhi0 = standalone_math_sin(phi0),
        cosPhi0 = standalone_math_cos(phi0);

    for (var j = 0; j < m; ++j, lambda0 = lambda1, sinPhi0 = sinPhi1, cosPhi0 = cosPhi1, point0 = point1) {
      var point1 = ring[j],
          lambda1 = standalone_longitude(point1),
          phi1 = point1[1] / 2 + standalone_quarterPi,
          sinPhi1 = standalone_math_sin(phi1),
          cosPhi1 = standalone_math_cos(phi1),
          delta = lambda1 - lambda0,
          sign = delta >= 0 ? 1 : -1,
          absDelta = sign * delta,
          antimeridian = absDelta > standalone_math_pi,
          k = sinPhi0 * sinPhi1;

      sum.add(standalone_math_atan2(k * sign * standalone_math_sin(absDelta), cosPhi0 * cosPhi1 + k * standalone_math_cos(absDelta)));
      angle += antimeridian ? delta + sign * standalone_math_tau : delta;

      // Are the longitudes either side of the point’s meridian (lambda),
      // and are the latitudes smaller than the parallel (phi)?
      if (antimeridian ^ lambda0 >= lambda ^ lambda1 >= lambda) {
        var arc = standalone_cartesianCross(standalone_cartesian_cartesian(point0), standalone_cartesian_cartesian(point1));
        standalone_cartesianNormalizeInPlace(arc);
        var intersection = standalone_cartesianCross(normal, arc);
        standalone_cartesianNormalizeInPlace(intersection);
        var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * standalone_math_asin(intersection[2]);
        if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) {
          winding += antimeridian ^ delta >= 0 ? 1 : -1;
        }
      }
    }
  }

  // First, determine whether the South pole is inside or outside:
  //
  // It is inside if:
  // * the polygon winds around it in a clockwise direction.
  // * the polygon does not (cumulatively) wind around it, but has a negative
  //   (counter-clockwise) area.
  //
  // Second, count the (signed) number of times a segment crosses a lambda
  // from the point to the South pole.  If it is zero, then the point is the
  // same side as the South pole.

  return (angle < -standalone_src_math_epsilon || angle < standalone_src_math_epsilon && sum < -standalone_math_epsilon2) ^ (winding & 1);
}

;// ../../node_modules/d3-array/src/merge.js
function* standalone_flatten(arrays) {
  for (const array of arrays) {
    yield* array;
  }
}

function standalone_merge_merge(arrays) {
  return Array.from(standalone_flatten(arrays));
}

;// ../../node_modules/d3-geo/src/clip/index.js






/* harmony default export */ function standalone_src_clip(pointVisible, clipLine, interpolate, start) {
  return function(sink) {
    var line = clipLine(sink),
        ringBuffer = standalone_buffer(),
        ringSink = clipLine(ringBuffer),
        polygonStarted = false,
        polygon,
        segments,
        ring;

    var clip = {
      point: point,
      lineStart: lineStart,
      lineEnd: lineEnd,
      polygonStart: function() {
        clip.point = pointRing;
        clip.lineStart = ringStart;
        clip.lineEnd = ringEnd;
        segments = [];
        polygon = [];
      },
      polygonEnd: function() {
        clip.point = point;
        clip.lineStart = lineStart;
        clip.lineEnd = lineEnd;
        segments = standalone_merge_merge(segments);
        var startInside = standalone_polygonContains(polygon, start);
        if (segments.length) {
          if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
          standalone_rejoin(segments, standalone_compareIntersection, startInside, interpolate, sink);
        } else if (startInside) {
          if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
          sink.lineStart();
          interpolate(null, null, 1, sink);
          sink.lineEnd();
        }
        if (polygonStarted) sink.polygonEnd(), polygonStarted = false;
        segments = polygon = null;
      },
      sphere: function() {
        sink.polygonStart();
        sink.lineStart();
        interpolate(null, null, 1, sink);
        sink.lineEnd();
        sink.polygonEnd();
      }
    };

    function point(lambda, phi) {
      if (pointVisible(lambda, phi)) sink.point(lambda, phi);
    }

    function pointLine(lambda, phi) {
      line.point(lambda, phi);
    }

    function lineStart() {
      clip.point = pointLine;
      line.lineStart();
    }

    function lineEnd() {
      clip.point = point;
      line.lineEnd();
    }

    function pointRing(lambda, phi) {
      ring.push([lambda, phi]);
      ringSink.point(lambda, phi);
    }

    function ringStart() {
      ringSink.lineStart();
      ring = [];
    }

    function ringEnd() {
      pointRing(ring[0][0], ring[0][1]);
      ringSink.lineEnd();

      var clean = ringSink.clean(),
          ringSegments = ringBuffer.result(),
          i, n = ringSegments.length, m,
          segment,
          point;

      ring.pop();
      polygon.push(ring);
      ring = null;

      if (!n) return;

      // No intersections.
      if (clean & 1) {
        segment = ringSegments[0];
        if ((m = segment.length - 1) > 0) {
          if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
          sink.lineStart();
          for (i = 0; i < m; ++i) sink.point((point = segment[i])[0], point[1]);
          sink.lineEnd();
        }
        return;
      }

      // Rejoin connected segments.
      // TODO reuse ringBuffer.rejoin()?
      if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));

      segments.push(ringSegments.filter(standalone_validSegment));
    }

    return clip;
  };
}

function standalone_validSegment(segment) {
  return segment.length > 1;
}

// Intersections are sorted along the clip edge. For both antimeridian cutting
// and circle clipping, the same comparison is used.
function standalone_compareIntersection(a, b) {
  return ((a = a.x)[0] < 0 ? a[1] - standalone_math_halfPi - standalone_src_math_epsilon : standalone_math_halfPi - a[1])
       - ((b = b.x)[0] < 0 ? b[1] - standalone_math_halfPi - standalone_src_math_epsilon : standalone_math_halfPi - b[1]);
}

;// ../../node_modules/d3-geo/src/clip/antimeridian.js



/* harmony default export */ const standalone_antimeridian = (standalone_src_clip(
  function() { return true; },
  standalone_clipAntimeridianLine,
  standalone_clipAntimeridianInterpolate,
  [-standalone_math_pi, -standalone_math_halfPi]
));

// Takes a line and cuts into visible segments. Return values: 0 - there were
// intersections or the line was empty; 1 - no intersections; 2 - there were
// intersections, and the first and last segments should be rejoined.
function standalone_clipAntimeridianLine(stream) {
  var lambda0 = NaN,
      phi0 = NaN,
      sign0 = NaN,
      clean; // no intersections

  return {
    lineStart: function() {
      stream.lineStart();
      clean = 1;
    },
    point: function(lambda1, phi1) {
      var sign1 = lambda1 > 0 ? standalone_math_pi : -standalone_math_pi,
          delta = standalone_math_abs(lambda1 - lambda0);
      if (standalone_math_abs(delta - standalone_math_pi) < standalone_src_math_epsilon) { // line crosses a pole
        stream.point(lambda0, phi0 = (phi0 + phi1) / 2 > 0 ? standalone_math_halfPi : -standalone_math_halfPi);
        stream.point(sign0, phi0);
        stream.lineEnd();
        stream.lineStart();
        stream.point(sign1, phi0);
        stream.point(lambda1, phi0);
        clean = 0;
      } else if (sign0 !== sign1 && delta >= standalone_math_pi) { // line crosses antimeridian
        if (standalone_math_abs(lambda0 - sign0) < standalone_src_math_epsilon) lambda0 -= sign0 * standalone_src_math_epsilon; // handle degeneracies
        if (standalone_math_abs(lambda1 - sign1) < standalone_src_math_epsilon) lambda1 -= sign1 * standalone_src_math_epsilon;
        phi0 = standalone_clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1);
        stream.point(sign0, phi0);
        stream.lineEnd();
        stream.lineStart();
        stream.point(sign1, phi0);
        clean = 0;
      }
      stream.point(lambda0 = lambda1, phi0 = phi1);
      sign0 = sign1;
    },
    lineEnd: function() {
      stream.lineEnd();
      lambda0 = phi0 = NaN;
    },
    clean: function() {
      return 2 - clean; // if intersections, rejoin first and last segments
    }
  };
}

function standalone_clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1) {
  var cosPhi0,
      cosPhi1,
      sinLambda0Lambda1 = standalone_math_sin(lambda0 - lambda1);
  return standalone_math_abs(sinLambda0Lambda1) > standalone_src_math_epsilon
      ? standalone_atan((standalone_math_sin(phi0) * (cosPhi1 = standalone_math_cos(phi1)) * standalone_math_sin(lambda1)
          - standalone_math_sin(phi1) * (cosPhi0 = standalone_math_cos(phi0)) * standalone_math_sin(lambda0))
          / (cosPhi0 * cosPhi1 * sinLambda0Lambda1))
      : (phi0 + phi1) / 2;
}

function standalone_clipAntimeridianInterpolate(from, to, direction, stream) {
  var phi;
  if (from == null) {
    phi = direction * standalone_math_halfPi;
    stream.point(-standalone_math_pi, phi);
    stream.point(0, phi);
    stream.point(standalone_math_pi, phi);
    stream.point(standalone_math_pi, 0);
    stream.point(standalone_math_pi, -phi);
    stream.point(0, -phi);
    stream.point(-standalone_math_pi, -phi);
    stream.point(-standalone_math_pi, 0);
    stream.point(-standalone_math_pi, phi);
  } else if (standalone_math_abs(from[0] - to[0]) > standalone_src_math_epsilon) {
    var lambda = from[0] < to[0] ? standalone_math_pi : -standalone_math_pi;
    phi = direction * lambda / 2;
    stream.point(-lambda, phi);
    stream.point(0, phi);
    stream.point(lambda, phi);
  } else {
    stream.point(to[0], to[1]);
  }
}

;// ../../node_modules/d3-geo/src/circle.js





// Generates a circle centered at [0°, 0°], with a given radius and precision.
function standalone_circleStream(stream, radius, delta, direction, t0, t1) {
  if (!delta) return;
  var cosRadius = standalone_math_cos(radius),
      sinRadius = standalone_math_sin(radius),
      step = direction * delta;
  if (t0 == null) {
    t0 = radius + direction * standalone_math_tau;
    t1 = radius - step / 2;
  } else {
    t0 = standalone_circleRadius(cosRadius, t0);
    t1 = standalone_circleRadius(cosRadius, t1);
    if (direction > 0 ? t0 < t1 : t0 > t1) t0 += direction * standalone_math_tau;
  }
  for (var point, t = t0; direction > 0 ? t > t1 : t < t1; t -= step) {
    point = standalone_spherical([cosRadius, -sinRadius * standalone_math_cos(t), -sinRadius * standalone_math_sin(t)]);
    stream.point(point[0], point[1]);
  }
}

// Returns the signed angle of a cartesian point relative to [cosRadius, 0, 0].
function standalone_circleRadius(cosRadius, point) {
  point = standalone_cartesian_cartesian(point), point[0] -= cosRadius;
  standalone_cartesianNormalizeInPlace(point);
  var radius = standalone_math_acos(-point[1]);
  return ((-point[2] < 0 ? -radius : radius) + standalone_math_tau - standalone_src_math_epsilon) % standalone_math_tau;
}

/* harmony default export */ function standalone_src_circle() {
  var center = constant([0, 0]),
      radius = constant(90),
      precision = constant(2),
      ring,
      rotate,
      stream = {point: point};

  function point(x, y) {
    ring.push(x = rotate(x, y));
    x[0] *= degrees, x[1] *= degrees;
  }

  function circle() {
    var c = center.apply(this, arguments),
        r = radius.apply(this, arguments) * radians,
        p = precision.apply(this, arguments) * radians;
    ring = [];
    rotate = rotateRadians(-c[0] * radians, -c[1] * radians, 0).invert;
    standalone_circleStream(stream, r, p, 1);
    c = {type: "Polygon", coordinates: [ring]};
    ring = rotate = null;
    return c;
  }

  circle.center = function(_) {
    return arguments.length ? (center = typeof _ === "function" ? _ : constant([+_[0], +_[1]]), circle) : center;
  };

  circle.radius = function(_) {
    return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), circle) : radius;
  };

  circle.precision = function(_) {
    return arguments.length ? (precision = typeof _ === "function" ? _ : constant(+_), circle) : precision;
  };

  return circle;
}

;// ../../node_modules/d3-geo/src/clip/circle.js






/* harmony default export */ function standalone_clip_circle(radius) {
  var cr = standalone_math_cos(radius),
      delta = 2 * standalone_src_math_radians,
      smallRadius = cr > 0,
      notHemisphere = standalone_math_abs(cr) > standalone_src_math_epsilon; // TODO optimise for this common case

  function interpolate(from, to, direction, stream) {
    standalone_circleStream(stream, radius, delta, direction, from, to);
  }

  function visible(lambda, phi) {
    return standalone_math_cos(lambda) * standalone_math_cos(phi) > cr;
  }

  // Takes a line and cuts into visible segments. Return values used for polygon
  // clipping: 0 - there were intersections or the line was empty; 1 - no
  // intersections 2 - there were intersections, and the first and last segments
  // should be rejoined.
  function clipLine(stream) {
    var point0, // previous point
        c0, // code for previous point
        v0, // visibility of previous point
        v00, // visibility of first point
        clean; // no intersections
    return {
      lineStart: function() {
        v00 = v0 = false;
        clean = 1;
      },
      point: function(lambda, phi) {
        var point1 = [lambda, phi],
            point2,
            v = visible(lambda, phi),
            c = smallRadius
              ? v ? 0 : code(lambda, phi)
              : v ? code(lambda + (lambda < 0 ? standalone_math_pi : -standalone_math_pi), phi) : 0;
        if (!point0 && (v00 = v0 = v)) stream.lineStart();
        if (v !== v0) {
          point2 = intersect(point0, point1);
          if (!point2 || standalone_pointEqual(point0, point2) || standalone_pointEqual(point1, point2))
            point1[2] = 1;
        }
        if (v !== v0) {
          clean = 0;
          if (v) {
            // outside going in
            stream.lineStart();
            point2 = intersect(point1, point0);
            stream.point(point2[0], point2[1]);
          } else {
            // inside going out
            point2 = intersect(point0, point1);
            stream.point(point2[0], point2[1], 2);
            stream.lineEnd();
          }
          point0 = point2;
        } else if (notHemisphere && point0 && smallRadius ^ v) {
          var t;
          // If the codes for two points are different, or are both zero,
          // and there this segment intersects with the small circle.
          if (!(c & c0) && (t = intersect(point1, point0, true))) {
            clean = 0;
            if (smallRadius) {
              stream.lineStart();
              stream.point(t[0][0], t[0][1]);
              stream.point(t[1][0], t[1][1]);
              stream.lineEnd();
            } else {
              stream.point(t[1][0], t[1][1]);
              stream.lineEnd();
              stream.lineStart();
              stream.point(t[0][0], t[0][1], 3);
            }
          }
        }
        if (v && (!point0 || !standalone_pointEqual(point0, point1))) {
          stream.point(point1[0], point1[1]);
        }
        point0 = point1, v0 = v, c0 = c;
      },
      lineEnd: function() {
        if (v0) stream.lineEnd();
        point0 = null;
      },
      // Rejoin first and last segments if there were intersections and the first
      // and last points were visible.
      clean: function() {
        return clean | ((v00 && v0) << 1);
      }
    };
  }

  // Intersects the great circle between a and b with the clip circle.
  function intersect(a, b, two) {
    var pa = standalone_cartesian_cartesian(a),
        pb = standalone_cartesian_cartesian(b);

    // We have two planes, n1.p = d1 and n2.p = d2.
    // Find intersection line p(t) = c1 n1 + c2 n2 + t (n1 ⨯ n2).
    var n1 = [1, 0, 0], // normal
        n2 = standalone_cartesianCross(pa, pb),
        n2n2 = standalone_cartesianDot(n2, n2),
        n1n2 = n2[0], // cartesianDot(n1, n2),
        determinant = n2n2 - n1n2 * n1n2;

    // Two polar points.
    if (!determinant) return !two && a;

    var c1 =  cr * n2n2 / determinant,
        c2 = -cr * n1n2 / determinant,
        n1xn2 = standalone_cartesianCross(n1, n2),
        A = standalone_cartesianScale(n1, c1),
        B = standalone_cartesianScale(n2, c2);
    standalone_cartesianAddInPlace(A, B);

    // Solve |p(t)|^2 = 1.
    var u = n1xn2,
        w = standalone_cartesianDot(A, u),
        uu = standalone_cartesianDot(u, u),
        t2 = w * w - uu * (standalone_cartesianDot(A, A) - 1);

    if (t2 < 0) return;

    var t = standalone_math_sqrt(t2),
        q = standalone_cartesianScale(u, (-w - t) / uu);
    standalone_cartesianAddInPlace(q, A);
    q = standalone_spherical(q);

    if (!two) return q;

    // Two intersection points.
    var lambda0 = a[0],
        lambda1 = b[0],
        phi0 = a[1],
        phi1 = b[1],
        z;

    if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z;

    var delta = lambda1 - lambda0,
        polar = standalone_math_abs(delta - standalone_math_pi) < standalone_src_math_epsilon,
        meridian = polar || delta < standalone_src_math_epsilon;

    if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z;

    // Check that the first point is between a and b.
    if (meridian
        ? polar
          ? phi0 + phi1 > 0 ^ q[1] < (standalone_math_abs(q[0] - lambda0) < standalone_src_math_epsilon ? phi0 : phi1)
          : phi0 <= q[1] && q[1] <= phi1
        : delta > standalone_math_pi ^ (lambda0 <= q[0] && q[0] <= lambda1)) {
      var q1 = standalone_cartesianScale(u, (-w + t) / uu);
      standalone_cartesianAddInPlace(q1, A);
      return [q, standalone_spherical(q1)];
    }
  }

  // Generates a 4-bit vector representing the location of a point relative to
  // the small circle's bounding box.
  function code(lambda, phi) {
    var r = smallRadius ? radius : standalone_math_pi - radius,
        code = 0;
    if (lambda < -r) code |= 1; // left
    else if (lambda > r) code |= 2; // right
    if (phi < -r) code |= 4; // below
    else if (phi > r) code |= 8; // above
    return code;
  }

  return standalone_src_clip(visible, clipLine, interpolate, smallRadius ? [0, -radius] : [-standalone_math_pi, radius - standalone_math_pi]);
}

;// ../../node_modules/d3-geo/src/clip/line.js
/* harmony default export */ function standalone_clip_line(a, b, x0, y0, x1, y1) {
  var ax = a[0],
      ay = a[1],
      bx = b[0],
      by = b[1],
      t0 = 0,
      t1 = 1,
      dx = bx - ax,
      dy = by - ay,
      r;

  r = x0 - ax;
  if (!dx && r > 0) return;
  r /= dx;
  if (dx < 0) {
    if (r < t0) return;
    if (r < t1) t1 = r;
  } else if (dx > 0) {
    if (r > t1) return;
    if (r > t0) t0 = r;
  }

  r = x1 - ax;
  if (!dx && r < 0) return;
  r /= dx;
  if (dx < 0) {
    if (r > t1) return;
    if (r > t0) t0 = r;
  } else if (dx > 0) {
    if (r < t0) return;
    if (r < t1) t1 = r;
  }

  r = y0 - ay;
  if (!dy && r > 0) return;
  r /= dy;
  if (dy < 0) {
    if (r < t0) return;
    if (r < t1) t1 = r;
  } else if (dy > 0) {
    if (r > t1) return;
    if (r > t0) t0 = r;
  }

  r = y1 - ay;
  if (!dy && r < 0) return;
  r /= dy;
  if (dy < 0) {
    if (r > t1) return;
    if (r > t0) t0 = r;
  } else if (dy > 0) {
    if (r < t0) return;
    if (r < t1) t1 = r;
  }

  if (t0 > 0) a[0] = ax + t0 * dx, a[1] = ay + t0 * dy;
  if (t1 < 1) b[0] = ax + t1 * dx, b[1] = ay + t1 * dy;
  return true;
}

;// ../../node_modules/d3-geo/src/clip/rectangle.js






var standalone_clipMax = 1e9, standalone_clipMin = -standalone_clipMax;

// TODO Use d3-polygon’s polygonContains here for the ring check?
// TODO Eliminate duplicate buffering in clipBuffer and polygon.push?

function standalone_clipRectangle(x0, y0, x1, y1) {

  function visible(x, y) {
    return x0 <= x && x <= x1 && y0 <= y && y <= y1;
  }

  function interpolate(from, to, direction, stream) {
    var a = 0, a1 = 0;
    if (from == null
        || (a = corner(from, direction)) !== (a1 = corner(to, direction))
        || comparePoint(from, to) < 0 ^ direction > 0) {
      do stream.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
      while ((a = (a + direction + 4) % 4) !== a1);
    } else {
      stream.point(to[0], to[1]);
    }
  }

  function corner(p, direction) {
    return standalone_math_abs(p[0] - x0) < standalone_src_math_epsilon ? direction > 0 ? 0 : 3
        : standalone_math_abs(p[0] - x1) < standalone_src_math_epsilon ? direction > 0 ? 2 : 1
        : standalone_math_abs(p[1] - y0) < standalone_src_math_epsilon ? direction > 0 ? 1 : 0
        : direction > 0 ? 3 : 2; // abs(p[1] - y1) < epsilon
  }

  function compareIntersection(a, b) {
    return comparePoint(a.x, b.x);
  }

  function comparePoint(a, b) {
    var ca = corner(a, 1),
        cb = corner(b, 1);
    return ca !== cb ? ca - cb
        : ca === 0 ? b[1] - a[1]
        : ca === 1 ? a[0] - b[0]
        : ca === 2 ? a[1] - b[1]
        : b[0] - a[0];
  }

  return function(stream) {
    var activeStream = stream,
        bufferStream = standalone_buffer(),
        segments,
        polygon,
        ring,
        x__, y__, v__, // first point
        x_, y_, v_, // previous point
        first,
        clean;

    var clipStream = {
      point: point,
      lineStart: lineStart,
      lineEnd: lineEnd,
      polygonStart: polygonStart,
      polygonEnd: polygonEnd
    };

    function point(x, y) {
      if (visible(x, y)) activeStream.point(x, y);
    }

    function polygonInside() {
      var winding = 0;

      for (var i = 0, n = polygon.length; i < n; ++i) {
        for (var ring = polygon[i], j = 1, m = ring.length, point = ring[0], a0, a1, b0 = point[0], b1 = point[1]; j < m; ++j) {
          a0 = b0, a1 = b1, point = ring[j], b0 = point[0], b1 = point[1];
          if (a1 <= y1) { if (b1 > y1 && (b0 - a0) * (y1 - a1) > (b1 - a1) * (x0 - a0)) ++winding; }
          else { if (b1 <= y1 && (b0 - a0) * (y1 - a1) < (b1 - a1) * (x0 - a0)) --winding; }
        }
      }

      return winding;
    }

    // Buffer geometry within a polygon and then clip it en masse.
    function polygonStart() {
      activeStream = bufferStream, segments = [], polygon = [], clean = true;
    }

    function polygonEnd() {
      var startInside = polygonInside(),
          cleanInside = clean && startInside,
          visible = (segments = standalone_merge_merge(segments)).length;
      if (cleanInside || visible) {
        stream.polygonStart();
        if (cleanInside) {
          stream.lineStart();
          interpolate(null, null, 1, stream);
          stream.lineEnd();
        }
        if (visible) {
          standalone_rejoin(segments, compareIntersection, startInside, interpolate, stream);
        }
        stream.polygonEnd();
      }
      activeStream = stream, segments = polygon = ring = null;
    }

    function lineStart() {
      clipStream.point = linePoint;
      if (polygon) polygon.push(ring = []);
      first = true;
      v_ = false;
      x_ = y_ = NaN;
    }

    // TODO rather than special-case polygons, simply handle them separately.
    // Ideally, coincident intersection points should be jittered to avoid
    // clipping issues.
    function lineEnd() {
      if (segments) {
        linePoint(x__, y__);
        if (v__ && v_) bufferStream.rejoin();
        segments.push(bufferStream.result());
      }
      clipStream.point = point;
      if (v_) activeStream.lineEnd();
    }

    function linePoint(x, y) {
      var v = visible(x, y);
      if (polygon) ring.push([x, y]);
      if (first) {
        x__ = x, y__ = y, v__ = v;
        first = false;
        if (v) {
          activeStream.lineStart();
          activeStream.point(x, y);
        }
      } else {
        if (v && v_) activeStream.point(x, y);
        else {
          var a = [x_ = Math.max(standalone_clipMin, Math.min(standalone_clipMax, x_)), y_ = Math.max(standalone_clipMin, Math.min(standalone_clipMax, y_))],
              b = [x = Math.max(standalone_clipMin, Math.min(standalone_clipMax, x)), y = Math.max(standalone_clipMin, Math.min(standalone_clipMax, y))];
          if (standalone_clip_line(a, b, x0, y0, x1, y1)) {
            if (!v_) {
              activeStream.lineStart();
              activeStream.point(a[0], a[1]);
            }
            activeStream.point(b[0], b[1]);
            if (!v) activeStream.lineEnd();
            clean = false;
          } else if (v) {
            activeStream.lineStart();
            activeStream.point(x, y);
            clean = false;
          }
        }
      }
      x_ = x, y_ = y, v_ = v;
    }

    return clipStream;
  };
}

;// ../../node_modules/d3-geo/src/compose.js
/* harmony default export */ function standalone_compose(a, b) {

  function compose(x, y) {
    return x = a(x, y), b(x[0], x[1]);
  }

  if (a.invert && b.invert) compose.invert = function(x, y) {
    return x = b.invert(x, y), x && a.invert(x[0], x[1]);
  };

  return compose;
}

;// ../../node_modules/d3-geo/src/rotation.js



function standalone_rotationIdentity(lambda, phi) {
  if (standalone_math_abs(lambda) > standalone_math_pi) lambda -= Math.round(lambda / standalone_math_tau) * standalone_math_tau;
  return [lambda, phi];
}

standalone_rotationIdentity.invert = standalone_rotationIdentity;

function standalone_rotation_rotateRadians(deltaLambda, deltaPhi, deltaGamma) {
  return (deltaLambda %= standalone_math_tau) ? (deltaPhi || deltaGamma ? standalone_compose(standalone_rotationLambda(deltaLambda), standalone_rotationPhiGamma(deltaPhi, deltaGamma))
    : standalone_rotationLambda(deltaLambda))
    : (deltaPhi || deltaGamma ? standalone_rotationPhiGamma(deltaPhi, deltaGamma)
    : standalone_rotationIdentity);
}

function standalone_forwardRotationLambda(deltaLambda) {
  return function(lambda, phi) {
    lambda += deltaLambda;
    if (standalone_math_abs(lambda) > standalone_math_pi) lambda -= Math.round(lambda / standalone_math_tau) * standalone_math_tau;
    return [lambda, phi];
  };
}

function standalone_rotationLambda(deltaLambda) {
  var rotation = standalone_forwardRotationLambda(deltaLambda);
  rotation.invert = standalone_forwardRotationLambda(-deltaLambda);
  return rotation;
}

function standalone_rotationPhiGamma(deltaPhi, deltaGamma) {
  var cosDeltaPhi = standalone_math_cos(deltaPhi),
      sinDeltaPhi = standalone_math_sin(deltaPhi),
      cosDeltaGamma = standalone_math_cos(deltaGamma),
      sinDeltaGamma = standalone_math_sin(deltaGamma);

  function rotation(lambda, phi) {
    var cosPhi = standalone_math_cos(phi),
        x = standalone_math_cos(lambda) * cosPhi,
        y = standalone_math_sin(lambda) * cosPhi,
        z = standalone_math_sin(phi),
        k = z * cosDeltaPhi + x * sinDeltaPhi;
    return [
      standalone_math_atan2(y * cosDeltaGamma - k * sinDeltaGamma, x * cosDeltaPhi - z * sinDeltaPhi),
      standalone_math_asin(k * cosDeltaGamma + y * sinDeltaGamma)
    ];
  }

  rotation.invert = function(lambda, phi) {
    var cosPhi = standalone_math_cos(phi),
        x = standalone_math_cos(lambda) * cosPhi,
        y = standalone_math_sin(lambda) * cosPhi,
        z = standalone_math_sin(phi),
        k = z * cosDeltaGamma - y * sinDeltaGamma;
    return [
      standalone_math_atan2(y * cosDeltaGamma + z * sinDeltaGamma, x * cosDeltaPhi + k * sinDeltaPhi),
      standalone_math_asin(k * cosDeltaPhi - x * sinDeltaPhi)
    ];
  };

  return rotation;
}

/* harmony default export */ function standalone_rotation(rotate) {
  rotate = standalone_rotation_rotateRadians(rotate[0] * standalone_src_math_radians, rotate[1] * standalone_src_math_radians, rotate.length > 2 ? rotate[2] * standalone_src_math_radians : 0);

  function forward(coordinates) {
    coordinates = rotate(coordinates[0] * standalone_src_math_radians, coordinates[1] * standalone_src_math_radians);
    return coordinates[0] *= standalone_src_math_degrees, coordinates[1] *= standalone_src_math_degrees, coordinates;
  }

  forward.invert = function(coordinates) {
    coordinates = rotate.invert(coordinates[0] * standalone_src_math_radians, coordinates[1] * standalone_src_math_radians);
    return coordinates[0] *= standalone_src_math_degrees, coordinates[1] *= standalone_src_math_degrees, coordinates;
  };

  return forward;
}

;// ../../node_modules/d3-geo/src/transform.js
/* harmony default export */ function standalone_src_transform(methods) {
  return {
    stream: standalone_transform_transformer(methods)
  };
}

function standalone_transform_transformer(methods) {
  return function(stream) {
    var s = new standalone_TransformStream;
    for (var key in methods) s[key] = methods[key];
    s.stream = stream;
    return s;
  };
}

function standalone_TransformStream() {}

standalone_TransformStream.prototype = {
  constructor: standalone_TransformStream,
  point: function(x, y) { this.stream.point(x, y); },
  sphere: function() { this.stream.sphere(); },
  lineStart: function() { this.stream.lineStart(); },
  lineEnd: function() { this.stream.lineEnd(); },
  polygonStart: function() { this.stream.polygonStart(); },
  polygonEnd: function() { this.stream.polygonEnd(); }
};

;// ../../node_modules/d3-geo/src/projection/fit.js



function standalone_fit(projection, fitBounds, object) {
  var clip = projection.clipExtent && projection.clipExtent();
  projection.scale(150).translate([0, 0]);
  if (clip != null) projection.clipExtent(null);
  standalone_src_stream(object, projection.stream(standalone_path_bounds));
  fitBounds(standalone_path_bounds.result());
  if (clip != null) projection.clipExtent(clip);
  return projection;
}

function standalone_fitExtent(projection, extent, object) {
  return standalone_fit(projection, function(b) {
    var w = extent[1][0] - extent[0][0],
        h = extent[1][1] - extent[0][1],
        k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1])),
        x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2,
        y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;
    projection.scale(150 * k).translate([x, y]);
  }, object);
}

function standalone_fitSize(projection, size, object) {
  return standalone_fitExtent(projection, [[0, 0], size], object);
}

function standalone_fitWidth(projection, width, object) {
  return standalone_fit(projection, function(b) {
    var w = +width,
        k = w / (b[1][0] - b[0][0]),
        x = (w - k * (b[1][0] + b[0][0])) / 2,
        y = -k * b[0][1];
    projection.scale(150 * k).translate([x, y]);
  }, object);
}

function standalone_fitHeight(projection, height, object) {
  return standalone_fit(projection, function(b) {
    var h = +height,
        k = h / (b[1][1] - b[0][1]),
        x = -k * b[0][0],
        y = (h - k * (b[1][1] + b[0][1])) / 2;
    projection.scale(150 * k).translate([x, y]);
  }, object);
}

;// ../../node_modules/d3-geo/src/projection/resample.js




var standalone_maxDepth = 16, // maximum depth of subdivision
    standalone_cosMinDistance = standalone_math_cos(30 * standalone_src_math_radians); // cos(minimum angular distance)

/* harmony default export */ function standalone_resample(project, delta2) {
  return +delta2 ? standalone_resample_resample(project, delta2) : standalone_resampleNone(project);
}

function standalone_resampleNone(project) {
  return standalone_transform_transformer({
    point: function(x, y) {
      x = project(x, y);
      this.stream.point(x[0], x[1]);
    }
  });
}

function standalone_resample_resample(project, delta2) {

  function resampleLineTo(x0, y0, lambda0, a0, b0, c0, x1, y1, lambda1, a1, b1, c1, depth, stream) {
    var dx = x1 - x0,
        dy = y1 - y0,
        d2 = dx * dx + dy * dy;
    if (d2 > 4 * delta2 && depth--) {
      var a = a0 + a1,
          b = b0 + b1,
          c = c0 + c1,
          m = standalone_math_sqrt(a * a + b * b + c * c),
          phi2 = standalone_math_asin(c /= m),
          lambda2 = standalone_math_abs(standalone_math_abs(c) - 1) < standalone_src_math_epsilon || standalone_math_abs(lambda0 - lambda1) < standalone_src_math_epsilon ? (lambda0 + lambda1) / 2 : standalone_math_atan2(b, a),
          p = project(lambda2, phi2),
          x2 = p[0],
          y2 = p[1],
          dx2 = x2 - x0,
          dy2 = y2 - y0,
          dz = dy * dx2 - dx * dy2;
      if (dz * dz / d2 > delta2 // perpendicular projected distance
          || standalone_math_abs((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 // midpoint close to an end
          || a0 * a1 + b0 * b1 + c0 * c1 < standalone_cosMinDistance) { // angular distance
        resampleLineTo(x0, y0, lambda0, a0, b0, c0, x2, y2, lambda2, a /= m, b /= m, c, depth, stream);
        stream.point(x2, y2);
        resampleLineTo(x2, y2, lambda2, a, b, c, x1, y1, lambda1, a1, b1, c1, depth, stream);
      }
    }
  }
  return function(stream) {
    var lambda00, x00, y00, a00, b00, c00, // first point
        lambda0, x0, y0, a0, b0, c0; // previous point

    var resampleStream = {
      point: point,
      lineStart: lineStart,
      lineEnd: lineEnd,
      polygonStart: function() { stream.polygonStart(); resampleStream.lineStart = ringStart; },
      polygonEnd: function() { stream.polygonEnd(); resampleStream.lineStart = lineStart; }
    };

    function point(x, y) {
      x = project(x, y);
      stream.point(x[0], x[1]);
    }

    function lineStart() {
      x0 = NaN;
      resampleStream.point = linePoint;
      stream.lineStart();
    }

    function linePoint(lambda, phi) {
      var c = standalone_cartesian_cartesian([lambda, phi]), p = project(lambda, phi);
      resampleLineTo(x0, y0, lambda0, a0, b0, c0, x0 = p[0], y0 = p[1], lambda0 = lambda, a0 = c[0], b0 = c[1], c0 = c[2], standalone_maxDepth, stream);
      stream.point(x0, y0);
    }

    function lineEnd() {
      resampleStream.point = point;
      stream.lineEnd();
    }

    function ringStart() {
      lineStart();
      resampleStream.point = ringPoint;
      resampleStream.lineEnd = ringEnd;
    }

    function ringPoint(lambda, phi) {
      linePoint(lambda00 = lambda, phi), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
      resampleStream.point = linePoint;
    }

    function ringEnd() {
      resampleLineTo(x0, y0, lambda0, a0, b0, c0, x00, y00, lambda00, a00, b00, c00, standalone_maxDepth, stream);
      resampleStream.lineEnd = lineEnd;
      lineEnd();
    }

    return resampleStream;
  };
}

;// ../../node_modules/d3-geo/src/projection/index.js











var standalone_transformRadians = standalone_transform_transformer({
  point: function(x, y) {
    this.stream.point(x * standalone_src_math_radians, y * standalone_src_math_radians);
  }
});

function standalone_transformRotate(rotate) {
  return standalone_transform_transformer({
    point: function(x, y) {
      var r = rotate(x, y);
      return this.stream.point(r[0], r[1]);
    }
  });
}

function standalone_scaleTranslate(k, dx, dy, sx, sy) {
  function transform(x, y) {
    x *= sx; y *= sy;
    return [dx + k * x, dy - k * y];
  }
  transform.invert = function(x, y) {
    return [(x - dx) / k * sx, (dy - y) / k * sy];
  };
  return transform;
}

function standalone_scaleTranslateRotate(k, dx, dy, sx, sy, alpha) {
  if (!alpha) return standalone_scaleTranslate(k, dx, dy, sx, sy);
  var cosAlpha = standalone_math_cos(alpha),
      sinAlpha = standalone_math_sin(alpha),
      a = cosAlpha * k,
      b = sinAlpha * k,
      ai = cosAlpha / k,
      bi = sinAlpha / k,
      ci = (sinAlpha * dy - cosAlpha * dx) / k,
      fi = (sinAlpha * dx + cosAlpha * dy) / k;
  function transform(x, y) {
    x *= sx; y *= sy;
    return [a * x - b * y + dx, dy - b * x - a * y];
  }
  transform.invert = function(x, y) {
    return [sx * (ai * x - bi * y + ci), sy * (fi - bi * x - ai * y)];
  };
  return transform;
}

function standalone_projection(project) {
  return standalone_projectionMutator(function() { return project; })();
}

function standalone_projectionMutator(projectAt) {
  var project,
      k = 150, // scale
      x = 480, y = 250, // translate
      lambda = 0, phi = 0, // center
      deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, rotate, // pre-rotate
      alpha = 0, // post-rotate angle
      sx = 1, // reflectX
      sy = 1, // reflectX
      theta = null, preclip = standalone_antimeridian, // pre-clip angle
      x0 = null, y0, x1, y1, postclip = standalone_d3_geo_src_identity, // post-clip extent
      delta2 = 0.5, // precision
      projectResample,
      projectTransform,
      projectRotateTransform,
      cache,
      cacheStream;

  function projection(point) {
    return projectRotateTransform(point[0] * standalone_src_math_radians, point[1] * standalone_src_math_radians);
  }

  function invert(point) {
    point = projectRotateTransform.invert(point[0], point[1]);
    return point && [point[0] * standalone_src_math_degrees, point[1] * standalone_src_math_degrees];
  }

  projection.stream = function(stream) {
    return cache && cacheStream === stream ? cache : cache = standalone_transformRadians(standalone_transformRotate(rotate)(preclip(projectResample(postclip(cacheStream = stream)))));
  };

  projection.preclip = function(_) {
    return arguments.length ? (preclip = _, theta = undefined, reset()) : preclip;
  };

  projection.postclip = function(_) {
    return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;
  };

  projection.clipAngle = function(_) {
    return arguments.length ? (preclip = +_ ? standalone_clip_circle(theta = _ * standalone_src_math_radians) : (theta = null, standalone_antimeridian), reset()) : theta * standalone_src_math_degrees;
  };

  projection.clipExtent = function(_) {
    return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, standalone_d3_geo_src_identity) : standalone_clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];
  };

  projection.scale = function(_) {
    return arguments.length ? (k = +_, recenter()) : k;
  };

  projection.translate = function(_) {
    return arguments.length ? (x = +_[0], y = +_[1], recenter()) : [x, y];
  };

  projection.center = function(_) {
    return arguments.length ? (lambda = _[0] % 360 * standalone_src_math_radians, phi = _[1] % 360 * standalone_src_math_radians, recenter()) : [lambda * standalone_src_math_degrees, phi * standalone_src_math_degrees];
  };

  projection.rotate = function(_) {
    return arguments.length ? (deltaLambda = _[0] % 360 * standalone_src_math_radians, deltaPhi = _[1] % 360 * standalone_src_math_radians, deltaGamma = _.length > 2 ? _[2] % 360 * standalone_src_math_radians : 0, recenter()) : [deltaLambda * standalone_src_math_degrees, deltaPhi * standalone_src_math_degrees, deltaGamma * standalone_src_math_degrees];
  };

  projection.angle = function(_) {
    return arguments.length ? (alpha = _ % 360 * standalone_src_math_radians, recenter()) : alpha * standalone_src_math_degrees;
  };

  projection.reflectX = function(_) {
    return arguments.length ? (sx = _ ? -1 : 1, recenter()) : sx < 0;
  };

  projection.reflectY = function(_) {
    return arguments.length ? (sy = _ ? -1 : 1, recenter()) : sy < 0;
  };

  projection.precision = function(_) {
    return arguments.length ? (projectResample = standalone_resample(projectTransform, delta2 = _ * _), reset()) : standalone_math_sqrt(delta2);
  };

  projection.fitExtent = function(extent, object) {
    return standalone_fitExtent(projection, extent, object);
  };

  projection.fitSize = function(size, object) {
    return standalone_fitSize(projection, size, object);
  };

  projection.fitWidth = function(width, object) {
    return standalone_fitWidth(projection, width, object);
  };

  projection.fitHeight = function(height, object) {
    return standalone_fitHeight(projection, height, object);
  };

  function recenter() {
    var center = standalone_scaleTranslateRotate(k, 0, 0, sx, sy, alpha).apply(null, project(lambda, phi)),
        transform = standalone_scaleTranslateRotate(k, x - center[0], y - center[1], sx, sy, alpha);
    rotate = standalone_rotation_rotateRadians(deltaLambda, deltaPhi, deltaGamma);
    projectTransform = standalone_compose(project, transform);
    projectRotateTransform = standalone_compose(rotate, projectTransform);
    projectResample = standalone_resample(projectTransform, delta2);
    return reset();
  }

  function reset() {
    cache = cacheStream = null;
    return projection;
  }

  return function() {
    project = projectAt.apply(this, arguments);
    projection.invert = project.invert && invert;
    return recenter();
  };
}

;// ../../node_modules/d3-geo/src/projection/conic.js



function standalone_conicProjection(projectAt) {
  var phi0 = 0,
      phi1 = standalone_math_pi / 3,
      m = standalone_projectionMutator(projectAt),
      p = m(phi0, phi1);

  p.parallels = function(_) {
    return arguments.length ? m(phi0 = _[0] * standalone_src_math_radians, phi1 = _[1] * standalone_src_math_radians) : [phi0 * standalone_src_math_degrees, phi1 * standalone_src_math_degrees];
  };

  return p;
}

;// ../../node_modules/d3-geo/src/projection/cylindricalEqualArea.js


function standalone_cylindricalEqualAreaRaw(phi0) {
  var cosPhi0 = standalone_math_cos(phi0);

  function forward(lambda, phi) {
    return [lambda * cosPhi0, standalone_math_sin(phi) / cosPhi0];
  }

  forward.invert = function(x, y) {
    return [x / cosPhi0, standalone_math_asin(y * cosPhi0)];
  };

  return forward;
}

;// ../../node_modules/d3-geo/src/projection/conicEqualArea.js




function standalone_conicEqualAreaRaw(y0, y1) {
  var sy0 = standalone_math_sin(y0), n = (sy0 + standalone_math_sin(y1)) / 2;

  // Are the parallels symmetrical around the Equator?
  if (standalone_math_abs(n) < standalone_src_math_epsilon) return standalone_cylindricalEqualAreaRaw(y0);

  var c = 1 + sy0 * (2 * n - sy0), r0 = standalone_math_sqrt(c) / n;

  function project(x, y) {
    var r = standalone_math_sqrt(c - 2 * n * standalone_math_sin(y)) / n;
    return [r * standalone_math_sin(x *= n), r0 - r * standalone_math_cos(x)];
  }

  project.invert = function(x, y) {
    var r0y = r0 - y,
        l = standalone_math_atan2(x, standalone_math_abs(r0y)) * standalone_math_sign(r0y);
    if (r0y * n < 0)
      l -= standalone_math_pi * standalone_math_sign(x) * standalone_math_sign(r0y);
    return [l / n, standalone_math_asin((c - (x * x + r0y * r0y) * n * n) / (2 * n))];
  };

  return project;
}

/* harmony default export */ function standalone_conicEqualArea() {
  return standalone_conicProjection(standalone_conicEqualAreaRaw)
      .scale(155.424)
      .center([0, 33.6442]);
}

;// ../../node_modules/d3-geo/src/projection/albers.js


/* harmony default export */ function standalone_albers() {
  return standalone_conicEqualArea()
      .parallels([29.5, 45.5])
      .scale(1070)
      .translate([480, 250])
      .rotate([96, 0])
      .center([-0.6, 38.7]);
}

;// ../../node_modules/d3-geo/src/projection/albersUsa.js





// The projections must have mutually exclusive clip regions on the sphere,
// as this will avoid emitting interleaving lines and polygons.
function standalone_multiplex(streams) {
  var n = streams.length;
  return {
    point: function(x, y) { var i = -1; while (++i < n) streams[i].point(x, y); },
    sphere: function() { var i = -1; while (++i < n) streams[i].sphere(); },
    lineStart: function() { var i = -1; while (++i < n) streams[i].lineStart(); },
    lineEnd: function() { var i = -1; while (++i < n) streams[i].lineEnd(); },
    polygonStart: function() { var i = -1; while (++i < n) streams[i].polygonStart(); },
    polygonEnd: function() { var i = -1; while (++i < n) streams[i].polygonEnd(); }
  };
}

// A composite projection for the United States, configured by default for
// 960×500. The projection also works quite well at 960×600 if you change the
// scale to 1285 and adjust the translate accordingly. The set of standard
// parallels for each region comes from USGS, which is published here:
// http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers
/* harmony default export */ function standalone_albersUsa() {
  var cache,
      cacheStream,
      lower48 = standalone_albers(), lower48Point,
      alaska = standalone_conicEqualArea().rotate([154, 0]).center([-2, 58.5]).parallels([55, 65]), alaskaPoint, // EPSG:3338
      hawaii = standalone_conicEqualArea().rotate([157, 0]).center([-3, 19.9]).parallels([8, 18]), hawaiiPoint, // ESRI:102007
      point, pointStream = {point: function(x, y) { point = [x, y]; }};

  function albersUsa(coordinates) {
    var x = coordinates[0], y = coordinates[1];
    return point = null,
        (lower48Point.point(x, y), point)
        || (alaskaPoint.point(x, y), point)
        || (hawaiiPoint.point(x, y), point);
  }

  albersUsa.invert = function(coordinates) {
    var k = lower48.scale(),
        t = lower48.translate(),
        x = (coordinates[0] - t[0]) / k,
        y = (coordinates[1] - t[1]) / k;
    return (y >= 0.120 && y < 0.234 && x >= -0.425 && x < -0.214 ? alaska
        : y >= 0.166 && y < 0.234 && x >= -0.214 && x < -0.115 ? hawaii
        : lower48).invert(coordinates);
  };

  albersUsa.stream = function(stream) {
    return cache && cacheStream === stream ? cache : cache = standalone_multiplex([lower48.stream(cacheStream = stream), alaska.stream(stream), hawaii.stream(stream)]);
  };

  albersUsa.precision = function(_) {
    if (!arguments.length) return lower48.precision();
    lower48.precision(_), alaska.precision(_), hawaii.precision(_);
    return reset();
  };

  albersUsa.scale = function(_) {
    if (!arguments.length) return lower48.scale();
    lower48.scale(_), alaska.scale(_ * 0.35), hawaii.scale(_);
    return albersUsa.translate(lower48.translate());
  };

  albersUsa.translate = function(_) {
    if (!arguments.length) return lower48.translate();
    var k = lower48.scale(), x = +_[0], y = +_[1];

    lower48Point = lower48
        .translate(_)
        .clipExtent([[x - 0.455 * k, y - 0.238 * k], [x + 0.455 * k, y + 0.238 * k]])
        .stream(pointStream);

    alaskaPoint = alaska
        .translate([x - 0.307 * k, y + 0.201 * k])
        .clipExtent([[x - 0.425 * k + standalone_src_math_epsilon, y + 0.120 * k + standalone_src_math_epsilon], [x - 0.214 * k - standalone_src_math_epsilon, y + 0.234 * k - standalone_src_math_epsilon]])
        .stream(pointStream);

    hawaiiPoint = hawaii
        .translate([x - 0.205 * k, y + 0.212 * k])
        .clipExtent([[x - 0.214 * k + standalone_src_math_epsilon, y + 0.166 * k + standalone_src_math_epsilon], [x - 0.115 * k - standalone_src_math_epsilon, y + 0.234 * k - standalone_src_math_epsilon]])
        .stream(pointStream);

    return reset();
  };

  albersUsa.fitExtent = function(extent, object) {
    return standalone_fitExtent(albersUsa, extent, object);
  };

  albersUsa.fitSize = function(size, object) {
    return standalone_fitSize(albersUsa, size, object);
  };

  albersUsa.fitWidth = function(width, object) {
    return standalone_fitWidth(albersUsa, width, object);
  };

  albersUsa.fitHeight = function(height, object) {
    return standalone_fitHeight(albersUsa, height, object);
  };

  function reset() {
    cache = cacheStream = null;
    return albersUsa;
  }

  return albersUsa.scale(1070);
}

;// ../../node_modules/d3-geo/src/projection/azimuthal.js


function standalone_azimuthalRaw(scale) {
  return function(x, y) {
    var cx = standalone_math_cos(x),
        cy = standalone_math_cos(y),
        k = scale(cx * cy);
        if (k === Infinity) return [2, 0];
    return [
      k * cy * standalone_math_sin(x),
      k * standalone_math_sin(y)
    ];
  }
}

function standalone_azimuthalInvert(angle) {
  return function(x, y) {
    var z = standalone_math_sqrt(x * x + y * y),
        c = angle(z),
        sc = standalone_math_sin(c),
        cc = standalone_math_cos(c);
    return [
      standalone_math_atan2(x * sc, z * cc),
      standalone_math_asin(z && y * sc / z)
    ];
  }
}

;// ../../node_modules/d3-geo/src/projection/azimuthalEqualArea.js




var standalone_azimuthalEqualAreaRaw = standalone_azimuthalRaw(function(cxcy) {
  return standalone_math_sqrt(2 / (1 + cxcy));
});

standalone_azimuthalEqualAreaRaw.invert = standalone_azimuthalInvert(function(z) {
  return 2 * standalone_math_asin(z / 2);
});

/* harmony default export */ function standalone_azimuthalEqualArea() {
  return standalone_projection(standalone_azimuthalEqualAreaRaw)
      .scale(124.75)
      .clipAngle(180 - 1e-3);
}

;// ../../node_modules/d3-geo/src/projection/azimuthalEquidistant.js




var standalone_azimuthalEquidistantRaw = standalone_azimuthalRaw(function(c) {
  return (c = standalone_math_acos(c)) && c / standalone_math_sin(c);
});

standalone_azimuthalEquidistantRaw.invert = standalone_azimuthalInvert(function(z) {
  return z;
});

/* harmony default export */ function standalone_azimuthalEquidistant() {
  return standalone_projection(standalone_azimuthalEquidistantRaw)
      .scale(79.4188)
      .clipAngle(180 - 1e-3);
}

;// ../../node_modules/d3-geo/src/projection/mercator.js




function standalone_mercatorRaw(lambda, phi) {
  return [lambda, standalone_math_log(standalone_tan((standalone_math_halfPi + phi) / 2))];
}

standalone_mercatorRaw.invert = function(x, y) {
  return [x, 2 * standalone_atan(standalone_math_exp(y)) - standalone_math_halfPi];
};

/* harmony default export */ function standalone_mercator() {
  return standalone_mercatorProjection(standalone_mercatorRaw)
      .scale(961 / standalone_math_tau);
}

function standalone_mercatorProjection(project) {
  var m = standalone_projection(project),
      center = m.center,
      scale = m.scale,
      translate = m.translate,
      clipExtent = m.clipExtent,
      x0 = null, y0, x1, y1; // clip extent

  m.scale = function(_) {
    return arguments.length ? (scale(_), reclip()) : scale();
  };

  m.translate = function(_) {
    return arguments.length ? (translate(_), reclip()) : translate();
  };

  m.center = function(_) {
    return arguments.length ? (center(_), reclip()) : center();
  };

  m.clipExtent = function(_) {
    return arguments.length ? ((_ == null ? x0 = y0 = x1 = y1 = null : (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1])), reclip()) : x0 == null ? null : [[x0, y0], [x1, y1]];
  };

  function reclip() {
    var k = standalone_math_pi * scale(),
        t = m(standalone_rotation(m.rotate()).invert([0, 0]));
    return clipExtent(x0 == null
        ? [[t[0] - k, t[1] - k], [t[0] + k, t[1] + k]] : project === standalone_mercatorRaw
        ? [[Math.max(t[0] - k, x0), y0], [Math.min(t[0] + k, x1), y1]]
        : [[x0, Math.max(t[1] - k, y0)], [x1, Math.min(t[1] + k, y1)]]);
  }

  return reclip();
}

;// ../../node_modules/d3-geo/src/projection/conicConformal.js




function standalone_tany(y) {
  return standalone_tan((standalone_math_halfPi + y) / 2);
}

function standalone_conicConformalRaw(y0, y1) {
  var cy0 = standalone_math_cos(y0),
      n = y0 === y1 ? standalone_math_sin(y0) : standalone_math_log(cy0 / standalone_math_cos(y1)) / standalone_math_log(standalone_tany(y1) / standalone_tany(y0)),
      f = cy0 * standalone_math_pow(standalone_tany(y0), n) / n;

  if (!n) return standalone_mercatorRaw;

  function project(x, y) {
    if (f > 0) { if (y < -standalone_math_halfPi + standalone_src_math_epsilon) y = -standalone_math_halfPi + standalone_src_math_epsilon; }
    else { if (y > standalone_math_halfPi - standalone_src_math_epsilon) y = standalone_math_halfPi - standalone_src_math_epsilon; }
    var r = f / standalone_math_pow(standalone_tany(y), n);
    return [r * standalone_math_sin(n * x), f - r * standalone_math_cos(n * x)];
  }

  project.invert = function(x, y) {
    var fy = f - y, r = standalone_math_sign(n) * standalone_math_sqrt(x * x + fy * fy),
      l = standalone_math_atan2(x, standalone_math_abs(fy)) * standalone_math_sign(fy);
    if (fy * n < 0)
      l -= standalone_math_pi * standalone_math_sign(x) * standalone_math_sign(fy);
    return [l / n, 2 * standalone_atan(standalone_math_pow(f / r, 1 / n)) - standalone_math_halfPi];
  };

  return project;
}

/* harmony default export */ function standalone_conicConformal() {
  return standalone_conicProjection(standalone_conicConformalRaw)
      .scale(109.5)
      .parallels([30, 30]);
}

;// ../../node_modules/d3-geo/src/projection/equirectangular.js


function standalone_equirectangularRaw(lambda, phi) {
  return [lambda, phi];
}

standalone_equirectangularRaw.invert = standalone_equirectangularRaw;

/* harmony default export */ function standalone_equirectangular() {
  return standalone_projection(standalone_equirectangularRaw)
      .scale(152.63);
}

;// ../../node_modules/d3-geo/src/projection/conicEquidistant.js




function standalone_conicEquidistantRaw(y0, y1) {
  var cy0 = standalone_math_cos(y0),
      n = y0 === y1 ? standalone_math_sin(y0) : (cy0 - standalone_math_cos(y1)) / (y1 - y0),
      g = cy0 / n + y0;

  if (standalone_math_abs(n) < standalone_src_math_epsilon) return standalone_equirectangularRaw;

  function project(x, y) {
    var gy = g - y, nx = n * x;
    return [gy * standalone_math_sin(nx), g - gy * standalone_math_cos(nx)];
  }

  project.invert = function(x, y) {
    var gy = g - y,
        l = standalone_math_atan2(x, standalone_math_abs(gy)) * standalone_math_sign(gy);
    if (gy * n < 0)
      l -= standalone_math_pi * standalone_math_sign(x) * standalone_math_sign(gy);
    return [l / n, g - standalone_math_sign(n) * standalone_math_sqrt(x * x + gy * gy)];
  };

  return project;
}

/* harmony default export */ function standalone_conicEquidistant() {
  return standalone_conicProjection(standalone_conicEquidistantRaw)
      .scale(131.154)
      .center([0, 13.9389]);
}

;// ../../node_modules/d3-geo/src/projection/equalEarth.js



var standalone_A1 = 1.340264,
    standalone_A2 = -0.081106,
    standalone_A3 = 0.000893,
    standalone_A4 = 0.003796,
    standalone_M = standalone_math_sqrt(3) / 2,
    standalone_iterations = 12;

function standalone_equalEarthRaw(lambda, phi) {
  var l = standalone_math_asin(standalone_M * standalone_math_sin(phi)), l2 = l * l, l6 = l2 * l2 * l2;
  return [
    lambda * standalone_math_cos(l) / (standalone_M * (standalone_A1 + 3 * standalone_A2 * l2 + l6 * (7 * standalone_A3 + 9 * standalone_A4 * l2))),
    l * (standalone_A1 + standalone_A2 * l2 + l6 * (standalone_A3 + standalone_A4 * l2))
  ];
}

standalone_equalEarthRaw.invert = function(x, y) {
  var l = y, l2 = l * l, l6 = l2 * l2 * l2;
  for (var i = 0, delta, fy, fpy; i < standalone_iterations; ++i) {
    fy = l * (standalone_A1 + standalone_A2 * l2 + l6 * (standalone_A3 + standalone_A4 * l2)) - y;
    fpy = standalone_A1 + 3 * standalone_A2 * l2 + l6 * (7 * standalone_A3 + 9 * standalone_A4 * l2);
    l -= delta = fy / fpy, l2 = l * l, l6 = l2 * l2 * l2;
    if (standalone_math_abs(delta) < standalone_math_epsilon2) break;
  }
  return [
    standalone_M * x * (standalone_A1 + 3 * standalone_A2 * l2 + l6 * (7 * standalone_A3 + 9 * standalone_A4 * l2)) / standalone_math_cos(l),
    standalone_math_asin(standalone_math_sin(l) / standalone_M)
  ];
};

/* harmony default export */ function standalone_equalEarth() {
  return standalone_projection(standalone_equalEarthRaw)
      .scale(177.158);
}

;// ../../node_modules/d3-geo/src/projection/gnomonic.js




function standalone_gnomonicRaw(x, y) {
  var cy = standalone_math_cos(y), k = standalone_math_cos(x) * cy;
  return [cy * standalone_math_sin(x) / k, standalone_math_sin(y) / k];
}

standalone_gnomonicRaw.invert = standalone_azimuthalInvert(standalone_atan);

/* harmony default export */ function standalone_gnomonic() {
  return standalone_projection(standalone_gnomonicRaw)
      .scale(144.049)
      .clipAngle(60);
}

;// ../../node_modules/d3-geo/src/projection/identity.js






/* harmony default export */ function standalone_projection_identity() {
  var k = 1, tx = 0, ty = 0, sx = 1, sy = 1, // scale, translate and reflect
      alpha = 0, ca, sa, // angle
      x0 = null, y0, x1, y1, // clip extent
      kx = 1, ky = 1,
      transform = standalone_transform_transformer({
        point: function(x, y) {
          var p = projection([x, y])
          this.stream.point(p[0], p[1]);
        }
      }),
      postclip = standalone_d3_geo_src_identity,
      cache,
      cacheStream;

  function reset() {
    kx = k * sx;
    ky = k * sy;
    cache = cacheStream = null;
    return projection;
  }

  function projection (p) {
    var x = p[0] * kx, y = p[1] * ky;
    if (alpha) {
      var t = y * ca - x * sa;
      x = x * ca + y * sa;
      y = t;
    }    
    return [x + tx, y + ty];
  }
  projection.invert = function(p) {
    var x = p[0] - tx, y = p[1] - ty;
    if (alpha) {
      var t = y * ca + x * sa;
      x = x * ca - y * sa;
      y = t;
    }
    return [x / kx, y / ky];
  };
  projection.stream = function(stream) {
    return cache && cacheStream === stream ? cache : cache = transform(postclip(cacheStream = stream));
  };
  projection.postclip = function(_) {
    return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;
  };
  projection.clipExtent = function(_) {
    return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, standalone_d3_geo_src_identity) : standalone_clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];
  };
  projection.scale = function(_) {
    return arguments.length ? (k = +_, reset()) : k;
  };
  projection.translate = function(_) {
    return arguments.length ? (tx = +_[0], ty = +_[1], reset()) : [tx, ty];
  }
  projection.angle = function(_) {
    return arguments.length ? (alpha = _ % 360 * standalone_src_math_radians, sa = standalone_math_sin(alpha), ca = standalone_math_cos(alpha), reset()) : alpha * standalone_src_math_degrees;
  };
  projection.reflectX = function(_) {
    return arguments.length ? (sx = _ ? -1 : 1, reset()) : sx < 0;
  };
  projection.reflectY = function(_) {
    return arguments.length ? (sy = _ ? -1 : 1, reset()) : sy < 0;
  };
  projection.fitExtent = function(extent, object) {
    return standalone_fitExtent(projection, extent, object);
  };
  projection.fitSize = function(size, object) {
    return standalone_fitSize(projection, size, object);
  };
  projection.fitWidth = function(width, object) {
    return standalone_fitWidth(projection, width, object);
  };
  projection.fitHeight = function(height, object) {
    return standalone_fitHeight(projection, height, object);
  };

  return projection;
}

;// ../../node_modules/d3-geo/src/projection/naturalEarth1.js



function standalone_naturalEarth1Raw(lambda, phi) {
  var phi2 = phi * phi, phi4 = phi2 * phi2;
  return [
    lambda * (0.8707 - 0.131979 * phi2 + phi4 * (-0.013791 + phi4 * (0.003971 * phi2 - 0.001529 * phi4))),
    phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4)))
  ];
}

standalone_naturalEarth1Raw.invert = function(x, y) {
  var phi = y, i = 25, delta;
  do {
    var phi2 = phi * phi, phi4 = phi2 * phi2;
    phi -= delta = (phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4))) - y) /
        (1.007226 + phi2 * (0.015085 * 3 + phi4 * (-0.044475 * 7 + 0.028874 * 9 * phi2 - 0.005916 * 11 * phi4)));
  } while (standalone_math_abs(delta) > standalone_src_math_epsilon && --i > 0);
  return [
    x / (0.8707 + (phi2 = phi * phi) * (-0.131979 + phi2 * (-0.013791 + phi2 * phi2 * phi2 * (0.003971 - 0.001529 * phi2)))),
    phi
  ];
};

/* harmony default export */ function standalone_naturalEarth1() {
  return standalone_projection(standalone_naturalEarth1Raw)
      .scale(175.295);
}

;// ../../node_modules/d3-geo/src/projection/orthographic.js




function standalone_orthographicRaw(x, y) {
  return [standalone_math_cos(y) * standalone_math_sin(x), standalone_math_sin(y)];
}

standalone_orthographicRaw.invert = standalone_azimuthalInvert(standalone_math_asin);

/* harmony default export */ function standalone_orthographic() {
  return standalone_projection(standalone_orthographicRaw)
      .scale(249.5)
      .clipAngle(90 + standalone_src_math_epsilon);
}

;// ../../node_modules/d3-geo/src/projection/stereographic.js




function standalone_stereographicRaw(x, y) {
  var cy = standalone_math_cos(y), k = 1 + standalone_math_cos(x) * cy;
  return [cy * standalone_math_sin(x) / k, standalone_math_sin(y) / k];
}

standalone_stereographicRaw.invert = standalone_azimuthalInvert(function(z) {
  return 2 * standalone_atan(z);
});

/* harmony default export */ function standalone_stereographic() {
  return standalone_projection(standalone_stereographicRaw)
      .scale(250)
      .clipAngle(142);
}

;// ../../node_modules/d3-geo/src/projection/transverseMercator.js



function standalone_transverseMercatorRaw(lambda, phi) {
  return [standalone_math_log(standalone_tan((standalone_math_halfPi + phi) / 2)), -lambda];
}

standalone_transverseMercatorRaw.invert = function(x, y) {
  return [-y, 2 * standalone_atan(standalone_math_exp(x)) - standalone_math_halfPi];
};

/* harmony default export */ function standalone_transverseMercator() {
  var m = standalone_mercatorProjection(standalone_transverseMercatorRaw),
      center = m.center,
      rotate = m.rotate;

  m.center = function(_) {
    return arguments.length ? center([-_[1], _[0]]) : (_ = center(), [_[1], -_[0]]);
  };

  m.rotate = function(_) {
    return arguments.length ? rotate([_[0], _[1], _.length > 2 ? _[2] + 90 : 90]) : (_ = rotate(), [_[0], _[1], _[2] - 90]);
  };

  return rotate([0, 0, 90])
      .scale(159.155);
}

;// ../../node_modules/d3-geo-projection/src/math.js
var standalone_src_math_abs = Math.abs;
var standalone_math_atan = Math.atan;
var standalone_src_math_atan2 = Math.atan2;
var standalone_math_ceil = Math.ceil;
var standalone_src_math_cos = Math.cos;
var standalone_src_math_exp = Math.exp;
var standalone_src_math_floor = Math.floor;
var standalone_src_math_log = Math.log;
var standalone_src_math_max = Math.max;
var standalone_src_math_min = Math.min;
var standalone_src_math_pow = Math.pow;
var standalone_round = Math.round;
var standalone_src_math_sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };
var standalone_src_math_sin = Math.sin;
var standalone_math_tan = Math.tan;

var standalone_d3_geo_projection_src_math_epsilon = 1e-6;
var standalone_src_math_epsilon2 = 1e-12;
var standalone_src_math_pi = Math.PI;
var standalone_src_math_halfPi = standalone_src_math_pi / 2;
var standalone_math_quarterPi = standalone_src_math_pi / 4;
var standalone_sqrt1_2 = Math.SQRT1_2;
var standalone_sqrt2 = standalone_src_math_sqrt(2);
var standalone_sqrtPi = standalone_src_math_sqrt(standalone_src_math_pi);
var standalone_src_math_tau = standalone_src_math_pi * 2;
var standalone_d3_geo_projection_src_math_degrees = 180 / standalone_src_math_pi;
var standalone_d3_geo_projection_src_math_radians = standalone_src_math_pi / 180;

function standalone_sinci(x) {
  return x ? x / Math.sin(x) : 1;
}

function standalone_src_math_asin(x) {
  return x > 1 ? standalone_src_math_halfPi : x < -1 ? -standalone_src_math_halfPi : Math.asin(x);
}

function standalone_src_math_acos(x) {
  return x > 1 ? 0 : x < -1 ? standalone_src_math_pi : Math.acos(x);
}

function standalone_src_math_sqrt(x) {
  return x > 0 ? Math.sqrt(x) : 0;
}

function standalone_math_tanh(x) {
  x = standalone_src_math_exp(2 * x);
  return (x - 1) / (x + 1);
}

function standalone_math_sinh(x) {
  return (standalone_src_math_exp(x) - standalone_src_math_exp(-x)) / 2;
}

function standalone_math_cosh(x) {
  return (standalone_src_math_exp(x) + standalone_src_math_exp(-x)) / 2;
}

function standalone_arsinh(x) {
  return standalone_src_math_log(x + standalone_src_math_sqrt(x * x + 1));
}

function standalone_arcosh(x) {
  return standalone_src_math_log(x + standalone_src_math_sqrt(x * x - 1));
}

;// ../../node_modules/d3-geo-projection/src/mollweide.js



function standalone_mollweideBromleyTheta(cp, phi) {
  var cpsinPhi = cp * standalone_src_math_sin(phi), i = 30, delta;
  do phi -= delta = (phi + standalone_src_math_sin(phi) - cpsinPhi) / (1 + standalone_src_math_cos(phi));
  while (standalone_src_math_abs(delta) > standalone_d3_geo_projection_src_math_epsilon && --i > 0);
  return phi / 2;
}

function standalone_mollweideBromleyRaw(cx, cy, cp) {

  function forward(lambda, phi) {
    return [cx * lambda * standalone_src_math_cos(phi = standalone_mollweideBromleyTheta(cp, phi)), cy * standalone_src_math_sin(phi)];
  }

  forward.invert = function(x, y) {
    return y = standalone_src_math_asin(y / cy), [x / (cx * standalone_src_math_cos(y)), standalone_src_math_asin((2 * y + standalone_src_math_sin(2 * y)) / cp)];
  };

  return forward;
}

var standalone_mollweideRaw = standalone_mollweideBromleyRaw(standalone_sqrt2 / standalone_src_math_halfPi, standalone_sqrt2, standalone_src_math_pi);

/* harmony default export */ function standalone_mollweide() {
  return standalone_projection(standalone_mollweideRaw)
      .scale(169.529);
}

;// ../../node_modules/vega-projection/build/vega-projection.module.js




const standalone_defaultPath = standalone_src_path();
const standalone_projectionProperties = [
// standard properties in d3-geo
'clipAngle', 'clipExtent', 'scale', 'translate', 'center', 'rotate', 'parallels', 'precision', 'reflectX', 'reflectY',
// extended properties in d3-geo-projections
'coefficient', 'distance', 'fraction', 'lobes', 'parallel', 'radius', 'ratio', 'spacing', 'tilt'];

/**
 * Augment projections with their type and a copy method.
 */
function standalone_vega_projection_module_create(type, constructor) {
  return function projection() {
    const p = constructor();
    p.type = type;
    p.path = standalone_src_path().projection(p);
    p.copy = p.copy || function () {
      const c = projection();
      standalone_projectionProperties.forEach(prop => {
        if (p[prop]) c[prop](p[prop]());
      });
      c.path.pointRadius(p.path.pointRadius());
      return c;
    };
    return standalone_registerScale(p);
  };
}
function standalone_vega_projection_module_projection(type, proj) {
  if (!type || typeof type !== 'string') {
    throw new Error('Projection type must be a name string.');
  }
  type = type.toLowerCase();
  if (arguments.length > 1) {
    standalone_projections[type] = standalone_vega_projection_module_create(type, proj);
    return this;
  } else {
    return standalone_projections[type] || null;
  }
}
function standalone_getProjectionPath(proj) {
  return proj && proj.path || standalone_defaultPath;
}
const standalone_projections = {
  // base d3-geo projection types
  albers: standalone_albers,
  albersusa: standalone_albersUsa,
  azimuthalequalarea: standalone_azimuthalEqualArea,
  azimuthalequidistant: standalone_azimuthalEquidistant,
  conicconformal: standalone_conicConformal,
  conicequalarea: standalone_conicEqualArea,
  conicequidistant: standalone_conicEquidistant,
  equalEarth: standalone_equalEarth,
  equirectangular: standalone_equirectangular,
  gnomonic: standalone_gnomonic,
  identity: standalone_projection_identity,
  mercator: standalone_mercator,
  mollweide: standalone_mollweide,
  naturalEarth1: standalone_naturalEarth1,
  orthographic: standalone_orthographic,
  stereographic: standalone_stereographic,
  transversemercator: standalone_transverseMercator
};
for (const key in standalone_projections) {
  standalone_vega_projection_module_projection(key, standalone_projections[key]);
}



;// ../../node_modules/d3-geo/src/graticule.js



function standalone_graticuleX(y0, y1, dy) {
  var y = standalone_range(y0, y1 - standalone_src_math_epsilon, dy).concat(y1);
  return function(x) { return y.map(function(y) { return [x, y]; }); };
}

function standalone_graticuleY(x0, x1, dx) {
  var x = standalone_range(x0, x1 - standalone_src_math_epsilon, dx).concat(x1);
  return function(y) { return x.map(function(x) { return [x, y]; }); };
}

function standalone_graticule() {
  var x1, x0, X1, X0,
      y1, y0, Y1, Y0,
      dx = 10, dy = dx, DX = 90, DY = 360,
      x, y, X, Y,
      precision = 2.5;

  function graticule() {
    return {type: "MultiLineString", coordinates: lines()};
  }

  function lines() {
    return standalone_range(standalone_ceil(X0 / DX) * DX, X1, DX).map(X)
        .concat(standalone_range(standalone_ceil(Y0 / DY) * DY, Y1, DY).map(Y))
        .concat(standalone_range(standalone_ceil(x0 / dx) * dx, x1, dx).filter(function(x) { return standalone_math_abs(x % DX) > standalone_src_math_epsilon; }).map(x))
        .concat(standalone_range(standalone_ceil(y0 / dy) * dy, y1, dy).filter(function(y) { return standalone_math_abs(y % DY) > standalone_src_math_epsilon; }).map(y));
  }

  graticule.lines = function() {
    return lines().map(function(coordinates) { return {type: "LineString", coordinates: coordinates}; });
  };

  graticule.outline = function() {
    return {
      type: "Polygon",
      coordinates: [
        X(X0).concat(
        Y(Y1).slice(1),
        X(X1).reverse().slice(1),
        Y(Y0).reverse().slice(1))
      ]
    };
  };

  graticule.extent = function(_) {
    if (!arguments.length) return graticule.extentMinor();
    return graticule.extentMajor(_).extentMinor(_);
  };

  graticule.extentMajor = function(_) {
    if (!arguments.length) return [[X0, Y0], [X1, Y1]];
    X0 = +_[0][0], X1 = +_[1][0];
    Y0 = +_[0][1], Y1 = +_[1][1];
    if (X0 > X1) _ = X0, X0 = X1, X1 = _;
    if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
    return graticule.precision(precision);
  };

  graticule.extentMinor = function(_) {
    if (!arguments.length) return [[x0, y0], [x1, y1]];
    x0 = +_[0][0], x1 = +_[1][0];
    y0 = +_[0][1], y1 = +_[1][1];
    if (x0 > x1) _ = x0, x0 = x1, x1 = _;
    if (y0 > y1) _ = y0, y0 = y1, y1 = _;
    return graticule.precision(precision);
  };

  graticule.step = function(_) {
    if (!arguments.length) return graticule.stepMinor();
    return graticule.stepMajor(_).stepMinor(_);
  };

  graticule.stepMajor = function(_) {
    if (!arguments.length) return [DX, DY];
    DX = +_[0], DY = +_[1];
    return graticule;
  };

  graticule.stepMinor = function(_) {
    if (!arguments.length) return [dx, dy];
    dx = +_[0], dy = +_[1];
    return graticule;
  };

  graticule.precision = function(_) {
    if (!arguments.length) return precision;
    precision = +_;
    x = standalone_graticuleX(y0, y1, 90);
    y = standalone_graticuleY(x0, x1, precision);
    X = standalone_graticuleX(Y0, Y1, 90);
    Y = standalone_graticuleY(X0, X1, precision);
    return graticule;
  };

  return graticule
      .extentMajor([[-180, -90 + standalone_src_math_epsilon], [180, 90 - standalone_src_math_epsilon]])
      .extentMinor([[-180, -80 - standalone_src_math_epsilon], [180, 80 + standalone_src_math_epsilon]]);
}

function standalone_graticule10() {
  return standalone_graticule()();
}

;// ../../node_modules/vega-geo/build/vega-geo.module.js









function standalone_vega_geo_module_noop() {}
const standalone_cases = [[], [[[1.0, 1.5], [0.5, 1.0]]], [[[1.5, 1.0], [1.0, 1.5]]], [[[1.5, 1.0], [0.5, 1.0]]], [[[1.0, 0.5], [1.5, 1.0]]], [[[1.0, 1.5], [0.5, 1.0]], [[1.0, 0.5], [1.5, 1.0]]], [[[1.0, 0.5], [1.0, 1.5]]], [[[1.0, 0.5], [0.5, 1.0]]], [[[0.5, 1.0], [1.0, 0.5]]], [[[1.0, 1.5], [1.0, 0.5]]], [[[0.5, 1.0], [1.0, 0.5]], [[1.5, 1.0], [1.0, 1.5]]], [[[1.5, 1.0], [1.0, 0.5]]], [[[0.5, 1.0], [1.5, 1.0]]], [[[1.0, 1.5], [1.5, 1.0]]], [[[0.5, 1.0], [1.0, 1.5]]], []];

// Implementation adapted from d3/d3-contour. Thanks!
function standalone_contours () {
  var dx = 1,
    dy = 1,
    smooth = smoothLinear;
  function contours(values, tz) {
    return tz.map(value => contour(values, value));
  }

  // Accumulate, smooth contour rings, assign holes to exterior rings.
  // Based on https://github.com/mbostock/shapefile/blob/v0.6.2/shp/polygon.js
  function contour(values, value) {
    var polygons = [],
      holes = [];
    isorings(values, value, ring => {
      smooth(ring, values, value);
      if (standalone_vega_geo_module_area(ring) > 0) polygons.push([ring]);else holes.push(ring);
    });
    holes.forEach(hole => {
      for (var i = 0, n = polygons.length, polygon; i < n; ++i) {
        if (standalone_contains((polygon = polygons[i])[0], hole) !== -1) {
          polygon.push(hole);
          return;
        }
      }
    });
    return {
      type: 'MultiPolygon',
      value: value,
      coordinates: polygons
    };
  }

  // Marching squares with isolines stitched into rings.
  // Based on https://github.com/topojson/topojson-client/blob/v3.0.0/src/stitch.js
  function isorings(values, value, callback) {
    var fragmentByStart = [],
      fragmentByEnd = [],
      x,
      y,
      t0,
      t1,
      t2,
      t3;

    // Special case for the first row (y = -1, t2 = t3 = 0).
    x = y = -1;
    t1 = values[0] >= value;
    standalone_cases[t1 << 1].forEach(stitch);
    while (++x < dx - 1) {
      t0 = t1, t1 = values[x + 1] >= value;
      standalone_cases[t0 | t1 << 1].forEach(stitch);
    }
    standalone_cases[t1 << 0].forEach(stitch);

    // General case for the intermediate rows.
    while (++y < dy - 1) {
      x = -1;
      t1 = values[y * dx + dx] >= value;
      t2 = values[y * dx] >= value;
      standalone_cases[t1 << 1 | t2 << 2].forEach(stitch);
      while (++x < dx - 1) {
        t0 = t1, t1 = values[y * dx + dx + x + 1] >= value;
        t3 = t2, t2 = values[y * dx + x + 1] >= value;
        standalone_cases[t0 | t1 << 1 | t2 << 2 | t3 << 3].forEach(stitch);
      }
      standalone_cases[t1 | t2 << 3].forEach(stitch);
    }

    // Special case for the last row (y = dy - 1, t0 = t1 = 0).
    x = -1;
    t2 = values[y * dx] >= value;
    standalone_cases[t2 << 2].forEach(stitch);
    while (++x < dx - 1) {
      t3 = t2, t2 = values[y * dx + x + 1] >= value;
      standalone_cases[t2 << 2 | t3 << 3].forEach(stitch);
    }
    standalone_cases[t2 << 3].forEach(stitch);
    function stitch(line) {
      var start = [line[0][0] + x, line[0][1] + y],
        end = [line[1][0] + x, line[1][1] + y],
        startIndex = index(start),
        endIndex = index(end),
        f,
        g;
      if (f = fragmentByEnd[startIndex]) {
        if (g = fragmentByStart[endIndex]) {
          delete fragmentByEnd[f.end];
          delete fragmentByStart[g.start];
          if (f === g) {
            f.ring.push(end);
            callback(f.ring);
          } else {
            fragmentByStart[f.start] = fragmentByEnd[g.end] = {
              start: f.start,
              end: g.end,
              ring: f.ring.concat(g.ring)
            };
          }
        } else {
          delete fragmentByEnd[f.end];
          f.ring.push(end);
          fragmentByEnd[f.end = endIndex] = f;
        }
      } else if (f = fragmentByStart[endIndex]) {
        if (g = fragmentByEnd[startIndex]) {
          delete fragmentByStart[f.start];
          delete fragmentByEnd[g.end];
          if (f === g) {
            f.ring.push(end);
            callback(f.ring);
          } else {
            fragmentByStart[g.start] = fragmentByEnd[f.end] = {
              start: g.start,
              end: f.end,
              ring: g.ring.concat(f.ring)
            };
          }
        } else {
          delete fragmentByStart[f.start];
          f.ring.unshift(start);
          fragmentByStart[f.start = startIndex] = f;
        }
      } else {
        fragmentByStart[startIndex] = fragmentByEnd[endIndex] = {
          start: startIndex,
          end: endIndex,
          ring: [start, end]
        };
      }
    }
  }
  function index(point) {
    return point[0] * 2 + point[1] * (dx + 1) * 4;
  }
  function smoothLinear(ring, values, value) {
    ring.forEach(point => {
      var x = point[0],
        y = point[1],
        xt = x | 0,
        yt = y | 0,
        v0,
        v1 = values[yt * dx + xt];
      if (x > 0 && x < dx && xt === x) {
        v0 = values[yt * dx + xt - 1];
        point[0] = x + (value - v0) / (v1 - v0) - 0.5;
      }
      if (y > 0 && y < dy && yt === y) {
        v0 = values[(yt - 1) * dx + xt];
        point[1] = y + (value - v0) / (v1 - v0) - 0.5;
      }
    });
  }
  contours.contour = contour;
  contours.size = function (_) {
    if (!arguments.length) return [dx, dy];
    var _0 = Math.floor(_[0]),
      _1 = Math.floor(_[1]);
    if (!(_0 >= 0 && _1 >= 0)) standalone_vega_util_module_error('invalid size');
    return dx = _0, dy = _1, contours;
  };
  contours.smooth = function (_) {
    return arguments.length ? (smooth = _ ? smoothLinear : standalone_vega_geo_module_noop, contours) : smooth === smoothLinear;
  };
  return contours;
}
function standalone_vega_geo_module_area(ring) {
  var i = 0,
    n = ring.length,
    area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];
  while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];
  return area;
}
function standalone_contains(ring, hole) {
  var i = -1,
    n = hole.length,
    c;
  while (++i < n) if (c = standalone_ringContains(ring, hole[i])) return c;
  return 0;
}
function standalone_ringContains(ring, point) {
  var x = point[0],
    y = point[1],
    contains = -1;
  for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) {
    var pi = ring[i],
      xi = pi[0],
      yi = pi[1],
      pj = ring[j],
      xj = pj[0],
      yj = pj[1];
    if (standalone_segmentContains(pi, pj, point)) return 0;
    if (yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) contains = -contains;
  }
  return contains;
}
function standalone_segmentContains(a, b, c) {
  var i;
  return standalone_collinear(a, b, c) && standalone_within(a[i = +(a[0] === b[0])], c[i], b[i]);
}
function standalone_collinear(a, b, c) {
  return (b[0] - a[0]) * (c[1] - a[1]) === (c[0] - a[0]) * (b[1] - a[1]);
}
function standalone_within(p, q, r) {
  return p <= q && q <= r || r <= q && q <= p;
}

function standalone_vega_geo_module_quantize (k, nice, zero) {
  return function (values) {
    var ex = standalone_extent(values),
      start = zero ? Math.min(ex[0], 0) : ex[0],
      stop = ex[1],
      span = stop - start,
      step = nice ? standalone_tickStep(start, stop, k) : span / (k + 1);
    return standalone_range(start + step, stop, step);
  };
}

/**
 * Generate isocontours (level sets) based on input raster grid data.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} [params.field] - The field with raster grid
 *   data. If unspecified, the tuple itself is interpreted as a raster grid.
 * @param {Array<number>} [params.thresholds] - Contour threshold array. If
 *   specified, the levels, nice, resolve, and zero parameters are ignored.
 * @param {number} [params.levels] - The desired number of contour levels.
 * @param {boolean} [params.nice] - Boolean flag indicating if the contour
 *   threshold values should be automatically aligned to "nice"
 *   human-friendly values. Setting this flag may cause the number of
 *   thresholds to deviate from the specified levels.
 * @param {string} [params.resolve] - The method for resolving thresholds
 *   across multiple input grids. If 'independent' (the default), threshold
 *   calculation will be performed separately for each grid. If 'shared', a
 *   single set of threshold values will be used for all input grids.
 * @param {boolean} [params.zero] - Boolean flag indicating if the contour
 *   threshold values should include zero.
 * @param {boolean} [params.smooth] - Boolean flag indicating if the contour
 *   polygons should be smoothed using linear interpolation. The default is
 *   true. The parameter is ignored when using density estimation.
 * @param {boolean} [params.scale] - Optional numerical value by which to
 *   scale the output isocontour coordinates. This parameter can be useful
 *   to scale the contours to match a desired output resolution.
 * @param {string} [params.as='contour'] - The output field in which to store
 *   the generated isocontour data (default 'contour').
 */
function standalone_Isocontour(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Isocontour.Definition = {
  'type': 'Isocontour',
  'metadata': {
    'generates': true
  },
  'params': [{
    'name': 'field',
    'type': 'field'
  }, {
    'name': 'thresholds',
    'type': 'number',
    'array': true
  }, {
    'name': 'levels',
    'type': 'number'
  }, {
    'name': 'nice',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'resolve',
    'type': 'enum',
    'values': ['shared', 'independent'],
    'default': 'independent'
  }, {
    'name': 'zero',
    'type': 'boolean',
    'default': true
  }, {
    'name': 'smooth',
    'type': 'boolean',
    'default': true
  }, {
    'name': 'scale',
    'type': 'number',
    'expr': true
  }, {
    'name': 'translate',
    'type': 'number',
    'array': true,
    'expr': true
  }, {
    'name': 'as',
    'type': 'string',
    'null': true,
    'default': 'contour'
  }]
};
standalone_inherits(standalone_Isocontour, standalone_Transform, {
  transform(_, pulse) {
    if (this.value && !pulse.changed() && !_.modified()) {
      return pulse.StopPropagation;
    }
    var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
      source = pulse.materialize(pulse.SOURCE).source,
      field = _.field || standalone_vega_util_module_identity,
      contour = standalone_contours().smooth(_.smooth !== false),
      tz = _.thresholds || standalone_levels(source, field, _),
      as = _.as === null ? null : _.as || 'contour',
      values = [];
    source.forEach(t => {
      const grid = field(t);

      // generate contour paths in GeoJSON format
      const paths = contour.size([grid.width, grid.height])(grid.values, standalone_vega_util_module_isArray(tz) ? tz : tz(grid.values));

      // adjust contour path coordinates as needed
      standalone_transformPaths(paths, grid, t, _);

      // ingest; copy source data properties to output
      paths.forEach(p => {
        values.push(standalone_rederive(t, standalone_ingest$1(as != null ? {
          [as]: p
        } : p)));
      });
    });
    if (this.value) out.rem = this.value;
    this.value = out.source = out.add = values;
    return out;
  }
});
function standalone_levels(values, f, _) {
  const q = standalone_vega_geo_module_quantize(_.levels || 10, _.nice, _.zero !== false);
  return _.resolve !== 'shared' ? q : q(values.map(t => standalone_max(f(t).values)));
}
function standalone_transformPaths(paths, grid, datum, _) {
  let s = _.scale || grid.scale,
    t = _.translate || grid.translate;
  if (standalone_vega_util_module_isFunction(s)) s = s(datum, _);
  if (standalone_vega_util_module_isFunction(t)) t = t(datum, _);
  if ((s === 1 || s == null) && !t) return;
  const sx = (standalone_isNumber(s) ? s : s[0]) || 1,
    sy = (standalone_isNumber(s) ? s : s[1]) || 1,
    tx = t && t[0] || 0,
    ty = t && t[1] || 0;
  paths.forEach(standalone_vega_geo_module_transform(grid, sx, sy, tx, ty));
}
function standalone_vega_geo_module_transform(grid, sx, sy, tx, ty) {
  const x1 = grid.x1 || 0,
    y1 = grid.y1 || 0,
    flip = sx * sy < 0;
  function transformPolygon(coordinates) {
    coordinates.forEach(transformRing);
  }
  function transformRing(coordinates) {
    if (flip) coordinates.reverse(); // maintain winding order
    coordinates.forEach(transformPoint);
  }
  function transformPoint(coordinates) {
    coordinates[0] = (coordinates[0] - x1) * sx + tx;
    coordinates[1] = (coordinates[1] - y1) * sy + ty;
  }
  return function (geometry) {
    geometry.coordinates.forEach(transformPolygon);
    return geometry;
  };
}

function standalone_radius(bw, data, f) {
  const v = bw >= 0 ? bw : standalone_estimateBandwidth(data, f);
  return Math.round((Math.sqrt(4 * v * v + 1) - 1) / 2);
}
function standalone_vega_geo_module_number(_) {
  return standalone_vega_util_module_isFunction(_) ? _ : standalone_vega_util_module_constant(+_);
}

// Implementation adapted from d3/d3-contour. Thanks!
function standalone_density2D () {
  var x = d => d[0],
    y = d => d[1],
    weight = standalone_one,
    bandwidth = [-1, -1],
    dx = 960,
    dy = 500,
    k = 2; // log2(cellSize)

  function density(data, counts) {
    const rx = standalone_radius(bandwidth[0], data, x) >> k,
      // blur x-radius
      ry = standalone_radius(bandwidth[1], data, y) >> k,
      // blur y-radius
      ox = rx ? rx + 2 : 0,
      // x-offset padding for blur
      oy = ry ? ry + 2 : 0,
      // y-offset padding for blur
      n = 2 * ox + (dx >> k),
      // grid width
      m = 2 * oy + (dy >> k),
      // grid height
      values0 = new Float32Array(n * m),
      values1 = new Float32Array(n * m);
    let values = values0;
    data.forEach(d => {
      const xi = ox + (+x(d) >> k),
        yi = oy + (+y(d) >> k);
      if (xi >= 0 && xi < n && yi >= 0 && yi < m) {
        values0[xi + yi * n] += +weight(d);
      }
    });
    if (rx > 0 && ry > 0) {
      standalone_blurX(n, m, values0, values1, rx);
      standalone_blurY(n, m, values1, values0, ry);
      standalone_blurX(n, m, values0, values1, rx);
      standalone_blurY(n, m, values1, values0, ry);
      standalone_blurX(n, m, values0, values1, rx);
      standalone_blurY(n, m, values1, values0, ry);
    } else if (rx > 0) {
      standalone_blurX(n, m, values0, values1, rx);
      standalone_blurX(n, m, values1, values0, rx);
      standalone_blurX(n, m, values0, values1, rx);
      values = values1;
    } else if (ry > 0) {
      standalone_blurY(n, m, values0, values1, ry);
      standalone_blurY(n, m, values1, values0, ry);
      standalone_blurY(n, m, values0, values1, ry);
      values = values1;
    }

    // scale density estimates
    // density in points per square pixel or probability density
    const s = counts ? Math.pow(2, -2 * k) : 1 / standalone_sum_sum(values);
    for (let i = 0, sz = n * m; i < sz; ++i) values[i] *= s;
    return {
      values: values,
      scale: 1 << k,
      width: n,
      height: m,
      x1: ox,
      y1: oy,
      x2: ox + (dx >> k),
      y2: oy + (dy >> k)
    };
  }
  density.x = function (_) {
    return arguments.length ? (x = standalone_vega_geo_module_number(_), density) : x;
  };
  density.y = function (_) {
    return arguments.length ? (y = standalone_vega_geo_module_number(_), density) : y;
  };
  density.weight = function (_) {
    return arguments.length ? (weight = standalone_vega_geo_module_number(_), density) : weight;
  };
  density.size = function (_) {
    if (!arguments.length) return [dx, dy];
    var _0 = +_[0],
      _1 = +_[1];
    if (!(_0 >= 0 && _1 >= 0)) standalone_vega_util_module_error('invalid size');
    return dx = _0, dy = _1, density;
  };
  density.cellSize = function (_) {
    if (!arguments.length) return 1 << k;
    if (!((_ = +_) >= 1)) standalone_vega_util_module_error('invalid cell size');
    k = Math.floor(Math.log(_) / Math.LN2);
    return density;
  };
  density.bandwidth = function (_) {
    if (!arguments.length) return bandwidth;
    _ = standalone_array(_);
    if (_.length === 1) _ = [+_[0], +_[0]];
    if (_.length !== 2) standalone_vega_util_module_error('invalid bandwidth');
    return bandwidth = _, density;
  };
  return density;
}
function standalone_blurX(n, m, source, target, r) {
  const w = (r << 1) + 1;
  for (let j = 0; j < m; ++j) {
    for (let i = 0, sr = 0; i < n + r; ++i) {
      if (i < n) {
        sr += source[i + j * n];
      }
      if (i >= r) {
        if (i >= w) {
          sr -= source[i - w + j * n];
        }
        target[i - r + j * n] = sr / Math.min(i + 1, n - 1 + w - i, w);
      }
    }
  }
}
function standalone_blurY(n, m, source, target, r) {
  const w = (r << 1) + 1;
  for (let i = 0; i < n; ++i) {
    for (let j = 0, sr = 0; j < m + r; ++j) {
      if (j < m) {
        sr += source[i + j * n];
      }
      if (j >= r) {
        if (j >= w) {
          sr -= source[i + (j - w) * n];
        }
        target[i + (j - r) * n] = sr / Math.min(j + 1, m - 1 + w - j, w);
      }
    }
  }
}

/**
 * Perform 2D kernel-density estimation of point data.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<number>} params.size - The [width, height] extent (in
 *   units of input pixels) over which to perform density estimation.
 * @param {function(object): number} params.x - The x-coordinate accessor.
 * @param {function(object): number} params.y - The y-coordinate accessor.
 * @param {function(object): number} [params.weight] - The weight accessor.
 * @param {Array<function(object): *>} [params.groupby] - An array of accessors
 *   to groupby.
 * @param {number} [params.cellSize] - Contour density calculation cell size.
 *   This parameter determines the level of spatial approximation. For example,
 *   the default value of 4 maps to 2x reductions in both x- and y- dimensions.
 *   A value of 1 will result in an output raster grid whose dimensions exactly
 *   matches the size parameter.
 * @param {Array<number>} [params.bandwidth] - The KDE kernel bandwidths,
 *   in pixels. The input can be a two-element array specifying separate
 *   x and y bandwidths, or a single-element array specifying both. If the
 *   bandwidth is unspecified or less than zero, the bandwidth will be
 *   automatically determined.
 * @param {boolean} [params.counts=false] - A boolean flag indicating if the
 *   output values should be probability estimates (false, default) or
 *   smoothed counts (true).
 * @param {string} [params.as='grid'] - The output field in which to store
 *   the generated raster grid (default 'grid').
 */
function standalone_KDE2D(params) {
  standalone_Transform.call(this, null, params);
}
standalone_KDE2D.Definition = {
  'type': 'KDE2D',
  'metadata': {
    'generates': true
  },
  'params': [{
    'name': 'size',
    'type': 'number',
    'array': true,
    'length': 2,
    'required': true
  }, {
    'name': 'x',
    'type': 'field',
    'required': true
  }, {
    'name': 'y',
    'type': 'field',
    'required': true
  }, {
    'name': 'weight',
    'type': 'field'
  }, {
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'cellSize',
    'type': 'number'
  }, {
    'name': 'bandwidth',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'counts',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'as',
    'type': 'string',
    'default': 'grid'
  }]
};
const standalone_PARAMS = ['x', 'y', 'weight', 'size', 'cellSize', 'bandwidth'];
function standalone_params(obj, _) {
  standalone_PARAMS.forEach(param => _[param] != null ? obj[param](_[param]) : 0);
  return obj;
}
standalone_inherits(standalone_KDE2D, standalone_Transform, {
  transform(_, pulse) {
    if (this.value && !pulse.changed() && !_.modified()) return pulse.StopPropagation;
    var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
      source = pulse.materialize(pulse.SOURCE).source,
      groups = standalone_vega_geo_module_partition(source, _.groupby),
      names = (_.groupby || []).map(standalone_accessorName),
      kde = standalone_params(standalone_density2D(), _),
      as = _.as || 'grid',
      values = [];
    function set(t, vals) {
      for (let i = 0; i < names.length; ++i) t[names[i]] = vals[i];
      return t;
    }

    // generate density raster grids
    values = groups.map(g => standalone_ingest$1(set({
      [as]: kde(g, _.counts)
    }, g.dims)));
    if (this.value) out.rem = this.value;
    this.value = out.source = out.add = values;
    return out;
  }
});
function standalone_vega_geo_module_partition(data, groupby) {
  var groups = [],
    get = f => f(t),
    map,
    i,
    n,
    t,
    k,
    g;

  // partition data points into groups
  if (groupby == null) {
    groups.push(data);
  } else {
    for (map = {}, i = 0, n = data.length; i < n; ++i) {
      t = data[i];
      k = groupby.map(get);
      g = map[k];
      if (!g) {
        map[k] = g = [];
        g.dims = k;
        groups.push(g);
      }
      g.push(t);
    }
  }
  return groups;
}

/**
 * Generate contours based on kernel-density estimation of point data.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<number>} params.size - The dimensions [width, height] over which to compute contours.
 *  If the values parameter is provided, this must be the dimensions of the input data.
 *  If density estimation is performed, this is the output view dimensions in pixels.
 * @param {Array<number>} [params.values] - An array of numeric values representing an
 *  width x height grid of values over which to compute contours. If unspecified, this
 *  transform will instead attempt to compute contours for the kernel density estimate
 *  using values drawn from data tuples in the input pulse.
 * @param {function(object): number} [params.x] - The pixel x-coordinate accessor for density estimation.
 * @param {function(object): number} [params.y] - The pixel y-coordinate accessor for density estimation.
 * @param {function(object): number} [params.weight] - The data point weight accessor for density estimation.
 * @param {number} [params.cellSize] - Contour density calculation cell size.
 * @param {number} [params.bandwidth] - Kernel density estimation bandwidth.
 * @param {Array<number>} [params.thresholds] - Contour threshold array. If
 *   this parameter is set, the count and nice parameters will be ignored.
 * @param {number} [params.count] - The desired number of contours.
 * @param {boolean} [params.nice] - Boolean flag indicating if the contour
 *   threshold values should be automatically aligned to "nice"
 *   human-friendly values. Setting this flag may cause the number of
 *   thresholds to deviate from the specified count.
 * @param {boolean} [params.smooth] - Boolean flag indicating if the contour
 *   polygons should be smoothed using linear interpolation. The default is
 *   true. The parameter is ignored when using density estimation.
 */
function standalone_Contour(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Contour.Definition = {
  'type': 'Contour',
  'metadata': {
    'generates': true
  },
  'params': [{
    'name': 'size',
    'type': 'number',
    'array': true,
    'length': 2,
    'required': true
  }, {
    'name': 'values',
    'type': 'number',
    'array': true
  }, {
    'name': 'x',
    'type': 'field'
  }, {
    'name': 'y',
    'type': 'field'
  }, {
    'name': 'weight',
    'type': 'field'
  }, {
    'name': 'cellSize',
    'type': 'number'
  }, {
    'name': 'bandwidth',
    'type': 'number'
  }, {
    'name': 'count',
    'type': 'number'
  }, {
    'name': 'nice',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'thresholds',
    'type': 'number',
    'array': true
  }, {
    'name': 'smooth',
    'type': 'boolean',
    'default': true
  }]
};
standalone_inherits(standalone_Contour, standalone_Transform, {
  transform(_, pulse) {
    if (this.value && !pulse.changed() && !_.modified()) {
      return pulse.StopPropagation;
    }
    var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
      contour = standalone_contours().smooth(_.smooth !== false),
      values = _.values,
      thresh = _.thresholds || standalone_vega_geo_module_quantize(_.count || 10, _.nice, !!values),
      size = _.size,
      grid,
      post;
    if (!values) {
      values = pulse.materialize(pulse.SOURCE).source;
      grid = standalone_params(standalone_density2D(), _)(values, true);
      post = standalone_vega_geo_module_transform(grid, grid.scale || 1, grid.scale || 1, 0, 0);
      size = [grid.width, grid.height];
      values = grid.values;
    }
    thresh = standalone_vega_util_module_isArray(thresh) ? thresh : thresh(values);
    values = contour.size(size)(values, thresh);
    if (post) values.forEach(post);
    if (this.value) out.rem = this.value;
    this.value = out.source = out.add = (values || []).map(standalone_ingest$1);
    return out;
  }
});

const standalone_Feature = 'Feature';
const standalone_FeatureCollection = 'FeatureCollection';
const standalone_MultiPoint = 'MultiPoint';

/**
 * Consolidate an array of [longitude, latitude] points or GeoJSON features
 * into a combined GeoJSON object. This transform is particularly useful for
 * combining geo data for a Projection's fit argument. The resulting GeoJSON
 * data is available as this transform's value. Input pulses are unchanged.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<function(object): *>} [params.fields] - A two-element array
 *   of field accessors for the longitude and latitude values.
 * @param {function(object): *} params.geojson - A field accessor for
 *   retrieving GeoJSON feature data.
 */
function standalone_GeoJSON(params) {
  standalone_Transform.call(this, null, params);
}
standalone_GeoJSON.Definition = {
  'type': 'GeoJSON',
  'metadata': {},
  'params': [{
    'name': 'fields',
    'type': 'field',
    'array': true,
    'length': 2
  }, {
    'name': 'geojson',
    'type': 'field'
  }]
};
standalone_inherits(standalone_GeoJSON, standalone_Transform, {
  transform(_, pulse) {
    var features = this._features,
      points = this._points,
      fields = _.fields,
      lon = fields && fields[0],
      lat = fields && fields[1],
      geojson = _.geojson || !fields && standalone_vega_util_module_identity,
      flag = pulse.ADD,
      mod;
    mod = _.modified() || pulse.changed(pulse.REM) || pulse.modified(standalone_accessorFields(geojson)) || lon && pulse.modified(standalone_accessorFields(lon)) || lat && pulse.modified(standalone_accessorFields(lat));
    if (!this.value || mod) {
      flag = pulse.SOURCE;
      this._features = features = [];
      this._points = points = [];
    }
    if (geojson) {
      pulse.visit(flag, t => features.push(geojson(t)));
    }
    if (lon && lat) {
      pulse.visit(flag, t => {
        var x = lon(t),
          y = lat(t);
        if (x != null && y != null && (x = +x) === x && (y = +y) === y) {
          points.push([x, y]);
        }
      });
      features = features.concat({
        type: standalone_Feature,
        geometry: {
          type: standalone_MultiPoint,
          coordinates: points
        }
      });
    }
    this.value = {
      type: standalone_FeatureCollection,
      features: features
    };
  }
});

/**
 * Map GeoJSON data to an SVG path string.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(number, number): *} params.projection - The cartographic
 *   projection to apply.
 * @param {function(object): *} [params.field] - The field with GeoJSON data,
 *   or null if the tuple itself is a GeoJSON feature.
 * @param {string} [params.as='path'] - The output field in which to store
 *   the generated path data (default 'path').
 */
function standalone_GeoPath(params) {
  standalone_Transform.call(this, null, params);
}
standalone_GeoPath.Definition = {
  'type': 'GeoPath',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'projection',
    'type': 'projection'
  }, {
    'name': 'field',
    'type': 'field'
  }, {
    'name': 'pointRadius',
    'type': 'number',
    'expr': true
  }, {
    'name': 'as',
    'type': 'string',
    'default': 'path'
  }]
};
standalone_inherits(standalone_GeoPath, standalone_Transform, {
  transform(_, pulse) {
    var out = pulse.fork(pulse.ALL),
      path = this.value,
      field = _.field || standalone_vega_util_module_identity,
      as = _.as || 'path',
      flag = out.SOURCE;
    if (!path || _.modified()) {
      // parameters updated, reset and reflow
      this.value = path = standalone_getProjectionPath(_.projection);
      out.materialize().reflow();
    } else {
      flag = field === standalone_vega_util_module_identity || pulse.modified(field.fields) ? out.ADD_MOD : out.ADD;
    }
    const prev = standalone_initPath(path, _.pointRadius);
    out.visit(flag, t => t[as] = path(field(t)));
    path.pointRadius(prev);
    return out.modifies(as);
  }
});
function standalone_initPath(path, pointRadius) {
  const prev = path.pointRadius();
  path.context(null);
  if (pointRadius != null) {
    path.pointRadius(pointRadius);
  }
  return prev;
}

/**
 * Geo-code a longitude/latitude point to an x/y coordinate.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(number, number): *} params.projection - The cartographic
 *   projection to apply.
 * @param {Array<function(object): *>} params.fields - A two-element array of
 *   field accessors for the longitude and latitude values.
 * @param {Array<string>} [params.as] - A two-element array of field names
 *   under which to store the result. Defaults to ['x','y'].
 */
function standalone_GeoPoint(params) {
  standalone_Transform.call(this, null, params);
}
standalone_GeoPoint.Definition = {
  'type': 'GeoPoint',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'projection',
    'type': 'projection',
    'required': true
  }, {
    'name': 'fields',
    'type': 'field',
    'array': true,
    'required': true,
    'length': 2
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': 2,
    'default': ['x', 'y']
  }]
};
standalone_inherits(standalone_GeoPoint, standalone_Transform, {
  transform(_, pulse) {
    var proj = _.projection,
      lon = _.fields[0],
      lat = _.fields[1],
      as = _.as || ['x', 'y'],
      x = as[0],
      y = as[1],
      mod;
    function set(t) {
      const xy = proj([lon(t), lat(t)]);
      if (xy) {
        t[x] = xy[0];
        t[y] = xy[1];
      } else {
        t[x] = undefined;
        t[y] = undefined;
      }
    }
    if (_.modified()) {
      // parameters updated, reflow
      pulse = pulse.materialize().reflow(true).visit(pulse.SOURCE, set);
    } else {
      mod = pulse.modified(lon.fields) || pulse.modified(lat.fields);
      pulse.visit(mod ? pulse.ADD_MOD : pulse.ADD, set);
    }
    return pulse.modifies(as);
  }
});

/**
 * Annotate items with a geopath shape generator.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(number, number): *} params.projection - The cartographic
 *   projection to apply.
 * @param {function(object): *} [params.field] - The field with GeoJSON data,
 *   or null if the tuple itself is a GeoJSON feature.
 * @param {string} [params.as='shape'] - The output field in which to store
 *   the generated path data (default 'shape').
 */
function standalone_GeoShape(params) {
  standalone_Transform.call(this, null, params);
}
standalone_GeoShape.Definition = {
  'type': 'GeoShape',
  'metadata': {
    'modifies': true,
    'nomod': true
  },
  'params': [{
    'name': 'projection',
    'type': 'projection'
  }, {
    'name': 'field',
    'type': 'field',
    'default': 'datum'
  }, {
    'name': 'pointRadius',
    'type': 'number',
    'expr': true
  }, {
    'name': 'as',
    'type': 'string',
    'default': 'shape'
  }]
};
standalone_inherits(standalone_GeoShape, standalone_Transform, {
  transform(_, pulse) {
    var out = pulse.fork(pulse.ALL),
      shape = this.value,
      as = _.as || 'shape',
      flag = out.ADD;
    if (!shape || _.modified()) {
      // parameters updated, reset and reflow
      this.value = shape = standalone_shapeGenerator(standalone_getProjectionPath(_.projection), _.field || standalone_field('datum'), _.pointRadius);
      out.materialize().reflow();
      flag = out.SOURCE;
    }
    out.visit(flag, t => t[as] = shape);
    return out.modifies(as);
  }
});
function standalone_shapeGenerator(path, field, pointRadius) {
  const shape = pointRadius == null ? _ => path(field(_)) : _ => {
    var prev = path.pointRadius(),
      value = path.pointRadius(pointRadius)(field(_));
    path.pointRadius(prev);
    return value;
  };
  shape.context = _ => {
    path.context(_);
    return shape;
  };
  return shape;
}

/**
 * GeoJSON feature generator for creating graticules.
 * @constructor
 */
function standalone_Graticule(params) {
  standalone_Transform.call(this, [], params);
  this.generator = standalone_graticule();
}
standalone_Graticule.Definition = {
  'type': 'Graticule',
  'metadata': {
    'changes': true,
    'generates': true
  },
  'params': [{
    'name': 'extent',
    'type': 'array',
    'array': true,
    'length': 2,
    'content': {
      'type': 'number',
      'array': true,
      'length': 2
    }
  }, {
    'name': 'extentMajor',
    'type': 'array',
    'array': true,
    'length': 2,
    'content': {
      'type': 'number',
      'array': true,
      'length': 2
    }
  }, {
    'name': 'extentMinor',
    'type': 'array',
    'array': true,
    'length': 2,
    'content': {
      'type': 'number',
      'array': true,
      'length': 2
    }
  }, {
    'name': 'step',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'stepMajor',
    'type': 'number',
    'array': true,
    'length': 2,
    'default': [90, 360]
  }, {
    'name': 'stepMinor',
    'type': 'number',
    'array': true,
    'length': 2,
    'default': [10, 10]
  }, {
    'name': 'precision',
    'type': 'number',
    'default': 2.5
  }]
};
standalone_inherits(standalone_Graticule, standalone_Transform, {
  transform(_, pulse) {
    var src = this.value,
      gen = this.generator,
      t;
    if (!src.length || _.modified()) {
      for (const prop in _) {
        if (standalone_vega_util_module_isFunction(gen[prop])) {
          gen[prop](_[prop]);
        }
      }
    }
    t = gen();
    if (src.length) {
      pulse.mod.push(standalone_replace(src[0], t));
    } else {
      pulse.add.push(standalone_ingest$1(t));
    }
    src[0] = t;
    return pulse;
  }
});

/**
 * Render a heatmap image for input raster grid data.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} [params.field] - The field with raster grid
 *   data. If unspecified, the tuple itself is interpreted as a raster grid.
 * @param {string} [params.color] - A constant color value or function for
 *   individual pixel color. If a function, it will be invoked with an input
 *   object that includes $x, $y, $value, and $max fields for the grid.
 * @param {number} [params.opacity] - A constant opacity value or function for
 *   individual pixel opacity. If a function, it will be invoked with an input
 *   object that includes $x, $y, $value, and $max fields for the grid.
 * @param {string} [params.resolve] - The method for resolving maximum values
 *   across multiple input grids. If 'independent' (the default), maximum
 *   calculation will be performed separately for each grid. If 'shared',
 *   a single global maximum will be used for all input grids.
 * @param {string} [params.as='image'] - The output field in which to store
 *   the generated bitmap canvas images (default 'image').
 */
function standalone_Heatmap(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Heatmap.Definition = {
  'type': 'heatmap',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'field',
    'type': 'field'
  }, {
    'name': 'color',
    'type': 'string',
    'expr': true
  }, {
    'name': 'opacity',
    'type': 'number',
    'expr': true
  }, {
    'name': 'resolve',
    'type': 'enum',
    'values': ['shared', 'independent'],
    'default': 'independent'
  }, {
    'name': 'as',
    'type': 'string',
    'default': 'image'
  }]
};
standalone_inherits(standalone_Heatmap, standalone_Transform, {
  transform(_, pulse) {
    if (!pulse.changed() && !_.modified()) {
      return pulse.StopPropagation;
    }
    var source = pulse.materialize(pulse.SOURCE).source,
      shared = _.resolve === 'shared',
      field = _.field || standalone_vega_util_module_identity,
      opacity = standalone_opacity_(_.opacity, _),
      color = standalone_color_(_.color, _),
      as = _.as || 'image',
      obj = {
        $x: 0,
        $y: 0,
        $value: 0,
        $max: shared ? standalone_max(source.map(t => standalone_max(field(t).values))) : 0
      };
    source.forEach(t => {
      const v = field(t);

      // build proxy data object
      const o = standalone_extend({}, t, obj);
      // set maximum value if not globally shared
      if (!shared) o.$max = standalone_max(v.values || []);

      // generate canvas image
      // optimize color/opacity if not pixel-dependent
      t[as] = standalone_toCanvas(v, o, color.dep ? color : standalone_vega_util_module_constant(color(o)), opacity.dep ? opacity : standalone_vega_util_module_constant(opacity(o)));
    });
    return pulse.reflow(true).modifies(as);
  }
});

// get image color function
function standalone_color_(color, _) {
  let f;
  if (standalone_vega_util_module_isFunction(color)) {
    f = obj => standalone_color_rgb(color(obj, _));
    f.dep = standalone_dependency(color);
  } else {
    // default to mid-grey
    f = standalone_vega_util_module_constant(standalone_color_rgb(color || '#888'));
  }
  return f;
}

// get image opacity function
function standalone_opacity_(opacity, _) {
  let f;
  if (standalone_vega_util_module_isFunction(opacity)) {
    f = obj => opacity(obj, _);
    f.dep = standalone_dependency(opacity);
  } else if (opacity) {
    f = standalone_vega_util_module_constant(opacity);
  } else {
    // default to [0, max] opacity gradient
    f = obj => obj.$value / obj.$max || 0;
    f.dep = true;
  }
  return f;
}

// check if function depends on individual pixel data
function standalone_dependency(f) {
  if (!standalone_vega_util_module_isFunction(f)) return false;
  const set = standalone_toSet(standalone_accessorFields(f));
  return set.$x || set.$y || set.$value || set.$max;
}

// render raster grid to canvas
function standalone_toCanvas(grid, obj, color, opacity) {
  const n = grid.width,
    m = grid.height,
    x1 = grid.x1 || 0,
    y1 = grid.y1 || 0,
    x2 = grid.x2 || n,
    y2 = grid.y2 || m,
    val = grid.values,
    value = val ? i => val[i] : standalone_zero,
    can = standalone_domCanvas(x2 - x1, y2 - y1),
    ctx = can.getContext('2d'),
    img = ctx.getImageData(0, 0, x2 - x1, y2 - y1),
    pix = img.data;
  for (let j = y1, k = 0; j < y2; ++j) {
    obj.$y = j - y1;
    for (let i = x1, r = j * n; i < x2; ++i, k += 4) {
      obj.$x = i - x1;
      obj.$value = value(i + r);
      const v = color(obj);
      pix[k + 0] = v.r;
      pix[k + 1] = v.g;
      pix[k + 2] = v.b;
      pix[k + 3] = ~~(255 * opacity(obj));
    }
  }
  ctx.putImageData(img, 0, 0);
  return can;
}

/**
 * Maintains a cartographic projection.
 * @constructor
 * @param {object} params - The parameters for this operator.
 */
function standalone_Projection(params) {
  standalone_Transform.call(this, null, params);
  this.modified(true); // always treat as modified
}
standalone_inherits(standalone_Projection, standalone_Transform, {
  transform(_, pulse) {
    let proj = this.value;
    if (!proj || _.modified('type')) {
      this.value = proj = standalone_vega_geo_module_create(_.type);
      standalone_projectionProperties.forEach(prop => {
        if (_[prop] != null) standalone_vega_geo_module_set(proj, prop, _[prop]);
      });
    } else {
      standalone_projectionProperties.forEach(prop => {
        if (_.modified(prop)) standalone_vega_geo_module_set(proj, prop, _[prop]);
      });
    }
    if (_.pointRadius != null) proj.path.pointRadius(_.pointRadius);
    if (_.fit) standalone_vega_geo_module_fit(proj, _);
    return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
  }
});
function standalone_vega_geo_module_fit(proj, _) {
  const data = standalone_collectGeoJSON(_.fit);
  _.extent ? proj.fitExtent(_.extent, data) : _.size ? proj.fitSize(_.size, data) : 0;
}
function standalone_vega_geo_module_create(type) {
  const constructor = standalone_vega_projection_module_projection((type || 'mercator').toLowerCase());
  if (!constructor) standalone_vega_util_module_error('Unrecognized projection type: ' + type);
  return constructor();
}
function standalone_vega_geo_module_set(proj, key, value) {
  if (standalone_vega_util_module_isFunction(proj[key])) proj[key](value);
}
function standalone_collectGeoJSON(data) {
  data = standalone_array(data);
  return data.length === 1 ? data[0] : {
    type: standalone_FeatureCollection,
    features: data.reduce((a, f) => a.concat(standalone_featurize(f)), [])
  };
}
function standalone_featurize(f) {
  return f.type === standalone_FeatureCollection ? f.features : standalone_array(f).filter(d => d != null).map(d => d.type === standalone_Feature ? d : {
    type: standalone_Feature,
    geometry: d
  });
}



;// ../../node_modules/d3-force/src/center.js
/* harmony default export */ function standalone_center(x, y) {
  var nodes, strength = 1;

  if (x == null) x = 0;
  if (y == null) y = 0;

  function force() {
    var i,
        n = nodes.length,
        node,
        sx = 0,
        sy = 0;

    for (i = 0; i < n; ++i) {
      node = nodes[i], sx += node.x, sy += node.y;
    }

    for (sx = (sx / n - x) * strength, sy = (sy / n - y) * strength, i = 0; i < n; ++i) {
      node = nodes[i], node.x -= sx, node.y -= sy;
    }
  }

  force.initialize = function(_) {
    nodes = _;
  };

  force.x = function(_) {
    return arguments.length ? (x = +_, force) : x;
  };

  force.y = function(_) {
    return arguments.length ? (y = +_, force) : y;
  };

  force.strength = function(_) {
    return arguments.length ? (strength = +_, force) : strength;
  };

  return force;
}

;// ../../node_modules/d3-quadtree/src/add.js
/* harmony default export */ function standalone_src_add(d) {
  const x = +this._x.call(null, d),
      y = +this._y.call(null, d);
  return standalone_add_add(this.cover(x, y), x, y, d);
}

function standalone_add_add(tree, x, y, d) {
  if (isNaN(x) || isNaN(y)) return tree; // ignore invalid points

  var parent,
      node = tree._root,
      leaf = {data: d},
      x0 = tree._x0,
      y0 = tree._y0,
      x1 = tree._x1,
      y1 = tree._y1,
      xm,
      ym,
      xp,
      yp,
      right,
      bottom,
      i,
      j;

  // If the tree is empty, initialize the root as a leaf.
  if (!node) return tree._root = leaf, tree;

  // Find the existing leaf for the new point, or add it.
  while (node.length) {
    if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
    if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
    if (parent = node, !(node = node[i = bottom << 1 | right])) return parent[i] = leaf, tree;
  }

  // Is the new point is exactly coincident with the existing point?
  xp = +tree._x.call(null, node.data);
  yp = +tree._y.call(null, node.data);
  if (x === xp && y === yp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree;

  // Otherwise, split the leaf node until the old and new point are separated.
  do {
    parent = parent ? parent[i] = new Array(4) : tree._root = new Array(4);
    if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
    if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  } while ((i = bottom << 1 | right) === (j = (yp >= ym) << 1 | (xp >= xm)));
  return parent[j] = node, parent[i] = leaf, tree;
}

function standalone_addAll(data) {
  var d, i, n = data.length,
      x,
      y,
      xz = new Array(n),
      yz = new Array(n),
      x0 = Infinity,
      y0 = Infinity,
      x1 = -Infinity,
      y1 = -Infinity;

  // Compute the points and their extent.
  for (i = 0; i < n; ++i) {
    if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) continue;
    xz[i] = x;
    yz[i] = y;
    if (x < x0) x0 = x;
    if (x > x1) x1 = x;
    if (y < y0) y0 = y;
    if (y > y1) y1 = y;
  }

  // If there were no (valid) points, abort.
  if (x0 > x1 || y0 > y1) return this;

  // Expand the tree to cover the new points.
  this.cover(x0, y0).cover(x1, y1);

  // Add the new points.
  for (i = 0; i < n; ++i) {
    standalone_add_add(this, xz[i], yz[i], data[i]);
  }

  return this;
}

;// ../../node_modules/d3-quadtree/src/cover.js
/* harmony default export */ function standalone_cover(x, y) {
  if (isNaN(x = +x) || isNaN(y = +y)) return this; // ignore invalid points

  var x0 = this._x0,
      y0 = this._y0,
      x1 = this._x1,
      y1 = this._y1;

  // If the quadtree has no extent, initialize them.
  // Integer extent are necessary so that if we later double the extent,
  // the existing quadrant boundaries don’t change due to floating point error!
  if (isNaN(x0)) {
    x1 = (x0 = Math.floor(x)) + 1;
    y1 = (y0 = Math.floor(y)) + 1;
  }

  // Otherwise, double repeatedly to cover.
  else {
    var z = x1 - x0 || 1,
        node = this._root,
        parent,
        i;

    while (x0 > x || x >= x1 || y0 > y || y >= y1) {
      i = (y < y0) << 1 | (x < x0);
      parent = new Array(4), parent[i] = node, node = parent, z *= 2;
      switch (i) {
        case 0: x1 = x0 + z, y1 = y0 + z; break;
        case 1: x0 = x1 - z, y1 = y0 + z; break;
        case 2: x1 = x0 + z, y0 = y1 - z; break;
        case 3: x0 = x1 - z, y0 = y1 - z; break;
      }
    }

    if (this._root && this._root.length) this._root = node;
  }

  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  return this;
}

;// ../../node_modules/d3-quadtree/src/data.js
/* harmony default export */ function standalone_data() {
  var data = [];
  this.visit(function(node) {
    if (!node.length) do data.push(node.data); while (node = node.next)
  });
  return data;
}

;// ../../node_modules/d3-quadtree/src/extent.js
/* harmony default export */ function standalone_src_extent(_) {
  return arguments.length
      ? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1])
      : isNaN(this._x0) ? undefined : [[this._x0, this._y0], [this._x1, this._y1]];
}

;// ../../node_modules/d3-quadtree/src/quad.js
/* harmony default export */ function standalone_src_quad(node, x0, y0, x1, y1) {
  this.node = node;
  this.x0 = x0;
  this.y0 = y0;
  this.x1 = x1;
  this.y1 = y1;
}

;// ../../node_modules/d3-quadtree/src/find.js


/* harmony default export */ function standalone_src_find(x, y, radius) {
  var data,
      x0 = this._x0,
      y0 = this._y0,
      x1,
      y1,
      x2,
      y2,
      x3 = this._x1,
      y3 = this._y1,
      quads = [],
      node = this._root,
      q,
      i;

  if (node) quads.push(new standalone_src_quad(node, x0, y0, x3, y3));
  if (radius == null) radius = Infinity;
  else {
    x0 = x - radius, y0 = y - radius;
    x3 = x + radius, y3 = y + radius;
    radius *= radius;
  }

  while (q = quads.pop()) {

    // Stop searching if this quadrant can’t contain a closer node.
    if (!(node = q.node)
        || (x1 = q.x0) > x3
        || (y1 = q.y0) > y3
        || (x2 = q.x1) < x0
        || (y2 = q.y1) < y0) continue;

    // Bisect the current quadrant.
    if (node.length) {
      var xm = (x1 + x2) / 2,
          ym = (y1 + y2) / 2;

      quads.push(
        new standalone_src_quad(node[3], xm, ym, x2, y2),
        new standalone_src_quad(node[2], x1, ym, xm, y2),
        new standalone_src_quad(node[1], xm, y1, x2, ym),
        new standalone_src_quad(node[0], x1, y1, xm, ym)
      );

      // Visit the closest quadrant first.
      if (i = (y >= ym) << 1 | (x >= xm)) {
        q = quads[quads.length - 1];
        quads[quads.length - 1] = quads[quads.length - 1 - i];
        quads[quads.length - 1 - i] = q;
      }
    }

    // Visit this point. (Visiting coincident points isn’t necessary!)
    else {
      var dx = x - +this._x.call(null, node.data),
          dy = y - +this._y.call(null, node.data),
          d2 = dx * dx + dy * dy;
      if (d2 < radius) {
        var d = Math.sqrt(radius = d2);
        x0 = x - d, y0 = y - d;
        x3 = x + d, y3 = y + d;
        data = node.data;
      }
    }
  }

  return data;
}

;// ../../node_modules/d3-quadtree/src/remove.js
/* harmony default export */ function standalone_remove(d) {
  if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this; // ignore invalid points

  var parent,
      node = this._root,
      retainer,
      previous,
      next,
      x0 = this._x0,
      y0 = this._y0,
      x1 = this._x1,
      y1 = this._y1,
      x,
      y,
      xm,
      ym,
      right,
      bottom,
      i,
      j;

  // If the tree is empty, initialize the root as a leaf.
  if (!node) return this;

  // Find the leaf node for the point.
  // While descending, also retain the deepest parent with a non-removed sibling.
  if (node.length) while (true) {
    if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
    if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
    if (!(parent = node, node = node[i = bottom << 1 | right])) return this;
    if (!node.length) break;
    if (parent[(i + 1) & 3] || parent[(i + 2) & 3] || parent[(i + 3) & 3]) retainer = parent, j = i;
  }

  // Find the point to remove.
  while (node.data !== d) if (!(previous = node, node = node.next)) return this;
  if (next = node.next) delete node.next;

  // If there are multiple coincident points, remove just the point.
  if (previous) return (next ? previous.next = next : delete previous.next), this;

  // If this is the root point, remove it.
  if (!parent) return this._root = next, this;

  // Remove this leaf.
  next ? parent[i] = next : delete parent[i];

  // If the parent now contains exactly one leaf, collapse superfluous parents.
  if ((node = parent[0] || parent[1] || parent[2] || parent[3])
      && node === (parent[3] || parent[2] || parent[1] || parent[0])
      && !node.length) {
    if (retainer) retainer[j] = node;
    else this._root = node;
  }

  return this;
}

function standalone_removeAll(data) {
  for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]);
  return this;
}

;// ../../node_modules/d3-quadtree/src/root.js
/* harmony default export */ function standalone_root() {
  return this._root;
}

;// ../../node_modules/d3-quadtree/src/size.js
/* harmony default export */ function standalone_size() {
  var size = 0;
  this.visit(function(node) {
    if (!node.length) do ++size; while (node = node.next)
  });
  return size;
}

;// ../../node_modules/d3-quadtree/src/visit.js


/* harmony default export */ function standalone_src_visit(callback) {
  var quads = [], q, node = this._root, child, x0, y0, x1, y1;
  if (node) quads.push(new standalone_src_quad(node, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
      var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child = node[3]) quads.push(new standalone_src_quad(child, xm, ym, x1, y1));
      if (child = node[2]) quads.push(new standalone_src_quad(child, x0, ym, xm, y1));
      if (child = node[1]) quads.push(new standalone_src_quad(child, xm, y0, x1, ym));
      if (child = node[0]) quads.push(new standalone_src_quad(child, x0, y0, xm, ym));
    }
  }
  return this;
}

;// ../../node_modules/d3-quadtree/src/visitAfter.js


/* harmony default export */ function standalone_visitAfter(callback) {
  var quads = [], next = [], q;
  if (this._root) quads.push(new standalone_src_quad(this._root, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    var node = q.node;
    if (node.length) {
      var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child = node[0]) quads.push(new standalone_src_quad(child, x0, y0, xm, ym));
      if (child = node[1]) quads.push(new standalone_src_quad(child, xm, y0, x1, ym));
      if (child = node[2]) quads.push(new standalone_src_quad(child, x0, ym, xm, y1));
      if (child = node[3]) quads.push(new standalone_src_quad(child, xm, ym, x1, y1));
    }
    next.push(q);
  }
  while (q = next.pop()) {
    callback(q.node, q.x0, q.y0, q.x1, q.y1);
  }
  return this;
}

;// ../../node_modules/d3-quadtree/src/x.js
function standalone_defaultX(d) {
  return d[0];
}

/* harmony default export */ function standalone_src_x(_) {
  return arguments.length ? (this._x = _, this) : this._x;
}

;// ../../node_modules/d3-quadtree/src/y.js
function standalone_defaultY(d) {
  return d[1];
}

/* harmony default export */ function standalone_src_y(_) {
  return arguments.length ? (this._y = _, this) : this._y;
}

;// ../../node_modules/d3-quadtree/src/quadtree.js













function standalone_quadtree(nodes, x, y) {
  var tree = new standalone_Quadtree(x == null ? standalone_defaultX : x, y == null ? standalone_defaultY : y, NaN, NaN, NaN, NaN);
  return nodes == null ? tree : tree.addAll(nodes);
}

function standalone_Quadtree(x, y, x0, y0, x1, y1) {
  this._x = x;
  this._y = y;
  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  this._root = undefined;
}

function standalone_leaf_copy(leaf) {
  var copy = {data: leaf.data}, next = copy;
  while (leaf = leaf.next) next = next.next = {data: leaf.data};
  return copy;
}

var standalone_treeProto = standalone_quadtree.prototype = standalone_Quadtree.prototype;

standalone_treeProto.copy = function() {
  var copy = new standalone_Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1),
      node = this._root,
      nodes,
      child;

  if (!node) return copy;

  if (!node.length) return copy._root = standalone_leaf_copy(node), copy;

  nodes = [{source: node, target: copy._root = new Array(4)}];
  while (node = nodes.pop()) {
    for (var i = 0; i < 4; ++i) {
      if (child = node.source[i]) {
        if (child.length) nodes.push({source: child, target: node.target[i] = new Array(4)});
        else node.target[i] = standalone_leaf_copy(child);
      }
    }
  }

  return copy;
};

standalone_treeProto.add = standalone_src_add;
standalone_treeProto.addAll = standalone_addAll;
standalone_treeProto.cover = standalone_cover;
standalone_treeProto.data = standalone_data;
standalone_treeProto.extent = standalone_src_extent;
standalone_treeProto.find = standalone_src_find;
standalone_treeProto.remove = standalone_remove;
standalone_treeProto.removeAll = standalone_removeAll;
standalone_treeProto.root = standalone_root;
standalone_treeProto.size = standalone_size;
standalone_treeProto.visit = standalone_src_visit;
standalone_treeProto.visitAfter = standalone_visitAfter;
standalone_treeProto.x = standalone_src_x;
standalone_treeProto.y = standalone_src_y;

;// ../../node_modules/d3-force/src/constant.js
/* harmony default export */ function standalone_d3_force_src_constant(x) {
  return function() {
    return x;
  };
}

;// ../../node_modules/d3-force/src/jiggle.js
/* harmony default export */ function standalone_jiggle(random) {
  return (random() - 0.5) * 1e-6;
}

;// ../../node_modules/d3-force/src/collide.js




function standalone_collide_x(d) {
  return d.x + d.vx;
}

function standalone_collide_y(d) {
  return d.y + d.vy;
}

/* harmony default export */ function standalone_collide(radius) {
  var nodes,
      radii,
      random,
      strength = 1,
      iterations = 1;

  if (typeof radius !== "function") radius = standalone_d3_force_src_constant(radius == null ? 1 : +radius);

  function force() {
    var i, n = nodes.length,
        tree,
        node,
        xi,
        yi,
        ri,
        ri2;

    for (var k = 0; k < iterations; ++k) {
      tree = standalone_quadtree(nodes, standalone_collide_x, standalone_collide_y).visitAfter(prepare);
      for (i = 0; i < n; ++i) {
        node = nodes[i];
        ri = radii[node.index], ri2 = ri * ri;
        xi = node.x + node.vx;
        yi = node.y + node.vy;
        tree.visit(apply);
      }
    }

    function apply(quad, x0, y0, x1, y1) {
      var data = quad.data, rj = quad.r, r = ri + rj;
      if (data) {
        if (data.index > node.index) {
          var x = xi - data.x - data.vx,
              y = yi - data.y - data.vy,
              l = x * x + y * y;
          if (l < r * r) {
            if (x === 0) x = standalone_jiggle(random), l += x * x;
            if (y === 0) y = standalone_jiggle(random), l += y * y;
            l = (r - (l = Math.sqrt(l))) / l * strength;
            node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj));
            node.vy += (y *= l) * r;
            data.vx -= x * (r = 1 - r);
            data.vy -= y * r;
          }
        }
        return;
      }
      return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r;
    }
  }

  function prepare(quad) {
    if (quad.data) return quad.r = radii[quad.data.index];
    for (var i = quad.r = 0; i < 4; ++i) {
      if (quad[i] && quad[i].r > quad.r) {
        quad.r = quad[i].r;
      }
    }
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length, node;
    radii = new Array(n);
    for (i = 0; i < n; ++i) node = nodes[i], radii[node.index] = +radius(node, i, nodes);
  }

  force.initialize = function(_nodes, _random) {
    nodes = _nodes;
    random = _random;
    initialize();
  };

  force.iterations = function(_) {
    return arguments.length ? (iterations = +_, force) : iterations;
  };

  force.strength = function(_) {
    return arguments.length ? (strength = +_, force) : strength;
  };

  force.radius = function(_) {
    return arguments.length ? (radius = typeof _ === "function" ? _ : standalone_d3_force_src_constant(+_), initialize(), force) : radius;
  };

  return force;
}

;// ../../node_modules/d3-dispatch/src/dispatch.js
var standalone_dispatch_noop = {value: () => {}};

function standalone_dispatch_dispatch() {
  for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {
    if (!(t = arguments[i] + "") || (t in _) || /[\s.]/.test(t)) throw new Error("illegal type: " + t);
    _[t] = [];
  }
  return new standalone_Dispatch(_);
}

function standalone_Dispatch(_) {
  this._ = _;
}

function standalone_parseTypenames(typenames, types) {
  return typenames.trim().split(/^|\s+/).map(function(t) {
    var name = "", i = t.indexOf(".");
    if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
    if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t);
    return {type: t, name: name};
  });
}

standalone_Dispatch.prototype = standalone_dispatch_dispatch.prototype = {
  constructor: standalone_Dispatch,
  on: function(typename, callback) {
    var _ = this._,
        T = standalone_parseTypenames(typename + "", _),
        t,
        i = -1,
        n = T.length;

    // If no callback was specified, return the callback of the given type and name.
    if (arguments.length < 2) {
      while (++i < n) if ((t = (typename = T[i]).type) && (t = standalone_dispatch_get(_[t], typename.name))) return t;
      return;
    }

    // If a type was specified, set the callback for the given type and name.
    // Otherwise, if a null callback was specified, remove callbacks of the given name.
    if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
    while (++i < n) {
      if (t = (typename = T[i]).type) _[t] = standalone_dispatch_set(_[t], typename.name, callback);
      else if (callback == null) for (t in _) _[t] = standalone_dispatch_set(_[t], typename.name, null);
    }

    return this;
  },
  copy: function() {
    var copy = {}, _ = this._;
    for (var t in _) copy[t] = _[t].slice();
    return new standalone_Dispatch(copy);
  },
  call: function(type, that) {
    if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2];
    if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
    for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  },
  apply: function(type, that, args) {
    if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
    for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  }
};

function standalone_dispatch_get(type, name) {
  for (var i = 0, n = type.length, c; i < n; ++i) {
    if ((c = type[i]).name === name) {
      return c.value;
    }
  }
}

function standalone_dispatch_set(type, name, callback) {
  for (var i = 0, n = type.length; i < n; ++i) {
    if (type[i].name === name) {
      type[i] = standalone_dispatch_noop, type = type.slice(0, i).concat(type.slice(i + 1));
      break;
    }
  }
  if (callback != null) type.push({name: name, value: callback});
  return type;
}

/* harmony default export */ const standalone_src_dispatch = (standalone_dispatch_dispatch);

;// ../../node_modules/d3-timer/src/timer.js
var standalone_timer_frame = 0, // is an animation frame pending?
    standalone_timeout = 0, // is a timeout pending?
    standalone_interval = 0, // are any timers active?
    standalone_pokeDelay = 1000, // how frequently we check for clock skew
    standalone_taskHead,
    standalone_taskTail,
    standalone_clockLast = 0,
    standalone_clockNow = 0,
    standalone_clockSkew = 0,
    standalone_clock = typeof performance === "object" && performance.now ? performance : Date,
    standalone_setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) { setTimeout(f, 17); };

function standalone_timer_now() {
  return standalone_clockNow || (standalone_setFrame(standalone_clearNow), standalone_clockNow = standalone_clock.now() + standalone_clockSkew);
}

function standalone_clearNow() {
  standalone_clockNow = 0;
}

function standalone_Timer() {
  this._call =
  this._time =
  this._next = null;
}

standalone_Timer.prototype = standalone_timer.prototype = {
  constructor: standalone_Timer,
  restart: function(callback, delay, time) {
    if (typeof callback !== "function") throw new TypeError("callback is not a function");
    time = (time == null ? standalone_timer_now() : +time) + (delay == null ? 0 : +delay);
    if (!this._next && standalone_taskTail !== this) {
      if (standalone_taskTail) standalone_taskTail._next = this;
      else standalone_taskHead = this;
      standalone_taskTail = this;
    }
    this._call = callback;
    this._time = time;
    standalone_sleep();
  },
  stop: function() {
    if (this._call) {
      this._call = null;
      this._time = Infinity;
      standalone_sleep();
    }
  }
};

function standalone_timer(callback, delay, time) {
  var t = new standalone_Timer;
  t.restart(callback, delay, time);
  return t;
}

function standalone_timerFlush() {
  standalone_timer_now(); // Get the current time, if not already set.
  ++standalone_timer_frame; // Pretend we’ve set an alarm, if we haven’t already.
  var t = standalone_taskHead, e;
  while (t) {
    if ((e = standalone_clockNow - t._time) >= 0) t._call.call(undefined, e);
    t = t._next;
  }
  --standalone_timer_frame;
}

function standalone_wake() {
  standalone_clockNow = (standalone_clockLast = standalone_clock.now()) + standalone_clockSkew;
  standalone_timer_frame = standalone_timeout = 0;
  try {
    standalone_timerFlush();
  } finally {
    standalone_timer_frame = 0;
    standalone_nap();
    standalone_clockNow = 0;
  }
}

function standalone_poke() {
  var now = standalone_clock.now(), delay = now - standalone_clockLast;
  if (delay > standalone_pokeDelay) standalone_clockSkew -= delay, standalone_clockLast = now;
}

function standalone_nap() {
  var t0, t1 = standalone_taskHead, t2, time = Infinity;
  while (t1) {
    if (t1._call) {
      if (time > t1._time) time = t1._time;
      t0 = t1, t1 = t1._next;
    } else {
      t2 = t1._next, t1._next = null;
      t1 = t0 ? t0._next = t2 : standalone_taskHead = t2;
    }
  }
  standalone_taskTail = t0;
  standalone_sleep(time);
}

function standalone_sleep(time) {
  if (standalone_timer_frame) return; // Soonest alarm already set, or will be.
  if (standalone_timeout) standalone_timeout = clearTimeout(standalone_timeout);
  var delay = time - standalone_clockNow; // Strictly less than if we recomputed clockNow.
  if (delay > 24) {
    if (time < Infinity) standalone_timeout = setTimeout(standalone_wake, time - standalone_clock.now() - standalone_clockSkew);
    if (standalone_interval) standalone_interval = clearInterval(standalone_interval);
  } else {
    if (!standalone_interval) standalone_clockLast = standalone_clock.now(), standalone_interval = setInterval(standalone_poke, standalone_pokeDelay);
    standalone_timer_frame = 1, standalone_setFrame(standalone_wake);
  }
}

;// ../../node_modules/d3-force/src/lcg.js
// https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
const standalone_lcg_a = 1664525;
const standalone_lcg_c = 1013904223;
const standalone_m = 4294967296; // 2^32

/* harmony default export */ function standalone_src_lcg() {
  let s = 1;
  return () => (s = (standalone_lcg_a * s + standalone_lcg_c) % standalone_m) / standalone_m;
}

;// ../../node_modules/d3-force/src/simulation.js




function standalone_simulation_x(d) {
  return d.x;
}

function standalone_simulation_y(d) {
  return d.y;
}

var standalone_initialRadius = 10,
    standalone_initialAngle = Math.PI * (3 - Math.sqrt(5));

/* harmony default export */ function standalone_simulation(nodes) {
  var simulation,
      alpha = 1,
      alphaMin = 0.001,
      alphaDecay = 1 - Math.pow(alphaMin, 1 / 300),
      alphaTarget = 0,
      velocityDecay = 0.6,
      forces = new Map(),
      stepper = standalone_timer(step),
      event = standalone_src_dispatch("tick", "end"),
      random = standalone_src_lcg();

  if (nodes == null) nodes = [];

  function step() {
    tick();
    event.call("tick", simulation);
    if (alpha < alphaMin) {
      stepper.stop();
      event.call("end", simulation);
    }
  }

  function tick(iterations) {
    var i, n = nodes.length, node;

    if (iterations === undefined) iterations = 1;

    for (var k = 0; k < iterations; ++k) {
      alpha += (alphaTarget - alpha) * alphaDecay;

      forces.forEach(function(force) {
        force(alpha);
      });

      for (i = 0; i < n; ++i) {
        node = nodes[i];
        if (node.fx == null) node.x += node.vx *= velocityDecay;
        else node.x = node.fx, node.vx = 0;
        if (node.fy == null) node.y += node.vy *= velocityDecay;
        else node.y = node.fy, node.vy = 0;
      }
    }

    return simulation;
  }

  function initializeNodes() {
    for (var i = 0, n = nodes.length, node; i < n; ++i) {
      node = nodes[i], node.index = i;
      if (node.fx != null) node.x = node.fx;
      if (node.fy != null) node.y = node.fy;
      if (isNaN(node.x) || isNaN(node.y)) {
        var radius = standalone_initialRadius * Math.sqrt(0.5 + i), angle = i * standalone_initialAngle;
        node.x = radius * Math.cos(angle);
        node.y = radius * Math.sin(angle);
      }
      if (isNaN(node.vx) || isNaN(node.vy)) {
        node.vx = node.vy = 0;
      }
    }
  }

  function initializeForce(force) {
    if (force.initialize) force.initialize(nodes, random);
    return force;
  }

  initializeNodes();

  return simulation = {
    tick: tick,

    restart: function() {
      return stepper.restart(step), simulation;
    },

    stop: function() {
      return stepper.stop(), simulation;
    },

    nodes: function(_) {
      return arguments.length ? (nodes = _, initializeNodes(), forces.forEach(initializeForce), simulation) : nodes;
    },

    alpha: function(_) {
      return arguments.length ? (alpha = +_, simulation) : alpha;
    },

    alphaMin: function(_) {
      return arguments.length ? (alphaMin = +_, simulation) : alphaMin;
    },

    alphaDecay: function(_) {
      return arguments.length ? (alphaDecay = +_, simulation) : +alphaDecay;
    },

    alphaTarget: function(_) {
      return arguments.length ? (alphaTarget = +_, simulation) : alphaTarget;
    },

    velocityDecay: function(_) {
      return arguments.length ? (velocityDecay = 1 - _, simulation) : 1 - velocityDecay;
    },

    randomSource: function(_) {
      return arguments.length ? (random = _, forces.forEach(initializeForce), simulation) : random;
    },

    force: function(name, _) {
      return arguments.length > 1 ? ((_ == null ? forces.delete(name) : forces.set(name, initializeForce(_))), simulation) : forces.get(name);
    },

    find: function(x, y, radius) {
      var i = 0,
          n = nodes.length,
          dx,
          dy,
          d2,
          node,
          closest;

      if (radius == null) radius = Infinity;
      else radius *= radius;

      for (i = 0; i < n; ++i) {
        node = nodes[i];
        dx = x - node.x;
        dy = y - node.y;
        d2 = dx * dx + dy * dy;
        if (d2 < radius) closest = node, radius = d2;
      }

      return closest;
    },

    on: function(name, _) {
      return arguments.length > 1 ? (event.on(name, _), simulation) : event.on(name);
    }
  };
}

;// ../../node_modules/d3-force/src/manyBody.js





/* harmony default export */ function standalone_manyBody() {
  var nodes,
      node,
      random,
      alpha,
      strength = standalone_d3_force_src_constant(-30),
      strengths,
      distanceMin2 = 1,
      distanceMax2 = Infinity,
      theta2 = 0.81;

  function force(_) {
    var i, n = nodes.length, tree = standalone_quadtree(nodes, standalone_simulation_x, standalone_simulation_y).visitAfter(accumulate);
    for (alpha = _, i = 0; i < n; ++i) node = nodes[i], tree.visit(apply);
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length, node;
    strengths = new Array(n);
    for (i = 0; i < n; ++i) node = nodes[i], strengths[node.index] = +strength(node, i, nodes);
  }

  function accumulate(quad) {
    var strength = 0, q, c, weight = 0, x, y, i;

    // For internal nodes, accumulate forces from child quadrants.
    if (quad.length) {
      for (x = y = i = 0; i < 4; ++i) {
        if ((q = quad[i]) && (c = Math.abs(q.value))) {
          strength += q.value, weight += c, x += c * q.x, y += c * q.y;
        }
      }
      quad.x = x / weight;
      quad.y = y / weight;
    }

    // For leaf nodes, accumulate forces from coincident quadrants.
    else {
      q = quad;
      q.x = q.data.x;
      q.y = q.data.y;
      do strength += strengths[q.data.index];
      while (q = q.next);
    }

    quad.value = strength;
  }

  function apply(quad, x1, _, x2) {
    if (!quad.value) return true;

    var x = quad.x - node.x,
        y = quad.y - node.y,
        w = x2 - x1,
        l = x * x + y * y;

    // Apply the Barnes-Hut approximation if possible.
    // Limit forces for very close nodes; randomize direction if coincident.
    if (w * w / theta2 < l) {
      if (l < distanceMax2) {
        if (x === 0) x = standalone_jiggle(random), l += x * x;
        if (y === 0) y = standalone_jiggle(random), l += y * y;
        if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
        node.vx += x * quad.value * alpha / l;
        node.vy += y * quad.value * alpha / l;
      }
      return true;
    }

    // Otherwise, process points directly.
    else if (quad.length || l >= distanceMax2) return;

    // Limit forces for very close nodes; randomize direction if coincident.
    if (quad.data !== node || quad.next) {
      if (x === 0) x = standalone_jiggle(random), l += x * x;
      if (y === 0) y = standalone_jiggle(random), l += y * y;
      if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
    }

    do if (quad.data !== node) {
      w = strengths[quad.data.index] * alpha / l;
      node.vx += x * w;
      node.vy += y * w;
    } while (quad = quad.next);
  }

  force.initialize = function(_nodes, _random) {
    nodes = _nodes;
    random = _random;
    initialize();
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : standalone_d3_force_src_constant(+_), initialize(), force) : strength;
  };

  force.distanceMin = function(_) {
    return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2);
  };

  force.distanceMax = function(_) {
    return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2);
  };

  force.theta = function(_) {
    return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2);
  };

  return force;
}

;// ../../node_modules/d3-force/src/link.js



function standalone_index(d) {
  return d.index;
}

function standalone_link_find(nodeById, nodeId) {
  var node = nodeById.get(nodeId);
  if (!node) throw new Error("node not found: " + nodeId);
  return node;
}

/* harmony default export */ function standalone_src_link(links) {
  var id = standalone_index,
      strength = defaultStrength,
      strengths,
      distance = standalone_d3_force_src_constant(30),
      distances,
      nodes,
      count,
      bias,
      random,
      iterations = 1;

  if (links == null) links = [];

  function defaultStrength(link) {
    return 1 / Math.min(count[link.source.index], count[link.target.index]);
  }

  function force(alpha) {
    for (var k = 0, n = links.length; k < iterations; ++k) {
      for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) {
        link = links[i], source = link.source, target = link.target;
        x = target.x + target.vx - source.x - source.vx || standalone_jiggle(random);
        y = target.y + target.vy - source.y - source.vy || standalone_jiggle(random);
        l = Math.sqrt(x * x + y * y);
        l = (l - distances[i]) / l * alpha * strengths[i];
        x *= l, y *= l;
        target.vx -= x * (b = bias[i]);
        target.vy -= y * b;
        source.vx += x * (b = 1 - b);
        source.vy += y * b;
      }
    }
  }

  function initialize() {
    if (!nodes) return;

    var i,
        n = nodes.length,
        m = links.length,
        nodeById = new Map(nodes.map((d, i) => [id(d, i, nodes), d])),
        link;

    for (i = 0, count = new Array(n); i < m; ++i) {
      link = links[i], link.index = i;
      if (typeof link.source !== "object") link.source = standalone_link_find(nodeById, link.source);
      if (typeof link.target !== "object") link.target = standalone_link_find(nodeById, link.target);
      count[link.source.index] = (count[link.source.index] || 0) + 1;
      count[link.target.index] = (count[link.target.index] || 0) + 1;
    }

    for (i = 0, bias = new Array(m); i < m; ++i) {
      link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);
    }

    strengths = new Array(m), initializeStrength();
    distances = new Array(m), initializeDistance();
  }

  function initializeStrength() {
    if (!nodes) return;

    for (var i = 0, n = links.length; i < n; ++i) {
      strengths[i] = +strength(links[i], i, links);
    }
  }

  function initializeDistance() {
    if (!nodes) return;

    for (var i = 0, n = links.length; i < n; ++i) {
      distances[i] = +distance(links[i], i, links);
    }
  }

  force.initialize = function(_nodes, _random) {
    nodes = _nodes;
    random = _random;
    initialize();
  };

  force.links = function(_) {
    return arguments.length ? (links = _, initialize(), force) : links;
  };

  force.id = function(_) {
    return arguments.length ? (id = _, force) : id;
  };

  force.iterations = function(_) {
    return arguments.length ? (iterations = +_, force) : iterations;
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : standalone_d3_force_src_constant(+_), initializeStrength(), force) : strength;
  };

  force.distance = function(_) {
    return arguments.length ? (distance = typeof _ === "function" ? _ : standalone_d3_force_src_constant(+_), initializeDistance(), force) : distance;
  };

  return force;
}

;// ../../node_modules/d3-force/src/x.js


/* harmony default export */ function standalone_d3_force_src_x(x) {
  var strength = standalone_d3_force_src_constant(0.1),
      nodes,
      strengths,
      xz;

  if (typeof x !== "function") x = standalone_d3_force_src_constant(x == null ? 0 : +x);

  function force(alpha) {
    for (var i = 0, n = nodes.length, node; i < n; ++i) {
      node = nodes[i], node.vx += (xz[i] - node.x) * strengths[i] * alpha;
    }
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length;
    strengths = new Array(n);
    xz = new Array(n);
    for (i = 0; i < n; ++i) {
      strengths[i] = isNaN(xz[i] = +x(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
    }
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : standalone_d3_force_src_constant(+_), initialize(), force) : strength;
  };

  force.x = function(_) {
    return arguments.length ? (x = typeof _ === "function" ? _ : standalone_d3_force_src_constant(+_), initialize(), force) : x;
  };

  return force;
}

;// ../../node_modules/d3-force/src/y.js


/* harmony default export */ function standalone_d3_force_src_y(y) {
  var strength = standalone_d3_force_src_constant(0.1),
      nodes,
      strengths,
      yz;

  if (typeof y !== "function") y = standalone_d3_force_src_constant(y == null ? 0 : +y);

  function force(alpha) {
    for (var i = 0, n = nodes.length, node; i < n; ++i) {
      node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha;
    }
  }

  function initialize() {
    if (!nodes) return;
    var i, n = nodes.length;
    strengths = new Array(n);
    yz = new Array(n);
    for (i = 0; i < n; ++i) {
      strengths[i] = isNaN(yz[i] = +y(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
    }
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : standalone_d3_force_src_constant(+_), initialize(), force) : strength;
  };

  force.y = function(_) {
    return arguments.length ? (y = typeof _ === "function" ? _ : standalone_d3_force_src_constant(+_), initialize(), force) : y;
  };

  return force;
}

;// ../../node_modules/vega-force/build/vega-force.module.js




const standalone_ForceMap = {
  center: standalone_center,
  collide: standalone_collide,
  nbody: standalone_manyBody,
  link: standalone_src_link,
  x: standalone_d3_force_src_x,
  y: standalone_d3_force_src_y
};
const standalone_Forces = 'forces',
  standalone_ForceParams = ['alpha', 'alphaMin', 'alphaTarget', 'velocityDecay', 'forces'],
  standalone_ForceConfig = ['static', 'iterations'],
  standalone_ForceOutput = ['x', 'y', 'vx', 'vy'];

/**
 * Force simulation layout.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<object>} params.forces - The forces to apply.
 */
function standalone_Force(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Force.Definition = {
  'type': 'Force',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'static',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'restart',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'iterations',
    'type': 'number',
    'default': 300
  }, {
    'name': 'alpha',
    'type': 'number',
    'default': 1
  }, {
    'name': 'alphaMin',
    'type': 'number',
    'default': 0.001
  }, {
    'name': 'alphaTarget',
    'type': 'number',
    'default': 0
  }, {
    'name': 'velocityDecay',
    'type': 'number',
    'default': 0.4
  }, {
    'name': 'forces',
    'type': 'param',
    'array': true,
    'params': [{
      'key': {
        'force': 'center'
      },
      'params': [{
        'name': 'x',
        'type': 'number',
        'default': 0
      }, {
        'name': 'y',
        'type': 'number',
        'default': 0
      }]
    }, {
      'key': {
        'force': 'collide'
      },
      'params': [{
        'name': 'radius',
        'type': 'number',
        'expr': true
      }, {
        'name': 'strength',
        'type': 'number',
        'default': 0.7
      }, {
        'name': 'iterations',
        'type': 'number',
        'default': 1
      }]
    }, {
      'key': {
        'force': 'nbody'
      },
      'params': [{
        'name': 'strength',
        'type': 'number',
        'default': -30,
        'expr': true
      }, {
        'name': 'theta',
        'type': 'number',
        'default': 0.9
      }, {
        'name': 'distanceMin',
        'type': 'number',
        'default': 1
      }, {
        'name': 'distanceMax',
        'type': 'number'
      }]
    }, {
      'key': {
        'force': 'link'
      },
      'params': [{
        'name': 'links',
        'type': 'data'
      }, {
        'name': 'id',
        'type': 'field'
      }, {
        'name': 'distance',
        'type': 'number',
        'default': 30,
        'expr': true
      }, {
        'name': 'strength',
        'type': 'number',
        'expr': true
      }, {
        'name': 'iterations',
        'type': 'number',
        'default': 1
      }]
    }, {
      'key': {
        'force': 'x'
      },
      'params': [{
        'name': 'strength',
        'type': 'number',
        'default': 0.1
      }, {
        'name': 'x',
        'type': 'field'
      }]
    }, {
      'key': {
        'force': 'y'
      },
      'params': [{
        'name': 'strength',
        'type': 'number',
        'default': 0.1
      }, {
        'name': 'y',
        'type': 'field'
      }]
    }]
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'modify': false,
    'default': standalone_ForceOutput
  }]
};
standalone_inherits(standalone_Force, standalone_Transform, {
  transform(_, pulse) {
    var sim = this.value,
      change = pulse.changed(pulse.ADD_REM),
      params = _.modified(standalone_ForceParams),
      iters = _.iterations || 300;

    // configure simulation
    if (!sim) {
      this.value = sim = standalone_vega_force_module_simulation(pulse.source, _);
      sim.on('tick', standalone_rerun(pulse.dataflow, this));
      if (!_.static) {
        change = true;
        sim.tick(); // ensure we run on init
      }
      pulse.modifies('index');
    } else {
      if (change) {
        pulse.modifies('index');
        sim.nodes(pulse.source);
      }
      if (params || pulse.changed(pulse.MOD)) {
        standalone_setup(sim, _, 0, pulse);
      }
    }

    // run simulation
    if (params || change || _.modified(standalone_ForceConfig) || pulse.changed() && _.restart) {
      sim.alpha(Math.max(sim.alpha(), _.alpha || 1)).alphaDecay(1 - Math.pow(sim.alphaMin(), 1 / iters));
      if (_.static) {
        for (sim.stop(); --iters >= 0;) sim.tick();
      } else {
        if (sim.stopped()) sim.restart();
        if (!change) return pulse.StopPropagation; // defer to sim ticks
      }
    }
    return this.finish(_, pulse);
  },
  finish(_, pulse) {
    const dataflow = pulse.dataflow;

    // inspect dependencies, touch link source data
    for (let args = this._argops, j = 0, m = args.length, arg; j < m; ++j) {
      arg = args[j];
      if (arg.name !== standalone_Forces || arg.op._argval.force !== 'link') {
        continue;
      }
      for (var ops = arg.op._argops, i = 0, n = ops.length, op; i < n; ++i) {
        if (ops[i].name === 'links' && (op = ops[i].op.source)) {
          dataflow.pulse(op, dataflow.changeset().reflow());
          break;
        }
      }
    }

    // reflow all nodes
    return pulse.reflow(_.modified()).modifies(standalone_ForceOutput);
  }
});
function standalone_rerun(df, op) {
  return () => df.touch(op).run();
}
function standalone_vega_force_module_simulation(nodes, _) {
  const sim = standalone_simulation(nodes),
    stop = sim.stop,
    restart = sim.restart;
  let stopped = false;
  sim.stopped = () => stopped;
  sim.restart = () => (stopped = false, restart());
  sim.stop = () => (stopped = true, stop());
  return standalone_setup(sim, _, true).on('end', () => stopped = true);
}
function standalone_setup(sim, _, init, pulse) {
  var f = standalone_array(_.forces),
    i,
    n,
    p,
    name;
  for (i = 0, n = standalone_ForceParams.length; i < n; ++i) {
    p = standalone_ForceParams[i];
    if (p !== standalone_Forces && _.modified(p)) sim[p](_[p]);
  }
  for (i = 0, n = f.length; i < n; ++i) {
    name = standalone_Forces + i;
    p = init || _.modified(standalone_Forces, i) ? standalone_getForce(f[i]) : pulse && standalone_modified(f[i], pulse) ? sim.force(name) : null;
    if (p) sim.force(name, p);
  }
  for (n = sim.numForces || 0; i < n; ++i) {
    sim.force(standalone_Forces + i, null); // remove
  }
  sim.numForces = f.length;
  return sim;
}
function standalone_modified(f, pulse) {
  var k, v;
  for (k in f) {
    if (standalone_vega_util_module_isFunction(v = f[k]) && pulse.modified(standalone_accessorFields(v))) return 1;
  }
  return 0;
}
function standalone_getForce(_) {
  var f, p;
  if (!standalone_vega_util_module_has(standalone_ForceMap, _.force)) {
    standalone_vega_util_module_error('Unrecognized force: ' + _.force);
  }
  f = standalone_ForceMap[_.force]();
  for (p in _) {
    if (standalone_vega_util_module_isFunction(f[p])) standalone_setForceParam(f[p], _[p], _);
  }
  return f;
}
function standalone_setForceParam(f, v, _) {
  f(standalone_vega_util_module_isFunction(v) ? d => v(d, _) : v);
}



;// ../../node_modules/d3-hierarchy/src/hierarchy/count.js
function standalone_count(node) {
  var sum = 0,
      children = node.children,
      i = children && children.length;
  if (!i) sum = 1;
  else while (--i >= 0) sum += children[i].value;
  node.value = sum;
}

/* harmony default export */ function standalone_hierarchy_count() {
  return this.eachAfter(standalone_count);
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/each.js
/* harmony default export */ function standalone_hierarchy_each(callback, that) {
  let index = -1;
  for (const node of this) {
    callback.call(that, node, ++index, this);
  }
  return this;
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/eachBefore.js
/* harmony default export */ function standalone_eachBefore(callback, that) {
  var node = this, nodes = [node], children, i, index = -1;
  while (node = nodes.pop()) {
    callback.call(that, node, ++index, this);
    if (children = node.children) {
      for (i = children.length - 1; i >= 0; --i) {
        nodes.push(children[i]);
      }
    }
  }
  return this;
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/eachAfter.js
/* harmony default export */ function standalone_eachAfter(callback, that) {
  var node = this, nodes = [node], next = [], children, i, n, index = -1;
  while (node = nodes.pop()) {
    next.push(node);
    if (children = node.children) {
      for (i = 0, n = children.length; i < n; ++i) {
        nodes.push(children[i]);
      }
    }
  }
  while (node = next.pop()) {
    callback.call(that, node, ++index, this);
  }
  return this;
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/find.js
/* harmony default export */ function standalone_hierarchy_find(callback, that) {
  let index = -1;
  for (const node of this) {
    if (callback.call(that, node, ++index, this)) {
      return node;
    }
  }
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/sum.js
/* harmony default export */ function standalone_hierarchy_sum(value) {
  return this.eachAfter(function(node) {
    var sum = +value(node.data) || 0,
        children = node.children,
        i = children && children.length;
    while (--i >= 0) sum += children[i].value;
    node.value = sum;
  });
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/sort.js
/* harmony default export */ function standalone_hierarchy_sort(compare) {
  return this.eachBefore(function(node) {
    if (node.children) {
      node.children.sort(compare);
    }
  });
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/path.js
/* harmony default export */ function standalone_hierarchy_path(end) {
  var start = this,
      ancestor = standalone_leastCommonAncestor(start, end),
      nodes = [start];
  while (start !== ancestor) {
    start = start.parent;
    nodes.push(start);
  }
  var k = nodes.length;
  while (end !== ancestor) {
    nodes.splice(k, 0, end);
    end = end.parent;
  }
  return nodes;
}

function standalone_leastCommonAncestor(a, b) {
  if (a === b) return a;
  var aNodes = a.ancestors(),
      bNodes = b.ancestors(),
      c = null;
  a = aNodes.pop();
  b = bNodes.pop();
  while (a === b) {
    c = a;
    a = aNodes.pop();
    b = bNodes.pop();
  }
  return c;
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/ancestors.js
/* harmony default export */ function standalone_ancestors() {
  var node = this, nodes = [node];
  while (node = node.parent) {
    nodes.push(node);
  }
  return nodes;
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/descendants.js
/* harmony default export */ function standalone_descendants() {
  return Array.from(this);
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/leaves.js
/* harmony default export */ function standalone_leaves() {
  var leaves = [];
  this.eachBefore(function(node) {
    if (!node.children) {
      leaves.push(node);
    }
  });
  return leaves;
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/links.js
/* harmony default export */ function standalone_links() {
  var root = this, links = [];
  root.each(function(node) {
    if (node !== root) { // Don’t include the root’s parent, if any.
      links.push({source: node.parent, target: node});
    }
  });
  return links;
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/iterator.js
/* harmony default export */ function* standalone_iterator() {
  var node = this, current, next = [node], children, i, n;
  do {
    current = next.reverse(), next = [];
    while (node = current.pop()) {
      yield node;
      if (children = node.children) {
        for (i = 0, n = children.length; i < n; ++i) {
          next.push(children[i]);
        }
      }
    }
  } while (next.length);
}

;// ../../node_modules/d3-hierarchy/src/hierarchy/index.js














function standalone_hierarchy(data, children) {
  if (data instanceof Map) {
    data = [undefined, data];
    if (children === undefined) children = standalone_mapChildren;
  } else if (children === undefined) {
    children = standalone_objectChildren;
  }

  var root = new standalone_Node(data),
      node,
      nodes = [root],
      child,
      childs,
      i,
      n;

  while (node = nodes.pop()) {
    if ((childs = children(node.data)) && (n = (childs = Array.from(childs)).length)) {
      node.children = childs;
      for (i = n - 1; i >= 0; --i) {
        nodes.push(child = childs[i] = new standalone_Node(childs[i]));
        child.parent = node;
        child.depth = node.depth + 1;
      }
    }
  }

  return root.eachBefore(standalone_computeHeight);
}

function standalone_node_copy() {
  return standalone_hierarchy(this).eachBefore(standalone_copyData);
}

function standalone_objectChildren(d) {
  return d.children;
}

function standalone_mapChildren(d) {
  return Array.isArray(d) ? d[1] : null;
}

function standalone_copyData(node) {
  if (node.data.value !== undefined) node.value = node.data.value;
  node.data = node.data.data;
}

function standalone_computeHeight(node) {
  var height = 0;
  do node.height = height;
  while ((node = node.parent) && (node.height < ++height));
}

function standalone_Node(data) {
  this.data = data;
  this.depth =
  this.height = 0;
  this.parent = null;
}

standalone_Node.prototype = standalone_hierarchy.prototype = {
  constructor: standalone_Node,
  count: standalone_hierarchy_count,
  each: standalone_hierarchy_each,
  eachAfter: standalone_eachAfter,
  eachBefore: standalone_eachBefore,
  find: standalone_hierarchy_find,
  sum: standalone_hierarchy_sum,
  sort: standalone_hierarchy_sort,
  path: standalone_hierarchy_path,
  ancestors: standalone_ancestors,
  descendants: standalone_descendants,
  leaves: standalone_leaves,
  links: standalone_links,
  copy: standalone_node_copy,
  [Symbol.iterator]: standalone_iterator
};

;// ../../node_modules/d3-hierarchy/src/accessors.js
function standalone_optional(f) {
  return f == null ? null : standalone_required(f);
}

function standalone_required(f) {
  if (typeof f !== "function") throw new Error;
  return f;
}

;// ../../node_modules/d3-hierarchy/src/constant.js
function standalone_constantZero() {
  return 0;
}

/* harmony default export */ function standalone_d3_hierarchy_src_constant(x) {
  return function() {
    return x;
  };
}

;// ../../node_modules/d3-hierarchy/src/lcg.js
// https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
const standalone_src_lcg_a = 1664525;
const standalone_src_lcg_c = 1013904223;
const standalone_lcg_m = 4294967296; // 2^32

/* harmony default export */ function standalone_d3_hierarchy_src_lcg() {
  let s = 1;
  return () => (s = (standalone_src_lcg_a * s + standalone_src_lcg_c) % standalone_lcg_m) / standalone_lcg_m;
}

;// ../../node_modules/d3-hierarchy/src/array.js
/* harmony default export */ function standalone_d3_hierarchy_src_array(x) {
  return typeof x === "object" && "length" in x
    ? x // Array, TypedArray, NodeList, array-like
    : Array.from(x); // Map, Set, iterable, string, or anything else
}

function standalone_shuffle(array, random) {
  let m = array.length,
      t,
      i;

  while (m) {
    i = random() * m-- | 0;
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

;// ../../node_modules/d3-hierarchy/src/pack/enclose.js



/* harmony default export */ function standalone_enclose(circles) {
  return standalone_packEncloseRandom(circles, lcg());
}

function standalone_packEncloseRandom(circles, random) {
  var i = 0, n = (circles = standalone_shuffle(Array.from(circles), random)).length, B = [], p, e;

  while (i < n) {
    p = circles[i];
    if (e && standalone_enclosesWeak(e, p)) ++i;
    else e = standalone_encloseBasis(B = standalone_extendBasis(B, p)), i = 0;
  }

  return e;
}

function standalone_extendBasis(B, p) {
  var i, j;

  if (standalone_enclosesWeakAll(p, B)) return [p];

  // If we get here then B must have at least one element.
  for (i = 0; i < B.length; ++i) {
    if (standalone_enclosesNot(p, B[i])
        && standalone_enclosesWeakAll(standalone_encloseBasis2(B[i], p), B)) {
      return [B[i], p];
    }
  }

  // If we get here then B must have at least two elements.
  for (i = 0; i < B.length - 1; ++i) {
    for (j = i + 1; j < B.length; ++j) {
      if (standalone_enclosesNot(standalone_encloseBasis2(B[i], B[j]), p)
          && standalone_enclosesNot(standalone_encloseBasis2(B[i], p), B[j])
          && standalone_enclosesNot(standalone_encloseBasis2(B[j], p), B[i])
          && standalone_enclosesWeakAll(standalone_encloseBasis3(B[i], B[j], p), B)) {
        return [B[i], B[j], p];
      }
    }
  }

  // If we get here then something is very wrong.
  throw new Error;
}

function standalone_enclosesNot(a, b) {
  var dr = a.r - b.r, dx = b.x - a.x, dy = b.y - a.y;
  return dr < 0 || dr * dr < dx * dx + dy * dy;
}

function standalone_enclosesWeak(a, b) {
  var dr = a.r - b.r + Math.max(a.r, b.r, 1) * 1e-9, dx = b.x - a.x, dy = b.y - a.y;
  return dr > 0 && dr * dr > dx * dx + dy * dy;
}

function standalone_enclosesWeakAll(a, B) {
  for (var i = 0; i < B.length; ++i) {
    if (!standalone_enclosesWeak(a, B[i])) {
      return false;
    }
  }
  return true;
}

function standalone_encloseBasis(B) {
  switch (B.length) {
    case 1: return standalone_encloseBasis1(B[0]);
    case 2: return standalone_encloseBasis2(B[0], B[1]);
    case 3: return standalone_encloseBasis3(B[0], B[1], B[2]);
  }
}

function standalone_encloseBasis1(a) {
  return {
    x: a.x,
    y: a.y,
    r: a.r
  };
}

function standalone_encloseBasis2(a, b) {
  var x1 = a.x, y1 = a.y, r1 = a.r,
      x2 = b.x, y2 = b.y, r2 = b.r,
      x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1,
      l = Math.sqrt(x21 * x21 + y21 * y21);
  return {
    x: (x1 + x2 + x21 / l * r21) / 2,
    y: (y1 + y2 + y21 / l * r21) / 2,
    r: (l + r1 + r2) / 2
  };
}

function standalone_encloseBasis3(a, b, c) {
  var x1 = a.x, y1 = a.y, r1 = a.r,
      x2 = b.x, y2 = b.y, r2 = b.r,
      x3 = c.x, y3 = c.y, r3 = c.r,
      a2 = x1 - x2,
      a3 = x1 - x3,
      b2 = y1 - y2,
      b3 = y1 - y3,
      c2 = r2 - r1,
      c3 = r3 - r1,
      d1 = x1 * x1 + y1 * y1 - r1 * r1,
      d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2,
      d3 = d1 - x3 * x3 - y3 * y3 + r3 * r3,
      ab = a3 * b2 - a2 * b3,
      xa = (b2 * d3 - b3 * d2) / (ab * 2) - x1,
      xb = (b3 * c2 - b2 * c3) / ab,
      ya = (a3 * d2 - a2 * d3) / (ab * 2) - y1,
      yb = (a2 * c3 - a3 * c2) / ab,
      A = xb * xb + yb * yb - 1,
      B = 2 * (r1 + xa * xb + ya * yb),
      C = xa * xa + ya * ya - r1 * r1,
      r = -(Math.abs(A) > 1e-6 ? (B + Math.sqrt(B * B - 4 * A * C)) / (2 * A) : C / B);
  return {
    x: x1 + xa + xb * r,
    y: y1 + ya + yb * r,
    r: r
  };
}

;// ../../node_modules/d3-hierarchy/src/pack/siblings.js




function standalone_place(b, a, c) {
  var dx = b.x - a.x, x, a2,
      dy = b.y - a.y, y, b2,
      d2 = dx * dx + dy * dy;
  if (d2) {
    a2 = a.r + c.r, a2 *= a2;
    b2 = b.r + c.r, b2 *= b2;
    if (a2 > b2) {
      x = (d2 + b2 - a2) / (2 * d2);
      y = Math.sqrt(Math.max(0, b2 / d2 - x * x));
      c.x = b.x - x * dx - y * dy;
      c.y = b.y - x * dy + y * dx;
    } else {
      x = (d2 + a2 - b2) / (2 * d2);
      y = Math.sqrt(Math.max(0, a2 / d2 - x * x));
      c.x = a.x + x * dx - y * dy;
      c.y = a.y + x * dy + y * dx;
    }
  } else {
    c.x = a.x + c.r;
    c.y = a.y;
  }
}

function standalone_intersects(a, b) {
  var dr = a.r + b.r - 1e-6, dx = b.x - a.x, dy = b.y - a.y;
  return dr > 0 && dr * dr > dx * dx + dy * dy;
}

function standalone_score(node) {
  var a = node._,
      b = node.next._,
      ab = a.r + b.r,
      dx = (a.x * b.r + b.x * a.r) / ab,
      dy = (a.y * b.r + b.y * a.r) / ab;
  return dx * dx + dy * dy;
}

function standalone_siblings_Node(circle) {
  this._ = circle;
  this.next = null;
  this.previous = null;
}

function standalone_packSiblingsRandom(circles, random) {
  if (!(n = (circles = standalone_d3_hierarchy_src_array(circles)).length)) return 0;

  var a, b, c, n, aa, ca, i, j, k, sj, sk;

  // Place the first circle.
  a = circles[0], a.x = 0, a.y = 0;
  if (!(n > 1)) return a.r;

  // Place the second circle.
  b = circles[1], a.x = -b.r, b.x = a.r, b.y = 0;
  if (!(n > 2)) return a.r + b.r;

  // Place the third circle.
  standalone_place(b, a, c = circles[2]);

  // Initialize the front-chain using the first three circles a, b and c.
  a = new standalone_siblings_Node(a), b = new standalone_siblings_Node(b), c = new standalone_siblings_Node(c);
  a.next = c.previous = b;
  b.next = a.previous = c;
  c.next = b.previous = a;

  // Attempt to place each remaining circle…
  pack: for (i = 3; i < n; ++i) {
    standalone_place(a._, b._, c = circles[i]), c = new standalone_siblings_Node(c);

    // Find the closest intersecting circle on the front-chain, if any.
    // “Closeness” is determined by linear distance along the front-chain.
    // “Ahead” or “behind” is likewise determined by linear distance.
    j = b.next, k = a.previous, sj = b._.r, sk = a._.r;
    do {
      if (sj <= sk) {
        if (standalone_intersects(j._, c._)) {
          b = j, a.next = b, b.previous = a, --i;
          continue pack;
        }
        sj += j._.r, j = j.next;
      } else {
        if (standalone_intersects(k._, c._)) {
          a = k, a.next = b, b.previous = a, --i;
          continue pack;
        }
        sk += k._.r, k = k.previous;
      }
    } while (j !== k.next);

    // Success! Insert the new circle c between a and b.
    c.previous = a, c.next = b, a.next = b.previous = b = c;

    // Compute the new closest circle pair to the centroid.
    aa = standalone_score(a);
    while ((c = c.next) !== b) {
      if ((ca = standalone_score(c)) < aa) {
        a = c, aa = ca;
      }
    }
    b = a.next;
  }

  // Compute the enclosing circle of the front chain.
  a = [b._], c = b; while ((c = c.next) !== b) a.push(c._); c = standalone_packEncloseRandom(a, random);

  // Translate the circles to put the enclosing circle around the origin.
  for (i = 0; i < n; ++i) a = circles[i], a.x -= c.x, a.y -= c.y;

  return c.r;
}

/* harmony default export */ function standalone_siblings(circles) {
  standalone_packSiblingsRandom(circles, lcg());
  return circles;
}

;// ../../node_modules/d3-hierarchy/src/pack/index.js





function standalone_defaultRadius(d) {
  return Math.sqrt(d.value);
}

/* harmony default export */ function standalone_pack() {
  var radius = null,
      dx = 1,
      dy = 1,
      padding = standalone_constantZero;

  function pack(root) {
    const random = standalone_d3_hierarchy_src_lcg();
    root.x = dx / 2, root.y = dy / 2;
    if (radius) {
      root.eachBefore(standalone_radiusLeaf(radius))
          .eachAfter(standalone_packChildrenRandom(padding, 0.5, random))
          .eachBefore(standalone_translateChild(1));
    } else {
      root.eachBefore(standalone_radiusLeaf(standalone_defaultRadius))
          .eachAfter(standalone_packChildrenRandom(standalone_constantZero, 1, random))
          .eachAfter(standalone_packChildrenRandom(padding, root.r / Math.min(dx, dy), random))
          .eachBefore(standalone_translateChild(Math.min(dx, dy) / (2 * root.r)));
    }
    return root;
  }

  pack.radius = function(x) {
    return arguments.length ? (radius = standalone_optional(x), pack) : radius;
  };

  pack.size = function(x) {
    return arguments.length ? (dx = +x[0], dy = +x[1], pack) : [dx, dy];
  };

  pack.padding = function(x) {
    return arguments.length ? (padding = typeof x === "function" ? x : standalone_d3_hierarchy_src_constant(+x), pack) : padding;
  };

  return pack;
}

function standalone_radiusLeaf(radius) {
  return function(node) {
    if (!node.children) {
      node.r = Math.max(0, +radius(node) || 0);
    }
  };
}

function standalone_packChildrenRandom(padding, k, random) {
  return function(node) {
    if (children = node.children) {
      var children,
          i,
          n = children.length,
          r = padding(node) * k || 0,
          e;

      if (r) for (i = 0; i < n; ++i) children[i].r += r;
      e = standalone_packSiblingsRandom(children, random);
      if (r) for (i = 0; i < n; ++i) children[i].r -= r;
      node.r = e + r;
    }
  };
}

function standalone_translateChild(k) {
  return function(node) {
    var parent = node.parent;
    node.r *= k;
    if (parent) {
      node.x = parent.x + k * node.x;
      node.y = parent.y + k * node.y;
    }
  };
}

;// ../../node_modules/d3-hierarchy/src/treemap/round.js
/* harmony default export */ function standalone_treemap_round(node) {
  node.x0 = Math.round(node.x0);
  node.y0 = Math.round(node.y0);
  node.x1 = Math.round(node.x1);
  node.y1 = Math.round(node.y1);
}

;// ../../node_modules/d3-hierarchy/src/treemap/dice.js
/* harmony default export */ function standalone_dice(parent, x0, y0, x1, y1) {
  var nodes = parent.children,
      node,
      i = -1,
      n = nodes.length,
      k = parent.value && (x1 - x0) / parent.value;

  while (++i < n) {
    node = nodes[i], node.y0 = y0, node.y1 = y1;
    node.x0 = x0, node.x1 = x0 += node.value * k;
  }
}

;// ../../node_modules/d3-hierarchy/src/partition.js



/* harmony default export */ function standalone_src_partition() {
  var dx = 1,
      dy = 1,
      padding = 0,
      round = false;

  function partition(root) {
    var n = root.height + 1;
    root.x0 =
    root.y0 = padding;
    root.x1 = dx;
    root.y1 = dy / n;
    root.eachBefore(positionNode(dy, n));
    if (round) root.eachBefore(standalone_treemap_round);
    return root;
  }

  function positionNode(dy, n) {
    return function(node) {
      if (node.children) {
        standalone_dice(node, node.x0, dy * (node.depth + 1) / n, node.x1, dy * (node.depth + 2) / n);
      }
      var x0 = node.x0,
          y0 = node.y0,
          x1 = node.x1 - padding,
          y1 = node.y1 - padding;
      if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
      if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
      node.x0 = x0;
      node.y0 = y0;
      node.x1 = x1;
      node.y1 = y1;
    };
  }

  partition.round = function(x) {
    return arguments.length ? (round = !!x, partition) : round;
  };

  partition.size = function(x) {
    return arguments.length ? (dx = +x[0], dy = +x[1], partition) : [dx, dy];
  };

  partition.padding = function(x) {
    return arguments.length ? (padding = +x, partition) : padding;
  };

  return partition;
}

;// ../../node_modules/d3-hierarchy/src/stratify.js



var standalone_preroot = {depth: -1},
    standalone_ambiguous = {},
    standalone_imputed = {};

function standalone_defaultId(d) {
  return d.id;
}

function standalone_defaultParentId(d) {
  return d.parentId;
}

/* harmony default export */ function standalone_stratify() {
  var id = standalone_defaultId,
      parentId = standalone_defaultParentId,
      path;

  function stratify(data) {
    var nodes = Array.from(data),
        currentId = id,
        currentParentId = parentId,
        n,
        d,
        i,
        root,
        parent,
        node,
        nodeId,
        nodeKey,
        nodeByKey = new Map;

    if (path != null) {
      const I = nodes.map((d, i) => standalone_stratify_normalize(path(d, i, data)));
      const P = I.map(standalone_parentof);
      const S = new Set(I).add("");
      for (const i of P) {
        if (!S.has(i)) {
          S.add(i);
          I.push(i);
          P.push(standalone_parentof(i));
          nodes.push(standalone_imputed);
        }
      }
      currentId = (_, i) => I[i];
      currentParentId = (_, i) => P[i];
    }

    for (i = 0, n = nodes.length; i < n; ++i) {
      d = nodes[i], node = nodes[i] = new standalone_Node(d);
      if ((nodeId = currentId(d, i, data)) != null && (nodeId += "")) {
        nodeKey = node.id = nodeId;
        nodeByKey.set(nodeKey, nodeByKey.has(nodeKey) ? standalone_ambiguous : node);
      }
      if ((nodeId = currentParentId(d, i, data)) != null && (nodeId += "")) {
        node.parent = nodeId;
      }
    }

    for (i = 0; i < n; ++i) {
      node = nodes[i];
      if (nodeId = node.parent) {
        parent = nodeByKey.get(nodeId);
        if (!parent) throw new Error("missing: " + nodeId);
        if (parent === standalone_ambiguous) throw new Error("ambiguous: " + nodeId);
        if (parent.children) parent.children.push(node);
        else parent.children = [node];
        node.parent = parent;
      } else {
        if (root) throw new Error("multiple roots");
        root = node;
      }
    }

    if (!root) throw new Error("no root");

    // When imputing internal nodes, only introduce roots if needed.
    // Then replace the imputed marker data with null.
    if (path != null) {
      while (root.data === standalone_imputed && root.children.length === 1) {
        root = root.children[0], --n;
      }
      for (let i = nodes.length - 1; i >= 0; --i) {
        node = nodes[i];
        if (node.data !== standalone_imputed) break;
        node.data = null;
      }
    }

    root.parent = standalone_preroot;
    root.eachBefore(function(node) { node.depth = node.parent.depth + 1; --n; }).eachBefore(standalone_computeHeight);
    root.parent = null;
    if (n > 0) throw new Error("cycle");

    return root;
  }

  stratify.id = function(x) {
    return arguments.length ? (id = standalone_optional(x), stratify) : id;
  };

  stratify.parentId = function(x) {
    return arguments.length ? (parentId = standalone_optional(x), stratify) : parentId;
  };

  stratify.path = function(x) {
    return arguments.length ? (path = standalone_optional(x), stratify) : path;
  };

  return stratify;
}

// To normalize a path, we coerce to a string, strip the trailing slash if any
// (as long as the trailing slash is not immediately preceded by another slash),
// and add leading slash if missing.
function standalone_stratify_normalize(path) {
  path = `${path}`;
  let i = path.length;
  if (standalone_slash(path, i - 1) && !standalone_slash(path, i - 2)) path = path.slice(0, -1);
  return path[0] === "/" ? path : `/${path}`;
}

// Walk backwards to find the first slash that is not the leading slash, e.g.:
// "/foo/bar" ⇥ "/foo", "/foo" ⇥ "/", "/" ↦ "". (The root is special-cased
// because the id of the root must be a truthy value.)
function standalone_parentof(path) {
  let i = path.length;
  if (i < 2) return "";
  while (--i > 1) if (standalone_slash(path, i)) break;
  return path.slice(0, i);
}

// Slashes can be escaped; to determine whether a slash is a path delimiter, we
// count the number of preceding backslashes escaping the forward slash: an odd
// number indicates an escaped forward slash.
function standalone_slash(path, i) {
  if (path[i] === "/") {
    let k = 0;
    while (i > 0 && path[--i] === "\\") ++k;
    if ((k & 1) === 0) return true;
  }
  return false;
}

;// ../../node_modules/d3-hierarchy/src/tree.js


function standalone_defaultSeparation(a, b) {
  return a.parent === b.parent ? 1 : 2;
}

// function radialSeparation(a, b) {
//   return (a.parent === b.parent ? 1 : 2) / a.depth;
// }

// This function is used to traverse the left contour of a subtree (or
// subforest). It returns the successor of v on this contour. This successor is
// either given by the leftmost child of v or by the thread of v. The function
// returns null if and only if v is on the highest level of its subtree.
function standalone_nextLeft(v) {
  var children = v.children;
  return children ? children[0] : v.t;
}

// This function works analogously to nextLeft.
function standalone_nextRight(v) {
  var children = v.children;
  return children ? children[children.length - 1] : v.t;
}

// Shifts the current subtree rooted at w+. This is done by increasing
// prelim(w+) and mod(w+) by shift.
function standalone_moveSubtree(wm, wp, shift) {
  var change = shift / (wp.i - wm.i);
  wp.c -= change;
  wp.s += shift;
  wm.c += change;
  wp.z += shift;
  wp.m += shift;
}

// All other shifts, applied to the smaller subtrees between w- and w+, are
// performed by this function. To prepare the shifts, we have to adjust
// change(w+), shift(w+), and change(w-).
function standalone_executeShifts(v) {
  var shift = 0,
      change = 0,
      children = v.children,
      i = children.length,
      w;
  while (--i >= 0) {
    w = children[i];
    w.z += shift;
    w.m += shift;
    shift += w.s + (change += w.c);
  }
}

// If vi-’s ancestor is a sibling of v, returns vi-’s ancestor. Otherwise,
// returns the specified (default) ancestor.
function standalone_nextAncestor(vim, v, ancestor) {
  return vim.a.parent === v.parent ? vim.a : ancestor;
}

function standalone_TreeNode(node, i) {
  this._ = node;
  this.parent = null;
  this.children = null;
  this.A = null; // default ancestor
  this.a = this; // ancestor
  this.z = 0; // prelim
  this.m = 0; // mod
  this.c = 0; // change
  this.s = 0; // shift
  this.t = null; // thread
  this.i = i; // number
}

standalone_TreeNode.prototype = Object.create(standalone_Node.prototype);

function standalone_treeRoot(root) {
  var tree = new standalone_TreeNode(root, 0),
      node,
      nodes = [tree],
      child,
      children,
      i,
      n;

  while (node = nodes.pop()) {
    if (children = node._.children) {
      node.children = new Array(n = children.length);
      for (i = n - 1; i >= 0; --i) {
        nodes.push(child = node.children[i] = new standalone_TreeNode(children[i], i));
        child.parent = node;
      }
    }
  }

  (tree.parent = new standalone_TreeNode(null, 0)).children = [tree];
  return tree;
}

// Node-link tree diagram using the Reingold-Tilford "tidy" algorithm
/* harmony default export */ function standalone_tree() {
  var separation = standalone_defaultSeparation,
      dx = 1,
      dy = 1,
      nodeSize = null;

  function tree(root) {
    var t = standalone_treeRoot(root);

    // Compute the layout using Buchheim et al.’s algorithm.
    t.eachAfter(firstWalk), t.parent.m = -t.z;
    t.eachBefore(secondWalk);

    // If a fixed node size is specified, scale x and y.
    if (nodeSize) root.eachBefore(sizeNode);

    // If a fixed tree size is specified, scale x and y based on the extent.
    // Compute the left-most, right-most, and depth-most nodes for extents.
    else {
      var left = root,
          right = root,
          bottom = root;
      root.eachBefore(function(node) {
        if (node.x < left.x) left = node;
        if (node.x > right.x) right = node;
        if (node.depth > bottom.depth) bottom = node;
      });
      var s = left === right ? 1 : separation(left, right) / 2,
          tx = s - left.x,
          kx = dx / (right.x + s + tx),
          ky = dy / (bottom.depth || 1);
      root.eachBefore(function(node) {
        node.x = (node.x + tx) * kx;
        node.y = node.depth * ky;
      });
    }

    return root;
  }

  // Computes a preliminary x-coordinate for v. Before that, FIRST WALK is
  // applied recursively to the children of v, as well as the function
  // APPORTION. After spacing out the children by calling EXECUTE SHIFTS, the
  // node v is placed to the midpoint of its outermost children.
  function firstWalk(v) {
    var children = v.children,
        siblings = v.parent.children,
        w = v.i ? siblings[v.i - 1] : null;
    if (children) {
      standalone_executeShifts(v);
      var midpoint = (children[0].z + children[children.length - 1].z) / 2;
      if (w) {
        v.z = w.z + separation(v._, w._);
        v.m = v.z - midpoint;
      } else {
        v.z = midpoint;
      }
    } else if (w) {
      v.z = w.z + separation(v._, w._);
    }
    v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
  }

  // Computes all real x-coordinates by summing up the modifiers recursively.
  function secondWalk(v) {
    v._.x = v.z + v.parent.m;
    v.m += v.parent.m;
  }

  // The core of the algorithm. Here, a new subtree is combined with the
  // previous subtrees. Threads are used to traverse the inside and outside
  // contours of the left and right subtree up to the highest common level. The
  // vertices used for the traversals are vi+, vi-, vo-, and vo+, where the
  // superscript o means outside and i means inside, the subscript - means left
  // subtree and + means right subtree. For summing up the modifiers along the
  // contour, we use respective variables si+, si-, so-, and so+. Whenever two
  // nodes of the inside contours conflict, we compute the left one of the
  // greatest uncommon ancestors using the function ANCESTOR and call MOVE
  // SUBTREE to shift the subtree and prepare the shifts of smaller subtrees.
  // Finally, we add a new thread (if necessary).
  function apportion(v, w, ancestor) {
    if (w) {
      var vip = v,
          vop = v,
          vim = w,
          vom = vip.parent.children[0],
          sip = vip.m,
          sop = vop.m,
          sim = vim.m,
          som = vom.m,
          shift;
      while (vim = standalone_nextRight(vim), vip = standalone_nextLeft(vip), vim && vip) {
        vom = standalone_nextLeft(vom);
        vop = standalone_nextRight(vop);
        vop.a = v;
        shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
        if (shift > 0) {
          standalone_moveSubtree(standalone_nextAncestor(vim, v, ancestor), v, shift);
          sip += shift;
          sop += shift;
        }
        sim += vim.m;
        sip += vip.m;
        som += vom.m;
        sop += vop.m;
      }
      if (vim && !standalone_nextRight(vop)) {
        vop.t = vim;
        vop.m += sim - sop;
      }
      if (vip && !standalone_nextLeft(vom)) {
        vom.t = vip;
        vom.m += sip - som;
        ancestor = v;
      }
    }
    return ancestor;
  }

  function sizeNode(node) {
    node.x *= dx;
    node.y = node.depth * dy;
  }

  tree.separation = function(x) {
    return arguments.length ? (separation = x, tree) : separation;
  };

  tree.size = function(x) {
    return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], tree) : (nodeSize ? null : [dx, dy]);
  };

  tree.nodeSize = function(x) {
    return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], tree) : (nodeSize ? [dx, dy] : null);
  };

  return tree;
}

;// ../../node_modules/d3-hierarchy/src/cluster.js
function standalone_cluster_defaultSeparation(a, b) {
  return a.parent === b.parent ? 1 : 2;
}

function standalone_meanX(children) {
  return children.reduce(standalone_meanXReduce, 0) / children.length;
}

function standalone_meanXReduce(x, c) {
  return x + c.x;
}

function standalone_maxY(children) {
  return 1 + children.reduce(standalone_maxYReduce, 0);
}

function standalone_maxYReduce(y, c) {
  return Math.max(y, c.y);
}

function standalone_leafLeft(node) {
  var children;
  while (children = node.children) node = children[0];
  return node;
}

function standalone_leafRight(node) {
  var children;
  while (children = node.children) node = children[children.length - 1];
  return node;
}

/* harmony default export */ function standalone_cluster() {
  var separation = standalone_cluster_defaultSeparation,
      dx = 1,
      dy = 1,
      nodeSize = false;

  function cluster(root) {
    var previousNode,
        x = 0;

    // First walk, computing the initial x & y values.
    root.eachAfter(function(node) {
      var children = node.children;
      if (children) {
        node.x = standalone_meanX(children);
        node.y = standalone_maxY(children);
      } else {
        node.x = previousNode ? x += separation(node, previousNode) : 0;
        node.y = 0;
        previousNode = node;
      }
    });

    var left = standalone_leafLeft(root),
        right = standalone_leafRight(root),
        x0 = left.x - separation(left, right) / 2,
        x1 = right.x + separation(right, left) / 2;

    // Second walk, normalizing x & y to the desired size.
    return root.eachAfter(nodeSize ? function(node) {
      node.x = (node.x - root.x) * dx;
      node.y = (root.y - node.y) * dy;
    } : function(node) {
      node.x = (node.x - x0) / (x1 - x0) * dx;
      node.y = (1 - (root.y ? node.y / root.y : 1)) * dy;
    });
  }

  cluster.separation = function(x) {
    return arguments.length ? (separation = x, cluster) : separation;
  };

  cluster.size = function(x) {
    return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? null : [dx, dy]);
  };

  cluster.nodeSize = function(x) {
    return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? [dx, dy] : null);
  };

  return cluster;
}

;// ../../node_modules/d3-hierarchy/src/treemap/binary.js
/* harmony default export */ function standalone_binary(parent, x0, y0, x1, y1) {
  var nodes = parent.children,
      i, n = nodes.length,
      sum, sums = new Array(n + 1);

  for (sums[0] = sum = i = 0; i < n; ++i) {
    sums[i + 1] = sum += nodes[i].value;
  }

  partition(0, n, parent.value, x0, y0, x1, y1);

  function partition(i, j, value, x0, y0, x1, y1) {
    if (i >= j - 1) {
      var node = nodes[i];
      node.x0 = x0, node.y0 = y0;
      node.x1 = x1, node.y1 = y1;
      return;
    }

    var valueOffset = sums[i],
        valueTarget = (value / 2) + valueOffset,
        k = i + 1,
        hi = j - 1;

    while (k < hi) {
      var mid = k + hi >>> 1;
      if (sums[mid] < valueTarget) k = mid + 1;
      else hi = mid;
    }

    if ((valueTarget - sums[k - 1]) < (sums[k] - valueTarget) && i + 1 < k) --k;

    var valueLeft = sums[k] - valueOffset,
        valueRight = value - valueLeft;

    if ((x1 - x0) > (y1 - y0)) {
      var xk = value ? (x0 * valueRight + x1 * valueLeft) / value : x1;
      partition(i, k, valueLeft, x0, y0, xk, y1);
      partition(k, j, valueRight, xk, y0, x1, y1);
    } else {
      var yk = value ? (y0 * valueRight + y1 * valueLeft) / value : y1;
      partition(i, k, valueLeft, x0, y0, x1, yk);
      partition(k, j, valueRight, x0, yk, x1, y1);
    }
  }
}

;// ../../node_modules/d3-hierarchy/src/treemap/slice.js
/* harmony default export */ function standalone_treemap_slice(parent, x0, y0, x1, y1) {
  var nodes = parent.children,
      node,
      i = -1,
      n = nodes.length,
      k = parent.value && (y1 - y0) / parent.value;

  while (++i < n) {
    node = nodes[i], node.x0 = x0, node.x1 = x1;
    node.y0 = y0, node.y1 = y0 += node.value * k;
  }
}

;// ../../node_modules/d3-hierarchy/src/treemap/sliceDice.js



/* harmony default export */ function standalone_sliceDice(parent, x0, y0, x1, y1) {
  (parent.depth & 1 ? standalone_treemap_slice : standalone_dice)(parent, x0, y0, x1, y1);
}

;// ../../node_modules/d3-hierarchy/src/treemap/squarify.js



var standalone_phi = (1 + Math.sqrt(5)) / 2;

function standalone_squarifyRatio(ratio, parent, x0, y0, x1, y1) {
  var rows = [],
      nodes = parent.children,
      row,
      nodeValue,
      i0 = 0,
      i1 = 0,
      n = nodes.length,
      dx, dy,
      value = parent.value,
      sumValue,
      minValue,
      maxValue,
      newRatio,
      minRatio,
      alpha,
      beta;

  while (i0 < n) {
    dx = x1 - x0, dy = y1 - y0;

    // Find the next non-empty node.
    do sumValue = nodes[i1++].value; while (!sumValue && i1 < n);
    minValue = maxValue = sumValue;
    alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
    beta = sumValue * sumValue * alpha;
    minRatio = Math.max(maxValue / beta, beta / minValue);

    // Keep adding nodes while the aspect ratio maintains or improves.
    for (; i1 < n; ++i1) {
      sumValue += nodeValue = nodes[i1].value;
      if (nodeValue < minValue) minValue = nodeValue;
      if (nodeValue > maxValue) maxValue = nodeValue;
      beta = sumValue * sumValue * alpha;
      newRatio = Math.max(maxValue / beta, beta / minValue);
      if (newRatio > minRatio) { sumValue -= nodeValue; break; }
      minRatio = newRatio;
    }

    // Position and record the row orientation.
    rows.push(row = {value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1)});
    if (row.dice) standalone_dice(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);
    else standalone_treemap_slice(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);
    value -= sumValue, i0 = i1;
  }

  return rows;
}

/* harmony default export */ const standalone_squarify = ((function custom(ratio) {

  function squarify(parent, x0, y0, x1, y1) {
    standalone_squarifyRatio(ratio, parent, x0, y0, x1, y1);
  }

  squarify.ratio = function(x) {
    return custom((x = +x) > 1 ? x : 1);
  };

  return squarify;
})(standalone_phi));

;// ../../node_modules/d3-hierarchy/src/treemap/resquarify.js




/* harmony default export */ const standalone_resquarify = ((function custom(ratio) {

  function resquarify(parent, x0, y0, x1, y1) {
    if ((rows = parent._squarify) && (rows.ratio === ratio)) {
      var rows,
          row,
          nodes,
          i,
          j = -1,
          n,
          m = rows.length,
          value = parent.value;

      while (++j < m) {
        row = rows[j], nodes = row.children;
        for (i = row.value = 0, n = nodes.length; i < n; ++i) row.value += nodes[i].value;
        if (row.dice) standalone_dice(row, x0, y0, x1, value ? y0 += (y1 - y0) * row.value / value : y1);
        else standalone_treemap_slice(row, x0, y0, value ? x0 += (x1 - x0) * row.value / value : x1, y1);
        value -= row.value;
      }
    } else {
      parent._squarify = rows = standalone_squarifyRatio(ratio, parent, x0, y0, x1, y1);
      rows.ratio = ratio;
    }
  }

  resquarify.ratio = function(x) {
    return custom((x = +x) > 1 ? x : 1);
  };

  return resquarify;
})(standalone_phi));

;// ../../node_modules/d3-hierarchy/src/treemap/index.js





/* harmony default export */ function standalone_treemap() {
  var tile = standalone_squarify,
      round = false,
      dx = 1,
      dy = 1,
      paddingStack = [0],
      paddingInner = standalone_constantZero,
      paddingTop = standalone_constantZero,
      paddingRight = standalone_constantZero,
      paddingBottom = standalone_constantZero,
      paddingLeft = standalone_constantZero;

  function treemap(root) {
    root.x0 =
    root.y0 = 0;
    root.x1 = dx;
    root.y1 = dy;
    root.eachBefore(positionNode);
    paddingStack = [0];
    if (round) root.eachBefore(standalone_treemap_round);
    return root;
  }

  function positionNode(node) {
    var p = paddingStack[node.depth],
        x0 = node.x0 + p,
        y0 = node.y0 + p,
        x1 = node.x1 - p,
        y1 = node.y1 - p;
    if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
    if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
    node.x0 = x0;
    node.y0 = y0;
    node.x1 = x1;
    node.y1 = y1;
    if (node.children) {
      p = paddingStack[node.depth + 1] = paddingInner(node) / 2;
      x0 += paddingLeft(node) - p;
      y0 += paddingTop(node) - p;
      x1 -= paddingRight(node) - p;
      y1 -= paddingBottom(node) - p;
      if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
      if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
      tile(node, x0, y0, x1, y1);
    }
  }

  treemap.round = function(x) {
    return arguments.length ? (round = !!x, treemap) : round;
  };

  treemap.size = function(x) {
    return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy];
  };

  treemap.tile = function(x) {
    return arguments.length ? (tile = standalone_required(x), treemap) : tile;
  };

  treemap.padding = function(x) {
    return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();
  };

  treemap.paddingInner = function(x) {
    return arguments.length ? (paddingInner = typeof x === "function" ? x : standalone_d3_hierarchy_src_constant(+x), treemap) : paddingInner;
  };

  treemap.paddingOuter = function(x) {
    return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();
  };

  treemap.paddingTop = function(x) {
    return arguments.length ? (paddingTop = typeof x === "function" ? x : standalone_d3_hierarchy_src_constant(+x), treemap) : paddingTop;
  };

  treemap.paddingRight = function(x) {
    return arguments.length ? (paddingRight = typeof x === "function" ? x : standalone_d3_hierarchy_src_constant(+x), treemap) : paddingRight;
  };

  treemap.paddingBottom = function(x) {
    return arguments.length ? (paddingBottom = typeof x === "function" ? x : standalone_d3_hierarchy_src_constant(+x), treemap) : paddingBottom;
  };

  treemap.paddingLeft = function(x) {
    return arguments.length ? (paddingLeft = typeof x === "function" ? x : standalone_d3_hierarchy_src_constant(+x), treemap) : paddingLeft;
  };

  return treemap;
}

;// ../../node_modules/vega-hierarchy/build/vega-hierarchy.module.js




// Build lookup table mapping tuple keys to tree node instances
function standalone_vega_hierarchy_module_lookup (tree, key, filter) {
  const map = {};
  tree.each(node => {
    const t = node.data;
    if (filter(t)) map[key(t)] = node;
  });
  tree.lookup = map;
  return tree;
}

/**
 * Nest tuples into a tree structure, grouped by key values.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<function(object): *>} params.keys - The key fields to nest by, in order.
 * @param {boolean} [params.generate=false] - A boolean flag indicating if
 *   non-leaf nodes generated by this transform should be included in the
 *   output. The default (false) includes only the input data (leaf nodes)
 *   in the data stream.
 */
function standalone_Nest(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Nest.Definition = {
  'type': 'Nest',
  'metadata': {
    'treesource': true,
    'changes': true
  },
  'params': [{
    'name': 'keys',
    'type': 'field',
    'array': true
  }, {
    'name': 'generate',
    'type': 'boolean'
  }]
};
const standalone_vega_hierarchy_module_children = n => n.values;
standalone_inherits(standalone_Nest, standalone_Transform, {
  transform(_, pulse) {
    if (!pulse.source) {
      standalone_vega_util_module_error('Nest transform requires an upstream data source.');
    }
    var gen = _.generate,
      mod = _.modified(),
      out = pulse.clone(),
      tree = this.value;
    if (!tree || mod || pulse.changed()) {
      // collect nodes to remove
      if (tree) {
        tree.each(node => {
          if (node.children && standalone_isTuple(node.data)) {
            out.rem.push(node.data);
          }
        });
      }

      // generate new tree structure
      this.value = tree = standalone_hierarchy({
        values: standalone_array(_.keys).reduce((n, k) => {
          n.key(k);
          return n;
        }, standalone_nest()).entries(out.source)
      }, standalone_vega_hierarchy_module_children);

      // collect nodes to add
      if (gen) {
        tree.each(node => {
          if (node.children) {
            node = standalone_ingest$1(node.data);
            out.add.push(node);
            out.source.push(node);
          }
        });
      }

      // build lookup table
      standalone_vega_hierarchy_module_lookup(tree, standalone_tupleid, standalone_tupleid);
    }
    out.source.root = tree;
    return out;
  }
});
function standalone_nest() {
  const keys = [],
    nest = {
      entries: array => entries(apply(array, 0), 0),
      key: d => (keys.push(d), nest)
    };
  function apply(array, depth) {
    if (depth >= keys.length) {
      return array;
    }
    const n = array.length,
      key = keys[depth++],
      valuesByKey = {},
      result = {};
    let i = -1,
      keyValue,
      value,
      values;
    while (++i < n) {
      keyValue = key(value = array[i]) + '';
      if (values = valuesByKey[keyValue]) {
        values.push(value);
      } else {
        valuesByKey[keyValue] = [value];
      }
    }
    for (keyValue in valuesByKey) {
      result[keyValue] = apply(valuesByKey[keyValue], depth);
    }
    return result;
  }
  function entries(map, depth) {
    if (++depth > keys.length) return map;
    const array = [];
    for (const key in map) {
      array.push({
        key,
        values: entries(map[key], depth)
      });
    }
    return array;
  }
  return nest;
}

/**
 * Abstract class for tree layout.
 * @constructor
 * @param {object} params - The parameters for this operator.
 */
function standalone_HierarchyLayout(params) {
  standalone_Transform.call(this, null, params);
}
const standalone_vega_hierarchy_module_defaultSeparation = (a, b) => a.parent === b.parent ? 1 : 2;
standalone_inherits(standalone_HierarchyLayout, standalone_Transform, {
  transform(_, pulse) {
    if (!pulse.source || !pulse.source.root) {
      standalone_vega_util_module_error(this.constructor.name + ' transform requires a backing tree data source.');
    }
    const layout = this.layout(_.method),
      fields = this.fields,
      root = pulse.source.root,
      as = _.as || fields;
    if (_.field) root.sum(_.field);else root.count();
    if (_.sort) root.sort(standalone_stableCompare(_.sort, d => d.data));
    standalone_setParams(layout, this.params, _);
    if (layout.separation) {
      layout.separation(_.separation !== false ? standalone_vega_hierarchy_module_defaultSeparation : standalone_one);
    }
    try {
      this.value = layout(root);
    } catch (err) {
      standalone_vega_util_module_error(err);
    }
    root.each(node => standalone_setFields(node, fields, as));
    return pulse.reflow(_.modified()).modifies(as).modifies('leaf');
  }
});
function standalone_setParams(layout, params, _) {
  for (let p, i = 0, n = params.length; i < n; ++i) {
    p = params[i];
    if (p in _) layout[p](_[p]);
  }
}
function standalone_setFields(node, fields, as) {
  const t = node.data,
    n = fields.length - 1;
  for (let i = 0; i < n; ++i) {
    t[as[i]] = node[fields[i]];
  }
  t[as[n]] = node.children ? node.children.length : 0;
}

const standalone_Output$3 = ['x', 'y', 'r', 'depth', 'children'];

/**
 * Packed circle tree layout.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The value field to size nodes.
 */
function standalone_Pack(params) {
  standalone_HierarchyLayout.call(this, params);
}
standalone_Pack.Definition = {
  'type': 'Pack',
  'metadata': {
    'tree': true,
    'modifies': true
  },
  'params': [{
    'name': 'field',
    'type': 'field'
  }, {
    'name': 'sort',
    'type': 'compare'
  }, {
    'name': 'padding',
    'type': 'number',
    'default': 0
  }, {
    'name': 'radius',
    'type': 'field',
    'default': null
  }, {
    'name': 'size',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': standalone_Output$3.length,
    'default': standalone_Output$3
  }]
};
standalone_inherits(standalone_Pack, standalone_HierarchyLayout, {
  layout: standalone_pack,
  params: ['radius', 'size', 'padding'],
  fields: standalone_Output$3
});

const standalone_Output$2 = ['x0', 'y0', 'x1', 'y1', 'depth', 'children'];

/**
 * Partition tree layout.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The value field to size nodes.
 */
function standalone_Partition(params) {
  standalone_HierarchyLayout.call(this, params);
}
standalone_Partition.Definition = {
  'type': 'Partition',
  'metadata': {
    'tree': true,
    'modifies': true
  },
  'params': [{
    'name': 'field',
    'type': 'field'
  }, {
    'name': 'sort',
    'type': 'compare'
  }, {
    'name': 'padding',
    'type': 'number',
    'default': 0
  }, {
    'name': 'round',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'size',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': standalone_Output$2.length,
    'default': standalone_Output$2
  }]
};
standalone_inherits(standalone_Partition, standalone_HierarchyLayout, {
  layout: standalone_src_partition,
  params: ['size', 'round', 'padding'],
  fields: standalone_Output$2
});

/**
 * Stratify a collection of tuples into a tree structure based on
 * id and parent id fields.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.key - Unique key field for each tuple.
 * @param {function(object): *} params.parentKey - Field with key for parent tuple.
 */
function standalone_Stratify(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Stratify.Definition = {
  'type': 'Stratify',
  'metadata': {
    'treesource': true
  },
  'params': [{
    'name': 'key',
    'type': 'field',
    'required': true
  }, {
    'name': 'parentKey',
    'type': 'field',
    'required': true
  }]
};
standalone_inherits(standalone_Stratify, standalone_Transform, {
  transform(_, pulse) {
    if (!pulse.source) {
      standalone_vega_util_module_error('Stratify transform requires an upstream data source.');
    }
    let tree = this.value;
    const mod = _.modified(),
      out = pulse.fork(pulse.ALL).materialize(pulse.SOURCE),
      run = !tree || mod || pulse.changed(pulse.ADD_REM) || pulse.modified(_.key.fields) || pulse.modified(_.parentKey.fields);

    // prevent upstream source pollution
    out.source = out.source.slice();
    if (run) {
      tree = out.source.length ? standalone_vega_hierarchy_module_lookup(standalone_stratify().id(_.key).parentId(_.parentKey)(out.source), _.key, standalone_truthy) : standalone_vega_hierarchy_module_lookup(standalone_stratify()([{}]), _.key, _.key);
    }
    out.source.root = this.value = tree;
    return out;
  }
});

const standalone_Layouts = {
  tidy: standalone_tree,
  cluster: standalone_cluster
};
const standalone_Output$1 = ['x', 'y', 'depth', 'children'];

/**
 * Tree layout. Depending on the method parameter, performs either
 * Reingold-Tilford 'tidy' layout or dendrogram 'cluster' layout.
 * @constructor
 * @param {object} params - The parameters for this operator.
 */
function standalone_Tree(params) {
  standalone_HierarchyLayout.call(this, params);
}
standalone_Tree.Definition = {
  'type': 'Tree',
  'metadata': {
    'tree': true,
    'modifies': true
  },
  'params': [{
    'name': 'field',
    'type': 'field'
  }, {
    'name': 'sort',
    'type': 'compare'
  }, {
    'name': 'method',
    'type': 'enum',
    'default': 'tidy',
    'values': ['tidy', 'cluster']
  }, {
    'name': 'size',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'nodeSize',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'separation',
    'type': 'boolean',
    'default': true
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': standalone_Output$1.length,
    'default': standalone_Output$1
  }]
};
standalone_inherits(standalone_Tree, standalone_HierarchyLayout, {
  /**
   * Tree layout generator. Supports both 'tidy' and 'cluster' layouts.
   */
  layout(method) {
    const m = method || 'tidy';
    if (standalone_vega_util_module_has(standalone_Layouts, m)) return standalone_Layouts[m]();else standalone_vega_util_module_error('Unrecognized Tree layout method: ' + m);
  },
  params: ['size', 'nodeSize'],
  fields: standalone_Output$1
});

/**
 * Generate tuples representing links between tree nodes.
 * The resulting tuples will contain 'source' and 'target' fields,
 * which point to parent and child node tuples, respectively.
 * @constructor
 * @param {object} params - The parameters for this operator.
 */
function standalone_TreeLinks(params) {
  standalone_Transform.call(this, [], params);
}
standalone_TreeLinks.Definition = {
  'type': 'TreeLinks',
  'metadata': {
    'tree': true,
    'generates': true,
    'changes': true
  },
  'params': []
};
standalone_inherits(standalone_TreeLinks, standalone_Transform, {
  transform(_, pulse) {
    const links = this.value,
      tree = pulse.source && pulse.source.root,
      out = pulse.fork(pulse.NO_SOURCE),
      lut = {};
    if (!tree) standalone_vega_util_module_error('TreeLinks transform requires a tree data source.');
    if (pulse.changed(pulse.ADD_REM)) {
      // remove previous links
      out.rem = links;

      // build lookup table of valid tuples
      pulse.visit(pulse.SOURCE, t => lut[standalone_tupleid(t)] = 1);

      // generate links for all edges incident on valid tuples
      tree.each(node => {
        const t = node.data,
          p = node.parent && node.parent.data;
        if (p && lut[standalone_tupleid(t)] && lut[standalone_tupleid(p)]) {
          out.add.push(standalone_ingest$1({
            source: p,
            target: t
          }));
        }
      });
      this.value = out.add;
    } else if (pulse.changed(pulse.MOD)) {
      // build lookup table of modified tuples
      pulse.visit(pulse.MOD, t => lut[standalone_tupleid(t)] = 1);

      // gather links incident on modified tuples
      links.forEach(link => {
        if (lut[standalone_tupleid(link.source)] || lut[standalone_tupleid(link.target)]) {
          out.mod.push(link);
        }
      });
    }
    return out;
  }
});

const standalone_Tiles = {
  binary: standalone_binary,
  dice: standalone_dice,
  slice: standalone_treemap_slice,
  slicedice: standalone_sliceDice,
  squarify: standalone_squarify,
  resquarify: standalone_resquarify
};
const standalone_vega_hierarchy_module_Output = ['x0', 'y0', 'x1', 'y1', 'depth', 'children'];

/**
 * Treemap layout.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The value field to size nodes.
 */
function standalone_Treemap(params) {
  standalone_HierarchyLayout.call(this, params);
}
standalone_Treemap.Definition = {
  'type': 'Treemap',
  'metadata': {
    'tree': true,
    'modifies': true
  },
  'params': [{
    'name': 'field',
    'type': 'field'
  }, {
    'name': 'sort',
    'type': 'compare'
  }, {
    'name': 'method',
    'type': 'enum',
    'default': 'squarify',
    'values': ['squarify', 'resquarify', 'binary', 'dice', 'slice', 'slicedice']
  }, {
    'name': 'padding',
    'type': 'number',
    'default': 0
  }, {
    'name': 'paddingInner',
    'type': 'number',
    'default': 0
  }, {
    'name': 'paddingOuter',
    'type': 'number',
    'default': 0
  }, {
    'name': 'paddingTop',
    'type': 'number',
    'default': 0
  }, {
    'name': 'paddingRight',
    'type': 'number',
    'default': 0
  }, {
    'name': 'paddingBottom',
    'type': 'number',
    'default': 0
  }, {
    'name': 'paddingLeft',
    'type': 'number',
    'default': 0
  }, {
    'name': 'ratio',
    'type': 'number',
    'default': 1.618033988749895
  }, {
    'name': 'round',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'size',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': standalone_vega_hierarchy_module_Output.length,
    'default': standalone_vega_hierarchy_module_Output
  }]
};
standalone_inherits(standalone_Treemap, standalone_HierarchyLayout, {
  /**
   * Treemap layout generator. Adds 'method' and 'ratio' parameters
   * to configure the underlying tile method.
   */
  layout() {
    const x = standalone_treemap();
    x.ratio = _ => {
      const t = x.tile();
      if (t.ratio) x.tile(t.ratio(_));
    };
    x.method = _ => {
      if (standalone_vega_util_module_has(standalone_Tiles, _)) x.tile(standalone_Tiles[_]);else standalone_vega_util_module_error('Unrecognized Treemap layout method: ' + _);
    };
    return x;
  },
  params: ['method', 'ratio', 'size', 'round', 'padding', 'paddingInner', 'paddingOuter', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'],
  fields: standalone_vega_hierarchy_module_Output
});



;// ../../node_modules/vega-label/build/vega-label.module.js





// bit mask for getting first 2 bytes of alpha value
const standalone_ALPHA_MASK = 0xff000000;
function standalone_baseBitmaps($, data) {
  const bitmap = $.bitmap();
  // when there is no base mark but data points are to be avoided
  (data || []).forEach(d => bitmap.set($(d.boundary[0]), $(d.boundary[3])));
  return [bitmap, undefined];
}
function standalone_markBitmaps($, baseMark, avoidMarks, labelInside, isGroupArea) {
  // create canvas
  const width = $.width,
    height = $.height,
    border = labelInside || isGroupArea,
    context = standalone_domCanvas(width, height).getContext('2d'),
    baseMarkContext = standalone_domCanvas(width, height).getContext('2d'),
    strokeContext = border && standalone_domCanvas(width, height).getContext('2d');

  // render all marks to be avoided into canvas
  avoidMarks.forEach(items => standalone_vega_label_module_draw(context, items, false));
  standalone_vega_label_module_draw(baseMarkContext, baseMark, false);
  if (border) {
    standalone_vega_label_module_draw(strokeContext, baseMark, true);
  }

  // get canvas buffer, create bitmaps
  const buffer = standalone_getBuffer(context, width, height),
    baseMarkBuffer = standalone_getBuffer(baseMarkContext, width, height),
    strokeBuffer = border && standalone_getBuffer(strokeContext, width, height),
    layer1 = $.bitmap(),
    layer2 = border && $.bitmap();

  // populate bitmap layers
  let x, y, u, v, index, alpha, strokeAlpha, baseMarkAlpha;
  for (y = 0; y < height; ++y) {
    for (x = 0; x < width; ++x) {
      index = y * width + x;
      alpha = buffer[index] & standalone_ALPHA_MASK;
      baseMarkAlpha = baseMarkBuffer[index] & standalone_ALPHA_MASK;
      strokeAlpha = border && strokeBuffer[index] & standalone_ALPHA_MASK;
      if (alpha || strokeAlpha || baseMarkAlpha) {
        u = $(x);
        v = $(y);
        if (!isGroupArea && (alpha || baseMarkAlpha)) layer1.set(u, v); // update interior bitmap
        if (border && (alpha || strokeAlpha)) layer2.set(u, v); // update border bitmap
      }
    }
  }
  return [layer1, layer2];
}
function standalone_getBuffer(context, width, height) {
  return new Uint32Array(context.getImageData(0, 0, width, height).data.buffer);
}
function standalone_vega_label_module_draw(context, items, interior) {
  if (!items.length) return;
  const type = items[0].mark.marktype;
  if (type === 'group') {
    items.forEach(group => {
      group.items.forEach(mark => standalone_vega_label_module_draw(context, mark.items, interior));
    });
  } else {
    standalone_Marks[type].draw(context, {
      items: interior ? items.map(standalone_prepare) : items
    });
  }
}

/**
 * Prepare item before drawing into canvas (setting stroke and opacity)
 * @param {object} source item to be prepared
 * @returns prepared item
 */
function standalone_prepare(source) {
  const item = standalone_rederive(source, {});
  if (item.stroke && item.strokeOpacity !== 0 || item.fill && item.fillOpacity !== 0) {
    return {
      ...item,
      strokeOpacity: 1,
      stroke: '#000',
      fillOpacity: 0
    };
  }
  return item;
}

const standalone_DIV = 5,
  // bit shift from x, y index to bit vector array index
  standalone_vega_label_module_MOD = 31,
  // bit mask for index lookup within a bit vector
  standalone_SIZE = 32,
  // individual bit vector size
  standalone_RIGHT0 = new Uint32Array(standalone_SIZE + 1),
  // left-anchored bit vectors, full -> 0
  standalone_RIGHT1 = new Uint32Array(standalone_SIZE + 1); // right-anchored bit vectors, 0 -> full

standalone_RIGHT1[0] = 0;
standalone_RIGHT0[0] = ~standalone_RIGHT1[0];
for (let i = 1; i <= standalone_SIZE; ++i) {
  standalone_RIGHT1[i] = standalone_RIGHT1[i - 1] << 1 | 1;
  standalone_RIGHT0[i] = ~standalone_RIGHT1[i];
}
function standalone_Bitmap (w, h) {
  const array = new Uint32Array(~~((w * h + standalone_SIZE) / standalone_SIZE));
  function _set(index, mask) {
    array[index] |= mask;
  }
  function _clear(index, mask) {
    array[index] &= mask;
  }
  return {
    array: array,
    get: (x, y) => {
      const index = y * w + x;
      return array[index >>> standalone_DIV] & 1 << (index & standalone_vega_label_module_MOD);
    },
    set: (x, y) => {
      const index = y * w + x;
      _set(index >>> standalone_DIV, 1 << (index & standalone_vega_label_module_MOD));
    },
    clear: (x, y) => {
      const index = y * w + x;
      _clear(index >>> standalone_DIV, ~(1 << (index & standalone_vega_label_module_MOD)));
    },
    getRange: (x, y, x2, y2) => {
      let r = y2,
        start,
        end,
        indexStart,
        indexEnd;
      for (; r >= y; --r) {
        start = r * w + x;
        end = r * w + x2;
        indexStart = start >>> standalone_DIV;
        indexEnd = end >>> standalone_DIV;
        if (indexStart === indexEnd) {
          if (array[indexStart] & standalone_RIGHT0[start & standalone_vega_label_module_MOD] & standalone_RIGHT1[(end & standalone_vega_label_module_MOD) + 1]) {
            return true;
          }
        } else {
          if (array[indexStart] & standalone_RIGHT0[start & standalone_vega_label_module_MOD]) return true;
          if (array[indexEnd] & standalone_RIGHT1[(end & standalone_vega_label_module_MOD) + 1]) return true;
          for (let i = indexStart + 1; i < indexEnd; ++i) {
            if (array[i]) return true;
          }
        }
      }
      return false;
    },
    setRange: (x, y, x2, y2) => {
      let start, end, indexStart, indexEnd, i;
      for (; y <= y2; ++y) {
        start = y * w + x;
        end = y * w + x2;
        indexStart = start >>> standalone_DIV;
        indexEnd = end >>> standalone_DIV;
        if (indexStart === indexEnd) {
          _set(indexStart, standalone_RIGHT0[start & standalone_vega_label_module_MOD] & standalone_RIGHT1[(end & standalone_vega_label_module_MOD) + 1]);
        } else {
          _set(indexStart, standalone_RIGHT0[start & standalone_vega_label_module_MOD]);
          _set(indexEnd, standalone_RIGHT1[(end & standalone_vega_label_module_MOD) + 1]);
          for (i = indexStart + 1; i < indexEnd; ++i) _set(i, 0xffffffff);
        }
      }
    },
    clearRange: (x, y, x2, y2) => {
      let start, end, indexStart, indexEnd, i;
      for (; y <= y2; ++y) {
        start = y * w + x;
        end = y * w + x2;
        indexStart = start >>> standalone_DIV;
        indexEnd = end >>> standalone_DIV;
        if (indexStart === indexEnd) {
          _clear(indexStart, standalone_RIGHT1[start & standalone_vega_label_module_MOD] | standalone_RIGHT0[(end & standalone_vega_label_module_MOD) + 1]);
        } else {
          _clear(indexStart, standalone_RIGHT1[start & standalone_vega_label_module_MOD]);
          _clear(indexEnd, standalone_RIGHT0[(end & standalone_vega_label_module_MOD) + 1]);
          for (i = indexStart + 1; i < indexEnd; ++i) _clear(i, 0);
        }
      }
    },
    outOfBounds: (x, y, x2, y2) => x < 0 || y < 0 || y2 >= h || x2 >= w
  };
}

function standalone_scaler (width, height, padding) {
  const ratio = Math.max(1, Math.sqrt(width * height / 1e6)),
    w = ~~((width + 2 * padding + ratio) / ratio),
    h = ~~((height + 2 * padding + ratio) / ratio),
    scale = _ => ~~((_ + padding) / ratio);
  scale.invert = _ => _ * ratio - padding;
  scale.bitmap = () => standalone_Bitmap(w, h);
  scale.ratio = ratio;
  scale.padding = padding;
  scale.width = width;
  scale.height = height;
  return scale;
}

function standalone_placeAreaLabelNaive ($, bitmaps, avoidBaseMark, markIndex) {
  const width = $.width,
    height = $.height;

  // try to place a label within an input area mark
  return function (d) {
    const items = d.datum.datum.items[markIndex].items,
      // area points
      n = items.length,
      // number of points
      textHeight = d.datum.fontSize,
      // label width
      textWidth = standalone_textMetrics.width(d.datum, d.datum.text); // label height

    let maxAreaWidth = 0,
      x1,
      x2,
      y1,
      y2,
      x,
      y,
      areaWidth;

    // for each area sample point
    for (let i = 0; i < n; ++i) {
      x1 = items[i].x;
      y1 = items[i].y;
      x2 = items[i].x2 === undefined ? x1 : items[i].x2;
      y2 = items[i].y2 === undefined ? y1 : items[i].y2;
      x = (x1 + x2) / 2;
      y = (y1 + y2) / 2;
      areaWidth = Math.abs(x2 - x1 + y2 - y1);
      if (areaWidth >= maxAreaWidth) {
        maxAreaWidth = areaWidth;
        d.x = x;
        d.y = y;
      }
    }
    x = textWidth / 2;
    y = textHeight / 2;
    x1 = d.x - x;
    x2 = d.x + x;
    y1 = d.y - y;
    y2 = d.y + y;
    d.align = 'center';
    if (x1 < 0 && x2 <= width) {
      d.align = 'left';
    } else if (0 <= x1 && width < x2) {
      d.align = 'right';
    }
    d.baseline = 'middle';
    if (y1 < 0 && y2 <= height) {
      d.baseline = 'top';
    } else if (0 <= y1 && height < y2) {
      d.baseline = 'bottom';
    }
    return true;
  };
}

function standalone_outOfBounds(x, y, textWidth, textHeight, width, height) {
  let r = textWidth / 2;
  return x - r < 0 || x + r > width || y - (r = textHeight / 2) < 0 || y + r > height;
}
function standalone_collision($, x, y, textHeight, textWidth, h, bm0, bm1) {
  const w = textWidth * h / (textHeight * 2),
    x1 = $(x - w),
    x2 = $(x + w),
    y1 = $(y - (h = h / 2)),
    y2 = $(y + h);
  return bm0.outOfBounds(x1, y1, x2, y2) || bm0.getRange(x1, y1, x2, y2) || bm1 && bm1.getRange(x1, y1, x2, y2);
}

function standalone_placeAreaLabelReducedSearch ($, bitmaps, avoidBaseMark, markIndex) {
  const width = $.width,
    height = $.height,
    bm0 = bitmaps[0],
    // where labels have been placed
    bm1 = bitmaps[1]; // area outlines

  function tryLabel(_x, _y, maxSize, textWidth, textHeight) {
    const x = $.invert(_x),
      y = $.invert(_y);
    let lo = maxSize,
      hi = height,
      mid;
    if (!standalone_outOfBounds(x, y, textWidth, textHeight, width, height) && !standalone_collision($, x, y, textHeight, textWidth, lo, bm0, bm1) && !standalone_collision($, x, y, textHeight, textWidth, textHeight, bm0, null)) {
      // if the label fits at the current sample point,
      // perform binary search to find the largest font size that fits
      while (hi - lo >= 1) {
        mid = (lo + hi) / 2;
        if (standalone_collision($, x, y, textHeight, textWidth, mid, bm0, bm1)) {
          hi = mid;
        } else {
          lo = mid;
        }
      }
      // place label if current lower bound exceeds prior max font size
      if (lo > maxSize) {
        return [x, y, lo, true];
      }
    }
  }

  // try to place a label within an input area mark
  return function (d) {
    const items = d.datum.datum.items[markIndex].items,
      // area points
      n = items.length,
      // number of points
      textHeight = d.datum.fontSize,
      // label width
      textWidth = standalone_textMetrics.width(d.datum, d.datum.text); // label height

    let maxSize = avoidBaseMark ? textHeight : 0,
      labelPlaced = false,
      labelPlaced2 = false,
      maxAreaWidth = 0,
      x1,
      x2,
      y1,
      y2,
      x,
      y,
      _x,
      _y,
      _x1,
      _xMid,
      _x2,
      _y1,
      _yMid,
      _y2,
      areaWidth,
      result,
      swapTmp;

    // for each area sample point
    for (let i = 0; i < n; ++i) {
      x1 = items[i].x;
      y1 = items[i].y;
      x2 = items[i].x2 === undefined ? x1 : items[i].x2;
      y2 = items[i].y2 === undefined ? y1 : items[i].y2;
      if (x1 > x2) {
        swapTmp = x1;
        x1 = x2;
        x2 = swapTmp;
      }
      if (y1 > y2) {
        swapTmp = y1;
        y1 = y2;
        y2 = swapTmp;
      }
      _x1 = $(x1);
      _x2 = $(x2);
      _xMid = ~~((_x1 + _x2) / 2);
      _y1 = $(y1);
      _y2 = $(y2);
      _yMid = ~~((_y1 + _y2) / 2);

      // search along the line from mid point between the 2 border to lower border
      for (_x = _xMid; _x >= _x1; --_x) {
        for (_y = _yMid; _y >= _y1; --_y) {
          result = tryLabel(_x, _y, maxSize, textWidth, textHeight);
          if (result) {
            [d.x, d.y, maxSize, labelPlaced] = result;
          }
        }
      }

      // search along the line from mid point between the 2 border to upper border
      for (_x = _xMid; _x <= _x2; ++_x) {
        for (_y = _yMid; _y <= _y2; ++_y) {
          result = tryLabel(_x, _y, maxSize, textWidth, textHeight);
          if (result) {
            [d.x, d.y, maxSize, labelPlaced] = result;
          }
        }
      }

      // place label at slice center if not placed through other means
      // and if we're not avoiding overlap with other areas
      if (!labelPlaced && !avoidBaseMark) {
        // one span is zero, hence we can add
        areaWidth = Math.abs(x2 - x1 + y2 - y1);
        x = (x1 + x2) / 2;
        y = (y1 + y2) / 2;

        // place label if it fits and improves the max area width
        if (areaWidth >= maxAreaWidth && !standalone_outOfBounds(x, y, textWidth, textHeight, width, height) && !standalone_collision($, x, y, textHeight, textWidth, textHeight, bm0, null)) {
          maxAreaWidth = areaWidth;
          d.x = x;
          d.y = y;
          labelPlaced2 = true;
        }
      }
    }

    // record current label placement information, update label bitmap
    if (labelPlaced || labelPlaced2) {
      x = textWidth / 2;
      y = textHeight / 2;
      bm0.setRange($(d.x - x), $(d.y - y), $(d.x + x), $(d.y + y));
      d.align = 'center';
      d.baseline = 'middle';
      return true;
    } else {
      return false;
    }
  };
}

// pixel direction offsets for flood fill search
const standalone_X_DIR = [-1, -1, 1, 1];
const standalone_Y_DIR = [-1, 1, -1, 1];
function standalone_placeAreaLabelFloodFill ($, bitmaps, avoidBaseMark, markIndex) {
  const width = $.width,
    height = $.height,
    bm0 = bitmaps[0],
    // where labels have been placed
    bm1 = bitmaps[1],
    // area outlines
    bm2 = $.bitmap(); // flood-fill visitations

  // try to place a label within an input area mark
  return function (d) {
    const items = d.datum.datum.items[markIndex].items,
      // area points
      n = items.length,
      // number of points
      textHeight = d.datum.fontSize,
      // label width
      textWidth = standalone_textMetrics.width(d.datum, d.datum.text),
      // label height
      stack = []; // flood fill stack

    let maxSize = avoidBaseMark ? textHeight : 0,
      labelPlaced = false,
      labelPlaced2 = false,
      maxAreaWidth = 0,
      x1,
      x2,
      y1,
      y2,
      x,
      y,
      _x,
      _y,
      lo,
      hi,
      mid,
      areaWidth;

    // for each area sample point
    for (let i = 0; i < n; ++i) {
      x1 = items[i].x;
      y1 = items[i].y;
      x2 = items[i].x2 === undefined ? x1 : items[i].x2;
      y2 = items[i].y2 === undefined ? y1 : items[i].y2;

      // add scaled center point to stack
      stack.push([$((x1 + x2) / 2), $((y1 + y2) / 2)]);

      // perform flood fill, visit points
      while (stack.length) {
        [_x, _y] = stack.pop();

        // exit if point already marked
        if (bm0.get(_x, _y) || bm1.get(_x, _y) || bm2.get(_x, _y)) continue;

        // mark point in flood fill bitmap
        // add search points for all (in bound) directions
        bm2.set(_x, _y);
        for (let j = 0; j < 4; ++j) {
          x = _x + standalone_X_DIR[j];
          y = _y + standalone_Y_DIR[j];
          if (!bm2.outOfBounds(x, y, x, y)) stack.push([x, y]);
        }

        // unscale point back to x, y space
        x = $.invert(_x);
        y = $.invert(_y);
        lo = maxSize;
        hi = height; // TODO: make this bound smaller

        if (!standalone_outOfBounds(x, y, textWidth, textHeight, width, height) && !standalone_collision($, x, y, textHeight, textWidth, lo, bm0, bm1) && !standalone_collision($, x, y, textHeight, textWidth, textHeight, bm0, null)) {
          // if the label fits at the current sample point,
          // perform binary search to find the largest font size that fits
          while (hi - lo >= 1) {
            mid = (lo + hi) / 2;
            if (standalone_collision($, x, y, textHeight, textWidth, mid, bm0, bm1)) {
              hi = mid;
            } else {
              lo = mid;
            }
          }
          // place label if current lower bound exceeds prior max font size
          if (lo > maxSize) {
            d.x = x;
            d.y = y;
            maxSize = lo;
            labelPlaced = true;
          }
        }
      }

      // place label at slice center if not placed through other means
      // and if we're not avoiding overlap with other areas
      if (!labelPlaced && !avoidBaseMark) {
        // one span is zero, hence we can add
        areaWidth = Math.abs(x2 - x1 + y2 - y1);
        x = (x1 + x2) / 2;
        y = (y1 + y2) / 2;

        // place label if it fits and improves the max area width
        if (areaWidth >= maxAreaWidth && !standalone_outOfBounds(x, y, textWidth, textHeight, width, height) && !standalone_collision($, x, y, textHeight, textWidth, textHeight, bm0, null)) {
          maxAreaWidth = areaWidth;
          d.x = x;
          d.y = y;
          labelPlaced2 = true;
        }
      }
    }

    // record current label placement information, update label bitmap
    if (labelPlaced || labelPlaced2) {
      x = textWidth / 2;
      y = textHeight / 2;
      bm0.setRange($(d.x - x), $(d.y - y), $(d.x + x), $(d.y + y));
      d.align = 'center';
      d.baseline = 'middle';
      return true;
    } else {
      return false;
    }
  };
}

const standalone_Aligns = ['right', 'center', 'left'],
  standalone_Baselines = ['bottom', 'middle', 'top'];
function standalone_placeMarkLabel ($, bitmaps, anchors, offsets) {
  const width = $.width,
    height = $.height,
    bm0 = bitmaps[0],
    bm1 = bitmaps[1],
    n = offsets.length;
  return function (d) {
    const boundary = d.boundary,
      textHeight = d.datum.fontSize;

    // can not be placed if the mark is not visible in the graph bound
    if (boundary[2] < 0 || boundary[5] < 0 || boundary[0] > width || boundary[3] > height) {
      return false;
    }
    let textWidth = d.textWidth ?? 0,
      dx,
      dy,
      isInside,
      sizeFactor,
      insideFactor,
      x1,
      x2,
      y1,
      y2,
      xc,
      yc,
      _x1,
      _x2,
      _y1,
      _y2;

    // for each anchor and offset
    for (let i = 0; i < n; ++i) {
      dx = (anchors[i] & 0x3) - 1;
      dy = (anchors[i] >>> 0x2 & 0x3) - 1;
      isInside = dx === 0 && dy === 0 || offsets[i] < 0;
      sizeFactor = dx && dy ? Math.SQRT1_2 : 1;
      insideFactor = offsets[i] < 0 ? -1 : 1;
      x1 = boundary[1 + dx] + offsets[i] * dx * sizeFactor;
      yc = boundary[4 + dy] + insideFactor * textHeight * dy / 2 + offsets[i] * dy * sizeFactor;
      y1 = yc - textHeight / 2;
      y2 = yc + textHeight / 2;
      _x1 = $(x1);
      _y1 = $(y1);
      _y2 = $(y2);
      if (!textWidth) {
        // to avoid finding width of text label,
        if (!standalone_test(_x1, _x1, _y1, _y2, bm0, bm1, x1, x1, y1, y2, boundary, isInside)) {
          // skip this anchor/offset option if we fail to place a label with 1px width
          continue;
        } else {
          // Otherwise, find the label width
          textWidth = standalone_textMetrics.width(d.datum, d.datum.text);
        }
      }
      xc = x1 + insideFactor * textWidth * dx / 2;
      x1 = xc - textWidth / 2;
      x2 = xc + textWidth / 2;
      _x1 = $(x1);
      _x2 = $(x2);
      if (standalone_test(_x1, _x2, _y1, _y2, bm0, bm1, x1, x2, y1, y2, boundary, isInside)) {
        // place label if the position is placeable
        d.x = !dx ? xc : dx * insideFactor < 0 ? x2 : x1;
        d.y = !dy ? yc : dy * insideFactor < 0 ? y2 : y1;
        d.align = standalone_Aligns[dx * insideFactor + 1];
        d.baseline = standalone_Baselines[dy * insideFactor + 1];
        bm0.setRange(_x1, _y1, _x2, _y2);
        return true;
      }
    }
    return false;
  };
}

// Test if a label with the given dimensions can be added without overlap
function standalone_test(_x1, _x2, _y1, _y2, bm0, bm1, x1, x2, y1, y2, boundary, isInside) {
  return !(bm0.outOfBounds(_x1, _y1, _x2, _y2) || (isInside && bm1 || bm0).getRange(_x1, _y1, _x2, _y2));
}

// 8-bit representation of anchors
const standalone_TOP = 0x0,
  standalone_MIDDLE = 0x4,
  standalone_BOTTOM = 0x8,
  standalone_LEFT = 0x0,
  standalone_CENTER = 0x1,
  standalone_RIGHT = 0x2;

// Mapping from text anchor to number representation
const standalone_anchorCode = {
  'top-left': standalone_TOP + standalone_LEFT,
  'top': standalone_TOP + standalone_CENTER,
  'top-right': standalone_TOP + standalone_RIGHT,
  'left': standalone_MIDDLE + standalone_LEFT,
  'middle': standalone_MIDDLE + standalone_CENTER,
  'right': standalone_MIDDLE + standalone_RIGHT,
  'bottom-left': standalone_BOTTOM + standalone_LEFT,
  'bottom': standalone_BOTTOM + standalone_CENTER,
  'bottom-right': standalone_BOTTOM + standalone_RIGHT
};
const standalone_placeAreaLabel = {
  'naive': standalone_placeAreaLabelNaive,
  'reduced-search': standalone_placeAreaLabelReducedSearch,
  'floodfill': standalone_placeAreaLabelFloodFill
};
function standalone_labelLayout (texts, size, compare, offset, anchor, avoidMarks, avoidBaseMark, lineAnchor, markIndex, padding, method) {
  // early exit for empty data
  if (!texts.length) return texts;
  const positions = Math.max(offset.length, anchor.length),
    offsets = standalone_getOffsets(offset, positions),
    anchors = standalone_getAnchors(anchor, positions),
    marktype = standalone_markType(texts[0].datum),
    grouptype = marktype === 'group' && texts[0].datum.items[markIndex].marktype,
    isGroupArea = grouptype === 'area',
    boundary = standalone_markBoundary(marktype, grouptype, lineAnchor, markIndex),
    infPadding = padding === null || padding === Infinity,
    isNaiveGroupArea = isGroupArea && method === 'naive';
  let maxTextWidth = -1,
    maxTextHeight = -1;

  // prepare text mark data for placing
  const data = texts.map(d => {
    const textWidth = infPadding ? standalone_textMetrics.width(d, d.text) : undefined;
    maxTextWidth = Math.max(maxTextWidth, textWidth);
    maxTextHeight = Math.max(maxTextHeight, d.fontSize);
    return {
      datum: d,
      opacity: 0,
      x: undefined,
      y: undefined,
      align: undefined,
      baseline: undefined,
      boundary: boundary(d),
      textWidth
    };
  });
  padding = padding === null || padding === Infinity ? Math.max(maxTextWidth, maxTextHeight) + Math.max(...offset) : padding;
  const $ = standalone_scaler(size[0], size[1], padding);
  let bitmaps;
  if (!isNaiveGroupArea) {
    // sort labels in priority order, if comparator is provided
    if (compare) {
      data.sort((a, b) => compare(a.datum, b.datum));
    }

    // flag indicating if label can be placed inside its base mark
    let labelInside = false;
    for (let i = 0; i < anchors.length && !labelInside; ++i) {
      // label inside if anchor is at center
      // label inside if offset to be inside the mark bound
      labelInside = anchors[i] === 0x5 || offsets[i] < 0;
    }

    // extract data information from base mark when base mark is to be avoided
    // base mark is implicitly avoided if it is a group area
    const baseMark = (marktype && avoidBaseMark || isGroupArea) && texts.map(d => d.datum);

    // generate bitmaps for layout calculation
    bitmaps = avoidMarks.length || baseMark ? standalone_markBitmaps($, baseMark || [], avoidMarks, labelInside, isGroupArea) : standalone_baseBitmaps($, avoidBaseMark && data);
  }

  // generate label placement function
  const place = isGroupArea ? standalone_placeAreaLabel[method]($, bitmaps, avoidBaseMark, markIndex) : standalone_placeMarkLabel($, bitmaps, anchors, offsets);

  // place all labels
  data.forEach(d => d.opacity = +place(d));
  return data;
}
function standalone_getOffsets(_, count) {
  const offsets = new Float64Array(count),
    n = _.length;
  for (let i = 0; i < n; ++i) offsets[i] = _[i] || 0;
  for (let i = n; i < count; ++i) offsets[i] = offsets[n - 1];
  return offsets;
}
function standalone_getAnchors(_, count) {
  const anchors = new Int8Array(count),
    n = _.length;
  for (let i = 0; i < n; ++i) anchors[i] |= standalone_anchorCode[_[i]];
  for (let i = n; i < count; ++i) anchors[i] = anchors[n - 1];
  return anchors;
}
function standalone_markType(item) {
  return item && item.mark && item.mark.marktype;
}

/**
 * Factory function for function for getting base mark boundary, depending
 * on mark and group type. When mark type is undefined, line or area: boundary
 * is the coordinate of each data point. When base mark is grouped line,
 * boundary is either at the start or end of the line depending on the
 * value of lineAnchor. Otherwise, use bounds of base mark.
 */
function standalone_markBoundary(marktype, grouptype, lineAnchor, markIndex) {
  const xy = d => [d.x, d.x, d.x, d.y, d.y, d.y];
  if (!marktype) {
    return xy; // no reactive geometry
  } else if (marktype === 'line' || marktype === 'area') {
    return d => xy(d.datum);
  } else if (grouptype === 'line') {
    return d => {
      const items = d.datum.items[markIndex].items;
      return xy(items.length ? items[lineAnchor === 'start' ? 0 : items.length - 1] : {
        x: NaN,
        y: NaN
      });
    };
  } else {
    return d => {
      const b = d.datum.bounds;
      return [b.x1, (b.x1 + b.x2) / 2, b.x2, b.y1, (b.y1 + b.y2) / 2, b.y2];
    };
  }
}

const standalone_vega_label_module_Output = ['x', 'y', 'opacity', 'align', 'baseline'];
const standalone_Anchors = ['top-left', 'left', 'bottom-left', 'top', 'bottom', 'top-right', 'right', 'bottom-right'];

/**
 * Compute text label layout to annotate marks.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<number>} params.size - The size of the layout, provided as a [width, height] array.
 * @param {function(*,*): number} [params.sort] - An optional
 *   comparator function for sorting label data in priority order.
 * @param {Array<string>} [params.anchor] - Label anchor points relative to the base mark bounding box.
 *   The available options are 'top-left', 'left', 'bottom-left', 'top',
 *   'bottom', 'top-right', 'right', 'bottom-right', 'middle'.
 * @param {Array<number>} [params.offset] - Label offsets (in pixels) from the base mark bounding box.
 *   This parameter is parallel to the list of anchor points.
 * @param {number | null} [params.padding=0] - The amount (in pixels) that a label may exceed the layout size.
 *   If this parameter is null, a label may exceed the layout size without any boundary.
 * @param {string} [params.lineAnchor='end'] - For group line mark labels only, indicates the anchor
 *   position for labels. One of 'start' or 'end'.
 * @param {string} [params.markIndex=0] - For group mark labels only, an index indicating
 *   which mark within the group should be labeled.
 * @param {Array<number>} [params.avoidMarks] - A list of additional mark names for which the label
 *   layout should avoid overlap.
 * @param {boolean} [params.avoidBaseMark=true] - Boolean flag indicating if labels should avoid
 *   overlap with the underlying base mark being labeled.
 * @param {string} [params.method='naive'] - For area make labels only, a method for
 *   place labels. One of 'naive', 'reduced-search', or 'floodfill'.
 * @param {Array<string>} [params.as] - The output fields written by the transform.
 *   The default is ['x', 'y', 'opacity', 'align', 'baseline'].
 */
function standalone_Label(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Label.Definition = {
  type: 'Label',
  metadata: {
    modifies: true
  },
  params: [{
    name: 'size',
    type: 'number',
    array: true,
    length: 2,
    required: true
  }, {
    name: 'sort',
    type: 'compare'
  }, {
    name: 'anchor',
    type: 'string',
    array: true,
    default: standalone_Anchors
  }, {
    name: 'offset',
    type: 'number',
    array: true,
    default: [1]
  }, {
    name: 'padding',
    type: 'number',
    default: 0,
    null: true
  }, {
    name: 'lineAnchor',
    type: 'string',
    values: ['start', 'end'],
    default: 'end'
  }, {
    name: 'markIndex',
    type: 'number',
    default: 0
  }, {
    name: 'avoidBaseMark',
    type: 'boolean',
    default: true
  }, {
    name: 'avoidMarks',
    type: 'data',
    array: true
  }, {
    name: 'method',
    type: 'string',
    default: 'naive'
  }, {
    name: 'as',
    type: 'string',
    array: true,
    length: standalone_vega_label_module_Output.length,
    default: standalone_vega_label_module_Output
  }]
};
standalone_inherits(standalone_Label, standalone_Transform, {
  transform(_, pulse) {
    function modp(param) {
      const p = _[param];
      return standalone_vega_util_module_isFunction(p) && pulse.modified(p.fields);
    }
    const mod = _.modified();
    if (!(mod || pulse.changed(pulse.ADD_REM) || modp('sort'))) return;
    if (!_.size || _.size.length !== 2) {
      standalone_vega_util_module_error('Size parameter should be specified as a [width, height] array.');
    }
    const as = _.as || standalone_vega_label_module_Output;

    // run label layout
    standalone_labelLayout(pulse.materialize(pulse.SOURCE).source || [], _.size, _.sort, standalone_array(_.offset == null ? 1 : _.offset), standalone_array(_.anchor || standalone_Anchors), _.avoidMarks || [], _.avoidBaseMark !== false, _.lineAnchor || 'end', _.markIndex || 0, _.padding === undefined ? 0 : _.padding, _.method || 'naive').forEach(l => {
      // write layout results to data stream
      const t = l.datum;
      t[as[0]] = l.x;
      t[as[1]] = l.y;
      t[as[2]] = l.opacity;
      t[as[3]] = l.align;
      t[as[4]] = l.baseline;
    });
    return pulse.reflow(mod).modifies(as);
  }
});



;// ../../node_modules/vega-regression/build/vega-regression.module.js




function standalone_vega_regression_module_partition (data, groupby) {
  var groups = [],
    get = function (f) {
      return f(t);
    },
    map,
    i,
    n,
    t,
    k,
    g;

  // partition data points into stack groups
  if (groupby == null) {
    groups.push(data);
  } else {
    for (map = {}, i = 0, n = data.length; i < n; ++i) {
      t = data[i];
      k = groupby.map(get);
      g = map[k];
      if (!g) {
        map[k] = g = [];
        g.dims = k;
        groups.push(g);
      }
      g.push(t);
    }
  }
  return groups;
}

/**
 * Compute locally-weighted regression fits for one or more data groups.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.x - An accessor for the predictor data field.
 * @param {function(object): *} params.y - An accessor for the predicted data field.
 * @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby.
 * @param {number} [params.bandwidth=0.3] - The loess bandwidth.
 */
function standalone_Loess(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Loess.Definition = {
  'type': 'Loess',
  'metadata': {
    'generates': true
  },
  'params': [{
    'name': 'x',
    'type': 'field',
    'required': true
  }, {
    'name': 'y',
    'type': 'field',
    'required': true
  }, {
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'bandwidth',
    'type': 'number',
    'default': 0.3
  }, {
    'name': 'as',
    'type': 'string',
    'array': true
  }]
};
standalone_inherits(standalone_Loess, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
    if (!this.value || pulse.changed() || _.modified()) {
      const source = pulse.materialize(pulse.SOURCE).source,
        groups = standalone_vega_regression_module_partition(source, _.groupby),
        names = (_.groupby || []).map(standalone_accessorName),
        m = names.length,
        as = _.as || [standalone_accessorName(_.x), standalone_accessorName(_.y)],
        values = [];
      groups.forEach(g => {
        standalone_loess(g, _.x, _.y, _.bandwidth || 0.3).forEach(p => {
          const t = {};
          for (let i = 0; i < m; ++i) {
            t[names[i]] = g.dims[i];
          }
          t[as[0]] = p[0];
          t[as[1]] = p[1];
          values.push(standalone_ingest$1(t));
        });
      });
      if (this.value) out.rem = this.value;
      this.value = out.add = out.source = values;
    }
    return out;
  }
});

const standalone_vega_regression_module_Methods = {
  constant: standalone_vega_statistics_module_constant,
  linear: standalone_linear,
  log: standalone_vega_statistics_module_log,
  exp: standalone_vega_statistics_module_exp,
  pow: standalone_vega_statistics_module_pow,
  quad: standalone_quad,
  poly: standalone_poly
};
const standalone_degreesOfFreedom = (method, order) => method === 'poly' ? order : method === 'quad' ? 2 : 1;

/**
 * Compute regression fits for one or more data groups.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.x - An accessor for the predictor data field.
 * @param {function(object): *} params.y - An accessor for the predicted data field.
 * @param {string} [params.method='linear'] - The regression method to apply.
 * @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby.
 * @param {Array<number>} [params.extent] - The domain extent over which to plot the regression line.
 * @param {number} [params.order=3] - The polynomial order. Only applies to the 'poly' method.
 */
function standalone_Regression(params) {
  standalone_Transform.call(this, null, params);
}
standalone_Regression.Definition = {
  'type': 'Regression',
  'metadata': {
    'generates': true
  },
  'params': [{
    'name': 'x',
    'type': 'field',
    'required': true
  }, {
    'name': 'y',
    'type': 'field',
    'required': true
  }, {
    'name': 'groupby',
    'type': 'field',
    'array': true
  }, {
    'name': 'method',
    'type': 'string',
    'default': 'linear',
    'values': Object.keys(standalone_vega_regression_module_Methods)
  }, {
    'name': 'order',
    'type': 'number',
    'default': 3
  }, {
    'name': 'extent',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'params',
    'type': 'boolean',
    'default': false
  }, {
    'name': 'as',
    'type': 'string',
    'array': true
  }]
};
standalone_inherits(standalone_Regression, standalone_Transform, {
  transform(_, pulse) {
    const out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
    if (!this.value || pulse.changed() || _.modified()) {
      const source = pulse.materialize(pulse.SOURCE).source,
        groups = standalone_vega_regression_module_partition(source, _.groupby),
        names = (_.groupby || []).map(standalone_accessorName),
        method = _.method || 'linear',
        order = _.order == null ? 3 : _.order,
        dof = standalone_degreesOfFreedom(method, order),
        as = _.as || [standalone_accessorName(_.x), standalone_accessorName(_.y)],
        fit = standalone_vega_regression_module_Methods[method],
        values = [];
      let domain = _.extent;
      if (!standalone_vega_util_module_has(standalone_vega_regression_module_Methods, method)) {
        standalone_vega_util_module_error('Invalid regression method: ' + method);
      }
      if (domain != null) {
        if (method === 'log' && domain[0] <= 0) {
          pulse.dataflow.warn('Ignoring extent with values <= 0 for log regression.');
          domain = null;
        }
      }
      groups.forEach(g => {
        const n = g.length;
        if (n <= dof) {
          pulse.dataflow.warn('Skipping regression with more parameters than data points.');
          return;
        }
        const model = fit(g, _.x, _.y, order);
        if (_.params) {
          // if parameter vectors requested return those
          values.push(standalone_ingest$1({
            keys: g.dims,
            coef: model.coef,
            rSquared: model.rSquared
          }));
          return;
        }
        const dom = domain || standalone_extent(g, _.x),
          add = p => {
            const t = {};
            for (let i = 0; i < names.length; ++i) {
              t[names[i]] = g.dims[i];
            }
            t[as[0]] = p[0];
            t[as[1]] = p[1];
            values.push(standalone_ingest$1(t));
          };
        if (method === 'linear' || method === 'constant') {
          // for linear or constant regression we only need the end points
          dom.forEach(x => add([x, model.predict(x)]));
        } else {
          // otherwise return trend line sample points
          standalone_sampleCurve(model.predict, dom, 25, 200).forEach(add);
        }
      });
      if (this.value) out.rem = this.value;
      this.value = out.add = out.source = values;
    }
    return out;
  }
});



;// ../../node_modules/robust-predicates/esm/util.js
const standalone_util_epsilon = 1.1102230246251565e-16;
const standalone_util_splitter = 134217729;
const standalone_util_resulterrbound = (3 + 8 * standalone_util_epsilon) * standalone_util_epsilon;

// fast_expansion_sum_zeroelim routine from oritinal code
function standalone_util_sum(elen, e, flen, f, h) {
    let Q, Qnew, hh, bvirt;
    let enow = e[0];
    let fnow = f[0];
    let eindex = 0;
    let findex = 0;
    if ((fnow > enow) === (fnow > -enow)) {
        Q = enow;
        enow = e[++eindex];
    } else {
        Q = fnow;
        fnow = f[++findex];
    }
    let hindex = 0;
    if (eindex < elen && findex < flen) {
        if ((fnow > enow) === (fnow > -enow)) {
            Qnew = enow + Q;
            hh = Q - (Qnew - enow);
            enow = e[++eindex];
        } else {
            Qnew = fnow + Q;
            hh = Q - (Qnew - fnow);
            fnow = f[++findex];
        }
        Q = Qnew;
        if (hh !== 0) {
            h[hindex++] = hh;
        }
        while (eindex < elen && findex < flen) {
            if ((fnow > enow) === (fnow > -enow)) {
                Qnew = Q + enow;
                bvirt = Qnew - Q;
                hh = Q - (Qnew - bvirt) + (enow - bvirt);
                enow = e[++eindex];
            } else {
                Qnew = Q + fnow;
                bvirt = Qnew - Q;
                hh = Q - (Qnew - bvirt) + (fnow - bvirt);
                fnow = f[++findex];
            }
            Q = Qnew;
            if (hh !== 0) {
                h[hindex++] = hh;
            }
        }
    }
    while (eindex < elen) {
        Qnew = Q + enow;
        bvirt = Qnew - Q;
        hh = Q - (Qnew - bvirt) + (enow - bvirt);
        enow = e[++eindex];
        Q = Qnew;
        if (hh !== 0) {
            h[hindex++] = hh;
        }
    }
    while (findex < flen) {
        Qnew = Q + fnow;
        bvirt = Qnew - Q;
        hh = Q - (Qnew - bvirt) + (fnow - bvirt);
        fnow = f[++findex];
        Q = Qnew;
        if (hh !== 0) {
            h[hindex++] = hh;
        }
    }
    if (Q !== 0 || hindex === 0) {
        h[hindex++] = Q;
    }
    return hindex;
}

function standalone_util_sum_three(alen, a, blen, b, clen, c, tmp, out) {
    return standalone_util_sum(standalone_util_sum(alen, a, blen, b, tmp), tmp, clen, c, out);
}

// scale_expansion_zeroelim routine from oritinal code
function standalone_util_scale(elen, e, b, h) {
    let Q, sum, hh, product1, product0;
    let bvirt, c, ahi, alo, bhi, blo;

    c = standalone_util_splitter * b;
    bhi = c - (c - b);
    blo = b - bhi;
    let enow = e[0];
    Q = enow * b;
    c = standalone_util_splitter * enow;
    ahi = c - (c - enow);
    alo = enow - ahi;
    hh = alo * blo - (Q - ahi * bhi - alo * bhi - ahi * blo);
    let hindex = 0;
    if (hh !== 0) {
        h[hindex++] = hh;
    }
    for (let i = 1; i < elen; i++) {
        enow = e[i];
        product1 = enow * b;
        c = standalone_util_splitter * enow;
        ahi = c - (c - enow);
        alo = enow - ahi;
        product0 = alo * blo - (product1 - ahi * bhi - alo * bhi - ahi * blo);
        sum = Q + product0;
        bvirt = sum - Q;
        hh = Q - (sum - bvirt) + (product0 - bvirt);
        if (hh !== 0) {
            h[hindex++] = hh;
        }
        Q = product1 + sum;
        hh = sum - (Q - product1);
        if (hh !== 0) {
            h[hindex++] = hh;
        }
    }
    if (Q !== 0 || hindex === 0) {
        h[hindex++] = Q;
    }
    return hindex;
}

function standalone_util_negate(elen, e) {
    for (let i = 0; i < elen; i++) e[i] = -e[i];
    return elen;
}

function standalone_util_estimate(elen, e) {
    let Q = e[0];
    for (let i = 1; i < elen; i++) Q += e[i];
    return Q;
}

function standalone_vec(n) {
    return new Float64Array(n);
}

;// ../../node_modules/robust-predicates/esm/orient2d.js


const standalone_ccwerrboundA = (3 + 16 * standalone_util_epsilon) * standalone_util_epsilon;
const standalone_ccwerrboundB = (2 + 12 * standalone_util_epsilon) * standalone_util_epsilon;
const standalone_ccwerrboundC = (9 + 64 * standalone_util_epsilon) * standalone_util_epsilon * standalone_util_epsilon;

const standalone_orient2d_B = standalone_vec(4);
const standalone_C1 = standalone_vec(8);
const standalone_C2 = standalone_vec(12);
const standalone_orient2d_D = standalone_vec(16);
const standalone_u = standalone_vec(4);

function standalone_orient2dadapt(ax, ay, bx, by, cx, cy, detsum) {
    let acxtail, acytail, bcxtail, bcytail;
    let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3;

    const acx = ax - cx;
    const bcx = bx - cx;
    const acy = ay - cy;
    const bcy = by - cy;

    s1 = acx * bcy;
    c = standalone_util_splitter * acx;
    ahi = c - (c - acx);
    alo = acx - ahi;
    c = standalone_util_splitter * bcy;
    bhi = c - (c - bcy);
    blo = bcy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = acy * bcx;
    c = standalone_util_splitter * acy;
    ahi = c - (c - acy);
    alo = acy - ahi;
    c = standalone_util_splitter * bcx;
    bhi = c - (c - bcx);
    blo = bcx - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_orient2d_B[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_orient2d_B[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_orient2d_B[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_orient2d_B[3] = u3;

    let det = standalone_util_estimate(4, standalone_orient2d_B);
    let errbound = standalone_ccwerrboundB * detsum;
    if (det >= errbound || -det >= errbound) {
        return det;
    }

    bvirt = ax - acx;
    acxtail = ax - (acx + bvirt) + (bvirt - cx);
    bvirt = bx - bcx;
    bcxtail = bx - (bcx + bvirt) + (bvirt - cx);
    bvirt = ay - acy;
    acytail = ay - (acy + bvirt) + (bvirt - cy);
    bvirt = by - bcy;
    bcytail = by - (bcy + bvirt) + (bvirt - cy);

    if (acxtail === 0 && acytail === 0 && bcxtail === 0 && bcytail === 0) {
        return det;
    }

    errbound = standalone_ccwerrboundC * detsum + standalone_util_resulterrbound * Math.abs(det);
    det += (acx * bcytail + bcy * acxtail) - (acy * bcxtail + bcx * acytail);
    if (det >= errbound || -det >= errbound) return det;

    s1 = acxtail * bcy;
    c = standalone_util_splitter * acxtail;
    ahi = c - (c - acxtail);
    alo = acxtail - ahi;
    c = standalone_util_splitter * bcy;
    bhi = c - (c - bcy);
    blo = bcy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = acytail * bcx;
    c = standalone_util_splitter * acytail;
    ahi = c - (c - acytail);
    alo = acytail - ahi;
    c = standalone_util_splitter * bcx;
    bhi = c - (c - bcx);
    blo = bcx - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_u[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_u[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_u[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_u[3] = u3;
    const C1len = standalone_util_sum(4, standalone_orient2d_B, 4, standalone_u, standalone_C1);

    s1 = acx * bcytail;
    c = standalone_util_splitter * acx;
    ahi = c - (c - acx);
    alo = acx - ahi;
    c = standalone_util_splitter * bcytail;
    bhi = c - (c - bcytail);
    blo = bcytail - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = acy * bcxtail;
    c = standalone_util_splitter * acy;
    ahi = c - (c - acy);
    alo = acy - ahi;
    c = standalone_util_splitter * bcxtail;
    bhi = c - (c - bcxtail);
    blo = bcxtail - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_u[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_u[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_u[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_u[3] = u3;
    const C2len = standalone_util_sum(C1len, standalone_C1, 4, standalone_u, standalone_C2);

    s1 = acxtail * bcytail;
    c = standalone_util_splitter * acxtail;
    ahi = c - (c - acxtail);
    alo = acxtail - ahi;
    c = standalone_util_splitter * bcytail;
    bhi = c - (c - bcytail);
    blo = bcytail - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = acytail * bcxtail;
    c = standalone_util_splitter * acytail;
    ahi = c - (c - acytail);
    alo = acytail - ahi;
    c = standalone_util_splitter * bcxtail;
    bhi = c - (c - bcxtail);
    blo = bcxtail - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_u[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_u[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_u[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_u[3] = u3;
    const Dlen = standalone_util_sum(C2len, standalone_C2, 4, standalone_u, standalone_orient2d_D);

    return standalone_orient2d_D[Dlen - 1];
}

function standalone_orient2d(ax, ay, bx, by, cx, cy) {
    const detleft = (ay - cy) * (bx - cx);
    const detright = (ax - cx) * (by - cy);
    const det = detleft - detright;

    const detsum = Math.abs(detleft + detright);
    if (Math.abs(det) >= standalone_ccwerrboundA * detsum) return det;

    return -standalone_orient2dadapt(ax, ay, bx, by, cx, cy, detsum);
}

function standalone_orient2dfast(ax, ay, bx, by, cx, cy) {
    return (ay - cy) * (bx - cx) - (ax - cx) * (by - cy);
}

;// ../../node_modules/robust-predicates/esm/orient3d.js


const standalone_o3derrboundA = (7 + 56 * standalone_util_epsilon) * standalone_util_epsilon;
const standalone_o3derrboundB = (3 + 28 * standalone_util_epsilon) * standalone_util_epsilon;
const standalone_o3derrboundC = (26 + 288 * standalone_util_epsilon) * standalone_util_epsilon * standalone_util_epsilon;

const standalone_bc = standalone_vec(4);
const standalone_ca = standalone_vec(4);
const standalone_ab = standalone_vec(4);
const standalone_at_b = standalone_vec(4);
const standalone_at_c = standalone_vec(4);
const standalone_bt_c = standalone_vec(4);
const standalone_bt_a = standalone_vec(4);
const standalone_ct_a = standalone_vec(4);
const standalone_ct_b = standalone_vec(4);
const standalone_bct = standalone_vec(8);
const standalone_cat = standalone_vec(8);
const standalone_abt = standalone_vec(8);
const standalone_orient3d_u = standalone_vec(4);

const standalone_8 = standalone_vec(8);
const standalone_8b = standalone_vec(8);
const standalone_16 = standalone_vec(8);
const standalone_12 = standalone_vec(12);

let standalone_fin = standalone_vec(192);
let standalone_fin2 = standalone_vec(192);

function standalone_finadd(finlen, alen, a) {
    finlen = sum(finlen, standalone_fin, alen, a, standalone_fin2);
    const tmp = standalone_fin; standalone_fin = standalone_fin2; standalone_fin2 = tmp;
    return finlen;
}

function standalone_tailinit(xtail, ytail, ax, ay, bx, by, a, b) {
    let bvirt, c, ahi, alo, bhi, blo, _i, _j, _k, _0, s1, s0, t1, t0, u3, negate;
    if (xtail === 0) {
        if (ytail === 0) {
            a[0] = 0;
            b[0] = 0;
            return 1;
        } else {
            negate = -ytail;
            s1 = negate * ax;
            c = splitter * negate;
            ahi = c - (c - negate);
            alo = negate - ahi;
            c = splitter * ax;
            bhi = c - (c - ax);
            blo = ax - bhi;
            a[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            a[1] = s1;
            s1 = ytail * bx;
            c = splitter * ytail;
            ahi = c - (c - ytail);
            alo = ytail - ahi;
            c = splitter * bx;
            bhi = c - (c - bx);
            blo = bx - bhi;
            b[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            b[1] = s1;
            return 2;
        }
    } else {
        if (ytail === 0) {
            s1 = xtail * ay;
            c = splitter * xtail;
            ahi = c - (c - xtail);
            alo = xtail - ahi;
            c = splitter * ay;
            bhi = c - (c - ay);
            blo = ay - bhi;
            a[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            a[1] = s1;
            negate = -xtail;
            s1 = negate * by;
            c = splitter * negate;
            ahi = c - (c - negate);
            alo = negate - ahi;
            c = splitter * by;
            bhi = c - (c - by);
            blo = by - bhi;
            b[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            b[1] = s1;
            return 2;
        } else {
            s1 = xtail * ay;
            c = splitter * xtail;
            ahi = c - (c - xtail);
            alo = xtail - ahi;
            c = splitter * ay;
            bhi = c - (c - ay);
            blo = ay - bhi;
            s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            t1 = ytail * ax;
            c = splitter * ytail;
            ahi = c - (c - ytail);
            alo = ytail - ahi;
            c = splitter * ax;
            bhi = c - (c - ax);
            blo = ax - bhi;
            t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
            _i = s0 - t0;
            bvirt = s0 - _i;
            a[0] = s0 - (_i + bvirt) + (bvirt - t0);
            _j = s1 + _i;
            bvirt = _j - s1;
            _0 = s1 - (_j - bvirt) + (_i - bvirt);
            _i = _0 - t1;
            bvirt = _0 - _i;
            a[1] = _0 - (_i + bvirt) + (bvirt - t1);
            u3 = _j + _i;
            bvirt = u3 - _j;
            a[2] = _j - (u3 - bvirt) + (_i - bvirt);
            a[3] = u3;
            s1 = ytail * bx;
            c = splitter * ytail;
            ahi = c - (c - ytail);
            alo = ytail - ahi;
            c = splitter * bx;
            bhi = c - (c - bx);
            blo = bx - bhi;
            s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            t1 = xtail * by;
            c = splitter * xtail;
            ahi = c - (c - xtail);
            alo = xtail - ahi;
            c = splitter * by;
            bhi = c - (c - by);
            blo = by - bhi;
            t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
            _i = s0 - t0;
            bvirt = s0 - _i;
            b[0] = s0 - (_i + bvirt) + (bvirt - t0);
            _j = s1 + _i;
            bvirt = _j - s1;
            _0 = s1 - (_j - bvirt) + (_i - bvirt);
            _i = _0 - t1;
            bvirt = _0 - _i;
            b[1] = _0 - (_i + bvirt) + (bvirt - t1);
            u3 = _j + _i;
            bvirt = u3 - _j;
            b[2] = _j - (u3 - bvirt) + (_i - bvirt);
            b[3] = u3;
            return 4;
        }
    }
}

function standalone_tailadd(finlen, a, b, k, z) {
    let bvirt, c, ahi, alo, bhi, blo, _i, _j, _k, _0, s1, s0, u3;
    s1 = a * b;
    c = splitter * a;
    ahi = c - (c - a);
    alo = a - ahi;
    c = splitter * b;
    bhi = c - (c - b);
    blo = b - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    c = splitter * k;
    bhi = c - (c - k);
    blo = k - bhi;
    _i = s0 * k;
    c = splitter * s0;
    ahi = c - (c - s0);
    alo = s0 - ahi;
    standalone_orient3d_u[0] = alo * blo - (_i - ahi * bhi - alo * bhi - ahi * blo);
    _j = s1 * k;
    c = splitter * s1;
    ahi = c - (c - s1);
    alo = s1 - ahi;
    _0 = alo * blo - (_j - ahi * bhi - alo * bhi - ahi * blo);
    _k = _i + _0;
    bvirt = _k - _i;
    standalone_orient3d_u[1] = _i - (_k - bvirt) + (_0 - bvirt);
    u3 = _j + _k;
    standalone_orient3d_u[2] = _k - (u3 - _j);
    standalone_orient3d_u[3] = u3;
    finlen = standalone_finadd(finlen, 4, standalone_orient3d_u);
    if (z !== 0) {
        c = splitter * z;
        bhi = c - (c - z);
        blo = z - bhi;
        _i = s0 * z;
        c = splitter * s0;
        ahi = c - (c - s0);
        alo = s0 - ahi;
        standalone_orient3d_u[0] = alo * blo - (_i - ahi * bhi - alo * bhi - ahi * blo);
        _j = s1 * z;
        c = splitter * s1;
        ahi = c - (c - s1);
        alo = s1 - ahi;
        _0 = alo * blo - (_j - ahi * bhi - alo * bhi - ahi * blo);
        _k = _i + _0;
        bvirt = _k - _i;
        standalone_orient3d_u[1] = _i - (_k - bvirt) + (_0 - bvirt);
        u3 = _j + _k;
        standalone_orient3d_u[2] = _k - (u3 - _j);
        standalone_orient3d_u[3] = u3;
        finlen = standalone_finadd(finlen, 4, standalone_orient3d_u);
    }
    return finlen;
}

function standalone_orient3dadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, permanent) {
    let finlen;
    let adxtail, bdxtail, cdxtail;
    let adytail, bdytail, cdytail;
    let adztail, bdztail, cdztail;
    let bvirt, c, ahi, alo, bhi, blo, _i, _j, _k, _0, s1, s0, t1, t0, u3;

    const adx = ax - dx;
    const bdx = bx - dx;
    const cdx = cx - dx;
    const ady = ay - dy;
    const bdy = by - dy;
    const cdy = cy - dy;
    const adz = az - dz;
    const bdz = bz - dz;
    const cdz = cz - dz;

    s1 = bdx * cdy;
    c = splitter * bdx;
    ahi = c - (c - bdx);
    alo = bdx - ahi;
    c = splitter * cdy;
    bhi = c - (c - cdy);
    blo = cdy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = cdx * bdy;
    c = splitter * cdx;
    ahi = c - (c - cdx);
    alo = cdx - ahi;
    c = splitter * bdy;
    bhi = c - (c - bdy);
    blo = bdy - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_bc[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_bc[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_bc[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_bc[3] = u3;
    s1 = cdx * ady;
    c = splitter * cdx;
    ahi = c - (c - cdx);
    alo = cdx - ahi;
    c = splitter * ady;
    bhi = c - (c - ady);
    blo = ady - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = adx * cdy;
    c = splitter * adx;
    ahi = c - (c - adx);
    alo = adx - ahi;
    c = splitter * cdy;
    bhi = c - (c - cdy);
    blo = cdy - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_ca[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_ca[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_ca[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_ca[3] = u3;
    s1 = adx * bdy;
    c = splitter * adx;
    ahi = c - (c - adx);
    alo = adx - ahi;
    c = splitter * bdy;
    bhi = c - (c - bdy);
    blo = bdy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = bdx * ady;
    c = splitter * bdx;
    ahi = c - (c - bdx);
    alo = bdx - ahi;
    c = splitter * ady;
    bhi = c - (c - ady);
    blo = ady - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_ab[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_ab[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_ab[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_ab[3] = u3;

    finlen = sum(
        sum(
            scale(4, standalone_bc, adz, standalone_8), standalone_8,
            scale(4, standalone_ca, bdz, standalone_8b), standalone_8b, standalone_16), standalone_16,
        scale(4, standalone_ab, cdz, standalone_8), standalone_8, standalone_fin);

    let det = estimate(finlen, standalone_fin);
    let errbound = standalone_o3derrboundB * permanent;
    if (det >= errbound || -det >= errbound) {
        return det;
    }

    bvirt = ax - adx;
    adxtail = ax - (adx + bvirt) + (bvirt - dx);
    bvirt = bx - bdx;
    bdxtail = bx - (bdx + bvirt) + (bvirt - dx);
    bvirt = cx - cdx;
    cdxtail = cx - (cdx + bvirt) + (bvirt - dx);
    bvirt = ay - ady;
    adytail = ay - (ady + bvirt) + (bvirt - dy);
    bvirt = by - bdy;
    bdytail = by - (bdy + bvirt) + (bvirt - dy);
    bvirt = cy - cdy;
    cdytail = cy - (cdy + bvirt) + (bvirt - dy);
    bvirt = az - adz;
    adztail = az - (adz + bvirt) + (bvirt - dz);
    bvirt = bz - bdz;
    bdztail = bz - (bdz + bvirt) + (bvirt - dz);
    bvirt = cz - cdz;
    cdztail = cz - (cdz + bvirt) + (bvirt - dz);

    if (adxtail === 0 && bdxtail === 0 && cdxtail === 0 &&
        adytail === 0 && bdytail === 0 && cdytail === 0 &&
        adztail === 0 && bdztail === 0 && cdztail === 0) {
        return det;
    }

    errbound = standalone_o3derrboundC * permanent + resulterrbound * Math.abs(det);
    det +=
        adz * (bdx * cdytail + cdy * bdxtail - (bdy * cdxtail + cdx * bdytail)) + adztail * (bdx * cdy - bdy * cdx) +
        bdz * (cdx * adytail + ady * cdxtail - (cdy * adxtail + adx * cdytail)) + bdztail * (cdx * ady - cdy * adx) +
        cdz * (adx * bdytail + bdy * adxtail - (ady * bdxtail + bdx * adytail)) + cdztail * (adx * bdy - ady * bdx);
    if (det >= errbound || -det >= errbound) {
        return det;
    }

    const at_len = standalone_tailinit(adxtail, adytail, bdx, bdy, cdx, cdy, standalone_at_b, standalone_at_c);
    const bt_len = standalone_tailinit(bdxtail, bdytail, cdx, cdy, adx, ady, standalone_bt_c, standalone_bt_a);
    const ct_len = standalone_tailinit(cdxtail, cdytail, adx, ady, bdx, bdy, standalone_ct_a, standalone_ct_b);

    const bctlen = sum(bt_len, standalone_bt_c, ct_len, standalone_ct_b, standalone_bct);
    finlen = standalone_finadd(finlen, scale(bctlen, standalone_bct, adz, standalone_16), standalone_16);

    const catlen = sum(ct_len, standalone_ct_a, at_len, standalone_at_c, standalone_cat);
    finlen = standalone_finadd(finlen, scale(catlen, standalone_cat, bdz, standalone_16), standalone_16);

    const abtlen = sum(at_len, standalone_at_b, bt_len, standalone_bt_a, standalone_abt);
    finlen = standalone_finadd(finlen, scale(abtlen, standalone_abt, cdz, standalone_16), standalone_16);

    if (adztail !== 0) {
        finlen = standalone_finadd(finlen, scale(4, standalone_bc, adztail, standalone_12), standalone_12);
        finlen = standalone_finadd(finlen, scale(bctlen, standalone_bct, adztail, standalone_16), standalone_16);
    }
    if (bdztail !== 0) {
        finlen = standalone_finadd(finlen, scale(4, standalone_ca, bdztail, standalone_12), standalone_12);
        finlen = standalone_finadd(finlen, scale(catlen, standalone_cat, bdztail, standalone_16), standalone_16);
    }
    if (cdztail !== 0) {
        finlen = standalone_finadd(finlen, scale(4, standalone_ab, cdztail, standalone_12), standalone_12);
        finlen = standalone_finadd(finlen, scale(abtlen, standalone_abt, cdztail, standalone_16), standalone_16);
    }

    if (adxtail !== 0) {
        if (bdytail !== 0) {
            finlen = standalone_tailadd(finlen, adxtail, bdytail, cdz, cdztail);
        }
        if (cdytail !== 0) {
            finlen = standalone_tailadd(finlen, -adxtail, cdytail, bdz, bdztail);
        }
    }
    if (bdxtail !== 0) {
        if (cdytail !== 0) {
            finlen = standalone_tailadd(finlen, bdxtail, cdytail, adz, adztail);
        }
        if (adytail !== 0) {
            finlen = standalone_tailadd(finlen, -bdxtail, adytail, cdz, cdztail);
        }
    }
    if (cdxtail !== 0) {
        if (adytail !== 0) {
            finlen = standalone_tailadd(finlen, cdxtail, adytail, bdz, bdztail);
        }
        if (bdytail !== 0) {
            finlen = standalone_tailadd(finlen, -cdxtail, bdytail, adz, adztail);
        }
    }

    return standalone_fin[finlen - 1];
}

function standalone_orient3d(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz) {
    const adx = ax - dx;
    const bdx = bx - dx;
    const cdx = cx - dx;
    const ady = ay - dy;
    const bdy = by - dy;
    const cdy = cy - dy;
    const adz = az - dz;
    const bdz = bz - dz;
    const cdz = cz - dz;

    const bdxcdy = bdx * cdy;
    const cdxbdy = cdx * bdy;

    const cdxady = cdx * ady;
    const adxcdy = adx * cdy;

    const adxbdy = adx * bdy;
    const bdxady = bdx * ady;

    const det =
        adz * (bdxcdy - cdxbdy) +
        bdz * (cdxady - adxcdy) +
        cdz * (adxbdy - bdxady);

    const permanent =
        (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) +
        (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) +
        (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz);

    const errbound = standalone_o3derrboundA * permanent;
    if (det > errbound || -det > errbound) {
        return det;
    }

    return standalone_orient3dadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, permanent);
}

function standalone_orient3dfast(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz) {
    const adx = ax - dx;
    const bdx = bx - dx;
    const cdx = cx - dx;
    const ady = ay - dy;
    const bdy = by - dy;
    const cdy = cy - dy;
    const adz = az - dz;
    const bdz = bz - dz;
    const cdz = cz - dz;

    return adx * (bdy * cdz - bdz * cdy) +
        bdx * (cdy * adz - cdz * ady) +
        cdx * (ady * bdz - adz * bdy);
}

;// ../../node_modules/robust-predicates/esm/incircle.js


const standalone_iccerrboundA = (10 + 96 * standalone_util_epsilon) * standalone_util_epsilon;
const standalone_iccerrboundB = (4 + 48 * standalone_util_epsilon) * standalone_util_epsilon;
const standalone_iccerrboundC = (44 + 576 * standalone_util_epsilon) * standalone_util_epsilon * standalone_util_epsilon;

const standalone_incircle_bc = standalone_vec(4);
const standalone_incircle_ca = standalone_vec(4);
const standalone_incircle_ab = standalone_vec(4);
const standalone_aa = standalone_vec(4);
const standalone_bb = standalone_vec(4);
const standalone_cc = standalone_vec(4);
const standalone_incircle_u = standalone_vec(4);
const standalone_v = standalone_vec(4);
const standalone_axtbc = standalone_vec(8);
const standalone_aytbc = standalone_vec(8);
const standalone_bxtca = standalone_vec(8);
const standalone_bytca = standalone_vec(8);
const standalone_cxtab = standalone_vec(8);
const standalone_cytab = standalone_vec(8);
const standalone_incircle_abt = standalone_vec(8);
const standalone_incircle_bct = standalone_vec(8);
const standalone_incircle_cat = standalone_vec(8);
const standalone_abtt = standalone_vec(4);
const standalone_bctt = standalone_vec(4);
const standalone_catt = standalone_vec(4);

const standalone_incircle_8 = standalone_vec(8);
const standalone_incircle_16 = standalone_vec(16);
const standalone_16b = standalone_vec(16);
const standalone_16c = standalone_vec(16);
const standalone_32 = standalone_vec(32);
const standalone_32b = standalone_vec(32);
const standalone_48 = standalone_vec(48);
const standalone_64 = standalone_vec(64);

let standalone_incircle_fin = standalone_vec(1152);
let standalone_incircle_fin2 = standalone_vec(1152);

function standalone_incircle_finadd(finlen, a, alen) {
    finlen = sum(finlen, standalone_incircle_fin, a, alen, standalone_incircle_fin2);
    const tmp = standalone_incircle_fin; standalone_incircle_fin = standalone_incircle_fin2; standalone_incircle_fin2 = tmp;
    return finlen;
}

function standalone_incircleadapt(ax, ay, bx, by, cx, cy, dx, dy, permanent) {
    let finlen;
    let adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail;
    let axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen;
    let abtlen, bctlen, catlen;
    let abttlen, bcttlen, cattlen;
    let n1, n0;

    let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3;

    const adx = ax - dx;
    const bdx = bx - dx;
    const cdx = cx - dx;
    const ady = ay - dy;
    const bdy = by - dy;
    const cdy = cy - dy;

    s1 = bdx * cdy;
    c = splitter * bdx;
    ahi = c - (c - bdx);
    alo = bdx - ahi;
    c = splitter * cdy;
    bhi = c - (c - cdy);
    blo = cdy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = cdx * bdy;
    c = splitter * cdx;
    ahi = c - (c - cdx);
    alo = cdx - ahi;
    c = splitter * bdy;
    bhi = c - (c - bdy);
    blo = bdy - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_incircle_bc[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_incircle_bc[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_incircle_bc[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_incircle_bc[3] = u3;
    s1 = cdx * ady;
    c = splitter * cdx;
    ahi = c - (c - cdx);
    alo = cdx - ahi;
    c = splitter * ady;
    bhi = c - (c - ady);
    blo = ady - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = adx * cdy;
    c = splitter * adx;
    ahi = c - (c - adx);
    alo = adx - ahi;
    c = splitter * cdy;
    bhi = c - (c - cdy);
    blo = cdy - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_incircle_ca[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_incircle_ca[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_incircle_ca[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_incircle_ca[3] = u3;
    s1 = adx * bdy;
    c = splitter * adx;
    ahi = c - (c - adx);
    alo = adx - ahi;
    c = splitter * bdy;
    bhi = c - (c - bdy);
    blo = bdy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = bdx * ady;
    c = splitter * bdx;
    ahi = c - (c - bdx);
    alo = bdx - ahi;
    c = splitter * ady;
    bhi = c - (c - ady);
    blo = ady - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_incircle_ab[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_incircle_ab[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_incircle_ab[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_incircle_ab[3] = u3;

    finlen = sum(
        sum(
            sum(
                scale(scale(4, standalone_incircle_bc, adx, standalone_incircle_8), standalone_incircle_8, adx, standalone_incircle_16), standalone_incircle_16,
                scale(scale(4, standalone_incircle_bc, ady, standalone_incircle_8), standalone_incircle_8, ady, standalone_16b), standalone_16b, standalone_32), standalone_32,
            sum(
                scale(scale(4, standalone_incircle_ca, bdx, standalone_incircle_8), standalone_incircle_8, bdx, standalone_incircle_16), standalone_incircle_16,
                scale(scale(4, standalone_incircle_ca, bdy, standalone_incircle_8), standalone_incircle_8, bdy, standalone_16b), standalone_16b, standalone_32b), standalone_32b, standalone_64), standalone_64,
        sum(
            scale(scale(4, standalone_incircle_ab, cdx, standalone_incircle_8), standalone_incircle_8, cdx, standalone_incircle_16), standalone_incircle_16,
            scale(scale(4, standalone_incircle_ab, cdy, standalone_incircle_8), standalone_incircle_8, cdy, standalone_16b), standalone_16b, standalone_32), standalone_32, standalone_incircle_fin);

    let det = estimate(finlen, standalone_incircle_fin);
    let errbound = standalone_iccerrboundB * permanent;
    if (det >= errbound || -det >= errbound) {
        return det;
    }

    bvirt = ax - adx;
    adxtail = ax - (adx + bvirt) + (bvirt - dx);
    bvirt = ay - ady;
    adytail = ay - (ady + bvirt) + (bvirt - dy);
    bvirt = bx - bdx;
    bdxtail = bx - (bdx + bvirt) + (bvirt - dx);
    bvirt = by - bdy;
    bdytail = by - (bdy + bvirt) + (bvirt - dy);
    bvirt = cx - cdx;
    cdxtail = cx - (cdx + bvirt) + (bvirt - dx);
    bvirt = cy - cdy;
    cdytail = cy - (cdy + bvirt) + (bvirt - dy);
    if (adxtail === 0 && bdxtail === 0 && cdxtail === 0 && adytail === 0 && bdytail === 0 && cdytail === 0) {
        return det;
    }

    errbound = standalone_iccerrboundC * permanent + resulterrbound * Math.abs(det);
    det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail) - (bdy * cdxtail + cdx * bdytail)) +
        2 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx)) +
        ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail) - (cdy * adxtail + adx * cdytail)) +
        2 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx)) +
        ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail) - (ady * bdxtail + bdx * adytail)) +
        2 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx));

    if (det >= errbound || -det >= errbound) {
        return det;
    }

    if (bdxtail !== 0 || bdytail !== 0 || cdxtail !== 0 || cdytail !== 0) {
        s1 = adx * adx;
        c = splitter * adx;
        ahi = c - (c - adx);
        alo = adx - ahi;
        s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo);
        t1 = ady * ady;
        c = splitter * ady;
        ahi = c - (c - ady);
        alo = ady - ahi;
        t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo);
        _i = s0 + t0;
        bvirt = _i - s0;
        standalone_aa[0] = s0 - (_i - bvirt) + (t0 - bvirt);
        _j = s1 + _i;
        bvirt = _j - s1;
        _0 = s1 - (_j - bvirt) + (_i - bvirt);
        _i = _0 + t1;
        bvirt = _i - _0;
        standalone_aa[1] = _0 - (_i - bvirt) + (t1 - bvirt);
        u3 = _j + _i;
        bvirt = u3 - _j;
        standalone_aa[2] = _j - (u3 - bvirt) + (_i - bvirt);
        standalone_aa[3] = u3;
    }
    if (cdxtail !== 0 || cdytail !== 0 || adxtail !== 0 || adytail !== 0) {
        s1 = bdx * bdx;
        c = splitter * bdx;
        ahi = c - (c - bdx);
        alo = bdx - ahi;
        s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo);
        t1 = bdy * bdy;
        c = splitter * bdy;
        ahi = c - (c - bdy);
        alo = bdy - ahi;
        t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo);
        _i = s0 + t0;
        bvirt = _i - s0;
        standalone_bb[0] = s0 - (_i - bvirt) + (t0 - bvirt);
        _j = s1 + _i;
        bvirt = _j - s1;
        _0 = s1 - (_j - bvirt) + (_i - bvirt);
        _i = _0 + t1;
        bvirt = _i - _0;
        standalone_bb[1] = _0 - (_i - bvirt) + (t1 - bvirt);
        u3 = _j + _i;
        bvirt = u3 - _j;
        standalone_bb[2] = _j - (u3 - bvirt) + (_i - bvirt);
        standalone_bb[3] = u3;
    }
    if (adxtail !== 0 || adytail !== 0 || bdxtail !== 0 || bdytail !== 0) {
        s1 = cdx * cdx;
        c = splitter * cdx;
        ahi = c - (c - cdx);
        alo = cdx - ahi;
        s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo);
        t1 = cdy * cdy;
        c = splitter * cdy;
        ahi = c - (c - cdy);
        alo = cdy - ahi;
        t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo);
        _i = s0 + t0;
        bvirt = _i - s0;
        standalone_cc[0] = s0 - (_i - bvirt) + (t0 - bvirt);
        _j = s1 + _i;
        bvirt = _j - s1;
        _0 = s1 - (_j - bvirt) + (_i - bvirt);
        _i = _0 + t1;
        bvirt = _i - _0;
        standalone_cc[1] = _0 - (_i - bvirt) + (t1 - bvirt);
        u3 = _j + _i;
        bvirt = u3 - _j;
        standalone_cc[2] = _j - (u3 - bvirt) + (_i - bvirt);
        standalone_cc[3] = u3;
    }

    if (adxtail !== 0) {
        axtbclen = scale(4, standalone_incircle_bc, adxtail, standalone_axtbc);
        finlen = standalone_incircle_finadd(finlen, sum_three(
            scale(axtbclen, standalone_axtbc, 2 * adx, standalone_incircle_16), standalone_incircle_16,
            scale(scale(4, standalone_cc, adxtail, standalone_incircle_8), standalone_incircle_8, bdy, standalone_16b), standalone_16b,
            scale(scale(4, standalone_bb, adxtail, standalone_incircle_8), standalone_incircle_8, -cdy, standalone_16c), standalone_16c, standalone_32, standalone_48), standalone_48);
    }
    if (adytail !== 0) {
        aytbclen = scale(4, standalone_incircle_bc, adytail, standalone_aytbc);
        finlen = standalone_incircle_finadd(finlen, sum_three(
            scale(aytbclen, standalone_aytbc, 2 * ady, standalone_incircle_16), standalone_incircle_16,
            scale(scale(4, standalone_bb, adytail, standalone_incircle_8), standalone_incircle_8, cdx, standalone_16b), standalone_16b,
            scale(scale(4, standalone_cc, adytail, standalone_incircle_8), standalone_incircle_8, -bdx, standalone_16c), standalone_16c, standalone_32, standalone_48), standalone_48);
    }
    if (bdxtail !== 0) {
        bxtcalen = scale(4, standalone_incircle_ca, bdxtail, standalone_bxtca);
        finlen = standalone_incircle_finadd(finlen, sum_three(
            scale(bxtcalen, standalone_bxtca, 2 * bdx, standalone_incircle_16), standalone_incircle_16,
            scale(scale(4, standalone_aa, bdxtail, standalone_incircle_8), standalone_incircle_8, cdy, standalone_16b), standalone_16b,
            scale(scale(4, standalone_cc, bdxtail, standalone_incircle_8), standalone_incircle_8, -ady, standalone_16c), standalone_16c, standalone_32, standalone_48), standalone_48);
    }
    if (bdytail !== 0) {
        bytcalen = scale(4, standalone_incircle_ca, bdytail, standalone_bytca);
        finlen = standalone_incircle_finadd(finlen, sum_three(
            scale(bytcalen, standalone_bytca, 2 * bdy, standalone_incircle_16), standalone_incircle_16,
            scale(scale(4, standalone_cc, bdytail, standalone_incircle_8), standalone_incircle_8, adx, standalone_16b), standalone_16b,
            scale(scale(4, standalone_aa, bdytail, standalone_incircle_8), standalone_incircle_8, -cdx, standalone_16c), standalone_16c, standalone_32, standalone_48), standalone_48);
    }
    if (cdxtail !== 0) {
        cxtablen = scale(4, standalone_incircle_ab, cdxtail, standalone_cxtab);
        finlen = standalone_incircle_finadd(finlen, sum_three(
            scale(cxtablen, standalone_cxtab, 2 * cdx, standalone_incircle_16), standalone_incircle_16,
            scale(scale(4, standalone_bb, cdxtail, standalone_incircle_8), standalone_incircle_8, ady, standalone_16b), standalone_16b,
            scale(scale(4, standalone_aa, cdxtail, standalone_incircle_8), standalone_incircle_8, -bdy, standalone_16c), standalone_16c, standalone_32, standalone_48), standalone_48);
    }
    if (cdytail !== 0) {
        cytablen = scale(4, standalone_incircle_ab, cdytail, standalone_cytab);
        finlen = standalone_incircle_finadd(finlen, sum_three(
            scale(cytablen, standalone_cytab, 2 * cdy, standalone_incircle_16), standalone_incircle_16,
            scale(scale(4, standalone_aa, cdytail, standalone_incircle_8), standalone_incircle_8, bdx, standalone_16b), standalone_16b,
            scale(scale(4, standalone_bb, cdytail, standalone_incircle_8), standalone_incircle_8, -adx, standalone_16c), standalone_16c, standalone_32, standalone_48), standalone_48);
    }

    if (adxtail !== 0 || adytail !== 0) {
        if (bdxtail !== 0 || bdytail !== 0 || cdxtail !== 0 || cdytail !== 0) {
            s1 = bdxtail * cdy;
            c = splitter * bdxtail;
            ahi = c - (c - bdxtail);
            alo = bdxtail - ahi;
            c = splitter * cdy;
            bhi = c - (c - cdy);
            blo = cdy - bhi;
            s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            t1 = bdx * cdytail;
            c = splitter * bdx;
            ahi = c - (c - bdx);
            alo = bdx - ahi;
            c = splitter * cdytail;
            bhi = c - (c - cdytail);
            blo = cdytail - bhi;
            t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
            _i = s0 + t0;
            bvirt = _i - s0;
            standalone_incircle_u[0] = s0 - (_i - bvirt) + (t0 - bvirt);
            _j = s1 + _i;
            bvirt = _j - s1;
            _0 = s1 - (_j - bvirt) + (_i - bvirt);
            _i = _0 + t1;
            bvirt = _i - _0;
            standalone_incircle_u[1] = _0 - (_i - bvirt) + (t1 - bvirt);
            u3 = _j + _i;
            bvirt = u3 - _j;
            standalone_incircle_u[2] = _j - (u3 - bvirt) + (_i - bvirt);
            standalone_incircle_u[3] = u3;
            s1 = cdxtail * -bdy;
            c = splitter * cdxtail;
            ahi = c - (c - cdxtail);
            alo = cdxtail - ahi;
            c = splitter * -bdy;
            bhi = c - (c - -bdy);
            blo = -bdy - bhi;
            s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            t1 = cdx * -bdytail;
            c = splitter * cdx;
            ahi = c - (c - cdx);
            alo = cdx - ahi;
            c = splitter * -bdytail;
            bhi = c - (c - -bdytail);
            blo = -bdytail - bhi;
            t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
            _i = s0 + t0;
            bvirt = _i - s0;
            standalone_v[0] = s0 - (_i - bvirt) + (t0 - bvirt);
            _j = s1 + _i;
            bvirt = _j - s1;
            _0 = s1 - (_j - bvirt) + (_i - bvirt);
            _i = _0 + t1;
            bvirt = _i - _0;
            standalone_v[1] = _0 - (_i - bvirt) + (t1 - bvirt);
            u3 = _j + _i;
            bvirt = u3 - _j;
            standalone_v[2] = _j - (u3 - bvirt) + (_i - bvirt);
            standalone_v[3] = u3;
            bctlen = sum(4, standalone_incircle_u, 4, standalone_v, standalone_incircle_bct);
            s1 = bdxtail * cdytail;
            c = splitter * bdxtail;
            ahi = c - (c - bdxtail);
            alo = bdxtail - ahi;
            c = splitter * cdytail;
            bhi = c - (c - cdytail);
            blo = cdytail - bhi;
            s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            t1 = cdxtail * bdytail;
            c = splitter * cdxtail;
            ahi = c - (c - cdxtail);
            alo = cdxtail - ahi;
            c = splitter * bdytail;
            bhi = c - (c - bdytail);
            blo = bdytail - bhi;
            t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
            _i = s0 - t0;
            bvirt = s0 - _i;
            standalone_bctt[0] = s0 - (_i + bvirt) + (bvirt - t0);
            _j = s1 + _i;
            bvirt = _j - s1;
            _0 = s1 - (_j - bvirt) + (_i - bvirt);
            _i = _0 - t1;
            bvirt = _0 - _i;
            standalone_bctt[1] = _0 - (_i + bvirt) + (bvirt - t1);
            u3 = _j + _i;
            bvirt = u3 - _j;
            standalone_bctt[2] = _j - (u3 - bvirt) + (_i - bvirt);
            standalone_bctt[3] = u3;
            bcttlen = 4;
        } else {
            standalone_incircle_bct[0] = 0;
            bctlen = 1;
            standalone_bctt[0] = 0;
            bcttlen = 1;
        }
        if (adxtail !== 0) {
            const len = scale(bctlen, standalone_incircle_bct, adxtail, standalone_16c);
            finlen = standalone_incircle_finadd(finlen, sum(
                scale(axtbclen, standalone_axtbc, adxtail, standalone_incircle_16), standalone_incircle_16,
                scale(len, standalone_16c, 2 * adx, standalone_32), standalone_32, standalone_48), standalone_48);

            const len2 = scale(bcttlen, standalone_bctt, adxtail, standalone_incircle_8);
            finlen = standalone_incircle_finadd(finlen, sum_three(
                scale(len2, standalone_incircle_8, 2 * adx, standalone_incircle_16), standalone_incircle_16,
                scale(len2, standalone_incircle_8, adxtail, standalone_16b), standalone_16b,
                scale(len, standalone_16c, adxtail, standalone_32), standalone_32, standalone_32b, standalone_64), standalone_64);

            if (bdytail !== 0) {
                finlen = standalone_incircle_finadd(finlen, scale(scale(4, standalone_cc, adxtail, standalone_incircle_8), standalone_incircle_8, bdytail, standalone_incircle_16), standalone_incircle_16);
            }
            if (cdytail !== 0) {
                finlen = standalone_incircle_finadd(finlen, scale(scale(4, standalone_bb, -adxtail, standalone_incircle_8), standalone_incircle_8, cdytail, standalone_incircle_16), standalone_incircle_16);
            }
        }
        if (adytail !== 0) {
            const len = scale(bctlen, standalone_incircle_bct, adytail, standalone_16c);
            finlen = standalone_incircle_finadd(finlen, sum(
                scale(aytbclen, standalone_aytbc, adytail, standalone_incircle_16), standalone_incircle_16,
                scale(len, standalone_16c, 2 * ady, standalone_32), standalone_32, standalone_48), standalone_48);

            const len2 = scale(bcttlen, standalone_bctt, adytail, standalone_incircle_8);
            finlen = standalone_incircle_finadd(finlen, sum_three(
                scale(len2, standalone_incircle_8, 2 * ady, standalone_incircle_16), standalone_incircle_16,
                scale(len2, standalone_incircle_8, adytail, standalone_16b), standalone_16b,
                scale(len, standalone_16c, adytail, standalone_32), standalone_32, standalone_32b, standalone_64), standalone_64);
        }
    }
    if (bdxtail !== 0 || bdytail !== 0) {
        if (cdxtail !== 0 || cdytail !== 0 || adxtail !== 0 || adytail !== 0) {
            s1 = cdxtail * ady;
            c = splitter * cdxtail;
            ahi = c - (c - cdxtail);
            alo = cdxtail - ahi;
            c = splitter * ady;
            bhi = c - (c - ady);
            blo = ady - bhi;
            s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            t1 = cdx * adytail;
            c = splitter * cdx;
            ahi = c - (c - cdx);
            alo = cdx - ahi;
            c = splitter * adytail;
            bhi = c - (c - adytail);
            blo = adytail - bhi;
            t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
            _i = s0 + t0;
            bvirt = _i - s0;
            standalone_incircle_u[0] = s0 - (_i - bvirt) + (t0 - bvirt);
            _j = s1 + _i;
            bvirt = _j - s1;
            _0 = s1 - (_j - bvirt) + (_i - bvirt);
            _i = _0 + t1;
            bvirt = _i - _0;
            standalone_incircle_u[1] = _0 - (_i - bvirt) + (t1 - bvirt);
            u3 = _j + _i;
            bvirt = u3 - _j;
            standalone_incircle_u[2] = _j - (u3 - bvirt) + (_i - bvirt);
            standalone_incircle_u[3] = u3;
            n1 = -cdy;
            n0 = -cdytail;
            s1 = adxtail * n1;
            c = splitter * adxtail;
            ahi = c - (c - adxtail);
            alo = adxtail - ahi;
            c = splitter * n1;
            bhi = c - (c - n1);
            blo = n1 - bhi;
            s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            t1 = adx * n0;
            c = splitter * adx;
            ahi = c - (c - adx);
            alo = adx - ahi;
            c = splitter * n0;
            bhi = c - (c - n0);
            blo = n0 - bhi;
            t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
            _i = s0 + t0;
            bvirt = _i - s0;
            standalone_v[0] = s0 - (_i - bvirt) + (t0 - bvirt);
            _j = s1 + _i;
            bvirt = _j - s1;
            _0 = s1 - (_j - bvirt) + (_i - bvirt);
            _i = _0 + t1;
            bvirt = _i - _0;
            standalone_v[1] = _0 - (_i - bvirt) + (t1 - bvirt);
            u3 = _j + _i;
            bvirt = u3 - _j;
            standalone_v[2] = _j - (u3 - bvirt) + (_i - bvirt);
            standalone_v[3] = u3;
            catlen = sum(4, standalone_incircle_u, 4, standalone_v, standalone_incircle_cat);
            s1 = cdxtail * adytail;
            c = splitter * cdxtail;
            ahi = c - (c - cdxtail);
            alo = cdxtail - ahi;
            c = splitter * adytail;
            bhi = c - (c - adytail);
            blo = adytail - bhi;
            s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            t1 = adxtail * cdytail;
            c = splitter * adxtail;
            ahi = c - (c - adxtail);
            alo = adxtail - ahi;
            c = splitter * cdytail;
            bhi = c - (c - cdytail);
            blo = cdytail - bhi;
            t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
            _i = s0 - t0;
            bvirt = s0 - _i;
            standalone_catt[0] = s0 - (_i + bvirt) + (bvirt - t0);
            _j = s1 + _i;
            bvirt = _j - s1;
            _0 = s1 - (_j - bvirt) + (_i - bvirt);
            _i = _0 - t1;
            bvirt = _0 - _i;
            standalone_catt[1] = _0 - (_i + bvirt) + (bvirt - t1);
            u3 = _j + _i;
            bvirt = u3 - _j;
            standalone_catt[2] = _j - (u3 - bvirt) + (_i - bvirt);
            standalone_catt[3] = u3;
            cattlen = 4;
        } else {
            standalone_incircle_cat[0] = 0;
            catlen = 1;
            standalone_catt[0] = 0;
            cattlen = 1;
        }
        if (bdxtail !== 0) {
            const len = scale(catlen, standalone_incircle_cat, bdxtail, standalone_16c);
            finlen = standalone_incircle_finadd(finlen, sum(
                scale(bxtcalen, standalone_bxtca, bdxtail, standalone_incircle_16), standalone_incircle_16,
                scale(len, standalone_16c, 2 * bdx, standalone_32), standalone_32, standalone_48), standalone_48);

            const len2 = scale(cattlen, standalone_catt, bdxtail, standalone_incircle_8);
            finlen = standalone_incircle_finadd(finlen, sum_three(
                scale(len2, standalone_incircle_8, 2 * bdx, standalone_incircle_16), standalone_incircle_16,
                scale(len2, standalone_incircle_8, bdxtail, standalone_16b), standalone_16b,
                scale(len, standalone_16c, bdxtail, standalone_32), standalone_32, standalone_32b, standalone_64), standalone_64);

            if (cdytail !== 0) {
                finlen = standalone_incircle_finadd(finlen, scale(scale(4, standalone_aa, bdxtail, standalone_incircle_8), standalone_incircle_8, cdytail, standalone_incircle_16), standalone_incircle_16);
            }
            if (adytail !== 0) {
                finlen = standalone_incircle_finadd(finlen, scale(scale(4, standalone_cc, -bdxtail, standalone_incircle_8), standalone_incircle_8, adytail, standalone_incircle_16), standalone_incircle_16);
            }
        }
        if (bdytail !== 0) {
            const len = scale(catlen, standalone_incircle_cat, bdytail, standalone_16c);
            finlen = standalone_incircle_finadd(finlen, sum(
                scale(bytcalen, standalone_bytca, bdytail, standalone_incircle_16), standalone_incircle_16,
                scale(len, standalone_16c, 2 * bdy, standalone_32), standalone_32, standalone_48), standalone_48);

            const len2 = scale(cattlen, standalone_catt, bdytail, standalone_incircle_8);
            finlen = standalone_incircle_finadd(finlen, sum_three(
                scale(len2, standalone_incircle_8, 2 * bdy, standalone_incircle_16), standalone_incircle_16,
                scale(len2, standalone_incircle_8, bdytail, standalone_16b), standalone_16b,
                scale(len, standalone_16c, bdytail, standalone_32), standalone_32,  standalone_32b, standalone_64), standalone_64);
        }
    }
    if (cdxtail !== 0 || cdytail !== 0) {
        if (adxtail !== 0 || adytail !== 0 || bdxtail !== 0 || bdytail !== 0) {
            s1 = adxtail * bdy;
            c = splitter * adxtail;
            ahi = c - (c - adxtail);
            alo = adxtail - ahi;
            c = splitter * bdy;
            bhi = c - (c - bdy);
            blo = bdy - bhi;
            s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            t1 = adx * bdytail;
            c = splitter * adx;
            ahi = c - (c - adx);
            alo = adx - ahi;
            c = splitter * bdytail;
            bhi = c - (c - bdytail);
            blo = bdytail - bhi;
            t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
            _i = s0 + t0;
            bvirt = _i - s0;
            standalone_incircle_u[0] = s0 - (_i - bvirt) + (t0 - bvirt);
            _j = s1 + _i;
            bvirt = _j - s1;
            _0 = s1 - (_j - bvirt) + (_i - bvirt);
            _i = _0 + t1;
            bvirt = _i - _0;
            standalone_incircle_u[1] = _0 - (_i - bvirt) + (t1 - bvirt);
            u3 = _j + _i;
            bvirt = u3 - _j;
            standalone_incircle_u[2] = _j - (u3 - bvirt) + (_i - bvirt);
            standalone_incircle_u[3] = u3;
            n1 = -ady;
            n0 = -adytail;
            s1 = bdxtail * n1;
            c = splitter * bdxtail;
            ahi = c - (c - bdxtail);
            alo = bdxtail - ahi;
            c = splitter * n1;
            bhi = c - (c - n1);
            blo = n1 - bhi;
            s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            t1 = bdx * n0;
            c = splitter * bdx;
            ahi = c - (c - bdx);
            alo = bdx - ahi;
            c = splitter * n0;
            bhi = c - (c - n0);
            blo = n0 - bhi;
            t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
            _i = s0 + t0;
            bvirt = _i - s0;
            standalone_v[0] = s0 - (_i - bvirt) + (t0 - bvirt);
            _j = s1 + _i;
            bvirt = _j - s1;
            _0 = s1 - (_j - bvirt) + (_i - bvirt);
            _i = _0 + t1;
            bvirt = _i - _0;
            standalone_v[1] = _0 - (_i - bvirt) + (t1 - bvirt);
            u3 = _j + _i;
            bvirt = u3 - _j;
            standalone_v[2] = _j - (u3 - bvirt) + (_i - bvirt);
            standalone_v[3] = u3;
            abtlen = sum(4, standalone_incircle_u, 4, standalone_v, standalone_incircle_abt);
            s1 = adxtail * bdytail;
            c = splitter * adxtail;
            ahi = c - (c - adxtail);
            alo = adxtail - ahi;
            c = splitter * bdytail;
            bhi = c - (c - bdytail);
            blo = bdytail - bhi;
            s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
            t1 = bdxtail * adytail;
            c = splitter * bdxtail;
            ahi = c - (c - bdxtail);
            alo = bdxtail - ahi;
            c = splitter * adytail;
            bhi = c - (c - adytail);
            blo = adytail - bhi;
            t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
            _i = s0 - t0;
            bvirt = s0 - _i;
            standalone_abtt[0] = s0 - (_i + bvirt) + (bvirt - t0);
            _j = s1 + _i;
            bvirt = _j - s1;
            _0 = s1 - (_j - bvirt) + (_i - bvirt);
            _i = _0 - t1;
            bvirt = _0 - _i;
            standalone_abtt[1] = _0 - (_i + bvirt) + (bvirt - t1);
            u3 = _j + _i;
            bvirt = u3 - _j;
            standalone_abtt[2] = _j - (u3 - bvirt) + (_i - bvirt);
            standalone_abtt[3] = u3;
            abttlen = 4;
        } else {
            standalone_incircle_abt[0] = 0;
            abtlen = 1;
            standalone_abtt[0] = 0;
            abttlen = 1;
        }
        if (cdxtail !== 0) {
            const len = scale(abtlen, standalone_incircle_abt, cdxtail, standalone_16c);
            finlen = standalone_incircle_finadd(finlen, sum(
                scale(cxtablen, standalone_cxtab, cdxtail, standalone_incircle_16), standalone_incircle_16,
                scale(len, standalone_16c, 2 * cdx, standalone_32), standalone_32, standalone_48), standalone_48);

            const len2 = scale(abttlen, standalone_abtt, cdxtail, standalone_incircle_8);
            finlen = standalone_incircle_finadd(finlen, sum_three(
                scale(len2, standalone_incircle_8, 2 * cdx, standalone_incircle_16), standalone_incircle_16,
                scale(len2, standalone_incircle_8, cdxtail, standalone_16b), standalone_16b,
                scale(len, standalone_16c, cdxtail, standalone_32), standalone_32, standalone_32b, standalone_64), standalone_64);

            if (adytail !== 0) {
                finlen = standalone_incircle_finadd(finlen, scale(scale(4, standalone_bb, cdxtail, standalone_incircle_8), standalone_incircle_8, adytail, standalone_incircle_16), standalone_incircle_16);
            }
            if (bdytail !== 0) {
                finlen = standalone_incircle_finadd(finlen, scale(scale(4, standalone_aa, -cdxtail, standalone_incircle_8), standalone_incircle_8, bdytail, standalone_incircle_16), standalone_incircle_16);
            }
        }
        if (cdytail !== 0) {
            const len = scale(abtlen, standalone_incircle_abt, cdytail, standalone_16c);
            finlen = standalone_incircle_finadd(finlen, sum(
                scale(cytablen, standalone_cytab, cdytail, standalone_incircle_16), standalone_incircle_16,
                scale(len, standalone_16c, 2 * cdy, standalone_32), standalone_32, standalone_48), standalone_48);

            const len2 = scale(abttlen, standalone_abtt, cdytail, standalone_incircle_8);
            finlen = standalone_incircle_finadd(finlen, sum_three(
                scale(len2, standalone_incircle_8, 2 * cdy, standalone_incircle_16), standalone_incircle_16,
                scale(len2, standalone_incircle_8, cdytail, standalone_16b), standalone_16b,
                scale(len, standalone_16c, cdytail, standalone_32), standalone_32, standalone_32b, standalone_64), standalone_64);
        }
    }

    return standalone_incircle_fin[finlen - 1];
}

function standalone_incircle(ax, ay, bx, by, cx, cy, dx, dy) {
    const adx = ax - dx;
    const bdx = bx - dx;
    const cdx = cx - dx;
    const ady = ay - dy;
    const bdy = by - dy;
    const cdy = cy - dy;

    const bdxcdy = bdx * cdy;
    const cdxbdy = cdx * bdy;
    const alift = adx * adx + ady * ady;

    const cdxady = cdx * ady;
    const adxcdy = adx * cdy;
    const blift = bdx * bdx + bdy * bdy;

    const adxbdy = adx * bdy;
    const bdxady = bdx * ady;
    const clift = cdx * cdx + cdy * cdy;

    const det =
        alift * (bdxcdy - cdxbdy) +
        blift * (cdxady - adxcdy) +
        clift * (adxbdy - bdxady);

    const permanent =
        (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * alift +
        (Math.abs(cdxady) + Math.abs(adxcdy)) * blift +
        (Math.abs(adxbdy) + Math.abs(bdxady)) * clift;

    const errbound = standalone_iccerrboundA * permanent;

    if (det > errbound || -det > errbound) {
        return det;
    }
    return standalone_incircleadapt(ax, ay, bx, by, cx, cy, dx, dy, permanent);
}

function standalone_incirclefast(ax, ay, bx, by, cx, cy, dx, dy) {
    const adx = ax - dx;
    const ady = ay - dy;
    const bdx = bx - dx;
    const bdy = by - dy;
    const cdx = cx - dx;
    const cdy = cy - dy;

    const abdet = adx * bdy - bdx * ady;
    const bcdet = bdx * cdy - cdx * bdy;
    const cadet = cdx * ady - adx * cdy;
    const alift = adx * adx + ady * ady;
    const blift = bdx * bdx + bdy * bdy;
    const clift = cdx * cdx + cdy * cdy;

    return alift * bcdet + blift * cadet + clift * abdet;
}

;// ../../node_modules/robust-predicates/esm/insphere.js


const standalone_isperrboundA = (16 + 224 * standalone_util_epsilon) * standalone_util_epsilon;
const standalone_isperrboundB = (5 + 72 * standalone_util_epsilon) * standalone_util_epsilon;
const standalone_isperrboundC = (71 + 1408 * standalone_util_epsilon) * standalone_util_epsilon * standalone_util_epsilon;

const standalone_insphere_ab = standalone_vec(4);
const standalone_insphere_bc = standalone_vec(4);
const standalone_cd = standalone_vec(4);
const standalone_de = standalone_vec(4);
const standalone_insphere_ea = standalone_vec(4);
const standalone_ac = standalone_vec(4);
const standalone_bd = standalone_vec(4);
const standalone_ce = standalone_vec(4);
const standalone_da = standalone_vec(4);
const standalone_eb = standalone_vec(4);

const standalone_abc = standalone_vec(24);
const standalone_bcd = standalone_vec(24);
const standalone_cde = standalone_vec(24);
const standalone_dea = standalone_vec(24);
const standalone_eab = standalone_vec(24);
const standalone_abd = standalone_vec(24);
const standalone_bce = standalone_vec(24);
const standalone_cda = standalone_vec(24);
const standalone_deb = standalone_vec(24);
const standalone_eac = standalone_vec(24);

const standalone_adet = standalone_vec(1152);
const standalone_bdet = standalone_vec(1152);
const standalone_cdet = standalone_vec(1152);
const standalone_ddet = standalone_vec(1152);
const standalone_edet = standalone_vec(1152);
const standalone_abdet = standalone_vec(2304);
const standalone_cddet = standalone_vec(2304);
const standalone_cdedet = standalone_vec(3456);
const standalone_deter = standalone_vec(5760);

const standalone_insphere_8 = standalone_vec(8);
const standalone_insphere_8b = standalone_vec(8);
const standalone_8c = standalone_vec(8);
const standalone_insphere_16 = standalone_vec(16);
const standalone_24 = standalone_vec(24);
const standalone_insphere_48 = standalone_vec(48);
const standalone_48b = standalone_vec(48);
const standalone_96 = standalone_vec(96);
const standalone_192 = standalone_vec(192);
const standalone_384x = standalone_vec(384);
const standalone_384y = standalone_vec(384);
const standalone_384z = standalone_vec(384);
const standalone_768 = standalone_vec(768);

function standalone_sum_three_scale(a, b, c, az, bz, cz, out) {
    return sum_three(
        scale(4, a, az, standalone_insphere_8), standalone_insphere_8,
        scale(4, b, bz, standalone_insphere_8b), standalone_insphere_8b,
        scale(4, c, cz, standalone_8c), standalone_8c, standalone_insphere_16, out);
}

function standalone_liftexact(alen, a, blen, b, clen, c, dlen, d, x, y, z, out) {
    const len = sum(
        sum(alen, a, blen, b, standalone_insphere_48), standalone_insphere_48,
        negate(sum(clen, c, dlen, d, standalone_48b), standalone_48b), standalone_48b, standalone_96);

    return sum_three(
        scale(scale(len, standalone_96, x, standalone_192), standalone_192, x, standalone_384x), standalone_384x,
        scale(scale(len, standalone_96, y, standalone_192), standalone_192, y, standalone_384y), standalone_384y,
        scale(scale(len, standalone_96, z, standalone_192), standalone_192, z, standalone_384z), standalone_384z, standalone_768, out);
}

function standalone_insphereexact(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez) {
    let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3;

    s1 = ax * by;
    c = splitter * ax;
    ahi = c - (c - ax);
    alo = ax - ahi;
    c = splitter * by;
    bhi = c - (c - by);
    blo = by - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = bx * ay;
    c = splitter * bx;
    ahi = c - (c - bx);
    alo = bx - ahi;
    c = splitter * ay;
    bhi = c - (c - ay);
    blo = ay - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_insphere_ab[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_insphere_ab[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_insphere_ab[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_insphere_ab[3] = u3;
    s1 = bx * cy;
    c = splitter * bx;
    ahi = c - (c - bx);
    alo = bx - ahi;
    c = splitter * cy;
    bhi = c - (c - cy);
    blo = cy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = cx * by;
    c = splitter * cx;
    ahi = c - (c - cx);
    alo = cx - ahi;
    c = splitter * by;
    bhi = c - (c - by);
    blo = by - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_insphere_bc[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_insphere_bc[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_insphere_bc[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_insphere_bc[3] = u3;
    s1 = cx * dy;
    c = splitter * cx;
    ahi = c - (c - cx);
    alo = cx - ahi;
    c = splitter * dy;
    bhi = c - (c - dy);
    blo = dy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = dx * cy;
    c = splitter * dx;
    ahi = c - (c - dx);
    alo = dx - ahi;
    c = splitter * cy;
    bhi = c - (c - cy);
    blo = cy - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_cd[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_cd[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_cd[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_cd[3] = u3;
    s1 = dx * ey;
    c = splitter * dx;
    ahi = c - (c - dx);
    alo = dx - ahi;
    c = splitter * ey;
    bhi = c - (c - ey);
    blo = ey - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = ex * dy;
    c = splitter * ex;
    ahi = c - (c - ex);
    alo = ex - ahi;
    c = splitter * dy;
    bhi = c - (c - dy);
    blo = dy - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_de[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_de[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_de[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_de[3] = u3;
    s1 = ex * ay;
    c = splitter * ex;
    ahi = c - (c - ex);
    alo = ex - ahi;
    c = splitter * ay;
    bhi = c - (c - ay);
    blo = ay - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = ax * ey;
    c = splitter * ax;
    ahi = c - (c - ax);
    alo = ax - ahi;
    c = splitter * ey;
    bhi = c - (c - ey);
    blo = ey - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_insphere_ea[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_insphere_ea[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_insphere_ea[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_insphere_ea[3] = u3;
    s1 = ax * cy;
    c = splitter * ax;
    ahi = c - (c - ax);
    alo = ax - ahi;
    c = splitter * cy;
    bhi = c - (c - cy);
    blo = cy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = cx * ay;
    c = splitter * cx;
    ahi = c - (c - cx);
    alo = cx - ahi;
    c = splitter * ay;
    bhi = c - (c - ay);
    blo = ay - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_ac[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_ac[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_ac[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_ac[3] = u3;
    s1 = bx * dy;
    c = splitter * bx;
    ahi = c - (c - bx);
    alo = bx - ahi;
    c = splitter * dy;
    bhi = c - (c - dy);
    blo = dy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = dx * by;
    c = splitter * dx;
    ahi = c - (c - dx);
    alo = dx - ahi;
    c = splitter * by;
    bhi = c - (c - by);
    blo = by - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_bd[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_bd[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_bd[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_bd[3] = u3;
    s1 = cx * ey;
    c = splitter * cx;
    ahi = c - (c - cx);
    alo = cx - ahi;
    c = splitter * ey;
    bhi = c - (c - ey);
    blo = ey - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = ex * cy;
    c = splitter * ex;
    ahi = c - (c - ex);
    alo = ex - ahi;
    c = splitter * cy;
    bhi = c - (c - cy);
    blo = cy - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_ce[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_ce[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_ce[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_ce[3] = u3;
    s1 = dx * ay;
    c = splitter * dx;
    ahi = c - (c - dx);
    alo = dx - ahi;
    c = splitter * ay;
    bhi = c - (c - ay);
    blo = ay - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = ax * dy;
    c = splitter * ax;
    ahi = c - (c - ax);
    alo = ax - ahi;
    c = splitter * dy;
    bhi = c - (c - dy);
    blo = dy - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_da[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_da[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_da[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_da[3] = u3;
    s1 = ex * by;
    c = splitter * ex;
    ahi = c - (c - ex);
    alo = ex - ahi;
    c = splitter * by;
    bhi = c - (c - by);
    blo = by - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = bx * ey;
    c = splitter * bx;
    ahi = c - (c - bx);
    alo = bx - ahi;
    c = splitter * ey;
    bhi = c - (c - ey);
    blo = ey - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_eb[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_eb[1] = _0 - (_i + bvirt) + (bvirt - t1);
    u3 = _j + _i;
    bvirt = u3 - _j;
    standalone_eb[2] = _j - (u3 - bvirt) + (_i - bvirt);
    standalone_eb[3] = u3;

    const abclen = standalone_sum_three_scale(standalone_insphere_ab, standalone_insphere_bc, standalone_ac, cz, az, -bz, standalone_abc);
    const bcdlen = standalone_sum_three_scale(standalone_insphere_bc, standalone_cd, standalone_bd, dz, bz, -cz, standalone_bcd);
    const cdelen = standalone_sum_three_scale(standalone_cd, standalone_de, standalone_ce, ez, cz, -dz, standalone_cde);
    const dealen = standalone_sum_three_scale(standalone_de, standalone_insphere_ea, standalone_da, az, dz, -ez, standalone_dea);
    const eablen = standalone_sum_three_scale(standalone_insphere_ea, standalone_insphere_ab, standalone_eb, bz, ez, -az, standalone_eab);
    const abdlen = standalone_sum_three_scale(standalone_insphere_ab, standalone_bd, standalone_da, dz, az, bz, standalone_abd);
    const bcelen = standalone_sum_three_scale(standalone_insphere_bc, standalone_ce, standalone_eb, ez, bz, cz, standalone_bce);
    const cdalen = standalone_sum_three_scale(standalone_cd, standalone_da, standalone_ac, az, cz, dz, standalone_cda);
    const deblen = standalone_sum_three_scale(standalone_de, standalone_eb, standalone_bd, bz, dz, ez, standalone_deb);
    const eaclen = standalone_sum_three_scale(standalone_insphere_ea, standalone_ac, standalone_ce, cz, ez, az, standalone_eac);

    const deterlen = sum_three(
        standalone_liftexact(cdelen, standalone_cde, bcelen, standalone_bce, deblen, standalone_deb, bcdlen, standalone_bcd, ax, ay, az, standalone_adet), standalone_adet,
        standalone_liftexact(dealen, standalone_dea, cdalen, standalone_cda, eaclen, standalone_eac, cdelen, standalone_cde, bx, by, bz, standalone_bdet), standalone_bdet,
        sum_three(
            standalone_liftexact(eablen, standalone_eab, deblen, standalone_deb, abdlen, standalone_abd, dealen, standalone_dea, cx, cy, cz, standalone_cdet), standalone_cdet,
            standalone_liftexact(abclen, standalone_abc, eaclen, standalone_eac, bcelen, standalone_bce, eablen, standalone_eab, dx, dy, dz, standalone_ddet), standalone_ddet,
            standalone_liftexact(bcdlen, standalone_bcd, abdlen, standalone_abd, cdalen, standalone_cda, abclen, standalone_abc, ex, ey, ez, standalone_edet), standalone_edet, standalone_cddet, standalone_cdedet), standalone_cdedet, standalone_abdet, standalone_deter);

    return standalone_deter[deterlen - 1];
}

const standalone_xdet = standalone_vec(96);
const standalone_ydet = standalone_vec(96);
const standalone_zdet = standalone_vec(96);
const standalone_insphere_fin = standalone_vec(1152);

function standalone_liftadapt(a, b, c, az, bz, cz, x, y, z, out) {
    const len = standalone_sum_three_scale(a, b, c, az, bz, cz, standalone_24);
    return sum_three(
        scale(scale(len, standalone_24, x, standalone_insphere_48), standalone_insphere_48, x, standalone_xdet), standalone_xdet,
        scale(scale(len, standalone_24, y, standalone_insphere_48), standalone_insphere_48, y, standalone_ydet), standalone_ydet,
        scale(scale(len, standalone_24, z, standalone_insphere_48), standalone_insphere_48, z, standalone_zdet), standalone_zdet, standalone_192, out);
}

function standalone_insphereadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez, permanent) {
    let ab3, bc3, cd3, da3, ac3, bd3;

    let aextail, bextail, cextail, dextail;
    let aeytail, beytail, ceytail, deytail;
    let aeztail, beztail, ceztail, deztail;

    let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0;

    const aex = ax - ex;
    const bex = bx - ex;
    const cex = cx - ex;
    const dex = dx - ex;
    const aey = ay - ey;
    const bey = by - ey;
    const cey = cy - ey;
    const dey = dy - ey;
    const aez = az - ez;
    const bez = bz - ez;
    const cez = cz - ez;
    const dez = dz - ez;

    s1 = aex * bey;
    c = splitter * aex;
    ahi = c - (c - aex);
    alo = aex - ahi;
    c = splitter * bey;
    bhi = c - (c - bey);
    blo = bey - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = bex * aey;
    c = splitter * bex;
    ahi = c - (c - bex);
    alo = bex - ahi;
    c = splitter * aey;
    bhi = c - (c - aey);
    blo = aey - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_insphere_ab[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_insphere_ab[1] = _0 - (_i + bvirt) + (bvirt - t1);
    ab3 = _j + _i;
    bvirt = ab3 - _j;
    standalone_insphere_ab[2] = _j - (ab3 - bvirt) + (_i - bvirt);
    standalone_insphere_ab[3] = ab3;
    s1 = bex * cey;
    c = splitter * bex;
    ahi = c - (c - bex);
    alo = bex - ahi;
    c = splitter * cey;
    bhi = c - (c - cey);
    blo = cey - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = cex * bey;
    c = splitter * cex;
    ahi = c - (c - cex);
    alo = cex - ahi;
    c = splitter * bey;
    bhi = c - (c - bey);
    blo = bey - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_insphere_bc[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_insphere_bc[1] = _0 - (_i + bvirt) + (bvirt - t1);
    bc3 = _j + _i;
    bvirt = bc3 - _j;
    standalone_insphere_bc[2] = _j - (bc3 - bvirt) + (_i - bvirt);
    standalone_insphere_bc[3] = bc3;
    s1 = cex * dey;
    c = splitter * cex;
    ahi = c - (c - cex);
    alo = cex - ahi;
    c = splitter * dey;
    bhi = c - (c - dey);
    blo = dey - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = dex * cey;
    c = splitter * dex;
    ahi = c - (c - dex);
    alo = dex - ahi;
    c = splitter * cey;
    bhi = c - (c - cey);
    blo = cey - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_cd[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_cd[1] = _0 - (_i + bvirt) + (bvirt - t1);
    cd3 = _j + _i;
    bvirt = cd3 - _j;
    standalone_cd[2] = _j - (cd3 - bvirt) + (_i - bvirt);
    standalone_cd[3] = cd3;
    s1 = dex * aey;
    c = splitter * dex;
    ahi = c - (c - dex);
    alo = dex - ahi;
    c = splitter * aey;
    bhi = c - (c - aey);
    blo = aey - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = aex * dey;
    c = splitter * aex;
    ahi = c - (c - aex);
    alo = aex - ahi;
    c = splitter * dey;
    bhi = c - (c - dey);
    blo = dey - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_da[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_da[1] = _0 - (_i + bvirt) + (bvirt - t1);
    da3 = _j + _i;
    bvirt = da3 - _j;
    standalone_da[2] = _j - (da3 - bvirt) + (_i - bvirt);
    standalone_da[3] = da3;
    s1 = aex * cey;
    c = splitter * aex;
    ahi = c - (c - aex);
    alo = aex - ahi;
    c = splitter * cey;
    bhi = c - (c - cey);
    blo = cey - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = cex * aey;
    c = splitter * cex;
    ahi = c - (c - cex);
    alo = cex - ahi;
    c = splitter * aey;
    bhi = c - (c - aey);
    blo = aey - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_ac[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_ac[1] = _0 - (_i + bvirt) + (bvirt - t1);
    ac3 = _j + _i;
    bvirt = ac3 - _j;
    standalone_ac[2] = _j - (ac3 - bvirt) + (_i - bvirt);
    standalone_ac[3] = ac3;
    s1 = bex * dey;
    c = splitter * bex;
    ahi = c - (c - bex);
    alo = bex - ahi;
    c = splitter * dey;
    bhi = c - (c - dey);
    blo = dey - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t1 = dex * bey;
    c = splitter * dex;
    ahi = c - (c - dex);
    alo = dex - ahi;
    c = splitter * bey;
    bhi = c - (c - bey);
    blo = bey - bhi;
    t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t0;
    bvirt = s0 - _i;
    standalone_bd[0] = s0 - (_i + bvirt) + (bvirt - t0);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t1;
    bvirt = _0 - _i;
    standalone_bd[1] = _0 - (_i + bvirt) + (bvirt - t1);
    bd3 = _j + _i;
    bvirt = bd3 - _j;
    standalone_bd[2] = _j - (bd3 - bvirt) + (_i - bvirt);
    standalone_bd[3] = bd3;

    const finlen = sum(
        sum(
            negate(standalone_liftadapt(standalone_insphere_bc, standalone_cd, standalone_bd, dez, bez, -cez, aex, aey, aez, standalone_adet), standalone_adet), standalone_adet,
            standalone_liftadapt(standalone_cd, standalone_da, standalone_ac, aez, cez, dez, bex, bey, bez, standalone_bdet), standalone_bdet, standalone_abdet), standalone_abdet,
        sum(
            negate(standalone_liftadapt(standalone_da, standalone_insphere_ab, standalone_bd, bez, dez, aez, cex, cey, cez, standalone_cdet), standalone_cdet), standalone_cdet,
            standalone_liftadapt(standalone_insphere_ab, standalone_insphere_bc, standalone_ac, cez, aez, -bez, dex, dey, dez, standalone_ddet), standalone_ddet, standalone_cddet), standalone_cddet, standalone_insphere_fin);

    let det = estimate(finlen, standalone_insphere_fin);
    let errbound = standalone_isperrboundB * permanent;
    if (det >= errbound || -det >= errbound) {
        return det;
    }

    bvirt = ax - aex;
    aextail = ax - (aex + bvirt) + (bvirt - ex);
    bvirt = ay - aey;
    aeytail = ay - (aey + bvirt) + (bvirt - ey);
    bvirt = az - aez;
    aeztail = az - (aez + bvirt) + (bvirt - ez);
    bvirt = bx - bex;
    bextail = bx - (bex + bvirt) + (bvirt - ex);
    bvirt = by - bey;
    beytail = by - (bey + bvirt) + (bvirt - ey);
    bvirt = bz - bez;
    beztail = bz - (bez + bvirt) + (bvirt - ez);
    bvirt = cx - cex;
    cextail = cx - (cex + bvirt) + (bvirt - ex);
    bvirt = cy - cey;
    ceytail = cy - (cey + bvirt) + (bvirt - ey);
    bvirt = cz - cez;
    ceztail = cz - (cez + bvirt) + (bvirt - ez);
    bvirt = dx - dex;
    dextail = dx - (dex + bvirt) + (bvirt - ex);
    bvirt = dy - dey;
    deytail = dy - (dey + bvirt) + (bvirt - ey);
    bvirt = dz - dez;
    deztail = dz - (dez + bvirt) + (bvirt - ez);
    if (aextail === 0 && aeytail === 0 && aeztail === 0 &&
        bextail === 0 && beytail === 0 && beztail === 0 &&
        cextail === 0 && ceytail === 0 && ceztail === 0 &&
        dextail === 0 && deytail === 0 && deztail === 0) {
        return det;
    }

    errbound = standalone_isperrboundC * permanent + resulterrbound * Math.abs(det);

    const abeps = (aex * beytail + bey * aextail) - (aey * bextail + bex * aeytail);
    const bceps = (bex * ceytail + cey * bextail) - (bey * cextail + cex * beytail);
    const cdeps = (cex * deytail + dey * cextail) - (cey * dextail + dex * ceytail);
    const daeps = (dex * aeytail + aey * dextail) - (dey * aextail + aex * deytail);
    const aceps = (aex * ceytail + cey * aextail) - (aey * cextail + cex * aeytail);
    const bdeps = (bex * deytail + dey * bextail) - (bey * dextail + dex * beytail);
    det +=
        (((bex * bex + bey * bey + bez * bez) * ((cez * daeps + dez * aceps + aez * cdeps) +
        (ceztail * da3 + deztail * ac3 + aeztail * cd3)) + (dex * dex + dey * dey + dez * dez) *
        ((aez * bceps - bez * aceps + cez * abeps) + (aeztail * bc3 - beztail * ac3 + ceztail * ab3))) -
        ((aex * aex + aey * aey + aez * aez) * ((bez * cdeps - cez * bdeps + dez * bceps) +
        (beztail * cd3 - ceztail * bd3 + deztail * bc3)) + (cex * cex + cey * cey + cez * cez) *
        ((dez * abeps + aez * bdeps + bez * daeps) + (deztail * ab3 + aeztail * bd3 + beztail * da3)))) +
        2 * (((bex * bextail + bey * beytail + bez * beztail) * (cez * da3 + dez * ac3 + aez * cd3) +
        (dex * dextail + dey * deytail + dez * deztail) * (aez * bc3 - bez * ac3 + cez * ab3)) -
        ((aex * aextail + aey * aeytail + aez * aeztail) * (bez * cd3 - cez * bd3 + dez * bc3) +
        (cex * cextail + cey * ceytail + cez * ceztail) * (dez * ab3 + aez * bd3 + bez * da3)));

    if (det >= errbound || -det >= errbound) {
        return det;
    }

    return standalone_insphereexact(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez);
}

function standalone_insphere(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez) {
    const aex = ax - ex;
    const bex = bx - ex;
    const cex = cx - ex;
    const dex = dx - ex;
    const aey = ay - ey;
    const bey = by - ey;
    const cey = cy - ey;
    const dey = dy - ey;
    const aez = az - ez;
    const bez = bz - ez;
    const cez = cz - ez;
    const dez = dz - ez;

    const aexbey = aex * bey;
    const bexaey = bex * aey;
    const ab = aexbey - bexaey;
    const bexcey = bex * cey;
    const cexbey = cex * bey;
    const bc = bexcey - cexbey;
    const cexdey = cex * dey;
    const dexcey = dex * cey;
    const cd = cexdey - dexcey;
    const dexaey = dex * aey;
    const aexdey = aex * dey;
    const da = dexaey - aexdey;
    const aexcey = aex * cey;
    const cexaey = cex * aey;
    const ac = aexcey - cexaey;
    const bexdey = bex * dey;
    const dexbey = dex * bey;
    const bd = bexdey - dexbey;

    const alift = aex * aex + aey * aey + aez * aez;
    const blift = bex * bex + bey * bey + bez * bez;
    const clift = cex * cex + cey * cey + cez * cez;
    const dlift = dex * dex + dey * dey + dez * dez;

    const det =
        (clift * (dez * ab + aez * bd + bez * da) - dlift * (aez * bc - bez * ac + cez * ab)) +
        (alift * (bez * cd - cez * bd + dez * bc) - blift * (cez * da + dez * ac + aez * cd));

    const aezplus = Math.abs(aez);
    const bezplus = Math.abs(bez);
    const cezplus = Math.abs(cez);
    const dezplus = Math.abs(dez);
    const aexbeyplus = Math.abs(aexbey) + Math.abs(bexaey);
    const bexceyplus = Math.abs(bexcey) + Math.abs(cexbey);
    const cexdeyplus = Math.abs(cexdey) + Math.abs(dexcey);
    const dexaeyplus = Math.abs(dexaey) + Math.abs(aexdey);
    const aexceyplus = Math.abs(aexcey) + Math.abs(cexaey);
    const bexdeyplus = Math.abs(bexdey) + Math.abs(dexbey);
    const permanent =
        (cexdeyplus * bezplus + bexdeyplus * cezplus + bexceyplus * dezplus) * alift +
        (dexaeyplus * cezplus + aexceyplus * dezplus + cexdeyplus * aezplus) * blift +
        (aexbeyplus * dezplus + bexdeyplus * aezplus + dexaeyplus * bezplus) * clift +
        (bexceyplus * aezplus + aexceyplus * bezplus + aexbeyplus * cezplus) * dlift;

    const errbound = standalone_isperrboundA * permanent;
    if (det > errbound || -det > errbound) {
        return det;
    }
    return -standalone_insphereadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez, permanent);
}

function standalone_inspherefast(pax, pay, paz, pbx, pby, pbz, pcx, pcy, pcz, pdx, pdy, pdz, pex, pey, pez) {
    const aex = pax - pex;
    const bex = pbx - pex;
    const cex = pcx - pex;
    const dex = pdx - pex;
    const aey = pay - pey;
    const bey = pby - pey;
    const cey = pcy - pey;
    const dey = pdy - pey;
    const aez = paz - pez;
    const bez = pbz - pez;
    const cez = pcz - pez;
    const dez = pdz - pez;

    const ab = aex * bey - bex * aey;
    const bc = bex * cey - cex * bey;
    const cd = cex * dey - dex * cey;
    const da = dex * aey - aex * dey;
    const ac = aex * cey - cex * aey;
    const bd = bex * dey - dex * bey;

    const abc = aez * bc - bez * ac + cez * ab;
    const bcd = bez * cd - cez * bd + dez * bc;
    const cda = cez * da + dez * ac + aez * cd;
    const dab = dez * ab + aez * bd + bez * da;

    const alift = aex * aex + aey * aey + aez * aez;
    const blift = bex * bex + bey * bey + bez * bez;
    const clift = cex * cex + cey * cey + cez * cez;
    const dlift = dex * dex + dey * dey + dez * dez;

    return (clift * dab - dlift * abc) + (alift * bcd - blift * cda);
}

;// ../../node_modules/robust-predicates/index.js






;// ../../node_modules/delaunator/index.js

const standalone_delaunator_EPSILON = Math.pow(2, -52);
const standalone_EDGE_STACK = new Uint32Array(512);



class standalone_Delaunator {

    static from(points, getX = standalone_defaultGetX, getY = standalone_defaultGetY) {
        const n = points.length;
        const coords = new Float64Array(n * 2);

        for (let i = 0; i < n; i++) {
            const p = points[i];
            coords[2 * i] = getX(p);
            coords[2 * i + 1] = getY(p);
        }

        return new standalone_Delaunator(coords);
    }

    constructor(coords) {
        const n = coords.length >> 1;
        if (n > 0 && typeof coords[0] !== 'number') throw new Error('Expected coords to contain numbers.');

        this.coords = coords;

        // arrays that will store the triangulation graph
        const maxTriangles = Math.max(2 * n - 5, 0);
        this._triangles = new Uint32Array(maxTriangles * 3);
        this._halfedges = new Int32Array(maxTriangles * 3);

        // temporary arrays for tracking the edges of the advancing convex hull
        this._hashSize = Math.ceil(Math.sqrt(n));
        this._hullPrev = new Uint32Array(n); // edge to prev edge
        this._hullNext = new Uint32Array(n); // edge to next edge
        this._hullTri = new Uint32Array(n); // edge to adjacent triangle
        this._hullHash = new Int32Array(this._hashSize); // angular edge hash

        // temporary arrays for sorting points
        this._ids = new Uint32Array(n);
        this._dists = new Float64Array(n);

        this.update();
    }

    update() {
        const {coords, _hullPrev: hullPrev, _hullNext: hullNext, _hullTri: hullTri, _hullHash: hullHash} =  this;
        const n = coords.length >> 1;

        // populate an array of point indices; calculate input data bbox
        let minX = Infinity;
        let minY = Infinity;
        let maxX = -Infinity;
        let maxY = -Infinity;

        for (let i = 0; i < n; i++) {
            const x = coords[2 * i];
            const y = coords[2 * i + 1];
            if (x < minX) minX = x;
            if (y < minY) minY = y;
            if (x > maxX) maxX = x;
            if (y > maxY) maxY = y;
            this._ids[i] = i;
        }
        const cx = (minX + maxX) / 2;
        const cy = (minY + maxY) / 2;

        let i0, i1, i2;

        // pick a seed point close to the center
        for (let i = 0, minDist = Infinity; i < n; i++) {
            const d = standalone_dist(cx, cy, coords[2 * i], coords[2 * i + 1]);
            if (d < minDist) {
                i0 = i;
                minDist = d;
            }
        }
        const i0x = coords[2 * i0];
        const i0y = coords[2 * i0 + 1];

        // find the point closest to the seed
        for (let i = 0, minDist = Infinity; i < n; i++) {
            if (i === i0) continue;
            const d = standalone_dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]);
            if (d < minDist && d > 0) {
                i1 = i;
                minDist = d;
            }
        }
        let i1x = coords[2 * i1];
        let i1y = coords[2 * i1 + 1];

        let minRadius = Infinity;

        // find the third point which forms the smallest circumcircle with the first two
        for (let i = 0; i < n; i++) {
            if (i === i0 || i === i1) continue;
            const r = standalone_circumradius(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]);
            if (r < minRadius) {
                i2 = i;
                minRadius = r;
            }
        }
        let i2x = coords[2 * i2];
        let i2y = coords[2 * i2 + 1];

        if (minRadius === Infinity) {
            // order collinear points by dx (or dy if all x are identical)
            // and return the list as a hull
            for (let i = 0; i < n; i++) {
                this._dists[i] = (coords[2 * i] - coords[0]) || (coords[2 * i + 1] - coords[1]);
            }
            standalone_quicksort(this._ids, this._dists, 0, n - 1);
            const hull = new Uint32Array(n);
            let j = 0;
            for (let i = 0, d0 = -Infinity; i < n; i++) {
                const id = this._ids[i];
                const d = this._dists[id];
                if (d > d0) {
                    hull[j++] = id;
                    d0 = d;
                }
            }
            this.hull = hull.subarray(0, j);
            this.triangles = new Uint32Array(0);
            this.halfedges = new Uint32Array(0);
            return;
        }

        // swap the order of the seed points for counter-clockwise orientation
        if (standalone_orient2d(i0x, i0y, i1x, i1y, i2x, i2y) < 0) {
            const i = i1;
            const x = i1x;
            const y = i1y;
            i1 = i2;
            i1x = i2x;
            i1y = i2y;
            i2 = i;
            i2x = x;
            i2y = y;
        }

        const center = standalone_circumcenter(i0x, i0y, i1x, i1y, i2x, i2y);
        this._cx = center.x;
        this._cy = center.y;

        for (let i = 0; i < n; i++) {
            this._dists[i] = standalone_dist(coords[2 * i], coords[2 * i + 1], center.x, center.y);
        }

        // sort the points by distance from the seed triangle circumcenter
        standalone_quicksort(this._ids, this._dists, 0, n - 1);

        // set up the seed triangle as the starting hull
        this._hullStart = i0;
        let hullSize = 3;

        hullNext[i0] = hullPrev[i2] = i1;
        hullNext[i1] = hullPrev[i0] = i2;
        hullNext[i2] = hullPrev[i1] = i0;

        hullTri[i0] = 0;
        hullTri[i1] = 1;
        hullTri[i2] = 2;

        hullHash.fill(-1);
        hullHash[this._hashKey(i0x, i0y)] = i0;
        hullHash[this._hashKey(i1x, i1y)] = i1;
        hullHash[this._hashKey(i2x, i2y)] = i2;

        this.trianglesLen = 0;
        this._addTriangle(i0, i1, i2, -1, -1, -1);

        for (let k = 0, xp, yp; k < this._ids.length; k++) {
            const i = this._ids[k];
            const x = coords[2 * i];
            const y = coords[2 * i + 1];

            // skip near-duplicate points
            if (k > 0 && Math.abs(x - xp) <= standalone_delaunator_EPSILON && Math.abs(y - yp) <= standalone_delaunator_EPSILON) continue;
            xp = x;
            yp = y;

            // skip seed triangle points
            if (i === i0 || i === i1 || i === i2) continue;

            // find a visible edge on the convex hull using edge hash
            let start = 0;
            for (let j = 0, key = this._hashKey(x, y); j < this._hashSize; j++) {
                start = hullHash[(key + j) % this._hashSize];
                if (start !== -1 && start !== hullNext[start]) break;
            }

            start = hullPrev[start];
            let e = start, q;
            while (q = hullNext[e], standalone_orient2d(x, y, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1]) >= 0) {
                e = q;
                if (e === start) {
                    e = -1;
                    break;
                }
            }
            if (e === -1) continue; // likely a near-duplicate point; skip it

            // add the first triangle from the point
            let t = this._addTriangle(e, i, hullNext[e], -1, -1, hullTri[e]);

            // recursively flip triangles from the point until they satisfy the Delaunay condition
            hullTri[i] = this._legalize(t + 2);
            hullTri[e] = t; // keep track of boundary triangles on the hull
            hullSize++;

            // walk forward through the hull, adding more triangles and flipping recursively
            let n = hullNext[e];
            while (q = hullNext[n], standalone_orient2d(x, y, coords[2 * n], coords[2 * n + 1], coords[2 * q], coords[2 * q + 1]) < 0) {
                t = this._addTriangle(n, i, q, hullTri[i], -1, hullTri[n]);
                hullTri[i] = this._legalize(t + 2);
                hullNext[n] = n; // mark as removed
                hullSize--;
                n = q;
            }

            // walk backward from the other side, adding more triangles and flipping
            if (e === start) {
                while (q = hullPrev[e], standalone_orient2d(x, y, coords[2 * q], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1]) < 0) {
                    t = this._addTriangle(q, i, e, -1, hullTri[e], hullTri[q]);
                    this._legalize(t + 2);
                    hullTri[q] = t;
                    hullNext[e] = e; // mark as removed
                    hullSize--;
                    e = q;
                }
            }

            // update the hull indices
            this._hullStart = hullPrev[i] = e;
            hullNext[e] = hullPrev[n] = i;
            hullNext[i] = n;

            // save the two new edges in the hash table
            hullHash[this._hashKey(x, y)] = i;
            hullHash[this._hashKey(coords[2 * e], coords[2 * e + 1])] = e;
        }

        this.hull = new Uint32Array(hullSize);
        for (let i = 0, e = this._hullStart; i < hullSize; i++) {
            this.hull[i] = e;
            e = hullNext[e];
        }

        // trim typed triangle mesh arrays
        this.triangles = this._triangles.subarray(0, this.trianglesLen);
        this.halfedges = this._halfedges.subarray(0, this.trianglesLen);
    }

    _hashKey(x, y) {
        return Math.floor(standalone_pseudoAngle(x - this._cx, y - this._cy) * this._hashSize) % this._hashSize;
    }

    _legalize(a) {
        const {_triangles: triangles, _halfedges: halfedges, coords} = this;

        let i = 0;
        let ar = 0;

        // recursion eliminated with a fixed-size stack
        while (true) {
            const b = halfedges[a];

            /* if the pair of triangles doesn't satisfy the Delaunay condition
             * (p1 is inside the circumcircle of [p0, pl, pr]), flip them,
             * then do the same check/flip recursively for the new pair of triangles
             *
             *           pl                    pl
             *          /||\                  /  \
             *       al/ || \bl            al/    \a
             *        /  ||  \              /      \
             *       /  a||b  \    flip    /___ar___\
             *     p0\   ||   /p1   =>   p0\---bl---/p1
             *        \  ||  /              \      /
             *       ar\ || /br             b\    /br
             *          \||/                  \  /
             *           pr                    pr
             */
            const a0 = a - a % 3;
            ar = a0 + (a + 2) % 3;

            if (b === -1) { // convex hull edge
                if (i === 0) break;
                a = standalone_EDGE_STACK[--i];
                continue;
            }

            const b0 = b - b % 3;
            const al = a0 + (a + 1) % 3;
            const bl = b0 + (b + 2) % 3;

            const p0 = triangles[ar];
            const pr = triangles[a];
            const pl = triangles[al];
            const p1 = triangles[bl];

            const illegal = standalone_inCircle(
                coords[2 * p0], coords[2 * p0 + 1],
                coords[2 * pr], coords[2 * pr + 1],
                coords[2 * pl], coords[2 * pl + 1],
                coords[2 * p1], coords[2 * p1 + 1]);

            if (illegal) {
                triangles[a] = p1;
                triangles[b] = p0;

                const hbl = halfedges[bl];

                // edge swapped on the other side of the hull (rare); fix the halfedge reference
                if (hbl === -1) {
                    let e = this._hullStart;
                    do {
                        if (this._hullTri[e] === bl) {
                            this._hullTri[e] = a;
                            break;
                        }
                        e = this._hullPrev[e];
                    } while (e !== this._hullStart);
                }
                this._link(a, hbl);
                this._link(b, halfedges[ar]);
                this._link(ar, bl);

                const br = b0 + (b + 1) % 3;

                // don't worry about hitting the cap: it can only happen on extremely degenerate input
                if (i < standalone_EDGE_STACK.length) {
                    standalone_EDGE_STACK[i++] = br;
                }
            } else {
                if (i === 0) break;
                a = standalone_EDGE_STACK[--i];
            }
        }

        return ar;
    }

    _link(a, b) {
        this._halfedges[a] = b;
        if (b !== -1) this._halfedges[b] = a;
    }

    // add a new triangle given vertex indices and adjacent half-edge ids
    _addTriangle(i0, i1, i2, a, b, c) {
        const t = this.trianglesLen;

        this._triangles[t] = i0;
        this._triangles[t + 1] = i1;
        this._triangles[t + 2] = i2;

        this._link(t, a);
        this._link(t + 1, b);
        this._link(t + 2, c);

        this.trianglesLen += 3;

        return t;
    }
}

// monotonically increases with real angle, but doesn't need expensive trigonometry
function standalone_pseudoAngle(dx, dy) {
    const p = dx / (Math.abs(dx) + Math.abs(dy));
    return (dy > 0 ? 3 - p : 1 + p) / 4; // [0..1]
}

function standalone_dist(ax, ay, bx, by) {
    const dx = ax - bx;
    const dy = ay - by;
    return dx * dx + dy * dy;
}

function standalone_inCircle(ax, ay, bx, by, cx, cy, px, py) {
    const dx = ax - px;
    const dy = ay - py;
    const ex = bx - px;
    const ey = by - py;
    const fx = cx - px;
    const fy = cy - py;

    const ap = dx * dx + dy * dy;
    const bp = ex * ex + ey * ey;
    const cp = fx * fx + fy * fy;

    return dx * (ey * cp - bp * fy) -
           dy * (ex * cp - bp * fx) +
           ap * (ex * fy - ey * fx) < 0;
}

function standalone_circumradius(ax, ay, bx, by, cx, cy) {
    const dx = bx - ax;
    const dy = by - ay;
    const ex = cx - ax;
    const ey = cy - ay;

    const bl = dx * dx + dy * dy;
    const cl = ex * ex + ey * ey;
    const d = 0.5 / (dx * ey - dy * ex);

    const x = (ey * bl - dy * cl) * d;
    const y = (dx * cl - ex * bl) * d;

    return x * x + y * y;
}

function standalone_circumcenter(ax, ay, bx, by, cx, cy) {
    const dx = bx - ax;
    const dy = by - ay;
    const ex = cx - ax;
    const ey = cy - ay;

    const bl = dx * dx + dy * dy;
    const cl = ex * ex + ey * ey;
    const d = 0.5 / (dx * ey - dy * ex);

    const x = ax + (ey * bl - dy * cl) * d;
    const y = ay + (dx * cl - ex * bl) * d;

    return {x, y};
}

function standalone_quicksort(ids, dists, left, right) {
    if (right - left <= 20) {
        for (let i = left + 1; i <= right; i++) {
            const temp = ids[i];
            const tempDist = dists[temp];
            let j = i - 1;
            while (j >= left && dists[ids[j]] > tempDist) ids[j + 1] = ids[j--];
            ids[j + 1] = temp;
        }
    } else {
        const median = (left + right) >> 1;
        let i = left + 1;
        let j = right;
        standalone_delaunator_swap(ids, median, i);
        if (dists[ids[left]] > dists[ids[right]]) standalone_delaunator_swap(ids, left, right);
        if (dists[ids[i]] > dists[ids[right]]) standalone_delaunator_swap(ids, i, right);
        if (dists[ids[left]] > dists[ids[i]]) standalone_delaunator_swap(ids, left, i);

        const temp = ids[i];
        const tempDist = dists[temp];
        while (true) {
            do i++; while (dists[ids[i]] < tempDist);
            do j--; while (dists[ids[j]] > tempDist);
            if (j < i) break;
            standalone_delaunator_swap(ids, i, j);
        }
        ids[left + 1] = ids[j];
        ids[j] = temp;

        if (right - i + 1 >= j - left) {
            standalone_quicksort(ids, dists, i, right);
            standalone_quicksort(ids, dists, left, j - 1);
        } else {
            standalone_quicksort(ids, dists, left, j - 1);
            standalone_quicksort(ids, dists, i, right);
        }
    }
}

function standalone_delaunator_swap(arr, i, j) {
    const tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

function standalone_defaultGetX(p) {
    return p[0];
}
function standalone_defaultGetY(p) {
    return p[1];
}

;// ../../node_modules/d3-delaunay/src/path.js
const standalone_src_path_epsilon = 1e-6;

class standalone_path_Path {
  constructor() {
    this._x0 = this._y0 = // start of current subpath
    this._x1 = this._y1 = null; // end of current subpath
    this._ = "";
  }
  moveTo(x, y) {
    this._ += `M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}`;
  }
  closePath() {
    if (this._x1 !== null) {
      this._x1 = this._x0, this._y1 = this._y0;
      this._ += "Z";
    }
  }
  lineTo(x, y) {
    this._ += `L${this._x1 = +x},${this._y1 = +y}`;
  }
  arc(x, y, r) {
    x = +x, y = +y, r = +r;
    const x0 = x + r;
    const y0 = y;
    if (r < 0) throw new Error("negative radius");
    if (this._x1 === null) this._ += `M${x0},${y0}`;
    else if (Math.abs(this._x1 - x0) > standalone_src_path_epsilon || Math.abs(this._y1 - y0) > standalone_src_path_epsilon) this._ += "L" + x0 + "," + y0;
    if (!r) return;
    this._ += `A${r},${r},0,1,1,${x - r},${y}A${r},${r},0,1,1,${this._x1 = x0},${this._y1 = y0}`;
  }
  rect(x, y, w, h) {
    this._ += `M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}h${+w}v${+h}h${-w}Z`;
  }
  value() {
    return this._ || null;
  }
}

;// ../../node_modules/d3-delaunay/src/polygon.js
class standalone_Polygon {
  constructor() {
    this._ = [];
  }
  moveTo(x, y) {
    this._.push([x, y]);
  }
  closePath() {
    this._.push(this._[0].slice());
  }
  lineTo(x, y) {
    this._.push([x, y]);
  }
  value() {
    return this._.length ? this._ : null;
  }
}

;// ../../node_modules/d3-delaunay/src/voronoi.js



class standalone_Voronoi {
  constructor(delaunay, [xmin, ymin, xmax, ymax] = [0, 0, 960, 500]) {
    if (!((xmax = +xmax) >= (xmin = +xmin)) || !((ymax = +ymax) >= (ymin = +ymin))) throw new Error("invalid bounds");
    this.delaunay = delaunay;
    this._circumcenters = new Float64Array(delaunay.points.length * 2);
    this.vectors = new Float64Array(delaunay.points.length * 2);
    this.xmax = xmax, this.xmin = xmin;
    this.ymax = ymax, this.ymin = ymin;
    this._init();
  }
  update() {
    this.delaunay.update();
    this._init();
    return this;
  }
  _init() {
    const {delaunay: {points, hull, triangles}, vectors} = this;
    let bx, by; // lazily computed barycenter of the hull

    // Compute circumcenters.
    const circumcenters = this.circumcenters = this._circumcenters.subarray(0, triangles.length / 3 * 2);
    for (let i = 0, j = 0, n = triangles.length, x, y; i < n; i += 3, j += 2) {
      const t1 = triangles[i] * 2;
      const t2 = triangles[i + 1] * 2;
      const t3 = triangles[i + 2] * 2;
      const x1 = points[t1];
      const y1 = points[t1 + 1];
      const x2 = points[t2];
      const y2 = points[t2 + 1];
      const x3 = points[t3];
      const y3 = points[t3 + 1];

      const dx = x2 - x1;
      const dy = y2 - y1;
      const ex = x3 - x1;
      const ey = y3 - y1;
      const ab = (dx * ey - dy * ex) * 2;

      if (Math.abs(ab) < 1e-9) {
        // For a degenerate triangle, the circumcenter is at the infinity, in a
        // direction orthogonal to the halfedge and away from the “center” of
        // the diagram <bx, by>, defined as the hull’s barycenter.
        if (bx === undefined) {
          bx = by = 0;
          for (const i of hull) bx += points[i * 2], by += points[i * 2 + 1];
          bx /= hull.length, by /= hull.length;
        }
        const a = 1e9 * Math.sign((bx - x1) * ey - (by - y1) * ex);
        x = (x1 + x3) / 2 - a * ey;
        y = (y1 + y3) / 2 + a * ex;
      } else {
        const d = 1 / ab;
        const bl = dx * dx + dy * dy;
        const cl = ex * ex + ey * ey;
        x = x1 + (ey * bl - dy * cl) * d;
        y = y1 + (dx * cl - ex * bl) * d;
      }
      circumcenters[j] = x;
      circumcenters[j + 1] = y;
    }

    // Compute exterior cell rays.
    let h = hull[hull.length - 1];
    let p0, p1 = h * 4;
    let x0, x1 = points[2 * h];
    let y0, y1 = points[2 * h + 1];
    vectors.fill(0);
    for (let i = 0; i < hull.length; ++i) {
      h = hull[i];
      p0 = p1, x0 = x1, y0 = y1;
      p1 = h * 4, x1 = points[2 * h], y1 = points[2 * h + 1];
      vectors[p0 + 2] = vectors[p1] = y0 - y1;
      vectors[p0 + 3] = vectors[p1 + 1] = x1 - x0;
    }
  }
  render(context) {
    const buffer = context == null ? context = new standalone_path_Path : undefined;
    const {delaunay: {halfedges, inedges, hull}, circumcenters, vectors} = this;
    if (hull.length <= 1) return null;
    for (let i = 0, n = halfedges.length; i < n; ++i) {
      const j = halfedges[i];
      if (j < i) continue;
      const ti = Math.floor(i / 3) * 2;
      const tj = Math.floor(j / 3) * 2;
      const xi = circumcenters[ti];
      const yi = circumcenters[ti + 1];
      const xj = circumcenters[tj];
      const yj = circumcenters[tj + 1];
      this._renderSegment(xi, yi, xj, yj, context);
    }
    let h0, h1 = hull[hull.length - 1];
    for (let i = 0; i < hull.length; ++i) {
      h0 = h1, h1 = hull[i];
      const t = Math.floor(inedges[h1] / 3) * 2;
      const x = circumcenters[t];
      const y = circumcenters[t + 1];
      const v = h0 * 4;
      const p = this._project(x, y, vectors[v + 2], vectors[v + 3]);
      if (p) this._renderSegment(x, y, p[0], p[1], context);
    }
    return buffer && buffer.value();
  }
  renderBounds(context) {
    const buffer = context == null ? context = new standalone_path_Path : undefined;
    context.rect(this.xmin, this.ymin, this.xmax - this.xmin, this.ymax - this.ymin);
    return buffer && buffer.value();
  }
  renderCell(i, context) {
    const buffer = context == null ? context = new standalone_path_Path : undefined;
    const points = this._clip(i);
    if (points === null || !points.length) return;
    context.moveTo(points[0], points[1]);
    let n = points.length;
    while (points[0] === points[n-2] && points[1] === points[n-1] && n > 1) n -= 2;
    for (let i = 2; i < n; i += 2) {
      if (points[i] !== points[i-2] || points[i+1] !== points[i-1])
        context.lineTo(points[i], points[i + 1]);
    }
    context.closePath();
    return buffer && buffer.value();
  }
  *cellPolygons() {
    const {delaunay: {points}} = this;
    for (let i = 0, n = points.length / 2; i < n; ++i) {
      const cell = this.cellPolygon(i);
      if (cell) cell.index = i, yield cell;
    }
  }
  cellPolygon(i) {
    const polygon = new standalone_Polygon;
    this.renderCell(i, polygon);
    return polygon.value();
  }
  _renderSegment(x0, y0, x1, y1, context) {
    let S;
    const c0 = this._regioncode(x0, y0);
    const c1 = this._regioncode(x1, y1);
    if (c0 === 0 && c1 === 0) {
      context.moveTo(x0, y0);
      context.lineTo(x1, y1);
    } else if (S = this._clipSegment(x0, y0, x1, y1, c0, c1)) {
      context.moveTo(S[0], S[1]);
      context.lineTo(S[2], S[3]);
    }
  }
  contains(i, x, y) {
    if ((x = +x, x !== x) || (y = +y, y !== y)) return false;
    return this.delaunay._step(i, x, y) === i;
  }
  *neighbors(i) {
    const ci = this._clip(i);
    if (ci) for (const j of this.delaunay.neighbors(i)) {
      const cj = this._clip(j);
      // find the common edge
      if (cj) loop: for (let ai = 0, li = ci.length; ai < li; ai += 2) {
        for (let aj = 0, lj = cj.length; aj < lj; aj += 2) {
          if (ci[ai] === cj[aj]
              && ci[ai + 1] === cj[aj + 1]
              && ci[(ai + 2) % li] === cj[(aj + lj - 2) % lj]
              && ci[(ai + 3) % li] === cj[(aj + lj - 1) % lj]) {
            yield j;
            break loop;
          }
        }
      }
    }
  }
  _cell(i) {
    const {circumcenters, delaunay: {inedges, halfedges, triangles}} = this;
    const e0 = inedges[i];
    if (e0 === -1) return null; // coincident point
    const points = [];
    let e = e0;
    do {
      const t = Math.floor(e / 3);
      points.push(circumcenters[t * 2], circumcenters[t * 2 + 1]);
      e = e % 3 === 2 ? e - 2 : e + 1;
      if (triangles[e] !== i) break; // bad triangulation
      e = halfedges[e];
    } while (e !== e0 && e !== -1);
    return points;
  }
  _clip(i) {
    // degenerate case (1 valid point: return the box)
    if (i === 0 && this.delaunay.hull.length === 1) {
      return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];
    }
    const points = this._cell(i);
    if (points === null) return null;
    const {vectors: V} = this;
    const v = i * 4;
    return this._simplify(V[v] || V[v + 1]
        ? this._clipInfinite(i, points, V[v], V[v + 1], V[v + 2], V[v + 3])
        : this._clipFinite(i, points));
  }
  _clipFinite(i, points) {
    const n = points.length;
    let P = null;
    let x0, y0, x1 = points[n - 2], y1 = points[n - 1];
    let c0, c1 = this._regioncode(x1, y1);
    let e0, e1 = 0;
    for (let j = 0; j < n; j += 2) {
      x0 = x1, y0 = y1, x1 = points[j], y1 = points[j + 1];
      c0 = c1, c1 = this._regioncode(x1, y1);
      if (c0 === 0 && c1 === 0) {
        e0 = e1, e1 = 0;
        if (P) P.push(x1, y1);
        else P = [x1, y1];
      } else {
        let S, sx0, sy0, sx1, sy1;
        if (c0 === 0) {
          if ((S = this._clipSegment(x0, y0, x1, y1, c0, c1)) === null) continue;
          [sx0, sy0, sx1, sy1] = S;
        } else {
          if ((S = this._clipSegment(x1, y1, x0, y0, c1, c0)) === null) continue;
          [sx1, sy1, sx0, sy0] = S;
          e0 = e1, e1 = this._edgecode(sx0, sy0);
          if (e0 && e1) this._edge(i, e0, e1, P, P.length);
          if (P) P.push(sx0, sy0);
          else P = [sx0, sy0];
        }
        e0 = e1, e1 = this._edgecode(sx1, sy1);
        if (e0 && e1) this._edge(i, e0, e1, P, P.length);
        if (P) P.push(sx1, sy1);
        else P = [sx1, sy1];
      }
    }
    if (P) {
      e0 = e1, e1 = this._edgecode(P[0], P[1]);
      if (e0 && e1) this._edge(i, e0, e1, P, P.length);
    } else if (this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {
      return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];
    }
    return P;
  }
  _clipSegment(x0, y0, x1, y1, c0, c1) {
    // for more robustness, always consider the segment in the same order
    const flip = c0 < c1;
    if (flip) [x0, y0, x1, y1, c0, c1] = [x1, y1, x0, y0, c1, c0];
    while (true) {
      if (c0 === 0 && c1 === 0) return flip ? [x1, y1, x0, y0] : [x0, y0, x1, y1];
      if (c0 & c1) return null;
      let x, y, c = c0 || c1;
      if (c & 0b1000) x = x0 + (x1 - x0) * (this.ymax - y0) / (y1 - y0), y = this.ymax;
      else if (c & 0b0100) x = x0 + (x1 - x0) * (this.ymin - y0) / (y1 - y0), y = this.ymin;
      else if (c & 0b0010) y = y0 + (y1 - y0) * (this.xmax - x0) / (x1 - x0), x = this.xmax;
      else y = y0 + (y1 - y0) * (this.xmin - x0) / (x1 - x0), x = this.xmin;
      if (c0) x0 = x, y0 = y, c0 = this._regioncode(x0, y0);
      else x1 = x, y1 = y, c1 = this._regioncode(x1, y1);
    }
  }
  _clipInfinite(i, points, vx0, vy0, vxn, vyn) {
    let P = Array.from(points), p;
    if (p = this._project(P[0], P[1], vx0, vy0)) P.unshift(p[0], p[1]);
    if (p = this._project(P[P.length - 2], P[P.length - 1], vxn, vyn)) P.push(p[0], p[1]);
    if (P = this._clipFinite(i, P)) {
      for (let j = 0, n = P.length, c0, c1 = this._edgecode(P[n - 2], P[n - 1]); j < n; j += 2) {
        c0 = c1, c1 = this._edgecode(P[j], P[j + 1]);
        if (c0 && c1) j = this._edge(i, c0, c1, P, j), n = P.length;
      }
    } else if (this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {
      P = [this.xmin, this.ymin, this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax];
    }
    return P;
  }
  _edge(i, e0, e1, P, j) {
    while (e0 !== e1) {
      let x, y;
      switch (e0) {
        case 0b0101: e0 = 0b0100; continue; // top-left
        case 0b0100: e0 = 0b0110, x = this.xmax, y = this.ymin; break; // top
        case 0b0110: e0 = 0b0010; continue; // top-right
        case 0b0010: e0 = 0b1010, x = this.xmax, y = this.ymax; break; // right
        case 0b1010: e0 = 0b1000; continue; // bottom-right
        case 0b1000: e0 = 0b1001, x = this.xmin, y = this.ymax; break; // bottom
        case 0b1001: e0 = 0b0001; continue; // bottom-left
        case 0b0001: e0 = 0b0101, x = this.xmin, y = this.ymin; break; // left
      }
      // Note: this implicitly checks for out of bounds: if P[j] or P[j+1] are
      // undefined, the conditional statement will be executed.
      if ((P[j] !== x || P[j + 1] !== y) && this.contains(i, x, y)) {
        P.splice(j, 0, x, y), j += 2;
      }
    }
    return j;
  }
  _project(x0, y0, vx, vy) {
    let t = Infinity, c, x, y;
    if (vy < 0) { // top
      if (y0 <= this.ymin) return null;
      if ((c = (this.ymin - y0) / vy) < t) y = this.ymin, x = x0 + (t = c) * vx;
    } else if (vy > 0) { // bottom
      if (y0 >= this.ymax) return null;
      if ((c = (this.ymax - y0) / vy) < t) y = this.ymax, x = x0 + (t = c) * vx;
    }
    if (vx > 0) { // right
      if (x0 >= this.xmax) return null;
      if ((c = (this.xmax - x0) / vx) < t) x = this.xmax, y = y0 + (t = c) * vy;
    } else if (vx < 0) { // left
      if (x0 <= this.xmin) return null;
      if ((c = (this.xmin - x0) / vx) < t) x = this.xmin, y = y0 + (t = c) * vy;
    }
    return [x, y];
  }
  _edgecode(x, y) {
    return (x === this.xmin ? 0b0001
        : x === this.xmax ? 0b0010 : 0b0000)
        | (y === this.ymin ? 0b0100
        : y === this.ymax ? 0b1000 : 0b0000);
  }
  _regioncode(x, y) {
    return (x < this.xmin ? 0b0001
        : x > this.xmax ? 0b0010 : 0b0000)
        | (y < this.ymin ? 0b0100
        : y > this.ymax ? 0b1000 : 0b0000);
  }
  _simplify(P) {
    if (P && P.length > 4) {
      for (let i = 0; i < P.length; i+= 2) {
        const j = (i + 2) % P.length, k = (i + 4) % P.length;
        if (P[i] === P[j] && P[j] === P[k] || P[i + 1] === P[j + 1] && P[j + 1] === P[k + 1]) {
          P.splice(j, 2), i -= 2;
        }
      }
      if (!P.length) P = null;
    }
    return P;
  }
}

;// ../../node_modules/d3-delaunay/src/delaunay.js





const standalone_delaunay_tau = 2 * Math.PI, standalone_delaunay_pow = Math.pow;

function standalone_pointX(p) {
  return p[0];
}

function standalone_pointY(p) {
  return p[1];
}

// A triangulation is collinear if all its triangles have a non-null area
function standalone_delaunay_collinear(d) {
  const {triangles, coords} = d;
  for (let i = 0; i < triangles.length; i += 3) {
    const a = 2 * triangles[i],
          b = 2 * triangles[i + 1],
          c = 2 * triangles[i + 2],
          cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1])
                - (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]);
    if (cross > 1e-10) return false;
  }
  return true;
}

function standalone_jitter(x, y, r) {
  return [x + Math.sin(x + y) * r, y + Math.cos(x - y) * r];
}

class standalone_Delaunay {
  static from(points, fx = standalone_pointX, fy = standalone_pointY, that) {
    return new standalone_Delaunay("length" in points
        ? standalone_flatArray(points, fx, fy, that)
        : Float64Array.from(standalone_flatIterable(points, fx, fy, that)));
  }
  constructor(points) {
    this._delaunator = new standalone_Delaunator(points);
    this.inedges = new Int32Array(points.length / 2);
    this._hullIndex = new Int32Array(points.length / 2);
    this.points = this._delaunator.coords;
    this._init();
  }
  update() {
    this._delaunator.update();
    this._init();
    return this;
  }
  _init() {
    const d = this._delaunator, points = this.points;

    // check for collinear
    if (d.hull && d.hull.length > 2 && standalone_delaunay_collinear(d)) {
      this.collinear = Int32Array.from({length: points.length/2}, (_,i) => i)
        .sort((i, j) => points[2 * i] - points[2 * j] || points[2 * i + 1] - points[2 * j + 1]); // for exact neighbors
      const e = this.collinear[0], f = this.collinear[this.collinear.length - 1],
        bounds = [ points[2 * e], points[2 * e + 1], points[2 * f], points[2 * f + 1] ],
        r = 1e-8 * Math.hypot(bounds[3] - bounds[1], bounds[2] - bounds[0]);
      for (let i = 0, n = points.length / 2; i < n; ++i) {
        const p = standalone_jitter(points[2 * i], points[2 * i + 1], r);
        points[2 * i] = p[0];
        points[2 * i + 1] = p[1];
      }
      this._delaunator = new standalone_Delaunator(points);
    } else {
      delete this.collinear;
    }

    const halfedges = this.halfedges = this._delaunator.halfedges;
    const hull = this.hull = this._delaunator.hull;
    const triangles = this.triangles = this._delaunator.triangles;
    const inedges = this.inedges.fill(-1);
    const hullIndex = this._hullIndex.fill(-1);

    // Compute an index from each point to an (arbitrary) incoming halfedge
    // Used to give the first neighbor of each point; for this reason,
    // on the hull we give priority to exterior halfedges
    for (let e = 0, n = halfedges.length; e < n; ++e) {
      const p = triangles[e % 3 === 2 ? e - 2 : e + 1];
      if (halfedges[e] === -1 || inedges[p] === -1) inedges[p] = e;
    }
    for (let i = 0, n = hull.length; i < n; ++i) {
      hullIndex[hull[i]] = i;
    }

    // degenerate case: 1 or 2 (distinct) points
    if (hull.length <= 2 && hull.length > 0) {
      this.triangles = new Int32Array(3).fill(-1);
      this.halfedges = new Int32Array(3).fill(-1);
      this.triangles[0] = hull[0];
      inedges[hull[0]] = 1;
      if (hull.length === 2) {
        inedges[hull[1]] = 0;
        this.triangles[1] = hull[1];
        this.triangles[2] = hull[1];
      }
    }
  }
  voronoi(bounds) {
    return new standalone_Voronoi(this, bounds);
  }
  *neighbors(i) {
    const {inedges, hull, _hullIndex, halfedges, triangles, collinear} = this;

    // degenerate case with several collinear points
    if (collinear) {
      const l = collinear.indexOf(i);
      if (l > 0) yield collinear[l - 1];
      if (l < collinear.length - 1) yield collinear[l + 1];
      return;
    }

    const e0 = inedges[i];
    if (e0 === -1) return; // coincident point
    let e = e0, p0 = -1;
    do {
      yield p0 = triangles[e];
      e = e % 3 === 2 ? e - 2 : e + 1;
      if (triangles[e] !== i) return; // bad triangulation
      e = halfedges[e];
      if (e === -1) {
        const p = hull[(_hullIndex[i] + 1) % hull.length];
        if (p !== p0) yield p;
        return;
      }
    } while (e !== e0);
  }
  find(x, y, i = 0) {
    if ((x = +x, x !== x) || (y = +y, y !== y)) return -1;
    const i0 = i;
    let c;
    while ((c = this._step(i, x, y)) >= 0 && c !== i && c !== i0) i = c;
    return c;
  }
  _step(i, x, y) {
    const {inedges, hull, _hullIndex, halfedges, triangles, points} = this;
    if (inedges[i] === -1 || !points.length) return (i + 1) % (points.length >> 1);
    let c = i;
    let dc = standalone_delaunay_pow(x - points[i * 2], 2) + standalone_delaunay_pow(y - points[i * 2 + 1], 2);
    const e0 = inedges[i];
    let e = e0;
    do {
      let t = triangles[e];
      const dt = standalone_delaunay_pow(x - points[t * 2], 2) + standalone_delaunay_pow(y - points[t * 2 + 1], 2);
      if (dt < dc) dc = dt, c = t;
      e = e % 3 === 2 ? e - 2 : e + 1;
      if (triangles[e] !== i) break; // bad triangulation
      e = halfedges[e];
      if (e === -1) {
        e = hull[(_hullIndex[i] + 1) % hull.length];
        if (e !== t) {
          if (standalone_delaunay_pow(x - points[e * 2], 2) + standalone_delaunay_pow(y - points[e * 2 + 1], 2) < dc) return e;
        }
        break;
      }
    } while (e !== e0);
    return c;
  }
  render(context) {
    const buffer = context == null ? context = new standalone_path_Path : undefined;
    const {points, halfedges, triangles} = this;
    for (let i = 0, n = halfedges.length; i < n; ++i) {
      const j = halfedges[i];
      if (j < i) continue;
      const ti = triangles[i] * 2;
      const tj = triangles[j] * 2;
      context.moveTo(points[ti], points[ti + 1]);
      context.lineTo(points[tj], points[tj + 1]);
    }
    this.renderHull(context);
    return buffer && buffer.value();
  }
  renderPoints(context, r) {
    if (r === undefined && (!context || typeof context.moveTo !== "function")) r = context, context = null;
    r = r == undefined ? 2 : +r;
    const buffer = context == null ? context = new standalone_path_Path : undefined;
    const {points} = this;
    for (let i = 0, n = points.length; i < n; i += 2) {
      const x = points[i], y = points[i + 1];
      context.moveTo(x + r, y);
      context.arc(x, y, r, 0, standalone_delaunay_tau);
    }
    return buffer && buffer.value();
  }
  renderHull(context) {
    const buffer = context == null ? context = new standalone_path_Path : undefined;
    const {hull, points} = this;
    const h = hull[0] * 2, n = hull.length;
    context.moveTo(points[h], points[h + 1]);
    for (let i = 1; i < n; ++i) {
      const h = 2 * hull[i];
      context.lineTo(points[h], points[h + 1]);
    }
    context.closePath();
    return buffer && buffer.value();
  }
  hullPolygon() {
    const polygon = new standalone_Polygon;
    this.renderHull(polygon);
    return polygon.value();
  }
  renderTriangle(i, context) {
    const buffer = context == null ? context = new standalone_path_Path : undefined;
    const {points, triangles} = this;
    const t0 = triangles[i *= 3] * 2;
    const t1 = triangles[i + 1] * 2;
    const t2 = triangles[i + 2] * 2;
    context.moveTo(points[t0], points[t0 + 1]);
    context.lineTo(points[t1], points[t1 + 1]);
    context.lineTo(points[t2], points[t2 + 1]);
    context.closePath();
    return buffer && buffer.value();
  }
  *trianglePolygons() {
    const {triangles} = this;
    for (let i = 0, n = triangles.length / 3; i < n; ++i) {
      yield this.trianglePolygon(i);
    }
  }
  trianglePolygon(i) {
    const polygon = new standalone_Polygon;
    this.renderTriangle(i, polygon);
    return polygon.value();
  }
}

function standalone_flatArray(points, fx, fy, that) {
  const n = points.length;
  const array = new Float64Array(n * 2);
  for (let i = 0; i < n; ++i) {
    const p = points[i];
    array[i * 2] = fx.call(that, p, i, points);
    array[i * 2 + 1] = fy.call(that, p, i, points);
  }
  return array;
}

function* standalone_flatIterable(points, fx, fy, that) {
  let i = 0;
  for (const p of points) {
    yield fx.call(that, p, i, points);
    yield fy.call(that, p, i, points);
    ++i;
  }
}

;// ../../node_modules/vega-voronoi/build/vega-voronoi.module.js




function standalone_vega_voronoi_module_Voronoi(params) {
  standalone_Transform.call(this, null, params);
}
standalone_vega_voronoi_module_Voronoi.Definition = {
  'type': 'Voronoi',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'x',
    'type': 'field',
    'required': true
  }, {
    'name': 'y',
    'type': 'field',
    'required': true
  }, {
    'name': 'size',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'extent',
    'type': 'array',
    'array': true,
    'length': 2,
    'default': [[-1e5, -1e5], [1e5, 1e5]],
    'content': {
      'type': 'number',
      'array': true,
      'length': 2
    }
  }, {
    'name': 'as',
    'type': 'string',
    'default': 'path'
  }]
};
const standalone_defaultExtent = [-1e5, -1e5, 1e5, 1e5];
standalone_inherits(standalone_vega_voronoi_module_Voronoi, standalone_Transform, {
  transform(_, pulse) {
    const as = _.as || 'path',
      data = pulse.source;

    // nothing to do if no data
    if (!data || !data.length) return pulse;

    // configure and construct voronoi diagram
    let s = _.size;
    s = s ? [0, 0, s[0], s[1]] : (s = _.extent) ? [s[0][0], s[0][1], s[1][0], s[1][1]] : standalone_defaultExtent;
    const voronoi = this.value = standalone_Delaunay.from(data, _.x, _.y).voronoi(s);

    // map polygons to paths
    for (let i = 0, n = data.length; i < n; ++i) {
      const polygon = voronoi.cellPolygon(i);
      data[i][as] = polygon && !standalone_isPoint(polygon) ? standalone_toPathString(polygon) : null;
    }
    return pulse.reflow(_.modified()).modifies(as);
  }
});

// suppress duplicated end point vertices
function standalone_toPathString(p) {
  const x = p[0][0],
    y = p[0][1];
  let n = p.length - 1;
  for (; p[n][0] === x && p[n][1] === y; --n);
  return 'M' + p.slice(0, n + 1).join('L') + 'Z';
}
function standalone_isPoint(p) {
  return p.length === 2 && p[0][0] === p[1][0] && p[0][1] === p[1][1];
}



;// ../../node_modules/vega-wordcloud/build/vega-wordcloud.module.js






/*
Copyright (c) 2013, Jason Davies.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

  * The name Jason Davies may not be used to endorse or promote products
    derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL JASON DAVIES BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// Word cloud layout by Jason Davies, https://www.jasondavies.com/wordcloud/
// Algorithm due to Jonathan Feinberg, http://static.mrfeinberg.com/bv_ch03.pdf

var standalone_cloudRadians = Math.PI / 180,
  standalone_cw = 1 << 11 >> 5,
  standalone_ch = 1 << 11;
function standalone_cloud () {
  var size = [256, 256],
    text,
    font,
    fontSize,
    fontStyle,
    fontWeight,
    rotate,
    padding,
    spiral = standalone_archimedeanSpiral,
    words = [],
    random = Math.random,
    cloud = {};
  cloud.layout = function () {
    var contextAndRatio = getContext(standalone_domCanvas()),
      board = standalone_zeroArray((size[0] >> 5) * size[1]),
      bounds = null,
      n = words.length,
      i = -1,
      tags = [],
      data = words.map(d => ({
        text: text(d),
        font: font(d),
        style: fontStyle(d),
        weight: fontWeight(d),
        rotate: rotate(d),
        size: ~~(fontSize(d) + 1e-14),
        padding: padding(d),
        xoff: 0,
        yoff: 0,
        x1: 0,
        y1: 0,
        x0: 0,
        y0: 0,
        hasText: false,
        sprite: null,
        datum: d
      })).sort((a, b) => b.size - a.size);
    while (++i < n) {
      var d = data[i];
      d.x = size[0] * (random() + .5) >> 1;
      d.y = size[1] * (random() + .5) >> 1;
      standalone_cloudSprite(contextAndRatio, d, data, i);
      if (d.hasText && place(board, d, bounds)) {
        tags.push(d);
        if (bounds) standalone_cloudBounds(bounds, d);else bounds = [{
          x: d.x + d.x0,
          y: d.y + d.y0
        }, {
          x: d.x + d.x1,
          y: d.y + d.y1
        }];
        // Temporary hack
        d.x -= size[0] >> 1;
        d.y -= size[1] >> 1;
      }
    }
    return tags;
  };
  function getContext(canvas) {
    canvas.width = canvas.height = 1;
    var ratio = Math.sqrt(canvas.getContext('2d').getImageData(0, 0, 1, 1).data.length >> 2);
    canvas.width = (standalone_cw << 5) / ratio;
    canvas.height = standalone_ch / ratio;
    var context = canvas.getContext('2d');
    context.fillStyle = context.strokeStyle = 'red';
    context.textAlign = 'center';
    return {
      context: context,
      ratio: ratio
    };
  }
  function place(board, tag, bounds) {
    var startX = tag.x,
      startY = tag.y,
      maxDelta = Math.hypot(size[0], size[1]),
      s = spiral(size),
      dt = random() < .5 ? 1 : -1,
      t = -dt,
      dxdy,
      dx,
      dy;
    while (dxdy = s(t += dt)) {
      dx = ~~dxdy[0];
      dy = ~~dxdy[1];
      if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break;
      tag.x = startX + dx;
      tag.y = startY + dy;
      if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 || tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue;
      // TODO only check for collisions within current bounds.
      if (!bounds || !standalone_cloudCollide(tag, board, size[0])) {
        if (!bounds || standalone_collideRects(tag, bounds)) {
          var sprite = tag.sprite,
            w = tag.width >> 5,
            sw = size[0] >> 5,
            lx = tag.x - (w << 4),
            sx = lx & 0x7f,
            msx = 32 - sx,
            h = tag.y1 - tag.y0,
            x = (tag.y + tag.y0) * sw + (lx >> 5),
            last;
          for (var j = 0; j < h; j++) {
            last = 0;
            for (var i = 0; i <= w; i++) {
              board[x + i] |= last << msx | (i < w ? (last = sprite[j * w + i]) >>> sx : 0);
            }
            x += sw;
          }
          tag.sprite = null;
          return true;
        }
      }
    }
    return false;
  }
  cloud.words = function (_) {
    if (arguments.length) {
      words = _;
      return cloud;
    } else {
      return words;
    }
  };
  cloud.size = function (_) {
    if (arguments.length) {
      size = [+_[0], +_[1]];
      return cloud;
    } else {
      return size;
    }
  };
  cloud.font = function (_) {
    if (arguments.length) {
      font = standalone_functor(_);
      return cloud;
    } else {
      return font;
    }
  };
  cloud.fontStyle = function (_) {
    if (arguments.length) {
      fontStyle = standalone_functor(_);
      return cloud;
    } else {
      return fontStyle;
    }
  };
  cloud.fontWeight = function (_) {
    if (arguments.length) {
      fontWeight = standalone_functor(_);
      return cloud;
    } else {
      return fontWeight;
    }
  };
  cloud.rotate = function (_) {
    if (arguments.length) {
      rotate = standalone_functor(_);
      return cloud;
    } else {
      return rotate;
    }
  };
  cloud.text = function (_) {
    if (arguments.length) {
      text = standalone_functor(_);
      return cloud;
    } else {
      return text;
    }
  };
  cloud.spiral = function (_) {
    if (arguments.length) {
      spiral = standalone_spirals[_] || _;
      return cloud;
    } else {
      return spiral;
    }
  };
  cloud.fontSize = function (_) {
    if (arguments.length) {
      fontSize = standalone_functor(_);
      return cloud;
    } else {
      return fontSize;
    }
  };
  cloud.padding = function (_) {
    if (arguments.length) {
      padding = standalone_functor(_);
      return cloud;
    } else {
      return padding;
    }
  };
  cloud.random = function (_) {
    if (arguments.length) {
      random = _;
      return cloud;
    } else {
      return random;
    }
  };
  return cloud;
}

// Fetches a monochrome sprite bitmap for the specified text.
// Load in batches for speed.
function standalone_cloudSprite(contextAndRatio, d, data, di) {
  if (d.sprite) return;
  var c = contextAndRatio.context,
    ratio = contextAndRatio.ratio;
  c.clearRect(0, 0, (standalone_cw << 5) / ratio, standalone_ch / ratio);
  var x = 0,
    y = 0,
    maxh = 0,
    n = data.length,
    w,
    w32,
    h,
    i,
    j;
  --di;
  while (++di < n) {
    d = data[di];
    c.save();
    c.font = d.style + ' ' + d.weight + ' ' + ~~((d.size + 1) / ratio) + 'px ' + d.font;
    w = c.measureText(d.text + 'm').width * ratio;
    h = d.size << 1;
    if (d.rotate) {
      var sr = Math.sin(d.rotate * standalone_cloudRadians),
        cr = Math.cos(d.rotate * standalone_cloudRadians),
        wcr = w * cr,
        wsr = w * sr,
        hcr = h * cr,
        hsr = h * sr;
      w = Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f >> 5 << 5;
      h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));
    } else {
      w = w + 0x1f >> 5 << 5;
    }
    if (h > maxh) maxh = h;
    if (x + w >= standalone_cw << 5) {
      x = 0;
      y += maxh;
      maxh = 0;
    }
    if (y + h >= standalone_ch) break;
    c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio);
    if (d.rotate) c.rotate(d.rotate * standalone_cloudRadians);
    c.fillText(d.text, 0, 0);
    if (d.padding) {
      c.lineWidth = 2 * d.padding;
      c.strokeText(d.text, 0, 0);
    }
    c.restore();
    d.width = w;
    d.height = h;
    d.xoff = x;
    d.yoff = y;
    d.x1 = w >> 1;
    d.y1 = h >> 1;
    d.x0 = -d.x1;
    d.y0 = -d.y1;
    d.hasText = true;
    x += w;
  }
  var pixels = c.getImageData(0, 0, (standalone_cw << 5) / ratio, standalone_ch / ratio).data,
    sprite = [];
  while (--di >= 0) {
    d = data[di];
    if (!d.hasText) continue;
    w = d.width;
    w32 = w >> 5;
    h = d.y1 - d.y0;
    // Zero the buffer
    for (i = 0; i < h * w32; i++) sprite[i] = 0;
    x = d.xoff;
    if (x == null) return;
    y = d.yoff;
    var seen = 0,
      seenRow = -1;
    for (j = 0; j < h; j++) {
      for (i = 0; i < w; i++) {
        var k = w32 * j + (i >> 5),
          m = pixels[(y + j) * (standalone_cw << 5) + (x + i) << 2] ? 1 << 31 - i % 32 : 0;
        sprite[k] |= m;
        seen |= m;
      }
      if (seen) seenRow = j;else {
        d.y0++;
        h--;
        j--;
        y++;
      }
    }
    d.y1 = d.y0 + seenRow;
    d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32);
  }
}

// Use mask-based collision detection.
function standalone_cloudCollide(tag, board, sw) {
  sw >>= 5;
  var sprite = tag.sprite,
    w = tag.width >> 5,
    lx = tag.x - (w << 4),
    sx = lx & 0x7f,
    msx = 32 - sx,
    h = tag.y1 - tag.y0,
    x = (tag.y + tag.y0) * sw + (lx >> 5),
    last;
  for (var j = 0; j < h; j++) {
    last = 0;
    for (var i = 0; i <= w; i++) {
      if ((last << msx | (i < w ? (last = sprite[j * w + i]) >>> sx : 0)) & board[x + i]) return true;
    }
    x += sw;
  }
  return false;
}
function standalone_cloudBounds(bounds, d) {
  var b0 = bounds[0],
    b1 = bounds[1];
  if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0;
  if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0;
  if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1;
  if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1;
}
function standalone_collideRects(a, b) {
  return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y;
}
function standalone_archimedeanSpiral(size) {
  var e = size[0] / size[1];
  return function (t) {
    return [e * (t *= .1) * Math.cos(t), t * Math.sin(t)];
  };
}
function standalone_rectangularSpiral(size) {
  var dy = 4,
    dx = dy * size[0] / size[1],
    x = 0,
    y = 0;
  return function (t) {
    var sign = t < 0 ? -1 : 1;
    // See triangular numbers: T_n = n * (n + 1) / 2.
    switch (Math.sqrt(1 + 4 * sign * t) - sign & 3) {
      case 0:
        x += dx;
        break;
      case 1:
        y += dy;
        break;
      case 2:
        x -= dx;
        break;
      default:
        y -= dy;
        break;
    }
    return [x, y];
  };
}

// TODO reuse arrays?
function standalone_zeroArray(n) {
  var a = [],
    i = -1;
  while (++i < n) a[i] = 0;
  return a;
}
function standalone_functor(d) {
  return typeof d === 'function' ? d : function () {
    return d;
  };
}
var standalone_spirals = {
  archimedean: standalone_archimedeanSpiral,
  rectangular: standalone_rectangularSpiral
};

const standalone_vega_wordcloud_module_Output = ['x', 'y', 'font', 'fontSize', 'fontStyle', 'fontWeight', 'angle'];
const standalone_vega_wordcloud_module_Params = ['text', 'font', 'rotate', 'fontSize', 'fontStyle', 'fontWeight'];
function standalone_Wordcloud(params) {
  standalone_Transform.call(this, standalone_cloud(), params);
}
standalone_Wordcloud.Definition = {
  'type': 'Wordcloud',
  'metadata': {
    'modifies': true
  },
  'params': [{
    'name': 'size',
    'type': 'number',
    'array': true,
    'length': 2
  }, {
    'name': 'font',
    'type': 'string',
    'expr': true,
    'default': 'sans-serif'
  }, {
    'name': 'fontStyle',
    'type': 'string',
    'expr': true,
    'default': 'normal'
  }, {
    'name': 'fontWeight',
    'type': 'string',
    'expr': true,
    'default': 'normal'
  }, {
    'name': 'fontSize',
    'type': 'number',
    'expr': true,
    'default': 14
  }, {
    'name': 'fontSizeRange',
    'type': 'number',
    'array': 'nullable',
    'default': [10, 50]
  }, {
    'name': 'rotate',
    'type': 'number',
    'expr': true,
    'default': 0
  }, {
    'name': 'text',
    'type': 'field'
  }, {
    'name': 'spiral',
    'type': 'string',
    'values': ['archimedean', 'rectangular']
  }, {
    'name': 'padding',
    'type': 'number',
    'expr': true
  }, {
    'name': 'as',
    'type': 'string',
    'array': true,
    'length': 7,
    'default': standalone_vega_wordcloud_module_Output
  }]
};
standalone_inherits(standalone_Wordcloud, standalone_Transform, {
  transform(_, pulse) {
    if (_.size && !(_.size[0] && _.size[1])) {
      standalone_vega_util_module_error('Wordcloud size dimensions must be non-zero.');
    }
    function modp(param) {
      const p = _[param];
      return standalone_vega_util_module_isFunction(p) && pulse.modified(p.fields);
    }
    const mod = _.modified();
    if (!(mod || pulse.changed(pulse.ADD_REM) || standalone_vega_wordcloud_module_Params.some(modp))) return;
    const data = pulse.materialize(pulse.SOURCE).source,
      layout = this.value,
      as = _.as || standalone_vega_wordcloud_module_Output;
    let fontSize = _.fontSize || 14,
      range;
    standalone_vega_util_module_isFunction(fontSize) ? range = _.fontSizeRange : fontSize = standalone_vega_util_module_constant(fontSize);

    // create font size scaling function as needed
    if (range) {
      const fsize = fontSize,
        sizeScale = standalone_vega_scale_module_scale('sqrt')().domain(standalone_extent(data, fsize)).range(range);
      fontSize = x => sizeScale(fsize(x));
    }
    data.forEach(t => {
      t[as[0]] = NaN;
      t[as[1]] = NaN;
      t[as[3]] = 0;
    });

    // configure layout
    const words = layout.words(data).text(_.text).size(_.size || [500, 500]).padding(_.padding || 1).spiral(_.spiral || 'archimedean').rotate(_.rotate || 0).font(_.font || 'sans-serif').fontStyle(_.fontStyle || 'normal').fontWeight(_.fontWeight || 'normal').fontSize(fontSize).random(standalone_random).layout();
    const size = layout.size(),
      dx = size[0] >> 1,
      dy = size[1] >> 1,
      n = words.length;
    for (let i = 0, w, t; i < n; ++i) {
      w = words[i];
      t = w.datum;
      t[as[0]] = w.x + dx;
      t[as[1]] = w.y + dy;
      t[as[2]] = w.font;
      t[as[3]] = w.size;
      t[as[4]] = w.style;
      t[as[5]] = w.weight;
      t[as[6]] = w.rotate;
    }
    return pulse.reflow(mod).modifies(as);
  }
});



;// ../../node_modules/d3-array/src/permute.js
function standalone_permute_permute(source, keys) {
  return Array.from(keys, key => source[key]);
}

;// ../../node_modules/vega-crossfilter/build/vega-crossfilter.module.js




const standalone_array8 = n => new Uint8Array(n);
const standalone_array16 = n => new Uint16Array(n);
const standalone_array32 = n => new Uint32Array(n);

/**
 * Maintains CrossFilter state.
 */
function standalone_Bitmaps() {
  let width = 8,
    data = [],
    seen = standalone_array32(0),
    curr = standalone_vega_crossfilter_module_array(0, width),
    prev = standalone_vega_crossfilter_module_array(0, width);
  return {
    data: () => data,
    seen: () => seen = standalone_lengthen(seen, data.length),
    add(array) {
      for (let i = 0, j = data.length, n = array.length, t; i < n; ++i) {
        t = array[i];
        t._index = j++;
        data.push(t);
      }
    },
    remove(num, map) {
      // map: index -> boolean (true => remove)
      const n = data.length,
        copy = Array(n - num),
        reindex = data; // reuse old data array for index map
      let t, i, j;

      // seek forward to first removal
      for (i = 0; !map[i] && i < n; ++i) {
        copy[i] = data[i];
        reindex[i] = i;
      }

      // condense arrays
      for (j = i; i < n; ++i) {
        t = data[i];
        if (!map[i]) {
          reindex[i] = j;
          curr[j] = curr[i];
          prev[j] = prev[i];
          copy[j] = t;
          t._index = j++;
        } else {
          reindex[i] = -1;
        }
        curr[i] = 0; // clear unused bits
      }
      data = copy;
      return reindex;
    },
    size: () => data.length,
    curr: () => curr,
    prev: () => prev,
    reset: k => prev[k] = curr[k],
    all: () => width < 0x101 ? 0xff : width < 0x10001 ? 0xffff : 0xffffffff,
    set(k, one) {
      curr[k] |= one;
    },
    clear(k, one) {
      curr[k] &= ~one;
    },
    resize(n, m) {
      const k = curr.length;
      if (n > k || m > width) {
        width = Math.max(m, width);
        curr = standalone_vega_crossfilter_module_array(n, width, curr);
        prev = standalone_vega_crossfilter_module_array(n, width);
      }
    }
  };
}
function standalone_lengthen(array, length, copy) {
  if (array.length >= length) return array;
  copy = copy || new array.constructor(length);
  copy.set(array);
  return copy;
}
function standalone_vega_crossfilter_module_array(n, m, array) {
  const copy = (m < 0x101 ? standalone_array8 : m < 0x10001 ? standalone_array16 : standalone_array32)(n);
  if (array) copy.set(array);
  return copy;
}

function standalone_Dimension (index, i, query) {
  const bit = 1 << i;
  return {
    one: bit,
    zero: ~bit,
    range: query.slice(),
    bisect: index.bisect,
    index: index.index,
    size: index.size,
    onAdd(added, curr) {
      const dim = this,
        range = dim.bisect(dim.range, added.value),
        idx = added.index,
        lo = range[0],
        hi = range[1],
        n1 = idx.length;
      let i;
      for (i = 0; i < lo; ++i) curr[idx[i]] |= bit;
      for (i = hi; i < n1; ++i) curr[idx[i]] |= bit;
      return dim;
    }
  };
}

/**
 * Maintains a list of values, sorted by key.
 */
function standalone_SortedIndex() {
  let index = standalone_array32(0),
    value = [],
    size = 0;
  function insert(key, data, base) {
    if (!data.length) return [];
    const n0 = size,
      n1 = data.length,
      addi = standalone_array32(n1);
    let addv = Array(n1),
      oldv,
      oldi,
      i;
    for (i = 0; i < n1; ++i) {
      addv[i] = key(data[i]);
      addi[i] = i;
    }
    addv = standalone_vega_crossfilter_module_sort(addv, addi);
    if (n0) {
      oldv = value;
      oldi = index;
      value = Array(n0 + n1);
      index = standalone_array32(n0 + n1);
      standalone_vega_crossfilter_module_merge(base, oldv, oldi, n0, addv, addi, n1, value, index);
    } else {
      if (base > 0) for (i = 0; i < n1; ++i) {
        addi[i] += base;
      }
      value = addv;
      index = addi;
    }
    size = n0 + n1;
    return {
      index: addi,
      value: addv
    };
  }
  function remove(num, map) {
    // map: index -> remove
    const n = size;
    let idx, i, j;

    // seek forward to first removal
    for (i = 0; !map[index[i]] && i < n; ++i);

    // condense index and value arrays
    for (j = i; i < n; ++i) {
      if (!map[idx = index[i]]) {
        index[j] = idx;
        value[j] = value[i];
        ++j;
      }
    }
    size = n - num;
  }
  function reindex(map) {
    for (let i = 0, n = size; i < n; ++i) {
      index[i] = map[index[i]];
    }
  }
  function bisect(range, array) {
    let n;
    if (array) {
      n = array.length;
    } else {
      array = value;
      n = size;
    }
    return [standalone_bisectLeft(array, range[0], 0, n), standalone_bisectRight(array, range[1], 0, n)];
  }
  return {
    insert: insert,
    remove: remove,
    bisect: bisect,
    reindex: reindex,
    index: () => index,
    size: () => size
  };
}
function standalone_vega_crossfilter_module_sort(values, index) {
  values.sort.call(index, (a, b) => {
    const x = values[a],
      y = values[b];
    return x < y ? -1 : x > y ? 1 : 0;
  });
  return standalone_permute_permute(values, index);
}
function standalone_vega_crossfilter_module_merge(base, value0, index0, n0, value1, index1, n1, value, index) {
  let i0 = 0,
    i1 = 0,
    i;
  for (i = 0; i0 < n0 && i1 < n1; ++i) {
    if (value0[i0] < value1[i1]) {
      value[i] = value0[i0];
      index[i] = index0[i0++];
    } else {
      value[i] = value1[i1];
      index[i] = index1[i1++] + base;
    }
  }
  for (; i0 < n0; ++i0, ++i) {
    value[i] = value0[i0];
    index[i] = index0[i0];
  }
  for (; i1 < n1; ++i1, ++i) {
    value[i] = value1[i1];
    index[i] = index1[i1] + base;
  }
}

/**
 * An indexed multi-dimensional filter.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<function(object): *>} params.fields - An array of dimension accessors to filter.
 * @param {Array} params.query - An array of per-dimension range queries.
 */
function standalone_CrossFilter(params) {
  standalone_Transform.call(this, standalone_Bitmaps(), params);
  this._indices = null;
  this._dims = null;
}
standalone_CrossFilter.Definition = {
  'type': 'CrossFilter',
  'metadata': {},
  'params': [{
    'name': 'fields',
    'type': 'field',
    'array': true,
    'required': true
  }, {
    'name': 'query',
    'type': 'array',
    'array': true,
    'required': true,
    'content': {
      'type': 'number',
      'array': true,
      'length': 2
    }
  }]
};
standalone_inherits(standalone_CrossFilter, standalone_Transform, {
  transform(_, pulse) {
    if (!this._dims) {
      return this.init(_, pulse);
    } else {
      var init = _.modified('fields') || _.fields.some(f => pulse.modified(f.fields));
      return init ? this.reinit(_, pulse) : this.eval(_, pulse);
    }
  },
  init(_, pulse) {
    const fields = _.fields,
      query = _.query,
      indices = this._indices = {},
      dims = this._dims = [],
      m = query.length;
    let i = 0,
      key,
      index;

    // instantiate indices and dimensions
    for (; i < m; ++i) {
      key = fields[i].fname;
      index = indices[key] || (indices[key] = standalone_SortedIndex());
      dims.push(standalone_Dimension(index, i, query[i]));
    }
    return this.eval(_, pulse);
  },
  reinit(_, pulse) {
    const output = pulse.materialize().fork(),
      fields = _.fields,
      query = _.query,
      indices = this._indices,
      dims = this._dims,
      bits = this.value,
      curr = bits.curr(),
      prev = bits.prev(),
      all = bits.all(),
      out = output.rem = output.add,
      mod = output.mod,
      m = query.length,
      adds = {};
    let add, index, key, mods, remMap, modMap, i, n, f;

    // set prev to current state
    prev.set(curr);

    // if pulse has remove tuples, process them first
    if (pulse.rem.length) {
      remMap = this.remove(_, pulse, output);
    }

    // if pulse has added tuples, add them to state
    if (pulse.add.length) {
      bits.add(pulse.add);
    }

    // if pulse has modified tuples, create an index map
    if (pulse.mod.length) {
      modMap = {};
      for (mods = pulse.mod, i = 0, n = mods.length; i < n; ++i) {
        modMap[mods[i]._index] = 1;
      }
    }

    // re-initialize indices as needed, update curr bitmap
    for (i = 0; i < m; ++i) {
      f = fields[i];
      if (!dims[i] || _.modified('fields', i) || pulse.modified(f.fields)) {
        key = f.fname;
        if (!(add = adds[key])) {
          indices[key] = index = standalone_SortedIndex();
          adds[key] = add = index.insert(f, pulse.source, 0);
        }
        dims[i] = standalone_Dimension(index, i, query[i]).onAdd(add, curr);
      }
    }

    // visit each tuple
    // if filter state changed, push index to add/rem
    // else if in mod and passes a filter, push index to mod
    for (i = 0, n = bits.data().length; i < n; ++i) {
      if (remMap[i]) {
        // skip if removed tuple
        continue;
      } else if (prev[i] !== curr[i]) {
        // add if state changed
        out.push(i);
      } else if (modMap[i] && curr[i] !== all) {
        // otherwise, pass mods through
        mod.push(i);
      }
    }
    bits.mask = (1 << m) - 1;
    return output;
  },
  eval(_, pulse) {
    const output = pulse.materialize().fork(),
      m = this._dims.length;
    let mask = 0;
    if (pulse.rem.length) {
      this.remove(_, pulse, output);
      mask |= (1 << m) - 1;
    }
    if (_.modified('query') && !_.modified('fields')) {
      mask |= this.update(_, pulse, output);
    }
    if (pulse.add.length) {
      this.insert(_, pulse, output);
      mask |= (1 << m) - 1;
    }
    if (pulse.mod.length) {
      this.modify(pulse, output);
      mask |= (1 << m) - 1;
    }
    this.value.mask = mask;
    return output;
  },
  insert(_, pulse, output) {
    const tuples = pulse.add,
      bits = this.value,
      dims = this._dims,
      indices = this._indices,
      fields = _.fields,
      adds = {},
      out = output.add,
      n = bits.size() + tuples.length,
      m = dims.length;
    let k = bits.size(),
      j,
      key,
      add;

    // resize bitmaps and add tuples as needed
    bits.resize(n, m);
    bits.add(tuples);
    const curr = bits.curr(),
      prev = bits.prev(),
      all = bits.all();

    // add to dimensional indices
    for (j = 0; j < m; ++j) {
      key = fields[j].fname;
      add = adds[key] || (adds[key] = indices[key].insert(fields[j], tuples, k));
      dims[j].onAdd(add, curr);
    }

    // set previous filters, output if passes at least one filter
    for (; k < n; ++k) {
      prev[k] = all;
      if (curr[k] !== all) out.push(k);
    }
  },
  modify(pulse, output) {
    const out = output.mod,
      bits = this.value,
      curr = bits.curr(),
      all = bits.all(),
      tuples = pulse.mod;
    let i, n, k;
    for (i = 0, n = tuples.length; i < n; ++i) {
      k = tuples[i]._index;
      if (curr[k] !== all) out.push(k);
    }
  },
  remove(_, pulse, output) {
    const indices = this._indices,
      bits = this.value,
      curr = bits.curr(),
      prev = bits.prev(),
      all = bits.all(),
      map = {},
      out = output.rem,
      tuples = pulse.rem;
    let i, n, k, f;

    // process tuples, output if passes at least one filter
    for (i = 0, n = tuples.length; i < n; ++i) {
      k = tuples[i]._index;
      map[k] = 1; // build index map
      prev[k] = f = curr[k];
      curr[k] = all;
      if (f !== all) out.push(k);
    }

    // remove from dimensional indices
    for (k in indices) {
      indices[k].remove(n, map);
    }
    this.reindex(pulse, n, map);
    return map;
  },
  // reindex filters and indices after propagation completes
  reindex(pulse, num, map) {
    const indices = this._indices,
      bits = this.value;
    pulse.runAfter(() => {
      const indexMap = bits.remove(num, map);
      for (const key in indices) indices[key].reindex(indexMap);
    });
  },
  update(_, pulse, output) {
    const dims = this._dims,
      query = _.query,
      stamp = pulse.stamp,
      m = dims.length;
    let mask = 0,
      i,
      q;

    // survey how many queries have changed
    output.filters = 0;
    for (q = 0; q < m; ++q) {
      if (_.modified('query', q)) {
        i = q;
        ++mask;
      }
    }
    if (mask === 1) {
      // only one query changed, use more efficient update
      mask = dims[i].one;
      this.incrementOne(dims[i], query[i], output.add, output.rem);
    } else {
      // multiple queries changed, perform full record keeping
      for (q = 0, mask = 0; q < m; ++q) {
        if (!_.modified('query', q)) continue;
        mask |= dims[q].one;
        this.incrementAll(dims[q], query[q], stamp, output.add);
        output.rem = output.add; // duplicate add/rem for downstream resolve
      }
    }
    return mask;
  },
  incrementAll(dim, query, stamp, out) {
    const bits = this.value,
      seen = bits.seen(),
      curr = bits.curr(),
      prev = bits.prev(),
      index = dim.index(),
      old = dim.bisect(dim.range),
      range = dim.bisect(query),
      lo1 = range[0],
      hi1 = range[1],
      lo0 = old[0],
      hi0 = old[1],
      one = dim.one;
    let i, j, k;

    // Fast incremental update based on previous lo index.
    if (lo1 < lo0) {
      for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {
        k = index[i];
        if (seen[k] !== stamp) {
          prev[k] = curr[k];
          seen[k] = stamp;
          out.push(k);
        }
        curr[k] ^= one;
      }
    } else if (lo1 > lo0) {
      for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {
        k = index[i];
        if (seen[k] !== stamp) {
          prev[k] = curr[k];
          seen[k] = stamp;
          out.push(k);
        }
        curr[k] ^= one;
      }
    }

    // Fast incremental update based on previous hi index.
    if (hi1 > hi0) {
      for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {
        k = index[i];
        if (seen[k] !== stamp) {
          prev[k] = curr[k];
          seen[k] = stamp;
          out.push(k);
        }
        curr[k] ^= one;
      }
    } else if (hi1 < hi0) {
      for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {
        k = index[i];
        if (seen[k] !== stamp) {
          prev[k] = curr[k];
          seen[k] = stamp;
          out.push(k);
        }
        curr[k] ^= one;
      }
    }
    dim.range = query.slice();
  },
  incrementOne(dim, query, add, rem) {
    const bits = this.value,
      curr = bits.curr(),
      index = dim.index(),
      old = dim.bisect(dim.range),
      range = dim.bisect(query),
      lo1 = range[0],
      hi1 = range[1],
      lo0 = old[0],
      hi0 = old[1],
      one = dim.one;
    let i, j, k;

    // Fast incremental update based on previous lo index.
    if (lo1 < lo0) {
      for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {
        k = index[i];
        curr[k] ^= one;
        add.push(k);
      }
    } else if (lo1 > lo0) {
      for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {
        k = index[i];
        curr[k] ^= one;
        rem.push(k);
      }
    }

    // Fast incremental update based on previous hi index.
    if (hi1 > hi0) {
      for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {
        k = index[i];
        curr[k] ^= one;
        add.push(k);
      }
    } else if (hi1 < hi0) {
      for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {
        k = index[i];
        curr[k] ^= one;
        rem.push(k);
      }
    }
    dim.range = query.slice();
  }
});

/**
 * Selectively filters tuples by resolving against a filter bitmap.
 * Useful for processing the output of a cross-filter transform.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {object} params.ignore - A bit mask indicating which filters to ignore.
 * @param {object} params.filter - The per-tuple filter bitmaps. Typically this
 *   parameter value is a reference to a {@link CrossFilter} transform.
 */
function standalone_ResolveFilter(params) {
  standalone_Transform.call(this, null, params);
}
standalone_ResolveFilter.Definition = {
  'type': 'ResolveFilter',
  'metadata': {},
  'params': [{
    'name': 'ignore',
    'type': 'number',
    'required': true,
    'description': 'A bit mask indicating which filters to ignore.'
  }, {
    'name': 'filter',
    'type': 'object',
    'required': true,
    'description': 'Per-tuple filter bitmaps from a CrossFilter transform.'
  }]
};
standalone_inherits(standalone_ResolveFilter, standalone_Transform, {
  transform(_, pulse) {
    const ignore = ~(_.ignore || 0),
      // bit mask where zeros -> dims to ignore
      bitmap = _.filter,
      mask = bitmap.mask;

    // exit early if no relevant filter changes
    if ((mask & ignore) === 0) return pulse.StopPropagation;
    const output = pulse.fork(pulse.ALL),
      data = bitmap.data(),
      curr = bitmap.curr(),
      prev = bitmap.prev(),
      pass = k => !(curr[k] & ignore) ? data[k] : null;

    // propagate all mod tuples that pass the filter
    output.filter(output.MOD, pass);

    // determine add & rem tuples via filter functions
    // for efficiency, we do *not* populate new arrays,
    // instead we add filter functions applied downstream

    if (!(mask & mask - 1)) {
      // only one filter changed
      output.filter(output.ADD, pass);
      output.filter(output.REM, k => (curr[k] & ignore) === mask ? data[k] : null);
    } else {
      // multiple filters changed
      output.filter(output.ADD, k => {
        const c = curr[k] & ignore,
          f = !c && c ^ prev[k] & ignore;
        return f ? data[k] : null;
      });
      output.filter(output.REM, k => {
        const c = curr[k] & ignore,
          f = c && !(c ^ (c ^ prev[k] & ignore));
        return f ? data[k] : null;
      });
    }

    // add filter to source data in case of reflow...
    return output.filter(output.SOURCE, t => pass(t._index));
  }
});



;// ../../node_modules/vega-expression/build/vega-expression.module.js


const standalone_RawCode = 'RawCode';
const standalone_Literal = 'Literal';
const standalone_Property = 'Property';
const standalone_vega_expression_module_Identifier = 'Identifier';
const standalone_ArrayExpression = 'ArrayExpression';
const standalone_BinaryExpression = 'BinaryExpression';
const standalone_CallExpression = 'CallExpression';
const standalone_ConditionalExpression = 'ConditionalExpression';
const standalone_LogicalExpression = 'LogicalExpression';
const standalone_MemberExpression = 'MemberExpression';
const standalone_ObjectExpression = 'ObjectExpression';
const standalone_UnaryExpression = 'UnaryExpression';
function standalone_ASTNode(type) {
  this.type = type;
}
standalone_ASTNode.prototype.visit = function (visitor) {
  let c, i, n;
  if (visitor(this)) return 1;
  for (c = standalone_vega_expression_module_children(this), i = 0, n = c.length; i < n; ++i) {
    if (c[i].visit(visitor)) return 1;
  }
};
function standalone_vega_expression_module_children(node) {
  switch (node.type) {
    case standalone_ArrayExpression:
      return node.elements;
    case standalone_BinaryExpression:
    case standalone_LogicalExpression:
      return [node.left, node.right];
    case standalone_CallExpression:
      return [node.callee].concat(node.arguments);
    case standalone_ConditionalExpression:
      return [node.test, node.consequent, node.alternate];
    case standalone_MemberExpression:
      return [node.object, node.property];
    case standalone_ObjectExpression:
      return node.properties;
    case standalone_Property:
      return [node.key, node.value];
    case standalone_UnaryExpression:
      return [node.argument];
    case standalone_vega_expression_module_Identifier:
    case standalone_Literal:
    case standalone_RawCode:
    default:
      return [];
  }
}

/*
  The following expression parser is based on Esprima (http://esprima.org/).
  Original header comment and license for Esprima is included here:

  Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
  Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
  Copyright (C) 2013 Mathias Bynens <mathias@qiwi.be>
  Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
  Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
  Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var standalone_TokenName, standalone_vega_expression_module_source, standalone_vega_expression_module_index, standalone_vega_expression_module_length, standalone_lookahead;
var standalone_TokenBooleanLiteral = 1,
  standalone_TokenEOF = 2,
  standalone_TokenIdentifier = 3,
  standalone_TokenKeyword = 4,
  standalone_TokenNullLiteral = 5,
  standalone_TokenNumericLiteral = 6,
  standalone_TokenPunctuator = 7,
  standalone_TokenStringLiteral = 8,
  standalone_TokenRegularExpression = 9;
standalone_TokenName = {};
standalone_TokenName[standalone_TokenBooleanLiteral] = 'Boolean';
standalone_TokenName[standalone_TokenEOF] = '<end>';
standalone_TokenName[standalone_TokenIdentifier] = 'Identifier';
standalone_TokenName[standalone_TokenKeyword] = 'Keyword';
standalone_TokenName[standalone_TokenNullLiteral] = 'Null';
standalone_TokenName[standalone_TokenNumericLiteral] = 'Numeric';
standalone_TokenName[standalone_TokenPunctuator] = 'Punctuator';
standalone_TokenName[standalone_TokenStringLiteral] = 'String';
standalone_TokenName[standalone_TokenRegularExpression] = 'RegularExpression';
var standalone_SyntaxArrayExpression = 'ArrayExpression',
  standalone_SyntaxBinaryExpression = 'BinaryExpression',
  standalone_SyntaxCallExpression = 'CallExpression',
  standalone_SyntaxConditionalExpression = 'ConditionalExpression',
  standalone_SyntaxIdentifier = 'Identifier',
  standalone_SyntaxLiteral = 'Literal',
  standalone_SyntaxLogicalExpression = 'LogicalExpression',
  standalone_SyntaxMemberExpression = 'MemberExpression',
  standalone_SyntaxObjectExpression = 'ObjectExpression',
  standalone_SyntaxProperty = 'Property',
  standalone_SyntaxUnaryExpression = 'UnaryExpression';

// Error messages should be identical to V8.
var standalone_MessageUnexpectedToken = 'Unexpected token %0',
  standalone_MessageUnexpectedNumber = 'Unexpected number',
  standalone_MessageUnexpectedString = 'Unexpected string',
  standalone_MessageUnexpectedIdentifier = 'Unexpected identifier',
  standalone_MessageUnexpectedReserved = 'Unexpected reserved word',
  standalone_MessageUnexpectedEOS = 'Unexpected end of input',
  standalone_MessageInvalidRegExp = 'Invalid regular expression',
  standalone_MessageUnterminatedRegExp = 'Invalid regular expression: missing /',
  standalone_MessageStrictOctalLiteral = 'Octal literals are not allowed in strict mode.',
  standalone_MessageStrictDuplicateProperty = 'Duplicate data property in object literal not allowed in strict mode';
var standalone_ILLEGAL = 'ILLEGAL',
  standalone_DISABLED = 'Disabled.';

// See also tools/generate-unicode-regex.py.
var standalone_RegexNonAsciiIdentifierStart = new RegExp('[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]'),
  // eslint-disable-next-line no-misleading-character-class
  standalone_RegexNonAsciiIdentifierPart = new RegExp('[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u08A0-\\u08B2\\u08E4-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BEF\\u0C00-\\u0C03\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C58\\u0C59\\u0C60-\\u0C63\\u0C66-\\u0C6F\\u0C81-\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CDE\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0CF1\\u0CF2\\u0D01-\\u0D03\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4E\\u0D57\\u0D60-\\u0D63\\u0D66-\\u0D6F\\u0D7A-\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1CD0-\\u1CD2\\u1CD4-\\u1CF6\\u1CF8\\u1CF9\\u1D00-\\u1DF5\\u1DFC-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u200C\\u200D\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA69D\\uA69F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C4\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2D\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]');

// Ensure the condition is true, otherwise throw an error.
// This is only to have a better contract semantic, i.e. another safety net
// to catch a logic error. The condition shall be fulfilled in normal case.
// Do NOT use this to enforce a certain condition on any user input.

function standalone_assert(condition, message) {
  /* istanbul ignore next */
  if (!condition) {
    throw new Error('ASSERT: ' + message);
  }
}
function standalone_isDecimalDigit(ch) {
  return ch >= 0x30 && ch <= 0x39; // 0..9
}
function standalone_isHexDigit(ch) {
  return '0123456789abcdefABCDEF'.includes(ch);
}
function standalone_isOctalDigit(ch) {
  return '01234567'.includes(ch);
}

// 7.2 White Space

function standalone_isWhiteSpace(ch) {
  return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].includes(ch);
}

// 7.3 Line Terminators

function standalone_isLineTerminator(ch) {
  return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
}

// 7.6 Identifier Names and Identifiers

function standalone_isIdentifierStart(ch) {
  return ch === 0x24 || ch === 0x5F ||
  // $ (dollar) and _ (underscore)
  ch >= 0x41 && ch <= 0x5A ||
  // A..Z
  ch >= 0x61 && ch <= 0x7A ||
  // a..z
  ch === 0x5C ||
  // \ (backslash)
  ch >= 0x80 && standalone_RegexNonAsciiIdentifierStart.test(String.fromCharCode(ch));
}
function standalone_isIdentifierPart(ch) {
  return ch === 0x24 || ch === 0x5F ||
  // $ (dollar) and _ (underscore)
  ch >= 0x41 && ch <= 0x5A ||
  // A..Z
  ch >= 0x61 && ch <= 0x7A ||
  // a..z
  ch >= 0x30 && ch <= 0x39 ||
  // 0..9
  ch === 0x5C ||
  // \ (backslash)
  ch >= 0x80 && standalone_RegexNonAsciiIdentifierPart.test(String.fromCharCode(ch));
}

// 7.6.1.1 Keywords

const standalone_keywords = {
  'if': 1,
  'in': 1,
  'do': 1,
  'var': 1,
  'for': 1,
  'new': 1,
  'try': 1,
  'let': 1,
  'this': 1,
  'else': 1,
  'case': 1,
  'void': 1,
  'with': 1,
  'enum': 1,
  'while': 1,
  'break': 1,
  'catch': 1,
  'throw': 1,
  'const': 1,
  'yield': 1,
  'class': 1,
  'super': 1,
  'return': 1,
  'typeof': 1,
  'delete': 1,
  'switch': 1,
  'export': 1,
  'import': 1,
  'public': 1,
  'static': 1,
  'default': 1,
  'finally': 1,
  'extends': 1,
  'package': 1,
  'private': 1,
  'function': 1,
  'continue': 1,
  'debugger': 1,
  'interface': 1,
  'protected': 1,
  'instanceof': 1,
  'implements': 1
};
function standalone_skipComment() {
  while (standalone_vega_expression_module_index < standalone_vega_expression_module_length) {
    const ch = standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index);
    if (standalone_isWhiteSpace(ch) || standalone_isLineTerminator(ch)) {
      ++standalone_vega_expression_module_index;
    } else {
      break;
    }
  }
}
function standalone_scanHexEscape(prefix) {
  var i,
    len,
    ch,
    code = 0;
  len = prefix === 'u' ? 4 : 2;
  for (i = 0; i < len; ++i) {
    if (standalone_vega_expression_module_index < standalone_vega_expression_module_length && standalone_isHexDigit(standalone_vega_expression_module_source[standalone_vega_expression_module_index])) {
      ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
      code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
    } else {
      standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
    }
  }
  return String.fromCharCode(code);
}
function standalone_scanUnicodeCodePointEscape() {
  var ch, code, cu1, cu2;
  ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index];
  code = 0;

  // At least, one hex digit is required.
  if (ch === '}') {
    standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
  }
  while (standalone_vega_expression_module_index < standalone_vega_expression_module_length) {
    ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
    if (!standalone_isHexDigit(ch)) {
      break;
    }
    code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  }
  if (code > 0x10FFFF || ch !== '}') {
    standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
  }

  // UTF-16 Encoding
  if (code <= 0xFFFF) {
    return String.fromCharCode(code);
  }
  cu1 = (code - 0x10000 >> 10) + 0xD800;
  cu2 = (code - 0x10000 & 1023) + 0xDC00;
  return String.fromCharCode(cu1, cu2);
}
function standalone_getEscapedIdentifier() {
  var ch, id;
  ch = standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index++);
  id = String.fromCharCode(ch);

  // '\u' (U+005C, U+0075) denotes an escaped character.
  if (ch === 0x5C) {
    if (standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index) !== 0x75) {
      standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
    }
    ++standalone_vega_expression_module_index;
    ch = standalone_scanHexEscape('u');
    if (!ch || ch === '\\' || !standalone_isIdentifierStart(ch.charCodeAt(0))) {
      standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
    }
    id = ch;
  }
  while (standalone_vega_expression_module_index < standalone_vega_expression_module_length) {
    ch = standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index);
    if (!standalone_isIdentifierPart(ch)) {
      break;
    }
    ++standalone_vega_expression_module_index;
    id += String.fromCharCode(ch);

    // '\u' (U+005C, U+0075) denotes an escaped character.
    if (ch === 0x5C) {
      id = id.substr(0, id.length - 1);
      if (standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index) !== 0x75) {
        standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
      }
      ++standalone_vega_expression_module_index;
      ch = standalone_scanHexEscape('u');
      if (!ch || ch === '\\' || !standalone_isIdentifierPart(ch.charCodeAt(0))) {
        standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
      }
      id += ch;
    }
  }
  return id;
}
function standalone_getIdentifier() {
  var start, ch;
  start = standalone_vega_expression_module_index++;
  while (standalone_vega_expression_module_index < standalone_vega_expression_module_length) {
    ch = standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index);
    if (ch === 0x5C) {
      // Blackslash (U+005C) marks Unicode escape sequence.
      standalone_vega_expression_module_index = start;
      return standalone_getEscapedIdentifier();
    }
    if (standalone_isIdentifierPart(ch)) {
      ++standalone_vega_expression_module_index;
    } else {
      break;
    }
  }
  return standalone_vega_expression_module_source.slice(start, standalone_vega_expression_module_index);
}
function standalone_scanIdentifier() {
  var start, id, type;
  start = standalone_vega_expression_module_index;

  // Backslash (U+005C) starts an escaped character.
  id = standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index) === 0x5C ? standalone_getEscapedIdentifier() : standalone_getIdentifier();

  // There is no keyword or literal with only one character.
  // Thus, it must be an identifier.
  if (id.length === 1) {
    type = standalone_TokenIdentifier;
  } else if (standalone_keywords.hasOwnProperty(id)) {
    // eslint-disable-line no-prototype-builtins
    type = standalone_TokenKeyword;
  } else if (id === 'null') {
    type = standalone_TokenNullLiteral;
  } else if (id === 'true' || id === 'false') {
    type = standalone_TokenBooleanLiteral;
  } else {
    type = standalone_TokenIdentifier;
  }
  return {
    type: type,
    value: id,
    start: start,
    end: standalone_vega_expression_module_index
  };
}

// 7.7 Punctuators

function standalone_scanPunctuator() {
  var start = standalone_vega_expression_module_index,
    code = standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index),
    code2,
    ch1 = standalone_vega_expression_module_source[standalone_vega_expression_module_index],
    ch2,
    ch3,
    ch4;
  switch (code) {
    // Check for most common single-character punctuators.
    case 0x2E: // . dot
    case 0x28: // ( open bracket
    case 0x29: // ) close bracket
    case 0x3B: // ; semicolon
    case 0x2C: // , comma
    case 0x7B: // { open curly brace
    case 0x7D: // } close curly brace
    case 0x5B: // [
    case 0x5D: // ]
    case 0x3A: // :
    case 0x3F: // ?
    case 0x7E:
      // ~
      ++standalone_vega_expression_module_index;
      return {
        type: standalone_TokenPunctuator,
        value: String.fromCharCode(code),
        start: start,
        end: standalone_vega_expression_module_index
      };
    default:
      code2 = standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index + 1);

      // '=' (U+003D) marks an assignment or comparison operator.
      if (code2 === 0x3D) {
        switch (code) {
          case 0x2B: // +
          case 0x2D: // -
          case 0x2F: // /
          case 0x3C: // <
          case 0x3E: // >
          case 0x5E: // ^
          case 0x7C: // |
          case 0x25: // %
          case 0x26: // &
          case 0x2A:
            // *
            standalone_vega_expression_module_index += 2;
            return {
              type: standalone_TokenPunctuator,
              value: String.fromCharCode(code) + String.fromCharCode(code2),
              start: start,
              end: standalone_vega_expression_module_index
            };
          case 0x21: // !
          case 0x3D:
            // =
            standalone_vega_expression_module_index += 2;

            // !== and ===
            if (standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index) === 0x3D) {
              ++standalone_vega_expression_module_index;
            }
            return {
              type: standalone_TokenPunctuator,
              value: standalone_vega_expression_module_source.slice(start, standalone_vega_expression_module_index),
              start: start,
              end: standalone_vega_expression_module_index
            };
        }
      }
  }

  // 4-character punctuator: >>>=

  ch4 = standalone_vega_expression_module_source.substr(standalone_vega_expression_module_index, 4);
  if (ch4 === '>>>=') {
    standalone_vega_expression_module_index += 4;
    return {
      type: standalone_TokenPunctuator,
      value: ch4,
      start: start,
      end: standalone_vega_expression_module_index
    };
  }

  // 3-character punctuators: === !== >>> <<= >>=

  ch3 = ch4.substr(0, 3);
  if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') {
    standalone_vega_expression_module_index += 3;
    return {
      type: standalone_TokenPunctuator,
      value: ch3,
      start: start,
      end: standalone_vega_expression_module_index
    };
  }

  // Other 2-character punctuators: ++ -- << >> && ||
  ch2 = ch3.substr(0, 2);
  if (ch1 === ch2[1] && '+-<>&|'.includes(ch1) || ch2 === '=>') {
    standalone_vega_expression_module_index += 2;
    return {
      type: standalone_TokenPunctuator,
      value: ch2,
      start: start,
      end: standalone_vega_expression_module_index
    };
  }
  if (ch2 === '//') {
    standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
  }

  // 1-character punctuators: < > = ! + - * % & | ^ /

  if ('<>=!+-*%&|^/'.includes(ch1)) {
    ++standalone_vega_expression_module_index;
    return {
      type: standalone_TokenPunctuator,
      value: ch1,
      start: start,
      end: standalone_vega_expression_module_index
    };
  }
  standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
}

// 7.8.3 Numeric Literals

function standalone_scanHexLiteral(start) {
  let number = '';
  while (standalone_vega_expression_module_index < standalone_vega_expression_module_length) {
    if (!standalone_isHexDigit(standalone_vega_expression_module_source[standalone_vega_expression_module_index])) {
      break;
    }
    number += standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
  }
  if (number.length === 0) {
    standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
  }
  if (standalone_isIdentifierStart(standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index))) {
    standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
  }
  return {
    type: standalone_TokenNumericLiteral,
    value: parseInt('0x' + number, 16),
    start: start,
    end: standalone_vega_expression_module_index
  };
}
function standalone_scanOctalLiteral(start) {
  let number = '0' + standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
  while (standalone_vega_expression_module_index < standalone_vega_expression_module_length) {
    if (!standalone_isOctalDigit(standalone_vega_expression_module_source[standalone_vega_expression_module_index])) {
      break;
    }
    number += standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
  }
  if (standalone_isIdentifierStart(standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index)) || standalone_isDecimalDigit(standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index))) {
    standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
  }
  return {
    type: standalone_TokenNumericLiteral,
    value: parseInt(number, 8),
    octal: true,
    start: start,
    end: standalone_vega_expression_module_index
  };
}
function standalone_scanNumericLiteral() {
  var number, start, ch;
  ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index];
  standalone_assert(standalone_isDecimalDigit(ch.charCodeAt(0)) || ch === '.', 'Numeric literal must start with a decimal digit or a decimal point');
  start = standalone_vega_expression_module_index;
  number = '';
  if (ch !== '.') {
    number = standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
    ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index];

    // Hex number starts with '0x'.
    // Octal number starts with '0'.
    if (number === '0') {
      if (ch === 'x' || ch === 'X') {
        ++standalone_vega_expression_module_index;
        return standalone_scanHexLiteral(start);
      }
      if (standalone_isOctalDigit(ch)) {
        return standalone_scanOctalLiteral(start);
      }

      // decimal number starts with '0' such as '09' is illegal.
      if (ch && standalone_isDecimalDigit(ch.charCodeAt(0))) {
        standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
      }
    }
    while (standalone_isDecimalDigit(standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index))) {
      number += standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
    }
    ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index];
  }
  if (ch === '.') {
    number += standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
    while (standalone_isDecimalDigit(standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index))) {
      number += standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
    }
    ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index];
  }
  if (ch === 'e' || ch === 'E') {
    number += standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
    ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index];
    if (ch === '+' || ch === '-') {
      number += standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
    }
    if (standalone_isDecimalDigit(standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index))) {
      while (standalone_isDecimalDigit(standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index))) {
        number += standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
      }
    } else {
      standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
    }
  }
  if (standalone_isIdentifierStart(standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index))) {
    standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
  }
  return {
    type: standalone_TokenNumericLiteral,
    value: parseFloat(number),
    start: start,
    end: standalone_vega_expression_module_index
  };
}

// 7.8.4 String Literals

function standalone_scanStringLiteral() {
  var str = '',
    quote,
    start,
    ch,
    code,
    octal = false;
  quote = standalone_vega_expression_module_source[standalone_vega_expression_module_index];
  standalone_assert(quote === '\'' || quote === '"', 'String literal must starts with a quote');
  start = standalone_vega_expression_module_index;
  ++standalone_vega_expression_module_index;
  while (standalone_vega_expression_module_index < standalone_vega_expression_module_length) {
    ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
    if (ch === quote) {
      quote = '';
      break;
    } else if (ch === '\\') {
      ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
      if (!ch || !standalone_isLineTerminator(ch.charCodeAt(0))) {
        switch (ch) {
          case 'u':
          case 'x':
            if (standalone_vega_expression_module_source[standalone_vega_expression_module_index] === '{') {
              ++standalone_vega_expression_module_index;
              str += standalone_scanUnicodeCodePointEscape();
            } else {
              str += standalone_scanHexEscape(ch);
            }
            break;
          case 'n':
            str += '\n';
            break;
          case 'r':
            str += '\r';
            break;
          case 't':
            str += '\t';
            break;
          case 'b':
            str += '\b';
            break;
          case 'f':
            str += '\f';
            break;
          case 'v':
            str += '\x0B';
            break;
          default:
            if (standalone_isOctalDigit(ch)) {
              code = '01234567'.indexOf(ch);

              // \0 is not octal escape sequence
              if (code !== 0) {
                octal = true;
              }
              if (standalone_vega_expression_module_index < standalone_vega_expression_module_length && standalone_isOctalDigit(standalone_vega_expression_module_source[standalone_vega_expression_module_index])) {
                octal = true;
                code = code * 8 + '01234567'.indexOf(standalone_vega_expression_module_source[standalone_vega_expression_module_index++]);

                // 3 digits are only allowed when string starts
                // with 0, 1, 2, 3
                if ('0123'.includes(ch) && standalone_vega_expression_module_index < standalone_vega_expression_module_length && standalone_isOctalDigit(standalone_vega_expression_module_source[standalone_vega_expression_module_index])) {
                  code = code * 8 + '01234567'.indexOf(standalone_vega_expression_module_source[standalone_vega_expression_module_index++]);
                }
              }
              str += String.fromCharCode(code);
            } else {
              str += ch;
            }
            break;
        }
      } else {
        if (ch === '\r' && standalone_vega_expression_module_source[standalone_vega_expression_module_index] === '\n') {
          ++standalone_vega_expression_module_index;
        }
      }
    } else if (standalone_isLineTerminator(ch.charCodeAt(0))) {
      break;
    } else {
      str += ch;
    }
  }
  if (quote !== '') {
    standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
  }
  return {
    type: standalone_TokenStringLiteral,
    value: str,
    octal: octal,
    start: start,
    end: standalone_vega_expression_module_index
  };
}
function standalone_testRegExp(pattern, flags) {
  let tmp = pattern;
  if (flags.includes('u')) {
    // Replace each astral symbol and every Unicode code point
    // escape sequence with a single ASCII symbol to avoid throwing on
    // regular expressions that are only valid in combination with the
    // `/u` flag.
    // Note: replacing with the ASCII symbol `x` might cause false
    // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
    // perfectly valid pattern that is equivalent to `[a-b]`, but it
    // would be replaced by `[x-b]` which throws an error.
    tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, ($0, $1) => {
      if (parseInt($1, 16) <= 0x10FFFF) {
        return 'x';
      }
      standalone_throwError({}, standalone_MessageInvalidRegExp);
    }).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x');
  }

  // First, detect invalid regular expressions.
  try {
    new RegExp(tmp);
  } catch (e) {
    standalone_throwError({}, standalone_MessageInvalidRegExp);
  }

  // Return a regular expression object for this pattern-flag pair, or
  // `null` in case the current environment doesn't support the flags it
  // uses.
  try {
    return new RegExp(pattern, flags);
  } catch (exception) {
    return null;
  }
}
function standalone_scanRegExpBody() {
  var ch, str, classMarker, terminated, body;
  ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index];
  standalone_assert(ch === '/', 'Regular expression literal must start with a slash');
  str = standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
  classMarker = false;
  terminated = false;
  while (standalone_vega_expression_module_index < standalone_vega_expression_module_length) {
    ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
    str += ch;
    if (ch === '\\') {
      ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index++];
      // ECMA-262 7.8.5
      if (standalone_isLineTerminator(ch.charCodeAt(0))) {
        standalone_throwError({}, standalone_MessageUnterminatedRegExp);
      }
      str += ch;
    } else if (standalone_isLineTerminator(ch.charCodeAt(0))) {
      standalone_throwError({}, standalone_MessageUnterminatedRegExp);
    } else if (classMarker) {
      if (ch === ']') {
        classMarker = false;
      }
    } else {
      if (ch === '/') {
        terminated = true;
        break;
      } else if (ch === '[') {
        classMarker = true;
      }
    }
  }
  if (!terminated) {
    standalone_throwError({}, standalone_MessageUnterminatedRegExp);
  }

  // Exclude leading and trailing slash.
  body = str.substr(1, str.length - 2);
  return {
    value: body,
    literal: str
  };
}
function standalone_scanRegExpFlags() {
  var ch, str, flags;
  str = '';
  flags = '';
  while (standalone_vega_expression_module_index < standalone_vega_expression_module_length) {
    ch = standalone_vega_expression_module_source[standalone_vega_expression_module_index];
    if (!standalone_isIdentifierPart(ch.charCodeAt(0))) {
      break;
    }
    ++standalone_vega_expression_module_index;
    if (ch === '\\' && standalone_vega_expression_module_index < standalone_vega_expression_module_length) {
      standalone_throwError({}, standalone_MessageUnexpectedToken, standalone_ILLEGAL);
    } else {
      flags += ch;
      str += ch;
    }
  }
  if (flags.search(/[^gimuy]/g) >= 0) {
    standalone_throwError({}, standalone_MessageInvalidRegExp, flags);
  }
  return {
    value: flags,
    literal: str
  };
}
function standalone_scanRegExp() {
  var start, body, flags, value;
  standalone_lookahead = null;
  standalone_skipComment();
  start = standalone_vega_expression_module_index;
  body = standalone_scanRegExpBody();
  flags = standalone_scanRegExpFlags();
  value = standalone_testRegExp(body.value, flags.value);
  return {
    literal: body.literal + flags.literal,
    value: value,
    regex: {
      pattern: body.value,
      flags: flags.value
    },
    start: start,
    end: standalone_vega_expression_module_index
  };
}
function standalone_isIdentifierName(token) {
  return token.type === standalone_TokenIdentifier || token.type === standalone_TokenKeyword || token.type === standalone_TokenBooleanLiteral || token.type === standalone_TokenNullLiteral;
}
function standalone_advance() {
  standalone_skipComment();
  if (standalone_vega_expression_module_index >= standalone_vega_expression_module_length) {
    return {
      type: standalone_TokenEOF,
      start: standalone_vega_expression_module_index,
      end: standalone_vega_expression_module_index
    };
  }
  const ch = standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index);
  if (standalone_isIdentifierStart(ch)) {
    return standalone_scanIdentifier();
  }

  // Very common: ( and ) and ;
  if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {
    return standalone_scanPunctuator();
  }

  // String literal starts with single quote (U+0027) or double quote (U+0022).
  if (ch === 0x27 || ch === 0x22) {
    return standalone_scanStringLiteral();
  }

  // Dot (.) U+002E can also start a floating-point number, hence the need
  // to check the next character.
  if (ch === 0x2E) {
    if (standalone_isDecimalDigit(standalone_vega_expression_module_source.charCodeAt(standalone_vega_expression_module_index + 1))) {
      return standalone_scanNumericLiteral();
    }
    return standalone_scanPunctuator();
  }
  if (standalone_isDecimalDigit(ch)) {
    return standalone_scanNumericLiteral();
  }
  return standalone_scanPunctuator();
}
function standalone_lex() {
  const token = standalone_lookahead;
  standalone_vega_expression_module_index = token.end;
  standalone_lookahead = standalone_advance();
  standalone_vega_expression_module_index = token.end;
  return token;
}
function standalone_vega_expression_module_peek() {
  const pos = standalone_vega_expression_module_index;
  standalone_lookahead = standalone_advance();
  standalone_vega_expression_module_index = pos;
}
function standalone_finishArrayExpression(elements) {
  const node = new standalone_ASTNode(standalone_SyntaxArrayExpression);
  node.elements = elements;
  return node;
}
function standalone_finishBinaryExpression(operator, left, right) {
  const node = new standalone_ASTNode(operator === '||' || operator === '&&' ? standalone_SyntaxLogicalExpression : standalone_SyntaxBinaryExpression);
  node.operator = operator;
  node.left = left;
  node.right = right;
  return node;
}
function standalone_finishCallExpression(callee, args) {
  const node = new standalone_ASTNode(standalone_SyntaxCallExpression);
  node.callee = callee;
  node.arguments = args;
  return node;
}
function standalone_finishConditionalExpression(test, consequent, alternate) {
  const node = new standalone_ASTNode(standalone_SyntaxConditionalExpression);
  node.test = test;
  node.consequent = consequent;
  node.alternate = alternate;
  return node;
}
function standalone_finishIdentifier(name) {
  const node = new standalone_ASTNode(standalone_SyntaxIdentifier);
  node.name = name;
  return node;
}
function standalone_finishLiteral(token) {
  const node = new standalone_ASTNode(standalone_SyntaxLiteral);
  node.value = token.value;
  node.raw = standalone_vega_expression_module_source.slice(token.start, token.end);
  if (token.regex) {
    if (node.raw === '//') {
      node.raw = '/(?:)/';
    }
    node.regex = token.regex;
  }
  return node;
}
function standalone_finishMemberExpression(accessor, object, property) {
  const node = new standalone_ASTNode(standalone_SyntaxMemberExpression);
  node.computed = accessor === '[';
  node.object = object;
  node.property = property;
  if (!node.computed) property.member = true;
  return node;
}
function standalone_finishObjectExpression(properties) {
  const node = new standalone_ASTNode(standalone_SyntaxObjectExpression);
  node.properties = properties;
  return node;
}
function standalone_finishProperty(kind, key, value) {
  const node = new standalone_ASTNode(standalone_SyntaxProperty);
  node.key = key;
  node.value = value;
  node.kind = kind;
  return node;
}
function standalone_finishUnaryExpression(operator, argument) {
  const node = new standalone_ASTNode(standalone_SyntaxUnaryExpression);
  node.operator = operator;
  node.argument = argument;
  node.prefix = true;
  return node;
}

// Throw an exception

function standalone_throwError(token, messageFormat) {
  var error,
    args = Array.prototype.slice.call(arguments, 2),
    msg = messageFormat.replace(/%(\d)/g, (whole, index) => {
      standalone_assert(index < args.length, 'Message reference must be in range');
      return args[index];
    });
  error = new Error(msg);
  error.index = standalone_vega_expression_module_index;
  error.description = msg;
  throw error;
}

// Throw an exception because of the token.

function standalone_throwUnexpected(token) {
  if (token.type === standalone_TokenEOF) {
    standalone_throwError(token, standalone_MessageUnexpectedEOS);
  }
  if (token.type === standalone_TokenNumericLiteral) {
    standalone_throwError(token, standalone_MessageUnexpectedNumber);
  }
  if (token.type === standalone_TokenStringLiteral) {
    standalone_throwError(token, standalone_MessageUnexpectedString);
  }
  if (token.type === standalone_TokenIdentifier) {
    standalone_throwError(token, standalone_MessageUnexpectedIdentifier);
  }
  if (token.type === standalone_TokenKeyword) {
    standalone_throwError(token, standalone_MessageUnexpectedReserved);
  }

  // BooleanLiteral, NullLiteral, or Punctuator.
  standalone_throwError(token, standalone_MessageUnexpectedToken, token.value);
}

// Expect the next token to match the specified punctuator.
// If not, an exception will be thrown.

function standalone_expect(value) {
  const token = standalone_lex();
  if (token.type !== standalone_TokenPunctuator || token.value !== value) {
    standalone_throwUnexpected(token);
  }
}

// Return true if the next token matches the specified punctuator.

function standalone_match(value) {
  return standalone_lookahead.type === standalone_TokenPunctuator && standalone_lookahead.value === value;
}

// Return true if the next token matches the specified keyword

function standalone_matchKeyword(keyword) {
  return standalone_lookahead.type === standalone_TokenKeyword && standalone_lookahead.value === keyword;
}

// 11.1.4 Array Initialiser

function standalone_parseArrayInitialiser() {
  const elements = [];
  standalone_vega_expression_module_index = standalone_lookahead.start;
  standalone_expect('[');
  while (!standalone_match(']')) {
    if (standalone_match(',')) {
      standalone_lex();
      elements.push(null);
    } else {
      elements.push(standalone_parseConditionalExpression());
      if (!standalone_match(']')) {
        standalone_expect(',');
      }
    }
  }
  standalone_lex();
  return standalone_finishArrayExpression(elements);
}

// 11.1.5 Object Initialiser

function standalone_parseObjectPropertyKey() {
  standalone_vega_expression_module_index = standalone_lookahead.start;
  const token = standalone_lex();

  // Note: This function is called only from parseObjectProperty(), where
  // EOF and Punctuator tokens are already filtered out.

  if (token.type === standalone_TokenStringLiteral || token.type === standalone_TokenNumericLiteral) {
    if (token.octal) {
      standalone_throwError(token, standalone_MessageStrictOctalLiteral);
    }
    return standalone_finishLiteral(token);
  }
  return standalone_finishIdentifier(token.value);
}
function standalone_parseObjectProperty() {
  var token, key, id, value;
  standalone_vega_expression_module_index = standalone_lookahead.start;
  token = standalone_lookahead;
  if (token.type === standalone_TokenIdentifier) {
    id = standalone_parseObjectPropertyKey();
    standalone_expect(':');
    value = standalone_parseConditionalExpression();
    return standalone_finishProperty('init', id, value);
  }
  if (token.type === standalone_TokenEOF || token.type === standalone_TokenPunctuator) {
    standalone_throwUnexpected(token);
  } else {
    key = standalone_parseObjectPropertyKey();
    standalone_expect(':');
    value = standalone_parseConditionalExpression();
    return standalone_finishProperty('init', key, value);
  }
}
function standalone_parseObjectInitialiser() {
  var properties = [],
    property,
    name,
    key,
    map = {},
    toString = String;
  standalone_vega_expression_module_index = standalone_lookahead.start;
  standalone_expect('{');
  while (!standalone_match('}')) {
    property = standalone_parseObjectProperty();
    if (property.key.type === standalone_SyntaxIdentifier) {
      name = property.key.name;
    } else {
      name = toString(property.key.value);
    }
    key = '$' + name;
    if (Object.prototype.hasOwnProperty.call(map, key)) {
      standalone_throwError({}, standalone_MessageStrictDuplicateProperty);
    } else {
      map[key] = true;
    }
    properties.push(property);
    if (!standalone_match('}')) {
      standalone_expect(',');
    }
  }
  standalone_expect('}');
  return standalone_finishObjectExpression(properties);
}

// 11.1.6 The Grouping Operator

function standalone_parseGroupExpression() {
  standalone_expect('(');
  const expr = standalone_parseExpression();
  standalone_expect(')');
  return expr;
}

// 11.1 Primary Expressions

const standalone_legalKeywords = {
  'if': 1
};
function standalone_parsePrimaryExpression() {
  var type, token, expr;
  if (standalone_match('(')) {
    return standalone_parseGroupExpression();
  }
  if (standalone_match('[')) {
    return standalone_parseArrayInitialiser();
  }
  if (standalone_match('{')) {
    return standalone_parseObjectInitialiser();
  }
  type = standalone_lookahead.type;
  standalone_vega_expression_module_index = standalone_lookahead.start;
  if (type === standalone_TokenIdentifier || standalone_legalKeywords[standalone_lookahead.value]) {
    expr = standalone_finishIdentifier(standalone_lex().value);
  } else if (type === standalone_TokenStringLiteral || type === standalone_TokenNumericLiteral) {
    if (standalone_lookahead.octal) {
      standalone_throwError(standalone_lookahead, standalone_MessageStrictOctalLiteral);
    }
    expr = standalone_finishLiteral(standalone_lex());
  } else if (type === standalone_TokenKeyword) {
    throw new Error(standalone_DISABLED);
  } else if (type === standalone_TokenBooleanLiteral) {
    token = standalone_lex();
    token.value = token.value === 'true';
    expr = standalone_finishLiteral(token);
  } else if (type === standalone_TokenNullLiteral) {
    token = standalone_lex();
    token.value = null;
    expr = standalone_finishLiteral(token);
  } else if (standalone_match('/') || standalone_match('/=')) {
    expr = standalone_finishLiteral(standalone_scanRegExp());
    standalone_vega_expression_module_peek();
  } else {
    standalone_throwUnexpected(standalone_lex());
  }
  return expr;
}

// 11.2 Left-Hand-Side Expressions

function standalone_parseArguments() {
  const args = [];
  standalone_expect('(');
  if (!standalone_match(')')) {
    while (standalone_vega_expression_module_index < standalone_vega_expression_module_length) {
      args.push(standalone_parseConditionalExpression());
      if (standalone_match(')')) {
        break;
      }
      standalone_expect(',');
    }
  }
  standalone_expect(')');
  return args;
}
function standalone_parseNonComputedProperty() {
  standalone_vega_expression_module_index = standalone_lookahead.start;
  const token = standalone_lex();
  if (!standalone_isIdentifierName(token)) {
    standalone_throwUnexpected(token);
  }
  return standalone_finishIdentifier(token.value);
}
function standalone_parseNonComputedMember() {
  standalone_expect('.');
  return standalone_parseNonComputedProperty();
}
function standalone_parseComputedMember() {
  standalone_expect('[');
  const expr = standalone_parseExpression();
  standalone_expect(']');
  return expr;
}
function standalone_parseLeftHandSideExpressionAllowCall() {
  var expr, args, property;
  expr = standalone_parsePrimaryExpression();
  for (;;) {
    if (standalone_match('.')) {
      property = standalone_parseNonComputedMember();
      expr = standalone_finishMemberExpression('.', expr, property);
    } else if (standalone_match('(')) {
      args = standalone_parseArguments();
      expr = standalone_finishCallExpression(expr, args);
    } else if (standalone_match('[')) {
      property = standalone_parseComputedMember();
      expr = standalone_finishMemberExpression('[', expr, property);
    } else {
      break;
    }
  }
  return expr;
}

// 11.3 Postfix Expressions

function standalone_parsePostfixExpression() {
  const expr = standalone_parseLeftHandSideExpressionAllowCall();
  if (standalone_lookahead.type === standalone_TokenPunctuator) {
    if (standalone_match('++') || standalone_match('--')) {
      throw new Error(standalone_DISABLED);
    }
  }
  return expr;
}

// 11.4 Unary Operators

function standalone_parseUnaryExpression() {
  var token, expr;
  if (standalone_lookahead.type !== standalone_TokenPunctuator && standalone_lookahead.type !== standalone_TokenKeyword) {
    expr = standalone_parsePostfixExpression();
  } else if (standalone_match('++') || standalone_match('--')) {
    throw new Error(standalone_DISABLED);
  } else if (standalone_match('+') || standalone_match('-') || standalone_match('~') || standalone_match('!')) {
    token = standalone_lex();
    expr = standalone_parseUnaryExpression();
    expr = standalone_finishUnaryExpression(token.value, expr);
  } else if (standalone_matchKeyword('delete') || standalone_matchKeyword('void') || standalone_matchKeyword('typeof')) {
    throw new Error(standalone_DISABLED);
  } else {
    expr = standalone_parsePostfixExpression();
  }
  return expr;
}
function standalone_binaryPrecedence(token) {
  let prec = 0;
  if (token.type !== standalone_TokenPunctuator && token.type !== standalone_TokenKeyword) {
    return 0;
  }
  switch (token.value) {
    case '||':
      prec = 1;
      break;
    case '&&':
      prec = 2;
      break;
    case '|':
      prec = 3;
      break;
    case '^':
      prec = 4;
      break;
    case '&':
      prec = 5;
      break;
    case '==':
    case '!=':
    case '===':
    case '!==':
      prec = 6;
      break;
    case '<':
    case '>':
    case '<=':
    case '>=':
    case 'instanceof':
    case 'in':
      prec = 7;
      break;
    case '<<':
    case '>>':
    case '>>>':
      prec = 8;
      break;
    case '+':
    case '-':
      prec = 9;
      break;
    case '*':
    case '/':
    case '%':
      prec = 11;
      break;
  }
  return prec;
}

// 11.5 Multiplicative Operators
// 11.6 Additive Operators
// 11.7 Bitwise Shift Operators
// 11.8 Relational Operators
// 11.9 Equality Operators
// 11.10 Binary Bitwise Operators
// 11.11 Binary Logical Operators

function standalone_parseBinaryExpression() {
  var marker, markers, expr, token, prec, stack, right, operator, left, i;
  marker = standalone_lookahead;
  left = standalone_parseUnaryExpression();
  token = standalone_lookahead;
  prec = standalone_binaryPrecedence(token);
  if (prec === 0) {
    return left;
  }
  token.prec = prec;
  standalone_lex();
  markers = [marker, standalone_lookahead];
  right = standalone_parseUnaryExpression();
  stack = [left, token, right];
  while ((prec = standalone_binaryPrecedence(standalone_lookahead)) > 0) {
    // Reduce: make a binary expression from the three topmost entries.
    while (stack.length > 2 && prec <= stack[stack.length - 2].prec) {
      right = stack.pop();
      operator = stack.pop().value;
      left = stack.pop();
      markers.pop();
      expr = standalone_finishBinaryExpression(operator, left, right);
      stack.push(expr);
    }

    // Shift.
    token = standalone_lex();
    token.prec = prec;
    stack.push(token);
    markers.push(standalone_lookahead);
    expr = standalone_parseUnaryExpression();
    stack.push(expr);
  }

  // Final reduce to clean-up the stack.
  i = stack.length - 1;
  expr = stack[i];
  markers.pop();
  while (i > 1) {
    markers.pop();
    expr = standalone_finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
    i -= 2;
  }
  return expr;
}

// 11.12 Conditional Operator

function standalone_parseConditionalExpression() {
  var expr, consequent, alternate;
  expr = standalone_parseBinaryExpression();
  if (standalone_match('?')) {
    standalone_lex();
    consequent = standalone_parseConditionalExpression();
    standalone_expect(':');
    alternate = standalone_parseConditionalExpression();
    expr = standalone_finishConditionalExpression(expr, consequent, alternate);
  }
  return expr;
}

// 11.14 Comma Operator

function standalone_parseExpression() {
  const expr = standalone_parseConditionalExpression();
  if (standalone_match(',')) {
    throw new Error(standalone_DISABLED); // no sequence expressions
  }
  return expr;
}
function standalone_parser (code) {
  standalone_vega_expression_module_source = code;
  standalone_vega_expression_module_index = 0;
  standalone_vega_expression_module_length = standalone_vega_expression_module_source.length;
  standalone_lookahead = null;
  standalone_vega_expression_module_peek();
  const expr = standalone_parseExpression();
  if (standalone_lookahead.type !== standalone_TokenEOF) {
    throw new Error('Unexpect token after expression.');
  }
  return expr;
}

var standalone_Constants = {
  NaN: 'NaN',
  E: 'Math.E',
  LN2: 'Math.LN2',
  LN10: 'Math.LN10',
  LOG2E: 'Math.LOG2E',
  LOG10E: 'Math.LOG10E',
  PI: 'Math.PI',
  SQRT1_2: 'Math.SQRT1_2',
  SQRT2: 'Math.SQRT2',
  MIN_VALUE: 'Number.MIN_VALUE',
  MAX_VALUE: 'Number.MAX_VALUE'
};

function standalone_Functions (codegen) {
  function fncall(name, args, cast, type) {
    let obj = codegen(args[0]);
    if (cast) {
      obj = cast + '(' + obj + ')';
      if (cast.lastIndexOf('new ', 0) === 0) obj = '(' + obj + ')';
    }
    return obj + '.' + name + (type < 0 ? '' : type === 0 ? '()' : '(' + args.slice(1).map(codegen).join(',') + ')');
  }
  function fn(name, cast, type) {
    return args => fncall(name, args, cast, type);
  }
  const DATE = 'new Date',
    STRING = 'String',
    REGEXP = 'RegExp';
  return {
    // MATH functions
    isNaN: 'Number.isNaN',
    isFinite: 'Number.isFinite',
    abs: 'Math.abs',
    acos: 'Math.acos',
    asin: 'Math.asin',
    atan: 'Math.atan',
    atan2: 'Math.atan2',
    ceil: 'Math.ceil',
    cos: 'Math.cos',
    exp: 'Math.exp',
    floor: 'Math.floor',
    hypot: 'Math.hypot',
    log: 'Math.log',
    max: 'Math.max',
    min: 'Math.min',
    pow: 'Math.pow',
    random: 'Math.random',
    round: 'Math.round',
    sin: 'Math.sin',
    sqrt: 'Math.sqrt',
    tan: 'Math.tan',
    clamp: function (args) {
      if (args.length < 3) standalone_vega_util_module_error('Missing arguments to clamp function.');
      if (args.length > 3) standalone_vega_util_module_error('Too many arguments to clamp function.');
      const a = args.map(codegen);
      return 'Math.max(' + a[1] + ', Math.min(' + a[2] + ',' + a[0] + '))';
    },
    // DATE functions
    now: 'Date.now',
    utc: 'Date.UTC',
    datetime: DATE,
    date: fn('getDate', DATE, 0),
    day: fn('getDay', DATE, 0),
    year: fn('getFullYear', DATE, 0),
    month: fn('getMonth', DATE, 0),
    hours: fn('getHours', DATE, 0),
    minutes: fn('getMinutes', DATE, 0),
    seconds: fn('getSeconds', DATE, 0),
    milliseconds: fn('getMilliseconds', DATE, 0),
    time: fn('getTime', DATE, 0),
    timezoneoffset: fn('getTimezoneOffset', DATE, 0),
    utcdate: fn('getUTCDate', DATE, 0),
    utcday: fn('getUTCDay', DATE, 0),
    utcyear: fn('getUTCFullYear', DATE, 0),
    utcmonth: fn('getUTCMonth', DATE, 0),
    utchours: fn('getUTCHours', DATE, 0),
    utcminutes: fn('getUTCMinutes', DATE, 0),
    utcseconds: fn('getUTCSeconds', DATE, 0),
    utcmilliseconds: fn('getUTCMilliseconds', DATE, 0),
    // sequence functions
    length: fn('length', null, -1),
    // STRING functions
    parseFloat: 'parseFloat',
    parseInt: 'parseInt',
    upper: fn('toUpperCase', STRING, 0),
    lower: fn('toLowerCase', STRING, 0),
    substring: fn('substring', STRING),
    split: fn('split', STRING),
    trim: fn('trim', STRING, 0),
    // REGEXP functions
    regexp: REGEXP,
    test: fn('test', REGEXP),
    // Control Flow functions
    if: function (args) {
      if (args.length < 3) standalone_vega_util_module_error('Missing arguments to if function.');
      if (args.length > 3) standalone_vega_util_module_error('Too many arguments to if function.');
      const a = args.map(codegen);
      return '(' + a[0] + '?' + a[1] + ':' + a[2] + ')';
    }
  };
}

function standalone_stripQuotes(s) {
  const n = s && s.length - 1;
  return n && (s[0] === '"' && s[n] === '"' || s[0] === '\'' && s[n] === '\'') ? s.slice(1, -1) : s;
}
function standalone_codegen (opt) {
  opt = opt || {};
  const allowed = opt.allowed ? standalone_toSet(opt.allowed) : {},
    forbidden = opt.forbidden ? standalone_toSet(opt.forbidden) : {},
    constants = opt.constants || standalone_Constants,
    functions = (opt.functions || standalone_Functions)(visit),
    globalvar = opt.globalvar,
    fieldvar = opt.fieldvar,
    outputGlobal = standalone_vega_util_module_isFunction(globalvar) ? globalvar : id => `${globalvar}["${id}"]`;
  let globals = {},
    fields = {},
    memberDepth = 0;
  function visit(ast) {
    if (standalone_vega_util_module_isString(ast)) return ast;
    const generator = Generators[ast.type];
    if (generator == null) standalone_vega_util_module_error('Unsupported type: ' + ast.type);
    return generator(ast);
  }
  const Generators = {
    Literal: n => n.raw,
    Identifier: n => {
      const id = n.name;
      if (memberDepth > 0) {
        return id;
      } else if (standalone_vega_util_module_has(forbidden, id)) {
        return standalone_vega_util_module_error('Illegal identifier: ' + id);
      } else if (standalone_vega_util_module_has(constants, id)) {
        return constants[id];
      } else if (standalone_vega_util_module_has(allowed, id)) {
        return id;
      } else {
        globals[id] = 1;
        return outputGlobal(id);
      }
    },
    MemberExpression: n => {
      const d = !n.computed,
        o = visit(n.object);
      if (d) memberDepth += 1;
      const p = visit(n.property);
      if (o === fieldvar) {
        // strip quotes to sanitize field name (#1653)
        fields[standalone_stripQuotes(p)] = 1;
      }
      if (d) memberDepth -= 1;
      return o + (d ? '.' + p : '[' + p + ']');
    },
    CallExpression: n => {
      if (n.callee.type !== 'Identifier') {
        standalone_vega_util_module_error('Illegal callee type: ' + n.callee.type);
      }
      const callee = n.callee.name,
        args = n.arguments,
        fn = standalone_vega_util_module_has(functions, callee) && functions[callee];
      if (!fn) standalone_vega_util_module_error('Unrecognized function: ' + callee);
      return standalone_vega_util_module_isFunction(fn) ? fn(args) : fn + '(' + args.map(visit).join(',') + ')';
    },
    ArrayExpression: n => '[' + n.elements.map(visit).join(',') + ']',
    BinaryExpression: n => '(' + visit(n.left) + ' ' + n.operator + ' ' + visit(n.right) + ')',
    UnaryExpression: n => '(' + n.operator + visit(n.argument) + ')',
    ConditionalExpression: n => '(' + visit(n.test) + '?' + visit(n.consequent) + ':' + visit(n.alternate) + ')',
    LogicalExpression: n => '(' + visit(n.left) + n.operator + visit(n.right) + ')',
    ObjectExpression: n => '{' + n.properties.map(visit).join(',') + '}',
    Property: n => {
      memberDepth += 1;
      const k = visit(n.key);
      memberDepth -= 1;
      return k + ':' + visit(n.value);
    }
  };
  function codegen(ast) {
    const result = {
      code: visit(ast),
      globals: Object.keys(globals),
      fields: Object.keys(fields)
    };
    globals = {};
    fields = {};
    return result;
  }
  codegen.functions = functions;
  codegen.constants = constants;
  return codegen;
}



;// ../../node_modules/d3-geo/src/area.js





var standalone_area_areaRingSum = new standalone_Adder();

// hello?

var standalone_area_areaSum = new standalone_Adder(),
    standalone_lambda00,
    standalone_phi00,
    standalone_lambda0,
    standalone_cosPhi0,
    standalone_sinPhi0;

var standalone_area_areaStream = {
  point: standalone_noop_noop,
  lineStart: standalone_noop_noop,
  lineEnd: standalone_noop_noop,
  polygonStart: function() {
    standalone_area_areaRingSum = new standalone_Adder();
    standalone_area_areaStream.lineStart = standalone_area_areaRingStart;
    standalone_area_areaStream.lineEnd = standalone_area_areaRingEnd;
  },
  polygonEnd: function() {
    var areaRing = +standalone_area_areaRingSum;
    standalone_area_areaSum.add(areaRing < 0 ? standalone_math_tau + areaRing : areaRing);
    this.lineStart = this.lineEnd = this.point = standalone_noop_noop;
  },
  sphere: function() {
    standalone_area_areaSum.add(standalone_math_tau);
  }
};

function standalone_area_areaRingStart() {
  standalone_area_areaStream.point = standalone_area_areaPointFirst;
}

function standalone_area_areaRingEnd() {
  standalone_area_areaPoint(standalone_lambda00, standalone_phi00);
}

function standalone_area_areaPointFirst(lambda, phi) {
  standalone_area_areaStream.point = standalone_area_areaPoint;
  standalone_lambda00 = lambda, standalone_phi00 = phi;
  lambda *= standalone_src_math_radians, phi *= standalone_src_math_radians;
  standalone_lambda0 = lambda, standalone_cosPhi0 = standalone_math_cos(phi = phi / 2 + standalone_quarterPi), standalone_sinPhi0 = standalone_math_sin(phi);
}

function standalone_area_areaPoint(lambda, phi) {
  lambda *= standalone_src_math_radians, phi *= standalone_src_math_radians;
  phi = phi / 2 + standalone_quarterPi; // half the angular distance from south pole

  // Spherical excess E for a spherical triangle with vertices: south pole,
  // previous point, current point.  Uses a formula derived from Cagnoli’s
  // theorem.  See Todhunter, Spherical Trig. (1871), Sec. 103, Eq. (2).
  var dLambda = lambda - standalone_lambda0,
      sdLambda = dLambda >= 0 ? 1 : -1,
      adLambda = sdLambda * dLambda,
      cosPhi = standalone_math_cos(phi),
      sinPhi = standalone_math_sin(phi),
      k = standalone_sinPhi0 * sinPhi,
      u = standalone_cosPhi0 * cosPhi + k * standalone_math_cos(adLambda),
      v = k * sdLambda * standalone_math_sin(adLambda);
  standalone_area_areaRingSum.add(standalone_math_atan2(v, u));

  // Advance the previous points.
  standalone_lambda0 = lambda, standalone_cosPhi0 = cosPhi, standalone_sinPhi0 = sinPhi;
}

/* harmony default export */ function standalone_d3_geo_src_area(object) {
  standalone_area_areaSum = new standalone_Adder();
  standalone_src_stream(object, standalone_area_areaStream);
  return standalone_area_areaSum * 2;
}

;// ../../node_modules/d3-geo/src/bounds.js






var standalone_bounds_lambda0, standalone_phi0, standalone_lambda1, standalone_phi1, // bounds
    standalone_lambda2, // previous lambda-coordinate
    standalone_bounds_lambda00, standalone_bounds_phi00, // first point
    standalone_p0, // previous 3D point
    standalone_deltaSum,
    standalone_ranges,
    standalone_bounds_range;

var standalone_bounds_boundsStream = {
  point: standalone_bounds_boundsPoint,
  lineStart: standalone_boundsLineStart,
  lineEnd: standalone_boundsLineEnd,
  polygonStart: function() {
    standalone_bounds_boundsStream.point = standalone_boundsRingPoint;
    standalone_bounds_boundsStream.lineStart = standalone_boundsRingStart;
    standalone_bounds_boundsStream.lineEnd = standalone_boundsRingEnd;
    standalone_deltaSum = new standalone_Adder();
    standalone_area_areaStream.polygonStart();
  },
  polygonEnd: function() {
    standalone_area_areaStream.polygonEnd();
    standalone_bounds_boundsStream.point = standalone_bounds_boundsPoint;
    standalone_bounds_boundsStream.lineStart = standalone_boundsLineStart;
    standalone_bounds_boundsStream.lineEnd = standalone_boundsLineEnd;
    if (standalone_area_areaRingSum < 0) standalone_bounds_lambda0 = -(standalone_lambda1 = 180), standalone_phi0 = -(standalone_phi1 = 90);
    else if (standalone_deltaSum > standalone_src_math_epsilon) standalone_phi1 = 90;
    else if (standalone_deltaSum < -standalone_src_math_epsilon) standalone_phi0 = -90;
    standalone_bounds_range[0] = standalone_bounds_lambda0, standalone_bounds_range[1] = standalone_lambda1;
  },
  sphere: function() {
    standalone_bounds_lambda0 = -(standalone_lambda1 = 180), standalone_phi0 = -(standalone_phi1 = 90);
  }
};

function standalone_bounds_boundsPoint(lambda, phi) {
  standalone_ranges.push(standalone_bounds_range = [standalone_bounds_lambda0 = lambda, standalone_lambda1 = lambda]);
  if (phi < standalone_phi0) standalone_phi0 = phi;
  if (phi > standalone_phi1) standalone_phi1 = phi;
}

function standalone_linePoint(lambda, phi) {
  var p = standalone_cartesian_cartesian([lambda * standalone_src_math_radians, phi * standalone_src_math_radians]);
  if (standalone_p0) {
    var normal = standalone_cartesianCross(standalone_p0, p),
        equatorial = [normal[1], -normal[0], 0],
        inflection = standalone_cartesianCross(equatorial, normal);
    standalone_cartesianNormalizeInPlace(inflection);
    inflection = standalone_spherical(inflection);
    var delta = lambda - standalone_lambda2,
        sign = delta > 0 ? 1 : -1,
        lambdai = inflection[0] * standalone_src_math_degrees * sign,
        phii,
        antimeridian = standalone_math_abs(delta) > 180;
    if (antimeridian ^ (sign * standalone_lambda2 < lambdai && lambdai < sign * lambda)) {
      phii = inflection[1] * standalone_src_math_degrees;
      if (phii > standalone_phi1) standalone_phi1 = phii;
    } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign * standalone_lambda2 < lambdai && lambdai < sign * lambda)) {
      phii = -inflection[1] * standalone_src_math_degrees;
      if (phii < standalone_phi0) standalone_phi0 = phii;
    } else {
      if (phi < standalone_phi0) standalone_phi0 = phi;
      if (phi > standalone_phi1) standalone_phi1 = phi;
    }
    if (antimeridian) {
      if (lambda < standalone_lambda2) {
        if (standalone_angle(standalone_bounds_lambda0, lambda) > standalone_angle(standalone_bounds_lambda0, standalone_lambda1)) standalone_lambda1 = lambda;
      } else {
        if (standalone_angle(lambda, standalone_lambda1) > standalone_angle(standalone_bounds_lambda0, standalone_lambda1)) standalone_bounds_lambda0 = lambda;
      }
    } else {
      if (standalone_lambda1 >= standalone_bounds_lambda0) {
        if (lambda < standalone_bounds_lambda0) standalone_bounds_lambda0 = lambda;
        if (lambda > standalone_lambda1) standalone_lambda1 = lambda;
      } else {
        if (lambda > standalone_lambda2) {
          if (standalone_angle(standalone_bounds_lambda0, lambda) > standalone_angle(standalone_bounds_lambda0, standalone_lambda1)) standalone_lambda1 = lambda;
        } else {
          if (standalone_angle(lambda, standalone_lambda1) > standalone_angle(standalone_bounds_lambda0, standalone_lambda1)) standalone_bounds_lambda0 = lambda;
        }
      }
    }
  } else {
    standalone_ranges.push(standalone_bounds_range = [standalone_bounds_lambda0 = lambda, standalone_lambda1 = lambda]);
  }
  if (phi < standalone_phi0) standalone_phi0 = phi;
  if (phi > standalone_phi1) standalone_phi1 = phi;
  standalone_p0 = p, standalone_lambda2 = lambda;
}

function standalone_boundsLineStart() {
  standalone_bounds_boundsStream.point = standalone_linePoint;
}

function standalone_boundsLineEnd() {
  standalone_bounds_range[0] = standalone_bounds_lambda0, standalone_bounds_range[1] = standalone_lambda1;
  standalone_bounds_boundsStream.point = standalone_bounds_boundsPoint;
  standalone_p0 = null;
}

function standalone_boundsRingPoint(lambda, phi) {
  if (standalone_p0) {
    var delta = lambda - standalone_lambda2;
    standalone_deltaSum.add(standalone_math_abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);
  } else {
    standalone_bounds_lambda00 = lambda, standalone_bounds_phi00 = phi;
  }
  standalone_area_areaStream.point(lambda, phi);
  standalone_linePoint(lambda, phi);
}

function standalone_boundsRingStart() {
  standalone_area_areaStream.lineStart();
}

function standalone_boundsRingEnd() {
  standalone_boundsRingPoint(standalone_bounds_lambda00, standalone_bounds_phi00);
  standalone_area_areaStream.lineEnd();
  if (standalone_math_abs(standalone_deltaSum) > standalone_src_math_epsilon) standalone_bounds_lambda0 = -(standalone_lambda1 = 180);
  standalone_bounds_range[0] = standalone_bounds_lambda0, standalone_bounds_range[1] = standalone_lambda1;
  standalone_p0 = null;
}

// Finds the left-right distance between two longitudes.
// This is almost the same as (lambda1 - lambda0 + 360°) % 360°, except that we want
// the distance between ±180° to be 360°.
function standalone_angle(lambda0, lambda1) {
  return (lambda1 -= lambda0) < 0 ? lambda1 + 360 : lambda1;
}

function standalone_rangeCompare(a, b) {
  return a[0] - b[0];
}

function standalone_rangeContains(range, x) {
  return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
}

/* harmony default export */ function standalone_src_bounds(feature) {
  var i, n, a, b, merged, deltaMax, delta;

  standalone_phi1 = standalone_lambda1 = -(standalone_bounds_lambda0 = standalone_phi0 = Infinity);
  standalone_ranges = [];
  standalone_src_stream(feature, standalone_bounds_boundsStream);

  // First, sort ranges by their minimum longitudes.
  if (n = standalone_ranges.length) {
    standalone_ranges.sort(standalone_rangeCompare);

    // Then, merge any ranges that overlap.
    for (i = 1, a = standalone_ranges[0], merged = [a]; i < n; ++i) {
      b = standalone_ranges[i];
      if (standalone_rangeContains(a, b[0]) || standalone_rangeContains(a, b[1])) {
        if (standalone_angle(a[0], b[1]) > standalone_angle(a[0], a[1])) a[1] = b[1];
        if (standalone_angle(b[0], a[1]) > standalone_angle(a[0], a[1])) a[0] = b[0];
      } else {
        merged.push(a = b);
      }
    }

    // Finally, find the largest gap between the merged ranges.
    // The final bounding box will be the inverse of this gap.
    for (deltaMax = -Infinity, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i) {
      b = merged[i];
      if ((delta = standalone_angle(a[1], b[0])) > deltaMax) deltaMax = delta, standalone_bounds_lambda0 = b[0], standalone_lambda1 = a[1];
    }
  }

  standalone_ranges = standalone_bounds_range = null;

  return standalone_bounds_lambda0 === Infinity || standalone_phi0 === Infinity
      ? [[NaN, NaN], [NaN, NaN]]
      : [[standalone_bounds_lambda0, standalone_phi0], [standalone_lambda1, standalone_phi1]];
}

;// ../../node_modules/d3-geo/src/centroid.js





var standalone_W0, standalone_W1,
    standalone_centroid_X0, standalone_centroid_Y0, standalone_centroid_Z0,
    standalone_centroid_X1, standalone_centroid_Y1, standalone_centroid_Z1,
    standalone_centroid_X2, standalone_centroid_Y2, standalone_centroid_Z2,
    standalone_centroid_lambda00, standalone_centroid_phi00, // first point
    standalone_src_centroid_x0, standalone_src_centroid_y0, standalone_z0; // previous point

var standalone_centroid_centroidStream = {
  sphere: standalone_noop_noop,
  point: standalone_centroid_centroidPoint,
  lineStart: standalone_centroid_centroidLineStart,
  lineEnd: standalone_centroid_centroidLineEnd,
  polygonStart: function() {
    standalone_centroid_centroidStream.lineStart = standalone_centroid_centroidRingStart;
    standalone_centroid_centroidStream.lineEnd = standalone_centroid_centroidRingEnd;
  },
  polygonEnd: function() {
    standalone_centroid_centroidStream.lineStart = standalone_centroid_centroidLineStart;
    standalone_centroid_centroidStream.lineEnd = standalone_centroid_centroidLineEnd;
  }
};

// Arithmetic mean of Cartesian vectors.
function standalone_centroid_centroidPoint(lambda, phi) {
  lambda *= standalone_src_math_radians, phi *= standalone_src_math_radians;
  var cosPhi = standalone_math_cos(phi);
  standalone_centroidPointCartesian(cosPhi * standalone_math_cos(lambda), cosPhi * standalone_math_sin(lambda), standalone_math_sin(phi));
}

function standalone_centroidPointCartesian(x, y, z) {
  ++standalone_W0;
  standalone_centroid_X0 += (x - standalone_centroid_X0) / standalone_W0;
  standalone_centroid_Y0 += (y - standalone_centroid_Y0) / standalone_W0;
  standalone_centroid_Z0 += (z - standalone_centroid_Z0) / standalone_W0;
}

function standalone_centroid_centroidLineStart() {
  standalone_centroid_centroidStream.point = standalone_centroidLinePointFirst;
}

function standalone_centroidLinePointFirst(lambda, phi) {
  lambda *= standalone_src_math_radians, phi *= standalone_src_math_radians;
  var cosPhi = standalone_math_cos(phi);
  standalone_src_centroid_x0 = cosPhi * standalone_math_cos(lambda);
  standalone_src_centroid_y0 = cosPhi * standalone_math_sin(lambda);
  standalone_z0 = standalone_math_sin(phi);
  standalone_centroid_centroidStream.point = standalone_centroidLinePoint;
  standalone_centroidPointCartesian(standalone_src_centroid_x0, standalone_src_centroid_y0, standalone_z0);
}

function standalone_centroidLinePoint(lambda, phi) {
  lambda *= standalone_src_math_radians, phi *= standalone_src_math_radians;
  var cosPhi = standalone_math_cos(phi),
      x = cosPhi * standalone_math_cos(lambda),
      y = cosPhi * standalone_math_sin(lambda),
      z = standalone_math_sin(phi),
      w = standalone_math_atan2(standalone_math_sqrt((w = standalone_src_centroid_y0 * z - standalone_z0 * y) * w + (w = standalone_z0 * x - standalone_src_centroid_x0 * z) * w + (w = standalone_src_centroid_x0 * y - standalone_src_centroid_y0 * x) * w), standalone_src_centroid_x0 * x + standalone_src_centroid_y0 * y + standalone_z0 * z);
  standalone_W1 += w;
  standalone_centroid_X1 += w * (standalone_src_centroid_x0 + (standalone_src_centroid_x0 = x));
  standalone_centroid_Y1 += w * (standalone_src_centroid_y0 + (standalone_src_centroid_y0 = y));
  standalone_centroid_Z1 += w * (standalone_z0 + (standalone_z0 = z));
  standalone_centroidPointCartesian(standalone_src_centroid_x0, standalone_src_centroid_y0, standalone_z0);
}

function standalone_centroid_centroidLineEnd() {
  standalone_centroid_centroidStream.point = standalone_centroid_centroidPoint;
}

// See J. E. Brock, The Inertia Tensor for a Spherical Triangle,
// J. Applied Mechanics 42, 239 (1975).
function standalone_centroid_centroidRingStart() {
  standalone_centroid_centroidStream.point = standalone_centroidRingPointFirst;
}

function standalone_centroid_centroidRingEnd() {
  standalone_centroidRingPoint(standalone_centroid_lambda00, standalone_centroid_phi00);
  standalone_centroid_centroidStream.point = standalone_centroid_centroidPoint;
}

function standalone_centroidRingPointFirst(lambda, phi) {
  standalone_centroid_lambda00 = lambda, standalone_centroid_phi00 = phi;
  lambda *= standalone_src_math_radians, phi *= standalone_src_math_radians;
  standalone_centroid_centroidStream.point = standalone_centroidRingPoint;
  var cosPhi = standalone_math_cos(phi);
  standalone_src_centroid_x0 = cosPhi * standalone_math_cos(lambda);
  standalone_src_centroid_y0 = cosPhi * standalone_math_sin(lambda);
  standalone_z0 = standalone_math_sin(phi);
  standalone_centroidPointCartesian(standalone_src_centroid_x0, standalone_src_centroid_y0, standalone_z0);
}

function standalone_centroidRingPoint(lambda, phi) {
  lambda *= standalone_src_math_radians, phi *= standalone_src_math_radians;
  var cosPhi = standalone_math_cos(phi),
      x = cosPhi * standalone_math_cos(lambda),
      y = cosPhi * standalone_math_sin(lambda),
      z = standalone_math_sin(phi),
      cx = standalone_src_centroid_y0 * z - standalone_z0 * y,
      cy = standalone_z0 * x - standalone_src_centroid_x0 * z,
      cz = standalone_src_centroid_x0 * y - standalone_src_centroid_y0 * x,
      m = standalone_hypot(cx, cy, cz),
      w = standalone_math_asin(m), // line weight = angle
      v = m && -w / m; // area weight multiplier
  standalone_centroid_X2.add(v * cx);
  standalone_centroid_Y2.add(v * cy);
  standalone_centroid_Z2.add(v * cz);
  standalone_W1 += w;
  standalone_centroid_X1 += w * (standalone_src_centroid_x0 + (standalone_src_centroid_x0 = x));
  standalone_centroid_Y1 += w * (standalone_src_centroid_y0 + (standalone_src_centroid_y0 = y));
  standalone_centroid_Z1 += w * (standalone_z0 + (standalone_z0 = z));
  standalone_centroidPointCartesian(standalone_src_centroid_x0, standalone_src_centroid_y0, standalone_z0);
}

/* harmony default export */ function standalone_src_centroid(object) {
  standalone_W0 = standalone_W1 =
  standalone_centroid_X0 = standalone_centroid_Y0 = standalone_centroid_Z0 =
  standalone_centroid_X1 = standalone_centroid_Y1 = standalone_centroid_Z1 = 0;
  standalone_centroid_X2 = new standalone_Adder();
  standalone_centroid_Y2 = new standalone_Adder();
  standalone_centroid_Z2 = new standalone_Adder();
  standalone_src_stream(object, standalone_centroid_centroidStream);

  var x = +standalone_centroid_X2,
      y = +standalone_centroid_Y2,
      z = +standalone_centroid_Z2,
      m = standalone_hypot(x, y, z);

  // If the area-weighted ccentroid is undefined, fall back to length-weighted ccentroid.
  if (m < standalone_math_epsilon2) {
    x = standalone_centroid_X1, y = standalone_centroid_Y1, z = standalone_centroid_Z1;
    // If the feature has zero length, fall back to arithmetic mean of point vectors.
    if (standalone_W1 < standalone_src_math_epsilon) x = standalone_centroid_X0, y = standalone_centroid_Y0, z = standalone_centroid_Z0;
    m = standalone_hypot(x, y, z);
    // If the feature still has an undefined ccentroid, then return.
    if (m < standalone_math_epsilon2) return [NaN, NaN];
  }

  return [standalone_math_atan2(y, x) * standalone_src_math_degrees, standalone_math_asin(z / m) * standalone_src_math_degrees];
}

;// ../../node_modules/d3-array/src/union.js


function standalone_union(...others) {
  const set = new standalone_InternSet();
  for (const other of others) {
    for (const o of other) {
      set.add(o);
    }
  }
  return set;
}

;// ../../node_modules/d3-array/src/intersection.js


function standalone_intersection(values, ...others) {
  values = new standalone_InternSet(values);
  others = others.map(standalone_intersection_set);
  out: for (const value of values) {
    for (const other of others) {
      if (!other.has(value)) {
        values.delete(value);
        continue out;
      }
    }
  }
  return values;
}

function standalone_intersection_set(values) {
  return values instanceof standalone_InternSet ? values : new standalone_InternSet(values);
}

;// ../../node_modules/vega-selections/build/vega-selection.module.js




// Registers vega-util field accessors to protect against XSS attacks
const standalone_SELECTION_GETTER = Symbol('vega_selection_getter');
function standalone_vega_selection_module_getter(f) {
  if (!f.getter || !f.getter[standalone_SELECTION_GETTER]) {
    f.getter = standalone_field(f.field);
    f.getter[standalone_SELECTION_GETTER] = true;
  }
  return f.getter;
}
const standalone_Intersect = 'intersect';
const standalone_Union = 'union';
const standalone_VlMulti = 'vlMulti';
const standalone_VlPoint = 'vlPoint';
const standalone_Or = 'or';
const standalone_And = 'and';
const standalone_SelectionId = '_vgsid_';
const standalone_$selectionId = standalone_field(standalone_SelectionId);

const standalone_TYPE_ENUM = 'E',
  standalone_TYPE_RANGE_INC = 'R',
  standalone_TYPE_RANGE_EXC = 'R-E',
  standalone_TYPE_RANGE_LE = 'R-LE',
  standalone_TYPE_RANGE_RE = 'R-RE',
  standalone_UNIT_INDEX = 'index:unit';

// TODO: revisit date coercion?
function standalone_testPoint(datum, entry) {
  var fields = entry.fields,
    values = entry.values,
    n = fields.length,
    i = 0,
    dval,
    f;
  for (; i < n; ++i) {
    f = fields[i];
    dval = standalone_vega_selection_module_getter(f)(datum);
    if (standalone_isDate(dval)) dval = standalone_toNumber(dval);
    if (standalone_isDate(values[i])) values[i] = standalone_toNumber(values[i]);
    if (standalone_vega_util_module_isArray(values[i]) && standalone_isDate(values[i][0])) values[i] = values[i].map(standalone_toNumber);
    if (f.type === standalone_TYPE_ENUM) {
      // Enumerated fields can either specify individual values (single/multi selections)
      // or an array of values (interval selections).
      if (standalone_vega_util_module_isArray(values[i]) ? values[i].indexOf(dval) < 0 : dval !== values[i]) {
        return false;
      }
    } else {
      if (f.type === standalone_TYPE_RANGE_INC) {
        if (!standalone_inrange(dval, values[i])) return false;
      } else if (f.type === standalone_TYPE_RANGE_RE) {
        // Discrete selection of bins test within the range [bin_start, bin_end).
        if (!standalone_inrange(dval, values[i], true, false)) return false;
      } else if (f.type === standalone_TYPE_RANGE_EXC) {
        // 'R-E'/'R-LE' included for completeness.
        if (!standalone_inrange(dval, values[i], false, false)) return false;
      } else if (f.type === standalone_TYPE_RANGE_LE) {
        if (!standalone_inrange(dval, values[i], false, true)) return false;
      }
    }
  }
  return true;
}

/**
 * Tests if a tuple is contained within an interactive selection.
 * @param {string} name - The name of the data set representing the selection.
 *  Tuples in the dataset are of the form
 *  {unit: string, fields: array<fielddef>, values: array<*>}.
 *  Fielddef is of the form
 *  {field: string, channel: string, type: 'E' | 'R'} where
 *  'type' identifies whether tuples in the dataset enumerate
 *  values for the field, or specify a continuous range.
 * @param {object} datum - The tuple to test for inclusion.
 * @param {string} op - The set operation for combining selections.
 *   One of 'intersect' or 'union' (default).
 * @return {boolean} - True if the datum is in the selection, false otherwise.
 */
function standalone_selectionTest(name, datum, op) {
  var data = this.context.data[name],
    entries = data ? data.values.value : [],
    unitIdx = data ? data[standalone_UNIT_INDEX] && data[standalone_UNIT_INDEX].value : undefined,
    intersect = op === standalone_Intersect,
    n = entries.length,
    i = 0,
    entry,
    miss,
    count,
    unit,
    b;
  for (; i < n; ++i) {
    entry = entries[i];
    if (unitIdx && intersect) {
      // multi selections union within the same unit and intersect across units.
      miss = miss || {};
      count = miss[unit = entry.unit] || 0;

      // if we've already matched this unit, skip.
      if (count === -1) continue;
      b = standalone_testPoint(datum, entry);
      miss[unit] = b ? -1 : ++count;

      // if we match and there are no other units return true
      // if we've missed against all tuples in this unit return false
      if (b && unitIdx.size === 1) return true;
      if (!b && count === unitIdx.get(unit).count) return false;
    } else {
      b = standalone_testPoint(datum, entry);

      // if we find a miss and we do require intersection return false
      // if we find a match and we don't require intersection return true
      if (intersect ^ b) return b;
    }
  }

  // if intersecting and we made it here, then we saw no misses
  // if not intersecting, then we saw no matches
  // if no active selections, return false
  return n && intersect;
}
const standalone_vega_selection_module_bisect = standalone_bisector(standalone_$selectionId),
  standalone_vega_selection_module_bisectLeft = standalone_vega_selection_module_bisect.left,
  standalone_vega_selection_module_bisectRight = standalone_vega_selection_module_bisect.right;
function standalone_selectionIdTest(name, datum, op) {
  const data = this.context.data[name],
    entries = data ? data.values.value : [],
    unitIdx = data ? data[standalone_UNIT_INDEX] && data[standalone_UNIT_INDEX].value : undefined,
    intersect = op === standalone_Intersect,
    value = standalone_$selectionId(datum),
    index = standalone_vega_selection_module_bisectLeft(entries, value);
  if (index === entries.length) return false;
  if (standalone_$selectionId(entries[index]) !== value) return false;
  if (unitIdx && intersect) {
    if (unitIdx.size === 1) return true;
    if (standalone_vega_selection_module_bisectRight(entries, value) - index < unitIdx.size) return false;
  }
  return true;
}

/**
 * Maps an array of scene graph items to an array of selection tuples.
 * @param {string} name  - The name of the dataset representing the selection.
 * @param {string} base  - The base object that generated tuples extend.
 *
 * @returns {array} An array of selection entries for the given unit.
 */
function standalone_selectionTuples(array, base) {
  return array.map(x => standalone_extend(base.fields ? {
    values: base.fields.map(f => standalone_vega_selection_module_getter(f)(x.datum))
  } : {
    [standalone_SelectionId]: standalone_$selectionId(x.datum)
  }, base));
}

/**
 * Resolves selection for use as a scale domain or reads via the API.
 * @param {string} name - The name of the dataset representing the selection
 * @param {string} [op='union'] - The set operation for combining selections.
 *                 One of 'intersect' or 'union' (default).
 * @param {boolean} isMulti - Identifies a "multi" selection to perform more
 *                 expensive resolution computation.
 * @param {boolean} vl5 - With Vega-Lite v5, "multi" selections are now called "point"
 *                 selections, and thus the resolved tuple should reflect this name.
 *                 This parameter allows us to reflect this change without triggering
 *                 a major version bump for Vega.
 * @returns {object} An object of selected fields and values.
 */
function standalone_selectionResolve(name, op, isMulti, vl5) {
  var data = this.context.data[name],
    entries = data ? data.values.value : [],
    resolved = {},
    multiRes = {},
    types = {},
    entry,
    fields,
    values,
    unit,
    field,
    value,
    res,
    resUnit,
    type,
    union,
    n = entries.length,
    i = 0,
    j,
    m;

  // First union all entries within the same unit.
  for (; i < n; ++i) {
    entry = entries[i];
    unit = entry.unit;
    fields = entry.fields;
    values = entry.values;
    if (fields && values) {
      // Intentional selection stores
      for (j = 0, m = fields.length; j < m; ++j) {
        field = fields[j];
        res = resolved[field.field] || (resolved[field.field] = {});
        resUnit = res[unit] || (res[unit] = []);
        types[field.field] = type = field.type.charAt(0);
        union = standalone_vega_selection_module_ops[`${type}_union`];
        res[unit] = union(resUnit, standalone_array(values[j]));
      }

      // If the same multi-selection is repeated over views and projected over
      // an encoding, it may operate over different fields making it especially
      // tricky to reliably resolve it. At best, we can de-dupe identical entries
      // but doing so may be more computationally expensive than it is worth.
      // Instead, for now, we simply transform our store representation into
      // a more human-friendly one.
      if (isMulti) {
        resUnit = multiRes[unit] || (multiRes[unit] = []);
        resUnit.push(standalone_array(values).reduce((obj, curr, j) => (obj[fields[j].field] = curr, obj), {}));
      }
    } else {
      // Short circuit extensional selectionId stores which hold sorted IDs unique to each unit.
      field = standalone_SelectionId;
      value = standalone_$selectionId(entry);
      res = resolved[field] || (resolved[field] = {});
      resUnit = res[unit] || (res[unit] = []);
      resUnit.push(value);
      if (isMulti) {
        resUnit = multiRes[unit] || (multiRes[unit] = []);
        resUnit.push({
          [standalone_SelectionId]: value
        });
      }
    }
  }

  // Then resolve fields across units as per the op.
  op = op || standalone_Union;
  if (resolved[standalone_SelectionId]) {
    resolved[standalone_SelectionId] = standalone_vega_selection_module_ops[`${standalone_SelectionId}_${op}`](...Object.values(resolved[standalone_SelectionId]));
  } else {
    Object.keys(resolved).forEach(field => {
      resolved[field] = Object.keys(resolved[field]).map(unit => resolved[field][unit]).reduce((acc, curr) => acc === undefined ? curr : standalone_vega_selection_module_ops[`${types[field]}_${op}`](acc, curr));
    });
  }
  entries = Object.keys(multiRes);
  if (isMulti && entries.length) {
    const key = vl5 ? standalone_VlPoint : standalone_VlMulti;
    resolved[key] = op === standalone_Union ? {
      [standalone_Or]: entries.reduce((acc, k) => (acc.push(...multiRes[k]), acc), [])
    } : {
      [standalone_And]: entries.map(k => ({
        [standalone_Or]: multiRes[k]
      }))
    };
  }
  return resolved;
}
var standalone_vega_selection_module_ops = {
  [`${standalone_SelectionId}_union`]: standalone_union,
  [`${standalone_SelectionId}_intersect`]: standalone_intersection,
  E_union: function (base, value) {
    if (!base.length) return value;
    var i = 0,
      n = value.length;
    for (; i < n; ++i) if (base.indexOf(value[i]) < 0) base.push(value[i]);
    return base;
  },
  E_intersect: function (base, value) {
    return !base.length ? value : base.filter(v => value.indexOf(v) >= 0);
  },
  R_union: function (base, value) {
    var lo = standalone_toNumber(value[0]),
      hi = standalone_toNumber(value[1]);
    if (lo > hi) {
      lo = value[1];
      hi = value[0];
    }
    if (!base.length) return [lo, hi];
    if (base[0] > lo) base[0] = lo;
    if (base[1] < hi) base[1] = hi;
    return base;
  },
  R_intersect: function (base, value) {
    var lo = standalone_toNumber(value[0]),
      hi = standalone_toNumber(value[1]);
    if (lo > hi) {
      lo = value[1];
      hi = value[0];
    }
    if (!base.length) return [lo, hi];
    if (hi < base[0] || base[1] < lo) {
      return [];
    } else {
      if (base[0] < lo) base[0] = lo;
      if (base[1] > hi) base[1] = hi;
    }
    return base;
  }
};

const standalone_DataPrefix = ':',
  standalone_IndexPrefix = '@';
function standalone_selectionVisitor(name, args, scope, params) {
  if (args[0].type !== standalone_Literal) standalone_vega_util_module_error('First argument to selection functions must be a string literal.');
  const data = args[0].value,
    op = args.length >= 2 && standalone_peek(args).value,
    field = 'unit',
    indexName = standalone_IndexPrefix + field,
    dataName = standalone_DataPrefix + data;

  // eslint-disable-next-line no-prototype-builtins
  if (op === standalone_Intersect && !standalone_vega_util_module_has(params, indexName)) {
    params[indexName] = scope.getData(data).indataRef(scope, field);
  }

  // eslint-disable-next-line no-prototype-builtins
  if (!standalone_vega_util_module_has(params, dataName)) {
    params[dataName] = scope.getData(data).tuplesRef();
  }
}



;// ../../node_modules/vega-functions/build/vega-functions.module.js












function standalone_vega_functions_module_data(name) {
  const data = this.context.data[name];
  return data ? data.values.value : [];
}
function standalone_indata(name, field, value) {
  const index = this.context.data[name]['index:' + field],
    entry = index ? index.value.get(value) : undefined;
  return entry ? entry.count : entry;
}
function standalone_setdata(name, tuples) {
  const df = this.context.dataflow,
    data = this.context.data[name],
    input = data.input;
  df.pulse(input, df.changeset().remove(standalone_truthy).insert(tuples));
  return 1;
}

function standalone_encode (item, name, retval) {
  if (item) {
    const df = this.context.dataflow,
      target = item.mark.source;
    df.pulse(target, df.changeset().encode(item, name));
  }
  return retval !== undefined ? retval : item;
}

const standalone_wrap = method => function (value, spec) {
  const locale = this.context.dataflow.locale();
  return value === null ? 'null' : locale[method](spec)(value);
};
const standalone_vega_functions_module_format = standalone_wrap('format');
const standalone_vega_functions_module_timeFormat = standalone_wrap('timeFormat');
const standalone_vega_functions_module_utcFormat = standalone_wrap('utcFormat');
const standalone_vega_functions_module_timeParse = standalone_wrap('timeParse');
const standalone_vega_functions_module_utcParse = standalone_wrap('utcParse');
const standalone_dateObj = new Date(2000, 0, 1);
function standalone_vega_functions_module_time(month, day, specifier) {
  if (!Number.isInteger(month) || !Number.isInteger(day)) return '';
  standalone_dateObj.setYear(2000);
  standalone_dateObj.setMonth(month);
  standalone_dateObj.setDate(day);
  return standalone_vega_functions_module_timeFormat.call(this, standalone_dateObj, specifier);
}
function standalone_monthFormat(month) {
  return standalone_vega_functions_module_time.call(this, month, 1, '%B');
}
function standalone_monthAbbrevFormat(month) {
  return standalone_vega_functions_module_time.call(this, month, 1, '%b');
}
function standalone_dayFormat(day) {
  return standalone_vega_functions_module_time.call(this, 0, 2 + day, '%A');
}
function standalone_dayAbbrevFormat(day) {
  return standalone_vega_functions_module_time.call(this, 0, 2 + day, '%a');
}

const standalone_vega_functions_module_DataPrefix = ':';
const standalone_vega_functions_module_IndexPrefix = '@';
const standalone_ScalePrefix = '%';
const standalone_SignalPrefix = '$';

function standalone_dataVisitor(name, args, scope, params) {
  if (args[0].type !== standalone_Literal) {
    standalone_vega_util_module_error('First argument to data functions must be a string literal.');
  }
  const data = args[0].value,
    dataName = standalone_vega_functions_module_DataPrefix + data;
  if (!standalone_vega_util_module_has(dataName, params)) {
    try {
      params[dataName] = scope.getData(data).tuplesRef();
    } catch (err) {
      // if data set does not exist, there's nothing to track
    }
  }
}
function standalone_indataVisitor(name, args, scope, params) {
  if (args[0].type !== standalone_Literal) standalone_vega_util_module_error('First argument to indata must be a string literal.');
  if (args[1].type !== standalone_Literal) standalone_vega_util_module_error('Second argument to indata must be a string literal.');
  const data = args[0].value,
    field = args[1].value,
    indexName = standalone_vega_functions_module_IndexPrefix + field;
  if (!standalone_vega_util_module_has(indexName, params)) {
    params[indexName] = scope.getData(data).indataRef(scope, field);
  }
}
function standalone_scaleVisitor(name, args, scope, params) {
  if (args[0].type === standalone_Literal) {
    // add scale dependency
    standalone_addScaleDependency(scope, params, args[0].value);
  } else {
    // indirect scale lookup; add all scales as parameters
    for (name in scope.scales) {
      standalone_addScaleDependency(scope, params, name);
    }
  }
}
function standalone_addScaleDependency(scope, params, name) {
  const scaleName = standalone_ScalePrefix + name;
  if (!standalone_vega_util_module_has(params, scaleName)) {
    try {
      params[scaleName] = scope.scaleRef(name);
    } catch (err) {
      // TODO: error handling? warning?
    }
  }
}

function standalone_getScale(nameOrFunction, ctx) {
  if (standalone_vega_util_module_isFunction(nameOrFunction)) {
    return nameOrFunction;
  }
  if (standalone_vega_util_module_isString(nameOrFunction)) {
    const maybeScale = ctx.scales[nameOrFunction];
    return maybeScale && standalone_isRegisteredScale(maybeScale.value) ? maybeScale.value : undefined;
  }
  return undefined;
}
function standalone_internalScaleFunctions(codegen, fnctx, visitors) {
  // add helper method to the 'this' expression function context
  fnctx.__bandwidth = s => s && s.bandwidth ? s.bandwidth() : 0;

  // register AST visitors for internal scale functions
  visitors._bandwidth = standalone_scaleVisitor;
  visitors._range = standalone_scaleVisitor;
  visitors._scale = standalone_scaleVisitor;

  // resolve scale reference directly to the signal hash argument
  const ref = arg => '_[' + (arg.type === standalone_Literal ? standalone_$(standalone_ScalePrefix + arg.value) : standalone_$(standalone_ScalePrefix) + '+' + codegen(arg)) + ']';

  // define and return internal scale function code generators
  // these internal functions are called by mark encoders
  return {
    _bandwidth: args => `this.__bandwidth(${ref(args[0])})`,
    _range: args => `${ref(args[0])}.range()`,
    _scale: args => `${ref(args[0])}(${codegen(args[1])})`
  };
}

function standalone_geoMethod(methodName, globalMethod) {
  return function (projection, geojson, group) {
    if (projection) {
      // projection defined, use it
      const p = standalone_getScale(projection, (group || this).context);
      return p && p.path[methodName](geojson);
    } else {
      // projection undefined, use global method
      return globalMethod(geojson);
    }
  };
}
const standalone_geoArea = standalone_geoMethod('area', standalone_d3_geo_src_area);
const standalone_geoBounds = standalone_geoMethod('bounds', standalone_src_bounds);
const standalone_geoCentroid = standalone_geoMethod('centroid', standalone_src_centroid);
function standalone_geoScale(projection, group) {
  const p = standalone_getScale(projection, (group || this).context);
  return p && p.scale();
}

function standalone_inScope (item) {
  const group = this.context.group;
  let value = false;
  if (group) while (item) {
    if (item === group) {
      value = true;
      break;
    }
    item = item.mark.group;
  }
  return value;
}

function standalone_vega_functions_module_log(df, method, args) {
  try {
    df[method].apply(df, ['EXPRESSION'].concat([].slice.call(args)));
  } catch (err) {
    df.warn(err);
  }
  return args[args.length - 1];
}
function standalone_warn() {
  return standalone_vega_functions_module_log(this.context.dataflow, 'warn', arguments);
}
function standalone_info() {
  return standalone_vega_functions_module_log(this.context.dataflow, 'info', arguments);
}
function standalone_vega_functions_module_debug() {
  return standalone_vega_functions_module_log(this.context.dataflow, 'debug', arguments);
}

// https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
function standalone_channel_luminance_value(channelValue) {
  const val = channelValue / 255;
  if (val <= 0.03928) {
    return val / 12.92;
  }
  return Math.pow((val + 0.055) / 1.055, 2.4);
}
function standalone_luminance(color) {
  const c = standalone_color_rgb(color),
    r = standalone_channel_luminance_value(c.r),
    g = standalone_channel_luminance_value(c.g),
    b = standalone_channel_luminance_value(c.b);
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

// https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
function standalone_contrast(color1, color2) {
  const lum1 = standalone_luminance(color1),
    lum2 = standalone_luminance(color2),
    lumL = Math.max(lum1, lum2),
    lumD = Math.min(lum1, lum2);
  return (lumL + 0.05) / (lumD + 0.05);
}

function standalone_vega_functions_module_merge () {
  const args = [].slice.call(arguments);
  args.unshift({});
  return standalone_extend(...args);
}

function standalone_equal(a, b) {
  return a === b || a !== a && b !== b ? true : standalone_vega_util_module_isArray(a) ? standalone_vega_util_module_isArray(b) && a.length === b.length ? standalone_equalArray(a, b) : false : standalone_vega_util_module_isObject(a) && standalone_vega_util_module_isObject(b) ? standalone_equalObject(a, b) : false;
}
function standalone_equalArray(a, b) {
  for (let i = 0, n = a.length; i < n; ++i) {
    if (!standalone_equal(a[i], b[i])) return false;
  }
  return true;
}
function standalone_equalObject(a, b) {
  for (const key in a) {
    if (!standalone_equal(a[key], b[key])) return false;
  }
  return true;
}
function standalone_removePredicate(props) {
  return _ => standalone_equalObject(props, _);
}
function standalone_modify (name, insert, remove, toggle, modify, values) {
  const df = this.context.dataflow,
    data = this.context.data[name],
    input = data.input,
    stamp = df.stamp();
  let changes = data.changes,
    predicate,
    key;
  if (df._trigger === false || !(input.value.length || insert || toggle)) {
    // nothing to do!
    return 0;
  }
  if (!changes || changes.stamp < stamp) {
    data.changes = changes = df.changeset();
    changes.stamp = stamp;
    df.runAfter(() => {
      data.modified = true;
      df.pulse(input, changes).run();
    }, true, 1);
  }
  if (remove) {
    predicate = remove === true ? standalone_truthy : standalone_vega_util_module_isArray(remove) || standalone_isTuple(remove) ? remove : standalone_removePredicate(remove);
    changes.remove(predicate);
  }
  if (insert) {
    changes.insert(insert);
  }
  if (toggle) {
    predicate = standalone_removePredicate(toggle);
    if (input.value.some(predicate)) {
      changes.remove(predicate);
    } else {
      changes.insert(toggle);
    }
  }
  if (modify) {
    for (key in values) {
      changes.modify(modify, key, values[key]);
    }
  }
  return 1;
}

function standalone_pinchDistance(event) {
  const t = event.touches,
    dx = t[0].clientX - t[1].clientX,
    dy = t[0].clientY - t[1].clientY;
  return Math.hypot(dx, dy);
}
function standalone_pinchAngle(event) {
  const t = event.touches;
  return Math.atan2(t[0].clientY - t[1].clientY, t[0].clientX - t[1].clientX);
}

// memoize accessor functions
const standalone_accessors = {};
function standalone_pluck (data, name) {
  const accessor = standalone_accessors[name] || (standalone_accessors[name] = standalone_field(name));
  return standalone_vega_util_module_isArray(data) ? data.map(accessor) : accessor(data);
}

function standalone_vega_functions_module_array(seq) {
  return standalone_vega_util_module_isArray(seq) || ArrayBuffer.isView(seq) ? seq : null;
}
function standalone_vega_functions_module_sequence(seq) {
  return standalone_vega_functions_module_array(seq) || (standalone_vega_util_module_isString(seq) ? seq : null);
}
function standalone_vega_functions_module_join(seq) {
  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }
  return standalone_vega_functions_module_array(seq).join(...args);
}
function standalone_indexof(seq) {
  for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
    args[_key2 - 1] = arguments[_key2];
  }
  return standalone_vega_functions_module_sequence(seq).indexOf(...args);
}
function standalone_lastindexof(seq) {
  for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
    args[_key3 - 1] = arguments[_key3];
  }
  return standalone_vega_functions_module_sequence(seq).lastIndexOf(...args);
}
function standalone_vega_functions_module_slice(seq) {
  for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
    args[_key4 - 1] = arguments[_key4];
  }
  return standalone_vega_functions_module_sequence(seq).slice(...args);
}
function standalone_vega_functions_module_replace(str, pattern, repl) {
  if (standalone_vega_util_module_isFunction(repl)) standalone_vega_util_module_error('Function argument passed to replace.');
  return String(str).replace(pattern, repl);
}
function standalone_vega_functions_module_reverse(seq) {
  return standalone_vega_functions_module_array(seq).slice().reverse();
}

function standalone_bandspace(count, paddingInner, paddingOuter) {
  return standalone_bandSpace(count || 0, paddingInner || 0, paddingOuter || 0);
}
function standalone_bandwidth(name, group) {
  const s = standalone_getScale(name, (group || this).context);
  return s && s.bandwidth ? s.bandwidth() : 0;
}
function standalone_vega_functions_module_copy(name, group) {
  const s = standalone_getScale(name, (group || this).context);
  return s ? s.copy() : undefined;
}
function standalone_domain(name, group) {
  const s = standalone_getScale(name, (group || this).context);
  return s ? s.domain() : [];
}
function standalone_invert(name, range, group) {
  const s = standalone_getScale(name, (group || this).context);
  return !s ? undefined : standalone_vega_util_module_isArray(range) ? (s.invertRange || s.invert)(range) : (s.invert || s.invertExtent)(range);
}
function standalone_vega_functions_module_range(name, group) {
  const s = standalone_getScale(name, (group || this).context);
  return s && s.range ? s.range() : [];
}
function standalone_vega_functions_module_scale(name, value, group) {
  const s = standalone_getScale(name, (group || this).context);
  return s ? s(value) : undefined;
}

function standalone_scaleGradient (scale, p0, p1, count, group) {
  scale = standalone_getScale(scale, (group || this).context);
  const gradient = standalone_Gradient(p0, p1);
  let stops = scale.domain(),
    min = stops[0],
    max = standalone_peek(stops),
    fraction = standalone_vega_util_module_identity;
  if (!(max - min)) {
    // expand scale if domain has zero span, fix #1479
    scale = (scale.interpolator ? standalone_vega_scale_module_scale('sequential')().interpolator(scale.interpolator()) : standalone_vega_scale_module_scale('linear')().interpolate(scale.interpolate()).range(scale.range())).domain([min = 0, max = 1]);
  } else {
    fraction = standalone_scaleFraction(scale, min, max);
  }
  if (scale.ticks) {
    stops = scale.ticks(+count || 15);
    if (min !== stops[0]) stops.unshift(min);
    if (max !== standalone_peek(stops)) stops.push(max);
  }
  stops.forEach(_ => gradient.stop(fraction(_), scale(_)));
  return gradient;
}

function standalone_geoShape(projection, geojson, group) {
  const p = standalone_getScale(projection, (group || this).context);
  return function (context) {
    return p ? p.path.context(context)(geojson) : '';
  };
}
function standalone_pathShape(path) {
  let p = null;
  return function (context) {
    return context ? standalone_pathRender(context, p = p || standalone_vega_scenegraph_module_parse(path)) : path;
  };
}

const standalone_datum = d => d.data;
function standalone_treeNodes(name, context) {
  const tree = standalone_vega_functions_module_data.call(context, name);
  return tree.root && tree.root.lookup || {};
}
function standalone_treePath(name, source, target) {
  const nodes = standalone_treeNodes(name, this),
    s = nodes[source],
    t = nodes[target];
  return s && t ? s.path(t).map(standalone_datum) : undefined;
}
function standalone_treeAncestors(name, node) {
  const n = standalone_treeNodes(name, this)[node];
  return n ? n.ancestors().map(standalone_datum) : undefined;
}

const standalone_window = () => typeof window !== 'undefined' && window || null;
function standalone_screen() {
  const w = standalone_window();
  return w ? w.screen : {};
}
function standalone_windowSize() {
  const w = standalone_window();
  return w ? [w.innerWidth, w.innerHeight] : [undefined, undefined];
}
function standalone_containerSize() {
  const view = this.context.dataflow,
    el = view.container && view.container();
  return el ? [el.clientWidth, el.clientHeight] : [undefined, undefined];
}

function standalone_vega_functions_module_intersect (b, opt, group) {
  if (!b) return [];
  const [u, v] = b,
    box = new standalone_Bounds().set(u[0], u[1], v[0], v[1]),
    scene = group || this.context.dataflow.scenegraph().root;
  return standalone_vega_scenegraph_module_intersect(scene, box, standalone_vega_functions_module_filter(opt));
}
function standalone_vega_functions_module_filter(opt) {
  let p = null;
  if (opt) {
    const types = standalone_array(opt.marktype),
      names = standalone_array(opt.markname);
    p = _ => (!types.length || types.some(t => _.marktype === t)) && (!names.length || names.some(s => _.name === s));
  }
  return p;
}

/**
 * Appends a new point to the lasso
 *
 * @param {*} lasso the lasso in pixel space
 * @param {*} x the x coordinate in pixel space
 * @param {*} y the y coordinate in pixel space
 * @param {*} minDist the minimum distance, in pixels, that thenew point needs to be apart from the last point
 * @returns a new array containing the lasso with the new point
 */
function standalone_lassoAppend(lasso, x, y) {
  let minDist = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 5;
  lasso = standalone_array(lasso);
  const last = lasso[lasso.length - 1];

  // Add point to lasso if its the first point or distance to last point exceed minDist
  return last === undefined || Math.hypot(last[0] - x, last[1] - y) > minDist ? [...lasso, [x, y]] : lasso;
}

/**
 * Generates a svg path command which draws a lasso
 *
 * @param {*} lasso the lasso in pixel space in the form [[x,y], [x,y], ...]
 * @returns the svg path command that draws the lasso
 */
function standalone_lassoPath(lasso) {
  return standalone_array(lasso).reduce((svg, _ref, i) => {
    let [x, y] = _ref;
    return svg += i == 0 ? `M ${x},${y} ` : i === lasso.length - 1 ? ' Z' : `L ${x},${y} `;
  }, '');
}

/**
 * Inverts the lasso from pixel space to an array of vega scenegraph tuples
 *
 * @param {*} data the dataset
 * @param {*} pixelLasso the lasso in pixel space, [[x,y], [x,y], ...]
 * @param {*} unit the unit where the lasso is defined
 *
 * @returns an array of vega scenegraph tuples
 */
function standalone_intersectLasso(markname, pixelLasso, unit) {
  const {
    x,
    y,
    mark
  } = unit;
  const bb = new standalone_Bounds().set(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, Number.MIN_SAFE_INTEGER);

  // Get bounding box around lasso
  for (const [px, py] of pixelLasso) {
    if (px < bb.x1) bb.x1 = px;
    if (px > bb.x2) bb.x2 = px;
    if (py < bb.y1) bb.y1 = py;
    if (py > bb.y2) bb.y2 = py;
  }

  // Translate bb against unit coordinates
  bb.translate(x, y);
  const intersection = standalone_vega_functions_module_intersect([[bb.x1, bb.y1], [bb.x2, bb.y2]], markname, mark);

  // Check every point against the lasso
  return intersection.filter(tuple => standalone_pointInPolygon(tuple.x, tuple.y, pixelLasso));
}

/**
 * Performs a test if a point is inside a polygon based on the idea from
 * https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html
 *
 * This method will not need the same start/end point since it wraps around the edges of the array
 *
 * @param {*} test a point to test against
 * @param {*} polygon a polygon in the form [[x,y], [x,y], ...]
 * @returns true if the point lies inside the polygon, false otherwise
 */
function standalone_pointInPolygon(testx, testy, polygon) {
  let intersections = 0;
  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    const [prevX, prevY] = polygon[j];
    const [x, y] = polygon[i];

    // count intersections
    if (y > testy != prevY > testy && testx < (prevX - x) * (testy - y) / (prevY - y) + x) {
      intersections++;
    }
  }

  // point is in polygon if intersection count is odd
  return intersections & 1;
}

// Expression function context object
const standalone_functionContext = {
  random() {
    return standalone_random();
  },
  // override default
  cumulativeNormal: standalone_cumulativeNormal,
  cumulativeLogNormal: standalone_cumulativeLogNormal,
  cumulativeUniform: standalone_cumulativeUniform,
  densityNormal: standalone_densityNormal,
  densityLogNormal: standalone_densityLogNormal,
  densityUniform: standalone_densityUniform,
  quantileNormal: standalone_quantileNormal,
  quantileLogNormal: standalone_quantileLogNormal,
  quantileUniform: standalone_quantileUniform,
  sampleNormal: standalone_sampleNormal,
  sampleLogNormal: standalone_sampleLogNormal,
  sampleUniform: standalone_sampleUniform,
  isArray: standalone_vega_util_module_isArray,
  isBoolean: standalone_isBoolean,
  isDate: standalone_isDate,
  isDefined(_) {
    return _ !== undefined;
  },
  isNumber: standalone_isNumber,
  isObject: standalone_vega_util_module_isObject,
  isRegExp: standalone_isRegExp,
  isString: standalone_vega_util_module_isString,
  isTuple: standalone_isTuple,
  isValid(_) {
    return _ != null && _ === _;
  },
  toBoolean: standalone_toBoolean,
  toDate(_) {
    return standalone_toDate(_);
  },
  // suppress extra arguments
  toNumber: standalone_toNumber,
  toString: standalone_vega_util_module_toString,
  indexof: standalone_indexof,
  join: standalone_vega_functions_module_join,
  lastindexof: standalone_lastindexof,
  replace: standalone_vega_functions_module_replace,
  reverse: standalone_vega_functions_module_reverse,
  slice: standalone_vega_functions_module_slice,
  flush: standalone_vega_util_module_flush,
  lerp: standalone_lerp,
  merge: standalone_vega_functions_module_merge,
  pad: standalone_pad,
  peek: standalone_peek,
  pluck: standalone_pluck,
  span: standalone_span,
  inrange: standalone_inrange,
  truncate: standalone_truncate,
  rgb: standalone_color_rgb,
  lab: standalone_lab,
  hcl: standalone_hcl,
  hsl: standalone_hsl,
  luminance: standalone_luminance,
  contrast: standalone_contrast,
  sequence: standalone_range,
  format: standalone_vega_functions_module_format,
  utcFormat: standalone_vega_functions_module_utcFormat,
  utcParse: standalone_vega_functions_module_utcParse,
  utcOffset: standalone_utcOffset,
  utcSequence: standalone_utcSequence,
  timeFormat: standalone_vega_functions_module_timeFormat,
  timeParse: standalone_vega_functions_module_timeParse,
  timeOffset: standalone_timeOffset,
  timeSequence: standalone_timeSequence,
  timeUnitSpecifier: standalone_timeUnitSpecifier,
  monthFormat: standalone_monthFormat,
  monthAbbrevFormat: standalone_monthAbbrevFormat,
  dayFormat: standalone_dayFormat,
  dayAbbrevFormat: standalone_dayAbbrevFormat,
  quarter: standalone_quarter,
  utcquarter: standalone_utcquarter,
  week: standalone_week,
  utcweek: standalone_utcweek,
  dayofyear: standalone_dayofyear,
  utcdayofyear: standalone_utcdayofyear,
  warn: standalone_warn,
  info: standalone_info,
  debug: standalone_vega_functions_module_debug,
  extent(_) {
    return standalone_extent(_);
  },
  // suppress extra arguments
  inScope: standalone_inScope,
  intersect: standalone_vega_functions_module_intersect,
  clampRange: standalone_clampRange,
  pinchDistance: standalone_pinchDistance,
  pinchAngle: standalone_pinchAngle,
  screen: standalone_screen,
  containerSize: standalone_containerSize,
  windowSize: standalone_windowSize,
  bandspace: standalone_bandspace,
  setdata: standalone_setdata,
  pathShape: standalone_pathShape,
  panLinear: standalone_panLinear,
  panLog: standalone_panLog,
  panPow: standalone_panPow,
  panSymlog: standalone_panSymlog,
  zoomLinear: standalone_zoomLinear,
  zoomLog: standalone_zoomLog,
  zoomPow: standalone_zoomPow,
  zoomSymlog: standalone_zoomSymlog,
  encode: standalone_encode,
  modify: standalone_modify,
  lassoAppend: standalone_lassoAppend,
  lassoPath: standalone_lassoPath,
  intersectLasso: standalone_intersectLasso
};
const standalone_eventFunctions = ['view', 'item', 'group', 'xy', 'x', 'y'],
  // event functions
  standalone_eventPrefix = 'event.vega.',
  // event function prefix
  standalone_thisPrefix = 'this.',
  // function context prefix
  standalone_astVisitors = {}; // AST visitors for dependency analysis

// export code generator parameters
const standalone_codegenParams = {
  forbidden: ['_'],
  allowed: ['datum', 'event', 'item'],
  fieldvar: 'datum',
  globalvar: id => `_[${standalone_$(standalone_SignalPrefix + id)}]`,
  functions: standalone_buildFunctions,
  constants: standalone_Constants,
  visitors: standalone_astVisitors
};

// export code generator
const standalone_codeGenerator = standalone_codegen(standalone_codegenParams);

// Build expression function registry
function standalone_buildFunctions(codegen) {
  const fn = standalone_Functions(codegen);
  standalone_eventFunctions.forEach(name => fn[name] = standalone_eventPrefix + name);
  for (const name in standalone_functionContext) {
    fn[name] = standalone_thisPrefix + name;
  }
  standalone_extend(fn, standalone_internalScaleFunctions(codegen, standalone_functionContext, standalone_astVisitors));
  return fn;
}

// Register an expression function
function standalone_expressionFunction(name, fn, visitor) {
  if (arguments.length === 1) {
    return standalone_functionContext[name];
  }

  // register with the functionContext
  standalone_functionContext[name] = fn;

  // if there is an astVisitor register that, too
  if (visitor) standalone_astVisitors[name] = visitor;

  // if the code generator has already been initialized,
  // we need to also register the function with it
  if (standalone_codeGenerator) standalone_codeGenerator.functions[name] = standalone_thisPrefix + name;
  return this;
}

// register expression functions with ast visitors
standalone_expressionFunction('bandwidth', standalone_bandwidth, standalone_scaleVisitor);
standalone_expressionFunction('copy', standalone_vega_functions_module_copy, standalone_scaleVisitor);
standalone_expressionFunction('domain', standalone_domain, standalone_scaleVisitor);
standalone_expressionFunction('range', standalone_vega_functions_module_range, standalone_scaleVisitor);
standalone_expressionFunction('invert', standalone_invert, standalone_scaleVisitor);
standalone_expressionFunction('scale', standalone_vega_functions_module_scale, standalone_scaleVisitor);
standalone_expressionFunction('gradient', standalone_scaleGradient, standalone_scaleVisitor);
standalone_expressionFunction('geoArea', standalone_geoArea, standalone_scaleVisitor);
standalone_expressionFunction('geoBounds', standalone_geoBounds, standalone_scaleVisitor);
standalone_expressionFunction('geoCentroid', standalone_geoCentroid, standalone_scaleVisitor);
standalone_expressionFunction('geoShape', standalone_geoShape, standalone_scaleVisitor);
standalone_expressionFunction('geoScale', standalone_geoScale, standalone_scaleVisitor);
standalone_expressionFunction('indata', standalone_indata, standalone_indataVisitor);
standalone_expressionFunction('data', standalone_vega_functions_module_data, standalone_dataVisitor);
standalone_expressionFunction('treePath', standalone_treePath, standalone_dataVisitor);
standalone_expressionFunction('treeAncestors', standalone_treeAncestors, standalone_dataVisitor);

// register Vega-Lite selection functions
standalone_expressionFunction('vlSelectionTest', standalone_selectionTest, standalone_selectionVisitor);
standalone_expressionFunction('vlSelectionIdTest', standalone_selectionIdTest, standalone_selectionVisitor);
standalone_expressionFunction('vlSelectionResolve', standalone_selectionResolve, standalone_selectionVisitor);
standalone_expressionFunction('vlSelectionTuples', standalone_selectionTuples);

function standalone_vega_functions_module_parser (expr, scope) {
  const params = {};

  // parse the expression to an abstract syntax tree (ast)
  let ast;
  try {
    expr = standalone_vega_util_module_isString(expr) ? expr : standalone_$(expr) + '';
    ast = standalone_parser(expr);
  } catch (err) {
    standalone_vega_util_module_error('Expression parse error: ' + expr);
  }

  // analyze ast function calls for dependencies
  ast.visit(node => {
    if (node.type !== standalone_CallExpression) return;
    const name = node.callee.name,
      visit = standalone_codegenParams.visitors[name];
    if (visit) visit(name, node.arguments, scope, params);
  });

  // perform code generation
  const gen = standalone_codeGenerator(ast);

  // collect signal dependencies
  gen.globals.forEach(name => {
    const signalName = standalone_SignalPrefix + name;
    if (!standalone_vega_util_module_has(params, signalName) && scope.getSignal(name)) {
      params[signalName] = scope.signalRef(name);
    }
  });

  // return generated expression code and dependencies
  return {
    $expr: standalone_extend({
      code: gen.code
    }, scope.options.ast ? {
      ast
    } : null),
    $fields: gen.fields,
    $params: params
  };
}



;// ../../node_modules/vega-runtime/build/vega-runtime.module.js



/**
 * Parse a serialized dataflow specification.
 */
function standalone_vega_runtime_module_parse (spec) {
  const ctx = this,
    operators = spec.operators || [];

  // parse background
  if (spec.background) {
    ctx.background = spec.background;
  }

  // parse event configuration
  if (spec.eventConfig) {
    ctx.eventConfig = spec.eventConfig;
  }

  // parse locale configuration
  if (spec.locale) {
    ctx.locale = spec.locale;
  }

  // parse operators
  operators.forEach(entry => ctx.parseOperator(entry));

  // parse operator parameters
  operators.forEach(entry => ctx.parseOperatorParameters(entry));

  // parse streams
  (spec.streams || []).forEach(entry => ctx.parseStream(entry));

  // parse updates
  (spec.updates || []).forEach(entry => ctx.parseUpdate(entry));
  return ctx.resolve();
}

const standalone_Skip = standalone_toSet(['rule']),
  standalone_Swap = standalone_toSet(['group', 'image', 'rect']);
function standalone_adjustSpatial(encode, marktype) {
  let code = '';
  if (standalone_Skip[marktype]) return code;
  if (encode.x2) {
    if (encode.x) {
      if (standalone_Swap[marktype]) {
        code += 'if(o.x>o.x2)$=o.x,o.x=o.x2,o.x2=$;';
      }
      code += 'o.width=o.x2-o.x;';
    } else {
      code += 'o.x=o.x2-(o.width||0);';
    }
  }
  if (encode.xc) {
    code += 'o.x=o.xc-(o.width||0)/2;';
  }
  if (encode.y2) {
    if (encode.y) {
      if (standalone_Swap[marktype]) {
        code += 'if(o.y>o.y2)$=o.y,o.y=o.y2,o.y2=$;';
      }
      code += 'o.height=o.y2-o.y;';
    } else {
      code += 'o.y=o.y2-(o.height||0);';
    }
  }
  if (encode.yc) {
    code += 'o.y=o.yc-(o.height||0)/2;';
  }
  return code;
}
function standalone_canonicalType(type) {
  return (type + '').toLowerCase();
}
function standalone_isOperator(type) {
  return standalone_canonicalType(type) === 'operator';
}
function standalone_isCollect(type) {
  return standalone_canonicalType(type) === 'collect';
}

function standalone_expression(ctx, args, code) {
  // wrap code in return statement if expression does not terminate
  if (!code.endsWith(';')) {
    code = 'return(' + code + ');';
  }
  const fn = Function(...args.concat(code));
  return ctx && ctx.functions ? fn.bind(ctx.functions) : fn;
}

// generate code for comparing a single field
function src_standalone_compare(u, v, lt, gt) {
  return `((u = ${u}) < (v = ${v}) || u == null) && v != null ? ${lt}
  : (u > v || v == null) && u != null ? ${gt}
  : ((v = v instanceof Date ? +v : v), (u = u instanceof Date ? +u : u)) !== u && v === v ? ${lt}
  : v !== v && u === u ? ${gt} : `;
}
var standalone_expressionCodegen = {
  /**
   * Parse an expression used to update an operator value.
   */
  operator: (ctx, expr) => standalone_expression(ctx, ['_'], expr.code),
  /**
   * Parse an expression provided as an operator parameter value.
   */
  parameter: (ctx, expr) => standalone_expression(ctx, ['datum', '_'], expr.code),
  /**
   * Parse an expression applied to an event stream.
   */
  event: (ctx, expr) => standalone_expression(ctx, ['event'], expr.code),
  /**
   * Parse an expression used to handle an event-driven operator update.
   */
  handler: (ctx, expr) => {
    const code = `var datum=event.item&&event.item.datum;return ${expr.code};`;
    return standalone_expression(ctx, ['_', 'event'], code);
  },
  /**
   * Parse an expression that performs visual encoding.
   */
  encode: (ctx, encode) => {
    const {
      marktype,
      channels
    } = encode;
    let code = 'var o=item,datum=o.datum,m=0,$;';
    for (const name in channels) {
      const o = 'o[' + standalone_$(name) + ']';
      code += `$=${channels[name].code};if(${o}!==$)${o}=$,m=1;`;
    }
    code += standalone_adjustSpatial(channels, marktype);
    code += 'return m;';
    return standalone_expression(ctx, ['item', '_'], code);
  },
  /**
   * Optimized code generators for access and comparison.
   */
  codegen: {
    get(path) {
      const ref = `[${path.map(standalone_$).join('][')}]`;
      const get = Function('_', `return _${ref};`);
      get.path = ref;
      return get;
    },
    comparator(fields, orders) {
      let t;
      const map = (f, i) => {
        const o = orders[i];
        let u, v;
        if (f.path) {
          u = `a${f.path}`;
          v = `b${f.path}`;
        } else {
          (t = t || {})['f' + i] = f;
          u = `this.f${i}(a)`;
          v = `this.f${i}(b)`;
        }
        return src_standalone_compare(u, v, -o, o);
      };
      const fn = Function('a', 'b', 'var u, v; return ' + fields.map(map).join('') + '0;');
      return t ? fn.bind(t) : fn;
    }
  }
};

/**
 * Parse a dataflow operator.
 */
function standalone_parseOperator(spec) {
  const ctx = this;
  if (standalone_isOperator(spec.type) || !spec.type) {
    ctx.operator(spec, spec.update ? ctx.operatorExpression(spec.update) : null);
  } else {
    ctx.transform(spec, spec.type);
  }
}

/**
 * Parse and assign operator parameters.
 */
function standalone_parseOperatorParameters(spec) {
  const ctx = this;
  if (spec.params) {
    const op = ctx.get(spec.id);
    if (!op) standalone_vega_util_module_error('Invalid operator id: ' + spec.id);
    ctx.dataflow.connect(op, op.parameters(ctx.parseParameters(spec.params), spec.react, spec.initonly));
  }
}

/**
 * Parse a set of operator parameters.
 */
function standalone_parseParameters(spec, params) {
  params = params || {};
  const ctx = this;
  for (const key in spec) {
    const value = spec[key];
    params[key] = standalone_vega_util_module_isArray(value) ? value.map(v => standalone_parseParameter(v, ctx, params)) : standalone_parseParameter(value, ctx, params);
  }
  return params;
}

/**
 * Parse a single parameter.
 */
function standalone_parseParameter(spec, ctx, params) {
  if (!spec || !standalone_vega_util_module_isObject(spec)) return spec;
  for (let i = 0, n = standalone_PARSERS.length, p; i < n; ++i) {
    p = standalone_PARSERS[i];
    if (standalone_vega_util_module_has(spec, p.key)) {
      return p.parse(spec, ctx, params);
    }
  }
  return spec;
}

/** Reference parsers. */
var standalone_PARSERS = [{
  key: '$ref',
  parse: standalone_getOperator
}, {
  key: '$key',
  parse: standalone_getKey
}, {
  key: '$expr',
  parse: standalone_getExpression
}, {
  key: '$field',
  parse: standalone_vega_runtime_module_getField
}, {
  key: '$encode',
  parse: standalone_getEncode
}, {
  key: '$compare',
  parse: standalone_getCompare
}, {
  key: '$context',
  parse: standalone_vega_runtime_module_getContext
}, {
  key: '$subflow',
  parse: standalone_getSubflow
}, {
  key: '$tupleid',
  parse: standalone_getTupleId
}];

/**
 * Resolve an operator reference.
 */
function standalone_getOperator(_, ctx) {
  return ctx.get(_.$ref) || standalone_vega_util_module_error('Operator not defined: ' + _.$ref);
}

/**
 * Resolve an expression reference.
 */
function standalone_getExpression(_, ctx, params) {
  if (_.$params) {
    // parse expression parameters
    ctx.parseParameters(_.$params, params);
  }
  const k = 'e:' + _.$expr.code;
  return ctx.fn[k] || (ctx.fn[k] = standalone_accessor(ctx.parameterExpression(_.$expr), _.$fields));
}

/**
 * Resolve a key accessor reference.
 */
function standalone_getKey(_, ctx) {
  const k = 'k:' + _.$key + '_' + !!_.$flat;
  return ctx.fn[k] || (ctx.fn[k] = standalone_key(_.$key, _.$flat, ctx.expr.codegen));
}

/**
 * Resolve a field accessor reference.
 */
function standalone_vega_runtime_module_getField(_, ctx) {
  if (!_.$field) return null;
  const k = 'f:' + _.$field + '_' + _.$name;
  return ctx.fn[k] || (ctx.fn[k] = standalone_field(_.$field, _.$name, ctx.expr.codegen));
}

/**
 * Resolve a comparator function reference.
 */
function standalone_getCompare(_, ctx) {
  // As of Vega 5.5.3, $tupleid sort is no longer used.
  // Keep here for now for backwards compatibility.
  const k = 'c:' + _.$compare + '_' + _.$order,
    c = standalone_array(_.$compare).map(_ => _ && _.$tupleid ? standalone_tupleid : _);
  return ctx.fn[k] || (ctx.fn[k] = standalone_compare(c, _.$order, ctx.expr.codegen));
}

/**
 * Resolve an encode operator reference.
 */
function standalone_getEncode(_, ctx) {
  const spec = _.$encode,
    encode = {};
  for (const name in spec) {
    const enc = spec[name];
    encode[name] = standalone_accessor(ctx.encodeExpression(enc.$expr), enc.$fields);
    encode[name].output = enc.$output;
  }
  return encode;
}

/**
 * Resolve a context reference.
 */
function standalone_vega_runtime_module_getContext(_, ctx) {
  return ctx;
}

/**
 * Resolve a recursive subflow specification.
 */
function standalone_getSubflow(_, ctx) {
  const spec = _.$subflow;
  return function (dataflow, key, parent) {
    const subctx = ctx.fork().parse(spec),
      op = subctx.get(spec.operators[0].id),
      p = subctx.signals.parent;
    if (p) p.set(parent);
    op.detachSubflow = () => ctx.detach(subctx);
    return op;
  };
}

/**
 * Resolve a tuple id reference.
 */
function standalone_getTupleId() {
  return standalone_tupleid;
}

/**
 * Parse an event stream specification.
 */
function standalone_parseStream (spec) {
  var ctx = this,
    filter = spec.filter != null ? ctx.eventExpression(spec.filter) : undefined,
    stream = spec.stream != null ? ctx.get(spec.stream) : undefined,
    args;
  if (spec.source) {
    stream = ctx.events(spec.source, spec.type, filter);
  } else if (spec.merge) {
    args = spec.merge.map(_ => ctx.get(_));
    stream = args[0].merge.apply(args[0], args.slice(1));
  }
  if (spec.between) {
    args = spec.between.map(_ => ctx.get(_));
    stream = stream.between(args[0], args[1]);
  }
  if (spec.filter) {
    stream = stream.filter(filter);
  }
  if (spec.throttle != null) {
    stream = stream.throttle(+spec.throttle);
  }
  if (spec.debounce != null) {
    stream = stream.debounce(+spec.debounce);
  }
  if (stream == null) {
    standalone_vega_util_module_error('Invalid stream definition: ' + JSON.stringify(spec));
  }
  if (spec.consume) stream.consume(true);
  ctx.stream(spec, stream);
}

/**
 * Parse an event-driven operator update.
 */
function standalone_parseUpdate (spec) {
  var ctx = this,
    srcid = standalone_vega_util_module_isObject(srcid = spec.source) ? srcid.$ref : srcid,
    source = ctx.get(srcid),
    target = null,
    update = spec.update,
    params = undefined;
  if (!source) standalone_vega_util_module_error('Source not defined: ' + spec.source);
  target = spec.target && spec.target.$expr ? ctx.eventExpression(spec.target.$expr) : ctx.get(spec.target);
  if (update && update.$expr) {
    if (update.$params) {
      params = ctx.parseParameters(update.$params);
    }
    update = ctx.handlerExpression(update.$expr);
  }
  ctx.update(spec, source, target, update, params);
}

const standalone_vega_runtime_module_SKIP = {
  skip: true
};
function standalone_getState(options) {
  var ctx = this,
    state = {};
  if (options.signals) {
    var signals = state.signals = {};
    Object.keys(ctx.signals).forEach(key => {
      const op = ctx.signals[key];
      if (options.signals(key, op)) {
        signals[key] = op.value;
      }
    });
  }
  if (options.data) {
    var data = state.data = {};
    Object.keys(ctx.data).forEach(key => {
      const dataset = ctx.data[key];
      if (options.data(key, dataset)) {
        data[key] = dataset.input.value;
      }
    });
  }
  if (ctx.subcontext && options.recurse !== false) {
    state.subcontext = ctx.subcontext.map(ctx => ctx.getState(options));
  }
  return state;
}
function standalone_setState(state) {
  var ctx = this,
    df = ctx.dataflow,
    data = state.data,
    signals = state.signals;
  Object.keys(signals || {}).forEach(key => {
    df.update(ctx.signals[key], signals[key], standalone_vega_runtime_module_SKIP);
  });
  Object.keys(data || {}).forEach(key => {
    df.pulse(ctx.data[key].input, df.changeset().remove(standalone_truthy).insert(data[key]));
  });
  (state.subcontext || []).forEach((substate, i) => {
    const subctx = ctx.subcontext[i];
    if (subctx) subctx.setState(substate);
  });
}

/**
 * Context objects store the current parse state.
 * Enables lookup of parsed operators, event streams, accessors, etc.
 * Provides a 'fork' method for creating child contexts for subflows.
 */
function standalone_vega_runtime_module_context (df, transforms, functions, expr) {
  return new standalone_Context(df, transforms, functions, expr);
}
function standalone_Context(df, transforms, functions, expr) {
  this.dataflow = df;
  this.transforms = transforms;
  this.events = df.events.bind(df);
  this.expr = expr || standalone_expressionCodegen, this.signals = {};
  this.scales = {};
  this.nodes = {};
  this.data = {};
  this.fn = {};
  if (functions) {
    this.functions = Object.create(functions);
    this.functions.context = this;
  }
}
function standalone_Subcontext(ctx) {
  this.dataflow = ctx.dataflow;
  this.transforms = ctx.transforms;
  this.events = ctx.events;
  this.expr = ctx.expr;
  this.signals = Object.create(ctx.signals);
  this.scales = Object.create(ctx.scales);
  this.nodes = Object.create(ctx.nodes);
  this.data = Object.create(ctx.data);
  this.fn = Object.create(ctx.fn);
  if (ctx.functions) {
    this.functions = Object.create(ctx.functions);
    this.functions.context = this;
  }
}
standalone_Context.prototype = standalone_Subcontext.prototype = {
  fork() {
    const ctx = new standalone_Subcontext(this);
    (this.subcontext || (this.subcontext = [])).push(ctx);
    return ctx;
  },
  detach(ctx) {
    this.subcontext = this.subcontext.filter(c => c !== ctx);

    // disconnect all nodes in the subcontext
    // wipe out targets first for better efficiency
    const keys = Object.keys(ctx.nodes);
    for (const key of keys) ctx.nodes[key]._targets = null;
    for (const key of keys) ctx.nodes[key].detach();
    ctx.nodes = null;
  },
  get(id) {
    return this.nodes[id];
  },
  set(id, node) {
    return this.nodes[id] = node;
  },
  add(spec, op) {
    const ctx = this,
      df = ctx.dataflow,
      data = spec.value;
    ctx.set(spec.id, op);
    if (standalone_isCollect(spec.type) && data) {
      if (data.$ingest) {
        df.ingest(op, data.$ingest, data.$format);
      } else if (data.$request) {
        df.preload(op, data.$request, data.$format);
      } else {
        df.pulse(op, df.changeset().insert(data));
      }
    }
    if (spec.root) {
      ctx.root = op;
    }
    if (spec.parent) {
      let p = ctx.get(spec.parent.$ref);
      if (p) {
        df.connect(p, [op]);
        op.targets().add(p);
      } else {
        (ctx.unresolved = ctx.unresolved || []).push(() => {
          p = ctx.get(spec.parent.$ref);
          df.connect(p, [op]);
          op.targets().add(p);
        });
      }
    }
    if (spec.signal) {
      ctx.signals[spec.signal] = op;
    }
    if (spec.scale) {
      ctx.scales[spec.scale] = op;
    }
    if (spec.data) {
      for (const name in spec.data) {
        const data = ctx.data[name] || (ctx.data[name] = {});
        spec.data[name].forEach(role => data[role] = op);
      }
    }
  },
  resolve() {
    (this.unresolved || []).forEach(fn => fn());
    delete this.unresolved;
    return this;
  },
  operator(spec, update) {
    this.add(spec, this.dataflow.add(spec.value, update));
  },
  transform(spec, type) {
    this.add(spec, this.dataflow.add(this.transforms[standalone_canonicalType(type)]));
  },
  stream(spec, stream) {
    this.set(spec.id, stream);
  },
  update(spec, stream, target, update, params) {
    this.dataflow.on(stream, target, update, params, spec.options);
  },
  // expression parsing
  operatorExpression(expr) {
    return this.expr.operator(this, expr);
  },
  parameterExpression(expr) {
    return this.expr.parameter(this, expr);
  },
  eventExpression(expr) {
    return this.expr.event(this, expr);
  },
  handlerExpression(expr) {
    return this.expr.handler(this, expr);
  },
  encodeExpression(encode) {
    return this.expr.encode(this, encode);
  },
  // parse methods
  parse: standalone_vega_runtime_module_parse,
  parseOperator: standalone_parseOperator,
  parseOperatorParameters: standalone_parseOperatorParameters,
  parseParameters: standalone_parseParameters,
  parseStream: standalone_parseStream,
  parseUpdate: standalone_parseUpdate,
  // state methods
  getState: standalone_getState,
  setState: standalone_setState
};



;// ../../node_modules/d3-timer/src/interval.js


/* harmony default export */ function standalone_src_interval(callback, delay, time) {
  var t = new standalone_Timer, total = delay;
  if (delay == null) return t.restart(callback, delay, time), t;
  t._restart = t.restart;
  t.restart = function(callback, delay, time) {
    delay = +delay, time = time == null ? standalone_timer_now() : +time;
    t._restart(function tick(elapsed) {
      elapsed += total;
      t._restart(tick, total += delay, time);
      callback(elapsed);
    }, delay, time);
  }
  t.restart(callback, delay, time);
  return t;
}

;// ../../node_modules/vega-view/build/vega-view.module.js









// initialize aria role and label attributes
function standalone_initializeAria(view) {
  const el = view.container();
  if (el) {
    el.setAttribute('role', 'graphics-document');
    el.setAttribute('aria-roleDescription', 'visualization');
    standalone_ariaLabel(el, view.description());
  }
}

// update aria-label if we have a DOM container element
function standalone_ariaLabel(el, desc) {
  if (el) desc == null ? el.removeAttribute('aria-label') : el.setAttribute('aria-label', desc);
}

function standalone_vega_view_module_background (view) {
  // respond to background signal
  view.add(null, _ => {
    view._background = _.bg;
    view._resize = 1;
    return _.bg;
  }, {
    bg: view._signals.background
  });
}

const standalone_Default = 'default';
function standalone_cursor (view) {
  // get cursor signal, add to dataflow if needed
  const cursor = view._signals.cursor || (view._signals.cursor = view.add({
    user: standalone_Default,
    item: null
  }));

  // evaluate cursor on each pointermove event
  view.on(view.events('view', 'pointermove'), cursor, (_, event) => {
    const value = cursor.value,
      user = value ? standalone_vega_util_module_isString(value) ? value : value.user : standalone_Default,
      item = event.item && event.item.cursor || null;
    return value && user === value.user && item == value.item ? value : {
      user: user,
      item: item
    };
  });

  // when cursor signal updates, set visible cursor
  view.add(null, function (_) {
    let user = _.cursor,
      item = this.value;
    if (!standalone_vega_util_module_isString(user)) {
      item = user.item;
      user = user.user;
    }
    standalone_setCursor(view, user && user !== standalone_Default ? user : item || user);
    return item;
  }, {
    cursor: cursor
  });
}
function standalone_setCursor(view, cursor) {
  const el = view.globalCursor() ? typeof document !== 'undefined' && document.body : view.container();
  if (el) {
    return cursor == null ? el.style.removeProperty('cursor') : el.style.cursor = cursor;
  }
}

function standalone_dataref(view, name) {
  var data = view._runtime.data;
  if (!standalone_vega_util_module_has(data, name)) {
    standalone_vega_util_module_error('Unrecognized data set: ' + name);
  }
  return data[name];
}
function standalone_vega_view_module_data(name, values) {
  return arguments.length < 2 ? standalone_dataref(this, name).values.value : standalone_change.call(this, name, standalone_changeset().remove(standalone_truthy).insert(values));
}
function standalone_change(name, changes) {
  if (!standalone_isChangeSet(changes)) {
    standalone_vega_util_module_error('Second argument to changes must be a changeset.');
  }
  const dataset = standalone_dataref(this, name);
  dataset.modified = true;
  return this.pulse(dataset.input, changes);
}
function standalone_vega_view_module_insert(name, _) {
  return standalone_change.call(this, name, standalone_changeset().insert(_));
}
function standalone_vega_view_module_remove(name, _) {
  return standalone_change.call(this, name, standalone_changeset().remove(_));
}

function standalone_width(view) {
  var padding = view.padding();
  return Math.max(0, view._viewWidth + padding.left + padding.right);
}
function standalone_height(view) {
  var padding = view.padding();
  return Math.max(0, view._viewHeight + padding.top + padding.bottom);
}
function standalone_vega_view_module_offset(view) {
  var padding = view.padding(),
    origin = view._origin;
  return [padding.left + origin[0], padding.top + origin[1]];
}
function standalone_resizeRenderer(view) {
  var origin = standalone_vega_view_module_offset(view),
    w = standalone_width(view),
    h = standalone_height(view);
  view._renderer.background(view.background());
  view._renderer.resize(w, h, origin);
  view._handler.origin(origin);
  view._resizeListeners.forEach(handler => {
    try {
      handler(w, h);
    } catch (error) {
      view.error(error);
    }
  });
}

/**
 * Extend an event with additional view-specific methods.
 * Adds a new property ('vega') to an event that provides a number
 * of methods for querying information about the current interaction.
 * The vega object provides the following methods:
 *   view - Returns the backing View instance.
 *   item - Returns the currently active scenegraph item (if any).
 *   group - Returns the currently active scenegraph group (if any).
 *     This method accepts a single string-typed argument indicating the name
 *     of the desired parent group. The scenegraph will be traversed from
 *     the item up towards the root to search for a matching group. If no
 *     argument is provided the enclosing group for the active item is
 *     returned, unless the item it itself a group, in which case it is
 *     returned directly.
 *   xy - Returns a two-element array containing the x and y coordinates for
 *     mouse or touch events. For touch events, this is based on the first
 *     elements in the changedTouches array. This method accepts a single
 *     argument: either an item instance or mark name that should serve as
 *     the reference coordinate system. If no argument is provided the
 *     top-level view coordinate system is assumed.
 *   x - Returns the current x-coordinate, accepts the same arguments as xy.
 *   y - Returns the current y-coordinate, accepts the same arguments as xy.
 * @param {Event} event - The input event to extend.
 * @param {Item} item - The currently active scenegraph item (if any).
 * @return {Event} - The extended input event.
 */
function standalone_eventExtend (view, event, item) {
  var r = view._renderer,
    el = r && r.canvas(),
    p,
    e,
    translate;
  if (el) {
    translate = standalone_vega_view_module_offset(view);
    e = event.changedTouches ? event.changedTouches[0] : event;
    p = standalone_vega_scenegraph_module_point(e, el);
    p[0] -= translate[0];
    p[1] -= translate[1];
  }
  event.dataflow = view;
  event.item = item;
  event.vega = standalone_extension(view, item, p);
  return event;
}
function standalone_extension(view, item, point) {
  const itemGroup = item ? item.mark.marktype === 'group' ? item : item.mark.group : null;
  function group(name) {
    var g = itemGroup,
      i;
    if (name) for (i = item; i; i = i.mark.group) {
      if (i.mark.name === name) {
        g = i;
        break;
      }
    }
    return g && g.mark && g.mark.interactive ? g : {};
  }
  function xy(item) {
    if (!item) return point;
    if (standalone_vega_util_module_isString(item)) item = group(item);
    const p = point.slice();
    while (item) {
      p[0] -= item.x || 0;
      p[1] -= item.y || 0;
      item = item.mark && item.mark.group;
    }
    return p;
  }
  return {
    view: standalone_vega_util_module_constant(view),
    item: standalone_vega_util_module_constant(item || {}),
    group: group,
    xy: xy,
    x: item => xy(item)[0],
    y: item => xy(item)[1]
  };
}

const standalone_VIEW = 'view',
  standalone_TIMER = 'timer',
  standalone_WINDOW = 'window',
  standalone_NO_TRAP = {
    trap: false
  };

/**
 * Initialize event handling configuration.
 * @param {object} config - The configuration settings.
 * @return {object}
 */
function standalone_initializeEventConfig(config) {
  const events = standalone_extend({
    defaults: {}
  }, config);
  const unpack = (obj, keys) => {
    keys.forEach(k => {
      if (standalone_vega_util_module_isArray(obj[k])) obj[k] = standalone_toSet(obj[k]);
    });
  };
  unpack(events.defaults, ['prevent', 'allow']);
  unpack(events, ['view', 'window', 'selector']);
  return events;
}
function standalone_trackEventListener(view, sources, type, handler) {
  view._eventListeners.push({
    type: type,
    sources: standalone_array(sources),
    handler: handler
  });
}
function standalone_prevent(view, type) {
  var def = view._eventConfig.defaults,
    prevent = def.prevent,
    allow = def.allow;
  return prevent === false || allow === true ? false : prevent === true || allow === false ? true : prevent ? prevent[type] : allow ? !allow[type] : view.preventDefault();
}
function standalone_permit(view, key, type) {
  const rule = view._eventConfig && view._eventConfig[key];
  if (rule === false || standalone_vega_util_module_isObject(rule) && !rule[type]) {
    view.warn(`Blocked ${key} ${type} event listener.`);
    return false;
  }
  return true;
}

/**
 * Create a new event stream from an event source.
 * @param {object} source - The event source to monitor.
 * @param {string} type - The event type.
 * @param {function(object): boolean} [filter] - Event filter function.
 * @return {EventStream}
 */
function standalone_vega_view_module_events(source, type, filter) {
  var view = this,
    s = new standalone_EventStream(filter),
    send = function (e, item) {
      view.runAsync(null, () => {
        if (source === standalone_VIEW && standalone_prevent(view, type)) {
          e.preventDefault();
        }
        s.receive(standalone_eventExtend(view, e, item));
      });
    },
    sources;
  if (source === standalone_TIMER) {
    if (standalone_permit(view, 'timer', type)) {
      view.timer(send, type);
    }
  } else if (source === standalone_VIEW) {
    if (standalone_permit(view, 'view', type)) {
      // send traps errors, so use {trap: false} option
      view.addEventListener(type, send, standalone_NO_TRAP);
    }
  } else {
    if (source === standalone_WINDOW) {
      if (standalone_permit(view, 'window', type) && typeof window !== 'undefined') {
        sources = [window];
      }
    } else if (typeof document !== 'undefined') {
      if (standalone_permit(view, 'selector', type)) {
        sources = Array.from(document.querySelectorAll(source));
      }
    }
    if (!sources) {
      view.warn('Can not resolve event source: ' + source);
    } else {
      for (var i = 0, n = sources.length; i < n; ++i) {
        sources[i].addEventListener(type, send);
      }
      standalone_trackEventListener(view, sources, type, send);
    }
  }
  return s;
}

function standalone_itemFilter(event) {
  return event.item;
}
function standalone_markTarget(event) {
  // grab upstream collector feeding the mark operator
  return event.item.mark.source;
}
function standalone_invoke(name) {
  return function (_, event) {
    return event.vega.view().changeset().encode(event.item, name);
  };
}
function standalone_vega_view_module_hover (hoverSet, leaveSet) {
  hoverSet = [hoverSet || 'hover'];
  leaveSet = [leaveSet || 'update', hoverSet[0]];

  // invoke hover set upon pointerover
  this.on(this.events('view', 'pointerover', standalone_itemFilter), standalone_markTarget, standalone_invoke(hoverSet));

  // invoke leave set upon pointerout
  this.on(this.events('view', 'pointerout', standalone_itemFilter), standalone_markTarget, standalone_invoke(leaveSet));
  return this;
}

/**
 * Finalize a View instance that is being removed.
 * Cancel any running timers.
 * Remove all external event listeners.
 * Remove any currently displayed tooltip.
 */
function standalone_finalize () {
  var tooltip = this._tooltip,
    timers = this._timers,
    handlers = this._handler.handlers(),
    listeners = this._eventListeners,
    n,
    m,
    e,
    h,
    t;
  n = timers.length;
  while (--n >= 0) {
    timers[n].stop();
  }
  n = listeners.length;
  while (--n >= 0) {
    e = listeners[n];
    m = e.sources.length;
    while (--m >= 0) {
      e.sources[m].removeEventListener(e.type, e.handler);
    }
  }
  if (tooltip) {
    tooltip.call(this, this._handler, null, null, null);
  }

  // turn off all registered handlers
  n = handlers.length;
  while (--n >= 0) {
    t = handlers[n].type;
    h = handlers[n].handler;
    this._handler.off(t, h);
  }
  return this;
}

function standalone_vega_view_module_element (tag, attr, text) {
  const el = document.createElement(tag);
  for (const key in attr) el.setAttribute(key, attr[key]);
  if (text != null) el.textContent = text;
  return el;
}

const standalone_BindClass = 'vega-bind',
  standalone_NameClass = 'vega-bind-name',
  standalone_RadioClass = 'vega-bind-radio';

/**
 * Bind a signal to an external HTML input element. The resulting two-way
 * binding will propagate input changes to signals, and propagate signal
 * changes to the input element state. If this view instance has no parent
 * element, we assume the view is headless and no bindings are created.
 * @param {Element|string} el - The parent DOM element to which the input
 *   element should be appended as a child. If string-valued, this argument
 *   will be treated as a CSS selector. If null or undefined, the parent
 *   element of this view will be used as the element.
 * @param {object} param - The binding parameters which specify the signal
 *   to bind to, the input element type, and type-specific configuration.
 * @return {View} - This view instance.
 */
function standalone_vega_view_module_bind (view, el, binding) {
  if (!el) return;
  const param = binding.param;
  let bind = binding.state;
  if (!bind) {
    bind = binding.state = {
      elements: null,
      active: false,
      set: null,
      update: value => {
        if (value != view.signal(param.signal)) {
          view.runAsync(null, () => {
            bind.source = true;
            view.signal(param.signal, value);
          });
        }
      }
    };
    if (param.debounce) {
      bind.update = standalone_debounce(param.debounce, bind.update);
    }
  }
  const create = param.input == null && param.element ? standalone_target : standalone_generate;
  create(bind, el, param, view);
  if (!bind.active) {
    view.on(view._signals[param.signal], null, () => {
      bind.source ? bind.source = false : bind.set(view.signal(param.signal));
    });
    bind.active = true;
  }
  return bind;
}

/**
 * Bind the signal to an external EventTarget.
 */
function standalone_target(bind, node, param, view) {
  const type = param.event || 'input';
  const handler = () => bind.update(node.value);

  // initialize signal value to external input value
  view.signal(param.signal, node.value);

  // listen for changes on the element
  node.addEventListener(type, handler);

  // register with view, so we can remove it upon finalization
  standalone_trackEventListener(view, node, type, handler);

  // propagate change to element
  bind.set = value => {
    node.value = value;
    node.dispatchEvent(standalone_vega_view_module_event(type));
  };
}
function standalone_vega_view_module_event(type) {
  return typeof Event !== 'undefined' ? new Event(type) : {
    type
  };
}

/**
 * Generate an HTML input form element and bind it to a signal.
 */
function standalone_generate(bind, el, param, view) {
  const value = view.signal(param.signal);
  const div = standalone_vega_view_module_element('div', {
    'class': standalone_BindClass
  });
  const wrapper = param.input === 'radio' ? div : div.appendChild(standalone_vega_view_module_element('label'));
  wrapper.appendChild(standalone_vega_view_module_element('span', {
    'class': standalone_NameClass
  }, param.name || param.signal));
  el.appendChild(div);
  let input = standalone_vega_view_module_form;
  switch (param.input) {
    case 'checkbox':
      input = standalone_vega_view_module_checkbox;
      break;
    case 'select':
      input = standalone_vega_view_module_select;
      break;
    case 'radio':
      input = standalone_vega_view_module_radio;
      break;
    case 'range':
      input = standalone_vega_view_module_range;
      break;
  }
  input(bind, wrapper, param, value);
}

/**
 * Generates an arbitrary input form element.
 * The input type is controlled via user-provided parameters.
 */
function standalone_vega_view_module_form(bind, el, param, value) {
  const node = standalone_vega_view_module_element('input');
  for (const key in param) {
    if (key !== 'signal' && key !== 'element') {
      node.setAttribute(key === 'input' ? 'type' : key, param[key]);
    }
  }
  node.setAttribute('name', param.signal);
  node.value = value;
  el.appendChild(node);
  node.addEventListener('input', () => bind.update(node.value));
  bind.elements = [node];
  bind.set = value => node.value = value;
}

/**
 * Generates a checkbox input element.
 */
function standalone_vega_view_module_checkbox(bind, el, param, value) {
  const attr = {
    type: 'checkbox',
    name: param.signal
  };
  if (value) attr.checked = true;
  const node = standalone_vega_view_module_element('input', attr);
  el.appendChild(node);
  node.addEventListener('change', () => bind.update(node.checked));
  bind.elements = [node];
  bind.set = value => node.checked = !!value || null;
}

/**
 * Generates a selection list input element.
 */
function standalone_vega_view_module_select(bind, el, param, value) {
  const node = standalone_vega_view_module_element('select', {
      name: param.signal
    }),
    labels = param.labels || [];
  param.options.forEach((option, i) => {
    const attr = {
      value: option
    };
    if (standalone_valuesEqual(option, value)) attr.selected = true;
    node.appendChild(standalone_vega_view_module_element('option', attr, (labels[i] || option) + ''));
  });
  el.appendChild(node);
  node.addEventListener('change', () => {
    bind.update(param.options[node.selectedIndex]);
  });
  bind.elements = [node];
  bind.set = value => {
    for (let i = 0, n = param.options.length; i < n; ++i) {
      if (standalone_valuesEqual(param.options[i], value)) {
        node.selectedIndex = i;
        return;
      }
    }
  };
}

/**
 * Generates a radio button group.
 */
function standalone_vega_view_module_radio(bind, el, param, value) {
  const group = standalone_vega_view_module_element('span', {
      'class': standalone_RadioClass
    }),
    labels = param.labels || [];
  el.appendChild(group);
  bind.elements = param.options.map((option, i) => {
    const attr = {
      type: 'radio',
      name: param.signal,
      value: option
    };
    if (standalone_valuesEqual(option, value)) attr.checked = true;
    const input = standalone_vega_view_module_element('input', attr);
    input.addEventListener('change', () => bind.update(option));
    const label = standalone_vega_view_module_element('label', {}, (labels[i] || option) + '');
    label.prepend(input);
    group.appendChild(label);
    return input;
  });
  bind.set = value => {
    const nodes = bind.elements,
      n = nodes.length;
    for (let i = 0; i < n; ++i) {
      if (standalone_valuesEqual(nodes[i].value, value)) nodes[i].checked = true;
    }
  };
}

/**
 * Generates a slider input element.
 */
function standalone_vega_view_module_range(bind, el, param, value) {
  value = value !== undefined ? value : (+param.max + +param.min) / 2;
  const max = param.max != null ? param.max : Math.max(100, +value) || 100,
    min = param.min || Math.min(0, max, +value) || 0,
    step = param.step || standalone_tickStep(min, max, 100);
  const node = standalone_vega_view_module_element('input', {
    type: 'range',
    name: param.signal,
    min: min,
    max: max,
    step: step
  });
  node.value = value;
  const span = standalone_vega_view_module_element('span', {}, +value);
  el.appendChild(node);
  el.appendChild(span);
  const update = () => {
    span.textContent = node.value;
    bind.update(+node.value);
  };

  // subscribe to both input and change
  node.addEventListener('input', update);
  node.addEventListener('change', update);
  bind.elements = [node];
  bind.set = value => {
    node.value = value;
    span.textContent = value;
  };
}
function standalone_valuesEqual(a, b) {
  return a === b || a + '' === b + '';
}

function standalone_initializeRenderer (view, r, el, constructor, scaleFactor, opt) {
  r = r || new constructor(view.loader());
  return r.initialize(el, standalone_width(view), standalone_height(view), standalone_vega_view_module_offset(view), scaleFactor, opt).background(view.background());
}

function standalone_trap (view, fn) {
  return !fn ? null : function () {
    try {
      fn.apply(this, arguments);
    } catch (error) {
      view.error(error);
    }
  };
}

function standalone_initializeHandler (view, prevHandler, el, constructor) {
  // instantiate scenegraph handler
  const handler = new constructor(view.loader(), standalone_trap(view, view.tooltip())).scene(view.scenegraph().root).initialize(el, standalone_vega_view_module_offset(view), view);

  // transfer event handlers
  if (prevHandler) {
    prevHandler.handlers().forEach(h => {
      handler.on(h.type, h.handler);
    });
  }
  return handler;
}

function standalone_vega_view_module_initialize (el, elBind) {
  const view = this,
    type = view._renderType,
    config = view._eventConfig.bind,
    module = standalone_renderModule(type);

  // containing dom element
  el = view._el = el ? standalone_vega_view_module_lookup(view, el, true) : null;

  // initialize aria attributes
  standalone_initializeAria(view);

  // select appropriate renderer & handler
  if (!module) view.error('Unrecognized renderer type: ' + type);
  const Handler = module.handler || standalone_CanvasHandler,
    Renderer = el ? module.renderer : module.headless;

  // initialize renderer and input handler
  view._renderer = !Renderer ? null : standalone_initializeRenderer(view, view._renderer, el, Renderer);
  view._handler = standalone_initializeHandler(view, view._handler, el, Handler);
  view._redraw = true;

  // initialize signal bindings
  if (el && config !== 'none') {
    elBind = elBind ? view._elBind = standalone_vega_view_module_lookup(view, elBind, true) : el.appendChild(standalone_vega_view_module_element('form', {
      'class': 'vega-bindings'
    }));
    view._bind.forEach(_ => {
      if (_.param.element && config !== 'container') {
        _.element = standalone_vega_view_module_lookup(view, _.param.element, !!_.param.input);
      }
    });
    view._bind.forEach(_ => {
      standalone_vega_view_module_bind(view, _.element || elBind, _);
    });
  }
  return view;
}
function standalone_vega_view_module_lookup(view, el, clear) {
  if (typeof el === 'string') {
    if (typeof document !== 'undefined') {
      el = document.querySelector(el);
      if (!el) {
        view.error('Signal bind element not found: ' + el);
        return null;
      }
    } else {
      view.error('DOM document instance not found.');
      return null;
    }
  }
  if (el && clear) {
    try {
      el.textContent = '';
    } catch (e) {
      el = null;
      view.error(e);
    }
  }
  return el;
}

const standalone_vega_view_module_number = _ => +_ || 0;
const standalone_paddingObject = _ => ({
  top: _,
  bottom: _,
  left: _,
  right: _
});
function standalone_padding (_) {
  return standalone_vega_util_module_isObject(_) ? {
    top: standalone_vega_view_module_number(_.top),
    bottom: standalone_vega_view_module_number(_.bottom),
    left: standalone_vega_view_module_number(_.left),
    right: standalone_vega_view_module_number(_.right)
  } : standalone_paddingObject(standalone_vega_view_module_number(_));
}

/**
 * Render the current scene in a headless fashion.
 * This method is asynchronous, returning a Promise instance.
 * @return {Promise} - A Promise that resolves to a renderer.
 */
async function standalone_renderHeadless (view, type, scaleFactor, opt) {
  const module = standalone_renderModule(type),
    ctr = module && module.headless;
  if (!ctr) standalone_vega_util_module_error('Unrecognized renderer type: ' + type);
  await view.runAsync();
  return standalone_initializeRenderer(view, null, null, ctr, scaleFactor, opt).renderAsync(view._scenegraph.root);
}

/**
 * Produce an image URL for the visualization. Depending on the type
 * parameter, the generated URL contains data for either a PNG or SVG image.
 * The URL can be used (for example) to download images of the visualization.
 * This method is asynchronous, returning a Promise instance.
 * @param {string} type - The image type. One of 'svg', 'png' or 'canvas'.
 *   The 'canvas' and 'png' types are synonyms for a PNG image.
 * @return {Promise} - A promise that resolves to an image URL.
 */
async function standalone_renderToImageURL (type, scaleFactor) {
  if (type !== standalone_RenderType.Canvas && type !== standalone_RenderType.SVG && type !== standalone_RenderType.PNG) {
    standalone_vega_util_module_error('Unrecognized image type: ' + type);
  }
  const r = await standalone_renderHeadless(this, type, scaleFactor);
  return type === standalone_RenderType.SVG ? standalone_toBlobURL(r.svg(), 'image/svg+xml') : r.canvas().toDataURL('image/png');
}
function standalone_toBlobURL(data, mime) {
  const blob = new Blob([data], {
    type: mime
  });
  return window.URL.createObjectURL(blob);
}

/**
 * Produce a Canvas instance containing a rendered visualization.
 * This method is asynchronous, returning a Promise instance.
 * @return {Promise} - A promise that resolves to a Canvas instance.
 */
async function standalone_renderToCanvas (scaleFactor, opt) {
  const r = await standalone_renderHeadless(this, standalone_RenderType.Canvas, scaleFactor, opt);
  return r.canvas();
}

/**
 * Produce a rendered SVG string of the visualization.
 * This method is asynchronous, returning a Promise instance.
 * @return {Promise} - A promise that resolves to an SVG string.
 */
async function standalone_renderToSVG (scaleFactor) {
  const r = await standalone_renderHeadless(this, standalone_RenderType.SVG, scaleFactor);
  return r.svg();
}

function standalone_runtime (view, spec, expr) {
  return standalone_vega_runtime_module_context(view, standalone_transforms, standalone_functionContext, expr).parse(spec);
}

function standalone_vega_view_module_scale(name) {
  var scales = this._runtime.scales;
  if (!standalone_vega_util_module_has(scales, name)) {
    standalone_vega_util_module_error('Unrecognized scale or projection: ' + name);
  }
  return scales[name].value;
}

var standalone_Width = 'width',
  standalone_Height = 'height',
  standalone_vega_view_module_Padding = 'padding',
  standalone_vega_view_module_Skip = {
    skip: true
  };
function standalone_viewWidth(view, width) {
  var a = view.autosize(),
    p = view.padding();
  return width - (a && a.contains === standalone_vega_view_module_Padding ? p.left + p.right : 0);
}
function standalone_viewHeight(view, height) {
  var a = view.autosize(),
    p = view.padding();
  return height - (a && a.contains === standalone_vega_view_module_Padding ? p.top + p.bottom : 0);
}
function standalone_initializeResize(view) {
  var s = view._signals,
    w = s[standalone_Width],
    h = s[standalone_Height],
    p = s[standalone_vega_view_module_Padding];
  function resetSize() {
    view._autosize = view._resize = 1;
  }

  // respond to width signal
  view._resizeWidth = view.add(null, _ => {
    view._width = _.size;
    view._viewWidth = standalone_viewWidth(view, _.size);
    resetSize();
  }, {
    size: w
  });

  // respond to height signal
  view._resizeHeight = view.add(null, _ => {
    view._height = _.size;
    view._viewHeight = standalone_viewHeight(view, _.size);
    resetSize();
  }, {
    size: h
  });

  // respond to padding signal
  const resizePadding = view.add(null, resetSize, {
    pad: p
  });

  // set rank to run immediately after source signal
  view._resizeWidth.rank = w.rank + 1;
  view._resizeHeight.rank = h.rank + 1;
  resizePadding.rank = p.rank + 1;
}
function standalone_resizeView(viewWidth, viewHeight, width, height, origin, auto) {
  this.runAfter(view => {
    let rerun = 0;

    // reset autosize flag
    view._autosize = 0;

    // width value changed: update signal, skip resize op
    if (view.width() !== width) {
      rerun = 1;
      view.signal(standalone_Width, width, standalone_vega_view_module_Skip); // set width, skip update calc
      view._resizeWidth.skip(true); // skip width resize handler
    }

    // height value changed: update signal, skip resize op
    if (view.height() !== height) {
      rerun = 1;
      view.signal(standalone_Height, height, standalone_vega_view_module_Skip); // set height, skip update calc
      view._resizeHeight.skip(true); // skip height resize handler
    }

    // view width changed: update view property, set resize flag
    if (view._viewWidth !== viewWidth) {
      view._resize = 1;
      view._viewWidth = viewWidth;
    }

    // view height changed: update view property, set resize flag
    if (view._viewHeight !== viewHeight) {
      view._resize = 1;
      view._viewHeight = viewHeight;
    }

    // origin changed: update view property, set resize flag
    if (view._origin[0] !== origin[0] || view._origin[1] !== origin[1]) {
      view._resize = 1;
      view._origin = origin;
    }

    // run dataflow on width/height signal change
    if (rerun) view.run('enter');
    if (auto) view.runAfter(v => v.resize());
  }, false, 1);
}

/**
 * Get the current view state, consisting of signal values and/or data sets.
 * @param {object} [options] - Options flags indicating which state to export.
 *   If unspecified, all signals and data sets will be exported.
 * @param {function(string, Operator):boolean} [options.signals] - Optional
 *   predicate function for testing if a signal should be included in the
 *   exported state. If unspecified, all signals will be included, except for
 *   those named 'parent' or those which refer to a Transform value.
 * @param {function(string, object):boolean} [options.data] - Optional
 *   predicate function for testing if a data set's input should be included
 *   in the exported state. If unspecified, all data sets that have been
 *   explicitly modified will be included.
 * @param {boolean} [options.recurse=true] - Flag indicating if the exported
 *   state should recursively include state from group mark sub-contexts.
 * @return {object} - An object containing the exported state values.
 */
function standalone_vega_view_module_getState(options) {
  return this._runtime.getState(options || {
    data: standalone_dataTest,
    signals: standalone_signalTest,
    recurse: true
  });
}
function standalone_dataTest(name, data) {
  return data.modified && standalone_vega_util_module_isArray(data.input.value) && !name.startsWith('_:vega:_');
}
function standalone_signalTest(name, op) {
  return !(name === 'parent' || op instanceof standalone_transforms.proxy);
}

/**
 * Sets the current view state and updates the view by invoking run.
 * @param {object} state - A state object containing signal and/or
 *   data set values, following the format used by the getState method.
 * @return {View} - This view instance.
 */
function standalone_vega_view_module_setState(state) {
  this.runAsync(null, v => {
    v._trigger = false;
    v._runtime.setState(state);
  }, v => {
    v._trigger = true;
  });
  return this;
}

function standalone_vega_view_module_timer (callback, delay) {
  function tick(elapsed) {
    callback({
      timestamp: Date.now(),
      elapsed: elapsed
    });
  }
  this._timers.push(standalone_src_interval(tick, delay));
}

function standalone_vega_view_module_defaultTooltip (handler, event, item, value) {
  const el = handler.element();
  if (el) el.setAttribute('title', standalone_formatTooltip(value));
}
function standalone_formatTooltip(value) {
  return value == null ? '' : standalone_vega_util_module_isArray(value) ? standalone_formatArray(value) : standalone_vega_util_module_isObject(value) && !standalone_isDate(value) ? standalone_formatObject(value) : value + '';
}
function standalone_formatObject(obj) {
  return Object.keys(obj).map(key => {
    const v = obj[key];
    return key + ': ' + (standalone_vega_util_module_isArray(v) ? standalone_formatArray(v) : standalone_vega_view_module_formatValue(v));
  }).join('\n');
}
function standalone_formatArray(value) {
  return '[' + value.map(standalone_vega_view_module_formatValue).join(', ') + ']';
}
function standalone_vega_view_module_formatValue(value) {
  return standalone_vega_util_module_isArray(value) ? '[\u2026]' : standalone_vega_util_module_isObject(value) && !standalone_isDate(value) ? '{\u2026}' : value;
}

function standalone_watchPixelRatio () {
  // based on https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#monitoring_screen_resolution_or_zoom_level_changes
  if (this.renderer() === 'canvas' && this._renderer._canvas) {
    let remove = null;
    const updatePixelRatio = () => {
      if (remove != null) {
        remove();
      }
      const media = matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
      media.addEventListener('change', updatePixelRatio);
      remove = () => {
        media.removeEventListener('change', updatePixelRatio);
      };
      this._renderer._canvas.getContext('2d').pixelRatio = window.devicePixelRatio || 1;
      this._redraw = true;
      this._resize = 1;
      this.resize().runAsync();
    };
    updatePixelRatio();
  }
}

/**
 * Create a new View instance from a Vega dataflow runtime specification.
 * The generated View will not immediately be ready for display. Callers
 * should also invoke the initialize method (e.g., to set the parent
 * DOM element in browser-based deployment) and then invoke the run
 * method to evaluate the dataflow graph. Rendering will automatically
 * be performed upon dataflow runs.
 * @constructor
 * @param {object} spec - The Vega dataflow runtime specification.
 */
function standalone_View(spec, options) {
  const view = this;
  options = options || {};
  standalone_Dataflow.call(view);
  if (options.loader) view.loader(options.loader);
  if (options.logger) view.logger(options.logger);
  if (options.logLevel != null) view.logLevel(options.logLevel);
  if (options.locale || spec.locale) {
    const loc = standalone_extend({}, spec.locale, options.locale);
    view.locale(standalone_vega_format_module_locale(loc.number, loc.time));
  }
  view._el = null;
  view._elBind = null;
  view._renderType = options.renderer || standalone_RenderType.Canvas;
  view._scenegraph = new standalone_Scenegraph();
  const root = view._scenegraph.root;

  // initialize renderer, handler and event management
  view._renderer = null;
  view._tooltip = options.tooltip || standalone_vega_view_module_defaultTooltip, view._redraw = true;
  view._handler = new standalone_CanvasHandler().scene(root);
  view._globalCursor = false;
  view._preventDefault = false;
  view._timers = [];
  view._eventListeners = [];
  view._resizeListeners = [];

  // initialize event configuration
  view._eventConfig = standalone_initializeEventConfig(spec.eventConfig);
  view.globalCursor(view._eventConfig.globalCursor);

  // initialize dataflow graph
  const ctx = standalone_runtime(view, spec, options.expr);
  view._runtime = ctx;
  view._signals = ctx.signals;
  view._bind = (spec.bindings || []).map(_ => ({
    state: null,
    param: standalone_extend({}, _)
  }));

  // initialize scenegraph
  if (ctx.root) ctx.root.set(root);
  root.source = ctx.data.root.input;
  view.pulse(ctx.data.root.input, view.changeset().insert(root.items));

  // initialize view size
  view._width = view.width();
  view._height = view.height();
  view._viewWidth = standalone_viewWidth(view, view._width);
  view._viewHeight = standalone_viewHeight(view, view._height);
  view._origin = [0, 0];
  view._resize = 0;
  view._autosize = 1;
  standalone_initializeResize(view);

  // initialize background color
  standalone_vega_view_module_background(view);

  // initialize cursor
  standalone_cursor(view);

  // initialize view description
  view.description(spec.description);

  // initialize hover proessing, if requested
  if (options.hover) view.hover();

  // initialize DOM container(s) and renderer
  if (options.container) view.initialize(options.container, options.bind);
  if (options.watchPixelRatio) view._watchPixelRatio();
}
function standalone_lookupSignal(view, name) {
  return standalone_vega_util_module_has(view._signals, name) ? view._signals[name] : standalone_vega_util_module_error('Unrecognized signal name: ' + standalone_$(name));
}
function standalone_findOperatorHandler(op, handler) {
  const h = (op._targets || []).filter(op => op._update && op._update.handler === handler);
  return h.length ? h[0] : null;
}
function standalone_addOperatorListener(view, name, op, handler) {
  let h = standalone_findOperatorHandler(op, handler);
  if (!h) {
    h = standalone_trap(view, () => handler(name, op.value));
    h.handler = handler;
    view.on(op, null, h);
  }
  return view;
}
function standalone_removeOperatorListener(view, op, handler) {
  const h = standalone_findOperatorHandler(op, handler);
  if (h) op._targets.remove(h);
  return view;
}
standalone_inherits(standalone_View, standalone_Dataflow, {
  // -- DATAFLOW / RENDERING ----

  async evaluate(encode, prerun, postrun) {
    // evaluate dataflow and prerun
    await standalone_Dataflow.prototype.evaluate.call(this, encode, prerun);

    // render as needed
    if (this._redraw || this._resize) {
      try {
        if (this._renderer) {
          if (this._resize) {
            this._resize = 0;
            standalone_resizeRenderer(this);
          }
          await this._renderer.renderAsync(this._scenegraph.root);
        }
        this._redraw = false;
      } catch (e) {
        this.error(e);
      }
    }

    // evaluate postrun
    if (postrun) standalone_asyncCallback(this, postrun);
    return this;
  },
  dirty(item) {
    this._redraw = true;
    this._renderer && this._renderer.dirty(item);
  },
  // -- GET / SET ----

  description(text) {
    if (arguments.length) {
      const desc = text != null ? text + '' : null;
      if (desc !== this._desc) standalone_ariaLabel(this._el, this._desc = desc);
      return this;
    }
    return this._desc;
  },
  container() {
    return this._el;
  },
  scenegraph() {
    return this._scenegraph;
  },
  origin() {
    return this._origin.slice();
  },
  signal(name, value, options) {
    const op = standalone_lookupSignal(this, name);
    return arguments.length === 1 ? op.value : this.update(op, value, options);
  },
  width(_) {
    return arguments.length ? this.signal('width', _) : this.signal('width');
  },
  height(_) {
    return arguments.length ? this.signal('height', _) : this.signal('height');
  },
  padding(_) {
    return arguments.length ? this.signal('padding', standalone_padding(_)) : standalone_padding(this.signal('padding'));
  },
  autosize(_) {
    return arguments.length ? this.signal('autosize', _) : this.signal('autosize');
  },
  background(_) {
    return arguments.length ? this.signal('background', _) : this.signal('background');
  },
  renderer(type) {
    if (!arguments.length) return this._renderType;
    if (!standalone_renderModule(type)) standalone_vega_util_module_error('Unrecognized renderer type: ' + type);
    if (type !== this._renderType) {
      this._renderType = type;
      this._resetRenderer();
    }
    return this;
  },
  tooltip(handler) {
    if (!arguments.length) return this._tooltip;
    if (handler !== this._tooltip) {
      this._tooltip = handler;
      this._resetRenderer();
    }
    return this;
  },
  loader(loader) {
    if (!arguments.length) return this._loader;
    if (loader !== this._loader) {
      standalone_Dataflow.prototype.loader.call(this, loader);
      this._resetRenderer();
    }
    return this;
  },
  resize() {
    // set flag to perform autosize
    this._autosize = 1;
    // touch autosize signal to ensure top-level ViewLayout runs
    return this.touch(standalone_lookupSignal(this, 'autosize'));
  },
  _resetRenderer() {
    if (this._renderer) {
      this._renderer = null;
      this.initialize(this._el, this._elBind);
    }
  },
  // -- SIZING ----
  _resizeView: standalone_resizeView,
  // -- EVENT HANDLING ----

  addEventListener(type, handler, options) {
    let callback = handler;
    if (!(options && options.trap === false)) {
      // wrap callback in error handler
      callback = standalone_trap(this, handler);
      callback.raw = handler;
    }
    this._handler.on(type, callback);
    return this;
  },
  removeEventListener(type, handler) {
    var handlers = this._handler.handlers(type),
      i = handlers.length,
      h,
      t;

    // search registered handlers, remove if match found
    while (--i >= 0) {
      t = handlers[i].type;
      h = handlers[i].handler;
      if (type === t && (handler === h || handler === h.raw)) {
        this._handler.off(t, h);
        break;
      }
    }
    return this;
  },
  addResizeListener(handler) {
    const l = this._resizeListeners;
    if (!l.includes(handler)) {
      // add handler if it isn't already registered
      // note: error trapping handled elsewhere, so
      // no need to wrap handlers here
      l.push(handler);
    }
    return this;
  },
  removeResizeListener(handler) {
    var l = this._resizeListeners,
      i = l.indexOf(handler);
    if (i >= 0) {
      l.splice(i, 1);
    }
    return this;
  },
  addSignalListener(name, handler) {
    return standalone_addOperatorListener(this, name, standalone_lookupSignal(this, name), handler);
  },
  removeSignalListener(name, handler) {
    return standalone_removeOperatorListener(this, standalone_lookupSignal(this, name), handler);
  },
  addDataListener(name, handler) {
    return standalone_addOperatorListener(this, name, standalone_dataref(this, name).values, handler);
  },
  removeDataListener(name, handler) {
    return standalone_removeOperatorListener(this, standalone_dataref(this, name).values, handler);
  },
  globalCursor(_) {
    if (arguments.length) {
      if (this._globalCursor !== !!_) {
        const prev = standalone_setCursor(this, null); // clear previous cursor
        this._globalCursor = !!_;
        if (prev) standalone_setCursor(this, prev); // swap cursor
      }
      return this;
    } else {
      return this._globalCursor;
    }
  },
  preventDefault(_) {
    if (arguments.length) {
      this._preventDefault = _;
      return this;
    } else {
      return this._preventDefault;
    }
  },
  timer: standalone_vega_view_module_timer,
  events: standalone_vega_view_module_events,
  finalize: standalone_finalize,
  hover: standalone_vega_view_module_hover,
  // -- DATA ----
  data: standalone_vega_view_module_data,
  change: standalone_change,
  insert: standalone_vega_view_module_insert,
  remove: standalone_vega_view_module_remove,
  // -- SCALES --
  scale: standalone_vega_view_module_scale,
  // -- INITIALIZATION ----
  initialize: standalone_vega_view_module_initialize,
  // -- HEADLESS RENDERING ----
  toImageURL: standalone_renderToImageURL,
  toCanvas: standalone_renderToCanvas,
  toSVG: standalone_renderToSVG,
  // -- SAVE / RESTORE STATE ----
  getState: standalone_vega_view_module_getState,
  setState: standalone_vega_view_module_setState,
  // RE-RENDER ON ZOOM
  _watchPixelRatio: standalone_watchPixelRatio
});



;// ../../node_modules/vega-event-selector/build/vega-event-selector.module.js
const standalone_vega_event_selector_module_VIEW = 'view',
  standalone_LBRACK = '[',
  standalone_RBRACK = ']',
  standalone_LBRACE = '{',
  standalone_RBRACE = '}',
  standalone_COLON = ':',
  standalone_COMMA = ',',
  standalone_NAME = '@',
  standalone_GT = '>',
  standalone_vega_event_selector_module_ILLEGAL = /[[\]{}]/,
  standalone_DEFAULT_MARKS = {
    '*': 1,
    arc: 1,
    area: 1,
    group: 1,
    image: 1,
    line: 1,
    path: 1,
    rect: 1,
    rule: 1,
    shape: 1,
    symbol: 1,
    text: 1,
    trail: 1
  };
let standalone_DEFAULT_SOURCE, standalone_MARKS;

/**
 * Parse an event selector string.
 * Returns an array of event stream definitions.
 */
function standalone_eventSelector (selector, source, marks) {
  standalone_DEFAULT_SOURCE = source || standalone_vega_event_selector_module_VIEW;
  standalone_MARKS = marks || standalone_DEFAULT_MARKS;
  return standalone_parseMerge(selector.trim()).map(standalone_parseSelector);
}
function standalone_isMarkType(type) {
  return standalone_MARKS[type];
}
function standalone_vega_event_selector_module_find(s, i, endChar, pushChar, popChar) {
  const n = s.length;
  let count = 0,
    c;
  for (; i < n; ++i) {
    c = s[i];
    if (!count && c === endChar) return i;else if (popChar && popChar.indexOf(c) >= 0) --count;else if (pushChar && pushChar.indexOf(c) >= 0) ++count;
  }
  return i;
}
function standalone_parseMerge(s) {
  const output = [],
    n = s.length;
  let start = 0,
    i = 0;
  while (i < n) {
    i = standalone_vega_event_selector_module_find(s, i, standalone_COMMA, standalone_LBRACK + standalone_LBRACE, standalone_RBRACK + standalone_RBRACE);
    output.push(s.substring(start, i).trim());
    start = ++i;
  }
  if (output.length === 0) {
    throw 'Empty event selector: ' + s;
  }
  return output;
}
function standalone_parseSelector(s) {
  return s[0] === '[' ? standalone_parseBetween(s) : standalone_vega_event_selector_module_parseStream(s);
}
function standalone_parseBetween(s) {
  const n = s.length;
  let i = 1,
    b;
  i = standalone_vega_event_selector_module_find(s, i, standalone_RBRACK, standalone_LBRACK, standalone_RBRACK);
  if (i === n) {
    throw 'Empty between selector: ' + s;
  }
  b = standalone_parseMerge(s.substring(1, i));
  if (b.length !== 2) {
    throw 'Between selector must have two elements: ' + s;
  }
  s = s.slice(i + 1).trim();
  if (s[0] !== standalone_GT) {
    throw 'Expected \'>\' after between selector: ' + s;
  }
  b = b.map(standalone_parseSelector);
  const stream = standalone_parseSelector(s.slice(1).trim());
  if (stream.between) {
    return {
      between: b,
      stream: stream
    };
  } else {
    stream.between = b;
  }
  return stream;
}
function standalone_vega_event_selector_module_parseStream(s) {
  const stream = {
      source: standalone_DEFAULT_SOURCE
    },
    source = [];
  let throttle = [0, 0],
    markname = 0,
    start = 0,
    n = s.length,
    i = 0,
    j,
    filter;

  // extract throttle from end
  if (s[n - 1] === standalone_RBRACE) {
    i = s.lastIndexOf(standalone_LBRACE);
    if (i >= 0) {
      try {
        throttle = standalone_parseThrottle(s.substring(i + 1, n - 1));
      } catch (e) {
        throw 'Invalid throttle specification: ' + s;
      }
      s = s.slice(0, i).trim();
      n = s.length;
    } else throw 'Unmatched right brace: ' + s;
    i = 0;
  }
  if (!n) throw s;

  // set name flag based on first char
  if (s[0] === standalone_NAME) markname = ++i;

  // extract first part of multi-part stream selector
  j = standalone_vega_event_selector_module_find(s, i, standalone_COLON);
  if (j < n) {
    source.push(s.substring(start, j).trim());
    start = i = ++j;
  }

  // extract remaining part of stream selector
  i = standalone_vega_event_selector_module_find(s, i, standalone_LBRACK);
  if (i === n) {
    source.push(s.substring(start, n).trim());
  } else {
    source.push(s.substring(start, i).trim());
    filter = [];
    start = ++i;
    if (start === n) throw 'Unmatched left bracket: ' + s;
  }

  // extract filters
  while (i < n) {
    i = standalone_vega_event_selector_module_find(s, i, standalone_RBRACK);
    if (i === n) throw 'Unmatched left bracket: ' + s;
    filter.push(s.substring(start, i).trim());
    if (i < n - 1 && s[++i] !== standalone_LBRACK) throw 'Expected left bracket: ' + s;
    start = ++i;
  }

  // marshall event stream specification
  if (!(n = source.length) || standalone_vega_event_selector_module_ILLEGAL.test(source[n - 1])) {
    throw 'Invalid event selector: ' + s;
  }
  if (n > 1) {
    stream.type = source[1];
    if (markname) {
      stream.markname = source[0].slice(1);
    } else if (standalone_isMarkType(source[0])) {
      stream.marktype = source[0];
    } else {
      stream.source = source[0];
    }
  } else {
    stream.type = source[0];
  }
  if (stream.type.slice(-1) === '!') {
    stream.consume = true;
    stream.type = stream.type.slice(0, -1);
  }
  if (filter != null) stream.filter = filter;
  if (throttle[0]) stream.throttle = throttle[0];
  if (throttle[1]) stream.debounce = throttle[1];
  return stream;
}
function standalone_parseThrottle(s) {
  const a = s.split(standalone_COMMA);
  if (!s.length || a.length > 2) throw s;
  return a.map(_ => {
    const x = +_;
    if (x !== x) throw s;
    return x;
  });
}



;// ../../node_modules/vega-parser/build/vega-parser.module.js






function standalone_parseAutosize (spec) {
  return standalone_vega_util_module_isObject(spec) ? spec : {
    type: spec || 'pad'
  };
}

const standalone_vega_parser_module_number = _ => +_ || 0;
const standalone_vega_parser_module_paddingObject = _ => ({
  top: _,
  bottom: _,
  left: _,
  right: _
});
function standalone_parsePadding (spec) {
  return !standalone_vega_util_module_isObject(spec) ? standalone_vega_parser_module_paddingObject(standalone_vega_parser_module_number(spec)) : spec.signal ? spec : {
    top: standalone_vega_parser_module_number(spec.top),
    bottom: standalone_vega_parser_module_number(spec.bottom),
    left: standalone_vega_parser_module_number(spec.left),
    right: standalone_vega_parser_module_number(spec.right)
  };
}

const standalone_encoder = _ => standalone_vega_util_module_isObject(_) && !standalone_vega_util_module_isArray(_) ? standalone_extend({}, _) : {
  value: _
};
function standalone_addEncode(object, name, value, set) {
  if (value != null) {
    const isEncoder = standalone_vega_util_module_isObject(value) && !standalone_vega_util_module_isArray(value) || standalone_vega_util_module_isArray(value) && value.length && standalone_vega_util_module_isObject(value[0]);

    // Always assign signal to update, even if the signal is from the enter block
    if (isEncoder) {
      object.update[name] = value;
    } else {
      object[set || 'enter'][name] = {
        value: value
      };
    }
    return 1;
  } else {
    return 0;
  }
}
function standalone_addEncoders(object, enter, update) {
  for (const name in enter) {
    standalone_addEncode(object, name, enter[name]);
  }
  for (const name in update) {
    standalone_addEncode(object, name, update[name], 'update');
  }
}
function standalone_extendEncode(encode, extra, skip) {
  for (const name in extra) {
    if (skip && standalone_vega_util_module_has(skip, name)) continue;
    encode[name] = standalone_extend(encode[name] || {}, extra[name]);
  }
  return encode;
}
function standalone_vega_parser_module_has(key, encode) {
  return encode && (encode.enter && encode.enter[key] || encode.update && encode.update[key]);
}

const standalone_MarkRole = 'mark';
const standalone_vega_parser_module_FrameRole = 'frame';
const standalone_vega_parser_module_ScopeRole = 'scope';
const standalone_vega_parser_module_AxisRole = 'axis';
const standalone_AxisDomainRole = 'axis-domain';
const standalone_AxisGridRole = 'axis-grid';
const standalone_AxisLabelRole = 'axis-label';
const standalone_AxisTickRole = 'axis-tick';
const standalone_AxisTitleRole = 'axis-title';
const standalone_vega_parser_module_LegendRole = 'legend';
const standalone_LegendBandRole = 'legend-band';
const standalone_LegendEntryRole = 'legend-entry';
const standalone_LegendGradientRole = 'legend-gradient';
const standalone_LegendLabelRole = 'legend-label';
const standalone_LegendSymbolRole = 'legend-symbol';
const standalone_LegendTitleRole = 'legend-title';
const standalone_vega_parser_module_TitleRole = 'title';
const standalone_TitleTextRole = 'title-text';
const standalone_TitleSubtitleRole = 'title-subtitle';

function standalone_applyDefaults (encode, type, role, style, config) {
  const defaults = {},
    enter = {};
  let update, key, skip, props;

  // if text mark, apply global lineBreak settings (#2370)
  key = 'lineBreak';
  if (type === 'text' && config[key] != null && !standalone_vega_parser_module_has(key, encode)) {
    standalone_applyDefault(defaults, key, config[key]);
  }

  // ignore legend and axis roles
  if (role == 'legend' || String(role).startsWith('axis')) {
    role = null;
  }

  // resolve mark config
  props = role === standalone_vega_parser_module_FrameRole ? config.group : role === standalone_MarkRole ? standalone_extend({}, config.mark, config[type]) : null;
  for (key in props) {
    // do not apply defaults if relevant fields are defined
    skip = standalone_vega_parser_module_has(key, encode) || (key === 'fill' || key === 'stroke') && (standalone_vega_parser_module_has('fill', encode) || standalone_vega_parser_module_has('stroke', encode));
    if (!skip) standalone_applyDefault(defaults, key, props[key]);
  }

  // resolve styles, apply with increasing precedence
  standalone_array(style).forEach(name => {
    const props = config.style && config.style[name];
    for (const key in props) {
      if (!standalone_vega_parser_module_has(key, encode)) {
        standalone_applyDefault(defaults, key, props[key]);
      }
    }
  });
  encode = standalone_extend({}, encode); // defensive copy
  for (key in defaults) {
    props = defaults[key];
    if (props.signal) {
      (update = update || {})[key] = props;
    } else {
      enter[key] = props;
    }
  }
  encode.enter = standalone_extend(enter, encode.enter);
  if (update) encode.update = standalone_extend(update, encode.update);
  return encode;
}
function standalone_applyDefault(defaults, key, value) {
  defaults[key] = value && value.signal ? {
    signal: value.signal
  } : {
    value: value
  };
}

const standalone_scaleRef = scale => standalone_vega_util_module_isString(scale) ? standalone_$(scale) : scale.signal ? `(${scale.signal})` : standalone_vega_parser_module_field(scale);
function standalone_entry$1(enc) {
  if (enc.gradient != null) {
    return standalone_vega_parser_module_gradient(enc);
  }
  let value = enc.signal ? `(${enc.signal})` : enc.color ? standalone_vega_parser_module_color(enc.color) : enc.field != null ? standalone_vega_parser_module_field(enc.field) : enc.value !== undefined ? standalone_$(enc.value) : undefined;
  if (enc.scale != null) {
    value = standalone_vega_parser_module_scale(enc, value);
  }
  if (value === undefined) {
    value = null;
  }
  if (enc.exponent != null) {
    value = `pow(${value},${standalone_property(enc.exponent)})`;
  }
  if (enc.mult != null) {
    value += `*${standalone_property(enc.mult)}`;
  }
  if (enc.offset != null) {
    value += `+${standalone_property(enc.offset)}`;
  }
  if (enc.round) {
    value = `round(${value})`;
  }
  return value;
}
const src_standalone_color = (type, x, y, z) => `(${type}(${[x, y, z].map(standalone_entry$1).join(',')})+'')`;
function standalone_vega_parser_module_color(enc) {
  return enc.c ? src_standalone_color('hcl', enc.h, enc.c, enc.l) : enc.h || enc.s ? src_standalone_color('hsl', enc.h, enc.s, enc.l) : enc.l || enc.a ? src_standalone_color('lab', enc.l, enc.a, enc.b) : enc.r || enc.g || enc.b ? src_standalone_color('rgb', enc.r, enc.g, enc.b) : null;
}
function standalone_vega_parser_module_gradient(enc) {
  // map undefined to null; expression lang does not allow undefined
  const args = [enc.start, enc.stop, enc.count].map(_ => _ == null ? null : standalone_$(_));

  // trim null inputs from the end
  while (args.length && standalone_peek(args) == null) args.pop();
  args.unshift(standalone_scaleRef(enc.gradient));
  return `gradient(${args.join(',')})`;
}
function standalone_property(property) {
  return standalone_vega_util_module_isObject(property) ? '(' + standalone_entry$1(property) + ')' : property;
}
function standalone_vega_parser_module_field(ref) {
  return standalone_resolveField(standalone_vega_util_module_isObject(ref) ? ref : {
    datum: ref
  });
}
function standalone_resolveField(ref) {
  let object, level, field;
  if (ref.signal) {
    object = 'datum';
    field = ref.signal;
  } else if (ref.group || ref.parent) {
    level = Math.max(1, ref.level || 1);
    object = 'item';
    while (level-- > 0) {
      object += '.mark.group';
    }
    if (ref.parent) {
      field = ref.parent;
      object += '.datum';
    } else {
      field = ref.group;
    }
  } else if (ref.datum) {
    object = 'datum';
    field = ref.datum;
  } else {
    standalone_vega_util_module_error('Invalid field reference: ' + standalone_$(ref));
  }
  if (!ref.signal) {
    field = standalone_vega_util_module_isString(field) ? standalone_splitAccessPath(field).map(standalone_$).join('][') : standalone_resolveField(field);
  }
  return object + '[' + field + ']';
}
function standalone_vega_parser_module_scale(enc, value) {
  const scale = standalone_scaleRef(enc.scale);
  if (enc.range != null) {
    // pull value from scale range
    value = `lerp(_range(${scale}), ${+enc.range})`;
  } else {
    // run value through scale and/or pull scale bandwidth
    if (value !== undefined) value = `_scale(${scale}, ${value})`;
    if (enc.band) {
      value = (value ? value + '+' : '') + `_bandwidth(${scale})` + (+enc.band === 1 ? '' : '*' + standalone_property(enc.band));
      if (enc.extra) {
        // include logic to handle extraneous elements
        value = `(datum.extra ? _scale(${scale}, datum.extra.value) : ${value})`;
      }
    }
    if (value == null) value = '0';
  }
  return value;
}

function standalone_vega_parser_module_rule (enc) {
  let code = '';
  enc.forEach(rule => {
    const value = standalone_entry$1(rule);
    code += rule.test ? `(${rule.test})?${value}:` : value;
  });

  // if no else clause, terminate with null (#1366)
  if (standalone_peek(code) === ':') {
    code += 'null';
  }
  return code;
}

function standalone_parseEncode (encode, type, role, style, scope, params) {
  const enc = {};
  params = params || {};
  params.encoders = {
    $encode: enc
  };
  encode = standalone_applyDefaults(encode, type, role, style, scope.config);
  for (const key in encode) {
    enc[key] = standalone_parseBlock(encode[key], type, params, scope);
  }
  return params;
}
function standalone_parseBlock(block, marktype, params, scope) {
  const channels = {},
    fields = {};
  for (const name in block) {
    if (block[name] != null) {
      // skip any null entries
      channels[name] = standalone_parse$1(standalone_expr(block[name]), scope, params, fields);
    }
  }
  return {
    $expr: {
      marktype,
      channels
    },
    $fields: Object.keys(fields),
    $output: Object.keys(block)
  };
}
function standalone_expr(enc) {
  return standalone_vega_util_module_isArray(enc) ? standalone_vega_parser_module_rule(enc) : standalone_entry$1(enc);
}
function standalone_parse$1(code, scope, params, fields) {
  const expr = standalone_vega_functions_module_parser(code, scope);
  expr.$fields.forEach(name => fields[name] = 1);
  standalone_extend(params, expr.$params);
  return expr.$expr;
}

const standalone_OUTER = 'outer',
  standalone_OUTER_INVALID = ['value', 'update', 'init', 'react', 'bind'];
function standalone_outerError(prefix, name) {
  standalone_vega_util_module_error(prefix + ' for "outer" push: ' + standalone_$(name));
}
function standalone_parseSignal (signal, scope) {
  const name = signal.name;
  if (signal.push === standalone_OUTER) {
    // signal must already be defined, raise error if not
    if (!scope.signals[name]) standalone_outerError('No prior signal definition', name);
    // signal push must not use properties reserved for standard definition
    standalone_OUTER_INVALID.forEach(prop => {
      if (signal[prop] !== undefined) standalone_outerError('Invalid property ', prop);
    });
  } else {
    // define a new signal in the current scope
    const op = scope.addSignal(name, signal.value);
    if (signal.react === false) op.react = false;
    if (signal.bind) scope.addBinding(name, signal.bind);
  }
}

function standalone_Entry(type, value, params, parent) {
  this.id = -1;
  this.type = type;
  this.value = value;
  this.params = params;
  if (parent) this.parent = parent;
}
function standalone_entry(type, value, params, parent) {
  return new standalone_Entry(type, value, params, parent);
}
function standalone_operator(value, params) {
  return standalone_entry('operator', value, params);
}

// -----

function standalone_ref(op) {
  const ref = {
    $ref: op.id
  };
  // if operator not yet registered, cache ref to resolve later
  if (op.id < 0) (op.refs = op.refs || []).push(ref);
  return ref;
}
function standalone_fieldRef$1(field, name) {
  return name ? {
    $field: field,
    $name: name
  } : {
    $field: field
  };
}
const standalone_keyFieldRef = standalone_fieldRef$1('key');
function standalone_compareRef(fields, orders) {
  return {
    $compare: fields,
    $order: orders
  };
}
function standalone_keyRef(fields, flat) {
  const ref = {
    $key: fields
  };
  if (flat) ref.$flat = true;
  return ref;
}

// -----

const standalone_Ascending = 'ascending';
const standalone_Descending = 'descending';
function standalone_sortKey(sort) {
  return !standalone_vega_util_module_isObject(sort) ? '' : (sort.order === standalone_Descending ? '-' : '+') + standalone_aggrField(sort.op, sort.field);
}
function standalone_aggrField(op, field) {
  return (op && op.signal ? '$' + op.signal : op || '') + (op && field ? '_' : '') + (field && field.signal ? '$' + field.signal : field || '');
}

// -----

const standalone_Scope$1 = 'scope';
const standalone_vega_parser_module_View = 'view';
function standalone_isSignal(_) {
  return _ && _.signal;
}
function standalone_isExpr$1(_) {
  return _ && _.expr;
}
function standalone_hasSignal(_) {
  if (standalone_isSignal(_)) return true;
  if (standalone_vega_util_module_isObject(_)) for (const key in _) {
    if (standalone_hasSignal(_[key])) return true;
  }
  return false;
}
function standalone_vega_parser_module_value(specValue, defaultValue) {
  return specValue != null ? specValue : defaultValue;
}
function standalone_deref(v) {
  return v && v.signal || v;
}

const standalone_vega_parser_module_Timer = 'timer';
function standalone_vega_parser_module_parseStream(stream, scope) {
  const method = stream.merge ? standalone_mergeStream : stream.stream ? standalone_nestedStream : stream.type ? standalone_eventStream : standalone_vega_util_module_error('Invalid stream specification: ' + standalone_$(stream));
  return method(stream, scope);
}
function standalone_eventSource(source) {
  return source === standalone_Scope$1 ? standalone_vega_parser_module_View : source || standalone_vega_parser_module_View;
}
function standalone_mergeStream(stream, scope) {
  const list = stream.merge.map(s => standalone_vega_parser_module_parseStream(s, scope)),
    entry = standalone_streamParameters({
      merge: list
    }, stream, scope);
  return scope.addStream(entry).id;
}
function standalone_nestedStream(stream, scope) {
  const id = standalone_vega_parser_module_parseStream(stream.stream, scope),
    entry = standalone_streamParameters({
      stream: id
    }, stream, scope);
  return scope.addStream(entry).id;
}
function standalone_eventStream(stream, scope) {
  let id;
  if (stream.type === standalone_vega_parser_module_Timer) {
    id = scope.event(standalone_vega_parser_module_Timer, stream.throttle);
    stream = {
      between: stream.between,
      filter: stream.filter
    };
  } else {
    id = scope.event(standalone_eventSource(stream.source), stream.type);
  }
  const entry = standalone_streamParameters({
    stream: id
  }, stream, scope);
  return Object.keys(entry).length === 1 ? id : scope.addStream(entry).id;
}
function standalone_streamParameters(entry, stream, scope) {
  let param = stream.between;
  if (param) {
    if (param.length !== 2) {
      standalone_vega_util_module_error('Stream "between" parameter must have 2 entries: ' + standalone_$(stream));
    }
    entry.between = [standalone_vega_parser_module_parseStream(param[0], scope), standalone_vega_parser_module_parseStream(param[1], scope)];
  }
  param = stream.filter ? [].concat(stream.filter) : [];
  if (stream.marktype || stream.markname || stream.markrole) {
    // add filter for mark type, name and/or role
    param.push(standalone_filterMark(stream.marktype, stream.markname, stream.markrole));
  }
  if (stream.source === standalone_Scope$1) {
    // add filter to limit events from sub-scope only
    param.push('inScope(event.item)');
  }
  if (param.length) {
    entry.filter = standalone_vega_functions_module_parser('(' + param.join(')&&(') + ')', scope).$expr;
  }
  if ((param = stream.throttle) != null) {
    entry.throttle = +param;
  }
  if ((param = stream.debounce) != null) {
    entry.debounce = +param;
  }
  if (stream.consume) {
    entry.consume = true;
  }
  return entry;
}
function standalone_filterMark(type, name, role) {
  const item = 'event.item';
  return item + (type && type !== '*' ? '&&' + item + '.mark.marktype===\'' + type + '\'' : '') + (role ? '&&' + item + '.mark.role===\'' + role + '\'' : '') + (name ? '&&' + item + '.mark.name===\'' + name + '\'' : '');
}

// bypass expression parser for internal operator references
const standalone_OP_VALUE_EXPR = {
  code: '_.$value',
  ast: {
    type: 'Identifier',
    value: 'value'
  }
};
function standalone_vega_parser_module_parseUpdate (spec, scope, target) {
  const encode = spec.encode,
    entry = {
      target: target
    };
  let events = spec.events,
    update = spec.update,
    sources = [];
  if (!events) {
    standalone_vega_util_module_error('Signal update missing events specification.');
  }

  // interpret as an event selector string
  if (standalone_vega_util_module_isString(events)) {
    events = standalone_eventSelector(events, scope.isSubscope() ? standalone_Scope$1 : standalone_vega_parser_module_View);
  }

  // separate event streams from signal updates
  events = standalone_array(events).filter(s => s.signal || s.scale ? (sources.push(s), 0) : 1);

  // merge internal operator listeners
  if (sources.length > 1) {
    sources = [standalone_mergeSources(sources)];
  }

  // merge event streams, include as source
  if (events.length) {
    sources.push(events.length > 1 ? {
      merge: events
    } : events[0]);
  }
  if (encode != null) {
    if (update) standalone_vega_util_module_error('Signal encode and update are mutually exclusive.');
    update = 'encode(item(),' + standalone_$(encode) + ')';
  }

  // resolve update value
  entry.update = standalone_vega_util_module_isString(update) ? standalone_vega_functions_module_parser(update, scope) : update.expr != null ? standalone_vega_functions_module_parser(update.expr, scope) : update.value != null ? update.value : update.signal != null ? {
    $expr: standalone_OP_VALUE_EXPR,
    $params: {
      $value: scope.signalRef(update.signal)
    }
  } : standalone_vega_util_module_error('Invalid signal update specification.');
  if (spec.force) {
    entry.options = {
      force: true
    };
  }
  sources.forEach(source => scope.addUpdate(standalone_extend(standalone_streamSource(source, scope), entry)));
}
function standalone_streamSource(stream, scope) {
  return {
    source: stream.signal ? scope.signalRef(stream.signal) : stream.scale ? scope.scaleRef(stream.scale) : standalone_vega_parser_module_parseStream(stream, scope)
  };
}
function standalone_mergeSources(sources) {
  return {
    signal: '[' + sources.map(s => s.scale ? 'scale("' + s.scale + '")' : s.signal) + ']'
  };
}

function standalone_parseSignalUpdates (signal, scope) {
  const op = scope.getSignal(signal.name);
  let expr = signal.update;
  if (signal.init) {
    if (expr) {
      standalone_vega_util_module_error('Signals can not include both init and update expressions.');
    } else {
      expr = signal.init;
      op.initonly = true;
    }
  }
  if (expr) {
    expr = standalone_vega_functions_module_parser(expr, scope);
    op.update = expr.$expr;
    op.params = expr.$params;
  }
  if (signal.on) {
    signal.on.forEach(_ => standalone_vega_parser_module_parseUpdate(_, scope, op.id));
  }
}

const standalone_vega_parser_module_transform = name => (params, value, parent) => standalone_entry(name, value, params || undefined, parent);
const standalone_vega_parser_module_Aggregate = standalone_vega_parser_module_transform('aggregate');
const standalone_vega_parser_module_AxisTicks = standalone_vega_parser_module_transform('axisticks');
const standalone_vega_parser_module_Bound = standalone_vega_parser_module_transform('bound');
const standalone_vega_parser_module_Collect = standalone_vega_parser_module_transform('collect');
const standalone_vega_parser_module_Compare = standalone_vega_parser_module_transform('compare');
const standalone_vega_parser_module_DataJoin = standalone_vega_parser_module_transform('datajoin');
const standalone_vega_parser_module_Encode = standalone_vega_parser_module_transform('encode');
const standalone_vega_parser_module_Expression = standalone_vega_parser_module_transform('expression');
const standalone_vega_parser_module_Facet = standalone_vega_parser_module_transform('facet');
const standalone_vega_parser_module_Field = standalone_vega_parser_module_transform('field');
const standalone_vega_parser_module_Key = standalone_vega_parser_module_transform('key');
const standalone_vega_parser_module_LegendEntries = standalone_vega_parser_module_transform('legendentries');
const standalone_vega_parser_module_Load = standalone_vega_parser_module_transform('load');
const standalone_vega_parser_module_Mark = standalone_vega_parser_module_transform('mark');
const standalone_vega_parser_module_MultiExtent = standalone_vega_parser_module_transform('multiextent');
const standalone_vega_parser_module_MultiValues = standalone_vega_parser_module_transform('multivalues');
const standalone_vega_parser_module_Overlap = standalone_vega_parser_module_transform('overlap');
const standalone_vega_parser_module_Params = standalone_vega_parser_module_transform('params');
const standalone_vega_parser_module_PreFacet = standalone_vega_parser_module_transform('prefacet');
const standalone_vega_parser_module_Projection = standalone_vega_parser_module_transform('projection');
const standalone_vega_parser_module_Proxy = standalone_vega_parser_module_transform('proxy');
const standalone_vega_parser_module_Relay = standalone_vega_parser_module_transform('relay');
const standalone_vega_parser_module_Render = standalone_vega_parser_module_transform('render');
const standalone_vega_parser_module_Scale = standalone_vega_parser_module_transform('scale');
const standalone_vega_parser_module_Sieve = standalone_vega_parser_module_transform('sieve');
const standalone_vega_parser_module_SortItems = standalone_vega_parser_module_transform('sortitems');
const standalone_vega_parser_module_ViewLayout = standalone_vega_parser_module_transform('viewlayout');
const standalone_vega_parser_module_Values = standalone_vega_parser_module_transform('values');

let standalone_FIELD_REF_ID = 0;
const standalone_MULTIDOMAIN_SORT_OPS = {
  min: 'min',
  max: 'max',
  count: 'sum'
};
function standalone_initScale(spec, scope) {
  const type = spec.type || 'linear';
  if (!standalone_isValidScaleType(type)) {
    standalone_vega_util_module_error('Unrecognized scale type: ' + standalone_$(type));
  }
  scope.addScale(spec.name, {
    type,
    domain: undefined
  });
}
function standalone_parseScale(spec, scope) {
  const params = scope.getScale(spec.name).params;
  let key;
  params.domain = standalone_parseScaleDomain(spec.domain, spec, scope);
  if (spec.range != null) {
    params.range = standalone_parseScaleRange(spec, scope, params);
  }
  if (spec.interpolate != null) {
    standalone_parseScaleInterpolate(spec.interpolate, params);
  }
  if (spec.nice != null) {
    params.nice = standalone_parseScaleNice(spec.nice, scope);
  }
  if (spec.bins != null) {
    params.bins = standalone_parseScaleBins(spec.bins, scope);
  }
  for (key in spec) {
    if (standalone_vega_util_module_has(params, key) || key === 'name') continue;
    params[key] = standalone_parseLiteral(spec[key], scope);
  }
}
function standalone_parseLiteral(v, scope) {
  return !standalone_vega_util_module_isObject(v) ? v : v.signal ? scope.signalRef(v.signal) : standalone_vega_util_module_error('Unsupported object: ' + standalone_$(v));
}
function standalone_parseArray(v, scope) {
  return v.signal ? scope.signalRef(v.signal) : v.map(v => standalone_parseLiteral(v, scope));
}
function standalone_dataLookupError(name) {
  standalone_vega_util_module_error('Can not find data set: ' + standalone_$(name));
}

// -- SCALE DOMAIN ----

function standalone_parseScaleDomain(domain, spec, scope) {
  if (!domain) {
    if (spec.domainMin != null || spec.domainMax != null) {
      standalone_vega_util_module_error('No scale domain defined for domainMin/domainMax to override.');
    }
    return; // default domain
  }
  return domain.signal ? scope.signalRef(domain.signal) : (standalone_vega_util_module_isArray(domain) ? standalone_explicitDomain : domain.fields ? standalone_multipleDomain : standalone_singularDomain)(domain, spec, scope);
}
function standalone_explicitDomain(domain, spec, scope) {
  return domain.map(v => standalone_parseLiteral(v, scope));
}
function standalone_singularDomain(domain, spec, scope) {
  const data = scope.getData(domain.data);
  if (!data) standalone_dataLookupError(domain.data);
  return standalone_isDiscrete(spec.type) ? data.valuesRef(scope, domain.field, standalone_parseSort(domain.sort, false)) : standalone_isQuantile(spec.type) ? data.domainRef(scope, domain.field) : data.extentRef(scope, domain.field);
}
function standalone_multipleDomain(domain, spec, scope) {
  const data = domain.data,
    fields = domain.fields.reduce((dom, d) => {
      d = standalone_vega_util_module_isString(d) ? {
        data: data,
        field: d
      } : standalone_vega_util_module_isArray(d) || d.signal ? standalone_fieldRef(d, scope) : d;
      dom.push(d);
      return dom;
    }, []);
  return (standalone_isDiscrete(spec.type) ? standalone_ordinalMultipleDomain : standalone_isQuantile(spec.type) ? standalone_quantileMultipleDomain : standalone_numericMultipleDomain)(domain, scope, fields);
}
function standalone_fieldRef(data, scope) {
  const name = '_:vega:_' + standalone_FIELD_REF_ID++,
    coll = standalone_vega_parser_module_Collect({});
  if (standalone_vega_util_module_isArray(data)) {
    coll.value = {
      $ingest: data
    };
  } else if (data.signal) {
    const code = 'setdata(' + standalone_$(name) + ',' + data.signal + ')';
    coll.params.input = scope.signalRef(code);
  }
  scope.addDataPipeline(name, [coll, standalone_vega_parser_module_Sieve({})]);
  return {
    data: name,
    field: 'data'
  };
}
function standalone_ordinalMultipleDomain(domain, scope, fields) {
  const sort = standalone_parseSort(domain.sort, true);
  let a, v;

  // get value counts for each domain field
  const counts = fields.map(f => {
    const data = scope.getData(f.data);
    if (!data) standalone_dataLookupError(f.data);
    return data.countsRef(scope, f.field, sort);
  });

  // aggregate the results from each domain field
  const p = {
    groupby: standalone_keyFieldRef,
    pulse: counts
  };
  if (sort) {
    a = sort.op || 'count';
    v = sort.field ? standalone_aggrField(a, sort.field) : 'count';
    p.ops = [standalone_MULTIDOMAIN_SORT_OPS[a]];
    p.fields = [scope.fieldRef(v)];
    p.as = [v];
  }
  a = scope.add(standalone_vega_parser_module_Aggregate(p));

  // collect aggregate output
  const c = scope.add(standalone_vega_parser_module_Collect({
    pulse: standalone_ref(a)
  }));

  // extract values for combined domain
  v = scope.add(standalone_vega_parser_module_Values({
    field: standalone_keyFieldRef,
    sort: scope.sortRef(sort),
    pulse: standalone_ref(c)
  }));
  return standalone_ref(v);
}
function standalone_parseSort(sort, multidomain) {
  if (sort) {
    if (!sort.field && !sort.op) {
      if (standalone_vega_util_module_isObject(sort)) sort.field = 'key';else sort = {
        field: 'key'
      };
    } else if (!sort.field && sort.op !== 'count') {
      standalone_vega_util_module_error('No field provided for sort aggregate op: ' + sort.op);
    } else if (multidomain && sort.field) {
      if (sort.op && !standalone_MULTIDOMAIN_SORT_OPS[sort.op]) {
        standalone_vega_util_module_error('Multiple domain scales can not be sorted using ' + sort.op);
      }
    }
  }
  return sort;
}
function standalone_quantileMultipleDomain(domain, scope, fields) {
  // get value arrays for each domain field
  const values = fields.map(f => {
    const data = scope.getData(f.data);
    if (!data) standalone_dataLookupError(f.data);
    return data.domainRef(scope, f.field);
  });

  // combine value arrays
  return standalone_ref(scope.add(standalone_vega_parser_module_MultiValues({
    values: values
  })));
}
function standalone_numericMultipleDomain(domain, scope, fields) {
  // get extents for each domain field
  const extents = fields.map(f => {
    const data = scope.getData(f.data);
    if (!data) standalone_dataLookupError(f.data);
    return data.extentRef(scope, f.field);
  });

  // combine extents
  return standalone_ref(scope.add(standalone_vega_parser_module_MultiExtent({
    extents: extents
  })));
}

// -- SCALE BINS -----

function standalone_parseScaleBins(v, scope) {
  return v.signal || standalone_vega_util_module_isArray(v) ? standalone_parseArray(v, scope) : scope.objectProperty(v);
}

// -- SCALE NICE -----

function standalone_parseScaleNice(nice, scope) {
  return nice.signal ? scope.signalRef(nice.signal) : standalone_vega_util_module_isObject(nice) ? {
    interval: standalone_parseLiteral(nice.interval),
    step: standalone_parseLiteral(nice.step)
  } : standalone_parseLiteral(nice);
}

// -- SCALE INTERPOLATION -----

function standalone_parseScaleInterpolate(interpolate, params) {
  params.interpolate = standalone_parseLiteral(interpolate.type || interpolate);
  if (interpolate.gamma != null) {
    params.interpolateGamma = standalone_parseLiteral(interpolate.gamma);
  }
}

// -- SCALE RANGE -----

function standalone_parseScaleRange(spec, scope, params) {
  const config = scope.config.range;
  let range = spec.range;
  if (range.signal) {
    return scope.signalRef(range.signal);
  } else if (standalone_vega_util_module_isString(range)) {
    if (config && standalone_vega_util_module_has(config, range)) {
      spec = standalone_extend({}, spec, {
        range: config[range]
      });
      return standalone_parseScaleRange(spec, scope, params);
    } else if (range === 'width') {
      range = [0, {
        signal: 'width'
      }];
    } else if (range === 'height') {
      range = standalone_isDiscrete(spec.type) ? [0, {
        signal: 'height'
      }] : [{
        signal: 'height'
      }, 0];
    } else {
      standalone_vega_util_module_error('Unrecognized scale range value: ' + standalone_$(range));
    }
  } else if (range.scheme) {
    params.scheme = standalone_vega_util_module_isArray(range.scheme) ? standalone_parseArray(range.scheme, scope) : standalone_parseLiteral(range.scheme, scope);
    if (range.extent) params.schemeExtent = standalone_parseArray(range.extent, scope);
    if (range.count) params.schemeCount = standalone_parseLiteral(range.count, scope);
    return;
  } else if (range.step) {
    params.rangeStep = standalone_parseLiteral(range.step, scope);
    return;
  } else if (standalone_isDiscrete(spec.type) && !standalone_vega_util_module_isArray(range)) {
    return standalone_parseScaleDomain(range, spec, scope);
  } else if (!standalone_vega_util_module_isArray(range)) {
    standalone_vega_util_module_error('Unsupported range type: ' + standalone_$(range));
  }
  return range.map(v => (standalone_vega_util_module_isArray(v) ? standalone_parseArray : standalone_parseLiteral)(v, scope));
}

function standalone_parseProjection (proj, scope) {
  const config = scope.config.projection || {},
    params = {};
  for (const name in proj) {
    if (name === 'name') continue;
    params[name] = standalone_parseParameter$1(proj[name], name, scope);
  }

  // apply projection defaults from config
  for (const name in config) {
    if (params[name] == null) {
      params[name] = standalone_parseParameter$1(config[name], name, scope);
    }
  }
  scope.addProjection(proj.name, params);
}
function standalone_parseParameter$1(_, name, scope) {
  return standalone_vega_util_module_isArray(_) ? _.map(_ => standalone_parseParameter$1(_, name, scope)) : !standalone_vega_util_module_isObject(_) ? _ : _.signal ? scope.signalRef(_.signal) : name === 'fit' ? _ : standalone_vega_util_module_error('Unsupported parameter object: ' + standalone_$(_));
}

const standalone_vega_parser_module_Top = 'top';
const standalone_vega_parser_module_Left = 'left';
const standalone_vega_parser_module_Right = 'right';
const standalone_vega_parser_module_Bottom = 'bottom';
const standalone_vega_parser_module_Center = 'center';
const standalone_Vertical = 'vertical';
const standalone_vega_parser_module_Start = 'start';
const standalone_vega_parser_module_Middle = 'middle';
const standalone_vega_parser_module_End = 'end';
const standalone_Index = 'index';
const standalone_vega_parser_module_Label = 'label';
const standalone_Offset = 'offset';
const standalone_Perc = 'perc';
const standalone_Perc2 = 'perc2';
const standalone_Value = 'value';
const standalone_GuideLabelStyle = 'guide-label';
const standalone_GuideTitleStyle = 'guide-title';
const standalone_GroupTitleStyle = 'group-title';
const standalone_GroupSubtitleStyle = 'group-subtitle';
const standalone_vega_parser_module_Symbols = 'symbol';
const standalone_vega_parser_module_Gradient = 'gradient';
const standalone_vega_parser_module_Discrete = 'discrete';
const standalone_Size = 'size';
const standalone_Shape = 'shape';
const standalone_Fill = 'fill';
const standalone_Stroke = 'stroke';
const standalone_StrokeWidth = 'strokeWidth';
const standalone_StrokeDash = 'strokeDash';
const standalone_Opacity = 'opacity';

// Encoding channels supported by legends
// In priority order of 'canonical' scale
const standalone_LegendScales = [standalone_Size, standalone_Shape, standalone_Fill, standalone_Stroke, standalone_StrokeWidth, standalone_StrokeDash, standalone_Opacity];
const standalone_vega_parser_module_Skip = {
  name: 1,
  style: 1,
  interactive: 1
};
const standalone_vega_parser_module_zero = {
  value: 0
};
const standalone_vega_parser_module_one = {
  value: 1
};

const standalone_GroupMark = 'group';
const standalone_RectMark = 'rect';
const standalone_RuleMark = 'rule';
const standalone_SymbolMark = 'symbol';
const standalone_TextMark = 'text';

function standalone_guideGroup (mark) {
  mark.type = standalone_GroupMark;
  mark.interactive = mark.interactive || false;
  return mark;
}

function standalone_vega_parser_module_lookup(spec, config) {
  const _ = (name, dflt) => standalone_vega_parser_module_value(spec[name], standalone_vega_parser_module_value(config[name], dflt));
  _.isVertical = s => standalone_Vertical === standalone_vega_parser_module_value(spec.direction, config.direction || (s ? config.symbolDirection : config.gradientDirection));
  _.gradientLength = () => standalone_vega_parser_module_value(spec.gradientLength, config.gradientLength || config.gradientWidth);
  _.gradientThickness = () => standalone_vega_parser_module_value(spec.gradientThickness, config.gradientThickness || config.gradientHeight);
  _.entryColumns = () => standalone_vega_parser_module_value(spec.columns, standalone_vega_parser_module_value(config.columns, +_.isVertical(true)));
  return _;
}
function standalone_getEncoding(name, encode) {
  const v = encode && (encode.update && encode.update[name] || encode.enter && encode.enter[name]);
  return v && v.signal ? v : v ? v.value : null;
}
function standalone_getStyle(name, scope, style) {
  const s = scope.config.style[style];
  return s && s[name];
}
function standalone_anchorExpr(s, e, m) {
  return `item.anchor === '${standalone_vega_parser_module_Start}' ? ${s} : item.anchor === '${standalone_vega_parser_module_End}' ? ${e} : ${m}`;
}
const standalone_alignExpr$1 = standalone_anchorExpr(standalone_$(standalone_vega_parser_module_Left), standalone_$(standalone_vega_parser_module_Right), standalone_$(standalone_vega_parser_module_Center));
function standalone_tickBand(_) {
  const v = _('tickBand');
  let offset = _('tickOffset'),
    band,
    extra;
  if (!v) {
    // if no tick band entry, fall back on other properties
    band = _('bandPosition');
    extra = _('tickExtra');
  } else if (v.signal) {
    // if signal, augment code to interpret values
    band = {
      signal: `(${v.signal}) === 'extent' ? 1 : 0.5`
    };
    extra = {
      signal: `(${v.signal}) === 'extent'`
    };
    if (!standalone_vega_util_module_isObject(offset)) {
      offset = {
        signal: `(${v.signal}) === 'extent' ? 0 : ${offset}`
      };
    }
  } else if (v === 'extent') {
    // if constant, simply set values
    band = 1;
    extra = true;
    offset = 0;
  } else {
    band = 0.5;
    extra = false;
  }
  return {
    extra,
    band,
    offset
  };
}
function standalone_extendOffset(value, offset) {
  return !offset ? value : !value ? offset : !standalone_vega_util_module_isObject(value) ? {
    value,
    offset
  } : Object.assign({}, value, {
    offset: standalone_extendOffset(value.offset, offset)
  });
}

function standalone_guideMark (mark, extras) {
  if (extras) {
    mark.name = extras.name;
    mark.style = extras.style || mark.style;
    mark.interactive = !!extras.interactive;
    mark.encode = standalone_extendEncode(mark.encode, extras, standalone_vega_parser_module_Skip);
  } else {
    mark.interactive = false;
  }
  return mark;
}

function standalone_legendGradient (spec, scale, config, userEncode) {
  const _ = standalone_vega_parser_module_lookup(spec, config),
    vertical = _.isVertical(),
    thickness = _.gradientThickness(),
    length = _.gradientLength();
  let enter, start, stop, width, height;
  if (vertical) {
    start = [0, 1];
    stop = [0, 0];
    width = thickness;
    height = length;
  } else {
    start = [0, 0];
    stop = [1, 0];
    width = length;
    height = thickness;
  }
  const encode = {
    enter: enter = {
      opacity: standalone_vega_parser_module_zero,
      x: standalone_vega_parser_module_zero,
      y: standalone_vega_parser_module_zero,
      width: standalone_encoder(width),
      height: standalone_encoder(height)
    },
    update: standalone_extend({}, enter, {
      opacity: standalone_vega_parser_module_one,
      fill: {
        gradient: scale,
        start: start,
        stop: stop
      }
    }),
    exit: {
      opacity: standalone_vega_parser_module_zero
    }
  };
  standalone_addEncoders(encode, {
    stroke: _('gradientStrokeColor'),
    strokeWidth: _('gradientStrokeWidth')
  }, {
    // update
    opacity: _('gradientOpacity')
  });
  return standalone_guideMark({
    type: standalone_RectMark,
    role: standalone_LegendGradientRole,
    encode
  }, userEncode);
}

function standalone_legendGradientDiscrete (spec, scale, config, userEncode, dataRef) {
  const _ = standalone_vega_parser_module_lookup(spec, config),
    vertical = _.isVertical(),
    thickness = _.gradientThickness(),
    length = _.gradientLength();
  let u,
    v,
    uu,
    vv,
    adjust = '';
  vertical ? (u = 'y', uu = 'y2', v = 'x', vv = 'width', adjust = '1-') : (u = 'x', uu = 'x2', v = 'y', vv = 'height');
  const enter = {
    opacity: standalone_vega_parser_module_zero,
    fill: {
      scale: scale,
      field: standalone_Value
    }
  };
  enter[u] = {
    signal: adjust + 'datum.' + standalone_Perc,
    mult: length
  };
  enter[v] = standalone_vega_parser_module_zero;
  enter[uu] = {
    signal: adjust + 'datum.' + standalone_Perc2,
    mult: length
  };
  enter[vv] = standalone_encoder(thickness);
  const encode = {
    enter: enter,
    update: standalone_extend({}, enter, {
      opacity: standalone_vega_parser_module_one
    }),
    exit: {
      opacity: standalone_vega_parser_module_zero
    }
  };
  standalone_addEncoders(encode, {
    stroke: _('gradientStrokeColor'),
    strokeWidth: _('gradientStrokeWidth')
  }, {
    // update
    opacity: _('gradientOpacity')
  });
  return standalone_guideMark({
    type: standalone_RectMark,
    role: standalone_LegendBandRole,
    key: standalone_Value,
    from: dataRef,
    encode
  }, userEncode);
}

const standalone_alignExpr = `datum.${standalone_Perc}<=0?"${standalone_vega_parser_module_Left}":datum.${standalone_Perc}>=1?"${standalone_vega_parser_module_Right}":"${standalone_vega_parser_module_Center}"`,
  standalone_baselineExpr = `datum.${standalone_Perc}<=0?"${standalone_vega_parser_module_Bottom}":datum.${standalone_Perc}>=1?"${standalone_vega_parser_module_Top}":"${standalone_vega_parser_module_Middle}"`;
function standalone_legendGradientLabels (spec, config, userEncode, dataRef) {
  const _ = standalone_vega_parser_module_lookup(spec, config),
    vertical = _.isVertical(),
    thickness = standalone_encoder(_.gradientThickness()),
    length = _.gradientLength();
  let overlap = _('labelOverlap'),
    enter,
    update,
    u,
    v,
    adjust = '';
  const encode = {
    enter: enter = {
      opacity: standalone_vega_parser_module_zero
    },
    update: update = {
      opacity: standalone_vega_parser_module_one,
      text: {
        field: standalone_vega_parser_module_Label
      }
    },
    exit: {
      opacity: standalone_vega_parser_module_zero
    }
  };
  standalone_addEncoders(encode, {
    fill: _('labelColor'),
    fillOpacity: _('labelOpacity'),
    font: _('labelFont'),
    fontSize: _('labelFontSize'),
    fontStyle: _('labelFontStyle'),
    fontWeight: _('labelFontWeight'),
    limit: standalone_vega_parser_module_value(spec.labelLimit, config.gradientLabelLimit)
  });
  if (vertical) {
    enter.align = {
      value: 'left'
    };
    enter.baseline = update.baseline = {
      signal: standalone_baselineExpr
    };
    u = 'y';
    v = 'x';
    adjust = '1-';
  } else {
    enter.align = update.align = {
      signal: standalone_alignExpr
    };
    enter.baseline = {
      value: 'top'
    };
    u = 'x';
    v = 'y';
  }
  enter[u] = update[u] = {
    signal: adjust + 'datum.' + standalone_Perc,
    mult: length
  };
  enter[v] = update[v] = thickness;
  thickness.offset = standalone_vega_parser_module_value(spec.labelOffset, config.gradientLabelOffset) || 0;
  overlap = overlap ? {
    separation: _('labelSeparation'),
    method: overlap,
    order: 'datum.' + standalone_Index
  } : undefined;

  // type, role, style, key, dataRef, encode, extras
  return standalone_guideMark({
    type: standalone_TextMark,
    role: standalone_LegendLabelRole,
    style: standalone_GuideLabelStyle,
    key: standalone_Value,
    from: dataRef,
    encode,
    overlap
  }, userEncode);
}

// userEncode is top-level, includes entries, symbols, labels
function standalone_legendSymbolGroups (spec, config, userEncode, dataRef, columns) {
  const _ = standalone_vega_parser_module_lookup(spec, config),
    entries = userEncode.entries,
    interactive = !!(entries && entries.interactive),
    name = entries ? entries.name : undefined,
    height = _('clipHeight'),
    symbolOffset = _('symbolOffset'),
    valueRef = {
      data: 'value'
    },
    xSignal = `(${columns}) ? datum.${standalone_Offset} : datum.${standalone_Size}`,
    yEncode = height ? standalone_encoder(height) : {
      field: standalone_Size
    },
    index = `datum.${standalone_Index}`,
    ncols = `max(1, ${columns})`;
  let encode, enter, update, nrows, sort;
  yEncode.mult = 0.5;

  // -- LEGEND SYMBOLS --
  encode = {
    enter: enter = {
      opacity: standalone_vega_parser_module_zero,
      x: {
        signal: xSignal,
        mult: 0.5,
        offset: symbolOffset
      },
      y: yEncode
    },
    update: update = {
      opacity: standalone_vega_parser_module_one,
      x: enter.x,
      y: enter.y
    },
    exit: {
      opacity: standalone_vega_parser_module_zero
    }
  };
  let baseFill = null,
    baseStroke = null;
  if (!spec.fill) {
    baseFill = config.symbolBaseFillColor;
    baseStroke = config.symbolBaseStrokeColor;
  }
  standalone_addEncoders(encode, {
    fill: _('symbolFillColor', baseFill),
    shape: _('symbolType'),
    size: _('symbolSize'),
    stroke: _('symbolStrokeColor', baseStroke),
    strokeDash: _('symbolDash'),
    strokeDashOffset: _('symbolDashOffset'),
    strokeWidth: _('symbolStrokeWidth')
  }, {
    // update
    opacity: _('symbolOpacity')
  });
  standalone_LegendScales.forEach(scale => {
    if (spec[scale]) {
      update[scale] = enter[scale] = {
        scale: spec[scale],
        field: standalone_Value
      };
    }
  });
  const symbols = standalone_guideMark({
    type: standalone_SymbolMark,
    role: standalone_LegendSymbolRole,
    key: standalone_Value,
    from: valueRef,
    clip: height ? true : undefined,
    encode
  }, userEncode.symbols);

  // -- LEGEND LABELS --
  const labelOffset = standalone_encoder(symbolOffset);
  labelOffset.offset = _('labelOffset');
  encode = {
    enter: enter = {
      opacity: standalone_vega_parser_module_zero,
      x: {
        signal: xSignal,
        offset: labelOffset
      },
      y: yEncode
    },
    update: update = {
      opacity: standalone_vega_parser_module_one,
      text: {
        field: standalone_vega_parser_module_Label
      },
      x: enter.x,
      y: enter.y
    },
    exit: {
      opacity: standalone_vega_parser_module_zero
    }
  };
  standalone_addEncoders(encode, {
    align: _('labelAlign'),
    baseline: _('labelBaseline'),
    fill: _('labelColor'),
    fillOpacity: _('labelOpacity'),
    font: _('labelFont'),
    fontSize: _('labelFontSize'),
    fontStyle: _('labelFontStyle'),
    fontWeight: _('labelFontWeight'),
    limit: _('labelLimit')
  });
  const labels = standalone_guideMark({
    type: standalone_TextMark,
    role: standalone_LegendLabelRole,
    style: standalone_GuideLabelStyle,
    key: standalone_Value,
    from: valueRef,
    encode
  }, userEncode.labels);

  // -- LEGEND ENTRY GROUPS --
  encode = {
    enter: {
      noBound: {
        value: !height
      },
      // ignore width/height in bounds calc
      width: standalone_vega_parser_module_zero,
      height: height ? standalone_encoder(height) : standalone_vega_parser_module_zero,
      opacity: standalone_vega_parser_module_zero
    },
    exit: {
      opacity: standalone_vega_parser_module_zero
    },
    update: update = {
      opacity: standalone_vega_parser_module_one,
      row: {
        signal: null
      },
      column: {
        signal: null
      }
    }
  };

  // annotate and sort groups to ensure correct ordering
  if (_.isVertical(true)) {
    nrows = `ceil(item.mark.items.length / ${ncols})`;
    update.row.signal = `${index}%${nrows}`;
    update.column.signal = `floor(${index} / ${nrows})`;
    sort = {
      field: ['row', index]
    };
  } else {
    update.row.signal = `floor(${index} / ${ncols})`;
    update.column.signal = `${index} % ${ncols}`;
    sort = {
      field: index
    };
  }
  // handle zero column case (implies infinite columns)
  update.column.signal = `(${columns})?${update.column.signal}:${index}`;

  // facet legend entries into sub-groups
  dataRef = {
    facet: {
      data: dataRef,
      name: 'value',
      groupby: standalone_Index
    }
  };
  return standalone_guideGroup({
    role: standalone_vega_parser_module_ScopeRole,
    from: dataRef,
    encode: standalone_extendEncode(encode, entries, standalone_vega_parser_module_Skip),
    marks: [symbols, labels],
    name,
    interactive,
    sort
  });
}
function standalone_legendSymbolLayout(spec, config) {
  const _ = standalone_vega_parser_module_lookup(spec, config);

  // layout parameters for legend entries
  return {
    align: _('gridAlign'),
    columns: _.entryColumns(),
    center: {
      row: true,
      column: false
    },
    padding: {
      row: _('rowPadding'),
      column: _('columnPadding')
    }
  };
}

// expression logic for align, anchor, angle, and baseline calculation
const standalone_isL = 'item.orient === "left"',
  standalone_isR = 'item.orient === "right"',
  standalone_isLR = `(${standalone_isL} || ${standalone_isR})`,
  standalone_isVG = `datum.vgrad && ${standalone_isLR}`,
  standalone_baseline = standalone_anchorExpr('"top"', '"bottom"', '"middle"'),
  standalone_alignFlip = standalone_anchorExpr('"right"', '"left"', '"center"'),
  standalone_exprAlign = `datum.vgrad && ${standalone_isR} ? (${standalone_alignFlip}) : (${standalone_isLR} && !(datum.vgrad && ${standalone_isL})) ? "left" : ${standalone_alignExpr$1}`,
  standalone_exprAnchor = `item._anchor || (${standalone_isLR} ? "middle" : "start")`,
  standalone_exprAngle = `${standalone_isVG} ? (${standalone_isL} ? -90 : 90) : 0`,
  standalone_exprBaseline = `${standalone_isLR} ? (datum.vgrad ? (${standalone_isR} ? "bottom" : "top") : ${standalone_baseline}) : "top"`;
function standalone_legendTitle (spec, config, userEncode, dataRef) {
  const _ = standalone_vega_parser_module_lookup(spec, config);
  const encode = {
    enter: {
      opacity: standalone_vega_parser_module_zero
    },
    update: {
      opacity: standalone_vega_parser_module_one,
      x: {
        field: {
          group: 'padding'
        }
      },
      y: {
        field: {
          group: 'padding'
        }
      }
    },
    exit: {
      opacity: standalone_vega_parser_module_zero
    }
  };
  standalone_addEncoders(encode, {
    orient: _('titleOrient'),
    _anchor: _('titleAnchor'),
    anchor: {
      signal: standalone_exprAnchor
    },
    angle: {
      signal: standalone_exprAngle
    },
    align: {
      signal: standalone_exprAlign
    },
    baseline: {
      signal: standalone_exprBaseline
    },
    text: spec.title,
    fill: _('titleColor'),
    fillOpacity: _('titleOpacity'),
    font: _('titleFont'),
    fontSize: _('titleFontSize'),
    fontStyle: _('titleFontStyle'),
    fontWeight: _('titleFontWeight'),
    limit: _('titleLimit'),
    lineHeight: _('titleLineHeight')
  }, {
    // require update
    align: _('titleAlign'),
    baseline: _('titleBaseline')
  });
  return standalone_guideMark({
    type: standalone_TextMark,
    role: standalone_LegendTitleRole,
    style: standalone_GuideTitleStyle,
    from: dataRef,
    encode
  }, userEncode);
}

function standalone_vega_parser_module_clip (clip, scope) {
  let expr;
  if (standalone_vega_util_module_isObject(clip)) {
    if (clip.signal) {
      expr = clip.signal;
    } else if (clip.path) {
      expr = 'pathShape(' + standalone_param(clip.path) + ')';
    } else if (clip.sphere) {
      expr = 'geoShape(' + standalone_param(clip.sphere) + ', {type: "Sphere"})';
    }
  }
  return expr ? scope.signalRef(expr) : !!clip;
}
function standalone_param(value) {
  return standalone_vega_util_module_isObject(value) && value.signal ? value.signal : standalone_$(value);
}

function standalone_getRole (spec) {
  const role = spec.role || '';
  return role.startsWith('axis') || role.startsWith('legend') || role.startsWith('title') ? role : spec.type === standalone_GroupMark ? standalone_vega_parser_module_ScopeRole : role || standalone_MarkRole;
}

function standalone_vega_parser_module_definition (spec) {
  return {
    marktype: spec.type,
    name: spec.name || undefined,
    role: spec.role || standalone_getRole(spec),
    zindex: +spec.zindex || undefined,
    aria: spec.aria,
    description: spec.description
  };
}

function standalone_interactive (spec, scope) {
  return spec && spec.signal ? scope.signalRef(spec.signal) : spec === false ? false : true;
}

/**
 * Parse a data transform specification.
 */
function standalone_parseTransform (spec, scope) {
  const def = standalone_definition(spec.type);
  if (!def) standalone_vega_util_module_error('Unrecognized transform type: ' + standalone_$(spec.type));
  const t = standalone_entry(def.type.toLowerCase(), null, standalone_vega_parser_module_parseParameters(def, spec, scope));
  if (spec.signal) scope.addSignal(spec.signal, scope.proxy(t));
  t.metadata = def.metadata || {};
  return t;
}

/**
 * Parse all parameters of a data transform.
 */
function standalone_vega_parser_module_parseParameters(def, spec, scope) {
  const params = {},
    n = def.params.length;
  for (let i = 0; i < n; ++i) {
    const pdef = def.params[i];
    params[pdef.name] = standalone_vega_parser_module_parseParameter(pdef, spec, scope);
  }
  return params;
}

/**
 * Parse a data transform parameter.
 */
function standalone_vega_parser_module_parseParameter(def, spec, scope) {
  const type = def.type,
    value = spec[def.name];
  if (type === 'index') {
    return standalone_parseIndexParameter(def, spec, scope);
  } else if (value === undefined) {
    if (def.required) {
      standalone_vega_util_module_error('Missing required ' + standalone_$(spec.type) + ' parameter: ' + standalone_$(def.name));
    }
    return;
  } else if (type === 'param') {
    return standalone_parseSubParameters(def, spec, scope);
  } else if (type === 'projection') {
    return scope.projectionRef(spec[def.name]);
  }
  return def.array && !standalone_isSignal(value) ? value.map(v => standalone_parameterValue(def, v, scope)) : standalone_parameterValue(def, value, scope);
}

/**
 * Parse a single parameter value.
 */
function standalone_parameterValue(def, value, scope) {
  const type = def.type;
  if (standalone_isSignal(value)) {
    return standalone_isExpr(type) ? standalone_vega_util_module_error('Expression references can not be signals.') : standalone_isField(type) ? scope.fieldRef(value) : standalone_isCompare(type) ? scope.compareRef(value) : scope.signalRef(value.signal);
  } else {
    const expr = def.expr || standalone_isField(type);
    return expr && standalone_outerExpr(value) ? scope.exprRef(value.expr, value.as) : expr && standalone_outerField(value) ? standalone_fieldRef$1(value.field, value.as) : standalone_isExpr(type) ? standalone_vega_functions_module_parser(value, scope) : standalone_isData(type) ? standalone_ref(scope.getData(value).values) : standalone_isField(type) ? standalone_fieldRef$1(value) : standalone_isCompare(type) ? scope.compareRef(value) : value;
  }
}

/**
 * Parse parameter for accessing an index of another data set.
 */
function standalone_parseIndexParameter(def, spec, scope) {
  if (!standalone_vega_util_module_isString(spec.from)) {
    standalone_vega_util_module_error('Lookup "from" parameter must be a string literal.');
  }
  return scope.getData(spec.from).lookupRef(scope, spec.key);
}

/**
 * Parse a parameter that contains one or more sub-parameter objects.
 */
function standalone_parseSubParameters(def, spec, scope) {
  const value = spec[def.name];
  if (def.array) {
    if (!standalone_vega_util_module_isArray(value)) {
      // signals not allowed!
      standalone_vega_util_module_error('Expected an array of sub-parameters. Instead: ' + standalone_$(value));
    }
    return value.map(v => standalone_parseSubParameter(def, v, scope));
  } else {
    return standalone_parseSubParameter(def, value, scope);
  }
}

/**
 * Parse a sub-parameter object.
 */
function standalone_parseSubParameter(def, value, scope) {
  const n = def.params.length;
  let pdef;

  // loop over defs to find matching key
  for (let i = 0; i < n; ++i) {
    pdef = def.params[i];
    for (const k in pdef.key) {
      if (pdef.key[k] !== value[k]) {
        pdef = null;
        break;
      }
    }
    if (pdef) break;
  }
  // raise error if matching key not found
  if (!pdef) standalone_vega_util_module_error('Unsupported parameter: ' + standalone_$(value));

  // parse params, create Params transform, return ref
  const params = standalone_extend(standalone_vega_parser_module_parseParameters(pdef, value, scope), pdef.key);
  return standalone_ref(scope.add(standalone_vega_parser_module_Params(params)));
}

// -- Utilities -----

const standalone_outerExpr = _ => _ && _.expr;
const standalone_outerField = _ => _ && _.field;
const standalone_isData = _ => _ === 'data';
const standalone_isExpr = _ => _ === 'expr';
const standalone_isField = _ => _ === 'field';
const standalone_isCompare = _ => _ === 'compare';

function standalone_parseData$1 (from, group, scope) {
  let facet, key, op, dataRef, parent;

  // if no source data, generate singleton datum
  if (!from) {
    dataRef = standalone_ref(scope.add(standalone_vega_parser_module_Collect(null, [{}])));
  }

  // if faceted, process facet specification
  else if (facet = from.facet) {
    if (!group) standalone_vega_util_module_error('Only group marks can be faceted.');

    // use pre-faceted source data, if available
    if (facet.field != null) {
      dataRef = parent = standalone_getDataRef(facet, scope);
    } else {
      // generate facet aggregates if no direct data specification
      if (!from.data) {
        op = standalone_parseTransform(standalone_extend({
          type: 'aggregate',
          groupby: standalone_array(facet.groupby)
        }, facet.aggregate), scope);
        op.params.key = scope.keyRef(facet.groupby);
        op.params.pulse = standalone_getDataRef(facet, scope);
        dataRef = parent = standalone_ref(scope.add(op));
      } else {
        parent = standalone_ref(scope.getData(from.data).aggregate);
      }
      key = scope.keyRef(facet.groupby, true);
    }
  }

  // if not yet defined, get source data reference
  if (!dataRef) {
    dataRef = standalone_getDataRef(from, scope);
  }
  return {
    key: key,
    pulse: dataRef,
    parent: parent
  };
}
function standalone_getDataRef(from, scope) {
  return from.$ref ? from : from.data && from.data.$ref ? from.data : standalone_ref(scope.getData(from.data).output);
}

function standalone_DataScope(scope, input, output, values, aggr) {
  this.scope = scope; // parent scope object
  this.input = input; // first operator in pipeline (tuple input)
  this.output = output; // last operator in pipeline (tuple output)
  this.values = values; // operator for accessing tuples (but not tuple flow)

  // last aggregate in transform pipeline
  this.aggregate = aggr;

  // lookup table of field indices
  this.index = {};
}
standalone_DataScope.fromEntries = function (scope, entries) {
  const n = entries.length,
    values = entries[n - 1],
    output = entries[n - 2];
  let input = entries[0],
    aggr = null,
    i = 1;
  if (input && input.type === 'load') {
    input = entries[1];
  }

  // add operator entries to this scope, wire up pulse chain
  scope.add(entries[0]);
  for (; i < n; ++i) {
    entries[i].params.pulse = standalone_ref(entries[i - 1]);
    scope.add(entries[i]);
    if (entries[i].type === 'aggregate') aggr = entries[i];
  }
  return new standalone_DataScope(scope, input, output, values, aggr);
};
function standalone_fieldKey(field) {
  return standalone_vega_util_module_isString(field) ? field : null;
}
function standalone_addSortField(scope, p, sort) {
  const as = standalone_aggrField(sort.op, sort.field);
  let s;
  if (p.ops) {
    for (let i = 0, n = p.as.length; i < n; ++i) {
      if (p.as[i] === as) return;
    }
  } else {
    p.ops = ['count'];
    p.fields = [null];
    p.as = ['count'];
  }
  if (sort.op) {
    p.ops.push((s = sort.op.signal) ? scope.signalRef(s) : sort.op);
    p.fields.push(scope.fieldRef(sort.field));
    p.as.push(as);
  }
}
function standalone_cache(scope, ds, name, optype, field, counts, index) {
  const cache = ds[name] || (ds[name] = {}),
    sort = standalone_sortKey(counts);
  let k = standalone_fieldKey(field),
    v,
    op;
  if (k != null) {
    scope = ds.scope;
    k = k + (sort ? '|' + sort : '');
    v = cache[k];
  }
  if (!v) {
    const params = counts ? {
      field: standalone_keyFieldRef,
      pulse: ds.countsRef(scope, field, counts)
    } : {
      field: scope.fieldRef(field),
      pulse: standalone_ref(ds.output)
    };
    if (sort) params.sort = scope.sortRef(counts);
    op = scope.add(standalone_entry(optype, undefined, params));
    if (index) ds.index[field] = op;
    v = standalone_ref(op);
    if (k != null) cache[k] = v;
  }
  return v;
}
standalone_DataScope.prototype = {
  countsRef(scope, field, sort) {
    const ds = this,
      cache = ds.counts || (ds.counts = {}),
      k = standalone_fieldKey(field);
    let v, a, p;
    if (k != null) {
      scope = ds.scope;
      v = cache[k];
    }
    if (!v) {
      p = {
        groupby: scope.fieldRef(field, 'key'),
        pulse: standalone_ref(ds.output)
      };
      if (sort && sort.field) standalone_addSortField(scope, p, sort);
      a = scope.add(standalone_vega_parser_module_Aggregate(p));
      v = scope.add(standalone_vega_parser_module_Collect({
        pulse: standalone_ref(a)
      }));
      v = {
        agg: a,
        ref: standalone_ref(v)
      };
      if (k != null) cache[k] = v;
    } else if (sort && sort.field) {
      standalone_addSortField(scope, v.agg.params, sort);
    }
    return v.ref;
  },
  tuplesRef() {
    return standalone_ref(this.values);
  },
  extentRef(scope, field) {
    return standalone_cache(scope, this, 'extent', 'extent', field, false);
  },
  domainRef(scope, field) {
    return standalone_cache(scope, this, 'domain', 'values', field, false);
  },
  valuesRef(scope, field, sort) {
    return standalone_cache(scope, this, 'vals', 'values', field, sort || true);
  },
  lookupRef(scope, field) {
    return standalone_cache(scope, this, 'lookup', 'tupleindex', field, false);
  },
  indataRef(scope, field) {
    return standalone_cache(scope, this, 'indata', 'tupleindex', field, true, true);
  }
};

function standalone_parseFacet (spec, scope, group) {
  const facet = spec.from.facet,
    name = facet.name,
    data = standalone_getDataRef(facet, scope);
  let op;
  if (!facet.name) {
    standalone_vega_util_module_error('Facet must have a name: ' + standalone_$(facet));
  }
  if (!facet.data) {
    standalone_vega_util_module_error('Facet must reference a data set: ' + standalone_$(facet));
  }
  if (facet.field) {
    op = scope.add(standalone_vega_parser_module_PreFacet({
      field: scope.fieldRef(facet.field),
      pulse: data
    }));
  } else if (facet.groupby) {
    op = scope.add(standalone_vega_parser_module_Facet({
      key: scope.keyRef(facet.groupby),
      group: standalone_ref(scope.proxy(group.parent)),
      pulse: data
    }));
  } else {
    standalone_vega_util_module_error('Facet must specify groupby or field: ' + standalone_$(facet));
  }

  // initialize facet subscope
  const subscope = scope.fork(),
    source = subscope.add(standalone_vega_parser_module_Collect()),
    values = subscope.add(standalone_vega_parser_module_Sieve({
      pulse: standalone_ref(source)
    }));
  subscope.addData(name, new standalone_DataScope(subscope, source, source, values));
  subscope.addSignal('parent', null);

  // parse faceted subflow
  op.params.subflow = {
    $subflow: subscope.parse(spec).toRuntime()
  };
}

function standalone_parseSubflow (spec, scope, input) {
  const op = scope.add(standalone_vega_parser_module_PreFacet({
      pulse: input.pulse
    })),
    subscope = scope.fork();
  subscope.add(standalone_vega_parser_module_Sieve());
  subscope.addSignal('parent', null);

  // parse group mark subflow
  op.params.subflow = {
    $subflow: subscope.parse(spec).toRuntime()
  };
}

function standalone_parseTrigger (spec, scope, name) {
  const remove = spec.remove,
    insert = spec.insert,
    toggle = spec.toggle,
    modify = spec.modify,
    values = spec.values,
    op = scope.add(standalone_operator());
  const update = 'if(' + spec.trigger + ',modify("' + name + '",' + [insert, remove, toggle, modify, values].map(_ => _ == null ? 'null' : _).join(',') + '),0)';
  const expr = standalone_vega_functions_module_parser(update, scope);
  op.update = expr.$expr;
  op.params = expr.$params;
}

function standalone_parseMark (spec, scope) {
  const role = standalone_getRole(spec),
    group = spec.type === standalone_GroupMark,
    facet = spec.from && spec.from.facet,
    overlap = spec.overlap;
  let layout = spec.layout || role === standalone_vega_parser_module_ScopeRole || role === standalone_vega_parser_module_FrameRole,
    ops,
    op,
    store,
    enc,
    name,
    layoutRef,
    boundRef;
  const nested = role === standalone_MarkRole || layout || facet;

  // resolve input data
  const input = standalone_parseData$1(spec.from, group, scope);

  // data join to map tuples to visual items
  op = scope.add(standalone_vega_parser_module_DataJoin({
    key: input.key || (spec.key ? standalone_fieldRef$1(spec.key) : undefined),
    pulse: input.pulse,
    clean: !group
  }));
  const joinRef = standalone_ref(op);

  // collect visual items
  op = store = scope.add(standalone_vega_parser_module_Collect({
    pulse: joinRef
  }));

  // connect visual items to scenegraph
  op = scope.add(standalone_vega_parser_module_Mark({
    markdef: standalone_vega_parser_module_definition(spec),
    interactive: standalone_interactive(spec.interactive, scope),
    clip: standalone_vega_parser_module_clip(spec.clip, scope),
    context: {
      $context: true
    },
    groups: scope.lookup(),
    parent: scope.signals.parent ? scope.signalRef('parent') : null,
    index: scope.markpath(),
    pulse: standalone_ref(op)
  }));
  const markRef = standalone_ref(op);

  // add visual encoders
  op = enc = scope.add(standalone_vega_parser_module_Encode(standalone_parseEncode(spec.encode, spec.type, role, spec.style, scope, {
    mod: false,
    pulse: markRef
  })));

  // monitor parent marks to propagate changes
  op.params.parent = scope.encode();

  // add post-encoding transforms, if defined
  if (spec.transform) {
    spec.transform.forEach(_ => {
      const tx = standalone_parseTransform(_, scope),
        md = tx.metadata;
      if (md.generates || md.changes) {
        standalone_vega_util_module_error('Mark transforms should not generate new data.');
      }
      if (!md.nomod) enc.params.mod = true; // update encode mod handling
      tx.params.pulse = standalone_ref(op);
      scope.add(op = tx);
    });
  }

  // if item sort specified, perform post-encoding
  if (spec.sort) {
    op = scope.add(standalone_vega_parser_module_SortItems({
      sort: scope.compareRef(spec.sort),
      pulse: standalone_ref(op)
    }));
  }
  const encodeRef = standalone_ref(op);

  // add view layout operator if needed
  if (facet || layout) {
    layout = scope.add(standalone_vega_parser_module_ViewLayout({
      layout: scope.objectProperty(spec.layout),
      legends: scope.legends,
      mark: markRef,
      pulse: encodeRef
    }));
    layoutRef = standalone_ref(layout);
  }

  // compute bounding boxes
  const bound = scope.add(standalone_vega_parser_module_Bound({
    mark: markRef,
    pulse: layoutRef || encodeRef
  }));
  boundRef = standalone_ref(bound);

  // if group mark, recurse to parse nested content
  if (group) {
    // juggle layout & bounds to ensure they run *after* any faceting transforms
    if (nested) {
      ops = scope.operators;
      ops.pop();
      if (layout) ops.pop();
    }
    scope.pushState(encodeRef, layoutRef || boundRef, joinRef);
    facet ? standalone_parseFacet(spec, scope, input) // explicit facet
    : nested ? standalone_parseSubflow(spec, scope, input) // standard mark group
    : scope.parse(spec); // guide group, we can avoid nested scopes
    scope.popState();
    if (nested) {
      if (layout) ops.push(layout);
      ops.push(bound);
    }
  }

  // if requested, add overlap removal transform
  if (overlap) {
    boundRef = standalone_parseOverlap(overlap, boundRef, scope);
  }

  // render / sieve items
  const render = scope.add(standalone_vega_parser_module_Render({
      pulse: boundRef
    })),
    sieve = scope.add(standalone_vega_parser_module_Sieve({
      pulse: standalone_ref(render)
    }, undefined, scope.parent()));

  // if mark is named, make accessible as reactive geometry
  // add trigger updates if defined
  if (spec.name != null) {
    name = spec.name;
    scope.addData(name, new standalone_DataScope(scope, store, render, sieve));
    if (spec.on) spec.on.forEach(on => {
      if (on.insert || on.remove || on.toggle) {
        standalone_vega_util_module_error('Marks only support modify triggers.');
      }
      standalone_parseTrigger(on, scope, name);
    });
  }
}
function standalone_parseOverlap(overlap, source, scope) {
  const method = overlap.method,
    bound = overlap.bound,
    sep = overlap.separation;
  const params = {
    separation: standalone_isSignal(sep) ? scope.signalRef(sep.signal) : sep,
    method: standalone_isSignal(method) ? scope.signalRef(method.signal) : method,
    pulse: source
  };
  if (overlap.order) {
    params.sort = scope.compareRef({
      field: overlap.order
    });
  }
  if (bound) {
    const tol = bound.tolerance;
    params.boundTolerance = standalone_isSignal(tol) ? scope.signalRef(tol.signal) : +tol;
    params.boundScale = scope.scaleRef(bound.scale);
    params.boundOrient = bound.orient;
  }
  return standalone_ref(scope.add(standalone_vega_parser_module_Overlap(params)));
}

function standalone_parseLegend (spec, scope) {
  const config = scope.config.legend,
    encode = spec.encode || {},
    _ = standalone_vega_parser_module_lookup(spec, config),
    legendEncode = encode.legend || {},
    name = legendEncode.name || undefined,
    interactive = legendEncode.interactive,
    style = legendEncode.style,
    scales = {};
  let scale = 0,
    entryLayout,
    params,
    children;

  // resolve scales and 'canonical' scale name
  standalone_LegendScales.forEach(s => spec[s] ? (scales[s] = spec[s], scale = scale || spec[s]) : 0);
  if (!scale) standalone_vega_util_module_error('Missing valid scale for legend.');

  // resolve legend type (symbol, gradient, or discrete gradient)
  const type = standalone_legendType(spec, scope.scaleType(scale));

  // single-element data source for legend group
  const datum = {
    title: spec.title != null,
    scales: scales,
    type: type,
    vgrad: type !== 'symbol' && _.isVertical()
  };
  const dataRef = standalone_ref(scope.add(standalone_vega_parser_module_Collect(null, [datum])));

  // encoding properties for legend entry sub-group
  const entryEncode = {
    enter: {
      x: {
        value: 0
      },
      y: {
        value: 0
      }
    }
  };

  // data source for legend values
  const entryRef = standalone_ref(scope.add(standalone_vega_parser_module_LegendEntries(params = {
    type: type,
    scale: scope.scaleRef(scale),
    count: scope.objectProperty(_('tickCount')),
    limit: scope.property(_('symbolLimit')),
    values: scope.objectProperty(spec.values),
    minstep: scope.property(spec.tickMinStep),
    formatType: scope.property(spec.formatType),
    formatSpecifier: scope.property(spec.format)
  })));

  // continuous gradient legend
  if (type === standalone_vega_parser_module_Gradient) {
    children = [standalone_legendGradient(spec, scale, config, encode.gradient), standalone_legendGradientLabels(spec, config, encode.labels, entryRef)];
    // adjust default tick count based on the gradient length
    params.count = params.count || scope.signalRef(`max(2,2*floor((${standalone_deref(_.gradientLength())})/100))`);
  }

  // discrete gradient legend
  else if (type === standalone_vega_parser_module_Discrete) {
    children = [standalone_legendGradientDiscrete(spec, scale, config, encode.gradient, entryRef), standalone_legendGradientLabels(spec, config, encode.labels, entryRef)];
  }

  // symbol legend
  else {
    // determine legend symbol group layout
    entryLayout = standalone_legendSymbolLayout(spec, config);
    children = [standalone_legendSymbolGroups(spec, config, encode, entryRef, standalone_deref(entryLayout.columns))];
    // pass symbol size information to legend entry generator
    params.size = standalone_sizeExpression(spec, scope, children[0].marks);
  }

  // generate legend marks
  children = [standalone_guideGroup({
    role: standalone_LegendEntryRole,
    from: dataRef,
    encode: entryEncode,
    marks: children,
    layout: entryLayout,
    interactive
  })];

  // include legend title if defined
  if (datum.title) {
    children.push(standalone_legendTitle(spec, config, encode.title, dataRef));
  }

  // parse legend specification
  return standalone_parseMark(standalone_guideGroup({
    role: standalone_vega_parser_module_LegendRole,
    from: dataRef,
    encode: standalone_extendEncode(standalone_buildLegendEncode(_, spec, config), legendEncode, standalone_vega_parser_module_Skip),
    marks: children,
    aria: _('aria'),
    description: _('description'),
    zindex: _('zindex'),
    name,
    interactive,
    style
  }), scope);
}
function standalone_legendType(spec, scaleType) {
  let type = spec.type || standalone_vega_parser_module_Symbols;
  if (!spec.type && standalone_scaleCount(spec) === 1 && (spec.fill || spec.stroke)) {
    type = standalone_isContinuous(scaleType) ? standalone_vega_parser_module_Gradient : standalone_isDiscretizing(scaleType) ? standalone_vega_parser_module_Discrete : standalone_vega_parser_module_Symbols;
  }
  return type !== standalone_vega_parser_module_Gradient ? type : standalone_isDiscretizing(scaleType) ? standalone_vega_parser_module_Discrete : standalone_vega_parser_module_Gradient;
}
function standalone_scaleCount(spec) {
  return standalone_LegendScales.reduce((count, type) => count + (spec[type] ? 1 : 0), 0);
}
function standalone_buildLegendEncode(_, spec, config) {
  const encode = {
    enter: {},
    update: {}
  };
  standalone_addEncoders(encode, {
    orient: _('orient'),
    offset: _('offset'),
    padding: _('padding'),
    titlePadding: _('titlePadding'),
    cornerRadius: _('cornerRadius'),
    fill: _('fillColor'),
    stroke: _('strokeColor'),
    strokeWidth: config.strokeWidth,
    strokeDash: config.strokeDash,
    x: _('legendX'),
    y: _('legendY'),
    // accessibility support
    format: spec.format,
    formatType: spec.formatType
  });
  return encode;
}
function standalone_sizeExpression(spec, scope, marks) {
  const size = standalone_deref(standalone_getChannel('size', spec, marks)),
    strokeWidth = standalone_deref(standalone_getChannel('strokeWidth', spec, marks)),
    fontSize = standalone_deref(standalone_getFontSize(marks[1].encode, scope, standalone_GuideLabelStyle));
  return standalone_vega_functions_module_parser(`max(ceil(sqrt(${size})+${strokeWidth}),${fontSize})`, scope);
}
function standalone_getChannel(name, spec, marks) {
  return spec[name] ? `scale("${spec[name]}",datum)` : standalone_getEncoding(name, marks[0].encode);
}
function standalone_getFontSize(encode, scope, style) {
  return standalone_getEncoding('fontSize', encode) || standalone_getStyle('fontSize', scope, style);
}

const standalone_angleExpr = `item.orient==="${standalone_vega_parser_module_Left}"?-90:item.orient==="${standalone_vega_parser_module_Right}"?90:0`;
function standalone_parseTitle (spec, scope) {
  spec = standalone_vega_util_module_isString(spec) ? {
    text: spec
  } : spec;
  const _ = standalone_vega_parser_module_lookup(spec, scope.config.title),
    encode = spec.encode || {},
    userEncode = encode.group || {},
    name = userEncode.name || undefined,
    interactive = userEncode.interactive,
    style = userEncode.style,
    children = [];

  // single-element data source for group title
  const datum = {},
    dataRef = standalone_ref(scope.add(standalone_vega_parser_module_Collect(null, [datum])));

  // include title text
  children.push(standalone_buildTitle(spec, _, standalone_titleEncode(spec), dataRef));

  // include subtitle text
  if (spec.subtitle) {
    children.push(standalone_buildSubTitle(spec, _, encode.subtitle, dataRef));
  }

  // parse title specification
  return standalone_parseMark(standalone_guideGroup({
    role: standalone_vega_parser_module_TitleRole,
    from: dataRef,
    encode: standalone_groupEncode(_, userEncode),
    marks: children,
    aria: _('aria'),
    description: _('description'),
    zindex: _('zindex'),
    name,
    interactive,
    style
  }), scope);
}

// provide backwards-compatibility for title custom encode;
// the top-level encode block has been *deprecated*.
function standalone_titleEncode(spec) {
  const encode = spec.encode;
  return encode && encode.title || standalone_extend({
    name: spec.name,
    interactive: spec.interactive,
    style: spec.style
  }, encode);
}
function standalone_groupEncode(_, userEncode) {
  const encode = {
    enter: {},
    update: {}
  };
  standalone_addEncoders(encode, {
    orient: _('orient'),
    anchor: _('anchor'),
    align: {
      signal: standalone_alignExpr$1
    },
    angle: {
      signal: standalone_angleExpr
    },
    limit: _('limit'),
    frame: _('frame'),
    offset: _('offset') || 0,
    padding: _('subtitlePadding')
  });
  return standalone_extendEncode(encode, userEncode, standalone_vega_parser_module_Skip);
}
function standalone_buildTitle(spec, _, userEncode, dataRef) {
  const zero = {
      value: 0
    },
    text = spec.text,
    encode = {
      enter: {
        opacity: zero
      },
      update: {
        opacity: {
          value: 1
        }
      },
      exit: {
        opacity: zero
      }
    };
  standalone_addEncoders(encode, {
    text: text,
    align: {
      signal: 'item.mark.group.align'
    },
    angle: {
      signal: 'item.mark.group.angle'
    },
    limit: {
      signal: 'item.mark.group.limit'
    },
    baseline: 'top',
    dx: _('dx'),
    dy: _('dy'),
    fill: _('color'),
    font: _('font'),
    fontSize: _('fontSize'),
    fontStyle: _('fontStyle'),
    fontWeight: _('fontWeight'),
    lineHeight: _('lineHeight')
  }, {
    // update
    align: _('align'),
    angle: _('angle'),
    baseline: _('baseline')
  });
  return standalone_guideMark({
    type: standalone_TextMark,
    role: standalone_TitleTextRole,
    style: standalone_GroupTitleStyle,
    from: dataRef,
    encode
  }, userEncode);
}
function standalone_buildSubTitle(spec, _, userEncode, dataRef) {
  const zero = {
      value: 0
    },
    text = spec.subtitle,
    encode = {
      enter: {
        opacity: zero
      },
      update: {
        opacity: {
          value: 1
        }
      },
      exit: {
        opacity: zero
      }
    };
  standalone_addEncoders(encode, {
    text: text,
    align: {
      signal: 'item.mark.group.align'
    },
    angle: {
      signal: 'item.mark.group.angle'
    },
    limit: {
      signal: 'item.mark.group.limit'
    },
    baseline: 'top',
    dx: _('dx'),
    dy: _('dy'),
    fill: _('subtitleColor'),
    font: _('subtitleFont'),
    fontSize: _('subtitleFontSize'),
    fontStyle: _('subtitleFontStyle'),
    fontWeight: _('subtitleFontWeight'),
    lineHeight: _('subtitleLineHeight')
  }, {
    // update
    align: _('align'),
    angle: _('angle'),
    baseline: _('baseline')
  });
  return standalone_guideMark({
    type: standalone_TextMark,
    role: standalone_TitleSubtitleRole,
    style: standalone_GroupSubtitleStyle,
    from: dataRef,
    encode
  }, userEncode);
}

function standalone_parseData(data, scope) {
  const transforms = [];
  if (data.transform) {
    data.transform.forEach(tx => {
      transforms.push(standalone_parseTransform(tx, scope));
    });
  }
  if (data.on) {
    data.on.forEach(on => {
      standalone_parseTrigger(on, scope, data.name);
    });
  }
  scope.addDataPipeline(data.name, standalone_analyze(data, scope, transforms));
}

/**
 * Analyze a data pipeline, add needed operators.
 */
function standalone_analyze(data, scope, ops) {
  const output = [];
  let source = null,
    modify = false,
    generate = false,
    upstream,
    i,
    n,
    t,
    m;
  if (data.values) {
    // hard-wired input data set
    if (standalone_isSignal(data.values) || standalone_hasSignal(data.format)) {
      // if either values is signal or format has signal, use dynamic loader
      output.push(standalone_vega_parser_module_load(scope, data));
      output.push(source = standalone_collect());
    } else {
      // otherwise, ingest upon dataflow init
      output.push(source = standalone_collect({
        $ingest: data.values,
        $format: data.format
      }));
    }
  } else if (data.url) {
    // load data from external source
    if (standalone_hasSignal(data.url) || standalone_hasSignal(data.format)) {
      // if either url or format has signal, use dynamic loader
      output.push(standalone_vega_parser_module_load(scope, data));
      output.push(source = standalone_collect());
    } else {
      // otherwise, request load upon dataflow init
      output.push(source = standalone_collect({
        $request: data.url,
        $format: data.format
      }));
    }
  } else if (data.source) {
    // derives from one or more other data sets
    source = upstream = standalone_array(data.source).map(d => standalone_ref(scope.getData(d).output));
    output.push(null); // populate later
  }

  // scan data transforms, add collectors as needed
  for (i = 0, n = ops.length; i < n; ++i) {
    t = ops[i];
    m = t.metadata;
    if (!source && !m.source) {
      output.push(source = standalone_collect());
    }
    output.push(t);
    if (m.generates) generate = true;
    if (m.modifies && !generate) modify = true;
    if (m.source) source = t;else if (m.changes) source = null;
  }
  if (upstream) {
    n = upstream.length - 1;
    output[0] = standalone_vega_parser_module_Relay({
      derive: modify,
      pulse: n ? upstream : upstream[0]
    });
    if (modify || n) {
      // collect derived and multi-pulse tuples
      output.splice(1, 0, standalone_collect());
    }
  }
  if (!source) output.push(standalone_collect());
  output.push(standalone_vega_parser_module_Sieve({}));
  return output;
}
function standalone_collect(values) {
  const s = standalone_vega_parser_module_Collect({}, values);
  s.metadata = {
    source: true
  };
  return s;
}
function standalone_vega_parser_module_load(scope, data) {
  return standalone_vega_parser_module_Load({
    url: data.url ? scope.property(data.url) : undefined,
    async: data.async ? scope.property(data.async) : undefined,
    values: data.values ? scope.property(data.values) : undefined,
    format: scope.objectProperty(data.format)
  });
}

const standalone_isX = orient => orient === standalone_vega_parser_module_Bottom || orient === standalone_vega_parser_module_Top;

// get sign coefficient based on axis orient
const standalone_getSign = (orient, a, b) => standalone_isSignal(orient) ? standalone_ifLeftTopExpr(orient.signal, a, b) : orient === standalone_vega_parser_module_Left || orient === standalone_vega_parser_module_Top ? a : b;

// condition on axis x-direction
const standalone_ifX = (orient, a, b) => standalone_isSignal(orient) ? standalone_ifXEnc(orient.signal, a, b) : standalone_isX(orient) ? a : b;

// condition on axis y-direction
const standalone_ifY = (orient, a, b) => standalone_isSignal(orient) ? standalone_ifYEnc(orient.signal, a, b) : standalone_isX(orient) ? b : a;
const standalone_ifTop = (orient, a, b) => standalone_isSignal(orient) ? standalone_ifTopExpr(orient.signal, a, b) : orient === standalone_vega_parser_module_Top ? {
  value: a
} : {
  value: b
};
const standalone_ifRight = (orient, a, b) => standalone_isSignal(orient) ? standalone_ifRightExpr(orient.signal, a, b) : orient === standalone_vega_parser_module_Right ? {
  value: a
} : {
  value: b
};
const standalone_ifXEnc = ($orient, a, b) => standalone_ifEnc(`${$orient} === '${standalone_vega_parser_module_Top}' || ${$orient} === '${standalone_vega_parser_module_Bottom}'`, a, b);
const standalone_ifYEnc = ($orient, a, b) => standalone_ifEnc(`${$orient} !== '${standalone_vega_parser_module_Top}' && ${$orient} !== '${standalone_vega_parser_module_Bottom}'`, a, b);
const standalone_ifLeftTopExpr = ($orient, a, b) => standalone_ifExpr(`${$orient} === '${standalone_vega_parser_module_Left}' || ${$orient} === '${standalone_vega_parser_module_Top}'`, a, b);
const standalone_ifTopExpr = ($orient, a, b) => standalone_ifExpr(`${$orient} === '${standalone_vega_parser_module_Top}'`, a, b);
const standalone_ifRightExpr = ($orient, a, b) => standalone_ifExpr(`${$orient} === '${standalone_vega_parser_module_Right}'`, a, b);
const standalone_ifEnc = (test, a, b) => {
  // ensure inputs are encoder objects (or null)
  a = a != null ? standalone_encoder(a) : a;
  b = b != null ? standalone_encoder(b) : b;
  if (standalone_isSimple(a) && standalone_isSimple(b)) {
    // if possible generate simple signal expression
    a = a ? a.signal || standalone_$(a.value) : null;
    b = b ? b.signal || standalone_$(b.value) : null;
    return {
      signal: `${test} ? (${a}) : (${b})`
    };
  } else {
    // otherwise generate rule set
    return [standalone_extend({
      test
    }, a)].concat(b || []);
  }
};
const standalone_isSimple = enc => enc == null || Object.keys(enc).length === 1;
const standalone_ifExpr = (test, a, b) => ({
  signal: `${test} ? (${standalone_toExpr(a)}) : (${standalone_toExpr(b)})`
});
const standalone_ifOrient = ($orient, t, b, l, r) => ({
  signal: (l != null ? `${$orient} === '${standalone_vega_parser_module_Left}' ? (${standalone_toExpr(l)}) : ` : '') + (b != null ? `${$orient} === '${standalone_vega_parser_module_Bottom}' ? (${standalone_toExpr(b)}) : ` : '') + (r != null ? `${$orient} === '${standalone_vega_parser_module_Right}' ? (${standalone_toExpr(r)}) : ` : '') + (t != null ? `${$orient} === '${standalone_vega_parser_module_Top}' ? (${standalone_toExpr(t)}) : ` : '') + '(null)'
});
const standalone_toExpr = v => standalone_isSignal(v) ? v.signal : v == null ? null : standalone_$(v);
const standalone_mult = (sign, value) => value === 0 ? 0 : standalone_isSignal(sign) ? {
  signal: `(${sign.signal}) * ${value}`
} : {
  value: sign * value
};
const standalone_patch = (value, base) => {
  const s = value.signal;
  return s && s.endsWith('(null)') ? {
    signal: s.slice(0, -6) + base.signal
  } : value;
};

function standalone_fallback(prop, config, axisConfig, style) {
  let styleProp;
  if (config && standalone_vega_util_module_has(config, prop)) {
    return config[prop];
  } else if (standalone_vega_util_module_has(axisConfig, prop)) {
    return axisConfig[prop];
  } else if (prop.startsWith('title')) {
    switch (prop) {
      case 'titleColor':
        styleProp = 'fill';
        break;
      case 'titleFont':
      case 'titleFontSize':
      case 'titleFontWeight':
        styleProp = prop[5].toLowerCase() + prop.slice(6);
    }
    return style[standalone_GuideTitleStyle][styleProp];
  } else if (prop.startsWith('label')) {
    switch (prop) {
      case 'labelColor':
        styleProp = 'fill';
        break;
      case 'labelFont':
      case 'labelFontSize':
        styleProp = prop[5].toLowerCase() + prop.slice(6);
    }
    return style[standalone_GuideLabelStyle][styleProp];
  }
  return null;
}
function standalone_vega_parser_module_keys(objects) {
  const map = {};
  for (const obj of objects) {
    if (!obj) continue;
    for (const key in obj) map[key] = 1;
  }
  return Object.keys(map);
}
function standalone_axisConfig (spec, scope) {
  var config = scope.config,
    style = config.style,
    axis = config.axis,
    band = scope.scaleType(spec.scale) === 'band' && config.axisBand,
    orient = spec.orient,
    xy,
    or,
    key;
  if (standalone_isSignal(orient)) {
    const xyKeys = standalone_vega_parser_module_keys([config.axisX, config.axisY]),
      orientKeys = standalone_vega_parser_module_keys([config.axisTop, config.axisBottom, config.axisLeft, config.axisRight]);
    xy = {};
    for (key of xyKeys) {
      xy[key] = standalone_ifX(orient, standalone_fallback(key, config.axisX, axis, style), standalone_fallback(key, config.axisY, axis, style));
    }
    or = {};
    for (key of orientKeys) {
      or[key] = standalone_ifOrient(orient.signal, standalone_fallback(key, config.axisTop, axis, style), standalone_fallback(key, config.axisBottom, axis, style), standalone_fallback(key, config.axisLeft, axis, style), standalone_fallback(key, config.axisRight, axis, style));
    }
  } else {
    xy = orient === standalone_vega_parser_module_Top || orient === standalone_vega_parser_module_Bottom ? config.axisX : config.axisY;
    or = config['axis' + orient[0].toUpperCase() + orient.slice(1)];
  }
  const result = xy || or || band ? standalone_extend({}, axis, xy, or, band) : axis;
  return result;
}

function standalone_axisDomain (spec, config, userEncode, dataRef) {
  const _ = standalone_vega_parser_module_lookup(spec, config),
    orient = spec.orient;
  let enter, update;
  const encode = {
    enter: enter = {
      opacity: standalone_vega_parser_module_zero
    },
    update: update = {
      opacity: standalone_vega_parser_module_one
    },
    exit: {
      opacity: standalone_vega_parser_module_zero
    }
  };
  standalone_addEncoders(encode, {
    stroke: _('domainColor'),
    strokeCap: _('domainCap'),
    strokeDash: _('domainDash'),
    strokeDashOffset: _('domainDashOffset'),
    strokeWidth: _('domainWidth'),
    strokeOpacity: _('domainOpacity')
  });
  const pos0 = standalone_position(spec, 0);
  const pos1 = standalone_position(spec, 1);
  enter.x = update.x = standalone_ifX(orient, pos0, standalone_vega_parser_module_zero);
  enter.x2 = update.x2 = standalone_ifX(orient, pos1);
  enter.y = update.y = standalone_ifY(orient, pos0, standalone_vega_parser_module_zero);
  enter.y2 = update.y2 = standalone_ifY(orient, pos1);
  return standalone_guideMark({
    type: standalone_RuleMark,
    role: standalone_AxisDomainRole,
    from: dataRef,
    encode
  }, userEncode);
}
function standalone_position(spec, pos) {
  return {
    scale: spec.scale,
    range: pos
  };
}

function standalone_axisGrid (spec, config, userEncode, dataRef, band) {
  const _ = standalone_vega_parser_module_lookup(spec, config),
    orient = spec.orient,
    vscale = spec.gridScale,
    sign = standalone_getSign(orient, 1, -1),
    offset = standalone_vega_parser_module_offsetValue(spec.offset, sign);
  let enter, exit, update;
  const encode = {
    enter: enter = {
      opacity: standalone_vega_parser_module_zero
    },
    update: update = {
      opacity: standalone_vega_parser_module_one
    },
    exit: exit = {
      opacity: standalone_vega_parser_module_zero
    }
  };
  standalone_addEncoders(encode, {
    stroke: _('gridColor'),
    strokeCap: _('gridCap'),
    strokeDash: _('gridDash'),
    strokeDashOffset: _('gridDashOffset'),
    strokeOpacity: _('gridOpacity'),
    strokeWidth: _('gridWidth')
  });
  const tickPos = {
    scale: spec.scale,
    field: standalone_Value,
    band: band.band,
    extra: band.extra,
    offset: band.offset,
    round: _('tickRound')
  };
  const sz = standalone_ifX(orient, {
    signal: 'height'
  }, {
    signal: 'width'
  });
  const gridStart = vscale ? {
    scale: vscale,
    range: 0,
    mult: sign,
    offset: offset
  } : {
    value: 0,
    offset: offset
  };
  const gridEnd = vscale ? {
    scale: vscale,
    range: 1,
    mult: sign,
    offset: offset
  } : standalone_extend(sz, {
    mult: sign,
    offset: offset
  });
  enter.x = update.x = standalone_ifX(orient, tickPos, gridStart);
  enter.y = update.y = standalone_ifY(orient, tickPos, gridStart);
  enter.x2 = update.x2 = standalone_ifY(orient, gridEnd);
  enter.y2 = update.y2 = standalone_ifX(orient, gridEnd);
  exit.x = standalone_ifX(orient, tickPos);
  exit.y = standalone_ifY(orient, tickPos);
  return standalone_guideMark({
    type: standalone_RuleMark,
    role: standalone_AxisGridRole,
    key: standalone_Value,
    from: dataRef,
    encode
  }, userEncode);
}
function standalone_vega_parser_module_offsetValue(offset, sign) {
  if (sign === 1) ; else if (!standalone_vega_util_module_isObject(offset)) {
    offset = standalone_isSignal(sign) ? {
      signal: `(${sign.signal}) * (${offset || 0})`
    } : sign * (offset || 0);
  } else {
    let entry = offset = standalone_extend({}, offset);
    while (entry.mult != null) {
      if (!standalone_vega_util_module_isObject(entry.mult)) {
        entry.mult = standalone_isSignal(sign) // no offset if sign === 1
        ? {
          signal: `(${entry.mult}) * (${sign.signal})`
        } : entry.mult * sign;
        return offset;
      } else {
        entry = entry.mult = standalone_extend({}, entry.mult);
      }
    }
    entry.mult = sign;
  }
  return offset;
}

function standalone_axisTicks (spec, config, userEncode, dataRef, size, band) {
  const _ = standalone_vega_parser_module_lookup(spec, config),
    orient = spec.orient,
    sign = standalone_getSign(orient, -1, 1);
  let enter, exit, update;
  const encode = {
    enter: enter = {
      opacity: standalone_vega_parser_module_zero
    },
    update: update = {
      opacity: standalone_vega_parser_module_one
    },
    exit: exit = {
      opacity: standalone_vega_parser_module_zero
    }
  };
  standalone_addEncoders(encode, {
    stroke: _('tickColor'),
    strokeCap: _('tickCap'),
    strokeDash: _('tickDash'),
    strokeDashOffset: _('tickDashOffset'),
    strokeOpacity: _('tickOpacity'),
    strokeWidth: _('tickWidth')
  });
  const tickSize = standalone_encoder(size);
  tickSize.mult = sign;
  const tickPos = {
    scale: spec.scale,
    field: standalone_Value,
    band: band.band,
    extra: band.extra,
    offset: band.offset,
    round: _('tickRound')
  };
  update.y = enter.y = standalone_ifX(orient, standalone_vega_parser_module_zero, tickPos);
  update.y2 = enter.y2 = standalone_ifX(orient, tickSize);
  exit.x = standalone_ifX(orient, tickPos);
  update.x = enter.x = standalone_ifY(orient, standalone_vega_parser_module_zero, tickPos);
  update.x2 = enter.x2 = standalone_ifY(orient, tickSize);
  exit.y = standalone_ifY(orient, tickPos);
  return standalone_guideMark({
    type: standalone_RuleMark,
    role: standalone_AxisTickRole,
    key: standalone_Value,
    from: dataRef,
    encode
  }, userEncode);
}

function standalone_flushExpr(scale, threshold, a, b, c) {
  return {
    signal: 'flush(range("' + scale + '"), ' + 'scale("' + scale + '", datum.value), ' + threshold + ',' + a + ',' + b + ',' + c + ')'
  };
}
function standalone_axisLabels (spec, config, userEncode, dataRef, size, band) {
  const _ = standalone_vega_parser_module_lookup(spec, config),
    orient = spec.orient,
    scale = spec.scale,
    sign = standalone_getSign(orient, -1, 1),
    flush = standalone_deref(_('labelFlush')),
    flushOffset = standalone_deref(_('labelFlushOffset')),
    labelAlign = _('labelAlign'),
    labelBaseline = _('labelBaseline');
  let flushOn = flush === 0 || !!flush,
    update;
  const tickSize = standalone_encoder(size);
  tickSize.mult = sign;
  tickSize.offset = standalone_encoder(_('labelPadding') || 0);
  tickSize.offset.mult = sign;
  const tickPos = {
    scale: scale,
    field: standalone_Value,
    band: 0.5,
    offset: standalone_extendOffset(band.offset, _('labelOffset'))
  };
  const align = standalone_ifX(orient, flushOn ? standalone_flushExpr(scale, flush, '"left"', '"right"', '"center"') : {
    value: 'center'
  }, standalone_ifRight(orient, 'left', 'right'));
  const baseline = standalone_ifX(orient, standalone_ifTop(orient, 'bottom', 'top'), flushOn ? standalone_flushExpr(scale, flush, '"top"', '"bottom"', '"middle"') : {
    value: 'middle'
  });
  const offsetExpr = standalone_flushExpr(scale, flush, `-(${flushOffset})`, flushOffset, 0);
  flushOn = flushOn && flushOffset;
  const enter = {
    opacity: standalone_vega_parser_module_zero,
    x: standalone_ifX(orient, tickPos, tickSize),
    y: standalone_ifY(orient, tickPos, tickSize)
  };
  const encode = {
    enter: enter,
    update: update = {
      opacity: standalone_vega_parser_module_one,
      text: {
        field: standalone_vega_parser_module_Label
      },
      x: enter.x,
      y: enter.y,
      align,
      baseline
    },
    exit: {
      opacity: standalone_vega_parser_module_zero,
      x: enter.x,
      y: enter.y
    }
  };
  standalone_addEncoders(encode, {
    dx: !labelAlign && flushOn ? standalone_ifX(orient, offsetExpr) : null,
    dy: !labelBaseline && flushOn ? standalone_ifY(orient, offsetExpr) : null
  });
  standalone_addEncoders(encode, {
    angle: _('labelAngle'),
    fill: _('labelColor'),
    fillOpacity: _('labelOpacity'),
    font: _('labelFont'),
    fontSize: _('labelFontSize'),
    fontWeight: _('labelFontWeight'),
    fontStyle: _('labelFontStyle'),
    limit: _('labelLimit'),
    lineHeight: _('labelLineHeight')
  }, {
    align: labelAlign,
    baseline: labelBaseline
  });
  const bound = _('labelBound');
  let overlap = _('labelOverlap');

  // if overlap method or bound defined, request label overlap removal
  overlap = overlap || bound ? {
    separation: _('labelSeparation'),
    method: overlap,
    order: 'datum.index',
    bound: bound ? {
      scale,
      orient,
      tolerance: bound
    } : null
  } : undefined;
  if (update.align !== align) {
    update.align = standalone_patch(update.align, align);
  }
  if (update.baseline !== baseline) {
    update.baseline = standalone_patch(update.baseline, baseline);
  }
  return standalone_guideMark({
    type: standalone_TextMark,
    role: standalone_AxisLabelRole,
    style: standalone_GuideLabelStyle,
    key: standalone_Value,
    from: dataRef,
    encode,
    overlap
  }, userEncode);
}

function standalone_axisTitle (spec, config, userEncode, dataRef) {
  const _ = standalone_vega_parser_module_lookup(spec, config),
    orient = spec.orient,
    sign = standalone_getSign(orient, -1, 1);
  let enter, update;
  const encode = {
    enter: enter = {
      opacity: standalone_vega_parser_module_zero,
      anchor: standalone_encoder(_('titleAnchor', null)),
      align: {
        signal: standalone_alignExpr$1
      }
    },
    update: update = standalone_extend({}, enter, {
      opacity: standalone_vega_parser_module_one,
      text: standalone_encoder(spec.title)
    }),
    exit: {
      opacity: standalone_vega_parser_module_zero
    }
  };
  const titlePos = {
    signal: `lerp(range("${spec.scale}"), ${standalone_anchorExpr(0, 1, 0.5)})`
  };
  update.x = standalone_ifX(orient, titlePos);
  update.y = standalone_ifY(orient, titlePos);
  enter.angle = standalone_ifX(orient, standalone_vega_parser_module_zero, standalone_mult(sign, 90));
  enter.baseline = standalone_ifX(orient, standalone_ifTop(orient, standalone_vega_parser_module_Bottom, standalone_vega_parser_module_Top), {
    value: standalone_vega_parser_module_Bottom
  });
  update.angle = enter.angle;
  update.baseline = enter.baseline;
  standalone_addEncoders(encode, {
    fill: _('titleColor'),
    fillOpacity: _('titleOpacity'),
    font: _('titleFont'),
    fontSize: _('titleFontSize'),
    fontStyle: _('titleFontStyle'),
    fontWeight: _('titleFontWeight'),
    limit: _('titleLimit'),
    lineHeight: _('titleLineHeight')
  }, {
    // require update
    align: _('titleAlign'),
    angle: _('titleAngle'),
    baseline: _('titleBaseline')
  });
  standalone_autoLayout(_, orient, encode, userEncode);
  encode.update.align = standalone_patch(encode.update.align, enter.align);
  encode.update.angle = standalone_patch(encode.update.angle, enter.angle);
  encode.update.baseline = standalone_patch(encode.update.baseline, enter.baseline);
  return standalone_guideMark({
    type: standalone_TextMark,
    role: standalone_AxisTitleRole,
    style: standalone_GuideTitleStyle,
    from: dataRef,
    encode
  }, userEncode);
}
function standalone_autoLayout(_, orient, encode, userEncode) {
  const auto = (value, dim) => value != null ? (encode.update[dim] = standalone_patch(standalone_encoder(value), encode.update[dim]), false) : !standalone_vega_parser_module_has(dim, userEncode) ? true : false;
  const autoY = auto(_('titleX'), 'x'),
    autoX = auto(_('titleY'), 'y');
  encode.enter.auto = autoX === autoY ? standalone_encoder(autoX) : standalone_ifX(orient, standalone_encoder(autoX), standalone_encoder(autoY));
}

function standalone_parseAxis (spec, scope) {
  const config = standalone_axisConfig(spec, scope),
    encode = spec.encode || {},
    axisEncode = encode.axis || {},
    name = axisEncode.name || undefined,
    interactive = axisEncode.interactive,
    style = axisEncode.style,
    _ = standalone_vega_parser_module_lookup(spec, config),
    band = standalone_tickBand(_);

  // single-element data source for axis group
  const datum = {
    scale: spec.scale,
    ticks: !!_('ticks'),
    labels: !!_('labels'),
    grid: !!_('grid'),
    domain: !!_('domain'),
    title: spec.title != null
  };
  const dataRef = standalone_ref(scope.add(standalone_vega_parser_module_Collect({}, [datum])));

  // data source for axis ticks
  const ticksRef = standalone_ref(scope.add(standalone_vega_parser_module_AxisTicks({
    scale: scope.scaleRef(spec.scale),
    extra: scope.property(band.extra),
    count: scope.objectProperty(spec.tickCount),
    values: scope.objectProperty(spec.values),
    minstep: scope.property(spec.tickMinStep),
    formatType: scope.property(spec.formatType),
    formatSpecifier: scope.property(spec.format)
  })));

  // generate axis marks
  const children = [];
  let size;

  // include axis gridlines if requested
  if (datum.grid) {
    children.push(standalone_axisGrid(spec, config, encode.grid, ticksRef, band));
  }

  // include axis ticks if requested
  if (datum.ticks) {
    size = _('tickSize');
    children.push(standalone_axisTicks(spec, config, encode.ticks, ticksRef, size, band));
  }

  // include axis labels if requested
  if (datum.labels) {
    size = datum.ticks ? size : 0;
    children.push(standalone_axisLabels(spec, config, encode.labels, ticksRef, size, band));
  }

  // include axis domain path if requested
  if (datum.domain) {
    children.push(standalone_axisDomain(spec, config, encode.domain, dataRef));
  }

  // include axis title if defined
  if (datum.title) {
    children.push(standalone_axisTitle(spec, config, encode.title, dataRef));
  }

  // parse axis specification
  return standalone_parseMark(standalone_guideGroup({
    role: standalone_vega_parser_module_AxisRole,
    from: dataRef,
    encode: standalone_extendEncode(standalone_buildAxisEncode(_, spec), axisEncode, standalone_vega_parser_module_Skip),
    marks: children,
    aria: _('aria'),
    description: _('description'),
    zindex: _('zindex'),
    name,
    interactive,
    style
  }), scope);
}
function standalone_buildAxisEncode(_, spec) {
  const encode = {
    enter: {},
    update: {}
  };
  standalone_addEncoders(encode, {
    orient: _('orient'),
    offset: _('offset') || 0,
    position: standalone_vega_parser_module_value(spec.position, 0),
    titlePadding: _('titlePadding'),
    minExtent: _('minExtent'),
    maxExtent: _('maxExtent'),
    range: {
      signal: `abs(span(range("${spec.scale}")))`
    },
    translate: _('translate'),
    // accessibility support
    format: spec.format,
    formatType: spec.formatType
  });
  return encode;
}

function standalone_parseScope (spec, scope, preprocessed) {
  const signals = standalone_array(spec.signals),
    scales = standalone_array(spec.scales);

  // parse signal definitions, if not already preprocessed
  if (!preprocessed) signals.forEach(_ => standalone_parseSignal(_, scope));

  // parse cartographic projection definitions
  standalone_array(spec.projections).forEach(_ => standalone_parseProjection(_, scope));

  // initialize scale references
  scales.forEach(_ => standalone_initScale(_, scope));

  // parse data sources
  standalone_array(spec.data).forEach(_ => standalone_parseData(_, scope));

  // parse scale definitions
  scales.forEach(_ => standalone_parseScale(_, scope));

  // parse signal updates
  (preprocessed || signals).forEach(_ => standalone_parseSignalUpdates(_, scope));

  // parse axis definitions
  standalone_array(spec.axes).forEach(_ => standalone_parseAxis(_, scope));

  // parse mark definitions
  standalone_array(spec.marks).forEach(_ => standalone_parseMark(_, scope));

  // parse legend definitions
  standalone_array(spec.legends).forEach(_ => standalone_parseLegend(_, scope));

  // parse title, if defined
  if (spec.title) standalone_parseTitle(spec.title, scope);

  // parse collected lambda (anonymous) expressions
  scope.parseLambdas();
  return scope;
}

const standalone_rootEncode = spec => standalone_extendEncode({
  enter: {
    x: {
      value: 0
    },
    y: {
      value: 0
    }
  },
  update: {
    width: {
      signal: 'width'
    },
    height: {
      signal: 'height'
    }
  }
}, spec);
function standalone_parseView(spec, scope) {
  const config = scope.config;

  // add scenegraph root
  const root = standalone_ref(scope.root = scope.add(standalone_operator()));

  // parse top-level signal definitions
  const signals = standalone_collectSignals(spec, config);
  signals.forEach(_ => standalone_parseSignal(_, scope));

  // assign description, event, legend, and locale configuration
  scope.description = spec.description || config.description;
  scope.eventConfig = config.events;
  scope.legends = scope.objectProperty(config.legend && config.legend.layout);
  scope.locale = config.locale;

  // store root group item
  const input = scope.add(standalone_vega_parser_module_Collect());

  // encode root group item
  const encode = scope.add(standalone_vega_parser_module_Encode(standalone_parseEncode(standalone_rootEncode(spec.encode), standalone_GroupMark, standalone_vega_parser_module_FrameRole, spec.style, scope, {
    pulse: standalone_ref(input)
  })));

  // perform view layout
  const parent = scope.add(standalone_vega_parser_module_ViewLayout({
    layout: scope.objectProperty(spec.layout),
    legends: scope.legends,
    autosize: scope.signalRef('autosize'),
    mark: root,
    pulse: standalone_ref(encode)
  }));
  scope.operators.pop();

  // parse remainder of specification
  scope.pushState(standalone_ref(encode), standalone_ref(parent), null);
  standalone_parseScope(spec, scope, signals);
  scope.operators.push(parent);

  // bound / render / sieve root item
  let op = scope.add(standalone_vega_parser_module_Bound({
    mark: root,
    pulse: standalone_ref(parent)
  }));
  op = scope.add(standalone_vega_parser_module_Render({
    pulse: standalone_ref(op)
  }));
  op = scope.add(standalone_vega_parser_module_Sieve({
    pulse: standalone_ref(op)
  }));

  // track metadata for root item
  scope.addData('root', new standalone_DataScope(scope, input, input, op));
  return scope;
}
function standalone_signalObject(name, value) {
  return value && value.signal ? {
    name,
    update: value.signal
  } : {
    name,
    value
  };
}

/**
 * Collect top-level signals, merging values as needed. Signals
 * defined in the config signals arrays are added only if that
 * signal is not explicitly defined in the specification.
 * Built-in signals (autosize, background, padding, width, height)
 * receive special treatment. They are initialized using the
 * top-level spec property, or, if undefined in the spec, using
 * the corresponding top-level config property. If this property
 * is a signal reference object, the signal expression maps to the
 * signal 'update' property. If the spec's top-level signal array
 * contains an entry that matches a built-in signal, that entry
 * will be merged with the built-in specification, potentially
 * overwriting existing 'value' or 'update' properties.
 */
function standalone_collectSignals(spec, config) {
  const _ = name => standalone_vega_parser_module_value(spec[name], config[name]),
    signals = [standalone_signalObject('background', _('background')), standalone_signalObject('autosize', standalone_parseAutosize(_('autosize'))), standalone_signalObject('padding', standalone_parsePadding(_('padding'))), standalone_signalObject('width', _('width') || 0), standalone_signalObject('height', _('height') || 0)],
    pre = signals.reduce((p, s) => (p[s.name] = s, p), {}),
    map = {};

  // add spec signal array
  standalone_array(spec.signals).forEach(s => {
    if (standalone_vega_util_module_has(pre, s.name)) {
      // merge if built-in signal
      s = standalone_extend(pre[s.name], s);
    } else {
      // otherwise add to signal list
      signals.push(s);
    }
    map[s.name] = s;
  });

  // add config signal array
  standalone_array(config.signals).forEach(s => {
    if (!standalone_vega_util_module_has(map, s.name) && !standalone_vega_util_module_has(pre, s.name)) {
      // add to signal list if not already defined
      signals.push(s);
    }
  });
  return signals;
}

function standalone_Scope(config, options) {
  this.config = config || {};
  this.options = options || {};
  this.bindings = [];
  this.field = {};
  this.signals = {};
  this.lambdas = {};
  this.scales = {};
  this.events = {};
  this.data = {};
  this.streams = [];
  this.updates = [];
  this.operators = [];
  this.eventConfig = null;
  this.locale = null;
  this._id = 0;
  this._subid = 0;
  this._nextsub = [0];
  this._parent = [];
  this._encode = [];
  this._lookup = [];
  this._markpath = [];
}
function standalone_Subscope(scope) {
  this.config = scope.config;
  this.options = scope.options;
  this.legends = scope.legends;
  this.field = Object.create(scope.field);
  this.signals = Object.create(scope.signals);
  this.lambdas = Object.create(scope.lambdas);
  this.scales = Object.create(scope.scales);
  this.events = Object.create(scope.events);
  this.data = Object.create(scope.data);
  this.streams = [];
  this.updates = [];
  this.operators = [];
  this._id = 0;
  this._subid = ++scope._nextsub[0];
  this._nextsub = scope._nextsub;
  this._parent = scope._parent.slice();
  this._encode = scope._encode.slice();
  this._lookup = scope._lookup.slice();
  this._markpath = scope._markpath;
}
standalone_Scope.prototype = standalone_Subscope.prototype = {
  parse(spec) {
    return standalone_parseScope(spec, this);
  },
  fork() {
    return new standalone_Subscope(this);
  },
  isSubscope() {
    return this._subid > 0;
  },
  toRuntime() {
    this.finish();
    return {
      description: this.description,
      operators: this.operators,
      streams: this.streams,
      updates: this.updates,
      bindings: this.bindings,
      eventConfig: this.eventConfig,
      locale: this.locale
    };
  },
  id() {
    return (this._subid ? this._subid + ':' : 0) + this._id++;
  },
  add(op) {
    this.operators.push(op);
    op.id = this.id();
    // if pre-registration references exist, resolve them now
    if (op.refs) {
      op.refs.forEach(ref => {
        ref.$ref = op.id;
      });
      op.refs = null;
    }
    return op;
  },
  proxy(op) {
    const vref = op instanceof standalone_Entry ? standalone_ref(op) : op;
    return this.add(standalone_vega_parser_module_Proxy({
      value: vref
    }));
  },
  addStream(stream) {
    this.streams.push(stream);
    stream.id = this.id();
    return stream;
  },
  addUpdate(update) {
    this.updates.push(update);
    return update;
  },
  // Apply metadata
  finish() {
    let name, ds;

    // annotate root
    if (this.root) this.root.root = true;

    // annotate signals
    for (name in this.signals) {
      this.signals[name].signal = name;
    }

    // annotate scales
    for (name in this.scales) {
      this.scales[name].scale = name;
    }

    // annotate data sets
    function annotate(op, name, type) {
      let data, list;
      if (op) {
        data = op.data || (op.data = {});
        list = data[name] || (data[name] = []);
        list.push(type);
      }
    }
    for (name in this.data) {
      ds = this.data[name];
      annotate(ds.input, name, 'input');
      annotate(ds.output, name, 'output');
      annotate(ds.values, name, 'values');
      for (const field in ds.index) {
        annotate(ds.index[field], name, 'index:' + field);
      }
    }
    return this;
  },
  // ----

  pushState(encode, parent, lookup) {
    this._encode.push(standalone_ref(this.add(standalone_vega_parser_module_Sieve({
      pulse: encode
    }))));
    this._parent.push(parent);
    this._lookup.push(lookup ? standalone_ref(this.proxy(lookup)) : null);
    this._markpath.push(-1);
  },
  popState() {
    this._encode.pop();
    this._parent.pop();
    this._lookup.pop();
    this._markpath.pop();
  },
  parent() {
    return standalone_peek(this._parent);
  },
  encode() {
    return standalone_peek(this._encode);
  },
  lookup() {
    return standalone_peek(this._lookup);
  },
  markpath() {
    const p = this._markpath;
    return ++p[p.length - 1];
  },
  // ----

  fieldRef(field, name) {
    if (standalone_vega_util_module_isString(field)) return standalone_fieldRef$1(field, name);
    if (!field.signal) {
      standalone_vega_util_module_error('Unsupported field reference: ' + standalone_$(field));
    }
    const s = field.signal;
    let f = this.field[s];
    if (!f) {
      const params = {
        name: this.signalRef(s)
      };
      if (name) params.as = name;
      this.field[s] = f = standalone_ref(this.add(standalone_vega_parser_module_Field(params)));
    }
    return f;
  },
  compareRef(cmp) {
    let signal = false;
    const check = _ => standalone_isSignal(_) ? (signal = true, this.signalRef(_.signal)) : standalone_isExpr$1(_) ? (signal = true, this.exprRef(_.expr)) : _;
    const fields = standalone_array(cmp.field).map(check),
      orders = standalone_array(cmp.order).map(check);
    return signal ? standalone_ref(this.add(standalone_vega_parser_module_Compare({
      fields: fields,
      orders: orders
    }))) : standalone_compareRef(fields, orders);
  },
  keyRef(fields, flat) {
    let signal = false;
    const check = _ => standalone_isSignal(_) ? (signal = true, standalone_ref(sig[_.signal])) : _;
    const sig = this.signals;
    fields = standalone_array(fields).map(check);
    return signal ? standalone_ref(this.add(standalone_vega_parser_module_Key({
      fields: fields,
      flat: flat
    }))) : standalone_keyRef(fields, flat);
  },
  sortRef(sort) {
    if (!sort) return sort;

    // including id ensures stable sorting
    const a = standalone_aggrField(sort.op, sort.field),
      o = sort.order || standalone_Ascending;
    return o.signal ? standalone_ref(this.add(standalone_vega_parser_module_Compare({
      fields: a,
      orders: this.signalRef(o.signal)
    }))) : standalone_compareRef(a, o);
  },
  // ----

  event(source, type) {
    const key = source + ':' + type;
    if (!this.events[key]) {
      const id = this.id();
      this.streams.push({
        id: id,
        source: source,
        type: type
      });
      this.events[key] = id;
    }
    return this.events[key];
  },
  // ----

  hasOwnSignal(name) {
    return standalone_vega_util_module_has(this.signals, name);
  },
  addSignal(name, value) {
    if (this.hasOwnSignal(name)) {
      standalone_vega_util_module_error('Duplicate signal name: ' + standalone_$(name));
    }
    const op = value instanceof standalone_Entry ? value : this.add(standalone_operator(value));
    return this.signals[name] = op;
  },
  getSignal(name) {
    if (!this.signals[name]) {
      standalone_vega_util_module_error('Unrecognized signal name: ' + standalone_$(name));
    }
    return this.signals[name];
  },
  signalRef(s) {
    if (this.signals[s]) {
      return standalone_ref(this.signals[s]);
    } else if (!standalone_vega_util_module_has(this.lambdas, s)) {
      this.lambdas[s] = this.add(standalone_operator(null));
    }
    return standalone_ref(this.lambdas[s]);
  },
  parseLambdas() {
    const code = Object.keys(this.lambdas);
    for (let i = 0, n = code.length; i < n; ++i) {
      const s = code[i],
        e = standalone_vega_functions_module_parser(s, this),
        op = this.lambdas[s];
      op.params = e.$params;
      op.update = e.$expr;
    }
  },
  property(spec) {
    return spec && spec.signal ? this.signalRef(spec.signal) : spec;
  },
  objectProperty(spec) {
    return !spec || !standalone_vega_util_module_isObject(spec) ? spec : this.signalRef(spec.signal || standalone_propertyLambda(spec));
  },
  exprRef(code, name) {
    const params = {
      expr: standalone_vega_functions_module_parser(code, this)
    };
    if (name) params.expr.$name = name;
    return standalone_ref(this.add(standalone_vega_parser_module_Expression(params)));
  },
  addBinding(name, bind) {
    if (!this.bindings) {
      standalone_vega_util_module_error('Nested signals do not support binding: ' + standalone_$(name));
    }
    this.bindings.push(standalone_extend({
      signal: name
    }, bind));
  },
  // ----

  addScaleProj(name, transform) {
    if (standalone_vega_util_module_has(this.scales, name)) {
      standalone_vega_util_module_error('Duplicate scale or projection name: ' + standalone_$(name));
    }
    this.scales[name] = this.add(transform);
  },
  addScale(name, params) {
    this.addScaleProj(name, standalone_vega_parser_module_Scale(params));
  },
  addProjection(name, params) {
    this.addScaleProj(name, standalone_vega_parser_module_Projection(params));
  },
  getScale(name) {
    if (!this.scales[name]) {
      standalone_vega_util_module_error('Unrecognized scale name: ' + standalone_$(name));
    }
    return this.scales[name];
  },
  scaleRef(name) {
    return standalone_ref(this.getScale(name));
  },
  scaleType(name) {
    return this.getScale(name).params.type;
  },
  projectionRef(name) {
    return this.scaleRef(name);
  },
  projectionType(name) {
    return this.scaleType(name);
  },
  // ----

  addData(name, dataScope) {
    if (standalone_vega_util_module_has(this.data, name)) {
      standalone_vega_util_module_error('Duplicate data set name: ' + standalone_$(name));
    }
    return this.data[name] = dataScope;
  },
  getData(name) {
    if (!this.data[name]) {
      standalone_vega_util_module_error('Undefined data set name: ' + standalone_$(name));
    }
    return this.data[name];
  },
  addDataPipeline(name, entries) {
    if (standalone_vega_util_module_has(this.data, name)) {
      standalone_vega_util_module_error('Duplicate data set name: ' + standalone_$(name));
    }
    return this.addData(name, standalone_DataScope.fromEntries(this, entries));
  }
};
function standalone_propertyLambda(spec) {
  return (standalone_vega_util_module_isArray(spec) ? standalone_arrayLambda : standalone_objectLambda)(spec);
}
function standalone_arrayLambda(array) {
  const n = array.length;
  let code = '[';
  for (let i = 0; i < n; ++i) {
    const value = array[i];
    code += (i > 0 ? ',' : '') + (standalone_vega_util_module_isObject(value) ? value.signal || standalone_propertyLambda(value) : standalone_$(value));
  }
  return code + ']';
}
function standalone_objectLambda(obj) {
  let code = '{',
    i = 0,
    key,
    value;
  for (key in obj) {
    value = obj[key];
    code += (++i > 1 ? ',' : '') + standalone_$(key) + ':' + (standalone_vega_util_module_isObject(value) ? value.signal || standalone_propertyLambda(value) : standalone_$(value));
  }
  return code + '}';
}

/**
 * Standard configuration defaults for Vega specification parsing.
 * Users can provide their own (sub-)set of these default values
 * by passing in a config object to the top-level parse method.
 */
function standalone_defaults () {
  const defaultFont = 'sans-serif',
    defaultSymbolSize = 30,
    defaultStrokeWidth = 2,
    defaultColor = '#4c78a8',
    black = '#000',
    gray = '#888',
    lightGray = '#ddd';
  return {
    // default visualization description
    description: 'Vega visualization',
    // default padding around visualization
    padding: 0,
    // default for automatic sizing; options: 'none', 'pad', 'fit'
    // or provide an object (e.g., {'type': 'pad', 'resize': true})
    autosize: 'pad',
    // default view background color
    // covers the entire view component
    background: null,
    // default event handling configuration
    // preventDefault for view-sourced event types except 'wheel'
    events: {
      defaults: {
        allow: ['wheel']
      }
    },
    // defaults for top-level group marks
    // accepts mark properties (fill, stroke, etc)
    // covers the data rectangle within group width/height
    group: null,
    // defaults for basic mark types
    // each subset accepts mark properties (fill, stroke, etc)
    mark: null,
    arc: {
      fill: defaultColor
    },
    area: {
      fill: defaultColor
    },
    image: null,
    line: {
      stroke: defaultColor,
      strokeWidth: defaultStrokeWidth
    },
    path: {
      stroke: defaultColor
    },
    rect: {
      fill: defaultColor
    },
    rule: {
      stroke: black
    },
    shape: {
      stroke: defaultColor
    },
    symbol: {
      fill: defaultColor,
      size: 64
    },
    text: {
      fill: black,
      font: defaultFont,
      fontSize: 11
    },
    trail: {
      fill: defaultColor,
      size: defaultStrokeWidth
    },
    // style definitions
    style: {
      // axis & legend labels
      'guide-label': {
        fill: black,
        font: defaultFont,
        fontSize: 10
      },
      // axis & legend titles
      'guide-title': {
        fill: black,
        font: defaultFont,
        fontSize: 11,
        fontWeight: 'bold'
      },
      // headers, including chart title
      'group-title': {
        fill: black,
        font: defaultFont,
        fontSize: 13,
        fontWeight: 'bold'
      },
      // chart subtitle
      'group-subtitle': {
        fill: black,
        font: defaultFont,
        fontSize: 12
      },
      // defaults for styled point marks in Vega-Lite
      point: {
        size: defaultSymbolSize,
        strokeWidth: defaultStrokeWidth,
        shape: 'circle'
      },
      circle: {
        size: defaultSymbolSize,
        strokeWidth: defaultStrokeWidth
      },
      square: {
        size: defaultSymbolSize,
        strokeWidth: defaultStrokeWidth,
        shape: 'square'
      },
      // defaults for styled group marks in Vega-Lite
      cell: {
        fill: 'transparent',
        stroke: lightGray
      },
      view: {
        fill: 'transparent'
      }
    },
    // defaults for title
    title: {
      orient: 'top',
      anchor: 'middle',
      offset: 4,
      subtitlePadding: 3
    },
    // defaults for axes
    axis: {
      minExtent: 0,
      maxExtent: 200,
      bandPosition: 0.5,
      domain: true,
      domainWidth: 1,
      domainColor: gray,
      grid: false,
      gridWidth: 1,
      gridColor: lightGray,
      labels: true,
      labelAngle: 0,
      labelLimit: 180,
      labelOffset: 0,
      labelPadding: 2,
      ticks: true,
      tickColor: gray,
      tickOffset: 0,
      tickRound: true,
      tickSize: 5,
      tickWidth: 1,
      titlePadding: 4
    },
    // correction for centering bias
    axisBand: {
      tickOffset: -0.5
    },
    // defaults for cartographic projection
    projection: {
      type: 'mercator'
    },
    // defaults for legends
    legend: {
      orient: 'right',
      padding: 0,
      gridAlign: 'each',
      columnPadding: 10,
      rowPadding: 2,
      symbolDirection: 'vertical',
      gradientDirection: 'vertical',
      gradientLength: 200,
      gradientThickness: 16,
      gradientStrokeColor: lightGray,
      gradientStrokeWidth: 0,
      gradientLabelOffset: 2,
      labelAlign: 'left',
      labelBaseline: 'middle',
      labelLimit: 160,
      labelOffset: 4,
      labelOverlap: true,
      symbolLimit: 30,
      symbolType: 'circle',
      symbolSize: 100,
      symbolOffset: 0,
      symbolStrokeWidth: 1.5,
      symbolBaseFillColor: 'transparent',
      symbolBaseStrokeColor: gray,
      titleLimit: 180,
      titleOrient: 'top',
      titlePadding: 5,
      layout: {
        offset: 18,
        direction: 'horizontal',
        left: {
          direction: 'vertical'
        },
        right: {
          direction: 'vertical'
        }
      }
    },
    // defaults for scale ranges
    range: {
      category: {
        scheme: 'tableau10'
      },
      ordinal: {
        scheme: 'blues'
      },
      heatmap: {
        scheme: 'yellowgreenblue'
      },
      ramp: {
        scheme: 'blues'
      },
      diverging: {
        scheme: 'blueorange',
        extent: [1, 0]
      },
      symbol: ['circle', 'square', 'triangle-up', 'cross', 'diamond', 'triangle-right', 'triangle-down', 'triangle-left']
    }
  };
}

function standalone_vega_parser_module_parse (spec, config, options) {
  if (!standalone_vega_util_module_isObject(spec)) {
    standalone_vega_util_module_error('Input Vega specification must be an object.');
  }
  config = standalone_mergeConfig(standalone_defaults(), config, spec.config);
  return standalone_parseView(spec, new standalone_Scope(config, options)).toRuntime();
}



;// ../../node_modules/vega/build/vega.module.js





























var standalone_version = "5.30.0";

// -- Transforms -----

standalone_extend(standalone_transforms, standalone_vega_transforms_module_namespaceObject, standalone_vega_view_transforms_module_namespaceObject, standalone_vega_encode_module_namespaceObject, standalone_vega_geo_module_namespaceObject, standalone_vega_force_module_namespaceObject, standalone_vega_label_module_namespaceObject, standalone_vega_hierarchy_module_namespaceObject, standalone_vega_regression_module_namespaceObject, standalone_vega_voronoi_module_namespaceObject, standalone_vega_wordcloud_module_namespaceObject, standalone_vega_crossfilter_module_namespaceObject);



;// ../../node_modules/vega-interpreter/build/vega-interpreter.module.js
function standalone_vega_interpreter_module_adjustSpatial (item, encode, swap) {
  let t;
  if (encode.x2) {
    if (encode.x) {
      if (swap && item.x > item.x2) {
        t = item.x;
        item.x = item.x2;
        item.x2 = t;
      }
      item.width = item.x2 - item.x;
    } else {
      item.x = item.x2 - (item.width || 0);
    }
  }
  if (encode.xc) {
    item.x = item.xc - (item.width || 0) / 2;
  }
  if (encode.y2) {
    if (encode.y) {
      if (swap && item.y > item.y2) {
        t = item.y;
        item.y = item.y2;
        item.y2 = t;
      }
      item.height = item.y2 - item.y;
    } else {
      item.y = item.y2 - (item.height || 0);
    }
  }
  if (encode.yc) {
    item.y = item.yc - (item.height || 0) / 2;
  }
}

var standalone_vega_interpreter_module_Constants = {
  NaN: NaN,
  E: Math.E,
  LN2: Math.LN2,
  LN10: Math.LN10,
  LOG2E: Math.LOG2E,
  LOG10E: Math.LOG10E,
  PI: Math.PI,
  SQRT1_2: Math.SQRT1_2,
  SQRT2: Math.SQRT2,
  MIN_VALUE: Number.MIN_VALUE,
  MAX_VALUE: Number.MAX_VALUE
};

var standalone_Ops = {
  '*': (a, b) => a * b,
  '+': (a, b) => a + b,
  '-': (a, b) => a - b,
  '/': (a, b) => a / b,
  '%': (a, b) => a % b,
  '>': (a, b) => a > b,
  '<': (a, b) => a < b,
  '<=': (a, b) => a <= b,
  '>=': (a, b) => a >= b,
  '==': (a, b) => a == b,
  '!=': (a, b) => a != b,
  '===': (a, b) => a === b,
  '!==': (a, b) => a !== b,
  '&': (a, b) => a & b,
  '|': (a, b) => a | b,
  '^': (a, b) => a ^ b,
  '<<': (a, b) => a << b,
  '>>': (a, b) => a >> b,
  '>>>': (a, b) => a >>> b
};

var standalone_Unary = {
  '+': a => +a,
  '-': a => -a,
  '~': a => ~a,
  '!': a => !a
};

const standalone_vega_interpreter_module_slice = Array.prototype.slice;
const standalone_vega_interpreter_module_apply = (m, args, cast) => {
  const obj = cast ? cast(args[0]) : args[0];
  return obj[m].apply(obj, standalone_vega_interpreter_module_slice.call(args, 1));
};
const standalone_datetime = (y, m, d, H, M, S, ms) => new Date(y, m || 0, d != null ? d : 1, H || 0, M || 0, S || 0, ms || 0);
var standalone_vega_interpreter_module_Functions = {
  // math functions
  isNaN: Number.isNaN,
  isFinite: Number.isFinite,
  abs: Math.abs,
  acos: Math.acos,
  asin: Math.asin,
  atan: Math.atan,
  atan2: Math.atan2,
  ceil: Math.ceil,
  cos: Math.cos,
  exp: Math.exp,
  floor: Math.floor,
  log: Math.log,
  max: Math.max,
  min: Math.min,
  pow: Math.pow,
  random: Math.random,
  round: Math.round,
  sin: Math.sin,
  sqrt: Math.sqrt,
  tan: Math.tan,
  clamp: (a, b, c) => Math.max(b, Math.min(c, a)),
  // date functions
  now: Date.now,
  utc: Date.UTC,
  datetime: standalone_datetime,
  date: d => new Date(d).getDate(),
  day: d => new Date(d).getDay(),
  year: d => new Date(d).getFullYear(),
  month: d => new Date(d).getMonth(),
  hours: d => new Date(d).getHours(),
  minutes: d => new Date(d).getMinutes(),
  seconds: d => new Date(d).getSeconds(),
  milliseconds: d => new Date(d).getMilliseconds(),
  time: d => new Date(d).getTime(),
  timezoneoffset: d => new Date(d).getTimezoneOffset(),
  utcdate: d => new Date(d).getUTCDate(),
  utcday: d => new Date(d).getUTCDay(),
  utcyear: d => new Date(d).getUTCFullYear(),
  utcmonth: d => new Date(d).getUTCMonth(),
  utchours: d => new Date(d).getUTCHours(),
  utcminutes: d => new Date(d).getUTCMinutes(),
  utcseconds: d => new Date(d).getUTCSeconds(),
  utcmilliseconds: d => new Date(d).getUTCMilliseconds(),
  // sequence functions
  length: x => x.length,
  join: function () {
    return standalone_vega_interpreter_module_apply('join', arguments);
  },
  indexof: function () {
    return standalone_vega_interpreter_module_apply('indexOf', arguments);
  },
  lastindexof: function () {
    return standalone_vega_interpreter_module_apply('lastIndexOf', arguments);
  },
  slice: function () {
    return standalone_vega_interpreter_module_apply('slice', arguments);
  },
  reverse: x => x.slice().reverse(),
  // string functions
  parseFloat: parseFloat,
  parseInt: parseInt,
  upper: x => String(x).toUpperCase(),
  lower: x => String(x).toLowerCase(),
  substring: function () {
    return standalone_vega_interpreter_module_apply('substring', arguments, String);
  },
  split: function () {
    return standalone_vega_interpreter_module_apply('split', arguments, String);
  },
  replace: function () {
    return standalone_vega_interpreter_module_apply('replace', arguments, String);
  },
  trim: x => String(x).trim(),
  // regexp functions
  regexp: RegExp,
  test: (r, t) => RegExp(r).test(t)
};

const standalone_EventFunctions = ['view', 'item', 'group', 'xy', 'x', 'y'];
const standalone_DisallowedMethods = new Set([Function, eval, setTimeout, setInterval]);
if (typeof setImmediate === 'function') standalone_DisallowedMethods.add(setImmediate);
const standalone_Visitors = {
  Literal: ($, n) => n.value,
  Identifier: ($, n) => {
    const id = n.name;
    return $.memberDepth > 0 ? id : id === 'datum' ? $.datum : id === 'event' ? $.event : id === 'item' ? $.item : standalone_vega_interpreter_module_Constants[id] || $.params['$' + id];
  },
  MemberExpression: ($, n) => {
    const d = !n.computed,
      o = $(n.object);
    if (d) $.memberDepth += 1;
    const p = $(n.property);
    if (d) $.memberDepth -= 1;
    if (standalone_DisallowedMethods.has(o[p])) {
      // eslint-disable-next-line no-console
      console.error(`Prevented interpretation of member "${p}" which could lead to insecure code execution`);
      return;
    }
    return o[p];
  },
  CallExpression: ($, n) => {
    const args = n.arguments;
    let name = n.callee.name;

    // handle special internal functions used by encoders
    // re-route to corresponding standard function
    if (name.startsWith('_')) {
      name = name.slice(1);
    }

    // special case "if" due to conditional evaluation of branches
    return name === 'if' ? $(args[0]) ? $(args[1]) : $(args[2]) : ($.fn[name] || standalone_vega_interpreter_module_Functions[name]).apply($.fn, args.map($));
  },
  ArrayExpression: ($, n) => n.elements.map($),
  BinaryExpression: ($, n) => standalone_Ops[n.operator]($(n.left), $(n.right)),
  UnaryExpression: ($, n) => standalone_Unary[n.operator]($(n.argument)),
  ConditionalExpression: ($, n) => $(n.test) ? $(n.consequent) : $(n.alternate),
  LogicalExpression: ($, n) => n.operator === '&&' ? $(n.left) && $(n.right) : $(n.left) || $(n.right),
  ObjectExpression: ($, n) => n.properties.reduce((o, p) => {
    $.memberDepth += 1;
    const k = $(p.key);
    $.memberDepth -= 1;
    if (standalone_DisallowedMethods.has($(p.value))) {
      // eslint-disable-next-line no-console
      console.error(`Prevented interpretation of property "${k}" which could lead to insecure code execution`);
    } else {
      o[k] = $(p.value);
    }
    return o;
  }, {})
};
function standalone_interpret (ast, fn, params, datum, event, item) {
  const $ = n => standalone_Visitors[n.type]($, n);
  $.memberDepth = 0;
  $.fn = Object.create(fn);
  $.params = params;
  $.datum = datum;
  $.event = event;
  $.item = item;

  // route event functions to annotated vega event context
  standalone_EventFunctions.forEach(f => $.fn[f] = function () {
    return event.vega[f](...arguments);
  });
  return $(ast);
}

var standalone_vega_interpreter_module_expression = {
  /**
   * Parse an expression used to update an operator value.
   */
  operator(ctx, expr) {
    const ast = expr.ast,
      fn = ctx.functions;
    return _ => standalone_interpret(ast, fn, _);
  },
  /**
   * Parse an expression provided as an operator parameter value.
   */
  parameter(ctx, expr) {
    const ast = expr.ast,
      fn = ctx.functions;
    return (datum, _) => standalone_interpret(ast, fn, _, datum);
  },
  /**
   * Parse an expression applied to an event stream.
   */
  event(ctx, expr) {
    const ast = expr.ast,
      fn = ctx.functions;
    return event => standalone_interpret(ast, fn, undefined, undefined, event);
  },
  /**
   * Parse an expression used to handle an event-driven operator update.
   */
  handler(ctx, expr) {
    const ast = expr.ast,
      fn = ctx.functions;
    return (_, event) => {
      const datum = event.item && event.item.datum;
      return standalone_interpret(ast, fn, _, datum, event);
    };
  },
  /**
   * Parse an expression that performs visual encoding.
   */
  encode(ctx, encode) {
    const {
        marktype,
        channels
      } = encode,
      fn = ctx.functions,
      swap = marktype === 'group' || marktype === 'image' || marktype === 'rect';
    return (item, _) => {
      const datum = item.datum;
      let m = 0,
        v;
      for (const name in channels) {
        v = standalone_interpret(channels[name].ast, fn, _, datum, undefined, item);
        if (item[name] !== v) {
          item[name] = v;
          m = 1;
        }
      }
      if (marktype !== 'rule') {
        standalone_vega_interpreter_module_adjustSpatial(item, channels, swap);
      }
      return m;
    };
  }
};



;// ../../node_modules/vega-lite/build/package.json
const standalone_package_namespaceObject = {"rE":"5.23.0"};
;// ../../node_modules/vega-lite/build/src/logical.js

function standalone_isLogicalOr(op) {
    return standalone_util_hasProperty(op, 'or');
}
function standalone_isLogicalAnd(op) {
    return standalone_util_hasProperty(op, 'and');
}
function standalone_isLogicalNot(op) {
    return standalone_util_hasProperty(op, 'not');
}
function standalone_forEachLeaf(op, fn) {
    if (standalone_isLogicalNot(op)) {
        standalone_forEachLeaf(op.not, fn);
    }
    else if (standalone_isLogicalAnd(op)) {
        for (const subop of op.and) {
            standalone_forEachLeaf(subop, fn);
        }
    }
    else if (standalone_isLogicalOr(op)) {
        for (const subop of op.or) {
            standalone_forEachLeaf(subop, fn);
        }
    }
    else {
        fn(op);
    }
}
function standalone_normalizeLogicalComposition(op, normalizer) {
    if (standalone_isLogicalNot(op)) {
        return { not: standalone_normalizeLogicalComposition(op.not, normalizer) };
    }
    else if (standalone_isLogicalAnd(op)) {
        return { and: op.and.map(o => standalone_normalizeLogicalComposition(o, normalizer)) };
    }
    else if (standalone_isLogicalOr(op)) {
        return { or: op.or.map(o => standalone_normalizeLogicalComposition(o, normalizer)) };
    }
    else {
        return normalizer(op);
    }
}
//# sourceMappingURL=logical.js.map
;// ../../node_modules/vega-lite/build/src/util.js


const standalone_duplicate = structuredClone;
function standalone_never(message) {
    throw new Error(message);
}
/**
 * Creates an object composed of the picked object properties.
 *
 * var object = {'a': 1, 'b': '2', 'c': 3};
 * pick(object, ['a', 'c']);
 * // → {'a': 1, 'c': 3}
 */
// eslint-disable-next-line @typescript-eslint/ban-types
function standalone_util_pick(obj, props) {
    const copy = {};
    for (const prop of props) {
        if (standalone_vega_util_module_has(obj, prop)) {
            copy[prop] = obj[prop];
        }
    }
    return copy;
}
/**
 * The opposite of _.pick; this method creates an object composed of the own
 * and inherited enumerable string keyed properties of object that are not omitted.
 */
// eslint-disable-next-line @typescript-eslint/ban-types
function standalone_omit(obj, props) {
    const copy = { ...obj };
    for (const prop of props) {
        delete copy[prop];
    }
    return copy;
}
/**
 * Monkey patch Set so that `stringify` produces a string representation of sets.
 */
Set.prototype['toJSON'] = function () {
    return `Set(${[...this].map(x => standalone_util_stringify(x)).join(',')})`;
};
/**
 * Converts any object to a string of limited size, or a number.
 */
function standalone_util_hash(a) {
    if (standalone_isNumber(a)) {
        return a;
    }
    const str = standalone_vega_util_module_isString(a) ? a : standalone_util_stringify(a);
    // short strings can be used as hash directly, longer strings are hashed to reduce memory usage
    if (str.length < 250) {
        return str;
    }
    // from http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
    let h = 0;
    for (let i = 0; i < str.length; i++) {
        const char = str.charCodeAt(i);
        h = (h << 5) - h + char;
        h = h & h; // Convert to 32bit integer
    }
    return h;
}
function standalone_isNullOrFalse(x) {
    return x === false || x === null;
}
function standalone_util_contains(array, item) {
    return array.includes(item);
}
/**
 * Returns true if any item returns true.
 */
function standalone_some(arr, f) {
    let i = 0;
    for (const [k, a] of arr.entries()) {
        if (f(a, k, i++)) {
            return true;
        }
    }
    return false;
}
/**
 * Returns true if all items return true.
 */
function standalone_every(arr, f) {
    let i = 0;
    for (const [k, a] of arr.entries()) {
        if (!f(a, k, i++)) {
            return false;
        }
    }
    return true;
}
/**
 * recursively merges src into dest
 */
function standalone_mergeDeep(dest, ...src) {
    for (const s of src) {
        standalone_deepMerge_(dest, s ?? {});
    }
    return dest;
}
function standalone_deepMerge_(dest, src) {
    for (const property of standalone_util_keys(src)) {
        standalone_writeConfig(dest, property, src[property], true);
    }
}
function standalone_unique(values, f) {
    const results = [];
    const u = {};
    let v;
    for (const val of values) {
        v = f(val);
        if (v in u) {
            continue;
        }
        u[v] = 1;
        results.push(val);
    }
    return results;
}
/**
 * Returns true if the two dictionaries agree. Applies only to defined values.
 */
function standalone_isEqual(dict, other) {
    const dictKeys = standalone_util_keys(dict);
    const otherKeys = standalone_util_keys(other);
    if (dictKeys.length !== otherKeys.length) {
        return false;
    }
    for (const key of dictKeys) {
        if (dict[key] !== other[key]) {
            return false;
        }
    }
    return true;
}
function standalone_setEqual(a, b) {
    if (a.size !== b.size) {
        return false;
    }
    for (const e of a) {
        if (!b.has(e)) {
            return false;
        }
    }
    return true;
}
function standalone_hasIntersection(a, b) {
    for (const key of a) {
        if (b.has(key)) {
            return true;
        }
    }
    return false;
}
function standalone_prefixGenerator(a) {
    const prefixes = new Set();
    for (const x of a) {
        const splitField = standalone_splitAccessPath(x);
        // Wrap every element other than the first in `[]`
        const wrappedWithAccessors = splitField.map((y, i) => (i === 0 ? y : `[${y}]`));
        const computedPrefixes = wrappedWithAccessors.map((_, i) => wrappedWithAccessors.slice(0, i + 1).join(''));
        for (const y of computedPrefixes) {
            prefixes.add(y);
        }
    }
    return prefixes;
}
/**
 * Returns true if a and b have an intersection. Also return true if a or b are undefined
 * since this means we don't know what fields a node produces or depends on.
 */
function standalone_fieldIntersection(a, b) {
    if (a === undefined || b === undefined) {
        return true;
    }
    return standalone_hasIntersection(standalone_prefixGenerator(a), standalone_prefixGenerator(b));
}
// eslint-disable-next-line @typescript-eslint/ban-types
function standalone_isEmpty(obj) {
    return standalone_util_keys(obj).length === 0;
}
// This is a stricter version of Object.keys but with better types. See https://github.com/Microsoft/TypeScript/pull/12253#issuecomment-263132208
const standalone_util_keys = Object.keys;
// Stricter version from https://github.com/microsoft/TypeScript/issues/51572#issuecomment-1319153323
const standalone_vals = Object.values;
// Stricter version from https://github.com/microsoft/TypeScript/issues/51572#issuecomment-1319153323
const standalone_entries = Object.entries;
function standalone_util_isBoolean(b) {
    return b === true || b === false;
}
/**
 * Convert a string into a valid variable name
 */
function standalone_varName(s) {
    // Replace non-alphanumeric characters (anything besides a-zA-Z0-9_) with _
    const alphanumericS = s.replace(/\W/g, '_');
    // Add _ if the string has leading numbers.
    return (s.match(/^\d+/) ? '_' : '') + alphanumericS;
}
function standalone_logicalExpr(op, cb) {
    if (standalone_isLogicalNot(op)) {
        return `!(${standalone_logicalExpr(op.not, cb)})`;
    }
    else if (standalone_isLogicalAnd(op)) {
        return `(${op.and.map((and) => standalone_logicalExpr(and, cb)).join(') && (')})`;
    }
    else if (standalone_isLogicalOr(op)) {
        return `(${op.or.map((or) => standalone_logicalExpr(or, cb)).join(') || (')})`;
    }
    else {
        return cb(op);
    }
}
/**
 * Delete nested property of an object, and delete the ancestors of the property if they become empty.
 */
function standalone_deleteNestedProperty(obj, orderedProps) {
    if (orderedProps.length === 0) {
        return true;
    }
    const prop = orderedProps.shift(); // eslint-disable-line @typescript-eslint/no-non-null-assertion
    if (prop in obj && standalone_deleteNestedProperty(obj[prop], orderedProps)) {
        delete obj[prop];
    }
    return standalone_isEmpty(obj);
}
function standalone_titleCase(s) {
    return s.charAt(0).toUpperCase() + s.substr(1);
}
/**
 * Converts a path to an access path with datum.
 * @param path The field name.
 * @param datum The string to use for `datum`.
 */
function standalone_accessPathWithDatum(path, datum = 'datum') {
    const pieces = standalone_splitAccessPath(path);
    const prefixes = [];
    for (let i = 1; i <= pieces.length; i++) {
        const prefix = `[${pieces.slice(0, i).map(standalone_$).join('][')}]`;
        prefixes.push(`${datum}${prefix}`);
    }
    return prefixes.join(' && ');
}
/**
 * Return access with datum to the flattened field.
 *
 * @param path The field name.
 * @param datum The string to use for `datum`.
 */
function standalone_flatAccessWithDatum(path, datum = 'datum') {
    return `${datum}[${standalone_$(standalone_splitAccessPath(path).join('.'))}]`;
}
/**
 * Return access with datum to **an unescaped path**.
 *
 * ```ts
 * console.log(accessWithDatumToUnescapedPath("vega's favorite"))
 * // "datum['vega\\'s favorite']"
 * ```
 *
 * @param path The unescaped path name. E.g., `"a.b"`, `"vega's favorite"`. (Note
 * that the field defs take escaped strings like `"a\\.b"`, `"vega\\'s favorite"`,
 * but this function is for the unescaped field/path)
 */
function standalone_accessWithDatumToUnescapedPath(unescapedPath) {
    const singleQuoteEscapedPath = unescapedPath.replaceAll("'", "\\'");
    return `datum['${singleQuoteEscapedPath}']`;
}
function standalone_escapePathAccess(string) {
    return string.replace(/(\[|\]|\.|'|")/g, '\\$1');
}
/**
 * Replaces path accesses with access to non-nested field.
 * For example, `foo["bar"].baz` becomes `foo\\.bar\\.baz`.
 */
function standalone_replacePathInField(path) {
    return `${standalone_splitAccessPath(path).map(standalone_escapePathAccess).join('\\.')}`;
}
/**
 * Replace all occurrences of a string with another string.
 *
 * @param string the string to replace in
 * @param find the string to replace
 * @param replacement the replacement
 */
function standalone_replaceAll(string, find, replacement) {
    return string.replace(new RegExp(find.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replacement);
}
/**
 * Remove path accesses with access from field.
 * For example, `foo["bar"].baz` becomes `foo.bar.baz`.
 */
function standalone_removePathFromField(path) {
    return `${standalone_splitAccessPath(path).join('.')}`;
}
/**
 * Count the depth of the path. Returns 1 for fields that are not nested.
 */
function standalone_accessPathDepth(path) {
    if (!path) {
        return 0;
    }
    return standalone_splitAccessPath(path).length;
}
/**
 * This is a replacement for chained || for numeric properties or properties that respect null so that 0 will be included.
 */
function standalone_getFirstDefined(...args) {
    return args.find(a => a !== undefined);
}
// variable used to generate id
let standalone_idCounter = 42;
/**
 * Returns a new random id every time it gets called.
 *
 * Has side effect!
 */
function standalone_uniqueId(prefix) {
    const id = ++standalone_idCounter;
    return prefix ? String(prefix) + id : id;
}
/**
 * Resets the id counter used in uniqueId. This can be useful for testing.
 */
function standalone_resetIdCounter() {
    standalone_idCounter = 42;
}
function standalone_internalField(name) {
    return standalone_isInternalField(name) ? name : `__${name}`;
}
function standalone_isInternalField(name) {
    return name.startsWith('__');
}
/**
 * Normalize angle to be within [0,360).
 */
function standalone_normalizeAngle(angle) {
    if (angle === undefined) {
        return undefined;
    }
    return ((angle % 360) + 360) % 360;
}
/**
 * Returns whether the passed in value is a valid number.
 */
function standalone_isNumeric(value) {
    if (standalone_isNumber(value)) {
        return true;
    }
    return !isNaN(value) && !isNaN(parseFloat(value));
}
const standalone_clonedProto = Object.getPrototypeOf(structuredClone({}));
/**
 * Compares two values for equality, including arrays and objects.
 *
 * Adapted from https://github.com/epoberezkin/fast-deep-equal.
 */
function standalone_deepEqual(a, b) {
    if (a === b)
        return true;
    if (a && b && typeof a == 'object' && typeof b == 'object') {
        // compare names to avoid issues with structured clone
        if (a.constructor.name !== b.constructor.name)
            return false;
        let length;
        let i;
        if (Array.isArray(a)) {
            length = a.length;
            if (length != b.length)
                return false;
            for (i = length; i-- !== 0;)
                if (!standalone_deepEqual(a[i], b[i]))
                    return false;
            return true;
        }
        if (a instanceof Map && b instanceof Map) {
            if (a.size !== b.size)
                return false;
            for (const e of a.entries())
                if (!b.has(e[0]))
                    return false;
            for (const e of a.entries())
                if (!standalone_deepEqual(e[1], b.get(e[0])))
                    return false;
            return true;
        }
        if (a instanceof Set && b instanceof Set) {
            if (a.size !== b.size)
                return false;
            for (const e of a.entries())
                if (!b.has(e[0]))
                    return false;
            return true;
        }
        if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
            length = a.length;
            if (length != b.length)
                return false;
            for (i = length; i-- !== 0;)
                if (a[i] !== b[i])
                    return false;
            return true;
        }
        if (a.constructor === RegExp)
            return a.source === b.source && a.flags === b.flags;
        // also compare to structured clone prototype
        if (a.valueOf !== Object.prototype.valueOf && a.valueOf !== standalone_clonedProto.valueOf)
            return a.valueOf() === b.valueOf();
        if (a.toString !== Object.prototype.toString && a.toString !== standalone_clonedProto.toString)
            return a.toString() === b.toString();
        const ks = Object.keys(a);
        length = ks.length;
        if (length !== Object.keys(b).length)
            return false;
        for (i = length; i-- !== 0;)
            if (!Object.prototype.hasOwnProperty.call(b, ks[i]))
                return false;
        for (i = length; i-- !== 0;) {
            const key = ks[i];
            if (!standalone_deepEqual(a[key], b[key]))
                return false;
        }
        return true;
    }
    // true if both NaN, false otherwise
    return a !== a && b !== b;
}
/**
 * Converts any object to a string representation that can be consumed by humans.
 *
 * Adapted from https://github.com/epoberezkin/fast-json-stable-stringify
 */
function standalone_util_stringify(data) {
    const seen = [];
    return (function _stringify(node) {
        if (node && node.toJSON && typeof node.toJSON === 'function') {
            node = node.toJSON();
        }
        if (node === undefined)
            return undefined;
        if (typeof node == 'number')
            return isFinite(node) ? '' + node : 'null';
        if (typeof node !== 'object')
            return JSON.stringify(node);
        let i, out;
        if (Array.isArray(node)) {
            out = '[';
            for (i = 0; i < node.length; i++) {
                if (i)
                    out += ',';
                out += _stringify(node[i]) || 'null';
            }
            return out + ']';
        }
        if (node === null)
            return 'null';
        if (seen.includes(node)) {
            throw new TypeError('Converting circular structure to JSON');
        }
        const seenIndex = seen.push(node) - 1;
        const ks = Object.keys(node).sort();
        out = '';
        for (i = 0; i < ks.length; i++) {
            const key = ks[i];
            const value = _stringify(node[key]);
            if (!value)
                continue;
            if (out)
                out += ',';
            out += JSON.stringify(key) + ':' + value;
        }
        seen.splice(seenIndex, 1);
        return `{${out}}`;
    })(data);
}
/**
 * Check if the input object has the property and it's not undefined.
 *
 * @param object the object
 * @param property the property to search
 * @returns if the object has the property and it's not undefined.
 */
function standalone_util_hasProperty(obj, key) {
    return standalone_vega_util_module_isObject(obj) && standalone_vega_util_module_has(obj, key) && obj[key] !== undefined;
}
//# sourceMappingURL=util.js.map
;// ../../node_modules/vega-lite/build/src/channel.js
/*
 * Constants and utilities for encoding channels (Visual variables)
 * such as 'x', 'y', 'color'.
 */


// Facet
const standalone_ROW = 'row';
const standalone_COLUMN = 'column';
const standalone_FACET = 'facet';
// Position
const standalone_channel_X = 'x';
const standalone_channel_Y = 'y';
const standalone_channel_X2 = 'x2';
const standalone_channel_Y2 = 'y2';
// Position Offset
const standalone_XOFFSET = 'xOffset';
const standalone_YOFFSET = 'yOffset';
// Arc-Position
const standalone_RADIUS = 'radius';
const standalone_RADIUS2 = 'radius2';
const standalone_THETA = 'theta';
const standalone_THETA2 = 'theta2';
// Geo Position
const standalone_LATITUDE = 'latitude';
const standalone_LONGITUDE = 'longitude';
const standalone_LATITUDE2 = 'latitude2';
const standalone_LONGITUDE2 = 'longitude2';
// Time
const standalone_TIME = 'time';
// Mark property with scale
const standalone_COLOR = 'color';
const standalone_FILL = 'fill';
const standalone_STROKE = 'stroke';
const standalone_SHAPE = 'shape';
const standalone_channel_SIZE = 'size';
const standalone_ANGLE = 'angle';
const standalone_OPACITY = 'opacity';
const standalone_FILLOPACITY = 'fillOpacity';
const standalone_STROKEOPACITY = 'strokeOpacity';
const standalone_STROKEWIDTH = 'strokeWidth';
const standalone_STROKEDASH = 'strokeDash';
// Non-scale channel
const standalone_TEXT = 'text';
const standalone_ORDER = 'order';
const standalone_DETAIL = 'detail';
const standalone_KEY = 'key';
const standalone_TOOLTIP = 'tooltip';
const standalone_HREF = 'href';
const standalone_channel_URL = 'url';
const standalone_DESCRIPTION = 'description';
const standalone_POSITION_CHANNEL_INDEX = {
    x: 1,
    y: 1,
    x2: 1,
    y2: 1
};
const standalone_POLAR_POSITION_CHANNEL_INDEX = {
    theta: 1,
    theta2: 1,
    radius: 1,
    radius2: 1
};
function standalone_isPolarPositionChannel(c) {
    return standalone_vega_util_module_has(standalone_POLAR_POSITION_CHANNEL_INDEX, c);
}
const standalone_GEO_POSIITON_CHANNEL_INDEX = {
    longitude: 1,
    longitude2: 1,
    latitude: 1,
    latitude2: 1
};
function standalone_getPositionChannelFromLatLong(channel) {
    switch (channel) {
        case standalone_LATITUDE:
            return 'y';
        case standalone_LATITUDE2:
            return 'y2';
        case standalone_LONGITUDE:
            return 'x';
        case standalone_LONGITUDE2:
            return 'x2';
    }
}
function standalone_isGeoPositionChannel(c) {
    return standalone_vega_util_module_has(standalone_GEO_POSIITON_CHANNEL_INDEX, c);
}
const standalone_GEOPOSITION_CHANNELS = standalone_util_keys(standalone_GEO_POSIITON_CHANNEL_INDEX);
const standalone_UNIT_CHANNEL_INDEX = {
    ...standalone_POSITION_CHANNEL_INDEX,
    ...standalone_POLAR_POSITION_CHANNEL_INDEX,
    ...standalone_GEO_POSIITON_CHANNEL_INDEX,
    xOffset: 1,
    yOffset: 1,
    // color
    color: 1,
    fill: 1,
    stroke: 1,
    // time
    time: 1,
    // other non-position with scale
    opacity: 1,
    fillOpacity: 1,
    strokeOpacity: 1,
    strokeWidth: 1,
    strokeDash: 1,
    size: 1,
    angle: 1,
    shape: 1,
    // channels without scales
    order: 1,
    text: 1,
    detail: 1,
    key: 1,
    tooltip: 1,
    href: 1,
    url: 1,
    description: 1
};
function standalone_isColorChannel(channel) {
    return channel === standalone_COLOR || channel === standalone_FILL || channel === standalone_STROKE;
}
const standalone_FACET_CHANNEL_INDEX = {
    row: 1,
    column: 1,
    facet: 1
};
const standalone_FACET_CHANNELS = standalone_util_keys(standalone_FACET_CHANNEL_INDEX);
const standalone_CHANNEL_INDEX = {
    ...standalone_UNIT_CHANNEL_INDEX,
    ...standalone_FACET_CHANNEL_INDEX
};
const standalone_CHANNELS = standalone_util_keys(standalone_CHANNEL_INDEX);
const { order: standalone_o, detail: standalone_d, tooltip: standalone_tt1, ...standalone_SINGLE_DEF_CHANNEL_INDEX } = standalone_CHANNEL_INDEX;
const { row: standalone_r, column: src_standalone_c, facet: standalone_f, ...standalone_SINGLE_DEF_UNIT_CHANNEL_INDEX } = standalone_SINGLE_DEF_CHANNEL_INDEX;
/**
 * Channels that cannot have an array of channelDef.
 * model.fieldDef, getFieldDef only work for these channels.
 *
 * (The only two channels that can have an array of channelDefs are "detail" and "order".
 * Since there can be multiple fieldDefs for detail and order, getFieldDef/model.fieldDef
 * are not applicable for them. Similarly, selection projection won't work with "detail" and "order".)
 */
const standalone_SINGLE_DEF_CHANNELS = standalone_util_keys(standalone_SINGLE_DEF_CHANNEL_INDEX);
const standalone_SINGLE_DEF_UNIT_CHANNELS = standalone_util_keys(standalone_SINGLE_DEF_UNIT_CHANNEL_INDEX);
function standalone_isSingleDefUnitChannel(str) {
    return standalone_vega_util_module_has(standalone_SINGLE_DEF_UNIT_CHANNEL_INDEX, str);
}
function standalone_isChannel(str) {
    return standalone_vega_util_module_has(standalone_CHANNEL_INDEX, str);
}
const standalone_SECONDARY_RANGE_CHANNEL = [standalone_channel_X2, standalone_channel_Y2, standalone_LATITUDE2, standalone_LONGITUDE2, standalone_THETA2, standalone_RADIUS2];
function standalone_isSecondaryRangeChannel(c) {
    const main = standalone_getMainRangeChannel(c);
    return main !== c;
}
/**
 * Get the main channel for a range channel. E.g. `x` for `x2`.
 */
function standalone_getMainRangeChannel(channel) {
    switch (channel) {
        case standalone_channel_X2:
            return standalone_channel_X;
        case standalone_channel_Y2:
            return standalone_channel_Y;
        case standalone_LATITUDE2:
            return standalone_LATITUDE;
        case standalone_LONGITUDE2:
            return standalone_LONGITUDE;
        case standalone_THETA2:
            return standalone_THETA;
        case standalone_RADIUS2:
            return standalone_RADIUS;
    }
    return channel;
}
function standalone_getVgPositionChannel(channel) {
    if (standalone_isPolarPositionChannel(channel)) {
        switch (channel) {
            case standalone_THETA:
                return 'startAngle';
            case standalone_THETA2:
                return 'endAngle';
            case standalone_RADIUS:
                return 'outerRadius';
            case standalone_RADIUS2:
                return 'innerRadius';
        }
    }
    return channel;
}
/**
 * Get the main channel for a range channel. E.g. `x` for `x2`.
 */
function standalone_getSecondaryRangeChannel(channel) {
    switch (channel) {
        case standalone_channel_X:
            return standalone_channel_X2;
        case standalone_channel_Y:
            return standalone_channel_Y2;
        case standalone_LATITUDE:
            return standalone_LATITUDE2;
        case standalone_LONGITUDE:
            return standalone_LONGITUDE2;
        case standalone_THETA:
            return standalone_THETA2;
        case standalone_RADIUS:
            return standalone_RADIUS2;
    }
    return undefined;
}
function standalone_getSizeChannel(channel) {
    switch (channel) {
        case standalone_channel_X:
        case standalone_channel_X2:
            return 'width';
        case standalone_channel_Y:
        case standalone_channel_Y2:
            return 'height';
    }
    return undefined;
}
/**
 * Get the main channel for a range channel. E.g. `x` for `x2`.
 */
function standalone_getOffsetChannel(channel) {
    switch (channel) {
        case standalone_channel_X:
            return 'xOffset';
        case standalone_channel_Y:
            return 'yOffset';
        case standalone_channel_X2:
            return 'x2Offset';
        case standalone_channel_Y2:
            return 'y2Offset';
        case standalone_THETA:
            return 'thetaOffset';
        case standalone_RADIUS:
            return 'radiusOffset';
        case standalone_THETA2:
            return 'theta2Offset';
        case standalone_RADIUS2:
            return 'radius2Offset';
    }
    return undefined;
}
/**
 * Get the main channel for a range channel. E.g. `x` for `x2`.
 */
function standalone_getOffsetScaleChannel(channel) {
    switch (channel) {
        case standalone_channel_X:
            return 'xOffset';
        case standalone_channel_Y:
            return 'yOffset';
    }
    return undefined;
}
function standalone_getMainChannelFromOffsetChannel(channel) {
    switch (channel) {
        case 'xOffset':
            return 'x';
        case 'yOffset':
            return 'y';
    }
}
// CHANNELS without COLUMN, ROW
const standalone_UNIT_CHANNELS = standalone_util_keys(standalone_UNIT_CHANNEL_INDEX);
// NONPOSITION_CHANNELS = UNIT_CHANNELS without X, Y, X2, Y2;
const { x: src_standalone_x, y: src_standalone_y, 
// x2 and y2 share the same scale as x and y
x2: standalone_x2, y2: standalone_y2, 
//
xOffset: standalone_xo, yOffset: standalone_yo, latitude: standalone_latitude, longitude: src_standalone_longitude, latitude2: standalone_latitude2, longitude2: standalone_longitude2, theta: standalone_theta, theta2: standalone_theta2, radius: src_standalone_radius, radius2: standalone_radius2, 
// The rest of unit channels then have scale
...standalone_NONPOSITION_CHANNEL_INDEX } = standalone_UNIT_CHANNEL_INDEX;
const standalone_NONPOSITION_CHANNELS = standalone_util_keys(standalone_NONPOSITION_CHANNEL_INDEX);
const standalone_POSITION_SCALE_CHANNEL_INDEX = {
    x: 1,
    y: 1
};
const standalone_POSITION_SCALE_CHANNELS = standalone_util_keys(standalone_POSITION_SCALE_CHANNEL_INDEX);
function standalone_isXorY(channel) {
    return standalone_vega_util_module_has(standalone_POSITION_SCALE_CHANNEL_INDEX, channel);
}
const standalone_POLAR_POSITION_SCALE_CHANNEL_INDEX = {
    theta: 1,
    radius: 1
};
const standalone_POLAR_POSITION_SCALE_CHANNELS = standalone_util_keys(standalone_POLAR_POSITION_SCALE_CHANNEL_INDEX);
function standalone_getPositionScaleChannel(sizeType) {
    return sizeType === 'width' ? standalone_channel_X : standalone_channel_Y;
}
const standalone_OFFSET_SCALE_CHANNEL_INDEX = { xOffset: 1, yOffset: 1 };
const standalone_OFFSET_SCALE_CHANNELS = standalone_util_keys(standalone_OFFSET_SCALE_CHANNEL_INDEX);
function standalone_isXorYOffset(channel) {
    return standalone_vega_util_module_has(standalone_OFFSET_SCALE_CHANNEL_INDEX, channel);
}
const standalone_TIME_SCALE_CHANNEL_INDEX = {
    time: 1
};
const standalone_TIME_SCALE_CHANNELS = standalone_util_keys(standalone_TIME_SCALE_CHANNEL_INDEX);
function standalone_isTime(channel) {
    return channel in standalone_TIME_SCALE_CHANNEL_INDEX;
}
// NON_POSITION_SCALE_CHANNEL = SCALE_CHANNELS without position / offset
const { 
// x2 and y2 share the same scale as x and y
// text and tooltip have format instead of scale,
// href has neither format, nor scale
text: standalone_t, tooltip: standalone_tt, href: standalone_hr, url: src_standalone_u, description: standalone_al, 
// detail and order have no scale
detail: standalone_dd, key: src_standalone_k, order: standalone_oo, ...standalone_NONPOSITION_SCALE_CHANNEL_INDEX } = standalone_NONPOSITION_CHANNEL_INDEX;
const standalone_NONPOSITION_SCALE_CHANNELS = standalone_util_keys(standalone_NONPOSITION_SCALE_CHANNEL_INDEX);
function standalone_isNonPositionScaleChannel(channel) {
    return standalone_vega_util_module_has(standalone_NONPOSITION_CHANNEL_INDEX, channel);
}
/**
 * @returns whether Vega supports legends for a particular channel
 */
function standalone_supportLegend(channel) {
    switch (channel) {
        case standalone_COLOR:
        case standalone_FILL:
        case standalone_STROKE:
        case standalone_channel_SIZE:
        case standalone_SHAPE:
        case standalone_OPACITY:
        case standalone_STROKEWIDTH:
        case standalone_STROKEDASH:
            return true;
        case standalone_FILLOPACITY:
        case standalone_STROKEOPACITY:
        case standalone_ANGLE:
        case standalone_TIME:
            return false;
    }
}
// Declare SCALE_CHANNEL_INDEX
const standalone_SCALE_CHANNEL_INDEX = {
    ...standalone_POSITION_SCALE_CHANNEL_INDEX,
    ...standalone_POLAR_POSITION_SCALE_CHANNEL_INDEX,
    ...standalone_OFFSET_SCALE_CHANNEL_INDEX,
    ...standalone_NONPOSITION_SCALE_CHANNEL_INDEX
};
/** List of channels with scales */
const standalone_SCALE_CHANNELS = standalone_util_keys(standalone_SCALE_CHANNEL_INDEX);
function standalone_isScaleChannel(channel) {
    return standalone_vega_util_module_has(standalone_SCALE_CHANNEL_INDEX, channel);
}
/**
 * Return whether a channel supports a particular mark type.
 * @param channel  channel name
 * @param mark the mark type
 * @return whether the mark supports the channel
 */
function standalone_supportMark(channel, mark) {
    return standalone_getSupportedMark(channel)[mark];
}
const standalone_ALL_MARKS = {
    // all marks
    arc: 'always',
    area: 'always',
    bar: 'always',
    circle: 'always',
    geoshape: 'always',
    image: 'always',
    line: 'always',
    rule: 'always',
    point: 'always',
    rect: 'always',
    square: 'always',
    trail: 'always',
    text: 'always',
    tick: 'always'
};
const { geoshape: standalone_g, ...standalone_ALL_MARKS_EXCEPT_GEOSHAPE } = standalone_ALL_MARKS;
/**
 * Return a dictionary showing whether a channel supports mark type.
 * @param channel
 * @return A dictionary mapping mark types to 'always', 'binned', or undefined
 */
function standalone_getSupportedMark(channel) {
    switch (channel) {
        case standalone_COLOR:
        case standalone_FILL:
        case standalone_STROKE:
        // falls through
        case standalone_DESCRIPTION:
        case standalone_DETAIL:
        case standalone_KEY:
        case standalone_TOOLTIP:
        case standalone_HREF:
        case standalone_ORDER: // TODO: revise (order might not support rect, which is not stackable?)
        case standalone_OPACITY:
        case standalone_FILLOPACITY:
        case standalone_STROKEOPACITY:
        case standalone_STROKEWIDTH:
        // falls through
        case standalone_FACET:
        case standalone_ROW: // falls through
        case standalone_COLUMN:
            return standalone_ALL_MARKS;
        case standalone_channel_X:
        case standalone_channel_Y:
        case standalone_XOFFSET:
        case standalone_YOFFSET:
        case standalone_LATITUDE:
        case standalone_LONGITUDE:
        case standalone_TIME:
            // all marks except geoshape. geoshape does not use X, Y -- it uses a projection
            return standalone_ALL_MARKS_EXCEPT_GEOSHAPE;
        case standalone_channel_X2:
        case standalone_channel_Y2:
        case standalone_LATITUDE2:
        case standalone_LONGITUDE2:
            return {
                area: 'always',
                bar: 'always',
                image: 'always',
                rect: 'always',
                rule: 'always',
                circle: 'binned',
                point: 'binned',
                square: 'binned',
                tick: 'binned',
                line: 'binned',
                trail: 'binned'
            };
        case standalone_channel_SIZE:
            return {
                point: 'always',
                tick: 'always',
                rule: 'always',
                circle: 'always',
                square: 'always',
                bar: 'always',
                text: 'always',
                line: 'always',
                trail: 'always'
            };
        case standalone_STROKEDASH:
            return {
                line: 'always',
                point: 'always',
                tick: 'always',
                rule: 'always',
                circle: 'always',
                square: 'always',
                bar: 'always',
                geoshape: 'always'
            };
        case standalone_SHAPE:
            return { point: 'always', geoshape: 'always' };
        case standalone_TEXT:
            return { text: 'always' };
        case standalone_ANGLE:
            return { point: 'always', square: 'always', text: 'always' };
        case standalone_channel_URL:
            return { image: 'always' };
        case standalone_THETA:
            return { text: 'always', arc: 'always' };
        case standalone_RADIUS:
            return { text: 'always', arc: 'always' };
        case standalone_THETA2:
        case standalone_RADIUS2:
            return { arc: 'always' };
    }
}
function standalone_rangeType(channel) {
    switch (channel) {
        case standalone_channel_X:
        case standalone_channel_Y:
        case standalone_THETA:
        case standalone_RADIUS:
        case standalone_XOFFSET:
        case standalone_YOFFSET:
        case standalone_channel_SIZE:
        case standalone_ANGLE:
        case standalone_STROKEWIDTH:
        case standalone_OPACITY:
        case standalone_FILLOPACITY:
        case standalone_STROKEOPACITY:
        case standalone_TIME:
        // X2 and Y2 use X and Y scales, so they similarly have continuous range. [falls through]
        case standalone_channel_X2:
        case standalone_channel_Y2:
        case standalone_THETA2:
        case standalone_RADIUS2:
            return undefined;
        case standalone_FACET:
        case standalone_ROW:
        case standalone_COLUMN:
        case standalone_SHAPE:
        case standalone_STROKEDASH:
        // TEXT, TOOLTIP, URL, and HREF have no scale but have discrete output [falls through]
        case standalone_TEXT:
        case standalone_TOOLTIP:
        case standalone_HREF:
        case standalone_channel_URL:
        case standalone_DESCRIPTION:
            return 'discrete';
        // Color can be either continuous or discrete, depending on scale type.
        case standalone_COLOR:
        case standalone_FILL:
        case standalone_STROKE:
            return 'flexible';
        // No scale, no range type.
        case standalone_LATITUDE:
        case standalone_LONGITUDE:
        case standalone_LATITUDE2:
        case standalone_LONGITUDE2:
        case standalone_DETAIL:
        case standalone_KEY:
        case standalone_ORDER:
            return undefined;
    }
}
//# sourceMappingURL=channel.js.map
;// ../../node_modules/vega-lite/build/src/aggregate.js


const standalone_AGGREGATE_OP_INDEX = {
    argmax: 1,
    argmin: 1,
    average: 1,
    count: 1,
    distinct: 1,
    exponential: 1,
    exponentialb: 1,
    product: 1,
    max: 1,
    mean: 1,
    median: 1,
    min: 1,
    missing: 1,
    q1: 1,
    q3: 1,
    ci0: 1,
    ci1: 1,
    stderr: 1,
    stdev: 1,
    stdevp: 1,
    sum: 1,
    valid: 1,
    values: 1,
    variance: 1,
    variancep: 1
};
const standalone_MULTIDOMAIN_SORT_OP_INDEX = {
    count: 1,
    min: 1,
    max: 1
};
function standalone_isArgminDef(a) {
    return standalone_util_hasProperty(a, 'argmin');
}
function standalone_isArgmaxDef(a) {
    return standalone_util_hasProperty(a, 'argmax');
}
function standalone_isAggregateOp(a) {
    return standalone_vega_util_module_isString(a) && standalone_vega_util_module_has(standalone_AGGREGATE_OP_INDEX, a);
}
const standalone_COUNTING_OPS = new Set([
    'count',
    'valid',
    'missing',
    'distinct'
]);
function standalone_isCountingAggregateOp(aggregate) {
    return standalone_vega_util_module_isString(aggregate) && standalone_COUNTING_OPS.has(aggregate);
}
function standalone_isMinMaxOp(aggregate) {
    return standalone_vega_util_module_isString(aggregate) && standalone_util_contains(['min', 'max'], aggregate);
}
/** Additive-based aggregation operations. These can be applied to stack. */
const standalone_SUM_OPS = new Set([
    'count',
    'sum',
    'distinct',
    'valid',
    'missing'
]);
/**
 * Aggregation operators that always produce values within the range [domainMin, domainMax].
 */
const standalone_SHARED_DOMAIN_OPS = new Set([
    'mean',
    'average',
    'median',
    'q1',
    'q3',
    'min',
    'max'
]);
//# sourceMappingURL=aggregate.js.map
;// ../../node_modules/vega-lite/build/src/bin.js




/**
 * Create a key for the bin configuration. Not for prebinned bin.
 */
function standalone_binToString(bin) {
    if (standalone_isBoolean(bin)) {
        bin = standalone_normalizeBin(bin, undefined);
    }
    return ('bin' +
        standalone_util_keys(bin)
            .map(p => (standalone_isParameterExtent(bin[p]) ? standalone_varName(`_${p}_${standalone_entries(bin[p])}`) : standalone_varName(`_${p}_${bin[p]}`)))
            .join(''));
}
/**
 * Vega-Lite should bin the data.
 */
function standalone_isBinning(bin) {
    return bin === true || (standalone_isBinParams(bin) && !bin.binned);
}
/**
 * The data is already binned and so Vega-Lite should not bin it again.
 */
function standalone_isBinned(bin) {
    return bin === 'binned' || (standalone_isBinParams(bin) && bin.binned === true);
}
function standalone_isBinParams(bin) {
    return standalone_vega_util_module_isObject(bin);
}
function standalone_isParameterExtent(extent) {
    return standalone_util_hasProperty(extent, 'param');
}
function standalone_autoMaxBins(channel) {
    switch (channel) {
        case standalone_ROW:
        case standalone_COLUMN:
        case standalone_channel_SIZE:
        case standalone_COLOR:
        case standalone_FILL:
        case standalone_STROKE:
        case standalone_STROKEWIDTH:
        case standalone_OPACITY:
        case standalone_FILLOPACITY:
        case standalone_STROKEOPACITY:
        // Facets and Size shouldn't have too many bins
        // We choose 6 like shape to simplify the rule [falls through]
        case standalone_SHAPE:
            return 6; // Vega's "shape" has 6 distinct values
        case standalone_STROKEDASH:
            return 4; // We only provide 5 different stroke dash values (but 4 is more effective)
        default:
            return 10;
    }
}
//# sourceMappingURL=bin.js.map
;// ../../node_modules/vega-lite/build/src/expr.js


function standalone_isExprRef(o) {
    return standalone_util_hasProperty(o, 'expr');
}
function standalone_replaceExprRef(index, { level } = { level: 0 }) {
    const props = standalone_util_keys(index || {});
    const newIndex = {};
    for (const prop of props) {
        newIndex[prop] = level === 0 ? standalone_signalRefOrValue(index[prop]) : standalone_replaceExprRef(index[prop], { level: level - 1 });
    }
    return newIndex;
}
//# sourceMappingURL=expr.js.map
;// ../../node_modules/vega-lite/build/src/title.js


function standalone_extractTitleConfig(titleConfig) {
    const { 
    // These are non-mark title config that need to be hardcoded
    anchor, frame, offset, orient, angle, limit, 
    // color needs to be redirect to fill
    color, 
    // subtitle properties
    subtitleColor, subtitleFont, subtitleFontSize, subtitleFontStyle, subtitleFontWeight, subtitleLineHeight, subtitlePadding, 
    // The rest are mark config.
    ...rest } = titleConfig;
    const titleMarkConfig = {
        ...rest,
        ...(color ? { fill: color } : {})
    };
    // These are non-mark title config that need to be hardcoded
    const nonMarkTitleProperties = {
        ...(anchor ? { anchor } : {}),
        ...(frame ? { frame } : {}),
        ...(offset ? { offset } : {}),
        ...(orient ? { orient } : {}),
        ...(angle !== undefined ? { angle } : {}),
        ...(limit !== undefined ? { limit } : {})
    };
    // subtitle part can stay in config.title since header titles do not use subtitle
    const subtitle = {
        ...(subtitleColor ? { subtitleColor } : {}),
        ...(subtitleFont ? { subtitleFont } : {}),
        ...(subtitleFontSize ? { subtitleFontSize } : {}),
        ...(subtitleFontStyle ? { subtitleFontStyle } : {}),
        ...(subtitleFontWeight ? { subtitleFontWeight } : {}),
        ...(subtitleLineHeight ? { subtitleLineHeight } : {}),
        ...(subtitlePadding ? { subtitlePadding } : {})
    };
    const subtitleMarkConfig = standalone_util_pick(titleConfig, ['align', 'baseline', 'dx', 'dy', 'limit']);
    return { titleMarkConfig, subtitleMarkConfig, nonMarkTitleProperties, subtitle };
}
function standalone_isText(v) {
    return standalone_vega_util_module_isString(v) || (standalone_vega_util_module_isArray(v) && standalone_vega_util_module_isString(v[0]));
}
//# sourceMappingURL=title.js.map
;// ../../node_modules/vega-lite/build/src/vega.schema.js


function standalone_isSignalRef(o) {
    return standalone_util_hasProperty(o, 'signal');
}
function standalone_isVgRangeStep(range) {
    return standalone_util_hasProperty(range, 'step');
}
function standalone_isDataRefUnionedDomain(domain) {
    if (!standalone_vega_util_module_isArray(domain)) {
        return standalone_util_hasProperty(domain, 'fields') && !standalone_util_hasProperty(domain, 'data');
    }
    return false;
}
function standalone_isFieldRefUnionDomain(domain) {
    if (!standalone_vega_util_module_isArray(domain)) {
        return standalone_util_hasProperty(domain, 'fields') && standalone_util_hasProperty(domain, 'data');
    }
    return false;
}
function standalone_isDataRefDomain(domain) {
    if (!standalone_vega_util_module_isArray(domain)) {
        return standalone_util_hasProperty(domain, 'field') && standalone_util_hasProperty(domain, 'data');
    }
    return false;
}
const standalone_VG_MARK_CONFIG_INDEX = {
    aria: 1,
    description: 1,
    ariaRole: 1,
    ariaRoleDescription: 1,
    blend: 1,
    opacity: 1,
    fill: 1,
    fillOpacity: 1,
    stroke: 1,
    strokeCap: 1,
    strokeWidth: 1,
    strokeOpacity: 1,
    strokeDash: 1,
    strokeDashOffset: 1,
    strokeJoin: 1,
    strokeOffset: 1,
    strokeMiterLimit: 1,
    startAngle: 1,
    endAngle: 1,
    padAngle: 1,
    innerRadius: 1,
    outerRadius: 1,
    size: 1,
    shape: 1,
    interpolate: 1,
    tension: 1,
    orient: 1,
    align: 1,
    baseline: 1,
    text: 1,
    dir: 1,
    dx: 1,
    dy: 1,
    ellipsis: 1,
    limit: 1,
    radius: 1,
    theta: 1,
    angle: 1,
    font: 1,
    fontSize: 1,
    fontWeight: 1,
    fontStyle: 1,
    lineBreak: 1,
    lineHeight: 1,
    cursor: 1,
    href: 1,
    tooltip: 1,
    cornerRadius: 1,
    cornerRadiusTopLeft: 1,
    cornerRadiusTopRight: 1,
    cornerRadiusBottomLeft: 1,
    cornerRadiusBottomRight: 1,
    aspect: 1,
    width: 1,
    height: 1,
    url: 1,
    smooth: 1
    // commented below are vg channel that do not have mark config.
    // x: 1,
    // y: 1,
    // x2: 1,
    // y2: 1,
    // xc'|'yc'
    // clip: 1,
    // path: 1,
    // url: 1,
};
const standalone_VG_MARK_CONFIGS = standalone_util_keys(standalone_VG_MARK_CONFIG_INDEX);
const standalone_VG_MARK_INDEX = {
    arc: 1,
    area: 1,
    group: 1,
    image: 1,
    line: 1,
    path: 1,
    rect: 1,
    rule: 1,
    shape: 1,
    symbol: 1,
    text: 1,
    trail: 1
};
// Vega's cornerRadius channels.
const standalone_VG_CORNERRADIUS_CHANNELS = [
    'cornerRadius',
    'cornerRadiusTopLeft',
    'cornerRadiusTopRight',
    'cornerRadiusBottomLeft',
    'cornerRadiusBottomRight'
];
//# sourceMappingURL=vega.schema.js.map
;// ../../node_modules/vega-lite/build/src/compile/common.js






const standalone_BIN_RANGE_DELIMITER = ' \u2013 ';
function standalone_signalOrValueRefWithCondition(val) {
    const condition = standalone_vega_util_module_isArray(val.condition)
        ? val.condition.map(standalone_conditionalSignalRefOrValue)
        : standalone_conditionalSignalRefOrValue(val.condition);
    return {
        ...standalone_signalRefOrValue(val),
        condition
    };
}
function standalone_signalRefOrValue(value) {
    if (standalone_isExprRef(value)) {
        const { expr, ...rest } = value;
        return { signal: expr, ...rest };
    }
    return value;
}
function standalone_conditionalSignalRefOrValue(value) {
    if (standalone_isExprRef(value)) {
        const { expr, ...rest } = value;
        return { signal: expr, ...rest };
    }
    return value;
}
function standalone_signalOrValueRef(value) {
    if (standalone_isExprRef(value)) {
        const { expr, ...rest } = value;
        return { signal: expr, ...rest };
    }
    if (standalone_isSignalRef(value)) {
        return value;
    }
    return value !== undefined ? { value } : undefined;
}
function standalone_exprFromSignalRefOrValue(ref) {
    if (standalone_isSignalRef(ref)) {
        return ref.signal;
    }
    return standalone_$(ref);
}
function standalone_exprFromValueRefOrSignalRef(ref) {
    if (standalone_isSignalRef(ref)) {
        return ref.signal;
    }
    return standalone_$(ref.value);
}
function standalone_signalOrStringValue(v) {
    if (standalone_isSignalRef(v)) {
        return v.signal;
    }
    return v == null ? null : standalone_$(v);
}
function standalone_applyMarkConfig(e, model, propsList) {
    for (const property of propsList) {
        const value = standalone_getMarkConfig(property, model.markDef, model.config);
        if (value !== undefined) {
            e[property] = standalone_signalOrValueRef(value);
        }
    }
    return e;
}
function standalone_common_getStyles(mark) {
    return [].concat(mark.type, mark.style ?? []);
}
function standalone_getMarkPropOrConfig(channel, mark, config, opt = {}) {
    const { vgChannel, ignoreVgConfig } = opt;
    if (vgChannel && standalone_util_hasProperty(mark, vgChannel)) {
        return mark[vgChannel];
    }
    else if (mark[channel] !== undefined) {
        return mark[channel];
    }
    else if (ignoreVgConfig && (!vgChannel || vgChannel === channel)) {
        return undefined;
    }
    return standalone_getMarkConfig(channel, mark, config, opt);
}
/**
 * Return property value from style or mark specific config property if exists.
 * Otherwise, return general mark specific config.
 */
function standalone_getMarkConfig(channel, mark, config, { vgChannel } = {}) {
    const cfg = standalone_getMarkStyleConfig(channel, mark, config.style);
    return standalone_getFirstDefined(
    // style config has highest precedence
    vgChannel ? cfg : undefined, cfg, 
    // then mark-specific config
    vgChannel ? config[mark.type][vgChannel] : undefined, config[mark.type][channel], // Need to cast because MarkDef doesn't perfectly match with AnyMarkConfig, but if the type isn't available, we'll get nothing here, which is fine
    // If there is vgChannel, skip vl channel.
    // For example, vl size for text is vg fontSize, but config.mark.size is only for point size.
    vgChannel ? config.mark[vgChannel] : config.mark[channel] // Need to cast for the same reason as above
    );
}
function standalone_getMarkStyleConfig(prop, mark, styleConfigIndex) {
    return standalone_getStyleConfig(prop, standalone_common_getStyles(mark), styleConfigIndex);
}
function standalone_getStyleConfig(p, styles, styleConfigIndex) {
    styles = standalone_array(styles);
    let value;
    for (const style of styles) {
        const styleConfig = styleConfigIndex[style];
        if (standalone_util_hasProperty(styleConfig, p)) {
            value = styleConfig[p];
        }
    }
    return value;
}
/**
 * Return Vega sort parameters (tuple of field and order).
 */
function standalone_sortParams(orderDef, fieldRefOption) {
    return standalone_array(orderDef).reduce((s, orderChannelDef) => {
        s.field.push(standalone_vgField(orderChannelDef, fieldRefOption));
        s.order.push(orderChannelDef.sort ?? 'ascending');
        return s;
    }, { field: [], order: [] });
}
function standalone_mergeTitleFieldDefs(f1, f2) {
    const merged = [...f1];
    f2.forEach(fdToMerge => {
        for (const fieldDef1 of merged) {
            // If already exists, no need to append to merged array
            if (standalone_deepEqual(fieldDef1, fdToMerge)) {
                return;
            }
        }
        merged.push(fdToMerge);
    });
    return merged;
}
function standalone_mergeTitle(title1, title2) {
    if (standalone_deepEqual(title1, title2) || !title2) {
        // if titles are the same or title2 is falsy
        return title1;
    }
    else if (!title1) {
        // if title1 is falsy
        return title2;
    }
    else {
        return [...standalone_array(title1), ...standalone_array(title2)].join(', ');
    }
}
function standalone_mergeTitleComponent(v1, v2) {
    const v1Val = v1.value;
    const v2Val = v2.value;
    if (v1Val == null || v2Val === null) {
        return {
            explicit: v1.explicit,
            value: null
        };
    }
    else if ((standalone_isText(v1Val) || standalone_isSignalRef(v1Val)) && (standalone_isText(v2Val) || standalone_isSignalRef(v2Val))) {
        return {
            explicit: v1.explicit,
            value: standalone_mergeTitle(v1Val, v2Val)
        };
    }
    else if (standalone_isText(v1Val) || standalone_isSignalRef(v1Val)) {
        return {
            explicit: v1.explicit,
            value: v1Val
        };
    }
    else if (standalone_isText(v2Val) || standalone_isSignalRef(v2Val)) {
        return {
            explicit: v1.explicit,
            value: v2Val
        };
    }
    else if (!standalone_isText(v1Val) && !standalone_isSignalRef(v1Val) && !standalone_isText(v2Val) && !standalone_isSignalRef(v2Val)) {
        return {
            explicit: v1.explicit,
            value: standalone_mergeTitleFieldDefs(v1Val, v2Val)
        };
    }
    /* istanbul ignore next: Condition should not happen -- only for warning in development. */
    throw new Error('It should never reach here');
}
//# sourceMappingURL=common.js.map
;// ../../node_modules/vega-lite/build/src/log/message.js
/**
 * Collection of all Vega-Lite Error Messages
 */



function standalone_invalidSpec(spec) {
    return `Invalid specification ${standalone_util_stringify(spec)}. Make sure the specification includes at least one of the following properties: "mark", "layer", "facet", "hconcat", "vconcat", "concat", or "repeat".`;
}
// FIT
const standalone_FIT_NON_SINGLE = 'Autosize "fit" only works for single views and layered views.';
function standalone_containerSizeNonSingle(name) {
    const uName = name == 'width' ? 'Width' : 'Height';
    return `${uName} "container" only works for single views and layered views.`;
}
function standalone_containerSizeNotCompatibleWithAutosize(name) {
    const uName = name == 'width' ? 'Width' : 'Height';
    const fitDirection = name == 'width' ? 'x' : 'y';
    return `${uName} "container" only works well with autosize "fit" or "fit-${fitDirection}".`;
}
function standalone_droppingFit(channel) {
    return channel
        ? `Dropping "fit-${channel}" because spec has discrete ${standalone_getSizeChannel(channel)}.`
        : `Dropping "fit" because spec has discrete size.`;
}
// VIEW SIZE
function standalone_unknownField(channel) {
    return `Unknown field for ${channel}. Cannot calculate view size.`;
}
// SELECTION
function standalone_cannotProjectOnChannelWithoutField(channel) {
    return `Cannot project a selection on encoding channel "${channel}", which has no field.`;
}
function standalone_cannotProjectAggregate(channel, aggregate) {
    return `Cannot project a selection on encoding channel "${channel}" as it uses an aggregate function ("${aggregate}").`;
}
function standalone_nearestNotSupportForContinuous(mark) {
    return `The "nearest" transform is not supported for ${mark} marks.`;
}
function standalone_selectionNotSupported(mark) {
    return `Selection not supported for ${mark} yet.`;
}
function standalone_selectionNotFound(name) {
    return `Cannot find a selection named "${name}".`;
}
const standalone_SCALE_BINDINGS_CONTINUOUS = 'Scale bindings are currently only supported for scales with unbinned, continuous domains.';
const standalone_SEQUENTIAL_SCALE_DEPRECATED = 'Sequntial scales are deprecated. The available quantitative scale type values are linear, log, pow, sqrt, symlog, time and utc';
const standalone_LEGEND_BINDINGS_MUST_HAVE_PROJECTION = 'Legend bindings are only supported for selections over an individual field or encoding channel.';
function standalone_cannotLookupVariableParameter(name) {
    return `Lookups can only be performed on selection parameters. "${name}" is a variable parameter.`;
}
function standalone_noSameUnitLookup(name) {
    return (`Cannot define and lookup the "${name}" selection in the same view. ` +
        `Try moving the lookup into a second, layered view?`);
}
const standalone_NEEDS_SAME_SELECTION = 'The same selection must be used to override scale domains in a layered view.';
const standalone_INTERVAL_INITIALIZED_WITH_POS = 'Interval selections should be initialized using "x", "y", "longitude", or "latitude" keys.';
// REPEAT
function standalone_noSuchRepeatedValue(field) {
    return `Unknown repeated value "${field}".`;
}
function standalone_columnsNotSupportByRowCol(type) {
    return `The "columns" property cannot be used when "${type}" has nested row/column.`;
}
const standalone_MULTIPLE_TIMER_ANIMATION_SELECTION = 'Multiple timer selections in one unit spec are not supported. Ignoring all but the first.';
const standalone_MULTI_VIEW_ANIMATION_UNSUPPORTED = 'Animation involving facet, layer, or concat is currently unsupported.';
function standalone_selectionAsScaleDomainWithoutField(field) {
    return ('A "field" or "encoding" must be specified when using a selection as a scale domain. ' +
        `Using "field": ${standalone_$(field)}.`);
}
function standalone_selectionAsScaleDomainWrongEncodings(encodings, encoding, extent, field) {
    return ((!encodings.length ? 'No ' : 'Multiple ') +
        `matching ${standalone_$(encoding)} encoding found for selection ${standalone_$(extent.param)}. ` +
        `Using "field": ${standalone_$(field)}.`);
}
// CONCAT / REPEAT
const standalone_CONCAT_CANNOT_SHARE_AXIS = 'Axes cannot be shared in concatenated or repeated views yet (https://github.com/vega/vega-lite/issues/2415).';
// DATA
function standalone_unrecognizedParse(p) {
    return `Unrecognized parse "${p}".`;
}
function standalone_differentParse(field, local, ancestor) {
    return `An ancestor parsed field "${field}" as ${ancestor} but a child wants to parse the field as ${local}.`;
}
const standalone_ADD_SAME_CHILD_TWICE = 'Attempt to add the same child twice.';
// TRANSFORMS
function standalone_invalidTransformIgnored(transform) {
    return `Ignoring an invalid transform: ${standalone_util_stringify(transform)}.`;
}
const standalone_NO_FIELDS_NEEDS_AS = 'If "from.fields" is not specified, "as" has to be a string that specifies the key to be used for the data from the secondary source.';
// ENCODING & FACET
function standalone_customFormatTypeNotAllowed(channel) {
    return `Config.customFormatTypes is not true, thus custom format type and format for channel ${channel} are dropped.`;
}
function standalone_projectionOverridden(opt) {
    const { parentProjection, projection } = opt;
    return `Layer's shared projection ${standalone_util_stringify(parentProjection)} is overridden by a child projection ${standalone_util_stringify(projection)}.`;
}
const standalone_REPLACE_ANGLE_WITH_THETA = 'Arc marks uses theta channel rather than angle, replacing angle with theta.';
function standalone_offsetNestedInsideContinuousPositionScaleDropped(mainChannel) {
    return `${mainChannel}Offset dropped because ${mainChannel} is continuous`;
}
function standalone_primitiveChannelDef(channel, type, value) {
    return `Channel ${channel} is a ${type}. Converted to {value: ${standalone_util_stringify(value)}}.`;
}
function standalone_invalidFieldType(type) {
    return `Invalid field type "${type}".`;
}
function standalone_invalidFieldTypeForCountAggregate(type, aggregate) {
    return `Invalid field type "${type}" for aggregate: "${aggregate}", using "quantitative" instead.`;
}
function standalone_invalidAggregate(aggregate) {
    return `Invalid aggregation operator "${aggregate}".`;
}
function standalone_missingFieldType(channel, newType) {
    return `Missing type for channel "${channel}", using "${newType}" instead.`;
}
function standalone_droppingColor(type, opt) {
    const { fill, stroke } = opt;
    return `Dropping color ${type} as the plot also has ${fill && stroke ? 'fill and stroke' : fill ? 'fill' : 'stroke'}.`;
}
function standalone_relativeBandSizeNotSupported(sizeChannel) {
    return `Position range does not support relative band size for ${sizeChannel}.`;
}
function standalone_emptyFieldDef(fieldDef, channel) {
    return `Dropping ${standalone_util_stringify(fieldDef)} from channel "${channel}" since it does not contain any data field, datum, value, or signal.`;
}
const standalone_LINE_WITH_VARYING_SIZE = 'Line marks cannot encode size with a non-groupby field. You may want to use trail marks instead.';
function standalone_incompatibleChannel(channel, markOrFacet, when) {
    return `${channel} dropped as it is incompatible with "${markOrFacet}"${when ? ` when ${when}` : ''}.`;
}
function standalone_offsetEncodingScaleIgnored(channel) {
    return `${channel} encoding has no scale, so specified scale is ignored.`;
}
function standalone_invalidEncodingChannel(channel) {
    return `${channel}-encoding is dropped as ${channel} is not a valid encoding channel.`;
}
function standalone_channelShouldBeDiscrete(channel) {
    return `${channel} encoding should be discrete (ordinal / nominal / binned).`;
}
function standalone_channelShouldBeDiscreteOrDiscretizing(channel) {
    return `${channel} encoding should be discrete (ordinal / nominal / binned) or use a discretizing scale (e.g. threshold).`;
}
function standalone_facetChannelDropped(channels) {
    return `Facet encoding dropped as ${channels.join(' and ')} ${channels.length > 1 ? 'are' : 'is'} also specified.`;
}
function standalone_discreteChannelCannotEncode(channel, type) {
    return `Using discrete channel "${channel}" to encode "${type}" field can be misleading as it does not encode ${type === 'ordinal' ? 'order' : 'magnitude'}.`;
}
// MARK
function standalone_rangeMarkAlignmentCannotBeExpression(align) {
    return `The ${align} for range marks cannot be an expression`;
}
function standalone_lineWithRange(hasX2, hasY2) {
    const channels = hasX2 && hasY2 ? 'x2 and y2' : hasX2 ? 'x2' : 'y2';
    return `Line mark is for continuous lines and thus cannot be used with ${channels}. We will use the rule mark (line segments) instead.`;
}
function standalone_orientOverridden(original, actual) {
    return `Specified orient "${original}" overridden with "${actual}".`;
}
// SCALE
const standalone_CANNOT_UNION_CUSTOM_DOMAIN_WITH_FIELD_DOMAIN = 'Custom domain scale cannot be unioned with default field-based domain.';
function standalone_cannotUseScalePropertyWithNonColor(prop) {
    return `Cannot use the scale property "${prop}" with non-color channel.`;
}
function standalone_cannotUseRelativeBandSizeWithNonBandScale(scaleType) {
    return `Cannot use the relative band size with ${scaleType} scale.`;
}
function standalone_unaggregateDomainHasNoEffectForRawField(fieldDef) {
    return `Using unaggregated domain with raw field has no effect (${standalone_util_stringify(fieldDef)}).`;
}
function standalone_unaggregateDomainWithNonSharedDomainOp(aggregate) {
    return `Unaggregated domain not applicable for "${aggregate}" since it produces values outside the origin domain of the source data.`;
}
function standalone_unaggregatedDomainWithLogScale(fieldDef) {
    return `Unaggregated domain is currently unsupported for log scale (${standalone_util_stringify(fieldDef)}).`;
}
function standalone_cannotApplySizeToNonOrientedMark(mark) {
    return `Cannot apply size to non-oriented mark "${mark}".`;
}
function standalone_scaleTypeNotWorkWithChannel(channel, scaleType, defaultScaleType) {
    return `Channel "${channel}" does not work with "${scaleType}" scale. We are using "${defaultScaleType}" scale instead.`;
}
function standalone_scaleTypeNotWorkWithFieldDef(scaleType, defaultScaleType) {
    return `FieldDef does not work with "${scaleType}" scale. We are using "${defaultScaleType}" scale instead.`;
}
function standalone_scalePropertyNotWorkWithScaleType(scaleType, propName, channel) {
    return `${channel}-scale's "${propName}" is dropped as it does not work with ${scaleType} scale.`;
}
function standalone_scaleTypeNotWorkWithMark(mark, scaleType) {
    return `Scale type "${scaleType}" does not work with mark "${mark}".`;
}
function standalone_stepDropped(channel) {
    return `The step for "${channel}" is dropped because the ${channel === 'width' ? 'x' : 'y'} is continuous.`;
}
function standalone_mergeConflictingProperty(property, propertyOf, v1, v2) {
    return `Conflicting ${propertyOf.toString()} property "${property.toString()}" (${standalone_util_stringify(v1)} and ${standalone_util_stringify(v2)}). Using ${standalone_util_stringify(v1)}.`;
}
function standalone_mergeConflictingDomainProperty(property, propertyOf, v1, v2) {
    return `Conflicting ${propertyOf.toString()} property "${property.toString()}" (${standalone_util_stringify(v1)} and ${standalone_util_stringify(v2)}). Using the union of the two domains.`;
}
function standalone_independentScaleMeansIndependentGuide(channel) {
    return `Setting the scale to be independent for "${channel}" means we also have to set the guide (axis or legend) to be independent.`;
}
function standalone_domainSortDropped(sort) {
    return `Dropping sort property ${standalone_util_stringify(sort)} as unioned domains only support boolean or op "count", "min", and "max".`;
}
const standalone_MORE_THAN_ONE_SORT = 'Domains that should be unioned has conflicting sort properties. Sort will be set to true.';
const standalone_FACETED_INDEPENDENT_DIFFERENT_SOURCES = 'Detected faceted independent scales that union domain of multiple fields from different data sources. We will use the first field. The result view size may be incorrect.';
const standalone_FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES = 'Detected faceted independent scales that union domain of the same fields from different source. We will assume that this is the same field from a different fork of the same data source. However, if this is not the case, the result view size may be incorrect.';
const standalone_FACETED_INDEPENDENT_SAME_SOURCE = 'Detected faceted independent scales that union domain of multiple fields from the same data source. We will use the first field. The result view size may be incorrect.';
// AXIS
const standalone_INVALID_CHANNEL_FOR_AXIS = 'Invalid channel for axis.';
// STACK
function standalone_cannotStackRangedMark(channel) {
    return `Cannot stack "${channel}" if there is already "${channel}2".`;
}
function standalone_stackNonLinearScale(scaleType) {
    return `Stack is applied to a non-linear scale (${scaleType}).`;
}
function standalone_stackNonSummativeAggregate(aggregate) {
    return `Stacking is applied even though the aggregate function is non-summative ("${aggregate}").`;
}
// TIMEUNIT
function standalone_invalidTimeUnit(unitName, value) {
    return `Invalid ${unitName}: ${standalone_util_stringify(value)}.`;
}
function standalone_droppedDay(d) {
    return `Dropping day from datetime ${standalone_util_stringify(d)} as day cannot be combined with other units.`;
}
function standalone_errorBarCenterAndExtentAreNotNeeded(center, extent) {
    return `${extent ? 'extent ' : ''}${extent && center ? 'and ' : ''}${center ? 'center ' : ''}${extent && center ? 'are ' : 'is '}not needed when data are aggregated.`;
}
function standalone_errorBarCenterIsUsedWithWrongExtent(center, extent, mark) {
    return `${center} is not usually used with ${extent} for ${mark}.`;
}
function standalone_errorBarContinuousAxisHasCustomizedAggregate(aggregate, compositeMark) {
    return `Continuous axis should not have customized aggregation function ${aggregate}; ${compositeMark} already agregates the axis.`;
}
function standalone_errorBand1DNotSupport(property) {
    return `1D error band does not support ${property}.`;
}
// CHANNEL
function standalone_channelRequiredForBinned(channel) {
    return `Channel ${channel} is required for "binned" bin.`;
}
function standalone_channelShouldNotBeUsedForBinned(channel) {
    return `Channel ${channel} should not be used with "binned" bin.`;
}
function standalone_domainRequiredForThresholdScale(channel) {
    return `Domain for ${channel} is required for threshold scale.`;
}
//# sourceMappingURL=message.js.map
;// ../../node_modules/vega-lite/build/src/log/index.js
/**
 * Vega-Lite's singleton logger utility.
 */
var standalone_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var standalone_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var standalone_LocalLogger_level;


/**
 * Main (default) Vega Logger instance for Vega-Lite.
 */
const standalone_main = standalone_logger(standalone_vega_util_module_Warn);
let standalone_current = standalone_main;
/**
 * Logger tool for checking if the code throws correct warning.
 */
class standalone_LocalLogger {
    constructor() {
        this.warns = [];
        this.infos = [];
        this.debugs = [];
        standalone_LocalLogger_level.set(this, Warn);
    }
    level(_) {
        if (_) {
            standalone_classPrivateFieldSet(this, standalone_LocalLogger_level, _, "f");
            return this;
        }
        return standalone_classPrivateFieldGet(this, standalone_LocalLogger_level, "f");
    }
    warn(...args) {
        if (standalone_classPrivateFieldGet(this, standalone_LocalLogger_level, "f") >= Warn)
            this.warns.push(...args);
        return this;
    }
    info(...args) {
        if (standalone_classPrivateFieldGet(this, standalone_LocalLogger_level, "f") >= Info)
            this.infos.push(...args);
        return this;
    }
    debug(...args) {
        if (standalone_classPrivateFieldGet(this, standalone_LocalLogger_level, "f") >= Debug)
            this.debugs.push(...args);
        return this;
    }
    error(...args) {
        if (standalone_classPrivateFieldGet(this, standalone_LocalLogger_level, "f") >= ErrorLevel)
            throw Error(...args);
        return this;
    }
}
standalone_LocalLogger_level = new WeakMap();
function standalone_log_wrap(f) {
    return () => {
        standalone_current = new standalone_LocalLogger();
        f(standalone_current);
        standalone_log_reset();
    };
}
/**
 * Set the singleton logger to be a custom logger.
 */
function standalone_log_set(newLogger) {
    standalone_current = newLogger;
    return standalone_current;
}
/**
 * Reset the main logger to use the default Vega Logger.
 */
function standalone_log_reset() {
    standalone_current = standalone_main;
    return standalone_current;
}
function standalone_log_error(...args) {
    standalone_current.error(...args);
}
function standalone_log_warn(...args) {
    standalone_current.warn(...args);
}
function standalone_log_info(...args) {
    standalone_current.info(...args);
}
function standalone_log_debug(...args) {
    standalone_current.debug(...args);
}
//# sourceMappingURL=index.js.map
;// ../../node_modules/vega-lite/build/src/datetime.js
// DateTime definition object




function standalone_isDateTime(o) {
    if (o && standalone_vega_util_module_isObject(o)) {
        for (const part of standalone_TIMEUNIT_PARTS) {
            if (standalone_util_hasProperty(o, part)) {
                return true;
            }
        }
    }
    return false;
}
const standalone_MONTHS = [
    'january',
    'february',
    'march',
    'april',
    'may',
    'june',
    'july',
    'august',
    'september',
    'october',
    'november',
    'december'
];
const standalone_SHORT_MONTHS = standalone_MONTHS.map(m => m.substr(0, 3));
const standalone_DAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
const standalone_SHORT_DAYS = standalone_DAYS.map(d => d.substr(0, 3));
function standalone_normalizeQuarter(q) {
    if (standalone_isNumeric(q)) {
        q = +q;
    }
    if (standalone_isNumber(q)) {
        if (q > 4) {
            standalone_log_warn(standalone_invalidTimeUnit('quarter', q));
        }
        // We accept 1-based quarter, so need to readjust to 0-based quarter
        return q - 1;
    }
    else {
        // Invalid quarter
        throw new Error(standalone_invalidTimeUnit('quarter', q));
    }
}
function standalone_normalizeMonth(m) {
    if (standalone_isNumeric(m)) {
        m = +m;
    }
    if (standalone_isNumber(m)) {
        // We accept 1-based month, so need to readjust to 0-based month
        return m - 1;
    }
    else {
        const lowerM = m.toLowerCase();
        const monthIndex = standalone_MONTHS.indexOf(lowerM);
        if (monthIndex !== -1) {
            return monthIndex; // 0 for january, ...
        }
        const shortM = lowerM.substr(0, 3);
        const shortMonthIndex = standalone_SHORT_MONTHS.indexOf(shortM);
        if (shortMonthIndex !== -1) {
            return shortMonthIndex;
        }
        // Invalid month
        throw new Error(standalone_invalidTimeUnit('month', m));
    }
}
function standalone_normalizeDay(d) {
    if (standalone_isNumeric(d)) {
        d = +d;
    }
    if (standalone_isNumber(d)) {
        // mod so that this can be both 0-based where 0 = sunday
        // and 1-based where 7=sunday
        return d % 7;
    }
    else {
        const lowerD = d.toLowerCase();
        const dayIndex = standalone_DAYS.indexOf(lowerD);
        if (dayIndex !== -1) {
            return dayIndex; // 0 for january, ...
        }
        const shortD = lowerD.substr(0, 3);
        const shortDayIndex = standalone_SHORT_DAYS.indexOf(shortD);
        if (shortDayIndex !== -1) {
            return shortDayIndex;
        }
        // Invalid day
        throw new Error(standalone_invalidTimeUnit('day', d));
    }
}
/**
 * @param d the date.
 * @param normalize whether to normalize quarter, month, day. This should probably be true if d is a DateTime.
 * @returns array of date time parts [year, month, day, hours, minutes, seconds, milliseconds]
 */
function standalone_dateTimeParts(d, normalize) {
    const parts = [];
    if (normalize && d.day !== undefined) {
        if (standalone_util_keys(d).length > 1) {
            standalone_log_warn(standalone_droppedDay(d));
            d = standalone_duplicate(d);
            delete d.day;
        }
    }
    if (d.year !== undefined) {
        parts.push(d.year);
    }
    else {
        // Just like Vega's timeunit transform, set default year to 2012, so domain conversion will be compatible with Vega
        // Note: 2012 is a leap year (and so the date February 29 is respected) that begins on a Sunday (and so days of the week will order properly at the beginning of the year).
        parts.push(2012);
    }
    if (d.month !== undefined) {
        const month = normalize ? standalone_normalizeMonth(d.month) : d.month;
        parts.push(month);
    }
    else if (d.quarter !== undefined) {
        const quarter = normalize ? standalone_normalizeQuarter(d.quarter) : d.quarter;
        parts.push(standalone_isNumber(quarter) ? quarter * 3 : `${quarter}*3`);
    }
    else {
        parts.push(0); // months start at zero in JS
    }
    if (d.date !== undefined) {
        parts.push(d.date);
    }
    else if (d.day !== undefined) {
        // HACK: Day only works as a standalone unit
        // This is only correct because we always set year to 2006 for day
        const day = normalize ? standalone_normalizeDay(d.day) : d.day;
        parts.push(standalone_isNumber(day) ? day + 1 : `${day}+1`);
    }
    else {
        parts.push(1); // Date starts at 1 in JS
    }
    // Note: can't use TimeUnit enum here as importing it will create
    // circular dependency problem!
    for (const timeUnit of ['hours', 'minutes', 'seconds', 'milliseconds']) {
        const unit = d[timeUnit];
        parts.push(typeof unit === 'undefined' ? 0 : unit);
    }
    return parts;
}
/**
 * Return Vega expression for a date time.
 *
 * @param d the date time.
 * @returns the Vega expression.
 */
function standalone_dateTimeToExpr(d) {
    const parts = standalone_dateTimeParts(d, true);
    const string = parts.join(', ');
    if (d.utc) {
        return `utc(${string})`;
    }
    else {
        return `datetime(${string})`;
    }
}
/**
 * Return Vega expression for a date time expression.
 *
 * @param d the internal date time object with expression.
 * @returns the Vega expression.
 */
function standalone_dateTimeExprToExpr(d) {
    const parts = standalone_dateTimeParts(d, false);
    const string = parts.join(', ');
    if (d.utc) {
        return `utc(${string})`;
    }
    else {
        return `datetime(${string})`;
    }
}
/**
 * @param d the date time.
 * @returns the timestamp.
 */
function standalone_dateTimeToTimestamp(d) {
    const parts = standalone_dateTimeParts(d, true);
    if (d.utc) {
        return +new Date(Date.UTC(...parts));
    }
    else {
        return +new Date(...parts);
    }
}
//# sourceMappingURL=datetime.js.map
;// ../../node_modules/vega-lite/build/src/timeunit.js




/** Time Unit that only corresponds to only one part of Date objects. */
const standalone_LOCAL_SINGLE_TIMEUNIT_INDEX = {
    year: 1,
    quarter: 1,
    month: 1,
    week: 1,
    day: 1,
    dayofyear: 1,
    date: 1,
    hours: 1,
    minutes: 1,
    seconds: 1,
    milliseconds: 1
};
const standalone_TIMEUNIT_PARTS = standalone_util_keys(standalone_LOCAL_SINGLE_TIMEUNIT_INDEX);
function standalone_isLocalSingleTimeUnit(timeUnit) {
    return standalone_vega_util_module_has(standalone_LOCAL_SINGLE_TIMEUNIT_INDEX, timeUnit);
}
const standalone_UTC_SINGLE_TIMEUNIT_INDEX = {
    utcyear: 1,
    utcquarter: 1,
    utcmonth: 1,
    utcweek: 1,
    utcday: 1,
    utcdayofyear: 1,
    utcdate: 1,
    utchours: 1,
    utcminutes: 1,
    utcseconds: 1,
    utcmilliseconds: 1
};
const standalone_LOCAL_MULTI_TIMEUNIT_INDEX = {
    yearquarter: 1,
    yearquartermonth: 1,
    yearmonth: 1,
    yearmonthdate: 1,
    yearmonthdatehours: 1,
    yearmonthdatehoursminutes: 1,
    yearmonthdatehoursminutesseconds: 1,
    yearweek: 1,
    yearweekday: 1,
    yearweekdayhours: 1,
    yearweekdayhoursminutes: 1,
    yearweekdayhoursminutesseconds: 1,
    yeardayofyear: 1,
    quartermonth: 1,
    monthdate: 1,
    monthdatehours: 1,
    monthdatehoursminutes: 1,
    monthdatehoursminutesseconds: 1,
    weekday: 1,
    weekdayhours: 1,
    weekdayhoursminutes: 1,
    weekdayhoursminutesseconds: 1,
    dayhours: 1,
    dayhoursminutes: 1,
    dayhoursminutesseconds: 1,
    hoursminutes: 1,
    hoursminutesseconds: 1,
    minutesseconds: 1,
    secondsmilliseconds: 1
};
const standalone_BINNED_LOCAL_TIMEUNIT_INDEX = {
    binnedyear: 1,
    binnedyearquarter: 1,
    binnedyearquartermonth: 1,
    binnedyearmonth: 1,
    binnedyearmonthdate: 1,
    binnedyearmonthdatehours: 1,
    binnedyearmonthdatehoursminutes: 1,
    binnedyearmonthdatehoursminutesseconds: 1,
    binnedyearweek: 1,
    binnedyearweekday: 1,
    binnedyearweekdayhours: 1,
    binnedyearweekdayhoursminutes: 1,
    binnedyearweekdayhoursminutesseconds: 1,
    binnedyeardayofyear: 1
};
const standalone_BINNED_UTC_TIMEUNIT_INDEX = {
    binnedutcyear: 1,
    binnedutcyearquarter: 1,
    binnedutcyearquartermonth: 1,
    binnedutcyearmonth: 1,
    binnedutcyearmonthdate: 1,
    binnedutcyearmonthdatehours: 1,
    binnedutcyearmonthdatehoursminutes: 1,
    binnedutcyearmonthdatehoursminutesseconds: 1,
    binnedutcyearweek: 1,
    binnedutcyearweekday: 1,
    binnedutcyearweekdayhours: 1,
    binnedutcyearweekdayhoursminutes: 1,
    binnedutcyearweekdayhoursminutesseconds: 1,
    binnedutcyeardayofyear: 1
};
const standalone_BINNED_TIMEUNIT_INDEX = {
    ...standalone_BINNED_LOCAL_TIMEUNIT_INDEX,
    ...standalone_BINNED_UTC_TIMEUNIT_INDEX
};
function standalone_isBinnedTimeUnit(timeUnit) {
    if (standalone_vega_util_module_isObject(timeUnit)) {
        return timeUnit.binned;
    }
    return standalone_isBinnedTimeUnitString(timeUnit);
}
function standalone_isBinnedTimeUnitString(timeUnit) {
    return timeUnit && timeUnit.startsWith('binned');
}
const standalone_UTC_MULTI_TIMEUNIT_INDEX = {
    utcyearquarter: 1,
    utcyearquartermonth: 1,
    utcyearmonth: 1,
    utcyearmonthdate: 1,
    utcyearmonthdatehours: 1,
    utcyearmonthdatehoursminutes: 1,
    utcyearmonthdatehoursminutesseconds: 1,
    utcyearweek: 1,
    utcyearweekday: 1,
    utcyearweekdayhours: 1,
    utcyearweekdayhoursminutes: 1,
    utcyearweekdayhoursminutesseconds: 1,
    utcyeardayofyear: 1,
    utcquartermonth: 1,
    utcmonthdate: 1,
    utcmonthdatehours: 1,
    utcmonthdatehoursminutes: 1,
    utcmonthdatehoursminutesseconds: 1,
    utcweekday: 1,
    utcweekdayhours: 1,
    utcweekdayhoursminutes: 1,
    utcweekdayhoursminutesseconds: 1,
    utcdayhours: 1,
    utcdayhoursminutes: 1,
    utcdayhoursminutesseconds: 1,
    utchoursminutes: 1,
    utchoursminutesseconds: 1,
    utcminutesseconds: 1,
    utcsecondsmilliseconds: 1
};
function standalone_isUTCTimeUnit(t) {
    return t.startsWith('utc');
}
function standalone_getLocalTimeUnitFromUTCTimeUnit(t) {
    return t.substring(3);
}
// In order of increasing specificity
const standalone_VEGALITE_TIMEFORMAT = {
    'year-month': '%b %Y ',
    'year-month-date': '%b %d, %Y '
};
function standalone_getTimeUnitParts(timeUnit) {
    return standalone_TIMEUNIT_PARTS.filter(part => standalone_containsTimeUnit(timeUnit, part));
}
function standalone_getSmallestTimeUnitPart(timeUnit) {
    const parts = standalone_getTimeUnitParts(timeUnit);
    return parts[parts.length - 1];
}
/** Returns true if fullTimeUnit contains the timeUnit, false otherwise. */
function standalone_containsTimeUnit(fullTimeUnit, timeUnit) {
    const index = fullTimeUnit.indexOf(timeUnit);
    if (index < 0) {
        return false;
    }
    // exclude milliseconds
    if (index > 0 && timeUnit === 'seconds' && fullTimeUnit.charAt(index - 1) === 'i') {
        return false;
    }
    // exclude dayofyear
    if (fullTimeUnit.length > index + 3 && timeUnit === 'day' && fullTimeUnit.charAt(index + 3) === 'o') {
        return false;
    }
    if (index > 0 && timeUnit === 'year' && fullTimeUnit.charAt(index - 1) === 'f') {
        return false;
    }
    return true;
}
/**
 * Returns Vega expression for a given timeUnit and fieldRef
 */
function standalone_timeunit_fieldExpr(fullTimeUnit, field, { end } = { end: false }) {
    const fieldRef = standalone_accessPathWithDatum(field);
    const utc = standalone_isUTCTimeUnit(fullTimeUnit) ? 'utc' : '';
    function func(timeUnit) {
        if (timeUnit === 'quarter') {
            // quarter starting at 0 (0,3,6,9).
            return `(${utc}quarter(${fieldRef})-1)`;
        }
        else {
            return `${utc}${timeUnit}(${fieldRef})`;
        }
    }
    let lastTimeUnit;
    const dateExpr = {};
    for (const part of standalone_TIMEUNIT_PARTS) {
        if (standalone_containsTimeUnit(fullTimeUnit, part)) {
            dateExpr[part] = func(part);
            lastTimeUnit = part;
        }
    }
    if (end) {
        dateExpr[lastTimeUnit] += '+1';
    }
    return standalone_dateTimeExprToExpr(dateExpr);
}
function standalone_timeUnitSpecifierExpression(timeUnit) {
    if (!timeUnit) {
        return undefined;
    }
    const timeUnitParts = standalone_getTimeUnitParts(timeUnit);
    return `timeUnitSpecifier(${standalone_util_stringify(timeUnitParts)}, ${standalone_util_stringify(standalone_VEGALITE_TIMEFORMAT)})`;
}
/**
 * Returns the signal expression used for axis labels for a time unit.
 */
function standalone_formatExpression(timeUnit, field, isUTCScale) {
    if (!timeUnit) {
        return undefined;
    }
    const expr = standalone_timeUnitSpecifierExpression(timeUnit);
    // We only use utcFormat for utc scale
    // For utc time units, the data is already converted as a part of timeUnit transform.
    // Thus, utc time units should use timeFormat to avoid shifting the time twice.
    const utc = isUTCScale || standalone_isUTCTimeUnit(timeUnit);
    return `${utc ? 'utc' : 'time'}Format(${field}, ${expr})`;
}
function standalone_normalizeTimeUnit(timeUnit) {
    if (!timeUnit) {
        return undefined;
    }
    let params;
    if (standalone_vega_util_module_isString(timeUnit)) {
        if (standalone_isBinnedTimeUnitString(timeUnit)) {
            params = {
                unit: timeUnit.substring(6),
                binned: true
            };
        }
        else {
            params = {
                unit: timeUnit
            };
        }
    }
    else if (standalone_vega_util_module_isObject(timeUnit)) {
        params = {
            ...timeUnit,
            ...(timeUnit.unit ? { unit: timeUnit.unit } : {})
        };
    }
    if (standalone_isUTCTimeUnit(params.unit)) {
        params.utc = true;
        params.unit = standalone_getLocalTimeUnitFromUTCTimeUnit(params.unit);
    }
    return params;
}
function standalone_timeUnitToString(tu) {
    const { utc, ...rest } = standalone_normalizeTimeUnit(tu);
    if (rest.unit) {
        return ((utc ? 'utc' : '') +
            standalone_util_keys(rest)
                .map(p => standalone_varName(`${p === 'unit' ? '' : `_${p}_`}${rest[p]}`))
                .join(''));
    }
    else {
        // when maxbins is specified instead of units
        return ((utc ? 'utc' : '') +
            'timeunit' +
            standalone_util_keys(rest)
                .map(p => standalone_varName(`_${p}_${rest[p]}`))
                .join(''));
    }
}
function standalone_durationExpr(timeUnit, wrap = x => x) {
    const normalizedTimeUnit = standalone_normalizeTimeUnit(timeUnit);
    const smallestUnitPart = standalone_getSmallestTimeUnitPart(normalizedTimeUnit.unit);
    if (smallestUnitPart && smallestUnitPart !== 'day') {
        const startDate = {
            year: 2001, // pick a non-leap year
            month: 1,
            date: 1,
            hours: 0,
            minutes: 0,
            seconds: 0,
            milliseconds: 0
        };
        const { step, part } = standalone_getDateTimePartAndStep(smallestUnitPart, normalizedTimeUnit.step);
        const endDate = {
            ...startDate,
            [part]: +startDate[part] + step
        };
        // Calculate timestamp duration for the smallest unit listed
        return `${wrap(standalone_dateTimeToExpr(endDate))} - ${wrap(standalone_dateTimeToExpr(startDate))}`;
    }
    return undefined;
}
const standalone_DATE_PARTS = {
    year: 1,
    month: 1,
    date: 1,
    hours: 1,
    minutes: 1,
    seconds: 1,
    milliseconds: 1
};
function standalone_isDatePart(timeUnit) {
    return standalone_vega_util_module_has(standalone_DATE_PARTS, timeUnit);
}
function standalone_getDateTimePartAndStep(timeUnit, step = 1) {
    if (standalone_isDatePart(timeUnit)) {
        return { part: timeUnit, step };
    }
    switch (timeUnit) {
        case 'day':
        case 'dayofyear':
            return { part: 'date', step };
        case 'quarter':
            return { part: 'month', step: step * 3 };
        case 'week':
            return { part: 'date', step: step * 7 };
    }
}
//# sourceMappingURL=timeunit.js.map
;// ../../node_modules/vega-lite/build/src/predicate.js






function standalone_isSelectionPredicate(predicate) {
    return standalone_util_hasProperty(predicate, 'param');
}
function standalone_isFieldEqualPredicate(predicate) {
    return !!predicate?.field && predicate.equal !== undefined;
}
function standalone_isFieldLTPredicate(predicate) {
    return !!predicate?.field && predicate.lt !== undefined;
}
function standalone_isFieldLTEPredicate(predicate) {
    return !!predicate?.field && predicate.lte !== undefined;
}
function standalone_isFieldGTPredicate(predicate) {
    return !!predicate?.field && predicate.gt !== undefined;
}
function standalone_isFieldGTEPredicate(predicate) {
    return !!predicate?.field && predicate.gte !== undefined;
}
function standalone_isFieldRangePredicate(predicate) {
    if (predicate?.field) {
        if (standalone_vega_util_module_isArray(predicate.range) && predicate.range.length === 2) {
            return true;
        }
        else if (standalone_isSignalRef(predicate.range)) {
            return true;
        }
    }
    return false;
}
function standalone_isFieldOneOfPredicate(predicate) {
    return (!!predicate?.field && (standalone_vega_util_module_isArray(predicate.oneOf) || standalone_vega_util_module_isArray(predicate.in)) // backward compatibility
    );
}
function standalone_isFieldValidPredicate(predicate) {
    return !!predicate?.field && predicate.valid !== undefined;
}
function standalone_isFieldPredicate(predicate) {
    return (standalone_isFieldOneOfPredicate(predicate) ||
        standalone_isFieldEqualPredicate(predicate) ||
        standalone_isFieldRangePredicate(predicate) ||
        standalone_isFieldLTPredicate(predicate) ||
        standalone_isFieldGTPredicate(predicate) ||
        standalone_isFieldLTEPredicate(predicate) ||
        standalone_isFieldGTEPredicate(predicate));
}
function standalone_predicateValueExpr(v, timeUnit) {
    return standalone_valueExpr(v, { timeUnit, wrapTime: true });
}
function standalone_predicateValuesExpr(vals, timeUnit) {
    return vals.map(v => standalone_predicateValueExpr(v, timeUnit));
}
// This method is used by Voyager. Do not change its behavior without changing Voyager.
function standalone_fieldFilterExpression(predicate, useInRange = true) {
    const { field } = predicate;
    const normalizedTimeUnit = standalone_normalizeTimeUnit(predicate.timeUnit);
    const { unit, binned } = normalizedTimeUnit || {};
    const rawFieldExpr = standalone_vgField(predicate, { expr: 'datum' });
    const fieldExpr = unit
        ? // For timeUnit, cast into integer with time() so we can use ===, inrange, indexOf to compare values directly.
            // TODO: We calculate timeUnit on the fly here. Consider if we would like to consolidate this with timeUnit pipeline
            // TODO: support utc
            `time(${!binned ? standalone_timeunit_fieldExpr(unit, field) : rawFieldExpr})`
        : rawFieldExpr;
    if (standalone_isFieldEqualPredicate(predicate)) {
        return `${fieldExpr}===${standalone_predicateValueExpr(predicate.equal, unit)}`;
    }
    else if (standalone_isFieldLTPredicate(predicate)) {
        const upper = predicate.lt;
        return `${fieldExpr}<${standalone_predicateValueExpr(upper, unit)}`;
    }
    else if (standalone_isFieldGTPredicate(predicate)) {
        const lower = predicate.gt;
        return `${fieldExpr}>${standalone_predicateValueExpr(lower, unit)}`;
    }
    else if (standalone_isFieldLTEPredicate(predicate)) {
        const upper = predicate.lte;
        return `${fieldExpr}<=${standalone_predicateValueExpr(upper, unit)}`;
    }
    else if (standalone_isFieldGTEPredicate(predicate)) {
        const lower = predicate.gte;
        return `${fieldExpr}>=${standalone_predicateValueExpr(lower, unit)}`;
    }
    else if (standalone_isFieldOneOfPredicate(predicate)) {
        return `indexof([${standalone_predicateValuesExpr(predicate.oneOf, unit).join(',')}], ${fieldExpr}) !== -1`;
    }
    else if (standalone_isFieldValidPredicate(predicate)) {
        return standalone_fieldValidPredicate(fieldExpr, predicate.valid);
    }
    else if (standalone_isFieldRangePredicate(predicate)) {
        const { range } = standalone_replaceExprRef(predicate);
        const lower = standalone_isSignalRef(range) ? { signal: `${range.signal}[0]` } : range[0];
        const upper = standalone_isSignalRef(range) ? { signal: `${range.signal}[1]` } : range[1];
        if (lower !== null && upper !== null && useInRange) {
            return ('inrange(' + fieldExpr + ', [' + standalone_predicateValueExpr(lower, unit) + ', ' + standalone_predicateValueExpr(upper, unit) + '])');
        }
        const exprs = [];
        if (lower !== null) {
            exprs.push(`${fieldExpr} >= ${standalone_predicateValueExpr(lower, unit)}`);
        }
        if (upper !== null) {
            exprs.push(`${fieldExpr} <= ${standalone_predicateValueExpr(upper, unit)}`);
        }
        return exprs.length > 0 ? exprs.join(' && ') : 'true';
    }
    /* istanbul ignore next: it should never reach here */
    throw new Error(`Invalid field predicate: ${standalone_util_stringify(predicate)}`);
}
function standalone_fieldValidPredicate(fieldExpr, valid = true) {
    if (valid) {
        return `isValid(${fieldExpr}) && isFinite(+${fieldExpr})`;
    }
    else {
        return `!isValid(${fieldExpr}) || !isFinite(+${fieldExpr})`;
    }
}
function standalone_normalizePredicate(f) {
    if (standalone_isFieldPredicate(f) && f.timeUnit) {
        return {
            ...f,
            timeUnit: standalone_normalizeTimeUnit(f.timeUnit)
        };
    }
    return f;
}
//# sourceMappingURL=predicate.js.map
;// ../../node_modules/vega-lite/build/src/type.js


/**
 * Data type based on level of measurement
 */
const standalone_type_Type = {
    quantitative: 'quantitative',
    ordinal: 'ordinal',
    temporal: 'temporal',
    nominal: 'nominal',
    geojson: 'geojson'
};
function standalone_isType(t) {
    return hasOwnProperty(standalone_type_Type, t);
}
function standalone_type_isContinuous(type) {
    return type === 'quantitative' || type === 'temporal';
}
function standalone_type_isDiscrete(type) {
    return type === 'ordinal' || type === 'nominal';
}
const standalone_QUANTITATIVE = standalone_type_Type.quantitative;
const standalone_ORDINAL = standalone_type_Type.ordinal;
const standalone_TEMPORAL = standalone_type_Type.temporal;
const standalone_NOMINAL = standalone_type_Type.nominal;
const standalone_GEOJSON = standalone_type_Type.geojson;
const standalone_TYPES = standalone_util_keys(standalone_type_Type);
/**
 * Get full, lowercase type name for a given type.
 * @param  type
 * @return Full type name.
 */
function standalone_getFullName(type) {
    if (type) {
        type = type.toLowerCase();
        switch (type) {
            case 'q':
            case standalone_QUANTITATIVE:
                return 'quantitative';
            case 't':
            case standalone_TEMPORAL:
                return 'temporal';
            case 'o':
            case standalone_ORDINAL:
                return 'ordinal';
            case 'n':
            case standalone_NOMINAL:
                return 'nominal';
            case standalone_GEOJSON:
                return 'geojson';
        }
    }
    // If we get invalid input, return undefined type.
    return undefined;
}
//# sourceMappingURL=type.js.map
;// ../../node_modules/vega-lite/build/src/scale.js






const standalone_ScaleType = {
    // Continuous - Quantitative
    LINEAR: 'linear',
    LOG: 'log',
    POW: 'pow',
    SQRT: 'sqrt',
    SYMLOG: 'symlog',
    IDENTITY: 'identity',
    SEQUENTIAL: 'sequential',
    // Continuous - Time
    TIME: 'time',
    UTC: 'utc',
    // Discretizing scales
    QUANTILE: 'quantile',
    QUANTIZE: 'quantize',
    THRESHOLD: 'threshold',
    BIN_ORDINAL: 'bin-ordinal',
    // Discrete scales
    ORDINAL: 'ordinal',
    POINT: 'point',
    BAND: 'band'
};
/**
 * Index for scale categories -- only scale of the same categories can be merged together.
 * Current implementation is trying to be conservative and avoid merging scale type that might not work together
 */
const standalone_SCALE_CATEGORY_INDEX = {
    linear: 'numeric',
    log: 'numeric',
    pow: 'numeric',
    sqrt: 'numeric',
    symlog: 'numeric',
    identity: 'numeric',
    sequential: 'numeric',
    time: 'time',
    utc: 'time',
    ordinal: 'ordinal',
    'bin-ordinal': 'bin-ordinal', // TODO: should bin-ordinal support merging with other
    point: 'ordinal-position',
    band: 'ordinal-position',
    quantile: 'discretizing',
    quantize: 'discretizing',
    threshold: 'discretizing'
};
const standalone_SCALE_TYPES = standalone_util_keys(standalone_SCALE_CATEGORY_INDEX);
/**
 * Whether the two given scale types can be merged together.
 */
function standalone_scaleCompatible(scaleType1, scaleType2) {
    const scaleCategory1 = standalone_SCALE_CATEGORY_INDEX[scaleType1];
    const scaleCategory2 = standalone_SCALE_CATEGORY_INDEX[scaleType2];
    return (scaleCategory1 === scaleCategory2 ||
        (scaleCategory1 === 'ordinal-position' && scaleCategory2 === 'time') ||
        (scaleCategory2 === 'ordinal-position' && scaleCategory1 === 'time'));
}
/**
 * Index for scale precedence -- high score = higher priority for merging.
 */
const standalone_SCALE_PRECEDENCE_INDEX = {
    // numeric
    linear: 0,
    log: 1,
    pow: 1,
    sqrt: 1,
    symlog: 1,
    identity: 1,
    sequential: 1,
    // time
    time: 0,
    utc: 0,
    // ordinal-position -- these have higher precedence than continuous scales as they support more types of data
    point: 10,
    band: 11, // band has higher precedence as it is better for interaction
    // non grouped types
    ordinal: 0,
    'bin-ordinal': 0,
    quantile: 0,
    quantize: 0,
    threshold: 0
};
/**
 * Return scale categories -- only scale of the same categories can be merged together.
 */
function standalone_scaleTypePrecedence(scaleType) {
    return standalone_SCALE_PRECEDENCE_INDEX[scaleType];
}
const standalone_QUANTITATIVE_SCALES = new Set([
    'linear',
    'log',
    'pow',
    'sqrt',
    'symlog'
]);
const standalone_CONTINUOUS_TO_CONTINUOUS_SCALES = new Set([
    ...standalone_QUANTITATIVE_SCALES,
    'time',
    'utc'
]);
function standalone_isQuantitative(type) {
    return standalone_QUANTITATIVE_SCALES.has(type);
}
const standalone_CONTINUOUS_TO_DISCRETE_SCALES = new Set([
    'quantile',
    'quantize',
    'threshold'
]);
const standalone_CONTINUOUS_DOMAIN_SCALES = new Set([
    ...standalone_CONTINUOUS_TO_CONTINUOUS_SCALES,
    ...standalone_CONTINUOUS_TO_DISCRETE_SCALES,
    'sequential',
    'identity'
]);
const standalone_DISCRETE_DOMAIN_SCALES = new Set([
    'ordinal',
    'bin-ordinal',
    'point',
    'band'
]);
const standalone_TIME_SCALE_TYPES = new Set(['time', 'utc']);
function standalone_hasDiscreteDomain(type) {
    return standalone_DISCRETE_DOMAIN_SCALES.has(type);
}
function standalone_hasContinuousDomain(type) {
    return standalone_CONTINUOUS_DOMAIN_SCALES.has(type);
}
function standalone_isContinuousToContinuous(type) {
    return standalone_CONTINUOUS_TO_CONTINUOUS_SCALES.has(type);
}
function standalone_isContinuousToDiscrete(type) {
    return standalone_CONTINUOUS_TO_DISCRETE_SCALES.has(type);
}
const standalone_defaultScaleConfig = {
    pointPadding: 0.5,
    barBandPaddingInner: 0.1,
    rectBandPaddingInner: 0,
    tickBandPaddingInner: 0.25,
    bandWithNestedOffsetPaddingInner: 0.2,
    bandWithNestedOffsetPaddingOuter: 0.2,
    minBandSize: 2,
    minFontSize: 8,
    maxFontSize: 40,
    minOpacity: 0.3,
    maxOpacity: 0.8,
    // FIXME: revise if these *can* become ratios of width/height step
    minSize: 4, // Point size is area. For square point, 9 = 3 pixel ^ 2, not too small!
    minStrokeWidth: 1,
    maxStrokeWidth: 4,
    quantileCount: 4,
    quantizeCount: 4,
    zero: true,
    framesPerSecond: 2,
    animationDuration: 5
};
function standalone_isExtendedScheme(scheme) {
    return !standalone_vega_util_module_isString(scheme) && standalone_util_hasProperty(scheme, 'name');
}
function standalone_isParameterDomain(domain) {
    return standalone_util_hasProperty(domain, 'param');
}
function standalone_isDomainUnionWith(domain) {
    return standalone_util_hasProperty(domain, 'unionWith');
}
function standalone_isFieldRange(range) {
    return standalone_vega_util_module_isObject(range) && 'field' in range;
}
const standalone_SCALE_PROPERTY_INDEX = {
    type: 1,
    domain: 1,
    domainMax: 1,
    domainMin: 1,
    domainMid: 1,
    domainRaw: 1,
    align: 1,
    range: 1,
    rangeMax: 1,
    rangeMin: 1,
    scheme: 1,
    bins: 1,
    // Other properties
    reverse: 1,
    round: 1,
    // quantitative / time
    clamp: 1,
    nice: 1,
    // quantitative
    base: 1,
    exponent: 1,
    constant: 1,
    interpolate: 1,
    zero: 1, // zero depends on domain
    // band/point
    padding: 1,
    paddingInner: 1,
    paddingOuter: 1
};
const standalone_SCALE_PROPERTIES = standalone_util_keys(standalone_SCALE_PROPERTY_INDEX);
const { type: standalone_scale_type, domain: standalone_scale_domain, range: standalone_scale_range, rangeMax: standalone_rangeMax, rangeMin: standalone_rangeMin, scheme: standalone_scale_scheme, ...standalone_NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTY_INDEX } = standalone_SCALE_PROPERTY_INDEX;
const standalone_NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES = standalone_util_keys(standalone_NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTY_INDEX);
function standalone_scaleTypeSupportProperty(scaleType, propName) {
    switch (propName) {
        case 'type':
        case 'domain':
        case 'reverse':
        case 'range':
            return true;
        case 'scheme':
        case 'interpolate':
            return !['point', 'band', 'identity'].includes(scaleType);
        case 'bins':
            return !['point', 'band', 'identity', 'ordinal'].includes(scaleType);
        case 'round':
            return standalone_isContinuousToContinuous(scaleType) || scaleType === 'band' || scaleType === 'point';
        case 'padding':
        case 'rangeMin':
        case 'rangeMax':
            return standalone_isContinuousToContinuous(scaleType) || ['point', 'band'].includes(scaleType);
        case 'paddingOuter':
        case 'align':
            return ['point', 'band'].includes(scaleType);
        case 'paddingInner':
            return scaleType === 'band';
        case 'domainMax':
        case 'domainMid':
        case 'domainMin':
        case 'domainRaw':
        case 'clamp':
            return standalone_isContinuousToContinuous(scaleType);
        case 'nice':
            return standalone_isContinuousToContinuous(scaleType) || scaleType === 'quantize' || scaleType === 'threshold';
        case 'exponent':
            return scaleType === 'pow';
        case 'base':
            return scaleType === 'log';
        case 'constant':
            return scaleType === 'symlog';
        case 'zero':
            return (standalone_hasContinuousDomain(scaleType) &&
                !standalone_util_contains([
                    'log', // log scale cannot have zero value
                    'time',
                    'utc', // zero is not meaningful for time
                    'threshold', // threshold requires custom domain so zero does not matter
                    'quantile' // quantile depends on distribution so zero does not matter
                ], scaleType));
    }
}
/**
 * Returns undefined if the input channel supports the input scale property name
 */
function standalone_channelScalePropertyIncompatability(channel, propName) {
    switch (propName) {
        case 'interpolate':
        case 'scheme':
        case 'domainMid':
            if (!standalone_isColorChannel(channel)) {
                return standalone_cannotUseScalePropertyWithNonColor(propName);
            }
            return undefined;
        case 'align':
        case 'type':
        case 'bins':
        case 'domain':
        case 'domainMax':
        case 'domainMin':
        case 'domainRaw':
        case 'range':
        case 'base':
        case 'exponent':
        case 'constant':
        case 'nice':
        case 'padding':
        case 'paddingInner':
        case 'paddingOuter':
        case 'rangeMax':
        case 'rangeMin':
        case 'reverse':
        case 'round':
        case 'clamp':
        case 'zero':
            return undefined; // GOOD!
    }
}
function standalone_scaleTypeSupportDataType(specifiedType, fieldDefType) {
    if (standalone_util_contains([standalone_ORDINAL, standalone_NOMINAL], fieldDefType)) {
        return specifiedType === undefined || standalone_hasDiscreteDomain(specifiedType);
    }
    else if (fieldDefType === standalone_TEMPORAL) {
        return standalone_util_contains([standalone_ScaleType.TIME, standalone_ScaleType.UTC, undefined], specifiedType);
    }
    else if (fieldDefType === standalone_QUANTITATIVE) {
        return standalone_isQuantitative(specifiedType) || standalone_isContinuousToDiscrete(specifiedType) || specifiedType === undefined;
    }
    return true;
}
function standalone_channelSupportScaleType(channel, scaleType, hasNestedOffsetScale = false) {
    if (!standalone_isScaleChannel(channel)) {
        return false;
    }
    switch (channel) {
        case standalone_channel_X:
        case standalone_channel_Y:
        case standalone_XOFFSET:
        case standalone_YOFFSET:
        case standalone_THETA:
        case standalone_RADIUS:
            if (standalone_isContinuousToContinuous(scaleType)) {
                return true;
            }
            else if (scaleType === 'band') {
                return true;
            }
            else if (scaleType === 'point') {
                /*
                  Point scale can't be use if the position has a nested offset scale
                  because if there is a nested scale, then it's band.
                */
                return !hasNestedOffsetScale;
            }
            return false;
        case standalone_TIME:
            return standalone_util_contains(['linear', 'band'], scaleType);
        case standalone_channel_SIZE: // TODO: size and opacity can support ordinal with more modification
        case standalone_STROKEWIDTH:
        case standalone_OPACITY:
        case standalone_FILLOPACITY:
        case standalone_STROKEOPACITY:
        case standalone_ANGLE:
            // Although it generally doesn't make sense to use band with size and opacity,
            // it can also work since we use band: 0.5 to get midpoint.
            return (standalone_isContinuousToContinuous(scaleType) ||
                standalone_isContinuousToDiscrete(scaleType) ||
                standalone_util_contains(['band', 'point', 'ordinal'], scaleType));
        case standalone_COLOR:
        case standalone_FILL:
        case standalone_STROKE:
            return scaleType !== 'band'; // band does not make sense with color
        case standalone_STROKEDASH:
        case standalone_SHAPE:
            return scaleType === 'ordinal' || standalone_isContinuousToDiscrete(scaleType);
    }
}
//# sourceMappingURL=scale.js.map
;// ../../node_modules/vega-lite/build/src/invalid.js

function standalone_isScaleInvalidDataIncludeAsValue(invalidDataMode) {
    return standalone_vega_util_module_isObject(invalidDataMode) && 'value' in invalidDataMode;
}
//# sourceMappingURL=invalid.js.map
;// ../../node_modules/vega-lite/build/src/mark.js


/**
 * All types of primitive marks.
 */
const standalone_mark_Mark = {
    arc: 'arc',
    area: 'area',
    bar: 'bar',
    image: 'image',
    line: 'line',
    point: 'point',
    rect: 'rect',
    rule: 'rule',
    text: 'text',
    tick: 'tick',
    trail: 'trail',
    circle: 'circle',
    square: 'square',
    geoshape: 'geoshape'
};
const standalone_ARC = standalone_mark_Mark.arc;
const standalone_AREA = standalone_mark_Mark.area;
const standalone_BAR = standalone_mark_Mark.bar;
const standalone_IMAGE = standalone_mark_Mark.image;
const standalone_LINE = standalone_mark_Mark.line;
const standalone_POINT = standalone_mark_Mark.point;
const standalone_RECT = standalone_mark_Mark.rect;
const standalone_RULE = standalone_mark_Mark.rule;
const standalone_mark_TEXT = standalone_mark_Mark.text;
const standalone_TICK = standalone_mark_Mark.tick;
const standalone_TRAIL = standalone_mark_Mark.trail;
const standalone_CIRCLE = standalone_mark_Mark.circle;
const standalone_SQUARE = standalone_mark_Mark.square;
const standalone_GEOSHAPE = standalone_mark_Mark.geoshape;
function standalone_isMark(m) {
    return hasOwnProperty(standalone_mark_Mark, m);
}
const standalone_PATH_MARKS = (/* unused pure expression or super */ null && (['line', 'area', 'trail']));
function standalone_isPathMark(m) {
    return ['line', 'area', 'trail'].includes(m);
}
function standalone_isRectBasedMark(m) {
    return ['rect', 'bar', 'image', 'arc', 'tick' /* arc is rect/interval in polar coordinate */].includes(m);
}
const standalone_PRIMITIVE_MARKS = new Set(standalone_util_keys(standalone_mark_Mark));
function standalone_isMarkDef(mark) {
    return standalone_util_hasProperty(mark, 'type');
}
function standalone_isPrimitiveMark(mark) {
    const markType = standalone_isMarkDef(mark) ? mark.type : mark;
    return standalone_PRIMITIVE_MARKS.has(markType);
}
const standalone_STROKE_CONFIG = [
    'stroke',
    'strokeWidth',
    'strokeDash',
    'strokeDashOffset',
    'strokeOpacity',
    'strokeJoin',
    'strokeMiterLimit'
];
const standalone_FILL_CONFIG = ['fill', 'fillOpacity'];
const standalone_FILL_STROKE_CONFIG = [...standalone_STROKE_CONFIG, ...standalone_FILL_CONFIG];
const standalone_VL_ONLY_MARK_CONFIG_INDEX = {
    color: 1,
    filled: 1,
    invalid: 1,
    order: 1,
    radius2: 1,
    theta2: 1,
    timeUnitBandSize: 1,
    timeUnitBandPosition: 1
};
const standalone_VL_ONLY_MARK_CONFIG_PROPERTIES = standalone_util_keys(standalone_VL_ONLY_MARK_CONFIG_INDEX);
const standalone_VL_ONLY_RECT_CONFIG = [
    'binSpacing',
    'continuousBandSize',
    'discreteBandSize',
    'minBandSize'
];
const standalone_VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = {
    area: ['line', 'point'],
    bar: standalone_VL_ONLY_RECT_CONFIG,
    rect: standalone_VL_ONLY_RECT_CONFIG,
    line: ['point'],
    tick: ['bandSize', 'thickness', ...standalone_VL_ONLY_RECT_CONFIG]
};
const standalone_defaultMarkConfig = {
    color: '#4c78a8',
    invalid: 'break-paths-show-path-domains',
    timeUnitBandSize: 1
};
const standalone_MARK_CONFIG_INDEX = {
    mark: 1,
    arc: 1,
    area: 1,
    bar: 1,
    circle: 1,
    image: 1,
    line: 1,
    point: 1,
    rect: 1,
    rule: 1,
    square: 1,
    text: 1,
    tick: 1,
    trail: 1,
    geoshape: 1
};
const standalone_MARK_CONFIGS = standalone_util_keys(standalone_MARK_CONFIG_INDEX);
function standalone_isRelativeBandSize(o) {
    return standalone_util_hasProperty(o, 'band');
}
const standalone_BAR_CORNER_RADIUS_INDEX = {
    horizontal: ['cornerRadiusTopRight', 'cornerRadiusBottomRight'],
    vertical: ['cornerRadiusTopLeft', 'cornerRadiusTopRight']
};
const standalone_DEFAULT_RECT_BAND_SIZE = 5;
const standalone_defaultRectConfig = {
    binSpacing: 0,
    continuousBandSize: standalone_DEFAULT_RECT_BAND_SIZE,
    minBandSize: 0.25,
    timeUnitBandPosition: 0.5
};
const standalone_defaultBarConfig = {
    ...standalone_defaultRectConfig,
    binSpacing: 1
};
const standalone_defaultTickConfig = {
    ...standalone_defaultRectConfig,
    thickness: 1
};
function standalone_getMarkType(m) {
    return standalone_isMarkDef(m) ? m.type : m;
}
//# sourceMappingURL=mark.js.map
;// ../../node_modules/vega-lite/build/src/compile/invalid/normalizeInvalidDataMode.js
function standalone_normalizeInvalidDataMode(mode, { isPath }) {
    if (mode === undefined || mode === 'break-paths-show-path-domains') {
        return isPath ? 'break-paths-show-domains' : 'filter';
    }
    else if (mode === null) {
        return 'show';
    }
    return mode;
}
//# sourceMappingURL=normalizeInvalidDataMode.js.map
;// ../../node_modules/vega-lite/build/src/compile/invalid/ScaleInvalidDataMode.js




function standalone_getScaleInvalidDataMode({ markDef, config, scaleChannel, scaleType, isCountAggregate }) {
    if (!scaleType || !standalone_hasContinuousDomain(scaleType) || isCountAggregate) {
        // - Discrete scales can always display null as another category
        // - Count cannot output null values
        return 'always-valid';
    }
    const invalidMode = standalone_normalizeInvalidDataMode(standalone_getMarkPropOrConfig('invalid', markDef, config), {
        isPath: standalone_isPathMark(markDef.type)
    });
    const scaleOutputForInvalid = config.scale?.invalid?.[scaleChannel];
    if (scaleOutputForInvalid !== undefined) {
        // Regardless of the current invalid mode, if the channel has a default value, we consider the field valid.
        return 'show';
    }
    return invalidMode;
}
function standalone_shouldBreakPath(mode) {
    return mode === 'break-paths-filter-domains' || mode === 'break-paths-show-domains';
}
//# sourceMappingURL=ScaleInvalidDataMode.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/scaledZeroOrMinOrMax.js
function standalone_scaledZeroOrMinOrMax({ scaleName, scale, mode }) {
    const domain = `domain('${scaleName}')`;
    if (!scale || !scaleName) {
        return undefined;
    }
    const min = `${domain}[0]`;
    const max = `peek(${domain})`; // peek = the last item of the array
    // If there is a scale (and hence its name)
    const domainHasZero = scale.domainHasZero();
    // zeroOrMin or zeroOrMax mode
    if (domainHasZero === 'definitely') {
        return {
            scale: scaleName,
            value: 0
        };
    }
    else if (domainHasZero === 'maybe') {
        const nonZeroValue = mode === 'zeroOrMin' ? min : max;
        return { signal: `scale('${scaleName}', inrange(0, ${domain}) ? 0 : ${nonZeroValue})` };
    }
    else {
        // domainHasZero === 'definitely-not'
        return { signal: `scale('${scaleName}', ${mode === 'zeroOrMin' ? min : max})` };
    }
}
//# sourceMappingURL=scaledZeroOrMinOrMax.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/invalid.js







function standalone_getConditionalValueRefForIncludingInvalidValue({ scaleChannel, channelDef, scale, scaleName, markDef, config }) {
    const scaleType = scale?.get('type');
    const fieldDef = standalone_getFieldDef(channelDef);
    const isCountAggregate = standalone_isCountingAggregateOp(fieldDef?.aggregate);
    const invalidDataMode = standalone_getScaleInvalidDataMode({
        scaleChannel,
        markDef,
        config,
        scaleType,
        isCountAggregate
    });
    if (fieldDef && invalidDataMode === 'show') {
        const includeAs = config.scale.invalid?.[scaleChannel] ?? 'zero-or-min';
        return {
            test: standalone_fieldValidPredicate(standalone_vgField(fieldDef, { expr: 'datum' }), false),
            ...standalone_refForInvalidValues(includeAs, scale, scaleName)
        };
    }
    return undefined;
}
function standalone_refForInvalidValues(includeAs, scale, scaleName) {
    if (standalone_isScaleInvalidDataIncludeAsValue(includeAs)) {
        const { value } = includeAs;
        return standalone_isSignalRef(value) ? { signal: value.signal } : { value };
    }
    return standalone_scaledZeroOrMinOrMax({
        scale,
        scaleName,
        mode: 'zeroOrMin'
    });
}
//# sourceMappingURL=invalid.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/valueref.js













function standalone_midPointRefWithPositionInvalidTest(params) {
    const { channel, channelDef, markDef, scale, scaleName, config } = params;
    const scaleChannel = standalone_getMainRangeChannel(channel);
    const mainRef = standalone_midPoint(params);
    const valueRefForIncludingInvalid = standalone_getConditionalValueRefForIncludingInvalidValue({
        scaleChannel,
        channelDef,
        scale,
        scaleName,
        markDef,
        config
    });
    return valueRefForIncludingInvalid !== undefined ? [valueRefForIncludingInvalid, mainRef] : mainRef;
}
function standalone_datumDefToExpr(datumDef) {
    const { datum } = datumDef;
    if (standalone_isDateTime(datum)) {
        return standalone_dateTimeToExpr(datum);
    }
    return `${standalone_util_stringify(datum)}`;
}
function standalone_valueRefForFieldOrDatumDef(fieldDef, scaleName, opt, encode) {
    const ref = {};
    if (scaleName) {
        ref.scale = scaleName;
    }
    if (standalone_isDatumDef(fieldDef)) {
        const { datum } = fieldDef;
        if (standalone_isDateTime(datum)) {
            ref.signal = standalone_dateTimeToExpr(datum);
        }
        else if (standalone_isSignalRef(datum)) {
            ref.signal = datum.signal;
        }
        else if (standalone_isExprRef(datum)) {
            ref.signal = datum.expr;
        }
        else {
            ref.value = datum;
        }
    }
    else {
        ref.field = standalone_vgField(fieldDef, opt);
    }
    if (encode) {
        const { offset, band } = encode;
        if (offset) {
            ref.offset = offset;
        }
        if (band) {
            ref.band = band;
        }
    }
    return ref;
}
/**
 * Signal that returns the middle of a bin from start and end field. Should only be used with x and y.
 */
function standalone_interpolatedSignalRef({ scaleName, fieldOrDatumDef, fieldOrDatumDef2, offset, startSuffix, endSuffix = 'end', bandPosition = 0.5 }) {
    const expr = !standalone_isSignalRef(bandPosition) && 0 < bandPosition && bandPosition < 1 ? 'datum' : undefined;
    const start = standalone_vgField(fieldOrDatumDef, { expr, suffix: startSuffix });
    const end = fieldOrDatumDef2 !== undefined
        ? standalone_vgField(fieldOrDatumDef2, { expr })
        : standalone_vgField(fieldOrDatumDef, { suffix: endSuffix, expr });
    const ref = {};
    if (bandPosition === 0 || bandPosition === 1) {
        ref.scale = scaleName;
        const field = bandPosition === 0 ? start : end;
        ref.field = field;
    }
    else {
        const datum = standalone_isSignalRef(bandPosition)
            ? `(1-${bandPosition.signal}) * ${start} + ${bandPosition.signal} * ${end}`
            : `${1 - bandPosition} * ${start} + ${bandPosition} * ${end}`;
        ref.signal = `scale("${scaleName}", ${datum})`;
    }
    if (offset) {
        ref.offset = offset;
    }
    return ref;
}
function standalone_binSizeExpr({ scaleName, fieldDef }) {
    const start = standalone_vgField(fieldDef, { expr: 'datum' });
    const end = standalone_vgField(fieldDef, { expr: 'datum', suffix: 'end' });
    return `abs(scale("${scaleName}", ${end}) - scale("${scaleName}", ${start}))`;
}
/**
 * @returns {VgValueRef} Value Ref for xc / yc or mid point for other channels.
 */
function standalone_midPoint({ channel, channelDef, channel2Def, markDef, config, scaleName, scale, stack, offset, defaultRef, bandPosition }) {
    // TODO: datum support
    if (channelDef) {
        /* istanbul ignore else */
        if (standalone_isFieldOrDatumDef(channelDef)) {
            const scaleType = scale?.get('type');
            if (standalone_isTypedFieldDef(channelDef)) {
                bandPosition ?? (bandPosition = standalone_getBandPosition({
                    fieldDef: channelDef,
                    fieldDef2: channel2Def,
                    markDef,
                    config
                }));
                const { bin, timeUnit, type } = channelDef;
                if (standalone_isBinning(bin) || (bandPosition && timeUnit && type === standalone_TEMPORAL)) {
                    // Use middle only for x an y to place marks in the center between start and end of the bin range.
                    // We do not use the mid point for other channels (e.g. size) so that properties of legends and marks match.
                    if (stack?.impute) {
                        // For stack, we computed bin_mid so we can impute.
                        return standalone_valueRefForFieldOrDatumDef(channelDef, scaleName, { binSuffix: 'mid' }, { offset });
                    }
                    if (bandPosition && !standalone_hasDiscreteDomain(scaleType)) {
                        // if band = 0, no need to call interpolation
                        // For non-stack, we can just calculate bin mid on the fly using signal.
                        return standalone_interpolatedSignalRef({ scaleName, fieldOrDatumDef: channelDef, bandPosition, offset });
                    }
                    return standalone_valueRefForFieldOrDatumDef(channelDef, scaleName, standalone_binRequiresRange(channelDef, channel) ? { binSuffix: 'range' } : {}, {
                        offset
                    });
                }
                else if (standalone_isBinned(bin)) {
                    if (standalone_isFieldDef(channel2Def)) {
                        return standalone_interpolatedSignalRef({
                            scaleName,
                            fieldOrDatumDef: channelDef,
                            fieldOrDatumDef2: channel2Def,
                            bandPosition,
                            offset
                        });
                    }
                    else {
                        const channel2 = channel === standalone_channel_X ? standalone_channel_X2 : standalone_channel_Y2;
                        standalone_log_warn(standalone_channelRequiredForBinned(channel2));
                    }
                }
            }
            return standalone_valueRefForFieldOrDatumDef(channelDef, scaleName, standalone_hasDiscreteDomain(scaleType) ? { binSuffix: 'range' } : {}, // no need for bin suffix if there is no scale
            {
                offset,
                // For band, to get mid point, need to offset by half of the band
                band: scaleType === 'band' ? (bandPosition ?? channelDef.bandPosition ?? 0.5) : undefined
            });
        }
        else if (standalone_isValueDef(channelDef)) {
            const value = channelDef.value;
            const offsetMixins = offset ? { offset } : {};
            return { ...standalone_widthHeightValueOrSignalRef(channel, value), ...offsetMixins };
        }
        // If channelDef is neither field def or value def, it's a condition-only def.
        // In such case, we will use default ref.
    }
    if (standalone_vega_util_module_isFunction(defaultRef)) {
        defaultRef = defaultRef();
    }
    if (defaultRef) {
        // for non-position, ref could be undefined.
        return {
            ...defaultRef,
            // only include offset when it is non-zero (zero = no offset)
            ...(offset ? { offset } : {})
        };
    }
    return defaultRef;
}
/**
 * Convert special "width" and "height" values in Vega-Lite into Vega value ref.
 */
function standalone_widthHeightValueOrSignalRef(channel, value) {
    if (standalone_util_contains(['x', 'x2'], channel) && value === 'width') {
        return { field: { group: 'width' } };
    }
    else if (standalone_util_contains(['y', 'y2'], channel) && value === 'height') {
        return { field: { group: 'height' } };
    }
    return standalone_signalOrValueRef(value);
}
//# sourceMappingURL=valueref.js.map
;// ../../node_modules/vega-lite/build/src/compile/format.js










function standalone_isCustomFormatType(formatType) {
    return formatType && formatType !== 'number' && formatType !== 'time';
}
function standalone_customFormatExpr(formatType, field, format) {
    return `${formatType}(${field}${format ? `, ${standalone_util_stringify(format)}` : ''})`;
}
const standalone_format_BIN_RANGE_DELIMITER = ' \u2013 ';
function standalone_formatSignalRef({ fieldOrDatumDef, format, formatType, expr, normalizeStack, config }) {
    if (standalone_isCustomFormatType(formatType)) {
        return standalone_formatCustomType({
            fieldOrDatumDef,
            format,
            formatType,
            expr,
            config
        });
    }
    const field = standalone_fieldToFormat(fieldOrDatumDef, expr, normalizeStack);
    const type = standalone_channelDefType(fieldOrDatumDef);
    if (format === undefined && formatType === undefined && config.customFormatTypes) {
        if (type === 'quantitative') {
            if (normalizeStack && config.normalizedNumberFormatType)
                return standalone_formatCustomType({
                    fieldOrDatumDef,
                    format: config.normalizedNumberFormat,
                    formatType: config.normalizedNumberFormatType,
                    expr,
                    config
                });
            if (config.numberFormatType) {
                return standalone_formatCustomType({
                    fieldOrDatumDef,
                    format: config.numberFormat,
                    formatType: config.numberFormatType,
                    expr,
                    config
                });
            }
        }
        if (type === 'temporal' &&
            config.timeFormatType &&
            standalone_isFieldDef(fieldOrDatumDef) &&
            fieldOrDatumDef.timeUnit === undefined) {
            return standalone_formatCustomType({
                fieldOrDatumDef,
                format: config.timeFormat,
                formatType: config.timeFormatType,
                expr,
                config
            });
        }
    }
    if (standalone_isFieldOrDatumDefForTimeFormat(fieldOrDatumDef)) {
        const signal = standalone_timeFormatExpression({
            field,
            timeUnit: standalone_isFieldDef(fieldOrDatumDef) ? standalone_normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit : undefined,
            format,
            formatType: config.timeFormatType,
            rawTimeFormat: config.timeFormat,
            isUTCScale: standalone_isScaleFieldDef(fieldOrDatumDef) && fieldOrDatumDef.scale?.type === standalone_ScaleType.UTC
        });
        return signal ? { signal } : undefined;
    }
    format = standalone_numberFormat({ type, specifiedFormat: format, config, normalizeStack });
    if (standalone_isFieldDef(fieldOrDatumDef) && standalone_isBinning(fieldOrDatumDef.bin)) {
        const endField = standalone_vgField(fieldOrDatumDef, { expr, binSuffix: 'end' });
        return {
            signal: standalone_binFormatExpression(field, endField, format, formatType, config)
        };
    }
    else if (format || standalone_channelDefType(fieldOrDatumDef) === 'quantitative') {
        return {
            signal: `${standalone_formatExpr(field, format)}`
        };
    }
    else {
        return { signal: `isValid(${field}) ? ${field} : ""+${field}` };
    }
}
function standalone_fieldToFormat(fieldOrDatumDef, expr, normalizeStack) {
    if (standalone_isFieldDef(fieldOrDatumDef)) {
        if (normalizeStack) {
            return `${standalone_vgField(fieldOrDatumDef, { expr, suffix: 'end' })}-${standalone_vgField(fieldOrDatumDef, {
                expr,
                suffix: 'start'
            })}`;
        }
        else {
            return standalone_vgField(fieldOrDatumDef, { expr });
        }
    }
    else {
        return standalone_datumDefToExpr(fieldOrDatumDef);
    }
}
function standalone_formatCustomType({ fieldOrDatumDef, format, formatType, expr, normalizeStack, config, field }) {
    field ?? (field = standalone_fieldToFormat(fieldOrDatumDef, expr, normalizeStack));
    if (field !== 'datum.value' && // For axis/legend, we can't correctly know the end of the bin from `datum`
        standalone_isFieldDef(fieldOrDatumDef) &&
        standalone_isBinning(fieldOrDatumDef.bin)) {
        const endField = standalone_vgField(fieldOrDatumDef, { expr, binSuffix: 'end' });
        return {
            signal: standalone_binFormatExpression(field, endField, format, formatType, config)
        };
    }
    return { signal: standalone_customFormatExpr(formatType, field, format) };
}
function standalone_guideFormat(fieldOrDatumDef, type, format, formatType, config, omitTimeFormatConfig // axis doesn't use config.timeFormat
) {
    if (standalone_vega_util_module_isString(formatType) && standalone_isCustomFormatType(formatType)) {
        return undefined; // handled in encode block
    }
    else if (format === undefined && formatType === undefined && config.customFormatTypes) {
        if (standalone_channelDefType(fieldOrDatumDef) === 'quantitative') {
            if (config.normalizedNumberFormatType &&
                standalone_isPositionFieldOrDatumDef(fieldOrDatumDef) &&
                fieldOrDatumDef.stack === 'normalize') {
                return undefined; // handled in encode block
            }
            if (config.numberFormatType) {
                return undefined; // handled in encode block
            }
        }
    }
    if (standalone_isPositionFieldOrDatumDef(fieldOrDatumDef) &&
        fieldOrDatumDef.stack === 'normalize' &&
        config.normalizedNumberFormat) {
        return standalone_numberFormat({
            type: 'quantitative',
            config,
            normalizeStack: true
        });
    }
    if (standalone_isFieldOrDatumDefForTimeFormat(fieldOrDatumDef)) {
        const timeUnit = standalone_isFieldDef(fieldOrDatumDef) ? standalone_normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit : undefined;
        if (timeUnit === undefined && config.customFormatTypes && config.timeFormatType) {
            return undefined; // hanlded in encode block
        }
        return standalone_format_timeFormat({ specifiedFormat: format, timeUnit, config, omitTimeFormatConfig });
    }
    return standalone_numberFormat({ type, specifiedFormat: format, config });
}
function standalone_guideFormatType(formatType, fieldOrDatumDef, scaleType) {
    if (formatType && (standalone_isSignalRef(formatType) || formatType === 'number' || formatType === 'time')) {
        return formatType;
    }
    if (standalone_isFieldOrDatumDefForTimeFormat(fieldOrDatumDef) && scaleType !== 'time' && scaleType !== 'utc') {
        return standalone_isFieldDef(fieldOrDatumDef) && standalone_normalizeTimeUnit(fieldOrDatumDef?.timeUnit)?.utc ? 'utc' : 'time';
    }
    return undefined;
}
/**
 * Returns number format for a fieldDef.
 */
function standalone_numberFormat({ type, specifiedFormat, config, normalizeStack }) {
    // Specified format in axis/legend has higher precedence than fieldDef.format
    if (standalone_vega_util_module_isString(specifiedFormat)) {
        return specifiedFormat;
    }
    if (type === standalone_QUANTITATIVE) {
        // we only apply the default if the field is quantitative
        return normalizeStack ? config.normalizedNumberFormat : config.numberFormat;
    }
    return undefined;
}
/**
 * Returns time format for a fieldDef for use in guides.
 */
function standalone_format_timeFormat({ specifiedFormat, timeUnit, config, omitTimeFormatConfig }) {
    if (specifiedFormat) {
        return specifiedFormat;
    }
    if (timeUnit) {
        return {
            signal: standalone_timeUnitSpecifierExpression(timeUnit)
        };
    }
    return omitTimeFormatConfig ? undefined : config.timeFormat;
}
function standalone_formatExpr(field, format) {
    return `format(${field}, "${format || ''}")`;
}
function standalone_binNumberFormatExpr(field, format, formatType, config) {
    if (standalone_isCustomFormatType(formatType)) {
        return standalone_customFormatExpr(formatType, field, format);
    }
    return standalone_formatExpr(field, (standalone_vega_util_module_isString(format) ? format : undefined) ?? config.numberFormat);
}
function standalone_binFormatExpression(startField, endField, format, formatType, config) {
    if (format === undefined && formatType === undefined && config.customFormatTypes && config.numberFormatType) {
        return standalone_binFormatExpression(startField, endField, config.numberFormat, config.numberFormatType, config);
    }
    const start = standalone_binNumberFormatExpr(startField, format, formatType, config);
    const end = standalone_binNumberFormatExpr(endField, format, formatType, config);
    return `${standalone_fieldValidPredicate(startField, false)} ? "null" : ${start} + "${standalone_format_BIN_RANGE_DELIMITER}" + ${end}`;
}
/**
 * Returns the time expression used for axis/legend labels or text mark for a temporal field
 */
function standalone_timeFormatExpression({ field, timeUnit, format, formatType, rawTimeFormat, isUTCScale }) {
    if (!timeUnit || format) {
        // If there is no time unit, or if user explicitly specifies format for axis/legend/text.
        if (!timeUnit && formatType) {
            return `${formatType}(${field}, '${format}')`;
        }
        format = standalone_vega_util_module_isString(format) ? format : rawTimeFormat; // only use provided timeFormat if there is no timeUnit.
        return `${isUTCScale ? 'utc' : 'time'}Format(${field}, '${format}')`;
    }
    else {
        return standalone_formatExpression(timeUnit, field, isUTCScale);
    }
}
//# sourceMappingURL=format.js.map
;// ../../node_modules/vega-lite/build/src/sort.js


const standalone_DEFAULT_SORT_OP = 'min';
const standalone_SORT_BY_CHANNEL_INDEX = {
    x: 1,
    y: 1,
    color: 1,
    fill: 1,
    stroke: 1,
    strokeWidth: 1,
    size: 1,
    shape: 1,
    fillOpacity: 1,
    strokeOpacity: 1,
    opacity: 1,
    text: 1
};
function standalone_isSortByChannel(c) {
    return standalone_vega_util_module_has(standalone_SORT_BY_CHANNEL_INDEX, c);
}
function standalone_isSortByEncoding(sort) {
    return standalone_util_hasProperty(sort, 'encoding');
}
function standalone_isSortField(sort) {
    return sort && (sort.op === 'count' || standalone_util_hasProperty(sort, 'field'));
}
function standalone_isSortArray(sort) {
    return sort && standalone_vega_util_module_isArray(sort);
}
//# sourceMappingURL=sort.js.map
;// ../../node_modules/vega-lite/build/src/spec/facet.js

function standalone_isFacetMapping(f) {
    return standalone_util_hasProperty(f, 'row') || standalone_util_hasProperty(f, 'column');
}
function standalone_isFacetFieldDef(channelDef) {
    return standalone_util_hasProperty(channelDef, 'header');
}
function standalone_isFacetSpec(spec) {
    return standalone_util_hasProperty(spec, 'facet');
}
//# sourceMappingURL=facet.js.map
;// ../../node_modules/vega-lite/build/src/channeldef.js

















function standalone_isConditionalParameter(c) {
    return standalone_util_hasProperty(c, 'param');
}
function standalone_isRepeatRef(field) {
    return !standalone_vega_util_module_isString(field) && standalone_util_hasProperty(field, 'repeat');
}
function standalone_toFieldDefBase(fieldDef) {
    const { field, timeUnit, bin, aggregate } = fieldDef;
    return {
        ...(timeUnit ? { timeUnit } : {}),
        ...(bin ? { bin } : {}),
        ...(aggregate ? { aggregate } : {}),
        field
    };
}
function standalone_isSortableFieldDef(fieldDef) {
    return standalone_util_hasProperty(fieldDef, 'sort');
}
function standalone_getBandPosition({ fieldDef, fieldDef2, markDef: mark, config }) {
    if (standalone_isFieldOrDatumDef(fieldDef) && fieldDef.bandPosition !== undefined) {
        return fieldDef.bandPosition;
    }
    if (standalone_isFieldDef(fieldDef)) {
        const { timeUnit, bin } = fieldDef;
        if (timeUnit && !fieldDef2) {
            return standalone_getMarkConfig('timeUnitBandPosition', mark, config);
        }
        else if (standalone_isBinning(bin)) {
            return 0.5;
        }
    }
    return undefined;
}
function standalone_getBandSize({ channel, fieldDef, fieldDef2, markDef: mark, config, scaleType, useVlSizeChannel }) {
    const sizeChannel = standalone_getSizeChannel(channel);
    const size = standalone_getMarkPropOrConfig(useVlSizeChannel ? 'size' : sizeChannel, mark, config, {
        vgChannel: sizeChannel
    });
    if (size !== undefined) {
        return size;
    }
    if (standalone_isFieldDef(fieldDef)) {
        const { timeUnit, bin } = fieldDef;
        if (timeUnit && !fieldDef2) {
            return { band: standalone_getMarkConfig('timeUnitBandSize', mark, config) };
        }
        else if (standalone_isBinning(bin) && !standalone_hasDiscreteDomain(scaleType)) {
            return { band: 1 };
        }
    }
    if (standalone_isRectBasedMark(mark.type)) {
        if (scaleType) {
            if (standalone_hasDiscreteDomain(scaleType)) {
                return config[mark.type]?.discreteBandSize || { band: 1 };
            }
            else {
                return config[mark.type]?.continuousBandSize;
            }
        }
        return config[mark.type]?.discreteBandSize;
    }
    return undefined;
}
function standalone_hasBandEnd(fieldDef, fieldDef2, markDef, config) {
    if (standalone_isBinning(fieldDef.bin) || (fieldDef.timeUnit && standalone_isTypedFieldDef(fieldDef) && fieldDef.type === 'temporal')) {
        // Need to check bandPosition because non-rect marks (e.g., point) with timeUnit
        // doesn't have to use bandEnd if there is no bandPosition.
        return standalone_getBandPosition({ fieldDef, fieldDef2, markDef, config }) !== undefined;
    }
    return false;
}
function standalone_isOrderOnlyDef(orderDef) {
    return standalone_util_hasProperty(orderDef, 'sort') && !standalone_util_hasProperty(orderDef, 'field');
}
function standalone_isConditionalDef(channelDef) {
    return standalone_util_hasProperty(channelDef, 'condition');
}
/**
 * Return if a channelDef is a ConditionalValueDef with ConditionFieldDef
 */
function standalone_hasConditionalFieldDef(channelDef) {
    const condition = channelDef?.['condition'];
    return !!condition && !standalone_vega_util_module_isArray(condition) && standalone_isFieldDef(condition);
}
function standalone_hasConditionalFieldOrDatumDef(channelDef) {
    const condition = channelDef?.['condition'];
    return !!condition && !standalone_vega_util_module_isArray(condition) && standalone_isFieldOrDatumDef(condition);
}
function standalone_hasConditionalValueDef(channelDef) {
    const condition = channelDef?.['condition'];
    return !!condition && (standalone_vega_util_module_isArray(condition) || standalone_isValueDef(condition));
}
function standalone_isFieldDef(channelDef) {
    return standalone_util_hasProperty(channelDef, 'field') || channelDef?.aggregate === 'count';
}
function standalone_channelDefType(channelDef) {
    return channelDef?.['type'];
}
function standalone_isDatumDef(channelDef) {
    return standalone_util_hasProperty(channelDef, 'datum');
}
function standalone_isContinuousFieldOrDatumDef(cd) {
    // TODO: make datum support DateTime object
    return (standalone_isTypedFieldDef(cd) && !standalone_channeldef_isDiscrete(cd)) || standalone_isNumericDataDef(cd);
}
function standalone_isUnbinnedQuantitativeFieldOrDatumDef(cd) {
    // TODO: make datum support DateTime object
    return (standalone_isTypedFieldDef(cd) && cd.type === 'quantitative' && !cd.bin) || standalone_isNumericDataDef(cd);
}
function standalone_isNumericDataDef(cd) {
    return standalone_isDatumDef(cd) && standalone_isNumber(cd.datum);
}
function standalone_isFieldOrDatumDef(channelDef) {
    return standalone_isFieldDef(channelDef) || standalone_isDatumDef(channelDef);
}
function standalone_isTypedFieldDef(channelDef) {
    return (channelDef &&
        (standalone_util_hasProperty(channelDef, 'field') || channelDef['aggregate'] === 'count') &&
        standalone_util_hasProperty(channelDef, 'type'));
}
function standalone_isValueDef(channelDef) {
    return standalone_util_hasProperty(channelDef, 'value');
}
function standalone_isScaleFieldDef(channelDef) {
    return standalone_util_hasProperty(channelDef, 'scale') || standalone_util_hasProperty(channelDef, 'sort');
}
function standalone_isPositionFieldOrDatumDef(channelDef) {
    return standalone_util_hasProperty(channelDef, 'axis') || standalone_util_hasProperty(channelDef, 'stack') || standalone_util_hasProperty(channelDef, 'impute');
}
function standalone_isMarkPropFieldOrDatumDef(channelDef) {
    return standalone_util_hasProperty(channelDef, 'legend');
}
function standalone_isStringFieldOrDatumDef(channelDef) {
    return standalone_util_hasProperty(channelDef, 'format') || standalone_util_hasProperty(channelDef, 'formatType');
}
function standalone_toStringFieldDef(fieldDef) {
    // omit properties that don't exist in string field defs
    return standalone_omit(fieldDef, ['legend', 'axis', 'header', 'scale']);
}
function standalone_isOpFieldDef(fieldDef) {
    return standalone_util_hasProperty(fieldDef, 'op');
}
/**
 * Get a Vega field reference from a Vega-Lite field def.
 */
function standalone_vgField(fieldDef, opt = {}) {
    let field = fieldDef.field;
    const prefix = opt.prefix;
    let suffix = opt.suffix;
    let argAccessor = ''; // for accessing argmin/argmax field at the end without getting escaped
    if (standalone_isCount(fieldDef)) {
        field = standalone_internalField('count');
    }
    else {
        let fn;
        if (!opt.nofn) {
            if (standalone_isOpFieldDef(fieldDef)) {
                fn = fieldDef.op;
            }
            else {
                const { bin, aggregate, timeUnit } = fieldDef;
                if (standalone_isBinning(bin)) {
                    fn = standalone_binToString(bin);
                    suffix = (opt.binSuffix ?? '') + (opt.suffix ?? '');
                }
                else if (aggregate) {
                    if (standalone_isArgmaxDef(aggregate)) {
                        argAccessor = `["${field}"]`;
                        field = `argmax_${aggregate.argmax}`;
                    }
                    else if (standalone_isArgminDef(aggregate)) {
                        argAccessor = `["${field}"]`;
                        field = `argmin_${aggregate.argmin}`;
                    }
                    else {
                        fn = String(aggregate);
                    }
                }
                else if (timeUnit && !standalone_isBinnedTimeUnit(timeUnit)) {
                    fn = standalone_timeUnitToString(timeUnit);
                    suffix = ((!['range', 'mid'].includes(opt.binSuffix) && opt.binSuffix) || '') + (opt.suffix ?? '');
                }
            }
        }
        if (fn) {
            field = field ? `${fn}_${field}` : fn;
        }
    }
    if (suffix) {
        field = `${field}_${suffix}`;
    }
    if (prefix) {
        field = `${prefix}_${field}`;
    }
    if (opt.forAs) {
        return standalone_removePathFromField(field);
    }
    else if (opt.expr) {
        // Expression to access flattened field. No need to escape dots.
        return standalone_flatAccessWithDatum(field, opt.expr) + argAccessor;
    }
    else {
        // We flattened all fields so paths should have become dot.
        return standalone_replacePathInField(field) + argAccessor;
    }
}
function standalone_channeldef_isDiscrete(def) {
    switch (def.type) {
        case 'nominal':
        case 'ordinal':
        case 'geojson':
            return true;
        case 'quantitative':
            return standalone_isFieldDef(def) && !!def.bin;
        case 'temporal':
            return false;
    }
    throw new Error(standalone_invalidFieldType(def.type));
}
function standalone_channeldef_isDiscretizing(def) {
    return standalone_isScaleFieldDef(def) && standalone_isContinuousToDiscrete(def.scale?.type);
}
function standalone_isCount(fieldDef) {
    return fieldDef.aggregate === 'count';
}
function standalone_verbalTitleFormatter(fieldDef, config) {
    const { field, bin, timeUnit, aggregate } = fieldDef;
    if (aggregate === 'count') {
        return config.countTitle;
    }
    else if (standalone_isBinning(bin)) {
        return `${field} (binned)`;
    }
    else if (timeUnit && !standalone_isBinnedTimeUnit(timeUnit)) {
        const unit = standalone_normalizeTimeUnit(timeUnit)?.unit;
        if (unit) {
            return `${field} (${standalone_getTimeUnitParts(unit).join('-')})`;
        }
    }
    else if (aggregate) {
        if (standalone_isArgmaxDef(aggregate)) {
            return `${field} for max ${aggregate.argmax}`;
        }
        else if (standalone_isArgminDef(aggregate)) {
            return `${field} for min ${aggregate.argmin}`;
        }
        else {
            return `${standalone_titleCase(aggregate)} of ${field}`;
        }
    }
    return field;
}
function standalone_functionalTitleFormatter(fieldDef) {
    const { aggregate, bin, timeUnit, field } = fieldDef;
    if (standalone_isArgmaxDef(aggregate)) {
        return `${field} for argmax(${aggregate.argmax})`;
    }
    else if (standalone_isArgminDef(aggregate)) {
        return `${field} for argmin(${aggregate.argmin})`;
    }
    const timeUnitParams = timeUnit && !standalone_isBinnedTimeUnit(timeUnit) ? standalone_normalizeTimeUnit(timeUnit) : undefined;
    const fn = aggregate || timeUnitParams?.unit || (timeUnitParams?.maxbins && 'timeunit') || (standalone_isBinning(bin) && 'bin');
    return fn ? `${fn.toUpperCase()}(${field})` : field;
}
const standalone_defaultTitleFormatter = (fieldDef, config) => {
    switch (config.fieldTitle) {
        case 'plain':
            return fieldDef.field;
        case 'functional':
            return standalone_functionalTitleFormatter(fieldDef);
        default:
            return standalone_verbalTitleFormatter(fieldDef, config);
    }
};
let standalone_titleFormatter = standalone_defaultTitleFormatter;
function standalone_setTitleFormatter(formatter) {
    standalone_titleFormatter = formatter;
}
function standalone_resetTitleFormatter() {
    standalone_setTitleFormatter(standalone_defaultTitleFormatter);
}
function standalone_channeldef_title(fieldOrDatumDef, config, { allowDisabling, includeDefault = true }) {
    const guideTitle = standalone_getGuide(fieldOrDatumDef)?.title;
    if (!standalone_isFieldDef(fieldOrDatumDef)) {
        return guideTitle ?? fieldOrDatumDef.title;
    }
    const fieldDef = fieldOrDatumDef;
    const def = includeDefault ? standalone_defaultTitle(fieldDef, config) : undefined;
    if (allowDisabling) {
        return standalone_getFirstDefined(guideTitle, fieldDef.title, def);
    }
    else {
        return guideTitle ?? fieldDef.title ?? def;
    }
}
function standalone_getGuide(fieldDef) {
    if (standalone_isPositionFieldOrDatumDef(fieldDef) && fieldDef.axis) {
        return fieldDef.axis;
    }
    else if (standalone_isMarkPropFieldOrDatumDef(fieldDef) && fieldDef.legend) {
        return fieldDef.legend;
    }
    else if (standalone_isFacetFieldDef(fieldDef) && fieldDef.header) {
        return fieldDef.header;
    }
    return undefined;
}
function standalone_defaultTitle(fieldDef, config) {
    return standalone_titleFormatter(fieldDef, config);
}
function standalone_getFormatMixins(fieldDef) {
    if (standalone_isStringFieldOrDatumDef(fieldDef)) {
        const { format, formatType } = fieldDef;
        return { format, formatType };
    }
    else {
        const guide = standalone_getGuide(fieldDef) ?? {};
        const { format, formatType } = guide;
        return { format, formatType };
    }
}
function standalone_defaultType(fieldDef, channel) {
    switch (channel) {
        case 'latitude':
        case 'longitude':
            return 'quantitative';
        case 'row':
        case 'column':
        case 'facet':
        case 'shape':
        case 'strokeDash':
            return 'nominal';
        case 'order':
            return 'ordinal';
    }
    if (standalone_isSortableFieldDef(fieldDef) && standalone_vega_util_module_isArray(fieldDef.sort)) {
        return 'ordinal';
    }
    const { aggregate, bin, timeUnit } = fieldDef;
    if (timeUnit) {
        return 'temporal';
    }
    if (bin || (aggregate && !standalone_isArgmaxDef(aggregate) && !standalone_isArgminDef(aggregate))) {
        return 'quantitative';
    }
    if (standalone_isScaleFieldDef(fieldDef) && fieldDef.scale?.type) {
        switch (standalone_SCALE_CATEGORY_INDEX[fieldDef.scale.type]) {
            case 'numeric':
            case 'discretizing':
                return 'quantitative';
            case 'time':
                return 'temporal';
        }
    }
    return 'nominal';
}
/**
 * Returns the fieldDef -- either from the outer channelDef or from the condition of channelDef.
 * @param channelDef
 */
function standalone_getFieldDef(channelDef) {
    if (standalone_isFieldDef(channelDef)) {
        return channelDef;
    }
    else if (standalone_hasConditionalFieldDef(channelDef)) {
        return channelDef.condition;
    }
    return undefined;
}
function standalone_getFieldOrDatumDef(channelDef) {
    if (standalone_isFieldOrDatumDef(channelDef)) {
        return channelDef;
    }
    else if (standalone_hasConditionalFieldOrDatumDef(channelDef)) {
        return channelDef.condition;
    }
    return undefined;
}
/**
 * Convert type to full, lowercase type, or augment the fieldDef with a default type if missing.
 */
function standalone_initChannelDef(channelDef, channel, config, opt = {}) {
    if (standalone_vega_util_module_isString(channelDef) || standalone_isNumber(channelDef) || standalone_isBoolean(channelDef)) {
        const primitiveType = standalone_vega_util_module_isString(channelDef) ? 'string' : standalone_isNumber(channelDef) ? 'number' : 'boolean';
        standalone_log_warn(standalone_primitiveChannelDef(channel, primitiveType, channelDef));
        return { value: channelDef };
    }
    // If a fieldDef contains a field, we need type.
    if (standalone_isFieldOrDatumDef(channelDef)) {
        return standalone_initFieldOrDatumDef(channelDef, channel, config, opt);
    }
    else if (standalone_hasConditionalFieldOrDatumDef(channelDef)) {
        return {
            ...channelDef,
            // Need to cast as normalizeFieldDef normally return FieldDef, but here we know that it is definitely Condition<FieldDef>
            condition: standalone_initFieldOrDatumDef(channelDef.condition, channel, config, opt)
        };
    }
    return channelDef;
}
function standalone_initFieldOrDatumDef(fd, channel, config, opt) {
    if (standalone_isStringFieldOrDatumDef(fd)) {
        const { format, formatType, ...rest } = fd;
        if (standalone_isCustomFormatType(formatType) && !config.customFormatTypes) {
            standalone_log_warn(standalone_customFormatTypeNotAllowed(channel));
            return standalone_initFieldOrDatumDef(rest, channel, config, opt);
        }
    }
    else {
        const guideType = standalone_isPositionFieldOrDatumDef(fd)
            ? 'axis'
            : standalone_isMarkPropFieldOrDatumDef(fd)
                ? 'legend'
                : standalone_isFacetFieldDef(fd)
                    ? 'header'
                    : null;
        if (guideType && fd[guideType]) {
            const { format, formatType, ...newGuide } = fd[guideType];
            if (standalone_isCustomFormatType(formatType) && !config.customFormatTypes) {
                standalone_log_warn(standalone_customFormatTypeNotAllowed(channel));
                return standalone_initFieldOrDatumDef({ ...fd, [guideType]: newGuide }, channel, config, opt);
            }
        }
    }
    if (standalone_isFieldDef(fd)) {
        return standalone_initFieldDef(fd, channel, opt);
    }
    return standalone_initDatumDef(fd);
}
function standalone_initDatumDef(datumDef) {
    let type = datumDef['type'];
    if (type) {
        return datumDef;
    }
    const { datum } = datumDef;
    type = standalone_isNumber(datum) ? 'quantitative' : standalone_vega_util_module_isString(datum) ? 'nominal' : standalone_isDateTime(datum) ? 'temporal' : undefined;
    return { ...datumDef, type };
}
function standalone_initFieldDef(fd, channel, { compositeMark = false } = {}) {
    const { aggregate, timeUnit, bin, field } = fd;
    const fieldDef = { ...fd };
    // Drop invalid aggregate
    if (!compositeMark && aggregate && !standalone_isAggregateOp(aggregate) && !standalone_isArgmaxDef(aggregate) && !standalone_isArgminDef(aggregate)) {
        standalone_log_warn(standalone_invalidAggregate(aggregate));
        delete fieldDef.aggregate;
    }
    // Normalize Time Unit
    if (timeUnit) {
        fieldDef.timeUnit = standalone_normalizeTimeUnit(timeUnit);
    }
    if (field) {
        fieldDef.field = `${field}`;
    }
    // Normalize bin
    if (standalone_isBinning(bin)) {
        fieldDef.bin = standalone_normalizeBin(bin, channel);
    }
    if (standalone_isBinned(bin) && !standalone_isXorY(channel)) {
        standalone_log_warn(standalone_channelShouldNotBeUsedForBinned(channel));
    }
    // Normalize Type
    if (standalone_isTypedFieldDef(fieldDef)) {
        const { type } = fieldDef;
        const fullType = standalone_getFullName(type);
        if (type !== fullType) {
            // convert short type to full type
            fieldDef.type = fullType;
        }
        if (type !== 'quantitative') {
            if (standalone_isCountingAggregateOp(aggregate)) {
                standalone_log_warn(standalone_invalidFieldTypeForCountAggregate(type, aggregate));
                fieldDef.type = 'quantitative';
            }
        }
    }
    else if (!standalone_isSecondaryRangeChannel(channel)) {
        // If type is empty / invalid, then augment with default type
        const newType = standalone_defaultType(fieldDef, channel);
        fieldDef['type'] = newType;
    }
    if (standalone_isTypedFieldDef(fieldDef)) {
        const { compatible, warning } = standalone_channelCompatibility(fieldDef, channel) || {};
        if (compatible === false) {
            standalone_log_warn(warning);
        }
    }
    if (standalone_isSortableFieldDef(fieldDef) && standalone_vega_util_module_isString(fieldDef.sort)) {
        const { sort } = fieldDef;
        if (standalone_isSortByChannel(sort)) {
            return {
                ...fieldDef,
                sort: { encoding: sort }
            };
        }
        const sub = sort.substring(1);
        if (sort.charAt(0) === '-' && standalone_isSortByChannel(sub)) {
            return {
                ...fieldDef,
                sort: { encoding: sub, order: 'descending' }
            };
        }
    }
    if (standalone_isFacetFieldDef(fieldDef)) {
        const { header } = fieldDef;
        if (header) {
            const { orient, ...rest } = header;
            if (orient) {
                return {
                    ...fieldDef,
                    header: {
                        ...rest,
                        labelOrient: header.labelOrient || orient,
                        titleOrient: header.titleOrient || orient
                    }
                };
            }
        }
    }
    return fieldDef;
}
function standalone_normalizeBin(bin, channel) {
    if (standalone_isBoolean(bin)) {
        return { maxbins: standalone_autoMaxBins(channel) };
    }
    else if (bin === 'binned') {
        return {
            binned: true
        };
    }
    else if (!bin.maxbins && !bin.step) {
        return { ...bin, maxbins: standalone_autoMaxBins(channel) };
    }
    else {
        return bin;
    }
}
const standalone_COMPATIBLE = { compatible: true };
function standalone_channelCompatibility(fieldDef, channel) {
    const type = fieldDef.type;
    if (type === 'geojson' && channel !== 'shape') {
        return {
            compatible: false,
            warning: `Channel ${channel} should not be used with a geojson data.`
        };
    }
    switch (channel) {
        case standalone_ROW:
        case standalone_COLUMN:
        case standalone_FACET:
            if (!standalone_channeldef_isDiscrete(fieldDef)) {
                return {
                    compatible: false,
                    warning: standalone_channelShouldBeDiscrete(channel)
                };
            }
            return standalone_COMPATIBLE;
        case standalone_channel_X:
        case standalone_channel_Y:
        case standalone_XOFFSET:
        case standalone_YOFFSET:
        case standalone_COLOR:
        case standalone_FILL:
        case standalone_STROKE:
        case standalone_TEXT:
        case standalone_DETAIL:
        case standalone_KEY:
        case standalone_TOOLTIP:
        case standalone_HREF:
        case standalone_channel_URL:
        case standalone_ANGLE:
        case standalone_THETA:
        case standalone_RADIUS:
        case standalone_DESCRIPTION:
            return standalone_COMPATIBLE;
        case standalone_LONGITUDE:
        case standalone_LONGITUDE2:
        case standalone_LATITUDE:
        case standalone_LATITUDE2:
            if (type !== standalone_QUANTITATIVE) {
                return {
                    compatible: false,
                    warning: `Channel ${channel} should be used with a quantitative field only, not ${fieldDef.type} field.`
                };
            }
            return standalone_COMPATIBLE;
        case standalone_OPACITY:
        case standalone_FILLOPACITY:
        case standalone_STROKEOPACITY:
        case standalone_STROKEWIDTH:
        case standalone_channel_SIZE:
        case standalone_THETA2:
        case standalone_RADIUS2:
        case standalone_channel_X2:
        case standalone_channel_Y2:
        case standalone_TIME:
            if (type === 'nominal' && !fieldDef['sort']) {
                return {
                    compatible: false,
                    warning: `Channel ${channel} should not be used with an unsorted discrete field.`
                };
            }
            return standalone_COMPATIBLE;
        case standalone_SHAPE:
        case standalone_STROKEDASH:
            if (!standalone_channeldef_isDiscrete(fieldDef) && !standalone_channeldef_isDiscretizing(fieldDef)) {
                return {
                    compatible: false,
                    warning: standalone_channelShouldBeDiscreteOrDiscretizing(channel)
                };
            }
            return standalone_COMPATIBLE;
        case standalone_ORDER:
            if (fieldDef.type === 'nominal' && !('sort' in fieldDef)) {
                return {
                    compatible: false,
                    warning: `Channel order is inappropriate for nominal field, which has no inherent order.`
                };
            }
            return standalone_COMPATIBLE;
    }
}
/**
 * Check if the field def uses a time format or does not use any format but is temporal
 * (this does not cover field defs that are temporal but use a number format).
 */
function standalone_isFieldOrDatumDefForTimeFormat(fieldOrDatumDef) {
    const { formatType } = standalone_getFormatMixins(fieldOrDatumDef);
    return formatType === 'time' || (!formatType && standalone_isTemporalFieldDef(fieldOrDatumDef));
}
/**
 * Check if field def has type `temporal`. If you want to also cover field defs that use a time format, use `isFieldOrDatumDefForTimeFormat`.
 */
function standalone_isTemporalFieldDef(def) {
    return def && (def['type'] === 'temporal' || (standalone_isFieldDef(def) && !!def.timeUnit));
}
/**
 * Getting a value associated with a fielddef.
 * Convert the value to Vega expression if applicable (for datetime object, or string if the field def is temporal or has timeUnit)
 */
function standalone_valueExpr(v, { timeUnit, type, wrapTime, undefinedIfExprNotRequired }) {
    const unit = timeUnit && standalone_normalizeTimeUnit(timeUnit)?.unit;
    let isTime = unit || type === 'temporal';
    let expr;
    if (standalone_isExprRef(v)) {
        expr = v.expr;
    }
    else if (standalone_isSignalRef(v)) {
        expr = v.signal;
    }
    else if (standalone_isDateTime(v)) {
        isTime = true;
        expr = standalone_dateTimeToExpr(v);
    }
    else if (standalone_vega_util_module_isString(v) || standalone_isNumber(v)) {
        if (isTime) {
            expr = `datetime(${standalone_util_stringify(v)})`;
            if (standalone_isLocalSingleTimeUnit(unit)) {
                // for single timeUnit, we will use dateTimeToExpr to convert number/string to match the timeUnit
                if ((standalone_isNumber(v) && v < 10000) || (standalone_vega_util_module_isString(v) && isNaN(Date.parse(v)))) {
                    expr = standalone_dateTimeToExpr({ [unit]: v });
                }
            }
        }
    }
    if (expr) {
        return wrapTime && isTime ? `time(${expr})` : expr;
    }
    // number or boolean or normal string
    return undefinedIfExprNotRequired ? undefined : standalone_util_stringify(v);
}
/**
 * Standardize value array -- convert each value to Vega expression if applicable
 */
function standalone_valueArray(fieldOrDatumDef, values) {
    const { type } = fieldOrDatumDef;
    return values.map(v => {
        const timeUnit = standalone_isFieldDef(fieldOrDatumDef) && !standalone_isBinnedTimeUnit(fieldOrDatumDef.timeUnit) ? fieldOrDatumDef.timeUnit : undefined;
        const expr = standalone_valueExpr(v, {
            timeUnit,
            type,
            undefinedIfExprNotRequired: true
        });
        // return signal for the expression if we need an expression
        if (expr !== undefined) {
            return { signal: expr };
        }
        // otherwise just return the original value
        return v;
    });
}
/**
 * Checks whether a fieldDef for a particular channel requires a computed bin range.
 */
function standalone_binRequiresRange(fieldDef, channel) {
    if (!standalone_isBinning(fieldDef.bin)) {
        console.warn('Only call this method for binned field defs.');
        return false;
    }
    // We need the range only when the user explicitly forces a binned field to be use discrete scale. In this case, bin range is used in axis and legend labels.
    // We could check whether the axis or legend exists (not disabled) but that seems overkill.
    return standalone_isScaleChannel(channel) && ['ordinal', 'nominal'].includes(fieldDef.type);
}
//# sourceMappingURL=channeldef.js.map
;// ../../node_modules/vega-lite/build/src/axis.js


const standalone_CONDITIONAL_AXIS_PROP_INDEX = {
    labelAlign: {
        part: 'labels',
        vgProp: 'align'
    },
    labelBaseline: {
        part: 'labels',
        vgProp: 'baseline'
    },
    labelColor: {
        part: 'labels',
        vgProp: 'fill'
    },
    labelFont: {
        part: 'labels',
        vgProp: 'font'
    },
    labelFontSize: {
        part: 'labels',
        vgProp: 'fontSize'
    },
    labelFontStyle: {
        part: 'labels',
        vgProp: 'fontStyle'
    },
    labelFontWeight: {
        part: 'labels',
        vgProp: 'fontWeight'
    },
    labelOpacity: {
        part: 'labels',
        vgProp: 'opacity'
    },
    labelOffset: null,
    labelPadding: null, // There is no fixed vgProp for tickSize, need to use signal.
    gridColor: {
        part: 'grid',
        vgProp: 'stroke'
    },
    gridDash: {
        part: 'grid',
        vgProp: 'strokeDash'
    },
    gridDashOffset: {
        part: 'grid',
        vgProp: 'strokeDashOffset'
    },
    gridOpacity: {
        part: 'grid',
        vgProp: 'opacity'
    },
    gridWidth: {
        part: 'grid',
        vgProp: 'strokeWidth'
    },
    tickColor: {
        part: 'ticks',
        vgProp: 'stroke'
    },
    tickDash: {
        part: 'ticks',
        vgProp: 'strokeDash'
    },
    tickDashOffset: {
        part: 'ticks',
        vgProp: 'strokeDashOffset'
    },
    tickOpacity: {
        part: 'ticks',
        vgProp: 'opacity'
    },
    tickSize: null, // There is no fixed vgProp for tickSize, need to use signal.
    tickWidth: {
        part: 'ticks',
        vgProp: 'strokeWidth'
    }
};
function standalone_isConditionalAxisValue(v) {
    return v?.condition;
}
const standalone_AXIS_PARTS = ['domain', 'grid', 'labels', 'ticks', 'title'];
/**
 * A dictionary listing whether a certain axis property is applicable for only main axes or only grid axes.
 */
const standalone_AXIS_PROPERTY_TYPE = {
    grid: 'grid',
    gridCap: 'grid',
    gridColor: 'grid',
    gridDash: 'grid',
    gridDashOffset: 'grid',
    gridOpacity: 'grid',
    gridScale: 'grid',
    gridWidth: 'grid',
    orient: 'main',
    bandPosition: 'both', // Need to be applied to grid axis too, so the grid will align with ticks.
    aria: 'main',
    description: 'main',
    domain: 'main',
    domainCap: 'main',
    domainColor: 'main',
    domainDash: 'main',
    domainDashOffset: 'main',
    domainOpacity: 'main',
    domainWidth: 'main',
    format: 'main',
    formatType: 'main',
    labelAlign: 'main',
    labelAngle: 'main',
    labelBaseline: 'main',
    labelBound: 'main',
    labelColor: 'main',
    labelFlush: 'main',
    labelFlushOffset: 'main',
    labelFont: 'main',
    labelFontSize: 'main',
    labelFontStyle: 'main',
    labelFontWeight: 'main',
    labelLimit: 'main',
    labelLineHeight: 'main',
    labelOffset: 'main',
    labelOpacity: 'main',
    labelOverlap: 'main',
    labelPadding: 'main',
    labels: 'main',
    labelSeparation: 'main',
    maxExtent: 'main',
    minExtent: 'main',
    offset: 'both',
    position: 'main',
    tickCap: 'main',
    tickColor: 'main',
    tickDash: 'main',
    tickDashOffset: 'main',
    tickMinStep: 'both',
    tickOffset: 'both', // Need to be applied to grid axis too, so the grid will align with ticks.
    tickOpacity: 'main',
    tickRound: 'both', // Apply rounding to grid and ticks so they are aligned.
    ticks: 'main',
    tickSize: 'main',
    tickWidth: 'both',
    title: 'main',
    titleAlign: 'main',
    titleAnchor: 'main',
    titleAngle: 'main',
    titleBaseline: 'main',
    titleColor: 'main',
    titleFont: 'main',
    titleFontSize: 'main',
    titleFontStyle: 'main',
    titleFontWeight: 'main',
    titleLimit: 'main',
    titleLineHeight: 'main',
    titleOpacity: 'main',
    titlePadding: 'main',
    titleX: 'main',
    titleY: 'main',
    encode: 'both', // we hide this in Vega-Lite
    scale: 'both',
    tickBand: 'both',
    tickCount: 'both',
    tickExtra: 'both',
    translate: 'both',
    values: 'both',
    zindex: 'both' // this is actually set afterward, so it doesn't matter
};
const standalone_COMMON_AXIS_PROPERTIES_INDEX = {
    orient: 1, // other things can depend on orient
    aria: 1,
    bandPosition: 1,
    description: 1,
    domain: 1,
    domainCap: 1,
    domainColor: 1,
    domainDash: 1,
    domainDashOffset: 1,
    domainOpacity: 1,
    domainWidth: 1,
    format: 1,
    formatType: 1,
    grid: 1,
    gridCap: 1,
    gridColor: 1,
    gridDash: 1,
    gridDashOffset: 1,
    gridOpacity: 1,
    gridWidth: 1,
    labelAlign: 1,
    labelAngle: 1,
    labelBaseline: 1,
    labelBound: 1,
    labelColor: 1,
    labelFlush: 1,
    labelFlushOffset: 1,
    labelFont: 1,
    labelFontSize: 1,
    labelFontStyle: 1,
    labelFontWeight: 1,
    labelLimit: 1,
    labelLineHeight: 1,
    labelOffset: 1,
    labelOpacity: 1,
    labelOverlap: 1,
    labelPadding: 1,
    labels: 1,
    labelSeparation: 1,
    maxExtent: 1,
    minExtent: 1,
    offset: 1,
    position: 1,
    tickBand: 1,
    tickCap: 1,
    tickColor: 1,
    tickCount: 1,
    tickDash: 1,
    tickDashOffset: 1,
    tickExtra: 1,
    tickMinStep: 1,
    tickOffset: 1,
    tickOpacity: 1,
    tickRound: 1,
    ticks: 1,
    tickSize: 1,
    tickWidth: 1,
    title: 1,
    titleAlign: 1,
    titleAnchor: 1,
    titleAngle: 1,
    titleBaseline: 1,
    titleColor: 1,
    titleFont: 1,
    titleFontSize: 1,
    titleFontStyle: 1,
    titleFontWeight: 1,
    titleLimit: 1,
    titleLineHeight: 1,
    titleOpacity: 1,
    titlePadding: 1,
    titleX: 1,
    titleY: 1,
    translate: 1,
    values: 1,
    zindex: 1
};
const standalone_AXIS_PROPERTIES_INDEX = {
    ...standalone_COMMON_AXIS_PROPERTIES_INDEX,
    style: 1,
    labelExpr: 1,
    encoding: 1
};
function standalone_isAxisProperty(prop) {
    return standalone_vega_util_module_has(standalone_AXIS_PROPERTIES_INDEX, prop);
}
// Export for dependent projects
const standalone_AXIS_PROPERTIES = standalone_util_keys(standalone_AXIS_PROPERTIES_INDEX);
const standalone_AXIS_CONFIGS_INDEX = {
    axis: 1,
    axisBand: 1,
    axisBottom: 1,
    axisDiscrete: 1,
    axisLeft: 1,
    axisPoint: 1,
    axisQuantitative: 1,
    axisRight: 1,
    axisTemporal: 1,
    axisTop: 1,
    axisX: 1,
    axisXBand: 1,
    axisXDiscrete: 1,
    axisXPoint: 1,
    axisXQuantitative: 1,
    axisXTemporal: 1,
    axisY: 1,
    axisYBand: 1,
    axisYDiscrete: 1,
    axisYPoint: 1,
    axisYQuantitative: 1,
    axisYTemporal: 1
};
const standalone_AXIS_CONFIGS = standalone_util_keys(standalone_AXIS_CONFIGS_INDEX);
//# sourceMappingURL=axis.js.map
;// ../../node_modules/vega-lite/build/src/spec/unit.js

function standalone_isUnitSpec(spec) {
    return standalone_util_hasProperty(spec, 'mark');
}
//# sourceMappingURL=unit.js.map
;// ../../node_modules/vega-lite/build/src/compositemark/base.js


class standalone_CompositeMarkNormalizer {
    constructor(name, run) {
        this.name = name;
        this.run = run;
    }
    hasMatchingType(spec) {
        if (standalone_isUnitSpec(spec)) {
            return standalone_getMarkType(spec.mark) === this.name;
        }
        return false;
    }
}
//# sourceMappingURL=base.js.map
;// ../../node_modules/vega-lite/build/src/encoding.js










function standalone_channelHasField(encoding, channel) {
    const channelDef = encoding && encoding[channel];
    if (channelDef) {
        if (standalone_vega_util_module_isArray(channelDef)) {
            return standalone_some(channelDef, fieldDef => !!fieldDef.field);
        }
        else {
            return standalone_isFieldDef(channelDef) || standalone_hasConditionalFieldDef(channelDef);
        }
    }
    return false;
}
function standalone_channelHasFieldOrDatum(encoding, channel) {
    const channelDef = encoding && encoding[channel];
    if (channelDef) {
        if (standalone_vega_util_module_isArray(channelDef)) {
            return standalone_some(channelDef, fieldDef => !!fieldDef.field);
        }
        else {
            return standalone_isFieldDef(channelDef) || standalone_isDatumDef(channelDef) || standalone_hasConditionalFieldOrDatumDef(channelDef);
        }
    }
    return false;
}
function standalone_channelHasNestedOffsetScale(encoding, channel) {
    if (standalone_isXorY(channel)) {
        const fieldDef = encoding[channel];
        if ((standalone_isFieldDef(fieldDef) || standalone_isDatumDef(fieldDef)) &&
            (standalone_type_isDiscrete(fieldDef.type) || (standalone_isFieldDef(fieldDef) && fieldDef.timeUnit))) {
            const offsetChannel = standalone_getOffsetScaleChannel(channel);
            return standalone_channelHasFieldOrDatum(encoding, offsetChannel);
        }
    }
    return false;
}
function standalone_isAggregate(encoding) {
    return standalone_some(standalone_CHANNELS, channel => {
        if (standalone_channelHasField(encoding, channel)) {
            const channelDef = encoding[channel];
            if (standalone_vega_util_module_isArray(channelDef)) {
                return standalone_some(channelDef, fieldDef => !!fieldDef.aggregate);
            }
            else {
                const fieldDef = standalone_getFieldDef(channelDef);
                return fieldDef && !!fieldDef.aggregate;
            }
        }
        return false;
    });
}
function standalone_extractTransformsFromEncoding(oldEncoding, config) {
    const groupby = [];
    const bins = [];
    const timeUnits = [];
    const aggregate = [];
    const encoding = {};
    standalone_forEach(oldEncoding, (channelDef, channel) => {
        // Extract potential embedded transformations along with remaining properties
        if (standalone_isFieldDef(channelDef)) {
            const { field, aggregate: aggOp, bin, timeUnit, ...remaining } = channelDef;
            if (aggOp || timeUnit || bin) {
                const guide = standalone_getGuide(channelDef);
                const isTitleDefined = guide?.title;
                let newField = standalone_vgField(channelDef, { forAs: true });
                const newFieldDef = {
                    // Only add title if it doesn't exist
                    ...(isTitleDefined ? [] : { title: standalone_channeldef_title(channelDef, config, { allowDisabling: true }) }),
                    ...remaining,
                    // Always overwrite field
                    field: newField
                };
                if (aggOp) {
                    let op;
                    if (standalone_isArgmaxDef(aggOp)) {
                        op = 'argmax';
                        newField = standalone_vgField({ op: 'argmax', field: aggOp.argmax }, { forAs: true });
                        newFieldDef.field = `${newField}.${field}`;
                    }
                    else if (standalone_isArgminDef(aggOp)) {
                        op = 'argmin';
                        newField = standalone_vgField({ op: 'argmin', field: aggOp.argmin }, { forAs: true });
                        newFieldDef.field = `${newField}.${field}`;
                    }
                    else if (aggOp !== 'boxplot' && aggOp !== 'errorbar' && aggOp !== 'errorband') {
                        op = aggOp;
                    }
                    if (op) {
                        const aggregateEntry = {
                            op,
                            as: newField
                        };
                        if (field) {
                            aggregateEntry.field = field;
                        }
                        aggregate.push(aggregateEntry);
                    }
                }
                else {
                    groupby.push(newField);
                    if (standalone_isTypedFieldDef(channelDef) && standalone_isBinning(bin)) {
                        bins.push({ bin, field, as: newField });
                        // Add additional groupbys for range and end of bins
                        groupby.push(standalone_vgField(channelDef, { binSuffix: 'end' }));
                        if (standalone_binRequiresRange(channelDef, channel)) {
                            groupby.push(standalone_vgField(channelDef, { binSuffix: 'range' }));
                        }
                        // Create accompanying 'x2' or 'y2' field if channel is 'x' or 'y' respectively
                        if (standalone_isXorY(channel)) {
                            const secondaryChannel = {
                                field: `${newField}_end`
                            };
                            encoding[`${channel}2`] = secondaryChannel;
                        }
                        newFieldDef.bin = 'binned';
                        if (!standalone_isSecondaryRangeChannel(channel)) {
                            newFieldDef['type'] = standalone_QUANTITATIVE;
                        }
                    }
                    else if (timeUnit && !standalone_isBinnedTimeUnit(timeUnit)) {
                        timeUnits.push({
                            timeUnit,
                            field,
                            as: newField
                        });
                        // define the format type for later compilation
                        const formatType = standalone_isTypedFieldDef(channelDef) && channelDef.type !== standalone_TEMPORAL && 'time';
                        if (formatType) {
                            if (channel === standalone_TEXT || channel === standalone_TOOLTIP) {
                                newFieldDef['formatType'] = formatType;
                            }
                            else if (standalone_isNonPositionScaleChannel(channel)) {
                                newFieldDef['legend'] = {
                                    formatType,
                                    ...newFieldDef['legend']
                                };
                            }
                            else if (standalone_isXorY(channel)) {
                                newFieldDef['axis'] = {
                                    formatType,
                                    ...newFieldDef['axis']
                                };
                            }
                        }
                    }
                }
                // now the field should refer to post-transformed field instead
                encoding[channel] = newFieldDef;
            }
            else {
                groupby.push(field);
                encoding[channel] = oldEncoding[channel];
            }
        }
        else {
            // For value def / signal ref / datum def, just copy
            encoding[channel] = oldEncoding[channel];
        }
    });
    return {
        bins,
        timeUnits,
        aggregate,
        groupby,
        encoding
    };
}
function standalone_markChannelCompatible(encoding, channel, mark) {
    const markSupported = standalone_supportMark(channel, mark);
    if (!markSupported) {
        return false;
    }
    else if (markSupported === 'binned') {
        const primaryFieldDef = encoding[channel === standalone_channel_X2 ? standalone_channel_X : standalone_channel_Y];
        // circle, point, square and tick only support x2/y2 when their corresponding x/y fieldDef
        // has "binned" data and thus need x2/y2 to specify the bin-end field.
        if (standalone_isFieldDef(primaryFieldDef) && standalone_isFieldDef(encoding[channel]) && standalone_isBinned(primaryFieldDef.bin)) {
            return true;
        }
        else {
            return false;
        }
    }
    return true;
}
function standalone_initEncoding(encoding, mark, filled, config) {
    const normalizedEncoding = {};
    for (const key of standalone_util_keys(encoding)) {
        if (!standalone_isChannel(key)) {
            // Drop invalid channel
            standalone_log_warn(standalone_invalidEncodingChannel(key));
        }
    }
    for (let channel of standalone_UNIT_CHANNELS) {
        if (!encoding[channel]) {
            continue;
        }
        const channelDef = encoding[channel];
        if (standalone_isXorYOffset(channel)) {
            const mainChannel = standalone_getMainChannelFromOffsetChannel(channel);
            const positionDef = normalizedEncoding[mainChannel];
            if (standalone_isFieldDef(positionDef)) {
                if (standalone_type_isContinuous(positionDef.type)) {
                    if (standalone_isFieldDef(channelDef) && !positionDef.timeUnit) {
                        // TODO: nesting continuous field instead continuous field should
                        // behave like offsetting the data in data domain
                        standalone_log_warn(standalone_offsetNestedInsideContinuousPositionScaleDropped(mainChannel));
                        continue;
                    }
                }
            }
        }
        if (channel === 'angle' && mark === 'arc' && !encoding.theta) {
            standalone_log_warn(standalone_REPLACE_ANGLE_WITH_THETA);
            channel = standalone_THETA;
        }
        if (!standalone_markChannelCompatible(encoding, channel, mark)) {
            // Drop unsupported channel
            standalone_log_warn(standalone_incompatibleChannel(channel, mark));
            continue;
        }
        // Drop line's size if the field is aggregated.
        if (channel === standalone_channel_SIZE && mark === 'line') {
            const fieldDef = standalone_getFieldDef(encoding[channel]);
            if (fieldDef?.aggregate) {
                standalone_log_warn(standalone_LINE_WITH_VARYING_SIZE);
                continue;
            }
        }
        // Drop color if either fill or stroke is specified
        if (channel === standalone_COLOR && (filled ? 'fill' in encoding : 'stroke' in encoding)) {
            standalone_log_warn(standalone_droppingColor('encoding', { fill: 'fill' in encoding, stroke: 'stroke' in encoding }));
            continue;
        }
        if (channel === standalone_DETAIL ||
            (channel === standalone_ORDER && !standalone_vega_util_module_isArray(channelDef) && !standalone_isValueDef(channelDef)) ||
            (channel === standalone_TOOLTIP && standalone_vega_util_module_isArray(channelDef))) {
            if (channelDef) {
                if (channel === standalone_ORDER) {
                    const def = encoding[channel];
                    if (standalone_isOrderOnlyDef(def)) {
                        normalizedEncoding[channel] = def;
                        continue;
                    }
                }
                // Array of fieldDefs for detail channel (or production rule)
                normalizedEncoding[channel] = standalone_array(channelDef).reduce((defs, fieldDef) => {
                    if (!standalone_isFieldDef(fieldDef)) {
                        standalone_log_warn(standalone_emptyFieldDef(fieldDef, channel));
                    }
                    else {
                        defs.push(standalone_initFieldDef(fieldDef, channel));
                    }
                    return defs;
                }, []);
            }
        }
        else {
            if (channel === standalone_TOOLTIP && channelDef === null) {
                // Preserve null so we can use it to disable tooltip
                normalizedEncoding[channel] = null;
            }
            else if (!standalone_isFieldDef(channelDef) &&
                !standalone_isDatumDef(channelDef) &&
                !standalone_isValueDef(channelDef) &&
                !standalone_isConditionalDef(channelDef) &&
                !standalone_isSignalRef(channelDef)) {
                standalone_log_warn(standalone_emptyFieldDef(channelDef, channel));
                continue;
            }
            normalizedEncoding[channel] = standalone_initChannelDef(channelDef, channel, config);
        }
    }
    return normalizedEncoding;
}
/**
 * For composite marks, we have to call initChannelDef during init so we can infer types earlier.
 */
function standalone_normalizeEncoding(encoding, config) {
    const normalizedEncoding = {};
    for (const channel of standalone_util_keys(encoding)) {
        const newChannelDef = standalone_initChannelDef(encoding[channel], channel, config, { compositeMark: true });
        normalizedEncoding[channel] = newChannelDef;
    }
    return normalizedEncoding;
}
function standalone_fieldDefs(encoding) {
    const arr = [];
    for (const channel of standalone_util_keys(encoding)) {
        if (standalone_channelHasField(encoding, channel)) {
            const channelDef = encoding[channel];
            const channelDefArray = standalone_array(channelDef);
            for (const def of channelDefArray) {
                if (standalone_isFieldDef(def)) {
                    arr.push(def);
                }
                else if (standalone_hasConditionalFieldDef(def)) {
                    arr.push(def.condition);
                }
            }
        }
    }
    return arr;
}
function standalone_forEach(mapping, f, thisArg) {
    if (!mapping) {
        return;
    }
    for (const channel of standalone_util_keys(mapping)) {
        const el = mapping[channel];
        if (standalone_vega_util_module_isArray(el)) {
            for (const channelDef of el) {
                f.call(thisArg, channelDef, channel);
            }
        }
        else {
            f.call(thisArg, el, channel);
        }
    }
}
function standalone_reduce(mapping, f, init, thisArg) {
    if (!mapping) {
        return init;
    }
    return standalone_util_keys(mapping).reduce((r, channel) => {
        const map = mapping[channel];
        if (standalone_vega_util_module_isArray(map)) {
            return map.reduce((r1, channelDef) => {
                return f.call(thisArg, r1, channelDef, channel);
            }, r);
        }
        else {
            return f.call(thisArg, r, map, channel);
        }
    }, init);
}
/**
 * Returns list of path grouping fields for the given encoding
 */
function standalone_pathGroupingFields(mark, encoding) {
    return standalone_util_keys(encoding).reduce((details, channel) => {
        switch (channel) {
            // x, y, x2, y2, lat, long, lat1, long2, order, tooltip, href, aria label, cursor should not cause lines to group
            case standalone_channel_X:
            case standalone_channel_Y:
            case standalone_HREF:
            case standalone_DESCRIPTION:
            case standalone_channel_URL:
            case standalone_channel_X2:
            case standalone_channel_Y2:
            case standalone_XOFFSET:
            case standalone_YOFFSET:
            case standalone_THETA:
            case standalone_THETA2:
            case standalone_RADIUS:
            case standalone_RADIUS2:
            case standalone_TIME:
            // falls through
            case standalone_LATITUDE:
            case standalone_LONGITUDE:
            case standalone_LATITUDE2:
            case standalone_LONGITUDE2:
            // TODO: case 'cursor':
            // text, shape, shouldn't be a part of line/trail/area [falls through]
            case standalone_TEXT:
            case standalone_SHAPE:
            case standalone_ANGLE:
            // falls through
            // tooltip fields should not be added to group by [falls through]
            case standalone_TOOLTIP:
                return details;
            case standalone_ORDER:
                // order should not group line / trail
                if (mark === 'line' || mark === 'trail') {
                    return details;
                }
            // but order should group area for stacking (falls through)
            case standalone_DETAIL:
            case standalone_KEY: {
                const channelDef = encoding[channel];
                if (standalone_vega_util_module_isArray(channelDef) || standalone_isFieldDef(channelDef)) {
                    for (const fieldDef of standalone_array(channelDef)) {
                        if (!fieldDef.aggregate) {
                            details.push(standalone_vgField(fieldDef, {}));
                        }
                    }
                }
                return details;
            }
            case standalone_channel_SIZE:
                if (mark === 'trail') {
                    // For trail, size should not group trail lines.
                    return details;
                }
            // For line, size should group lines.
            // falls through
            case standalone_COLOR:
            case standalone_FILL:
            case standalone_STROKE:
            case standalone_OPACITY:
            case standalone_FILLOPACITY:
            case standalone_STROKEOPACITY:
            case standalone_STROKEDASH:
            case standalone_STROKEWIDTH: {
                // TODO strokeDashOffset:
                // falls through
                const fieldDef = standalone_getFieldDef(encoding[channel]);
                if (fieldDef && !fieldDef.aggregate) {
                    details.push(standalone_vgField(fieldDef, {}));
                }
                return details;
            }
        }
    }, []);
}
//# sourceMappingURL=encoding.js.map
;// ../../node_modules/vega-lite/build/src/compositemark/common.js








function standalone_filterTooltipWithAggregatedField(oldEncoding) {
    const { tooltip, ...filteredEncoding } = oldEncoding;
    if (!tooltip) {
        return { filteredEncoding };
    }
    let customTooltipWithAggregatedField;
    let customTooltipWithoutAggregatedField;
    if (standalone_vega_util_module_isArray(tooltip)) {
        for (const t of tooltip) {
            if (t.aggregate) {
                if (!customTooltipWithAggregatedField) {
                    customTooltipWithAggregatedField = [];
                }
                customTooltipWithAggregatedField.push(t);
            }
            else {
                if (!customTooltipWithoutAggregatedField) {
                    customTooltipWithoutAggregatedField = [];
                }
                customTooltipWithoutAggregatedField.push(t);
            }
        }
        if (customTooltipWithAggregatedField) {
            filteredEncoding.tooltip = customTooltipWithAggregatedField;
        }
    }
    else {
        if (tooltip.aggregate) {
            filteredEncoding.tooltip = tooltip;
        }
        else {
            customTooltipWithoutAggregatedField = tooltip;
        }
    }
    if (standalone_vega_util_module_isArray(customTooltipWithoutAggregatedField) && customTooltipWithoutAggregatedField.length === 1) {
        customTooltipWithoutAggregatedField = customTooltipWithoutAggregatedField[0];
    }
    return { customTooltipWithoutAggregatedField, filteredEncoding };
}
function standalone_getCompositeMarkTooltip(tooltipSummary, continuousAxisChannelDef, encodingWithoutContinuousAxis, withFieldName = true) {
    if ('tooltip' in encodingWithoutContinuousAxis) {
        return { tooltip: encodingWithoutContinuousAxis.tooltip };
    }
    const fiveSummaryTooltip = tooltipSummary.map(({ fieldPrefix, titlePrefix }) => {
        const mainTitle = withFieldName ? ` of ${standalone_getTitle(continuousAxisChannelDef)}` : '';
        return {
            field: fieldPrefix + continuousAxisChannelDef.field,
            type: continuousAxisChannelDef.type,
            title: standalone_isSignalRef(titlePrefix) ? { signal: `${titlePrefix}"${escape(mainTitle)}"` } : titlePrefix + mainTitle
        };
    });
    const tooltipFieldDefs = standalone_fieldDefs(encodingWithoutContinuousAxis).map(standalone_toStringFieldDef);
    return {
        tooltip: [
            ...fiveSummaryTooltip,
            // need to cast because TextFieldDef supports fewer types of bin
            ...standalone_unique(tooltipFieldDefs, standalone_util_hash)
        ]
    };
}
function standalone_getTitle(continuousAxisChannelDef) {
    const { title, field } = continuousAxisChannelDef;
    return standalone_getFirstDefined(title, field);
}
function standalone_makeCompositeAggregatePartFactory(compositeMarkDef, continuousAxis, continuousAxisChannelDef, sharedEncoding, compositeMarkConfig) {
    const { scale, axis } = continuousAxisChannelDef;
    return ({ partName, mark, positionPrefix, endPositionPrefix = undefined, extraEncoding = {} }) => {
        const title = standalone_getTitle(continuousAxisChannelDef);
        return standalone_partLayerMixins(compositeMarkDef, partName, compositeMarkConfig, {
            mark, // TODO better remove this method and just have mark as a parameter of the method
            encoding: {
                [continuousAxis]: {
                    field: `${positionPrefix}_${continuousAxisChannelDef.field}`,
                    type: continuousAxisChannelDef.type,
                    ...(title !== undefined ? { title } : {}),
                    ...(scale !== undefined ? { scale } : {}),
                    ...(axis !== undefined ? { axis } : {})
                },
                ...(standalone_vega_util_module_isString(endPositionPrefix)
                    ? {
                        [`${continuousAxis}2`]: {
                            field: `${endPositionPrefix}_${continuousAxisChannelDef.field}`
                        }
                    }
                    : {}),
                ...sharedEncoding,
                ...extraEncoding
            }
        });
    };
}
function standalone_partLayerMixins(markDef, part, compositeMarkConfig, partBaseSpec) {
    const { clip, color, opacity } = markDef;
    const mark = markDef.type;
    if (markDef[part] || (markDef[part] === undefined && compositeMarkConfig[part])) {
        return [
            {
                ...partBaseSpec,
                mark: {
                    ...compositeMarkConfig[part],
                    ...(clip ? { clip } : {}),
                    ...(color ? { color } : {}),
                    ...(opacity ? { opacity } : {}),
                    ...(standalone_isMarkDef(partBaseSpec.mark) ? partBaseSpec.mark : { type: partBaseSpec.mark }),
                    style: `${mark}-${String(part)}`,
                    ...(standalone_isBoolean(markDef[part]) ? {} : markDef[part])
                }
            }
        ];
    }
    return [];
}
function standalone_compositeMarkContinuousAxis(spec, orient, compositeMark) {
    const { encoding } = spec;
    const continuousAxis = orient === 'vertical' ? 'y' : 'x';
    const continuousAxisChannelDef = encoding[continuousAxis]; // Safe to cast because if x is not continuous fielddef, the orient would not be horizontal.
    const continuousAxisChannelDef2 = encoding[`${continuousAxis}2`];
    const continuousAxisChannelDefError = encoding[`${continuousAxis}Error`];
    const continuousAxisChannelDefError2 = encoding[`${continuousAxis}Error2`];
    return {
        continuousAxisChannelDef: standalone_filterAggregateFromChannelDef(continuousAxisChannelDef, compositeMark),
        continuousAxisChannelDef2: standalone_filterAggregateFromChannelDef(continuousAxisChannelDef2, compositeMark),
        continuousAxisChannelDefError: standalone_filterAggregateFromChannelDef(continuousAxisChannelDefError, compositeMark),
        continuousAxisChannelDefError2: standalone_filterAggregateFromChannelDef(continuousAxisChannelDefError2, compositeMark),
        continuousAxis
    };
}
function standalone_filterAggregateFromChannelDef(continuousAxisChannelDef, compositeMark) {
    if (continuousAxisChannelDef?.aggregate) {
        const { aggregate, ...continuousAxisWithoutAggregate } = continuousAxisChannelDef;
        if (aggregate !== compositeMark) {
            standalone_log_warn(standalone_errorBarContinuousAxisHasCustomizedAggregate(aggregate, compositeMark));
        }
        return continuousAxisWithoutAggregate;
    }
    else {
        return continuousAxisChannelDef;
    }
}
function standalone_compositeMarkOrient(spec, compositeMark) {
    const { mark, encoding } = spec;
    const { x, y } = encoding;
    if (standalone_isMarkDef(mark) && mark.orient) {
        return mark.orient;
    }
    if (standalone_isContinuousFieldOrDatumDef(x)) {
        // x is continuous
        if (standalone_isContinuousFieldOrDatumDef(y)) {
            // both x and y are continuous
            const xAggregate = standalone_isFieldDef(x) && x.aggregate;
            const yAggregate = standalone_isFieldDef(y) && y.aggregate;
            if (!xAggregate && yAggregate === compositeMark) {
                return 'vertical';
            }
            else if (!yAggregate && xAggregate === compositeMark) {
                return 'horizontal';
            }
            else if (xAggregate === compositeMark && yAggregate === compositeMark) {
                throw new Error('Both x and y cannot have aggregate');
            }
            else {
                if (standalone_isFieldOrDatumDefForTimeFormat(y) && !standalone_isFieldOrDatumDefForTimeFormat(x)) {
                    // y is temporal but x is not
                    return 'horizontal';
                }
                // default orientation for two continuous
                return 'vertical';
            }
        }
        return 'horizontal';
    }
    else if (standalone_isContinuousFieldOrDatumDef(y)) {
        // y is continuous but x is not
        return 'vertical';
    }
    else {
        // Neither x nor y is continuous.
        throw new Error(`Need a valid continuous axis for ${compositeMark}s`);
    }
}
//# sourceMappingURL=common.js.map
;// ../../node_modules/vega-lite/build/src/compositemark/boxplot.js








const standalone_BOXPLOT = 'boxplot';
const standalone_BOXPLOT_PARTS = ['box', 'median', 'outliers', 'rule', 'ticks'];
const standalone_boxPlotNormalizer = new standalone_CompositeMarkNormalizer(standalone_BOXPLOT, standalone_normalizeBoxPlot);
function standalone_getBoxPlotType(extent) {
    if (standalone_isNumber(extent)) {
        return 'tukey';
    }
    // Ham: If we ever want to, we could add another extent syntax `{kIQR: number}` for the original [Q1-k*IQR, Q3+k*IQR] whisker and call this boxPlotType = `kIQR`. However, I'm not exposing this for now.
    return extent;
}
function standalone_normalizeBoxPlot(spec, { config }) {
    // Need to initEncoding first so we can infer type
    spec = {
        ...spec,
        encoding: standalone_normalizeEncoding(spec.encoding, config)
    };
    const { mark, encoding: _encoding, params, projection: _p, ...outerSpec } = spec;
    const markDef = standalone_isMarkDef(mark) ? mark : { type: mark };
    // TODO(https://github.com/vega/vega-lite/issues/3702): add selection support
    if (params) {
        standalone_log_warn(standalone_selectionNotSupported('boxplot'));
    }
    const extent = markDef.extent ?? config.boxplot.extent;
    const sizeValue = standalone_getMarkPropOrConfig('size', markDef, // TODO: https://github.com/vega/vega-lite/issues/6245
    config);
    const invalid = markDef.invalid;
    const boxPlotType = standalone_getBoxPlotType(extent);
    const { bins, timeUnits, transform, continuousAxisChannelDef, continuousAxis, groupby, aggregate, encodingWithoutContinuousAxis, ticksOrient, boxOrient, customTooltipWithoutAggregatedField } = standalone_boxParams(spec, extent, config);
    const aliasedFieldName = standalone_removePathFromField(continuousAxisChannelDef.field);
    const { color, size, ...encodingWithoutSizeColorAndContinuousAxis } = encodingWithoutContinuousAxis;
    const makeBoxPlotPart = (sharedEncoding) => {
        return standalone_makeCompositeAggregatePartFactory(markDef, continuousAxis, continuousAxisChannelDef, sharedEncoding, config.boxplot);
    };
    const makeBoxPlotExtent = makeBoxPlotPart(encodingWithoutSizeColorAndContinuousAxis);
    const makeBoxPlotBox = makeBoxPlotPart(encodingWithoutContinuousAxis);
    const defaultBoxColor = (standalone_vega_util_module_isObject(config.boxplot.box) ? config.boxplot.box.color : config.mark.color) || '#4c78a8';
    const makeBoxPlotMidTick = makeBoxPlotPart({
        ...encodingWithoutSizeColorAndContinuousAxis,
        ...(size ? { size } : {}),
        color: {
            condition: {
                test: `${standalone_accessWithDatumToUnescapedPath(`lower_box_${continuousAxisChannelDef.field}`)} >= ${standalone_accessWithDatumToUnescapedPath(`upper_box_${continuousAxisChannelDef.field}`)}`,
                ...(color || { value: defaultBoxColor })
            }
        }
    });
    const fiveSummaryTooltipEncoding = standalone_getCompositeMarkTooltip([
        { fieldPrefix: boxPlotType === 'min-max' ? 'upper_whisker_' : 'max_', titlePrefix: 'Max' },
        { fieldPrefix: 'upper_box_', titlePrefix: 'Q3' },
        { fieldPrefix: 'mid_box_', titlePrefix: 'Median' },
        { fieldPrefix: 'lower_box_', titlePrefix: 'Q1' },
        { fieldPrefix: boxPlotType === 'min-max' ? 'lower_whisker_' : 'min_', titlePrefix: 'Min' }
    ], continuousAxisChannelDef, encodingWithoutContinuousAxis);
    // ## Whisker Layers
    const endTick = { type: 'tick', color: 'black', opacity: 1, orient: ticksOrient, invalid, aria: false };
    const whiskerTooltipEncoding = boxPlotType === 'min-max'
        ? fiveSummaryTooltipEncoding // for min-max, show five-summary tooltip for whisker
        : // for tukey / k-IQR, just show upper/lower-whisker
            standalone_getCompositeMarkTooltip([
                { fieldPrefix: 'upper_whisker_', titlePrefix: 'Upper Whisker' },
                { fieldPrefix: 'lower_whisker_', titlePrefix: 'Lower Whisker' }
            ], continuousAxisChannelDef, encodingWithoutContinuousAxis);
    const whiskerLayers = [
        ...makeBoxPlotExtent({
            partName: 'rule',
            mark: { type: 'rule', invalid, aria: false },
            positionPrefix: 'lower_whisker',
            endPositionPrefix: 'lower_box',
            extraEncoding: whiskerTooltipEncoding
        }),
        ...makeBoxPlotExtent({
            partName: 'rule',
            mark: { type: 'rule', invalid, aria: false },
            positionPrefix: 'upper_box',
            endPositionPrefix: 'upper_whisker',
            extraEncoding: whiskerTooltipEncoding
        }),
        ...makeBoxPlotExtent({
            partName: 'ticks',
            mark: endTick,
            positionPrefix: 'lower_whisker',
            extraEncoding: whiskerTooltipEncoding
        }),
        ...makeBoxPlotExtent({
            partName: 'ticks',
            mark: endTick,
            positionPrefix: 'upper_whisker',
            extraEncoding: whiskerTooltipEncoding
        })
    ];
    // ## Box Layers
    // TODO: support hiding certain mark parts
    const boxLayers = [
        ...(boxPlotType !== 'tukey' ? whiskerLayers : []),
        ...makeBoxPlotBox({
            partName: 'box',
            mark: {
                type: 'bar',
                ...(sizeValue ? { size: sizeValue } : {}),
                orient: boxOrient,
                invalid,
                ariaRoleDescription: 'box'
            },
            positionPrefix: 'lower_box',
            endPositionPrefix: 'upper_box',
            extraEncoding: fiveSummaryTooltipEncoding
        }),
        ...makeBoxPlotMidTick({
            partName: 'median',
            mark: {
                type: 'tick',
                invalid,
                ...(standalone_vega_util_module_isObject(config.boxplot.median) && config.boxplot.median.color ? { color: config.boxplot.median.color } : {}),
                ...(sizeValue ? { size: sizeValue } : {}),
                orient: ticksOrient,
                aria: false
            },
            positionPrefix: 'mid_box',
            extraEncoding: fiveSummaryTooltipEncoding
        })
    ];
    if (boxPlotType === 'min-max') {
        return {
            ...outerSpec,
            transform: (outerSpec.transform ?? []).concat(transform),
            layer: boxLayers
        };
    }
    // Tukey Box Plot
    const lowerBoxExpr = standalone_accessWithDatumToUnescapedPath(`lower_box_${continuousAxisChannelDef.field}`);
    const upperBoxExpr = standalone_accessWithDatumToUnescapedPath(`upper_box_${continuousAxisChannelDef.field}`);
    const iqrExpr = `(${upperBoxExpr} - ${lowerBoxExpr})`;
    const lowerWhiskerExpr = `${lowerBoxExpr} - ${extent} * ${iqrExpr}`;
    const upperWhiskerExpr = `${upperBoxExpr} + ${extent} * ${iqrExpr}`;
    const fieldExpr = standalone_accessWithDatumToUnescapedPath(continuousAxisChannelDef.field);
    const joinaggregateTransform = {
        joinaggregate: standalone_boxParamsQuartiles(continuousAxisChannelDef.field),
        groupby
    };
    const filteredWhiskerSpec = {
        transform: [
            {
                filter: `(${lowerWhiskerExpr} <= ${fieldExpr}) && (${fieldExpr} <= ${upperWhiskerExpr})`
            },
            {
                aggregate: [
                    {
                        op: 'min',
                        field: continuousAxisChannelDef.field,
                        as: `lower_whisker_${aliasedFieldName}`
                    },
                    {
                        op: 'max',
                        field: continuousAxisChannelDef.field,
                        as: `upper_whisker_${aliasedFieldName}`
                    },
                    // preserve lower_box / upper_box
                    {
                        op: 'min',
                        field: `lower_box_${continuousAxisChannelDef.field}`,
                        as: `lower_box_${aliasedFieldName}`
                    },
                    {
                        op: 'max',
                        field: `upper_box_${continuousAxisChannelDef.field}`,
                        as: `upper_box_${aliasedFieldName}`
                    },
                    ...aggregate
                ],
                groupby
            }
        ],
        layer: whiskerLayers
    };
    const { tooltip, ...encodingWithoutSizeColorContinuousAxisAndTooltip } = encodingWithoutSizeColorAndContinuousAxis;
    const { scale, axis } = continuousAxisChannelDef;
    const title = standalone_getTitle(continuousAxisChannelDef);
    const axisWithoutTitle = standalone_omit(axis, ['title']);
    const outlierLayersMixins = standalone_partLayerMixins(markDef, 'outliers', config.boxplot, {
        transform: [{ filter: `(${fieldExpr} < ${lowerWhiskerExpr}) || (${fieldExpr} > ${upperWhiskerExpr})` }],
        mark: 'point',
        encoding: {
            [continuousAxis]: {
                field: continuousAxisChannelDef.field,
                type: continuousAxisChannelDef.type,
                ...(title !== undefined ? { title } : {}),
                ...(scale !== undefined ? { scale } : {}),
                // add axis without title since we already added the title above
                ...(standalone_isEmpty(axisWithoutTitle) ? {} : { axis: axisWithoutTitle })
            },
            ...encodingWithoutSizeColorContinuousAxisAndTooltip,
            ...(color ? { color } : {}),
            ...(customTooltipWithoutAggregatedField ? { tooltip: customTooltipWithoutAggregatedField } : {})
        }
    })[0];
    let filteredLayersMixins;
    const filteredLayersMixinsTransforms = [...bins, ...timeUnits, joinaggregateTransform];
    if (outlierLayersMixins) {
        filteredLayersMixins = {
            transform: filteredLayersMixinsTransforms,
            layer: [outlierLayersMixins, filteredWhiskerSpec]
        };
    }
    else {
        filteredLayersMixins = filteredWhiskerSpec;
        filteredLayersMixins.transform.unshift(...filteredLayersMixinsTransforms);
    }
    return {
        ...outerSpec,
        layer: [
            filteredLayersMixins,
            {
                // boxplot
                transform,
                layer: boxLayers
            }
        ]
    };
}
function standalone_boxParamsQuartiles(continousAxisField) {
    const aliasedFieldName = standalone_removePathFromField(continousAxisField);
    return [
        {
            op: 'q1',
            field: continousAxisField,
            as: `lower_box_${aliasedFieldName}`
        },
        {
            op: 'q3',
            field: continousAxisField,
            as: `upper_box_${aliasedFieldName}`
        }
    ];
}
function standalone_boxParams(spec, extent, config) {
    const orient = standalone_compositeMarkOrient(spec, standalone_BOXPLOT);
    const { continuousAxisChannelDef, continuousAxis } = standalone_compositeMarkContinuousAxis(spec, orient, standalone_BOXPLOT);
    const continuousFieldName = continuousAxisChannelDef.field;
    const aliasedFieldName = standalone_removePathFromField(continuousFieldName);
    const boxPlotType = standalone_getBoxPlotType(extent);
    const boxplotSpecificAggregate = [
        ...standalone_boxParamsQuartiles(continuousFieldName),
        {
            op: 'median',
            field: continuousFieldName,
            as: `mid_box_${aliasedFieldName}`
        },
        {
            op: 'min',
            field: continuousFieldName,
            as: (boxPlotType === 'min-max' ? 'lower_whisker_' : 'min_') + aliasedFieldName
        },
        {
            op: 'max',
            field: continuousFieldName,
            as: (boxPlotType === 'min-max' ? 'upper_whisker_' : 'max_') + aliasedFieldName
        }
    ];
    const postAggregateCalculates = boxPlotType === 'min-max' || boxPlotType === 'tukey'
        ? []
        : [
            // This is for the  original k-IQR, which we do not expose
            {
                calculate: `${standalone_accessWithDatumToUnescapedPath(`upper_box_${aliasedFieldName}`)} - ${standalone_accessWithDatumToUnescapedPath(`lower_box_${aliasedFieldName}`)}`,
                as: `iqr_${aliasedFieldName}`
            },
            {
                calculate: `min(${standalone_accessWithDatumToUnescapedPath(`upper_box_${aliasedFieldName}`)} + ${standalone_accessWithDatumToUnescapedPath(`iqr_${aliasedFieldName}`)} * ${extent}, ${standalone_accessWithDatumToUnescapedPath(`max_${aliasedFieldName}`)})`,
                as: `upper_whisker_${aliasedFieldName}`
            },
            {
                calculate: `max(${standalone_accessWithDatumToUnescapedPath(`lower_box_${aliasedFieldName}`)} - ${standalone_accessWithDatumToUnescapedPath(`iqr_${aliasedFieldName}`)} * ${extent}, ${standalone_accessWithDatumToUnescapedPath(`min_${aliasedFieldName}`)})`,
                as: `lower_whisker_${aliasedFieldName}`
            }
        ];
    const { [continuousAxis]: oldContinuousAxisChannelDef, ...oldEncodingWithoutContinuousAxis } = spec.encoding;
    const { customTooltipWithoutAggregatedField, filteredEncoding } = standalone_filterTooltipWithAggregatedField(oldEncodingWithoutContinuousAxis);
    const { bins, timeUnits, aggregate, groupby, encoding: encodingWithoutContinuousAxis } = standalone_extractTransformsFromEncoding(filteredEncoding, config);
    const ticksOrient = orient === 'vertical' ? 'horizontal' : 'vertical';
    const boxOrient = orient;
    const transform = [
        ...bins,
        ...timeUnits,
        {
            aggregate: [...aggregate, ...boxplotSpecificAggregate],
            groupby
        },
        ...postAggregateCalculates
    ];
    return {
        bins,
        timeUnits,
        transform,
        groupby,
        aggregate,
        continuousAxisChannelDef,
        continuousAxis,
        encodingWithoutContinuousAxis,
        ticksOrient,
        boxOrient,
        customTooltipWithoutAggregatedField
    };
}
//# sourceMappingURL=boxplot.js.map
;// ../../node_modules/vega-lite/build/src/compositemark/errorbar.js







const standalone_ERRORBAR = 'errorbar';
const standalone_ERRORBAR_PARTS = ['ticks', 'rule'];
const standalone_errorBarNormalizer = new standalone_CompositeMarkNormalizer(standalone_ERRORBAR, standalone_normalizeErrorBar);
function standalone_normalizeErrorBar(spec, { config }) {
    // Need to initEncoding first so we can infer type
    spec = {
        ...spec,
        encoding: standalone_normalizeEncoding(spec.encoding, config)
    };
    const { transform, continuousAxisChannelDef, continuousAxis, encodingWithoutContinuousAxis, ticksOrient, markDef, outerSpec, tooltipEncoding } = standalone_errorBarParams(spec, standalone_ERRORBAR, config);
    delete encodingWithoutContinuousAxis.size;
    const makeErrorBarPart = standalone_makeCompositeAggregatePartFactory(markDef, continuousAxis, continuousAxisChannelDef, encodingWithoutContinuousAxis, config.errorbar);
    const thickness = markDef.thickness;
    const size = markDef.size;
    const tick = {
        type: 'tick',
        orient: ticksOrient,
        aria: false,
        ...(thickness !== undefined ? { thickness } : {}),
        ...(size !== undefined ? { size } : {})
    };
    const layer = [
        ...makeErrorBarPart({
            partName: 'ticks',
            mark: tick,
            positionPrefix: 'lower',
            extraEncoding: tooltipEncoding
        }),
        ...makeErrorBarPart({
            partName: 'ticks',
            mark: tick,
            positionPrefix: 'upper',
            extraEncoding: tooltipEncoding
        }),
        ...makeErrorBarPart({
            partName: 'rule',
            mark: {
                type: 'rule',
                ariaRoleDescription: 'errorbar',
                ...(thickness !== undefined ? { size: thickness } : {})
            },
            positionPrefix: 'lower',
            endPositionPrefix: 'upper',
            extraEncoding: tooltipEncoding
        })
    ];
    return {
        ...outerSpec,
        transform,
        ...(layer.length > 1 ? { layer } : { ...layer[0] })
    };
}
function standalone_errorBarOrientAndInputType(spec, compositeMark) {
    const { encoding } = spec;
    if (standalone_errorBarIsInputTypeRaw(encoding)) {
        return {
            orient: standalone_compositeMarkOrient(spec, compositeMark),
            inputType: 'raw'
        };
    }
    const isTypeAggregatedUpperLower = standalone_errorBarIsInputTypeAggregatedUpperLower(encoding);
    const isTypeAggregatedError = standalone_errorBarIsInputTypeAggregatedError(encoding);
    const x = encoding.x;
    const y = encoding.y;
    if (isTypeAggregatedUpperLower) {
        // type is aggregated-upper-lower
        if (isTypeAggregatedError) {
            throw new Error(`${compositeMark} cannot be both type aggregated-upper-lower and aggregated-error`);
        }
        const x2 = encoding.x2;
        const y2 = encoding.y2;
        if (standalone_isFieldOrDatumDef(x2) && standalone_isFieldOrDatumDef(y2)) {
            // having both x, x2 and y, y2
            throw new Error(`${compositeMark} cannot have both x2 and y2`);
        }
        else if (standalone_isFieldOrDatumDef(x2)) {
            if (standalone_isContinuousFieldOrDatumDef(x)) {
                // having x, x2 quantitative and field y, y2 are not specified
                return { orient: 'horizontal', inputType: 'aggregated-upper-lower' };
            }
            else {
                // having x, x2 that are not both quantitative
                throw new Error(`Both x and x2 have to be quantitative in ${compositeMark}`);
            }
        }
        else if (standalone_isFieldOrDatumDef(y2)) {
            // y2 is a FieldDef
            if (standalone_isContinuousFieldOrDatumDef(y)) {
                // having y, y2 quantitative and field x, x2 are not specified
                return { orient: 'vertical', inputType: 'aggregated-upper-lower' };
            }
            else {
                // having y, y2 that are not both quantitative
                throw new Error(`Both y and y2 have to be quantitative in ${compositeMark}`);
            }
        }
        throw new Error('No ranged axis');
    }
    else {
        // type is aggregated-error
        const xError = encoding.xError;
        const xError2 = encoding.xError2;
        const yError = encoding.yError;
        const yError2 = encoding.yError2;
        if (standalone_isFieldOrDatumDef(xError2) && !standalone_isFieldOrDatumDef(xError)) {
            // having xError2 without xError
            throw new Error(`${compositeMark} cannot have xError2 without xError`);
        }
        if (standalone_isFieldOrDatumDef(yError2) && !standalone_isFieldOrDatumDef(yError)) {
            // having yError2 without yError
            throw new Error(`${compositeMark} cannot have yError2 without yError`);
        }
        if (standalone_isFieldOrDatumDef(xError) && standalone_isFieldOrDatumDef(yError)) {
            // having both xError and yError
            throw new Error(`${compositeMark} cannot have both xError and yError with both are quantiative`);
        }
        else if (standalone_isFieldOrDatumDef(xError)) {
            if (standalone_isContinuousFieldOrDatumDef(x)) {
                // having x and xError that are all quantitative
                return { orient: 'horizontal', inputType: 'aggregated-error' };
            }
            else {
                // having x, xError, and xError2 that are not all quantitative
                throw new Error('All x, xError, and xError2 (if exist) have to be quantitative');
            }
        }
        else if (standalone_isFieldOrDatumDef(yError)) {
            if (standalone_isContinuousFieldOrDatumDef(y)) {
                // having y and yError that are all quantitative
                return { orient: 'vertical', inputType: 'aggregated-error' };
            }
            else {
                // having y, yError, and yError2 that are not all quantitative
                throw new Error('All y, yError, and yError2 (if exist) have to be quantitative');
            }
        }
        throw new Error('No ranged axis');
    }
}
function standalone_errorBarIsInputTypeRaw(encoding) {
    return ((standalone_isFieldOrDatumDef(encoding.x) || standalone_isFieldOrDatumDef(encoding.y)) &&
        !standalone_isFieldOrDatumDef(encoding.x2) &&
        !standalone_isFieldOrDatumDef(encoding.y2) &&
        !standalone_isFieldOrDatumDef(encoding.xError) &&
        !standalone_isFieldOrDatumDef(encoding.xError2) &&
        !standalone_isFieldOrDatumDef(encoding.yError) &&
        !standalone_isFieldOrDatumDef(encoding.yError2));
}
function standalone_errorBarIsInputTypeAggregatedUpperLower(encoding) {
    return standalone_isFieldOrDatumDef(encoding.x2) || standalone_isFieldOrDatumDef(encoding.y2);
}
function standalone_errorBarIsInputTypeAggregatedError(encoding) {
    return (standalone_isFieldOrDatumDef(encoding.xError) ||
        standalone_isFieldOrDatumDef(encoding.xError2) ||
        standalone_isFieldOrDatumDef(encoding.yError) ||
        standalone_isFieldOrDatumDef(encoding.yError2));
}
function standalone_errorBarParams(spec, compositeMark, config) {
    // TODO: use selection
    const { mark, encoding, params, projection: _p, ...outerSpec } = spec;
    const markDef = standalone_isMarkDef(mark) ? mark : { type: mark };
    // TODO(https://github.com/vega/vega-lite/issues/3702): add selection support
    if (params) {
        standalone_log_warn(standalone_selectionNotSupported(compositeMark));
    }
    const { orient, inputType } = standalone_errorBarOrientAndInputType(spec, compositeMark);
    const { continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, continuousAxis } = standalone_compositeMarkContinuousAxis(spec, orient, compositeMark);
    const { errorBarSpecificAggregate, postAggregateCalculates, tooltipSummary, tooltipTitleWithFieldName } = standalone_errorBarAggregationAndCalculation(markDef, continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, inputType, compositeMark, config);
    const { [continuousAxis]: oldContinuousAxisChannelDef, [continuousAxis === 'x' ? 'x2' : 'y2']: oldContinuousAxisChannelDef2, [continuousAxis === 'x' ? 'xError' : 'yError']: oldContinuousAxisChannelDefError, [continuousAxis === 'x' ? 'xError2' : 'yError2']: oldContinuousAxisChannelDefError2, ...oldEncodingWithoutContinuousAxis } = encoding;
    const { bins, timeUnits, aggregate: oldAggregate, groupby: oldGroupBy, encoding: encodingWithoutContinuousAxis } = standalone_extractTransformsFromEncoding(oldEncodingWithoutContinuousAxis, config);
    const aggregate = [...oldAggregate, ...errorBarSpecificAggregate];
    const groupby = inputType !== 'raw' ? [] : oldGroupBy;
    const tooltipEncoding = standalone_getCompositeMarkTooltip(tooltipSummary, continuousAxisChannelDef, encodingWithoutContinuousAxis, tooltipTitleWithFieldName);
    return {
        transform: [
            ...(outerSpec.transform ?? []),
            ...bins,
            ...timeUnits,
            ...(aggregate.length === 0 ? [] : [{ aggregate, groupby }]),
            ...postAggregateCalculates
        ],
        groupby,
        continuousAxisChannelDef,
        continuousAxis,
        encodingWithoutContinuousAxis,
        ticksOrient: orient === 'vertical' ? 'horizontal' : 'vertical',
        markDef,
        outerSpec,
        tooltipEncoding
    };
}
function standalone_errorBarAggregationAndCalculation(markDef, continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, inputType, compositeMark, config) {
    let errorBarSpecificAggregate = [];
    let postAggregateCalculates = [];
    const continuousFieldName = continuousAxisChannelDef.field;
    let tooltipSummary;
    let tooltipTitleWithFieldName = false;
    if (inputType === 'raw') {
        const center = markDef.center
            ? markDef.center
            : markDef.extent
                ? markDef.extent === 'iqr'
                    ? 'median'
                    : 'mean'
                : config.errorbar.center;
        const extent = markDef.extent ? markDef.extent : center === 'mean' ? 'stderr' : 'iqr';
        if ((center === 'median') !== (extent === 'iqr')) {
            standalone_log_warn(standalone_errorBarCenterIsUsedWithWrongExtent(center, extent, compositeMark));
        }
        if (extent === 'stderr' || extent === 'stdev') {
            errorBarSpecificAggregate = [
                { op: extent, field: continuousFieldName, as: `extent_${continuousFieldName}` },
                { op: center, field: continuousFieldName, as: `center_${continuousFieldName}` }
            ];
            postAggregateCalculates = [
                {
                    calculate: `${standalone_accessWithDatumToUnescapedPath(`center_${continuousFieldName}`)} + ${standalone_accessWithDatumToUnescapedPath(`extent_${continuousFieldName}`)}`,
                    as: `upper_${continuousFieldName}`
                },
                {
                    calculate: `${standalone_accessWithDatumToUnescapedPath(`center_${continuousFieldName}`)} - ${standalone_accessWithDatumToUnescapedPath(`extent_${continuousFieldName}`)}`,
                    as: `lower_${continuousFieldName}`
                }
            ];
            tooltipSummary = [
                { fieldPrefix: 'center_', titlePrefix: standalone_titleCase(center) },
                { fieldPrefix: 'upper_', titlePrefix: standalone_getTitlePrefix(center, extent, '+') },
                { fieldPrefix: 'lower_', titlePrefix: standalone_getTitlePrefix(center, extent, '-') }
            ];
            tooltipTitleWithFieldName = true;
        }
        else {
            let centerOp;
            let lowerExtentOp;
            let upperExtentOp;
            if (extent === 'ci') {
                centerOp = 'mean';
                lowerExtentOp = 'ci0';
                upperExtentOp = 'ci1';
            }
            else {
                centerOp = 'median';
                lowerExtentOp = 'q1';
                upperExtentOp = 'q3';
            }
            errorBarSpecificAggregate = [
                { op: lowerExtentOp, field: continuousFieldName, as: `lower_${continuousFieldName}` },
                { op: upperExtentOp, field: continuousFieldName, as: `upper_${continuousFieldName}` },
                { op: centerOp, field: continuousFieldName, as: `center_${continuousFieldName}` }
            ];
            tooltipSummary = [
                {
                    fieldPrefix: 'upper_',
                    titlePrefix: standalone_channeldef_title({ field: continuousFieldName, aggregate: upperExtentOp, type: 'quantitative' }, config, {
                        allowDisabling: false
                    })
                },
                {
                    fieldPrefix: 'lower_',
                    titlePrefix: standalone_channeldef_title({ field: continuousFieldName, aggregate: lowerExtentOp, type: 'quantitative' }, config, {
                        allowDisabling: false
                    })
                },
                {
                    fieldPrefix: 'center_',
                    titlePrefix: standalone_channeldef_title({ field: continuousFieldName, aggregate: centerOp, type: 'quantitative' }, config, {
                        allowDisabling: false
                    })
                }
            ];
        }
    }
    else {
        if (markDef.center || markDef.extent) {
            standalone_log_warn(standalone_errorBarCenterAndExtentAreNotNeeded(markDef.center, markDef.extent));
        }
        if (inputType === 'aggregated-upper-lower') {
            tooltipSummary = [];
            postAggregateCalculates = [
                {
                    calculate: standalone_accessWithDatumToUnescapedPath(continuousAxisChannelDef2.field),
                    as: `upper_${continuousFieldName}`
                },
                { calculate: standalone_accessWithDatumToUnescapedPath(continuousFieldName), as: `lower_${continuousFieldName}` }
            ];
        }
        else if (inputType === 'aggregated-error') {
            tooltipSummary = [{ fieldPrefix: '', titlePrefix: continuousFieldName }];
            postAggregateCalculates = [
                {
                    calculate: `${standalone_accessWithDatumToUnescapedPath(continuousFieldName)} + ${standalone_accessWithDatumToUnescapedPath(continuousAxisChannelDefError.field)}`,
                    as: `upper_${continuousFieldName}`
                }
            ];
            if (continuousAxisChannelDefError2) {
                postAggregateCalculates.push({
                    calculate: `${standalone_accessWithDatumToUnescapedPath(continuousFieldName)} + ${standalone_accessWithDatumToUnescapedPath(continuousAxisChannelDefError2.field)}`,
                    as: `lower_${continuousFieldName}`
                });
            }
            else {
                postAggregateCalculates.push({
                    calculate: `${standalone_accessWithDatumToUnescapedPath(continuousFieldName)} - ${standalone_accessWithDatumToUnescapedPath(continuousAxisChannelDefError.field)}`,
                    as: `lower_${continuousFieldName}`
                });
            }
        }
        for (const postAggregateCalculate of postAggregateCalculates) {
            tooltipSummary.push({
                fieldPrefix: postAggregateCalculate.as.substring(0, 6),
                titlePrefix: standalone_replaceAll(standalone_replaceAll(postAggregateCalculate.calculate, "datum['", ''), "']", '')
            });
        }
    }
    return { postAggregateCalculates, errorBarSpecificAggregate, tooltipSummary, tooltipTitleWithFieldName };
}
function standalone_getTitlePrefix(center, extent, operation) {
    return `${standalone_titleCase(center)} ${operation} ${extent}`;
}
//# sourceMappingURL=errorbar.js.map
;// ../../node_modules/vega-lite/build/src/compositemark/errorband.js





const standalone_ERRORBAND = 'errorband';
const standalone_ERRORBAND_PARTS = ['band', 'borders'];
const standalone_errorBandNormalizer = new standalone_CompositeMarkNormalizer(standalone_ERRORBAND, standalone_normalizeErrorBand);
function standalone_normalizeErrorBand(spec, { config }) {
    // Need to initEncoding first so we can infer type
    spec = {
        ...spec,
        encoding: standalone_normalizeEncoding(spec.encoding, config)
    };
    const { transform, continuousAxisChannelDef, continuousAxis, encodingWithoutContinuousAxis, markDef, outerSpec, tooltipEncoding } = standalone_errorBarParams(spec, standalone_ERRORBAND, config);
    const errorBandDef = markDef;
    const makeErrorBandPart = standalone_makeCompositeAggregatePartFactory(errorBandDef, continuousAxis, continuousAxisChannelDef, encodingWithoutContinuousAxis, config.errorband);
    const is2D = spec.encoding.x !== undefined && spec.encoding.y !== undefined;
    let bandMark = { type: is2D ? 'area' : 'rect' };
    let bordersMark = { type: is2D ? 'line' : 'rule' };
    const interpolate = {
        ...(errorBandDef.interpolate ? { interpolate: errorBandDef.interpolate } : {}),
        ...(errorBandDef.tension && errorBandDef.interpolate ? { tension: errorBandDef.tension } : {})
    };
    if (is2D) {
        bandMark = {
            ...bandMark,
            ...interpolate,
            ariaRoleDescription: 'errorband'
        };
        bordersMark = {
            ...bordersMark,
            ...interpolate,
            aria: false
        };
    }
    else if (errorBandDef.interpolate) {
        standalone_log_warn(standalone_errorBand1DNotSupport('interpolate'));
    }
    else if (errorBandDef.tension) {
        standalone_log_warn(standalone_errorBand1DNotSupport('tension'));
    }
    return {
        ...outerSpec,
        transform,
        layer: [
            ...makeErrorBandPart({
                partName: 'band',
                mark: bandMark,
                positionPrefix: 'lower',
                endPositionPrefix: 'upper',
                extraEncoding: tooltipEncoding
            }),
            ...makeErrorBandPart({
                partName: 'borders',
                mark: bordersMark,
                positionPrefix: 'lower',
                extraEncoding: tooltipEncoding
            }),
            ...makeErrorBandPart({
                partName: 'borders',
                mark: bordersMark,
                positionPrefix: 'upper',
                extraEncoding: tooltipEncoding
            })
        ]
    };
}
//# sourceMappingURL=errorband.js.map
;// ../../node_modules/vega-lite/build/src/compositemark/index.js





/**
 * Registry index for all composite mark's normalizer
 */
const standalone_compositeMarkRegistry = {};
function standalone_compositemark_add(mark, run, parts) {
    const normalizer = new standalone_CompositeMarkNormalizer(mark, run);
    standalone_compositeMarkRegistry[mark] = { normalizer, parts };
}
function standalone_compositemark_remove(mark) {
    delete standalone_compositeMarkRegistry[mark];
}
function standalone_getAllCompositeMarks() {
    return standalone_util_keys(standalone_compositeMarkRegistry);
}
standalone_compositemark_add(standalone_BOXPLOT, standalone_normalizeBoxPlot, standalone_BOXPLOT_PARTS);
standalone_compositemark_add(standalone_ERRORBAR, standalone_normalizeErrorBar, standalone_ERRORBAR_PARTS);
standalone_compositemark_add(standalone_ERRORBAND, standalone_normalizeErrorBand, standalone_ERRORBAND_PARTS);
//# sourceMappingURL=index.js.map
;// ../../node_modules/vega-lite/build/src/guide.js
const standalone_VL_ONLY_LEGEND_CONFIG = [
    'gradientHorizontalMaxLength',
    'gradientHorizontalMinLength',
    'gradientVerticalMaxLength',
    'gradientVerticalMinLength',
    'unselectedOpacity'
];
//# sourceMappingURL=guide.js.map
;// ../../node_modules/vega-lite/build/src/header.js

const standalone_HEADER_TITLE_PROPERTIES_MAP = {
    titleAlign: 'align',
    titleAnchor: 'anchor',
    titleAngle: 'angle',
    titleBaseline: 'baseline',
    titleColor: 'color',
    titleFont: 'font',
    titleFontSize: 'fontSize',
    titleFontStyle: 'fontStyle',
    titleFontWeight: 'fontWeight',
    titleLimit: 'limit',
    titleLineHeight: 'lineHeight',
    titleOrient: 'orient',
    titlePadding: 'offset'
};
const standalone_HEADER_LABEL_PROPERTIES_MAP = {
    labelAlign: 'align',
    labelAnchor: 'anchor',
    labelAngle: 'angle',
    labelBaseline: 'baseline',
    labelColor: 'color',
    labelFont: 'font',
    labelFontSize: 'fontSize',
    labelFontStyle: 'fontStyle',
    labelFontWeight: 'fontWeight',
    labelLimit: 'limit',
    labelLineHeight: 'lineHeight',
    labelOrient: 'orient',
    labelPadding: 'offset'
};
const standalone_HEADER_TITLE_PROPERTIES = standalone_util_keys(standalone_HEADER_TITLE_PROPERTIES_MAP);
const standalone_HEADER_LABEL_PROPERTIES = standalone_util_keys(standalone_HEADER_LABEL_PROPERTIES_MAP);
const standalone_HEADER_CONFIGS_INDEX = {
    header: 1,
    headerRow: 1,
    headerColumn: 1,
    headerFacet: 1
};
const standalone_HEADER_CONFIGS = standalone_util_keys(standalone_HEADER_CONFIGS_INDEX);
//# sourceMappingURL=header.js.map
;// ../../node_modules/vega-lite/build/src/legend.js

const standalone_LEGEND_SCALE_CHANNELS = [
    'size',
    'shape',
    'fill',
    'stroke',
    'strokeDash',
    'strokeWidth',
    'opacity'
];
const standalone_defaultLegendConfig = {
    gradientHorizontalMaxLength: 200,
    gradientHorizontalMinLength: 100,
    gradientVerticalMaxLength: 200,
    gradientVerticalMinLength: 64, // This is Vega's minimum.
    unselectedOpacity: 0.35
};
const standalone_COMMON_LEGEND_PROPERTY_INDEX = {
    aria: 1,
    clipHeight: 1,
    columnPadding: 1,
    columns: 1,
    cornerRadius: 1,
    description: 1,
    direction: 1,
    fillColor: 1,
    format: 1,
    formatType: 1,
    gradientLength: 1,
    gradientOpacity: 1,
    gradientStrokeColor: 1,
    gradientStrokeWidth: 1,
    gradientThickness: 1,
    gridAlign: 1,
    labelAlign: 1,
    labelBaseline: 1,
    labelColor: 1,
    labelFont: 1,
    labelFontSize: 1,
    labelFontStyle: 1,
    labelFontWeight: 1,
    labelLimit: 1,
    labelOffset: 1,
    labelOpacity: 1,
    labelOverlap: 1,
    labelPadding: 1,
    labelSeparation: 1,
    legendX: 1,
    legendY: 1,
    offset: 1,
    orient: 1,
    padding: 1,
    rowPadding: 1,
    strokeColor: 1,
    symbolDash: 1,
    symbolDashOffset: 1,
    symbolFillColor: 1,
    symbolLimit: 1,
    symbolOffset: 1,
    symbolOpacity: 1,
    symbolSize: 1,
    symbolStrokeColor: 1,
    symbolStrokeWidth: 1,
    symbolType: 1,
    tickCount: 1,
    tickMinStep: 1,
    title: 1,
    titleAlign: 1,
    titleAnchor: 1,
    titleBaseline: 1,
    titleColor: 1,
    titleFont: 1,
    titleFontSize: 1,
    titleFontStyle: 1,
    titleFontWeight: 1,
    titleLimit: 1,
    titleLineHeight: 1,
    titleOpacity: 1,
    titleOrient: 1,
    titlePadding: 1,
    type: 1,
    values: 1,
    zindex: 1
};
const standalone_LEGEND_PROPERTIES = standalone_util_keys(standalone_COMMON_LEGEND_PROPERTY_INDEX);
//# sourceMappingURL=legend.js.map
;// ../../node_modules/vega-lite/build/src/selection.js

const standalone_SELECTION_ID = '_vgsid_';
const standalone_defaultConfig = {
    point: {
        on: 'click',
        fields: [standalone_SELECTION_ID],
        toggle: 'event.shiftKey',
        resolve: 'global',
        clear: 'dblclick'
    },
    interval: {
        on: '[pointerdown, window:pointerup] > window:pointermove!',
        encodings: ['x', 'y'],
        translate: '[pointerdown, window:pointerup] > window:pointermove!',
        zoom: 'wheel!',
        mark: { fill: '#333', fillOpacity: 0.125, stroke: 'white' },
        resolve: 'global',
        clear: 'dblclick'
    }
};
function standalone_isLegendBinding(bind) {
    return bind === 'legend' || !!bind?.legend;
}
function standalone_isLegendStreamBinding(bind) {
    return standalone_isLegendBinding(bind) && standalone_vega_util_module_isObject(bind);
}
function standalone_isSelectionParameter(param) {
    return !!param?.['select'];
}
//# sourceMappingURL=selection.js.map
;// ../../node_modules/vega-lite/build/src/parameter.js

function standalone_assembleParameterSignals(params) {
    const signals = [];
    for (const param of params || []) {
        // Selection parameters are handled separately via assembleSelectionTopLevelSignals
        // and assembleSignals methods registered on the Model.
        if (standalone_isSelectionParameter(param))
            continue;
        const { expr, bind, ...rest } = param;
        if (bind && expr) {
            // Vega's InitSignal -- apply expr to "init"
            const signal = {
                ...rest,
                bind,
                init: expr
            };
            signals.push(signal);
        }
        else {
            const signal = {
                ...rest,
                ...(expr ? { update: expr } : {}),
                ...(bind ? { bind } : {})
            };
            signals.push(signal);
        }
    }
    return signals;
}
//# sourceMappingURL=parameter.js.map
;// ../../node_modules/vega-lite/build/src/spec/concat.js

function standalone_isAnyConcatSpec(spec) {
    return standalone_isVConcatSpec(spec) || standalone_isHConcatSpec(spec) || standalone_isConcatSpec(spec);
}
function standalone_isConcatSpec(spec) {
    return standalone_util_hasProperty(spec, 'concat');
}
function standalone_isVConcatSpec(spec) {
    return standalone_util_hasProperty(spec, 'vconcat');
}
function standalone_isHConcatSpec(spec) {
    return standalone_util_hasProperty(spec, 'hconcat');
}
//# sourceMappingURL=concat.js.map
;// ../../node_modules/vega-lite/build/src/spec/base.js




function standalone_getStepFor({ step, offsetIsDiscrete }) {
    if (offsetIsDiscrete) {
        return step.for ?? 'offset';
    }
    else {
        return 'position';
    }
}
function standalone_isStep(size) {
    return standalone_util_hasProperty(size, 'step');
}
function standalone_isFrameMixins(o) {
    return standalone_util_hasProperty(o, 'view') || standalone_util_hasProperty(o, 'width') || standalone_util_hasProperty(o, 'height');
}
const standalone_DEFAULT_SPACING = 20;
const standalone_COMPOSITION_LAYOUT_INDEX = {
    align: 1,
    bounds: 1,
    center: 1,
    columns: 1,
    spacing: 1
};
const standalone_COMPOSITION_LAYOUT_PROPERTIES = standalone_util_keys(standalone_COMPOSITION_LAYOUT_INDEX);
function standalone_extractCompositionLayout(spec, specType, config) {
    const compositionConfig = config[specType];
    const layout = {};
    // Apply config first
    const { spacing: spacingConfig, columns } = compositionConfig;
    if (spacingConfig !== undefined) {
        layout.spacing = spacingConfig;
    }
    if (columns !== undefined) {
        if ((standalone_isFacetSpec(spec) && !standalone_isFacetMapping(spec.facet)) || standalone_isConcatSpec(spec)) {
            layout.columns = columns;
        }
    }
    if (standalone_isVConcatSpec(spec)) {
        layout.columns = 1;
    }
    // Then copy properties from the spec
    for (const prop of standalone_COMPOSITION_LAYOUT_PROPERTIES) {
        if (spec[prop] !== undefined) {
            if (prop === 'spacing') {
                const spacing = spec[prop];
                layout[prop] = standalone_isNumber(spacing)
                    ? spacing
                    : {
                        row: spacing.row ?? spacingConfig,
                        column: spacing.column ?? spacingConfig
                    };
            }
            else {
                layout[prop] = spec[prop];
            }
        }
    }
    return layout;
}
//# sourceMappingURL=base.js.map
;// ../../node_modules/vega-lite/build/src/config.js
















function standalone_getViewConfigContinuousSize(viewConfig, channel) {
    return viewConfig[channel] ?? viewConfig[channel === 'width' ? 'continuousWidth' : 'continuousHeight']; // get width/height for backwards compatibility
}
function standalone_getViewConfigDiscreteStep(viewConfig, channel) {
    const size = standalone_getViewConfigDiscreteSize(viewConfig, channel);
    return standalone_isStep(size) ? size.step : standalone_DEFAULT_STEP;
}
function standalone_getViewConfigDiscreteSize(viewConfig, channel) {
    const size = viewConfig[channel] ?? viewConfig[channel === 'width' ? 'discreteWidth' : 'discreteHeight']; // get width/height for backwards compatibility
    return standalone_getFirstDefined(size, { step: viewConfig.step });
}
const standalone_DEFAULT_STEP = 20;
const standalone_defaultViewConfig = {
    continuousWidth: 200,
    continuousHeight: 200,
    step: standalone_DEFAULT_STEP
};
function standalone_isVgScheme(rangeScheme) {
    return hasProperty(rangeScheme, 'scheme');
}
const standalone_config_defaultConfig = {
    background: 'white',
    padding: 5,
    timeFormat: '%b %d, %Y',
    countTitle: 'Count of Records',
    view: standalone_defaultViewConfig,
    mark: standalone_defaultMarkConfig,
    arc: {},
    area: {},
    bar: standalone_defaultBarConfig,
    circle: {},
    geoshape: {},
    image: {},
    line: {},
    point: {},
    rect: standalone_defaultRectConfig,
    rule: { color: 'black' }, // Need this to override default color in mark config
    square: {},
    text: { color: 'black' }, // Need this to override default color in mark config
    tick: standalone_defaultTickConfig,
    trail: {},
    boxplot: {
        size: 14,
        extent: 1.5,
        box: {},
        median: { color: 'white' },
        outliers: {},
        rule: {},
        ticks: null
    },
    errorbar: {
        center: 'mean',
        rule: true,
        ticks: false
    },
    errorband: {
        band: {
            opacity: 0.3
        },
        borders: false
    },
    scale: standalone_defaultScaleConfig,
    projection: {},
    legend: standalone_defaultLegendConfig,
    header: { titlePadding: 10, labelPadding: 10 },
    headerColumn: {},
    headerRow: {},
    headerFacet: {},
    selection: standalone_defaultConfig,
    style: {},
    title: {},
    facet: { spacing: standalone_DEFAULT_SPACING },
    concat: { spacing: standalone_DEFAULT_SPACING },
    normalizedNumberFormat: '.0%'
};
// Tableau10 color palette, copied from `vegaScale.scheme('tableau10')`
const standalone_tab10 = [
    '#4c78a8',
    '#f58518',
    '#e45756',
    '#72b7b2',
    '#54a24b',
    '#eeca3b',
    '#b279a2',
    '#ff9da6',
    '#9d755d',
    '#bab0ac'
];
const standalone_DEFAULT_FONT_SIZE = {
    text: 11,
    guideLabel: 10,
    guideTitle: 11,
    groupTitle: 13,
    groupSubtitle: 12
};
const standalone_DEFAULT_COLOR = {
    blue: standalone_tab10[0],
    orange: standalone_tab10[1],
    red: standalone_tab10[2],
    teal: standalone_tab10[3],
    green: standalone_tab10[4],
    yellow: standalone_tab10[5],
    purple: standalone_tab10[6],
    pink: standalone_tab10[7],
    brown: standalone_tab10[8],
    gray0: '#000',
    gray1: '#111',
    gray2: '#222',
    gray3: '#333',
    gray4: '#444',
    gray5: '#555',
    gray6: '#666',
    gray7: '#777',
    gray8: '#888',
    gray9: '#999',
    gray10: '#aaa',
    gray11: '#bbb',
    gray12: '#ccc',
    gray13: '#ddd',
    gray14: '#eee',
    gray15: '#fff'
};
function standalone_colorSignalConfig(color = {}) {
    return {
        signals: [
            {
                name: 'color',
                value: standalone_vega_util_module_isObject(color) ? { ...standalone_DEFAULT_COLOR, ...color } : standalone_DEFAULT_COLOR
            }
        ],
        mark: { color: { signal: 'color.blue' } },
        rule: { color: { signal: 'color.gray0' } },
        text: {
            color: { signal: 'color.gray0' }
        },
        style: {
            'guide-label': {
                fill: { signal: 'color.gray0' }
            },
            'guide-title': {
                fill: { signal: 'color.gray0' }
            },
            'group-title': {
                fill: { signal: 'color.gray0' }
            },
            'group-subtitle': {
                fill: { signal: 'color.gray0' }
            },
            cell: {
                stroke: { signal: 'color.gray8' }
            }
        },
        axis: {
            domainColor: { signal: 'color.gray13' },
            gridColor: { signal: 'color.gray8' },
            tickColor: { signal: 'color.gray13' }
        },
        range: {
            category: [
                { signal: 'color.blue' },
                { signal: 'color.orange' },
                { signal: 'color.red' },
                { signal: 'color.teal' },
                { signal: 'color.green' },
                { signal: 'color.yellow' },
                { signal: 'color.purple' },
                { signal: 'color.pink' },
                { signal: 'color.brown' },
                { signal: 'color.grey8' }
            ]
        }
    };
}
function standalone_fontSizeSignalConfig(fontSize) {
    return {
        signals: [
            {
                name: 'fontSize',
                value: standalone_vega_util_module_isObject(fontSize) ? { ...standalone_DEFAULT_FONT_SIZE, ...fontSize } : standalone_DEFAULT_FONT_SIZE
            }
        ],
        text: {
            fontSize: { signal: 'fontSize.text' }
        },
        style: {
            'guide-label': {
                fontSize: { signal: 'fontSize.guideLabel' }
            },
            'guide-title': {
                fontSize: { signal: 'fontSize.guideTitle' }
            },
            'group-title': {
                fontSize: { signal: 'fontSize.groupTitle' }
            },
            'group-subtitle': {
                fontSize: { signal: 'fontSize.groupSubtitle' }
            }
        }
    };
}
function standalone_fontConfig(font) {
    return {
        text: { font },
        style: {
            'guide-label': { font },
            'guide-title': { font },
            'group-title': { font },
            'group-subtitle': { font }
        }
    };
}
function standalone_getAxisConfigInternal(axisConfig) {
    const props = standalone_util_keys(axisConfig || {});
    const axisConfigInternal = {};
    for (const prop of props) {
        const val = axisConfig[prop];
        axisConfigInternal[prop] = standalone_isConditionalAxisValue(val)
            ? standalone_signalOrValueRefWithCondition(val)
            : standalone_signalRefOrValue(val);
    }
    return axisConfigInternal;
}
function standalone_getStyleConfigInternal(styleConfig) {
    const props = standalone_util_keys(styleConfig);
    const styleConfigInternal = {};
    for (const prop of props) {
        // We need to cast to cheat a bit here since styleConfig can be either mark config or axis config
        styleConfigInternal[prop] = standalone_getAxisConfigInternal(styleConfig[prop]);
    }
    return styleConfigInternal;
}
const standalone_configPropsWithExpr = [
    ...standalone_MARK_CONFIGS,
    ...standalone_AXIS_CONFIGS,
    ...standalone_HEADER_CONFIGS,
    'background',
    'padding',
    'legend',
    'lineBreak',
    'scale',
    'style',
    'title',
    'view'
];
/**
 * Merge specified config with default config and config for the `color` flag,
 * then replace all expressions with signals
 */
function standalone_initConfig(specifiedConfig = {}) {
    const { color, font, fontSize, selection, ...restConfig } = specifiedConfig;
    const mergedConfig = standalone_mergeConfig({}, standalone_duplicate(standalone_config_defaultConfig), font ? standalone_fontConfig(font) : {}, color ? standalone_colorSignalConfig(color) : {}, fontSize ? standalone_fontSizeSignalConfig(fontSize) : {}, restConfig || {});
    // mergeConfig doesn't recurse and overrides object values.
    if (selection) {
        standalone_writeConfig(mergedConfig, 'selection', selection, true);
    }
    const outputConfig = standalone_omit(mergedConfig, standalone_configPropsWithExpr);
    for (const prop of ['background', 'lineBreak', 'padding']) {
        if (mergedConfig[prop]) {
            outputConfig[prop] = standalone_signalRefOrValue(mergedConfig[prop]);
        }
    }
    for (const markConfigType of standalone_MARK_CONFIGS) {
        if (mergedConfig[markConfigType]) {
            // FIXME: outputConfig[markConfigType] expects that types are replaced recursively but replaceExprRef only replaces one level deep
            outputConfig[markConfigType] = standalone_replaceExprRef(mergedConfig[markConfigType]);
        }
    }
    for (const axisConfigType of standalone_AXIS_CONFIGS) {
        if (mergedConfig[axisConfigType]) {
            outputConfig[axisConfigType] = standalone_getAxisConfigInternal(mergedConfig[axisConfigType]);
        }
    }
    for (const headerConfigType of standalone_HEADER_CONFIGS) {
        if (mergedConfig[headerConfigType]) {
            outputConfig[headerConfigType] = standalone_replaceExprRef(mergedConfig[headerConfigType]);
        }
    }
    if (mergedConfig.legend) {
        outputConfig.legend = standalone_replaceExprRef(mergedConfig.legend);
    }
    if (mergedConfig.scale) {
        const { invalid, ...otherScaleConfig } = mergedConfig.scale;
        const newScaleInvalid = standalone_replaceExprRef(invalid, { level: 1 });
        outputConfig.scale = {
            ...standalone_replaceExprRef(otherScaleConfig),
            ...(standalone_util_keys(newScaleInvalid).length > 0 ? { invalid: newScaleInvalid } : {})
        };
    }
    if (mergedConfig.style) {
        outputConfig.style = standalone_getStyleConfigInternal(mergedConfig.style);
    }
    if (mergedConfig.title) {
        outputConfig.title = standalone_replaceExprRef(mergedConfig.title);
    }
    if (mergedConfig.view) {
        outputConfig.view = standalone_replaceExprRef(mergedConfig.view);
    }
    return outputConfig;
}
const standalone_MARK_STYLES = new Set(['view', ...standalone_PRIMITIVE_MARKS]);
const standalone_VL_ONLY_CONFIG_PROPERTIES = [
    'color',
    'fontSize',
    'background', // We apply background to the spec directly.
    'padding',
    'facet',
    'concat',
    'numberFormat',
    'numberFormatType',
    'normalizedNumberFormat',
    'normalizedNumberFormatType',
    'timeFormat',
    'countTitle',
    'header',
    'axisQuantitative',
    'axisTemporal',
    'axisDiscrete',
    'axisPoint',
    'axisXBand',
    'axisXPoint',
    'axisXDiscrete',
    'axisXQuantitative',
    'axisXTemporal',
    'axisYBand',
    'axisYPoint',
    'axisYDiscrete',
    'axisYQuantitative',
    'axisYTemporal',
    'scale',
    'selection',
    'overlay' // FIXME: Redesign and unhide this
];
const standalone_VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = {
    view: ['continuousWidth', 'continuousHeight', 'discreteWidth', 'discreteHeight', 'step'],
    ...standalone_VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX
};
function standalone_stripAndRedirectConfig(config) {
    config = standalone_duplicate(config);
    for (const prop of standalone_VL_ONLY_CONFIG_PROPERTIES) {
        delete config[prop];
    }
    if (config.axis) {
        // delete condition axis config
        for (const prop in config.axis) {
            if (standalone_isConditionalAxisValue(config.axis[prop])) {
                delete config.axis[prop];
            }
        }
    }
    if (config.legend) {
        for (const prop of standalone_VL_ONLY_LEGEND_CONFIG) {
            delete config.legend[prop];
        }
    }
    // Remove Vega-Lite only generic mark config
    if (config.mark) {
        for (const prop of standalone_VL_ONLY_MARK_CONFIG_PROPERTIES) {
            delete config.mark[prop];
        }
        if (config.mark.tooltip && standalone_vega_util_module_isObject(config.mark.tooltip)) {
            delete config.mark.tooltip;
        }
    }
    if (config.params) {
        config.signals = (config.signals || []).concat(standalone_assembleParameterSignals(config.params));
        delete config.params;
    }
    for (const markType of standalone_MARK_STYLES) {
        // Remove Vega-Lite-only mark config
        for (const prop of standalone_VL_ONLY_MARK_CONFIG_PROPERTIES) {
            delete config[markType][prop];
        }
        // Remove Vega-Lite only mark-specific config
        const vlOnlyMarkSpecificConfigs = standalone_VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX[markType];
        if (vlOnlyMarkSpecificConfigs) {
            for (const prop of vlOnlyMarkSpecificConfigs) {
                delete config[markType][prop];
            }
        }
        // Redirect mark config to config.style so that mark config only affect its own mark type
        // without affecting other marks that share the same underlying Vega marks.
        // For example, config.rect should not affect bar marks.
        standalone_redirectConfigToStyleConfig(config, markType);
    }
    for (const m of standalone_getAllCompositeMarks()) {
        // Clean up the composite mark config as we don't need them in the output specs anymore
        delete config[m];
    }
    standalone_redirectTitleConfig(config);
    // Remove empty config objects.
    for (const prop in config) {
        // @ts-ignore
        if (standalone_vega_util_module_isObject(config[prop]) && standalone_isEmpty(config[prop])) {
            // @ts-ignore
            delete config[prop];
        }
    }
    return standalone_isEmpty(config) ? undefined : config;
}
/**
 *
 * Redirect config.title -- so that title config do not affect header labels,
 * which also uses `title` directive to implement.
 *
 * For subtitle configs in config.title, keep them in config.title as header titles never have subtitles.
 */
function standalone_redirectTitleConfig(config) {
    const { titleMarkConfig, subtitleMarkConfig, subtitle } = standalone_extractTitleConfig(config.title);
    // set config.style if title/subtitleMarkConfig is not an empty object
    if (!standalone_isEmpty(titleMarkConfig)) {
        config.style['group-title'] = {
            ...config.style['group-title'],
            ...titleMarkConfig // config.title has higher precedence than config.style.group-title in Vega
        };
    }
    if (!standalone_isEmpty(subtitleMarkConfig)) {
        config.style['group-subtitle'] = {
            ...config.style['group-subtitle'],
            ...subtitleMarkConfig
        };
    }
    // subtitle part can stay in config.title since header titles do not use subtitle
    if (!standalone_isEmpty(subtitle)) {
        config.title = subtitle;
    }
    else {
        delete config.title;
    }
}
function standalone_redirectConfigToStyleConfig(config, prop, // string = composite mark
toProp, compositeMarkPart) {
    const propConfig = compositeMarkPart
        ? config[prop][compositeMarkPart]
        : config[prop];
    if (prop === 'view') {
        toProp = 'cell'; // View's default style is "cell"
    }
    const style = {
        ...propConfig,
        ...config.style[toProp ?? prop]
    };
    // set config.style if it is not an empty object
    if (!standalone_isEmpty(style)) {
        config.style[toProp ?? prop] = style;
    }
    if (!compositeMarkPart) {
        // For composite mark, so don't delete the whole config yet as we have to do multiple redirections.
        delete config[prop];
    }
}
//# sourceMappingURL=config.js.map
;// ../../node_modules/vega-lite/build/src/spec/layer.js

function standalone_isLayerSpec(spec) {
    return standalone_util_hasProperty(spec, 'layer');
}
//# sourceMappingURL=layer.js.map
;// ../../node_modules/vega-lite/build/src/spec/repeat.js


function standalone_isRepeatSpec(spec) {
    return standalone_util_hasProperty(spec, 'repeat');
}
function standalone_isLayerRepeatSpec(spec) {
    return !standalone_vega_util_module_isArray(spec.repeat) && standalone_util_hasProperty(spec.repeat, 'layer');
}
//# sourceMappingURL=repeat.js.map
;// ../../node_modules/vega-lite/build/src/spec/index.js





//# sourceMappingURL=index.js.map
;// ../../node_modules/vega-lite/build/src/spec/map.js






class standalone_SpecMapper {
    map(spec, params) {
        if (standalone_isFacetSpec(spec)) {
            return this.mapFacet(spec, params);
        }
        else if (standalone_isRepeatSpec(spec)) {
            return this.mapRepeat(spec, params);
        }
        else if (standalone_isHConcatSpec(spec)) {
            return this.mapHConcat(spec, params);
        }
        else if (standalone_isVConcatSpec(spec)) {
            return this.mapVConcat(spec, params);
        }
        else if (standalone_isConcatSpec(spec)) {
            return this.mapConcat(spec, params);
        }
        else {
            return this.mapLayerOrUnit(spec, params);
        }
    }
    mapLayerOrUnit(spec, params) {
        if (standalone_isLayerSpec(spec)) {
            return this.mapLayer(spec, params);
        }
        else if (standalone_isUnitSpec(spec)) {
            return this.mapUnit(spec, params);
        }
        throw new Error(standalone_invalidSpec(spec));
    }
    mapLayer(spec, params) {
        return {
            ...spec,
            layer: spec.layer.map(subspec => this.mapLayerOrUnit(subspec, params))
        };
    }
    mapHConcat(spec, params) {
        return {
            ...spec,
            hconcat: spec.hconcat.map(subspec => this.map(subspec, params))
        };
    }
    mapVConcat(spec, params) {
        return {
            ...spec,
            vconcat: spec.vconcat.map(subspec => this.map(subspec, params))
        };
    }
    mapConcat(spec, params) {
        const { concat, ...rest } = spec;
        return {
            ...rest,
            concat: concat.map(subspec => this.map(subspec, params))
        };
    }
    mapFacet(spec, params) {
        return {
            // as any is required here since TS cannot infer that FO may only be FieldName or Field, but not RepeatRef
            ...spec,
            // TODO: remove "any" once we support all facet listed in https://github.com/vega/vega-lite/issues/2760
            spec: this.map(spec.spec, params)
        };
    }
    mapRepeat(spec, params) {
        return {
            ...spec,
            // as any is required here since TS cannot infer that the output type satisfies the input type
            spec: this.map(spec.spec, params)
        };
    }
}
//# sourceMappingURL=map.js.map
;// ../../node_modules/vega-lite/build/src/stack.js








const standalone_STACK_OFFSET_INDEX = {
    zero: 1,
    center: 1,
    normalize: 1
};
function standalone_isStackOffset(s) {
    return standalone_vega_util_module_has(standalone_STACK_OFFSET_INDEX, s);
}
const standalone_STACKABLE_MARKS = new Set([standalone_ARC, standalone_BAR, standalone_AREA, standalone_RULE, standalone_POINT, standalone_CIRCLE, standalone_SQUARE, standalone_LINE, standalone_mark_TEXT, standalone_TICK]);
const standalone_STACK_BY_DEFAULT_MARKS = new Set([standalone_BAR, standalone_AREA, standalone_ARC]);
function standalone_isUnbinnedQuantitative(channelDef) {
    return standalone_isFieldDef(channelDef) && standalone_channelDefType(channelDef) === 'quantitative' && !channelDef.bin;
}
function standalone_potentialStackedChannel(encoding, x, { orient, type: mark }) {
    const y = x === 'x' ? 'y' : 'radius';
    const isCartesianBarOrArea = x === 'x' && ['bar', 'area'].includes(mark);
    const xDef = encoding[x];
    const yDef = encoding[y];
    if (standalone_isFieldDef(xDef) && standalone_isFieldDef(yDef)) {
        if (standalone_isUnbinnedQuantitative(xDef) && standalone_isUnbinnedQuantitative(yDef)) {
            if (xDef.stack) {
                return x;
            }
            else if (yDef.stack) {
                return y;
            }
            const xAggregate = standalone_isFieldDef(xDef) && !!xDef.aggregate;
            const yAggregate = standalone_isFieldDef(yDef) && !!yDef.aggregate;
            // if there is no explicit stacking, only apply stack if there is only one aggregate for x or y
            if (xAggregate !== yAggregate) {
                return xAggregate ? x : y;
            }
            if (isCartesianBarOrArea) {
                if (orient === 'vertical') {
                    return y;
                }
                else if (orient === 'horizontal') {
                    return x;
                }
            }
        }
        else if (standalone_isUnbinnedQuantitative(xDef)) {
            return x;
        }
        else if (standalone_isUnbinnedQuantitative(yDef)) {
            return y;
        }
    }
    else if (standalone_isUnbinnedQuantitative(xDef)) {
        if (isCartesianBarOrArea && orient === 'vertical') {
            return undefined;
        }
        return x;
    }
    else if (standalone_isUnbinnedQuantitative(yDef)) {
        if (isCartesianBarOrArea && orient === 'horizontal') {
            return undefined;
        }
        return y;
    }
    return undefined;
}
function standalone_getDimensionChannel(channel) {
    switch (channel) {
        case 'x':
            return 'y';
        case 'y':
            return 'x';
        case 'theta':
            return 'radius';
        case 'radius':
            return 'theta';
    }
}
function standalone_stack(m, encoding) {
    const markDef = standalone_isMarkDef(m) ? m : { type: m };
    const mark = markDef.type;
    // Should have stackable mark
    if (!standalone_STACKABLE_MARKS.has(mark)) {
        return null;
    }
    // Run potential stacked twice, one for Cartesian and another for Polar,
    // so text marks can be stacked in any of the coordinates.
    // Note: The logic here is not perfectly correct.  If we want to support stacked dot plots where each dot is a pie chart with label, we have to change the stack logic here to separate Cartesian stacking for polar stacking.
    // However, since we probably never want to do that, let's just note the limitation here.
    const fieldChannel = standalone_potentialStackedChannel(encoding, 'x', markDef) || standalone_potentialStackedChannel(encoding, 'theta', markDef);
    if (!fieldChannel) {
        return null;
    }
    const stackedFieldDef = encoding[fieldChannel];
    const stackedField = standalone_isFieldDef(stackedFieldDef) ? standalone_vgField(stackedFieldDef, {}) : undefined;
    const dimensionChannel = standalone_getDimensionChannel(fieldChannel);
    const groupbyChannels = [];
    const groupbyFields = new Set();
    if (encoding[dimensionChannel]) {
        const dimensionDef = encoding[dimensionChannel];
        const dimensionField = standalone_isFieldDef(dimensionDef) ? standalone_vgField(dimensionDef, {}) : undefined;
        if (dimensionField && dimensionField !== stackedField) {
            // avoid grouping by the stacked field
            groupbyChannels.push(dimensionChannel);
            groupbyFields.add(dimensionField);
        }
    }
    const dimensionOffsetChannel = dimensionChannel === 'x' ? 'xOffset' : 'yOffset';
    const dimensionOffsetDef = encoding[dimensionOffsetChannel];
    const dimensionOffsetField = standalone_isFieldDef(dimensionOffsetDef) ? standalone_vgField(dimensionOffsetDef, {}) : undefined;
    if (dimensionOffsetField && dimensionOffsetField !== stackedField) {
        // avoid grouping by the stacked field
        groupbyChannels.push(dimensionOffsetChannel);
        groupbyFields.add(dimensionOffsetField);
    }
    // If the dimension has offset, don't stack anymore
    // Should have grouping level of detail that is different from the dimension field
    const stackBy = standalone_NONPOSITION_CHANNELS.reduce((sc, channel) => {
        // Ignore tooltip in stackBy (https://github.com/vega/vega-lite/issues/4001)
        if (channel !== 'tooltip' && standalone_channelHasField(encoding, channel)) {
            const channelDef = encoding[channel];
            for (const cDef of standalone_array(channelDef)) {
                const fieldDef = standalone_getFieldDef(cDef);
                if (fieldDef.aggregate) {
                    continue;
                }
                // Check whether the channel's field is identical to x/y's field or if the channel is a repeat
                const f = standalone_vgField(fieldDef, {});
                if (
                // if fielddef is a repeat, just include it in the stack by
                !f ||
                    // otherwise, the field must be different from the groupBy fields.
                    !groupbyFields.has(f)) {
                    sc.push({ channel, fieldDef });
                }
            }
        }
        return sc;
    }, []);
    // Automatically determine offset
    let offset;
    if (stackedFieldDef.stack !== undefined) {
        if (standalone_isBoolean(stackedFieldDef.stack)) {
            offset = stackedFieldDef.stack ? 'zero' : null;
        }
        else {
            offset = stackedFieldDef.stack;
        }
    }
    else if (standalone_STACK_BY_DEFAULT_MARKS.has(mark)) {
        offset = 'zero';
    }
    if (!offset || !standalone_isStackOffset(offset)) {
        return null;
    }
    if (standalone_isAggregate(encoding) && stackBy.length === 0) {
        return null;
    }
    // warn when stacking non-linear
    if (stackedFieldDef?.scale?.type && stackedFieldDef?.scale?.type !== standalone_ScaleType.LINEAR) {
        if (stackedFieldDef?.stack) {
            standalone_log_warn(standalone_stackNonLinearScale(stackedFieldDef.scale.type));
        }
    }
    // Check if it is a ranged mark
    if (standalone_isFieldOrDatumDef(encoding[standalone_getSecondaryRangeChannel(fieldChannel)])) {
        if (stackedFieldDef.stack !== undefined) {
            standalone_log_warn(standalone_cannotStackRangedMark(fieldChannel));
        }
        return null;
    }
    // Warn if stacking non-summative aggregate
    if (standalone_isFieldDef(stackedFieldDef) &&
        stackedFieldDef.aggregate &&
        !standalone_SUM_OPS.has(stackedFieldDef.aggregate)) {
        standalone_log_warn(standalone_stackNonSummativeAggregate(stackedFieldDef.aggregate));
    }
    return {
        groupbyChannels,
        groupbyFields,
        fieldChannel,
        impute: stackedFieldDef.impute === null ? false : standalone_isPathMark(mark),
        stackBy,
        offset
    };
}
//# sourceMappingURL=stack.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/init.js









function standalone_initMarkdef(originalMarkDef, encoding, config) {
    // FIXME: markDef expects that exprRefs are replaced recursively but replaceExprRef only replaces the top level
    const markDef = standalone_replaceExprRef(originalMarkDef);
    // set orient, which can be overridden by rules as sometimes the specified orient is invalid.
    const specifiedOrient = standalone_getMarkPropOrConfig('orient', markDef, config);
    markDef.orient = standalone_orient(markDef.type, encoding, specifiedOrient);
    if (specifiedOrient !== undefined && specifiedOrient !== markDef.orient) {
        standalone_log_warn(standalone_orientOverridden(markDef.orient, specifiedOrient));
    }
    if (markDef.type === 'bar' && markDef.orient) {
        const cornerRadiusEnd = standalone_getMarkPropOrConfig('cornerRadiusEnd', markDef, config);
        if (cornerRadiusEnd !== undefined) {
            const newProps = (markDef.orient === 'horizontal' && encoding.x2) || (markDef.orient === 'vertical' && encoding.y2)
                ? ['cornerRadius']
                : standalone_BAR_CORNER_RADIUS_INDEX[markDef.orient];
            for (const newProp of newProps) {
                markDef[newProp] = cornerRadiusEnd;
            }
            if (markDef.cornerRadiusEnd !== undefined) {
                delete markDef.cornerRadiusEnd; // no need to keep the original cap cornerRadius
            }
        }
    }
    // set opacity and filled if not specified in mark config
    const specifiedOpacity = standalone_getMarkPropOrConfig('opacity', markDef, config);
    const specifiedfillOpacity = standalone_getMarkPropOrConfig('fillOpacity', markDef, config);
    if (specifiedOpacity === undefined && specifiedfillOpacity === undefined) {
        markDef.opacity = standalone_opacity(markDef.type, encoding);
    }
    // set cursor, which should be pointer if href channel is present unless otherwise specified
    const specifiedCursor = standalone_getMarkPropOrConfig('cursor', markDef, config);
    if (specifiedCursor === undefined) {
        markDef.cursor = standalone_init_cursor(markDef, encoding, config);
    }
    return markDef;
}
function standalone_init_cursor(markDef, encoding, config) {
    if (encoding.href || markDef.href || standalone_getMarkPropOrConfig('href', markDef, config)) {
        return 'pointer';
    }
    return markDef.cursor;
}
function standalone_opacity(mark, encoding) {
    if (standalone_util_contains([standalone_POINT, standalone_TICK, standalone_CIRCLE, standalone_SQUARE], mark)) {
        // point-based marks
        if (!standalone_isAggregate(encoding)) {
            return 0.7;
        }
    }
    return undefined;
}
function standalone_defaultFilled(markDef, config, { graticule }) {
    if (graticule) {
        return false;
    }
    const filledConfig = standalone_getMarkConfig('filled', markDef, config);
    const mark = markDef.type;
    return standalone_getFirstDefined(filledConfig, mark !== standalone_POINT && mark !== standalone_LINE && mark !== standalone_RULE);
}
function standalone_orient(mark, encoding, specifiedOrient) {
    switch (mark) {
        case standalone_POINT:
        case standalone_CIRCLE:
        case standalone_SQUARE:
        case standalone_mark_TEXT:
        case standalone_RECT:
        case standalone_IMAGE:
            // orient is meaningless for these marks.
            return undefined;
    }
    const { x, y, x2, y2 } = encoding;
    switch (mark) {
        case standalone_BAR:
            if (standalone_isFieldDef(x) && (standalone_isBinned(x.bin) || (standalone_isFieldDef(y) && y.aggregate && !x.aggregate))) {
                return 'vertical';
            }
            if (standalone_isFieldDef(y) && (standalone_isBinned(y.bin) || (standalone_isFieldDef(x) && x.aggregate && !y.aggregate))) {
                return 'horizontal';
            }
            if (y2 || x2) {
                // Ranged bar does not always have clear orientation, so we allow overriding
                if (specifiedOrient) {
                    return specifiedOrient;
                }
                // If y is range and x is non-range, non-bin Q
                if (!x2) {
                    if ((standalone_isFieldDef(x) && x.type === standalone_QUANTITATIVE && !standalone_isBinning(x.bin)) || standalone_isNumericDataDef(x)) {
                        if (standalone_isFieldDef(y) && standalone_isBinned(y.bin)) {
                            return 'horizontal';
                        }
                    }
                    return 'vertical';
                }
                // If x is range and y is non-range, non-bin Q
                if (!y2) {
                    if ((standalone_isFieldDef(y) && y.type === standalone_QUANTITATIVE && !standalone_isBinning(y.bin)) || standalone_isNumericDataDef(y)) {
                        if (standalone_isFieldDef(x) && standalone_isBinned(x.bin)) {
                            return 'vertical';
                        }
                    }
                    return 'horizontal';
                }
            }
        // falls through
        case standalone_RULE:
            // return undefined for line segment rule and bar with both axis ranged
            // we have to ignore the case that the data are already binned
            if (x2 && !(standalone_isFieldDef(x) && standalone_isBinned(x.bin)) && y2 && !(standalone_isFieldDef(y) && standalone_isBinned(y.bin))) {
                return undefined;
            }
        // falls through
        case standalone_AREA:
            // If there are range for both x and y, y (vertical) has higher precedence.
            if (y2) {
                if (standalone_isFieldDef(y) && standalone_isBinned(y.bin)) {
                    return 'horizontal';
                }
                else {
                    return 'vertical';
                }
            }
            else if (x2) {
                if (standalone_isFieldDef(x) && standalone_isBinned(x.bin)) {
                    return 'vertical';
                }
                else {
                    return 'horizontal';
                }
            }
            else if (mark === standalone_RULE) {
                if (x && !y) {
                    return 'vertical';
                }
                else if (y && !x) {
                    return 'horizontal';
                }
            }
        // falls through
        case standalone_LINE:
        case standalone_TICK: {
            const xIsMeasure = standalone_isUnbinnedQuantitativeFieldOrDatumDef(x);
            const yIsMeasure = standalone_isUnbinnedQuantitativeFieldOrDatumDef(y);
            if (specifiedOrient) {
                return specifiedOrient;
            }
            else if (xIsMeasure && !yIsMeasure) {
                // Tick is opposite to bar, line, area
                return mark !== 'tick' ? 'horizontal' : 'vertical';
            }
            else if (!xIsMeasure && yIsMeasure) {
                // Tick is opposite to bar, line, area
                return mark !== 'tick' ? 'vertical' : 'horizontal';
            }
            else if (xIsMeasure && yIsMeasure) {
                return 'vertical';
            }
            else {
                const xIsTemporal = standalone_isTypedFieldDef(x) && x.type === standalone_TEMPORAL;
                const yIsTemporal = standalone_isTypedFieldDef(y) && y.type === standalone_TEMPORAL;
                // x: T, y: N --> vertical tick
                if (xIsTemporal && !yIsTemporal) {
                    return 'vertical';
                }
                else if (!xIsTemporal && yIsTemporal) {
                    return 'horizontal';
                }
            }
            return undefined;
        }
    }
    return 'vertical';
}
//# sourceMappingURL=init.js.map
;// ../../node_modules/vega-lite/build/src/normalize/pathoverlay.js







function standalone_dropLineAndPoint(markDef) {
    const { point: _point, line: _line, ...mark } = markDef;
    return standalone_util_keys(mark).length > 1 ? mark : mark.type;
}
function standalone_dropLineAndPointFromConfig(config) {
    for (const mark of ['line', 'area', 'rule', 'trail']) {
        if (config[mark]) {
            config = {
                ...config,
                // TODO: remove as any
                [mark]: standalone_omit(config[mark], ['point', 'line'])
            };
        }
    }
    return config;
}
function standalone_getPointOverlay(markDef, markConfig = {}, encoding) {
    if (markDef.point === 'transparent') {
        return { opacity: 0 };
    }
    else if (markDef.point) {
        // truthy : true or object
        return standalone_vega_util_module_isObject(markDef.point) ? markDef.point : {};
    }
    else if (markDef.point !== undefined) {
        // false or null
        return null;
    }
    else {
        // undefined (not disabled)
        if (markConfig.point || encoding.shape) {
            // enable point overlay if config[mark].point is truthy or if encoding.shape is provided
            return standalone_vega_util_module_isObject(markConfig.point) ? markConfig.point : {};
        }
        // markDef.point is defined as falsy
        return undefined;
    }
}
function standalone_getLineOverlay(markDef, markConfig = {}) {
    if (markDef.line) {
        // true or object
        return markDef.line === true ? {} : markDef.line;
    }
    else if (markDef.line !== undefined) {
        // false or null
        return null;
    }
    else {
        // undefined (not disabled)
        if (markConfig.line) {
            // enable line overlay if config[mark].line is truthy
            return markConfig.line === true ? {} : markConfig.line;
        }
        // markDef.point is defined as falsy
        return undefined;
    }
}
class standalone_PathOverlayNormalizer {
    constructor() {
        this.name = 'path-overlay';
    }
    hasMatchingType(spec, config) {
        if (standalone_isUnitSpec(spec)) {
            const { mark, encoding } = spec;
            const markDef = standalone_isMarkDef(mark) ? mark : { type: mark };
            switch (markDef.type) {
                case 'line':
                case 'rule':
                case 'trail':
                    return !!standalone_getPointOverlay(markDef, config[markDef.type], encoding);
                case 'area':
                    return (
                    // false / null are also included as we want to remove the properties
                    !!standalone_getPointOverlay(markDef, config[markDef.type], encoding) ||
                        !!standalone_getLineOverlay(markDef, config[markDef.type]));
            }
        }
        return false;
    }
    run(spec, normParams, normalize) {
        const { config } = normParams;
        const { params, projection, mark, name, encoding: e, ...outerSpec } = spec;
        // Need to call normalizeEncoding because we need the inferred types to correctly determine stack
        const encoding = standalone_normalizeEncoding(e, config);
        const markDef = standalone_isMarkDef(mark) ? mark : { type: mark };
        const pointOverlay = standalone_getPointOverlay(markDef, config[markDef.type], encoding);
        const lineOverlay = markDef.type === 'area' && standalone_getLineOverlay(markDef, config[markDef.type]);
        const layer = [
            {
                name,
                ...(params ? { params } : {}),
                mark: standalone_dropLineAndPoint({
                    // TODO: extract this 0.7 to be shared with default opacity for point/tick/...
                    ...(markDef.type === 'area' && markDef.opacity === undefined && markDef.fillOpacity === undefined
                        ? { opacity: 0.7 }
                        : {}),
                    ...markDef
                }),
                // drop shape from encoding as this might be used to trigger point overlay
                encoding: standalone_omit(encoding, ['shape'])
            }
        ];
        // FIXME: determine rules for applying selections.
        // Need to copy stack config to overlayed layer
        // FIXME: normalizer shouldn't call `initMarkdef`, a method from an init phase.
        const stackProps = standalone_stack(standalone_initMarkdef(markDef, encoding, config), encoding);
        let overlayEncoding = encoding;
        if (stackProps) {
            const { fieldChannel: stackFieldChannel, offset } = stackProps;
            overlayEncoding = {
                ...encoding,
                [stackFieldChannel]: {
                    ...encoding[stackFieldChannel],
                    ...(offset ? { stack: offset } : {})
                }
            };
        }
        // overlay line layer should be on the edge of area but passing y2/x2 makes
        // it as "rule" mark so that it draws unwanted vertical/horizontal lines.
        // point overlay also should not have y2/x2 as it does not support.
        overlayEncoding = standalone_omit(overlayEncoding, ['y2', 'x2']);
        if (lineOverlay) {
            layer.push({
                ...(projection ? { projection } : {}),
                mark: {
                    type: 'line',
                    ...standalone_util_pick(markDef, ['clip', 'interpolate', 'tension', 'tooltip']),
                    ...lineOverlay
                },
                encoding: overlayEncoding
            });
        }
        if (pointOverlay) {
            layer.push({
                ...(projection ? { projection } : {}),
                mark: {
                    type: 'point',
                    opacity: 1,
                    filled: true,
                    ...standalone_util_pick(markDef, ['clip', 'tooltip']),
                    ...pointOverlay
                },
                encoding: overlayEncoding
            });
        }
        return normalize({
            ...outerSpec,
            layer
        }, {
            ...normParams,
            config: standalone_dropLineAndPointFromConfig(config)
        });
    }
}
//# sourceMappingURL=pathoverlay.js.map
;// ../../node_modules/vega-lite/build/src/normalize/repeater.js






function standalone_replaceRepeaterInFacet(facet, repeater) {
    if (!repeater) {
        return facet;
    }
    if (standalone_isFacetMapping(facet)) {
        return standalone_replaceRepeaterInMapping(facet, repeater);
    }
    return standalone_replaceRepeaterInFieldDef(facet, repeater);
}
function standalone_replaceRepeaterInEncoding(encoding, repeater) {
    if (!repeater) {
        return encoding;
    }
    return standalone_replaceRepeaterInMapping(encoding, repeater);
}
/**
 * Replaces repeated value and returns if the repeated value is valid.
 */
function standalone_replaceRepeatInProp(prop, o, repeater) {
    const val = o[prop];
    if (standalone_isRepeatRef(val)) {
        if (val.repeat in repeater) {
            return { ...o, [prop]: repeater[val.repeat] };
        }
        else {
            standalone_log_warn(standalone_noSuchRepeatedValue(val.repeat));
            return undefined;
        }
    }
    return o;
}
/**
 * Replace repeater values in a field def with the concrete field name.
 */
function standalone_replaceRepeaterInFieldDef(fieldDef, repeater) {
    fieldDef = standalone_replaceRepeatInProp('field', fieldDef, repeater);
    if (fieldDef === undefined) {
        // the field def should be ignored
        return undefined;
    }
    else if (fieldDef === null) {
        return null;
    }
    if (standalone_isSortableFieldDef(fieldDef) && standalone_isSortField(fieldDef.sort)) {
        const sort = standalone_replaceRepeatInProp('field', fieldDef.sort, repeater);
        fieldDef = {
            ...fieldDef,
            ...(sort ? { sort } : {})
        };
    }
    return fieldDef;
}
function standalone_replaceRepeaterInFieldOrDatumDef(def, repeater) {
    if (standalone_isFieldDef(def)) {
        return standalone_replaceRepeaterInFieldDef(def, repeater);
    }
    else {
        const datumDef = standalone_replaceRepeatInProp('datum', def, repeater);
        if (datumDef !== def && !datumDef.type) {
            datumDef.type = 'nominal';
        }
        return datumDef;
    }
}
function standalone_replaceRepeaterInChannelDef(channelDef, repeater) {
    if (standalone_isFieldOrDatumDef(channelDef)) {
        const fd = standalone_replaceRepeaterInFieldOrDatumDef(channelDef, repeater);
        if (fd) {
            return fd;
        }
        else if (standalone_isConditionalDef(channelDef)) {
            return { condition: channelDef.condition };
        }
    }
    else {
        if (standalone_hasConditionalFieldOrDatumDef(channelDef)) {
            const fd = standalone_replaceRepeaterInFieldOrDatumDef(channelDef.condition, repeater);
            if (fd) {
                return {
                    ...channelDef,
                    condition: fd
                };
            }
            else {
                const { condition, ...channelDefWithoutCondition } = channelDef;
                return channelDefWithoutCondition;
            }
        }
        return channelDef;
    }
    return undefined;
}
function standalone_replaceRepeaterInMapping(mapping, repeater) {
    const out = {};
    for (const channel in mapping) {
        if (standalone_util_hasProperty(mapping, channel)) {
            const channelDef = mapping[channel];
            if (standalone_vega_util_module_isArray(channelDef)) {
                // array cannot have condition
                out[channel] = channelDef // somehow we need to cast it here
                    .map(cd => standalone_replaceRepeaterInChannelDef(cd, repeater))
                    .filter(cd => cd);
            }
            else {
                const cd = standalone_replaceRepeaterInChannelDef(channelDef, repeater);
                if (cd !== undefined) {
                    out[channel] = cd;
                }
            }
        }
    }
    return out;
}
//# sourceMappingURL=repeater.js.map
;// ../../node_modules/vega-lite/build/src/normalize/ruleforrangedline.js







class standalone_RuleForRangedLineNormalizer {
    constructor() {
        this.name = 'RuleForRangedLine';
    }
    hasMatchingType(spec) {
        if (standalone_isUnitSpec(spec)) {
            const { encoding, mark } = spec;
            if (mark === 'line' || (standalone_isMarkDef(mark) && mark.type === 'line')) {
                for (const channel of standalone_SECONDARY_RANGE_CHANNEL) {
                    const mainChannel = standalone_getMainRangeChannel(channel);
                    const mainChannelDef = encoding[mainChannel];
                    if (encoding[channel]) {
                        if ((standalone_isFieldDef(mainChannelDef) && !standalone_isBinned(mainChannelDef.bin)) || standalone_isDatumDef(mainChannelDef)) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
    run(spec, params, normalize) {
        const { encoding, mark } = spec;
        standalone_log_warn(standalone_lineWithRange(!!encoding.x2, !!encoding.y2));
        return normalize({
            ...spec,
            mark: standalone_vega_util_module_isObject(mark) ? { ...mark, type: 'rule' } : 'rule'
        }, params);
    }
}
//# sourceMappingURL=ruleforrangedline.js.map
;// ../../node_modules/vega-lite/build/src/normalize/core.js

















class standalone_CoreNormalizer extends standalone_SpecMapper {
    constructor() {
        super(...arguments);
        this.nonFacetUnitNormalizers = [
            standalone_boxPlotNormalizer,
            standalone_errorBarNormalizer,
            standalone_errorBandNormalizer,
            new standalone_PathOverlayNormalizer(),
            new standalone_RuleForRangedLineNormalizer()
        ];
    }
    map(spec, params) {
        // Special handling for a faceted unit spec as it can return a facet spec, not just a layer or unit spec like a normal unit spec.
        if (standalone_isUnitSpec(spec)) {
            const hasRow = standalone_channelHasField(spec.encoding, standalone_ROW);
            const hasColumn = standalone_channelHasField(spec.encoding, standalone_COLUMN);
            const hasFacet = standalone_channelHasField(spec.encoding, standalone_FACET);
            if (hasRow || hasColumn || hasFacet) {
                return this.mapFacetedUnit(spec, params);
            }
        }
        return super.map(spec, params);
    }
    // This is for normalizing non-facet unit
    mapUnit(spec, params) {
        const { parentEncoding, parentProjection } = params;
        const encoding = standalone_replaceRepeaterInEncoding(spec.encoding, params.repeater);
        const specWithReplacedEncoding = {
            ...spec,
            ...(spec.name ? { name: [params.repeaterPrefix, spec.name].filter(n => n).join('_') } : {}),
            ...(encoding ? { encoding } : {})
        };
        if (parentEncoding || parentProjection) {
            return this.mapUnitWithParentEncodingOrProjection(specWithReplacedEncoding, params);
        }
        const normalizeLayerOrUnit = this.mapLayerOrUnit.bind(this);
        for (const unitNormalizer of this.nonFacetUnitNormalizers) {
            if (unitNormalizer.hasMatchingType(specWithReplacedEncoding, params.config)) {
                return unitNormalizer.run(specWithReplacedEncoding, params, normalizeLayerOrUnit);
            }
        }
        return specWithReplacedEncoding;
    }
    mapRepeat(spec, params) {
        if (standalone_isLayerRepeatSpec(spec)) {
            return this.mapLayerRepeat(spec, params);
        }
        else {
            return this.mapNonLayerRepeat(spec, params);
        }
    }
    mapLayerRepeat(spec, params) {
        const { repeat, spec: childSpec, ...rest } = spec;
        const { row, column, layer } = repeat;
        const { repeater = {}, repeaterPrefix = '' } = params;
        if (row || column) {
            return this.mapRepeat({
                ...spec,
                repeat: {
                    ...(row ? { row } : {}),
                    ...(column ? { column } : {})
                },
                spec: {
                    repeat: { layer },
                    spec: childSpec
                }
            }, params);
        }
        else {
            return {
                ...rest,
                layer: layer.map(layerValue => {
                    const childRepeater = {
                        ...repeater,
                        layer: layerValue
                    };
                    const childName = `${(childSpec.name ? `${childSpec.name}_` : '') + repeaterPrefix}child__layer_${standalone_varName(layerValue)}`;
                    const child = this.mapLayerOrUnit(childSpec, { ...params, repeater: childRepeater, repeaterPrefix: childName });
                    child.name = childName;
                    return child;
                })
            };
        }
    }
    mapNonLayerRepeat(spec, params) {
        const { repeat, spec: childSpec, data, ...remainingProperties } = spec;
        if (!standalone_vega_util_module_isArray(repeat) && spec.columns) {
            // is repeat with row/column
            spec = standalone_omit(spec, ['columns']);
            standalone_log_warn(standalone_columnsNotSupportByRowCol('repeat'));
        }
        const concat = [];
        const { repeater = {}, repeaterPrefix = '' } = params;
        const row = (!standalone_vega_util_module_isArray(repeat) && repeat.row) || [repeater ? repeater.row : null];
        const column = (!standalone_vega_util_module_isArray(repeat) && repeat.column) || [repeater ? repeater.column : null];
        const repeatValues = (standalone_vega_util_module_isArray(repeat) && repeat) || [repeater ? repeater.repeat : null];
        // cross product
        for (const repeatValue of repeatValues) {
            for (const rowValue of row) {
                for (const columnValue of column) {
                    const childRepeater = {
                        repeat: repeatValue,
                        row: rowValue,
                        column: columnValue,
                        layer: repeater.layer
                    };
                    const childName = (childSpec.name ? `${childSpec.name}_` : '') +
                        repeaterPrefix +
                        'child__' +
                        (standalone_vega_util_module_isArray(repeat)
                            ? `${standalone_varName(repeatValue)}`
                            : (repeat.row ? `row_${standalone_varName(rowValue)}` : '') +
                                (repeat.column ? `column_${standalone_varName(columnValue)}` : ''));
                    const child = this.map(childSpec, { ...params, repeater: childRepeater, repeaterPrefix: childName });
                    child.name = childName;
                    // we move data up
                    concat.push(standalone_omit(child, ['data']));
                }
            }
        }
        const columns = standalone_vega_util_module_isArray(repeat) ? spec.columns : repeat.column ? repeat.column.length : 1;
        return {
            data: childSpec.data ?? data, // data from child spec should have precedence
            align: 'all',
            ...remainingProperties,
            columns,
            concat
        };
    }
    mapFacet(spec, params) {
        const { facet } = spec;
        if (standalone_isFacetMapping(facet) && spec.columns) {
            // is facet with row/column
            spec = standalone_omit(spec, ['columns']);
            standalone_log_warn(standalone_columnsNotSupportByRowCol('facet'));
        }
        return super.mapFacet(spec, params);
    }
    mapUnitWithParentEncodingOrProjection(spec, params) {
        const { encoding, projection } = spec;
        const { parentEncoding, parentProjection, config } = params;
        const mergedProjection = standalone_mergeProjection({ parentProjection, projection });
        const mergedEncoding = standalone_mergeEncoding({
            parentEncoding,
            encoding: standalone_replaceRepeaterInEncoding(encoding, params.repeater)
        });
        return this.mapUnit({
            ...spec,
            ...(mergedProjection ? { projection: mergedProjection } : {}),
            ...(mergedEncoding ? { encoding: mergedEncoding } : {})
        }, { config });
    }
    mapFacetedUnit(spec, normParams) {
        // New encoding in the inside spec should not contain row / column
        // as row/column should be moved to facet
        const { row, column, facet, ...encoding } = spec.encoding;
        // Mark and encoding should be moved into the inner spec
        const { mark, width, projection, height, view, params, encoding: _, ...outerSpec } = spec;
        const { facetMapping, layout } = this.getFacetMappingAndLayout({ row, column, facet }, normParams);
        const newEncoding = standalone_replaceRepeaterInEncoding(encoding, normParams.repeater);
        return this.mapFacet({
            ...outerSpec,
            ...layout,
            // row / column has higher precedence than facet
            facet: facetMapping,
            spec: {
                ...(width ? { width } : {}),
                ...(height ? { height } : {}),
                ...(view ? { view } : {}),
                ...(projection ? { projection } : {}),
                mark,
                encoding: newEncoding,
                ...(params ? { params } : {})
            }
        }, normParams);
    }
    getFacetMappingAndLayout(facets, params) {
        const { row, column, facet } = facets;
        if (row || column) {
            if (facet) {
                standalone_log_warn(standalone_facetChannelDropped([...(row ? [standalone_ROW] : []), ...(column ? [standalone_COLUMN] : [])]));
            }
            const facetMapping = {};
            const layout = {};
            for (const channel of [standalone_ROW, standalone_COLUMN]) {
                const def = facets[channel];
                if (def) {
                    const { align, center, spacing, columns, ...defWithoutLayout } = def;
                    facetMapping[channel] = defWithoutLayout;
                    for (const prop of ['align', 'center', 'spacing']) {
                        if (def[prop] !== undefined) {
                            layout[prop] ?? (layout[prop] = {});
                            layout[prop][channel] = def[prop];
                        }
                    }
                }
            }
            return { facetMapping, layout };
        }
        else {
            const { align, center, spacing, columns, ...facetMapping } = facet;
            return {
                facetMapping: standalone_replaceRepeaterInFacet(facetMapping, params.repeater),
                layout: {
                    ...(align ? { align } : {}),
                    ...(center ? { center } : {}),
                    ...(spacing ? { spacing } : {}),
                    ...(columns ? { columns } : {})
                }
            };
        }
    }
    mapLayer(spec, { parentEncoding, parentProjection, ...otherParams }) {
        // Special handling for extended layer spec
        const { encoding, projection, ...rest } = spec;
        const params = {
            ...otherParams,
            parentEncoding: standalone_mergeEncoding({ parentEncoding, encoding, layer: true }),
            parentProjection: standalone_mergeProjection({ parentProjection, projection })
        };
        return super.mapLayer({
            ...rest,
            ...(spec.name ? { name: [params.repeaterPrefix, spec.name].filter(n => n).join('_') } : {})
        }, params);
    }
}
function standalone_mergeEncoding({ parentEncoding, encoding = {}, layer }) {
    let merged = {};
    if (parentEncoding) {
        const channels = new Set([...standalone_util_keys(parentEncoding), ...standalone_util_keys(encoding)]);
        for (const channel of channels) {
            const channelDef = encoding[channel];
            const parentChannelDef = parentEncoding[channel];
            if (standalone_isFieldOrDatumDef(channelDef)) {
                // Field/Datum Def can inherit properties from its parent
                // Note that parentChannelDef doesn't have to be a field/datum def if the channelDef is already one.
                const mergedChannelDef = {
                    ...parentChannelDef,
                    ...channelDef
                };
                merged[channel] = mergedChannelDef;
            }
            else if (standalone_hasConditionalFieldOrDatumDef(channelDef)) {
                merged[channel] = {
                    ...channelDef,
                    condition: {
                        ...parentChannelDef,
                        ...channelDef.condition
                    }
                };
            }
            else if (channelDef || channelDef === null) {
                merged[channel] = channelDef;
            }
            else if (layer ||
                standalone_isValueDef(parentChannelDef) ||
                standalone_isSignalRef(parentChannelDef) ||
                standalone_isFieldOrDatumDef(parentChannelDef) ||
                standalone_vega_util_module_isArray(parentChannelDef)) {
                merged[channel] = parentChannelDef;
            }
        }
    }
    else {
        merged = encoding;
    }
    return !merged || standalone_isEmpty(merged) ? undefined : merged;
}
function standalone_mergeProjection(opt) {
    const { parentProjection, projection } = opt;
    if (parentProjection && projection) {
        standalone_log_warn(standalone_projectionOverridden({ parentProjection, projection }));
    }
    return projection ?? parentProjection;
}
//# sourceMappingURL=core.js.map
;// ../../node_modules/vega-lite/build/src/transform.js



function standalone_isFilter(t) {
    return standalone_util_hasProperty(t, 'filter');
}
function standalone_isImputeSequence(t) {
    return standalone_util_hasProperty(t, 'stop');
}
function standalone_isLookup(t) {
    return standalone_util_hasProperty(t, 'lookup');
}
function standalone_isLookupData(from) {
    return standalone_util_hasProperty(from, 'data');
}
function standalone_isLookupSelection(from) {
    return standalone_util_hasProperty(from, 'param');
}
function standalone_isPivot(t) {
    return standalone_util_hasProperty(t, 'pivot');
}
function standalone_isDensity(t) {
    return standalone_util_hasProperty(t, 'density');
}
function standalone_transform_isQuantile(t) {
    return standalone_util_hasProperty(t, 'quantile');
}
function standalone_isRegression(t) {
    return standalone_util_hasProperty(t, 'regression');
}
function standalone_isLoess(t) {
    return standalone_util_hasProperty(t, 'loess');
}
function standalone_isSample(t) {
    return standalone_util_hasProperty(t, 'sample');
}
function standalone_isWindow(t) {
    return standalone_util_hasProperty(t, 'window');
}
function standalone_isJoinAggregate(t) {
    return standalone_util_hasProperty(t, 'joinaggregate');
}
function standalone_isFlatten(t) {
    return standalone_util_hasProperty(t, 'flatten');
}
function standalone_isCalculate(t) {
    return standalone_util_hasProperty(t, 'calculate');
}
function standalone_isBin(t) {
    return standalone_util_hasProperty(t, 'bin');
}
function standalone_isImpute(t) {
    return standalone_util_hasProperty(t, 'impute');
}
function standalone_isTimeUnit(t) {
    return standalone_util_hasProperty(t, 'timeUnit');
}
function standalone_transform_isAggregate(t) {
    return standalone_util_hasProperty(t, 'aggregate');
}
function standalone_isStack(t) {
    return standalone_util_hasProperty(t, 'stack');
}
function standalone_isFold(t) {
    return standalone_util_hasProperty(t, 'fold');
}
function standalone_isExtent(t) {
    return standalone_util_hasProperty(t, 'extent') && !standalone_util_hasProperty(t, 'density') && !standalone_util_hasProperty(t, 'regression');
}
function standalone_normalizeTransform(transform) {
    return transform.map(t => {
        if (standalone_isFilter(t)) {
            return {
                filter: standalone_normalizeLogicalComposition(t.filter, standalone_normalizePredicate)
            };
        }
        return t;
    });
}
//# sourceMappingURL=transform.js.map
;// ../../node_modules/vega-lite/build/src/normalize/selectioncompat.js







class standalone_SelectionCompatibilityNormalizer extends standalone_SpecMapper {
    map(spec, normParams) {
        normParams.emptySelections ?? (normParams.emptySelections = {});
        normParams.selectionPredicates ?? (normParams.selectionPredicates = {});
        spec = standalone_normalizeTransforms(spec, normParams);
        return super.map(spec, normParams);
    }
    mapLayerOrUnit(spec, normParams) {
        spec = standalone_normalizeTransforms(spec, normParams);
        if (spec.encoding) {
            const encoding = {};
            for (const [channel, enc] of standalone_entries(spec.encoding)) {
                encoding[channel] = standalone_normalizeChannelDef(enc, normParams);
            }
            spec = { ...spec, encoding };
        }
        return super.mapLayerOrUnit(spec, normParams);
    }
    mapUnit(spec, normParams) {
        const { selection, ...rest } = spec;
        if (selection) {
            return {
                ...rest,
                params: standalone_entries(selection).map(([name, selDef]) => {
                    const { init: value, bind, empty, ...select } = selDef;
                    if (select.type === 'single') {
                        select.type = 'point';
                        select.toggle = false;
                    }
                    else if (select.type === 'multi') {
                        select.type = 'point';
                    }
                    // Propagate emptiness forwards and backwards
                    normParams.emptySelections[name] = empty !== 'none';
                    for (const pred of standalone_vals(normParams.selectionPredicates[name] ?? {})) {
                        pred.empty = empty !== 'none';
                    }
                    return { name, value, select, bind };
                })
            };
        }
        return spec;
    }
}
function standalone_normalizeTransforms(spec, normParams) {
    const { transform: tx, ...rest } = spec;
    if (tx) {
        const transform = tx.map((t) => {
            if (standalone_isFilter(t)) {
                return { filter: standalone_selectioncompat_normalizePredicate(t, normParams) };
            }
            else if (standalone_isBin(t) && standalone_isBinParams(t.bin)) {
                return {
                    ...t,
                    bin: standalone_normalizeBinExtent(t.bin)
                };
            }
            else if (standalone_isLookup(t)) {
                const { selection: param, ...from } = t.from;
                return param
                    ? {
                        ...t,
                        from: { param, ...from }
                    }
                    : t;
            }
            return t;
        });
        return { ...rest, transform };
    }
    return spec;
}
function standalone_normalizeChannelDef(obj, normParams) {
    const enc = standalone_duplicate(obj);
    if (standalone_isFieldDef(enc) && standalone_isBinParams(enc.bin)) {
        enc.bin = standalone_normalizeBinExtent(enc.bin);
    }
    if (standalone_isScaleFieldDef(enc) && enc.scale?.domain?.selection) {
        const { selection: param, ...domain } = enc.scale.domain;
        enc.scale.domain = { ...domain, ...(param ? { param } : {}) };
    }
    if (standalone_isConditionalDef(enc)) {
        if (standalone_vega_util_module_isArray(enc.condition)) {
            enc.condition = enc.condition.map((c) => {
                const { selection, param, test, ...cond } = c;
                return param ? c : { ...cond, test: standalone_selectioncompat_normalizePredicate(c, normParams) };
            });
        }
        else {
            const { selection, param, test, ...cond } = standalone_normalizeChannelDef(enc.condition, normParams);
            enc.condition = param
                ? enc.condition
                : {
                    ...cond,
                    test: standalone_selectioncompat_normalizePredicate(enc.condition, normParams)
                };
        }
    }
    return enc;
}
function standalone_normalizeBinExtent(bin) {
    const ext = bin.extent;
    if (ext?.selection) {
        const { selection: param, ...rest } = ext;
        return { ...bin, extent: { ...rest, param } };
    }
    return bin;
}
function standalone_selectioncompat_normalizePredicate(op, normParams) {
    // Normalize old compositions of selection names (e.g., selection: {and: ["one", "two"]})
    const normalizeSelectionComposition = (o) => {
        return standalone_normalizeLogicalComposition(o, param => {
            var _a;
            const empty = normParams.emptySelections[param] ?? true;
            const pred = { param, empty };
            (_a = normParams.selectionPredicates)[param] ?? (_a[param] = []);
            normParams.selectionPredicates[param].push(pred);
            return pred;
        });
    };
    return op.selection
        ? normalizeSelectionComposition(op.selection)
        : standalone_normalizeLogicalComposition(op.test || op.filter, o => o.selection ? normalizeSelectionComposition(o.selection) : o);
}
//# sourceMappingURL=selectioncompat.js.map
;// ../../node_modules/vega-lite/build/src/normalize/toplevelselection.js




class standalone_TopLevelSelectionsNormalizer extends standalone_SpecMapper {
    map(spec, normParams) {
        const selections = normParams.selections ?? [];
        if (spec.params && !standalone_isUnitSpec(spec)) {
            const params = [];
            for (const param of spec.params) {
                if (standalone_isSelectionParameter(param)) {
                    selections.push(param);
                }
                else {
                    params.push(param);
                }
            }
            spec.params = params;
        }
        normParams.selections = selections;
        return super.map(spec, normParams);
    }
    mapUnit(spec, normParams) {
        const selections = normParams.selections;
        if (!selections || !selections.length)
            return spec;
        const path = (normParams.path ?? []).concat(spec.name);
        const params = [];
        for (const selection of selections) {
            // By default, apply selections to all unit views.
            if (!selection.views || !selection.views.length) {
                params.push(selection);
            }
            else {
                for (const view of selection.views) {
                    // view is either a specific unit name, or a partial path through the spec tree.
                    if ((standalone_vega_util_module_isString(view) && (view === spec.name || path.includes(view))) ||
                        (standalone_vega_util_module_isArray(view) &&
                            // logic for backwards compatibility with view paths before we had unique names
                            // @ts-ignore
                            view.map(v => path.indexOf(v)).every((v, i, arr) => v !== -1 && (i === 0 || v > arr[i - 1])))) {
                        params.push(selection);
                    }
                }
            }
        }
        if (params.length)
            spec.params = params;
        return spec;
    }
}
for (const method of ['mapFacet', 'mapRepeat', 'mapHConcat', 'mapVConcat', 'mapLayer']) {
    const proto = standalone_TopLevelSelectionsNormalizer.prototype[method];
    standalone_TopLevelSelectionsNormalizer.prototype[method] = function (spec, params) {
        return proto.call(this, spec, standalone_addSpecNameToParams(spec, params));
    };
}
function standalone_addSpecNameToParams(spec, params) {
    return spec.name
        ? {
            ...params,
            path: (params.path ?? []).concat(spec.name)
        }
        : params;
}
//# sourceMappingURL=toplevelselection.js.map
;// ../../node_modules/vega-lite/build/src/normalize/index.js








function standalone_normalize_normalize(spec, config) {
    if (config === undefined) {
        config = standalone_initConfig(spec.config);
    }
    const normalizedSpec = standalone_normalizeGenericSpec(spec, config);
    const { width, height } = spec;
    const autosize = src_standalone_normalizeAutoSize(normalizedSpec, { width, height, autosize: spec.autosize }, config);
    return {
        ...normalizedSpec,
        ...(autosize ? { autosize } : {})
    };
}
const standalone_coreNormalizer = new standalone_CoreNormalizer();
const standalone_selectionCompatNormalizer = new standalone_SelectionCompatibilityNormalizer();
const standalone_topLevelSelectionNormalizer = new standalone_TopLevelSelectionsNormalizer();
/**
 * Decompose extended unit specs into composition of pure unit specs.
 * And push top-level selection definitions down to unit specs.
 */
function standalone_normalizeGenericSpec(spec, config = {}) {
    const normParams = { config };
    return standalone_topLevelSelectionNormalizer.map(standalone_coreNormalizer.map(standalone_selectionCompatNormalizer.map(spec, normParams), normParams), normParams);
}
function standalone_normalizeAutoSize(autosize) {
    return standalone_vega_util_module_isString(autosize) ? { type: autosize } : (autosize ?? {});
}
/**
 * Normalize autosize and deal with width or height == "container".
 */
function src_standalone_normalizeAutoSize(spec, sizeInfo, config) {
    let { width, height } = sizeInfo;
    const isFitCompatible = standalone_isUnitSpec(spec) || standalone_isLayerSpec(spec);
    const autosizeDefault = {};
    if (!isFitCompatible) {
        // If spec is not compatible with autosize == "fit", discard width/height == container
        if (width == 'container') {
            standalone_log_warn(standalone_containerSizeNonSingle('width'));
            width = undefined;
        }
        if (height == 'container') {
            standalone_log_warn(standalone_containerSizeNonSingle('height'));
            height = undefined;
        }
    }
    else {
        // Default autosize parameters to fit when width/height is "container"
        if (width == 'container' && height == 'container') {
            autosizeDefault.type = 'fit';
            autosizeDefault.contains = 'padding';
        }
        else if (width == 'container') {
            autosizeDefault.type = 'fit-x';
            autosizeDefault.contains = 'padding';
        }
        else if (height == 'container') {
            autosizeDefault.type = 'fit-y';
            autosizeDefault.contains = 'padding';
        }
    }
    const autosize = {
        type: 'pad',
        ...autosizeDefault,
        ...(config ? standalone_normalizeAutoSize(config.autosize) : {}),
        ...standalone_normalizeAutoSize(spec.autosize)
    };
    if (autosize.type === 'fit' && !isFitCompatible) {
        standalone_log_warn(standalone_FIT_NON_SINGLE);
        autosize.type = 'pad';
    }
    if (width == 'container' && !(autosize.type == 'fit' || autosize.type == 'fit-x')) {
        standalone_log_warn(standalone_containerSizeNotCompatibleWithAutosize('width'));
    }
    if (height == 'container' && !(autosize.type == 'fit' || autosize.type == 'fit-y')) {
        standalone_log_warn(standalone_containerSizeNotCompatibleWithAutosize('height'));
    }
    // Delete autosize property if it's Vega's default
    if (standalone_deepEqual(autosize, { type: 'pad' })) {
        return undefined;
    }
    return autosize;
}
//# sourceMappingURL=index.js.map
;// ../../node_modules/vega-lite/build/src/spec/toplevel.js


function standalone_isFitType(autoSizeType) {
    return ['fit', 'fit-x', 'fit-y'].includes(autoSizeType);
}
function standalone_getFitType(sizeType) {
    return sizeType ? `fit-${standalone_getPositionScaleChannel(sizeType)}` : 'fit';
}
const standalone_TOP_LEVEL_PROPERTIES = [
    'background',
    'padding'
    // We do not include "autosize" here as it is supported by only unit and layer specs and thus need to be normalized
];
function standalone_extractTopLevelProperties(t, includeParams) {
    const o = {};
    for (const p of standalone_TOP_LEVEL_PROPERTIES) {
        if (t && t[p] !== undefined) {
            o[p] = standalone_signalRefOrValue(t[p]);
        }
    }
    if (includeParams) {
        o.params = t.params;
    }
    return o;
}
//# sourceMappingURL=toplevel.js.map
;// ../../node_modules/vega-lite/build/src/compile/split.js


/**
 * Generic class for storing properties that are explicitly specified
 * and implicitly determined by the compiler.
 * This is important for scale/axis/legend merging as
 * we want to prioritize properties that users explicitly specified.
 */
// eslint-disable-next-line @typescript-eslint/ban-types
class standalone_Split {
    constructor(explicit = {}, implicit = {}) {
        this.explicit = explicit;
        this.implicit = implicit;
    }
    clone() {
        return new standalone_Split(standalone_duplicate(this.explicit), standalone_duplicate(this.implicit));
    }
    combine() {
        return {
            ...this.explicit, // Explicit properties comes first
            ...this.implicit
        };
    }
    get(key) {
        // Explicit has higher precedence
        return standalone_getFirstDefined(this.explicit[key], this.implicit[key]);
    }
    getWithExplicit(key) {
        // Explicit has higher precedence
        if (this.explicit[key] !== undefined) {
            return { explicit: true, value: this.explicit[key] };
        }
        else if (this.implicit[key] !== undefined) {
            return { explicit: false, value: this.implicit[key] };
        }
        return { explicit: false, value: undefined };
    }
    setWithExplicit(key, { value, explicit }) {
        if (value !== undefined) {
            this.set(key, value, explicit);
        }
    }
    set(key, value, explicit) {
        delete this[explicit ? 'implicit' : 'explicit'][key];
        this[explicit ? 'explicit' : 'implicit'][key] = value;
        return this;
    }
    copyKeyFromSplit(key, { explicit, implicit }) {
        // Explicit has higher precedence
        if (explicit[key] !== undefined) {
            this.set(key, explicit[key], true);
        }
        else if (implicit[key] !== undefined) {
            this.set(key, implicit[key], false);
        }
    }
    copyKeyFromObject(key, s) {
        // Explicit has higher precedence
        if (s[key] !== undefined) {
            this.set(key, s[key], true);
        }
    }
    /**
     * Merge split object into this split object. Properties from the other split
     * overwrite properties from this split.
     */
    copyAll(other) {
        for (const key of standalone_util_keys(other.combine())) {
            const val = other.getWithExplicit(key);
            this.setWithExplicit(key, val);
        }
    }
}
function standalone_makeExplicit(value) {
    return {
        explicit: true,
        value
    };
}
function standalone_makeImplicit(value) {
    return {
        explicit: false,
        value
    };
}
function standalone_tieBreakByComparing(compare) {
    return (v1, v2, property, propertyOf) => {
        const diff = compare(v1.value, v2.value);
        if (diff > 0) {
            return v1;
        }
        else if (diff < 0) {
            return v2;
        }
        return standalone_defaultTieBreaker(v1, v2, property, propertyOf);
    };
}
function standalone_defaultTieBreaker(v1, v2, property, propertyOf) {
    if (v1.explicit && v2.explicit) {
        standalone_log_warn(standalone_mergeConflictingProperty(property, propertyOf, v1.value, v2.value));
    }
    // If equal score, prefer v1.
    return v1;
}
function standalone_mergeValuesWithExplicit(v1, v2, property, propertyOf, tieBreaker = standalone_defaultTieBreaker) {
    if (v1 === undefined || v1.value === undefined) {
        // For first run
        return v2;
    }
    if (v1.explicit && !v2.explicit) {
        return v1;
    }
    else if (v2.explicit && !v1.explicit) {
        return v2;
    }
    else if (standalone_deepEqual(v1.value, v2.value)) {
        return v1;
    }
    else {
        return tieBreaker(v1, v2, property, propertyOf);
    }
}
//# sourceMappingURL=split.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/index.js

/**
 * Class to track interesting properties (see https://15721.courses.cs.cmu.edu/spring2016/papers/graefe-ieee1995.pdf)
 * about how fields have been parsed or whether they have been derived in a transform. We use this to not parse the
 * same field again (or differently).
 */
class standalone_AncestorParse extends standalone_Split {
    constructor(explicit = {}, implicit = {}, parseNothing = false) {
        super(explicit, implicit);
        this.explicit = explicit;
        this.implicit = implicit;
        this.parseNothing = parseNothing;
    }
    clone() {
        const clone = super.clone();
        clone.parseNothing = this.parseNothing;
        return clone;
    }
}
//# sourceMappingURL=index.js.map
;// ../../node_modules/vega-lite/build/src/data.js

function standalone_isUrlData(data) {
    return standalone_util_hasProperty(data, 'url');
}
function standalone_isInlineData(data) {
    return standalone_util_hasProperty(data, 'values');
}
function standalone_isNamedData(data) {
    return standalone_util_hasProperty(data, 'name') && !standalone_isUrlData(data) && !standalone_isInlineData(data) && !standalone_isGenerator(data);
}
function standalone_isGenerator(data) {
    return data && (standalone_isSequenceGenerator(data) || standalone_isSphereGenerator(data) || standalone_isGraticuleGenerator(data));
}
function standalone_isSequenceGenerator(data) {
    return standalone_util_hasProperty(data, 'sequence');
}
function standalone_isSphereGenerator(data) {
    return standalone_util_hasProperty(data, 'sphere');
}
function standalone_isGraticuleGenerator(data) {
    return standalone_util_hasProperty(data, 'graticule');
}
var standalone_DataSourceType;
(function (DataSourceType) {
    DataSourceType[DataSourceType["Raw"] = 0] = "Raw";
    /** Main data source for marks */
    DataSourceType[DataSourceType["Main"] = 1] = "Main";
    DataSourceType[DataSourceType["Row"] = 2] = "Row";
    DataSourceType[DataSourceType["Column"] = 3] = "Column";
    DataSourceType[DataSourceType["Lookup"] = 4] = "Lookup";
    /** Pre-filter-invalid data source for scale domains */
    DataSourceType[DataSourceType["PreFilterInvalid"] = 5] = "PreFilterInvalid";
    /** Post-filter-invalid data source for scale domains */
    DataSourceType[DataSourceType["PostFilterInvalid"] = 6] = "PostFilterInvalid";
})(standalone_DataSourceType || (standalone_DataSourceType = {}));
//# sourceMappingURL=data.js.map
;// ../../node_modules/vega-lite/build/src/compile/invalid/datasources.js


function standalone_getDataSourcesForHandlingInvalidValues({ invalid, isPath }) {
    const normalizedInvalid = standalone_normalizeInvalidDataMode(invalid, { isPath });
    switch (normalizedInvalid) {
        case 'filter':
            // Both marks and scales use post-filter data
            return {
                marks: 'exclude-invalid-values',
                scales: 'exclude-invalid-values'
            };
        case 'break-paths-show-domains':
            return {
                // Path-based marks use pre-filter data so we know to skip these invalid points in the path.
                // For non-path based marks, we skip by not showing them at all.
                marks: isPath ? 'include-invalid-values' : 'exclude-invalid-values',
                scales: 'include-invalid-values'
            };
        case 'break-paths-filter-domains':
            // For path marks, the marks will use unfiltered data (and skip points). But we need a separate data sources to feed the domain.
            // For non-path marks, we can use the filtered data for both marks and scales.
            return {
                marks: isPath ? 'include-invalid-values' : 'exclude-invalid-values',
                // Unlike 'break-paths-show-domains', 'break-paths-filter-domains' uses post-filter data to feed scale.
                scales: 'exclude-invalid-values'
            };
        case 'show':
            return {
                marks: 'include-invalid-values',
                scales: 'include-invalid-values'
            };
    }
}
function standalone_getScaleDataSourceForHandlingInvalidValues(props) {
    const { marks, scales } = standalone_getDataSourcesForHandlingInvalidValues(props);
    if (marks === scales) {
        // If both marks and scales use the same data, there is only the main data source.
        return standalone_DataSourceType.Main;
    }
    // If marks and scales use differetnt data, return the pre/post-filter data source accordingly.
    return scales === 'include-invalid-values' ? standalone_DataSourceType.PreFilterInvalid : standalone_DataSourceType.PostFilterInvalid;
}
//# sourceMappingURL=datasources.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/dataflow.js


/**
 * A node in the dataflow tree.
 */
class standalone_DataFlowNode {
    constructor(parent, debugName) {
        this.debugName = debugName;
        this._children = [];
        this._parent = null;
        if (parent) {
            this.parent = parent;
        }
    }
    /**
     * Clone this node with a deep copy but don't clone links to children or parents.
     */
    clone() {
        throw new Error('Cannot clone node');
    }
    get parent() {
        return this._parent;
    }
    /**
     * Set the parent of the node and also add this node to the parent's children.
     */
    set parent(parent) {
        this._parent = parent;
        if (parent) {
            parent.addChild(this);
        }
    }
    get children() {
        return this._children;
    }
    numChildren() {
        return this._children.length;
    }
    addChild(child, loc) {
        // do not add the same child twice
        if (this._children.includes(child)) {
            standalone_log_warn(standalone_ADD_SAME_CHILD_TWICE);
            return;
        }
        if (loc !== undefined) {
            this._children.splice(loc, 0, child);
        }
        else {
            this._children.push(child);
        }
    }
    removeChild(oldChild) {
        const loc = this._children.indexOf(oldChild);
        this._children.splice(loc, 1);
        return loc;
    }
    /**
     * Remove node from the dataflow.
     */
    remove() {
        let loc = this._parent.removeChild(this);
        for (const child of this._children) {
            // do not use the set method because we want to insert at a particular location
            child._parent = this._parent;
            this._parent.addChild(child, loc++);
        }
    }
    /**
     * Insert another node as a parent of this node.
     */
    insertAsParentOf(other) {
        const parent = other.parent;
        parent.removeChild(this);
        this.parent = parent;
        other.parent = this;
    }
    swapWithParent() {
        const parent = this._parent;
        const newParent = parent.parent;
        // reconnect the children
        for (const child of this._children) {
            child.parent = parent;
        }
        // remove old links
        this._children = []; // equivalent to removing every child link one by one
        parent.removeChild(this);
        const loc = parent.parent.removeChild(parent);
        // swap two nodes but maintain order in children
        this._parent = newParent;
        newParent.addChild(this, loc);
        parent.parent = this;
    }
}
class standalone_OutputNode extends standalone_DataFlowNode {
    clone() {
        const cloneObj = new this.constructor();
        cloneObj.debugName = `clone_${this.debugName}`;
        cloneObj._source = this._source;
        cloneObj._name = `clone_${this._name}`;
        cloneObj.type = this.type;
        cloneObj.refCounts = this.refCounts;
        cloneObj.refCounts[cloneObj._name] = 0;
        return cloneObj;
    }
    /**
     * @param source The name of the source. Will change in assemble.
     * @param type The type of the output node.
     * @param refCounts A global ref counter map.
     */
    constructor(parent, source, type, refCounts) {
        super(parent, source);
        this.type = type;
        this.refCounts = refCounts;
        this._source = this._name = source;
        if (this.refCounts && !(this._name in this.refCounts)) {
            this.refCounts[this._name] = 0;
        }
    }
    dependentFields() {
        return new Set();
    }
    producedFields() {
        return new Set();
    }
    hash() {
        if (this._hash === undefined) {
            this._hash = `Output ${standalone_uniqueId()}`;
        }
        return this._hash;
    }
    /**
     * Request the datasource name and increase the ref counter.
     *
     * During the parsing phase, this will return the simple name such as 'main' or 'raw'.
     * It is crucial to request the name from an output node to mark it as a required node.
     * If nobody ever requests the name, this datasource will not be instantiated in the assemble phase.
     *
     * In the assemble phase, this will return the correct name.
     */
    getSource() {
        this.refCounts[this._name]++;
        return this._source;
    }
    isRequired() {
        return !!this.refCounts[this._name];
    }
    setSource(source) {
        this._source = source;
    }
}
//# sourceMappingURL=dataflow.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/timeunit.js







function standalone_isTimeUnitTransformComponent(timeUnitComponent) {
    return timeUnitComponent.as !== undefined;
}
function standalone_offsetAs(field) {
    return `${field}_end`;
}
class standalone_TimeUnitNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_TimeUnitNode(null, standalone_duplicate(this.timeUnits));
    }
    constructor(parent, timeUnits) {
        super(parent);
        this.timeUnits = timeUnits;
    }
    static makeFromEncoding(parent, model) {
        const formula = model.reduceFieldDef((timeUnitComponent, fieldDef, channel) => {
            const { field, timeUnit } = fieldDef;
            if (timeUnit) {
                let component;
                if (standalone_isBinnedTimeUnit(timeUnit)) {
                    // For binned time unit, only produce end if the mark is a rect-based mark (rect, bar, image, arc), which needs "range".
                    if (standalone_isUnitModel(model)) {
                        const { mark, markDef, config } = model;
                        const bandPosition = standalone_getBandPosition({ fieldDef, markDef, config });
                        if (standalone_isRectBasedMark(mark) || !!bandPosition) {
                            component = {
                                timeUnit: standalone_normalizeTimeUnit(timeUnit),
                                field
                            };
                        }
                    }
                }
                else {
                    component = {
                        as: standalone_vgField(fieldDef, { forAs: true }),
                        field,
                        timeUnit
                    };
                }
                if (standalone_isUnitModel(model)) {
                    const { mark, markDef, config } = model;
                    const bandPosition = standalone_getBandPosition({ fieldDef, markDef, config });
                    if (standalone_isRectBasedMark(mark) && standalone_isXorY(channel) && bandPosition !== 0.5) {
                        component.rectBandPosition = bandPosition;
                    }
                }
                if (component) {
                    timeUnitComponent[standalone_util_hash(component)] = component;
                }
            }
            return timeUnitComponent;
        }, {});
        if (standalone_isEmpty(formula)) {
            return null;
        }
        return new standalone_TimeUnitNode(parent, formula);
    }
    static makeFromTransform(parent, t) {
        const { timeUnit, ...other } = { ...t };
        const normalizedTimeUnit = standalone_normalizeTimeUnit(timeUnit);
        const component = {
            ...other,
            timeUnit: normalizedTimeUnit
        };
        return new standalone_TimeUnitNode(parent, {
            [standalone_util_hash(component)]: component
        });
    }
    /**
     * Merge together TimeUnitNodes assigning the children of `other` to `this`
     * and removing `other`.
     */
    merge(other) {
        this.timeUnits = { ...this.timeUnits };
        // if the same hash happen twice, merge
        for (const key in other.timeUnits) {
            if (!this.timeUnits[key]) {
                // copy if it's not a duplicate
                this.timeUnits[key] = other.timeUnits[key];
            }
        }
        for (const child of other.children) {
            other.removeChild(child);
            child.parent = this;
        }
        other.remove();
    }
    /**
     * Remove time units coming from the other node.
     */
    removeFormulas(fields) {
        const newFormula = {};
        for (const [key, timeUnitComponent] of standalone_entries(this.timeUnits)) {
            const fieldAs = standalone_isTimeUnitTransformComponent(timeUnitComponent)
                ? timeUnitComponent.as
                : `${timeUnitComponent.field}_end`;
            if (!fields.has(fieldAs)) {
                newFormula[key] = timeUnitComponent;
            }
        }
        this.timeUnits = newFormula;
    }
    producedFields() {
        return new Set(standalone_vals(this.timeUnits).map(f => {
            return standalone_isTimeUnitTransformComponent(f) ? f.as : standalone_offsetAs(f.field);
        }));
    }
    dependentFields() {
        return new Set(standalone_vals(this.timeUnits).map(f => f.field));
    }
    hash() {
        return `TimeUnit ${standalone_util_hash(this.timeUnits)}`;
    }
    assemble() {
        const transforms = [];
        for (const f of standalone_vals(this.timeUnits)) {
            const { rectBandPosition } = f;
            const normalizedTimeUnit = standalone_normalizeTimeUnit(f.timeUnit);
            if (standalone_isTimeUnitTransformComponent(f)) {
                const { field, as } = f;
                const { unit, utc, ...params } = normalizedTimeUnit;
                const startEnd = [as, `${as}_end`];
                transforms.push({
                    field: standalone_replacePathInField(field),
                    type: 'timeunit',
                    ...(unit ? { units: standalone_getTimeUnitParts(unit) } : {}),
                    ...(utc ? { timezone: 'utc' } : {}),
                    ...params,
                    as: startEnd
                });
                transforms.push(...standalone_offsetedRectFormulas(startEnd, rectBandPosition, normalizedTimeUnit));
            }
            else if (f) {
                const { field: escapedField } = f;
                // since this is a expression, we want the unescaped field name
                const field = escapedField.replaceAll('\\.', '.');
                const expr = standalone_offsetExpr({ timeUnit: normalizedTimeUnit, field });
                const endAs = standalone_offsetAs(field);
                transforms.push({
                    type: 'formula',
                    expr,
                    as: endAs
                });
                transforms.push(...standalone_offsetedRectFormulas([field, endAs], rectBandPosition, normalizedTimeUnit));
            }
        }
        return transforms;
    }
}
const standalone_OFFSETTED_RECT_START_SUFFIX = 'offsetted_rect_start';
const standalone_OFFSETTED_RECT_END_SUFFIX = 'offsetted_rect_end';
function standalone_offsetExpr({ timeUnit, field, reverse }) {
    const { unit, utc } = timeUnit;
    const smallestUnit = standalone_getSmallestTimeUnitPart(unit);
    const { part, step } = standalone_getDateTimePartAndStep(smallestUnit, timeUnit.step);
    const offsetFn = utc ? 'utcOffset' : 'timeOffset';
    const expr = `${offsetFn}('${part}', ${standalone_accessWithDatumToUnescapedPath(field)}, ${reverse ? -step : step})`;
    return expr;
}
function standalone_offsetedRectFormulas([startField, endField], rectBandPosition, timeUnit) {
    if (rectBandPosition !== undefined && rectBandPosition !== 0.5) {
        const startExpr = standalone_accessWithDatumToUnescapedPath(startField);
        const endExpr = standalone_accessWithDatumToUnescapedPath(endField);
        return [
            {
                type: 'formula',
                expr: standalone_interpolateExpr([
                    standalone_offsetExpr({
                        timeUnit,
                        field: startField,
                        reverse: true
                    }),
                    startExpr
                ], rectBandPosition + 0.5),
                as: `${startField}_${standalone_OFFSETTED_RECT_START_SUFFIX}`
            },
            {
                type: 'formula',
                expr: standalone_interpolateExpr([startExpr, endExpr], rectBandPosition + 0.5),
                as: `${startField}_${standalone_OFFSETTED_RECT_END_SUFFIX}`
            }
        ];
    }
    return [];
}
function standalone_interpolateExpr([start, end], fraction) {
    return `${1 - fraction} * ${start} + ${fraction} * ${end}`;
}
//# sourceMappingURL=timeunit.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/project.js









const standalone_TUPLE_FIELDS = '_tuple_fields';
class standalone_SelectionProjectionComponent {
    constructor(...items) {
        this.items = items;
        this.hasChannel = {};
        this.hasField = {};
        this.hasSelectionId = false;
    }
}
const standalone_project_project = {
    defined: () => {
        return true; // This transform handles its own defaults, so always run parse.
    },
    parse: (model, selCmpt, selDef) => {
        const name = selCmpt.name;
        const proj = (selCmpt.project ?? (selCmpt.project = new standalone_SelectionProjectionComponent()));
        const parsed = {};
        const timeUnits = {};
        const signals = new Set();
        const signalName = (p, range) => {
            const suffix = range === 'visual' ? p.channel : p.field;
            let sg = standalone_varName(`${name}_${suffix}`);
            for (let counter = 1; signals.has(sg); counter++) {
                sg = standalone_varName(`${name}_${suffix}_${counter}`);
            }
            signals.add(sg);
            return { [range]: sg };
        };
        const type = selCmpt.type;
        const cfg = model.config.selection[type];
        const init = selDef.value !== undefined
            ? standalone_array(selDef.value)
            : null;
        // If no explicit projection (either fields or encodings) is specified, set some defaults.
        // If an initial value is set, try to infer projections.
        let { fields, encodings } = (standalone_vega_util_module_isObject(selDef.select) ? selDef.select : {});
        if (!fields && !encodings && init) {
            for (const initVal of init) {
                // initVal may be a scalar value to smoothen varParam -> pointSelection gradient.
                if (!standalone_vega_util_module_isObject(initVal)) {
                    continue;
                }
                for (const key of standalone_util_keys(initVal)) {
                    if (standalone_isSingleDefUnitChannel(key)) {
                        (encodings || (encodings = [])).push(key);
                    }
                    else {
                        if (type === 'interval') {
                            standalone_log_warn(standalone_INTERVAL_INITIALIZED_WITH_POS);
                            encodings = cfg.encodings;
                        }
                        else {
                            (fields ?? (fields = [])).push(key);
                        }
                    }
                }
            }
        }
        // If no initial value is specified, use the default configuration.
        // We break this out as a separate if block (instead of an else condition)
        // to account for unprojected point selections that have scalar initial values
        if (!fields && !encodings) {
            encodings = cfg.encodings;
            if ('fields' in cfg) {
                fields = cfg.fields;
            }
        }
        for (const channel of encodings ?? []) {
            const fieldDef = model.fieldDef(channel);
            if (fieldDef) {
                let field = fieldDef.field;
                if (fieldDef.aggregate) {
                    standalone_log_warn(standalone_cannotProjectAggregate(channel, fieldDef.aggregate));
                    continue;
                }
                else if (!field) {
                    standalone_log_warn(standalone_cannotProjectOnChannelWithoutField(channel));
                    continue;
                }
                if (fieldDef.timeUnit && !standalone_isBinnedTimeUnit(fieldDef.timeUnit)) {
                    field = model.vgField(channel);
                    // Construct TimeUnitComponents which will be combined into a
                    // TimeUnitNode. This node may need to be inserted into the
                    // dataflow if the selection is used across views that do not
                    // have these time units defined.
                    const component = {
                        timeUnit: fieldDef.timeUnit,
                        as: field,
                        field: fieldDef.field
                    };
                    timeUnits[standalone_util_hash(component)] = component;
                }
                // Prevent duplicate projections on the same field.
                // TODO: what if the same field is bound to multiple channels (e.g., SPLOM diag).
                if (!parsed[field]) {
                    // Determine whether the tuple will store enumerated or ranged values.
                    // Interval selections store ranges for continuous scales, and enumerations otherwise.
                    // Single/multi selections store ranges for binned fields, and enumerations otherwise.
                    const tplType = type === 'interval' &&
                        standalone_isScaleChannel(channel) &&
                        standalone_hasContinuousDomain(model.getScaleComponent(channel).get('type'))
                        ? 'R'
                        : fieldDef.bin
                            ? 'R-RE'
                            : 'E';
                    const p = { field, channel, type: tplType, index: proj.items.length };
                    p.signals = { ...signalName(p, 'data'), ...signalName(p, 'visual') };
                    proj.items.push((parsed[field] = p));
                    proj.hasField[field] = parsed[field];
                    proj.hasSelectionId = proj.hasSelectionId || field === standalone_SELECTION_ID;
                    if (standalone_isGeoPositionChannel(channel)) {
                        p.geoChannel = channel;
                        p.channel = standalone_getPositionChannelFromLatLong(channel);
                        proj.hasChannel[p.channel] = parsed[field];
                    }
                    else {
                        proj.hasChannel[channel] = parsed[field];
                    }
                }
            }
            else {
                standalone_log_warn(standalone_cannotProjectOnChannelWithoutField(channel));
            }
        }
        for (const field of fields ?? []) {
            if (proj.hasField[field])
                continue;
            const p = { type: 'E', field, index: proj.items.length };
            p.signals = { ...signalName(p, 'data') };
            proj.items.push(p);
            proj.hasField[field] = p;
            proj.hasSelectionId = proj.hasSelectionId || field === standalone_SELECTION_ID;
        }
        if (init) {
            selCmpt.init = init.map((v) => {
                // Selections can be initialized either with a full object that maps projections to values
                // or scalar values to smoothen the abstraction gradient from variable params to point selections.
                return proj.items.map(p => standalone_vega_util_module_isObject(v) ? (v[p.geoChannel || p.channel] !== undefined ? v[p.geoChannel || p.channel] : v[p.field]) : v);
            });
        }
        if (!standalone_isEmpty(timeUnits)) {
            proj.timeUnit = new standalone_TimeUnitNode(null, timeUnits);
        }
    },
    signals: (model, selCmpt, allSignals) => {
        const name = selCmpt.name + standalone_TUPLE_FIELDS;
        const hasSignal = allSignals.filter(s => s.name === name);
        return hasSignal.length > 0 || selCmpt.project.hasSelectionId
            ? allSignals
            : allSignals.concat({
                name,
                value: selCmpt.project.items.map(standalone_assembleProjection)
            });
    }
};
/* harmony default export */ const standalone_selection_project = (standalone_project_project);
//# sourceMappingURL=project.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/point.js







const standalone_CURR = '_curr';
const standalone_ANIM_VALUE = 'anim_value';
const standalone_ANIM_CLOCK = 'anim_clock';
const standalone_EASED_ANIM_CLOCK = 'eased_anim_clock';
const standalone_MIN_EXTENT = 'min_extent';
const standalone_MAX_RANGE_EXTENT = 'max_range_extent';
const standalone_LAST_TICK = 'last_tick_at';
const standalone_IS_PLAYING = 'is_playing';
const standalone_THROTTLE = (1 / 60) * 1000; // 60 FPS
const standalone_animationSignals = (selectionName, scaleName) => {
    return [
        // timer signals
        {
            name: standalone_EASED_ANIM_CLOCK,
            // update: 'easeLinear(anim_clock / max_range_extent) * max_range_extent'
            update: standalone_ANIM_CLOCK // TODO: replace with above once easing functions are implemented in vega-functions
        },
        // scale signals
        // TODO(jzong): uncomment commented signals below when implementing interpolation
        { name: `${selectionName}_domain`, init: `domain('${scaleName}')` },
        { name: standalone_MIN_EXTENT, init: `extent(${selectionName}_domain)[0]` },
        // {name: 'max_extent', init: `extent(${selectionName}_domain)[1]`},
        { name: standalone_MAX_RANGE_EXTENT, init: `extent(range('${scaleName}'))[1]` },
        // {name: 't_index', update: `indexof(${selectionName}_domain, anim_value)`},
        { name: standalone_ANIM_VALUE, update: `invert('${scaleName}', ${standalone_EASED_ANIM_CLOCK})` }
    ];
};
const standalone_point_point = {
    defined: selCmpt => selCmpt.type === 'point',
    topLevelSignals: (model, selCmpt, signals) => {
        if (standalone_isTimerSelection(selCmpt)) {
            signals = signals.concat([
                {
                    name: standalone_ANIM_CLOCK,
                    init: '0',
                    on: [
                        {
                            events: { type: 'timer', throttle: standalone_THROTTLE },
                            update: `${standalone_IS_PLAYING} ? (${standalone_ANIM_CLOCK} + (now() - ${standalone_LAST_TICK}) > ${standalone_MAX_RANGE_EXTENT} ? 0 : ${standalone_ANIM_CLOCK} + (now() - ${standalone_LAST_TICK})) : ${standalone_ANIM_CLOCK}`
                        }
                    ]
                },
                {
                    name: standalone_LAST_TICK,
                    init: 'now()',
                    on: [{ events: [{ signal: standalone_ANIM_CLOCK }, { signal: standalone_IS_PLAYING }], update: 'now()' }]
                },
                {
                    name: standalone_IS_PLAYING,
                    init: 'true'
                }
            ]);
        }
        return signals;
    },
    signals: (model, selCmpt, signals) => {
        const name = selCmpt.name;
        const fieldsSg = name + standalone_TUPLE_FIELDS;
        const project = selCmpt.project;
        const datum = '(item().isVoronoi ? datum.datum : datum)';
        // Only add a discrete selection to the store if a datum is present _and_
        // the interaction isn't occurring on a group mark. This guards against
        // polluting interactive state with invalid values in faceted displays
        // as the group marks are also data-driven. We force the update to account
        // for constant null states but varying toggles (e.g., shift-click in
        // whitespace followed by a click in whitespace; the store should only
        // be cleared on the second click).
        const brushes = standalone_vals(model.component.selection ?? {})
            .reduce((acc, cmpt) => {
            return cmpt.type === 'interval' ? acc.concat(cmpt.name + standalone_BRUSH) : acc;
        }, [])
            .map(b => `indexof(item().mark.name, '${b}') < 0`)
            .join(' && ');
        const test = `datum && item().mark.marktype !== 'group' && indexof(item().mark.role, 'legend') < 0${brushes ? ` && ${brushes}` : ''}`;
        let update = `unit: ${standalone_unitName(model)}, `;
        if (selCmpt.project.hasSelectionId) {
            update += `${standalone_SELECTION_ID}: ${datum}[${standalone_$(standalone_SELECTION_ID)}]`;
        }
        else if (standalone_isTimerSelection(selCmpt)) {
            update += `fields: ${fieldsSg}, values: [${standalone_ANIM_VALUE} ? ${standalone_ANIM_VALUE} : ${standalone_MIN_EXTENT}]`;
        }
        else {
            const values = project.items
                .map(p => {
                const fieldDef = model.fieldDef(p.channel);
                // Binned fields should capture extents, for a range test against the raw field.
                return fieldDef?.bin
                    ? `[${datum}[${standalone_$(model.vgField(p.channel, {}))}], ` +
                        `${datum}[${standalone_$(model.vgField(p.channel, { binSuffix: 'end' }))}]]`
                    : `${datum}[${standalone_$(p.field)}]`;
            })
                .join(', ');
            update += `fields: ${fieldsSg}, values: [${values}]`;
        }
        if (standalone_isTimerSelection(selCmpt)) {
            // timer event: selection is for animation
            return signals.concat(standalone_animationSignals(selCmpt.name, model.scaleName(standalone_TIME)), [
                {
                    name: name + standalone_TUPLE,
                    on: [
                        {
                            events: [{ signal: standalone_EASED_ANIM_CLOCK }, { signal: standalone_ANIM_VALUE }],
                            update: `{${update}}`,
                            force: true
                        }
                    ]
                }
            ]);
        }
        else {
            const events = selCmpt.events;
            return signals.concat([
                {
                    name: name + standalone_TUPLE,
                    on: events
                        ? [
                            {
                                events,
                                update: `${test} ? {${update}} : null`,
                                force: true
                            }
                        ]
                        : []
                }
            ]);
        }
    }
};
/* harmony default export */ const standalone_selection_point = (standalone_point_point);
//# sourceMappingURL=point.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/assemble.js











function standalone_assembleProjection(proj) {
    const { signals, hasLegend, index, ...rest } = proj;
    rest.field = standalone_replacePathInField(rest.field);
    return rest;
}
function standalone_assembleInit(init, isExpr = true, wrap = standalone_vega_util_module_identity) {
    if (standalone_vega_util_module_isArray(init)) {
        const assembled = init.map(v => standalone_assembleInit(v, isExpr, wrap));
        return isExpr ? `[${assembled.join(', ')}]` : assembled;
    }
    else if (standalone_isDateTime(init)) {
        if (isExpr) {
            return wrap(standalone_dateTimeToExpr(init));
        }
        else {
            return wrap(standalone_dateTimeToTimestamp(init));
        }
    }
    return isExpr ? wrap(standalone_util_stringify(init)) : init;
}
function standalone_assembleUnitSelectionSignals(model, signals) {
    for (const selCmpt of standalone_vals(model.component.selection ?? {})) {
        const name = selCmpt.name;
        let modifyExpr = `${name}${standalone_TUPLE}, ${selCmpt.resolve === 'global' ? 'true' : `{unit: ${standalone_unitName(model)}}`}`;
        for (const c of standalone_selectionCompilers) {
            if (!c.defined(selCmpt))
                continue;
            if (c.signals)
                signals = c.signals(model, selCmpt, signals);
            if (c.modifyExpr)
                modifyExpr = c.modifyExpr(model, selCmpt, modifyExpr);
        }
        signals.push({
            name: name + standalone_MODIFY,
            on: [
                {
                    events: { signal: selCmpt.name + standalone_TUPLE },
                    update: `modify(${standalone_$(selCmpt.name + standalone_STORE)}, ${modifyExpr})`
                }
            ]
        });
    }
    return standalone_cleanupEmptyOnArray(signals);
}
function standalone_assembleFacetSignals(model, signals) {
    if (model.component.selection && standalone_util_keys(model.component.selection).length) {
        const name = standalone_$(model.getName('cell'));
        signals.unshift({
            name: 'facet',
            value: {},
            on: [
                {
                    events: standalone_eventSelector('pointermove', 'scope'),
                    update: `isTuple(facet) ? facet : group(${name}).datum`
                }
            ]
        });
    }
    return standalone_cleanupEmptyOnArray(signals);
}
function standalone_assembleTopLevelSignals(model, signals) {
    let hasSelections = false;
    for (const selCmpt of standalone_vals(model.component.selection ?? {})) {
        const name = selCmpt.name;
        const store = standalone_$(name + standalone_STORE);
        const hasSg = signals.filter(s => s.name === name);
        if (hasSg.length === 0) {
            const resolve = selCmpt.resolve === 'global' ? 'union' : selCmpt.resolve;
            const isPoint = selCmpt.type === 'point' ? ', true, true)' : ')';
            signals.push({
                name: selCmpt.name,
                update: `${standalone_VL_SELECTION_RESOLVE}(${store}, ${standalone_$(resolve)}${isPoint}`
            });
        }
        hasSelections = true;
        for (const c of standalone_selectionCompilers) {
            if (c.defined(selCmpt) && c.topLevelSignals) {
                signals = c.topLevelSignals(model, selCmpt, signals);
            }
        }
    }
    if (hasSelections) {
        const hasUnit = signals.filter(s => s.name === 'unit');
        if (hasUnit.length === 0) {
            signals.unshift({
                name: 'unit',
                value: {},
                on: [{ events: 'pointermove', update: 'isTuple(group()) ? group() : unit' }]
            });
        }
    }
    return standalone_cleanupEmptyOnArray(signals);
}
function standalone_assembleUnitSelectionData(model, data) {
    const selectionData = [];
    const animationData = [];
    const unit = standalone_unitName(model, { escape: false });
    for (const selCmpt of standalone_vals(model.component.selection ?? {})) {
        const store = { name: selCmpt.name + standalone_STORE };
        if (selCmpt.project.hasSelectionId) {
            store.transform = [{ type: 'collect', sort: { field: standalone_SELECTION_ID } }];
        }
        if (selCmpt.init) {
            const fields = selCmpt.project.items.map(standalone_assembleProjection);
            store.values = selCmpt.project.hasSelectionId
                ? selCmpt.init.map(i => ({ unit, [standalone_SELECTION_ID]: standalone_assembleInit(i, false)[0] }))
                : selCmpt.init.map(i => ({ unit, fields, values: standalone_assembleInit(i, false) }));
        }
        const contains = [...selectionData, ...data].filter(d => d.name === selCmpt.name + standalone_STORE);
        if (!contains.length) {
            selectionData.push(store);
        }
        if (standalone_isTimerSelection(selCmpt) && data.length) {
            // TODO(jzong): eventually uncomment this stuff when we want to support multi-view
            // const sourceName =
            //   model.parent && model.parent.type !== 'unit' // facet, layer, or concat
            //     ? model.parent.lookupDataSource(model.parent.getDataName(DataSourceType.Main))
            //     : model.lookupDataSource(model.getDataName(DataSourceType.Main));
            const sourceName = model.lookupDataSource(model.getDataName(standalone_DataSourceType.Main));
            const sourceData = data.find(d => d.name === sourceName);
            // find the filter transform for the current selection
            const sourceDataFilter = sourceData.transform.find(t => t.type === 'filter' && t.expr.includes('vlSelectionTest'));
            if (sourceDataFilter) {
                // remove it from the original dataset
                sourceData.transform = sourceData.transform.filter(t => t !== sourceDataFilter);
                // create dataset to hold current animation frame
                const currentFrame = {
                    name: sourceData.name + standalone_CURR,
                    source: sourceData.name,
                    transform: [sourceDataFilter] // add the selection filter to the animation dataset
                };
                animationData.push(currentFrame);
            }
        }
    }
    return selectionData.concat(data, animationData);
}
function standalone_assembleUnitSelectionMarks(model, marks) {
    for (const selCmpt of standalone_vals(model.component.selection ?? {})) {
        for (const c of standalone_selectionCompilers) {
            if (c.defined(selCmpt) && c.marks) {
                marks = c.marks(model, selCmpt, marks);
            }
        }
    }
    return marks;
}
function standalone_assembleLayerSelectionMarks(model, marks) {
    for (const child of model.children) {
        if (standalone_isUnitModel(child)) {
            marks = standalone_assembleUnitSelectionMarks(child, marks);
        }
    }
    return marks;
}
function standalone_assembleSelectionScaleDomain(model, extent, scaleCmpt, domain) {
    const parsedExtent = standalone_parseSelectionExtent(model, extent.param, extent);
    return {
        signal: standalone_hasContinuousDomain(scaleCmpt.get('type')) && standalone_vega_util_module_isArray(domain) && domain[0] > domain[1]
            ? `isValid(${parsedExtent}) && reverse(${parsedExtent})`
            : parsedExtent
    };
}
function standalone_cleanupEmptyOnArray(signals) {
    return signals.map(s => {
        if (s.on && !s.on.length)
            delete s.on;
        return s;
    });
}
//# sourceMappingURL=assemble.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/scales.js







const standalone_scaleBindings = {
    defined: selCmpt => {
        return selCmpt.type === 'interval' && selCmpt.resolve === 'global' && selCmpt.bind && selCmpt.bind === 'scales';
    },
    parse: (model, selCmpt) => {
        const bound = (selCmpt.scales = []);
        for (const proj of selCmpt.project.items) {
            const channel = proj.channel;
            if (!standalone_isScaleChannel(channel)) {
                continue;
            }
            const scale = model.getScaleComponent(channel);
            const scaleType = scale ? scale.get('type') : undefined;
            if (scaleType == 'sequential') {
                standalone_log_warn(standalone_SEQUENTIAL_SCALE_DEPRECATED);
            }
            if (!scale || !standalone_hasContinuousDomain(scaleType)) {
                standalone_log_warn(standalone_SCALE_BINDINGS_CONTINUOUS);
                continue;
            }
            scale.set('selectionExtent', { param: selCmpt.name, field: proj.field }, true);
            bound.push(proj);
        }
    },
    topLevelSignals: (model, selCmpt, signals) => {
        const bound = selCmpt.scales.filter(proj => signals.filter(s => s.name === proj.signals.data).length === 0);
        // Top-level signals are only needed for multiview displays and if this
        // view's top-level signals haven't already been generated.
        if (!model.parent || standalone_isTopLevelLayer(model) || bound.length === 0) {
            return signals;
        }
        // vlSelectionResolve does not account for the behavior of bound scales in
        // multiview displays. Each unit view adds a tuple to the store, but the
        // state of the selection is the unit selection most recently updated. This
        // state is captured by the top-level signals that we insert and "push
        // outer" to from within the units. We need to reassemble this state into
        // the top-level named signal, except no single selCmpt has a global view.
        const namedSg = signals.find(s => s.name === selCmpt.name);
        let update = namedSg.update;
        if (update.includes(standalone_VL_SELECTION_RESOLVE)) {
            namedSg.update = `{${bound
                .map(proj => `${standalone_$(standalone_replacePathInField(proj.field))}: ${proj.signals.data}`)
                .join(', ')}}`;
        }
        else {
            for (const proj of bound) {
                const mapping = `${standalone_$(standalone_replacePathInField(proj.field))}: ${proj.signals.data}`;
                if (!update.includes(mapping)) {
                    update = `${update.substring(0, update.length - 1)}, ${mapping}}`;
                }
            }
            namedSg.update = update;
        }
        return signals.concat(bound.map(proj => ({ name: proj.signals.data })));
    },
    signals: (model, selCmpt, signals) => {
        // Nested signals need only push to top-level signals with multiview displays.
        if (model.parent && !standalone_isTopLevelLayer(model)) {
            for (const proj of selCmpt.scales) {
                const signal = signals.find(s => s.name === proj.signals.data);
                signal.push = 'outer';
                delete signal.value;
                delete signal.update;
            }
        }
        return signals;
    }
};
/* harmony default export */ const standalone_selection_scales = (standalone_scaleBindings);
function standalone_scales_domain(model, channel) {
    const scale = standalone_$(model.scaleName(channel));
    return `domain(${scale})`;
}
function standalone_isTopLevelLayer(model) {
    return model.parent && standalone_isLayerModel(model.parent) && (!model.parent.parent || standalone_isTopLevelLayer(model.parent.parent));
}
//# sourceMappingURL=scales.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/interval.js












const standalone_BRUSH = '_brush';
const standalone_SCALE_TRIGGER = '_scale_trigger';
const standalone_GEO_INIT_TICK = 'geo_interval_init_tick'; // Workaround for https://github.com/vega/vega/issues/3481
const standalone_INIT = '_init';
const standalone_interval_CENTER = '_center';
const standalone_interval_interval = {
    defined: selCmpt => selCmpt.type === 'interval',
    parse: (model, selCmpt, selDef) => {
        var _a;
        if (model.hasProjection) {
            const def = { ...(standalone_vega_util_module_isObject(selDef.select) ? selDef.select : {}) };
            def.fields = [standalone_SELECTION_ID];
            if (!def.encodings) {
                // Remap default x/y projection
                def.encodings = selDef.value ? standalone_util_keys(selDef.value) : [standalone_LONGITUDE, standalone_LATITUDE];
            }
            selDef.select = { type: 'interval', ...def };
        }
        if (selCmpt.translate && !standalone_selection_scales.defined(selCmpt)) {
            const filterExpr = `!event.item || event.item.mark.name !== ${standalone_$(selCmpt.name + standalone_BRUSH)}`;
            for (const evt of selCmpt.events) {
                if (!evt.between) {
                    standalone_log_warn(`${evt} is not an ordered event stream for interval selections.`);
                    continue;
                }
                const filters = standalone_array(((_a = evt.between[0]).filter ?? (_a.filter = [])));
                if (!filters.includes(filterExpr)) {
                    filters.push(filterExpr);
                }
            }
        }
    },
    signals: (model, selCmpt, signals) => {
        const name = selCmpt.name;
        const tupleSg = name + standalone_TUPLE;
        const channels = standalone_vals(selCmpt.project.hasChannel).filter(p => p.channel === standalone_channel_X || p.channel === standalone_channel_Y);
        const init = selCmpt.init ? selCmpt.init[0] : null;
        signals.push(...channels.reduce((arr, proj) => arr.concat(standalone_channelSignals(model, selCmpt, proj, init && init[proj.index])), []));
        if (!model.hasProjection) {
            // Proxy scale reactions to ensure that an infinite loop doesn't occur
            // when an interval selection filter touches the scale.
            if (!standalone_selection_scales.defined(selCmpt)) {
                const triggerSg = name + standalone_SCALE_TRIGGER;
                const scaleTriggers = channels.map(proj => {
                    const channel = proj.channel;
                    const { data: dname, visual: vname } = proj.signals;
                    const scaleName = standalone_$(model.scaleName(channel));
                    const scaleType = model.getScaleComponent(channel).get('type');
                    const toNum = standalone_hasContinuousDomain(scaleType) ? '+' : '';
                    return (`(!isArray(${dname}) || ` +
                        `(${toNum}invert(${scaleName}, ${vname})[0] === ${toNum}${dname}[0] && ` +
                        `${toNum}invert(${scaleName}, ${vname})[1] === ${toNum}${dname}[1]))`);
                });
                if (scaleTriggers.length) {
                    signals.push({
                        name: triggerSg,
                        value: {},
                        on: [
                            {
                                events: channels.map(proj => ({ scale: model.scaleName(proj.channel) })),
                                update: scaleTriggers.join(' && ') + ` ? ${triggerSg} : {}`
                            }
                        ]
                    });
                }
            }
            // Only add an interval to the store if it has valid data extents. Data extents
            // are set to null if pixel extents are equal to account for intervals over
            // ordinal/nominal domains which, when inverted, will still produce a valid datum.
            const dataSignals = channels.map(proj => proj.signals.data);
            const update = `unit: ${standalone_unitName(model)}, fields: ${name + standalone_TUPLE_FIELDS}, values`;
            return signals.concat({
                name: tupleSg,
                ...(init ? { init: `{${update}: ${standalone_assembleInit(init)}}` } : {}),
                ...(dataSignals.length
                    ? {
                        on: [
                            {
                                events: [{ signal: dataSignals.join(' || ') }], // Prevents double invocation, see https://github.com/vega/vega/issues/1672.
                                update: `${dataSignals.join(' && ')} ? {${update}: [${dataSignals}]} : null`
                            }
                        ]
                    }
                    : {})
            });
        }
        else {
            const projection = standalone_$(model.projectionName());
            const centerSg = model.projectionName() + standalone_interval_CENTER;
            const { x, y } = selCmpt.project.hasChannel;
            const xvname = x && x.signals.visual;
            const yvname = y && y.signals.visual;
            const xinit = x ? init && init[x.index] : `${centerSg}[0]`;
            const yinit = y ? init && init[y.index] : `${centerSg}[1]`;
            const sizeSg = (layout) => model.getSizeSignalRef(layout).signal;
            const bbox = `[` +
                `[${xvname ? xvname + '[0]' : '0'}, ${yvname ? yvname + '[0]' : '0'}],` +
                `[${xvname ? xvname + '[1]' : sizeSg('width')}, ` +
                `${yvname ? yvname + '[1]' : sizeSg('height')}]` +
                `]`;
            if (init) {
                signals.unshift({
                    name: name + standalone_INIT,
                    init: `[scale(${projection}, [${x ? xinit[0] : xinit}, ${y ? yinit[0] : yinit}]), ` +
                        `scale(${projection}, [${x ? xinit[1] : xinit}, ${y ? yinit[1] : yinit}])]`
                });
                if (!x || !y) {
                    // If initializing a uni-dimensional brush, use the center of the view to determine the other coord
                    const hasCenterSg = signals.find(s => s.name === centerSg);
                    if (!hasCenterSg) {
                        signals.unshift({
                            name: centerSg,
                            update: `invert(${projection}, [${sizeSg('width')}/2, ${sizeSg('height')}/2])`
                        });
                    }
                }
            }
            const intersect = `intersect(${bbox}, {markname: ${standalone_$(model.getName('marks'))}}, unit.mark)`;
            const base = `{unit: ${standalone_unitName(model)}}`;
            const update = `vlSelectionTuples(${intersect}, ${base})`;
            const visualSignals = channels.map(proj => proj.signals.visual);
            return signals.concat({
                name: tupleSg,
                on: [
                    {
                        events: [
                            ...(visualSignals.length ? [{ signal: visualSignals.join(' || ') }] : []),
                            ...(init ? [{ signal: standalone_GEO_INIT_TICK }] : [])
                        ],
                        update
                    }
                ]
            });
        }
    },
    topLevelSignals: (model, selCmpt, signals) => {
        if (standalone_isUnitModel(model) && model.hasProjection && selCmpt.init) {
            // Workaround for https://github.com/vega/vega/issues/3481
            // The scenegraph isn't populated on the first pulse. So we use a timer signal
            // to re-pulse the dataflow as soon as possible. We return an object to ensure
            // this only occurs once.
            const hasTick = signals.filter(s => s.name === standalone_GEO_INIT_TICK);
            if (!hasTick.length) {
                signals.unshift({
                    name: standalone_GEO_INIT_TICK,
                    value: null,
                    on: [
                        {
                            events: 'timer{1}',
                            update: `${standalone_GEO_INIT_TICK} === null ? {} : ${standalone_GEO_INIT_TICK}`
                        }
                    ]
                });
            }
        }
        return signals;
    },
    marks: (model, selCmpt, marks) => {
        const name = selCmpt.name;
        const { x, y } = selCmpt.project.hasChannel;
        const xvname = x?.signals.visual;
        const yvname = y?.signals.visual;
        const store = `data(${standalone_$(selCmpt.name + standalone_STORE)})`;
        // Do not add a brush if we're binding to scales
        // or we don't have a valid interval projection
        if (standalone_selection_scales.defined(selCmpt) || (!x && !y)) {
            return marks;
        }
        const update = {
            x: x !== undefined ? { signal: `${xvname}[0]` } : { value: 0 },
            y: y !== undefined ? { signal: `${yvname}[0]` } : { value: 0 },
            x2: x !== undefined ? { signal: `${xvname}[1]` } : { field: { group: 'width' } },
            y2: y !== undefined ? { signal: `${yvname}[1]` } : { field: { group: 'height' } }
        };
        // If the selection is resolved to global, only a single interval is in
        // the store. Wrap brush mark's encodings with a production rule to test
        // this based on the `unit` property. Hide the brush mark if it corresponds
        // to a unit different from the one in the store.
        if (selCmpt.resolve === 'global') {
            for (const key of standalone_util_keys(update)) {
                update[key] = [
                    {
                        test: `${store}.length && ${store}[0].unit === ${standalone_unitName(model)}`,
                        ...update[key]
                    },
                    { value: 0 }
                ];
            }
        }
        // Two brush marks ensure that fill colors and other aesthetic choices do
        // not interefere with the core marks, but that the brushed region can still
        // be interacted with (e.g., dragging it around).
        const { fill, fillOpacity, cursor, ...stroke } = selCmpt.mark;
        const vgStroke = standalone_util_keys(stroke).reduce((def, k) => {
            def[k] = [
                {
                    test: [
                        x !== undefined && `${xvname}[0] !== ${xvname}[1]`,
                        y !== undefined && `${yvname}[0] !== ${yvname}[1]`
                    ]
                        .filter(t => t)
                        .join(' && '),
                    value: stroke[k]
                },
                { value: null }
            ];
            return def;
        }, {});
        // Set cursor to move unless the brush cannot be translated
        const vgCursor = cursor ?? (selCmpt.translate ? 'move' : null);
        return [
            {
                name: `${name + standalone_BRUSH}_bg`,
                type: 'rect',
                clip: true,
                encode: {
                    enter: {
                        fill: { value: fill },
                        fillOpacity: { value: fillOpacity }
                    },
                    update
                }
            },
            ...marks,
            {
                name: name + standalone_BRUSH,
                type: 'rect',
                clip: true,
                encode: {
                    enter: {
                        ...(vgCursor ? { cursor: { value: vgCursor } } : {}),
                        fill: { value: 'transparent' }
                    },
                    update: { ...update, ...vgStroke }
                }
            }
        ];
    }
};
/* harmony default export */ const standalone_selection_interval = (standalone_interval_interval);
/**
 * Returns the visual and data signals for an interval selection.
 */
function standalone_channelSignals(model, selCmpt, proj, init) {
    const scaledInterval = !model.hasProjection;
    const channel = proj.channel;
    const vname = proj.signals.visual;
    const scaleName = standalone_$(scaledInterval ? model.scaleName(channel) : model.projectionName());
    const scaled = (str) => `scale(${scaleName}, ${str})`;
    const size = model.getSizeSignalRef(channel === standalone_channel_X ? 'width' : 'height').signal;
    const coord = `${channel}(unit)`;
    const von = selCmpt.events.reduce((def, evt) => {
        return [
            ...def,
            { events: evt.between[0], update: `[${coord}, ${coord}]` }, // Brush Start
            { events: evt, update: `[${vname}[0], clamp(${coord}, 0, ${size})]` } // Brush End
        ];
    }, []);
    if (scaledInterval) {
        const dname = proj.signals.data;
        const hasScales = standalone_selection_scales.defined(selCmpt);
        const scale = model.getScaleComponent(channel);
        const scaleType = scale ? scale.get('type') : undefined;
        const vinit = init ? { init: standalone_assembleInit(init, true, scaled) } : { value: [] };
        // React to pan/zooms of continuous scales. Non-continuous scales
        // (band, point) cannot be pan/zoomed and any other changes
        // to their domains (e.g., filtering) should clear the brushes.
        von.push({
            events: { signal: selCmpt.name + standalone_SCALE_TRIGGER },
            update: standalone_hasContinuousDomain(scaleType) ? `[${scaled(`${dname}[0]`)}, ${scaled(`${dname}[1]`)}]` : `[0, 0]`
        });
        return hasScales
            ? [{ name: dname, on: [] }]
            : [
                { name: vname, ...vinit, on: von },
                {
                    name: dname,
                    ...(init ? { init: standalone_assembleInit(init) } : {}), // Cannot be `value` as `init` may require datetime exprs.
                    on: [
                        {
                            events: { signal: vname },
                            update: `${vname}[0] === ${vname}[1] ? null : invert(${scaleName}, ${vname})`
                        }
                    ]
                }
            ];
    }
    else {
        const initIdx = channel === standalone_channel_X ? 0 : 1;
        const initSg = selCmpt.name + standalone_INIT;
        const vinit = init ? { init: `[${initSg}[0][${initIdx}], ${initSg}[1][${initIdx}]]` } : { value: [] };
        return [{ name: vname, ...vinit, on: von }];
    }
}
//# sourceMappingURL=interval.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/conditional.js




/**
 * Return a VgEncodeEntry that includes a Vega production rule for a scale channel's encoding or guide encoding, which includes:
 * (1) the conditional rules (if provided as part of channelDef)
 * (2) invalidValueRef for handling invalid values (if provided as a parameter of this method)
 * (3) main reference for the encoded data.
 */
function standalone_wrapCondition({ model, channelDef, vgChannel, invalidValueRef, mainRefFn }) {
    const condition = standalone_isConditionalDef(channelDef) && channelDef.condition;
    let valueRefs = [];
    if (condition) {
        const conditions = standalone_array(condition);
        valueRefs = conditions.map(c => {
            const conditionValueRef = mainRefFn(c);
            if (standalone_isConditionalParameter(c)) {
                const { param, empty } = c;
                const test = standalone_parseSelectionPredicate(model, { param, empty });
                return { test, ...conditionValueRef };
            }
            else {
                const test = standalone_predicate_expression(model, c.test); // FIXME: remove casting once TS is no longer dumb about it
                return { test, ...conditionValueRef };
            }
        });
    }
    if (invalidValueRef !== undefined) {
        valueRefs.push(invalidValueRef);
    }
    const mainValueRef = mainRefFn(channelDef);
    if (mainValueRef !== undefined) {
        valueRefs.push(mainValueRef);
    }
    if (valueRefs.length > 1 ||
        (valueRefs.length === 1 && Boolean(valueRefs[0].test)) // We must use array form valueRefs if test exists, otherwise Vega won't execute the test.
    ) {
        return { [vgChannel]: valueRefs };
    }
    else if (valueRefs.length === 1) {
        return { [vgChannel]: valueRefs[0] };
    }
    return {};
}
//# sourceMappingURL=conditional.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/text.js




function standalone_text_text(model, channel = 'text') {
    const channelDef = model.encoding[channel];
    return standalone_wrapCondition({
        model,
        channelDef,
        vgChannel: channel,
        mainRefFn: cDef => standalone_textRef(cDef, model.config),
        invalidValueRef: undefined // text encoding doesn't have continuous scales and thus can't have invalid values
    });
}
function standalone_textRef(channelDef, config, expr = 'datum') {
    // text
    if (channelDef) {
        if (standalone_isValueDef(channelDef)) {
            return standalone_signalOrValueRef(channelDef.value);
        }
        if (standalone_isFieldOrDatumDef(channelDef)) {
            const { format, formatType } = standalone_getFormatMixins(channelDef);
            return standalone_formatSignalRef({ fieldOrDatumDef: channelDef, format, formatType, expr, config });
        }
    }
    return undefined;
}
//# sourceMappingURL=text.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/tooltip.js











function standalone_tooltip(model, opt = {}) {
    const { encoding, markDef, config, stack } = model;
    const channelDef = encoding.tooltip;
    if (standalone_vega_util_module_isArray(channelDef)) {
        return { tooltip: standalone_tooltipRefForEncoding({ tooltip: channelDef }, stack, config, opt) };
    }
    else {
        const datum = opt.reactiveGeom ? 'datum.datum' : 'datum';
        const mainRefFn = (cDef) => {
            // use valueRef based on channelDef first
            const tooltipRefFromChannelDef = standalone_textRef(cDef, config, datum);
            if (tooltipRefFromChannelDef) {
                return tooltipRefFromChannelDef;
            }
            if (cDef === null) {
                // Allow using encoding.tooltip = null to disable tooltip
                return undefined;
            }
            let markTooltip = standalone_getMarkPropOrConfig('tooltip', markDef, config);
            if (markTooltip === true) {
                markTooltip = { content: 'encoding' };
            }
            if (standalone_vega_util_module_isString(markTooltip)) {
                return { value: markTooltip };
            }
            else if (standalone_vega_util_module_isObject(markTooltip)) {
                // `tooltip` is `{fields: 'encodings' | 'fields'}`
                if (standalone_isSignalRef(markTooltip)) {
                    return markTooltip;
                }
                else if (markTooltip.content === 'encoding') {
                    return standalone_tooltipRefForEncoding(encoding, stack, config, opt);
                }
                else {
                    return { signal: datum };
                }
            }
            return undefined;
        };
        return standalone_wrapCondition({
            model,
            channelDef,
            vgChannel: 'tooltip',
            mainRefFn,
            invalidValueRef: undefined // tooltip encoding doesn't have continuous scales and thus can't have invalid values
        });
    }
}
function standalone_tooltipData(encoding, stack, config, { reactiveGeom } = {}) {
    const formatConfig = { ...config, ...config.tooltipFormat };
    const toSkip = new Set();
    const expr = reactiveGeom ? 'datum.datum' : 'datum';
    const tuples = [];
    function add(fDef, channel) {
        const mainChannel = standalone_getMainRangeChannel(channel);
        const fieldDef = standalone_isTypedFieldDef(fDef)
            ? fDef
            : {
                ...fDef,
                type: encoding[mainChannel].type // for secondary field def, copy type from main channel
            };
        const title = fieldDef.title || standalone_defaultTitle(fieldDef, formatConfig);
        const key = standalone_array(title).join(', ').replaceAll(/"/g, '\\"');
        let value;
        if (standalone_isXorY(channel)) {
            const channel2 = channel === 'x' ? 'x2' : 'y2';
            const fieldDef2 = standalone_getFieldDef(encoding[channel2]);
            if (standalone_isBinned(fieldDef.bin) && fieldDef2) {
                const startField = standalone_vgField(fieldDef, { expr });
                const endField = standalone_vgField(fieldDef2, { expr });
                const { format, formatType } = standalone_getFormatMixins(fieldDef);
                value = standalone_binFormatExpression(startField, endField, format, formatType, formatConfig);
                toSkip.add(channel2);
            }
        }
        if ((standalone_isXorY(channel) || channel === standalone_THETA || channel === standalone_RADIUS) &&
            stack &&
            stack.fieldChannel === channel &&
            stack.offset === 'normalize') {
            const { format, formatType } = standalone_getFormatMixins(fieldDef);
            value = standalone_formatSignalRef({
                fieldOrDatumDef: fieldDef,
                format,
                formatType,
                expr,
                config: formatConfig,
                normalizeStack: true
            }).signal;
        }
        value ?? (value = standalone_textRef(fieldDef, formatConfig, expr).signal);
        tuples.push({ channel, key, value });
    }
    standalone_forEach(encoding, (channelDef, channel) => {
        if (standalone_isFieldDef(channelDef)) {
            add(channelDef, channel);
        }
        else if (standalone_hasConditionalFieldDef(channelDef)) {
            add(channelDef.condition, channel);
        }
    });
    const out = {};
    for (const { channel, key, value } of tuples) {
        if (!toSkip.has(channel) && !out[key]) {
            out[key] = value;
        }
    }
    return out;
}
function standalone_tooltipRefForEncoding(encoding, stack, config, { reactiveGeom } = {}) {
    const data = standalone_tooltipData(encoding, stack, config, { reactiveGeom });
    const keyValues = standalone_entries(data).map(([key, value]) => `"${key}": ${value}`);
    return keyValues.length > 0 ? { signal: `{${keyValues.join(', ')}}` } : undefined;
}
//# sourceMappingURL=tooltip.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/aria.js







function standalone_aria(model) {
    const { markDef, config } = model;
    const enableAria = standalone_getMarkPropOrConfig('aria', markDef, config);
    // We can ignore other aria properties if ariaHidden is true.
    if (enableAria === false) {
        // getMarkGroups sets aria to false already so we don't have to set it in the encode block
        return {};
    }
    return {
        ...(enableAria ? { aria: enableAria } : {}),
        ...standalone_ariaRoleDescription(model),
        ...standalone_description(model)
    };
}
function standalone_ariaRoleDescription(model) {
    const { mark, markDef, config } = model;
    if (config.aria === false) {
        return {};
    }
    const ariaRoleDesc = standalone_getMarkPropOrConfig('ariaRoleDescription', markDef, config);
    if (ariaRoleDesc != null) {
        return { ariaRoleDescription: { value: ariaRoleDesc } };
    }
    return standalone_vega_util_module_has(standalone_VG_MARK_INDEX, mark) ? {} : { ariaRoleDescription: { value: mark } };
}
function standalone_description(model) {
    const { encoding, markDef, config, stack } = model;
    const channelDef = encoding.description;
    if (channelDef) {
        return standalone_wrapCondition({
            model,
            channelDef,
            vgChannel: 'description',
            mainRefFn: cDef => standalone_textRef(cDef, model.config),
            invalidValueRef: undefined // aria encoding doesn't have continuous scales and thus can't have invalid values
        });
    }
    // Use default from mark def or config if defined.
    // Functions in encode usually just return undefined but since we are defining a default below, we need to check the default here.
    const descriptionValue = standalone_getMarkPropOrConfig('description', markDef, config);
    if (descriptionValue != null) {
        return {
            description: standalone_signalOrValueRef(descriptionValue)
        };
    }
    if (config.aria === false) {
        return {};
    }
    const data = standalone_tooltipData(encoding, stack, config);
    if (standalone_isEmpty(data)) {
        return undefined;
    }
    return {
        description: {
            signal: standalone_entries(data)
                .map(([key, value], index) => `"${index > 0 ? '; ' : ''}${key}: " + (${value})`)
                .join(' + ')
        }
    };
}
//# sourceMappingURL=aria.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/nonposition.js





/**
 * Return encode for non-positional channels with scales. (Text doesn't have scale.)
 */
function standalone_nonPosition(channel, model, opt = {}) {
    const { markDef, encoding, config } = model;
    const { vgChannel } = opt;
    let { defaultRef, defaultValue } = opt;
    const channelDef = encoding[channel];
    if (defaultRef === undefined) {
        // prettier-ignore
        defaultValue ?? (defaultValue = standalone_getMarkPropOrConfig(channel, markDef, config, {
            vgChannel,
            // If there is no conditonal def, we ignore vgConfig so the output spec is concise.
            // However, if there is a conditional def, we must include vgConfig so the default is respected.
            ignoreVgConfig: !standalone_isConditionalDef(channelDef)
        }));
        if (defaultValue !== undefined) {
            defaultRef = standalone_signalOrValueRef(defaultValue);
        }
    }
    const commonProps = {
        markDef,
        config,
        scaleName: model.scaleName(channel),
        scale: model.getScaleComponent(channel)
    };
    const invalidValueRef = standalone_getConditionalValueRefForIncludingInvalidValue({
        ...commonProps,
        scaleChannel: channel,
        channelDef
    });
    const mainRefFn = (cDef) => {
        return standalone_midPoint({
            ...commonProps,
            channel,
            channelDef: cDef,
            stack: null, // No need to provide stack for non-position as it does not affect mid point
            defaultRef
        });
    };
    return standalone_wrapCondition({
        model,
        channelDef,
        vgChannel: vgChannel ?? channel,
        invalidValueRef,
        mainRefFn
    });
}
//# sourceMappingURL=nonposition.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/color.js




function standalone_color_color(model, opt = { filled: undefined }) {
    const { markDef, encoding, config } = model;
    const { type: markType } = markDef;
    // Allow filled to be overridden (for trail's "filled")
    const filled = opt.filled ?? standalone_getMarkPropOrConfig('filled', markDef, config);
    const transparentIfNeeded = standalone_util_contains(['bar', 'point', 'circle', 'square', 'geoshape'], markType)
        ? 'transparent'
        : undefined;
    const defaultFill = standalone_getMarkPropOrConfig(filled === true ? 'color' : undefined, markDef, config, { vgChannel: 'fill' }) ??
        // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified
        config.mark[filled === true && 'color'] ??
        // If there is no fill, always fill symbols, bar, geoshape
        // with transparent fills https://github.com/vega/vega-lite/issues/1316
        transparentIfNeeded;
    const defaultStroke = standalone_getMarkPropOrConfig(filled === false ? 'color' : undefined, markDef, config, { vgChannel: 'stroke' }) ??
        // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified
        config.mark[filled === false && 'color'];
    const colorVgChannel = filled ? 'fill' : 'stroke';
    const fillStrokeMarkDefAndConfig = {
        ...(defaultFill ? { fill: standalone_signalOrValueRef(defaultFill) } : {}),
        ...(defaultStroke ? { stroke: standalone_signalOrValueRef(defaultStroke) } : {})
    };
    if (markDef.color && (filled ? markDef.fill : markDef.stroke)) {
        standalone_log_warn(standalone_droppingColor('property', { fill: 'fill' in markDef, stroke: 'stroke' in markDef }));
    }
    return {
        ...fillStrokeMarkDefAndConfig,
        ...standalone_nonPosition('color', model, {
            vgChannel: colorVgChannel,
            defaultValue: filled ? defaultFill : defaultStroke
        }),
        ...standalone_nonPosition('fill', model, {
            // if there is encoding.fill, include default fill just in case we have conditional-only fill encoding
            defaultValue: encoding.fill ? defaultFill : undefined
        }),
        ...standalone_nonPosition('stroke', model, {
            // if there is encoding.stroke, include default fill just in case we have conditional-only stroke encoding
            defaultValue: encoding.stroke ? defaultStroke : undefined
        })
    };
}
//# sourceMappingURL=color.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/zindex.js




function standalone_zindex(model) {
    const { encoding, mark } = model;
    const order = encoding.order;
    if (!standalone_isPathMark(mark) && standalone_isValueDef(order)) {
        return standalone_wrapCondition({
            model,
            channelDef: order,
            vgChannel: 'zindex',
            mainRefFn: cd => standalone_signalOrValueRef(cd.value),
            invalidValueRef: undefined // zindex encoding doesn't have continuous scales and thus can't have invalid values
        });
    }
    return {};
}
//# sourceMappingURL=zindex.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/offset.js


function standalone_positionOffset({ channel: baseChannel, markDef, encoding = {}, model, bandPosition }) {
    const channel = `${baseChannel}Offset`; // Need to cast as the type can't be inferred automatically
    const defaultValue = markDef[channel];
    // FIXME: remove as any
    const channelDef = encoding[channel];
    if ((channel === 'xOffset' || channel === 'yOffset') && channelDef) {
        const ref = standalone_midPoint({
            channel: channel,
            channelDef,
            markDef,
            config: model?.config,
            scaleName: model.scaleName(channel),
            scale: model.getScaleComponent(channel),
            stack: null,
            defaultRef: standalone_signalOrValueRef(defaultValue),
            bandPosition
        });
        return { offsetType: 'encoding', offset: ref };
    }
    const markDefOffsetValue = markDef[channel];
    if (markDefOffsetValue) {
        return { offsetType: 'visual', offset: markDefOffsetValue };
    }
    return {};
}
//# sourceMappingURL=offset.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/position-point.js






/**
 * Return encode for point (non-band) position channels.
 */
function standalone_pointPosition(channel, model, { defaultPos, vgChannel }) {
    const { encoding, markDef, config, stack } = model;
    const channelDef = encoding[channel];
    const channel2Def = encoding[standalone_getSecondaryRangeChannel(channel)];
    const scaleName = model.scaleName(channel);
    const scale = model.getScaleComponent(channel);
    const { offset, offsetType } = standalone_positionOffset({
        channel,
        markDef,
        encoding,
        model,
        bandPosition: 0.5
    });
    // Get default position or position from mark def
    const defaultRef = standalone_pointPositionDefaultRef({
        model,
        defaultPos,
        channel,
        scaleName,
        scale
    });
    const valueRef = !channelDef && standalone_isXorY(channel) && (encoding.latitude || encoding.longitude)
        ? // use geopoint output if there are lat/long and there is no point position overriding lat/long.
            { field: model.getName(channel) }
        : standalone_positionRef({
            channel,
            channelDef,
            channel2Def,
            markDef,
            config,
            scaleName,
            scale,
            stack,
            offset,
            defaultRef,
            bandPosition: offsetType === 'encoding' ? 0 : undefined
        });
    return valueRef ? { [vgChannel || channel]: valueRef } : undefined;
}
// TODO: we need to find a way to refactor these so that scaleName is a part of scale
// but that's complicated. For now, this is a huge step moving forward.
/**
 * @return Vega ValueRef for normal x- or y-position without projection
 */
function standalone_positionRef(params) {
    const { channel, channelDef, scaleName, stack, offset, markDef } = params;
    // This isn't a part of midPoint because we use midPoint for non-position too
    if (standalone_isFieldOrDatumDef(channelDef) && stack && channel === stack.fieldChannel) {
        if (standalone_isFieldDef(channelDef)) {
            let bandPosition = channelDef.bandPosition;
            if (bandPosition === undefined && markDef.type === 'text' && (channel === 'radius' || channel === 'theta')) {
                // theta and radius of text mark should use bandPosition = 0.5 by default
                // so that labels for arc marks are centered automatically
                bandPosition = 0.5;
            }
            if (bandPosition !== undefined) {
                return standalone_interpolatedSignalRef({
                    scaleName,
                    fieldOrDatumDef: channelDef, // positionRef always have type
                    startSuffix: 'start',
                    bandPosition,
                    offset
                });
            }
        }
        // x or y use stack_end so that stacked line's point mark use stack_end too.
        return standalone_valueRefForFieldOrDatumDef(channelDef, scaleName, { suffix: 'end' }, { offset });
    }
    return standalone_midPointRefWithPositionInvalidTest(params);
}
function standalone_pointPositionDefaultRef({ model, defaultPos, channel, scaleName, scale }) {
    const { markDef, config } = model;
    return () => {
        const mainChannel = standalone_getMainRangeChannel(channel);
        const vgChannel = standalone_getVgPositionChannel(channel);
        const definedValueOrConfig = standalone_getMarkPropOrConfig(channel, markDef, config, { vgChannel });
        if (definedValueOrConfig !== undefined) {
            return standalone_widthHeightValueOrSignalRef(channel, definedValueOrConfig);
        }
        switch (defaultPos) {
            case 'zeroOrMin':
                return standalone_zeroOrMinOrMaxPosition({ scaleName, scale, mode: 'zeroOrMin', mainChannel, config });
            case 'zeroOrMax':
                return standalone_zeroOrMinOrMaxPosition({
                    scaleName,
                    scale,
                    mode: { zeroOrMax: { widthSignal: model.width.signal, heightSignal: model.height.signal } },
                    mainChannel,
                    config
                });
            case 'mid': {
                const sizeRef = model[standalone_getSizeChannel(channel)];
                return { ...sizeRef, mult: 0.5 };
            }
        }
        // defaultPos === null
        return undefined;
    };
}
function standalone_zeroOrMinOrMaxPosition({ mainChannel, config, ...otherProps }) {
    const scaledValueRef = standalone_scaledZeroOrMinOrMax(otherProps);
    const { mode } = otherProps;
    if (scaledValueRef) {
        return scaledValueRef;
    }
    switch (mainChannel) {
        case 'radius': {
            if (mode === 'zeroOrMin') {
                return { value: 0 }; // min value
            }
            const { widthSignal, heightSignal } = mode.zeroOrMax;
            // max of radius is min(width, height) / 2
            return {
                signal: `min(${widthSignal},${heightSignal})/2`
            };
        }
        case 'theta':
            return mode === 'zeroOrMin' ? { value: 0 } : { signal: '2*PI' };
        case 'x':
            return mode === 'zeroOrMin' ? { value: 0 } : { field: { group: 'width' } };
        case 'y':
            return mode === 'zeroOrMin' ? { field: { group: 'height' } } : { value: 0 };
    }
}
//# sourceMappingURL=position-point.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/position-align.js




const standalone_ALIGNED_X_CHANNEL = {
    left: 'x',
    center: 'xc',
    right: 'x2'
};
const standalone_BASELINED_Y_CHANNEL = {
    top: 'y',
    middle: 'yc',
    bottom: 'y2'
};
function standalone_vgAlignedPositionChannel(channel, markDef, config, defaultAlign = 'middle') {
    if (channel === 'radius' || channel === 'theta') {
        return standalone_getVgPositionChannel(channel);
    }
    const alignChannel = channel === 'x' ? 'align' : 'baseline';
    const align = standalone_getMarkPropOrConfig(alignChannel, markDef, config);
    let alignExcludingSignal;
    if (standalone_isSignalRef(align)) {
        standalone_log_warn(standalone_rangeMarkAlignmentCannotBeExpression(alignChannel));
        alignExcludingSignal = undefined;
    }
    else {
        alignExcludingSignal = align;
    }
    // FIXME: remove as any
    if (channel === 'x') {
        return standalone_ALIGNED_X_CHANNEL[alignExcludingSignal || (defaultAlign === 'top' ? 'left' : 'center')];
    }
    else {
        return standalone_BASELINED_Y_CHANNEL[alignExcludingSignal || defaultAlign];
    }
}
//# sourceMappingURL=position-align.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/position-range.js









/**
 * Utility for area/rule position, which can be either point or range.
 * (One of the axes should be point and the other should be range.)
 */
function standalone_pointOrRangePosition(channel, model, { defaultPos, defaultPos2, range }) {
    if (range) {
        return standalone_rangePosition(channel, model, { defaultPos, defaultPos2 });
    }
    return standalone_pointPosition(channel, model, { defaultPos });
}
function standalone_rangePosition(channel, model, { defaultPos, defaultPos2 }) {
    const { markDef, config } = model;
    const channel2 = standalone_getSecondaryRangeChannel(channel);
    const sizeChannel = standalone_getSizeChannel(channel);
    const pos2Mixins = standalone_pointPosition2OrSize(model, defaultPos2, channel2);
    const vgChannel = pos2Mixins[sizeChannel]
        ? // If there is width/height, we need to position the marks based on the alignment.
            standalone_vgAlignedPositionChannel(channel, markDef, config)
        : // Otherwise, make sure to apply to the right Vg Channel (for arc mark)
            standalone_getVgPositionChannel(channel);
    return {
        ...standalone_pointPosition(channel, model, { defaultPos, vgChannel }),
        ...pos2Mixins
    };
}
/**
 * Return encode for x2, y2.
 * If channel is not specified, return one channel based on orientation.
 */
function standalone_pointPosition2OrSize(model, defaultPos, channel) {
    const { encoding, mark, markDef, stack, config } = model;
    const baseChannel = standalone_getMainRangeChannel(channel);
    const sizeChannel = standalone_getSizeChannel(channel);
    const vgChannel = standalone_getVgPositionChannel(channel);
    const channelDef = encoding[baseChannel];
    const scaleName = model.scaleName(baseChannel);
    const scale = model.getScaleComponent(baseChannel);
    const { offset } = channel in encoding || channel in markDef
        ? standalone_positionOffset({ channel, markDef, encoding, model })
        : standalone_positionOffset({ channel: baseChannel, markDef, encoding, model });
    if (!channelDef && (channel === 'x2' || channel === 'y2') && (encoding.latitude || encoding.longitude)) {
        const vgSizeChannel = standalone_getSizeChannel(channel);
        const size = model.markDef[vgSizeChannel];
        if (size != null) {
            return {
                [vgSizeChannel]: { value: size }
            };
        }
        else {
            return {
                [vgChannel]: { field: model.getName(channel) }
            };
        }
    }
    const valueRef = standalone_position2Ref({
        channel,
        channelDef,
        channel2Def: encoding[channel],
        markDef,
        config,
        scaleName,
        scale,
        stack,
        offset,
        defaultRef: undefined
    });
    if (valueRef !== undefined) {
        return { [vgChannel]: valueRef };
    }
    // TODO: check width/height encoding here once we add them
    // no x2/y2 encoding, then try to read x2/y2 or width/height based on precedence:
    // markDef > config.style > mark-specific config (config[mark]) > general mark config (config.mark)
    return (standalone_position2orSize(channel, markDef) ||
        standalone_position2orSize(channel, {
            [channel]: standalone_getMarkStyleConfig(channel, markDef, config.style),
            [sizeChannel]: standalone_getMarkStyleConfig(sizeChannel, markDef, config.style)
        }) ||
        standalone_position2orSize(channel, config[mark]) ||
        standalone_position2orSize(channel, config.mark) || {
        [vgChannel]: standalone_pointPositionDefaultRef({
            model,
            defaultPos,
            channel,
            scaleName,
            scale
        })()
    });
}
function standalone_position2Ref({ channel, channelDef, channel2Def, markDef, config, scaleName, scale, stack, offset, defaultRef }) {
    if (standalone_isFieldOrDatumDef(channelDef) &&
        stack &&
        // If fieldChannel is X and channel is X2 (or Y and Y2)
        channel.charAt(0) === stack.fieldChannel.charAt(0)) {
        return standalone_valueRefForFieldOrDatumDef(channelDef, scaleName, { suffix: 'start' }, { offset });
    }
    return standalone_midPointRefWithPositionInvalidTest({
        channel,
        channelDef: channel2Def,
        scaleName,
        scale,
        stack,
        markDef,
        config,
        offset,
        defaultRef
    });
}
function standalone_position2orSize(channel, markDef) {
    const sizeChannel = standalone_getSizeChannel(channel);
    const vgChannel = standalone_getVgPositionChannel(channel);
    if (markDef[vgChannel] !== undefined) {
        return { [vgChannel]: standalone_widthHeightValueOrSignalRef(channel, markDef[vgChannel]) };
    }
    else if (markDef[channel] !== undefined) {
        return { [vgChannel]: standalone_widthHeightValueOrSignalRef(channel, markDef[channel]) };
    }
    else if (markDef[sizeChannel]) {
        const dimensionSize = markDef[sizeChannel];
        if (standalone_isRelativeBandSize(dimensionSize)) {
            standalone_log_warn(standalone_relativeBandSizeNotSupported(sizeChannel));
        }
        else {
            return { [sizeChannel]: standalone_widthHeightValueOrSignalRef(channel, dimensionSize) };
        }
    }
    return undefined;
}
//# sourceMappingURL=position-range.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/position-rect.js



















function standalone_rectPosition(model, channel) {
    const { config, encoding, markDef } = model;
    const mark = markDef.type;
    const channel2 = standalone_getSecondaryRangeChannel(channel);
    const sizeChannel = standalone_getSizeChannel(channel);
    const channelDef = encoding[channel];
    const channelDef2 = encoding[channel2];
    const scale = model.getScaleComponent(channel);
    const scaleType = scale ? scale.get('type') : undefined;
    const orient = markDef.orient;
    const hasSizeDef = encoding[sizeChannel] ??
        encoding.size ??
        standalone_getMarkPropOrConfig('size', markDef, config, { vgChannel: sizeChannel });
    const offsetScaleChannel = standalone_getOffsetChannel(channel);
    const isBarOrTickBand = (mark === 'bar' && (channel === 'x' ? orient === 'vertical' : orient === 'horizontal')) ||
        (mark === 'tick' && (channel === 'y' ? orient === 'vertical' : orient === 'horizontal'));
    // x, x2, and width -- we must specify two of these in all conditions
    if (standalone_isFieldDef(channelDef) &&
        (standalone_isBinning(channelDef.bin) || standalone_isBinned(channelDef.bin) || (channelDef.timeUnit && !channelDef2)) &&
        !(hasSizeDef && !standalone_isRelativeBandSize(hasSizeDef)) &&
        !encoding[offsetScaleChannel] &&
        !standalone_hasDiscreteDomain(scaleType)) {
        return standalone_rectBinPosition({
            fieldDef: channelDef,
            fieldDef2: channelDef2,
            channel,
            model
        });
    }
    else if (((standalone_isFieldOrDatumDef(channelDef) && standalone_hasDiscreteDomain(scaleType)) || isBarOrTickBand) && !channelDef2) {
        return standalone_positionAndSize(channelDef, channel, model);
    }
    else {
        return standalone_rangePosition(channel, model, { defaultPos: 'zeroOrMax', defaultPos2: 'zeroOrMin' });
    }
}
function standalone_defaultSizeRef(sizeChannel, scaleName, scale, config, bandSize, hasFieldDef, mark) {
    if (standalone_isRelativeBandSize(bandSize)) {
        if (scale) {
            const scaleType = scale.get('type');
            if (scaleType === 'band') {
                let bandWidth = `bandwidth('${scaleName}')`;
                if (bandSize.band !== 1) {
                    bandWidth = `${bandSize.band} * ${bandWidth}`;
                }
                const minBandSize = standalone_getMarkConfig('minBandSize', { type: mark }, config);
                return { signal: minBandSize ? `max(${standalone_signalOrStringValue(minBandSize)}, ${bandWidth})` : bandWidth };
            }
            else if (bandSize.band !== 1) {
                standalone_log_warn(standalone_cannotUseRelativeBandSizeWithNonBandScale(scaleType));
                bandSize = undefined;
            }
        }
        else {
            return {
                mult: bandSize.band,
                field: { group: sizeChannel }
            };
        }
    }
    else if (standalone_isSignalRef(bandSize)) {
        return bandSize;
    }
    else if (bandSize) {
        return { value: bandSize };
    }
    // no valid band size
    if (scale) {
        const scaleRange = scale.get('range');
        if (standalone_isVgRangeStep(scaleRange) && standalone_isNumber(scaleRange.step)) {
            return { value: scaleRange.step - 2 };
        }
    }
    if (!hasFieldDef) {
        const { bandPaddingInner, barBandPaddingInner, rectBandPaddingInner, tickBandPaddingInner } = config.scale;
        const padding = standalone_getFirstDefined(bandPaddingInner, mark === 'tick' ? tickBandPaddingInner : mark === 'bar' ? barBandPaddingInner : rectBandPaddingInner); // this part is like paddingInner in scale.ts
        if (standalone_isSignalRef(padding)) {
            return { signal: `(1 - (${padding.signal})) * ${sizeChannel}` };
        }
        else if (standalone_isNumber(padding)) {
            return { signal: `${1 - padding} * ${sizeChannel}` };
        }
    }
    const defaultStep = standalone_getViewConfigDiscreteStep(config.view, sizeChannel);
    return { value: defaultStep - 2 };
}
/**
 * Output position encoding and its size encoding for continuous, point, and band scales.
 */
function standalone_positionAndSize(fieldDef, channel, model) {
    const { markDef, encoding, config, stack } = model;
    const orient = markDef.orient;
    const scaleName = model.scaleName(channel);
    const scale = model.getScaleComponent(channel);
    const vgSizeChannel = standalone_getSizeChannel(channel);
    const channel2 = standalone_getSecondaryRangeChannel(channel);
    const offsetScaleChannel = standalone_getOffsetChannel(channel);
    const offsetScaleName = model.scaleName(offsetScaleChannel);
    const offsetScale = model.getScaleComponent(standalone_getOffsetScaleChannel(channel));
    const useVlSizeChannel = 
    // Always uses size channel for ticks, because tick only calls rectPosition() for the size channel
    markDef.type === 'tick' ||
        // use "size" channel for bars, if there is orient and the channel matches the right orientation
        (orient === 'horizontal' && channel === 'y') ||
        (orient === 'vertical' && channel === 'x');
    // Use size encoding / mark property / config if it exists
    let sizeMixins;
    if (encoding.size || markDef.size) {
        if (useVlSizeChannel) {
            sizeMixins = standalone_nonPosition('size', model, {
                vgChannel: vgSizeChannel,
                defaultRef: standalone_signalOrValueRef(markDef.size)
            });
        }
        else {
            standalone_log_warn(standalone_cannotApplySizeToNonOrientedMark(markDef.type));
        }
    }
    const hasSizeFromMarkOrEncoding = !!sizeMixins;
    // Otherwise, apply default value
    const bandSize = standalone_getBandSize({
        channel,
        fieldDef,
        markDef,
        config,
        scaleType: (scale || offsetScale)?.get('type'),
        useVlSizeChannel
    });
    sizeMixins = sizeMixins || {
        [vgSizeChannel]: standalone_defaultSizeRef(vgSizeChannel, offsetScaleName || scaleName, offsetScale || scale, config, bandSize, !!fieldDef, markDef.type)
    };
    /*
      Band scales with size value and all point scales, use xc/yc + band=0.5
  
      Otherwise (band scales that has size based on a band ref), use x/y with position band = (1 - size_band) / 2.
      In this case, size_band is the band specified in the x/y-encoding.
      By default band is 1, so `(1 - band) / 2` = 0.
      If band is 0.6, the the x/y position in such case should be `(1 - band) / 2` = 0.2
     */
    const defaultBandAlign = (scale || offsetScale)?.get('type') === 'band' && standalone_isRelativeBandSize(bandSize) && !hasSizeFromMarkOrEncoding
        ? 'top'
        : 'middle';
    const vgChannel = standalone_vgAlignedPositionChannel(channel, markDef, config, defaultBandAlign);
    const center = vgChannel === 'xc' || vgChannel === 'yc';
    const { offset, offsetType } = standalone_positionOffset({ channel, markDef, encoding, model, bandPosition: center ? 0.5 : 0 });
    const posRef = standalone_midPointRefWithPositionInvalidTest({
        channel,
        channelDef: fieldDef,
        markDef,
        config,
        scaleName,
        scale,
        stack,
        offset,
        defaultRef: standalone_pointPositionDefaultRef({ model, defaultPos: 'mid', channel, scaleName, scale }),
        bandPosition: center
            ? offsetType === 'encoding'
                ? 0
                : 0.5
            : standalone_isSignalRef(bandSize)
                ? { signal: `(1-${bandSize})/2` }
                : standalone_isRelativeBandSize(bandSize)
                    ? (1 - bandSize.band) / 2
                    : 0
    });
    if (vgSizeChannel) {
        return { [vgChannel]: posRef, ...sizeMixins };
    }
    else {
        // otherwise, we must simulate size by setting position2 = position + size
        // (for theta/radius since Vega doesn't have thetaWidth/radiusWidth)
        const vgChannel2 = standalone_getVgPositionChannel(channel2);
        const sizeRef = sizeMixins[vgSizeChannel];
        const sizeOffset = offset ? { ...sizeRef, offset } : sizeRef;
        return {
            [vgChannel]: posRef,
            // posRef might be an array that wraps position invalid test
            [vgChannel2]: standalone_vega_util_module_isArray(posRef)
                ? [posRef[0], { ...posRef[1], offset: sizeOffset }]
                : {
                    ...posRef,
                    offset: sizeOffset
                }
        };
    }
}
function standalone_getBinSpacing(channel, spacing, reverse, axisTranslate, offset, minBandSize, bandSizeExpr) {
    if (standalone_isPolarPositionChannel(channel)) {
        return 0;
    }
    const isEnd = channel === 'x' || channel === 'y2';
    const spacingOffset = isEnd ? -spacing / 2 : spacing / 2;
    if (standalone_isSignalRef(reverse) || standalone_isSignalRef(offset) || standalone_isSignalRef(axisTranslate) || minBandSize) {
        const reverseExpr = standalone_signalOrStringValue(reverse);
        const offsetExpr = standalone_signalOrStringValue(offset);
        const axisTranslateExpr = standalone_signalOrStringValue(axisTranslate);
        const minBandSizeExpr = standalone_signalOrStringValue(minBandSize);
        const sign = isEnd ? '' : '-';
        const spacingAndSizeOffset = minBandSize
            ? `(${bandSizeExpr} < ${minBandSizeExpr} ? ${sign}0.5 * (${minBandSizeExpr} - (${bandSizeExpr})) : ${spacingOffset})`
            : spacingOffset;
        const t = axisTranslateExpr ? `${axisTranslateExpr} + ` : '';
        const r = reverseExpr ? `(${reverseExpr} ? -1 : 1) * ` : '';
        const o = offsetExpr ? `(${offsetExpr} + ${spacingAndSizeOffset})` : spacingAndSizeOffset;
        return {
            signal: t + r + o
        };
    }
    else {
        offset = offset || 0;
        return axisTranslate + (reverse ? -offset - spacingOffset : +offset + spacingOffset);
    }
}
function standalone_rectBinPosition({ fieldDef, fieldDef2, channel, model }) {
    const { config, markDef, encoding } = model;
    const scale = model.getScaleComponent(channel);
    const scaleName = model.scaleName(channel);
    const scaleType = scale ? scale.get('type') : undefined;
    const reverse = scale.get('reverse');
    const bandSize = standalone_getBandSize({ channel, fieldDef, markDef, config, scaleType });
    const axis = model.component.axes[channel]?.[0];
    const axisTranslate = axis?.get('translate') ?? 0.5; // vega default is 0.5
    const spacing = standalone_isXorY(channel) ? (standalone_getMarkPropOrConfig('binSpacing', markDef, config) ?? 0) : 0;
    const channel2 = standalone_getSecondaryRangeChannel(channel);
    const vgChannel = standalone_getVgPositionChannel(channel);
    const vgChannel2 = standalone_getVgPositionChannel(channel2);
    const minBandSize = standalone_getMarkConfig('minBandSize', markDef, config);
    const { offset } = standalone_positionOffset({ channel, markDef, encoding, model, bandPosition: 0 });
    const { offset: offset2 } = standalone_positionOffset({ channel: channel2, markDef, encoding, model, bandPosition: 0 });
    const bandSizeExpr = standalone_binSizeExpr({ fieldDef, scaleName });
    const binSpacingOffset = standalone_getBinSpacing(channel, spacing, reverse, axisTranslate, offset, minBandSize, bandSizeExpr);
    const binSpacingOffset2 = standalone_getBinSpacing(channel2, spacing, reverse, axisTranslate, offset2 ?? offset, minBandSize, bandSizeExpr);
    const bandPositionForBandSize = standalone_isSignalRef(bandSize)
        ? { signal: `(1-${bandSize.signal})/2` }
        : standalone_isRelativeBandSize(bandSize)
            ? (1 - bandSize.band) / 2
            : 0.5;
    const bandPosition = standalone_getBandPosition({ fieldDef, fieldDef2, markDef, config });
    if (standalone_isBinning(fieldDef.bin) || fieldDef.timeUnit) {
        const useRectOffsetField = fieldDef.timeUnit && bandPosition !== 0.5;
        return {
            [vgChannel2]: standalone_rectBinRef({
                fieldDef,
                scaleName,
                bandPosition: bandPositionForBandSize,
                offset: binSpacingOffset2,
                useRectOffsetField
            }),
            [vgChannel]: standalone_rectBinRef({
                fieldDef,
                scaleName,
                bandPosition: standalone_isSignalRef(bandPositionForBandSize)
                    ? { signal: `1-${bandPositionForBandSize.signal}` }
                    : 1 - bandPositionForBandSize,
                offset: binSpacingOffset,
                useRectOffsetField
            })
        };
    }
    else if (standalone_isBinned(fieldDef.bin)) {
        const startRef = standalone_valueRefForFieldOrDatumDef(fieldDef, scaleName, {}, { offset: binSpacingOffset2 });
        if (standalone_isFieldDef(fieldDef2)) {
            return {
                [vgChannel2]: startRef,
                [vgChannel]: standalone_valueRefForFieldOrDatumDef(fieldDef2, scaleName, {}, { offset: binSpacingOffset })
            };
        }
        else if (standalone_isBinParams(fieldDef.bin) && fieldDef.bin.step) {
            return {
                [vgChannel2]: startRef,
                [vgChannel]: {
                    signal: `scale("${scaleName}", ${standalone_vgField(fieldDef, { expr: 'datum' })} + ${fieldDef.bin.step})`,
                    offset: binSpacingOffset
                }
            };
        }
    }
    standalone_log_warn(standalone_channelRequiredForBinned(channel2));
    return undefined;
}
/**
 * Value Ref for binned fields
 */
function standalone_rectBinRef({ fieldDef, scaleName, bandPosition, offset, useRectOffsetField }) {
    return standalone_interpolatedSignalRef({
        scaleName,
        fieldOrDatumDef: fieldDef,
        bandPosition,
        offset,
        ...(useRectOffsetField
            ? {
                startSuffix: standalone_OFFSETTED_RECT_START_SUFFIX,
                endSuffix: standalone_OFFSETTED_RECT_END_SUFFIX
            }
            : {})
    });
}
//# sourceMappingURL=position-rect.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/base.js
















const standalone_ALWAYS_IGNORE = new Set(['aria', 'width', 'height']);
function standalone_baseEncodeEntry(model, ignore) {
    const { fill = undefined, stroke = undefined } = ignore.color === 'include' ? standalone_color_color(model) : {};
    return {
        ...standalone_markDefProperties(model.markDef, ignore),
        ...standalone_colorRef('fill', fill),
        ...standalone_colorRef('stroke', stroke),
        ...standalone_nonPosition('opacity', model),
        ...standalone_nonPosition('fillOpacity', model),
        ...standalone_nonPosition('strokeOpacity', model),
        ...standalone_nonPosition('strokeWidth', model),
        ...standalone_nonPosition('strokeDash', model),
        ...standalone_zindex(model),
        ...standalone_tooltip(model),
        ...standalone_text_text(model, 'href'),
        ...standalone_aria(model)
    };
}
function standalone_colorRef(channel, valueRef) {
    return valueRef ? { [channel]: valueRef } : {};
}
function standalone_markDefProperties(mark, ignore) {
    return standalone_VG_MARK_CONFIGS.reduce((m, prop) => {
        if (!standalone_ALWAYS_IGNORE.has(prop) && standalone_util_hasProperty(mark, prop) && ignore[prop] !== 'ignore') {
            m[prop] = standalone_signalOrValueRef(mark[prop]);
        }
        return m;
    }, {});
}
//# sourceMappingURL=base.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/defined.js





/**
 * Create Vega's "defined" encoding to break paths in a path mark for invalid values.
 */
function standalone_defined(model) {
    const { config, markDef } = model;
    // For each channel (x/y), add fields to break path to a set first.
    const fieldsToBreakPath = new Set();
    model.forEachFieldDef((fieldDef, channel) => {
        let scaleType;
        if (!standalone_isScaleChannel(channel) || !(scaleType = model.getScaleType(channel))) {
            // Skip if the channel is not a scale channel or does not have a scale
            return;
        }
        const isCountAggregate = standalone_isCountingAggregateOp(fieldDef.aggregate);
        const invalidDataMode = standalone_getScaleInvalidDataMode({
            scaleChannel: channel,
            markDef,
            config,
            scaleType,
            isCountAggregate
        });
        if (standalone_shouldBreakPath(invalidDataMode)) {
            const field = model.vgField(channel, { expr: 'datum', binSuffix: model.stack?.impute ? 'mid' : undefined });
            if (field) {
                fieldsToBreakPath.add(field);
            }
        }
    });
    // If the set is not empty, return a defined signal.
    if (fieldsToBreakPath.size > 0) {
        const signal = [...fieldsToBreakPath].map(field => standalone_fieldValidPredicate(field, true)).join(' && ');
        return { defined: { signal } };
    }
    return undefined;
}
function standalone_valueIfDefined(prop, value) {
    if (value !== undefined) {
        return { [prop]: standalone_signalOrValueRef(value) };
    }
    return undefined;
}
//# sourceMappingURL=defined.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/encode/index.js










//# sourceMappingURL=index.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/nearest.js



const standalone_VORONOI = 'voronoi';
const standalone_nearest = {
    defined: selCmpt => {
        return selCmpt.type === 'point' && selCmpt.nearest;
    },
    parse: (model, selCmpt) => {
        // Scope selection events to the voronoi mark to prevent capturing
        // events that occur on the group mark (https://github.com/vega/vega/issues/2112).
        if (selCmpt.events) {
            for (const s of selCmpt.events) {
                s.markname = model.getName(standalone_VORONOI);
            }
        }
    },
    marks: (model, selCmpt, marks) => {
        const { x, y } = selCmpt.project.hasChannel;
        const markType = model.mark;
        if (standalone_isPathMark(markType)) {
            standalone_log_warn(standalone_nearestNotSupportForContinuous(markType));
            return marks;
        }
        const cellDef = {
            name: model.getName(standalone_VORONOI),
            type: 'path',
            interactive: true,
            from: { data: model.getName('marks') },
            encode: {
                update: {
                    fill: { value: 'transparent' },
                    strokeWidth: { value: 0.35 },
                    stroke: { value: 'transparent' },
                    isVoronoi: { value: true },
                    ...standalone_tooltip(model, { reactiveGeom: true })
                }
            },
            transform: [
                {
                    type: 'voronoi',
                    x: { expr: x || !y ? 'datum.datum.x || 0' : '0' },
                    y: { expr: y || !x ? 'datum.datum.y || 0' : '0' },
                    size: [model.getSizeSignalRef('width'), model.getSizeSignalRef('height')]
                }
            ]
        };
        let index = 0;
        let exists = false;
        marks.forEach((mark, i) => {
            const name = mark.name ?? '';
            if (name === model.component.mark[0].name) {
                index = i;
            }
            else if (name.includes(standalone_VORONOI)) {
                exists = true;
            }
        });
        if (!exists) {
            marks.splice(index + 1, 0, cellDef);
        }
        return marks;
    }
};
/* harmony default export */ const standalone_selection_nearest = (standalone_nearest);
//# sourceMappingURL=nearest.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/inputs.js







const standalone_inputBindings = {
    defined: selCmpt => {
        return (selCmpt.type === 'point' &&
            selCmpt.resolve === 'global' &&
            selCmpt.bind &&
            selCmpt.bind !== 'scales' &&
            !standalone_isLegendBinding(selCmpt.bind));
    },
    parse: (model, selCmpt, selDef) => standalone_disableDirectManipulation(selCmpt, selDef),
    topLevelSignals: (model, selCmpt, signals) => {
        const name = selCmpt.name;
        const proj = selCmpt.project;
        const bind = selCmpt.bind;
        const init = selCmpt.init && selCmpt.init[0]; // Can only exist on single selections (one initial value).
        const datum = standalone_selection_nearest.defined(selCmpt) ? '(item().isVoronoi ? datum.datum : datum)' : 'datum';
        proj.items.forEach((p, i) => {
            const sgname = standalone_varName(`${name}_${p.field}`);
            const hasSignal = signals.filter(s => s.name === sgname);
            if (!hasSignal.length) {
                signals.unshift({
                    name: sgname,
                    ...(init ? { init: standalone_assembleInit(init[i]) } : { value: null }),
                    on: selCmpt.events
                        ? [
                            {
                                events: selCmpt.events,
                                update: `datum && item().mark.marktype !== 'group' ? ${datum}[${standalone_$(p.field)}] : null`
                            }
                        ]
                        : [],
                    bind: bind[p.field] ?? bind[p.channel] ?? bind
                });
            }
        });
        return signals;
    },
    signals: (model, selCmpt, signals) => {
        const name = selCmpt.name;
        const proj = selCmpt.project;
        const signal = signals.find(s => s.name === name + standalone_TUPLE);
        const fields = name + standalone_TUPLE_FIELDS;
        const values = proj.items.map(p => standalone_varName(`${name}_${p.field}`));
        const valid = values.map(v => `${v} !== null`).join(' && ');
        if (values.length) {
            signal.update = `${valid} ? {fields: ${fields}, values: [${values.join(', ')}]} : null`;
        }
        delete signal.value;
        delete signal.on;
        return signals;
    }
};
/* harmony default export */ const standalone_inputs = (standalone_inputBindings);
//# sourceMappingURL=inputs.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/toggle.js

const standalone_TOGGLE = '_toggle';
const standalone_toggle = {
    defined: selCmpt => {
        return selCmpt.type === 'point' && !standalone_isTimerSelection(selCmpt) && !!selCmpt.toggle;
    },
    signals: (model, selCmpt, signals) => {
        return signals.concat({
            name: selCmpt.name + standalone_TOGGLE,
            value: false,
            on: [{ events: selCmpt.events, update: selCmpt.toggle }]
        });
    },
    modifyExpr: (model, selCmpt) => {
        const tpl = selCmpt.name + standalone_TUPLE;
        const signal = selCmpt.name + standalone_TOGGLE;
        return (`${signal} ? null : ${tpl}, ` +
            (selCmpt.resolve === 'global' ? `${signal} ? null : true, ` : `${signal} ? null : {unit: ${standalone_unitName(model)}}, `) +
            `${signal} ? ${tpl} : null`);
    }
};
/* harmony default export */ const standalone_selection_toggle = (standalone_toggle);
//# sourceMappingURL=toggle.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/clear.js






const standalone_clear = {
    defined: selCmpt => {
        return selCmpt.clear !== undefined && selCmpt.clear !== false && !standalone_isTimerSelection(selCmpt);
    },
    parse: (model, selCmpt) => {
        if (selCmpt.clear) {
            selCmpt.clear = standalone_vega_util_module_isString(selCmpt.clear) ? standalone_eventSelector(selCmpt.clear, 'view') : selCmpt.clear;
        }
    },
    topLevelSignals: (model, selCmpt, signals) => {
        if (standalone_inputs.defined(selCmpt)) {
            for (const proj of selCmpt.project.items) {
                const idx = signals.findIndex(n => n.name === standalone_varName(`${selCmpt.name}_${proj.field}`));
                if (idx !== -1) {
                    signals[idx].on.push({ events: selCmpt.clear, update: 'null' });
                }
            }
        }
        return signals;
    },
    signals: (model, selCmpt, signals) => {
        function addClear(idx, update) {
            if (idx !== -1 && signals[idx].on) {
                signals[idx].on.push({ events: selCmpt.clear, update });
            }
        }
        // Be as minimalist as possible when adding clear triggers to minimize dataflow execution.
        if (selCmpt.type === 'interval') {
            for (const proj of selCmpt.project.items) {
                const vIdx = signals.findIndex(n => n.name === proj.signals.visual);
                addClear(vIdx, '[0, 0]');
                if (vIdx === -1) {
                    const dIdx = signals.findIndex(n => n.name === proj.signals.data);
                    addClear(dIdx, 'null');
                }
            }
        }
        else {
            let tIdx = signals.findIndex(n => n.name === selCmpt.name + standalone_TUPLE);
            addClear(tIdx, 'null');
            if (standalone_selection_toggle.defined(selCmpt)) {
                tIdx = signals.findIndex(n => n.name === selCmpt.name + standalone_TOGGLE);
                addClear(tIdx, 'false');
            }
        }
        return signals;
    }
};
/* harmony default export */ const standalone_selection_clear = (standalone_clear);
//# sourceMappingURL=clear.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/legends.js









const standalone_legendBindings = {
    defined: selCmpt => {
        const spec = selCmpt.resolve === 'global' && selCmpt.bind && standalone_isLegendBinding(selCmpt.bind);
        const projLen = selCmpt.project.items.length === 1 && selCmpt.project.items[0].field !== standalone_SELECTION_ID;
        if (spec && !projLen) {
            standalone_log_warn(standalone_LEGEND_BINDINGS_MUST_HAVE_PROJECTION);
        }
        return spec && projLen;
    },
    parse: (model, selCmpt, selDef) => {
        // Allow legend items to be toggleable by default even though direct manipulation is disabled.
        const selDef_ = standalone_duplicate(selDef);
        selDef_.select = standalone_vega_util_module_isString(selDef_.select)
            ? { type: selDef_.select, toggle: selCmpt.toggle }
            : { ...selDef_.select, toggle: selCmpt.toggle };
        standalone_disableDirectManipulation(selCmpt, selDef_);
        if (standalone_vega_util_module_isObject(selDef.select) && (selDef.select.on || selDef.select.clear)) {
            const legendFilter = 'event.item && indexof(event.item.mark.role, "legend") < 0';
            for (const evt of selCmpt.events) {
                evt.filter = standalone_array(evt.filter ?? []);
                if (!evt.filter.includes(legendFilter)) {
                    evt.filter.push(legendFilter);
                }
            }
        }
        const evt = standalone_isLegendStreamBinding(selCmpt.bind) ? selCmpt.bind.legend : 'click';
        const stream = standalone_vega_util_module_isString(evt) ? standalone_eventSelector(evt, 'view') : standalone_array(evt);
        selCmpt.bind = { legend: { merge: stream } };
    },
    topLevelSignals: (model, selCmpt, signals) => {
        const selName = selCmpt.name;
        const stream = standalone_isLegendStreamBinding(selCmpt.bind) && selCmpt.bind.legend;
        const markName = (name) => (s) => {
            const ds = standalone_duplicate(s);
            ds.markname = name;
            return ds;
        };
        for (const proj of selCmpt.project.items) {
            if (!proj.hasLegend)
                continue;
            const prefix = `${standalone_varName(proj.field)}_legend`;
            const sgName = `${selName}_${prefix}`;
            const hasSignal = signals.filter(s => s.name === sgName);
            if (hasSignal.length === 0) {
                const events = stream.merge
                    .map(markName(`${prefix}_symbols`))
                    .concat(stream.merge.map(markName(`${prefix}_labels`)))
                    .concat(stream.merge.map(markName(`${prefix}_entries`)));
                signals.unshift({
                    name: sgName,
                    ...(!selCmpt.init ? { value: null } : {}),
                    on: [
                        // Legend entries do not store values, so we need to walk the scenegraph to the symbol datum.
                        {
                            events,
                            update: 'isDefined(datum.value) ? datum.value : item().items[0].items[0].datum.value',
                            force: true
                        },
                        { events: stream.merge, update: `!event.item || !datum ? null : ${sgName}`, force: true }
                    ]
                });
            }
        }
        return signals;
    },
    signals: (model, selCmpt, signals) => {
        const name = selCmpt.name;
        const proj = selCmpt.project;
        const tuple = signals.find(s => s.name === name + standalone_TUPLE);
        const fields = name + standalone_TUPLE_FIELDS;
        const values = proj.items.filter(p => p.hasLegend).map(p => standalone_varName(`${name}_${standalone_varName(p.field)}_legend`));
        const valid = values.map(v => `${v} !== null`).join(' && ');
        const update = `${valid} ? {fields: ${fields}, values: [${values.join(', ')}]} : null`;
        if (selCmpt.events && values.length > 0) {
            tuple.on.push({
                events: values.map(signal => ({ signal })),
                update
            });
        }
        else if (values.length > 0) {
            tuple.update = update;
            delete tuple.value;
            delete tuple.on;
        }
        const toggle = signals.find(s => s.name === name + standalone_TOGGLE);
        const events = standalone_isLegendStreamBinding(selCmpt.bind) && selCmpt.bind.legend;
        if (toggle) {
            if (!selCmpt.events)
                toggle.on[0].events = events;
            else
                toggle.on.push({ ...toggle.on[0], events });
        }
        return signals;
    }
};
/* harmony default export */ const standalone_legends = (standalone_legendBindings);
function standalone_parseInteractiveLegend(model, channel, legendCmpt) {
    const field = model.fieldDef(channel)?.field;
    for (const selCmpt of standalone_vals(model.component.selection ?? {})) {
        const proj = selCmpt.project.hasField[field] ?? selCmpt.project.hasChannel[channel];
        if (proj && standalone_legendBindings.defined(selCmpt)) {
            const legendSelections = legendCmpt.get('selections') ?? [];
            legendSelections.push(selCmpt.name);
            legendCmpt.set('selections', legendSelections, false);
            proj.hasLegend = true;
        }
    }
}
//# sourceMappingURL=legends.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/translate.js




const standalone_ANCHOR = '_translate_anchor';
const standalone_DELTA = '_translate_delta';
const standalone_translate_translate = {
    defined: selCmpt => {
        return selCmpt.type === 'interval' && selCmpt.translate;
    },
    signals: (model, selCmpt, signals) => {
        const name = selCmpt.name;
        const boundScales = standalone_selection_scales.defined(selCmpt);
        const anchor = name + standalone_ANCHOR;
        const { x, y } = selCmpt.project.hasChannel;
        let events = standalone_eventSelector(selCmpt.translate, 'scope');
        if (!boundScales) {
            events = events.map(e => ((e.between[0].markname = name + standalone_BRUSH), e));
        }
        signals.push({
            name: anchor,
            value: {},
            on: [
                {
                    events: events.map(e => e.between[0]),
                    update: '{x: x(unit), y: y(unit)' +
                        (x !== undefined ? `, extent_x: ${boundScales ? standalone_scales_domain(model, standalone_channel_X) : `slice(${x.signals.visual})`}` : '') +
                        (y !== undefined ? `, extent_y: ${boundScales ? standalone_scales_domain(model, standalone_channel_Y) : `slice(${y.signals.visual})`}` : '') +
                        '}'
                }
            ]
        }, {
            name: name + standalone_DELTA,
            value: {},
            on: [
                {
                    events,
                    update: `{x: ${anchor}.x - x(unit), y: ${anchor}.y - y(unit)}`
                }
            ]
        });
        if (x !== undefined) {
            standalone_onDelta(model, selCmpt, x, 'width', signals);
        }
        if (y !== undefined) {
            standalone_onDelta(model, selCmpt, y, 'height', signals);
        }
        return signals;
    }
};
/* harmony default export */ const standalone_selection_translate = (standalone_translate_translate);
function standalone_onDelta(model, selCmpt, proj, size, signals) {
    const name = selCmpt.name;
    const anchor = name + standalone_ANCHOR;
    const delta = name + standalone_DELTA;
    const channel = proj.channel;
    const boundScales = standalone_selection_scales.defined(selCmpt);
    const signal = signals.find(s => s.name === proj.signals[boundScales ? 'data' : 'visual']);
    const sizeSg = model.getSizeSignalRef(size).signal;
    const scaleCmpt = model.getScaleComponent(channel);
    const scaleType = scaleCmpt && scaleCmpt.get('type');
    const reversed = scaleCmpt && scaleCmpt.get('reverse'); // scale parsing sets this flag for fieldDef.sort
    const sign = !boundScales ? '' : channel === standalone_channel_X ? (reversed ? '' : '-') : reversed ? '-' : '';
    const extent = `${anchor}.extent_${channel}`;
    const offset = `${sign}${delta}.${channel} / ${boundScales ? `${sizeSg}` : `span(${extent})`}`;
    const panFn = !boundScales || !scaleCmpt
        ? 'panLinear'
        : scaleType === 'log'
            ? 'panLog'
            : scaleType === 'symlog'
                ? 'panSymlog'
                : scaleType === 'pow'
                    ? 'panPow'
                    : 'panLinear';
    const arg = !boundScales
        ? ''
        : scaleType === 'pow'
            ? `, ${scaleCmpt.get('exponent') ?? 1}`
            : scaleType === 'symlog'
                ? `, ${scaleCmpt.get('constant') ?? 1}`
                : '';
    const update = `${panFn}(${extent}, ${offset}${arg})`;
    signal.on.push({
        events: { signal: delta },
        update: boundScales ? update : `clampRange(${update}, 0, ${sizeSg})`
    });
}
//# sourceMappingURL=translate.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/zoom.js





const standalone_zoom_ANCHOR = '_zoom_anchor';
const standalone_zoom_DELTA = '_zoom_delta';
const standalone_zoom_zoom = {
    defined: selCmpt => {
        return selCmpt.type === 'interval' && selCmpt.zoom;
    },
    signals: (model, selCmpt, signals) => {
        const name = selCmpt.name;
        const boundScales = standalone_selection_scales.defined(selCmpt);
        const delta = name + standalone_zoom_DELTA;
        const { x, y } = selCmpt.project.hasChannel;
        const sx = standalone_$(model.scaleName(standalone_channel_X));
        const sy = standalone_$(model.scaleName(standalone_channel_Y));
        let events = standalone_eventSelector(selCmpt.zoom, 'scope');
        if (!boundScales) {
            events = events.map(e => ((e.markname = name + standalone_BRUSH), e));
        }
        signals.push({
            name: name + standalone_zoom_ANCHOR,
            on: [
                {
                    events,
                    update: !boundScales
                        ? `{x: x(unit), y: y(unit)}`
                        : '{' +
                            [sx ? `x: invert(${sx}, x(unit))` : '', sy ? `y: invert(${sy}, y(unit))` : '']
                                .filter(expr => expr)
                                .join(', ') +
                            '}'
                }
            ]
        }, {
            name: delta,
            on: [
                {
                    events,
                    force: true,
                    update: 'pow(1.001, event.deltaY * pow(16, event.deltaMode))'
                }
            ]
        });
        if (x !== undefined) {
            standalone_zoom_onDelta(model, selCmpt, x, 'width', signals);
        }
        if (y !== undefined) {
            standalone_zoom_onDelta(model, selCmpt, y, 'height', signals);
        }
        return signals;
    }
};
/* harmony default export */ const standalone_selection_zoom = (standalone_zoom_zoom);
function standalone_zoom_onDelta(model, selCmpt, proj, size, signals) {
    const name = selCmpt.name;
    const channel = proj.channel;
    const boundScales = standalone_selection_scales.defined(selCmpt);
    const signal = signals.find(s => s.name === proj.signals[boundScales ? 'data' : 'visual']);
    const sizeSg = model.getSizeSignalRef(size).signal;
    const scaleCmpt = model.getScaleComponent(channel);
    const scaleType = scaleCmpt && scaleCmpt.get('type');
    const base = boundScales ? standalone_scales_domain(model, channel) : signal.name;
    const delta = name + standalone_zoom_DELTA;
    const anchor = `${name}${standalone_zoom_ANCHOR}.${channel}`;
    const zoomFn = !boundScales || !scaleCmpt
        ? 'zoomLinear'
        : scaleType === 'log'
            ? 'zoomLog'
            : scaleType === 'symlog'
                ? 'zoomSymlog'
                : scaleType === 'pow'
                    ? 'zoomPow'
                    : 'zoomLinear';
    const arg = !boundScales
        ? ''
        : scaleType === 'pow'
            ? `, ${scaleCmpt.get('exponent') ?? 1}`
            : scaleType === 'symlog'
                ? `, ${scaleCmpt.get('constant') ?? 1}`
                : '';
    const update = `${zoomFn}(${base}, ${anchor}, ${delta}${arg})`;
    signal.on.push({
        events: { signal: delta },
        update: boundScales ? update : `clampRange(${update}, 0, ${sizeSg})`
    });
}
//# sourceMappingURL=zoom.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/index.js
















const standalone_STORE = '_store';
const standalone_TUPLE = '_tuple';
const standalone_MODIFY = '_modify';
const standalone_SELECTION_DOMAIN = '_selection_domain_';
const standalone_VL_SELECTION_RESOLVE = 'vlSelectionResolve';
// Order matters for parsing and assembly.
const standalone_selectionCompilers = [
    standalone_selection_point,
    standalone_selection_interval,
    standalone_selection_project,
    standalone_selection_toggle,
    // Bindings may disable direct manipulation.
    standalone_inputs,
    standalone_selection_scales,
    standalone_legends,
    standalone_selection_clear,
    standalone_selection_translate,
    standalone_selection_zoom,
    standalone_selection_nearest
];
function standalone_getFacetModel(model) {
    let parent = model.parent;
    while (parent) {
        if (standalone_isFacetModel(parent))
            break;
        parent = parent.parent;
    }
    return parent;
}
function standalone_unitName(model, { escape } = { escape: true }) {
    let name = escape ? standalone_$(model.name) : model.name;
    const facetModel = standalone_getFacetModel(model);
    if (facetModel) {
        const { facet } = facetModel;
        for (const channel of standalone_FACET_CHANNELS) {
            if (facet[channel]) {
                name += ` + '__facet_${channel}_' + (facet[${standalone_$(facetModel.vgField(channel))}])`;
            }
        }
    }
    return name;
}
function standalone_requiresSelectionId(model) {
    return standalone_vals(model.component.selection ?? {}).reduce((identifier, selCmpt) => {
        return identifier || selCmpt.project.hasSelectionId;
    }, false);
}
// Binding a point selection to query widgets or legends disables default direct manipulation interaction.
// A user can choose to re-enable it by explicitly specifying triggering input events.
function standalone_disableDirectManipulation(selCmpt, selDef) {
    if (standalone_vega_util_module_isString(selDef.select) || !selDef.select.on)
        delete selCmpt.events;
    if (standalone_vega_util_module_isString(selDef.select) || !selDef.select.clear)
        delete selCmpt.clear;
    if (standalone_vega_util_module_isString(selDef.select) || !selDef.select.toggle)
        delete selCmpt.toggle;
}
function standalone_isTimerSelection(selCmpt) {
    return selCmpt.events?.find(e => 'type' in e && e.type === 'timer');
}
//# sourceMappingURL=index.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/expressions.js

function standalone_getName(node) {
    const name = [];
    if (node.type === 'Identifier') {
        return [node.name];
    }
    if (node.type === 'Literal') {
        return [node.value];
    }
    if (node.type === 'MemberExpression') {
        name.push(...standalone_getName(node.object));
        name.push(...standalone_getName(node.property));
    }
    return name;
}
function standalone_startsWithDatum(node) {
    if (node.object.type === 'MemberExpression') {
        return standalone_startsWithDatum(node.object);
    }
    return node.object.name === 'datum';
}
function standalone_getDependentFields(expression) {
    const ast = standalone_parser(expression);
    const dependents = new Set();
    // visit is missing in types https://github.com/vega/vega/issues/3298
    ast.visit((node) => {
        if (node.type === 'MemberExpression' && standalone_startsWithDatum(node)) {
            dependents.add(standalone_getName(node).slice(1).join('.'));
        }
    });
    return dependents;
}
//# sourceMappingURL=expressions.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/filter.js




class standalone_FilterNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_FilterNode(null, this.model, standalone_duplicate(this.filter));
    }
    constructor(parent, model, filter) {
        super(parent);
        this.model = model;
        this.filter = filter;
        // TODO: refactor this to not take a node and
        // then add a static function makeFromOperand and make the constructor take only an expression
        this.expr = standalone_predicate_expression(this.model, this.filter, this);
        this._dependentFields = standalone_getDependentFields(this.expr);
    }
    dependentFields() {
        return this._dependentFields;
    }
    producedFields() {
        return new Set(); // filter does not produce any new fields
    }
    assemble() {
        return {
            type: 'filter',
            expr: this.expr
        };
    }
    hash() {
        return `Filter ${this.expr}`;
    }
}
//# sourceMappingURL=filter.js.map
;// ../../node_modules/vega-lite/build/src/compile/selection/parse.js









function standalone_parseUnitSelection(model, selDefs) {
    const selCmpts = {};
    const selectionConfig = model.config.selection;
    if (!selDefs || !selDefs.length)
        return selCmpts;
    let nTimerSelections = 0;
    for (const def of selDefs) {
        const name = standalone_varName(def.name);
        const selDef = def.select;
        const type = standalone_vega_util_module_isString(selDef) ? selDef : selDef.type;
        const defaults = standalone_vega_util_module_isObject(selDef) ? standalone_duplicate(selDef) : { type };
        // Set default values from config if a property hasn't been specified,
        // or if it is true. E.g., "translate": true should use the default
        // event handlers for translate. However, true may be a valid value for
        // a property (e.g., "nearest": true).
        const cfg = selectionConfig[type];
        for (const key in cfg) {
            // Project transform applies its defaults.
            if (key === 'fields' || key === 'encodings') {
                continue;
            }
            if (key === 'mark') {
                defaults.mark = { ...cfg.mark, ...defaults.mark };
            }
            if (defaults[key] === undefined || defaults[key] === true) {
                defaults[key] = standalone_duplicate(cfg[key] ?? defaults[key]);
            }
        }
        const selCmpt = (selCmpts[name] = {
            ...defaults,
            name,
            type,
            init: def.value,
            bind: def.bind,
            events: standalone_vega_util_module_isString(defaults.on) ? standalone_eventSelector(defaults.on, 'scope') : standalone_array(standalone_duplicate(defaults.on))
        });
        if (standalone_isTimerSelection(selCmpt)) {
            nTimerSelections++;
            // check for multiple timer selections and ignore all but the first one
            if (nTimerSelections > 1) {
                delete selCmpts[name];
                continue;
            }
        }
        const def_ = standalone_duplicate(def); // defensive copy to prevent compilers from causing side effects
        for (const c of standalone_selectionCompilers) {
            if (c.defined(selCmpt) && c.parse) {
                c.parse(model, selCmpt, def_);
            }
        }
    }
    if (nTimerSelections > 1) {
        // if multiple timer selections were found, issue a warning
        standalone_log_warn(standalone_MULTIPLE_TIMER_ANIMATION_SELECTION);
    }
    return selCmpts;
}
function standalone_parseSelectionPredicate(model, pred, dfnode, datum = 'datum') {
    const name = standalone_vega_util_module_isString(pred) ? pred : pred.param;
    const vname = standalone_varName(name);
    const store = standalone_$(vname + standalone_STORE);
    let selCmpt;
    try {
        selCmpt = model.getSelectionComponent(vname, name);
    }
    catch (e) {
        // If a selection isn't found, treat as a variable parameter and coerce to boolean.
        return `!!${vname}`;
    }
    if (selCmpt.project.timeUnit) {
        const child = dfnode ?? model.component.data.raw;
        const tunode = selCmpt.project.timeUnit.clone();
        if (child.parent) {
            tunode.insertAsParentOf(child);
        }
        else {
            child.parent = tunode;
        }
    }
    const fn = selCmpt.project.hasSelectionId ? 'vlSelectionIdTest(' : 'vlSelectionTest(';
    const resolve = selCmpt.resolve === 'global' ? ')' : `, ${standalone_$(selCmpt.resolve)})`;
    const test = `${fn}${store}, ${datum}${resolve}`;
    const length = `length(data(${store}))`;
    return pred.empty === false ? `${length} && ${test}` : `!${length} || ${test}`;
}
function standalone_parseSelectionExtent(model, name, extent) {
    const vname = standalone_varName(name);
    const encoding = extent.encoding;
    let field = extent.field;
    let selCmpt;
    try {
        selCmpt = model.getSelectionComponent(vname, name);
    }
    catch (e) {
        // If a selection isn't found, treat it as a variable parameter.
        return vname;
    }
    if (!encoding && !field) {
        field = selCmpt.project.items[0].field;
        if (selCmpt.project.items.length > 1) {
            standalone_log_warn(standalone_selectionAsScaleDomainWithoutField(field));
        }
    }
    else if (encoding && !field) {
        const encodings = selCmpt.project.items.filter(p => p.channel === encoding);
        if (!encodings.length || encodings.length > 1) {
            field = selCmpt.project.items[0].field;
            standalone_log_warn(standalone_selectionAsScaleDomainWrongEncodings(encodings, encoding, extent, field));
        }
        else {
            field = encodings[0].field;
        }
    }
    return `${selCmpt.name}[${standalone_$(standalone_replacePathInField(field))}]`;
}
function standalone_materializeSelections(model, main) {
    for (const [selection, selCmpt] of standalone_entries(model.component.selection ?? {})) {
        const lookupName = model.getName(`lookup_${selection}`);
        model.component.data.outputNodes[lookupName] = selCmpt.materialized = new standalone_OutputNode(new standalone_FilterNode(main, model, { param: selection }), lookupName, standalone_DataSourceType.Lookup, model.component.data.outputNodeRefCounts);
    }
}
//# sourceMappingURL=parse.js.map
;// ../../node_modules/vega-lite/build/src/compile/predicate.js




/**
 * Converts a predicate into an expression.
 */
// model is only used for selection filters.
function standalone_predicate_expression(model, filterOp, node) {
    return standalone_logicalExpr(filterOp, (predicate) => {
        if (standalone_vega_util_module_isString(predicate)) {
            return predicate;
        }
        else if (standalone_isSelectionPredicate(predicate)) {
            return standalone_parseSelectionPredicate(model, predicate, node);
        }
        else {
            // Filter Object
            return standalone_fieldFilterExpression(predicate);
        }
    });
}
//# sourceMappingURL=predicate.js.map
;// ../../node_modules/vega-lite/build/src/compile/axis/assemble.js









function standalone_assembleTitle(title, config) {
    if (!title) {
        return undefined;
    }
    if (standalone_vega_util_module_isArray(title) && !standalone_isText(title)) {
        return title.map(fieldDef => standalone_defaultTitle(fieldDef, config)).join(', ');
    }
    return title;
}
function standalone_setAxisEncode(axis, part, vgProp, vgRef) {
    var _a, _b;
    axis.encode ?? (axis.encode = {});
    (_a = axis.encode)[part] ?? (_a[part] = {});
    (_b = axis.encode[part]).update ?? (_b.update = {});
    // TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291
    axis.encode[part].update[vgProp] = vgRef;
}
function standalone_assembleAxis(axisCmpt, kind, config, opt = { header: false }) {
    const { disable, orient, scale, labelExpr, title, zindex, ...axis } = axisCmpt.combine();
    if (disable) {
        return undefined;
    }
    for (const p in axis) {
        const prop = p;
        const propType = standalone_AXIS_PROPERTY_TYPE[prop];
        const propValue = axis[prop];
        if (propType && propType !== kind && propType !== 'both') {
            // Remove properties that are not valid for this kind of axis
            delete axis[prop];
        }
        else if (standalone_isConditionalAxisValue(propValue)) {
            // deal with conditional axis value
            const { condition, ...valueOrSignalRef } = propValue;
            const conditions = standalone_array(condition);
            const propIndex = standalone_CONDITIONAL_AXIS_PROP_INDEX[prop];
            if (propIndex) {
                const { vgProp, part } = propIndex;
                // If there is a corresponding Vega property for the channel,
                // use Vega's custom axis encoding and delete the original axis property to avoid conflicts
                const vgRef = [
                    ...conditions.map(c => {
                        const { test, ...valueOrSignalCRef } = c;
                        return {
                            test: standalone_predicate_expression(null, test),
                            ...valueOrSignalCRef
                        };
                    }),
                    valueOrSignalRef
                ];
                standalone_setAxisEncode(axis, part, vgProp, vgRef);
                delete axis[prop];
            }
            else if (propIndex === null) {
                // If propIndex is null, this means we support conditional axis property by converting the condition to signal instead.
                const signalRef = {
                    signal: conditions
                        .map(c => {
                        const { test, ...valueOrSignalCRef } = c;
                        return `${standalone_predicate_expression(null, test)} ? ${standalone_exprFromValueRefOrSignalRef(valueOrSignalCRef)} : `;
                    })
                        .join('') + standalone_exprFromValueRefOrSignalRef(valueOrSignalRef)
                };
                axis[prop] = signalRef;
            }
        }
        else if (standalone_isSignalRef(propValue)) {
            const propIndex = standalone_CONDITIONAL_AXIS_PROP_INDEX[prop];
            if (propIndex) {
                const { vgProp, part } = propIndex;
                // FIXME: remove as any
                standalone_setAxisEncode(axis, part, vgProp, propValue);
                delete axis[prop];
            } // else do nothing since the property already supports signal
        }
        // Do not pass labelAlign/Baseline = null to Vega since it won't pass the schema
        // Note that we need to use null so the default labelAlign is preserved.
        if (standalone_util_contains(['labelAlign', 'labelBaseline'], prop) && axis[prop] === null) {
            delete axis[prop];
        }
    }
    if (kind === 'grid') {
        if (!axis.grid) {
            return undefined;
        }
        // Remove unnecessary encode block
        if (axis.encode) {
            // Only need to keep encode block for grid
            const { grid } = axis.encode;
            axis.encode = {
                ...(grid ? { grid } : {})
            };
            if (standalone_isEmpty(axis.encode)) {
                delete axis.encode;
            }
        }
        return {
            scale,
            orient,
            ...axis,
            domain: false,
            labels: false,
            aria: false, // always hide grid axis
            // Always set min/maxExtent to 0 to ensure that `config.axis*.minExtent` and `config.axis*.maxExtent`
            // would not affect gridAxis
            maxExtent: 0,
            minExtent: 0,
            ticks: false,
            zindex: standalone_getFirstDefined(zindex, 0) // put grid behind marks by default
        };
    }
    else {
        // kind === 'main'
        if (!opt.header && axisCmpt.mainExtracted) {
            // if mainExtracted has been extracted to a separate facet
            return undefined;
        }
        if (labelExpr !== undefined) {
            let expr = labelExpr;
            if (axis.encode?.labels?.update && standalone_isSignalRef(axis.encode.labels.update.text)) {
                expr = standalone_replaceAll(labelExpr, 'datum.label', axis.encode.labels.update.text.signal);
            }
            standalone_setAxisEncode(axis, 'labels', 'text', { signal: expr });
        }
        if (axis.labelAlign === null) {
            delete axis.labelAlign;
        }
        // Remove unnecessary encode block
        if (axis.encode) {
            for (const part of standalone_AXIS_PARTS) {
                if (!axisCmpt.hasAxisPart(part)) {
                    delete axis.encode[part];
                }
            }
            if (standalone_isEmpty(axis.encode)) {
                delete axis.encode;
            }
        }
        const titleString = standalone_assembleTitle(title, config);
        return {
            scale,
            orient,
            grid: false,
            ...(titleString ? { title: titleString } : {}),
            ...axis,
            ...(config.aria === false ? { aria: false } : {}),
            zindex: standalone_getFirstDefined(zindex, 0) // put axis line above marks by default
        };
    }
}
/**
 * Add axis signals so grid line works correctly
 * (Fix https://github.com/vega/vega-lite/issues/4226)
 */
function standalone_assembleAxisSignals(model) {
    const { axes } = model.component;
    const signals = [];
    for (const channel of standalone_POSITION_SCALE_CHANNELS) {
        if (axes[channel]) {
            for (const axis of axes[channel]) {
                if (!axis.get('disable') && !axis.get('gridScale')) {
                    // If there is x-axis but no y-scale for gridScale, need to set height/width so x-axis can draw the grid with the right height. Same for y-axis and width.
                    const sizeType = channel === 'x' ? 'height' : 'width';
                    const update = model.getSizeSignalRef(sizeType).signal;
                    if (sizeType !== update) {
                        signals.push({
                            name: sizeType,
                            update
                        });
                    }
                }
            }
        }
    }
    return signals;
}
function standalone_assembleAxes(axisComponents, config) {
    const { x = [], y = [] } = axisComponents;
    return [
        ...x.map(a => standalone_assembleAxis(a, 'grid', config)),
        ...y.map(a => standalone_assembleAxis(a, 'grid', config)),
        ...x.map(a => standalone_assembleAxis(a, 'main', config)),
        ...y.map(a => standalone_assembleAxis(a, 'main', config))
    ].filter(a => a); // filter undefined
}
//# sourceMappingURL=assemble.js.map
;// ../../node_modules/vega-lite/build/src/compile/axis/config.js





function standalone_getAxisConfigFromConfigTypes(configTypes, config, channel, orient) {
    // TODO: add special casing to add conditional value based on orient signal
    return Object.assign.apply(null, [
        {},
        ...configTypes.map(configType => {
            if (configType === 'axisOrient') {
                const orient1 = channel === 'x' ? 'bottom' : 'left';
                const orientConfig1 = config[channel === 'x' ? 'axisBottom' : 'axisLeft'] || {};
                const orientConfig2 = config[channel === 'x' ? 'axisTop' : 'axisRight'] || {};
                const props = new Set([...standalone_util_keys(orientConfig1), ...standalone_util_keys(orientConfig2)]);
                const conditionalOrientAxisConfig = {};
                for (const prop of props.values()) {
                    conditionalOrientAxisConfig[prop] = {
                        // orient is surely signal in this case
                        signal: `${orient['signal']} === "${orient1}" ? ${standalone_signalOrStringValue(orientConfig1[prop])} : ${standalone_signalOrStringValue(orientConfig2[prop])}`
                    };
                }
                return conditionalOrientAxisConfig;
            }
            return config[configType];
        })
    ]);
}
function standalone_getAxisConfigs(channel, scaleType, orient, config) {
    const typeBasedConfigTypes = scaleType === 'band'
        ? ['axisDiscrete', 'axisBand']
        : scaleType === 'point'
            ? ['axisDiscrete', 'axisPoint']
            : standalone_isQuantitative(scaleType)
                ? ['axisQuantitative']
                : scaleType === 'time' || scaleType === 'utc'
                    ? ['axisTemporal']
                    : [];
    const axisChannel = channel === 'x' ? 'axisX' : 'axisY';
    const axisOrient = standalone_isSignalRef(orient) ? 'axisOrient' : `axis${standalone_titleCase(orient)}`; // axisTop, axisBottom, ...
    const vlOnlyConfigTypes = [
        // technically Vega does have axisBand, but if we make another separation here,
        // it will further introduce complexity in the code
        ...typeBasedConfigTypes,
        ...typeBasedConfigTypes.map(c => axisChannel + c.substr(4))
    ];
    const vgConfigTypes = ['axis', axisOrient, axisChannel];
    return {
        vlOnlyAxisConfig: standalone_getAxisConfigFromConfigTypes(vlOnlyConfigTypes, config, channel, orient),
        vgAxisConfig: standalone_getAxisConfigFromConfigTypes(vgConfigTypes, config, channel, orient),
        axisConfigStyle: standalone_getAxisConfigStyle([...vgConfigTypes, ...vlOnlyConfigTypes], config)
    };
}
function standalone_getAxisConfigStyle(axisConfigTypes, config) {
    const toMerge = [{}];
    for (const configType of axisConfigTypes) {
        // TODO: add special casing to add conditional value based on orient signal
        let style = config[configType]?.style;
        if (style) {
            style = standalone_array(style);
            for (const s of style) {
                toMerge.push(config.style[s]);
            }
        }
    }
    return Object.assign.apply(null, toMerge);
}
function standalone_getAxisConfig(property, styleConfigIndex, style, axisConfigs = {}) {
    const styleConfig = standalone_getStyleConfig(property, style, styleConfigIndex);
    if (styleConfig !== undefined) {
        return {
            configFrom: 'style',
            configValue: styleConfig
        };
    }
    for (const configFrom of ['vlOnlyAxisConfig', 'vgAxisConfig', 'axisConfigStyle']) {
        if (axisConfigs[configFrom]?.[property] !== undefined) {
            return { configFrom, configValue: axisConfigs[configFrom][property] };
        }
    }
    return {};
}
//# sourceMappingURL=config.js.map
;// ../../node_modules/vega-lite/build/src/compile/axis/properties.js











const standalone_axisRules = {
    scale: ({ model, channel }) => model.scaleName(channel),
    format: ({ format }) => format, // we already calculate this in parse
    formatType: ({ formatType }) => formatType, // we already calculate this in parse
    grid: ({ fieldOrDatumDef, axis, scaleType }) => axis.grid ?? standalone_defaultGrid(scaleType, fieldOrDatumDef),
    gridScale: ({ model, channel }) => standalone_gridScale(model, channel),
    labelAlign: ({ axis, labelAngle, orient, channel }) => axis.labelAlign || standalone_defaultLabelAlign(labelAngle, orient, channel),
    labelAngle: ({ labelAngle }) => labelAngle, // we already calculate this in parse
    labelBaseline: ({ axis, labelAngle, orient, channel }) => axis.labelBaseline || standalone_defaultLabelBaseline(labelAngle, orient, channel),
    labelFlush: ({ axis, fieldOrDatumDef, channel }) => axis.labelFlush ?? standalone_defaultLabelFlush(fieldOrDatumDef.type, channel),
    labelOverlap: ({ axis, fieldOrDatumDef, scaleType }) => axis.labelOverlap ??
        standalone_defaultLabelOverlap(fieldOrDatumDef.type, scaleType, standalone_isFieldDef(fieldOrDatumDef) && !!fieldOrDatumDef.timeUnit, standalone_isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : undefined),
    // we already calculate orient in parse
    orient: ({ orient }) => orient, // Need to cast until Vega supports signal
    tickCount: ({ channel, model, axis, fieldOrDatumDef, scaleType }) => {
        const sizeType = channel === 'x' ? 'width' : channel === 'y' ? 'height' : undefined;
        const size = sizeType ? model.getSizeSignalRef(sizeType) : undefined;
        return axis.tickCount ?? standalone_defaultTickCount({ fieldOrDatumDef, scaleType, size, values: axis.values });
    },
    tickMinStep: standalone_defaultTickMinStep,
    title: ({ axis, model, channel }) => {
        if (axis.title !== undefined) {
            return axis.title;
        }
        const fieldDefTitle = standalone_getFieldDefTitle(model, channel);
        if (fieldDefTitle !== undefined) {
            return fieldDefTitle;
        }
        const fieldDef = model.typedFieldDef(channel);
        const channel2 = channel === 'x' ? 'x2' : 'y2';
        const fieldDef2 = model.fieldDef(channel2);
        // If title not specified, store base parts of fieldDef (and fieldDef2 if exists)
        return standalone_mergeTitleFieldDefs(fieldDef ? [standalone_toFieldDefBase(fieldDef)] : [], standalone_isFieldDef(fieldDef2) ? [standalone_toFieldDefBase(fieldDef2)] : []);
    },
    values: ({ axis, fieldOrDatumDef }) => standalone_properties_values(axis, fieldOrDatumDef),
    zindex: ({ axis, fieldOrDatumDef, mark }) => axis.zindex ?? standalone_defaultZindex(mark, fieldOrDatumDef)
};
// TODO: we need to refactor this method after we take care of config refactoring
/**
 * Default rules for whether to show a grid should be shown for a channel.
 * If `grid` is unspecified, the default value is `true` for ordinal scales that are not binned
 */
function standalone_defaultGrid(scaleType, fieldDef) {
    return !standalone_hasDiscreteDomain(scaleType) && standalone_isFieldDef(fieldDef) && !standalone_isBinning(fieldDef?.bin) && !standalone_isBinned(fieldDef?.bin);
}
function standalone_gridScale(model, channel) {
    const gridChannel = channel === 'x' ? 'y' : 'x';
    if (model.getScaleComponent(gridChannel)) {
        return model.scaleName(gridChannel);
    }
    return undefined;
}
function standalone_getLabelAngle(fieldOrDatumDef, axis, channel, styleConfig, axisConfigs) {
    const labelAngle = axis?.labelAngle;
    // try axis value
    if (labelAngle !== undefined) {
        return standalone_isSignalRef(labelAngle) ? labelAngle : standalone_normalizeAngle(labelAngle);
    }
    else {
        // try axis config value
        const { configValue: angle } = standalone_getAxisConfig('labelAngle', styleConfig, axis?.style, axisConfigs);
        if (angle !== undefined) {
            return standalone_normalizeAngle(angle);
        }
        else {
            // get default value
            if (channel === standalone_channel_X &&
                standalone_util_contains([standalone_NOMINAL, standalone_ORDINAL], fieldOrDatumDef.type) &&
                !(standalone_isFieldDef(fieldOrDatumDef) && fieldOrDatumDef.timeUnit)) {
                return 270;
            }
            // no default
            return undefined;
        }
    }
}
function standalone_normalizeAngleExpr(angle) {
    return `(((${angle.signal} % 360) + 360) % 360)`;
}
function standalone_defaultLabelBaseline(angle, orient, channel, alwaysIncludeMiddle) {
    if (angle !== undefined) {
        if (channel === 'x') {
            if (standalone_isSignalRef(angle)) {
                const a = standalone_normalizeAngleExpr(angle);
                const orientIsTop = standalone_isSignalRef(orient) ? `(${orient.signal} === "top")` : orient === 'top';
                return {
                    signal: `(45 < ${a} && ${a} < 135) || (225 < ${a} && ${a} < 315) ? "middle" :` +
                        `(${a} <= 45 || 315 <= ${a}) === ${orientIsTop} ? "bottom" : "top"`
                };
            }
            if ((45 < angle && angle < 135) || (225 < angle && angle < 315)) {
                return 'middle';
            }
            if (standalone_isSignalRef(orient)) {
                const op = angle <= 45 || 315 <= angle ? '===' : '!==';
                return { signal: `${orient.signal} ${op} "top" ? "bottom" : "top"` };
            }
            return (angle <= 45 || 315 <= angle) === (orient === 'top') ? 'bottom' : 'top';
        }
        else {
            if (standalone_isSignalRef(angle)) {
                const a = standalone_normalizeAngleExpr(angle);
                const orientIsLeft = standalone_isSignalRef(orient) ? `(${orient.signal} === "left")` : orient === 'left';
                const middle = alwaysIncludeMiddle ? '"middle"' : 'null';
                return {
                    signal: `${a} <= 45 || 315 <= ${a} || (135 <= ${a} && ${a} <= 225) ? ${middle} : (45 <= ${a} && ${a} <= 135) === ${orientIsLeft} ? "top" : "bottom"`
                };
            }
            if (angle <= 45 || 315 <= angle || (135 <= angle && angle <= 225)) {
                return alwaysIncludeMiddle ? 'middle' : null;
            }
            if (standalone_isSignalRef(orient)) {
                const op = 45 <= angle && angle <= 135 ? '===' : '!==';
                return { signal: `${orient.signal} ${op} "left" ? "top" : "bottom"` };
            }
            return (45 <= angle && angle <= 135) === (orient === 'left') ? 'top' : 'bottom';
        }
    }
    return undefined;
}
function standalone_defaultLabelAlign(angle, orient, channel) {
    if (angle === undefined) {
        return undefined;
    }
    const isX = channel === 'x';
    const startAngle = isX ? 0 : 90;
    const mainOrient = isX ? 'bottom' : 'left';
    if (standalone_isSignalRef(angle)) {
        const a = standalone_normalizeAngleExpr(angle);
        const orientIsMain = standalone_isSignalRef(orient) ? `(${orient.signal} === "${mainOrient}")` : orient === mainOrient;
        return {
            signal: `(${startAngle ? `(${a} + 90)` : a} % 180 === 0) ? ${isX ? null : '"center"'} :` +
                `(${startAngle} < ${a} && ${a} < ${180 + startAngle}) === ${orientIsMain} ? "left" : "right"`
        };
    }
    if ((angle + startAngle) % 180 === 0) {
        // For bottom, use default label align so label flush still works
        return isX ? null : 'center';
    }
    if (standalone_isSignalRef(orient)) {
        const op = startAngle < angle && angle < 180 + startAngle ? '===' : '!==';
        const orientIsMain = `${orient.signal} ${op} "${mainOrient}"`;
        return {
            signal: `${orientIsMain} ? "left" : "right"`
        };
    }
    if ((startAngle < angle && angle < 180 + startAngle) === (orient === mainOrient)) {
        return 'left';
    }
    return 'right';
}
function standalone_defaultLabelFlush(type, channel) {
    if (channel === 'x' && standalone_util_contains(['quantitative', 'temporal'], type)) {
        return true;
    }
    return undefined;
}
function standalone_defaultLabelOverlap(type, scaleType, hasTimeUnit, sort) {
    // do not prevent overlap for nominal data because there is no way to infer what the missing labels are
    if ((hasTimeUnit && !standalone_vega_util_module_isObject(sort)) || (type !== 'nominal' && type !== 'ordinal')) {
        if (scaleType === 'log' || scaleType === 'symlog') {
            return 'greedy';
        }
        return true;
    }
    return undefined;
}
function standalone_defaultOrient(channel) {
    return channel === 'x' ? 'bottom' : 'left';
}
function standalone_defaultTickCount({ fieldOrDatumDef, scaleType, size, values: vals }) {
    if (!vals && !standalone_hasDiscreteDomain(scaleType) && scaleType !== 'log') {
        if (standalone_isFieldDef(fieldOrDatumDef)) {
            if (standalone_isBinning(fieldOrDatumDef.bin)) {
                // for binned data, we don't want more ticks than maxbins
                return { signal: `ceil(${size.signal}/10)` };
            }
            if (fieldOrDatumDef.timeUnit &&
                standalone_util_contains(['month', 'hours', 'day', 'quarter'], standalone_normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit)) {
                return undefined;
            }
        }
        return { signal: `ceil(${size.signal}/40)` };
    }
    return undefined;
}
function standalone_defaultTickMinStep({ format, fieldOrDatumDef }) {
    if (format === 'd') {
        return 1;
    }
    if (standalone_isFieldDef(fieldOrDatumDef)) {
        const { timeUnit } = fieldOrDatumDef;
        if (timeUnit) {
            const signal = standalone_durationExpr(timeUnit);
            if (signal) {
                return { signal };
            }
        }
    }
    return undefined;
}
function standalone_getFieldDefTitle(model, channel) {
    const channel2 = channel === 'x' ? 'x2' : 'y2';
    const fieldDef = model.fieldDef(channel);
    const fieldDef2 = model.fieldDef(channel2);
    const title1 = fieldDef ? fieldDef.title : undefined;
    const title2 = fieldDef2 ? fieldDef2.title : undefined;
    if (title1 && title2) {
        return standalone_mergeTitle(title1, title2);
    }
    else if (title1) {
        return title1;
    }
    else if (title2) {
        return title2;
    }
    else if (title1 !== undefined) {
        // falsy value to disable config
        return title1;
    }
    else if (title2 !== undefined) {
        // falsy value to disable config
        return title2;
    }
    return undefined;
}
function standalone_properties_values(axis, fieldOrDatumDef) {
    const vals = axis.values;
    if (standalone_vega_util_module_isArray(vals)) {
        return standalone_valueArray(fieldOrDatumDef, vals);
    }
    else if (standalone_isSignalRef(vals)) {
        return vals;
    }
    return undefined;
}
function standalone_defaultZindex(mark, fieldDef) {
    if (mark === 'rect' && standalone_channeldef_isDiscrete(fieldDef)) {
        return 1;
    }
    return 0;
}
//# sourceMappingURL=properties.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/calculate.js






class standalone_CalculateNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_CalculateNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
        this._dependentFields = standalone_getDependentFields(this.transform.calculate);
    }
    static parseAllForSortIndex(parent, model) {
        // get all the encoding with sort fields from model
        model.forEachFieldDef((fieldDef, channel) => {
            if (!standalone_isScaleFieldDef(fieldDef)) {
                return;
            }
            if (standalone_isSortArray(fieldDef.sort)) {
                const { field, timeUnit } = fieldDef;
                const sort = fieldDef.sort;
                // generate `datum["a"] === val0 ? 0 : datum["a"] === val1 ? 1 : ... : n` via FieldEqualPredicate
                const calculate = sort
                    .map((sortValue, i) => {
                    return `${standalone_fieldFilterExpression({ field, timeUnit, equal: sortValue })} ? ${i} : `;
                })
                    .join('') + sort.length;
                parent = new standalone_CalculateNode(parent, {
                    calculate,
                    as: standalone_sortArrayIndexField(fieldDef, channel, { forAs: true })
                });
            }
        });
        return parent;
    }
    producedFields() {
        return new Set([this.transform.as]);
    }
    dependentFields() {
        return this._dependentFields;
    }
    assemble() {
        return {
            type: 'formula',
            expr: this.transform.calculate,
            as: this.transform.as
        };
    }
    hash() {
        return `Calculate ${standalone_util_hash(this.transform)}`;
    }
}
function standalone_sortArrayIndexField(fieldDef, channel, opt) {
    return standalone_vgField(fieldDef, { prefix: channel, suffix: 'sort_index', ...opt });
}
//# sourceMappingURL=calculate.js.map
;// ../../node_modules/vega-lite/build/src/compile/header/common.js

/**
 * Get header channel, which can be different from facet channel when orient is specified or when the facet channel is facet.
 */
function standalone_getHeaderChannel(channel, orient) {
    if (standalone_util_contains(['top', 'bottom'], orient)) {
        return 'column';
    }
    else if (standalone_util_contains(['left', 'right'], orient)) {
        return 'row';
    }
    return channel === 'row' ? 'row' : 'column';
}
function standalone_getHeaderProperty(prop, header, config, channel) {
    const headerSpecificConfig = channel === 'row' ? config.headerRow : channel === 'column' ? config.headerColumn : config.headerFacet;
    return standalone_getFirstDefined((header || {})[prop], headerSpecificConfig[prop], config.header[prop]);
}
function standalone_getHeaderProperties(properties, header, config, channel) {
    const props = {};
    for (const prop of properties) {
        const value = standalone_getHeaderProperty(prop, header || {}, config, channel);
        if (value !== undefined) {
            props[prop] = value;
        }
    }
    return props;
}
//# sourceMappingURL=common.js.map
;// ../../node_modules/vega-lite/build/src/compile/header/component.js
const standalone_HEADER_CHANNELS = ['row', 'column'];
const standalone_HEADER_TYPES = ['header', 'footer'];
//# sourceMappingURL=component.js.map
;// ../../node_modules/vega-lite/build/src/compile/header/assemble.js
/**
 * Utility for generating row / column headers
 */













// TODO: rename to assembleHeaderTitleGroup
function standalone_assembleTitleGroup(model, channel) {
    const title = model.component.layoutHeaders[channel].title;
    const config = model.config ? model.config : undefined;
    const facetFieldDef = model.component.layoutHeaders[channel].facetFieldDef
        ? model.component.layoutHeaders[channel].facetFieldDef
        : undefined;
    const { titleAnchor, titleAngle: ta, titleOrient } = standalone_getHeaderProperties(['titleAnchor', 'titleAngle', 'titleOrient'], facetFieldDef.header, config, channel);
    const headerChannel = standalone_getHeaderChannel(channel, titleOrient);
    const titleAngle = standalone_normalizeAngle(ta);
    return {
        name: `${channel}-title`,
        type: 'group',
        role: `${headerChannel}-title`,
        title: {
            text: title,
            ...(channel === 'row' ? { orient: 'left' } : {}),
            style: 'guide-title',
            ...standalone_defaultHeaderGuideBaseline(titleAngle, headerChannel),
            ...standalone_defaultHeaderGuideAlign(headerChannel, titleAngle, titleAnchor),
            ...standalone_assembleHeaderProperties(config, facetFieldDef, channel, standalone_HEADER_TITLE_PROPERTIES, standalone_HEADER_TITLE_PROPERTIES_MAP)
        }
    };
}
function standalone_defaultHeaderGuideAlign(headerChannel, angle, anchor = 'middle') {
    switch (anchor) {
        case 'start':
            return { align: 'left' };
        case 'end':
            return { align: 'right' };
    }
    const align = standalone_defaultLabelAlign(angle, headerChannel === 'row' ? 'left' : 'top', headerChannel === 'row' ? 'y' : 'x');
    return align ? { align } : {};
}
function standalone_defaultHeaderGuideBaseline(angle, channel) {
    const baseline = standalone_defaultLabelBaseline(angle, channel === 'row' ? 'left' : 'top', channel === 'row' ? 'y' : 'x', true);
    return baseline ? { baseline } : {};
}
function standalone_assembleHeaderGroups(model, channel) {
    const layoutHeader = model.component.layoutHeaders[channel];
    const groups = [];
    for (const headerType of standalone_HEADER_TYPES) {
        if (layoutHeader[headerType]) {
            for (const headerComponent of layoutHeader[headerType]) {
                const group = standalone_assembleHeaderGroup(model, channel, headerType, layoutHeader, headerComponent);
                if (group != null) {
                    groups.push(group);
                }
            }
        }
    }
    return groups;
}
function standalone_getSort(facetFieldDef, channel) {
    const { sort } = facetFieldDef;
    if (standalone_isSortField(sort)) {
        return {
            field: standalone_vgField(sort, { expr: 'datum' }),
            order: sort.order ?? 'ascending'
        };
    }
    else if (standalone_vega_util_module_isArray(sort)) {
        return {
            field: standalone_sortArrayIndexField(facetFieldDef, channel, { expr: 'datum' }),
            order: 'ascending'
        };
    }
    else {
        return {
            field: standalone_vgField(facetFieldDef, { expr: 'datum' }),
            order: sort ?? 'ascending'
        };
    }
}
function standalone_assembleLabelTitle(facetFieldDef, channel, config) {
    const { format, formatType, labelAngle, labelAnchor, labelOrient, labelExpr } = standalone_getHeaderProperties(['format', 'formatType', 'labelAngle', 'labelAnchor', 'labelOrient', 'labelExpr'], facetFieldDef.header, config, channel);
    const titleTextExpr = standalone_formatSignalRef({
        fieldOrDatumDef: facetFieldDef,
        format,
        formatType,
        expr: 'parent',
        config
    }).signal;
    const headerChannel = standalone_getHeaderChannel(channel, labelOrient);
    return {
        text: {
            signal: labelExpr
                ? standalone_replaceAll(standalone_replaceAll(labelExpr, 'datum.label', titleTextExpr), 'datum.value', standalone_vgField(facetFieldDef, { expr: 'parent' }))
                : titleTextExpr
        },
        ...(channel === 'row' ? { orient: 'left' } : {}),
        style: 'guide-label',
        frame: 'group',
        ...standalone_defaultHeaderGuideBaseline(labelAngle, headerChannel),
        ...standalone_defaultHeaderGuideAlign(headerChannel, labelAngle, labelAnchor),
        ...standalone_assembleHeaderProperties(config, facetFieldDef, channel, standalone_HEADER_LABEL_PROPERTIES, standalone_HEADER_LABEL_PROPERTIES_MAP)
    };
}
function standalone_assembleHeaderGroup(model, channel, headerType, layoutHeader, headerComponent) {
    if (headerComponent) {
        let title = null;
        const { facetFieldDef } = layoutHeader;
        const config = model.config ? model.config : undefined;
        if (facetFieldDef && headerComponent.labels) {
            const { labelOrient } = standalone_getHeaderProperties(['labelOrient'], facetFieldDef.header, config, channel);
            // Include label title in the header if orient aligns with the channel
            if ((channel === 'row' && !standalone_util_contains(['top', 'bottom'], labelOrient)) ||
                (channel === 'column' && !standalone_util_contains(['left', 'right'], labelOrient))) {
                title = standalone_assembleLabelTitle(facetFieldDef, channel, config);
            }
        }
        const isFacetWithoutRowCol = standalone_isFacetModel(model) && !standalone_isFacetMapping(model.facet);
        const axes = headerComponent.axes;
        const hasAxes = axes?.length > 0;
        if (title || hasAxes) {
            const sizeChannel = channel === 'row' ? 'height' : 'width';
            return {
                name: model.getName(`${channel}_${headerType}`),
                type: 'group',
                role: `${channel}-${headerType}`,
                ...(layoutHeader.facetFieldDef
                    ? {
                        from: { data: model.getName(`${channel}_domain`) },
                        sort: standalone_getSort(facetFieldDef, channel)
                    }
                    : {}),
                ...(hasAxes && isFacetWithoutRowCol
                    ? {
                        from: { data: model.getName(`facet_domain_${channel}`) }
                    }
                    : {}),
                ...(title ? { title } : {}),
                ...(headerComponent.sizeSignal
                    ? {
                        encode: {
                            update: {
                                [sizeChannel]: headerComponent.sizeSignal
                            }
                        }
                    }
                    : {}),
                ...(hasAxes ? { axes } : {})
            };
        }
    }
    return null;
}
const standalone_LAYOUT_TITLE_BAND = {
    column: {
        start: 0,
        end: 1
    },
    row: {
        start: 1,
        end: 0
    }
};
function standalone_getLayoutTitleBand(titleAnchor, headerChannel) {
    return standalone_LAYOUT_TITLE_BAND[headerChannel][titleAnchor];
}
function standalone_assembleLayoutTitleBand(headerComponentIndex, config) {
    const titleBand = {};
    for (const channel of standalone_FACET_CHANNELS) {
        const headerComponent = headerComponentIndex[channel];
        if (headerComponent?.facetFieldDef) {
            const { titleAnchor, titleOrient } = standalone_getHeaderProperties(['titleAnchor', 'titleOrient'], headerComponent.facetFieldDef.header, config, channel);
            const headerChannel = standalone_getHeaderChannel(channel, titleOrient);
            const band = standalone_getLayoutTitleBand(titleAnchor, headerChannel);
            if (band !== undefined) {
                titleBand[headerChannel] = band;
            }
        }
    }
    return standalone_isEmpty(titleBand) ? undefined : titleBand;
}
function standalone_assembleHeaderProperties(config, facetFieldDef, channel, properties, propertiesMap) {
    const props = {};
    for (const prop of properties) {
        if (!propertiesMap[prop]) {
            continue;
        }
        const value = standalone_getHeaderProperty(prop, facetFieldDef?.header, config, channel);
        if (value !== undefined) {
            props[propertiesMap[prop]] = value;
        }
    }
    return props;
}
//# sourceMappingURL=assemble.js.map
;// ../../node_modules/vega-lite/build/src/compile/layoutsize/assemble.js






function standalone_assembleLayoutSignals(model) {
    return [
        ...standalone_sizeSignals(model, 'width'),
        ...standalone_sizeSignals(model, 'height'),
        ...standalone_sizeSignals(model, 'childWidth'),
        ...standalone_sizeSignals(model, 'childHeight')
    ];
}
function standalone_sizeSignals(model, sizeType) {
    const channel = sizeType === 'width' ? 'x' : 'y';
    const size = model.component.layoutSize.get(sizeType);
    if (!size || size === 'merged') {
        return [];
    }
    // Read size signal name from name map, just in case it is the top-level size signal that got renamed.
    const name = model.getSizeSignalRef(sizeType).signal;
    if (size === 'step') {
        const scaleComponent = model.getScaleComponent(channel);
        if (scaleComponent) {
            const type = scaleComponent.get('type');
            const range = scaleComponent.get('range');
            if (standalone_hasDiscreteDomain(type) && standalone_isVgRangeStep(range)) {
                const scaleName = model.scaleName(channel);
                if (standalone_isFacetModel(model.parent)) {
                    // If parent is facet and this is an independent scale, return only signal signal
                    // as the width/height will be calculated using the cardinality from
                    // facet's aggregate rather than reading from scale domain
                    const parentResolve = model.parent.component.resolve;
                    if (parentResolve.scale[channel] === 'independent') {
                        return [standalone_stepSignal(scaleName, range)];
                    }
                }
                return [
                    standalone_stepSignal(scaleName, range),
                    {
                        name,
                        update: standalone_sizeExpr(scaleName, scaleComponent, `domain('${scaleName}').length`)
                    }
                ];
            }
        }
        /* istanbul ignore next: Condition should not happen -- only for warning in development. */
        throw new Error('layout size is step although width/height is not step.');
    }
    else if (size == 'container') {
        const isWidth = name.endsWith('width');
        const expr = isWidth ? 'containerSize()[0]' : 'containerSize()[1]';
        const defaultValue = standalone_getViewConfigContinuousSize(model.config.view, isWidth ? 'width' : 'height');
        const safeExpr = `isFinite(${expr}) ? ${expr} : ${defaultValue}`;
        return [{ name, init: safeExpr, on: [{ update: safeExpr, events: 'window:resize' }] }];
    }
    else {
        return [
            {
                name,
                value: size
            }
        ];
    }
}
function standalone_stepSignal(scaleName, range) {
    const name = `${scaleName}_step`;
    if (standalone_isSignalRef(range.step)) {
        return { name, update: range.step.signal };
    }
    else {
        return { name, value: range.step };
    }
}
function standalone_sizeExpr(scaleName, scaleComponent, cardinality) {
    const type = scaleComponent.get('type');
    const padding = scaleComponent.get('padding');
    const paddingOuter = standalone_getFirstDefined(scaleComponent.get('paddingOuter'), padding);
    let paddingInner = scaleComponent.get('paddingInner');
    paddingInner =
        type === 'band'
            ? // only band has real paddingInner
                paddingInner !== undefined
                    ? paddingInner
                    : padding
            : // For point, as calculated in https://github.com/vega/vega-scale/blob/master/src/band.js#L128,
                // it's equivalent to have paddingInner = 1 since there is only n-1 steps between n points.
                1;
    return `bandspace(${cardinality}, ${standalone_signalOrStringValue(paddingInner)}, ${standalone_signalOrStringValue(paddingOuter)}) * ${scaleName}_step`;
}
//# sourceMappingURL=assemble.js.map
;// ../../node_modules/vega-lite/build/src/compile/layoutsize/component.js
function standalone_getSizeTypeFromLayoutSizeType(layoutSizeType) {
    return layoutSizeType === 'childWidth' ? 'width' : layoutSizeType === 'childHeight' ? 'height' : layoutSizeType;
}
//# sourceMappingURL=component.js.map
;// ../../node_modules/vega-lite/build/src/compile/guide.js



function standalone_guideEncodeEntry(encoding, model) {
    return standalone_util_keys(encoding).reduce((encode, channel) => {
        return {
            ...encode,
            ...standalone_wrapCondition({
                model,
                channelDef: encoding[channel],
                vgChannel: channel,
                mainRefFn: def => standalone_signalOrValueRef(def.value),
                invalidValueRef: undefined // guide encoding won't show invalid values for the scale
            })
        };
    }, {});
}
//# sourceMappingURL=guide.js.map
;// ../../node_modules/vega-lite/build/src/compile/resolve.js



function standalone_defaultScaleResolve(channel, model) {
    if (standalone_isFacetModel(model)) {
        return channel === 'theta' ? 'independent' : 'shared';
    }
    else if (standalone_isLayerModel(model)) {
        return 'shared';
    }
    else if (standalone_isConcatModel(model)) {
        return standalone_isXorY(channel) || channel === 'theta' || channel === 'radius' ? 'independent' : 'shared';
    }
    /* istanbul ignore next: should never reach here. */
    throw new Error('invalid model type for resolve');
}
function standalone_parseGuideResolve(resolve, channel) {
    const channelScaleResolve = resolve.scale[channel];
    const guide = standalone_isXorY(channel) ? 'axis' : 'legend';
    if (channelScaleResolve === 'independent') {
        if (resolve[guide][channel] === 'shared') {
            standalone_log_warn(standalone_independentScaleMeansIndependentGuide(channel));
        }
        return 'independent';
    }
    return resolve[guide][channel] || 'shared';
}
//# sourceMappingURL=resolve.js.map
;// ../../node_modules/vega-lite/build/src/compile/legend/component.js



const standalone_LEGEND_COMPONENT_PROPERTY_INDEX = {
    ...standalone_COMMON_LEGEND_PROPERTY_INDEX,
    disable: 1,
    labelExpr: 1,
    selections: 1,
    // channel scales
    opacity: 1,
    shape: 1,
    stroke: 1,
    fill: 1,
    size: 1,
    strokeWidth: 1,
    strokeDash: 1,
    // encode
    encode: 1
};
const standalone_LEGEND_COMPONENT_PROPERTIES = standalone_util_keys(standalone_LEGEND_COMPONENT_PROPERTY_INDEX);
class standalone_LegendComponent extends standalone_Split {
}
//# sourceMappingURL=component.js.map
;// ../../node_modules/vega-lite/build/src/compile/legend/encode.js









const standalone_legendEncodeRules = {
    symbols: standalone_encode_symbols,
    gradient: standalone_encode_gradient,
    labels: standalone_labels,
    entries: standalone_encode_entries
};
function standalone_encode_symbols(symbolsSpec, { fieldOrDatumDef, model, channel, legendCmpt, legendType }) {
    if (legendType !== 'symbol') {
        return undefined;
    }
    const { markDef, encoding, config, mark } = model;
    const filled = markDef.filled && mark !== 'trail';
    let out = {
        ...standalone_applyMarkConfig({}, model, standalone_FILL_STROKE_CONFIG),
        ...standalone_color_color(model, { filled })
    }; // FIXME: remove this when VgEncodeEntry is compatible with SymbolEncodeEntry
    const symbolOpacity = legendCmpt.get('symbolOpacity') ?? config.legend.symbolOpacity;
    const symbolFillColor = legendCmpt.get('symbolFillColor') ?? config.legend.symbolFillColor;
    const symbolStrokeColor = legendCmpt.get('symbolStrokeColor') ?? config.legend.symbolStrokeColor;
    const opacity = symbolOpacity === undefined ? (standalone_getMaxValue(encoding.opacity) ?? markDef.opacity) : undefined;
    if (out.fill) {
        // for fill legend, we don't want any fill in symbol
        if (channel === 'fill' || (filled && channel === standalone_COLOR)) {
            delete out.fill;
        }
        else if (standalone_util_hasProperty(out.fill, 'field')) {
            // For others, set fill to some opaque value (or nothing if a color is already set)
            if (symbolFillColor) {
                delete out.fill;
            }
            else {
                out.fill = standalone_signalOrValueRef(config.legend.symbolBaseFillColor ?? 'black');
                out.fillOpacity = standalone_signalOrValueRef(opacity ?? 1);
            }
        }
        else if (standalone_vega_util_module_isArray(out.fill)) {
            const fill = standalone_getFirstConditionValue(encoding.fill ?? encoding.color) ?? markDef.fill ?? (filled && markDef.color);
            if (fill) {
                out.fill = standalone_signalOrValueRef(fill);
            }
        }
    }
    if (out.stroke) {
        if (channel === 'stroke' || (!filled && channel === standalone_COLOR)) {
            delete out.stroke;
        }
        else if (standalone_util_hasProperty(out.stroke, 'field') || symbolStrokeColor) {
            // For others, remove stroke field
            delete out.stroke;
        }
        else if (standalone_vega_util_module_isArray(out.stroke)) {
            const stroke = standalone_getFirstDefined(standalone_getFirstConditionValue(encoding.stroke || encoding.color), markDef.stroke, filled ? markDef.color : undefined);
            if (stroke) {
                out.stroke = { value: stroke };
            }
        }
    }
    if (channel !== standalone_OPACITY) {
        const condition = standalone_isFieldDef(fieldOrDatumDef) && standalone_selectedCondition(model, legendCmpt, fieldOrDatumDef);
        if (condition) {
            out.opacity = [
                { test: condition, ...standalone_signalOrValueRef(opacity ?? 1) },
                standalone_signalOrValueRef(config.legend.unselectedOpacity)
            ];
        }
        else if (opacity) {
            out.opacity = standalone_signalOrValueRef(opacity);
        }
    }
    out = { ...out, ...symbolsSpec };
    return standalone_isEmpty(out) ? undefined : out;
}
function standalone_encode_gradient(gradientSpec, { model, legendType, legendCmpt }) {
    if (legendType !== 'gradient') {
        return undefined;
    }
    const { config, markDef, encoding } = model;
    let out = {};
    const gradientOpacity = legendCmpt.get('gradientOpacity') ?? config.legend.gradientOpacity;
    const opacity = gradientOpacity === undefined ? standalone_getMaxValue(encoding.opacity) || markDef.opacity : undefined;
    if (opacity) {
        // only apply opacity if it is neither zero or undefined
        out.opacity = standalone_signalOrValueRef(opacity);
    }
    out = { ...out, ...gradientSpec };
    return standalone_isEmpty(out) ? undefined : out;
}
function standalone_labels(specifiedlabelsSpec, { fieldOrDatumDef, model, channel, legendCmpt }) {
    const legend = model.legend(channel) || {};
    const config = model.config;
    const condition = standalone_isFieldDef(fieldOrDatumDef) ? standalone_selectedCondition(model, legendCmpt, fieldOrDatumDef) : undefined;
    const opacity = condition ? [{ test: condition, value: 1 }, { value: config.legend.unselectedOpacity }] : undefined;
    const { format, formatType } = legend;
    let text = undefined;
    if (standalone_isCustomFormatType(formatType)) {
        text = standalone_formatCustomType({
            fieldOrDatumDef,
            field: 'datum.value',
            format,
            formatType,
            config
        });
    }
    else if (format === undefined && formatType === undefined && config.customFormatTypes) {
        if (fieldOrDatumDef.type === 'quantitative' && config.numberFormatType) {
            text = standalone_formatCustomType({
                fieldOrDatumDef,
                field: 'datum.value',
                format: config.numberFormat,
                formatType: config.numberFormatType,
                config
            });
        }
        else if (fieldOrDatumDef.type === 'temporal' &&
            config.timeFormatType &&
            standalone_isFieldDef(fieldOrDatumDef) &&
            fieldOrDatumDef.timeUnit === undefined) {
            text = standalone_formatCustomType({
                fieldOrDatumDef,
                field: 'datum.value',
                format: config.timeFormat,
                formatType: config.timeFormatType,
                config
            });
        }
    }
    const labelsSpec = {
        ...(opacity ? { opacity } : {}),
        ...(text ? { text } : {}),
        ...specifiedlabelsSpec
    };
    return standalone_isEmpty(labelsSpec) ? undefined : labelsSpec;
}
function standalone_encode_entries(entriesSpec, { legendCmpt }) {
    const selections = legendCmpt.get('selections');
    return selections?.length ? { ...entriesSpec, fill: { value: 'transparent' } } : entriesSpec;
}
function standalone_getMaxValue(channelDef) {
    return standalone_getConditionValue(channelDef, (v, conditionalDef) => Math.max(v, conditionalDef.value));
}
function standalone_getFirstConditionValue(channelDef) {
    return standalone_getConditionValue(channelDef, (v, conditionalDef) => {
        return standalone_getFirstDefined(v, conditionalDef.value);
    });
}
function standalone_getConditionValue(channelDef, reducer) {
    if (standalone_hasConditionalValueDef(channelDef)) {
        return standalone_array(channelDef.condition).reduce(reducer, channelDef.value);
    }
    else if (standalone_isValueDef(channelDef)) {
        return channelDef.value;
    }
    return undefined;
}
function standalone_selectedCondition(model, legendCmpt, fieldDef) {
    const selections = legendCmpt.get('selections');
    if (!selections?.length)
        return undefined;
    const field = standalone_$(fieldDef.field);
    return selections
        .map(name => {
        const store = standalone_$(standalone_varName(name) + standalone_STORE);
        return `(!length(data(${store})) || (${name}[${field}] && indexof(${name}[${field}], datum.value) >= 0))`;
    })
        .join(' || ');
}
//# sourceMappingURL=encode.js.map
;// ../../node_modules/vega-lite/build/src/compile/legend/properties.js








const standalone_legendRules = {
    direction: ({ direction }) => direction,
    format: ({ fieldOrDatumDef, legend, config }) => {
        const { format, formatType } = legend;
        return standalone_guideFormat(fieldOrDatumDef, fieldOrDatumDef.type, format, formatType, config, false);
    },
    formatType: ({ legend, fieldOrDatumDef, scaleType }) => {
        const { formatType } = legend;
        return standalone_guideFormatType(formatType, fieldOrDatumDef, scaleType);
    },
    gradientLength: params => {
        const { legend, legendConfig } = params;
        return legend.gradientLength ?? legendConfig.gradientLength ?? standalone_defaultGradientLength(params);
    },
    labelOverlap: ({ legend, legendConfig, scaleType }) => legend.labelOverlap ?? legendConfig.labelOverlap ?? standalone_properties_defaultLabelOverlap(scaleType),
    symbolType: ({ legend, markDef, channel, encoding }) => legend.symbolType ?? standalone_defaultSymbolType(markDef.type, channel, encoding.shape, markDef.shape),
    title: ({ fieldOrDatumDef, config }) => standalone_channeldef_title(fieldOrDatumDef, config, { allowDisabling: true }),
    type: ({ legendType, scaleType, channel }) => {
        if (standalone_isColorChannel(channel) && standalone_isContinuousToContinuous(scaleType)) {
            if (legendType === 'gradient') {
                return undefined;
            }
        }
        else if (legendType === 'symbol') {
            return undefined;
        }
        return legendType;
    }, // depended by other property, let's define upfront
    values: ({ fieldOrDatumDef, legend }) => standalone_legend_properties_values(legend, fieldOrDatumDef)
};
function standalone_legend_properties_values(legend, fieldOrDatumDef) {
    const vals = legend.values;
    if (standalone_vega_util_module_isArray(vals)) {
        return standalone_valueArray(fieldOrDatumDef, vals);
    }
    else if (standalone_isSignalRef(vals)) {
        return vals;
    }
    return undefined;
}
function standalone_defaultSymbolType(mark, channel, shapeChannelDef, markShape) {
    if (channel !== 'shape') {
        // use the value from the shape encoding or the mark config if they exist
        const shape = standalone_getFirstConditionValue(shapeChannelDef) ?? markShape;
        if (shape) {
            return shape;
        }
    }
    switch (mark) {
        case 'bar':
        case 'rect':
        case 'image':
        case 'square':
            return 'square';
        case 'line':
        case 'trail':
        case 'rule':
            return 'stroke';
        case 'arc':
        case 'point':
        case 'circle':
        case 'tick':
        case 'geoshape':
        case 'area':
        case 'text':
            return 'circle';
    }
}
function standalone_clipHeight(legendType) {
    if (legendType === 'gradient') {
        return 20;
    }
    return undefined;
}
function standalone_getLegendType(params) {
    const { legend } = params;
    return standalone_getFirstDefined(legend.type, standalone_properties_defaultType(params));
}
function standalone_properties_defaultType({ channel, timeUnit, scaleType }) {
    // Following the logic in https://github.com/vega/vega-parser/blob/master/src/parsers/legend.js
    if (standalone_isColorChannel(channel)) {
        if (standalone_util_contains(['quarter', 'month', 'day'], timeUnit)) {
            return 'symbol';
        }
        if (standalone_isContinuousToContinuous(scaleType)) {
            return 'gradient';
        }
    }
    return 'symbol';
}
function standalone_getDirection({ legendConfig, legendType, orient, legend }) {
    return (legend.direction ??
        legendConfig[legendType ? 'gradientDirection' : 'symbolDirection'] ??
        standalone_defaultDirection(orient, legendType));
}
function standalone_defaultDirection(orient, legendType) {
    switch (orient) {
        case 'top':
        case 'bottom':
            return 'horizontal';
        case 'left':
        case 'right':
        case 'none':
        case undefined: // undefined = "right" in Vega
            return undefined; // vertical is Vega's default
        default:
            // top-left / ...
            // For inner legend, uses compact layout like Tableau
            return legendType === 'gradient' ? 'horizontal' : undefined;
    }
}
function standalone_defaultGradientLength({ legendConfig, model, direction, orient, scaleType }) {
    const { gradientHorizontalMaxLength, gradientHorizontalMinLength, gradientVerticalMaxLength, gradientVerticalMinLength } = legendConfig;
    if (standalone_isContinuousToContinuous(scaleType)) {
        if (direction === 'horizontal') {
            if (orient === 'top' || orient === 'bottom') {
                return standalone_gradientLengthSignal(model, 'width', gradientHorizontalMinLength, gradientHorizontalMaxLength);
            }
            else {
                return gradientHorizontalMinLength;
            }
        }
        else {
            // vertical / undefined (Vega uses vertical by default)
            return standalone_gradientLengthSignal(model, 'height', gradientVerticalMinLength, gradientVerticalMaxLength);
        }
    }
    return undefined;
}
function standalone_gradientLengthSignal(model, sizeType, min, max) {
    const sizeSignal = model.getSizeSignalRef(sizeType).signal;
    return { signal: `clamp(${sizeSignal}, ${min}, ${max})` };
}
function standalone_properties_defaultLabelOverlap(scaleType) {
    if (standalone_util_contains(['quantile', 'threshold', 'log', 'symlog'], scaleType)) {
        return 'greedy';
    }
    return undefined;
}
//# sourceMappingURL=properties.js.map
;// ../../node_modules/vega-lite/build/src/compile/legend/parse.js















function standalone_parse_parseLegend(model) {
    const legendComponent = standalone_isUnitModel(model) ? standalone_parseUnitLegend(model) : standalone_parseNonUnitLegend(model);
    model.component.legends = legendComponent;
    return legendComponent;
}
function standalone_parseUnitLegend(model) {
    const { encoding } = model;
    const legendComponent = {};
    for (const channel of [standalone_COLOR, ...standalone_LEGEND_SCALE_CHANNELS]) {
        const def = standalone_getFieldOrDatumDef(encoding[channel]);
        if (!def || !model.getScaleComponent(channel)) {
            continue;
        }
        if (channel === standalone_SHAPE && standalone_isFieldDef(def) && def.type === standalone_GEOJSON) {
            continue;
        }
        legendComponent[channel] = standalone_parseLegendForChannel(model, channel);
    }
    return legendComponent;
}
function standalone_getLegendDefWithScale(model, channel) {
    const scale = model.scaleName(channel);
    if (model.mark === 'trail') {
        if (channel === 'color') {
            // trail is a filled mark, but its default symbolType ("stroke") should use "stroke"
            return { stroke: scale };
        }
        else if (channel === 'size') {
            return { strokeWidth: scale };
        }
    }
    if (channel === 'color') {
        return model.markDef.filled ? { fill: scale } : { stroke: scale };
    }
    return { [channel]: scale };
}
// eslint-disable-next-line @typescript-eslint/ban-types
function standalone_isExplicit(value, property, legend, fieldDef) {
    switch (property) {
        case 'disable':
            return legend !== undefined; // if axis is specified or null/false, then its enable/disable state is explicit
        case 'values':
            // specified legend.values is already respected, but may get transformed.
            return !!legend?.values;
        case 'title':
            // title can be explicit if fieldDef.title is set
            if (property === 'title' && value === fieldDef?.title) {
                return true;
            }
    }
    // Otherwise, things are explicit if the returned value matches the specified property
    return value === (legend || {})[property];
}
function standalone_parseLegendForChannel(model, channel) {
    let legend = model.legend(channel);
    const { markDef, encoding, config } = model;
    const legendConfig = config.legend;
    const legendCmpt = new standalone_LegendComponent({}, standalone_getLegendDefWithScale(model, channel));
    standalone_parseInteractiveLegend(model, channel, legendCmpt);
    const disable = legend !== undefined ? !legend : legendConfig.disable;
    legendCmpt.set('disable', disable, legend !== undefined);
    if (disable) {
        return legendCmpt;
    }
    legend = legend || {};
    const scaleType = model.getScaleComponent(channel).get('type');
    const fieldOrDatumDef = standalone_getFieldOrDatumDef(encoding[channel]);
    const timeUnit = standalone_isFieldDef(fieldOrDatumDef) ? standalone_normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit : undefined;
    const orient = legend.orient || config.legend.orient || 'right';
    const legendType = standalone_getLegendType({ legend, channel, timeUnit, scaleType });
    const direction = standalone_getDirection({ legend, legendType, orient, legendConfig });
    const ruleParams = {
        legend,
        channel,
        model,
        markDef,
        encoding,
        fieldOrDatumDef,
        legendConfig,
        config,
        scaleType,
        orient,
        legendType,
        direction
    };
    for (const property of standalone_LEGEND_COMPONENT_PROPERTIES) {
        if ((legendType === 'gradient' && property.startsWith('symbol')) ||
            (legendType === 'symbol' && property.startsWith('gradient'))) {
            continue;
        }
        const value = property in standalone_legendRules ? standalone_legendRules[property](ruleParams) : legend[property];
        if (value !== undefined) {
            const explicit = standalone_isExplicit(value, property, legend, model.fieldDef(channel));
            if (explicit || config.legend[property] === undefined) {
                legendCmpt.set(property, value, explicit);
            }
        }
    }
    const legendEncoding = legend?.encoding ?? {};
    const selections = legendCmpt.get('selections');
    const legendEncode = {};
    const legendEncodeParams = { fieldOrDatumDef, model, channel, legendCmpt, legendType };
    for (const part of ['labels', 'legend', 'title', 'symbols', 'gradient', 'entries']) {
        // FIXME: remove as any (figure out what legendEncoding.entries is)
        const legendEncodingPart = standalone_guideEncodeEntry(legendEncoding[part] ?? {}, model);
        const value = part in standalone_legendEncodeRules
            ? standalone_legendEncodeRules[part](legendEncodingPart, legendEncodeParams) // apply rule
            : legendEncodingPart; // no rule -- just default values
        if (value !== undefined && !standalone_isEmpty(value)) {
            legendEncode[part] = {
                ...(selections?.length && standalone_isFieldDef(fieldOrDatumDef)
                    ? { name: `${standalone_varName(fieldOrDatumDef.field)}_legend_${part}` }
                    : {}),
                ...(selections?.length ? { interactive: !!selections } : {}),
                update: value
            };
        }
    }
    if (!standalone_isEmpty(legendEncode)) {
        legendCmpt.set('encode', legendEncode, !!legend?.encoding);
    }
    return legendCmpt;
}
function standalone_parseNonUnitLegend(model) {
    const { legends, resolve } = model.component;
    for (const child of model.children) {
        standalone_parse_parseLegend(child);
        for (const channel of standalone_util_keys(child.component.legends)) {
            resolve.legend[channel] = standalone_parseGuideResolve(model.component.resolve, channel);
            if (resolve.legend[channel] === 'shared') {
                // If the resolve says shared (and has not been overridden)
                // We will try to merge and see if there is a conflict
                legends[channel] = standalone_mergeLegendComponent(legends[channel], child.component.legends[channel]);
                if (!legends[channel]) {
                    // If merge returns nothing, there is a conflict so we cannot make the legend shared.
                    // Thus, mark legend as independent and remove the legend component.
                    resolve.legend[channel] = 'independent';
                    delete legends[channel];
                }
            }
        }
    }
    for (const channel of standalone_util_keys(legends)) {
        for (const child of model.children) {
            if (!child.component.legends[channel]) {
                // skip if the child does not have a particular legend
                continue;
            }
            if (resolve.legend[channel] === 'shared') {
                // After merging shared legend, make sure to remove legend from child
                delete child.component.legends[channel];
            }
        }
    }
    return legends;
}
function standalone_mergeLegendComponent(mergedLegend, childLegend) {
    if (!mergedLegend) {
        return childLegend.clone();
    }
    const mergedOrient = mergedLegend.getWithExplicit('orient');
    const childOrient = childLegend.getWithExplicit('orient');
    if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) {
        // TODO: throw warning if resolve is explicit (We don't have info about explicit/implicit resolve yet.)
        // Cannot merge due to inconsistent orient
        return undefined;
    }
    let typeMerged = false;
    // Otherwise, let's merge
    for (const prop of standalone_LEGEND_COMPONENT_PROPERTIES) {
        const mergedValueWithExplicit = standalone_mergeValuesWithExplicit(mergedLegend.getWithExplicit(prop), childLegend.getWithExplicit(prop), prop, 'legend', 
        // Tie breaker function
        (v1, v2) => {
            switch (prop) {
                case 'symbolType':
                    return standalone_mergeSymbolType(v1, v2);
                case 'title':
                    return standalone_mergeTitleComponent(v1, v2);
                case 'type':
                    // There are only two types. If we have different types, then prefer symbol over gradient.
                    typeMerged = true;
                    return standalone_makeImplicit('symbol');
            }
            return standalone_defaultTieBreaker(v1, v2, prop, 'legend');
        });
        mergedLegend.setWithExplicit(prop, mergedValueWithExplicit);
    }
    if (typeMerged) {
        if (mergedLegend.implicit?.encode?.gradient) {
            standalone_deleteNestedProperty(mergedLegend.implicit, ['encode', 'gradient']);
        }
        if (mergedLegend.explicit?.encode?.gradient) {
            standalone_deleteNestedProperty(mergedLegend.explicit, ['encode', 'gradient']);
        }
    }
    return mergedLegend;
}
function standalone_mergeSymbolType(st1, st2) {
    if (st2.value === 'circle') {
        // prefer "circle" over "stroke"
        return st2;
    }
    return st1;
}
//# sourceMappingURL=parse.js.map
;// ../../node_modules/vega-lite/build/src/compile/legend/assemble.js




function standalone_setLegendEncode(legend, part, vgProp, vgRef) {
    var _a, _b;
    legend.encode ?? (legend.encode = {});
    (_a = legend.encode)[part] ?? (_a[part] = {});
    (_b = legend.encode[part]).update ?? (_b.update = {});
    // TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291
    legend.encode[part].update[vgProp] = vgRef;
}
function standalone_assembleLegends(model) {
    const legendComponentIndex = model.component.legends;
    const legendByDomain = {};
    for (const channel of standalone_util_keys(legendComponentIndex)) {
        const scaleComponent = model.getScaleComponent(channel);
        const domainHash = standalone_util_stringify(scaleComponent.get('domains'));
        if (legendByDomain[domainHash]) {
            for (const mergedLegendComponent of legendByDomain[domainHash]) {
                const merged = standalone_mergeLegendComponent(mergedLegendComponent, legendComponentIndex[channel]);
                if (!merged) {
                    // If cannot merge, need to add this legend separately
                    legendByDomain[domainHash].push(legendComponentIndex[channel]);
                }
            }
        }
        else {
            legendByDomain[domainHash] = [legendComponentIndex[channel].clone()];
        }
    }
    const legends = standalone_vals(legendByDomain)
        .flat()
        .map(l => standalone_assembleLegend(l, model.config))
        .filter(l => l !== undefined);
    return legends;
}
function standalone_assembleLegend(legendCmpt, config) {
    const { disable, labelExpr, selections, ...legend } = legendCmpt.combine();
    if (disable) {
        return undefined;
    }
    if (config.aria === false && legend.aria == undefined) {
        legend.aria = false;
    }
    if (legend.encode?.symbols) {
        const out = legend.encode.symbols.update;
        if (out.fill && out.fill['value'] !== 'transparent' && !out.stroke && !legend.stroke) {
            // For non color channel's legend, we need to override symbol stroke config from Vega config if stroke channel is not used.
            out.stroke = { value: 'transparent' };
        }
        // Remove properties that the legend is encoding.
        for (const property of standalone_LEGEND_SCALE_CHANNELS) {
            if (legend[property]) {
                delete out[property];
            }
        }
    }
    if (!legend.title) {
        // title schema doesn't include null, ''
        delete legend.title;
    }
    if (labelExpr !== undefined) {
        let expr = labelExpr;
        if (legend.encode?.labels?.update && standalone_isSignalRef(legend.encode.labels.update.text)) {
            expr = standalone_replaceAll(labelExpr, 'datum.label', legend.encode.labels.update.text.signal);
        }
        standalone_setLegendEncode(legend, 'labels', 'text', { signal: expr });
    }
    return legend;
}
//# sourceMappingURL=assemble.js.map
;// ../../node_modules/vega-lite/build/src/compile/projection/assemble.js



function standalone_assembleProjections(model) {
    if (standalone_isLayerModel(model) || standalone_isConcatModel(model)) {
        return standalone_assembleProjectionsForModelAndChildren(model);
    }
    else {
        return standalone_assembleProjectionForModel(model);
    }
}
function standalone_assembleProjectionsForModelAndChildren(model) {
    return model.children.reduce((projections, child) => {
        return projections.concat(child.assembleProjections());
    }, standalone_assembleProjectionForModel(model));
}
function standalone_assembleProjectionForModel(model) {
    const component = model.component.projection;
    if (!component || component.merged) {
        return [];
    }
    const projection = component.combine();
    const { name } = projection; // we need to extract name so that it is always present in the output and pass TS type validation
    if (!component.data) {
        // generate custom projection, no automatic fitting
        return [
            {
                name,
                // translate to center by default
                translate: { signal: '[width / 2, height / 2]' },
                // parameters, overwrite default translate if specified
                ...projection
            }
        ];
    }
    else {
        // generate projection that uses extent fitting
        const size = {
            signal: `[${component.size.map(ref => ref.signal).join(', ')}]`
        };
        const fits = component.data.reduce((sources, data) => {
            const source = standalone_isSignalRef(data) ? data.signal : `data('${model.lookupDataSource(data)}')`;
            if (!standalone_util_contains(sources, source)) {
                // build a unique list of sources
                sources.push(source);
            }
            return sources;
        }, []);
        if (fits.length <= 0) {
            throw new Error("Projection's fit didn't find any data sources");
        }
        return [
            {
                name,
                size,
                fit: {
                    signal: fits.length > 1 ? `[${fits.join(', ')}]` : fits[0]
                },
                ...projection
            }
        ];
    }
}
//# sourceMappingURL=assemble.js.map
;// ../../node_modules/vega-lite/build/src/projection.js
const standalone_PROJECTION_PROPERTIES = [
    'type',
    'clipAngle',
    'clipExtent',
    'center',
    'rotate',
    'precision',
    'reflectX',
    'reflectY',
    'coefficient',
    'distance',
    'fraction',
    'lobes',
    'parallel',
    'radius',
    'ratio',
    'spacing',
    'tilt'
];
//# sourceMappingURL=projection.js.map
;// ../../node_modules/vega-lite/build/src/compile/projection/component.js

class standalone_ProjectionComponent extends standalone_Split {
    constructor(name, specifiedProjection, size, data) {
        super({ ...specifiedProjection }, // all explicit properties of projection
        { name } // name as initial implicit property
        );
        this.specifiedProjection = specifiedProjection;
        this.size = size;
        this.data = data;
        this.merged = false;
    }
    /**
     * Whether the projection parameters should fit provided data.
     */
    get isFit() {
        return !!this.data;
    }
}
//# sourceMappingURL=component.js.map
;// ../../node_modules/vega-lite/build/src/compile/projection/parse.js










function standalone_parse_parseProjection(model) {
    model.component.projection = standalone_isUnitModel(model) ? standalone_parseUnitProjection(model) : standalone_parseNonUnitProjections(model);
}
function standalone_parseUnitProjection(model) {
    if (model.hasProjection) {
        const proj = standalone_replaceExprRef(model.specifiedProjection);
        const fit = !(proj && (proj.scale != null || proj.translate != null));
        const size = fit ? [model.getSizeSignalRef('width'), model.getSizeSignalRef('height')] : undefined;
        const data = fit ? standalone_gatherFitData(model) : undefined;
        const projComp = new standalone_ProjectionComponent(model.projectionName(true), {
            ...standalone_replaceExprRef(model.config.projection),
            ...proj
        }, size, data);
        if (!projComp.get('type')) {
            projComp.set('type', 'equalEarth', false);
        }
        return projComp;
    }
    return undefined;
}
function standalone_gatherFitData(model) {
    const data = [];
    const { encoding } = model;
    for (const posssiblePair of [
        [standalone_LONGITUDE, standalone_LATITUDE],
        [standalone_LONGITUDE2, standalone_LATITUDE2]
    ]) {
        if (standalone_getFieldOrDatumDef(encoding[posssiblePair[0]]) || standalone_getFieldOrDatumDef(encoding[posssiblePair[1]])) {
            data.push({
                signal: model.getName(`geojson_${data.length}`)
            });
        }
    }
    if (model.channelHasField(standalone_SHAPE) && model.typedFieldDef(standalone_SHAPE).type === standalone_GEOJSON) {
        data.push({
            signal: model.getName(`geojson_${data.length}`)
        });
    }
    if (data.length === 0) {
        // main source is geojson, so we can just use that
        data.push(model.requestDataName(standalone_DataSourceType.Main));
    }
    return data;
}
function standalone_mergeIfNoConflict(first, second) {
    const allPropertiesShared = standalone_every(standalone_PROJECTION_PROPERTIES, prop => {
        // neither has the property
        if (!standalone_vega_util_module_has(first.explicit, prop) && !standalone_vega_util_module_has(second.explicit, prop)) {
            return true;
        }
        // both have property and an equal value for property
        if (standalone_vega_util_module_has(first.explicit, prop) &&
            standalone_vega_util_module_has(second.explicit, prop) &&
            // some properties might be signals or objects and require hashing for comparison
            standalone_deepEqual(first.get(prop), second.get(prop))) {
            return true;
        }
        return false;
    });
    const size = standalone_deepEqual(first.size, second.size);
    if (size) {
        if (allPropertiesShared) {
            return first;
        }
        else if (standalone_deepEqual(first.explicit, {})) {
            return second;
        }
        else if (standalone_deepEqual(second.explicit, {})) {
            return first;
        }
    }
    // if all properties don't match, let each unit spec have its own projection
    return null;
}
function standalone_parseNonUnitProjections(model) {
    if (model.children.length === 0) {
        return undefined;
    }
    let nonUnitProjection;
    // parse all children first
    for (const child of model.children) {
        standalone_parse_parseProjection(child);
    }
    // analyze parsed projections, attempt to merge
    const mergable = standalone_every(model.children, child => {
        const projection = child.component.projection;
        if (!projection) {
            // child layer does not use a projection
            return true;
        }
        else if (!nonUnitProjection) {
            // cached 'projection' is null, cache this one
            nonUnitProjection = projection;
            return true;
        }
        else {
            const merge = standalone_mergeIfNoConflict(nonUnitProjection, projection);
            if (merge) {
                nonUnitProjection = merge;
            }
            return !!merge;
        }
    });
    // if cached one and all other children share the same projection,
    if (nonUnitProjection && mergable) {
        // so we can elevate it to the layer level
        const name = model.projectionName(true);
        const modelProjection = new standalone_ProjectionComponent(name, nonUnitProjection.specifiedProjection, nonUnitProjection.size, standalone_duplicate(nonUnitProjection.data));
        // rename and assign all others as merged
        for (const child of model.children) {
            const projection = child.component.projection;
            if (projection) {
                if (projection.isFit) {
                    modelProjection.data.push(...child.component.projection.data);
                }
                child.renameProjection(projection.get('name'), name);
                projection.merged = true;
            }
        }
        return modelProjection;
    }
    return undefined;
}
//# sourceMappingURL=parse.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/bin.js








function standalone_rangeFormula(model, fieldDef, channel, config) {
    if (standalone_binRequiresRange(fieldDef, channel)) {
        // read format from axis or legend, if there is no format then use config.numberFormat
        const guide = standalone_isUnitModel(model)
            ? (model.axis(channel) ?? model.legend(channel) ?? {})
            : {};
        const startField = standalone_vgField(fieldDef, { expr: 'datum' });
        const endField = standalone_vgField(fieldDef, { expr: 'datum', binSuffix: 'end' });
        return {
            formulaAs: standalone_vgField(fieldDef, { binSuffix: 'range', forAs: true }),
            formula: standalone_binFormatExpression(startField, endField, guide.format, guide.formatType, config)
        };
    }
    return {};
}
function standalone_binKey(bin, field) {
    return `${standalone_binToString(bin)}_${field}`;
}
function standalone_getSignalsFromModel(model, key) {
    return {
        signal: model.getName(`${key}_bins`),
        extentSignal: model.getName(`${key}_extent`)
    };
}
function standalone_getBinSignalName(model, field, bin) {
    const normalizedBin = standalone_normalizeBin(bin, undefined) ?? {};
    const key = standalone_binKey(normalizedBin, field);
    return model.getName(`${key}_bins`);
}
function standalone_isBinTransform(t) {
    return 'as' in t;
}
function standalone_createBinComponent(t, bin, model) {
    let as;
    let span;
    if (standalone_isBinTransform(t)) {
        as = standalone_vega_util_module_isString(t.as) ? [t.as, `${t.as}_end`] : [t.as[0], t.as[1]];
    }
    else {
        as = [standalone_vgField(t, { forAs: true }), standalone_vgField(t, { binSuffix: 'end', forAs: true })];
    }
    const normalizedBin = { ...standalone_normalizeBin(bin, undefined) };
    const key = standalone_binKey(normalizedBin, t.field);
    const { signal, extentSignal } = standalone_getSignalsFromModel(model, key);
    if (standalone_isParameterExtent(normalizedBin.extent)) {
        const ext = normalizedBin.extent;
        span = standalone_parseSelectionExtent(model, ext.param, ext);
        delete normalizedBin.extent; // Vega-Lite selection extent map to Vega's span property.
    }
    const binComponent = {
        bin: normalizedBin,
        field: t.field,
        as: [as],
        ...(signal ? { signal } : {}),
        ...(extentSignal ? { extentSignal } : {}),
        ...(span ? { span } : {})
    };
    return { key, binComponent };
}
class standalone_BinNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_BinNode(null, standalone_duplicate(this.bins));
    }
    constructor(parent, bins) {
        super(parent);
        this.bins = bins;
    }
    static makeFromEncoding(parent, model) {
        const bins = model.reduceFieldDef((binComponentIndex, fieldDef, channel) => {
            if (standalone_isTypedFieldDef(fieldDef) && standalone_isBinning(fieldDef.bin)) {
                const { key, binComponent } = standalone_createBinComponent(fieldDef, fieldDef.bin, model);
                binComponentIndex[key] = {
                    ...binComponent,
                    ...binComponentIndex[key],
                    ...standalone_rangeFormula(model, fieldDef, channel, model.config)
                };
            }
            return binComponentIndex;
        }, {});
        if (standalone_isEmpty(bins)) {
            return null;
        }
        return new standalone_BinNode(parent, bins);
    }
    /**
     * Creates a bin node from BinTransform.
     * The optional parameter should provide
     */
    static makeFromTransform(parent, t, model) {
        const { key, binComponent } = standalone_createBinComponent(t, t.bin, model);
        return new standalone_BinNode(parent, {
            [key]: binComponent
        });
    }
    /**
     * Merge bin nodes. This method either integrates the bin config from the other node
     * or if this node already has a bin config, renames the corresponding signal in the model.
     */
    merge(other, renameSignal) {
        for (const key of standalone_util_keys(other.bins)) {
            if (key in this.bins) {
                renameSignal(other.bins[key].signal, this.bins[key].signal);
                // Ensure that we don't have duplicate names for signal pairs
                this.bins[key].as = standalone_unique([...this.bins[key].as, ...other.bins[key].as], standalone_util_hash);
            }
            else {
                this.bins[key] = other.bins[key];
            }
        }
        for (const child of other.children) {
            other.removeChild(child);
            child.parent = this;
        }
        other.remove();
    }
    producedFields() {
        return new Set(standalone_vals(this.bins)
            .map(c => c.as)
            .flat(2));
    }
    dependentFields() {
        return new Set(standalone_vals(this.bins).map(c => c.field));
    }
    hash() {
        return `Bin ${standalone_util_hash(this.bins)}`;
    }
    assemble() {
        return standalone_vals(this.bins).flatMap(bin => {
            const transform = [];
            const [binAs, ...remainingAs] = bin.as;
            const { extent, ...params } = bin.bin;
            const binTrans = {
                type: 'bin',
                field: standalone_replacePathInField(bin.field),
                as: binAs,
                signal: bin.signal,
                ...(!standalone_isParameterExtent(extent) ? { extent } : { extent: null }),
                ...(bin.span ? { span: { signal: `span(${bin.span})` } } : {}),
                ...params
            };
            if (!extent && bin.extentSignal) {
                transform.push({
                    type: 'extent',
                    field: standalone_replacePathInField(bin.field),
                    signal: bin.extentSignal
                });
                binTrans.extent = { signal: bin.extentSignal };
            }
            transform.push(binTrans);
            for (const as of remainingAs) {
                for (let i = 0; i < 2; i++) {
                    transform.push({
                        type: 'formula',
                        expr: standalone_vgField({ field: binAs[i] }, { expr: 'datum' }),
                        as: as[i]
                    });
                }
            }
            if (bin.formula) {
                transform.push({
                    type: 'formula',
                    expr: bin.formula,
                    as: bin.formulaAs
                });
            }
            return transform;
        });
    }
}
//# sourceMappingURL=bin.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/aggregate.js










function standalone_addDimension(dims, channel, fieldDef, model) {
    const channelDef2 = standalone_isUnitModel(model) ? model.encoding[standalone_getSecondaryRangeChannel(channel)] : undefined;
    if (standalone_isTypedFieldDef(fieldDef) &&
        standalone_isUnitModel(model) &&
        standalone_hasBandEnd(fieldDef, channelDef2, model.markDef, model.config)) {
        dims.add(standalone_vgField(fieldDef, {}));
        dims.add(standalone_vgField(fieldDef, { suffix: 'end' }));
        const { mark, markDef, config } = model;
        const bandPosition = standalone_getBandPosition({ fieldDef, markDef, config });
        if (standalone_isRectBasedMark(mark) && bandPosition !== 0.5 && standalone_isXorY(channel)) {
            dims.add(standalone_vgField(fieldDef, { suffix: standalone_OFFSETTED_RECT_START_SUFFIX }));
            dims.add(standalone_vgField(fieldDef, { suffix: standalone_OFFSETTED_RECT_END_SUFFIX }));
        }
        if (fieldDef.bin && standalone_binRequiresRange(fieldDef, channel)) {
            dims.add(standalone_vgField(fieldDef, { binSuffix: 'range' }));
        }
    }
    else if (standalone_isGeoPositionChannel(channel)) {
        const posChannel = standalone_getPositionChannelFromLatLong(channel);
        dims.add(model.getName(posChannel));
    }
    else {
        dims.add(standalone_vgField(fieldDef));
    }
    if (standalone_isScaleFieldDef(fieldDef) && standalone_isFieldRange(fieldDef.scale?.range)) {
        dims.add(fieldDef.scale.range.field);
    }
    return dims;
}
function standalone_mergeMeasures(parentMeasures, childMeasures) {
    for (const field of standalone_util_keys(childMeasures)) {
        // when we merge a measure, we either have to add an aggregation operator or even a new field
        const ops = childMeasures[field];
        for (const op of standalone_util_keys(ops)) {
            if (field in parentMeasures) {
                // add operator to existing measure field
                parentMeasures[field][op] = new Set([...(parentMeasures[field][op] ?? []), ...ops[op]]);
            }
            else {
                parentMeasures[field] = { [op]: ops[op] };
            }
        }
    }
}
class standalone_AggregateNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_AggregateNode(null, new Set(this.dimensions), standalone_duplicate(this.measures));
    }
    /**
     * @param dimensions string set for dimensions
     * @param measures dictionary mapping field name => dict of aggregation functions and names to use
     */
    constructor(parent, dimensions, measures) {
        super(parent);
        this.dimensions = dimensions;
        this.measures = measures;
    }
    get groupBy() {
        return this.dimensions;
    }
    static makeFromEncoding(parent, model) {
        let isAggregate = false;
        model.forEachFieldDef(fd => {
            if (fd.aggregate) {
                isAggregate = true;
            }
        });
        const meas = {};
        const dims = new Set();
        if (!isAggregate) {
            // no need to create this node if the model has no aggregation
            return null;
        }
        model.forEachFieldDef((fieldDef, channel) => {
            const { aggregate, field } = fieldDef;
            if (aggregate) {
                if (aggregate === 'count') {
                    meas['*'] ?? (meas['*'] = {});
                    meas['*']['count'] = new Set([standalone_vgField(fieldDef, { forAs: true })]);
                }
                else {
                    if (standalone_isArgminDef(aggregate) || standalone_isArgmaxDef(aggregate)) {
                        const op = standalone_isArgminDef(aggregate) ? 'argmin' : 'argmax';
                        const argField = aggregate[op];
                        meas[argField] ?? (meas[argField] = {});
                        meas[argField][op] = new Set([standalone_vgField({ op, field: argField }, { forAs: true })]);
                    }
                    else {
                        meas[field] ?? (meas[field] = {});
                        meas[field][aggregate] = new Set([standalone_vgField(fieldDef, { forAs: true })]);
                    }
                    // For scale channel with domain === 'unaggregated', add min/max so we can use their union as unaggregated domain
                    if (standalone_isScaleChannel(channel) && model.scaleDomain(channel) === 'unaggregated') {
                        meas[field] ?? (meas[field] = {});
                        meas[field]['min'] = new Set([standalone_vgField({ field, aggregate: 'min' }, { forAs: true })]);
                        meas[field]['max'] = new Set([standalone_vgField({ field, aggregate: 'max' }, { forAs: true })]);
                    }
                }
            }
            else {
                standalone_addDimension(dims, channel, fieldDef, model);
            }
        });
        if (dims.size + standalone_util_keys(meas).length === 0) {
            return null;
        }
        return new standalone_AggregateNode(parent, dims, meas);
    }
    static makeFromTransform(parent, t) {
        var _a;
        const dims = new Set();
        const meas = {};
        for (const s of t.aggregate) {
            const { op, field, as } = s;
            if (op) {
                if (op === 'count') {
                    meas['*'] ?? (meas['*'] = {});
                    meas['*']['count'] = new Set([as ? as : standalone_vgField(s, { forAs: true })]);
                }
                else {
                    meas[field] ?? (meas[field] = {});
                    (_a = meas[field])[op] ?? (_a[op] = new Set());
                    meas[field][op].add(as ? as : standalone_vgField(s, { forAs: true }));
                }
            }
        }
        for (const s of t.groupby ?? []) {
            dims.add(s);
        }
        if (dims.size + standalone_util_keys(meas).length === 0) {
            return null;
        }
        return new standalone_AggregateNode(parent, dims, meas);
    }
    merge(other) {
        if (standalone_setEqual(this.dimensions, other.dimensions)) {
            standalone_mergeMeasures(this.measures, other.measures);
            return true;
        }
        standalone_log_debug('different dimensions, cannot merge');
        return false;
    }
    addDimensions(fields) {
        fields.forEach(this.dimensions.add, this.dimensions);
    }
    dependentFields() {
        return new Set([...this.dimensions, ...standalone_util_keys(this.measures)]);
    }
    producedFields() {
        const out = new Set();
        for (const field of standalone_util_keys(this.measures)) {
            for (const op of standalone_util_keys(this.measures[field])) {
                const m = this.measures[field][op];
                if (m.size === 0) {
                    out.add(`${op}_${field}`);
                }
                else {
                    m.forEach(out.add, out);
                }
            }
        }
        return out;
    }
    hash() {
        return `Aggregate ${standalone_util_hash({ dimensions: this.dimensions, measures: this.measures })}`;
    }
    assemble() {
        const ops = [];
        const fields = [];
        const as = [];
        for (const field of standalone_util_keys(this.measures)) {
            for (const op of standalone_util_keys(this.measures[field])) {
                for (const alias of this.measures[field][op]) {
                    as.push(alias);
                    ops.push(op);
                    fields.push(field === '*' ? null : standalone_replacePathInField(field));
                }
            }
        }
        const result = {
            type: 'aggregate',
            groupby: [...this.dimensions].map(standalone_replacePathInField),
            ops,
            fields,
            as
        };
        return result;
    }
}
//# sourceMappingURL=aggregate.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/facet.js













/**
 * A node that helps us track what fields we are faceting by.
 */
class standalone_FacetNode extends standalone_DataFlowNode {
    /**
     * @param model The facet model.
     * @param name The name that this facet source will have.
     * @param data The source data for this facet data.
     */
    constructor(parent, model, name, data) {
        super(parent);
        this.model = model;
        this.name = name;
        this.data = data;
        for (const channel of standalone_FACET_CHANNELS) {
            const fieldDef = model.facet[channel];
            if (fieldDef) {
                const { bin, sort } = fieldDef;
                this[channel] = {
                    name: model.getName(`${channel}_domain`),
                    fields: [standalone_vgField(fieldDef), ...(standalone_isBinning(bin) ? [standalone_vgField(fieldDef, { binSuffix: 'end' })] : [])],
                    ...(standalone_isSortField(sort)
                        ? { sortField: sort }
                        : standalone_vega_util_module_isArray(sort)
                            ? { sortIndexField: standalone_sortArrayIndexField(fieldDef, channel) }
                            : {})
                };
            }
        }
        this.childModel = model.child;
    }
    hash() {
        let out = `Facet`;
        for (const channel of standalone_FACET_CHANNELS) {
            if (this[channel]) {
                out += ` ${channel.charAt(0)}:${standalone_util_hash(this[channel])}`;
            }
        }
        return out;
    }
    get fields() {
        const f = [];
        for (const channel of standalone_FACET_CHANNELS) {
            if (this[channel]?.fields) {
                f.push(...this[channel].fields);
            }
        }
        return f;
    }
    dependentFields() {
        const depFields = new Set(this.fields);
        for (const channel of standalone_FACET_CHANNELS) {
            if (this[channel]) {
                if (this[channel].sortField) {
                    depFields.add(this[channel].sortField.field);
                }
                if (this[channel].sortIndexField) {
                    depFields.add(this[channel].sortIndexField);
                }
            }
        }
        return depFields;
    }
    producedFields() {
        return new Set(); // facet does not produce any new fields
    }
    /**
     * The name to reference this source is its name.
     */
    getSource() {
        return this.name;
    }
    getChildIndependentFieldsWithStep() {
        const childIndependentFieldsWithStep = {};
        for (const channel of standalone_POSITION_SCALE_CHANNELS) {
            const childScaleComponent = this.childModel.component.scales[channel];
            if (childScaleComponent && !childScaleComponent.merged) {
                // independent scale
                const type = childScaleComponent.get('type');
                const range = childScaleComponent.get('range');
                if (standalone_hasDiscreteDomain(type) && standalone_isVgRangeStep(range)) {
                    const domain = standalone_assembleDomain(this.childModel, channel);
                    const field = standalone_getFieldFromDomain(domain);
                    if (field) {
                        childIndependentFieldsWithStep[channel] = field;
                    }
                    else {
                        standalone_log_warn(standalone_unknownField(channel));
                    }
                }
            }
        }
        return childIndependentFieldsWithStep;
    }
    assembleRowColumnHeaderData(channel, crossedDataName, childIndependentFieldsWithStep) {
        const childChannel = { row: 'y', column: 'x', facet: undefined }[channel];
        const fields = [];
        const ops = [];
        const as = [];
        if (childChannel && childIndependentFieldsWithStep && childIndependentFieldsWithStep[childChannel]) {
            if (crossedDataName) {
                // If there is a crossed data, calculate max
                fields.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);
                ops.push('max');
            }
            else {
                // If there is no crossed data, just calculate distinct
                fields.push(childIndependentFieldsWithStep[childChannel]);
                ops.push('distinct');
            }
            // Although it is technically a max, just name it distinct so it's easier to refer to it
            as.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);
        }
        const { sortField, sortIndexField } = this[channel];
        if (sortField) {
            const { op = standalone_DEFAULT_SORT_OP, field } = sortField;
            fields.push(field);
            ops.push(op);
            as.push(standalone_vgField(sortField, { forAs: true }));
        }
        else if (sortIndexField) {
            fields.push(sortIndexField);
            ops.push('max');
            as.push(sortIndexField);
        }
        return {
            name: this[channel].name,
            // Use data from the crossed one if it exist
            source: crossedDataName ?? this.data,
            transform: [
                {
                    type: 'aggregate',
                    groupby: this[channel].fields,
                    ...(fields.length
                        ? {
                            fields,
                            ops,
                            as
                        }
                        : {})
                }
            ]
        };
    }
    assembleFacetHeaderData(childIndependentFieldsWithStep) {
        const { columns } = this.model.layout;
        const { layoutHeaders } = this.model.component;
        const data = [];
        const hasSharedAxis = {};
        for (const headerChannel of standalone_HEADER_CHANNELS) {
            for (const headerType of standalone_HEADER_TYPES) {
                const headers = (layoutHeaders[headerChannel] && layoutHeaders[headerChannel][headerType]) ?? [];
                for (const header of headers) {
                    if (header.axes?.length > 0) {
                        hasSharedAxis[headerChannel] = true;
                        break;
                    }
                }
            }
            if (hasSharedAxis[headerChannel]) {
                const cardinality = `length(data("${this.facet.name}"))`;
                const stop = headerChannel === 'row'
                    ? columns
                        ? { signal: `ceil(${cardinality} / ${columns})` }
                        : 1
                    : columns
                        ? { signal: `min(${cardinality}, ${columns})` }
                        : { signal: cardinality };
                data.push({
                    name: `${this.facet.name}_${headerChannel}`,
                    transform: [
                        {
                            type: 'sequence',
                            start: 0,
                            stop
                        }
                    ]
                });
            }
        }
        const { row, column } = hasSharedAxis;
        if (row || column) {
            data.unshift(this.assembleRowColumnHeaderData('facet', null, childIndependentFieldsWithStep));
        }
        return data;
    }
    assemble() {
        const data = [];
        let crossedDataName = null;
        const childIndependentFieldsWithStep = this.getChildIndependentFieldsWithStep();
        const { column, row, facet } = this;
        if (column && row && (childIndependentFieldsWithStep.x || childIndependentFieldsWithStep.y)) {
            // Need to create a cross dataset to correctly calculate cardinality
            crossedDataName = `cross_${this.column.name}_${this.row.name}`;
            const fields = [].concat(childIndependentFieldsWithStep.x ?? [], childIndependentFieldsWithStep.y ?? []);
            const ops = fields.map(() => 'distinct');
            data.push({
                name: crossedDataName,
                source: this.data,
                transform: [
                    {
                        type: 'aggregate',
                        groupby: this.fields,
                        fields,
                        ops
                    }
                ]
            });
        }
        for (const channel of [standalone_COLUMN, standalone_ROW]) {
            if (this[channel]) {
                data.push(this.assembleRowColumnHeaderData(channel, crossedDataName, childIndependentFieldsWithStep));
            }
        }
        if (facet) {
            const facetData = this.assembleFacetHeaderData(childIndependentFieldsWithStep);
            if (facetData) {
                data.push(...facetData);
            }
        }
        return data;
    }
}
//# sourceMappingURL=facet.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/formatparse.js
















/**
 * Remove quotes from a string.
 */
function standalone_unquote(pattern) {
    if ((pattern.startsWith("'") && pattern.endsWith("'")) || (pattern.startsWith('"') && pattern.endsWith('"'))) {
        return pattern.slice(1, -1);
    }
    return pattern;
}
/**
 * @param field The field.
 * @param parse What to parse the field as.
 */
function standalone_formatparse_parseExpression(field, parse) {
    const f = standalone_accessPathWithDatum(field);
    if (parse === 'number') {
        return `toNumber(${f})`;
    }
    else if (parse === 'boolean') {
        return `toBoolean(${f})`;
    }
    else if (parse === 'string') {
        return `toString(${f})`;
    }
    else if (parse === 'date') {
        return `toDate(${f})`;
    }
    else if (parse === 'flatten') {
        return f;
    }
    else if (parse.startsWith('date:')) {
        const specifier = standalone_unquote(parse.slice(5, parse.length));
        return `timeParse(${f},'${specifier}')`;
    }
    else if (parse.startsWith('utc:')) {
        const specifier = standalone_unquote(parse.slice(4, parse.length));
        return `utcParse(${f},'${specifier}')`;
    }
    else {
        standalone_log_warn(standalone_unrecognizedParse(parse));
        return null;
    }
}
function standalone_getImplicitFromFilterTransform(transform) {
    const implicit = {};
    standalone_forEachLeaf(transform.filter, filter => {
        if (standalone_isFieldPredicate(filter)) {
            // Automatically add a parse node for filters with filter objects
            let val = null;
            // For EqualFilter, just use the equal property.
            // For RangeFilter and OneOfFilter, all array members should have
            // the same type, so we only use the first one.
            if (standalone_isFieldEqualPredicate(filter)) {
                val = standalone_signalRefOrValue(filter.equal);
            }
            else if (standalone_isFieldLTEPredicate(filter)) {
                val = standalone_signalRefOrValue(filter.lte);
            }
            else if (standalone_isFieldLTPredicate(filter)) {
                val = standalone_signalRefOrValue(filter.lt);
            }
            else if (standalone_isFieldGTPredicate(filter)) {
                val = standalone_signalRefOrValue(filter.gt);
            }
            else if (standalone_isFieldGTEPredicate(filter)) {
                val = standalone_signalRefOrValue(filter.gte);
            }
            else if (standalone_isFieldRangePredicate(filter)) {
                // FIXME: remove as any
                val = filter.range[0];
            }
            else if (standalone_isFieldOneOfPredicate(filter)) {
                val = (filter.oneOf ?? filter.in)[0];
            } // else -- for filter expression, we can't infer anything
            if (val) {
                if (standalone_isDateTime(val)) {
                    implicit[filter.field] = 'date';
                }
                else if (standalone_isNumber(val)) {
                    implicit[filter.field] = 'number';
                }
                else if (standalone_vega_util_module_isString(val)) {
                    implicit[filter.field] = 'string';
                }
            }
            if (filter.timeUnit) {
                implicit[filter.field] = 'date';
            }
        }
    });
    return implicit;
}
/**
 * Creates a parse node for implicit parsing from a model and updates ancestorParse.
 */
function standalone_getImplicitFromEncoding(model) {
    const implicit = {};
    function add(fieldDef) {
        if (standalone_isFieldOrDatumDefForTimeFormat(fieldDef)) {
            implicit[fieldDef.field] = 'date';
        }
        else if (fieldDef.type === 'quantitative' &&
            standalone_isMinMaxOp(fieldDef.aggregate) // we need to parse numbers to support correct min and max
        ) {
            implicit[fieldDef.field] = 'number';
        }
        else if (standalone_accessPathDepth(fieldDef.field) > 1) {
            // For non-date/non-number (strings and booleans), derive a flattened field for a referenced nested field.
            // (Parsing numbers / dates already flattens numeric and temporal fields.)
            if (!(fieldDef.field in implicit)) {
                implicit[fieldDef.field] = 'flatten';
            }
        }
        else if (standalone_isScaleFieldDef(fieldDef) && standalone_isSortField(fieldDef.sort) && standalone_accessPathDepth(fieldDef.sort.field) > 1) {
            // Flatten fields that we sort by but that are not otherwise flattened.
            if (!(fieldDef.sort.field in implicit)) {
                implicit[fieldDef.sort.field] = 'flatten';
            }
        }
    }
    if (standalone_isUnitModel(model) || standalone_isFacetModel(model)) {
        // Parse encoded fields
        model.forEachFieldDef((fieldDef, channel) => {
            if (standalone_isTypedFieldDef(fieldDef)) {
                add(fieldDef);
            }
            else {
                const mainChannel = standalone_getMainRangeChannel(channel);
                const mainFieldDef = model.fieldDef(mainChannel);
                add({
                    ...fieldDef,
                    type: mainFieldDef.type
                });
            }
        });
    }
    // Parse quantitative dimension fields of path marks as numbers so that we sort them correctly.
    if (standalone_isUnitModel(model)) {
        const { mark, markDef, encoding } = model;
        if (standalone_isPathMark(mark) &&
            // No need to sort by dimension if we have a connected scatterplot (order channel is present)
            !model.encoding.order) {
            const dimensionChannel = markDef.orient === 'horizontal' ? 'y' : 'x';
            const dimensionChannelDef = encoding[dimensionChannel];
            if (standalone_isFieldDef(dimensionChannelDef) &&
                dimensionChannelDef.type === 'quantitative' &&
                !(dimensionChannelDef.field in implicit)) {
                implicit[dimensionChannelDef.field] = 'number';
            }
        }
    }
    return implicit;
}
/**
 * Creates a parse node for implicit parsing from a model and updates ancestorParse.
 */
function standalone_getImplicitFromSelection(model) {
    const implicit = {};
    if (standalone_isUnitModel(model) && model.component.selection) {
        for (const name of standalone_util_keys(model.component.selection)) {
            const selCmpt = model.component.selection[name];
            for (const proj of selCmpt.project.items) {
                if (!proj.channel && standalone_accessPathDepth(proj.field) > 1) {
                    implicit[proj.field] = 'flatten';
                }
            }
        }
    }
    return implicit;
}
class standalone_ParseNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_ParseNode(null, standalone_duplicate(this._parse));
    }
    constructor(parent, parse) {
        super(parent);
        this._parse = parse;
    }
    hash() {
        return `Parse ${standalone_util_hash(this._parse)}`;
    }
    /**
     * Creates a parse node from a data.format.parse and updates ancestorParse.
     */
    static makeExplicit(parent, model, ancestorParse) {
        // Custom parse
        let explicit = {};
        const data = model.data;
        if (!standalone_isGenerator(data) && data?.format?.parse) {
            explicit = data.format.parse;
        }
        return this.makeWithAncestors(parent, explicit, {}, ancestorParse);
    }
    /**
     * Creates a parse node from "explicit" parse and "implicit" parse and updates ancestorParse.
     */
    static makeWithAncestors(parent, explicit, implicit, ancestorParse) {
        // We should not parse what has already been parsed in a parent (explicitly or implicitly) or what has been derived (maked as "derived"). We also don't need to flatten a field that has already been parsed.
        for (const field of standalone_util_keys(implicit)) {
            const parsedAs = ancestorParse.getWithExplicit(field);
            if (parsedAs.value !== undefined) {
                // We always ignore derived fields even if they are implicitly defined because we expect users to create the right types.
                if (parsedAs.explicit ||
                    parsedAs.value === implicit[field] ||
                    parsedAs.value === 'derived' ||
                    implicit[field] === 'flatten') {
                    delete implicit[field];
                }
                else {
                    standalone_log_warn(standalone_differentParse(field, implicit[field], parsedAs.value));
                }
            }
        }
        for (const field of standalone_util_keys(explicit)) {
            const parsedAs = ancestorParse.get(field);
            if (parsedAs !== undefined) {
                // Don't parse a field again if it has been parsed with the same type already.
                if (parsedAs === explicit[field]) {
                    delete explicit[field];
                }
                else {
                    standalone_log_warn(standalone_differentParse(field, explicit[field], parsedAs));
                }
            }
        }
        const parse = new standalone_Split(explicit, implicit);
        // add the format parse from this model so that children don't parse the same field again
        ancestorParse.copyAll(parse);
        // copy only non-null parses
        const p = {};
        for (const key of standalone_util_keys(parse.combine())) {
            const val = parse.get(key);
            if (val !== null) {
                p[key] = val;
            }
        }
        if (standalone_util_keys(p).length === 0 || ancestorParse.parseNothing) {
            return null;
        }
        return new standalone_ParseNode(parent, p);
    }
    get parse() {
        return this._parse;
    }
    merge(other) {
        this._parse = { ...this._parse, ...other.parse };
        other.remove();
    }
    /**
     * Assemble an object for Vega's format.parse property.
     */
    assembleFormatParse() {
        const formatParse = {};
        for (const field of standalone_util_keys(this._parse)) {
            const p = this._parse[field];
            if (standalone_accessPathDepth(field) === 1) {
                formatParse[field] = p;
            }
        }
        return formatParse;
    }
    // format parse depends and produces all fields in its parse
    producedFields() {
        return new Set(standalone_util_keys(this._parse));
    }
    dependentFields() {
        return new Set(standalone_util_keys(this._parse));
    }
    assembleTransforms(onlyNested = false) {
        return standalone_util_keys(this._parse)
            .filter(field => (onlyNested ? standalone_accessPathDepth(field) > 1 : true))
            .map(field => {
            const expr = standalone_formatparse_parseExpression(field, this._parse[field]);
            if (!expr) {
                return null;
            }
            const formula = {
                type: 'formula',
                expr,
                as: standalone_removePathFromField(field) // Vega output is always flattened
            };
            return formula;
        })
            .filter(t => t !== null);
    }
}
//# sourceMappingURL=formatparse.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/identifier.js


class standalone_IdentifierNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_IdentifierNode(null);
    }
    constructor(parent) {
        super(parent);
    }
    dependentFields() {
        return new Set();
    }
    producedFields() {
        return new Set([standalone_SELECTION_ID]);
    }
    hash() {
        return 'Identifier';
    }
    assemble() {
        return { type: 'identifier', as: standalone_SELECTION_ID };
    }
}
//# sourceMappingURL=identifier.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/graticule.js


class standalone_GraticuleNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_GraticuleNode(null, this.params);
    }
    constructor(parent, params) {
        super(parent);
        this.params = params;
    }
    dependentFields() {
        return new Set();
    }
    producedFields() {
        return undefined; // there should never be a node before graticule
    }
    hash() {
        return `Graticule ${standalone_util_hash(this.params)}`;
    }
    assemble() {
        return {
            type: 'graticule',
            ...(this.params === true ? {} : this.params)
        };
    }
}
//# sourceMappingURL=graticule.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/sequence.js


class standalone_SequenceNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_SequenceNode(null, this.params);
    }
    constructor(parent, params) {
        super(parent);
        this.params = params;
    }
    dependentFields() {
        return new Set();
    }
    producedFields() {
        return new Set([this.params.as ?? 'data']);
    }
    hash() {
        return `Hash ${standalone_util_hash(this.params)}`;
    }
    assemble() {
        return {
            type: 'sequence',
            ...this.params
        };
    }
}
//# sourceMappingURL=sequence.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/source.js



class standalone_SourceNode extends standalone_DataFlowNode {
    constructor(data) {
        super(null); // source cannot have parent
        data ?? (data = { name: 'source' });
        let format;
        if (!standalone_isGenerator(data)) {
            format = data.format ? { ...standalone_omit(data.format, ['parse']) } : {};
        }
        if (standalone_isInlineData(data)) {
            this._data = { values: data.values };
        }
        else if (standalone_isUrlData(data)) {
            this._data = { url: data.url };
            if (!format.type) {
                // Extract extension from URL using snippet from
                // http://stackoverflow.com/questions/680929/how-to-extract-extension-from-filename-string-in-javascript
                let defaultExtension = /(?:\.([^.]+))?$/.exec(data.url)[1];
                if (!standalone_util_contains(['json', 'csv', 'tsv', 'dsv', 'topojson'], defaultExtension)) {
                    defaultExtension = 'json';
                }
                // defaultExtension has type string but we ensure that it is DataFormatType above
                format.type = defaultExtension;
            }
        }
        else if (standalone_isSphereGenerator(data)) {
            // hardwire GeoJSON sphere data into output specification
            this._data = { values: [{ type: 'Sphere' }] };
        }
        else if (standalone_isNamedData(data) || standalone_isGenerator(data)) {
            this._data = {};
        }
        // set flag to check if generator
        this._generator = standalone_isGenerator(data);
        // any dataset can be named
        if (data.name) {
            this._name = data.name;
        }
        if (format && !standalone_isEmpty(format)) {
            this._data.format = format;
        }
    }
    dependentFields() {
        return new Set();
    }
    producedFields() {
        return undefined; // we don't know what this source produces
    }
    get data() {
        return this._data;
    }
    hasName() {
        return !!this._name;
    }
    get isGenerator() {
        return this._generator;
    }
    get dataName() {
        return this._name;
    }
    set dataName(name) {
        this._name = name;
    }
    set parent(parent) {
        throw new Error('Source nodes have to be roots.');
    }
    remove() {
        throw new Error('Source nodes are roots and cannot be removed.');
    }
    hash() {
        throw new Error('Cannot hash sources');
    }
    assemble() {
        return {
            name: this._name,
            ...this._data,
            transform: []
        };
    }
}
//# sourceMappingURL=source.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/optimizer.js
var standalone_optimizer_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var standalone_optimizer_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var standalone_Optimizer_modified;



/**
 * Whether this dataflow node is the source of the dataflow that produces data i.e. a source or a generator.
 */
function standalone_isDataSourceNode(node) {
    return node instanceof standalone_SourceNode || node instanceof standalone_GraticuleNode || node instanceof standalone_SequenceNode;
}
/**
 * Abstract base class for Dataflow optimizers.
 * Contains only mutation handling logic. Subclasses need to implement iteration logic.
 */
class standalone_Optimizer {
    constructor() {
        standalone_Optimizer_modified.set(this, void 0);
        standalone_optimizer_classPrivateFieldSet(this, standalone_Optimizer_modified, false, "f");
    }
    // Once true, #modified is never set to false
    setModified() {
        standalone_optimizer_classPrivateFieldSet(this, standalone_Optimizer_modified, true, "f");
    }
    get modifiedFlag() {
        return standalone_optimizer_classPrivateFieldGet(this, standalone_Optimizer_modified, "f");
    }
}
standalone_Optimizer_modified = new WeakMap();
/**
 * Starts from a node and runs the optimization function (the "run" method) upwards to the root,
 * depending on the continue and modified flag values returned by the optimization function.
 */
class standalone_BottomUpOptimizer extends standalone_Optimizer {
    /**
     * Compute a map of node depths that we can use to determine a topological sort order.
     */
    getNodeDepths(node, depth, depths) {
        depths.set(node, depth);
        for (const child of node.children) {
            this.getNodeDepths(child, depth + 1, depths);
        }
        return depths;
    }
    /**
     * Run the optimizer on all nodes starting from the leaves.
     */
    optimize(node) {
        const depths = this.getNodeDepths(node, 0, new Map());
        const topologicalSort = [...depths.entries()].sort((a, b) => b[1] - a[1]);
        for (const tuple of topologicalSort) {
            this.run(tuple[0]);
        }
        return this.modifiedFlag;
    }
}
/**
 * The optimizer function (the "run" method), is invoked on the given node and then continues recursively.
 */
class standalone_TopDownOptimizer extends standalone_Optimizer {
    /**
     * Run the optimizer depth first on all nodes starting from the roots.
     */
    optimize(node) {
        this.run(node);
        for (const child of node.children) {
            this.optimize(child);
        }
        return this.modifiedFlag;
    }
}
//# sourceMappingURL=optimizer.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/optimizers.js












/**
 * Merge identical nodes at forks by comparing hashes.
 *
 * Does not need to iterate from leaves so we implement this with recursion as it's a bit simpler.
 */
class standalone_MergeIdenticalNodes extends standalone_TopDownOptimizer {
    mergeNodes(parent, nodes) {
        const mergedNode = nodes.shift();
        for (const node of nodes) {
            parent.removeChild(node);
            node.parent = mergedNode;
            node.remove();
        }
    }
    run(node) {
        const hashes = node.children.map(x => x.hash());
        const buckets = {};
        for (let i = 0; i < hashes.length; i++) {
            if (buckets[hashes[i]] === undefined) {
                buckets[hashes[i]] = [node.children[i]];
            }
            else {
                buckets[hashes[i]].push(node.children[i]);
            }
        }
        for (const k of standalone_util_keys(buckets)) {
            if (buckets[k].length > 1) {
                this.setModified();
                this.mergeNodes(node, buckets[k]);
            }
        }
    }
}
/**
 * Optimizer that removes identifier nodes that are not needed for selections.
 */
class standalone_RemoveUnnecessaryIdentifierNodes extends standalone_TopDownOptimizer {
    constructor(model) {
        super();
        this.requiresSelectionId = model && standalone_requiresSelectionId(model);
    }
    run(node) {
        if (node instanceof standalone_IdentifierNode) {
            // Only preserve IdentifierNodes if we have default discrete selections
            // in our model tree, and if the nodes come after tuple producing nodes.
            if (!(this.requiresSelectionId &&
                (standalone_isDataSourceNode(node.parent) || node.parent instanceof standalone_AggregateNode || node.parent instanceof standalone_ParseNode))) {
                this.setModified();
                node.remove();
            }
        }
    }
}
/**
 * Removes duplicate time unit nodes (as determined by the name of the output field) that may be generated due to
 * selections projected over time units. Only keeps the first time unit in any branch.
 *
 * This optimizer is a custom top down optimizer that keep track of produced fields in a branch.
 */
class standalone_RemoveDuplicateTimeUnits extends standalone_Optimizer {
    optimize(node) {
        this.run(node, new Set());
        return this.modifiedFlag;
    }
    run(node, timeUnitFields) {
        let producedFields = new Set();
        if (node instanceof standalone_TimeUnitNode) {
            producedFields = node.producedFields();
            if (standalone_hasIntersection(producedFields, timeUnitFields)) {
                this.setModified();
                node.removeFormulas(timeUnitFields);
                if (node.producedFields.length === 0) {
                    node.remove();
                }
            }
        }
        for (const child of node.children) {
            this.run(child, new Set([...timeUnitFields, ...producedFields]));
        }
    }
}
/**
 * Remove output nodes that are not required.
 */
class standalone_RemoveUnnecessaryOutputNodes extends standalone_TopDownOptimizer {
    constructor() {
        super();
    }
    run(node) {
        if (node instanceof standalone_OutputNode && !node.isRequired()) {
            this.setModified();
            node.remove();
        }
    }
}
/**
 * Move parse nodes up to forks and merges them if possible.
 */
class standalone_MoveParseUp extends standalone_BottomUpOptimizer {
    run(node) {
        if (standalone_isDataSourceNode(node)) {
            return;
        }
        if (node.numChildren() > 1) {
            // Don't move parse further up but continue with parent.
            return;
        }
        for (const child of node.children) {
            if (child instanceof standalone_ParseNode) {
                if (node instanceof standalone_ParseNode) {
                    this.setModified();
                    node.merge(child);
                }
                else {
                    // Don't swap with nodes that produce something that the parse node depends on (e.g. lookup).
                    if (standalone_fieldIntersection(node.producedFields(), child.dependentFields())) {
                        continue;
                    }
                    this.setModified();
                    child.swapWithParent();
                }
            }
        }
        return;
    }
}
/**
 * Inserts an intermediate ParseNode containing all non-conflicting parse fields and removes the empty ParseNodes.
 *
 * We assume that dependent paths that do not have a parse node can be just merged.
 */
class standalone_MergeParse extends standalone_BottomUpOptimizer {
    run(node) {
        const originalChildren = [...node.children];
        const parseChildren = node.children.filter((child) => child instanceof standalone_ParseNode);
        if (node.numChildren() > 1 && parseChildren.length >= 1) {
            const commonParse = {};
            const conflictingParse = new Set();
            for (const parseNode of parseChildren) {
                const parse = parseNode.parse;
                for (const k of standalone_util_keys(parse)) {
                    if (!(k in commonParse)) {
                        commonParse[k] = parse[k];
                    }
                    else if (commonParse[k] !== parse[k]) {
                        conflictingParse.add(k);
                    }
                }
            }
            for (const field of conflictingParse) {
                delete commonParse[field];
            }
            if (!standalone_isEmpty(commonParse)) {
                this.setModified();
                const mergedParseNode = new standalone_ParseNode(node, commonParse);
                for (const childNode of originalChildren) {
                    if (childNode instanceof standalone_ParseNode) {
                        for (const key of standalone_util_keys(commonParse)) {
                            delete childNode.parse[key];
                        }
                    }
                    node.removeChild(childNode);
                    childNode.parent = mergedParseNode;
                    // remove empty parse nodes
                    if (childNode instanceof standalone_ParseNode && standalone_util_keys(childNode.parse).length === 0) {
                        childNode.remove();
                    }
                }
            }
        }
    }
}
/**
 * Repeatedly remove leaf nodes that are not output or facet nodes.
 * The reason is that we don't need subtrees that don't have any output nodes.
 * Facet nodes are needed for the row or column domains.
 */
class standalone_RemoveUnusedSubtrees extends standalone_BottomUpOptimizer {
    run(node) {
        if (node instanceof standalone_OutputNode || node.numChildren() > 0 || node instanceof standalone_FacetNode) {
            // no need to continue with parent because it is output node or will have children (there was a fork)
        }
        else if (node instanceof standalone_SourceNode) {
            // ignore empty unused sources as they will be removed in optimizationDataflowHelper
        }
        else {
            this.setModified();
            node.remove();
        }
    }
}
/**
 * Merge adjacent time unit nodes.
 */
class standalone_MergeTimeUnits extends standalone_BottomUpOptimizer {
    run(node) {
        const timeUnitChildren = node.children.filter((x) => x instanceof standalone_TimeUnitNode);
        const combination = timeUnitChildren.pop();
        for (const timeUnit of timeUnitChildren) {
            this.setModified();
            combination.merge(timeUnit);
        }
    }
}
class standalone_MergeAggregates extends standalone_BottomUpOptimizer {
    run(node) {
        const aggChildren = node.children.filter((child) => child instanceof standalone_AggregateNode);
        // Object which we'll use to map the fields which an aggregate is grouped by to
        // the set of aggregates with that grouping. This is useful as only aggregates
        // with the same group by can be merged
        const groupedAggregates = {};
        // Build groupedAggregates
        for (const agg of aggChildren) {
            const groupBys = standalone_util_hash(agg.groupBy);
            if (!(groupBys in groupedAggregates)) {
                groupedAggregates[groupBys] = [];
            }
            groupedAggregates[groupBys].push(agg);
        }
        // Merge aggregateNodes with same key in groupedAggregates
        for (const group of standalone_util_keys(groupedAggregates)) {
            const mergeableAggs = groupedAggregates[group];
            if (mergeableAggs.length > 1) {
                const mergedAggs = mergeableAggs.pop();
                for (const agg of mergeableAggs) {
                    if (mergedAggs.merge(agg)) {
                        node.removeChild(agg);
                        agg.parent = mergedAggs;
                        agg.remove();
                        this.setModified();
                    }
                }
            }
        }
    }
}
/**
 * Merge bin nodes and move them up through forks. Stop at filters, parse, identifier as we want them to stay before the bin node.
 */
class standalone_MergeBins extends standalone_BottomUpOptimizer {
    constructor(model) {
        super();
        this.model = model;
    }
    run(node) {
        const moveBinsUp = !(standalone_isDataSourceNode(node) ||
            node instanceof standalone_FilterNode ||
            node instanceof standalone_ParseNode ||
            node instanceof standalone_IdentifierNode);
        const promotableBins = [];
        const remainingBins = [];
        for (const child of node.children) {
            if (child instanceof standalone_BinNode) {
                if (moveBinsUp && !standalone_fieldIntersection(node.producedFields(), child.dependentFields())) {
                    promotableBins.push(child);
                }
                else {
                    remainingBins.push(child);
                }
            }
        }
        if (promotableBins.length > 0) {
            const promotedBin = promotableBins.pop();
            for (const bin of promotableBins) {
                promotedBin.merge(bin, this.model.renameSignal.bind(this.model));
            }
            this.setModified();
            if (node instanceof standalone_BinNode) {
                node.merge(promotedBin, this.model.renameSignal.bind(this.model));
            }
            else {
                promotedBin.swapWithParent();
            }
        }
        if (remainingBins.length > 1) {
            const remainingBin = remainingBins.pop();
            for (const bin of remainingBins) {
                remainingBin.merge(bin, this.model.renameSignal.bind(this.model));
            }
            this.setModified();
        }
    }
}
/**
 * This optimizer takes output nodes that are at a fork and moves them before the fork.
 *
 * The algorithm iterates over the children and tries to find the last output node in a chain of output nodes.
 * It then moves all output nodes before that main output node. All other children (and the children of the output nodes)
 * are inserted after the main output node.
 */
class standalone_MergeOutputs extends standalone_BottomUpOptimizer {
    run(node) {
        const children = [...node.children];
        const hasOutputChild = standalone_some(children, child => child instanceof standalone_OutputNode);
        if (!hasOutputChild || node.numChildren() <= 1) {
            return;
        }
        const otherChildren = [];
        // The output node we will connect all other nodes to.
        // Output nodes will be added before the new node, other nodes after.
        let mainOutput;
        for (const child of children) {
            if (child instanceof standalone_OutputNode) {
                let lastOutput = child;
                while (lastOutput.numChildren() === 1) {
                    const [theChild] = lastOutput.children;
                    if (theChild instanceof standalone_OutputNode) {
                        lastOutput = theChild;
                    }
                    else {
                        break;
                    }
                }
                otherChildren.push(...lastOutput.children);
                if (mainOutput) {
                    // Move the output nodes before the mainOutput. We do this by setting
                    // the parent of the first not to the parent of the main output and
                    // the main output's parent to the last output.
                    // note: the child is the first output
                    node.removeChild(child);
                    child.parent = mainOutput.parent;
                    mainOutput.parent.removeChild(mainOutput);
                    mainOutput.parent = lastOutput;
                    this.setModified();
                }
                else {
                    mainOutput = lastOutput;
                }
            }
            else {
                otherChildren.push(child);
            }
        }
        if (otherChildren.length) {
            this.setModified();
            for (const child of otherChildren) {
                child.parent.removeChild(child);
                child.parent = mainOutput;
            }
        }
    }
}
//# sourceMappingURL=optimizers.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/joinaggregate.js




/**
 * A class for the join aggregate transform nodes.
 */
class standalone_JoinAggregateTransformNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_JoinAggregateTransformNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
    }
    addDimensions(fields) {
        this.transform.groupby = standalone_unique(this.transform.groupby.concat(fields), d => d);
    }
    dependentFields() {
        const out = new Set();
        if (this.transform.groupby) {
            this.transform.groupby.forEach(out.add, out);
        }
        this.transform.joinaggregate
            .map(w => w.field)
            .filter(f => f !== undefined)
            .forEach(out.add, out);
        return out;
    }
    producedFields() {
        return new Set(this.transform.joinaggregate.map(this.getDefaultName));
    }
    getDefaultName(joinAggregateFieldDef) {
        return joinAggregateFieldDef.as ?? standalone_vgField(joinAggregateFieldDef);
    }
    hash() {
        return `JoinAggregateTransform ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        const fields = [];
        const ops = [];
        const as = [];
        for (const joinaggregate of this.transform.joinaggregate) {
            ops.push(joinaggregate.op);
            as.push(this.getDefaultName(joinaggregate));
            fields.push(joinaggregate.field === undefined ? null : joinaggregate.field);
        }
        const groupby = this.transform.groupby;
        return {
            type: 'joinaggregate',
            as,
            ops,
            fields,
            ...(groupby !== undefined ? { groupby } : {})
        };
    }
}
//# sourceMappingURL=joinaggregate.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/filterinvalid.js






class standalone_FilterInvalidNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_FilterInvalidNode(null, { ...this.filter });
    }
    constructor(parent, filter) {
        super(parent);
        this.filter = filter;
    }
    static make(parent, model, dataSourcesForHandlingInvalidValues) {
        const { config, markDef } = model;
        const { marks, scales } = dataSourcesForHandlingInvalidValues;
        if (marks === 'include-invalid-values' && scales === 'include-invalid-values') {
            // If neither marks nor scale domains need data source to filter null values, then don't add the filter.
            return null;
        }
        const filter = model.reduceFieldDef((aggregator, fieldDef, channel) => {
            const scaleComponent = standalone_isScaleChannel(channel) && model.getScaleComponent(channel);
            if (scaleComponent) {
                const scaleType = scaleComponent.get('type');
                const { aggregate } = fieldDef;
                const invalidDataMode = standalone_getScaleInvalidDataMode({
                    scaleChannel: channel,
                    markDef,
                    config,
                    scaleType,
                    isCountAggregate: standalone_isCountingAggregateOp(aggregate)
                });
                // If the invalid data mode is include or always-valid, we don't need to filter invalid values as the scale can handle invalid values.
                if (invalidDataMode !== 'show' && invalidDataMode !== 'always-valid') {
                    aggregator[fieldDef.field] = fieldDef; // we know that the fieldDef is a typed field def
                }
            }
            return aggregator;
        }, {});
        if (!standalone_util_keys(filter).length) {
            return null;
        }
        return new standalone_FilterInvalidNode(parent, filter);
    }
    dependentFields() {
        return new Set(standalone_util_keys(this.filter));
    }
    producedFields() {
        return new Set(); // filter does not produce any new fields
    }
    hash() {
        return `FilterInvalid ${standalone_util_hash(this.filter)}`;
    }
    /**
     * Create the VgTransforms for each of the filtered fields.
     */
    assemble() {
        const filters = standalone_util_keys(this.filter).reduce((vegaFilters, field) => {
            const fieldDef = this.filter[field];
            const ref = standalone_vgField(fieldDef, { expr: 'datum' });
            if (fieldDef !== null) {
                if (fieldDef.type === 'temporal') {
                    vegaFilters.push(`(isDate(${ref}) || (${standalone_isValidFiniteNumberExpr(ref)}))`);
                }
                else if (fieldDef.type === 'quantitative') {
                    vegaFilters.push(standalone_isValidFiniteNumberExpr(ref));
                }
                else {
                    // should never get here
                }
            }
            return vegaFilters;
        }, []);
        return filters.length > 0
            ? {
                type: 'filter',
                expr: filters.join(' && ')
            }
            : null;
    }
}
function standalone_isValidFiniteNumberExpr(ref) {
    return `isValid(${ref}) && isFinite(+${ref})`;
}
//# sourceMappingURL=filterinvalid.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/stack.js






function standalone_getStackByFields(model) {
    return model.stack.stackBy.reduce((fields, by) => {
        const fieldDef = by.fieldDef;
        const _field = standalone_vgField(fieldDef);
        if (_field) {
            fields.push(_field);
        }
        return fields;
    }, []);
}
function standalone_isValidAsArray(as) {
    return standalone_vega_util_module_isArray(as) && as.every(s => standalone_vega_util_module_isString(s)) && as.length > 1;
}
class standalone_StackNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_StackNode(null, standalone_duplicate(this._stack));
    }
    constructor(parent, stack) {
        super(parent);
        this._stack = stack;
    }
    static makeFromTransform(parent, stackTransform) {
        const { stack, groupby, as, offset = 'zero' } = stackTransform;
        const sortFields = [];
        const sortOrder = [];
        if (stackTransform.sort !== undefined) {
            for (const sortField of stackTransform.sort) {
                sortFields.push(sortField.field);
                sortOrder.push(standalone_getFirstDefined(sortField.order, 'ascending'));
            }
        }
        const sort = {
            field: sortFields,
            order: sortOrder
        };
        let normalizedAs;
        if (standalone_isValidAsArray(as)) {
            normalizedAs = as;
        }
        else if (standalone_vega_util_module_isString(as)) {
            normalizedAs = [as, `${as}_end`];
        }
        else {
            normalizedAs = [`${stackTransform.stack}_start`, `${stackTransform.stack}_end`];
        }
        return new standalone_StackNode(parent, {
            dimensionFieldDefs: [],
            stackField: stack,
            groupby,
            offset,
            sort,
            facetby: [],
            as: normalizedAs
        });
    }
    static makeFromEncoding(parent, model) {
        const stackProperties = model.stack;
        const { encoding } = model;
        if (!stackProperties) {
            return null;
        }
        const { groupbyChannels, fieldChannel, offset, impute } = stackProperties;
        const dimensionFieldDefs = groupbyChannels
            .map(groupbyChannel => {
            const cDef = encoding[groupbyChannel];
            return standalone_getFieldDef(cDef);
        })
            .filter(def => !!def);
        const stackby = standalone_getStackByFields(model);
        const orderDef = model.encoding.order;
        let sort;
        if (standalone_vega_util_module_isArray(orderDef) || standalone_isFieldDef(orderDef)) {
            sort = standalone_sortParams(orderDef);
        }
        else {
            const sortOrder = standalone_isOrderOnlyDef(orderDef) ? orderDef.sort : fieldChannel === 'y' ? 'descending' : 'ascending';
            // default = descending by stackFields
            // FIXME is the default here correct for binned fields?
            sort = stackby.reduce((s, field) => {
                if (!s.field.includes(field)) {
                    s.field.push(field);
                    s.order.push(sortOrder);
                }
                return s;
            }, { field: [], order: [] });
        }
        return new standalone_StackNode(parent, {
            dimensionFieldDefs,
            stackField: model.vgField(fieldChannel),
            facetby: [],
            stackby,
            sort,
            offset,
            impute,
            as: [
                model.vgField(fieldChannel, { suffix: 'start', forAs: true }),
                model.vgField(fieldChannel, { suffix: 'end', forAs: true })
            ]
        });
    }
    get stack() {
        return this._stack;
    }
    addDimensions(fields) {
        this._stack.facetby.push(...fields);
    }
    dependentFields() {
        const out = new Set();
        out.add(this._stack.stackField);
        this.getGroupbyFields().forEach(out.add, out);
        this._stack.facetby.forEach(out.add, out);
        this._stack.sort.field.forEach(out.add, out);
        return out;
    }
    producedFields() {
        return new Set(this._stack.as);
    }
    hash() {
        return `Stack ${standalone_util_hash(this._stack)}`;
    }
    getGroupbyFields() {
        const { dimensionFieldDefs, impute, groupby } = this._stack;
        if (dimensionFieldDefs.length > 0) {
            return dimensionFieldDefs
                .map(dimensionFieldDef => {
                if (dimensionFieldDef.bin) {
                    if (impute) {
                        // For binned group by field with impute, we calculate bin_mid
                        // as we cannot impute two fields simultaneously
                        return [standalone_vgField(dimensionFieldDef, { binSuffix: 'mid' })];
                    }
                    return [
                        // For binned group by field without impute, we need both bin (start) and bin_end
                        standalone_vgField(dimensionFieldDef, {}),
                        standalone_vgField(dimensionFieldDef, { binSuffix: 'end' })
                    ];
                }
                return [standalone_vgField(dimensionFieldDef)];
            })
                .flat();
        }
        return groupby ?? [];
    }
    assemble() {
        const transform = [];
        const { facetby, dimensionFieldDefs, stackField: field, stackby, sort, offset, impute, as } = this._stack;
        // Impute
        if (impute) {
            for (const dimensionFieldDef of dimensionFieldDefs) {
                const { bandPosition = 0.5, bin } = dimensionFieldDef;
                if (bin) {
                    // As we can only impute one field at a time, we need to calculate
                    // mid point for a binned field
                    const binStart = standalone_vgField(dimensionFieldDef, { expr: 'datum' });
                    const binEnd = standalone_vgField(dimensionFieldDef, { expr: 'datum', binSuffix: 'end' });
                    transform.push({
                        type: 'formula',
                        expr: `${standalone_isValidFiniteNumberExpr(binStart)} ? ${bandPosition}*${binStart}+${1 - bandPosition}*${binEnd} : ${binStart}`,
                        as: standalone_vgField(dimensionFieldDef, { binSuffix: 'mid', forAs: true })
                    });
                }
                transform.push({
                    type: 'impute',
                    field,
                    groupby: [...stackby, ...facetby],
                    key: standalone_vgField(dimensionFieldDef, { binSuffix: 'mid' }),
                    method: 'value',
                    value: 0
                });
            }
        }
        // Stack
        transform.push({
            type: 'stack',
            groupby: [...this.getGroupbyFields(), ...facetby],
            field,
            sort,
            as,
            offset
        });
        return transform;
    }
}
//# sourceMappingURL=stack.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/window.js





/**
 * A class for the window transform nodes
 */
class standalone_WindowTransformNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_WindowTransformNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
    }
    addDimensions(fields) {
        this.transform.groupby = standalone_unique(this.transform.groupby.concat(fields), d => d);
    }
    dependentFields() {
        const out = new Set();
        (this.transform.groupby ?? []).forEach(out.add, out);
        (this.transform.sort ?? []).forEach(m => out.add(m.field));
        this.transform.window
            .map(w => w.field)
            .filter(f => f !== undefined)
            .forEach(out.add, out);
        return out;
    }
    producedFields() {
        return new Set(this.transform.window.map(this.getDefaultName));
    }
    getDefaultName(windowFieldDef) {
        return windowFieldDef.as ?? standalone_vgField(windowFieldDef);
    }
    hash() {
        return `WindowTransform ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        const fields = [];
        const ops = [];
        const as = [];
        const params = [];
        for (const window of this.transform.window) {
            ops.push(window.op);
            as.push(this.getDefaultName(window));
            params.push(window.param === undefined ? null : window.param);
            fields.push(window.field === undefined ? null : window.field);
        }
        const frame = this.transform.frame;
        const groupby = this.transform.groupby;
        if (frame && frame[0] === null && frame[1] === null && ops.every(o => standalone_isAggregateOp(o))) {
            // when the window does not rely on any particular window ops or frame, switch to a simpler and more efficient joinaggregate
            return {
                type: 'joinaggregate',
                as,
                ops: ops,
                fields,
                ...(groupby !== undefined ? { groupby } : {})
            };
        }
        const sortFields = [];
        const sortOrder = [];
        if (this.transform.sort !== undefined) {
            for (const sortField of this.transform.sort) {
                sortFields.push(sortField.field);
                sortOrder.push(sortField.order ?? 'ascending');
            }
        }
        const sort = {
            field: sortFields,
            order: sortOrder
        };
        const ignorePeers = this.transform.ignorePeers;
        return {
            type: 'window',
            params,
            as,
            ops,
            fields,
            sort,
            ...(ignorePeers !== undefined ? { ignorePeers } : {}),
            ...(groupby !== undefined ? { groupby } : {}),
            ...(frame !== undefined ? { frame } : {})
        };
    }
}
//# sourceMappingURL=window.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/subtree.js








/**
 * Clones the subtree and ignores output nodes except for the leaves, which are renamed.
 */
function standalone_cloneSubtree(facet) {
    function clone(node) {
        if (!(node instanceof standalone_FacetNode)) {
            const copy = node.clone();
            if (copy instanceof standalone_OutputNode) {
                const newName = standalone_FACET_SCALE_PREFIX + copy.getSource();
                copy.setSource(newName);
                facet.model.component.data.outputNodes[newName] = copy;
            }
            else if (copy instanceof standalone_AggregateNode ||
                copy instanceof standalone_StackNode ||
                copy instanceof standalone_WindowTransformNode ||
                copy instanceof standalone_JoinAggregateTransformNode) {
                copy.addDimensions(facet.fields);
            }
            for (const n of node.children.flatMap(clone)) {
                n.parent = copy;
            }
            return [copy];
        }
        return node.children.flatMap(clone);
    }
    return clone;
}
/**
 * Move facet nodes down to the next fork or output node. Also pull the main output with the facet node.
 * After moving down the facet node, make a copy of the subtree and make it a child of the main output.
 */
function standalone_moveFacetDown(node) {
    if (node instanceof standalone_FacetNode) {
        if (node.numChildren() === 1 && !(node.children[0] instanceof standalone_OutputNode)) {
            // move down until we hit a fork or output node
            const child = node.children[0];
            if (child instanceof standalone_AggregateNode ||
                child instanceof standalone_StackNode ||
                child instanceof standalone_WindowTransformNode ||
                child instanceof standalone_JoinAggregateTransformNode) {
                child.addDimensions(node.fields);
            }
            child.swapWithParent();
            standalone_moveFacetDown(node);
        }
        else {
            // move main to facet
            const facetMain = node.model.component.data.main;
            standalone_moveMainDownToFacet(facetMain);
            // replicate the subtree and place it before the facet's main node
            const cloner = standalone_cloneSubtree(node);
            const copy = node.children.map(cloner).flat();
            for (const c of copy) {
                c.parent = facetMain;
            }
        }
    }
    else {
        node.children.map(standalone_moveFacetDown);
    }
}
function standalone_moveMainDownToFacet(node) {
    if (node instanceof standalone_OutputNode && node.type === standalone_DataSourceType.Main) {
        if (node.numChildren() === 1) {
            const child = node.children[0];
            if (!(child instanceof standalone_FacetNode)) {
                child.swapWithParent();
                standalone_moveMainDownToFacet(node);
            }
        }
    }
}
//# sourceMappingURL=subtree.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/optimize.js



const standalone_FACET_SCALE_PREFIX = 'scale_';
const standalone_MAX_OPTIMIZATION_RUNS = 5;
/**
 * Iterates over a dataflow graph and checks whether all links are consistent.
 */
function standalone_checkLinks(nodes) {
    for (const node of nodes) {
        for (const child of node.children) {
            if (child.parent !== node) {
                // log.error('Dataflow graph is inconsistent.', node, child);
                return false;
            }
        }
        if (!standalone_checkLinks(node.children)) {
            return false;
        }
    }
    return true;
}
/**
 * Run the specified optimizer on the provided nodes.
 *
 * @param optimizer The optimizer instance to run.
 * @param nodes A set of nodes to optimize.
 */
function standalone_runOptimizer(optimizer, nodes) {
    let modified = false;
    for (const node of nodes) {
        modified = optimizer.optimize(node) || modified;
    }
    return modified;
}
function standalone_optimizationDataflowHelper(dataComponent, model, firstPass) {
    let roots = dataComponent.sources;
    let modified = false;
    modified = standalone_runOptimizer(new standalone_RemoveUnnecessaryOutputNodes(), roots) || modified;
    modified = standalone_runOptimizer(new standalone_RemoveUnnecessaryIdentifierNodes(model), roots) || modified;
    // remove source nodes that don't have any children because they also don't have output nodes
    roots = roots.filter(r => r.numChildren() > 0);
    modified = standalone_runOptimizer(new standalone_RemoveUnusedSubtrees(), roots) || modified;
    roots = roots.filter(r => r.numChildren() > 0);
    if (!firstPass) {
        // Only run these optimizations after the optimizer has moved down the facet node.
        // With this change, we can be more aggressive in the optimizations.
        modified = standalone_runOptimizer(new standalone_MoveParseUp(), roots) || modified;
        modified = standalone_runOptimizer(new standalone_MergeBins(model), roots) || modified;
        modified = standalone_runOptimizer(new standalone_RemoveDuplicateTimeUnits(), roots) || modified;
        modified = standalone_runOptimizer(new standalone_MergeParse(), roots) || modified;
        modified = standalone_runOptimizer(new standalone_MergeAggregates(), roots) || modified;
        modified = standalone_runOptimizer(new standalone_MergeTimeUnits(), roots) || modified;
        modified = standalone_runOptimizer(new standalone_MergeIdenticalNodes(), roots) || modified;
        modified = standalone_runOptimizer(new standalone_MergeOutputs(), roots) || modified;
    }
    dataComponent.sources = roots;
    return modified;
}
/**
 * Optimizes the dataflow of the passed in data component.
 */
function standalone_optimizeDataflow(data, model) {
    // check before optimizations
    standalone_checkLinks(data.sources);
    let firstPassCounter = 0;
    let secondPassCounter = 0;
    for (let i = 0; i < standalone_MAX_OPTIMIZATION_RUNS; i++) {
        if (!standalone_optimizationDataflowHelper(data, model, true)) {
            break;
        }
        firstPassCounter++;
    }
    // move facets down and make a copy of the subtree so that we can have scales at the top level
    data.sources.map(standalone_moveFacetDown);
    for (let i = 0; i < standalone_MAX_OPTIMIZATION_RUNS; i++) {
        if (!standalone_optimizationDataflowHelper(data, model, false)) {
            break;
        }
        secondPassCounter++;
    }
    // check after optimizations
    standalone_checkLinks(data.sources);
    if (Math.max(firstPassCounter, secondPassCounter) === standalone_MAX_OPTIMIZATION_RUNS) {
        standalone_log_warn(`Maximum optimization runs(${standalone_MAX_OPTIMIZATION_RUNS}) reached.`);
    }
}
//# sourceMappingURL=optimize.js.map
;// ../../node_modules/vega-lite/build/src/compile/signal.js
/**
 * A class that behaves like a SignalRef but lazily generates the signal.
 * The provided generator function should use `Model.getSignalName` to use the correct signal name.
 */
class standalone_SignalRefWrapper {
    constructor(exprGenerator) {
        Object.defineProperty(this, 'signal', {
            enumerable: true,
            get: exprGenerator
        });
    }
    static fromName(rename, signalName) {
        return new standalone_SignalRefWrapper(() => rename(signalName));
    }
}
//# sourceMappingURL=signal.js.map
;// ../../node_modules/vega-lite/build/src/compile/scale/domain.js






















function standalone_domain_parseScaleDomain(model) {
    if (standalone_isUnitModel(model)) {
        standalone_parseUnitScaleDomain(model);
    }
    else {
        standalone_parseNonUnitScaleDomain(model);
    }
}
function standalone_parseUnitScaleDomain(model) {
    const localScaleComponents = model.component.scales;
    for (const channel of standalone_util_keys(localScaleComponents)) {
        const domains = standalone_parseDomainForChannel(model, channel);
        const localScaleCmpt = localScaleComponents[channel];
        localScaleCmpt.setWithExplicit('domains', domains);
        standalone_parseSelectionDomain(model, channel);
        if (model.component.data.isFaceted) {
            // get resolve from closest facet parent as this decides whether we need to refer to cloned subtree or not
            let facetParent = model;
            while (!standalone_isFacetModel(facetParent) && facetParent.parent) {
                facetParent = facetParent.parent;
            }
            const resolve = facetParent.component.resolve.scale[channel];
            if (resolve === 'shared') {
                for (const domain of domains.value) {
                    // Replace the scale domain with data output from a cloned subtree after the facet.
                    if (standalone_isDataRefDomain(domain)) {
                        // use data from cloned subtree (which is the same as data but with a prefix added once)
                        domain.data = standalone_FACET_SCALE_PREFIX + domain.data.replace(standalone_FACET_SCALE_PREFIX, '');
                    }
                }
            }
        }
    }
}
function standalone_parseNonUnitScaleDomain(model) {
    for (const child of model.children) {
        standalone_domain_parseScaleDomain(child);
    }
    const localScaleComponents = model.component.scales;
    for (const channel of standalone_util_keys(localScaleComponents)) {
        let domains;
        let selectionExtent = null;
        for (const child of model.children) {
            const childComponent = child.component.scales[channel];
            if (childComponent) {
                if (domains === undefined) {
                    domains = childComponent.getWithExplicit('domains');
                }
                else {
                    domains = standalone_mergeValuesWithExplicit(domains, childComponent.getWithExplicit('domains'), 'domains', 'scale', standalone_domainsTieBreaker);
                }
                const se = childComponent.get('selectionExtent');
                if (selectionExtent && se && selectionExtent.param !== se.param) {
                    standalone_log_warn(standalone_NEEDS_SAME_SELECTION);
                }
                selectionExtent = se;
            }
        }
        localScaleComponents[channel].setWithExplicit('domains', domains);
        if (selectionExtent) {
            localScaleComponents[channel].set('selectionExtent', selectionExtent, true);
        }
    }
}
/**
 * Remove unaggregated domain if it is not applicable
 * Add unaggregated domain if domain is not specified and config.scale.useUnaggregatedDomain is true.
 */
function standalone_normalizeUnaggregatedDomain(domain, fieldDef, scaleType, scaleConfig) {
    if (domain === 'unaggregated') {
        const { valid, reason } = standalone_canUseUnaggregatedDomain(fieldDef, scaleType);
        if (!valid) {
            standalone_log_warn(reason);
            return undefined;
        }
    }
    else if (domain === undefined && scaleConfig.useUnaggregatedDomain) {
        // Apply config if domain is not specified.
        const { valid } = standalone_canUseUnaggregatedDomain(fieldDef, scaleType);
        if (valid) {
            return 'unaggregated';
        }
    }
    return domain;
}
function standalone_parseDomainForChannel(model, channel) {
    const scaleType = model.getScaleComponent(channel).get('type');
    const { encoding } = model;
    const domain = standalone_normalizeUnaggregatedDomain(model.scaleDomain(channel), model.typedFieldDef(channel), scaleType, model.config.scale);
    if (domain !== model.scaleDomain(channel)) {
        model.specifiedScales[channel] = {
            ...model.specifiedScales[channel],
            domain
        };
    }
    // If channel is either X or Y then union them with X2 & Y2 if they exist
    if (channel === 'x' && standalone_getFieldOrDatumDef(encoding.x2)) {
        if (standalone_getFieldOrDatumDef(encoding.x)) {
            return standalone_mergeValuesWithExplicit(standalone_parseSingleChannelDomain(scaleType, domain, model, 'x'), standalone_parseSingleChannelDomain(scaleType, domain, model, 'x2'), 'domain', 'scale', standalone_domainsTieBreaker);
        }
        else {
            return standalone_parseSingleChannelDomain(scaleType, domain, model, 'x2');
        }
    }
    else if (channel === 'y' && standalone_getFieldOrDatumDef(encoding.y2)) {
        if (standalone_getFieldOrDatumDef(encoding.y)) {
            return standalone_mergeValuesWithExplicit(standalone_parseSingleChannelDomain(scaleType, domain, model, 'y'), standalone_parseSingleChannelDomain(scaleType, domain, model, 'y2'), 'domain', 'scale', standalone_domainsTieBreaker);
        }
        else {
            return standalone_parseSingleChannelDomain(scaleType, domain, model, 'y2');
        }
    }
    return standalone_parseSingleChannelDomain(scaleType, domain, model, channel);
}
function standalone_mapDomainToDataSignal(domain, type, timeUnit) {
    return domain.map(v => {
        const data = standalone_valueExpr(v, { timeUnit, type });
        return { signal: `{data: ${data}}` };
    });
}
function standalone_convertDomainIfItIsDateTime(domain, type, timeUnit) {
    // explicit value
    const normalizedTimeUnit = standalone_normalizeTimeUnit(timeUnit)?.unit;
    if (type === 'temporal' || normalizedTimeUnit) {
        return standalone_mapDomainToDataSignal(domain, type, normalizedTimeUnit);
    }
    return [domain]; // Date time won't make sense
}
function standalone_parseSingleChannelDomain(scaleType, domain, model, channel) {
    const { encoding, markDef, mark, config, stack } = model;
    const fieldOrDatumDef = standalone_getFieldOrDatumDef(encoding[channel]);
    const { type } = fieldOrDatumDef;
    const timeUnit = fieldOrDatumDef['timeUnit'];
    const dataSourceTypeForScaleDomain = standalone_getScaleDataSourceForHandlingInvalidValues({
        invalid: standalone_getMarkConfig('invalid', markDef, config),
        isPath: standalone_isPathMark(mark)
    });
    if (standalone_isDomainUnionWith(domain)) {
        const defaultDomain = standalone_parseSingleChannelDomain(scaleType, undefined, model, channel);
        const unionWith = standalone_convertDomainIfItIsDateTime(domain.unionWith, type, timeUnit);
        return standalone_makeExplicit([...unionWith, ...defaultDomain.value]);
    }
    else if (standalone_isSignalRef(domain)) {
        return standalone_makeExplicit([domain]);
    }
    else if (domain && domain !== 'unaggregated' && !standalone_isParameterDomain(domain)) {
        return standalone_makeExplicit(standalone_convertDomainIfItIsDateTime(domain, type, timeUnit));
    }
    if (stack && channel === stack.fieldChannel) {
        if (stack.offset === 'normalize') {
            return standalone_makeImplicit([[0, 1]]);
        }
        const data = model.requestDataName(dataSourceTypeForScaleDomain);
        return standalone_makeImplicit([
            {
                data,
                field: model.vgField(channel, { suffix: 'start' })
            },
            {
                data,
                field: model.vgField(channel, { suffix: 'end' })
            }
        ]);
    }
    const sort = standalone_isScaleChannel(channel) && standalone_isFieldDef(fieldOrDatumDef) ? standalone_domainSort(model, channel, scaleType) : undefined;
    if (standalone_isDatumDef(fieldOrDatumDef)) {
        const d = standalone_convertDomainIfItIsDateTime([fieldOrDatumDef.datum], type, timeUnit);
        return standalone_makeImplicit(d);
    }
    const fieldDef = fieldOrDatumDef; // now we can be sure it's a fieldDef
    if (domain === 'unaggregated') {
        const { field } = fieldOrDatumDef;
        return standalone_makeImplicit([
            {
                data: model.requestDataName(dataSourceTypeForScaleDomain),
                field: standalone_vgField({ field, aggregate: 'min' })
            },
            {
                data: model.requestDataName(dataSourceTypeForScaleDomain),
                field: standalone_vgField({ field, aggregate: 'max' })
            }
        ]);
    }
    else if (standalone_isBinning(fieldDef.bin)) {
        if (standalone_hasDiscreteDomain(scaleType)) {
            if (scaleType === 'bin-ordinal') {
                // we can omit the domain as it is inferred from the `bins` property
                return standalone_makeImplicit([]);
            }
            // ordinal bin scale takes domain from bin_range, ordered by bin start
            // This is useful for both axis-based scale (x/y) and legend-based scale (other channels).
            return standalone_makeImplicit([
                {
                    // If sort by aggregation of a specified sort field, we need to use RAW table,
                    // so we can aggregate values for the scale independently from the main aggregation.
                    data: standalone_util_isBoolean(sort)
                        ? model.requestDataName(dataSourceTypeForScaleDomain)
                        : model.requestDataName(standalone_DataSourceType.Raw),
                    // Use range if we added it and the scale does not support computing a range as a signal.
                    field: model.vgField(channel, standalone_binRequiresRange(fieldDef, channel) ? { binSuffix: 'range' } : {}),
                    // we have to use a sort object if sort = true to make the sort correct by bin start
                    sort: sort === true || !standalone_vega_util_module_isObject(sort)
                        ? {
                            field: model.vgField(channel, {}),
                            op: 'min' // min or max doesn't matter since we sort by the start of the bin range
                        }
                        : sort
                }
            ]);
        }
        else {
            // continuous scales
            const { bin } = fieldDef;
            if (standalone_isBinning(bin)) {
                const binSignal = standalone_getBinSignalName(model, fieldDef.field, bin);
                return standalone_makeImplicit([
                    new standalone_SignalRefWrapper(() => {
                        const signal = model.getSignalName(binSignal);
                        return `[${signal}.start, ${signal}.stop]`;
                    })
                ]);
            }
            else {
                return standalone_makeImplicit([
                    {
                        data: model.requestDataName(dataSourceTypeForScaleDomain),
                        field: model.vgField(channel, {})
                    }
                ]);
            }
        }
    }
    else if (fieldDef.timeUnit && standalone_util_contains(['time', 'utc'], scaleType)) {
        const fieldDef2 = encoding[standalone_getSecondaryRangeChannel(channel)];
        if (standalone_hasBandEnd(fieldDef, fieldDef2, markDef, config)) {
            const data = model.requestDataName(dataSourceTypeForScaleDomain);
            const bandPosition = standalone_getBandPosition({ fieldDef, fieldDef2, markDef, config });
            const isRectWithOffset = standalone_isRectBasedMark(mark) && bandPosition !== 0.5 && standalone_isXorY(channel);
            return standalone_makeImplicit([
                {
                    data,
                    field: model.vgField(channel, isRectWithOffset ? { suffix: standalone_OFFSETTED_RECT_START_SUFFIX } : {})
                },
                {
                    data,
                    field: model.vgField(channel, { suffix: isRectWithOffset ? standalone_OFFSETTED_RECT_END_SUFFIX : 'end' })
                }
            ]);
        }
    }
    if (sort) {
        return standalone_makeImplicit([
            {
                // If sort by aggregation of a specified sort field, we need to use RAW table,
                // so we can aggregate values for the scale independently from the main aggregation.
                data: standalone_util_isBoolean(sort)
                    ? model.requestDataName(dataSourceTypeForScaleDomain)
                    : model.requestDataName(standalone_DataSourceType.Raw),
                field: model.vgField(channel),
                sort
            }
        ]);
    }
    else {
        return standalone_makeImplicit([
            {
                data: model.requestDataName(dataSourceTypeForScaleDomain),
                field: model.vgField(channel)
            }
        ]);
    }
}
function standalone_normalizeSortField(sort, isStackedMeasure) {
    const { op, field, order } = sort;
    return {
        // Apply default op
        op: op ?? (isStackedMeasure ? 'sum' : standalone_DEFAULT_SORT_OP),
        // flatten nested fields
        ...(field ? { field: standalone_replacePathInField(field) } : {}),
        ...(order ? { order } : {})
    };
}
function standalone_parseSelectionDomain(model, channel) {
    const scale = model.component.scales[channel];
    const spec = model.specifiedScales[channel].domain;
    const bin = model.fieldDef(channel)?.bin;
    const domain = standalone_isParameterDomain(spec) ? spec : undefined;
    const extent = standalone_isBinParams(bin) && standalone_isParameterExtent(bin.extent) ? bin.extent : undefined;
    if (domain || extent) {
        // As scale parsing occurs before selection parsing, we cannot set
        // domainRaw directly. So instead, we store the selectionExtent on
        // the scale component, and then add domainRaw during scale assembly.
        scale.set('selectionExtent', domain ?? extent, true);
    }
}
function standalone_domainSort(model, channel, scaleType) {
    if (!standalone_hasDiscreteDomain(scaleType)) {
        return undefined;
    }
    // save to cast as the only exception is the geojson type for shape, which would not generate a scale
    const fieldDef = model.fieldDef(channel);
    const sort = fieldDef.sort;
    // if the sort is specified with array, use the derived sort index field
    if (standalone_isSortArray(sort)) {
        return {
            op: 'min',
            field: standalone_sortArrayIndexField(fieldDef, channel),
            order: 'ascending'
        };
    }
    const { stack } = model;
    const stackDimensions = stack
        ? new Set([...stack.groupbyFields, ...stack.stackBy.map(s => s.fieldDef.field)])
        : undefined;
    // Sorted based on an aggregate calculation over a specified sort field (only for ordinal scale)
    if (standalone_isSortField(sort)) {
        const isStackedMeasure = stack && !stackDimensions.has(sort.field);
        return standalone_normalizeSortField(sort, isStackedMeasure);
    }
    else if (standalone_isSortByEncoding(sort)) {
        const { encoding, order } = sort;
        const fieldDefToSortBy = model.fieldDef(encoding);
        const { aggregate, field } = fieldDefToSortBy;
        const isStackedMeasure = stack && !stackDimensions.has(field);
        if (standalone_isArgminDef(aggregate) || standalone_isArgmaxDef(aggregate)) {
            return standalone_normalizeSortField({
                field: standalone_vgField(fieldDefToSortBy),
                order
            }, isStackedMeasure);
        }
        else if (standalone_isAggregateOp(aggregate) || !aggregate) {
            return standalone_normalizeSortField({
                op: aggregate, // can't be argmin/argmax since we don't support them in encoding field def
                field,
                order
            }, isStackedMeasure);
        }
    }
    else if (sort === 'descending') {
        return {
            op: 'min',
            field: model.vgField(channel),
            order: 'descending'
        };
    }
    else if (standalone_util_contains(['ascending', undefined /* default =ascending*/], sort)) {
        return true;
    }
    // sort == null
    return undefined;
}
/**
 * Determine if a scale can use unaggregated domain.
 * @return {Boolean} Returns true if all of the following conditions apply:
 * 1. `scale.domain` is `unaggregated`
 * 2. Aggregation function is not `count` or `sum`
 * 3. The scale is quantitative or time scale.
 */
function standalone_canUseUnaggregatedDomain(fieldDef, scaleType) {
    const { aggregate, type } = fieldDef;
    if (!aggregate) {
        return {
            valid: false,
            reason: standalone_unaggregateDomainHasNoEffectForRawField(fieldDef)
        };
    }
    if (standalone_vega_util_module_isString(aggregate) && !standalone_SHARED_DOMAIN_OPS.has(aggregate)) {
        return {
            valid: false,
            reason: standalone_unaggregateDomainWithNonSharedDomainOp(aggregate)
        };
    }
    if (type === 'quantitative') {
        if (scaleType === 'log') {
            return {
                valid: false,
                reason: standalone_unaggregatedDomainWithLogScale(fieldDef)
            };
        }
    }
    return { valid: true };
}
/**
 * Tie breaker for mergeValuesWithExplicit for domains. We concat the specified values.
 */
function standalone_domainsTieBreaker(v1, v2, property, propertyOf) {
    if (v1.explicit && v2.explicit) {
        standalone_log_warn(standalone_mergeConflictingDomainProperty(property, propertyOf, v1.value, v2.value));
    }
    // If equal score, concat the domains so that we union them later.
    return { explicit: v1.explicit, value: [...v1.value, ...v2.value] };
}
/**
 * Converts an array of domains to a single Vega scale domain.
 */
function standalone_mergeDomains(domains) {
    const uniqueDomains = standalone_unique(domains.map(domain => {
        // ignore sort property when computing the unique domains
        if (standalone_isDataRefDomain(domain)) {
            const { sort: _s, ...domainWithoutSort } = domain;
            return domainWithoutSort;
        }
        return domain;
    }), standalone_util_hash);
    const sorts = standalone_unique(domains
        .map(d => {
        if (standalone_isDataRefDomain(d)) {
            const s = d.sort;
            if (s !== undefined && !standalone_util_isBoolean(s)) {
                if ('op' in s && s.op === 'count') {
                    // let's make sure that if op is count, we don't use a field
                    delete s.field;
                }
                if (s.order === 'ascending') {
                    // drop order: ascending as it is the default
                    delete s.order;
                }
            }
            return s;
        }
        return undefined;
    })
        .filter(s => s !== undefined), standalone_util_hash);
    if (uniqueDomains.length === 0) {
        return undefined;
    }
    else if (uniqueDomains.length === 1) {
        const domain = domains[0];
        if (standalone_isDataRefDomain(domain) && sorts.length > 0) {
            let sort = sorts[0];
            if (sorts.length > 1) {
                standalone_log_warn(standalone_MORE_THAN_ONE_SORT);
                // Get sorts with non-default ops
                const filteredSorts = sorts.filter(s => standalone_vega_util_module_isObject(s) && 'op' in s && s.op !== 'min');
                if (sorts.every(s => standalone_vega_util_module_isObject(s) && 'op' in s) && filteredSorts.length === 1) {
                    sort = filteredSorts[0];
                }
                else {
                    sort = true;
                }
            }
            else {
                // Simplify domain sort by removing field and op when the field is the same as the domain field.
                if (standalone_vega_util_module_isObject(sort) && 'field' in sort) {
                    const sortField = sort.field;
                    if (domain.field === sortField) {
                        sort = sort.order ? { order: sort.order } : true;
                    }
                }
            }
            return {
                ...domain,
                sort
            };
        }
        return domain;
    }
    // only keep sort properties that work with unioned domains
    const unionDomainSorts = standalone_unique(sorts.map(s => {
        if (standalone_util_isBoolean(s) || !('op' in s) || (standalone_vega_util_module_isString(s.op) && standalone_vega_util_module_has(standalone_MULTIDOMAIN_SORT_OP_INDEX, s.op))) {
            return s;
        }
        standalone_log_warn(standalone_domainSortDropped(s));
        return true;
    }), standalone_util_hash);
    let sort;
    if (unionDomainSorts.length === 1) {
        sort = unionDomainSorts[0];
    }
    else if (unionDomainSorts.length > 1) {
        standalone_log_warn(standalone_MORE_THAN_ONE_SORT);
        sort = true;
    }
    const allData = standalone_unique(domains.map(d => {
        if (standalone_isDataRefDomain(d)) {
            return d.data;
        }
        return null;
    }), x => x);
    if (allData.length === 1 && allData[0] !== null) {
        // create a union domain of different fields with a single data source
        const domain = {
            data: allData[0],
            fields: uniqueDomains.map(d => d.field),
            ...(sort ? { sort } : {})
        };
        return domain;
    }
    return { fields: uniqueDomains, ...(sort ? { sort } : {}) };
}
/**
 * Return a field if a scale uses a single field.
 * Return `undefined` otherwise.
 */
function standalone_getFieldFromDomain(domain) {
    if (standalone_isDataRefDomain(domain) && standalone_vega_util_module_isString(domain.field)) {
        return domain.field;
    }
    else if (standalone_isDataRefUnionedDomain(domain)) {
        let field;
        for (const nonUnionDomain of domain.fields) {
            if (standalone_isDataRefDomain(nonUnionDomain) && standalone_vega_util_module_isString(nonUnionDomain.field)) {
                if (!field) {
                    field = nonUnionDomain.field;
                }
                else if (field !== nonUnionDomain.field) {
                    standalone_log_warn(standalone_FACETED_INDEPENDENT_DIFFERENT_SOURCES);
                    return field;
                }
            }
        }
        standalone_log_warn(standalone_FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES);
        return field;
    }
    else if (standalone_isFieldRefUnionDomain(domain)) {
        standalone_log_warn(standalone_FACETED_INDEPENDENT_SAME_SOURCE);
        const field = domain.fields[0];
        return standalone_vega_util_module_isString(field) ? field : undefined;
    }
    return undefined;
}
function standalone_assembleDomain(model, channel) {
    const scaleComponent = model.component.scales[channel];
    const domains = scaleComponent.get('domains').map((domain) => {
        // Correct references to data as the original domain's data was determined
        // in parseScale, which happens before parseData. Thus the original data
        // reference can be incorrect.
        if (standalone_isDataRefDomain(domain)) {
            domain.data = model.lookupDataSource(domain.data);
        }
        return domain;
    });
    // domains is an array that has to be merged into a single vega domain
    return standalone_mergeDomains(domains);
}
//# sourceMappingURL=domain.js.map
;// ../../node_modules/vega-lite/build/src/compile/scale/assemble.js







function standalone_assembleScales(model) {
    if (standalone_isLayerModel(model) || standalone_isConcatModel(model)) {
        // For concat and layer, include scales of children too
        return model.children.reduce((scales, child) => {
            return scales.concat(standalone_assembleScales(child));
        }, standalone_assembleScalesForModel(model));
    }
    else {
        // For facet, child scales would not be included in the parent's scope.
        // For unit, there is no child.
        return standalone_assembleScalesForModel(model);
    }
}
function standalone_assembleScalesForModel(model) {
    return standalone_util_keys(model.component.scales).reduce((scales, channel) => {
        const scaleComponent = model.component.scales[channel];
        if (scaleComponent.merged) {
            // Skipped merged scales
            return scales;
        }
        const scale = scaleComponent.combine();
        const { name, type, selectionExtent, domains: _d, range: _r, reverse, ...otherScaleProps } = scale;
        const range = standalone_assembleScaleRange(scale.range, name, channel, model);
        const domain = standalone_assembleDomain(model, channel);
        const domainRaw = selectionExtent
            ? standalone_assembleSelectionScaleDomain(model, selectionExtent, scaleComponent, domain)
            : null;
        scales.push({
            name,
            type,
            ...(domain ? { domain } : {}),
            ...(domainRaw ? { domainRaw } : {}),
            range,
            ...(reverse !== undefined ? { reverse: reverse } : {}),
            ...otherScaleProps
        });
        return scales;
    }, []);
}
function standalone_assembleScaleRange(scaleRange, scaleName, channel, model) {
    // add signals to x/y range
    if (standalone_isXorY(channel)) {
        if (standalone_isVgRangeStep(scaleRange)) {
            // For width/height step, use a signal created in layout assemble instead of a constant step.
            return {
                step: { signal: `${scaleName}_step` }
            };
        }
    }
    else if (standalone_vega_util_module_isObject(scaleRange) && standalone_isDataRefDomain(scaleRange)) {
        return {
            ...scaleRange,
            data: model.lookupDataSource(scaleRange.data)
        };
    }
    return scaleRange;
}
//# sourceMappingURL=assemble.js.map
;// ../../node_modules/vega-lite/build/src/compile/scale/component.js




class standalone_ScaleComponent extends standalone_Split {
    constructor(name, typeWithExplicit) {
        super({}, // no initial explicit property
        { name } // name as initial implicit property
        );
        this.merged = false;
        this.setWithExplicit('type', typeWithExplicit);
    }
    /**
     * Whether the scale definitely includes or not include zero in the domain
     */
    domainHasZero() {
        const scaleType = this.get('type');
        if (standalone_util_contains([standalone_ScaleType.LOG, standalone_ScaleType.TIME, standalone_ScaleType.UTC], scaleType)) {
            // Log scales cannot have zero.
            // Zero in time scale is arbitrary, and does not affect ratio.
            // (Time is an interval level of measurement, not ratio).
            // See https://en.wikipedia.org/wiki/Level_of_measurement for more info.
            return 'definitely-not';
        }
        const scaleZero = this.get('zero');
        if (scaleZero === true ||
            // If zero is undefined, linear/sqrt/pow scales have zero by default.
            (scaleZero === undefined && standalone_util_contains([standalone_ScaleType.LINEAR, standalone_ScaleType.SQRT, standalone_ScaleType.POW], scaleType))) {
            return 'definitely';
        }
        const domains = this.get('domains');
        if (domains.length > 0) {
            let hasExplicitDomainWithZero = false;
            let hasExplicitDomainWithoutZero = false;
            let hasDomainBasedOnField = false;
            for (const d of domains) {
                if (standalone_vega_util_module_isArray(d)) {
                    const first = d[0];
                    const last = d[d.length - 1];
                    if (standalone_isNumber(first) && standalone_isNumber(last)) {
                        if (first <= 0 && last >= 0) {
                            hasExplicitDomainWithZero = true;
                            continue;
                        }
                        else {
                            hasExplicitDomainWithoutZero = true;
                            continue;
                        }
                    }
                }
                hasDomainBasedOnField = true;
            }
            if (hasExplicitDomainWithZero) {
                return 'definitely';
            }
            else if (hasExplicitDomainWithoutZero && !hasDomainBasedOnField) {
                return 'definitely-not';
            }
        }
        return 'maybe';
    }
}
//# sourceMappingURL=component.js.map
;// ../../node_modules/vega-lite/build/src/compile/scale/range.js



















const standalone_RANGE_PROPERTIES = ['range', 'scheme'];
function standalone_parseUnitScaleRange(model) {
    const localScaleComponents = model.component.scales;
    // use SCALE_CHANNELS instead of scales[channel] to ensure that x, y come first!
    for (const channel of standalone_SCALE_CHANNELS) {
        const localScaleCmpt = localScaleComponents[channel];
        if (!localScaleCmpt) {
            continue;
        }
        const rangeWithExplicit = standalone_parseRangeForChannel(channel, model);
        localScaleCmpt.setWithExplicit('range', rangeWithExplicit);
    }
}
function standalone_getBinStepSignal(model, channel) {
    const fieldDef = model.fieldDef(channel);
    if (fieldDef?.bin) {
        const { bin, field } = fieldDef;
        const sizeType = standalone_getSizeChannel(channel);
        const sizeSignal = model.getName(sizeType);
        if (standalone_vega_util_module_isObject(bin) && bin.binned && bin.step !== undefined) {
            return new standalone_SignalRefWrapper(() => {
                const scaleName = model.scaleName(channel);
                const binCount = `(domain("${scaleName}")[1] - domain("${scaleName}")[0]) / ${bin.step}`;
                return `${model.getSignalName(sizeSignal)} / (${binCount})`;
            });
        }
        else if (standalone_isBinning(bin)) {
            const binSignal = standalone_getBinSignalName(model, field, bin);
            // TODO: extract this to be range step signal
            return new standalone_SignalRefWrapper(() => {
                const updatedName = model.getSignalName(binSignal);
                const binCount = `(${updatedName}.stop - ${updatedName}.start) / ${updatedName}.step`;
                return `${model.getSignalName(sizeSignal)} / (${binCount})`;
            });
        }
    }
    return undefined;
}
/**
 * Return mixins that includes one of the Vega range types (explicit range, range.step, range.scheme).
 */
function standalone_parseRangeForChannel(channel, model) {
    const specifiedScale = model.specifiedScales[channel];
    const { size } = model;
    const mergedScaleCmpt = model.getScaleComponent(channel);
    const scaleType = mergedScaleCmpt.get('type');
    // Check if any of the range properties is specified.
    // If so, check if it is compatible and make sure that we only output one of the properties
    for (const property of standalone_RANGE_PROPERTIES) {
        if (specifiedScale[property] !== undefined) {
            const supportedByScaleType = standalone_scaleTypeSupportProperty(scaleType, property);
            const channelIncompatability = standalone_channelScalePropertyIncompatability(channel, property);
            if (!supportedByScaleType) {
                standalone_log_warn(standalone_scalePropertyNotWorkWithScaleType(scaleType, property, channel));
            }
            else if (channelIncompatability) {
                // channel
                standalone_log_warn(channelIncompatability);
            }
            else {
                switch (property) {
                    case 'range': {
                        const range = specifiedScale.range;
                        if (standalone_vega_util_module_isArray(range)) {
                            if (standalone_isXorY(channel)) {
                                return standalone_makeExplicit(range.map(v => {
                                    if (v === 'width' || v === 'height') {
                                        // get signal for width/height
                                        // Just like default range logic below, we use SignalRefWrapper to account for potential merges and renames.
                                        const sizeSignal = model.getName(v);
                                        const getSignalName = model.getSignalName.bind(model);
                                        return standalone_SignalRefWrapper.fromName(getSignalName, sizeSignal);
                                    }
                                    return v;
                                }));
                            }
                        }
                        else if (standalone_vega_util_module_isObject(range)) {
                            return standalone_makeExplicit({
                                data: model.requestDataName(standalone_DataSourceType.Main),
                                field: range.field,
                                sort: { op: 'min', field: model.vgField(channel) }
                            });
                        }
                        return standalone_makeExplicit(range);
                    }
                    case 'scheme':
                        return standalone_makeExplicit(standalone_parseScheme(specifiedScale[property]));
                }
            }
        }
    }
    const sizeChannel = channel === standalone_channel_X || channel === 'xOffset' ? 'width' : 'height';
    const sizeValue = size[sizeChannel];
    if (standalone_isStep(sizeValue)) {
        if (standalone_isXorY(channel)) {
            if (standalone_hasDiscreteDomain(scaleType)) {
                const step = standalone_getPositionStep(sizeValue, model, channel);
                // Need to be explicit so layer with step wins over layer without step
                if (step) {
                    return standalone_makeExplicit({ step });
                }
            }
            else {
                standalone_log_warn(standalone_stepDropped(sizeChannel));
            }
        }
        else if (standalone_isXorYOffset(channel)) {
            const positionChannel = channel === standalone_XOFFSET ? 'x' : 'y';
            const positionScaleCmpt = model.getScaleComponent(positionChannel);
            const positionScaleType = positionScaleCmpt.get('type');
            if (positionScaleType === 'band') {
                const step = standalone_getOffsetStep(sizeValue, scaleType);
                if (step) {
                    return standalone_makeExplicit(step);
                }
            }
        }
    }
    const { rangeMin, rangeMax } = specifiedScale;
    const d = standalone_defaultRange(channel, model);
    if ((rangeMin !== undefined || rangeMax !== undefined) &&
        // it's ok to check just rangeMin's compatibility since rangeMin/rangeMax are the same
        standalone_scaleTypeSupportProperty(scaleType, 'rangeMin') &&
        standalone_vega_util_module_isArray(d) &&
        d.length === 2) {
        return standalone_makeExplicit([rangeMin ?? d[0], rangeMax ?? d[1]]);
    }
    return standalone_makeImplicit(d);
}
function standalone_parseScheme(scheme) {
    if (standalone_isExtendedScheme(scheme)) {
        return {
            scheme: scheme.name,
            ...standalone_omit(scheme, ['name'])
        };
    }
    return { scheme };
}
function standalone_fullWidthOrHeightRange(channel, model, scaleType, { center } = {}) {
    // If step is null, use zero to width or height.
    // Note that we use SignalRefWrapper to account for potential merges and renames.
    const sizeType = standalone_getSizeChannel(channel);
    const sizeSignal = model.getName(sizeType);
    const getSignalName = model.getSignalName.bind(model);
    if (channel === standalone_channel_Y && standalone_hasContinuousDomain(scaleType)) {
        // For y continuous scale, we have to start from the height as the bottom part has the max value.
        return center
            ? [
                standalone_SignalRefWrapper.fromName(name => `${getSignalName(name)}/2`, sizeSignal),
                standalone_SignalRefWrapper.fromName(name => `-${getSignalName(name)}/2`, sizeSignal)
            ]
            : [standalone_SignalRefWrapper.fromName(getSignalName, sizeSignal), 0];
    }
    else {
        return center
            ? [
                standalone_SignalRefWrapper.fromName(name => `-${getSignalName(name)}/2`, sizeSignal),
                standalone_SignalRefWrapper.fromName(name => `${getSignalName(name)}/2`, sizeSignal)
            ]
            : [0, standalone_SignalRefWrapper.fromName(getSignalName, sizeSignal)];
    }
}
function standalone_defaultRange(channel, model) {
    const { size, config, mark, encoding } = model;
    const { type } = standalone_getFieldOrDatumDef(encoding[channel]);
    const mergedScaleCmpt = model.getScaleComponent(channel);
    const scaleType = mergedScaleCmpt.get('type');
    const { domain, domainMid } = model.specifiedScales[channel];
    switch (channel) {
        case standalone_channel_X:
        case standalone_channel_Y: {
            // If there is no explicit width/height for discrete x/y scales
            if (standalone_util_contains(['point', 'band'], scaleType)) {
                const positionSize = standalone_getDiscretePositionSize(channel, size, config.view);
                if (standalone_isStep(positionSize)) {
                    const step = standalone_getPositionStep(positionSize, model, channel);
                    return { step };
                }
            }
            return standalone_fullWidthOrHeightRange(channel, model, scaleType);
        }
        case standalone_XOFFSET:
        case standalone_YOFFSET:
            return standalone_getOffsetRange(channel, model, scaleType);
        case standalone_channel_SIZE: {
            // TODO: support custom rangeMin, rangeMax
            const rangeMin = standalone_sizeRangeMin(mark, config);
            const rangeMax = standalone_sizeRangeMax(mark, size, model, config);
            if (standalone_isContinuousToDiscrete(scaleType)) {
                return standalone_range_interpolateRange(rangeMin, rangeMax, standalone_defaultContinuousToDiscreteCount(scaleType, config, domain, channel));
            }
            else {
                return [rangeMin, rangeMax];
            }
        }
        case standalone_THETA:
            return [0, Math.PI * 2];
        case standalone_ANGLE:
            // TODO: add config.scale.min/maxAngleDegree (for point and text) and config.scale.min/maxAngleRadian (for arc) once we add arc marks.
            // (It's weird to add just config.scale.min/maxAngleDegree for now)
            return [0, 360];
        case standalone_RADIUS: {
            // max radius = half od min(width,height)
            return [
                0,
                new standalone_SignalRefWrapper(() => {
                    const w = model.getSignalName(standalone_isFacetModel(model.parent) ? 'child_width' : 'width');
                    const h = model.getSignalName(standalone_isFacetModel(model.parent) ? 'child_height' : 'height');
                    return `min(${w},${h})/2`;
                })
            ];
        }
        case standalone_TIME: {
            // if (scaleType === 'band') {
            return { step: 1000 / config.scale.framesPerSecond };
            // }
            // return [0, config.scale.animationDuration * 1000]; // TODO(jzong): uncomment for linear scales when interpolation is implemented
        }
        case standalone_STROKEWIDTH:
            // TODO: support custom rangeMin, rangeMax
            return [config.scale.minStrokeWidth, config.scale.maxStrokeWidth];
        case standalone_STROKEDASH:
            return [
                // TODO: add this to Vega's config.range?
                [1, 0],
                [4, 2],
                [2, 1],
                [1, 1],
                [1, 2, 4, 2]
            ];
        case standalone_SHAPE:
            return 'symbol';
        case standalone_COLOR:
        case standalone_FILL:
        case standalone_STROKE:
            if (scaleType === 'ordinal') {
                // Only nominal data uses ordinal scale by default
                return type === 'nominal' ? 'category' : 'ordinal';
            }
            else {
                if (domainMid !== undefined) {
                    return 'diverging';
                }
                else {
                    return mark === 'rect' || mark === 'geoshape' ? 'heatmap' : 'ramp';
                }
            }
        case standalone_OPACITY:
        case standalone_FILLOPACITY:
        case standalone_STROKEOPACITY:
            // TODO: support custom rangeMin, rangeMax
            return [config.scale.minOpacity, config.scale.maxOpacity];
    }
}
function standalone_getPositionStep(step, model, channel) {
    const { encoding } = model;
    const mergedScaleCmpt = model.getScaleComponent(channel);
    const offsetChannel = standalone_getOffsetScaleChannel(channel);
    const offsetDef = encoding[offsetChannel];
    const stepFor = standalone_getStepFor({ step, offsetIsDiscrete: standalone_isFieldOrDatumDef(offsetDef) && standalone_type_isDiscrete(offsetDef.type) });
    if (stepFor === 'offset' && standalone_channelHasFieldOrDatum(encoding, offsetChannel)) {
        const offsetScaleCmpt = model.getScaleComponent(offsetChannel);
        const offsetScaleName = model.scaleName(offsetChannel);
        let stepCount = `domain('${offsetScaleName}').length`;
        if (offsetScaleCmpt.get('type') === 'band') {
            const offsetPaddingInner = offsetScaleCmpt.get('paddingInner') ?? offsetScaleCmpt.get('padding') ?? 0;
            const offsetPaddingOuter = offsetScaleCmpt.get('paddingOuter') ?? offsetScaleCmpt.get('padding') ?? 0;
            stepCount = `bandspace(${stepCount}, ${offsetPaddingInner}, ${offsetPaddingOuter})`;
        }
        const paddingInner = mergedScaleCmpt.get('paddingInner') ?? mergedScaleCmpt.get('padding');
        return {
            signal: `${step.step} * ${stepCount} / (1-${standalone_exprFromSignalRefOrValue(paddingInner)})`
        };
    }
    else {
        return step.step;
    }
}
function standalone_getOffsetStep(step, offsetScaleType) {
    const stepFor = standalone_getStepFor({ step, offsetIsDiscrete: standalone_hasDiscreteDomain(offsetScaleType) });
    if (stepFor === 'offset') {
        return { step: step.step };
    }
    return undefined;
}
function standalone_getOffsetRange(channel, model, offsetScaleType) {
    const positionChannel = channel === standalone_XOFFSET ? 'x' : 'y';
    const positionScaleCmpt = model.getScaleComponent(positionChannel);
    if (!positionScaleCmpt) {
        return standalone_fullWidthOrHeightRange(positionChannel, model, offsetScaleType, { center: true });
    }
    const positionScaleType = positionScaleCmpt.get('type');
    const positionScaleName = model.scaleName(positionChannel);
    const { markDef, config } = model;
    if (positionScaleType === 'band') {
        const size = standalone_getDiscretePositionSize(positionChannel, model.size, model.config.view);
        if (standalone_isStep(size)) {
            // step is for offset
            const step = standalone_getOffsetStep(size, offsetScaleType);
            if (step) {
                return step;
            }
        }
        // otherwise use the position
        return [0, { signal: `bandwidth('${positionScaleName}')` }];
    }
    else {
        // continuous scale
        const positionDef = model.encoding[positionChannel];
        if (standalone_isFieldDef(positionDef) && positionDef.timeUnit) {
            const duration = standalone_durationExpr(positionDef.timeUnit, expr => `scale('${positionScaleName}', ${expr})`);
            const padding = model.config.scale.bandWithNestedOffsetPaddingInner;
            const bandPositionOffset = standalone_getBandPosition({
                fieldDef: positionDef,
                markDef,
                config
            }) - 0.5;
            const bandPositionOffsetExpr = bandPositionOffset !== 0 ? ` + ${bandPositionOffset}` : '';
            if (padding) {
                const startRatio = standalone_isSignalRef(padding)
                    ? `${padding.signal}/2` + bandPositionOffsetExpr
                    : `${padding / 2 + bandPositionOffset}`;
                const endRatio = standalone_isSignalRef(padding)
                    ? `(1 - ${padding.signal}/2)` + bandPositionOffsetExpr
                    : `${1 - padding / 2 + bandPositionOffset}`;
                return [{ signal: `${startRatio} * (${duration})` }, { signal: `${endRatio} * (${duration})` }];
            }
            return [0, { signal: duration }];
        }
        return standalone_never(`Cannot use ${channel} scale if ${positionChannel} scale is not discrete.`);
    }
}
function standalone_getDiscretePositionSize(channel, size, viewConfig) {
    const sizeChannel = channel === standalone_channel_X ? 'width' : 'height';
    const sizeValue = size[sizeChannel];
    if (sizeValue) {
        return sizeValue;
    }
    return standalone_getViewConfigDiscreteSize(viewConfig, sizeChannel);
}
function standalone_defaultContinuousToDiscreteCount(scaleType, config, domain, channel) {
    switch (scaleType) {
        case 'quantile':
            return config.scale.quantileCount;
        case 'quantize':
            return config.scale.quantizeCount;
        case 'threshold':
            if (domain !== undefined && standalone_vega_util_module_isArray(domain)) {
                return domain.length + 1;
            }
            else {
                standalone_log_warn(standalone_domainRequiredForThresholdScale(channel));
                // default threshold boundaries for threshold scale since domain has cardinality of 2
                return 3;
            }
    }
}
/**
 * Returns the linear interpolation of the range according to the cardinality
 *
 * @param rangeMin start of the range
 * @param rangeMax end of the range
 * @param cardinality number of values in the output range
 */
function standalone_range_interpolateRange(rangeMin, rangeMax, cardinality) {
    // always return a signal since it's better to compute the sequence in Vega later
    const f = () => {
        const rMax = standalone_signalOrStringValue(rangeMax);
        const rMin = standalone_signalOrStringValue(rangeMin);
        const step = `(${rMax} - ${rMin}) / (${cardinality} - 1)`;
        return `sequence(${rMin}, ${rMax} + ${step}, ${step})`;
    };
    if (standalone_isSignalRef(rangeMax)) {
        return new standalone_SignalRefWrapper(f);
    }
    else {
        return { signal: f() };
    }
}
function standalone_sizeRangeMin(mark, config) {
    switch (mark) {
        case 'bar':
        case 'tick':
            return config.scale.minBandSize;
        case 'line':
        case 'trail':
        case 'rule':
            return config.scale.minStrokeWidth;
        case 'text':
            return config.scale.minFontSize;
        case 'point':
        case 'square':
        case 'circle':
            return config.scale.minSize;
    }
    /* istanbul ignore next: should never reach here */
    // sizeRangeMin not implemented for the mark
    throw new Error(standalone_incompatibleChannel('size', mark));
}
const standalone_MAX_SIZE_RANGE_STEP_RATIO = 0.95;
function standalone_sizeRangeMax(mark, size, model, config) {
    const xyStepSignals = {
        x: standalone_getBinStepSignal(model, 'x'),
        y: standalone_getBinStepSignal(model, 'y')
    };
    switch (mark) {
        case 'bar':
        case 'tick': {
            if (config.scale.maxBandSize !== undefined) {
                return config.scale.maxBandSize;
            }
            const min = standalone_minXYStep(size, xyStepSignals, config.view);
            if (standalone_isNumber(min)) {
                return min - 1;
            }
            else {
                return new standalone_SignalRefWrapper(() => `${min.signal} - 1`);
            }
        }
        case 'line':
        case 'trail':
        case 'rule':
            return config.scale.maxStrokeWidth;
        case 'text':
            return config.scale.maxFontSize;
        case 'point':
        case 'square':
        case 'circle': {
            if (config.scale.maxSize) {
                return config.scale.maxSize;
            }
            const pointStep = standalone_minXYStep(size, xyStepSignals, config.view);
            if (standalone_isNumber(pointStep)) {
                return Math.pow(standalone_MAX_SIZE_RANGE_STEP_RATIO * pointStep, 2);
            }
            else {
                return new standalone_SignalRefWrapper(() => `pow(${standalone_MAX_SIZE_RANGE_STEP_RATIO} * ${pointStep.signal}, 2)`);
            }
        }
    }
    /* istanbul ignore next: should never reach here */
    // sizeRangeMax not implemented for the mark
    throw new Error(standalone_incompatibleChannel('size', mark));
}
/**
 * @returns {number} Range step of x or y or minimum between the two if both are ordinal scale.
 */
function standalone_minXYStep(size, xyStepSignals, viewConfig) {
    const widthStep = standalone_isStep(size.width) ? size.width.step : standalone_getViewConfigDiscreteStep(viewConfig, 'width');
    const heightStep = standalone_isStep(size.height) ? size.height.step : standalone_getViewConfigDiscreteStep(viewConfig, 'height');
    if (xyStepSignals.x || xyStepSignals.y) {
        return new standalone_SignalRefWrapper(() => {
            const exprs = [
                xyStepSignals.x ? xyStepSignals.x.signal : widthStep,
                xyStepSignals.y ? xyStepSignals.y.signal : heightStep
            ];
            return `min(${exprs.join(', ')})`;
        });
    }
    return Math.min(widthStep, heightStep);
}
//# sourceMappingURL=range.js.map
;// ../../node_modules/vega-lite/build/src/compile/scale/properties.js
















function standalone_parseScaleProperty(model, property) {
    if (standalone_isUnitModel(model)) {
        standalone_parseUnitScaleProperty(model, property);
    }
    else {
        standalone_parseNonUnitScaleProperty(model, property);
    }
}
function standalone_parseUnitScaleProperty(model, property) {
    const localScaleComponents = model.component.scales;
    const { config, encoding, markDef, specifiedScales } = model;
    for (const channel of standalone_util_keys(localScaleComponents)) {
        const specifiedScale = specifiedScales[channel];
        const localScaleCmpt = localScaleComponents[channel];
        const mergedScaleCmpt = model.getScaleComponent(channel);
        const fieldOrDatumDef = standalone_getFieldOrDatumDef(encoding[channel]);
        const specifiedValue = specifiedScale[property];
        const scaleType = mergedScaleCmpt.get('type');
        const scalePadding = mergedScaleCmpt.get('padding');
        const scalePaddingInner = mergedScaleCmpt.get('paddingInner');
        const supportedByScaleType = standalone_scaleTypeSupportProperty(scaleType, property);
        const channelIncompatability = standalone_channelScalePropertyIncompatability(channel, property);
        if (specifiedValue !== undefined) {
            // If there is a specified value, check if it is compatible with scale type and channel
            if (!supportedByScaleType) {
                standalone_log_warn(standalone_scalePropertyNotWorkWithScaleType(scaleType, property, channel));
            }
            else if (channelIncompatability) {
                // channel
                standalone_log_warn(channelIncompatability);
            }
        }
        if (supportedByScaleType && channelIncompatability === undefined) {
            if (specifiedValue !== undefined) {
                const timeUnit = fieldOrDatumDef.timeUnit;
                const type = fieldOrDatumDef.type;
                switch (property) {
                    // domainMax/Min to signal if the value is a datetime object
                    case 'domainMax':
                    case 'domainMin':
                        if (standalone_isDateTime(specifiedScale[property]) || type === 'temporal' || timeUnit) {
                            localScaleCmpt.set(property, { signal: standalone_valueExpr(specifiedScale[property], { type, timeUnit }) }, true);
                        }
                        else {
                            localScaleCmpt.set(property, specifiedScale[property], true);
                        }
                        break;
                    default:
                        localScaleCmpt.copyKeyFromObject(property, specifiedScale);
                }
            }
            else {
                const value = standalone_util_hasProperty(standalone_scaleRules, property)
                    ? standalone_scaleRules[property]({
                        model,
                        channel,
                        fieldOrDatumDef,
                        scaleType,
                        scalePadding,
                        scalePaddingInner,
                        domain: specifiedScale.domain,
                        domainMin: specifiedScale.domainMin,
                        domainMax: specifiedScale.domainMax,
                        markDef,
                        config,
                        hasNestedOffsetScale: standalone_channelHasNestedOffsetScale(encoding, channel),
                        hasSecondaryRangeChannel: !!encoding[standalone_getSecondaryRangeChannel(channel)]
                    })
                    : config.scale[property];
                if (value !== undefined) {
                    localScaleCmpt.set(property, value, false);
                }
            }
        }
    }
}
const standalone_scaleRules = {
    bins: ({ model, fieldOrDatumDef }) => (standalone_isFieldDef(fieldOrDatumDef) ? standalone_bins(model, fieldOrDatumDef) : undefined),
    interpolate: ({ channel, fieldOrDatumDef }) => standalone_properties_interpolate(channel, fieldOrDatumDef.type),
    nice: ({ scaleType, channel, domain, domainMin, domainMax, fieldOrDatumDef }) => standalone_properties_nice(scaleType, channel, domain, domainMin, domainMax, fieldOrDatumDef),
    padding: ({ channel, scaleType, fieldOrDatumDef, markDef, config }) => standalone_properties_padding(channel, scaleType, config.scale, fieldOrDatumDef, markDef, config.bar),
    paddingInner: ({ scalePadding, channel, markDef, scaleType, config, hasNestedOffsetScale }) => standalone_paddingInner(scalePadding, channel, markDef.type, scaleType, config.scale, hasNestedOffsetScale),
    paddingOuter: ({ scalePadding, channel, scaleType, scalePaddingInner, config, hasNestedOffsetScale }) => standalone_paddingOuter(scalePadding, channel, scaleType, scalePaddingInner, config.scale, hasNestedOffsetScale),
    reverse: ({ fieldOrDatumDef, scaleType, channel, config }) => {
        const sort = standalone_isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : undefined;
        return standalone_properties_reverse(scaleType, sort, channel, config.scale);
    },
    zero: ({ channel, fieldOrDatumDef, domain, markDef, scaleType, config, hasSecondaryRangeChannel }) => standalone_properties_zero(channel, fieldOrDatumDef, domain, markDef, scaleType, config.scale, hasSecondaryRangeChannel)
};
// This method is here rather than in range.ts to avoid circular dependency.
function standalone_properties_parseScaleRange(model) {
    if (standalone_isUnitModel(model)) {
        standalone_parseUnitScaleRange(model);
    }
    else {
        standalone_parseNonUnitScaleProperty(model, 'range');
    }
}
function standalone_parseNonUnitScaleProperty(model, property) {
    const localScaleComponents = model.component.scales;
    for (const child of model.children) {
        if (property === 'range') {
            standalone_properties_parseScaleRange(child);
        }
        else {
            standalone_parseScaleProperty(child, property);
        }
    }
    for (const channel of standalone_util_keys(localScaleComponents)) {
        let valueWithExplicit;
        for (const child of model.children) {
            const childComponent = child.component.scales[channel];
            if (childComponent) {
                const childValueWithExplicit = childComponent.getWithExplicit(property);
                valueWithExplicit = standalone_mergeValuesWithExplicit(valueWithExplicit, childValueWithExplicit, property, 'scale', standalone_tieBreakByComparing((v1, v2) => {
                    switch (property) {
                        case 'range':
                            // For step, prefer larger step
                            if (v1.step && v2.step) {
                                return v1.step - v2.step;
                            }
                            return 0;
                        // TODO: precedence rule for other properties
                    }
                    return 0;
                }));
            }
        }
        localScaleComponents[channel].setWithExplicit(property, valueWithExplicit);
    }
}
function standalone_bins(model, fieldDef) {
    const bin = fieldDef.bin;
    if (standalone_isBinning(bin)) {
        const binSignal = standalone_getBinSignalName(model, fieldDef.field, bin);
        return new standalone_SignalRefWrapper(() => {
            return model.getSignalName(binSignal);
        });
    }
    else if (standalone_isBinned(bin) && standalone_isBinParams(bin) && bin.step !== undefined) {
        // start and stop will be determined from the scale domain
        return {
            step: bin.step
        };
    }
    return undefined;
}
function standalone_properties_interpolate(channel, type) {
    if (standalone_util_contains([standalone_COLOR, standalone_FILL, standalone_STROKE], channel) && type !== 'nominal') {
        return 'hcl';
    }
    return undefined;
}
function standalone_properties_nice(scaleType, channel, specifiedDomain, domainMin, domainMax, fieldOrDatumDef) {
    if (standalone_getFieldDef(fieldOrDatumDef)?.bin ||
        standalone_vega_util_module_isArray(specifiedDomain) ||
        domainMax != null ||
        domainMin != null ||
        standalone_util_contains([standalone_ScaleType.TIME, standalone_ScaleType.UTC], scaleType)) {
        return undefined;
    }
    return standalone_isXorY(channel) ? true : undefined;
}
function standalone_properties_padding(channel, scaleType, scaleConfig, fieldOrDatumDef, markDef, barConfig) {
    if (standalone_isXorY(channel)) {
        if (standalone_isContinuousToContinuous(scaleType)) {
            if (scaleConfig.continuousPadding !== undefined) {
                return scaleConfig.continuousPadding;
            }
            const { type, orient } = markDef;
            if (type === 'bar' && !(standalone_isFieldDef(fieldOrDatumDef) && (fieldOrDatumDef.bin || fieldOrDatumDef.timeUnit))) {
                if ((orient === 'vertical' && channel === 'x') || (orient === 'horizontal' && channel === 'y')) {
                    return barConfig.continuousBandSize;
                }
            }
        }
        if (scaleType === standalone_ScaleType.POINT) {
            return scaleConfig.pointPadding;
        }
    }
    return undefined;
}
function standalone_paddingInner(paddingValue, channel, mark, scaleType, scaleConfig, hasNestedOffsetScale = false) {
    if (paddingValue !== undefined) {
        // If user has already manually specified "padding", no need to add default paddingInner.
        return undefined;
    }
    if (standalone_isXorY(channel)) {
        // Padding is only set for X and Y by default.
        // Basically it doesn't make sense to add padding for color and size.
        // paddingOuter would only be called if it's a band scale, just return the default for bandScale.
        const { bandPaddingInner, barBandPaddingInner, rectBandPaddingInner, tickBandPaddingInner, bandWithNestedOffsetPaddingInner } = scaleConfig;
        if (hasNestedOffsetScale) {
            return bandWithNestedOffsetPaddingInner;
        }
        return standalone_getFirstDefined(bandPaddingInner, mark === 'bar' ? barBandPaddingInner : mark === 'tick' ? tickBandPaddingInner : rectBandPaddingInner);
    }
    else if (standalone_isXorYOffset(channel)) {
        if (scaleType === standalone_ScaleType.BAND) {
            return scaleConfig.offsetBandPaddingInner;
        }
    }
    return undefined;
}
function standalone_paddingOuter(paddingValue, channel, scaleType, paddingInnerValue, scaleConfig, hasNestedOffsetScale = false) {
    if (paddingValue !== undefined) {
        // If user has already manually specified "padding", no need to add default paddingOuter.
        return undefined;
    }
    if (standalone_isXorY(channel)) {
        const { bandPaddingOuter, bandWithNestedOffsetPaddingOuter } = scaleConfig;
        if (hasNestedOffsetScale) {
            return bandWithNestedOffsetPaddingOuter;
        }
        // Padding is only set for X and Y by default.
        // Basically it doesn't make sense to add padding for color and size.
        if (scaleType === standalone_ScaleType.BAND) {
            return standalone_getFirstDefined(bandPaddingOuter, 
            /* By default, paddingOuter is paddingInner / 2. The reason is that
              size (width/height) = step * (cardinality - paddingInner + 2 * paddingOuter).
              and we want the width/height to be integer by default.
              Note that step (by default) and cardinality are integers.) */
            standalone_isSignalRef(paddingInnerValue) ? { signal: `${paddingInnerValue.signal}/2` } : paddingInnerValue / 2);
        }
    }
    else if (standalone_isXorYOffset(channel)) {
        if (scaleType === standalone_ScaleType.POINT) {
            return 0.5; // so the point positions align with centers of band scales.
        }
        else if (scaleType === standalone_ScaleType.BAND) {
            return scaleConfig.offsetBandPaddingOuter;
        }
    }
    return undefined;
}
function standalone_properties_reverse(scaleType, sort, channel, scaleConfig) {
    if (channel === 'x' && scaleConfig.xReverse !== undefined) {
        if (standalone_hasContinuousDomain(scaleType) && sort === 'descending') {
            if (standalone_isSignalRef(scaleConfig.xReverse)) {
                return { signal: `!${scaleConfig.xReverse.signal}` };
            }
            else {
                return !scaleConfig.xReverse;
            }
        }
        return scaleConfig.xReverse;
    }
    if (standalone_hasContinuousDomain(scaleType) && sort === 'descending') {
        // For continuous domain scales, Vega does not support domain sort.
        // Thus, we reverse range instead if sort is descending
        return true;
    }
    return undefined;
}
function standalone_properties_zero(channel, fieldDef, specifiedDomain, markDef, scaleType, scaleConfig, hasSecondaryRangeChannel) {
    // If users explicitly provide a domain, we should not augment zero as that will be unexpected.
    const hasCustomDomain = !!specifiedDomain && specifiedDomain !== 'unaggregated';
    if (hasCustomDomain) {
        if (standalone_hasContinuousDomain(scaleType)) {
            if (standalone_vega_util_module_isArray(specifiedDomain)) {
                const first = specifiedDomain[0];
                const last = specifiedDomain[specifiedDomain.length - 1];
                if (standalone_isNumber(first) && first <= 0 && standalone_isNumber(last) && last >= 0) {
                    // if the domain includes zero, make zero remain true
                    return true;
                }
            }
            return false;
        }
    }
    // If there is no custom domain, return configZero value (=`true` as default) only for the following cases:
    // 1) using quantitative field with size
    // While this can be either ratio or interval fields, our assumption is that
    // ratio are more common. However, if the scaleType is discretizing scale, we want to return
    // false so that range doesn't start at zero
    if (channel === 'size' && fieldDef.type === 'quantitative' && !standalone_isContinuousToDiscrete(scaleType)) {
        return true;
    }
    // 2) non-binned, quantitative x-scale or y-scale
    // (For binning, we should not include zero by default because binning are calculated without zero.)
    // (For area/bar charts with ratio scale chart, we should always include zero.)
    if (!(standalone_isFieldDef(fieldDef) && fieldDef.bin) &&
        standalone_util_contains([...standalone_POSITION_SCALE_CHANNELS, ...standalone_POLAR_POSITION_SCALE_CHANNELS], channel)) {
        const { orient, type } = markDef;
        if (standalone_util_contains(['bar', 'area', 'line', 'trail'], type)) {
            if ((orient === 'horizontal' && channel === 'y') || (orient === 'vertical' && channel === 'x')) {
                return false;
            }
        }
        if (standalone_util_contains(['bar', 'area'], type) && !hasSecondaryRangeChannel) {
            return true;
        }
        return scaleConfig?.zero;
    }
    return false;
}
//# sourceMappingURL=properties.js.map
;// ../../node_modules/vega-lite/build/src/compile/scale/type.js









/**
 * Determine if there is a specified scale type and if it is appropriate,
 * or determine default type if type is unspecified or inappropriate.
 */
// NOTE: CompassQL uses this method.
function standalone_scaleType(specifiedScale, channel, fieldDef, mark, hasNestedOffsetScale = false) {
    const defaultScaleType = standalone_type_defaultType(channel, fieldDef, mark, hasNestedOffsetScale);
    const { type } = specifiedScale;
    if (!standalone_isScaleChannel(channel)) {
        // There is no scale for these channels
        return null;
    }
    if (type !== undefined) {
        // Check if explicitly specified scale type is supported by the channel
        if (!standalone_channelSupportScaleType(channel, type)) {
            standalone_log_warn(standalone_scaleTypeNotWorkWithChannel(channel, type, defaultScaleType));
            return defaultScaleType;
        }
        // Check if explicitly specified scale type is supported by the data type
        if (standalone_isFieldDef(fieldDef) && !standalone_scaleTypeSupportDataType(type, fieldDef.type)) {
            standalone_log_warn(standalone_scaleTypeNotWorkWithFieldDef(type, defaultScaleType));
            return defaultScaleType;
        }
        return type;
    }
    return defaultScaleType;
}
/**
 * Determine appropriate default scale type.
 */
// NOTE: Voyager uses this method.
function standalone_type_defaultType(channel, fieldDef, mark, hasNestedOffsetScale) {
    switch (fieldDef.type) {
        case 'nominal':
        case 'ordinal': {
            if (standalone_isColorChannel(channel) || standalone_rangeType(channel) === 'discrete') {
                if (channel === 'shape' && fieldDef.type === 'ordinal') {
                    standalone_log_warn(standalone_discreteChannelCannotEncode(channel, 'ordinal'));
                }
                return 'ordinal';
            }
            if (standalone_isTime(channel)) {
                return 'band';
            }
            if (standalone_isXorY(channel) || standalone_isXorYOffset(channel)) {
                if (standalone_util_contains(['rect', 'bar', 'image', 'rule', 'tick'], mark.type)) {
                    // The rect/bar/tick mark should fit into a band.
                    // For rule, using band scale to make rule align with axis ticks better https://github.com/vega/vega-lite/issues/3429
                    return 'band';
                }
                if (hasNestedOffsetScale) {
                    // If there is a nested offset scale, then there is a "band" for the span of the nested scale.
                    return 'band';
                }
            }
            else if (mark.type === 'arc' && channel in standalone_POLAR_POSITION_SCALE_CHANNEL_INDEX) {
                return 'band';
            }
            const dimensionSize = mark[standalone_getSizeChannel(channel)];
            if (standalone_isRelativeBandSize(dimensionSize)) {
                return 'band';
            }
            if (standalone_isPositionFieldOrDatumDef(fieldDef) && fieldDef.axis?.tickBand) {
                return 'band';
            }
            // Otherwise, use ordinal point scale so we can easily get center positions of the marks.
            return 'point';
        }
        case 'temporal':
            if (standalone_isColorChannel(channel)) {
                return 'time';
            }
            else if (standalone_rangeType(channel) === 'discrete') {
                standalone_log_warn(standalone_discreteChannelCannotEncode(channel, 'temporal'));
                // TODO: consider using quantize (equivalent to binning) once we have it
                return 'ordinal';
            }
            else if (standalone_isFieldDef(fieldDef) && fieldDef.timeUnit && standalone_normalizeTimeUnit(fieldDef.timeUnit).utc) {
                return 'utc';
            }
            else if (standalone_isTime(channel)) {
                // return 'linear';
                return 'band'; // TODO(jzong): when interpolation is implemented, this should be 'linear'
            }
            return 'time';
        case 'quantitative':
            if (standalone_isColorChannel(channel)) {
                if (standalone_isFieldDef(fieldDef) && standalone_isBinning(fieldDef.bin)) {
                    return 'bin-ordinal';
                }
                return 'linear';
            }
            else if (standalone_rangeType(channel) === 'discrete') {
                standalone_log_warn(standalone_discreteChannelCannotEncode(channel, 'quantitative'));
                // TODO: consider using quantize (equivalent to binning) once we have it
                return 'ordinal';
            }
            else if (standalone_isTime(channel)) {
                // return 'linear';
                return 'band'; // TODO(jzong): when interpolation is implemented, this should be 'linear'
            }
            return 'linear';
        case 'geojson':
            return undefined;
    }
    /* istanbul ignore next: should never reach this */
    throw new Error(standalone_invalidFieldType(fieldDef.type));
}
//# sourceMappingURL=type.js.map
;// ../../node_modules/vega-lite/build/src/compile/scale/parse.js














function standalone_parseScales(model, { ignoreRange } = {}) {
    standalone_parseScaleCore(model);
    standalone_domain_parseScaleDomain(model);
    for (const prop of standalone_NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES) {
        standalone_parseScaleProperty(model, prop);
    }
    if (!ignoreRange) {
        // range depends on zero
        standalone_properties_parseScaleRange(model);
    }
}
function standalone_parseScaleCore(model) {
    if (standalone_isUnitModel(model)) {
        model.component.scales = standalone_parseUnitScaleCore(model);
    }
    else {
        model.component.scales = standalone_parseNonUnitScaleCore(model);
    }
}
/**
 * Parse scales for all channels of a model.
 */
function standalone_parseUnitScaleCore(model) {
    const { encoding, mark, markDef } = model;
    const scaleComponents = {};
    for (const channel of standalone_SCALE_CHANNELS) {
        const fieldOrDatumDef = standalone_getFieldOrDatumDef(encoding[channel]); // must be typed def to have scale
        // Don't generate scale for shape of geoshape
        if (fieldOrDatumDef && mark === standalone_GEOSHAPE && channel === standalone_SHAPE && fieldOrDatumDef.type === standalone_GEOJSON) {
            continue;
        }
        let specifiedScale = fieldOrDatumDef && fieldOrDatumDef.scale;
        if (fieldOrDatumDef && specifiedScale !== null && specifiedScale !== false) {
            specifiedScale ?? (specifiedScale = {});
            const hasNestedOffsetScale = standalone_channelHasNestedOffsetScale(encoding, channel);
            const sType = standalone_scaleType(specifiedScale, channel, fieldOrDatumDef, markDef, hasNestedOffsetScale);
            scaleComponents[channel] = new standalone_ScaleComponent(model.scaleName(`${channel}`, true), {
                value: sType,
                explicit: specifiedScale.type === sType
            });
        }
    }
    return scaleComponents;
}
const standalone_scaleTypeTieBreaker = standalone_tieBreakByComparing((st1, st2) => standalone_scaleTypePrecedence(st1) - standalone_scaleTypePrecedence(st2));
function standalone_parseNonUnitScaleCore(model) {
    var _a;
    const scaleComponents = (model.component.scales = {});
    const scaleTypeWithExplicitIndex = {};
    const resolve = model.component.resolve;
    // Parse each child scale and determine if a particular channel can be merged.
    for (const child of model.children) {
        standalone_parseScaleCore(child);
        // Instead of always merging right away -- check if it is compatible to merge first!
        for (const channel of standalone_util_keys(child.component.scales)) {
            // if resolve is undefined, set default first
            (_a = resolve.scale)[channel] ?? (_a[channel] = standalone_defaultScaleResolve(channel, model));
            if (resolve.scale[channel] === 'shared') {
                const explicitScaleType = scaleTypeWithExplicitIndex[channel];
                const childScaleType = child.component.scales[channel].getWithExplicit('type');
                if (explicitScaleType) {
                    if (standalone_scaleCompatible(explicitScaleType.value, childScaleType.value)) {
                        // merge scale component if type are compatible
                        scaleTypeWithExplicitIndex[channel] = standalone_mergeValuesWithExplicit(explicitScaleType, childScaleType, 'type', 'scale', standalone_scaleTypeTieBreaker);
                    }
                    else {
                        // Otherwise, update conflicting channel to be independent
                        resolve.scale[channel] = 'independent';
                        // Remove from the index so they don't get merged
                        delete scaleTypeWithExplicitIndex[channel];
                    }
                }
                else {
                    scaleTypeWithExplicitIndex[channel] = childScaleType;
                }
            }
        }
    }
    // Merge each channel listed in the index
    for (const channel of standalone_util_keys(scaleTypeWithExplicitIndex)) {
        // Create new merged scale component
        const name = model.scaleName(channel, true);
        const typeWithExplicit = scaleTypeWithExplicitIndex[channel];
        scaleComponents[channel] = new standalone_ScaleComponent(name, typeWithExplicit);
        // rename each child and mark them as merged
        for (const child of model.children) {
            const childScale = child.component.scales[channel];
            if (childScale) {
                child.renameScale(childScale.get('name'), name);
                childScale.merged = true;
            }
        }
    }
    return scaleComponents;
}
//# sourceMappingURL=parse.js.map
;// ../../node_modules/vega-lite/build/src/compile/model.js



























class standalone_NameMap {
    constructor() {
        this.nameMap = {};
    }
    rename(oldName, newName) {
        this.nameMap[oldName] = newName;
    }
    has(name) {
        return this.nameMap[name] !== undefined;
    }
    get(name) {
        // If the name appears in the _nameMap, we need to read its new name.
        // We have to loop over the dict just in case the new name also gets renamed.
        while (this.nameMap[name] && name !== this.nameMap[name]) {
            name = this.nameMap[name];
        }
        return name;
    }
}
/*
  We use type guards instead of `instanceof` as `instanceof` makes
  different parts of the compiler depend on the actual implementation of
  the model classes, which in turn depend on different parts of the compiler.
  Thus, `instanceof` leads to circular dependency problems.

  On the other hand, type guards only make different parts of the compiler
  depend on the type of the model classes, but not the actual implementation.
*/
function standalone_isUnitModel(model) {
    return model?.type === 'unit';
}
function standalone_isFacetModel(model) {
    return model?.type === 'facet';
}
function standalone_isConcatModel(model) {
    return model?.type === 'concat';
}
function standalone_isLayerModel(model) {
    return model?.type === 'layer';
}
class standalone_Model {
    constructor(spec, type, parent, parentGivenName, config, resolve, view) {
        this.type = type;
        this.parent = parent;
        this.config = config;
        this.parent = parent;
        this.config = config;
        this.view = standalone_replaceExprRef(view);
        // If name is not provided, always use parent's givenName to avoid name conflicts.
        this.name = spec.name ?? parentGivenName;
        this.title = standalone_isText(spec.title) ? { text: spec.title } : spec.title ? standalone_replaceExprRef(spec.title) : undefined;
        // Shared name maps
        this.scaleNameMap = parent ? parent.scaleNameMap : new standalone_NameMap();
        this.projectionNameMap = parent ? parent.projectionNameMap : new standalone_NameMap();
        this.signalNameMap = parent ? parent.signalNameMap : new standalone_NameMap();
        this.data = spec.data;
        this.description = spec.description;
        this.transforms = standalone_normalizeTransform(spec.transform ?? []);
        this.layout = type === 'layer' || type === 'unit' ? {} : standalone_extractCompositionLayout(spec, type, config);
        this.component = {
            data: {
                sources: parent ? parent.component.data.sources : [],
                outputNodes: parent ? parent.component.data.outputNodes : {},
                outputNodeRefCounts: parent ? parent.component.data.outputNodeRefCounts : {},
                // data is faceted if the spec is a facet spec or the parent has faceted data and data is undefined
                isFaceted: standalone_isFacetSpec(spec) || (parent?.component.data.isFaceted && spec.data === undefined)
            },
            layoutSize: new standalone_Split(),
            layoutHeaders: { row: {}, column: {}, facet: {} },
            mark: null,
            resolve: {
                scale: {},
                axis: {},
                legend: {},
                ...(resolve ? standalone_duplicate(resolve) : {})
            },
            selection: null,
            scales: null,
            projection: null,
            axes: {},
            legends: {}
        };
    }
    get width() {
        return this.getSizeSignalRef('width');
    }
    get height() {
        return this.getSizeSignalRef('height');
    }
    parse() {
        this.parseScale();
        this.parseLayoutSize(); // depends on scale
        this.renameTopLevelLayoutSizeSignal();
        this.parseSelections();
        this.parseProjection();
        this.parseData(); // (pathorder) depends on markDef; selection filters depend on parsed selections; depends on projection because some transforms require the finalized projection name.
        this.parseAxesAndHeaders(); // depends on scale and layout size
        this.parseLegends(); // depends on scale, markDef
        this.parseMarkGroup(); // depends on data name, scale, layout size, axisGroup, and children's scale, axis, legend and mark.
    }
    parseScale() {
        standalone_parseScales(this);
    }
    parseProjection() {
        standalone_parse_parseProjection(this);
    }
    /**
     * Rename top-level spec's size to be just width / height, ignoring model name.
     * This essentially merges the top-level spec's width/height signals with the width/height signals
     * to help us reduce redundant signals declaration.
     */
    renameTopLevelLayoutSizeSignal() {
        if (this.getName('width') !== 'width') {
            this.renameSignal(this.getName('width'), 'width');
        }
        if (this.getName('height') !== 'height') {
            this.renameSignal(this.getName('height'), 'height');
        }
    }
    parseLegends() {
        standalone_parse_parseLegend(this);
    }
    assembleEncodeFromView(view) {
        // Exclude "style"
        const { style: _, ...baseView } = view;
        const e = {};
        for (const property of standalone_util_keys(baseView)) {
            const value = baseView[property];
            if (value !== undefined) {
                e[property] = standalone_signalOrValueRef(value);
            }
        }
        return e;
    }
    assembleGroupEncodeEntry(isTopLevel) {
        let encodeEntry = {};
        if (this.view) {
            encodeEntry = this.assembleEncodeFromView(this.view);
        }
        if (!isTopLevel) {
            // Descriptions are already added to the top-level description so we only need to add them to the inner views.
            if (this.description) {
                encodeEntry['description'] = standalone_signalOrValueRef(this.description);
            }
            // For top-level spec, we can set the global width and height signal to adjust the group size.
            // For other child specs, we have to manually set width and height in the encode entry.
            if (this.type === 'unit' || this.type === 'layer') {
                return {
                    width: this.getSizeSignalRef('width'),
                    height: this.getSizeSignalRef('height'),
                    ...encodeEntry
                };
            }
        }
        return standalone_isEmpty(encodeEntry) ? undefined : encodeEntry;
    }
    assembleLayout() {
        if (!this.layout) {
            return undefined;
        }
        const { spacing, ...layout } = this.layout;
        const { component, config } = this;
        const titleBand = standalone_assembleLayoutTitleBand(component.layoutHeaders, config);
        return {
            padding: spacing,
            ...this.assembleDefaultLayout(),
            ...layout,
            ...(titleBand ? { titleBand } : {})
        };
    }
    assembleDefaultLayout() {
        return {};
    }
    assembleHeaderMarks() {
        const { layoutHeaders } = this.component;
        let headerMarks = [];
        for (const channel of standalone_FACET_CHANNELS) {
            if (layoutHeaders[channel].title) {
                headerMarks.push(standalone_assembleTitleGroup(this, channel));
            }
        }
        for (const channel of standalone_HEADER_CHANNELS) {
            headerMarks = headerMarks.concat(standalone_assembleHeaderGroups(this, channel));
        }
        return headerMarks;
    }
    assembleAxes() {
        return standalone_assembleAxes(this.component.axes, this.config);
    }
    assembleLegends() {
        return standalone_assembleLegends(this);
    }
    assembleProjections() {
        return standalone_assembleProjections(this);
    }
    assembleTitle() {
        const { encoding, ...titleNoEncoding } = this.title ?? {};
        const title = {
            ...standalone_extractTitleConfig(this.config.title).nonMarkTitleProperties,
            ...titleNoEncoding,
            ...(encoding ? { encode: { update: encoding } } : {})
        };
        if (title.text) {
            if (standalone_util_contains(['unit', 'layer'], this.type)) {
                // Unit/Layer
                if (standalone_util_contains(['middle', undefined], title.anchor)) {
                    title.frame ?? (title.frame = 'group');
                }
            }
            else {
                // composition with Vega layout
                // Set title = "start" by default for composition as "middle" does not look nice
                // https://github.com/vega/vega/issues/960#issuecomment-471360328
                title.anchor ?? (title.anchor = 'start');
            }
            return standalone_isEmpty(title) ? undefined : title;
        }
        return undefined;
    }
    /**
     * Assemble the mark group for this model. We accept optional `signals` so that we can include concat top-level signals with the top-level model's local signals.
     */
    assembleGroup(signals = []) {
        const group = {};
        signals = signals.concat(this.assembleSignals());
        if (signals.length > 0) {
            group.signals = signals;
        }
        const layout = this.assembleLayout();
        if (layout) {
            group.layout = layout;
        }
        group.marks = [].concat(this.assembleHeaderMarks(), this.assembleMarks());
        // Only include scales if this spec is top-level or if parent is facet.
        // (Otherwise, it will be merged with upper-level's scope.)
        const scales = !this.parent || standalone_isFacetModel(this.parent) ? standalone_assembleScales(this) : [];
        if (scales.length > 0) {
            group.scales = scales;
        }
        const axes = this.assembleAxes();
        if (axes.length > 0) {
            group.axes = axes;
        }
        const legends = this.assembleLegends();
        if (legends.length > 0) {
            group.legends = legends;
        }
        return group;
    }
    getName(text) {
        return standalone_varName((this.name ? `${this.name}_` : '') + text);
    }
    getDataName(type) {
        return this.getName(standalone_DataSourceType[type].toLowerCase());
    }
    /**
     * Request a data source name for the given data source type and mark that data source as required.
     * This method should be called in parse, so that all used data source can be correctly instantiated in assembleData().
     * You can lookup the correct dataset name in assemble with `lookupDataSource`.
     */
    requestDataName(name) {
        const fullName = this.getDataName(name);
        // Increase ref count. This is critical because otherwise we won't create a data source.
        // We also increase the ref counts on OutputNode.getSource() calls.
        const refCounts = this.component.data.outputNodeRefCounts;
        refCounts[fullName] = (refCounts[fullName] || 0) + 1;
        return fullName;
    }
    getSizeSignalRef(layoutSizeType) {
        if (standalone_isFacetModel(this.parent)) {
            const sizeType = standalone_getSizeTypeFromLayoutSizeType(layoutSizeType);
            const channel = standalone_getPositionScaleChannel(sizeType);
            const scaleComponent = this.component.scales[channel];
            if (scaleComponent && !scaleComponent.merged) {
                // independent scale
                const type = scaleComponent.get('type');
                const range = scaleComponent.get('range');
                if (standalone_hasDiscreteDomain(type) && standalone_isVgRangeStep(range)) {
                    const scaleName = scaleComponent.get('name');
                    const domain = standalone_assembleDomain(this, channel);
                    const field = standalone_getFieldFromDomain(domain);
                    if (field) {
                        const fieldRef = standalone_vgField({ aggregate: 'distinct', field }, { expr: 'datum' });
                        return {
                            signal: standalone_sizeExpr(scaleName, scaleComponent, fieldRef)
                        };
                    }
                    else {
                        standalone_log_warn(standalone_unknownField(channel));
                        return null;
                    }
                }
            }
        }
        return {
            signal: this.signalNameMap.get(this.getName(layoutSizeType))
        };
    }
    /**
     * Lookup the name of the datasource for an output node. You probably want to call this in assemble.
     */
    lookupDataSource(name) {
        const node = this.component.data.outputNodes[name];
        if (!node) {
            // Name not found in map so let's just return what we got.
            // This can happen if we already have the correct name.
            return name;
        }
        return node.getSource();
    }
    getSignalName(oldSignalName) {
        return this.signalNameMap.get(oldSignalName);
    }
    renameSignal(oldName, newName) {
        this.signalNameMap.rename(oldName, newName);
    }
    renameScale(oldName, newName) {
        this.scaleNameMap.rename(oldName, newName);
    }
    renameProjection(oldName, newName) {
        this.projectionNameMap.rename(oldName, newName);
    }
    /**
     * @return scale name for a given channel after the scale has been parsed and named.
     */
    scaleName(originalScaleName, parse) {
        if (parse) {
            // During the parse phase always return a value
            // No need to refer to rename map because a scale can't be renamed
            // before it has the original name.
            return this.getName(originalScaleName);
        }
        // If there is a scale for the channel, it should either
        // be in the scale component or exist in the name map
        if (
        // If there is a scale for the channel, there should be a local scale component for it
        (standalone_isChannel(originalScaleName) && standalone_isScaleChannel(originalScaleName) && this.component.scales[originalScaleName]) ||
            // in the scale name map (the scale get merged by its parent)
            this.scaleNameMap.has(this.getName(originalScaleName))) {
            return this.scaleNameMap.get(this.getName(originalScaleName));
        }
        return undefined;
    }
    /**
     * @return projection name after the projection has been parsed and named.
     */
    projectionName(parse) {
        if (parse) {
            // During the parse phase always return a value
            // No need to refer to rename map because a projection can't be renamed
            // before it has the original name.
            return this.getName('projection');
        }
        if ((this.component.projection && !this.component.projection.merged) ||
            this.projectionNameMap.has(this.getName('projection'))) {
            return this.projectionNameMap.get(this.getName('projection'));
        }
        return undefined;
    }
    /**
     * Traverse a model's hierarchy to get the scale component for a particular channel.
     */
    getScaleComponent(channel) {
        /* istanbul ignore next: This is warning for debugging test */
        if (!this.component.scales) {
            throw new Error('getScaleComponent cannot be called before parseScale(). Make sure you have called parseScale or use parseUnitModelWithScale().');
        }
        const localScaleComponent = this.component.scales[channel];
        if (localScaleComponent && !localScaleComponent.merged) {
            return localScaleComponent;
        }
        return this.parent ? this.parent.getScaleComponent(channel) : undefined;
    }
    getScaleType(channel) {
        const scaleComponent = this.getScaleComponent(channel);
        return scaleComponent ? scaleComponent.get('type') : undefined;
    }
    /**
     * Traverse a model's hierarchy to get a particular selection component.
     */
    getSelectionComponent(variableName, origName) {
        let sel = this.component.selection[variableName];
        if (!sel && this.parent) {
            sel = this.parent.getSelectionComponent(variableName, origName);
        }
        if (!sel) {
            throw new Error(standalone_selectionNotFound(origName));
        }
        return sel;
    }
    /**
     * Returns true if the model has a signalRef for an axis orient.
     */
    hasAxisOrientSignalRef() {
        return (this.component.axes.x?.some(a => a.hasOrientSignalRef()) ||
            this.component.axes.y?.some(a => a.hasOrientSignalRef()));
    }
}
/** Abstract class for UnitModel and FacetModel. Both of which can contain fieldDefs as a part of its own specification. */
class standalone_ModelWithField extends standalone_Model {
    /** Get "field" reference for Vega */
    vgField(channel, opt = {}) {
        const fieldDef = this.fieldDef(channel);
        if (!fieldDef) {
            return undefined;
        }
        return standalone_vgField(fieldDef, opt);
    }
    reduceFieldDef(f, init) {
        return standalone_reduce(this.getMapping(), (acc, cd, c) => {
            const fieldDef = standalone_getFieldDef(cd);
            if (fieldDef) {
                return f(acc, fieldDef, c);
            }
            return acc;
        }, init);
    }
    forEachFieldDef(f, t) {
        standalone_forEach(this.getMapping(), (cd, c) => {
            const fieldDef = standalone_getFieldDef(cd);
            if (fieldDef) {
                f(fieldDef, c);
            }
        }, t);
    }
}
//# sourceMappingURL=model.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/density.js


/**
 * A class for density transform nodes
 */
class standalone_DensityTransformNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_DensityTransformNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
        this.transform = standalone_duplicate(transform); // duplicate to prevent side effects
        const specifiedAs = this.transform.as ?? [undefined, undefined];
        this.transform.as = [specifiedAs[0] ?? 'value', specifiedAs[1] ?? 'density'];
        const resolve = this.transform.resolve ?? 'shared';
        this.transform.resolve = resolve;
    }
    dependentFields() {
        return new Set([this.transform.density, ...(this.transform.groupby ?? [])]);
    }
    producedFields() {
        return new Set(this.transform.as);
    }
    hash() {
        return `DensityTransform ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        const { density, ...rest } = this.transform;
        const result = {
            type: 'kde',
            field: density,
            ...rest
        };
        result.resolve = this.transform.resolve;
        return result;
    }
}
//# sourceMappingURL=density.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/extent.js


/**
 * A class for flatten transform nodes
 */
class standalone_ExtentTransformNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_ExtentTransformNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
        this.transform = standalone_duplicate(transform);
    }
    dependentFields() {
        return new Set([this.transform.extent]);
    }
    producedFields() {
        return new Set([]);
    }
    hash() {
        return `ExtentTransform ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        const { extent, param } = this.transform;
        const result = {
            type: 'extent',
            field: extent,
            signal: param
        };
        return result;
    }
}
//# sourceMappingURL=extent.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/flatten.js


/**
 * A class for flatten transform nodes
 */
class standalone_FlattenTransformNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_FlattenTransformNode(this.parent, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
        this.transform = standalone_duplicate(transform); // duplicate to prevent side effects
        const { flatten, as = [] } = this.transform;
        this.transform.as = flatten.map((f, i) => as[i] ?? f);
    }
    dependentFields() {
        return new Set(this.transform.flatten);
    }
    producedFields() {
        return new Set(this.transform.as);
    }
    hash() {
        return `FlattenTransform ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        const { flatten: fields, as } = this.transform;
        const result = {
            type: 'flatten',
            fields,
            as
        };
        return result;
    }
}
//# sourceMappingURL=flatten.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/fold.js


/**
 * A class for flatten transform nodes
 */
class standalone_FoldTransformNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_FoldTransformNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
        this.transform = standalone_duplicate(transform); // duplicate to prevent side effects
        const specifiedAs = this.transform.as ?? [undefined, undefined];
        this.transform.as = [specifiedAs[0] ?? 'key', specifiedAs[1] ?? 'value'];
    }
    dependentFields() {
        return new Set(this.transform.fold);
    }
    producedFields() {
        return new Set(this.transform.as);
    }
    hash() {
        return `FoldTransform ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        const { fold, as } = this.transform;
        const result = {
            type: 'fold',
            fields: fold,
            as
        };
        return result;
    }
}
//# sourceMappingURL=fold.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/geojson.js






class standalone_GeoJSONNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_GeoJSONNode(null, standalone_duplicate(this.fields), this.geojson, this.signal);
    }
    static parseAll(parent, model) {
        if (model.component.projection && !model.component.projection.isFit) {
            return parent;
        }
        let geoJsonCounter = 0;
        for (const coordinates of [
            [standalone_LONGITUDE, standalone_LATITUDE],
            [standalone_LONGITUDE2, standalone_LATITUDE2]
        ]) {
            const pair = coordinates.map(channel => {
                const def = standalone_getFieldOrDatumDef(model.encoding[channel]);
                return standalone_isFieldDef(def)
                    ? def.field
                    : standalone_isDatumDef(def)
                        ? { expr: `${def.datum}` }
                        : standalone_isValueDef(def)
                            ? { expr: `${def['value']}` }
                            : undefined;
            });
            if (pair[0] || pair[1]) {
                parent = new standalone_GeoJSONNode(parent, pair, null, model.getName(`geojson_${geoJsonCounter++}`));
            }
        }
        if (model.channelHasField(standalone_SHAPE)) {
            const fieldDef = model.typedFieldDef(standalone_SHAPE);
            if (fieldDef.type === standalone_GEOJSON) {
                parent = new standalone_GeoJSONNode(parent, null, fieldDef.field, model.getName(`geojson_${geoJsonCounter++}`));
            }
        }
        return parent;
    }
    constructor(parent, fields, geojson, signal) {
        super(parent);
        this.fields = fields;
        this.geojson = geojson;
        this.signal = signal;
    }
    dependentFields() {
        const fields = (this.fields ?? []).filter(standalone_vega_util_module_isString);
        return new Set([...(this.geojson ? [this.geojson] : []), ...fields]);
    }
    producedFields() {
        return new Set();
    }
    hash() {
        return `GeoJSON ${this.geojson} ${this.signal} ${standalone_util_hash(this.fields)}`;
    }
    assemble() {
        return [
            ...(this.geojson
                ? [
                    {
                        type: 'filter',
                        expr: `isValid(datum["${this.geojson}"])`
                    }
                ]
                : []),
            {
                type: 'geojson',
                ...(this.fields ? { fields: this.fields } : {}),
                ...(this.geojson ? { geojson: this.geojson } : {}),
                signal: this.signal
            }
        ];
    }
}
//# sourceMappingURL=geojson.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/geopoint.js





class standalone_GeoPointNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_GeoPointNode(null, this.projection, standalone_duplicate(this.fields), standalone_duplicate(this.as));
    }
    constructor(parent, projection, fields, as) {
        super(parent);
        this.projection = projection;
        this.fields = fields;
        this.as = as;
    }
    static parseAll(parent, model) {
        if (!model.projectionName()) {
            return parent;
        }
        for (const coordinates of [
            [standalone_LONGITUDE, standalone_LATITUDE],
            [standalone_LONGITUDE2, standalone_LATITUDE2]
        ]) {
            const pair = coordinates.map(channel => {
                const def = standalone_getFieldOrDatumDef(model.encoding[channel]);
                return standalone_isFieldDef(def)
                    ? def.field
                    : standalone_isDatumDef(def)
                        ? { expr: `${def.datum}` }
                        : standalone_isValueDef(def)
                            ? { expr: `${def['value']}` }
                            : undefined;
            });
            const suffix = coordinates[0] === standalone_LONGITUDE2 ? '2' : '';
            if (pair[0] || pair[1]) {
                parent = new standalone_GeoPointNode(parent, model.projectionName(), pair, [
                    model.getName(`x${suffix}`),
                    model.getName(`y${suffix}`)
                ]);
            }
        }
        return parent;
    }
    dependentFields() {
        return new Set(this.fields.filter(standalone_vega_util_module_isString));
    }
    producedFields() {
        return new Set(this.as);
    }
    hash() {
        return `Geopoint ${this.projection} ${standalone_util_hash(this.fields)} ${standalone_util_hash(this.as)}`;
    }
    assemble() {
        return {
            type: 'geopoint',
            projection: this.projection,
            fields: this.fields,
            as: this.as
        };
    }
}
//# sourceMappingURL=geopoint.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/impute.js





class standalone_ImputeNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_ImputeNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
    }
    dependentFields() {
        return new Set([this.transform.impute, this.transform.key, ...(this.transform.groupby ?? [])]);
    }
    producedFields() {
        return new Set([this.transform.impute]);
    }
    processSequence(keyvals) {
        const { start = 0, stop, step } = keyvals;
        const result = [start, stop, ...(step ? [step] : [])].join(',');
        return { signal: `sequence(${result})` };
    }
    static makeFromTransform(parent, imputeTransform) {
        return new standalone_ImputeNode(parent, imputeTransform);
    }
    static makeFromEncoding(parent, model) {
        const encoding = model.encoding;
        const xDef = encoding.x;
        const yDef = encoding.y;
        if (standalone_isFieldDef(xDef) && standalone_isFieldDef(yDef)) {
            const imputedChannel = xDef.impute ? xDef : yDef.impute ? yDef : undefined;
            if (imputedChannel === undefined) {
                return undefined;
            }
            const keyChannel = xDef.impute ? yDef : yDef.impute ? xDef : undefined;
            const { method, value, frame, keyvals } = imputedChannel.impute;
            const groupbyFields = standalone_pathGroupingFields(model.mark, encoding);
            return new standalone_ImputeNode(parent, {
                impute: imputedChannel.field,
                key: keyChannel.field,
                ...(method ? { method } : {}),
                ...(value !== undefined ? { value } : {}),
                ...(frame ? { frame } : {}),
                ...(keyvals !== undefined ? { keyvals } : {}),
                ...(groupbyFields.length ? { groupby: groupbyFields } : {})
            });
        }
        return null;
    }
    hash() {
        return `Impute ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        const { impute, key, keyvals, method, groupby, value, frame = [null, null] } = this.transform;
        const imputeTransform = {
            type: 'impute',
            field: impute,
            key,
            ...(keyvals ? { keyvals: standalone_isImputeSequence(keyvals) ? this.processSequence(keyvals) : keyvals } : {}),
            method: 'value',
            ...(groupby ? { groupby } : {}),
            value: !method || method === 'value' ? value : null
        };
        if (method && method !== 'value') {
            const deriveNewField = {
                type: 'window',
                as: [`imputed_${impute}_value`],
                ops: [method],
                fields: [impute],
                frame,
                ignorePeers: false,
                ...(groupby ? { groupby } : {})
            };
            const replaceOriginal = {
                type: 'formula',
                expr: `datum.${impute} === null ? datum.imputed_${impute}_value : datum.${impute}`,
                as: impute
            };
            return [imputeTransform, deriveNewField, replaceOriginal];
        }
        else {
            return [imputeTransform];
        }
    }
}
//# sourceMappingURL=impute.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/loess.js


/**
 * A class for loess transform nodes
 */
class standalone_LoessTransformNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_LoessTransformNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
        this.transform = standalone_duplicate(transform); // duplicate to prevent side effects
        const specifiedAs = this.transform.as ?? [undefined, undefined];
        this.transform.as = [specifiedAs[0] ?? transform.on, specifiedAs[1] ?? transform.loess];
    }
    dependentFields() {
        return new Set([this.transform.loess, this.transform.on, ...(this.transform.groupby ?? [])]);
    }
    producedFields() {
        return new Set(this.transform.as);
    }
    hash() {
        return `LoessTransform ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        const { loess, on, ...rest } = this.transform;
        const result = {
            type: 'loess',
            x: on,
            y: loess,
            ...rest
        };
        return result;
    }
}
//# sourceMappingURL=loess.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/lookup.js








class standalone_LookupNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_LookupNode(null, standalone_duplicate(this.transform), this.secondary);
    }
    constructor(parent, transform, secondary) {
        super(parent);
        this.transform = transform;
        this.secondary = secondary;
    }
    static make(parent, model, transform, counter) {
        const sources = model.component.data.sources;
        const { from } = transform;
        let fromOutputNode = null;
        if (standalone_isLookupData(from)) {
            let fromSource = standalone_findSource(from.data, sources);
            if (!fromSource) {
                fromSource = new standalone_SourceNode(from.data);
                sources.push(fromSource);
            }
            const fromOutputName = model.getName(`lookup_${counter}`);
            fromOutputNode = new standalone_OutputNode(fromSource, fromOutputName, standalone_DataSourceType.Lookup, model.component.data.outputNodeRefCounts);
            model.component.data.outputNodes[fromOutputName] = fromOutputNode;
        }
        else if (standalone_isLookupSelection(from)) {
            const selName = from.param;
            transform = { as: selName, ...transform };
            let selCmpt;
            try {
                selCmpt = model.getSelectionComponent(standalone_varName(selName), selName);
            }
            catch (e) {
                throw new Error(standalone_cannotLookupVariableParameter(selName));
            }
            fromOutputNode = selCmpt.materialized;
            if (!fromOutputNode) {
                throw new Error(standalone_noSameUnitLookup(selName));
            }
        }
        return new standalone_LookupNode(parent, transform, fromOutputNode.getSource());
    }
    dependentFields() {
        return new Set([this.transform.lookup]);
    }
    producedFields() {
        return new Set(this.transform.as ? standalone_array(this.transform.as) : this.transform.from.fields);
    }
    hash() {
        return `Lookup ${standalone_util_hash({ transform: this.transform, secondary: this.secondary })}`;
    }
    assemble() {
        let foreign;
        if (this.transform.from.fields) {
            // lookup a few fields and add create a flat output
            foreign = {
                values: this.transform.from.fields,
                ...(this.transform.as ? { as: standalone_array(this.transform.as) } : {})
            };
        }
        else {
            // lookup full record and nest it
            let asName = this.transform.as;
            if (!standalone_vega_util_module_isString(asName)) {
                standalone_log_warn(standalone_NO_FIELDS_NEEDS_AS);
                asName = '_lookup';
            }
            foreign = {
                as: [asName]
            };
        }
        return {
            type: 'lookup',
            from: this.secondary,
            key: this.transform.from.key,
            fields: [this.transform.lookup],
            ...foreign,
            ...(this.transform.default ? { default: this.transform.default } : {})
        };
    }
}
//# sourceMappingURL=lookup.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/quantile.js


/**
 * A class for quantile transform nodes
 */
class standalone_QuantileTransformNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_QuantileTransformNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
        this.transform = standalone_duplicate(transform); // duplicate to prevent side effects
        const specifiedAs = this.transform.as ?? [undefined, undefined];
        this.transform.as = [specifiedAs[0] ?? 'prob', specifiedAs[1] ?? 'value'];
    }
    dependentFields() {
        return new Set([this.transform.quantile, ...(this.transform.groupby ?? [])]);
    }
    producedFields() {
        return new Set(this.transform.as);
    }
    hash() {
        return `QuantileTransform ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        const { quantile, ...rest } = this.transform;
        const result = {
            type: 'quantile',
            field: quantile,
            ...rest
        };
        return result;
    }
}
//# sourceMappingURL=quantile.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/regression.js


/**
 * A class for regression transform nodes
 */
class standalone_RegressionTransformNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_RegressionTransformNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
        this.transform = standalone_duplicate(transform); // duplicate to prevent side effects
        const specifiedAs = this.transform.as ?? [undefined, undefined];
        this.transform.as = [specifiedAs[0] ?? transform.on, specifiedAs[1] ?? transform.regression];
    }
    dependentFields() {
        return new Set([this.transform.regression, this.transform.on, ...(this.transform.groupby ?? [])]);
    }
    producedFields() {
        return new Set(this.transform.as);
    }
    hash() {
        return `RegressionTransform ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        const { regression, on, ...rest } = this.transform;
        const result = {
            type: 'regression',
            x: on,
            y: regression,
            ...rest
        };
        return result;
    }
}
//# sourceMappingURL=regression.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/pivot.js


/**
 * A class for pivot transform nodes.
 */
class standalone_PivotTransformNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_PivotTransformNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
    }
    addDimensions(fields) {
        this.transform.groupby = standalone_unique((this.transform.groupby ?? []).concat(fields), d => d);
    }
    producedFields() {
        return undefined; // return undefined so that potentially everything can depend on the pivot
    }
    dependentFields() {
        return new Set([this.transform.pivot, this.transform.value, ...(this.transform.groupby ?? [])]);
    }
    hash() {
        return `PivotTransform ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        const { pivot, value, groupby, limit, op } = this.transform;
        return {
            type: 'pivot',
            field: pivot,
            value,
            ...(limit !== undefined ? { limit } : {}),
            ...(op !== undefined ? { op } : {}),
            ...(groupby !== undefined ? { groupby } : {})
        };
    }
}
//# sourceMappingURL=pivot.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/sample.js


/**
 * A class for the sample transform nodes
 */
class standalone_SampleTransformNode extends standalone_DataFlowNode {
    clone() {
        return new standalone_SampleTransformNode(null, standalone_duplicate(this.transform));
    }
    constructor(parent, transform) {
        super(parent);
        this.transform = transform;
    }
    dependentFields() {
        return new Set();
    }
    producedFields() {
        return new Set();
    }
    hash() {
        return `SampleTransform ${standalone_util_hash(this.transform)}`;
    }
    assemble() {
        return {
            type: 'sample',
            size: this.transform.sample
        };
    }
}
//# sourceMappingURL=sample.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/assemble.js






























function standalone_makeWalkTree(data) {
    // to name datasources
    let datasetIndex = 0;
    /**
     * Recursively walk down the tree.
     */
    function walkTree(node, dataSource) {
        if (node instanceof standalone_SourceNode) {
            // If the source is a named data source or a data source with values, we need
            // to put it in a different data source. Otherwise, Vega may override the data.
            if (!node.isGenerator && !standalone_isUrlData(node.data)) {
                data.push(dataSource);
                const newData = {
                    name: null,
                    source: dataSource.name,
                    transform: []
                };
                dataSource = newData;
            }
        }
        if (node instanceof standalone_ParseNode) {
            if (node.parent instanceof standalone_SourceNode && !dataSource.source) {
                // If node's parent is a root source and the data source does not refer to another data source, use normal format parse
                dataSource.format = {
                    ...dataSource.format,
                    parse: node.assembleFormatParse()
                };
                // add calculates for all nested fields
                dataSource.transform.push(...node.assembleTransforms(true));
            }
            else {
                // Otherwise use Vega expression to parse
                dataSource.transform.push(...node.assembleTransforms());
            }
        }
        if (node instanceof standalone_FacetNode) {
            if (!dataSource.name) {
                dataSource.name = `data_${datasetIndex++}`;
            }
            if (!dataSource.source || dataSource.transform.length > 0) {
                data.push(dataSource);
                node.data = dataSource.name;
            }
            else {
                node.data = dataSource.source;
            }
            data.push(...node.assemble());
            // break here because the rest of the tree has to be taken care of by the facet.
            return;
        }
        if (node instanceof standalone_GraticuleNode ||
            node instanceof standalone_SequenceNode ||
            node instanceof standalone_FilterInvalidNode ||
            node instanceof standalone_FilterNode ||
            node instanceof standalone_CalculateNode ||
            node instanceof standalone_GeoPointNode ||
            node instanceof standalone_AggregateNode ||
            node instanceof standalone_LookupNode ||
            node instanceof standalone_WindowTransformNode ||
            node instanceof standalone_JoinAggregateTransformNode ||
            node instanceof standalone_FoldTransformNode ||
            node instanceof standalone_FlattenTransformNode ||
            node instanceof standalone_DensityTransformNode ||
            node instanceof standalone_LoessTransformNode ||
            node instanceof standalone_QuantileTransformNode ||
            node instanceof standalone_RegressionTransformNode ||
            node instanceof standalone_IdentifierNode ||
            node instanceof standalone_SampleTransformNode ||
            node instanceof standalone_PivotTransformNode ||
            node instanceof standalone_ExtentTransformNode) {
            dataSource.transform.push(node.assemble());
        }
        if (node instanceof standalone_BinNode ||
            node instanceof standalone_TimeUnitNode ||
            node instanceof standalone_ImputeNode ||
            node instanceof standalone_StackNode ||
            node instanceof standalone_GeoJSONNode) {
            dataSource.transform.push(...node.assemble());
        }
        if (node instanceof standalone_OutputNode) {
            if (dataSource.source && dataSource.transform.length === 0) {
                node.setSource(dataSource.source);
            }
            else if (node.parent instanceof standalone_OutputNode) {
                // Note that an output node may be required but we still do not assemble a
                // separate data source for it.
                node.setSource(dataSource.name);
            }
            else {
                if (!dataSource.name) {
                    dataSource.name = `data_${datasetIndex++}`;
                }
                // Here we set the name of the datasource we generated. From now on
                // other assemblers can use it.
                node.setSource(dataSource.name);
                // if this node has more than one child, we will add a datasource automatically
                if (node.numChildren() === 1) {
                    data.push(dataSource);
                    const newData = {
                        name: null,
                        source: dataSource.name,
                        transform: []
                    };
                    dataSource = newData;
                }
            }
        }
        switch (node.numChildren()) {
            case 0:
                // done
                if (node instanceof standalone_OutputNode && (!dataSource.source || dataSource.transform.length > 0)) {
                    // do not push empty datasources that are simply references
                    data.push(dataSource);
                }
                break;
            case 1:
                walkTree(node.children[0], dataSource);
                break;
            default: {
                if (!dataSource.name) {
                    dataSource.name = `data_${datasetIndex++}`;
                }
                let source = dataSource.name;
                if (!dataSource.source || dataSource.transform.length > 0) {
                    data.push(dataSource);
                }
                else {
                    source = dataSource.source;
                }
                for (const child of node.children) {
                    const newData = {
                        name: null,
                        source,
                        transform: []
                    };
                    walkTree(child, newData);
                }
                break;
            }
        }
    }
    return walkTree;
}
/**
 * Assemble data sources that are derived from faceted data.
 */
function standalone_assembleFacetData(root) {
    const data = [];
    const walkTree = standalone_makeWalkTree(data);
    for (const child of root.children) {
        walkTree(child, {
            source: root.name,
            name: null,
            transform: []
        });
    }
    return data;
}
/**
 * Create Vega data array from a given compiled model and append all of them to the given array
 *
 * @param  model
 * @param  data array
 * @return modified data array
 */
function standalone_assembleRootData(dataComponent, datasets) {
    const data = [];
    // dataComponent.sources.forEach(debug);
    // draw(dataComponent.sources);
    const walkTree = standalone_makeWalkTree(data);
    let sourceIndex = 0;
    for (const root of dataComponent.sources) {
        // assign a name if the source does not have a name yet
        if (!root.hasName()) {
            root.dataName = `source_${sourceIndex++}`;
        }
        const newData = root.assemble();
        walkTree(root, newData);
    }
    // remove empty transform arrays for cleaner output
    for (const d of data) {
        if (d.transform.length === 0) {
            delete d.transform;
        }
    }
    // move sources without transforms (the ones that are potentially used in lookups) to the beginning
    let whereTo = 0;
    for (const [i, d] of data.entries()) {
        if ((d.transform ?? []).length === 0 && !d.source) {
            data.splice(whereTo++, 0, data.splice(i, 1)[0]);
        }
    }
    // now fix the from references in lookup transforms
    for (const d of data) {
        for (const t of d.transform ?? []) {
            if (t.type === 'lookup') {
                t.from = dataComponent.outputNodes[t.from].getSource();
            }
        }
    }
    // inline values for datasets that are in the datastore
    for (const d of data) {
        if (d.name in datasets) {
            d.values = datasets[d.name];
        }
    }
    return data;
}
//# sourceMappingURL=assemble.js.map
;// ../../node_modules/vega-lite/build/src/compile/header/parse.js








function standalone_getHeaderType(orient) {
    if (orient === 'top' || orient === 'left' || standalone_isSignalRef(orient)) {
        // we always use header for orient signal since we can't dynamically make header becomes footer
        return 'header';
    }
    return 'footer';
}
function standalone_parseFacetHeaders(model) {
    for (const channel of standalone_FACET_CHANNELS) {
        standalone_parseFacetHeader(model, channel);
    }
    standalone_mergeChildAxis(model, 'x');
    standalone_mergeChildAxis(model, 'y');
}
function standalone_parseFacetHeader(model, channel) {
    const { facet, config, child, component } = model;
    if (model.channelHasField(channel)) {
        const fieldDef = facet[channel];
        const titleConfig = standalone_getHeaderProperty('title', null, config, channel);
        let title = standalone_channeldef_title(fieldDef, config, {
            allowDisabling: true,
            includeDefault: titleConfig === undefined || !!titleConfig
        });
        if (child.component.layoutHeaders[channel].title) {
            // TODO: better handle multiline titles
            title = standalone_vega_util_module_isArray(title) ? title.join(', ') : title;
            // merge title with child to produce "Title / Subtitle / Sub-subtitle"
            title += ` / ${child.component.layoutHeaders[channel].title}`;
            child.component.layoutHeaders[channel].title = null;
        }
        const labelOrient = standalone_getHeaderProperty('labelOrient', fieldDef.header, config, channel);
        const labels = fieldDef.header !== null ? standalone_getFirstDefined(fieldDef.header?.labels, config.header.labels, true) : false;
        const headerType = standalone_util_contains(['bottom', 'right'], labelOrient) ? 'footer' : 'header';
        component.layoutHeaders[channel] = {
            title: fieldDef.header !== null ? title : null,
            facetFieldDef: fieldDef,
            [headerType]: channel === 'facet' ? [] : [standalone_makeHeaderComponent(model, channel, labels)]
        };
    }
}
function standalone_makeHeaderComponent(model, channel, labels) {
    const sizeType = channel === 'row' ? 'height' : 'width';
    return {
        labels,
        sizeSignal: model.child.component.layoutSize.get(sizeType) ? model.child.getSizeSignalRef(sizeType) : undefined,
        axes: []
    };
}
function standalone_mergeChildAxis(model, channel) {
    const { child } = model;
    if (child.component.axes[channel]) {
        const { layoutHeaders, resolve } = model.component;
        resolve.axis[channel] = standalone_parseGuideResolve(resolve, channel);
        if (resolve.axis[channel] === 'shared') {
            // For shared axis, move the axes to facet's header or footer
            const headerChannel = channel === 'x' ? 'column' : 'row';
            const layoutHeader = layoutHeaders[headerChannel];
            for (const axisComponent of child.component.axes[channel]) {
                const headerType = standalone_getHeaderType(axisComponent.get('orient'));
                layoutHeader[headerType] ?? (layoutHeader[headerType] = [standalone_makeHeaderComponent(model, headerChannel, false)]);
                // FIXME: assemble shouldn't be called here, but we do it this way so we only extract the main part of the axes
                const mainAxis = standalone_assembleAxis(axisComponent, 'main', model.config, { header: true });
                if (mainAxis) {
                    // LayoutHeader no longer keep track of property precedence, thus let's combine.
                    layoutHeader[headerType][0].axes.push(mainAxis);
                }
                axisComponent.mainExtracted = true;
            }
        }
        else {
            // Otherwise do nothing for independent axes
        }
    }
}
//# sourceMappingURL=parse.js.map
;// ../../node_modules/vega-lite/build/src/compile/layoutsize/parse.js








function standalone_parseLayerLayoutSize(model) {
    standalone_parseChildrenLayoutSize(model);
    standalone_parseNonUnitLayoutSizeForChannel(model, 'width');
    standalone_parseNonUnitLayoutSizeForChannel(model, 'height');
}
function standalone_parseConcatLayoutSize(model) {
    standalone_parseChildrenLayoutSize(model);
    // for columns === 1 (vconcat), we can completely merge width. Otherwise, we can treat merged width as childWidth.
    const widthType = model.layout.columns === 1 ? 'width' : 'childWidth';
    // for columns === undefined (hconcat), we can completely merge height. Otherwise, we can treat merged height as childHeight.
    const heightType = model.layout.columns === undefined ? 'height' : 'childHeight';
    standalone_parseNonUnitLayoutSizeForChannel(model, widthType);
    standalone_parseNonUnitLayoutSizeForChannel(model, heightType);
}
function standalone_parseChildrenLayoutSize(model) {
    for (const child of model.children) {
        child.parseLayoutSize();
    }
}
/**
 * Merge child layout size (width or height).
 */
function standalone_parseNonUnitLayoutSizeForChannel(model, layoutSizeType) {
    /*
     * For concat, the parent width or height might not be the same as the children's shared height.
     * For example, hconcat's subviews may share width, but the shared width is not the hconcat view's width.
     *
     * layoutSizeType represents the output of the view (could be childWidth/childHeight/width/height)
     * while the sizeType represents the properties of the child.
     */
    const sizeType = standalone_getSizeTypeFromLayoutSizeType(layoutSizeType);
    const channel = standalone_getPositionScaleChannel(sizeType);
    const resolve = model.component.resolve;
    const layoutSizeCmpt = model.component.layoutSize;
    let mergedSize;
    // Try to merge layout size
    for (const child of model.children) {
        const childSize = child.component.layoutSize.getWithExplicit(sizeType);
        const scaleResolve = resolve.scale[channel] ?? standalone_defaultScaleResolve(channel, model);
        if (scaleResolve === 'independent' && childSize.value === 'step') {
            // Do not merge independent scales with range-step as their size depends
            // on the scale domains, which can be different between scales.
            mergedSize = undefined;
            break;
        }
        if (mergedSize) {
            if (scaleResolve === 'independent' && mergedSize.value !== childSize.value) {
                // For independent scale, only merge if all the sizes are the same.
                // If the values are different, abandon the merge!
                mergedSize = undefined;
                break;
            }
            mergedSize = standalone_mergeValuesWithExplicit(mergedSize, childSize, sizeType, '');
        }
        else {
            mergedSize = childSize;
        }
    }
    if (mergedSize) {
        // If merged, rename size and set size of all children.
        for (const child of model.children) {
            model.renameSignal(child.getName(sizeType), model.getName(layoutSizeType));
            child.component.layoutSize.set(sizeType, 'merged', false);
        }
        layoutSizeCmpt.setWithExplicit(layoutSizeType, mergedSize);
    }
    else {
        layoutSizeCmpt.setWithExplicit(layoutSizeType, {
            explicit: false,
            value: undefined
        });
    }
}
function standalone_parseUnitLayoutSize(model) {
    const { size, component } = model;
    for (const channel of standalone_POSITION_SCALE_CHANNELS) {
        const sizeType = standalone_getSizeChannel(channel);
        if (size[sizeType]) {
            const specifiedSize = size[sizeType];
            component.layoutSize.set(sizeType, standalone_isStep(specifiedSize) ? 'step' : specifiedSize, true);
        }
        else {
            const defaultSize = standalone_defaultUnitSize(model, sizeType);
            component.layoutSize.set(sizeType, defaultSize, false);
        }
    }
}
function standalone_defaultUnitSize(model, sizeType) {
    const channel = sizeType === 'width' ? 'x' : 'y';
    const config = model.config;
    const scaleComponent = model.getScaleComponent(channel);
    if (scaleComponent) {
        const scaleType = scaleComponent.get('type');
        const range = scaleComponent.get('range');
        if (standalone_hasDiscreteDomain(scaleType)) {
            const size = standalone_getViewConfigDiscreteSize(config.view, sizeType);
            if (standalone_isVgRangeStep(range) || standalone_isStep(size)) {
                // For discrete domain with range.step, use dynamic width/height
                return 'step';
            }
            else {
                return size;
            }
        }
        else {
            return standalone_getViewConfigContinuousSize(config.view, sizeType);
        }
    }
    else if (model.hasProjection || model.mark === 'arc') {
        // arc should use continuous size by default otherwise the pie is extremely small
        return standalone_getViewConfigContinuousSize(config.view, sizeType);
    }
    else {
        const size = standalone_getViewConfigDiscreteSize(config.view, sizeType);
        return standalone_isStep(size) ? size.step : size;
    }
}
//# sourceMappingURL=parse.js.map
;// ../../node_modules/vega-lite/build/src/compile/facet.js

























function standalone_facetSortFieldName(fieldDef, sort, opt) {
    return standalone_vgField(sort, { suffix: `by_${standalone_vgField(fieldDef)}`, ...opt });
}
class standalone_FacetModel extends standalone_ModelWithField {
    constructor(spec, parent, parentGivenName, config) {
        super(spec, 'facet', parent, parentGivenName, config, spec.resolve);
        this.child = standalone_buildModel(spec.spec, this, this.getName('child'), undefined, config);
        this.children = [this.child];
        this.facet = this.initFacet(spec.facet);
    }
    initFacet(facet) {
        // clone to prevent side effect to the original spec
        if (!standalone_isFacetMapping(facet)) {
            return { facet: this.initFacetFieldDef(facet, 'facet') };
        }
        const channels = standalone_util_keys(facet);
        const normalizedFacet = {};
        for (const channel of channels) {
            if (![standalone_ROW, standalone_COLUMN].includes(channel)) {
                // Drop unsupported channel
                standalone_log_warn(standalone_incompatibleChannel(channel, 'facet'));
                break;
            }
            const fieldDef = facet[channel];
            if (fieldDef.field === undefined) {
                standalone_log_warn(standalone_emptyFieldDef(fieldDef, channel));
                break;
            }
            normalizedFacet[channel] = this.initFacetFieldDef(fieldDef, channel);
        }
        return normalizedFacet;
    }
    initFacetFieldDef(fieldDef, channel) {
        // Cast because we call initFieldDef, which assumes general FieldDef.
        // However, FacetFieldDef is a bit more constrained than the general FieldDef
        const facetFieldDef = standalone_initFieldDef(fieldDef, channel);
        if (facetFieldDef.header) {
            facetFieldDef.header = standalone_replaceExprRef(facetFieldDef.header);
        }
        else if (facetFieldDef.header === null) {
            facetFieldDef.header = null;
        }
        return facetFieldDef;
    }
    channelHasField(channel) {
        return standalone_util_hasProperty(this.facet, channel);
    }
    fieldDef(channel) {
        return this.facet[channel];
    }
    parseData() {
        this.component.data = standalone_parse_parseData(this);
        this.child.parseData();
    }
    parseLayoutSize() {
        standalone_parseChildrenLayoutSize(this);
    }
    parseSelections() {
        // As a facet has a single child, the selection components are the same.
        // The child maintains its selections to assemble signals, which remain
        // within its unit.
        this.child.parseSelections();
        this.component.selection = this.child.component.selection;
        if (Object.values(this.component.selection).some(selCmpt => standalone_isTimerSelection(selCmpt))) {
            standalone_log_error(standalone_MULTI_VIEW_ANIMATION_UNSUPPORTED);
        }
    }
    parseMarkGroup() {
        this.child.parseMarkGroup();
    }
    parseAxesAndHeaders() {
        this.child.parseAxesAndHeaders();
        standalone_parseFacetHeaders(this);
    }
    assembleSelectionTopLevelSignals(signals) {
        return this.child.assembleSelectionTopLevelSignals(signals);
    }
    assembleSignals() {
        this.child.assembleSignals();
        return [];
    }
    assembleSelectionData(data) {
        return this.child.assembleSelectionData(data);
    }
    getHeaderLayoutMixins() {
        const layoutMixins = {};
        for (const channel of standalone_FACET_CHANNELS) {
            for (const headerType of standalone_HEADER_TYPES) {
                const layoutHeaderComponent = this.component.layoutHeaders[channel];
                const headerComponent = layoutHeaderComponent[headerType];
                const { facetFieldDef } = layoutHeaderComponent;
                if (facetFieldDef) {
                    const titleOrient = standalone_getHeaderProperty('titleOrient', facetFieldDef.header, this.config, channel);
                    if (['right', 'bottom'].includes(titleOrient)) {
                        const headerChannel = standalone_getHeaderChannel(channel, titleOrient);
                        layoutMixins.titleAnchor ?? (layoutMixins.titleAnchor = {});
                        layoutMixins.titleAnchor[headerChannel] = 'end';
                    }
                }
                if (headerComponent?.[0]) {
                    // set header/footerBand
                    const sizeType = channel === 'row' ? 'height' : 'width';
                    const bandType = headerType === 'header' ? 'headerBand' : 'footerBand';
                    if (channel !== 'facet' && !this.child.component.layoutSize.get(sizeType)) {
                        // If facet child does not have size signal, then apply headerBand
                        layoutMixins[bandType] ?? (layoutMixins[bandType] = {});
                        layoutMixins[bandType][channel] = 0.5;
                    }
                    if (layoutHeaderComponent.title) {
                        layoutMixins.offset ?? (layoutMixins.offset = {});
                        layoutMixins.offset[channel === 'row' ? 'rowTitle' : 'columnTitle'] = 10;
                    }
                }
            }
        }
        return layoutMixins;
    }
    assembleDefaultLayout() {
        const { column, row } = this.facet;
        const columns = column ? this.columnDistinctSignal() : row ? 1 : undefined;
        let align = 'all';
        // Do not align the cells if the scale corresponding to the direction is indepent.
        // We always align when we facet into both row and column.
        if (!row && this.component.resolve.scale.x === 'independent') {
            align = 'none';
        }
        else if (!column && this.component.resolve.scale.y === 'independent') {
            align = 'none';
        }
        return {
            ...this.getHeaderLayoutMixins(),
            ...(columns ? { columns } : {}),
            bounds: 'full',
            align
        };
    }
    assembleLayoutSignals() {
        // FIXME(https://github.com/vega/vega-lite/issues/1193): this can be incorrect if we have independent scales.
        return this.child.assembleLayoutSignals();
    }
    columnDistinctSignal() {
        if (this.parent && this.parent instanceof standalone_FacetModel) {
            // For nested facet, we will add columns to group mark instead
            // See discussion in https://github.com/vega/vega/issues/952
            // and https://github.com/vega/vega-view/releases/tag/v1.2.6
            return undefined;
        }
        else {
            // In facetNode.assemble(), the name is always this.getName('column') + '_layout'.
            const facetLayoutDataName = this.getName('column_domain');
            return { signal: `length(data('${facetLayoutDataName}'))` };
        }
    }
    assembleGroupStyle() {
        return undefined;
    }
    assembleGroup(signals) {
        if (this.parent && this.parent instanceof standalone_FacetModel) {
            // Provide number of columns for layout.
            // See discussion in https://github.com/vega/vega/issues/952
            // and https://github.com/vega/vega-view/releases/tag/v1.2.6
            return {
                ...(this.channelHasField('column')
                    ? {
                        encode: {
                            update: {
                                // TODO(https://github.com/vega/vega-lite/issues/2759):
                                // Correct the signal for facet of concat of facet_column
                                columns: { field: standalone_vgField(this.facet.column, { prefix: 'distinct' }) }
                            }
                        }
                    }
                    : {}),
                ...super.assembleGroup(signals)
            };
        }
        return super.assembleGroup(signals);
    }
    /**
     * Aggregate cardinality for calculating size
     */
    getCardinalityAggregateForChild() {
        const fields = [];
        const ops = [];
        const as = [];
        if (this.child instanceof standalone_FacetModel) {
            if (this.child.channelHasField('column')) {
                const field = standalone_vgField(this.child.facet.column);
                fields.push(field);
                ops.push('distinct');
                as.push(`distinct_${field}`);
            }
        }
        else {
            for (const channel of standalone_POSITION_SCALE_CHANNELS) {
                const childScaleComponent = this.child.component.scales[channel];
                if (childScaleComponent && !childScaleComponent.merged) {
                    const type = childScaleComponent.get('type');
                    const range = childScaleComponent.get('range');
                    if (standalone_hasDiscreteDomain(type) && standalone_isVgRangeStep(range)) {
                        const domain = standalone_assembleDomain(this.child, channel);
                        const field = standalone_getFieldFromDomain(domain);
                        if (field) {
                            fields.push(field);
                            ops.push('distinct');
                            as.push(`distinct_${field}`);
                        }
                        else {
                            standalone_log_warn(standalone_unknownField(channel));
                        }
                    }
                }
            }
        }
        return { fields, ops, as };
    }
    assembleFacet() {
        const { name, data } = this.component.data.facetRoot;
        const { row, column } = this.facet;
        const { fields, ops, as } = this.getCardinalityAggregateForChild();
        const groupby = [];
        for (const channel of standalone_FACET_CHANNELS) {
            const fieldDef = this.facet[channel];
            if (fieldDef) {
                groupby.push(standalone_vgField(fieldDef));
                const { bin, sort } = fieldDef;
                if (standalone_isBinning(bin)) {
                    groupby.push(standalone_vgField(fieldDef, { binSuffix: 'end' }));
                }
                if (standalone_isSortField(sort)) {
                    const { field, op = standalone_DEFAULT_SORT_OP } = sort;
                    const outputName = standalone_facetSortFieldName(fieldDef, sort);
                    if (row && column) {
                        // For crossed facet, use pre-calculate field as it requires a different groupby
                        // For each calculated field, apply max and assign them to the same name as
                        // all values of the same group should be the same anyway.
                        fields.push(outputName);
                        ops.push('max');
                        as.push(outputName);
                    }
                    else {
                        fields.push(field);
                        ops.push(op);
                        as.push(outputName);
                    }
                }
                else if (standalone_vega_util_module_isArray(sort)) {
                    const outputName = standalone_sortArrayIndexField(fieldDef, channel);
                    fields.push(outputName);
                    ops.push('max');
                    as.push(outputName);
                }
            }
        }
        const cross = !!row && !!column;
        return {
            name,
            data,
            groupby,
            ...(cross || fields.length > 0
                ? {
                    aggregate: {
                        ...(cross ? { cross } : {}),
                        ...(fields.length ? { fields, ops, as } : {})
                    }
                }
                : {})
        };
    }
    facetSortFields(channel) {
        const { facet } = this;
        const fieldDef = facet[channel];
        if (fieldDef) {
            if (standalone_isSortField(fieldDef.sort)) {
                return [standalone_facetSortFieldName(fieldDef, fieldDef.sort, { expr: 'datum' })];
            }
            else if (standalone_vega_util_module_isArray(fieldDef.sort)) {
                return [standalone_sortArrayIndexField(fieldDef, channel, { expr: 'datum' })];
            }
            return [standalone_vgField(fieldDef, { expr: 'datum' })];
        }
        return [];
    }
    facetSortOrder(channel) {
        const { facet } = this;
        const fieldDef = facet[channel];
        if (fieldDef) {
            const { sort } = fieldDef;
            const order = (standalone_isSortField(sort) ? sort.order : !standalone_vega_util_module_isArray(sort) && sort) || 'ascending';
            return [order];
        }
        return [];
    }
    assembleLabelTitle() {
        const { facet, config } = this;
        if (facet.facet) {
            // Facet always uses title to display labels
            return standalone_assembleLabelTitle(facet.facet, 'facet', config);
        }
        const ORTHOGONAL_ORIENT = {
            row: ['top', 'bottom'],
            column: ['left', 'right']
        };
        for (const channel of standalone_HEADER_CHANNELS) {
            if (facet[channel]) {
                const labelOrient = standalone_getHeaderProperty('labelOrient', facet[channel]?.header, config, channel);
                if (ORTHOGONAL_ORIENT[channel].includes(labelOrient)) {
                    // Row/Column with orthogonal labelOrient must use title to display labels
                    return standalone_assembleLabelTitle(facet[channel], channel, config);
                }
            }
        }
        return undefined;
    }
    assembleMarks() {
        const { child } = this;
        // If we facet by two dimensions, we need to add a cross operator to the aggregation
        // so that we create all groups
        const facetRoot = this.component.data.facetRoot;
        const data = standalone_assembleFacetData(facetRoot);
        const encodeEntry = child.assembleGroupEncodeEntry(false);
        const title = this.assembleLabelTitle() || child.assembleTitle();
        const style = child.assembleGroupStyle();
        const markGroup = {
            name: this.getName('cell'),
            type: 'group',
            ...(title ? { title } : {}),
            ...(style ? { style } : {}),
            from: {
                facet: this.assembleFacet()
            },
            // TODO: move this to after data
            sort: {
                field: standalone_FACET_CHANNELS.map(c => this.facetSortFields(c)).flat(),
                order: standalone_FACET_CHANNELS.map(c => this.facetSortOrder(c)).flat()
            },
            ...(data.length > 0 ? { data } : {}),
            ...(encodeEntry ? { encode: { update: encodeEntry } } : {}),
            ...child.assembleGroup(standalone_assembleFacetSignals(this, []))
        };
        return [markGroup];
    }
    getMapping() {
        return this.facet;
    }
}
//# sourceMappingURL=facet.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/joinaggregatefacet.js




function standalone_makeJoinAggregateFromFacet(parent, facet) {
    const { row, column } = facet;
    if (row && column) {
        let newParent = null;
        // only need to make one for crossed facet
        for (const fieldDef of [row, column]) {
            if (standalone_isSortField(fieldDef.sort)) {
                const { field, op = standalone_DEFAULT_SORT_OP } = fieldDef.sort;
                parent = newParent = new standalone_JoinAggregateTransformNode(parent, {
                    joinaggregate: [
                        {
                            op,
                            field,
                            as: standalone_facetSortFieldName(fieldDef, fieldDef.sort, { forAs: true })
                        }
                    ],
                    groupby: [standalone_vgField(fieldDef)]
                });
            }
        }
        return newParent;
    }
    return null;
}
//# sourceMappingURL=joinaggregatefacet.js.map
;// ../../node_modules/vega-lite/build/src/compile/data/parse.js









































function standalone_findSource(data, sources) {
    for (const other of sources) {
        const otherData = other.data;
        // if both datasets have a name defined, we cannot merge
        if (data.name && other.hasName() && data.name !== other.dataName) {
            continue;
        }
        const formatMesh = data.format?.mesh;
        const otherFeature = otherData.format?.feature;
        // feature and mesh are mutually exclusive
        if (formatMesh && otherFeature) {
            continue;
        }
        // we have to extract the same feature or mesh
        const formatFeature = data.format?.feature;
        if ((formatFeature || otherFeature) && formatFeature !== otherFeature) {
            continue;
        }
        const otherMesh = otherData.format?.mesh;
        if ((formatMesh || otherMesh) && formatMesh !== otherMesh) {
            continue;
        }
        if (standalone_isInlineData(data) && standalone_isInlineData(otherData)) {
            if (standalone_deepEqual(data.values, otherData.values)) {
                return other;
            }
        }
        else if (standalone_isUrlData(data) && standalone_isUrlData(otherData)) {
            if (data.url === otherData.url) {
                return other;
            }
        }
        else if (standalone_isNamedData(data)) {
            if (data.name === other.dataName) {
                return other;
            }
        }
    }
    return null;
}
function standalone_parseRoot(model, sources) {
    if (model.data || !model.parent) {
        // if the model defines a data source or is the root, create a source node
        if (model.data === null) {
            // data: null means we should ignore the parent's data so we just create a new data source
            const source = new standalone_SourceNode({ values: [] });
            sources.push(source);
            return source;
        }
        const existingSource = standalone_findSource(model.data, sources);
        if (existingSource) {
            if (!standalone_isGenerator(model.data)) {
                existingSource.data.format = standalone_mergeDeep({}, model.data.format, existingSource.data.format);
            }
            // if the new source has a name but the existing one does not, we can set it
            if (!existingSource.hasName() && model.data.name) {
                existingSource.dataName = model.data.name;
            }
            return existingSource;
        }
        else {
            const source = new standalone_SourceNode(model.data);
            sources.push(source);
            return source;
        }
    }
    else {
        // If we don't have a source defined (overriding parent's data), use the parent's facet root or main.
        return model.parent.component.data.facetRoot
            ? model.parent.component.data.facetRoot
            : model.parent.component.data.main;
    }
}
/**
 * Parses a transform array into a chain of connected dataflow nodes.
 */
function standalone_parseTransformArray(head, model, ancestorParse) {
    let lookupCounter = 0;
    for (const t of model.transforms) {
        let derivedType = undefined;
        let transformNode;
        if (standalone_isCalculate(t)) {
            transformNode = head = new standalone_CalculateNode(head, t);
            derivedType = 'derived';
        }
        else if (standalone_isFilter(t)) {
            const implicit = standalone_getImplicitFromFilterTransform(t);
            transformNode = head = standalone_ParseNode.makeWithAncestors(head, {}, implicit, ancestorParse) ?? head;
            head = new standalone_FilterNode(head, model, t.filter);
        }
        else if (standalone_isBin(t)) {
            transformNode = head = standalone_BinNode.makeFromTransform(head, t, model);
            derivedType = 'number';
        }
        else if (standalone_isTimeUnit(t)) {
            derivedType = 'date';
            const parsedAs = ancestorParse.getWithExplicit(t.field);
            // Create parse node because the input to time unit is always date.
            if (parsedAs.value === undefined) {
                head = new standalone_ParseNode(head, { [t.field]: derivedType });
                ancestorParse.set(t.field, derivedType, false);
            }
            transformNode = head = standalone_TimeUnitNode.makeFromTransform(head, t);
        }
        else if (standalone_transform_isAggregate(t)) {
            transformNode = head = standalone_AggregateNode.makeFromTransform(head, t);
            derivedType = 'number';
            if (standalone_requiresSelectionId(model)) {
                head = new standalone_IdentifierNode(head);
            }
        }
        else if (standalone_isLookup(t)) {
            transformNode = head = standalone_LookupNode.make(head, model, t, lookupCounter++);
            derivedType = 'derived';
        }
        else if (standalone_isWindow(t)) {
            transformNode = head = new standalone_WindowTransformNode(head, t);
            derivedType = 'number';
        }
        else if (standalone_isJoinAggregate(t)) {
            transformNode = head = new standalone_JoinAggregateTransformNode(head, t);
            derivedType = 'number';
        }
        else if (standalone_isStack(t)) {
            transformNode = head = standalone_StackNode.makeFromTransform(head, t);
            derivedType = 'derived';
        }
        else if (standalone_isFold(t)) {
            transformNode = head = new standalone_FoldTransformNode(head, t);
            derivedType = 'derived';
        }
        else if (standalone_isExtent(t)) {
            transformNode = head = new standalone_ExtentTransformNode(head, t);
            derivedType = 'derived';
        }
        else if (standalone_isFlatten(t)) {
            transformNode = head = new standalone_FlattenTransformNode(head, t);
            derivedType = 'derived';
        }
        else if (standalone_isPivot(t)) {
            transformNode = head = new standalone_PivotTransformNode(head, t);
            derivedType = 'derived';
        }
        else if (standalone_isSample(t)) {
            head = new standalone_SampleTransformNode(head, t);
        }
        else if (standalone_isImpute(t)) {
            transformNode = head = standalone_ImputeNode.makeFromTransform(head, t);
            derivedType = 'derived';
        }
        else if (standalone_isDensity(t)) {
            transformNode = head = new standalone_DensityTransformNode(head, t);
            derivedType = 'derived';
        }
        else if (standalone_transform_isQuantile(t)) {
            transformNode = head = new standalone_QuantileTransformNode(head, t);
            derivedType = 'derived';
        }
        else if (standalone_isRegression(t)) {
            transformNode = head = new standalone_RegressionTransformNode(head, t);
            derivedType = 'derived';
        }
        else if (standalone_isLoess(t)) {
            transformNode = head = new standalone_LoessTransformNode(head, t);
            derivedType = 'derived';
        }
        else {
            standalone_log_warn(standalone_invalidTransformIgnored(t));
            continue;
        }
        if (transformNode && derivedType !== undefined) {
            for (const field of transformNode.producedFields() ?? []) {
                ancestorParse.set(field, derivedType, false);
            }
        }
    }
    return head;
}
/*
Description of the dataflow (http://asciiflow.com/):
     +--------+
     | Source |
     +---+----+
         |
         v
     FormatParse
     (explicit)
         |
         v
     Transforms
(Filter, Calculate, Binning, TimeUnit, Aggregate, Window, ...)
         |
         v
     FormatParse
     (implicit)
         |
         v
 Binning (in `encoding`)
         |
         v
 Timeunit (in `encoding`)
         |
         v
Formula From Sort Array
         |
         v
      +--+--+
      | Raw |
      +-----+
         |
         v
  Aggregate (in `encoding`)
         |
         v
  Stack (in `encoding`)
         |
         v
+- - - - - - - - - - -+
|   PreFilterInvalid  | - - - -> scale domains
|(when scales need it)|
+- - - - - - - - - - -+
         |
         v
  Invalid Filter (if the main data source needs it)
         |
         v
   +----------+
   |   Main   | - - - -> scale domains
   +----------+
         |
         v
+- - - - - - - - - - -+
|   PostFilterInvalid | - - - -> scale domains
|(when scales need it)|
+- - - - - - - - - - -+
         |
         v
     +-------+
     | Facet |----> "column", "column-layout", and "row"
     +-------+
         |
         v
  ...Child data...
*/
function standalone_parse_parseData(model) {
    let head = standalone_parseRoot(model, model.component.data.sources);
    const { outputNodes, outputNodeRefCounts } = model.component.data;
    const data = model.data;
    const newData = data && (standalone_isGenerator(data) || standalone_isUrlData(data) || standalone_isInlineData(data));
    const ancestorParse = !newData && model.parent ? model.parent.component.data.ancestorParse.clone() : new standalone_AncestorParse();
    if (standalone_isGenerator(data)) {
        // insert generator transform
        if (standalone_isSequenceGenerator(data)) {
            head = new standalone_SequenceNode(head, data.sequence);
        }
        else if (standalone_isGraticuleGenerator(data)) {
            head = new standalone_GraticuleNode(head, data.graticule);
        }
        // no parsing necessary for generator
        ancestorParse.parseNothing = true;
    }
    else if (data?.format?.parse === null) {
        // format.parse: null means disable parsing
        ancestorParse.parseNothing = true;
    }
    head = standalone_ParseNode.makeExplicit(head, model, ancestorParse) ?? head;
    // Default discrete selections require an identifer transform to
    // uniquely identify data points. Add this transform at the head of
    // the pipeline such that the identifier field is available for all
    // subsequent datasets. During optimization, we will remove this
    // transform if it proves to be unnecessary. Additional identifier
    // transforms will be necessary when new tuples are constructed
    // (e.g., post-aggregation).
    head = new standalone_IdentifierNode(head);
    // HACK: This is equivalent for merging bin extent for union scale.
    // FIXME(https://github.com/vega/vega-lite/issues/2270): Correctly merge extent / bin node for shared bin scale
    const parentIsLayer = model.parent && standalone_isLayerModel(model.parent);
    if (standalone_isUnitModel(model) || standalone_isFacetModel(model)) {
        if (parentIsLayer) {
            head = standalone_BinNode.makeFromEncoding(head, model) ?? head;
        }
    }
    if (model.transforms.length > 0) {
        head = standalone_parseTransformArray(head, model, ancestorParse);
    }
    // create parse nodes for fields that need to be parsed (or flattened) implicitly
    const implicitSelection = standalone_getImplicitFromSelection(model);
    const implicitEncoding = standalone_getImplicitFromEncoding(model);
    head = standalone_ParseNode.makeWithAncestors(head, {}, { ...implicitSelection, ...implicitEncoding }, ancestorParse) ?? head;
    if (standalone_isUnitModel(model)) {
        head = standalone_GeoJSONNode.parseAll(head, model);
        head = standalone_GeoPointNode.parseAll(head, model);
    }
    if (standalone_isUnitModel(model) || standalone_isFacetModel(model)) {
        if (!parentIsLayer) {
            head = standalone_BinNode.makeFromEncoding(head, model) ?? head;
        }
        head = standalone_TimeUnitNode.makeFromEncoding(head, model) ?? head;
        head = standalone_CalculateNode.parseAllForSortIndex(head, model);
    }
    // add an output node pre aggregation
    const raw = (head = standalone_makeOutputNode(standalone_DataSourceType.Raw, model, head));
    if (standalone_isUnitModel(model)) {
        const agg = standalone_AggregateNode.makeFromEncoding(head, model);
        if (agg) {
            head = agg;
            if (standalone_requiresSelectionId(model)) {
                head = new standalone_IdentifierNode(head);
            }
        }
        head = standalone_ImputeNode.makeFromEncoding(head, model) ?? head;
        head = standalone_StackNode.makeFromEncoding(head, model) ?? head;
    }
    let preFilterInvalid;
    let dataSourcesForHandlingInvalidValues;
    if (standalone_isUnitModel(model)) {
        const { markDef, mark, config } = model;
        const invalid = standalone_getMarkPropOrConfig('invalid', markDef, config);
        const { marks, scales } = (dataSourcesForHandlingInvalidValues = standalone_getDataSourcesForHandlingInvalidValues({
            invalid,
            isPath: standalone_isPathMark(mark)
        }));
        if (marks !== scales && scales === 'include-invalid-values') {
            // Create a seperate preFilterInvalid dataSource if scales need pre-filter data but marks needs post-filter.
            preFilterInvalid = head = standalone_makeOutputNode(standalone_DataSourceType.PreFilterInvalid, model, head);
        }
        if (marks === 'exclude-invalid-values') {
            head = standalone_FilterInvalidNode.make(head, model, dataSourcesForHandlingInvalidValues) ?? head;
        }
    }
    // output "main" node for marks
    const main = (head = standalone_makeOutputNode(standalone_DataSourceType.Main, model, head));
    let postFilterInvalid;
    if (standalone_isUnitModel(model) && dataSourcesForHandlingInvalidValues) {
        const { marks, scales } = dataSourcesForHandlingInvalidValues;
        if (marks === 'include-invalid-values' && scales === 'exclude-invalid-values') {
            // Create a seperate postFilterInvalid dataSource if scales need post-filter data but marks needs pre-filter.
            head = standalone_FilterInvalidNode.make(head, model, dataSourcesForHandlingInvalidValues) ?? head;
            postFilterInvalid = head = standalone_makeOutputNode(standalone_DataSourceType.PostFilterInvalid, model, head);
        }
    }
    if (standalone_isUnitModel(model)) {
        standalone_materializeSelections(model, main);
    }
    // add facet marker
    let facetRoot = null;
    if (standalone_isFacetModel(model)) {
        const facetName = model.getName('facet');
        // Derive new aggregate for facet's sort field
        // augment data source with new fields for crossed facet
        head = standalone_makeJoinAggregateFromFacet(head, model.facet) ?? head;
        facetRoot = new standalone_FacetNode(head, model, facetName, main.getSource());
        outputNodes[facetName] = facetRoot;
    }
    return {
        ...model.component.data,
        outputNodes,
        outputNodeRefCounts,
        raw,
        main,
        facetRoot,
        ancestorParse,
        preFilterInvalid,
        postFilterInvalid
    };
}
function standalone_makeOutputNode(dataSourceType, model, head) {
    const { outputNodes, outputNodeRefCounts } = model.component.data;
    const name = model.getDataName(dataSourceType);
    const node = new standalone_OutputNode(head, name, dataSourceType, outputNodeRefCounts);
    outputNodes[name] = node;
    return node;
}
//# sourceMappingURL=parse.js.map
;// ../../node_modules/vega-lite/build/src/compile/concat.js










class standalone_ConcatModel extends standalone_Model {
    constructor(spec, parent, parentGivenName, config) {
        super(spec, 'concat', parent, parentGivenName, config, spec.resolve);
        if (spec.resolve?.axis?.x === 'shared' || spec.resolve?.axis?.y === 'shared') {
            standalone_log_warn(standalone_CONCAT_CANNOT_SHARE_AXIS);
        }
        this.children = this.getChildren(spec).map((child, i) => {
            return standalone_buildModel(child, this, this.getName(`concat_${i}`), undefined, config);
        });
    }
    parseData() {
        this.component.data = standalone_parse_parseData(this);
        for (const child of this.children) {
            child.parseData();
        }
    }
    parseSelections() {
        // Merge selections up the hierarchy so that they may be referenced
        // across unit specs. Persist their definitions within each child
        // to assemble signals which remain within output Vega unit groups.
        this.component.selection = {};
        for (const child of this.children) {
            child.parseSelections();
            for (const key of standalone_util_keys(child.component.selection)) {
                this.component.selection[key] = child.component.selection[key];
            }
        }
        if (Object.values(this.component.selection).some(selCmpt => standalone_isTimerSelection(selCmpt))) {
            standalone_log_error(standalone_MULTI_VIEW_ANIMATION_UNSUPPORTED);
        }
    }
    parseMarkGroup() {
        for (const child of this.children) {
            child.parseMarkGroup();
        }
    }
    parseAxesAndHeaders() {
        for (const child of this.children) {
            child.parseAxesAndHeaders();
        }
        // TODO(#2415): support shared axes
    }
    getChildren(spec) {
        if (standalone_isVConcatSpec(spec)) {
            return spec.vconcat;
        }
        else if (standalone_isHConcatSpec(spec)) {
            return spec.hconcat;
        }
        return spec.concat;
    }
    parseLayoutSize() {
        standalone_parseConcatLayoutSize(this);
    }
    parseAxisGroup() {
        return null;
    }
    assembleSelectionTopLevelSignals(signals) {
        return this.children.reduce((sg, child) => child.assembleSelectionTopLevelSignals(sg), signals);
    }
    assembleSignals() {
        this.children.forEach(child => child.assembleSignals());
        return [];
    }
    assembleLayoutSignals() {
        const layoutSignals = standalone_assembleLayoutSignals(this);
        for (const child of this.children) {
            layoutSignals.push(...child.assembleLayoutSignals());
        }
        return layoutSignals;
    }
    assembleSelectionData(data) {
        return this.children.reduce((db, child) => child.assembleSelectionData(db), data);
    }
    assembleMarks() {
        // only children have marks
        return this.children.map(child => {
            const title = child.assembleTitle();
            const style = child.assembleGroupStyle();
            const encodeEntry = child.assembleGroupEncodeEntry(false);
            return {
                type: 'group',
                name: child.getName('group'),
                ...(title ? { title } : {}),
                ...(style ? { style } : {}),
                ...(encodeEntry ? { encode: { update: encodeEntry } } : {}),
                ...child.assembleGroup()
            };
        });
    }
    assembleGroupStyle() {
        return undefined;
    }
    assembleDefaultLayout() {
        const columns = this.layout.columns;
        return {
            ...(columns != null ? { columns } : {}),
            bounds: 'full',
            // Use align each so it can work with multiple plots with different size
            align: 'each'
        };
    }
}
//# sourceMappingURL=concat.js.map
;// ../../node_modules/vega-lite/build/src/compile/axis/component.js




function standalone_isFalseOrNull(v) {
    return v === false || v === null;
}
const standalone_AXIS_COMPONENT_PROPERTIES_INDEX = {
    disable: 1,
    gridScale: 1,
    scale: 1,
    ...standalone_COMMON_AXIS_PROPERTIES_INDEX,
    labelExpr: 1,
    encode: 1
};
const standalone_AXIS_COMPONENT_PROPERTIES = standalone_util_keys(standalone_AXIS_COMPONENT_PROPERTIES_INDEX);
class standalone_AxisComponent extends standalone_Split {
    constructor(explicit = {}, implicit = {}, mainExtracted = false) {
        super();
        this.explicit = explicit;
        this.implicit = implicit;
        this.mainExtracted = mainExtracted;
    }
    clone() {
        return new standalone_AxisComponent(standalone_duplicate(this.explicit), standalone_duplicate(this.implicit), this.mainExtracted);
    }
    hasAxisPart(part) {
        // FIXME(https://github.com/vega/vega-lite/issues/2552) this method can be wrong if users use a Vega theme.
        if (part === 'axis') {
            // always has the axis container part
            return true;
        }
        if (part === 'grid' || part === 'title') {
            return !!this.get(part);
        }
        // Other parts are enabled by default, so they should not be false or null.
        return !standalone_isFalseOrNull(this.get(part));
    }
    hasOrientSignalRef() {
        return standalone_isSignalRef(this.explicit.orient);
    }
}
//# sourceMappingURL=component.js.map
;// ../../node_modules/vega-lite/build/src/compile/axis/encode.js



function standalone_encode_labels(model, channel, specifiedLabelsSpec) {
    const { encoding, config } = model;
    const fieldOrDatumDef = standalone_getFieldOrDatumDef(encoding[channel]) ?? standalone_getFieldOrDatumDef(encoding[standalone_getSecondaryRangeChannel(channel)]);
    const axis = model.axis(channel) || {};
    const { format, formatType } = axis;
    if (standalone_isCustomFormatType(formatType)) {
        return {
            text: standalone_formatCustomType({
                fieldOrDatumDef,
                field: 'datum.value',
                format,
                formatType,
                config
            }),
            ...specifiedLabelsSpec
        };
    }
    else if (format === undefined && formatType === undefined && config.customFormatTypes) {
        if (standalone_channelDefType(fieldOrDatumDef) === 'quantitative') {
            if (standalone_isPositionFieldOrDatumDef(fieldOrDatumDef) &&
                fieldOrDatumDef.stack === 'normalize' &&
                config.normalizedNumberFormatType) {
                return {
                    text: standalone_formatCustomType({
                        fieldOrDatumDef,
                        field: 'datum.value',
                        format: config.normalizedNumberFormat,
                        formatType: config.normalizedNumberFormatType,
                        config
                    }),
                    ...specifiedLabelsSpec
                };
            }
            else if (config.numberFormatType) {
                return {
                    text: standalone_formatCustomType({
                        fieldOrDatumDef,
                        field: 'datum.value',
                        format: config.numberFormat,
                        formatType: config.numberFormatType,
                        config
                    }),
                    ...specifiedLabelsSpec
                };
            }
        }
        if (standalone_channelDefType(fieldOrDatumDef) === 'temporal' &&
            config.timeFormatType &&
            standalone_isFieldDef(fieldOrDatumDef) &&
            !fieldOrDatumDef.timeUnit) {
            return {
                text: standalone_formatCustomType({
                    fieldOrDatumDef,
                    field: 'datum.value',
                    format: config.timeFormat,
                    formatType: config.timeFormatType,
                    config
                }),
                ...specifiedLabelsSpec
            };
        }
    }
    return specifiedLabelsSpec;
}
//# sourceMappingURL=encode.js.map
;// ../../node_modules/vega-lite/build/src/compile/axis/parse.js














function standalone_parseUnitAxes(model) {
    return standalone_POSITION_SCALE_CHANNELS.reduce((axis, channel) => {
        if (model.component.scales[channel]) {
            axis[channel] = [standalone_parse_parseAxis(channel, model)];
        }
        return axis;
    }, {});
}
const standalone_OPPOSITE_ORIENT = {
    bottom: 'top',
    top: 'bottom',
    left: 'right',
    right: 'left'
};
function standalone_parseLayerAxes(model) {
    const { axes, resolve } = model.component;
    const axisCount = { top: 0, bottom: 0, right: 0, left: 0 };
    for (const child of model.children) {
        child.parseAxesAndHeaders();
        for (const channel of standalone_util_keys(child.component.axes)) {
            resolve.axis[channel] = standalone_parseGuideResolve(model.component.resolve, channel);
            if (resolve.axis[channel] === 'shared') {
                // If the resolve says shared (and has not been overridden)
                // We will try to merge and see if there is a conflict
                axes[channel] = standalone_mergeAxisComponents(axes[channel], child.component.axes[channel]);
                if (!axes[channel]) {
                    // If merge returns nothing, there is a conflict so we cannot make the axis shared.
                    // Thus, mark axis as independent and remove the axis component.
                    resolve.axis[channel] = 'independent';
                    delete axes[channel];
                }
            }
        }
    }
    // Move axes to layer's axis component and merge shared axes
    for (const channel of standalone_POSITION_SCALE_CHANNELS) {
        for (const child of model.children) {
            if (!child.component.axes[channel]) {
                // skip if the child does not have a particular axis
                continue;
            }
            if (resolve.axis[channel] === 'independent') {
                // If axes are independent, concat the axisComponent array.
                axes[channel] = (axes[channel] ?? []).concat(child.component.axes[channel]);
                // Automatically adjust orient
                for (const axisComponent of child.component.axes[channel]) {
                    const { value: orient, explicit } = axisComponent.getWithExplicit('orient');
                    if (standalone_isSignalRef(orient)) {
                        continue;
                    }
                    if (axisCount[orient] > 0 && !explicit) {
                        // Change axis orient if the number do not match
                        const oppositeOrient = standalone_OPPOSITE_ORIENT[orient];
                        if (axisCount[orient] > axisCount[oppositeOrient]) {
                            axisComponent.set('orient', oppositeOrient, false);
                        }
                    }
                    axisCount[orient]++;
                    // TODO(https://github.com/vega/vega-lite/issues/2634): automatically add extra offset?
                }
            }
            // After merging, make sure to remove axes from child
            delete child.component.axes[channel];
        }
        // Show gridlines for first axis only for dual-axis chart
        if (resolve.axis[channel] === 'independent' && axes[channel] && axes[channel].length > 1) {
            for (const [index, axisCmpt] of (axes[channel] || []).entries()) {
                if (index > 0 && !!axisCmpt.get('grid') && !axisCmpt.explicit.grid) {
                    axisCmpt.implicit.grid = false;
                }
            }
        }
    }
}
function standalone_mergeAxisComponents(mergedAxisCmpts, childAxisCmpts) {
    if (mergedAxisCmpts) {
        // FIXME: this is a bit wrong once we support multiple axes
        if (mergedAxisCmpts.length !== childAxisCmpts.length) {
            return undefined; // Cannot merge axis component with different number of axes.
        }
        const length = mergedAxisCmpts.length;
        for (let i = 0; i < length; i++) {
            const merged = mergedAxisCmpts[i];
            const child = childAxisCmpts[i];
            if (!!merged !== !!child) {
                return undefined;
            }
            else if (merged && child) {
                const mergedOrient = merged.getWithExplicit('orient');
                const childOrient = child.getWithExplicit('orient');
                if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) {
                    // TODO: throw warning if resolve is explicit (We don't have info about explicit/implicit resolve yet.)
                    // Cannot merge due to inconsistent orient
                    return undefined;
                }
                else {
                    mergedAxisCmpts[i] = standalone_mergeAxisComponent(merged, child);
                }
            }
        }
    }
    else {
        // For first one, return a copy of the child
        return childAxisCmpts.map(axisComponent => axisComponent.clone());
    }
    return mergedAxisCmpts;
}
function standalone_mergeAxisComponent(merged, child) {
    for (const prop of standalone_AXIS_COMPONENT_PROPERTIES) {
        const mergedValueWithExplicit = standalone_mergeValuesWithExplicit(merged.getWithExplicit(prop), child.getWithExplicit(prop), prop, 'axis', 
        // Tie breaker function
        (v1, v2) => {
            switch (prop) {
                case 'title':
                    return standalone_mergeTitleComponent(v1, v2);
                case 'gridScale':
                    return {
                        explicit: v1.explicit, // keep the old explicit
                        value: standalone_getFirstDefined(v1.value, v2.value)
                    };
            }
            return standalone_defaultTieBreaker(v1, v2, prop, 'axis');
        });
        merged.setWithExplicit(prop, mergedValueWithExplicit);
    }
    return merged;
}
function standalone_parse_isExplicit(value, property, axis, model, channel) {
    if (property === 'disable') {
        return axis !== undefined; // if axis is specified or null/false, then its enable/disable state is explicit
    }
    axis = axis || {};
    switch (property) {
        case 'titleAngle':
        case 'labelAngle':
            return value === (standalone_isSignalRef(axis.labelAngle) ? axis.labelAngle : standalone_normalizeAngle(axis.labelAngle));
        case 'values':
            return !!axis.values;
        // specified axis.values is already respected, but may get transformed.
        case 'encode':
            // both VL axis.encoding and axis.labelAngle affect VG axis.encode
            return !!axis.encoding || !!axis.labelAngle;
        case 'title':
            // title can be explicit if fieldDef.title is set
            if (value === standalone_getFieldDefTitle(model, channel)) {
                return true;
            }
    }
    // Otherwise, things are explicit if the returned value matches the specified property
    return value === axis[property];
}
/**
 * Properties to always include values from config
 */
const standalone_propsToAlwaysIncludeConfig = new Set([
    'grid', // Grid is an exception because we need to set grid = true to generate another grid axis
    'translate', // translate has dependent logic for bar's bin position and it's 0.5 by default in Vega. If a config overrides this value, we need to know.
    // the rest are not axis configs in Vega, but are in VL, so we need to set too.
    'format',
    'formatType',
    'orient',
    'labelExpr',
    'tickCount',
    'position',
    'tickMinStep'
]);
function standalone_parse_parseAxis(channel, model) {
    let axis = model.axis(channel);
    const axisComponent = new standalone_AxisComponent();
    const fieldOrDatumDef = standalone_getFieldOrDatumDef(model.encoding[channel]);
    const { mark, config } = model;
    const orient = axis?.orient ||
        config[channel === 'x' ? 'axisX' : 'axisY']?.orient ||
        config.axis?.orient ||
        standalone_defaultOrient(channel);
    const scaleType = model.getScaleComponent(channel).get('type');
    const axisConfigs = standalone_getAxisConfigs(channel, scaleType, orient, model.config);
    const disable = axis !== undefined ? !axis : standalone_getAxisConfig('disable', config.style, axis?.style, axisConfigs).configValue;
    axisComponent.set('disable', disable, axis !== undefined);
    if (disable) {
        return axisComponent;
    }
    axis = axis || {};
    const labelAngle = standalone_getLabelAngle(fieldOrDatumDef, axis, channel, config.style, axisConfigs);
    const formatType = standalone_guideFormatType(axis.formatType, fieldOrDatumDef, scaleType);
    const format = standalone_guideFormat(fieldOrDatumDef, fieldOrDatumDef.type, axis.format, axis.formatType, config, true);
    const ruleParams = {
        fieldOrDatumDef,
        axis,
        channel,
        model,
        scaleType,
        orient,
        labelAngle,
        format,
        formatType,
        mark,
        config
    };
    // 1.2. Add properties
    for (const property of standalone_AXIS_COMPONENT_PROPERTIES) {
        const value = property in standalone_axisRules ? standalone_axisRules[property](ruleParams) : standalone_isAxisProperty(property) ? axis[property] : undefined;
        const hasValue = value !== undefined;
        const explicit = standalone_parse_isExplicit(value, property, axis, model, channel);
        if (hasValue && explicit) {
            axisComponent.set(property, value, explicit);
        }
        else {
            const { configValue = undefined, configFrom = undefined } = standalone_isAxisProperty(property) && property !== 'values'
                ? standalone_getAxisConfig(property, config.style, axis.style, axisConfigs)
                : {};
            const hasConfigValue = configValue !== undefined;
            if (hasValue && !hasConfigValue) {
                // only set property if it is explicitly set or has no config value (otherwise we will accidentally override config)
                axisComponent.set(property, value, explicit);
            }
            else if (
            // Cases need implicit values
            // 1. Axis config that aren't available in Vega
            !(configFrom === 'vgAxisConfig') ||
                // 2. Certain properties are always included (see `propsToAlwaysIncludeConfig`'s declaration for more details)
                (standalone_propsToAlwaysIncludeConfig.has(property) && hasConfigValue) ||
                // 3. Conditional axis values and signals
                standalone_isConditionalAxisValue(configValue) ||
                standalone_isSignalRef(configValue)) {
                // If a config is specified and is conditional, copy conditional value from axis config
                axisComponent.set(property, configValue, false);
            }
        }
    }
    // 2) Add guide encode definition groups
    const axisEncoding = axis.encoding ?? {};
    const axisEncode = standalone_AXIS_PARTS.reduce((e, part) => {
        if (!axisComponent.hasAxisPart(part)) {
            // No need to create encode for a disabled part.
            return e;
        }
        const axisEncodingPart = standalone_guideEncodeEntry(axisEncoding[part] ?? {}, model);
        const value = part === 'labels' ? standalone_encode_labels(model, channel, axisEncodingPart) : axisEncodingPart;
        if (value !== undefined && !standalone_isEmpty(value)) {
            e[part] = { update: value };
        }
        return e;
    }, {});
    // FIXME: By having encode as one property, we won't have fine grained encode merging.
    if (!standalone_isEmpty(axisEncode)) {
        axisComponent.set('encode', axisEncode, !!axis.encoding || axis.labelAngle !== undefined);
    }
    return axisComponent;
}
//# sourceMappingURL=parse.js.map
;// ../../node_modules/vega-lite/build/src/compile/layoutsize/init.js




function standalone_initLayoutSize({ encoding, size }) {
    for (const channel of standalone_POSITION_SCALE_CHANNELS) {
        const sizeType = standalone_getSizeChannel(channel);
        if (standalone_isStep(size[sizeType])) {
            if (standalone_isContinuousFieldOrDatumDef(encoding[channel])) {
                delete size[sizeType];
                standalone_log_warn(standalone_stepDropped(sizeType));
            }
        }
    }
    return size;
}
//# sourceMappingURL=init.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/arc.js

const standalone_arc_arc = {
    vgMark: 'arc',
    encodeEntry: (model) => {
        return {
            ...standalone_baseEncodeEntry(model, {
                align: 'ignore',
                baseline: 'ignore',
                color: 'include',
                size: 'ignore',
                orient: 'ignore',
                theta: 'ignore'
            }),
            ...standalone_pointPosition('x', model, { defaultPos: 'mid' }),
            ...standalone_pointPosition('y', model, { defaultPos: 'mid' }),
            // arcs are rectangles in polar coordinates
            ...standalone_rectPosition(model, 'radius'),
            ...standalone_rectPosition(model, 'theta')
        };
    }
};
//# sourceMappingURL=arc.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/area.js

const standalone_area_area = {
    vgMark: 'area',
    encodeEntry: (model) => {
        return {
            ...standalone_baseEncodeEntry(model, {
                align: 'ignore',
                baseline: 'ignore',
                color: 'include',
                orient: 'include',
                size: 'ignore',
                theta: 'ignore'
            }),
            ...standalone_pointOrRangePosition('x', model, {
                defaultPos: 'zeroOrMin',
                defaultPos2: 'zeroOrMin',
                range: model.markDef.orient === 'horizontal'
            }),
            ...standalone_pointOrRangePosition('y', model, {
                defaultPos: 'zeroOrMin',
                defaultPos2: 'zeroOrMin',
                range: model.markDef.orient === 'vertical'
            }),
            ...standalone_defined(model)
        };
    }
};
//# sourceMappingURL=area.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/bar.js

const standalone_bar = {
    vgMark: 'rect',
    encodeEntry: (model) => {
        return {
            ...standalone_baseEncodeEntry(model, {
                align: 'ignore',
                baseline: 'ignore',
                color: 'include',
                orient: 'ignore',
                size: 'ignore',
                theta: 'ignore'
            }),
            ...standalone_rectPosition(model, 'x'),
            ...standalone_rectPosition(model, 'y')
        };
    }
};
//# sourceMappingURL=bar.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/geoshape.js



const standalone_geoshape = {
    vgMark: 'shape',
    encodeEntry: (model) => {
        return {
            ...standalone_baseEncodeEntry(model, {
                align: 'ignore',
                baseline: 'ignore',
                color: 'include',
                size: 'ignore',
                orient: 'ignore',
                theta: 'ignore'
            })
        };
    },
    postEncodingTransform: (model) => {
        const { encoding } = model;
        const shapeDef = encoding.shape;
        const transform = {
            type: 'geoshape',
            projection: model.projectionName(),
            // as: 'shape',
            ...(shapeDef && standalone_isFieldDef(shapeDef) && shapeDef.type === standalone_GEOJSON
                ? { field: standalone_vgField(shapeDef, { expr: 'datum' }) }
                : {})
        };
        return [transform];
    }
};
//# sourceMappingURL=geoshape.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/image.js

const standalone_image_image = {
    vgMark: 'image',
    encodeEntry: (model) => {
        return {
            ...standalone_baseEncodeEntry(model, {
                align: 'ignore',
                baseline: 'ignore',
                color: 'ignore',
                orient: 'ignore',
                size: 'ignore',
                theta: 'ignore'
            }),
            ...standalone_rectPosition(model, 'x'),
            ...standalone_rectPosition(model, 'y'),
            ...standalone_text_text(model, 'url')
        };
    }
};
//# sourceMappingURL=image.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/line.js

const standalone_line_line = {
    vgMark: 'line',
    encodeEntry: (model) => {
        return {
            ...standalone_baseEncodeEntry(model, {
                align: 'ignore',
                baseline: 'ignore',
                color: 'include',
                size: 'ignore',
                orient: 'ignore',
                theta: 'ignore'
            }),
            ...standalone_pointPosition('x', model, { defaultPos: 'mid' }),
            ...standalone_pointPosition('y', model, { defaultPos: 'mid' }),
            ...standalone_nonPosition('size', model, {
                vgChannel: 'strokeWidth' // VL's line size is strokeWidth
            }),
            ...standalone_defined(model)
        };
    }
};
const standalone_line_trail = {
    vgMark: 'trail',
    encodeEntry: (model) => {
        return {
            ...standalone_baseEncodeEntry(model, {
                align: 'ignore',
                baseline: 'ignore',
                color: 'include',
                size: 'include',
                orient: 'ignore',
                theta: 'ignore'
            }),
            ...standalone_pointPosition('x', model, { defaultPos: 'mid' }),
            ...standalone_pointPosition('y', model, { defaultPos: 'mid' }),
            ...standalone_nonPosition('size', model),
            ...standalone_defined(model)
        };
    }
};
//# sourceMappingURL=line.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/point.js

function standalone_encodeEntry(model, fixedShape) {
    const { config } = model;
    return {
        ...standalone_baseEncodeEntry(model, {
            align: 'ignore',
            baseline: 'ignore',
            color: 'include',
            size: 'include',
            orient: 'ignore',
            theta: 'ignore'
        }),
        ...standalone_pointPosition('x', model, { defaultPos: 'mid' }),
        ...standalone_pointPosition('y', model, { defaultPos: 'mid' }),
        ...standalone_nonPosition('size', model),
        ...standalone_nonPosition('angle', model),
        ...standalone_shapeMixins(model, config, fixedShape)
    };
}
function standalone_shapeMixins(model, config, fixedShape) {
    if (fixedShape) {
        return { shape: { value: fixedShape } };
    }
    return standalone_nonPosition('shape', model);
}
const standalone_mark_point_point = {
    vgMark: 'symbol',
    encodeEntry: (model) => {
        return standalone_encodeEntry(model);
    }
};
const standalone_point_circle = {
    vgMark: 'symbol',
    encodeEntry: (model) => {
        return standalone_encodeEntry(model, 'circle');
    }
};
const standalone_point_square = {
    vgMark: 'symbol',
    encodeEntry: (model) => {
        return standalone_encodeEntry(model, 'square');
    }
};
//# sourceMappingURL=point.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/rect.js

const standalone_rect_rect = {
    vgMark: 'rect',
    encodeEntry: (model) => {
        return {
            ...standalone_baseEncodeEntry(model, {
                align: 'ignore',
                baseline: 'ignore',
                color: 'include',
                orient: 'ignore',
                size: 'ignore',
                theta: 'ignore'
            }),
            ...standalone_rectPosition(model, 'x'),
            ...standalone_rectPosition(model, 'y')
        };
    }
};
//# sourceMappingURL=rect.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/rule.js

const standalone_rule_rule = {
    vgMark: 'rule',
    encodeEntry: (model) => {
        const { markDef } = model;
        const orient = markDef.orient;
        if (!model.encoding.x && !model.encoding.y && !model.encoding.latitude && !model.encoding.longitude) {
            // Show nothing if we have none of x, y, lat, and long.
            return {};
        }
        return {
            ...standalone_baseEncodeEntry(model, {
                align: 'ignore',
                baseline: 'ignore',
                color: 'include',
                orient: 'ignore',
                size: 'ignore',
                theta: 'ignore'
            }),
            ...standalone_pointOrRangePosition('x', model, {
                defaultPos: orient === 'horizontal' ? 'zeroOrMax' : 'mid',
                defaultPos2: 'zeroOrMin',
                range: orient !== 'vertical' // include x2 for horizontal or line segment rule
            }),
            ...standalone_pointOrRangePosition('y', model, {
                defaultPos: orient === 'vertical' ? 'zeroOrMax' : 'mid',
                defaultPos2: 'zeroOrMin',
                range: orient !== 'horizontal' // include y2 for vertical or line segment rule
            }),
            ...standalone_nonPosition('size', model, {
                vgChannel: 'strokeWidth' // VL's rule size is strokeWidth
            })
        };
    }
};
//# sourceMappingURL=rule.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/text.js


const standalone_mark_text_text = {
    vgMark: 'text',
    encodeEntry: (model) => {
        const { config, encoding } = model;
        return {
            ...standalone_baseEncodeEntry(model, {
                align: 'include',
                baseline: 'include',
                color: 'include',
                size: 'ignore',
                orient: 'ignore',
                theta: 'include'
            }),
            ...standalone_pointPosition('x', model, { defaultPos: 'mid' }),
            ...standalone_pointPosition('y', model, { defaultPos: 'mid' }),
            ...standalone_text_text(model),
            ...standalone_nonPosition('size', model, {
                vgChannel: 'fontSize' // VL's text size is fontSize
            }),
            ...standalone_nonPosition('angle', model),
            ...standalone_valueIfDefined('align', standalone_align(model.markDef, encoding, config)),
            ...standalone_valueIfDefined('baseline', standalone_text_baseline(model.markDef, encoding, config)),
            ...standalone_pointPosition('radius', model, { defaultPos: null }),
            ...standalone_pointPosition('theta', model, { defaultPos: null })
        };
    }
};
function standalone_align(markDef, encoding, config) {
    const a = standalone_getMarkPropOrConfig('align', markDef, config);
    if (a === undefined) {
        return 'center';
    }
    // If there is a config, Vega-parser will process this already.
    return undefined;
}
function standalone_text_baseline(markDef, encoding, config) {
    const b = standalone_getMarkPropOrConfig('baseline', markDef, config);
    if (b === undefined) {
        return 'middle';
    }
    // If there is a config, Vega-parser will process this already.
    return undefined;
}
//# sourceMappingURL=text.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/tick.js


const standalone_tick_tick = {
    vgMark: 'rect',
    encodeEntry: (model) => {
        const { config, markDef } = model;
        const orient = markDef.orient;
        const vgSizeAxisChannel = orient === 'horizontal' ? 'x' : 'y';
        const vgThicknessAxisChannel = orient === 'horizontal' ? 'y' : 'x';
        const vgThicknessChannel = orient === 'horizontal' ? 'height' : 'width';
        return {
            ...standalone_baseEncodeEntry(model, {
                align: 'ignore',
                baseline: 'ignore',
                color: 'include',
                orient: 'ignore',
                size: 'ignore',
                theta: 'ignore'
            }),
            ...standalone_rectPosition(model, vgSizeAxisChannel),
            ...standalone_pointPosition(vgThicknessAxisChannel, model, {
                defaultPos: 'mid',
                vgChannel: vgThicknessAxisChannel === 'y' ? 'yc' : 'xc'
            }),
            [vgThicknessChannel]: standalone_signalOrValueRef(standalone_getMarkPropOrConfig('thickness', markDef, config))
        };
    }
};
//# sourceMappingURL=tick.js.map
;// ../../node_modules/vega-lite/build/src/compile/mark/mark.js



















const standalone_markCompiler = {
    arc: standalone_arc_arc,
    area: standalone_area_area,
    bar: standalone_bar,
    circle: standalone_point_circle,
    geoshape: standalone_geoshape,
    image: standalone_image_image,
    line: standalone_line_line,
    point: standalone_mark_point_point,
    rect: standalone_rect_rect,
    rule: standalone_rule_rule,
    square: standalone_point_square,
    text: standalone_mark_text_text,
    tick: standalone_tick_tick,
    trail: standalone_line_trail
};
function standalone_parseMarkGroups(model) {
    if (standalone_util_contains([standalone_LINE, standalone_AREA, standalone_TRAIL], model.mark)) {
        const details = standalone_pathGroupingFields(model.mark, model.encoding);
        if (details.length > 0) {
            return standalone_getPathGroups(model, details);
        }
        // otherwise use standard mark groups
    }
    else if (model.mark === standalone_BAR) {
        const hasCornerRadius = standalone_VG_CORNERRADIUS_CHANNELS.some(prop => standalone_getMarkPropOrConfig(prop, model.markDef, model.config));
        if (model.stack && !model.fieldDef('size') && hasCornerRadius) {
            return standalone_getGroupsForStackedBarWithCornerRadius(model);
        }
    }
    return standalone_getMarkGroup(model);
}
const standalone_FACETED_PATH_PREFIX = 'faceted_path_';
function standalone_getPathGroups(model, details) {
    // TODO: for non-stacked plot, map order to zindex. (Maybe rename order for layer to zindex?)
    return [
        {
            name: model.getName('pathgroup'),
            type: 'group',
            from: {
                facet: {
                    name: standalone_FACETED_PATH_PREFIX + model.requestDataName(standalone_DataSourceType.Main),
                    data: model.requestDataName(standalone_DataSourceType.Main),
                    groupby: details
                }
            },
            encode: {
                update: {
                    width: { field: { group: 'width' } },
                    height: { field: { group: 'height' } }
                }
            },
            // With subfacet for line/area group, need to use faceted data from above.
            marks: standalone_getMarkGroup(model, { fromPrefix: standalone_FACETED_PATH_PREFIX })
        }
    ];
}
const standalone_STACK_GROUP_PREFIX = 'stack_group_';
/**
 * We need to put stacked bars into groups in order to enable cornerRadius for stacks.
 * If stack is used and the model doesn't have size encoding, we put the mark into groups,
 * and apply cornerRadius properties at the group.
 */
function standalone_getGroupsForStackedBarWithCornerRadius(model) {
    // Generate the mark
    const [mark] = standalone_getMarkGroup(model, { fromPrefix: standalone_STACK_GROUP_PREFIX });
    // Get the scale for the stacked field
    const fieldScale = model.scaleName(model.stack.fieldChannel);
    const stackField = (opt = {}) => model.vgField(model.stack.fieldChannel, opt);
    // Find the min/max of the pixel value on the stacked direction
    const stackFieldGroup = (func, expr) => {
        const vgFieldMinMax = [
            stackField({ prefix: 'min', suffix: 'start', expr }),
            stackField({ prefix: 'max', suffix: 'start', expr }),
            stackField({ prefix: 'min', suffix: 'end', expr }),
            stackField({ prefix: 'max', suffix: 'end', expr })
        ];
        return `${func}(${vgFieldMinMax.map(field => `scale('${fieldScale}',${field})`).join(',')})`;
    };
    let groupUpdate;
    let innerGroupUpdate;
    // Build the encoding for group and an inner group
    if (model.stack.fieldChannel === 'x') {
        // Move cornerRadius, y/yc/y2/height properties to group
        // Group x/x2 should be the min/max of the marks within
        groupUpdate = {
            ...standalone_util_pick(mark.encode.update, ['y', 'yc', 'y2', 'height', ...standalone_VG_CORNERRADIUS_CHANNELS]),
            x: { signal: stackFieldGroup('min', 'datum') },
            x2: { signal: stackFieldGroup('max', 'datum') },
            clip: { value: true }
        };
        // Inner group should revert the x translation, and pass height through
        innerGroupUpdate = {
            x: { field: { group: 'x' }, mult: -1 },
            height: { field: { group: 'height' } }
        };
        // The marks should use the same height as group, without y/yc/y2 properties (because it's already done by group)
        // This is why size encoding is not supported yet
        mark.encode.update = {
            ...standalone_omit(mark.encode.update, ['y', 'yc', 'y2']),
            height: { field: { group: 'height' } }
        };
    }
    else {
        groupUpdate = {
            ...standalone_util_pick(mark.encode.update, ['x', 'xc', 'x2', 'width']),
            y: { signal: stackFieldGroup('min', 'datum') },
            y2: { signal: stackFieldGroup('max', 'datum') },
            clip: { value: true }
        };
        innerGroupUpdate = {
            y: { field: { group: 'y' }, mult: -1 },
            width: { field: { group: 'width' } }
        };
        mark.encode.update = {
            ...standalone_omit(mark.encode.update, ['x', 'xc', 'x2']),
            width: { field: { group: 'width' } }
        };
    }
    // Deal with cornerRadius properties
    for (const key of standalone_VG_CORNERRADIUS_CHANNELS) {
        const configValue = standalone_getMarkConfig(key, model.markDef, model.config);
        // Move from mark to group
        if (mark.encode.update[key]) {
            groupUpdate[key] = mark.encode.update[key];
            delete mark.encode.update[key];
        }
        else if (configValue) {
            groupUpdate[key] = standalone_signalOrValueRef(configValue);
        }
        // Overwrite any cornerRadius on mark set by config --- they are already moved to the group
        if (configValue) {
            mark.encode.update[key] = { value: 0 };
        }
    }
    const groupby = [];
    if (model.stack.groupbyChannels?.length > 0) {
        for (const groupbyChannel of model.stack.groupbyChannels) {
            // For bin and time unit, we have to add bin/timeunit -end channels.
            const groupByField = model.fieldDef(groupbyChannel);
            const field = standalone_vgField(groupByField);
            if (field) {
                groupby.push(field);
            }
            if (groupByField?.bin || groupByField?.timeUnit) {
                groupby.push(standalone_vgField(groupByField, { binSuffix: 'end' }));
            }
        }
    }
    const strokeProperties = [
        'stroke',
        'strokeWidth',
        'strokeJoin',
        'strokeCap',
        'strokeDash',
        'strokeDashOffset',
        'strokeMiterLimit',
        'strokeOpacity'
    ];
    // Generate stroke properties for the group
    groupUpdate = strokeProperties.reduce((encode, prop) => {
        if (mark.encode.update[prop]) {
            return { ...encode, [prop]: mark.encode.update[prop] };
        }
        else {
            const configValue = standalone_getMarkConfig(prop, model.markDef, model.config);
            if (configValue !== undefined) {
                return { ...encode, [prop]: standalone_signalOrValueRef(configValue) };
            }
            else {
                return encode;
            }
        }
    }, groupUpdate);
    // Apply strokeForeground and strokeOffset if stroke is used
    if (groupUpdate.stroke) {
        groupUpdate.strokeForeground = { value: true };
        groupUpdate.strokeOffset = { value: 0 };
    }
    return [
        {
            type: 'group',
            from: {
                facet: {
                    data: model.requestDataName(standalone_DataSourceType.Main),
                    name: standalone_STACK_GROUP_PREFIX + model.requestDataName(standalone_DataSourceType.Main),
                    groupby,
                    aggregate: {
                        fields: [
                            stackField({ suffix: 'start' }),
                            stackField({ suffix: 'start' }),
                            stackField({ suffix: 'end' }),
                            stackField({ suffix: 'end' })
                        ],
                        ops: ['min', 'max', 'min', 'max']
                    }
                }
            },
            encode: {
                update: groupUpdate
            },
            marks: [
                {
                    type: 'group',
                    encode: { update: innerGroupUpdate },
                    marks: [mark]
                }
            ]
        }
    ];
}
function standalone_mark_getSort(model) {
    const { encoding, stack, mark, markDef, config } = model;
    const order = encoding.order;
    if ((!standalone_vega_util_module_isArray(order) && standalone_isValueDef(order) && standalone_isNullOrFalse(order.value)) ||
        (!order && standalone_isNullOrFalse(standalone_getMarkPropOrConfig('order', markDef, config)))) {
        return undefined;
    }
    else if ((standalone_vega_util_module_isArray(order) || standalone_isFieldDef(order)) && !stack) {
        // Sort by the order field if it is specified and the field is not stacked. (For stacked field, order specify stack order.)
        return standalone_sortParams(order, { expr: 'datum' });
    }
    else if (standalone_isPathMark(mark)) {
        // For both line and area, we sort values based on dimension by default
        const dimensionChannel = markDef.orient === 'horizontal' ? 'y' : 'x';
        const dimensionChannelDef = encoding[dimensionChannel];
        if (standalone_isFieldDef(dimensionChannelDef)) {
            return { field: dimensionChannel };
        }
    }
    return undefined;
}
function standalone_getMarkGroup(model, opt = { fromPrefix: '' }) {
    const { mark, markDef, encoding, config } = model;
    const clip = standalone_getFirstDefined(markDef.clip, standalone_scaleClip(model), standalone_projectionClip(model));
    const style = standalone_common_getStyles(markDef);
    const key = encoding.key;
    const sort = standalone_mark_getSort(model);
    const interactive = standalone_interactiveFlag(model);
    const aria = standalone_getMarkPropOrConfig('aria', markDef, config);
    const postEncodingTransform = standalone_markCompiler[mark].postEncodingTransform
        ? standalone_markCompiler[mark].postEncodingTransform(model)
        : null;
    return [
        {
            name: model.getName('marks'),
            type: standalone_markCompiler[mark].vgMark,
            ...(clip ? { clip } : {}),
            ...(style ? { style } : {}),
            ...(key ? { key: key.field } : {}),
            ...(sort ? { sort } : {}),
            ...(interactive ? interactive : {}),
            ...(aria === false ? { aria } : {}),
            from: { data: opt.fromPrefix + model.requestDataName(standalone_DataSourceType.Main) },
            encode: {
                update: standalone_markCompiler[mark].encodeEntry(model)
            },
            ...(postEncodingTransform
                ? {
                    transform: postEncodingTransform
                }
                : {})
        }
    ];
}
/**
 * If scales are bound to interval selections, we want to automatically clip
 * marks to account for panning/zooming interactions. We identify bound scales
 * by the selectionExtent property, which gets added during scale parsing.
 */
function standalone_scaleClip(model) {
    const xScale = model.getScaleComponent('x');
    const yScale = model.getScaleComponent('y');
    return xScale?.get('selectionExtent') || yScale?.get('selectionExtent') ? true : undefined;
}
/**
 * If we use a custom projection with auto-fitting to the geodata extent,
 * we need to clip to ensure the chart size doesn't explode.
 */
function standalone_projectionClip(model) {
    const projection = model.component.projection;
    return projection && !projection.isFit ? true : undefined;
}
/**
 * Only output interactive flags if we have selections defined somewhere in our model hierarchy.
 */
function standalone_interactiveFlag(model) {
    if (!model.component.selection)
        return null;
    const unitCount = standalone_util_keys(model.component.selection).length;
    let parentCount = unitCount;
    let parent = model.parent;
    while (parent && parentCount === 0) {
        parentCount = standalone_util_keys(parent.component.selection).length;
        parent = parent.parent;
    }
    return parentCount
        ? {
            interactive: unitCount > 0 || model.mark === 'geoshape' || !!model.encoding.tooltip || !!model.markDef.tooltip
        }
        : null;
}
//# sourceMappingURL=mark.js.map
;// ../../node_modules/vega-lite/build/src/compile/unit.js


























/**
 * Internal model of Vega-Lite specification for the compiler.
 */
class standalone_UnitModel extends standalone_ModelWithField {
    constructor(spec, parent, parentGivenName, parentGivenSize = {}, config) {
        super(spec, 'unit', parent, parentGivenName, config, undefined, standalone_isFrameMixins(spec) ? spec.view : undefined);
        this.specifiedScales = {};
        this.specifiedAxes = {};
        this.specifiedLegends = {};
        this.specifiedProjection = {};
        this.selection = [];
        this.children = [];
        /**
         * Corrects the data references in marks after assemble.
         */
        this.correctDataNames = (mark) => {
            // for normal data references
            if (mark.from?.data) {
                mark.from.data = this.lookupDataSource(mark.from.data);
                if ('time' in this.encoding) {
                    mark.from.data = mark.from.data + standalone_CURR;
                }
            }
            // for access to facet data
            if (mark.from?.facet?.data) {
                mark.from.facet.data = this.lookupDataSource(mark.from.facet.data);
                // TOOD(jzong) uncomment this when it's time to implement facet animation
                // if ('time' in this.encoding) {
                //   mark.from.facet.data = mark.from.facet.data + CURR;
                // }
            }
            return mark;
        };
        const markDef = standalone_isMarkDef(spec.mark) ? { ...spec.mark } : { type: spec.mark };
        const mark = markDef.type;
        // Need to init filled before other mark properties because encoding depends on filled but other mark properties depend on types inside encoding
        if (markDef.filled === undefined) {
            markDef.filled = standalone_defaultFilled(markDef, config, {
                graticule: spec.data && standalone_isGraticuleGenerator(spec.data)
            });
        }
        const encoding = (this.encoding = standalone_initEncoding(spec.encoding || {}, mark, markDef.filled, config));
        this.markDef = standalone_initMarkdef(markDef, encoding, config);
        this.size = standalone_initLayoutSize({
            encoding,
            size: standalone_isFrameMixins(spec)
                ? {
                    ...parentGivenSize,
                    ...(spec.width ? { width: spec.width } : {}),
                    ...(spec.height ? { height: spec.height } : {})
                }
                : parentGivenSize
        });
        // calculate stack properties
        this.stack = standalone_stack(this.markDef, encoding);
        this.specifiedScales = this.initScales(mark, encoding);
        this.specifiedAxes = this.initAxes(encoding);
        this.specifiedLegends = this.initLegends(encoding);
        this.specifiedProjection = spec.projection;
        // Selections will be initialized upon parse.
        this.selection = (spec.params ?? []).filter(p => standalone_isSelectionParameter(p));
    }
    get hasProjection() {
        const { encoding } = this;
        const isGeoShapeMark = this.mark === standalone_GEOSHAPE;
        const hasGeoPosition = encoding && standalone_GEOPOSITION_CHANNELS.some(channel => standalone_isFieldOrDatumDef(encoding[channel]));
        return isGeoShapeMark || hasGeoPosition;
    }
    /**
     * Return specified Vega-Lite scale domain for a particular channel
     * @param channel
     */
    scaleDomain(channel) {
        const scale = this.specifiedScales[channel];
        return scale ? scale.domain : undefined;
    }
    axis(channel) {
        return this.specifiedAxes[channel];
    }
    legend(channel) {
        return this.specifiedLegends[channel];
    }
    initScales(mark, encoding) {
        return standalone_SCALE_CHANNELS.reduce((scales, channel) => {
            const fieldOrDatumDef = standalone_getFieldOrDatumDef(encoding[channel]);
            if (fieldOrDatumDef) {
                scales[channel] = this.initScale(fieldOrDatumDef.scale ?? {});
            }
            return scales;
        }, {});
    }
    initScale(scale) {
        const { domain, range } = scale;
        // TODO: we could simplify this function if we had a recursive replace function
        const scaleInternal = standalone_replaceExprRef(scale);
        if (standalone_vega_util_module_isArray(domain)) {
            scaleInternal.domain = domain.map(standalone_signalRefOrValue);
        }
        if (standalone_vega_util_module_isArray(range)) {
            scaleInternal.range = range.map(standalone_signalRefOrValue);
        }
        return scaleInternal;
    }
    initAxes(encoding) {
        return standalone_POSITION_SCALE_CHANNELS.reduce((_axis, channel) => {
            // Position Axis
            // TODO: handle ConditionFieldDef
            const channelDef = encoding[channel];
            if (standalone_isFieldOrDatumDef(channelDef) ||
                (channel === standalone_channel_X && standalone_isFieldOrDatumDef(encoding.x2)) ||
                (channel === standalone_channel_Y && standalone_isFieldOrDatumDef(encoding.y2))) {
                const axisSpec = standalone_isFieldOrDatumDef(channelDef) ? channelDef.axis : undefined;
                _axis[channel] = axisSpec
                    ? this.initAxis({ ...axisSpec }) // convert truthy value to object
                    : axisSpec;
            }
            return _axis;
        }, {});
    }
    initAxis(axis) {
        const props = standalone_util_keys(axis);
        const axisInternal = {};
        for (const prop of props) {
            const val = axis[prop];
            axisInternal[prop] = standalone_isConditionalAxisValue(val)
                ? standalone_signalOrValueRefWithCondition(val)
                : standalone_signalRefOrValue(val);
        }
        return axisInternal;
    }
    initLegends(encoding) {
        return standalone_NONPOSITION_SCALE_CHANNELS.reduce((_legend, channel) => {
            const fieldOrDatumDef = standalone_getFieldOrDatumDef(encoding[channel]);
            if (fieldOrDatumDef && standalone_supportLegend(channel)) {
                const legend = fieldOrDatumDef.legend;
                _legend[channel] = legend
                    ? standalone_replaceExprRef(legend) // convert truthy value to object
                    : legend;
            }
            return _legend;
        }, {});
    }
    parseData() {
        this.component.data = standalone_parse_parseData(this);
    }
    parseLayoutSize() {
        standalone_parseUnitLayoutSize(this);
    }
    parseSelections() {
        this.component.selection = standalone_parseUnitSelection(this, this.selection);
    }
    parseMarkGroup() {
        this.component.mark = standalone_parseMarkGroups(this);
    }
    parseAxesAndHeaders() {
        this.component.axes = standalone_parseUnitAxes(this);
    }
    assembleSelectionTopLevelSignals(signals) {
        return standalone_assembleTopLevelSignals(this, signals);
    }
    assembleSignals() {
        return [...standalone_assembleAxisSignals(this), ...standalone_assembleUnitSelectionSignals(this, [])];
    }
    assembleSelectionData(data) {
        return standalone_assembleUnitSelectionData(this, data);
    }
    assembleLayout() {
        return null;
    }
    assembleLayoutSignals() {
        return standalone_assembleLayoutSignals(this);
    }
    assembleMarks() {
        let marks = this.component.mark ?? [];
        // If this unit is part of a layer, selections should augment
        // all in concert rather than each unit individually. This
        // ensures correct interleaving of clipping and brushed marks.
        if (!this.parent || !standalone_isLayerModel(this.parent)) {
            marks = standalone_assembleUnitSelectionMarks(this, marks);
        }
        return marks.map(this.correctDataNames);
    }
    assembleGroupStyle() {
        const { style } = this.view || {};
        if (style !== undefined) {
            return style;
        }
        if (this.encoding.x || this.encoding.y) {
            return 'cell';
        }
        else {
            return 'view';
        }
    }
    getMapping() {
        return this.encoding;
    }
    get mark() {
        return this.markDef.type;
    }
    channelHasField(channel) {
        return standalone_channelHasField(this.encoding, channel);
    }
    fieldDef(channel) {
        const channelDef = this.encoding[channel];
        return standalone_getFieldDef(channelDef);
    }
    typedFieldDef(channel) {
        const fieldDef = this.fieldDef(channel);
        if (standalone_isTypedFieldDef(fieldDef)) {
            return fieldDef;
        }
        return null;
    }
}
//# sourceMappingURL=unit.js.map
;// ../../node_modules/vega-lite/build/src/compile/layer.js















class standalone_LayerModel extends standalone_Model {
    constructor(spec, parent, parentGivenName, parentGivenSize, config) {
        super(spec, 'layer', parent, parentGivenName, config, spec.resolve, spec.view);
        const layoutSize = {
            ...parentGivenSize,
            ...(spec.width ? { width: spec.width } : {}),
            ...(spec.height ? { height: spec.height } : {})
        };
        this.children = spec.layer.map((layer, i) => {
            if (standalone_isLayerSpec(layer)) {
                return new standalone_LayerModel(layer, this, this.getName(`layer_${i}`), layoutSize, config);
            }
            else if (standalone_isUnitSpec(layer)) {
                return new standalone_UnitModel(layer, this, this.getName(`layer_${i}`), layoutSize, config);
            }
            throw new Error(standalone_invalidSpec(layer));
        });
    }
    parseData() {
        this.component.data = standalone_parse_parseData(this);
        for (const child of this.children) {
            child.parseData();
        }
    }
    parseLayoutSize() {
        standalone_parseLayerLayoutSize(this);
    }
    parseSelections() {
        // Merge selections up the hierarchy so that they may be referenced
        // across unit specs. Persist their definitions within each child
        // to assemble signals which remain within output Vega unit groups.
        this.component.selection = {};
        for (const child of this.children) {
            child.parseSelections();
            for (const key of standalone_util_keys(child.component.selection)) {
                this.component.selection[key] = child.component.selection[key];
            }
        }
        if (Object.values(this.component.selection).some(selCmpt => standalone_isTimerSelection(selCmpt))) {
            standalone_log_error(standalone_MULTI_VIEW_ANIMATION_UNSUPPORTED);
        }
    }
    parseMarkGroup() {
        for (const child of this.children) {
            child.parseMarkGroup();
        }
    }
    parseAxesAndHeaders() {
        standalone_parseLayerAxes(this);
    }
    assembleSelectionTopLevelSignals(signals) {
        return this.children.reduce((sg, child) => child.assembleSelectionTopLevelSignals(sg), signals);
    }
    // TODO: Support same named selections across children.
    assembleSignals() {
        return this.children.reduce((signals, child) => {
            return signals.concat(child.assembleSignals());
        }, standalone_assembleAxisSignals(this));
    }
    assembleLayoutSignals() {
        return this.children.reduce((signals, child) => {
            return signals.concat(child.assembleLayoutSignals());
        }, standalone_assembleLayoutSignals(this));
    }
    assembleSelectionData(data) {
        return this.children.reduce((db, child) => child.assembleSelectionData(db), data);
    }
    assembleGroupStyle() {
        const uniqueStyles = new Set();
        for (const child of this.children) {
            for (const style of standalone_array(child.assembleGroupStyle())) {
                uniqueStyles.add(style);
            }
        }
        const styles = Array.from(uniqueStyles);
        return styles.length > 1 ? styles : styles.length === 1 ? styles[0] : undefined;
    }
    assembleTitle() {
        let title = super.assembleTitle();
        if (title) {
            return title;
        }
        // If title does not provide layer, look into children
        for (const child of this.children) {
            title = child.assembleTitle();
            if (title) {
                return title;
            }
        }
        return undefined;
    }
    assembleLayout() {
        return null;
    }
    assembleMarks() {
        return standalone_assembleLayerSelectionMarks(this, this.children.flatMap(child => {
            return child.assembleMarks();
        }));
    }
    assembleLegends() {
        return this.children.reduce((legends, child) => {
            return legends.concat(child.assembleLegends());
        }, standalone_assembleLegends(this));
    }
}
//# sourceMappingURL=layer.js.map
;// ../../node_modules/vega-lite/build/src/compile/buildmodel.js






function standalone_buildModel(spec, parent, parentGivenName, unitSize, config) {
    if (standalone_isFacetSpec(spec)) {
        return new standalone_FacetModel(spec, parent, parentGivenName, config);
    }
    else if (standalone_isLayerSpec(spec)) {
        return new standalone_LayerModel(spec, parent, parentGivenName, unitSize, config);
    }
    else if (standalone_isUnitSpec(spec)) {
        return new standalone_UnitModel(spec, parent, parentGivenName, unitSize, config);
    }
    else if (standalone_isAnyConcatSpec(spec)) {
        return new standalone_ConcatModel(spec, parent, parentGivenName, config);
    }
    throw new Error(standalone_invalidSpec(spec));
}
//# sourceMappingURL=buildmodel.js.map
;// ../../node_modules/vega-lite/build/src/compile/compile.js












/**
 * Vega-Lite's main function, for compiling Vega-Lite spec into Vega spec.
 *
 * At a high-level, we make the following transformations in different phases:
 *
 * Input spec
 *     |
 *     |  (Normalization)
 *     v
 * Normalized Spec (Row/Column channels in single-view specs becomes faceted specs, composite marks becomes layered specs.)
 *     |
 *     |  (Build Model)
 *     v
 * A model tree of the spec
 *     |
 *     |  (Parse)
 *     v
 * A model tree with parsed components (intermediate structure of visualization primitives in a format that can be easily merged)
 *     |
 *     | (Optimize)
 *     v
 * A model tree with parsed components with the data component optimized
 *     |
 *     | (Assemble)
 *     v
 * Vega spec
 *
 * @param inputSpec The Vega-Lite specification.
 * @param opt       Optional arguments passed to the Vega-Lite compiler.
 * @returns         An object containing the compiled Vega spec and normalized Vega-Lite spec.
 */
function standalone_compile(inputSpec, opt = {}) {
    // 0. Augment opt with default opts
    if (opt.logger) {
        // set the singleton logger to the provided logger
        standalone_log_set(opt.logger);
    }
    if (opt.fieldTitle) {
        // set the singleton field title formatter
        standalone_setTitleFormatter(opt.fieldTitle);
    }
    try {
        // 1. Initialize config by deep merging default config with the config provided via option and the input spec.
        const config = standalone_initConfig(standalone_mergeConfig(opt.config, inputSpec.config));
        // 2. Normalize: Convert input spec -> normalized spec
        // - Decompose all extended unit specs into composition of unit spec. For example, a box plot get expanded into multiple layers of bars, ticks, and rules. The shorthand row/column channel is also expanded to a facet spec.
        // - Normalize autosize and width or height spec
        const spec = standalone_normalize_normalize(inputSpec, config);
        // 3. Build Model: normalized spec -> Model (a tree structure)
        // This phases instantiates the models with default config by doing a top-down traversal. This allows us to pass properties that child models derive from their parents via their constructors.
        // See the abstract `Model` class and its children (UnitModel, LayerModel, FacetModel, ConcatModel) for different types of models.
        const model = standalone_buildModel(spec, null, '', undefined, config);
        // 4 Parse: Model --> Model with components
        // Note that components = intermediate representations that are equivalent to Vega specs.
        // We need these intermediate representation because we need to merge many visualization "components" like projections, scales, axes, and legends.
        // We will later convert these components into actual Vega specs in the assemble phase.
        // In this phase, we do a bottom-up traversal over the whole tree to
        // parse for each type of components once (e.g., data, layout, mark, scale).
        // By doing bottom-up traversal, we start parsing components of unit specs and
        // then merge child components of parent composite specs.
        //
        // Please see inside model.parse() for order of different components parsed.
        model.parse();
        // drawDataflow(model.component.data.sources);
        // 5. Optimize the dataflow. This will modify the data component of the model.
        standalone_optimizeDataflow(model.component.data, model);
        // drawDataflow(model.component.data.sources);
        // 6. Assemble: convert model components --> Vega Spec.
        const vgSpec = standalone_assembleTopLevelModel(model, standalone_getTopLevelProperties(inputSpec, spec.autosize, config, model), inputSpec.datasets, inputSpec.usermeta);
        return {
            spec: vgSpec,
            normalized: spec
        };
    }
    finally {
        // Reset the singleton logger if a logger is provided
        if (opt.logger) {
            standalone_log_reset();
        }
        // Reset the singleton field title formatter if provided
        if (opt.fieldTitle) {
            standalone_resetTitleFormatter();
        }
    }
}
function standalone_getTopLevelProperties(inputSpec, autosize, config, model) {
    const width = model.component.layoutSize.get('width');
    const height = model.component.layoutSize.get('height');
    if (autosize === undefined) {
        autosize = { type: 'pad' };
        if (model.hasAxisOrientSignalRef()) {
            autosize.resize = true;
        }
    }
    else if (standalone_vega_util_module_isString(autosize)) {
        autosize = { type: autosize };
    }
    if (width && height && standalone_isFitType(autosize.type)) {
        if (width === 'step' && height === 'step') {
            standalone_log_warn(standalone_droppingFit());
            autosize.type = 'pad';
        }
        else if (width === 'step' || height === 'step') {
            // effectively XOR, because else if
            // get step dimension
            const sizeType = width === 'step' ? 'width' : 'height';
            // log that we're dropping fit for respective channel
            standalone_log_warn(standalone_droppingFit(standalone_getPositionScaleChannel(sizeType)));
            // setting type to inverse fit (so if we dropped fit-x, type is now fit-y)
            const inverseSizeType = sizeType === 'width' ? 'height' : 'width';
            autosize.type = standalone_getFitType(inverseSizeType);
        }
    }
    return {
        ...(standalone_util_keys(autosize).length === 1 && autosize.type
            ? autosize.type === 'pad'
                ? {}
                : { autosize: autosize.type }
            : { autosize }),
        ...standalone_extractTopLevelProperties(config, false),
        ...standalone_extractTopLevelProperties(inputSpec, true)
    };
}
/*
 * Assemble the top-level model to a Vega spec.
 *
 * Note: this couldn't be `model.assemble()` since the top-level model
 * needs some special treatment to generate top-level properties.
 */
function standalone_assembleTopLevelModel(model, topLevelProperties, datasets = {}, usermeta) {
    // Config with Vega-Lite only config removed.
    const vgConfig = model.config ? standalone_stripAndRedirectConfig(model.config) : undefined;
    const rootData = standalone_assembleRootData(model.component.data, datasets);
    const data = model.assembleSelectionData(rootData);
    const projections = model.assembleProjections();
    const title = model.assembleTitle();
    const style = model.assembleGroupStyle();
    const encodeEntry = model.assembleGroupEncodeEntry(true);
    let layoutSignals = model.assembleLayoutSignals();
    // move width and height signals with values to top level
    layoutSignals = layoutSignals.filter(signal => {
        if ((signal.name === 'width' || signal.name === 'height') && signal.value !== undefined) {
            topLevelProperties[signal.name] = +signal.value;
            return false;
        }
        return true;
    });
    const { params, ...otherTopLevelProps } = topLevelProperties;
    return {
        $schema: 'https://vega.github.io/schema/vega/v5.json',
        ...(model.description ? { description: model.description } : {}),
        ...otherTopLevelProps,
        ...(title ? { title } : {}),
        ...(style ? { style } : {}),
        ...(encodeEntry ? { encode: { update: encodeEntry } } : {}),
        data,
        ...(projections.length > 0 ? { projections } : {}),
        ...model.assembleGroup([
            ...layoutSignals,
            ...model.assembleSelectionTopLevelSignals([]),
            ...standalone_assembleParameterSignals(params)
        ]),
        ...(vgConfig ? { config: vgConfig } : {}),
        ...(usermeta ? { usermeta } : {})
    };
}
//# sourceMappingURL=compile.js.map
;// ../../node_modules/vega-lite/build/src/index.js

const standalone_src_version = standalone_package_namespaceObject.rE;



//# sourceMappingURL=index.js.map
;// ../../node_modules/vega-schema-url-parser/dist/parser.module.js
function standalone_e(e){const[n,r]=/schema\/([\w-]+)\/([\w\.\-]+)\.json$/g.exec(e).slice(1,3);return{library:n,version:r}}/* harmony default export */ const standalone_parser_module = (standalone_e);
//# sourceMappingURL=parser.module.js.map

;// ../../node_modules/vega-themes/build/vega-themes.module.js
var standalone_vega_themes_module_name = "vega-themes";
var standalone_version$1 = "2.15.0";
var standalone_vega_themes_module_description = "Themes for stylized Vega and Vega-Lite visualizations.";
var standalone_vega_themes_module_keywords = ["vega", "vega-lite", "themes", "style"];
var standalone_license = "BSD-3-Clause";
var standalone_author = {
  name: "UW Interactive Data Lab",
  url: "https://idl.cs.washington.edu"
};
var standalone_contributors = [{
  name: "Emily Gu",
  url: "https://github.com/emilygu"
}, {
  name: "Arvind Satyanarayan",
  url: "http://arvindsatya.com"
}, {
  name: "Jeffrey Heer",
  url: "https://idl.cs.washington.edu"
}, {
  name: "Dominik Moritz",
  url: "https://www.domoritz.de"
}];
var standalone_vega_themes_module_main = "build/vega-themes.js";
var standalone_vega_themes_module_module = "build/vega-themes.module.js";
var standalone_unpkg = "build/vega-themes.min.js";
var standalone_jsdelivr = "build/vega-themes.min.js";
var standalone_types = "build/vega-themes.module.d.ts";
var standalone_repository = {
  type: "git",
  url: "https://github.com/vega/vega-themes.git"
};
var standalone_files = ["src", "build"];
var standalone_scripts = {
  prebuild: "yarn clean",
  build: "rollup -c",
  clean: "rimraf build && rimraf examples/build",
  "copy:data": "rsync -r node_modules/vega-datasets/data/* examples/data",
  "copy:build": "rsync -r build/* examples/build",
  "deploy:gh": "yarn build && mkdir -p examples/build && rsync -r build/* examples/build && gh-pages -d examples",
  preversion: "yarn lint",
  serve: "browser-sync start -s -f build examples --serveStatic examples",
  start: "yarn build && concurrently --kill-others -n Server,Rollup 'yarn serve' 'rollup -c -w'",
  format: "eslint . --fix",
  lint: "eslint .",
  release: "release-it"
};
var standalone_devDependencies = {
  "@babel/core": "^7.24.6",
  "@babel/plugin-transform-runtime": "^7.24.6",
  "@babel/preset-env": "^7.24.6",
  "@babel/preset-typescript": "^7.24.6",
  "@release-it/conventional-changelog": "^8.0.1",
  "@rollup/plugin-json": "^6.1.0",
  "@rollup/plugin-node-resolve": "^15.2.3",
  "@rollup/plugin-terser": "^0.4.4",
  "@typescript-eslint/eslint-plugin": "^7.11.0",
  "@typescript-eslint/parser": "^7.11.0",
  "browser-sync": "^3.0.2",
  concurrently: "^8.2.2",
  eslint: "^8.45.0",
  "eslint-config-prettier": "^9.1.0",
  "eslint-plugin-prettier": "^5.1.3",
  "gh-pages": "^6.1.1",
  prettier: "^3.2.5",
  "release-it": "^17.3.0",
  rollup: "^4.18.0",
  "rollup-plugin-bundle-size": "^1.0.3",
  "rollup-plugin-ts": "^3.4.5",
  typescript: "^5.4.5",
  vega: "^5.25.0",
  "vega-lite": "^5.9.3"
};
var standalone_peerDependencies = {
  vega: "*",
  "vega-lite": "*"
};
var standalone_dependencies = {};
var standalone_pkg = {
  name: standalone_vega_themes_module_name,
  version: standalone_version$1,
  description: standalone_vega_themes_module_description,
  keywords: standalone_vega_themes_module_keywords,
  license: standalone_license,
  author: standalone_author,
  contributors: standalone_contributors,
  main: standalone_vega_themes_module_main,
  module: standalone_vega_themes_module_module,
  unpkg: standalone_unpkg,
  jsdelivr: standalone_jsdelivr,
  types: standalone_types,
  repository: standalone_repository,
  files: standalone_files,
  scripts: standalone_scripts,
  devDependencies: standalone_devDependencies,
  peerDependencies: standalone_peerDependencies,
  dependencies: standalone_dependencies
};

const standalone_lightColor = '#fff';
const standalone_medColor = '#888';
const standalone_darkTheme = {
  background: '#333',
  view: {
    stroke: standalone_medColor
  },
  title: {
    color: standalone_lightColor,
    subtitleColor: standalone_lightColor
  },
  style: {
    'guide-label': {
      fill: standalone_lightColor
    },
    'guide-title': {
      fill: standalone_lightColor
    }
  },
  axis: {
    domainColor: standalone_lightColor,
    gridColor: standalone_medColor,
    tickColor: standalone_lightColor
  }
};

const standalone_markColor$7 = '#4572a7';
const standalone_excelTheme = {
  background: '#fff',
  arc: {
    fill: standalone_markColor$7
  },
  area: {
    fill: standalone_markColor$7
  },
  line: {
    stroke: standalone_markColor$7,
    strokeWidth: 2
  },
  path: {
    stroke: standalone_markColor$7
  },
  rect: {
    fill: standalone_markColor$7
  },
  shape: {
    stroke: standalone_markColor$7
  },
  symbol: {
    fill: standalone_markColor$7,
    strokeWidth: 1.5,
    size: 50
  },
  axis: {
    bandPosition: 0.5,
    grid: true,
    gridColor: '#000000',
    gridOpacity: 1,
    gridWidth: 0.5,
    labelPadding: 10,
    tickSize: 5,
    tickWidth: 0.5
  },
  axisBand: {
    grid: false,
    tickExtra: true
  },
  legend: {
    labelBaseline: 'middle',
    labelFontSize: 11,
    symbolSize: 50,
    symbolType: 'square'
  },
  range: {
    category: ['#4572a7', '#aa4643', '#8aa453', '#71598e', '#4598ae', '#d98445', '#94aace', '#d09393', '#b9cc98', '#a99cbc']
  }
};

const standalone_markColor$6 = '#30a2da';
const standalone_axisColor$2 = '#cbcbcb';
const standalone_guideLabelColor = '#999';
const standalone_guideTitleColor = '#333';
const standalone_backgroundColor$2 = '#f0f0f0';
const standalone_blackTitle = '#333';
const standalone_fiveThirtyEightTheme = {
  arc: {
    fill: standalone_markColor$6
  },
  area: {
    fill: standalone_markColor$6
  },
  axis: {
    domainColor: standalone_axisColor$2,
    grid: true,
    gridColor: standalone_axisColor$2,
    gridWidth: 1,
    labelColor: standalone_guideLabelColor,
    labelFontSize: 10,
    titleColor: standalone_guideTitleColor,
    tickColor: standalone_axisColor$2,
    tickSize: 10,
    titleFontSize: 14,
    titlePadding: 10,
    labelPadding: 4
  },
  axisBand: {
    grid: false
  },
  background: standalone_backgroundColor$2,
  group: {
    fill: standalone_backgroundColor$2
  },
  legend: {
    labelColor: standalone_blackTitle,
    labelFontSize: 11,
    padding: 1,
    symbolSize: 30,
    symbolType: 'square',
    titleColor: standalone_blackTitle,
    titleFontSize: 14,
    titlePadding: 10
  },
  line: {
    stroke: standalone_markColor$6,
    strokeWidth: 2
  },
  path: {
    stroke: standalone_markColor$6,
    strokeWidth: 0.5
  },
  rect: {
    fill: standalone_markColor$6
  },
  range: {
    category: ['#30a2da', '#fc4f30', '#e5ae38', '#6d904f', '#8b8b8b', '#b96db8', '#ff9e27', '#56cc60', '#52d2ca', '#52689e', '#545454', '#9fe4f8'],
    diverging: ['#cc0020', '#e77866', '#f6e7e1', '#d6e8ed', '#91bfd9', '#1d78b5'],
    heatmap: ['#d6e8ed', '#cee0e5', '#91bfd9', '#549cc6', '#1d78b5']
  },
  point: {
    filled: true,
    shape: 'circle'
  },
  shape: {
    stroke: standalone_markColor$6
  },
  bar: {
    binSpacing: 2,
    fill: standalone_markColor$6,
    stroke: null
  },
  title: {
    anchor: 'start',
    fontSize: 24,
    fontWeight: 600,
    offset: 20
  }
};

const standalone_markColor$5 = '#000';
const standalone_ggplot2Theme = {
  group: {
    fill: '#e5e5e5'
  },
  arc: {
    fill: standalone_markColor$5
  },
  area: {
    fill: standalone_markColor$5
  },
  line: {
    stroke: standalone_markColor$5
  },
  path: {
    stroke: standalone_markColor$5
  },
  rect: {
    fill: standalone_markColor$5
  },
  shape: {
    stroke: standalone_markColor$5
  },
  symbol: {
    fill: standalone_markColor$5,
    size: 40
  },
  axis: {
    domain: false,
    grid: true,
    gridColor: '#FFFFFF',
    gridOpacity: 1,
    labelColor: '#7F7F7F',
    labelPadding: 4,
    tickColor: '#7F7F7F',
    tickSize: 5.67,
    titleFontSize: 16,
    titleFontWeight: 'normal'
  },
  legend: {
    labelBaseline: 'middle',
    labelFontSize: 11,
    symbolSize: 40
  },
  range: {
    category: ['#000000', '#7F7F7F', '#1A1A1A', '#999999', '#333333', '#B0B0B0', '#4D4D4D', '#C9C9C9', '#666666', '#DCDCDC']
  }
};

const standalone_headlineFontSize = 22;
const standalone_headlineFontWeight = 'normal';
const standalone_labelFont$1 = 'Benton Gothic, sans-serif';
const standalone_labelFontSize = 11.5;
const standalone_labelFontWeight = 'normal';
const standalone_markColor$4 = '#82c6df';
// const markHighlight = '#006d8f';
// const markDemocrat = '#5789b8';
// const markRepublican = '#d94f54';
const standalone_titleFont = 'Benton Gothic Bold, sans-serif';
const standalone_titleFontWeight = 'normal';
const standalone_titleFontSize$1 = 13;
const standalone_colorSchemes$1 = {
  'category-6': ['#ec8431', '#829eb1', '#c89d29', '#3580b1', '#adc839', '#ab7fb4'],
  'fire-7': ['#fbf2c7', '#f9e39c', '#f8d36e', '#f4bb6a', '#e68a4f', '#d15a40', '#ab4232'],
  'fireandice-6': ['#e68a4f', '#f4bb6a', '#f9e39c', '#dadfe2', '#a6b7c6', '#849eae'],
  'ice-7': ['#edefee', '#dadfe2', '#c4ccd2', '#a6b7c6', '#849eae', '#607785', '#47525d']
};
const standalone_latimesTheme = {
  background: '#ffffff',
  title: {
    anchor: 'start',
    color: '#000000',
    font: standalone_titleFont,
    fontSize: standalone_headlineFontSize,
    fontWeight: standalone_headlineFontWeight
  },
  arc: {
    fill: standalone_markColor$4
  },
  area: {
    fill: standalone_markColor$4
  },
  line: {
    stroke: standalone_markColor$4,
    strokeWidth: 2
  },
  path: {
    stroke: standalone_markColor$4
  },
  rect: {
    fill: standalone_markColor$4
  },
  shape: {
    stroke: standalone_markColor$4
  },
  symbol: {
    fill: standalone_markColor$4,
    size: 30
  },
  axis: {
    labelFont: standalone_labelFont$1,
    labelFontSize: standalone_labelFontSize,
    labelFontWeight: standalone_labelFontWeight,
    titleFont: standalone_titleFont,
    titleFontSize: standalone_titleFontSize$1,
    titleFontWeight: standalone_titleFontWeight
  },
  axisX: {
    labelAngle: 0,
    labelPadding: 4,
    tickSize: 3
  },
  axisY: {
    labelBaseline: 'middle',
    maxExtent: 45,
    minExtent: 45,
    tickSize: 2,
    titleAlign: 'left',
    titleAngle: 0,
    titleX: -45,
    titleY: -11
  },
  legend: {
    labelFont: standalone_labelFont$1,
    labelFontSize: standalone_labelFontSize,
    symbolType: 'square',
    titleFont: standalone_titleFont,
    titleFontSize: standalone_titleFontSize$1,
    titleFontWeight: standalone_titleFontWeight
  },
  range: {
    category: standalone_colorSchemes$1['category-6'],
    diverging: standalone_colorSchemes$1['fireandice-6'],
    heatmap: standalone_colorSchemes$1['fire-7'],
    ordinal: standalone_colorSchemes$1['fire-7'],
    ramp: standalone_colorSchemes$1['fire-7']
  }
};

const standalone_markColor$3 = '#ab5787';
const standalone_axisColor$1 = '#979797';
const standalone_quartzTheme = {
  background: '#f9f9f9',
  arc: {
    fill: standalone_markColor$3
  },
  area: {
    fill: standalone_markColor$3
  },
  line: {
    stroke: standalone_markColor$3
  },
  path: {
    stroke: standalone_markColor$3
  },
  rect: {
    fill: standalone_markColor$3
  },
  shape: {
    stroke: standalone_markColor$3
  },
  symbol: {
    fill: standalone_markColor$3,
    size: 30
  },
  axis: {
    domainColor: standalone_axisColor$1,
    domainWidth: 0.5,
    gridWidth: 0.2,
    labelColor: standalone_axisColor$1,
    tickColor: standalone_axisColor$1,
    tickWidth: 0.2,
    titleColor: standalone_axisColor$1
  },
  axisBand: {
    grid: false
  },
  axisX: {
    grid: true,
    tickSize: 10
  },
  axisY: {
    domain: false,
    grid: true,
    tickSize: 0
  },
  legend: {
    labelFontSize: 11,
    padding: 1,
    symbolSize: 30,
    symbolType: 'square'
  },
  range: {
    category: ['#ab5787', '#51b2e5', '#703c5c', '#168dd9', '#d190b6', '#00609f', '#d365ba', '#154866', '#666666', '#c4c4c4']
  }
};

const standalone_markColor$2 = '#3e5c69';
const standalone_voxTheme = {
  background: '#fff',
  arc: {
    fill: standalone_markColor$2
  },
  area: {
    fill: standalone_markColor$2
  },
  line: {
    stroke: standalone_markColor$2
  },
  path: {
    stroke: standalone_markColor$2
  },
  rect: {
    fill: standalone_markColor$2
  },
  shape: {
    stroke: standalone_markColor$2
  },
  symbol: {
    fill: standalone_markColor$2
  },
  axis: {
    domainWidth: 0.5,
    grid: true,
    labelPadding: 2,
    tickSize: 5,
    tickWidth: 0.5,
    titleFontWeight: 'normal'
  },
  axisBand: {
    grid: false
  },
  axisX: {
    gridWidth: 0.2
  },
  axisY: {
    gridDash: [3],
    gridWidth: 0.4
  },
  legend: {
    labelFontSize: 11,
    padding: 1,
    symbolType: 'square'
  },
  range: {
    category: ['#3e5c69', '#6793a6', '#182429', '#0570b0', '#3690c0', '#74a9cf', '#a6bddb', '#e2ddf2']
  }
};

const standalone_markColor$1 = '#1696d2';
const standalone_axisColor = '#000000';
const standalone_backgroundColor$1 = '#FFFFFF';
const standalone_vega_themes_module_font = 'Lato';
const standalone_labelFont = 'Lato';
const standalone_sourceFont = 'Lato';
const standalone_gridColor$1 = '#DEDDDD';
const standalone_titleFontSize = 18;
const standalone_colorSchemes = {
  'main-colors': ['#1696d2', '#d2d2d2', '#000000', '#fdbf11', '#ec008b', '#55b748', '#5c5859', '#db2b27'],
  'shades-blue': ['#CFE8F3', '#A2D4EC', '#73BFE2', '#46ABDB', '#1696D2', '#12719E', '#0A4C6A', '#062635'],
  'shades-gray': ['#F5F5F5', '#ECECEC', '#E3E3E3', '#DCDBDB', '#D2D2D2', '#9D9D9D', '#696969', '#353535'],
  'shades-yellow': ['#FFF2CF', '#FCE39E', '#FDD870', '#FCCB41', '#FDBF11', '#E88E2D', '#CA5800', '#843215'],
  'shades-magenta': ['#F5CBDF', '#EB99C2', '#E46AA7', '#E54096', '#EC008B', '#AF1F6B', '#761548', '#351123'],
  'shades-green': ['#DCEDD9', '#BCDEB4', '#98CF90', '#78C26D', '#55B748', '#408941', '#2C5C2D', '#1A2E19'],
  'shades-black': ['#D5D5D4', '#ADABAC', '#848081', '#5C5859', '#332D2F', '#262223', '#1A1717', '#0E0C0D'],
  'shades-red': ['#F8D5D4', '#F1AAA9', '#E9807D', '#E25552', '#DB2B27', '#A4201D', '#6E1614', '#370B0A'],
  'one-group': ['#1696d2', '#000000'],
  'two-groups-cat-1': ['#1696d2', '#000000'],
  'two-groups-cat-2': ['#1696d2', '#fdbf11'],
  'two-groups-cat-3': ['#1696d2', '#db2b27'],
  'two-groups-seq': ['#a2d4ec', '#1696d2'],
  'three-groups-cat': ['#1696d2', '#fdbf11', '#000000'],
  'three-groups-seq': ['#a2d4ec', '#1696d2', '#0a4c6a'],
  'four-groups-cat-1': ['#000000', '#d2d2d2', '#fdbf11', '#1696d2'],
  'four-groups-cat-2': ['#1696d2', '#ec0008b', '#fdbf11', '#5c5859'],
  'four-groups-seq': ['#cfe8f3', '#73bf42', '#1696d2', '#0a4c6a'],
  'five-groups-cat-1': ['#1696d2', '#fdbf11', '#d2d2d2', '#ec008b', '#000000'],
  'five-groups-cat-2': ['#1696d2', '#0a4c6a', '#d2d2d2', '#fdbf11', '#332d2f'],
  'five-groups-seq': ['#cfe8f3', '#73bf42', '#1696d2', '#0a4c6a', '#000000'],
  'six-groups-cat-1': ['#1696d2', '#ec008b', '#fdbf11', '#000000', '#d2d2d2', '#55b748'],
  'six-groups-cat-2': ['#1696d2', '#d2d2d2', '#ec008b', '#fdbf11', '#332d2f', '#0a4c6a'],
  'six-groups-seq': ['#cfe8f3', '#a2d4ec', '#73bfe2', '#46abdb', '#1696d2', '#12719e'],
  'diverging-colors': ['#ca5800', '#fdbf11', '#fdd870', '#fff2cf', '#cfe8f3', '#73bfe2', '#1696d2', '#0a4c6a']
};
const standalone_urbanInstituteTheme = {
  background: standalone_backgroundColor$1,
  title: {
    anchor: 'start',
    fontSize: standalone_titleFontSize,
    font: standalone_vega_themes_module_font
  },
  axisX: {
    domain: true,
    domainColor: standalone_axisColor,
    domainWidth: 1,
    grid: false,
    labelFontSize: 12,
    labelFont: standalone_labelFont,
    labelAngle: 0,
    tickColor: standalone_axisColor,
    tickSize: 5,
    titleFontSize: 12,
    titlePadding: 10,
    titleFont: standalone_vega_themes_module_font
  },
  axisY: {
    domain: false,
    domainWidth: 1,
    grid: true,
    gridColor: standalone_gridColor$1,
    gridWidth: 1,
    labelFontSize: 12,
    labelFont: standalone_labelFont,
    labelPadding: 8,
    ticks: false,
    titleFontSize: 12,
    titlePadding: 10,
    titleFont: standalone_vega_themes_module_font,
    titleAngle: 0,
    titleY: -10,
    titleX: 18
  },
  legend: {
    labelFontSize: 12,
    labelFont: standalone_labelFont,
    symbolSize: 100,
    titleFontSize: 12,
    titlePadding: 10,
    titleFont: standalone_vega_themes_module_font,
    orient: 'right',
    offset: 10
  },
  view: {
    stroke: 'transparent'
  },
  range: {
    category: standalone_colorSchemes['six-groups-cat-1'],
    diverging: standalone_colorSchemes['diverging-colors'],
    heatmap: standalone_colorSchemes['diverging-colors'],
    ordinal: standalone_colorSchemes['six-groups-seq'],
    ramp: standalone_colorSchemes['shades-blue']
  },
  area: {
    fill: standalone_markColor$1
  },
  rect: {
    fill: standalone_markColor$1
  },
  line: {
    color: standalone_markColor$1,
    stroke: standalone_markColor$1,
    strokeWidth: 5
  },
  trail: {
    color: standalone_markColor$1,
    stroke: standalone_markColor$1,
    strokeWidth: 0,
    size: 1
  },
  path: {
    stroke: standalone_markColor$1,
    strokeWidth: 0.5
  },
  point: {
    filled: true
  },
  text: {
    font: standalone_sourceFont,
    color: standalone_markColor$1,
    fontSize: 11,
    align: 'center',
    fontWeight: 400,
    size: 11
  },
  style: {
    bar: {
      fill: standalone_markColor$1,
      stroke: null
    }
  },
  arc: {
    fill: standalone_markColor$1
  },
  shape: {
    stroke: standalone_markColor$1
  },
  symbol: {
    fill: standalone_markColor$1,
    size: 30
  }
};

/**
 * Copyright 2020 Google LLC.
 *
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file or at
 * https://developers.google.com/open-source/licenses/bsd
 */

const standalone_markColor = '#3366CC';
const standalone_gridColor = '#ccc';
const standalone_defaultFont$1 = 'Arial, sans-serif';
const standalone_googlechartsTheme = {
  arc: {
    fill: standalone_markColor
  },
  area: {
    fill: standalone_markColor
  },
  path: {
    stroke: standalone_markColor
  },
  rect: {
    fill: standalone_markColor
  },
  shape: {
    stroke: standalone_markColor
  },
  symbol: {
    stroke: standalone_markColor
  },
  circle: {
    fill: standalone_markColor
  },
  background: '#fff',
  padding: {
    top: 10,
    right: 10,
    bottom: 10,
    left: 10
  },
  style: {
    'guide-label': {
      font: standalone_defaultFont$1,
      fontSize: 12
    },
    'guide-title': {
      font: standalone_defaultFont$1,
      fontSize: 12
    },
    'group-title': {
      font: standalone_defaultFont$1,
      fontSize: 12
    }
  },
  title: {
    font: standalone_defaultFont$1,
    fontSize: 14,
    fontWeight: 'bold',
    dy: -3,
    anchor: 'start'
  },
  axis: {
    gridColor: standalone_gridColor,
    tickColor: standalone_gridColor,
    domain: false,
    grid: true
  },
  range: {
    category: ['#4285F4', '#DB4437', '#F4B400', '#0F9D58', '#AB47BC', '#00ACC1', '#FF7043', '#9E9D24', '#5C6BC0', '#F06292', '#00796B', '#C2185B'],
    heatmap: ['#c6dafc', '#5e97f6', '#2a56c6']
  }
};

const standalone_ptToPx = value => value * (1 / 3 + 1);
const standalone_fontSmallPx = standalone_ptToPx(9);
const standalone_legendFontPx = standalone_ptToPx(10);
const standalone_fontLargePx = standalone_ptToPx(12);
const standalone_fontStandard = 'Segoe UI';
const standalone_fontTitle = 'wf_standard-font, helvetica, arial, sans-serif';
const standalone_firstLevelElementColor = '#252423';
const standalone_secondLevelElementColor = '#605E5C';
const standalone_backgroundColor = 'transparent';
const standalone_backgroundSecondaryColor = '#C8C6C4';
const standalone_paletteColor1 = '#118DFF';
const standalone_paletteColor2 = '#12239E';
const standalone_paletteColor3 = '#E66C37';
const standalone_paletteColor4 = '#6B007B';
const standalone_paletteColor5 = '#E044A7';
const standalone_paletteColor6 = '#744EC2';
const standalone_paletteColor7 = '#D9B300';
const standalone_paletteColor8 = '#D64550';
const standalone_divergentColorMax = standalone_paletteColor1;
const standalone_divergentColorMin = '#DEEFFF';
const standalone_divergentPalette = [standalone_divergentColorMin, standalone_divergentColorMax];
const standalone_ordinalPalette = [standalone_divergentColorMin, '#c7e4ff', '#b0d9ff', '#9aceff', '#83c3ff', '#6cb9ff', '#55aeff', '#3fa3ff', '#2898ff', standalone_divergentColorMax];
const standalone_powerbiTheme = {
  view: {
    stroke: standalone_backgroundColor
  },
  background: standalone_backgroundColor,
  font: standalone_fontStandard,
  header: {
    titleFont: standalone_fontTitle,
    titleFontSize: standalone_fontLargePx,
    titleColor: standalone_firstLevelElementColor,
    labelFont: standalone_fontStandard,
    labelFontSize: standalone_legendFontPx,
    labelColor: standalone_secondLevelElementColor
  },
  axis: {
    ticks: false,
    grid: false,
    domain: false,
    labelColor: standalone_secondLevelElementColor,
    labelFontSize: standalone_fontSmallPx,
    titleFont: standalone_fontTitle,
    titleColor: standalone_firstLevelElementColor,
    titleFontSize: standalone_fontLargePx,
    titleFontWeight: 'normal'
  },
  axisQuantitative: {
    tickCount: 3,
    grid: true,
    gridColor: standalone_backgroundSecondaryColor,
    gridDash: [1, 5],
    labelFlush: false
  },
  axisBand: {
    tickExtra: true
  },
  axisX: {
    labelPadding: 5
  },
  axisY: {
    labelPadding: 10
  },
  bar: {
    fill: standalone_paletteColor1
  },
  line: {
    stroke: standalone_paletteColor1,
    strokeWidth: 3,
    strokeCap: 'round',
    strokeJoin: 'round'
  },
  text: {
    font: standalone_fontStandard,
    fontSize: standalone_fontSmallPx,
    fill: standalone_secondLevelElementColor
  },
  arc: {
    fill: standalone_paletteColor1
  },
  area: {
    fill: standalone_paletteColor1,
    line: true,
    opacity: 0.6
  },
  path: {
    stroke: standalone_paletteColor1
  },
  rect: {
    fill: standalone_paletteColor1
  },
  point: {
    fill: standalone_paletteColor1,
    filled: true,
    size: 75
  },
  shape: {
    stroke: standalone_paletteColor1
  },
  symbol: {
    fill: standalone_paletteColor1,
    strokeWidth: 1.5,
    size: 50
  },
  legend: {
    titleFont: standalone_fontStandard,
    titleFontWeight: 'bold',
    titleColor: standalone_secondLevelElementColor,
    labelFont: standalone_fontStandard,
    labelFontSize: standalone_legendFontPx,
    labelColor: standalone_secondLevelElementColor,
    symbolType: 'circle',
    symbolSize: 75
  },
  range: {
    category: [standalone_paletteColor1, standalone_paletteColor2, standalone_paletteColor3, standalone_paletteColor4, standalone_paletteColor5, standalone_paletteColor6, standalone_paletteColor7, standalone_paletteColor8],
    diverging: standalone_divergentPalette,
    heatmap: standalone_divergentPalette,
    ordinal: standalone_ordinalPalette
  }
};

const standalone_defaultFont = 'IBM Plex Sans,system-ui,-apple-system,BlinkMacSystemFont,".sfnstext-regular",sans-serif';
const standalone_condensedFont = 'IBM Plex Sans Condensed, system-ui, -apple-system, BlinkMacSystemFont, ".SFNSText-Regular", sans-serif';
const standalone_fontWeight = 400;
const standalone_TOKENS = {
  textPrimary: {
    g90: '#f4f4f4',
    g100: '#f4f4f4',
    white: '#161616',
    g10: '#161616'
  },
  textSecondary: {
    g90: '#c6c6c6',
    g100: '#c6c6c6',
    white: '#525252',
    g10: '#525252'
  },
  // layer
  layerAccent01: {
    white: '#e0e0e0',
    g10: '#e0e0e0',
    g90: '#525252',
    g100: '#393939'
  },
  // grid
  gridBg: {
    white: '#ffffff',
    g10: '#ffffff',
    g90: '#161616',
    g100: '#161616'
  }
};
const standalone_darkCategories = ['#8a3ffc', '#33b1ff', '#007d79', '#ff7eb6', '#fa4d56', '#fff1f1', '#6fdc8c', '#4589ff', '#d12771', '#d2a106', '#08bdba', '#bae6ff', '#ba4e00', '#d4bbff'];
const standalone_lightCategories = ['#6929c4', '#1192e8', '#005d5d', '#9f1853', '#fa4d56', '#570408', '#198038', '#002d9c', '#ee538b', '#b28600', '#009d9a', '#012749', '#8a3800', '#a56eff'];
function standalone_genCarbonConfig({
  theme,
  background
}) {
  const type = ['white', 'g10'].includes(theme) ? 'light' : 'dark';
  const viewbg = standalone_TOKENS.gridBg[theme];
  const titleColor = standalone_TOKENS.textPrimary[theme];
  const textColor = standalone_TOKENS.textSecondary[theme];
  const category = type === 'dark' ? standalone_darkCategories : standalone_lightCategories;
  const markColor = type === 'dark' ? '#d4bbff' : '#6929c4';
  return {
    background,
    arc: {
      fill: markColor
    },
    area: {
      fill: markColor
    },
    path: {
      stroke: markColor
    },
    rect: {
      fill: markColor
    },
    shape: {
      stroke: markColor
    },
    symbol: {
      stroke: markColor
    },
    circle: {
      fill: markColor
    },
    view: {
      fill: viewbg,
      stroke: viewbg
    },
    group: {
      fill: viewbg
    },
    title: {
      color: titleColor,
      anchor: 'start',
      dy: -15,
      fontSize: 16,
      font: standalone_defaultFont,
      fontWeight: 600
    },
    axis: {
      // Axis labels
      labelColor: textColor,
      labelFontSize: 12,
      labelFont: standalone_condensedFont,
      labelFontWeight: standalone_fontWeight,
      // Axis titles
      titleColor: titleColor,
      titleFontWeight: 600,
      titleFontSize: 12,
      // MISC
      grid: true,
      gridColor: standalone_TOKENS.layerAccent01[theme],
      labelAngle: 0
    },
    axisX: {
      titlePadding: 10
    },
    axisY: {
      titlePadding: 2.5
    },
    style: {
      'guide-label': {
        font: standalone_defaultFont,
        fill: textColor,
        fontWeight: standalone_fontWeight
      },
      'guide-title': {
        font: standalone_defaultFont,
        fill: textColor,
        fontWeight: standalone_fontWeight
      }
    },
    range: {
      category,
      diverging: ['#750e13', '#a2191f', '#da1e28', '#fa4d56', '#ff8389', '#ffb3b8', '#ffd7d9', '#fff1f1', '#e5f6ff', '#bae6ff', '#82cfff', '#33b1ff', '#1192e8', '#0072c3', '#00539a', '#003a6d'],
      heatmap: ['#f6f2ff', '#e8daff', '#d4bbff', '#be95ff', '#a56eff', '#8a3ffc', '#6929c4', '#491d8b', '#31135e', '#1c0f30']
    }
  };
}

const standalone_carbonwhite = standalone_genCarbonConfig({
  theme: 'white',
  background: '#ffffff'
});

const standalone_carbong10 = standalone_genCarbonConfig({
  theme: 'g10',
  background: '#f4f4f4'
});

const standalone_carbong90 = standalone_genCarbonConfig({
  theme: 'g90',
  background: '#262626'
});

const standalone_carbong100 = standalone_genCarbonConfig({
  theme: 'g100',
  background: '#161616'
});

const standalone_vega_themes_module_version = standalone_pkg.version;



;// ../../node_modules/vega-tooltip/build/vega-tooltip.module.js


var standalone_vega_tooltip_module_name = "vega-tooltip";
var standalone_vega_tooltip_module_version$1 = "0.35.2";
var standalone_vega_tooltip_module_description = "A tooltip plugin for Vega-Lite and Vega visualizations.";
var standalone_vega_tooltip_module_keywords = [
	"vega-lite",
	"vega",
	"tooltip"
];
var standalone_vega_tooltip_module_repository = {
	type: "git",
	url: "https://github.com/vega/vega-tooltip.git"
};
var standalone_vega_tooltip_module_author = {
	name: "UW Interactive Data Lab",
	url: "https://idl.cs.washington.edu"
};
var standalone_collaborators = [
	"Dominik Moritz",
	"Sira Horradarn",
	"Zening Qu",
	"Kanit Wongsuphasawat",
	"Yuri Astrakhan",
	"Jeffrey Heer"
];
var standalone_vega_tooltip_module_license = "BSD-3-Clause";
var standalone_bugs = {
	url: "https://github.com/vega/vega-tooltip/issues"
};
var standalone_homepage = "https://github.com/vega/vega-tooltip#readme";
var standalone_vega_tooltip_module_main = "build/vega-tooltip.js";
var standalone_vega_tooltip_module_module = "build/vega-tooltip.module.js";
var standalone_vega_tooltip_module_unpkg = "build/vega-tooltip.min.js";
var standalone_vega_tooltip_module_jsdelivr = "build/vega-tooltip.min.js";
var standalone_vega_tooltip_module_types = "build/src/index.d.ts";
var standalone_vega_tooltip_module_files = [
	"src",
	"build",
	"types"
];
var standalone_vega_tooltip_module_scripts = {
	prebuild: "npm run clean && npm run build:style",
	build: "rollup -c",
	"build:style": "./build-style.sh",
	clean: "rimraf build && rimraf src/style.ts",
	"copy:data": "cp -R node_modules/vega-datasets/data examples",
	"copy:build": "cp -R build examples",
	"deploy:gh": "npm run build && npm run copy:build && gh-pages -d examples && npm run clean",
	prepublishOnly: "npm run clean && npm run build",
	preversion: "npm run lint && npm run test",
	serve: "browser-sync start -s -f build examples --serveStatic examples",
	start: "npm run build && concurrently --kill-others -n Server,Rollup 'npm run serve' 'rollup -c -w'",
	pretest: "npm run build:style",
	test: "jest",
	"test:inspect": "node --inspect-brk ./node_modules/.bin/jest --runInBand",
	prepare: "npm run copy:data",
	prettierbase: "prettier '*.{css,scss,html}'",
	format: "eslint . --fix && npm run prettierbase -- --write",
	lint: "eslint . && npm run prettierbase -- --check",
	release: "release-it"
};
var standalone_vega_tooltip_module_devDependencies = {
	"@babel/core": "^7.26.0",
	"@babel/plugin-proposal-async-generator-functions": "^7.20.7",
	"@babel/plugin-proposal-json-strings": "^7.18.6",
	"@babel/plugin-proposal-object-rest-spread": "^7.20.7",
	"@babel/plugin-proposal-optional-catch-binding": "^7.18.6",
	"@babel/plugin-syntax-dynamic-import": "^7.8.3",
	"@babel/plugin-transform-runtime": "^7.25.9",
	"@babel/preset-env": "^7.26.0",
	"@babel/preset-typescript": "^7.26.0",
	"@release-it/conventional-changelog": "^9.0.2",
	"@rollup/plugin-json": "^6.1.0",
	"@rollup/plugin-node-resolve": "^15.3.0",
	"@rollup/plugin-terser": "^0.4.4",
	"@rollup/plugin-typescript": "^12.1.1",
	"@types/jest": "^29.5.14",
	"@typescript-eslint/eslint-plugin": "^8.13.0",
	"@typescript-eslint/parser": "^8.13.0",
	"browser-sync": "^3.0.3",
	concurrently: "^9.1.0",
	eslint: "^8.46.0",
	"eslint-config-prettier": "^9.1.0",
	"eslint-plugin-jest": "^28.8.3",
	"eslint-plugin-prettier": "^5.2.1",
	"gh-pages": "^6.2.0",
	jest: "^29.7.0",
	"jest-environment-jsdom": "^29.7.0",
	path: "^0.12.7",
	prettier: "^3.3.3",
	"release-it": "^17.10.0",
	rollup: "^4.24.4",
	"rollup-plugin-bundle-size": "^1.0.3",
	sass: "^1.80.6",
	typescript: "~5.6.3",
	"vega-datasets": "^2.9.0",
	"vega-typings": "^1.3.1"
};
var standalone_vega_tooltip_module_dependencies = {
	"vega-util": "^1.17.2"
};
var standalone_optionalDependencies = {
	"@rollup/rollup-linux-x64-gnu": "^4.24.4"
};
var standalone_vega_tooltip_module_pkg = {
	name: standalone_vega_tooltip_module_name,
	version: standalone_vega_tooltip_module_version$1,
	description: standalone_vega_tooltip_module_description,
	keywords: standalone_vega_tooltip_module_keywords,
	repository: standalone_vega_tooltip_module_repository,
	author: standalone_vega_tooltip_module_author,
	collaborators: standalone_collaborators,
	license: standalone_vega_tooltip_module_license,
	bugs: standalone_bugs,
	homepage: standalone_homepage,
	main: standalone_vega_tooltip_module_main,
	module: standalone_vega_tooltip_module_module,
	unpkg: standalone_vega_tooltip_module_unpkg,
	jsdelivr: standalone_vega_tooltip_module_jsdelivr,
	types: standalone_vega_tooltip_module_types,
	files: standalone_vega_tooltip_module_files,
	scripts: standalone_vega_tooltip_module_scripts,
	devDependencies: standalone_vega_tooltip_module_devDependencies,
	dependencies: standalone_vega_tooltip_module_dependencies,
	optionalDependencies: standalone_optionalDependencies
};

/**
 * Format the value to be shown in the tooltip.
 *
 * @param value The value to show in the tooltip.
 * @param valueToHtml Function to convert a single cell value to an HTML string
 */
function standalone_vega_tooltip_module_formatValue(value, valueToHtml, maxDepth, baseURL) {
    if (standalone_vega_util_module_isArray(value)) {
        return `[${value.map((v) => valueToHtml(standalone_vega_util_module_isString(v) ? v : standalone_vega_tooltip_module_stringify(v, maxDepth))).join(', ')}]`;
    }
    if (standalone_vega_util_module_isObject(value)) {
        let content = '';
        const { title, image, ...rest } = value;
        if (title) {
            content += `<h2>${valueToHtml(title)}</h2>`;
        }
        if (image) {
            content += `<img src="${new URL(valueToHtml(image), baseURL || location.href).href}">`;
        }
        const keys = Object.keys(rest);
        if (keys.length > 0) {
            content += '<table>';
            for (const key of keys) {
                let val = rest[key];
                // ignore undefined properties
                if (val === undefined) {
                    continue;
                }
                if (standalone_vega_util_module_isObject(val)) {
                    val = standalone_vega_tooltip_module_stringify(val, maxDepth);
                }
                content += `<tr><td class="key">${valueToHtml(key)}</td><td class="value">${valueToHtml(val)}</td></tr>`;
            }
            content += `</table>`;
        }
        return content || '{}'; // show empty object if there are no properties
    }
    return valueToHtml(value);
}
function standalone_replacer(maxDepth) {
    const stack = [];
    return function (key, value) {
        if (typeof value !== 'object' || value === null) {
            return value;
        }
        const pos = stack.indexOf(this) + 1;
        stack.length = pos;
        if (stack.length > maxDepth) {
            return '[Object]';
        }
        if (stack.indexOf(value) >= 0) {
            return '[Circular]';
        }
        stack.push(value);
        return value;
    };
}
/**
 * Stringify any JS object to valid JSON
 */
function standalone_vega_tooltip_module_stringify(obj, maxDepth) {
    return JSON.stringify(obj, standalone_replacer(maxDepth));
}

// generated with build-style.sh
var standalone_defaultStyle = `#vg-tooltip-element {
  visibility: hidden;
  padding: 8px;
  position: fixed;
  z-index: 1000;
  font-family: sans-serif;
  font-size: 11px;
  border-radius: 3px;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  /* The default theme is the light theme. */
  background-color: rgba(255, 255, 255, 0.95);
  border: 1px solid #d9d9d9;
  color: black;
}
#vg-tooltip-element.visible {
  visibility: visible;
}
#vg-tooltip-element h2 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 13px;
}
#vg-tooltip-element table {
  border-spacing: 0;
}
#vg-tooltip-element table tr {
  border: none;
}
#vg-tooltip-element table tr td {
  overflow: hidden;
  text-overflow: ellipsis;
  padding-top: 2px;
  padding-bottom: 2px;
}
#vg-tooltip-element table tr td.key {
  color: #808080;
  max-width: 150px;
  text-align: right;
  padding-right: 4px;
}
#vg-tooltip-element table tr td.value {
  display: block;
  max-width: 300px;
  max-height: 7em;
  text-align: left;
}
#vg-tooltip-element.dark-theme {
  background-color: rgba(32, 32, 32, 0.9);
  border: 1px solid #f5f5f5;
  color: white;
}
#vg-tooltip-element.dark-theme td.key {
  color: #bfbfbf;
}
`;

const standalone_EL_ID = 'vg-tooltip-element';
const standalone_DEFAULT_OPTIONS = {
    offsetX: 10,
    offsetY: 10,
    id: standalone_EL_ID,
    styleId: 'vega-tooltip-style',
    theme: 'light',
    disableDefaultStyle: false,
    sanitize: standalone_escapeHTML,
    maxDepth: 2,
    formatTooltip: standalone_vega_tooltip_module_formatValue,
    baseURL: '',
    anchor: 'cursor',
    position: ['top', 'bottom', 'left', 'right', 'top-left', 'top-right', 'bottom-left', 'bottom-right'],
};
/**
 * Escape special HTML characters.
 *
 * @param value A value to convert to string and HTML-escape.
 */
function standalone_escapeHTML(value) {
    return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;');
}
function standalone_createDefaultStyle(id) {
    // Just in case this id comes from a user, ensure these is no security issues
    if (!/^[A-Za-z]+[-:.\w]*$/.test(id)) {
        throw new Error('Invalid HTML ID');
    }
    return standalone_defaultStyle.toString().replace(standalone_EL_ID, id);
}

/**
 * Position the tooltip
 *
 * @param event The mouse event.
 * @param tooltipBox
 * @param options Tooltip handler options.
 */
function standalone_calculatePositionRelativeToCursor(event, tooltipBox, { offsetX, offsetY }) {
    // the possible positions for the tooltip
    const positions = standalone_getPositions({ x1: event.clientX, x2: event.clientX, y1: event.clientY, y2: event.clientY }, tooltipBox, offsetX, offsetY);
    // order of positions to try
    const postionArr = ['bottom-right', 'bottom-left', 'top-right', 'top-left'];
    // test positions till a valid one is found
    for (const p of postionArr) {
        if (standalone_tooltipIsInViewport(positions[p], tooltipBox)) {
            return positions[p];
        }
    }
    // default to top-left if a valid position is not found
    // this is legacy behavior
    return positions['top-left'];
}
/**
 * Calculates the position of the tooltip relative to the mark.
 * @param handler The handler instance.
 * @param event The mouse event.
 * @param item The item that the tooltip is being shown for.
 * @param tooltipBox Client rect of the tooltip element.
 * @param options Tooltip handler options.
 * @returns
 */
function standalone_calculatePositionRelativeToMark(handler, event, item, tooltipBox, options) {
    const { position, offsetX, offsetY } = options;
    const containerBox = handler._el.getBoundingClientRect();
    const origin = handler._origin;
    // bounds of the mark relative to the viewport
    const markBounds = standalone_getMarkBounds(containerBox, origin, item);
    // the possible positions for the tooltip
    const positions = standalone_getPositions(markBounds, tooltipBox, offsetX, offsetY);
    // positions to test
    const positionArr = Array.isArray(position) ? position : [position];
    // test positions till a valid one is found
    for (const p of positionArr) {
        // verify that the tooltip is in the view and the mouse is not where the tooltip would be
        if (standalone_tooltipIsInViewport(positions[p], tooltipBox) && !standalone_mouseIsOnTooltip(event, positions[p], tooltipBox)) {
            return positions[p];
        }
    }
    // default to cursor position if a valid position is not found
    return standalone_calculatePositionRelativeToCursor(event, tooltipBox, options);
}
// Calculates the bounds of the mark relative to the viewport.
function standalone_getMarkBounds(containerBox, origin, item) {
    // if this is a voronoi mark, we want to use the bounds of the point that voronoi cell represents
    const markBounds = item.isVoronoi ? item.datum.bounds : item.bounds;
    let left = containerBox.left + origin[0] + markBounds.x1;
    let top = containerBox.top + origin[1] + markBounds.y1;
    // traverse mark groups, summing their offsets to get the total offset
    // item bounds are relative to their group so if there are multiple nested groups we need to add them all
    let parentItem = item;
    while (parentItem.mark.group) {
        parentItem = parentItem.mark.group;
        left += parentItem.x ?? 0;
        top += parentItem.y ?? 0;
    }
    const markWidth = markBounds.x2 - markBounds.x1;
    const markHeight = markBounds.y2 - markBounds.y1;
    return {
        x1: left,
        x2: left + markWidth,
        y1: top,
        y2: top + markHeight,
    };
}
// Calculates the tooltip xy for each possible position.
function standalone_getPositions(markBounds, tooltipBox, offsetX, offsetY) {
    const xc = (markBounds.x1 + markBounds.x2) / 2;
    const yc = (markBounds.y1 + markBounds.y2) / 2;
    // x positions
    const left = markBounds.x1 - tooltipBox.width - offsetX;
    const center = xc - tooltipBox.width / 2;
    const right = markBounds.x2 + offsetX;
    // y positions
    const top = markBounds.y1 - tooltipBox.height - offsetY;
    const middle = yc - tooltipBox.height / 2;
    const bottom = markBounds.y2 + offsetY;
    const positions = {
        top: { x: center, y: top },
        bottom: { x: center, y: bottom },
        left: { x: left, y: middle },
        right: { x: right, y: middle },
        'top-left': { x: left, y: top },
        'top-right': { x: right, y: top },
        'bottom-left': { x: left, y: bottom },
        'bottom-right': { x: right, y: bottom },
    };
    return positions;
}
// Checks if the tooltip would be in the viewport at the given position
function standalone_tooltipIsInViewport(position, tooltipBox) {
    return (position.x >= 0 &&
        position.y >= 0 &&
        position.x + tooltipBox.width <= window.innerWidth &&
        position.y + tooltipBox.height <= window.innerHeight);
}
// Checks if the mouse is within the tooltip area
function standalone_mouseIsOnTooltip(event, position, tooltipBox) {
    return (event.clientX >= position.x &&
        event.clientX <= position.x + tooltipBox.width &&
        event.clientY >= position.y &&
        event.clientY <= position.y + tooltipBox.height);
}

/**
 * The tooltip handler class.
 */
class standalone_vega_tooltip_module_Handler {
    /**
     * Create the tooltip handler and initialize the element and style.
     *
     * @param options Tooltip Options
     */
    constructor(options) {
        this.options = { ...standalone_DEFAULT_OPTIONS, ...options };
        const elementId = this.options.id;
        this.el = null;
        // bind this to call
        this.call = this.tooltipHandler.bind(this);
        // prepend a default stylesheet for tooltips to the head
        if (!this.options.disableDefaultStyle && !document.getElementById(this.options.styleId)) {
            const style = document.createElement('style');
            style.setAttribute('id', this.options.styleId);
            style.innerHTML = standalone_createDefaultStyle(elementId);
            const head = document.head;
            if (head.childNodes.length > 0) {
                head.insertBefore(style, head.childNodes[0]);
            }
            else {
                head.appendChild(style);
            }
        }
    }
    /**
     * The tooltip handler function.
     */
    tooltipHandler(handler, event, item, value) {
        // append a div element that we use as a tooltip unless it already exists
        this.el = document.getElementById(this.options.id);
        if (!this.el) {
            this.el = document.createElement('div');
            this.el.setAttribute('id', this.options.id);
            this.el.classList.add('vg-tooltip');
            const tooltipContainer = document.fullscreenElement ?? document.body;
            tooltipContainer.appendChild(this.el);
        }
        // hide tooltip for null, undefined, or empty string values
        if (value == null || value === '') {
            this.el.classList.remove('visible', `${this.options.theme}-theme`);
            return;
        }
        // set the tooltip content
        this.el.innerHTML = this.options.formatTooltip(value, this.options.sanitize, this.options.maxDepth, this.options.baseURL);
        // make the tooltip visible
        this.el.classList.add('visible', `${this.options.theme}-theme`);
        const { x, y } = this.options.anchor === 'mark'
            ? standalone_calculatePositionRelativeToMark(handler, event, item, this.el.getBoundingClientRect(), this.options)
            : standalone_calculatePositionRelativeToCursor(event, this.el.getBoundingClientRect(), this.options);
        this.el.style.top = `${y}px`;
        this.el.style.left = `${x}px`;
    }
}

const standalone_vega_tooltip_module_version = standalone_vega_tooltip_module_pkg.version;
/**
 * Create a tooltip handler and register it with the provided view.
 *
 * @param view The Vega view.
 * @param opt Tooltip options.
 */
function standalone_vega_tooltip_module_index (view, opt) {
    const handler = new standalone_vega_tooltip_module_Handler(opt);
    view.tooltip(handler.call).run();
    return handler;
}


//# sourceMappingURL=vega-tooltip.module.js.map

;// ../../node_modules/vega-embed/build/vega-embed.module.js









/*!
 * https://github.com/Starcounter-Jack/JSON-Patch
 * (c) 2017-2022 Joachim Wester
 * MIT licensed
 */
var standalone_extends = ( false) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var standalone_hasOwnProperty = Object.prototype.hasOwnProperty;
function standalone_vega_embed_module_hasOwnProperty(obj, key) {
    return standalone_hasOwnProperty.call(obj, key);
}
function standalone_objectKeys(obj) {
    if (Array.isArray(obj)) {
        var keys_1 = new Array(obj.length);
        for (var k = 0; k < keys_1.length; k++) {
            keys_1[k] = "" + k;
        }
        return keys_1;
    }
    if (Object.keys) {
        return Object.keys(obj);
    }
    var keys = [];
    for (var i in obj) {
        if (standalone_vega_embed_module_hasOwnProperty(obj, i)) {
            keys.push(i);
        }
    }
    return keys;
}
/**
* Deeply clone the object.
* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy)
* @param  {any} obj value to clone
* @return {any} cloned obj
*/
function standalone_deepClone(obj) {
    switch (typeof obj) {
        case "object":
            return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5
        case "undefined":
            return null; //this is how JSON.stringify behaves for array items
        default:
            return obj; //no need to clone primitives
    }
}
//3x faster than cached /^\d+$/.test(str)
function standalone_vega_embed_module_isInteger(str) {
    var i = 0;
    var len = str.length;
    var charCode;
    while (i < len) {
        charCode = str.charCodeAt(i);
        if (charCode >= 48 && charCode <= 57) {
            i++;
            continue;
        }
        return false;
    }
    return true;
}
/**
* Escapes a json pointer path
* @param path The raw pointer
* @return the Escaped path
*/
function standalone_escapePathComponent(path) {
    if (path.indexOf('/') === -1 && path.indexOf('~') === -1)
        return path;
    return path.replace(/~/g, '~0').replace(/\//g, '~1');
}
/**
 * Unescapes a json pointer path
 * @param path The escaped pointer
 * @return The unescaped path
 */
function standalone_unescapePathComponent(path) {
    return path.replace(/~1/g, '/').replace(/~0/g, '~');
}
/**
* Recursively checks whether an object has any undefined values inside.
*/
function standalone_hasUndefined(obj) {
    if (obj === undefined) {
        return true;
    }
    if (obj) {
        if (Array.isArray(obj)) {
            for (var i_1 = 0, len = obj.length; i_1 < len; i_1++) {
                if (standalone_hasUndefined(obj[i_1])) {
                    return true;
                }
            }
        }
        else if (typeof obj === "object") {
            var objKeys = standalone_objectKeys(obj);
            var objKeysLength = objKeys.length;
            for (var i = 0; i < objKeysLength; i++) {
                if (standalone_hasUndefined(obj[objKeys[i]])) {
                    return true;
                }
            }
        }
    }
    return false;
}
function standalone_patchErrorMessageFormatter(message, args) {
    var messageParts = [message];
    for (var key in args) {
        var value = typeof args[key] === 'object' ? JSON.stringify(args[key], null, 2) : args[key]; // pretty print
        if (typeof value !== 'undefined') {
            messageParts.push(key + ": " + value);
        }
    }
    return messageParts.join('\n');
}
var standalone_PatchError = /** @class */ (function (_super) {
    standalone_extends(PatchError, _super);
    function PatchError(message, name, index, operation, tree) {
        var _newTarget = this.constructor;
        var _this = _super.call(this, standalone_patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree })) || this;
        _this.name = name;
        _this.index = index;
        _this.operation = operation;
        _this.tree = tree;
        Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359
        _this.message = standalone_patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree });
        return _this;
    }
    return PatchError;
}(Error));

var standalone_JsonPatchError = standalone_PatchError;
var src_standalone_deepClone = standalone_deepClone;
/* We use a Javascript hash to store each
 function. Each hash entry (property) uses
 the operation identifiers specified in rfc6902.
 In this way, we can map each patch operation
 to its dedicated function in efficient way.
 */
/* The operations applicable to an object */
var standalone_objOps = {
    add: function (obj, key, document) {
        obj[key] = this.value;
        return { newDocument: document };
    },
    remove: function (obj, key, document) {
        var removed = obj[key];
        delete obj[key];
        return { newDocument: document, removed: removed };
    },
    replace: function (obj, key, document) {
        var removed = obj[key];
        obj[key] = this.value;
        return { newDocument: document, removed: removed };
    },
    move: function (obj, key, document) {
        /* in case move target overwrites an existing value,
        return the removed value, this can be taxing performance-wise,
        and is potentially unneeded */
        var removed = standalone_getValueByPointer(document, this.path);
        if (removed) {
            removed = standalone_deepClone(removed);
        }
        var originalValue = standalone_applyOperation(document, { op: "remove", path: this.from }).removed;
        standalone_applyOperation(document, { op: "add", path: this.path, value: originalValue });
        return { newDocument: document, removed: removed };
    },
    copy: function (obj, key, document) {
        var valueToCopy = standalone_getValueByPointer(document, this.from);
        // enforce copy by value so further operations don't affect source (see issue #177)
        standalone_applyOperation(document, { op: "add", path: this.path, value: standalone_deepClone(valueToCopy) });
        return { newDocument: document };
    },
    test: function (obj, key, document) {
        return { newDocument: document, test: standalone_areEquals(obj[key], this.value) };
    },
    _get: function (obj, key, document) {
        this.value = obj[key];
        return { newDocument: document };
    }
};
/* The operations applicable to an array. Many are the same as for the object */
var standalone_arrOps = {
    add: function (arr, i, document) {
        if (standalone_vega_embed_module_isInteger(i)) {
            arr.splice(i, 0, this.value);
        }
        else { // array props
            arr[i] = this.value;
        }
        // this may be needed when using '-' in an array
        return { newDocument: document, index: i };
    },
    remove: function (arr, i, document) {
        var removedList = arr.splice(i, 1);
        return { newDocument: document, removed: removedList[0] };
    },
    replace: function (arr, i, document) {
        var removed = arr[i];
        arr[i] = this.value;
        return { newDocument: document, removed: removed };
    },
    move: standalone_objOps.move,
    copy: standalone_objOps.copy,
    test: standalone_objOps.test,
    _get: standalone_objOps._get
};
/**
 * Retrieves a value from a JSON document by a JSON pointer.
 * Returns the value.
 *
 * @param document The document to get the value from
 * @param pointer an escaped JSON pointer
 * @return The retrieved value
 */
function standalone_getValueByPointer(document, pointer) {
    if (pointer == '') {
        return document;
    }
    var getOriginalDestination = { op: "_get", path: pointer };
    standalone_applyOperation(document, getOriginalDestination);
    return getOriginalDestination.value;
}
/**
 * Apply a single JSON Patch Operation on a JSON document.
 * Returns the {newDocument, result} of the operation.
 * It modifies the `document` and `operation` objects - it gets the values by reference.
 * If you would like to avoid touching your values, clone them:
 * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.
 *
 * @param document The document to patch
 * @param operation The operation to apply
 * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.
 * @param mutateDocument Whether to mutate the original document or clone it before applying
 * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.
 * @return `{newDocument, result}` after the operation
 */
function standalone_applyOperation(document, operation, validateOperation, mutateDocument, banPrototypeModifications, index) {
    if (validateOperation === void 0) { validateOperation = false; }
    if (mutateDocument === void 0) { mutateDocument = true; }
    if (banPrototypeModifications === void 0) { banPrototypeModifications = true; }
    if (index === void 0) { index = 0; }
    if (validateOperation) {
        if (typeof validateOperation == 'function') {
            validateOperation(operation, 0, document, operation.path);
        }
        else {
            standalone_validator(operation, 0);
        }
    }
    /* ROOT OPERATIONS */
    if (operation.path === "") {
        var returnValue = { newDocument: document };
        if (operation.op === 'add') {
            returnValue.newDocument = operation.value;
            return returnValue;
        }
        else if (operation.op === 'replace') {
            returnValue.newDocument = operation.value;
            returnValue.removed = document; //document we removed
            return returnValue;
        }
        else if (operation.op === 'move' || operation.op === 'copy') { // it's a move or copy to root
            returnValue.newDocument = standalone_getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field
            if (operation.op === 'move') { // report removed item
                returnValue.removed = document;
            }
            return returnValue;
        }
        else if (operation.op === 'test') {
            returnValue.test = standalone_areEquals(document, operation.value);
            if (returnValue.test === false) {
                throw new standalone_JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
            }
            returnValue.newDocument = document;
            return returnValue;
        }
        else if (operation.op === 'remove') { // a remove on root
            returnValue.removed = document;
            returnValue.newDocument = null;
            return returnValue;
        }
        else if (operation.op === '_get') {
            operation.value = document;
            return returnValue;
        }
        else { /* bad operation */
            if (validateOperation) {
                throw new standalone_JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);
            }
            else {
                return returnValue;
            }
        }
    } /* END ROOT OPERATIONS */
    else {
        if (!mutateDocument) {
            document = standalone_deepClone(document);
        }
        var path = operation.path || "";
        var keys = path.split('/');
        var obj = document;
        var t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift
        var len = keys.length;
        var existingPathFragment = undefined;
        var key = void 0;
        var validateFunction = void 0;
        if (typeof validateOperation == 'function') {
            validateFunction = validateOperation;
        }
        else {
            validateFunction = standalone_validator;
        }
        while (true) {
            key = keys[t];
            if (key && key.indexOf('~') != -1) {
                key = standalone_unescapePathComponent(key);
            }
            if (banPrototypeModifications &&
                (key == '__proto__' ||
                    (key == 'prototype' && t > 0 && keys[t - 1] == 'constructor'))) {
                throw new TypeError('JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README');
            }
            if (validateOperation) {
                if (existingPathFragment === undefined) {
                    if (obj[key] === undefined) {
                        existingPathFragment = keys.slice(0, t).join('/');
                    }
                    else if (t == len - 1) {
                        existingPathFragment = operation.path;
                    }
                    if (existingPathFragment !== undefined) {
                        validateFunction(operation, 0, document, existingPathFragment);
                    }
                }
            }
            t++;
            if (Array.isArray(obj)) {
                if (key === '-') {
                    key = obj.length;
                }
                else {
                    if (validateOperation && !standalone_vega_embed_module_isInteger(key)) {
                        throw new standalone_JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document);
                    } // only parse key when it's an integer for `arr.prop` to work
                    else if (standalone_vega_embed_module_isInteger(key)) {
                        key = ~~key;
                    }
                }
                if (t >= len) {
                    if (validateOperation && operation.op === "add" && key > obj.length) {
                        throw new standalone_JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document);
                    }
                    var returnValue = standalone_arrOps[operation.op].call(operation, obj, key, document); // Apply patch
                    if (returnValue.test === false) {
                        throw new standalone_JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
                    }
                    return returnValue;
                }
            }
            else {
                if (t >= len) {
                    var returnValue = standalone_objOps[operation.op].call(operation, obj, key, document); // Apply patch
                    if (returnValue.test === false) {
                        throw new standalone_JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
                    }
                    return returnValue;
                }
            }
            obj = obj[key];
            // If we have more keys in the path, but the next value isn't a non-null object,
            // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.
            if (validateOperation && t < len && (!obj || typeof obj !== "object")) {
                throw new standalone_JsonPatchError('Cannot perform operation at the desired path', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);
            }
        }
    }
}
/**
 * Apply a full JSON Patch array on a JSON document.
 * Returns the {newDocument, result} of the patch.
 * It modifies the `document` object and `patch` - it gets the values by reference.
 * If you would like to avoid touching your values, clone them:
 * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.
 *
 * @param document The document to patch
 * @param patch The patch to apply
 * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.
 * @param mutateDocument Whether to mutate the original document or clone it before applying
 * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.
 * @return An array of `{newDocument, result}` after the patch
 */
function standalone_applyPatch(document, patch, validateOperation, mutateDocument, banPrototypeModifications) {
    if (mutateDocument === void 0) { mutateDocument = true; }
    if (banPrototypeModifications === void 0) { banPrototypeModifications = true; }
    if (validateOperation) {
        if (!Array.isArray(patch)) {
            throw new standalone_JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');
        }
    }
    if (!mutateDocument) {
        document = standalone_deepClone(document);
    }
    var results = new Array(patch.length);
    for (var i = 0, length_1 = patch.length; i < length_1; i++) {
        // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`
        results[i] = standalone_applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i);
        document = results[i].newDocument; // in case root was replaced
    }
    results.newDocument = document;
    return results;
}
/**
 * Apply a single JSON Patch Operation on a JSON document.
 * Returns the updated document.
 * Suitable as a reducer.
 *
 * @param document The document to patch
 * @param operation The operation to apply
 * @return The updated document
 */
function standalone_applyReducer(document, operation, index) {
    var operationResult = standalone_applyOperation(document, operation);
    if (operationResult.test === false) { // failed test
        throw new standalone_JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
    }
    return operationResult.newDocument;
}
/**
 * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.
 * @param {object} operation - operation object (patch)
 * @param {number} index - index of operation in the sequence
 * @param {object} [document] - object where the operation is supposed to be applied
 * @param {string} [existingPathFragment] - comes along with `document`
 */
function standalone_validator(operation, index, document, existingPathFragment) {
    if (typeof operation !== 'object' || operation === null || Array.isArray(operation)) {
        throw new standalone_JsonPatchError('Operation is not an object', 'OPERATION_NOT_AN_OBJECT', index, operation, document);
    }
    else if (!standalone_objOps[operation.op]) {
        throw new standalone_JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);
    }
    else if (typeof operation.path !== 'string') {
        throw new standalone_JsonPatchError('Operation `path` property is not a string', 'OPERATION_PATH_INVALID', index, operation, document);
    }
    else if (operation.path.indexOf('/') !== 0 && operation.path.length > 0) {
        // paths that aren't empty string should start with "/"
        throw new standalone_JsonPatchError('Operation `path` property must start with "/"', 'OPERATION_PATH_INVALID', index, operation, document);
    }
    else if ((operation.op === 'move' || operation.op === 'copy') && typeof operation.from !== 'string') {
        throw new standalone_JsonPatchError('Operation `from` property is not present (applicable in `move` and `copy` operations)', 'OPERATION_FROM_REQUIRED', index, operation, document);
    }
    else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && operation.value === undefined) {
        throw new standalone_JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_REQUIRED', index, operation, document);
    }
    else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && standalone_hasUndefined(operation.value)) {
        throw new standalone_JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED', index, operation, document);
    }
    else if (document) {
        if (operation.op == "add") {
            var pathLen = operation.path.split("/").length;
            var existingPathLen = existingPathFragment.split("/").length;
            if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {
                throw new standalone_JsonPatchError('Cannot perform an `add` operation at the desired path', 'OPERATION_PATH_CANNOT_ADD', index, operation, document);
            }
        }
        else if (operation.op === 'replace' || operation.op === 'remove' || operation.op === '_get') {
            if (operation.path !== existingPathFragment) {
                throw new standalone_JsonPatchError('Cannot perform the operation at a path that does not exist', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);
            }
        }
        else if (operation.op === 'move' || operation.op === 'copy') {
            var existingValue = { op: "_get", path: operation.from, value: undefined };
            var error = standalone_validate([existingValue], document);
            if (error && error.name === 'OPERATION_PATH_UNRESOLVABLE') {
                throw new standalone_JsonPatchError('Cannot perform the operation from a path that does not exist', 'OPERATION_FROM_UNRESOLVABLE', index, operation, document);
            }
        }
    }
}
/**
 * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.
 * If error is encountered, returns a JsonPatchError object
 * @param sequence
 * @param document
 * @returns {JsonPatchError|undefined}
 */
function standalone_validate(sequence, document, externalValidator) {
    try {
        if (!Array.isArray(sequence)) {
            throw new standalone_JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');
        }
        if (document) {
            //clone document and sequence so that we can safely try applying operations
            standalone_applyPatch(standalone_deepClone(document), standalone_deepClone(sequence), externalValidator || true);
        }
        else {
            externalValidator = externalValidator || standalone_validator;
            for (var i = 0; i < sequence.length; i++) {
                externalValidator(sequence[i], i, document, undefined);
            }
        }
    }
    catch (e) {
        if (e instanceof standalone_JsonPatchError) {
            return e;
        }
        else {
            throw e;
        }
    }
}
// based on https://github.com/epoberezkin/fast-deep-equal
// MIT License
// Copyright (c) 2017 Evgeny Poberezkin
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
function standalone_areEquals(a, b) {
    if (a === b)
        return true;
    if (a && b && typeof a == 'object' && typeof b == 'object') {
        var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key;
        if (arrA && arrB) {
            length = a.length;
            if (length != b.length)
                return false;
            for (i = length; i-- !== 0;)
                if (!standalone_areEquals(a[i], b[i]))
                    return false;
            return true;
        }
        if (arrA != arrB)
            return false;
        var keys = Object.keys(a);
        length = keys.length;
        if (length !== Object.keys(b).length)
            return false;
        for (i = length; i-- !== 0;)
            if (!b.hasOwnProperty(keys[i]))
                return false;
        for (i = length; i-- !== 0;) {
            key = keys[i];
            if (!standalone_areEquals(a[key], b[key]))
                return false;
        }
        return true;
    }
    return a !== a && b !== b;
}

var standalone_core = /*#__PURE__*/Object.freeze({
    __proto__: null,
    JsonPatchError: standalone_JsonPatchError,
    _areEquals: standalone_areEquals,
    applyOperation: standalone_applyOperation,
    applyPatch: standalone_applyPatch,
    applyReducer: standalone_applyReducer,
    deepClone: src_standalone_deepClone,
    getValueByPointer: standalone_getValueByPointer,
    validate: standalone_validate,
    validator: standalone_validator
});

/*!
 * https://github.com/Starcounter-Jack/JSON-Patch
 * (c) 2017-2021 Joachim Wester
 * MIT license
 */
var standalone_beforeDict = new WeakMap();
var standalone_Mirror = /** @class */ (function () {
    function Mirror(obj) {
        this.observers = new Map();
        this.obj = obj;
    }
    return Mirror;
}());
var standalone_ObserverInfo = /** @class */ (function () {
    function ObserverInfo(callback, observer) {
        this.callback = callback;
        this.observer = observer;
    }
    return ObserverInfo;
}());
function standalone_getMirror(obj) {
    return standalone_beforeDict.get(obj);
}
function standalone_getObserverFromMirror(mirror, callback) {
    return mirror.observers.get(callback);
}
function standalone_removeObserverFromMirror(mirror, observer) {
    mirror.observers.delete(observer.callback);
}
/**
 * Detach an observer from an object
 */
function standalone_unobserve(root, observer) {
    observer.unobserve();
}
/**
 * Observes changes made to an object, which can then be retrieved using generate
 */
function standalone_observe(obj, callback) {
    var patches = [];
    var observer;
    var mirror = standalone_getMirror(obj);
    if (!mirror) {
        mirror = new standalone_Mirror(obj);
        standalone_beforeDict.set(obj, mirror);
    }
    else {
        var observerInfo = standalone_getObserverFromMirror(mirror, callback);
        observer = observerInfo && observerInfo.observer;
    }
    if (observer) {
        return observer;
    }
    observer = {};
    mirror.value = standalone_deepClone(obj);
    if (callback) {
        observer.callback = callback;
        observer.next = null;
        var dirtyCheck = function () {
            standalone_vega_embed_module_generate(observer);
        };
        var fastCheck = function () {
            clearTimeout(observer.next);
            observer.next = setTimeout(dirtyCheck);
        };
        if (typeof window !== 'undefined') { //not Node
            window.addEventListener('mouseup', fastCheck);
            window.addEventListener('keyup', fastCheck);
            window.addEventListener('mousedown', fastCheck);
            window.addEventListener('keydown', fastCheck);
            window.addEventListener('change', fastCheck);
        }
    }
    observer.patches = patches;
    observer.object = obj;
    observer.unobserve = function () {
        standalone_vega_embed_module_generate(observer);
        clearTimeout(observer.next);
        standalone_removeObserverFromMirror(mirror, observer);
        if (typeof window !== 'undefined') {
            window.removeEventListener('mouseup', fastCheck);
            window.removeEventListener('keyup', fastCheck);
            window.removeEventListener('mousedown', fastCheck);
            window.removeEventListener('keydown', fastCheck);
            window.removeEventListener('change', fastCheck);
        }
    };
    mirror.observers.set(callback, new standalone_ObserverInfo(callback, observer));
    return observer;
}
/**
 * Generate an array of patches from an observer
 */
function standalone_vega_embed_module_generate(observer, invertible) {
    if (invertible === void 0) { invertible = false; }
    var mirror = standalone_beforeDict.get(observer.object);
    src_standalone_generate(mirror.value, observer.object, observer.patches, "", invertible);
    if (observer.patches.length) {
        standalone_applyPatch(mirror.value, observer.patches);
    }
    var temp = observer.patches;
    if (temp.length > 0) {
        observer.patches = [];
        if (observer.callback) {
            observer.callback(temp);
        }
    }
    return temp;
}
// Dirty check if obj is different from mirror, generate patches and update mirror
function src_standalone_generate(mirror, obj, patches, path, invertible) {
    if (obj === mirror) {
        return;
    }
    if (typeof obj.toJSON === "function") {
        obj = obj.toJSON();
    }
    var newKeys = standalone_objectKeys(obj);
    var oldKeys = standalone_objectKeys(mirror);
    var deleted = false;
    //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)"
    for (var t = oldKeys.length - 1; t >= 0; t--) {
        var key = oldKeys[t];
        var oldVal = mirror[key];
        if (standalone_vega_embed_module_hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) {
            var newVal = obj[key];
            if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) {
                src_standalone_generate(oldVal, newVal, patches, path + "/" + standalone_escapePathComponent(key), invertible);
            }
            else {
                if (oldVal !== newVal) {
                    if (invertible) {
                        patches.push({ op: "test", path: path + "/" + standalone_escapePathComponent(key), value: standalone_deepClone(oldVal) });
                    }
                    patches.push({ op: "replace", path: path + "/" + standalone_escapePathComponent(key), value: standalone_deepClone(newVal) });
                }
            }
        }
        else if (Array.isArray(mirror) === Array.isArray(obj)) {
            if (invertible) {
                patches.push({ op: "test", path: path + "/" + standalone_escapePathComponent(key), value: standalone_deepClone(oldVal) });
            }
            patches.push({ op: "remove", path: path + "/" + standalone_escapePathComponent(key) });
            deleted = true; // property has been deleted
        }
        else {
            if (invertible) {
                patches.push({ op: "test", path: path, value: mirror });
            }
            patches.push({ op: "replace", path: path, value: obj });
        }
    }
    if (!deleted && newKeys.length == oldKeys.length) {
        return;
    }
    for (var t = 0; t < newKeys.length; t++) {
        var key = newKeys[t];
        if (!standalone_vega_embed_module_hasOwnProperty(mirror, key) && obj[key] !== undefined) {
            patches.push({ op: "add", path: path + "/" + standalone_escapePathComponent(key), value: standalone_deepClone(obj[key]) });
        }
    }
}
/**
 * Create an array of patches from the differences in two objects
 */
function standalone_vega_embed_module_compare(tree1, tree2, invertible) {
    if (invertible === void 0) { invertible = false; }
    var patches = [];
    src_standalone_generate(tree1, tree2, patches, '', invertible);
    return patches;
}

var standalone_duplex = /*#__PURE__*/Object.freeze({
    __proto__: null,
    compare: standalone_vega_embed_module_compare,
    generate: standalone_vega_embed_module_generate,
    observe: standalone_observe,
    unobserve: standalone_unobserve
});

Object.assign({}, standalone_core, standalone_duplex, {
    JsonPatchError: standalone_PatchError,
    deepClone: standalone_deepClone,
    escapePathComponent: standalone_escapePathComponent,
    unescapePathComponent: standalone_unescapePathComponent
});

function standalone_getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

var standalone_lrucache;
var standalone_hasRequiredLrucache;

function standalone_requireLrucache () {
	if (standalone_hasRequiredLrucache) return standalone_lrucache;
	standalone_hasRequiredLrucache = 1;
	class LRUCache {
	  constructor () {
	    this.max = 1000;
	    this.map = new Map();
	  }

	  get (key) {
	    const value = this.map.get(key);
	    if (value === undefined) {
	      return undefined
	    } else {
	      // Remove the key from the map and add it to the end
	      this.map.delete(key);
	      this.map.set(key, value);
	      return value
	    }
	  }

	  delete (key) {
	    return this.map.delete(key)
	  }

	  set (key, value) {
	    const deleted = this.delete(key);

	    if (!deleted && value !== undefined) {
	      // If cache is full, delete the least recently used item
	      if (this.map.size >= this.max) {
	        const firstKey = this.map.keys().next().value;
	        this.delete(firstKey);
	      }

	      this.map.set(key, value);
	    }

	    return this
	  }
	}

	standalone_lrucache = LRUCache;
	return standalone_lrucache;
}

var standalone_parseOptions_1;
var standalone_hasRequiredParseOptions;

function standalone_requireParseOptions () {
	if (standalone_hasRequiredParseOptions) return standalone_parseOptions_1;
	standalone_hasRequiredParseOptions = 1;
	// parse out just the options we care about
	const looseOption = Object.freeze({ loose: true });
	const emptyOpts = Object.freeze({ });
	const parseOptions = options => {
	  if (!options) {
	    return emptyOpts
	  }

	  if (typeof options !== 'object') {
	    return looseOption
	  }

	  return options
	};
	standalone_parseOptions_1 = parseOptions;
	return standalone_parseOptions_1;
}

var standalone_vega_embed_module_re = {exports: {}};

var standalone_vega_embed_module_constants;
var standalone_hasRequiredConstants;

function standalone_requireConstants () {
	if (standalone_hasRequiredConstants) return standalone_vega_embed_module_constants;
	standalone_hasRequiredConstants = 1;
	// Note: this is the semver.org version of the spec that it implements
	// Not necessarily the package version of this code.
	const SEMVER_SPEC_VERSION = '2.0.0';

	const MAX_LENGTH = 256;
	const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
	/* istanbul ignore next */ 9007199254740991;

	// Max safe segment length for coercion.
	const MAX_SAFE_COMPONENT_LENGTH = 16;

	// Max safe length for a build identifier. The max length minus 6 characters for
	// the shortest version with a build 0.0.0+BUILD.
	const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;

	const RELEASE_TYPES = [
	  'major',
	  'premajor',
	  'minor',
	  'preminor',
	  'patch',
	  'prepatch',
	  'prerelease',
	];

	standalone_vega_embed_module_constants = {
	  MAX_LENGTH,
	  MAX_SAFE_COMPONENT_LENGTH,
	  MAX_SAFE_BUILD_LENGTH,
	  MAX_SAFE_INTEGER,
	  RELEASE_TYPES,
	  SEMVER_SPEC_VERSION,
	  FLAG_INCLUDE_PRERELEASE: 0b001,
	  FLAG_LOOSE: 0b010,
	};
	return standalone_vega_embed_module_constants;
}

var standalone_debug_1;
var standalone_hasRequiredDebug;

function standalone_requireDebug () {
	if (standalone_hasRequiredDebug) return standalone_debug_1;
	standalone_hasRequiredDebug = 1;
	const debug = (
	  typeof process === 'object' &&
	  process.env &&
	  process.env.NODE_DEBUG &&
	  /\bsemver\b/i.test(process.env.NODE_DEBUG)
	) ? (...args) => console.error('SEMVER', ...args)
	  : () => {};

	standalone_debug_1 = debug;
	return standalone_debug_1;
}

var standalone_hasRequiredRe;

function standalone_requireRe () {
	if (standalone_hasRequiredRe) return standalone_vega_embed_module_re.exports;
	standalone_hasRequiredRe = 1;
	(function (module, exports) {
		const {
		  MAX_SAFE_COMPONENT_LENGTH,
		  MAX_SAFE_BUILD_LENGTH,
		  MAX_LENGTH,
		} = standalone_requireConstants();
		const debug = standalone_requireDebug();
		exports = module.exports = {};

		// The actual regexps go on exports.re
		const re = exports.re = [];
		const safeRe = exports.safeRe = [];
		const src = exports.src = [];
		const t = exports.t = {};
		let R = 0;

		const LETTERDASHNUMBER = '[a-zA-Z0-9-]';

		// Replace some greedy regex tokens to prevent regex dos issues. These regex are
		// used internally via the safeRe object since all inputs in this library get
		// normalized first to trim and collapse all extra whitespace. The original
		// regexes are exported for userland consumption and lower level usage. A
		// future breaking change could export the safer regex only with a note that
		// all input should have extra whitespace removed.
		const safeRegexReplacements = [
		  ['\\s', 1],
		  ['\\d', MAX_LENGTH],
		  [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
		];

		const makeSafeRegex = (value) => {
		  for (const [token, max] of safeRegexReplacements) {
		    value = value
		      .split(`${token}*`).join(`${token}{0,${max}}`)
		      .split(`${token}+`).join(`${token}{1,${max}}`);
		  }
		  return value
		};

		const createToken = (name, value, isGlobal) => {
		  const safe = makeSafeRegex(value);
		  const index = R++;
		  debug(name, index, value);
		  t[name] = index;
		  src[index] = value;
		  re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
		  safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined);
		};

		// The following Regular Expressions can be used for tokenizing,
		// validating, and parsing SemVer version strings.

		// ## Numeric Identifier
		// A single `0`, or a non-zero digit followed by zero or more digits.

		createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
		createToken('NUMERICIDENTIFIERLOOSE', '\\d+');

		// ## Non-numeric Identifier
		// Zero or more digits, followed by a letter or hyphen, and then zero or
		// more letters, digits, or hyphens.

		createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);

		// ## Main Version
		// Three dot-separated numeric identifiers.

		createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
		                   `(${src[t.NUMERICIDENTIFIER]})\\.` +
		                   `(${src[t.NUMERICIDENTIFIER]})`);

		createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
		                        `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
		                        `(${src[t.NUMERICIDENTIFIERLOOSE]})`);

		// ## Pre-release Version Identifier
		// A numeric identifier, or a non-numeric identifier.

		createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
		}|${src[t.NONNUMERICIDENTIFIER]})`);

		createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
		}|${src[t.NONNUMERICIDENTIFIER]})`);

		// ## Pre-release Version
		// Hyphen, followed by one or more dot-separated pre-release version
		// identifiers.

		createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
		}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);

		createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
		}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);

		// ## Build Metadata Identifier
		// Any combination of digits, letters, or hyphens.

		createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`);

		// ## Build Metadata
		// Plus sign, followed by one or more period-separated build metadata
		// identifiers.

		createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
		}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);

		// ## Full Version String
		// A main version, followed optionally by a pre-release version and
		// build metadata.

		// Note that the only major, minor, patch, and pre-release sections of
		// the version string are capturing groups.  The build metadata is not a
		// capturing group, because it should not ever be used in version
		// comparison.

		createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
		}${src[t.PRERELEASE]}?${
		  src[t.BUILD]}?`);

		createToken('FULL', `^${src[t.FULLPLAIN]}$`);

		// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
		// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
		// common in the npm registry.
		createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
		}${src[t.PRERELEASELOOSE]}?${
		  src[t.BUILD]}?`);

		createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);

		createToken('GTLT', '((?:<|>)?=?)');

		// Something like "2.*" or "1.2.x".
		// Note that "x.x" is a valid xRange identifer, meaning "any version"
		// Only the first item is strictly required.
		createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
		createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);

		createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
		                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
		                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
		                   `(?:${src[t.PRERELEASE]})?${
		                     src[t.BUILD]}?` +
		                   `)?)?`);

		createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
		                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
		                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
		                        `(?:${src[t.PRERELEASELOOSE]})?${
		                          src[t.BUILD]}?` +
		                        `)?)?`);

		createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
		createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);

		// Coercion.
		// Extract anything that could conceivably be a part of a valid semver
		createToken('COERCEPLAIN', `${'(^|[^\\d])' +
		              '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
		              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
		              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
		createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
		createToken('COERCEFULL', src[t.COERCEPLAIN] +
		              `(?:${src[t.PRERELEASE]})?` +
		              `(?:${src[t.BUILD]})?` +
		              `(?:$|[^\\d])`);
		createToken('COERCERTL', src[t.COERCE], true);
		createToken('COERCERTLFULL', src[t.COERCEFULL], true);

		// Tilde ranges.
		// Meaning is "reasonably at or greater than"
		createToken('LONETILDE', '(?:~>?)');

		createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
		exports.tildeTrimReplace = '$1~';

		createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
		createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);

		// Caret ranges.
		// Meaning is "at least and backwards compatible with"
		createToken('LONECARET', '(?:\\^)');

		createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
		exports.caretTrimReplace = '$1^';

		createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
		createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);

		// A simple gt/lt/eq thing, or just "" to indicate "any version"
		createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
		createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);

		// An expression to strip any whitespace between the gtlt and the thing
		// it modifies, so that `> 1.2.3` ==> `>1.2.3`
		createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
		}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
		exports.comparatorTrimReplace = '$1$2$3';

		// Something like `1.2.3 - 1.2.4`
		// Note that these all use the loose form, because they'll be
		// checked against either the strict or loose comparator form
		// later.
		createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
		                   `\\s+-\\s+` +
		                   `(${src[t.XRANGEPLAIN]})` +
		                   `\\s*$`);

		createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
		                        `\\s+-\\s+` +
		                        `(${src[t.XRANGEPLAINLOOSE]})` +
		                        `\\s*$`);

		// Star ranges basically just allow anything at all.
		createToken('STAR', '(<|>)?=?\\s*\\*');
		// >=0.0.0 is like a star
		createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$');
		createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$'); 
	} (standalone_vega_embed_module_re, standalone_vega_embed_module_re.exports));
	return standalone_vega_embed_module_re.exports;
}

var standalone_identifiers;
var standalone_hasRequiredIdentifiers;

function standalone_requireIdentifiers () {
	if (standalone_hasRequiredIdentifiers) return standalone_identifiers;
	standalone_hasRequiredIdentifiers = 1;
	const numeric = /^[0-9]+$/;
	const compareIdentifiers = (a, b) => {
	  const anum = numeric.test(a);
	  const bnum = numeric.test(b);

	  if (anum && bnum) {
	    a = +a;
	    b = +b;
	  }

	  return a === b ? 0
	    : (anum && !bnum) ? -1
	    : (bnum && !anum) ? 1
	    : a < b ? -1
	    : 1
	};

	const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);

	standalone_identifiers = {
	  compareIdentifiers,
	  rcompareIdentifiers,
	};
	return standalone_identifiers;
}

var standalone_semver;
var standalone_hasRequiredSemver;

function standalone_requireSemver () {
	if (standalone_hasRequiredSemver) return standalone_semver;
	standalone_hasRequiredSemver = 1;
	const debug = standalone_requireDebug();
	const { MAX_LENGTH, MAX_SAFE_INTEGER } = standalone_requireConstants();
	const { safeRe: re, t } = standalone_requireRe();

	const parseOptions = standalone_requireParseOptions();
	const { compareIdentifiers } = standalone_requireIdentifiers();
	class SemVer {
	  constructor (version, options) {
	    options = parseOptions(options);

	    if (version instanceof SemVer) {
	      if (version.loose === !!options.loose &&
	          version.includePrerelease === !!options.includePrerelease) {
	        return version
	      } else {
	        version = version.version;
	      }
	    } else if (typeof version !== 'string') {
	      throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
	    }

	    if (version.length > MAX_LENGTH) {
	      throw new TypeError(
	        `version is longer than ${MAX_LENGTH} characters`
	      )
	    }

	    debug('SemVer', version, options);
	    this.options = options;
	    this.loose = !!options.loose;
	    // this isn't actually relevant for versions, but keep it so that we
	    // don't run into trouble passing this.options around.
	    this.includePrerelease = !!options.includePrerelease;

	    const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);

	    if (!m) {
	      throw new TypeError(`Invalid Version: ${version}`)
	    }

	    this.raw = version;

	    // these are actually numbers
	    this.major = +m[1];
	    this.minor = +m[2];
	    this.patch = +m[3];

	    if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
	      throw new TypeError('Invalid major version')
	    }

	    if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
	      throw new TypeError('Invalid minor version')
	    }

	    if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
	      throw new TypeError('Invalid patch version')
	    }

	    // numberify any prerelease numeric ids
	    if (!m[4]) {
	      this.prerelease = [];
	    } else {
	      this.prerelease = m[4].split('.').map((id) => {
	        if (/^[0-9]+$/.test(id)) {
	          const num = +id;
	          if (num >= 0 && num < MAX_SAFE_INTEGER) {
	            return num
	          }
	        }
	        return id
	      });
	    }

	    this.build = m[5] ? m[5].split('.') : [];
	    this.format();
	  }

	  format () {
	    this.version = `${this.major}.${this.minor}.${this.patch}`;
	    if (this.prerelease.length) {
	      this.version += `-${this.prerelease.join('.')}`;
	    }
	    return this.version
	  }

	  toString () {
	    return this.version
	  }

	  compare (other) {
	    debug('SemVer.compare', this.version, this.options, other);
	    if (!(other instanceof SemVer)) {
	      if (typeof other === 'string' && other === this.version) {
	        return 0
	      }
	      other = new SemVer(other, this.options);
	    }

	    if (other.version === this.version) {
	      return 0
	    }

	    return this.compareMain(other) || this.comparePre(other)
	  }

	  compareMain (other) {
	    if (!(other instanceof SemVer)) {
	      other = new SemVer(other, this.options);
	    }

	    return (
	      compareIdentifiers(this.major, other.major) ||
	      compareIdentifiers(this.minor, other.minor) ||
	      compareIdentifiers(this.patch, other.patch)
	    )
	  }

	  comparePre (other) {
	    if (!(other instanceof SemVer)) {
	      other = new SemVer(other, this.options);
	    }

	    // NOT having a prerelease is > having one
	    if (this.prerelease.length && !other.prerelease.length) {
	      return -1
	    } else if (!this.prerelease.length && other.prerelease.length) {
	      return 1
	    } else if (!this.prerelease.length && !other.prerelease.length) {
	      return 0
	    }

	    let i = 0;
	    do {
	      const a = this.prerelease[i];
	      const b = other.prerelease[i];
	      debug('prerelease compare', i, a, b);
	      if (a === undefined && b === undefined) {
	        return 0
	      } else if (b === undefined) {
	        return 1
	      } else if (a === undefined) {
	        return -1
	      } else if (a === b) {
	        continue
	      } else {
	        return compareIdentifiers(a, b)
	      }
	    } while (++i)
	  }

	  compareBuild (other) {
	    if (!(other instanceof SemVer)) {
	      other = new SemVer(other, this.options);
	    }

	    let i = 0;
	    do {
	      const a = this.build[i];
	      const b = other.build[i];
	      debug('build compare', i, a, b);
	      if (a === undefined && b === undefined) {
	        return 0
	      } else if (b === undefined) {
	        return 1
	      } else if (a === undefined) {
	        return -1
	      } else if (a === b) {
	        continue
	      } else {
	        return compareIdentifiers(a, b)
	      }
	    } while (++i)
	  }

	  // preminor will bump the version up to the next minor release, and immediately
	  // down to pre-release. premajor and prepatch work the same way.
	  inc (release, identifier, identifierBase) {
	    switch (release) {
	      case 'premajor':
	        this.prerelease.length = 0;
	        this.patch = 0;
	        this.minor = 0;
	        this.major++;
	        this.inc('pre', identifier, identifierBase);
	        break
	      case 'preminor':
	        this.prerelease.length = 0;
	        this.patch = 0;
	        this.minor++;
	        this.inc('pre', identifier, identifierBase);
	        break
	      case 'prepatch':
	        // If this is already a prerelease, it will bump to the next version
	        // drop any prereleases that might already exist, since they are not
	        // relevant at this point.
	        this.prerelease.length = 0;
	        this.inc('patch', identifier, identifierBase);
	        this.inc('pre', identifier, identifierBase);
	        break
	      // If the input is a non-prerelease version, this acts the same as
	      // prepatch.
	      case 'prerelease':
	        if (this.prerelease.length === 0) {
	          this.inc('patch', identifier, identifierBase);
	        }
	        this.inc('pre', identifier, identifierBase);
	        break

	      case 'major':
	        // If this is a pre-major version, bump up to the same major version.
	        // Otherwise increment major.
	        // 1.0.0-5 bumps to 1.0.0
	        // 1.1.0 bumps to 2.0.0
	        if (
	          this.minor !== 0 ||
	          this.patch !== 0 ||
	          this.prerelease.length === 0
	        ) {
	          this.major++;
	        }
	        this.minor = 0;
	        this.patch = 0;
	        this.prerelease = [];
	        break
	      case 'minor':
	        // If this is a pre-minor version, bump up to the same minor version.
	        // Otherwise increment minor.
	        // 1.2.0-5 bumps to 1.2.0
	        // 1.2.1 bumps to 1.3.0
	        if (this.patch !== 0 || this.prerelease.length === 0) {
	          this.minor++;
	        }
	        this.patch = 0;
	        this.prerelease = [];
	        break
	      case 'patch':
	        // If this is not a pre-release version, it will increment the patch.
	        // If it is a pre-release it will bump up to the same patch version.
	        // 1.2.0-5 patches to 1.2.0
	        // 1.2.0 patches to 1.2.1
	        if (this.prerelease.length === 0) {
	          this.patch++;
	        }
	        this.prerelease = [];
	        break
	      // This probably shouldn't be used publicly.
	      // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
	      case 'pre': {
	        const base = Number(identifierBase) ? 1 : 0;

	        if (!identifier && identifierBase === false) {
	          throw new Error('invalid increment argument: identifier is empty')
	        }

	        if (this.prerelease.length === 0) {
	          this.prerelease = [base];
	        } else {
	          let i = this.prerelease.length;
	          while (--i >= 0) {
	            if (typeof this.prerelease[i] === 'number') {
	              this.prerelease[i]++;
	              i = -2;
	            }
	          }
	          if (i === -1) {
	            // didn't increment anything
	            if (identifier === this.prerelease.join('.') && identifierBase === false) {
	              throw new Error('invalid increment argument: identifier already exists')
	            }
	            this.prerelease.push(base);
	          }
	        }
	        if (identifier) {
	          // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
	          // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
	          let prerelease = [identifier, base];
	          if (identifierBase === false) {
	            prerelease = [identifier];
	          }
	          if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
	            if (isNaN(this.prerelease[1])) {
	              this.prerelease = prerelease;
	            }
	          } else {
	            this.prerelease = prerelease;
	          }
	        }
	        break
	      }
	      default:
	        throw new Error(`invalid increment argument: ${release}`)
	    }
	    this.raw = this.format();
	    if (this.build.length) {
	      this.raw += `+${this.build.join('.')}`;
	    }
	    return this
	  }
	}

	standalone_semver = SemVer;
	return standalone_semver;
}

var standalone_compare_1;
var standalone_hasRequiredCompare;

function standalone_requireCompare () {
	if (standalone_hasRequiredCompare) return standalone_compare_1;
	standalone_hasRequiredCompare = 1;
	const SemVer = standalone_requireSemver();
	const compare = (a, b, loose) =>
	  new SemVer(a, loose).compare(new SemVer(b, loose));

	standalone_compare_1 = compare;
	return standalone_compare_1;
}

var standalone_eq_1;
var standalone_hasRequiredEq;

function standalone_requireEq () {
	if (standalone_hasRequiredEq) return standalone_eq_1;
	standalone_hasRequiredEq = 1;
	const compare = standalone_requireCompare();
	const eq = (a, b, loose) => compare(a, b, loose) === 0;
	standalone_eq_1 = eq;
	return standalone_eq_1;
}

var standalone_neq_1;
var standalone_hasRequiredNeq;

function standalone_requireNeq () {
	if (standalone_hasRequiredNeq) return standalone_neq_1;
	standalone_hasRequiredNeq = 1;
	const compare = standalone_requireCompare();
	const neq = (a, b, loose) => compare(a, b, loose) !== 0;
	standalone_neq_1 = neq;
	return standalone_neq_1;
}

var standalone_gt_1;
var standalone_hasRequiredGt;

function standalone_requireGt () {
	if (standalone_hasRequiredGt) return standalone_gt_1;
	standalone_hasRequiredGt = 1;
	const compare = standalone_requireCompare();
	const gt = (a, b, loose) => compare(a, b, loose) > 0;
	standalone_gt_1 = gt;
	return standalone_gt_1;
}

var standalone_gte_1;
var standalone_hasRequiredGte;

function standalone_requireGte () {
	if (standalone_hasRequiredGte) return standalone_gte_1;
	standalone_hasRequiredGte = 1;
	const compare = standalone_requireCompare();
	const gte = (a, b, loose) => compare(a, b, loose) >= 0;
	standalone_gte_1 = gte;
	return standalone_gte_1;
}

var standalone_lt_1;
var standalone_hasRequiredLt;

function standalone_requireLt () {
	if (standalone_hasRequiredLt) return standalone_lt_1;
	standalone_hasRequiredLt = 1;
	const compare = standalone_requireCompare();
	const lt = (a, b, loose) => compare(a, b, loose) < 0;
	standalone_lt_1 = lt;
	return standalone_lt_1;
}

var standalone_lte_1;
var standalone_hasRequiredLte;

function standalone_requireLte () {
	if (standalone_hasRequiredLte) return standalone_lte_1;
	standalone_hasRequiredLte = 1;
	const compare = standalone_requireCompare();
	const lte = (a, b, loose) => compare(a, b, loose) <= 0;
	standalone_lte_1 = lte;
	return standalone_lte_1;
}

var standalone_cmp_1;
var standalone_hasRequiredCmp;

function standalone_requireCmp () {
	if (standalone_hasRequiredCmp) return standalone_cmp_1;
	standalone_hasRequiredCmp = 1;
	const eq = standalone_requireEq();
	const neq = standalone_requireNeq();
	const gt = standalone_requireGt();
	const gte = standalone_requireGte();
	const lt = standalone_requireLt();
	const lte = standalone_requireLte();

	const cmp = (a, op, b, loose) => {
	  switch (op) {
	    case '===':
	      if (typeof a === 'object') {
	        a = a.version;
	      }
	      if (typeof b === 'object') {
	        b = b.version;
	      }
	      return a === b

	    case '!==':
	      if (typeof a === 'object') {
	        a = a.version;
	      }
	      if (typeof b === 'object') {
	        b = b.version;
	      }
	      return a !== b

	    case '':
	    case '=':
	    case '==':
	      return eq(a, b, loose)

	    case '!=':
	      return neq(a, b, loose)

	    case '>':
	      return gt(a, b, loose)

	    case '>=':
	      return gte(a, b, loose)

	    case '<':
	      return lt(a, b, loose)

	    case '<=':
	      return lte(a, b, loose)

	    default:
	      throw new TypeError(`Invalid operator: ${op}`)
	  }
	};
	standalone_cmp_1 = cmp;
	return standalone_cmp_1;
}

var standalone_vega_embed_module_comparator;
var standalone_hasRequiredComparator;

function standalone_requireComparator () {
	if (standalone_hasRequiredComparator) return standalone_vega_embed_module_comparator;
	standalone_hasRequiredComparator = 1;
	const ANY = Symbol('SemVer ANY');
	// hoisted class for cyclic dependency
	class Comparator {
	  static get ANY () {
	    return ANY
	  }

	  constructor (comp, options) {
	    options = parseOptions(options);

	    if (comp instanceof Comparator) {
	      if (comp.loose === !!options.loose) {
	        return comp
	      } else {
	        comp = comp.value;
	      }
	    }

	    comp = comp.trim().split(/\s+/).join(' ');
	    debug('comparator', comp, options);
	    this.options = options;
	    this.loose = !!options.loose;
	    this.parse(comp);

	    if (this.semver === ANY) {
	      this.value = '';
	    } else {
	      this.value = this.operator + this.semver.version;
	    }

	    debug('comp', this);
	  }

	  parse (comp) {
	    const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
	    const m = comp.match(r);

	    if (!m) {
	      throw new TypeError(`Invalid comparator: ${comp}`)
	    }

	    this.operator = m[1] !== undefined ? m[1] : '';
	    if (this.operator === '=') {
	      this.operator = '';
	    }

	    // if it literally is just '>' or '' then allow anything.
	    if (!m[2]) {
	      this.semver = ANY;
	    } else {
	      this.semver = new SemVer(m[2], this.options.loose);
	    }
	  }

	  toString () {
	    return this.value
	  }

	  test (version) {
	    debug('Comparator.test', version, this.options.loose);

	    if (this.semver === ANY || version === ANY) {
	      return true
	    }

	    if (typeof version === 'string') {
	      try {
	        version = new SemVer(version, this.options);
	      } catch (er) {
	        return false
	      }
	    }

	    return cmp(version, this.operator, this.semver, this.options)
	  }

	  intersects (comp, options) {
	    if (!(comp instanceof Comparator)) {
	      throw new TypeError('a Comparator is required')
	    }

	    if (this.operator === '') {
	      if (this.value === '') {
	        return true
	      }
	      return new Range(comp.value, options).test(this.value)
	    } else if (comp.operator === '') {
	      if (comp.value === '') {
	        return true
	      }
	      return new Range(this.value, options).test(comp.semver)
	    }

	    options = parseOptions(options);

	    // Special cases where nothing can possibly be lower
	    if (options.includePrerelease &&
	      (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
	      return false
	    }
	    if (!options.includePrerelease &&
	      (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
	      return false
	    }

	    // Same direction increasing (> or >=)
	    if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
	      return true
	    }
	    // Same direction decreasing (< or <=)
	    if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
	      return true
	    }
	    // same SemVer and both sides are inclusive (<= or >=)
	    if (
	      (this.semver.version === comp.semver.version) &&
	      this.operator.includes('=') && comp.operator.includes('=')) {
	      return true
	    }
	    // opposite directions less than
	    if (cmp(this.semver, '<', comp.semver, options) &&
	      this.operator.startsWith('>') && comp.operator.startsWith('<')) {
	      return true
	    }
	    // opposite directions greater than
	    if (cmp(this.semver, '>', comp.semver, options) &&
	      this.operator.startsWith('<') && comp.operator.startsWith('>')) {
	      return true
	    }
	    return false
	  }
	}

	standalone_vega_embed_module_comparator = Comparator;

	const parseOptions = standalone_requireParseOptions();
	const { safeRe: re, t } = standalone_requireRe();
	const cmp = standalone_requireCmp();
	const debug = standalone_requireDebug();
	const SemVer = standalone_requireSemver();
	const Range = standalone_requireRange();
	return standalone_vega_embed_module_comparator;
}

var standalone_vega_embed_module_range;
var standalone_hasRequiredRange;

function standalone_requireRange () {
	if (standalone_hasRequiredRange) return standalone_vega_embed_module_range;
	standalone_hasRequiredRange = 1;
	const SPACE_CHARACTERS = /\s+/g;

	// hoisted class for cyclic dependency
	class Range {
	  constructor (range, options) {
	    options = parseOptions(options);

	    if (range instanceof Range) {
	      if (
	        range.loose === !!options.loose &&
	        range.includePrerelease === !!options.includePrerelease
	      ) {
	        return range
	      } else {
	        return new Range(range.raw, options)
	      }
	    }

	    if (range instanceof Comparator) {
	      // just put it in the set and return
	      this.raw = range.value;
	      this.set = [[range]];
	      this.formatted = undefined;
	      return this
	    }

	    this.options = options;
	    this.loose = !!options.loose;
	    this.includePrerelease = !!options.includePrerelease;

	    // First reduce all whitespace as much as possible so we do not have to rely
	    // on potentially slow regexes like \s*. This is then stored and used for
	    // future error messages as well.
	    this.raw = range.trim().replace(SPACE_CHARACTERS, ' ');

	    // First, split on ||
	    this.set = this.raw
	      .split('||')
	      // map the range to a 2d array of comparators
	      .map(r => this.parseRange(r.trim()))
	      // throw out any comparator lists that are empty
	      // this generally means that it was not a valid range, which is allowed
	      // in loose mode, but will still throw if the WHOLE range is invalid.
	      .filter(c => c.length);

	    if (!this.set.length) {
	      throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
	    }

	    // if we have any that are not the null set, throw out null sets.
	    if (this.set.length > 1) {
	      // keep the first one, in case they're all null sets
	      const first = this.set[0];
	      this.set = this.set.filter(c => !isNullSet(c[0]));
	      if (this.set.length === 0) {
	        this.set = [first];
	      } else if (this.set.length > 1) {
	        // if we have any that are *, then the range is just *
	        for (const c of this.set) {
	          if (c.length === 1 && isAny(c[0])) {
	            this.set = [c];
	            break
	          }
	        }
	      }
	    }

	    this.formatted = undefined;
	  }

	  get range () {
	    if (this.formatted === undefined) {
	      this.formatted = '';
	      for (let i = 0; i < this.set.length; i++) {
	        if (i > 0) {
	          this.formatted += '||';
	        }
	        const comps = this.set[i];
	        for (let k = 0; k < comps.length; k++) {
	          if (k > 0) {
	            this.formatted += ' ';
	          }
	          this.formatted += comps[k].toString().trim();
	        }
	      }
	    }
	    return this.formatted
	  }

	  format () {
	    return this.range
	  }

	  toString () {
	    return this.range
	  }

	  parseRange (range) {
	    // memoize range parsing for performance.
	    // this is a very hot path, and fully deterministic.
	    const memoOpts =
	      (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
	      (this.options.loose && FLAG_LOOSE);
	    const memoKey = memoOpts + ':' + range;
	    const cached = cache.get(memoKey);
	    if (cached) {
	      return cached
	    }

	    const loose = this.options.loose;
	    // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
	    const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
	    range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
	    debug('hyphen replace', range);

	    // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
	    range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
	    debug('comparator trim', range);

	    // `~ 1.2.3` => `~1.2.3`
	    range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
	    debug('tilde trim', range);

	    // `^ 1.2.3` => `^1.2.3`
	    range = range.replace(re[t.CARETTRIM], caretTrimReplace);
	    debug('caret trim', range);

	    // At this point, the range is completely trimmed and
	    // ready to be split into comparators.

	    let rangeList = range
	      .split(' ')
	      .map(comp => parseComparator(comp, this.options))
	      .join(' ')
	      .split(/\s+/)
	      // >=0.0.0 is equivalent to *
	      .map(comp => replaceGTE0(comp, this.options));

	    if (loose) {
	      // in loose mode, throw out any that are not valid comparators
	      rangeList = rangeList.filter(comp => {
	        debug('loose invalid filter', comp, this.options);
	        return !!comp.match(re[t.COMPARATORLOOSE])
	      });
	    }
	    debug('range list', rangeList);

	    // if any comparators are the null set, then replace with JUST null set
	    // if more than one comparator, remove any * comparators
	    // also, don't include the same comparator more than once
	    const rangeMap = new Map();
	    const comparators = rangeList.map(comp => new Comparator(comp, this.options));
	    for (const comp of comparators) {
	      if (isNullSet(comp)) {
	        return [comp]
	      }
	      rangeMap.set(comp.value, comp);
	    }
	    if (rangeMap.size > 1 && rangeMap.has('')) {
	      rangeMap.delete('');
	    }

	    const result = [...rangeMap.values()];
	    cache.set(memoKey, result);
	    return result
	  }

	  intersects (range, options) {
	    if (!(range instanceof Range)) {
	      throw new TypeError('a Range is required')
	    }

	    return this.set.some((thisComparators) => {
	      return (
	        isSatisfiable(thisComparators, options) &&
	        range.set.some((rangeComparators) => {
	          return (
	            isSatisfiable(rangeComparators, options) &&
	            thisComparators.every((thisComparator) => {
	              return rangeComparators.every((rangeComparator) => {
	                return thisComparator.intersects(rangeComparator, options)
	              })
	            })
	          )
	        })
	      )
	    })
	  }

	  // if ANY of the sets match ALL of its comparators, then pass
	  test (version) {
	    if (!version) {
	      return false
	    }

	    if (typeof version === 'string') {
	      try {
	        version = new SemVer(version, this.options);
	      } catch (er) {
	        return false
	      }
	    }

	    for (let i = 0; i < this.set.length; i++) {
	      if (testSet(this.set[i], version, this.options)) {
	        return true
	      }
	    }
	    return false
	  }
	}

	standalone_vega_embed_module_range = Range;

	const LRU = standalone_requireLrucache();
	const cache = new LRU();

	const parseOptions = standalone_requireParseOptions();
	const Comparator = standalone_requireComparator();
	const debug = standalone_requireDebug();
	const SemVer = standalone_requireSemver();
	const {
	  safeRe: re,
	  t,
	  comparatorTrimReplace,
	  tildeTrimReplace,
	  caretTrimReplace,
	} = standalone_requireRe();
	const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = standalone_requireConstants();

	const isNullSet = c => c.value === '<0.0.0-0';
	const isAny = c => c.value === '';

	// take a set of comparators and determine whether there
	// exists a version which can satisfy it
	const isSatisfiable = (comparators, options) => {
	  let result = true;
	  const remainingComparators = comparators.slice();
	  let testComparator = remainingComparators.pop();

	  while (result && remainingComparators.length) {
	    result = remainingComparators.every((otherComparator) => {
	      return testComparator.intersects(otherComparator, options)
	    });

	    testComparator = remainingComparators.pop();
	  }

	  return result
	};

	// comprised of xranges, tildes, stars, and gtlt's at this point.
	// already replaced the hyphen ranges
	// turn into a set of JUST comparators.
	const parseComparator = (comp, options) => {
	  debug('comp', comp, options);
	  comp = replaceCarets(comp, options);
	  debug('caret', comp);
	  comp = replaceTildes(comp, options);
	  debug('tildes', comp);
	  comp = replaceXRanges(comp, options);
	  debug('xrange', comp);
	  comp = replaceStars(comp, options);
	  debug('stars', comp);
	  return comp
	};

	const isX = id => !id || id.toLowerCase() === 'x' || id === '*';

	// ~, ~> --> * (any, kinda silly)
	// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
	// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
	// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
	// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
	// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
	// ~0.0.1 --> >=0.0.1 <0.1.0-0
	const replaceTildes = (comp, options) => {
	  return comp
	    .trim()
	    .split(/\s+/)
	    .map((c) => replaceTilde(c, options))
	    .join(' ')
	};

	const replaceTilde = (comp, options) => {
	  const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
	  return comp.replace(r, (_, M, m, p, pr) => {
	    debug('tilde', comp, _, M, m, p, pr);
	    let ret;

	    if (isX(M)) {
	      ret = '';
	    } else if (isX(m)) {
	      ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
	    } else if (isX(p)) {
	      // ~1.2 == >=1.2.0 <1.3.0-0
	      ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
	    } else if (pr) {
	      debug('replaceTilde pr', pr);
	      ret = `>=${M}.${m}.${p}-${pr
	      } <${M}.${+m + 1}.0-0`;
	    } else {
	      // ~1.2.3 == >=1.2.3 <1.3.0-0
	      ret = `>=${M}.${m}.${p
	      } <${M}.${+m + 1}.0-0`;
	    }

	    debug('tilde return', ret);
	    return ret
	  })
	};

	// ^ --> * (any, kinda silly)
	// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
	// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
	// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
	// ^1.2.3 --> >=1.2.3 <2.0.0-0
	// ^1.2.0 --> >=1.2.0 <2.0.0-0
	// ^0.0.1 --> >=0.0.1 <0.0.2-0
	// ^0.1.0 --> >=0.1.0 <0.2.0-0
	const replaceCarets = (comp, options) => {
	  return comp
	    .trim()
	    .split(/\s+/)
	    .map((c) => replaceCaret(c, options))
	    .join(' ')
	};

	const replaceCaret = (comp, options) => {
	  debug('caret', comp, options);
	  const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
	  const z = options.includePrerelease ? '-0' : '';
	  return comp.replace(r, (_, M, m, p, pr) => {
	    debug('caret', comp, _, M, m, p, pr);
	    let ret;

	    if (isX(M)) {
	      ret = '';
	    } else if (isX(m)) {
	      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
	    } else if (isX(p)) {
	      if (M === '0') {
	        ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
	      } else {
	        ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
	      }
	    } else if (pr) {
	      debug('replaceCaret pr', pr);
	      if (M === '0') {
	        if (m === '0') {
	          ret = `>=${M}.${m}.${p}-${pr
	          } <${M}.${m}.${+p + 1}-0`;
	        } else {
	          ret = `>=${M}.${m}.${p}-${pr
	          } <${M}.${+m + 1}.0-0`;
	        }
	      } else {
	        ret = `>=${M}.${m}.${p}-${pr
	        } <${+M + 1}.0.0-0`;
	      }
	    } else {
	      debug('no pr');
	      if (M === '0') {
	        if (m === '0') {
	          ret = `>=${M}.${m}.${p
	          }${z} <${M}.${m}.${+p + 1}-0`;
	        } else {
	          ret = `>=${M}.${m}.${p
	          }${z} <${M}.${+m + 1}.0-0`;
	        }
	      } else {
	        ret = `>=${M}.${m}.${p
	        } <${+M + 1}.0.0-0`;
	      }
	    }

	    debug('caret return', ret);
	    return ret
	  })
	};

	const replaceXRanges = (comp, options) => {
	  debug('replaceXRanges', comp, options);
	  return comp
	    .split(/\s+/)
	    .map((c) => replaceXRange(c, options))
	    .join(' ')
	};

	const replaceXRange = (comp, options) => {
	  comp = comp.trim();
	  const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
	  return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
	    debug('xRange', comp, ret, gtlt, M, m, p, pr);
	    const xM = isX(M);
	    const xm = xM || isX(m);
	    const xp = xm || isX(p);
	    const anyX = xp;

	    if (gtlt === '=' && anyX) {
	      gtlt = '';
	    }

	    // if we're including prereleases in the match, then we need
	    // to fix this to -0, the lowest possible prerelease value
	    pr = options.includePrerelease ? '-0' : '';

	    if (xM) {
	      if (gtlt === '>' || gtlt === '<') {
	        // nothing is allowed
	        ret = '<0.0.0-0';
	      } else {
	        // nothing is forbidden
	        ret = '*';
	      }
	    } else if (gtlt && anyX) {
	      // we know patch is an x, because we have any x at all.
	      // replace X with 0
	      if (xm) {
	        m = 0;
	      }
	      p = 0;

	      if (gtlt === '>') {
	        // >1 => >=2.0.0
	        // >1.2 => >=1.3.0
	        gtlt = '>=';
	        if (xm) {
	          M = +M + 1;
	          m = 0;
	          p = 0;
	        } else {
	          m = +m + 1;
	          p = 0;
	        }
	      } else if (gtlt === '<=') {
	        // <=0.7.x is actually <0.8.0, since any 0.7.x should
	        // pass.  Similarly, <=7.x is actually <8.0.0, etc.
	        gtlt = '<';
	        if (xm) {
	          M = +M + 1;
	        } else {
	          m = +m + 1;
	        }
	      }

	      if (gtlt === '<') {
	        pr = '-0';
	      }

	      ret = `${gtlt + M}.${m}.${p}${pr}`;
	    } else if (xm) {
	      ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
	    } else if (xp) {
	      ret = `>=${M}.${m}.0${pr
	      } <${M}.${+m + 1}.0-0`;
	    }

	    debug('xRange return', ret);

	    return ret
	  })
	};

	// Because * is AND-ed with everything else in the comparator,
	// and '' means "any version", just remove the *s entirely.
	const replaceStars = (comp, options) => {
	  debug('replaceStars', comp, options);
	  // Looseness is ignored here.  star is always as loose as it gets!
	  return comp
	    .trim()
	    .replace(re[t.STAR], '')
	};

	const replaceGTE0 = (comp, options) => {
	  debug('replaceGTE0', comp, options);
	  return comp
	    .trim()
	    .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
	};

	// This function is passed to string.replace(re[t.HYPHENRANGE])
	// M, m, patch, prerelease, build
	// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
	// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
	// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
	// TODO build?
	const hyphenReplace = incPr => ($0,
	  from, fM, fm, fp, fpr, fb,
	  to, tM, tm, tp, tpr) => {
	  if (isX(fM)) {
	    from = '';
	  } else if (isX(fm)) {
	    from = `>=${fM}.0.0${incPr ? '-0' : ''}`;
	  } else if (isX(fp)) {
	    from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`;
	  } else if (fpr) {
	    from = `>=${from}`;
	  } else {
	    from = `>=${from}${incPr ? '-0' : ''}`;
	  }

	  if (isX(tM)) {
	    to = '';
	  } else if (isX(tm)) {
	    to = `<${+tM + 1}.0.0-0`;
	  } else if (isX(tp)) {
	    to = `<${tM}.${+tm + 1}.0-0`;
	  } else if (tpr) {
	    to = `<=${tM}.${tm}.${tp}-${tpr}`;
	  } else if (incPr) {
	    to = `<${tM}.${tm}.${+tp + 1}-0`;
	  } else {
	    to = `<=${to}`;
	  }

	  return `${from} ${to}`.trim()
	};

	const testSet = (set, version, options) => {
	  for (let i = 0; i < set.length; i++) {
	    if (!set[i].test(version)) {
	      return false
	    }
	  }

	  if (version.prerelease.length && !options.includePrerelease) {
	    // Find the set of versions that are allowed to have prereleases
	    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
	    // That should allow `1.2.3-pr.2` to pass.
	    // However, `1.2.4-alpha.notready` should NOT be allowed,
	    // even though it's within the range set by the comparators.
	    for (let i = 0; i < set.length; i++) {
	      debug(set[i].semver);
	      if (set[i].semver === Comparator.ANY) {
	        continue
	      }

	      if (set[i].semver.prerelease.length > 0) {
	        const allowed = set[i].semver;
	        if (allowed.major === version.major &&
	            allowed.minor === version.minor &&
	            allowed.patch === version.patch) {
	          return true
	        }
	      }
	    }

	    // Version has a -pre, but it's not one of the ones we like.
	    return false
	  }

	  return true
	};
	return standalone_vega_embed_module_range;
}

var standalone_satisfies_1;
var standalone_hasRequiredSatisfies;

function standalone_requireSatisfies () {
	if (standalone_hasRequiredSatisfies) return standalone_satisfies_1;
	standalone_hasRequiredSatisfies = 1;
	const Range = standalone_requireRange();
	const satisfies = (version, range, options) => {
	  try {
	    range = new Range(range, options);
	  } catch (er) {
	    return false
	  }
	  return range.test(version)
	};
	standalone_satisfies_1 = satisfies;
	return standalone_satisfies_1;
}

var standalone_satisfiesExports = standalone_requireSatisfies();
var standalone_satisfies = /*@__PURE__*/standalone_getDefaultExportFromCjs(standalone_satisfiesExports);

/**
 * Open editor url in a new window, and pass a message.
 */
function standalone_post (window, url, data) {
    const editor = window.open(url);
    const wait = 10000;
    const step = 250;
    const { origin } = new URL(url);
    let count = ~~(wait / step);
    function listen(evt) {
        if (evt.source === editor) {
            count = 0;
            window.removeEventListener('message', listen, false);
        }
    }
    window.addEventListener('message', listen, false);
    // send message
    // periodically resend until ack received or timeout
    function send() {
        if (count <= 0) {
            return;
        }
        editor.postMessage(data, origin);
        setTimeout(send, step);
        count -= 1;
    }
    setTimeout(send, step);
}

// generated with build-style.sh
var standalone_embedStyle = `.vega-embed {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
}
.vega-embed.has-actions {
  padding-right: 38px;
}
.vega-embed details:not([open]) > :not(summary) {
  display: none !important;
}
.vega-embed summary {
  list-style: none;
  position: absolute;
  top: 0;
  right: 0;
  padding: 6px;
  z-index: 1000;
  background: white;
  box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
  color: #1b1e23;
  border: 1px solid #aaa;
  border-radius: 999px;
  opacity: 0.2;
  transition: opacity 0.4s ease-in;
  cursor: pointer;
  line-height: 0px;
}
.vega-embed summary::-webkit-details-marker {
  display: none;
}
.vega-embed summary:active {
  box-shadow: #aaa 0px 0px 0px 1px inset;
}
.vega-embed summary svg {
  width: 14px;
  height: 14px;
}
.vega-embed details[open] summary {
  opacity: 0.7;
}
.vega-embed:hover summary, .vega-embed:focus-within summary {
  opacity: 1 !important;
  transition: opacity 0.2s ease;
}
.vega-embed .vega-actions {
  position: absolute;
  z-index: 1001;
  top: 35px;
  right: -9px;
  display: flex;
  flex-direction: column;
  padding-bottom: 8px;
  padding-top: 8px;
  border-radius: 4px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.2);
  border: 1px solid #d9d9d9;
  background: white;
  animation-duration: 0.15s;
  animation-name: scale-in;
  animation-timing-function: cubic-bezier(0.2, 0, 0.13, 1.5);
  text-align: left;
}
.vega-embed .vega-actions a {
  padding: 8px 16px;
  font-family: sans-serif;
  font-size: 14px;
  font-weight: 600;
  white-space: nowrap;
  color: #434a56;
  text-decoration: none;
}
.vega-embed .vega-actions a:hover, .vega-embed .vega-actions a:focus {
  background-color: #f7f7f9;
  color: black;
}
.vega-embed .vega-actions::before, .vega-embed .vega-actions::after {
  content: "";
  display: inline-block;
  position: absolute;
}
.vega-embed .vega-actions::before {
  left: auto;
  right: 14px;
  top: -16px;
  border: 8px solid rgba(0, 0, 0, 0);
  border-bottom-color: #d9d9d9;
}
.vega-embed .vega-actions::after {
  left: auto;
  right: 15px;
  top: -14px;
  border: 7px solid rgba(0, 0, 0, 0);
  border-bottom-color: #fff;
}
.vega-embed .chart-wrapper.fit-x {
  width: 100%;
}
.vega-embed .chart-wrapper.fit-y {
  height: 100%;
}

.vega-embed-wrapper {
  max-width: 100%;
  overflow: auto;
  padding-right: 14px;
}

@keyframes scale-in {
  from {
    opacity: 0;
    transform: scale(0.6);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
`;

function standalone_vega_embed_module_mergeDeep(dest, ...src) {
    for (const s of src) {
        standalone_vega_embed_module_deepMerge_(dest, s);
    }
    return dest;
}
function standalone_vega_embed_module_deepMerge_(dest, src) {
    for (const property of Object.keys(src)) {
        standalone_writeConfig(dest, property, src[property], true);
    }
}

var standalone_vega_embed_module_name = "vega-embed";
var standalone_vega_embed_module_version$1 = "6.29.0";
var standalone_vega_embed_module_description = "Publish Vega visualizations as embedded web components.";
var standalone_vega_embed_module_keywords = [
	"vega",
	"data",
	"visualization",
	"component",
	"embed"
];
var standalone_vega_embed_module_repository = {
	type: "git",
	url: "http://github.com/vega/vega-embed.git"
};
var standalone_vega_embed_module_author = {
	name: "UW Interactive Data Lab",
	url: "http://idl.cs.washington.edu"
};
var standalone_vega_embed_module_contributors = [
	{
		name: "Dominik Moritz",
		url: "https://www.domoritz.de"
	}
];
var standalone_vega_embed_module_bugs = {
	url: "https://github.com/vega/vega-embed/issues"
};
var standalone_vega_embed_module_homepage = "https://github.com/vega/vega-embed#readme";
var standalone_vega_embed_module_license = "BSD-3-Clause";
var standalone_vega_embed_module_main = "build/vega-embed.js";
var standalone_vega_embed_module_module = "build/vega-embed.module.js";
var standalone_vega_embed_module_unpkg = "build/vega-embed.min.js";
var standalone_vega_embed_module_jsdelivr = "build/vega-embed.min.js";
var standalone_vega_embed_module_types = "build/src/embed.d.ts";
var standalone_vega_embed_module_files = [
	"src",
	"build"
];
var standalone_vega_embed_module_exports = {
	".": {
		"import": {
			types: "./build/src/embed.d.ts",
			"default": "./build/vega-embed.module.js"
		},
		require: {
			"default": "./build/vega-embed.js"
		}
	}
};
var standalone_vega_embed_module_devDependencies = {
	"@babel/core": "^7.26.0",
	"@babel/eslint-parser": "^7.25.9",
	"@babel/plugin-syntax-dynamic-import": "^7.8.3",
	"@babel/plugin-transform-runtime": "^7.25.9",
	"@babel/preset-env": "^7.26.0",
	"@babel/preset-typescript": "^7.26.0",
	"@release-it/conventional-changelog": "^9.0.3",
	"@rollup/plugin-commonjs": "28.0.1",
	"@rollup/plugin-json": "^6.1.0",
	"@rollup/plugin-node-resolve": "^15.3.0",
	"@rollup/plugin-terser": "^0.4.4",
	"@rollup/plugin-typescript": "^12.1.1",
	"@types/semver": "^7.5.8",
	"@typescript-eslint/parser": "^8.15.0",
	"@vitest/coverage-istanbul": "^2.1.5",
	"browser-sync": "^3.0.3",
	concurrently: "^9.1.0",
	"del-cli": "^6.0.0",
	"eslint-config-prettier": "^9.1.0",
	"eslint-plugin-prettier": "^5.2.1",
	"eslint-plugin-vitest": "^0.5.4",
	eslint: "^9.15.0",
	jsdom: "^25.0.1",
	"postinstall-postinstall": "^2.1.0",
	prettier: "^3.3.3",
	"release-it": "^17.10.0",
	"rollup-plugin-bundle-size": "^1.0.3",
	rollup: "4.27.3",
	sass: "^1.81.0",
	"typescript-eslint": "^8.15.0",
	typescript: "^5.6.3",
	"vega-lite": "^5.21.0",
	vega: "^5.30.0",
	"vitest-canvas-mock": "^0.3.3",
	vitest: "^2.1.5"
};
var standalone_vega_embed_module_peerDependencies = {
	vega: "^5.21.0",
	"vega-lite": "*"
};
var standalone_vega_embed_module_dependencies = {
	"fast-json-patch": "^3.1.1",
	"json-stringify-pretty-compact": "^4.0.0",
	semver: "^7.6.3",
	tslib: "^2.8.1",
	"vega-interpreter": "^1.0.5",
	"vega-schema-url-parser": "^2.2.0",
	"vega-themes": "^2.15.0",
	"vega-tooltip": "^0.35.2"
};
var standalone_vega_embed_module_scripts = {
	prebuild: "npm run clean && npm run build:style",
	build: "rollup -c",
	"build:style": "./build-style.sh",
	clean: "del-cli build src/style.ts",
	prepublishOnly: "npm run clean && npm run build",
	preversion: "npm run lint && npm run test",
	serve: "browser-sync start --directory -s -f build *.html",
	start: "npm run build && concurrently --kill-others -n Server,Rollup 'npm run serve' 'rollup -c -w'",
	pretest: "npm run build:style",
	test: "vitest run",
	prettierbase: "prettier '*.{css,scss,html}'",
	format: "eslint . --fix && npm run prettierbase -- --write",
	lint: "eslint . && npm run prettierbase -- --check",
	release: "release-it"
};
var standalone_vega_embed_module_pkg = {
	name: standalone_vega_embed_module_name,
	version: standalone_vega_embed_module_version$1,
	description: standalone_vega_embed_module_description,
	keywords: standalone_vega_embed_module_keywords,
	repository: standalone_vega_embed_module_repository,
	author: standalone_vega_embed_module_author,
	contributors: standalone_vega_embed_module_contributors,
	bugs: standalone_vega_embed_module_bugs,
	homepage: standalone_vega_embed_module_homepage,
	license: standalone_vega_embed_module_license,
	main: standalone_vega_embed_module_main,
	module: standalone_vega_embed_module_module,
	unpkg: standalone_vega_embed_module_unpkg,
	jsdelivr: standalone_vega_embed_module_jsdelivr,
	types: standalone_vega_embed_module_types,
	files: standalone_vega_embed_module_files,
	exports: standalone_vega_embed_module_exports,
	devDependencies: standalone_vega_embed_module_devDependencies,
	peerDependencies: standalone_vega_embed_module_peerDependencies,
	dependencies: standalone_vega_embed_module_dependencies,
	scripts: standalone_vega_embed_module_scripts
};

const standalone_vega_embed_module_version = standalone_vega_embed_module_pkg.version;
const standalone_vega = standalone_vega_module_namespaceObject;
let standalone_vegaLite = standalone_build_src_namespaceObject;
// For backwards compatibility with Vega-Lite before v4.
const standalone_vega_embed_module_w = (typeof window !== 'undefined' ? window : undefined);
if (standalone_vegaLite === undefined && standalone_vega_embed_module_w?.vl?.compile) {
    standalone_vegaLite = standalone_vega_embed_module_w.vl;
}
const standalone_DEFAULT_ACTIONS = { export: { svg: true, png: true }, source: true, compiled: true, editor: true };
const standalone_I18N = {
    CLICK_TO_VIEW_ACTIONS: 'Click to view actions',
    COMPILED_ACTION: 'View Compiled Vega',
    EDITOR_ACTION: 'Open in Vega Editor',
    PNG_ACTION: 'Save as PNG',
    SOURCE_ACTION: 'View Source',
    SVG_ACTION: 'Save as SVG',
};
const standalone_NAMES = {
    vega: 'Vega',
    'vega-lite': 'Vega-Lite',
};
const standalone_VERSION = {
    vega: standalone_vega.version,
    'vega-lite': standalone_vegaLite ? standalone_vegaLite.version : 'not available',
};
const standalone_PREPROCESSOR = {
    vega: (vgSpec) => vgSpec,
    'vega-lite': (vlSpec, config) => standalone_vegaLite.compile(vlSpec, { config: config }).spec,
};
const standalone_SVG_CIRCLES = `
<svg viewBox="0 0 16 16" fill="currentColor" stroke="none" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
  <circle r="2" cy="8" cx="2"></circle>
  <circle r="2" cy="8" cx="8"></circle>
  <circle r="2" cy="8" cx="14"></circle>
</svg>`;
const standalone_CHART_WRAPPER_CLASS = 'chart-wrapper';
function standalone_isTooltipHandler(h) {
    return typeof h === 'function';
}
function standalone_viewSource(source, sourceHeader, sourceFooter, mode) {
    const header = `<html><head>${sourceHeader}</head><body><pre><code class="json">`;
    const footer = `</code></pre>${sourceFooter}</body></html>`;
    const win = window.open('');
    win.document.write(header + source + footer);
    win.document.title = `${standalone_NAMES[mode]} JSON Source`;
}
/**
 * Try to guess the type of spec.
 *
 * @param spec Vega or Vega-Lite spec.
 */
function standalone_guessMode(spec, providedMode) {
    // Decide mode
    if (spec.$schema) {
        const parsed = standalone_parser_module(spec.$schema);
        if (providedMode && providedMode !== parsed.library) {
            console.warn(`The given visualization spec is written in ${standalone_NAMES[parsed.library]}, but mode argument sets ${standalone_NAMES[providedMode] ?? providedMode}.`);
        }
        const mode = parsed.library;
        if (!standalone_satisfies(standalone_VERSION[mode], `^${parsed.version.slice(1)}`)) {
            console.warn(`The input spec uses ${standalone_NAMES[mode]} ${parsed.version}, but the current version of ${standalone_NAMES[mode]} is v${standalone_VERSION[mode]}.`);
        }
        return mode;
    }
    // try to guess from the provided spec
    if ('mark' in spec ||
        'encoding' in spec ||
        'layer' in spec ||
        'hconcat' in spec ||
        'vconcat' in spec ||
        'facet' in spec ||
        'repeat' in spec) {
        return 'vega-lite';
    }
    if ('marks' in spec || 'signals' in spec || 'scales' in spec || 'axes' in spec) {
        return 'vega';
    }
    return providedMode ?? 'vega';
}
function standalone_isLoader(o) {
    return !!(o && 'load' in o);
}
function standalone_createLoader(opts) {
    return standalone_isLoader(opts) ? opts : standalone_vega.loader(opts);
}
function standalone_embedOptionsFromUsermeta(parsedSpec) {
    const opts = parsedSpec.usermeta?.embedOptions ?? {};
    if (standalone_vega_util_module_isString(opts.defaultStyle)) {
        // we don't allow styles set via usermeta since it would allow injection of logic (we set the style via innerHTML)
        opts.defaultStyle = false;
    }
    return opts;
}
/**
 * Embed a Vega visualization component in a web page. This function returns a promise.
 *
 * @param el        DOM element in which to place component (DOM node or CSS selector).
 * @param spec      String : A URL string from which to load the Vega specification.
 *                  Object : The Vega/Vega-Lite specification as a parsed JSON object.
 * @param opts       A JavaScript object containing options for embedding.
 */
async function standalone_vega_embed_module_embed(el, spec, opts = {}) {
    let parsedSpec;
    let loader;
    if (standalone_vega_util_module_isString(spec)) {
        loader = standalone_createLoader(opts.loader);
        parsedSpec = JSON.parse(await loader.load(spec));
    }
    else {
        parsedSpec = spec;
    }
    const loadedEmbedOptions = standalone_embedOptionsFromUsermeta(parsedSpec);
    const usermetaLoader = loadedEmbedOptions.loader;
    // either create the loader for the first time or create a new loader if the spec has new loader options
    if (!loader || usermetaLoader) {
        loader = standalone_createLoader(opts.loader ?? usermetaLoader);
    }
    const usermetaOpts = await standalone_loadOpts(loadedEmbedOptions, loader);
    const parsedOpts = await standalone_loadOpts(opts, loader);
    const mergedOpts = {
        ...standalone_vega_embed_module_mergeDeep(parsedOpts, usermetaOpts),
        config: standalone_mergeConfig(parsedOpts.config ?? {}, usermetaOpts.config ?? {}),
    };
    return await standalone_embed(el, parsedSpec, mergedOpts, loader);
}
async function standalone_loadOpts(opt, loader) {
    const config = standalone_vega_util_module_isString(opt.config) ? JSON.parse(await loader.load(opt.config)) : (opt.config ?? {});
    const patch = standalone_vega_util_module_isString(opt.patch) ? JSON.parse(await loader.load(opt.patch)) : opt.patch;
    return {
        ...opt,
        ...(patch ? { patch } : {}),
        ...(config ? { config } : {}),
    };
}
function standalone_getRoot(el) {
    const possibleRoot = el.getRootNode ? el.getRootNode() : document;
    return possibleRoot instanceof ShadowRoot
        ? { root: possibleRoot, rootContainer: possibleRoot }
        : { root: document, rootContainer: document.head ?? document.body };
}
async function standalone_embed(el, spec, opts = {}, loader) {
    const config = opts.theme ? standalone_mergeConfig(standalone_vega_themes_module_namespaceObject[opts.theme], opts.config ?? {}) : opts.config;
    const actions = standalone_isBoolean(opts.actions) ? opts.actions : standalone_vega_embed_module_mergeDeep({}, standalone_DEFAULT_ACTIONS, opts.actions ?? {});
    const i18n = { ...standalone_I18N, ...opts.i18n };
    const renderer = opts.renderer ?? 'canvas';
    const logLevel = opts.logLevel ?? standalone_vega.Warn;
    const downloadFileName = opts.downloadFileName ?? 'visualization';
    const element = typeof el === 'string' ? document.querySelector(el) : el;
    if (!element) {
        throw new Error(`${el} does not exist`);
    }
    if (opts.defaultStyle !== false) {
        const ID = 'vega-embed-style';
        const { root, rootContainer } = standalone_getRoot(element);
        if (!root.getElementById(ID)) {
            const style = document.createElement('style');
            style.id = ID;
            style.innerHTML =
                opts.defaultStyle === undefined || opts.defaultStyle === true
                    ? (standalone_embedStyle).toString()
                    : opts.defaultStyle;
            rootContainer.appendChild(style);
        }
    }
    const mode = standalone_guessMode(spec, opts.mode);
    let vgSpec = standalone_PREPROCESSOR[mode](spec, config);
    if (mode === 'vega-lite') {
        if (vgSpec.$schema) {
            const parsed = standalone_parser_module(vgSpec.$schema);
            if (!standalone_satisfies(standalone_VERSION.vega, `^${parsed.version.slice(1)}`)) {
                console.warn(`The compiled spec uses Vega ${parsed.version}, but current version is v${standalone_VERSION.vega}.`);
            }
        }
    }
    element.classList.add('vega-embed');
    if (actions) {
        element.classList.add('has-actions');
    }
    element.innerHTML = ''; // clear container
    let container = element;
    if (actions) {
        const chartWrapper = document.createElement('div');
        chartWrapper.classList.add(standalone_CHART_WRAPPER_CLASS);
        element.appendChild(chartWrapper);
        container = chartWrapper;
    }
    const patch = opts.patch;
    if (patch) {
        vgSpec = patch instanceof Function ? patch(vgSpec) : standalone_applyPatch(vgSpec, patch, true, false).newDocument;
    }
    // Set locale. Note that this is a global setting.
    if (opts.formatLocale) {
        standalone_vega.formatLocale(opts.formatLocale);
    }
    if (opts.timeFormatLocale) {
        standalone_vega.timeFormatLocale(opts.timeFormatLocale);
    }
    // Set custom expression functions
    if (opts.expressionFunctions) {
        for (const name in opts.expressionFunctions) {
            const expressionFunction = opts.expressionFunctions[name];
            if ('fn' in expressionFunction) {
                standalone_vega.expressionFunction(name, expressionFunction.fn, expressionFunction['visitor']);
            }
            else if (expressionFunction instanceof Function) {
                standalone_vega.expressionFunction(name, expressionFunction);
            }
        }
    }
    const { ast } = opts;
    // Do not apply the config to Vega when we have already applied it to Vega-Lite.
    // This call may throw an Error if parsing fails.
    const runtime = standalone_vega.parse(vgSpec, mode === 'vega-lite' ? {} : config, { ast });
    const view = new (opts.viewClass || standalone_vega.View)(runtime, {
        loader,
        logLevel,
        renderer,
        ...(ast ? { expr: standalone_vega.expressionInterpreter ?? opts.expr ?? standalone_vega_interpreter_module_expression } : {}),
    });
    view.addSignalListener('autosize', (_, autosize) => {
        const { type } = autosize;
        if (type == 'fit-x') {
            container.classList.add('fit-x');
            container.classList.remove('fit-y');
        }
        else if (type == 'fit-y') {
            container.classList.remove('fit-x');
            container.classList.add('fit-y');
        }
        else if (type == 'fit') {
            container.classList.add('fit-x', 'fit-y');
        }
        else {
            container.classList.remove('fit-x', 'fit-y');
        }
    });
    if (opts.tooltip !== false) {
        const { loader: loader_, tooltip } = opts;
        const baseURL = loader_ && !standalone_isLoader(loader_) ? loader_?.baseURL : undefined;
        const handler = standalone_isTooltipHandler(tooltip)
            ? tooltip
            : // user provided boolean true or tooltip options
                new standalone_vega_tooltip_module_Handler({ baseURL, ...(tooltip === true ? {} : tooltip) }).call;
        view.tooltip(handler);
    }
    let { hover } = opts;
    if (hover === undefined) {
        hover = mode === 'vega';
    }
    if (hover) {
        const { hoverSet, updateSet } = (typeof hover === 'boolean' ? {} : hover);
        view.hover(hoverSet, updateSet);
    }
    if (opts) {
        if (opts.width != null) {
            view.width(opts.width);
        }
        if (opts.height != null) {
            view.height(opts.height);
        }
        if (opts.padding != null) {
            view.padding(opts.padding);
        }
    }
    await view.initialize(container, opts.bind).runAsync();
    let documentClickHandler;
    if (actions !== false) {
        let wrapper = element;
        if (opts.defaultStyle !== false || opts.forceActionsMenu) {
            const details = document.createElement('details');
            details.title = i18n.CLICK_TO_VIEW_ACTIONS;
            element.append(details);
            wrapper = details;
            const summary = document.createElement('summary');
            summary.innerHTML = standalone_SVG_CIRCLES;
            details.append(summary);
            documentClickHandler = (ev) => {
                if (!details.contains(ev.target)) {
                    details.removeAttribute('open');
                }
            };
            document.addEventListener('click', documentClickHandler);
        }
        const ctrl = document.createElement('div');
        wrapper.append(ctrl);
        ctrl.classList.add('vega-actions');
        // add 'Export' action
        if (actions === true || actions.export !== false) {
            for (const ext of ['svg', 'png']) {
                if (actions === true || actions.export === true || actions.export[ext]) {
                    const i18nExportAction = i18n[`${ext.toUpperCase()}_ACTION`];
                    const exportLink = document.createElement('a');
                    const scaleFactor = standalone_vega_util_module_isObject(opts.scaleFactor) ? opts.scaleFactor[ext] : opts.scaleFactor;
                    exportLink.text = i18nExportAction;
                    exportLink.href = '#';
                    exportLink.target = '_blank';
                    exportLink.download = `${downloadFileName}.${ext}`;
                    // add link on mousedown so that it's correct when the click happens
                    exportLink.addEventListener('mousedown', async function (e) {
                        e.preventDefault();
                        const url = await view.toImageURL(ext, scaleFactor);
                        this.href = url;
                    });
                    ctrl.append(exportLink);
                }
            }
        }
        // add 'View Source' action
        if (actions === true || actions.source !== false) {
            const viewSourceLink = document.createElement('a');
            viewSourceLink.text = i18n.SOURCE_ACTION;
            viewSourceLink.href = '#';
            viewSourceLink.addEventListener('click', function (e) {
                standalone_viewSource(standalone_stringify(spec), opts.sourceHeader ?? '', opts.sourceFooter ?? '', mode);
                e.preventDefault();
            });
            ctrl.append(viewSourceLink);
        }
        // add 'View Compiled' action
        if (mode === 'vega-lite' && (actions === true || actions.compiled !== false)) {
            const compileLink = document.createElement('a');
            compileLink.text = i18n.COMPILED_ACTION;
            compileLink.href = '#';
            compileLink.addEventListener('click', function (e) {
                standalone_viewSource(standalone_stringify(vgSpec), opts.sourceHeader ?? '', opts.sourceFooter ?? '', 'vega');
                e.preventDefault();
            });
            ctrl.append(compileLink);
        }
        // add 'Open in Vega Editor' action
        if (actions === true || actions.editor !== false) {
            const editorUrl = opts.editorUrl ?? 'https://vega.github.io/editor/';
            const editorLink = document.createElement('a');
            editorLink.text = i18n.EDITOR_ACTION;
            editorLink.href = '#';
            editorLink.addEventListener('click', function (e) {
                standalone_post(window, editorUrl, {
                    config: config,
                    mode: patch ? 'vega' : mode,
                    renderer,
                    spec: standalone_stringify(patch ? vgSpec : spec),
                });
                e.preventDefault();
            });
            ctrl.append(editorLink);
        }
    }
    function finalize() {
        if (documentClickHandler) {
            document.removeEventListener('click', documentClickHandler);
        }
        view.finalize();
    }
    return { view, spec, vgSpec, finalize, embedOptions: opts };
}


//# sourceMappingURL=vega-embed.module.js.map

;// ../../node_modules/svelte-vega/dist/constants.js
const standalone_WIDTH_HEIGHT = new Set(["width", "height"]);
//# sourceMappingURL=constants.js.map
// EXTERNAL MODULE: ../../node_modules/fast-deep-equal/index.js
var standalone_fast_deep_equal = __webpack_require__(792);
;// ../../node_modules/svelte-vega/dist/utils.js


function standalone_updateMultipleDatasetsInView(view, data) {
    for (const [name, value] of Object.entries(data)) {
        const getType = {};
        if (value) {
            if (!!value && getType.toString.call(value) === "[object Function]") {
                const parsedValue = value;
                parsedValue(view.data(name));
            }
            else {
                view.change(name, standalone_vega
                    .changeset()
                    .remove(() => true)
                    .insert(value));
            }
        }
    }
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function standalone_shallowEqual(a = {}, b = {}, ignore = new Set()) {
    const aKeys = Object.keys(a);
    const bKeys = Object.keys(b);
    return (a === b ||
        (aKeys.length === bKeys.length &&
            aKeys.filter((k) => !ignore.has(k)).every((key) => a[key] === b[key])));
}
function standalone_removeSignalListenersFromView(view, signalListeners) {
    const signalNames = Object.keys(signalListeners);
    for (const signalName of signalNames) {
        try {
            view.removeSignalListener(signalName, signalListeners[signalName]);
        }
        catch (error) {
            // eslint-disable-next-line no-console
            console.warn("Cannot remove invalid signal listener.", error);
        }
    }
    return signalNames.length > 0;
}
function standalone_addSignalListenersToView(view, signalListeners) {
    const signalNames = Object.keys(signalListeners);
    for (const signalName of signalNames) {
        try {
            view.addSignalListener(signalName, signalListeners[signalName]);
        }
        catch (error) {
            console.warn("Cannot add invalid signal listener.", error);
        }
    }
    return signalNames.length > 0;
}
function standalone_getUniqueFieldNames(specs) {
    return new Set(specs.flatMap((o) => Object.keys(o)));
}
function standalone_computeSpecChanges(newSpec, oldSpec) {
    if (newSpec === oldSpec)
        return false;
    const changes = {
        width: false,
        height: false,
        isExpensive: false,
    };
    const hasWidth = "width" in newSpec || "width" in oldSpec;
    const hasHeight = "height" in newSpec || "height" in oldSpec;
    if (hasWidth &&
        (!("width" in newSpec) ||
            !("width" in oldSpec) ||
            newSpec.width !== oldSpec.width)) {
        if ("width" in newSpec && typeof newSpec.width === "number") {
            changes.width = newSpec.width;
        }
        else {
            changes.isExpensive = true;
        }
    }
    if (hasHeight &&
        (!("height" in newSpec) ||
            !("height" in oldSpec) ||
            newSpec.height !== oldSpec.height)) {
        if ("height" in newSpec && typeof newSpec.height === "number") {
            changes.height = newSpec.height;
        }
        else {
            changes.isExpensive = true;
        }
    }
    const fieldNames = [...standalone_getUniqueFieldNames([newSpec, oldSpec])].filter((f) => f !== "width" && f !== "height");
    if (fieldNames.some((field) => !(field in newSpec) ||
        !(field in oldSpec) ||
        !standalone_fast_deep_equal(newSpec[field], oldSpec[field]))) {
        changes.isExpensive = true;
    }
    return changes.width !== false ||
        changes.height !== false ||
        changes.isExpensive
        ? changes
        : false;
}
function standalone_combineSpecWithDimension(spec, options) {
    const { width, height } = options;
    if (typeof width !== "undefined" && typeof height !== "undefined") {
        return { ...spec, width, height };
    }
    if (typeof width !== "undefined") {
        return { ...spec, width };
    }
    if (typeof height !== "undefined") {
        return { ...spec, height };
    }
    return spec;
}
//# sourceMappingURL=utils.js.map
;// ../../node_modules/svelte-vega/dist/VegaEmbed.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/node_modules/svelte-vega/dist/VegaEmbed.svelte generated by Svelte v3.59.2 */








function standalone_VegaEmbed_svelte_create_fragment(ctx) {
	let div;

	return {
		c() {
			div = standalone_internal_element("div");
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);
			/*div_binding*/ ctx[11](div);
		},
		p: standalone_noop,
		i: standalone_noop,
		o: standalone_noop,
		d(detaching) {
			if (detaching) standalone_detach(div);
			/*div_binding*/ ctx[11](null);
		}
	};
}

function standalone_VegaEmbed_svelte_instance($$self, $$props, $$invalidate) {
	let { options } = $$props;
	let { spec } = $$props;
	let { view } = $$props;
	let { signalListeners = {} } = $$props;
	let { data = {} } = $$props;
	const dispatch = standalone_createEventDispatcher();
	let result = undefined;
	let prevOptions = {};
	let prevSignalListeners = {};
	let prevSpec = {};
	let prevData = {};
	let chartContainer;

	standalone_onDestroy(() => {
		clearView();
	});

	async function createView() {
		clearView();

		try {
			$$invalidate(6, result = await standalone_vega_embed_module_embed(chartContainer, spec, options));
			$$invalidate(1, view = result.view);

			if (standalone_addSignalListenersToView(view, signalListeners)) {
				view.runAsync();
			}

			onNewView(view);
		} catch(e) {
			handleError(e);
		}
	}

	function clearView() {
		if (result) {
			result.finalize();
			$$invalidate(6, result = undefined);
			$$invalidate(1, view = undefined);
		}
	}

	function handleError(error) {
		dispatch("onError", { error });
		console.warn(error);
	}

	function onNewView(view) {
		update();
		dispatch("onNewView", { view });
	}

	async function update() {
		if (data && Object.keys(data).length > 0 && result !== undefined) {
			$$invalidate(1, view = result.view);
			standalone_updateMultipleDatasetsInView(view, data);
			await view.resize().runAsync();
		}
	}

	function div_binding($$value) {
		standalone_binding_callbacks[$$value ? 'unshift' : 'push'](() => {
			chartContainer = $$value;
			$$invalidate(0, chartContainer);
		});
	}

	$$self.$$set = $$props => {
		if ('options' in $$props) $$invalidate(2, options = $$props.options);
		if ('spec' in $$props) $$invalidate(3, spec = $$props.spec);
		if ('view' in $$props) $$invalidate(1, view = $$props.view);
		if ('signalListeners' in $$props) $$invalidate(4, signalListeners = $$props.signalListeners);
		if ('data' in $$props) $$invalidate(5, data = $$props.data);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*data, prevData*/ 1056) {
			$: {
				if (!standalone_shallowEqual(data, prevData)) {
					update();
				}

				$$invalidate(10, prevData = data);
			}
		}

		if ($$self.$$.dirty & /*chartContainer, options, prevOptions, spec, prevSpec, signalListeners, prevSignalListeners, result, view*/ 991) {
			$: {
				if (chartContainer !== undefined) {
					// only create a new view if neccessary
					if (!standalone_shallowEqual(options, prevOptions, standalone_WIDTH_HEIGHT)) {
						createView();
					} else {
						const specChanges = standalone_computeSpecChanges(standalone_combineSpecWithDimension(spec, options), standalone_combineSpecWithDimension(prevSpec, prevOptions));
						const newSignalListeners = signalListeners;
						const oldSignalListeners = prevSignalListeners;

						if (specChanges) {
							if (specChanges.isExpensive) {
								createView();
							} else if (result !== undefined) {
								const areSignalListenersChanged = !standalone_shallowEqual(newSignalListeners, oldSignalListeners);
								$$invalidate(1, view = result.view);

								if (specChanges.width !== false) {
									view.width(specChanges.width);
								}

								if (specChanges.height !== false) {
									view.height(specChanges.height);
								}

								if (areSignalListenersChanged) {
									if (oldSignalListeners) {
										standalone_removeSignalListenersFromView(view, oldSignalListeners);
									}

									if (newSignalListeners) {
										standalone_addSignalListenersToView(view, newSignalListeners);
									}
								}

								view.runAsync();
							}
						} else if (!standalone_shallowEqual(newSignalListeners, oldSignalListeners) && result !== undefined) {
							$$invalidate(1, view = result.view);

							if (oldSignalListeners) {
								standalone_removeSignalListenersFromView(view, oldSignalListeners);
							}

							if (newSignalListeners) {
								standalone_addSignalListenersToView(view, newSignalListeners);
							}

							view.runAsync();
						}
					}

					$$invalidate(7, prevOptions = options);
					$$invalidate(8, prevSignalListeners = signalListeners);
					$$invalidate(9, prevSpec = spec);
				}
			}
		}
	};

	return [
		chartContainer,
		view,
		options,
		spec,
		signalListeners,
		data,
		result,
		prevOptions,
		prevSignalListeners,
		prevSpec,
		prevData,
		div_binding
	];
}

class standalone_VegaEmbed extends standalone_SvelteComponent {
	constructor(options) {
		super();

		standalone_init(this, options, standalone_VegaEmbed_svelte_instance, standalone_VegaEmbed_svelte_create_fragment, standalone_safe_not_equal, {
			options: 2,
			spec: 3,
			view: 1,
			signalListeners: 4,
			data: 5
		});
	}
}

/* harmony default export */ const standalone_VegaEmbed_svelte = (standalone_VegaEmbed);
;// ../../node_modules/svelte-vega/dist/Vega.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/node_modules/svelte-vega/dist/Vega.svelte generated by Svelte v3.59.2 */




function standalone_Vega_svelte_create_fragment(ctx) {
	let vegaembed;
	let updating_view;
	let current;

	function vegaembed_view_binding(value) {
		/*vegaembed_view_binding*/ ctx[6](value);
	}

	let vegaembed_props = {
		spec: /*spec*/ ctx[1],
		data: /*data*/ ctx[2],
		signalListeners: /*signalListeners*/ ctx[3],
		options: /*vegaOptions*/ ctx[4]
	};

	if (/*view*/ ctx[0] !== void 0) {
		vegaembed_props.view = /*view*/ ctx[0];
	}

	vegaembed = new standalone_VegaEmbed_svelte({ props: vegaembed_props });
	standalone_binding_callbacks.push(() => standalone_bind(vegaembed, 'view', vegaembed_view_binding));
	vegaembed.$on("onNewView", /*onNewView_handler*/ ctx[7]);
	vegaembed.$on("onError", /*onError_handler*/ ctx[8]);

	return {
		c() {
			standalone_create_component(vegaembed.$$.fragment);
		},
		m(target, anchor) {
			standalone_mount_component(vegaembed, target, anchor);
			current = true;
		},
		p(ctx, [dirty]) {
			const vegaembed_changes = {};
			if (dirty & /*spec*/ 2) vegaembed_changes.spec = /*spec*/ ctx[1];
			if (dirty & /*data*/ 4) vegaembed_changes.data = /*data*/ ctx[2];
			if (dirty & /*signalListeners*/ 8) vegaembed_changes.signalListeners = /*signalListeners*/ ctx[3];
			if (dirty & /*vegaOptions*/ 16) vegaembed_changes.options = /*vegaOptions*/ ctx[4];

			if (!updating_view && dirty & /*view*/ 1) {
				updating_view = true;
				vegaembed_changes.view = /*view*/ ctx[0];
				standalone_add_flush_callback(() => updating_view = false);
			}

			vegaembed.$set(vegaembed_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(vegaembed.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(vegaembed.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			standalone_destroy_component(vegaembed, detaching);
		}
	};
}

const standalone_mode = "vega";

function standalone_Vega_svelte_instance($$self, $$props, $$invalidate) {
	let vegaOptions;
	let { spec } = $$props;
	let { options = {} } = $$props;
	let { data = {} } = $$props;
	let { signalListeners = {} } = $$props;
	let { view = undefined } = $$props;

	function vegaembed_view_binding(value) {
		view = value;
		$$invalidate(0, view);
	}

	function onNewView_handler(event) {
		standalone_bubble.call(this, $$self, event);
	}

	function onError_handler(event) {
		standalone_bubble.call(this, $$self, event);
	}

	$$self.$$set = $$props => {
		if ('spec' in $$props) $$invalidate(1, spec = $$props.spec);
		if ('options' in $$props) $$invalidate(5, options = $$props.options);
		if ('data' in $$props) $$invalidate(2, data = $$props.data);
		if ('signalListeners' in $$props) $$invalidate(3, signalListeners = $$props.signalListeners);
		if ('view' in $$props) $$invalidate(0, view = $$props.view);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*options*/ 32) {
			$: $$invalidate(4, vegaOptions = { ...options, mode: standalone_mode });
		}
	};

	return [
		view,
		spec,
		data,
		signalListeners,
		vegaOptions,
		options,
		vegaembed_view_binding,
		onNewView_handler,
		onError_handler
	];
}

class standalone_Vega extends standalone_SvelteComponent {
	constructor(options) {
		super();

		standalone_init(this, options, standalone_Vega_svelte_instance, standalone_Vega_svelte_create_fragment, standalone_safe_not_equal, {
			spec: 1,
			options: 5,
			data: 2,
			signalListeners: 3,
			view: 0
		});
	}
}

/* harmony default export */ const standalone_Vega_svelte = ((/* unused pure expression or super */ null && (standalone_Vega)));
;// ../../node_modules/svelte-vega/dist/VegaLite.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/node_modules/svelte-vega/dist/VegaLite.svelte generated by Svelte v3.59.2 */




function standalone_VegaLite_svelte_create_fragment(ctx) {
	let vegaembed;
	let updating_view;
	let current;

	function vegaembed_view_binding(value) {
		/*vegaembed_view_binding*/ ctx[6](value);
	}

	let vegaembed_props = {
		spec: /*spec*/ ctx[1],
		data: /*data*/ ctx[2],
		signalListeners: /*signalListeners*/ ctx[3],
		options: /*vegaLiteOptions*/ ctx[4]
	};

	if (/*view*/ ctx[0] !== void 0) {
		vegaembed_props.view = /*view*/ ctx[0];
	}

	vegaembed = new standalone_VegaEmbed_svelte({ props: vegaembed_props });
	standalone_binding_callbacks.push(() => standalone_bind(vegaembed, 'view', vegaembed_view_binding));
	vegaembed.$on("onNewView", /*onNewView_handler*/ ctx[7]);
	vegaembed.$on("onError", /*onError_handler*/ ctx[8]);

	return {
		c() {
			standalone_create_component(vegaembed.$$.fragment);
		},
		m(target, anchor) {
			standalone_mount_component(vegaembed, target, anchor);
			current = true;
		},
		p(ctx, [dirty]) {
			const vegaembed_changes = {};
			if (dirty & /*spec*/ 2) vegaembed_changes.spec = /*spec*/ ctx[1];
			if (dirty & /*data*/ 4) vegaembed_changes.data = /*data*/ ctx[2];
			if (dirty & /*signalListeners*/ 8) vegaembed_changes.signalListeners = /*signalListeners*/ ctx[3];
			if (dirty & /*vegaLiteOptions*/ 16) vegaembed_changes.options = /*vegaLiteOptions*/ ctx[4];

			if (!updating_view && dirty & /*view*/ 1) {
				updating_view = true;
				vegaembed_changes.view = /*view*/ ctx[0];
				standalone_add_flush_callback(() => updating_view = false);
			}

			vegaembed.$set(vegaembed_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(vegaembed.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(vegaembed.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			standalone_destroy_component(vegaembed, detaching);
		}
	};
}

const standalone_VegaLite_svelte_mode = "vega-lite";

function standalone_VegaLite_svelte_instance($$self, $$props, $$invalidate) {
	let vegaLiteOptions;
	let { spec } = $$props;
	let { options = {} } = $$props;
	let { data = {} } = $$props;
	let { signalListeners = {} } = $$props;
	let { view = undefined } = $$props;

	function vegaembed_view_binding(value) {
		view = value;
		$$invalidate(0, view);
	}

	function onNewView_handler(event) {
		standalone_bubble.call(this, $$self, event);
	}

	function onError_handler(event) {
		standalone_bubble.call(this, $$self, event);
	}

	$$self.$$set = $$props => {
		if ('spec' in $$props) $$invalidate(1, spec = $$props.spec);
		if ('options' in $$props) $$invalidate(5, options = $$props.options);
		if ('data' in $$props) $$invalidate(2, data = $$props.data);
		if ('signalListeners' in $$props) $$invalidate(3, signalListeners = $$props.signalListeners);
		if ('view' in $$props) $$invalidate(0, view = $$props.view);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*options*/ 32) {
			$: $$invalidate(4, vegaLiteOptions = { ...options, mode: standalone_VegaLite_svelte_mode });
		}
	};

	return [
		view,
		spec,
		data,
		signalListeners,
		vegaLiteOptions,
		options,
		vegaembed_view_binding,
		onNewView_handler,
		onError_handler
	];
}

class standalone_VegaLite extends standalone_SvelteComponent {
	constructor(options) {
		super();

		standalone_init(this, options, standalone_VegaLite_svelte_instance, standalone_VegaLite_svelte_create_fragment, standalone_safe_not_equal, {
			spec: 1,
			options: 5,
			data: 2,
			signalListeners: 3,
			view: 0
		});
	}
}

/* harmony default export */ const standalone_VegaLite_svelte = (standalone_VegaLite);
;// ../../node_modules/svelte-vega/dist/index.js



//# sourceMappingURL=index.js.map
;// ../../node_modules/arquero/src/util/is-array.js
/* harmony default export */ const standalone_is_array = (Array.isArray);

;// ../../node_modules/arquero/src/util/to-array.js


/* harmony default export */ function standalone_to_array(value) {
  return value != null
    ? (standalone_is_array(value) ? value : [value])
    : [];
}
;// ../../node_modules/arquero/src/helpers/slice.js
/**
 * Generate a table expression that filters a table based on ordered row
 * indices from start to end (end not included), where start and end
 * represent per-group ordered row numbers in the table. The resulting
 * string can be used as the input to the filter verb.
 * @param {number} [start] Zero-based index at which to start extraction.
 *  A negative index indicates an offset from the end of the group.
 *  If start is undefined, slice starts from the index 0.
 * @param {number} [end] Zero-based index before which to end extraction.
 *  A negative index indicates an offset from the end of the group.
 *  If end is omitted, slice extracts through the end of the group.
 * @return {string} A table expression string for slicing values.
 * @example slice(1, -1)
 */
/* harmony default export */ function standalone_helpers_slice(start = 0, end = Infinity) {
  return `${standalone_prep(start)} < row_number() && row_number() <= ${standalone_prep(end)}`;
}

function standalone_prep(index) {
  return index < 0 ? `count() + ${index}` : index;
}
;// ../../node_modules/arquero/src/table/transformable.js



/**
 * Abstract base class for transforming data.
 */
class standalone_Transformable {

  /**
   * Instantiate a new Transformable instance.
   * @param {Params} [params] The parameter values.
   */
  constructor(params) {
    if (params) this._params = params;
  }

  /**
   * Get or set table expression parameter values.
   * If called with no arguments, returns the current parameter values
   * as an object. Otherwise, adds the provided parameters to this
   * table's parameter set and returns the table. Any prior parameters
   * with names matching the input parameters are overridden.
   * @param {Params} [values] The parameter values.
   * @return {this|Params} The current parameters values (if called with
   *  no arguments) or this table.
   */
  params(values) {
    if (arguments.length) {
      if (values) {
        this._params = { ...this._params, ...values };
      }
      return this;
    } else {
      return this._params;
    }
  }

  /**
   * Create a new fully-materialized instance of this table.
   * All filter and orderby settings are removed from the new table.
   * Instead, the backing data itself is filtered and ordered as needed.
   * @param {number[]} [indices] Ordered row indices to materialize.
   *  If unspecified, all rows passing the table filter are used.
   * @return {this} A reified table.
   */
  reify(indices) {
    return this.__reify(this, indices);
  }

  // -- Transformation Verbs ------------------------------------------------

  /**
   * Count the number of values in a group. This method is a shorthand
   * for {@link Transformable#rollup} with a count aggregate function.
   * @param {CountOptions} [options] Options for the count.
   * @return {this} A new table with groupby and count columns.
   * @example table.groupby('colA').count()
   * @example table.groupby('colA').count({ as: 'num' })
   */
  count(options) {
    return this.__count(this, options);
  }

  /**
   * Derive new column values based on the provided expressions. By default,
   * new columns are added after (higher indices than) existing columns. Use
   * the before or after options to place new columns elsewhere.
   * @param {ExprObject} values Object of name-value pairs defining the
   *  columns to derive. The input object should have output column
   *  names for keys and table expressions for values.
   * @param {DeriveOptions} [options] Options for dropping or relocating
   *  derived columns. Use either a before or after property to indicate
   *  where to place derived columns. Specifying both before and after is an
   *  error. Unlike the relocate verb, this option affects only new columns;
   *  updated columns with existing names are excluded from relocation.
   * @return {this} A new table with derived columns added.
   * @example table.derive({ sumXY: d => d.x + d.y })
   * @example table.derive({ z: d => d.x * d.y }, { before: 'x' })
   */
  derive(values, options) {
    return this.__derive(this, values, options);
  }

  /**
   * Filter a table to a subset of rows based on the input criteria.
   * The resulting table provides a filtered view over the original data; no
   * data copy is made. To create a table that copies only filtered data to
   * new data structures, call {@link Transformable#reify} on the output table.
   * @param {TableExpr} criteria Filter criteria as a table expression.
   *  Both aggregate and window functions are permitted, taking into account
   *  {@link Transformable#groupby} or {@link Transformable#orderby} settings.
   * @return {this} A new table with filtered rows.
   * @example table.filter(d => abs(d.value) < 5)
   */
  filter(criteria) {
    return this.__filter(this, criteria);
  }

  /**
   * Extract rows with indices from start to end (end not included), where
   * start and end represent per-group ordered row numbers in the table.
   * @param {number} [start] Zero-based index at which to start extraction.
   *  A negative index indicates an offset from the end of the group.
   *  If start is undefined, slice starts from the index 0.
   * @param {number} [end] Zero-based index before which to end extraction.
   *  A negative index indicates an offset from the end of the group.
   *  If end is omitted, slice extracts through the end of the group.
   * @return {this} A new table with sliced rows.
   * @example table.slice(1, -1)
   */
  slice(start, end) {
    return this.filter(standalone_helpers_slice(start, end)).reify();
  }

  /**
   * Group table rows based on a set of column values.
   * Subsequent operations that are sensitive to grouping (such as
   * aggregate functions) will operate over the grouped rows.
   * To undo grouping, use {@link Transformable#ungroup}.
   * @param  {...ExprList} keys Key column values to group by.
   *  The keys may be specified using column name strings, column index
   *  numbers, value objects with output column names for keys and table
   *  expressions for values, or selection helper functions.
   * @return {this} A new table with grouped rows.
   * @example table.groupby('colA', 'colB')
   * @example table.groupby({ key: d => d.colA + d.colB })
   */
  groupby(...keys) {
    return this.__groupby(this, keys.flat());
  }

  /**
   * Order table rows based on a set of column values.
   * Subsequent operations sensitive to ordering (such as window functions)
   * will operate over sorted values.
   * The resulting table provides an view over the original data, without
   * any copying. To create a table with sorted data copied to new data
   * strucures, call {@link Transformable#reify} on the result of this method.
   * To undo ordering, use {@link Transformable#unorder}.
   * @param  {...OrderKeys} keys Key values to sort by, in precedence order.
   *  By default, sorting is done in ascending order.
   *  To sort in descending order, wrap values using {@link desc}.
   *  If a string, order by the column with that name.
   *  If a number, order by the column with that index.
   *  If a function, must be a valid table expression; aggregate functions
   *  are permitted, but window functions are not.
   *  If an object, object values must be valid values parameters
   *  with output column names for keys and table expressions
   *  for values (the output names will be ignored).
   *  If an array, array values must be valid key parameters.
   * @return {this} A new ordered table.
   * @example table.orderby('a', desc('b'))
   * @example table.orderby({ a: 'a', b: desc('b') )})
   * @example table.orderby(desc(d => d.a))
   */
  orderby(...keys) {
    return this.__orderby(this, keys.flat());
  }

  /**
   * Relocate a subset of columns to change their positions, also
   * potentially renaming them.
   * @param {Selection} columns An ordered selection of columns to relocate.
   *  The input may consist of column name strings, column integer indices,
   *  rename objects with current column names as keys and new column names
   *  as values, or functions that take a table as input and returns a valid
   *  selection parameter (typically the output of selection helper functions
   *  such as {@link all}, {@link not}, or {@link range}).
   * @param {RelocateOptions} options Options for relocating. Must include
   *  either the before or after property to indicate where to place the
   *  relocated columns. Specifying both before and after is an error.
   * @return {this} A new table with relocated columns.
   * @example table.relocate(['colY', 'colZ'], { after: 'colX' })
   * @example table.relocate(not('colB', 'colC'), { before: 'colA' })
   * @example table.relocate({ colA: 'newA', colB: 'newB' }, { after: 'colC' })
   */
  relocate(columns, options) {
    return this.__relocate(this, standalone_to_array(columns), options);
  }

  /**
   * Rename one or more columns, preserving column order.
   * @param {...Select} columns One or more rename objects with current
   *  column names as keys and new column names as values.
   * @return {this} A new table with renamed columns.
   * @example table.rename({ oldName: 'newName' })
   * @example table.rename({ a: 'a2', b: 'b2' })
   */
  rename(...columns) {
    return this.__rename(this, columns.flat());
  }

  /**
   * Rollup a table to produce an aggregate summary.
   * Often used in conjunction with {@link Transformable#groupby}.
   * To produce counts only, {@link Transformable#count} is a shortcut.
   * @param {ExprObject} [values] Object of name-value pairs defining aggregate
   *  output columns. The input object should have output column names for
   *  keys and table expressions for values. The expressions must be valid
   *  aggregate expressions: window functions are not allowed and column
   *  references must be arguments to aggregate functions.
   * @return {this} A new table of aggregate summary values.
   * @example table.groupby('colA').rollup({ mean: d => mean(d.colB) })
   * @example table.groupby('colA').rollup({ mean: op.median('colB') })
   */
  rollup(values) {
    return this.__rollup(this, values);
  }

  /**
   * Generate a table from a random sample of rows.
   * If the table is grouped, performs a stratified sample by
   * sampling from each group separately.
   * @param {number|TableExpr} size The number of samples to draw per group.
   *  If number-valued, the same sample size is used for each group.
   *  If function-valued, the input should be an aggregate table
   *  expression compatible with {@link Transformable#rollup}.
   * @param {SampleOptions} [options] Options for sampling.
   * @return {this} A new table with sampled rows.
   * @example table.sample(50)
   * @example table.sample(100, { replace: true })
   * @example table.groupby('colA').sample(() => op.floor(0.5 * op.count()))
   */
  sample(size, options) {
    return this.__sample(this, size, options);
  }

  /**
   * Select a subset of columns into a new table, potentially renaming them.
   * @param {...Select} columns An ordered selection of columns.
   *  The input may consist of column name strings, column integer indices,
   *  rename objects with current column names as keys and new column names
   *  as values, or functions that take a table as input and returns a valid
   *  selection parameter (typically the output of selection helper functions
   *  such as {@link all}, {@link not}, or {@link range}).
   * @return {this} A new table of selected columns.
   * @example table.select('colA', 'colB')
   * @example table.select(not('colB', 'colC'))
   * @example table.select({ colA: 'newA', colB: 'newB' })
   */
  select(...columns) {
    return this.__select(this, columns.flat());
  }

  /**
   * Ungroup a table, removing any grouping criteria.
   * Undoes the effects of {@link Transformable#groupby}.
   * @return {this} A new ungrouped table, or this table if not grouped.
   * @example table.ungroup()
   */
  ungroup() {
    return this.__ungroup(this);
  }

  /**
   * Unorder a table, removing any sorting criteria.
   * Undoes the effects of {@link Transformable#orderby}.
   * @return {this} A new unordered table, or this table if not ordered.
   * @example table.unorder()
   */
  unorder() {
    return this.__unorder(this);
  }

  // -- Cleaning Verbs ------------------------------------------------------

  /**
   * De-duplicate table rows by removing repeated row values.
   * @param {...ExprList} keys Key columns to check for duplicates.
   *  Two rows are considered duplicates if they have matching values for
   *  all keys. If keys are unspecified, all columns are used.
   *  The keys may be specified using column name strings, column index
   *  numbers, value objects with output column names for keys and table
   *  expressions for values, or selection helper functions.
   * @return {this} A new de-duplicated table.
   * @example table.dedupe()
   * @example table.dedupe('a', 'b')
   * @example table.dedupe({ abs: d => op.abs(d.a) })
   */
  dedupe(...keys) {
    return this.__dedupe(this, keys.flat());
  }

  /**
   * Impute missing values or rows. Accepts a set of column-expression pairs
   * and evaluates the expressions to replace any missing (null, undefined,
   * or NaN) values in the original column.
   * If the expand option is specified, imputes new rows for missing
   * combinations of values. All combinations of key values (a full cross
   * product) are considered for each level of grouping (specified by
   * {@link Transformable#groupby}). New rows will be added for any combination
   * of key and groupby values not already contained in the table. For all
   * non-key and non-group columns the new rows are populated with imputation
   * values (first argument) if specified, otherwise undefined.
   * If the expand option is specified, any filter or orderby settings are
   * removed from the output table, but groupby settings persist.
   * @param {ExprObject} values Object of name-value pairs for the column values
   *  to impute. The input object should have existing column names for keys
   *  and table expressions for values. The expressions will be evaluated to
   *  determine replacements for any missing values.
   * @param {ImputeOptions} [options] Imputation options. The expand
   *  property specifies a set of column values to consider for imputing
   *  missing rows. All combinations of expanded values are considered, and
   *  new rows are added for each combination that does not appear in the
   *  input table.
   * @return {this} A new table with imputed values and/or rows.
   * @example table.impute({ v: () => 0 })
   * @example table.impute({ v: d => op.mean(d.v) })
   * @example table.impute({ v: () => 0 }, { expand: ['x', 'y'] })
   */
  impute(values, options) {
    return this.__impute(this, values, options);
  }

  // -- Reshaping Verbs -----------------------------------------------------

  /**
   * Fold one or more columns into two key-value pair columns.
   * The fold transform is an inverse of the {@link Transformable#pivot} transform.
   * The resulting table has two new columns, one containing the column
   * names (named "key") and the other the column values (named "value").
   * The number of output rows equals the original row count multiplied
   * by the number of folded columns.
   * @param {ExprList} values The columns to fold.
   *  The columns may be specified using column name strings, column index
   *  numbers, value objects with output column names for keys and table
   *  expressions for values, or selection helper functions.
   * @param {FoldOptions} [options] Options for folding.
   * @return {this} A new folded table.
   * @example table.fold('colA')
   * @example table.fold(['colA', 'colB'])
   * @example table.fold(range(5, 8))
   */
  fold(values, options) {
    return this.__fold(this, values, options);
  }

  /**
   * Pivot columns into a cross-tabulation.
   * The pivot transform is an inverse of the {@link Transformable#fold} transform.
   * The resulting table has new columns for each unique combination
   * of the provided *keys*, populated with the provided *values*.
   * The provided *values* must be aggregates, as a single set of keys may
   * include more than one row. If string-valued, the *any* aggregate is used.
   * If only one *values* column is defined, the new pivoted columns will
   * be named using key values directly. Otherwise, input value column names
   * will be included as a component of the output column names.
   * @param {ExprList} keys Key values to map to new column names.
   *  The keys may be specified using column name strings, column index
   *  numbers, value objects with output column names for keys and table
   *  expressions for values, or selection helper functions.
   * @param {ExprList} values Output values for pivoted columns.
   *  Column references will be wrapped in an *any* aggregate.
   *  If object-valued, the input object should have output value
   *  names for keys and aggregate table expressions for values.
   * @param {PivotOptions} [options] Options for pivoting.
   * @return {this} A new pivoted table.
   * @example table.pivot('key', 'value')
   * @example table.pivot(['keyA', 'keyB'], ['valueA', 'valueB'])
   * @example table.pivot({ key: d => d.key }, { value: d => sum(d.value) })
   */
  pivot(keys, values, options) {
    return this.__pivot(this, keys, values, options);
  }

  /**
   * Spread array elements into a set of new columns.
   * Output columns are named based on the value key and array index.
   * @param {ExprList} values The column values to spread.
   *  The values may be specified using column name strings, column index
   *  numbers, value objects with output column names for keys and table
   *  expressions for values, or selection helper functions.
   * @param {SpreadOptions} [options] Options for spreading.
   * @return {this} A new table with the spread columns added.
   * @example table.spread({ a: split(d.text, '') })
   * @example table.spread('arrayCol', { limit: 100 })
   */
  spread(values, options) {
    return this.__spread(this, values, options);
  }

  /**
   * Unroll one or more array-valued columns into new rows.
   * If more than one array value is used, the number of new rows
   * is the smaller of the limit and the largest length.
   * Values for all other columns are copied over.
   * @param {ExprList} values The column values to unroll.
   *  The values may be specified using column name strings, column index
   *  numbers, value objects with output column names for keys and table
   *  expressions for values, or selection helper functions.
   * @param {UnrollOptions} [options] Options for unrolling.
   * @return {this} A new unrolled table.
   * @example table.unroll('colA', { limit: 1000 })
   */
  unroll(values, options) {
    return this.__unroll(this, values, options);
  }

  // -- Joins ---------------------------------------------------------------

  /**
   * Lookup values from a secondary table and add them as new columns.
   * A lookup occurs upon matching key values for rows in both tables.
   * If the secondary table has multiple rows with the same key, only
   * the last observed instance will be considered in the lookup.
   * Lookup is similar to {@link Transformable#join_left}, but with a simpler
   * syntax and the added constraint of allowing at most one match only.
   * @param {TableRef} other The secondary table to look up values from.
   * @param {JoinKeys} [on] Lookup keys (column name strings or table
   *  expressions) for this table and the secondary table, respectively.
   * @param {...ExprList} values The column values to add from the
   *  secondary table. Can be column name strings or objects with column
   *  names as keys and table expressions as values.
   * @return {this} A new table with lookup values added.
   * @example table.lookup(other, ['key1', 'key2'], 'value1', 'value2')
   */
  lookup(other, on, ...values) {
    return this.__lookup(this, other, on, values.flat());
  }

  /**
   * Join two tables, extending the columns of one table with
   * values from the other table. The current table is considered
   * the "left" table in the join, and the new table input is
   * considered the "right" table in the join. By default an inner
   * join is performed, removing all rows that do not match the
   * join criteria. To perform left, right, or full outer joins, use
   * the {@link Transformable#join_left}, {@link Transformable#join_right}, or
   * {@link Transformable#join_full} methods, or provide an options argument.
   * @param {TableRef} other The other (right) table to join with.
   * @param {JoinPredicate} [on] The join criteria for matching table rows.
   *  If unspecified, the values of all columns with matching names
   *  are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @param {JoinValues} [values] The columns to include in the join output.
   *  If unspecified, all columns from both tables are included; paired
   *  join keys sharing the same column name are included only once.
   *  If array-valued, a two element array should be provided, containing
   *  the columns to include for the left and right tables, respectively.
   *  Array input may consist of column name strings, objects with output
   *  names as keys and single-table table expressions as values, or the
   *  selection helper functions {@link all}, {@link not}, or {@link range}.
   *  If object-valued, specifies the key-value pairs for each output,
   *  defined using two-table table expressions.
   * @param {JoinOptions} [options] Options for the join.
   * @return {this} A new joined table.
   * @example table.join(other, ['keyL', 'keyR'])
   * @example table.join(other, (a, b) => equal(a.keyL, b.keyR))
   */
  join(other, on, values, options) {
    return this.__join(this, other, on, values, options);
  }

  /**
   * Perform a left outer join on two tables. Rows in the left table
   * that do not match a row in the right table will be preserved.
   * This is a convenience method with fixed options for {@link Transformable#join}.
   * @param {TableRef} other The other (right) table to join with.
   * @param {JoinPredicate} [on] The join criteria for matching table rows.
   *  If unspecified, the values of all columns with matching names
   *  are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @param {JoinValues} [values] The columns to include in the join output.
   *  If unspecified, all columns from both tables are included; paired
   *  join keys sharing the same column name are included only once.
   *  If array-valued, a two element array should be provided, containing
   *  the columns to include for the left and right tables, respectively.
   *  Array input may consist of column name strings, objects with output
   *  names as keys and single-table table expressions as values, or the
   *  selection helper functions {@link all}, {@link not}, or {@link range}.
   *  If object-valued, specifies the key-value pairs for each output,
   *  defined using two-table table expressions.
   * @param {JoinOptions} [options] Options for the join. With this method,
   *  any options will be overridden with {left: true, right: false}.
   * @return {this} A new joined table.
   * @example table.join_left(other, ['keyL', 'keyR'])
   * @example table.join_left(other, (a, b) => equal(a.keyL, b.keyR))
   */
  join_left(other, on, values, options) {
    const opt = { ...options, left: true, right: false };
    return this.__join(this, other, on, values, opt);
  }

  /**
   * Perform a right outer join on two tables. Rows in the right table
   * that do not match a row in the left table will be preserved.
   * This is a convenience method with fixed options for {@link Transformable#join}.
   * @param {TableRef} other The other (right) table to join with.
   * @param {JoinPredicate} [on] The join criteria for matching table rows.
   *  If unspecified, the values of all columns with matching names
   *  are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @param {JoinValues} [values] The columns to include in the join output.
   *  If unspecified, all columns from both tables are included; paired
   *  join keys sharing the same column name are included only once.
   *  If array-valued, a two element array should be provided, containing
   *  the columns to include for the left and right tables, respectively.
   *  Array input may consist of column name strings, objects with output
   *  names as keys and single-table table expressions as values, or the
   *  selection helper functions {@link all}, {@link not}, or {@link range}.
   *  If object-valued, specifies the key-value pairs for each output,
   *  defined using two-table table expressions.
   * @param {JoinOptions} [options] Options for the join. With this method,
   *  any options will be overridden with {left: false, right: true}.
   * @return {this} A new joined table.
   * @example table.join_right(other, ['keyL', 'keyR'])
   * @example table.join_right(other, (a, b) => equal(a.keyL, b.keyR))
   */
  join_right(other, on, values, options) {
    const opt = { ...options, left: false, right: true };
    return this.__join(this, other, on, values, opt);
  }

  /**
   * Perform a full outer join on two tables. Rows in either the left or
   * right table that do not match a row in the other will be preserved.
   * This is a convenience method with fixed options for {@link Transformable#join}.
   * @param {TableRef} other The other (right) table to join with.
   * @param {JoinPredicate} [on] The join criteria for matching table rows.
   *  If unspecified, the values of all columns with matching names
   *  are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @param {JoinValues} [values] The columns to include in the join output.
   *  If unspecified, all columns from both tables are included; paired
   *  join keys sharing the same column name are included only once.
   *  If array-valued, a two element array should be provided, containing
   *  the columns to include for the left and right tables, respectively.
   *  Array input may consist of column name strings, objects with output
   *  names as keys and single-table table expressions as values, or the
   *  selection helper functions {@link all}, {@link not}, or {@link range}.
   *  If object-valued, specifies the key-value pairs for each output,
   *  defined using two-table table expressions.
   * @param {JoinOptions} [options] Options for the join. With this method,
   *  any options will be overridden with {left: true, right: true}.
   * @return {this} A new joined table.
   * @example table.join_full(other, ['keyL', 'keyR'])
   * @example table.join_full(other, (a, b) => equal(a.keyL, b.keyR))
   */
  join_full(other, on, values, options) {
    const opt = { ...options, left: true, right: true };
    return this.__join(this, other, on, values, opt);
  }

  /**
   * Produce the Cartesian cross product of two tables. The output table
   * has one row for every pair of input table rows. Beware that outputs
   * may be quite large, as the number of output rows is the product of
   * the input row counts.
   * This is a convenience method for {@link Transformable#join} in which the
   * join criteria is always true.
   * @param {TableRef} other The other (right) table to join with.
   * @param {JoinValues} [values] The columns to include in the output.
   *  If unspecified, all columns from both tables are included.
   *  If array-valued, a two element array should be provided, containing
   *  the columns to include for the left and right tables, respectively.
   *  Array input may consist of column name strings, objects with output
   *  names as keys and single-table table expressions as values, or the
   *  selection helper functions {@link all}, {@link not}, or {@link range}.
   *  If object-valued, specifies the key-value pairs for each output,
   *  defined using two-table table expressions.
   * @param {JoinOptions} [options] Options for the join.
   * @return {this} A new joined table.
   * @example table.cross(other)
   * @example table.cross(other, [['leftKey', 'leftVal'], ['rightVal']])
   */
  cross(other, values, options) {
    return this.__cross(this, other, values, options);
  }

  /**
   * Perform a semi-join, filtering the left table to only rows that
   * match a row in the right table.
   * @param {TableRef} other The other (right) table to join with.
   * @param {JoinPredicate} [on] The join criteria for matching table rows.
   *  If unspecified, the values of all columns with matching names
   *  are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @return {this} A new filtered table.
   * @example table.semijoin(other)
   * @example table.semijoin(other, ['keyL', 'keyR'])
   * @example table.semijoin(other, (a, b) => equal(a.keyL, b.keyR))
   */
  semijoin(other, on) {
    return this.__semijoin(this, other, on);
  }

  /**
   * Perform an anti-join, filtering the left table to only rows that
   * do *not* match a row in the right table.
   * @param {TableRef} other The other (right) table to join with.
   * @param {JoinPredicate} [on] The join criteria for matching table rows.
   *  If unspecified, the values of all columns with matching names
   *  are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @return {this} A new filtered table.
   * @example table.antijoin(other)
   * @example table.antijoin(other, ['keyL', 'keyR'])
   * @example table.antijoin(other, (a, b) => equal(a.keyL, b.keyR))
   */
  antijoin(other, on) {
    return this.__antijoin(this, other, on);
  }

  // -- Set Operations ------------------------------------------------------

  /**
   * Concatenate multiple tables into a single table, preserving all rows.
   * This transformation mirrors the UNION_ALL operation in SQL.
   * Only named columns in this table are included in the output.
   * @see Transformable#union
   * @param  {...TableRef} tables A list of tables to concatenate.
   * @return {this} A new concatenated table.
   * @example table.concat(other)
   * @example table.concat(other1, other2)
   * @example table.concat([other1, other2])
   */
  concat(...tables) {
    return this.__concat(this, tables.flat());
  }

  /**
   * Union multiple tables into a single table, deduplicating all rows.
   * This transformation mirrors the UNION operation in SQL. It is
   * similar to {@link Transformable#concat} but suppresses duplicate rows with
   * values identical to another row.
   * Only named columns in this table are included in the output.
   * @see Transformable#concat
   * @param  {...TableRef} tables A list of tables to union.
   * @return {this} A new unioned table.
   * @example table.union(other)
   * @example table.union(other1, other2)
   * @example table.union([other1, other2])
   */
  union(...tables) {
    return this.__union(this, tables.flat());
  }

  /**
   * Intersect multiple tables, keeping only rows whose with identical
   * values for all columns in all tables, and deduplicates the rows.
   * This transformation is similar to a series of {@link Transformable#semijoin}
   * calls, but additionally suppresses duplicate rows.
   * @see Transformable#semijoin
   * @param  {...TableRef} tables A list of tables to intersect.
   * @return {this} A new filtered table.
   * @example table.intersect(other)
   * @example table.intersect(other1, other2)
   * @example table.intersect([other1, other2])
   */
  intersect(...tables) {
    return this.__intersect(this, tables.flat());
  }

  /**
   * Compute the set difference with multiple tables, keeping only rows in
   * this table that whose values do not occur in the other tables.
   * This transformation is similar to a series of {@link Transformable#antijoin}
   * calls, but additionally suppresses duplicate rows.
   * @see Transformable#antijoin
   * @param  {...TableRef} tables A list of tables to difference.
   * @return {this} A new filtered table.
   * @example table.except(other)
   * @example table.except(other1, other2)
   * @example table.except([other1, other2])
   */
  except(...tables) {
    return this.__except(this, tables.flat());
  }
}

// -- Parameter Types -------------------------------------------------------

/**
 * Table expression parameters.
 * @typedef {Object.<string, *>} Params
 */

/**
 * A reference to a column by string name or integer index.
 * @typedef {string|number} ColumnRef
 */

/**
 * A value that can be coerced to a string.
 * @typedef {object} Stringable
 * @property {() => string} toString String coercion method.
 */

/**
 * A table expression provided as a string or string-coercible value.
 * @typedef {string|Stringable} TableExprString
 */

/**
 * A struct object with arbitraty named properties.
 * @typedef {Object.<string, *>} Struct
 */

/**
 * A function defined over a table row.
 * @typedef {(d?: Struct, $?: Params) => any} TableExprFunc
 */

/**
 * A table expression defined over a single table.
 * @typedef {TableExprFunc|TableExprString} TableExpr
 */

/**
 * A function defined over rows from two tables.
 * @typedef {(a?: Struct, b?: Struct, $?: Params) => any} TableFunc2
 */

/**
 * A table expression defined over two tables.
 * @typedef {TableExprFunc2|TableExprString} TableExpr2
 */

/**
 * An object that maps current column names to new column names.
 * @typedef {{ [name: string]: string }} RenameMap
 */

/**
 * A selection helper function.
 * @typedef {(table: any) => string[]} SelectHelper
 */

/**
 * One or more column selections, potentially with renaming.
 * The input may consist of a column name string, column integer index, a
 * rename map object with current column names as keys and new column names
 * as values, or a select helper function that takes a table as input and
 * returns a valid selection parameter.
 * @typedef {ColumnRef|RenameMap|SelectHelper} SelectEntry
 */

/**
 * An ordered set of column selections, potentially with renaming.
 * @typedef {SelectEntry|SelectEntry[]} Select
 */

/**
 * An object of column name / table expression pairs.
 * @typedef {{ [name: string]: TableExpr }} ExprObject
 */

/**
 * An object of column name / two-table expression pairs.
 * @typedef {{ [name: string]: TableExpr2 }} Expr2Object
 */

/**
 * An ordered set of one or more column values.
 * @typedef {ColumnRef|SelectHelper|ExprObject} ListEntry
 */

/**
 * An ordered set of column values.
 * Entries may be column name strings, column index numbers, value objects
 * with output column names for keys and table expressions for values,
 * or a selection helper function.
 * @typedef {ListEntry|ListEntry[]} ExprList
 */

/**
 * A reference to a data table or transformable instance.
 * @typedef {Transformable|string} TableRef
 */

/**
 * One or more orderby sort criteria.
 * If a string, order by the column with that name.
 * If a number, order by the column with that index.
 * If a function, must be a valid table expression; aggregate functions
 *  are permitted, but window functions are not.
 * If an object, object values must be valid values parameters
 *  with output column names for keys and table expressions
 *  for values. The output name keys will subsequently be ignored.
 * @typedef {ColumnRef|TableExpr|ExprObject} OrderKey
 */

/**
 * An ordered set of orderby sort criteria, in precedence order.
 * @typedef {OrderKey|OrderKey[]} OrderKeys
 */

/**
 * Column values to use as a join key.
 * @typedef {ColumnRef|TableExprFunc} JoinKey
 */

/**
 * An ordered set of join keys.
 * @typedef {JoinKey|[JoinKey[]]|[JoinKey[], JoinKey[]]} JoinKeys
 */

/**
 * A predicate specification for joining two tables.
 * @typedef {JoinKeys|TableExprFunc2|null} JoinPredicate
 */

/**
 * An array of per-table join values to extract.
 * @typedef {[ExprList]|[ExprList, ExprList]|[ExprList, ExprList, Expr2Object]} JoinList
 */

/**
 * A specification of join values to extract.
 * @typedef {JoinList|Expr2Object} JoinValues
 */

// -- Transform Options -----------------------------------------------------

/**
 * Options for count transformations.
 * @typedef {object} CountOptions
 * @property {string} [as='count'] The name of the output count column.
 */

/**
 * Options for derive transformations.
 * @typedef {object} DeriveOptions
 * @property {boolean} [drop=false] A flag indicating if the original
 *  columns should be dropped, leaving only the derived columns. If true,
 *  the before and after options are ignored.
 * @property {Select} [before]
 *  An anchor column that relocated columns should be placed before.
 *  The value can be any legal column selection. If multiple columns are
 *  selected, only the first column will be used as an anchor.
 *  It is an error to specify both before and after options.
 * @property {Select} [after]
 *  An anchor column that relocated columns should be placed after.
 *  The value can be any legal column selection. If multiple columns are
 *  selected, only the last column will be used as an anchor.
 *  It is an error to specify both before and after options.
 */

/**
 * Options for relocate transformations.
 * @typedef {object} RelocateOptions
 * @property {Selection} [before]
 *  An anchor column that relocated columns should be placed before.
 *  The value can be any legal column selection. If multiple columns are
 *  selected, only the first column will be used as an anchor.
 *  It is an error to specify both before and after options.
 * @property {Selection} [after]
 *  An anchor column that relocated columns should be placed after.
 *  The value can be any legal column selection. If multiple columns are
 *  selected, only the last column will be used as an anchor.
 *  It is an error to specify both before and after options.
 */

/**
 * Options for sample transformations.
 * @typedef {object} SampleOptions
 * @property {boolean} [replace=false] Flag for sampling with replacement.
 * @property {boolean} [shuffle=true] Flag to ensure randomly ordered rows.
 * @property {string|TableExprFunc} [weight] Column values to use as weights
 *  for sampling. Rows will be sampled with probability proportional to
 *  their relative weight. The input should be a column name string or
 *  a table expression compatible with {@link Transformable#derive}.
 */

/**
 * Options for impute transformations.
 * @typedef {object} ImputeOptions
 * @property {ExprList} [expand] Column values to combine to impute missing
 *  rows. For column names and indices, all unique column values are
 *  considered. Otherwise, each entry should be an object of name-expresion
 *  pairs, with valid table expressions for {@link Transformable#rollup}.
 *  All combinations of values are checked for each set of unique groupby
 *  values.
 */

/**
 * Options for fold transformations.
 * @typedef {object} FoldOptions
 * @property {string[]} [as=['key', 'value']] An array indicating the
 *  output column names to use for the key and value columns, respectively.
 */

/**
 * Options for pivot transformations.
 * @typedef {object} PivotOptions
 * @property {number} [limit=Infinity] The maximum number of new columns to generate.
 * @property {string} [keySeparator='_'] A string to place between multiple key names.
 * @property {string} [valueSeparator='_'] A string to place between key and value names.
 * @property {boolean} [sort=true] Flag for alphabetical sorting of new column names.
 */

/**
 * Options for spread transformations.
 * @typedef {object} SpreadOptions
 * @property {boolean} [drop=true] Flag indicating if input columns to the
 *  spread operation should be dropped in the output table.
 * @property {number} [limit=Infinity] The maximum number of new columns to
 *  generate.
 * @property {string[]} [as] Output column names to use. This option only
 *  applies when a single column is spread. If the given array of names is
 *  shorter than the number of generated columns and no limit option is
 *  specified, the additional generated columns will be dropped.
 */

/**
 * Options for unroll transformations.
 * @typedef {object} UnrollOptions
 * @property {number} [limit=Infinity] The maximum number of new rows
 *  to generate per array value.
 * @property {boolean|string} [index=false] Flag or column name for adding
 *  zero-based array index values as an output column. If true, a new column
 *  named "index" will be included. If string-valued, a new column with
 *  the given name will be added.
 * @property {Select} [drop] Columns to drop from the output. The input may
 *  consist of column name strings, column integer indices, objects with
 *  column names as keys, or functions that take a table as input and
 *  return a valid selection parameter (typically the output of selection
 *  helper functions such as {@link all}, {@link not}, or {@link range}).
 */

/**
 * Options for join transformations.
 * @typedef {object} JoinOptions
 * @property {boolean} [left=false] Flag indicating a left outer join.
 *  If both the *left* and *right* are true, indicates a full outer join.
 * @property {boolean} [right=false] Flag indicating a right outer join.
 *  If both the *left* and *right* are true, indicates a full outer join.
 * @property {string[]} [suffix=['_1', '_2']] Column name suffixes to
 *  append if two columns with the same name are produced by the join.
 */
;// ../../node_modules/arquero/src/util/error.js
/* harmony default export */ function standalone_util_error(message) {
  throw Error(message);
}
;// ../../node_modules/arquero/src/util/is-number.js
/* harmony default export */ function standalone_is_number(value) {
  return typeof value === 'number';
}
;// ../../node_modules/arquero/src/util/is-function.js
/* harmony default export */ function standalone_util_is_function(value) {
  return typeof value === 'function';
}
;// ../../node_modules/arquero/src/util/repeat.js


/* harmony default export */ function standalone_util_repeat(reps, value) {
  const result = Array(reps);
  if (standalone_util_is_function(value)) {
    for (let i = 0; i < reps; ++i) {
      result[i] = value(i);
    }
  } else {
    result.fill(value);
  }
  return result;
}
;// ../../node_modules/arquero/src/table/table.js





/**
 * Abstract class representing a data table.
 */
class standalone_Table extends standalone_Transformable {

  /**
   * Instantiate a new Table instance.
   * @param {string[]} names An ordered list of column names.
   * @param {number} nrows The number of rows.
   * @param {TableData} data The backing data, which can vary by implementation.
   * @param {BitSet} [filter] A bit mask for which rows to include.
   * @param {GroupBySpec} [groups] A groupby specification for grouping ows.
   * @param {RowComparator} [order] A comparator function for sorting rows.
   * @param {Params} [params] Parameter values for table expressions.
   */
  constructor(names, nrows, data, filter, groups, order, params) {
    super(params);
    this._names = Object.freeze(names);
    this._data = data;
    this._total = nrows;
    this._nrows = filter ? filter.count() : nrows;
    this._mask = (nrows !== this._nrows && filter) || null;
    this._group = groups || null;
    this._order = order || null;
  }

  /**
   * Create a new table with the same type as this table.
   * The new table may have different data, filter, grouping, or ordering
   * based on the values of the optional configuration argument. If a
   * setting is not specified, it is inherited from the current table.
   * @param {CreateOptions} [options] Creation options for the new table.
   * @return {this} A newly created table.
   */
  create(options) { // eslint-disable-line no-unused-vars
    standalone_util_error('Not implemented');
  }

  /**
   * Provide an informative object string tag.
   */
  get [Symbol.toStringTag]() {
    if (!this._names) return 'Object'; // bail if called on prototype
    const nr = this.numRows() + ' row' + (this.numRows() !== 1 ? 's' : '');
    const nc = this.numCols() + ' col' + (this.numCols() !== 1 ? 's' : '');
    return `Table: ${nc} x ${nr}`
      + (this.isFiltered() ? ` (${this.totalRows()} backing)` : '')
      + (this.isGrouped() ? `, ${this._group.size} groups` : '')
      + (this.isOrdered() ? ', ordered' : '');
  }

  /**
   * Indicates if the table has a filter applied.
   * @return {boolean} True if filtered, false otherwise.
   */
  isFiltered() {
    return !!this._mask;
  }

  /**
   * Indicates if the table has a groupby specification.
   * @return {boolean} True if grouped, false otherwise.
   */
  isGrouped() {
    return !!this._group;
  }

  /**
   * Indicates if the table has a row order comparator.
   * @return {boolean} True if ordered, false otherwise.
   */
  isOrdered() {
    return !!this._order;
  }

  /**
   * Returns the internal table storage data structure.
   * @return {TableData} The backing table storage data structure.
   */
  data() {
    return this._data;
  }

  /**
   * Returns the filter bitset mask, if defined.
   * @return {BitSet} The filter bitset mask.
   */
  mask() {
    return this._mask;
  }

  /**
   * Returns the groupby specification, if defined.
   * @return {GroupBySpec} The groupby specification.
   */
  groups() {
    return this._group;
  }

  /**
   * Returns the row order comparator function, if specified.
   * @return {RowComparator} The row order comparator function.
   */
  comparator() {
    return this._order;
  }

  /**
   * The total number of rows in this table, counting both
   * filtered and unfiltered rows.
   * @return {number} The number of total rows.
   */
  totalRows() {
    return this._total;
  }

  /**
   * The number of active rows in this table. This number may be
   * less than the total rows if the table has been filtered.
   * @see Table.totalRows
   * @return {number} The number of rows.
   */
  numRows() {
    return this._nrows;
  }

  /**
   * The number of active rows in this table. This number may be
   * less than the total rows if the table has been filtered.
   * @see Table.totalRows
   * @return {number} The number of rows.
   */
  get size() {
    return this._nrows;
  }

  /**
   * The number of columns in this table.
   * @return {number} The number of columns.
   */
  numCols() {
    return this._names.length;
  }

  /**
   * Filter function invoked for each column name.
   * @callback NameFilter
   * @param {string} name The column name.
   * @param {number} index The column index.
   * @param {string[]} array The array of names.
   * @return {boolean} Returns true to retain the column name.
   */

  /**
   * The table column names, optionally filtered.
   * @param {NameFilter} [filter] An optional filter function.
   *  If unspecified, all column names are returned.
   * @return {string[]} An array of matching column names.
   */
  columnNames(filter) {
    return filter ? this._names.filter(filter) : this._names.slice();
  }

  /**
   * The column name at the given index.
   * @param {number} index The column index.
   * @return {string} The column name,
   *  or undefined if the index is out of range.
   */
  columnName(index) {
    return this._names[index];
  }

  /**
   * The column index for the given name.
   * @param {string} name The column name.
   * @return {number} The column index, or -1 if the name is not found.
   */
  columnIndex(name) {
    return this._names.indexOf(name);
  }

  /**
   * Deprecated alias for the table array() method: use table.array()
   * instead. Get an array of values contained in a column. The resulting
   * array respects any table filter or orderby criteria.
   * @param {string} name The column name.
   * @param {ArrayConstructor|TypedArrayConstructor} [constructor=Array]
   *  The array constructor for instantiating the output array.
   * @return {DataValue[]|TypedArray} The array of column values.
   */
  columnArray(name, constructor) {
    return this.array(name, constructor);
  }

  /**
   * Get an array of values contained in a column. The resulting array
   * respects any table filter or orderby criteria.
   * @param {string} name The column name.
   * @param {ArrayConstructor|TypedArrayConstructor} [constructor=Array]
   *  The array constructor for instantiating the output array.
   * @return {DataValue[]|TypedArray} The array of column values.
   */
  array(name, constructor) { // eslint-disable-line no-unused-vars
    standalone_util_error('Not implemented');
  }

  /**
   * Returns an iterator over column values.
   * @return {Iterator<object>} An iterator over row objects.
   */
  *values(name) {
    const get = this.getter(name);
    const n = this.numRows();
    for (let i = 0; i < n; ++i) {
      yield get(i);
    }
  }

  /**
   * Get the value for the given column and row.
   * @param {string} name The column name.
   * @param {number} [row=0] The row index, defaults to zero if not specified.
   * @return {DataValue} The data value at (column, row).
   */
  get(name, row = 0) { // eslint-disable-line no-unused-vars
    standalone_util_error('Not implemented');
  }

  /**
   * Returns an accessor ("getter") function for a column. The returned
   * function takes a row index as its single argument and returns the
   * corresponding column value.
   * @param {string} name The column name.
   * @return {ColumnGetter} The column getter function.
   */
  getter(name) { // eslint-disable-line no-unused-vars
    standalone_util_error('Not implemented');
  }

  /**
   * Returns an array of objects representing table rows.
   * @param {ObjectsOptions} [options] The options for row object generation.
   * @return {RowObject[]} An array of row objects.
   */
  objects(options) { // eslint-disable-line no-unused-vars
    standalone_util_error('Not implemented');
  }

  /**
   * Returns an object representing a table row.
   * @param {number} [row=0] The row index, defaults to zero if not specified.
   * @return {object} A row object with named properties for each column.
   */
   object(row) { // eslint-disable-line no-unused-vars
    standalone_util_error('Not implemented');
  }

  /**
   * Returns an iterator over objects representing table rows.
   * @return {Iterator<object>} An iterator over row objects.
   */
  [Symbol.iterator]() {
    standalone_util_error('Not implemented');
  }

  /**
   * Print the contents of this table using the console.table() method.
   * @param {PrintOptions|number} options The options for row object
   *  generation, determining which rows and columns are printed. If
   *  number-valued, specifies the row limit.
   */
  print(options = {}) {
    if (standalone_is_number(options)) {
      options = { limit: options };
    } else if (options.limit == null) {
      options.limit = 10;
    }

    const obj = this.objects({ ...options, grouped: false });
    const msg = `${this[Symbol.toStringTag]}. Showing ${obj.length} rows.`;

    console.log(msg);   // eslint-disable-line no-console
    console.table(obj); // eslint-disable-line no-console
  }

  /**
   * Returns an array of indices for all rows passing the table filter.
   * @param {boolean} [order=true] A flag indicating if the returned
   *  indices should be sorted if this table is ordered. If false, the
   *  returned indices may or may not be sorted.
   * @return {Uint32Array} An array of row indices.
   */
  indices(order = true) {
    if (this._index) return this._index;

    const n = this.numRows();
    const index = new Uint32Array(n);
    const ordered = this.isOrdered();
    const bits = this.mask();
    let row = -1;

    // inline the following for performance:
    // this.scan(row => index[++i] = row);
    if (bits) {
      for (let i = bits.next(0); i >= 0; i = bits.next(i + 1)) {
        index[++row] = i;
      }
    } else {
      for (let i = 0; i < n; ++i) {
        index[++row] = i;
      }
    }

    // sort index vector
    if (order && ordered) {
      const compare = this._order;
      const data = this._data;
      index.sort((a, b) => compare(a, b, data));
    }

    // save indices if they reflect table metadata
    if (order || !ordered) {
      this._index = index;
    }

    return index;
  }

  /**
   * Returns an array of indices for each group in the table.
   * If the table is not grouped, the result is the same as
   * {@link indices}, but wrapped within an array.
   * @param {boolean} [order=true] A flag indicating if the returned
   *  indices should be sorted if this table is ordered. If false, the
   *  returned indices may or may not be sorted.
   * @return {number[][]} An array of row index arrays, one per group.
   *  The indices will be filtered if the table is filtered.
   */
  partitions(order = true) {
    // return partitions if already generated
    if (this._partitions) {
      return this._partitions;
    }

    // if not grouped, return a single partition
    if (!this.isGrouped()) {
      return [ this.indices(order) ];
    }

    // generate partitions
    const { keys, size } = this._group;
    const part = standalone_util_repeat(size, () => []);

    // populate partitions, don't sort if indices don't exist
    // inline the following for performance:
    // this.scan(row => part[keys[row]].push(row), sort);
    const sort = this._index;
    const bits = this.mask();
    const n = this.numRows();
    if (sort && this.isOrdered()) {
      for (let i = 0, r; i < n; ++i) {
        r = sort[i];
        part[keys[r]].push(r);
      }
    } else if (bits) {
      for (let i = bits.next(0); i >= 0; i = bits.next(i + 1)) {
        part[keys[i]].push(i);
      }
    } else {
      for (let i = 0; i < n; ++i) {
        part[keys[i]].push(i);
      }
    }

    // if ordered but not yet sorted, sort partitions directly
    if (order && !sort && this.isOrdered()) {
      const compare = this._order;
      const data = this._data;
      for (let i = 0; i < size; ++i) {
        part[i].sort((a, b) => compare(a, b, data));
      }
    }

    // save partitions if they reflect table metadata
    if (order || !this.isOrdered()) {
      this._partitions = part;
    }

    return part;
  }

  /**
   * Callback function to cancel a table scan.
   * @callback ScanStop
   * @return {void}
   */

  /**
   * Callback function invoked for each row of a table scan.
   * @callback ScanVisitor
   * @param {number} [row] The table row index.
   * @param {TableData} [data] The backing table data store.
   * @param {ScanStop} [stop] Function to stop the scan early.
   *  Callees can invoke this function to prevent future calls.
   * @return {void}
   */

  /**
   * Perform a table scan, visiting each row of the table.
   * If this table is filtered, only rows passing the filter are visited.
   * @param {ScanVisitor} fn Callback invoked for each row of the table.
   * @param {boolean} [order=false] Indicates if the table should be
   *  scanned in the order determined by {@link Table#orderby}. This
   *  argument has no effect if the table is unordered.
   * @property {number} [limit=Infinity] The maximum number of objects to create.
   * @property {number} [offset=0] The row offset indicating how many initial rows to skip.
   */
  scan(fn, order, limit = Infinity, offset = 0) {
    const filter = this._mask;
    const nrows = this._nrows;
    const data = this._data;

    let i = offset || 0;
    if (i > nrows) return;

    const n = Math.min(nrows, i + limit);
    const stop = () => i = this._total;

    if (order && this.isOrdered() || filter && this._index) {
      const index = this.indices();
      const data = this._data;
      for (; i < n; ++i) {
        fn(index[i], data, stop);
      }
    } else if (filter) {
      let c = n - i + 1;
      for (i = filter.nth(i); --c && i > -1; i = filter.next(i + 1)) {
        fn(i, data, stop);
      }
    } else {
      for (; i < n; ++i) {
        fn(i, data, stop);
      }
    }
  }

  /**
   * Extract rows with indices from start to end (end not included), where
   * start and end represent per-group ordered row numbers in the table.
   * @param {number} [start] Zero-based index at which to start extraction.
   *  A negative index indicates an offset from the end of the group.
   *  If start is undefined, slice starts from the index 0.
   * @param {number} [end] Zero-based index before which to end extraction.
   *  A negative index indicates an offset from the end of the group.
   *  If end is omitted, slice extracts through the end of the group.
   * @return {this} A new table with sliced rows.
   * @example table.slice(1, -1)
   */
  slice(start = 0, end = Infinity) {
    if (this.isGrouped()) return super.slice(start, end);

    // if not grouped, scan table directly
    const indices = [];
    const nrows = this.numRows();
    start = Math.max(0, start + (start < 0 ? nrows : 0));
    end = Math.min(nrows, Math.max(0, end + (end < 0 ? nrows : 0)));
    this.scan(row => indices.push(row), true, end - start, start);
    return this.reify(indices);
  }

  /**
   * Reduce a table, processing all rows to produce a new table.
   * To produce standard aggregate summaries, use {@link rollup}.
   * This method allows the use of custom reducer implementations,
   * for example to produce multiple rows for an aggregate.
   * @param {Reducer} reducer The reducer to apply.
   * @return {Table} A new table of reducer outputs.
   */
  reduce(reducer) {
    return this.__reduce(this, reducer);
  }
}

/**
 * A typed array constructor.
 * @typedef {Uint8ArrayConstructor|Uint16ArrayConstructor|Uint32ArrayConstructor|BigUint64ArrayConstructor|Int8ArrayConstructor|Int16ArrayConstructor|Int32ArrayConstructor|BigInt64ArrayConstructor|Float32ArrayConstructor|Float64ArrayConstructor} TypedArrayConstructor
 */

/**
 * A typed array instance.
 * @typedef {Uint8Array|Uint16Array|Uint32Array|BigUint64Array|Int8Array|Int16Array|Int32Array|BigInt64Array|Float32Array|Float64Array} TypedArray
 */

/**
 * Backing table data.
 * @typedef {object|Array} TableData
 */

/**
 * Table value.
 * @typedef {*} DataValue
 */

/**
 * Table row object.
 * @typedef {Object.<string, DataValue>} RowObject
 */

/**
 * Table expression parameters.
 * @typedef {import('./transformable').Params} Params
 */

/**
 * Proxy type for BitSet class.
 * @typedef {import('./bit-set').default} BitSet
 */

/**
 * A table groupby specification.
 * @typedef {object} GroupBySpec
 * @property {number} size The number of groups.
 * @property {string[]} names Column names for each group.
 * @property {RowExpression[]} get Value accessor functions for each group.
 * @property {number[]} rows Indices of an example table row for each group.
 * @property {number[]} keys Per-row group indices, length is total rows of table.
 */

/**
 * Column value accessor.
 * @callback ColumnGetter
 * @param {number} [row] The table row.
 * @return {DataValue}
 */

/**
 * An expression evaluated over a table row.
 * @callback RowExpression
 * @param {number} [row] The table row.
 * @param {TableData} [data] The backing table data store.
 * @return {DataValue}
 */

/**
 * Comparator function for sorting table rows.
 * @callback RowComparator
 * @param {number} rowA The table row index for the first row.
 * @param {number} rowB The table row index for the second row.
 * @param {TableData} data The backing table data store.
 * @return {number} Negative if rowA < rowB, positive if
 *  rowA > rowB, otherwise zero.
 */

/**
 * Options for derived table creation.
 * @typedef {object} CreateOptions
 * @property {TableData} [data] The backing column data.
 * @property {string[]} [names] An ordered list of column names.
 * @property {BitSet} [filter] An additional filter BitSet to apply.
 * @property {GroupBySpec} [groups] The groupby specification to use, or null for no groups.
 * @property {RowComparator} [order] The orderby comparator function to use, or null for no order.
 */

/**
 * Options for generating row objects.
 * @typedef {object} PrintOptions
 * @property {number} [limit=Infinity] The maximum number of objects to create.
 * @property {number} [offset=0] The row offset indicating how many initial rows to skip.
 * @property {import('../table/transformable').Select} [columns]
 *  An ordered set of columns to include. The input may consist of column name
 *  strings, column integer indices, objects with current column names as keys
 *  and new column names as values (for renaming), or selection helper
 *  functions such as {@link all}, {@link not}, or {@link range}.
 */

/**
 * Options for generating row objects.
 * @typedef {object} ObjectsOptions
 * @property {number} [limit=Infinity] The maximum number of objects to create.
 * @property {number} [offset=0] The row offset indicating how many initial rows to skip.
 * @property {import('../table/transformable').Select} [columns]
 *  An ordered set of columns to include. The input may consist of column name
 *  strings, column integer indices, objects with current column names as keys
 *  and new column names as values (for renaming), or selection helper
 *  functions such as {@link all}, {@link not}, or {@link range}.
 * @property {'map'|'entries'|'object'|boolean} [grouped=false]
 *  The export format for groups of rows. The default (false) is to ignore
 *  groups, returning a flat array of objects. The valid values are 'map' or
 *  true (for Map instances), 'object' (for standard objects), or 'entries'
 *  (for arrays in the style of Object.entries). For the 'object' format,
 *  groupby keys are coerced to strings to use as object property names; note
 *  that this can lead to undesirable behavior if the groupby keys are object
 *  values. The 'map' and 'entries' options preserve the groupby key values.
 */

;// ../../node_modules/arquero/src/table/column.js


/**
 * Class representing an array-backed data column.
 */
class standalone_column_Column {
  /**
   * Create a new column instance.
   * @param {Array} data The backing array (or array-like object)
   *  containing the column data.
   */
  constructor(data) {
    this.data = data;
  }

  /**
   * Get the length (number of rows) of the column.
   * @return {number} The length of the column array.
   */
  get length() {
    return this.data.length;
  }

  /**
   * Get the column value at the given row index.
   * @param {number} row The row index of the value to retrieve.
   * @return {import('./table').DataValue} The column value.
   */
  get(row) {
    return this.data[row];
  }

  /**
   * Returns an iterator over the column values.
   * @return {Iterator<object>} An iterator over column values.
   */
  [Symbol.iterator]() {
    return this.data[Symbol.iterator]();
  }
}

/**
 * Column interface. Any object that adheres to this interface
 * can be used as a data column within a {@link ColumnTable}.
 * @typedef {object} ColumnType
 * @property {number} length
 *  The length (number of rows) of the column.
 * @property {import('./table').ColumnGetter} get
 *  Column value getter.
 */

/**
 * Column factory function interface.
 * @callback ColumnFactory
 * @param {*} data The input column data.
 * @return {ColumnType} A column instance.
 */

/**
 * Create a new column from the given input data.
 * @param {any} data The backing column data. If the value conforms to
 *  the Column interface it is returned directly. If the value is an
 *  array, it will be wrapped in a new Column instance.
 * @return {ColumnType} A compatible column instance.
 */
let standalone_defaultColumnFactory = function(data) {
  return data && standalone_util_is_function(data.get) ? data : new standalone_column_Column(data);
};

/**
 * Get or set the default factory function for instantiating table columns.
 * @param {ColumnFactory} [factory] The new default factory.
 * @return {ColumnFactory} The current default column factory.
 */
function standalone_columnFactory(factory) {
  return arguments.length
    ? (standalone_defaultColumnFactory = factory)
    : standalone_defaultColumnFactory;
}
;// ../../node_modules/arquero/src/util/is-date.js
/* harmony default export */ function standalone_is_date(value) {
  return value instanceof Date;
}
;// ../../node_modules/arquero/src/util/is-object.js
/* harmony default export */ function standalone_is_object(value) {
  return value === Object(value);
}
;// ../../node_modules/arquero/src/util/is-regexp.js
/* harmony default export */ function standalone_is_regexp(value) {
  return value instanceof RegExp;
}
;// ../../node_modules/arquero/src/util/is-string.js
/* harmony default export */ function standalone_is_string(value) {
  return typeof value === 'string';
}

;// ../../node_modules/arquero/src/table/columns-from.js








/* harmony default export */ function standalone_columns_from(values, names) {
  const raise = type => standalone_util_error(`Illegal argument type: ${type || typeof values}`);
  return values instanceof Map ? standalone_fromKeyValuePairs(values.entries(), names)
    : standalone_is_date(values) ? raise('Date')
    : standalone_is_regexp(values) ? raise('RegExp')
    : standalone_is_string(values) ? raise()
    : standalone_is_array(values) ? standalone_fromArray(values, names)
    : standalone_util_is_function(values[Symbol.iterator]) ? standalone_fromIterable(values, names)
    : standalone_is_object(values) ? standalone_fromKeyValuePairs(Object.entries(values), names)
    : raise();
}

function standalone_fromKeyValuePairs(entries, names = ['key', 'value']) {
  const keys = [];
  const vals = [];

  for (const [key, val] of entries) {
    keys.push(key);
    vals.push(val);
  }

  const columns = {};
  if (names[0]) columns[names[0]] = keys;
  if (names[1]) columns[names[1]] = vals;
  return columns;
}

function standalone_fromArray(values, names) {
  const len = values.length;
  const columns = {};
  const add = name => columns[name] = Array(len);

  if (len) {
    names = names || Object.keys(values[0]);
    const cols = names.map(add);
    const n = cols.length;
    for (let idx = 0; idx < len; ++idx) {
      const row = values[idx];
      for (let i = 0; i < n; ++i) {
        cols[i][idx] = row[names[i]];
      }
    }
  } else if (names) {
    names.forEach(add);
  }

  return columns;
}

function standalone_fromIterable(values, names) {
  const columns = {};
  const add = name => columns[name] = [];

  let cols;
  let n;
  for (const row of values) {
    if (!cols) {
      names = names || Object.keys(row);
      cols = names.map(add);
      n = cols.length;
    }
    for (let i = 0; i < n; ++i) {
      cols[i].push(row[names[i]]);
    }
  }

  if (!cols && names) {
    names.forEach(add);
  }

  return columns;
}
;// ../../node_modules/arquero/src/util/has.js
const { hasOwnProperty: standalone_has_hasOwnProperty } = Object.prototype;

/* harmony default export */ function standalone_util_has(object, property) {
  return standalone_has_hasOwnProperty.call(object, property);
}
;// ../../node_modules/arquero/src/table/column-set.js


/* harmony default export */ function standalone_column_set(table) {
  return table
    ? new standalone_ColumnSet({ ...table.data() }, table.columnNames())
    : new standalone_ColumnSet();
}

class standalone_ColumnSet {
  constructor(data, names) {
    this.data = data || {};
    this.names = names || [];
  }

  add(name, values) {
    if (!this.has(name)) this.names.push(name + '');
    return this.data[name] = values;
  }

  has(name) {
    return standalone_util_has(this.data, name);
  }

  new() {
    this.filter = null;
    this.groups = this.groups || null;
    this.order = null;
    return this;
  }

  groupby(groups) {
    this.groups = groups;
    return this;
  }
}
;// ../../node_modules/arquero/src/util/null.js
/**
 * Default NULL (missing) value to use.
 */
/* harmony default export */ const standalone_util_null = (undefined);
;// ../../node_modules/arquero/src/util/is-typed-array.js
const standalone_TypedArray = Object.getPrototypeOf(Int8Array);

/* harmony default export */ function standalone_is_typed_array(value) {
  return value instanceof standalone_TypedArray;
}
;// ../../node_modules/arquero/src/util/is-array-type.js



function standalone_is_array_type_isArrayType(value) {
  return standalone_is_array(value) || standalone_is_typed_array(value);
}
;// ../../node_modules/arquero/src/util/is-valid.js
/* harmony default export */ function standalone_is_valid(value) {
  return value != null && value === value;
}

;// ../../node_modules/arquero/src/op/functions/array.js





const standalone_isSeq = (seq) => standalone_is_array_type_isArrayType(seq) || standalone_is_string(seq);

/* harmony default export */ const standalone_functions_array = ({
  compact:      (arr) => standalone_is_array_type_isArrayType(arr) ? arr.filter(v => standalone_is_valid(v)) : arr,
  concat:       (...values) => [].concat(...values),
  includes:     (seq, value, index) => standalone_isSeq(seq)
                  ? seq.includes(value, index)
                  : false,
  indexof:      (seq, value) => standalone_isSeq(seq) ? seq.indexOf(value) : -1,
  join:         (arr, delim) => standalone_is_array_type_isArrayType(arr) ? arr.join(delim) : standalone_util_null,
  lastindexof:  (seq, value) => standalone_isSeq(seq) ? seq.lastIndexOf(value) : -1,
  length:       (seq) => standalone_isSeq(seq) ? seq.length : 0,
  pluck:        (arr, prop) => standalone_is_array_type_isArrayType(arr)
                  ? arr.map(v => standalone_is_valid(v) ? v[prop] : standalone_util_null)
                  : standalone_util_null,
  reverse:      (seq) => standalone_is_array_type_isArrayType(seq) ? seq.slice().reverse()
                  : standalone_is_string(seq) ? seq.split('').reverse().join('')
                  : standalone_util_null,
  slice:        (seq, start, end) => standalone_isSeq(seq) ? seq.slice(start, end) : standalone_util_null
});

;// ../../node_modules/arquero/src/op/functions/bin.js
/**
 * Truncate a value to a bin boundary.
 * Useful for creating equal-width histograms.
 * Values outside the [min, max] range will be mapped to
 * -Infinity (< min) or +Infinity (> max).
 * @param {number} value - The value to bin.
 * @param {number} min - The minimum bin boundary.
 * @param {number} max - The maximum bin boundary.
 * @param {number} step - The step size between bin boundaries.
 * @param {number} [offset=0] - Offset in steps by which to adjust
 *  the bin value. An offset of 1 will return the next boundary.
 */
/* harmony default export */ function standalone_functions_bin(value, min, max, step, offset) {
  return value == null ? null
    : value < min ? -Infinity
    : value > max ? +Infinity
    : (
        value = Math.max(min, Math.min(value, max)),
        min + step * Math.floor(1e-14 + (value - min) / step + (offset || 0))
      );
}
;// ../../node_modules/arquero/src/util/pad.js
/* harmony default export */ function standalone_util_pad(value, width, char = '0') {
  const s = value + '';
  const len = s.length;
  return len < width ? Array(width - len + 1).join(char) + s : s;
}
;// ../../node_modules/arquero/src/util/format-date.js


const standalone_pad2 = v => (v < 10 ? '0' : '') + v;

const standalone_format_date_formatYear = year => year < 0 ? '-' + standalone_util_pad(-year, 6)
  : year > 9999 ? '+' + standalone_util_pad(year, 6)
  : standalone_util_pad(year, 4);

function standalone_formatISO(year, month, date, hours, min, sec, ms, utc, short) {
  const suffix = utc ? 'Z' : '';
  return standalone_format_date_formatYear(year) + '-' + standalone_pad2(month + 1) + '-' + standalone_pad2(date) + (
    !short || ms ? 'T' + standalone_pad2(hours) + ':' + standalone_pad2(min) + ':' + standalone_pad2(sec) + '.' + standalone_util_pad(ms, 3) + suffix
    : sec ? 'T' + standalone_pad2(hours) + ':' + standalone_pad2(min) + ':' + standalone_pad2(sec) + suffix
    : min || hours || !utc ? 'T' + standalone_pad2(hours) + ':' + standalone_pad2(min) + suffix
    : ''
  );
}

function standalone_format_date_formatDate(d, short) {
  return isNaN(d)
    ? 'Invalid Date'
    : standalone_formatISO(
      d.getFullYear(),
      d.getMonth(),
      d.getDate(),
      d.getHours(),
      d.getMinutes(),
      d.getSeconds(),
      d.getMilliseconds(),
      false, short
    );
}

function standalone_formatUTCDate(d, short) {
  return isNaN(d)
    ? 'Invalid Date'
    : standalone_formatISO(
      d.getUTCFullYear(),
      d.getUTCMonth(),
      d.getUTCDate(),
      d.getUTCHours(),
      d.getUTCMinutes(),
      d.getUTCSeconds(),
      d.getUTCMilliseconds(),
      true, short
    );
}
;// ../../node_modules/arquero/src/util/is-iso-date-string.js
const standalone_iso_re = /^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/;

/* harmony default export */ function standalone_is_iso_date_string(value) {
  return value.match(standalone_iso_re);
}
;// ../../node_modules/arquero/src/util/parse-iso-date.js


/* harmony default export */ function standalone_parse_iso_date(value, parse = Date.parse) {
  return standalone_is_iso_date_string(value) ? parse(value) : value;
}
;// ../../node_modules/arquero/src/op/functions/date.js



const standalone_msMinute = 6e4;
const standalone_msDay = 864e5;
const standalone_msWeek = 6048e5;

const standalone_date_t0 = new Date();
const standalone_date_t1 = new Date();
const src_standalone_t = d => (
  standalone_date_t0.setTime(typeof d === 'string' ? standalone_parse_iso_date(d) : d),
  standalone_date_t0
);

/**
 * Function to create a new Date value.
 * If no arguments are provided, the current time is used.
 * @param {number} [year] The year.
 * @param {number} [month=0] The (zero-based) month.
 * @param {number} [date=1] The date within the month.
 * @param {number} [hours=0] The hour within the day.
 * @param {number} [minutes=0] The minute within the hour.
 * @param {number} [seconds=0] The second within the minute.
 * @param {number} [milliseconds=0] The milliseconds within the second.
 * @return {date} The resuting Date value.
 */
function standalone_date_datetime(year, month, date, hours, minutes, seconds, milliseconds) {
  return !arguments.length
    ? new Date(Date.now())
    : new Date(
        year,
        month || 0,
        date == null ? 1 : date,
        hours || 0,
        minutes || 0,
        seconds || 0,
        milliseconds || 0
      );
}

/**
 * Function to create a new Date value according to UTC time.
 * If no arguments are provided, the current time is used.
 * @param {number} [year] The year.
 * @param {number} [month=0] The (zero-based) month.
 * @param {number} [date=1] The date within the month.
 * @param {number} [hours=0] The hour within the day.
 * @param {number} [minutes=0] The minute within the hour.
 * @param {number} [seconds=0] The second within the minute.
 * @param {number} [milliseconds=0] The milliseconds within the second.
 * @return {date} The resuting Date value.
 */
function standalone_utcdatetime(year, month, date, hours, minutes, seconds, milliseconds) {
  return !arguments.length
    ? new Date(Date.now())
    : new Date(Date.UTC(
        year,
        month || 0,
        date == null ? 1 : date,
        hours || 0,
        minutes || 0,
        seconds || 0,
        milliseconds || 0
      ));
}

function standalone_date_dayofyear(date) {
  standalone_date_t1.setTime(+date);
  standalone_date_t1.setHours(0, 0, 0, 0);
  standalone_date_t0.setTime(+standalone_date_t1);
  standalone_date_t0.setMonth(0);
  standalone_date_t0.setDate(1);
  const tz = (standalone_date_t1.getTimezoneOffset() - standalone_date_t0.getTimezoneOffset()) * standalone_msMinute;
  return Math.floor(1 + ((standalone_date_t1 - standalone_date_t0) - tz) / standalone_msDay);
}

function standalone_date_utcdayofyear(date) {
  standalone_date_t1.setTime(+date);
  standalone_date_t1.setUTCHours(0, 0, 0, 0);
  const t0 = Date.UTC(standalone_date_t1.getUTCFullYear(), 0, 1);
  return Math.floor(1 + (standalone_date_t1 - t0) / standalone_msDay);
}

function standalone_date_week(date, firstday) {
  const i = firstday || 0;
  standalone_date_t1.setTime(+date);
  standalone_date_t1.setDate(standalone_date_t1.getDate() - (standalone_date_t1.getDay() + 7 - i) % 7);
  standalone_date_t1.setHours(0, 0, 0, 0);
  standalone_date_t0.setTime(+date);
  standalone_date_t0.setMonth(0);
  standalone_date_t0.setDate(1);
  standalone_date_t0.setDate(1 - (standalone_date_t0.getDay() + 7 - i) % 7);
  standalone_date_t0.setHours(0, 0, 0, 0);
  const tz = (standalone_date_t1.getTimezoneOffset() - standalone_date_t0.getTimezoneOffset()) * standalone_msMinute;
  return Math.floor((1 + (standalone_date_t1 - standalone_date_t0) - tz) / standalone_msWeek);
}

function standalone_date_utcweek(date, firstday) {
  const i = firstday || 0;
  standalone_date_t1.setTime(+date);
  standalone_date_t1.setUTCDate(standalone_date_t1.getUTCDate() - (standalone_date_t1.getUTCDay() + 7 - i) % 7);
  standalone_date_t1.setUTCHours(0, 0, 0, 0);
  standalone_date_t0.setTime(+date);
  standalone_date_t0.setUTCMonth(0);
  standalone_date_t0.setUTCDate(1);
  standalone_date_t0.setUTCDate(1 - (standalone_date_t0.getUTCDay() + 7 - i) % 7);
  standalone_date_t0.setUTCHours(0, 0, 0, 0);
  return Math.floor((1 + (standalone_date_t1 - standalone_date_t0)) / standalone_msWeek);
}

/* harmony default export */ const standalone_functions_date = ({
  format_date:     (date, shorten) => standalone_format_date_formatDate(src_standalone_t(date), !shorten),
  format_utcdate:  (date, shorten) => standalone_formatUTCDate(src_standalone_t(date), !shorten),
  timestamp:       (date) => +src_standalone_t(date),
  year:            (date) => src_standalone_t(date).getFullYear(),
  quarter:         (date) => Math.floor(src_standalone_t(date).getMonth() / 3),
  month:           (date) => src_standalone_t(date).getMonth(),
  date:            (date) => src_standalone_t(date).getDate(),
  dayofweek:       (date) => src_standalone_t(date).getDay(),
  hours:           (date) => src_standalone_t(date).getHours(),
  minutes:         (date) => src_standalone_t(date).getMinutes(),
  seconds:         (date) => src_standalone_t(date).getSeconds(),
  milliseconds:    (date) => src_standalone_t(date).getMilliseconds(),
  utcyear:         (date) => src_standalone_t(date).getUTCFullYear(),
  utcquarter:      (date) => Math.floor(src_standalone_t(date).getUTCMonth() / 3),
  utcmonth:        (date) => src_standalone_t(date).getUTCMonth(),
  utcdate:         (date) => src_standalone_t(date).getUTCDate(),
  utcdayofweek:    (date) => src_standalone_t(date).getUTCDay(),
  utchours:        (date) => src_standalone_t(date).getUTCHours(),
  utcminutes:      (date) => src_standalone_t(date).getUTCMinutes(),
  utcseconds:      (date) => src_standalone_t(date).getUTCSeconds(),
  utcmilliseconds: (date) => src_standalone_t(date).getUTCMilliseconds(),
  datetime: standalone_date_datetime,
  dayofyear: standalone_date_dayofyear,
  week: standalone_date_week,
  utcdatetime: standalone_utcdatetime,
  utcdayofyear: standalone_date_utcdayofyear,
  utcweek: standalone_date_utcweek,
  now: Date.now
});
;// ../../node_modules/arquero/src/op/functions/equal.js




/**
 * Compare two values for equality, using join semantics in which null
 * !== null. If the inputs are object-valued, a deep equality check
 * of array entries or object key-value pairs is performed.
 * @param {*} a The first input.
 * @param {*} b The second input.
 * @return {boolean} True if equal, false if not.
 */
function standalone_equal_equal(a, b) {
  return (a == null || b == null || a !== a || b !== b) ? false
    : a === b ? true
    : (standalone_is_date(a) || standalone_is_date(b)) ? +a === +b
    : (standalone_is_regexp(a) && standalone_is_regexp(b)) ? a + '' === b + ''
    : (standalone_is_object(a) && standalone_is_object(b)) ? standalone_equal_deepEqual(a, b)
    : false;
}

function standalone_equal_deepEqual(a, b) {
  if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) {
    return false;
  }

  if (a.length || b.length) {
    return standalone_arrayEqual(a, b);
  }

  const keysA = Object.keys(a);
  const keysB = Object.keys(b);
  if (keysA.length !== keysB.length) {
    return false;
  }
  keysA.sort();
  keysB.sort();

  if (!standalone_arrayEqual(keysA, keysB, (a, b) => a === b)) {
    return false;
  }

  const n = keysA.length;
  for (let i = 0; i < n; ++i) {
    const k = keysA[i];
    if (!standalone_equal_equal(a[k], b[k])) {
      return false;
    }
  }

  return true;
}

function standalone_arrayEqual(a, b, test = standalone_equal_equal) {
  const n = a.length;
  if (n !== b.length) return false;

  for (let i = 0; i < n; ++i) {
    if (!test(a[i], b[i])) {
      return false;
    }
  }

  return true;
}
;// ../../node_modules/arquero/src/op/functions/json.js
/* harmony default export */ const standalone_functions_json = ({
  parse_json: (str) => JSON.parse(str),
  to_json:    (val) => JSON.stringify(val)
});
;// ../../node_modules/arquero/src/util/random.js


let standalone_random_source = Math.random;

function standalone_random_random() {
  return standalone_random_source();
}

/**
 * Set a seed value for random number generation.
 * If the seed is a valid number, a 32-bit linear congruential generator
 * with the given seed will be used to generate random values.
 * If the seed is null, undefined, or not a valid number, the random
 * number generator will revert to Math.random.
 * @param {number} seed The random seed value. Should either be an
 *  integer or a fraction between 0 and 1.
 */
function standalone_seed(seed) {
  standalone_random_source = isValid(seed) && isFinite(seed = +seed) ? standalone_random_lcg(seed) : Math.random;
}

function standalone_random_lcg(seed) {
  const a = 0x19660D;
  const c = 0x3C6EF35F;
  const m = 1 / 0x100000000;
  seed = (0 <= seed && seed < 1 ? seed / m : Math.abs(seed)) | 0;

  // Random numbers using a Linear Congruential Generator with seed value
  // https://en.wikipedia.org/wiki/Linear_congruential_generator
  return () => (seed = a * seed + c | 0, m * (seed >>> 0));
}
;// ../../node_modules/arquero/src/op/functions/math.js


/* harmony default export */ const standalone_math = ({
  random: standalone_random_random,
  is_nan:    Number.isNaN,
  is_finite: Number.isFinite,

  abs:      Math.abs,
  cbrt:     Math.cbrt,
  ceil:     Math.ceil,
  clz32:    Math.clz32,
  exp:      Math.exp,
  expm1:    Math.expm1,
  floor:    Math.floor,
  fround:   Math.fround,
  greatest: Math.max,
  least:    Math.min,
  log:      Math.log,
  log10:    Math.log10,
  log1p:    Math.log1p,
  log2:     Math.log2,
  pow:      Math.pow,
  round:    Math.round,
  sign:     Math.sign,
  sqrt:     Math.sqrt,
  trunc:    Math.trunc,

  degrees:  (rad) => 180 * rad / Math.PI,
  radians:  (deg) => Math.PI * deg / 180,
  acos:     Math.acos,
  acosh:    Math.acosh,
  asin:     Math.asin,
  asinh:    Math.asinh,
  atan:     Math.atan,
  atan2:    Math.atan2,
  atanh:    Math.atanh,
  cos:      Math.cos,
  cosh:     Math.cosh,
  sin:      Math.sin,
  sinh:     Math.sinh,
  tan:      Math.tan,
  tanh:     Math.tanh
});
;// ../../node_modules/arquero/src/util/is-map.js
/* harmony default export */ function standalone_is_map(value) {
  return value instanceof Map;
}
;// ../../node_modules/arquero/src/util/is-set.js
/* harmony default export */ function standalone_is_set(value) {
  return value instanceof Set;
}
;// ../../node_modules/arquero/src/util/is-map-or-set.js



/* harmony default export */ function standalone_is_map_or_set(value) {
  return standalone_is_map(value) || standalone_is_set(value);
}
;// ../../node_modules/arquero/src/op/functions/object.js





function standalone_object_array(iter) {
  return Array.from(iter);
}

/* harmony default export */ const standalone_functions_object = ({
  has:      (obj, key) => standalone_is_map_or_set(obj) ? obj.has(key)
              : obj != null ? standalone_util_has(obj, key)
              : false,
  keys:     (obj) => standalone_is_map(obj) ? standalone_object_array(obj.keys())
              : obj != null ? Object.keys(obj)
              : [],
  values:   (obj) => standalone_is_map_or_set(obj) ? standalone_object_array(obj.values())
              : obj != null ? Object.values(obj)
              : [],
  entries:  (obj) => standalone_is_map_or_set(obj) ? standalone_object_array(obj.entries())
              : obj != null ? Object.entries(obj)
              : [],
  object:   (entries) => entries ? Object.fromEntries(entries) : standalone_util_null
});
;// ../../node_modules/arquero/src/op/functions/recode.js


/**
 * Recodes an input value to an alternative value, based on a provided
 * value map. If a fallback value is specified, it will be returned when
 * a matching value is not found in the map; otherwise, the input value
 * is returned unchanged.
 * @param {*} value The value to recode. The value must be safely
 *  coercible to a string for lookup against the value map.
 * @param {object|Map} map An object or Map with input values for keys and
 *  output recoded values as values. If a non-Map object, only the object's
 *  own properties will be considered.
 * @param {*} [fallback] A default fallback value to use if the input
 *  value is not found in the value map.
 * @return {*} The recoded value.
 */
/* harmony default export */ function standalone_recode(value, map, fallback) {
  if (map instanceof Map) {
    if (map.has(value)) return map.get(value);
  } else if (standalone_util_has(map, value)) {
    return map[value];
  }
  return fallback !== undefined ? fallback : value;
}
;// ../../node_modules/arquero/src/op/functions/sequence.js
/**
 * Returns an array containing an arithmetic sequence from the start value
 * to the stop value, in step increments. If step is positive, the last
 * element is the largest start + i * step less than stop; if step is
 * negative, the last element is the smallest start + i * step greater
 * than stop. If the returned array would contain an infinite number of
 * values, an empty range is returned.
 * @param {number} [start=0] The starting value of the sequence.
 * @param {number} [stop] The stopping value of the sequence.
 *  The stop value is exclusive; it is not included in the result.
 * @param {number} [step=1] The step increment between sequence values.
 * @return {number[]} The generated sequence.
 */
/* harmony default export */ function standalone_functions_sequence(start, stop, step) {
  let n = arguments.length;
  start = +start;
  stop = +stop;
  step = n < 2
    ? (stop = start, start = 0, 1)
    : n < 3 ? 1 : +step;

  n = Math.max(0, Math.ceil((stop - start) / step)) | 0;
  const seq = new Array(n);

  for (let i = 0; i < n; ++i) {
    seq[i] = start + i * step;
  }

  return seq;
}
;// ../../node_modules/arquero/src/op/functions/string.js
/* harmony default export */ const standalone_functions_string = ({
  parse_date:   (str) => str == null ? str : new Date(str),
  parse_float:  (str) => str == null ? str : Number.parseFloat(str),
  parse_int:    (str, radix) => str == null ? str : Number.parseInt(str, radix),
  endswith:     (str, search, length) => str == null ? false
                  : String(str).endsWith(search, length),
  match:        (str, regexp, index) => {
                  const m = str == null ? str : String(str).match(regexp);
                  return index == null || m == null ? m
                    : typeof index === 'number' ? m[index]
                    : m.groups ? m.groups[index]
                    : null;
                },
  normalize:    (str, form) => str == null ? str
                  : String(str).normalize(form),
  padend:       (str, len, fill) => str == null ? str
                  : String(str).padEnd(len, fill),
  padstart:     (str, len, fill) => str == null ? str
                  : String(str).padStart(len, fill),
  upper:        (str) => str == null ? str
                  : String(str).toUpperCase(),
  lower:        (str) => str == null ? str
                  : String(str).toLowerCase(),
  repeat:       (str, num) => str == null ? str
                  : String(str).repeat(num),
  replace:      (str, pattern, replacement) => str == null ? str
                  : String(str).replace(pattern, String(replacement)),
  substring:    (str, start, end) => str == null ? str
                  : String(str).substring(start, end),
  split:        (str, separator, limit) => str == null ? []
                  : String(str).split(separator, limit),
  startswith:   (str, search, length) => str == null ? false
                  : String(str).startsWith(search, length),
  trim:         (str) => str == null ? str
                  : String(str).trim()
});
;// ../../node_modules/arquero/src/op/functions/index.js











/* harmony default export */ const standalone_op_functions = ({
  bin: standalone_functions_bin,
  equal: standalone_equal_equal,
  recode: standalone_recode,
  sequence: standalone_functions_sequence,
  ...standalone_functions_array,
  ...standalone_functions_date,
  ...standalone_functions_json,
  ...standalone_math,
  ...standalone_functions_object,
  ...standalone_functions_string
});
;// ../../node_modules/arquero/src/util/is-bigint.js
/* harmony default export */ function standalone_is_bigint(value) {
  return typeof value === 'bigint';
}
;// ../../node_modules/arquero/src/util/to-string.js


/* harmony default export */ function standalone_to_string(v) {
  return v === undefined ? v + ''
    : standalone_is_bigint(v) ? v + 'n'
    : JSON.stringify(v);
}
;// ../../node_modules/arquero/src/op/op.js



/* harmony default export */ function standalone_op_op(name, fields = [], params = []) {
  return new standalone_Op(name, standalone_to_array(fields), standalone_to_array(params));
}

class standalone_Op {
  constructor(name, fields, params) {
    this.name = name;
    this.fields = fields;
    this.params = params;
  }
  toString() {
    const args = [
      ...this.fields.map(f => `d[${standalone_to_string(f)}]`),
      ...this.params.map(standalone_to_string)
    ];
    return `d => op.${this.name}(${args})`;
  }
  toObject() {
    return { expr: this.toString(), func: true };
  }
}
;// ../../node_modules/arquero/src/op/op-api.js



const standalone_any = (field) => standalone_op_op('any', field);
const standalone_op_api_count = () => standalone_op_op('count');
const standalone_array_agg = (field) => standalone_op_op('array_agg', field);
const standalone_array_agg_distinct = (field) => standalone_op_op('array_agg_distinct', field);
const standalone_map_agg = (key, value) => standalone_op_op('map_agg', [key, value]);
const standalone_object_agg = (key, value) => standalone_op_op('object_agg', [key, value]);
const standalone_entries_agg = (key, value) => standalone_op_op('entries_agg', [key, value]);

/**
 * @typedef {import('../table/transformable').Struct} Struct
 */

/**
 * All table expression operations including normal functions,
 * aggregate functions, and window functions.
 */
/* harmony default export */ const standalone_op_api = ({
  ...standalone_op_functions,

  /**
   * Generate an object representing the current table row.
   * @param {...string} names The column names to include in the object.
   *  If unspecified, all columns are included.
   * @return {Struct} The generated row object.
   */
  row_object: (...names) => standalone_op_op('row_object', null, names.flat()),

  /**
   * Aggregate function to count the number of records (rows).
   * @returns {number} The count of records.
   */
  count: standalone_op_api_count,

  /**
   * Aggregate function returning an arbitrary observed value.
   * @param {*} field The data field.
   * @return {*} An arbitrary observed value.
   */
  any: standalone_any,

  /**
   * Aggregate function to collect an array of values.
   * @param {*} field The data field.
   * @return {Array} A list of values.
   */
  array_agg: standalone_array_agg,

  /**
   * Aggregate function to collect an array of distinct (unique) values.
   * @param {*} field The data field.
   * @return {Array} An array of unique values.
   */
  array_agg_distinct: standalone_array_agg_distinct,

  /**
   * Aggregate function to create an object given input key and value fields.
   * @param {*} key The object key field.
   * @param {*} value The object value field.
   * @return {Struct} An object of key-value pairs.
   */
  object_agg: standalone_object_agg,

  /**
   * Aggregate function to create a Map given input key and value fields.
   * @param {*} key The object key field.
   * @param {*} value The object value field.
   * @return {Map} A Map of key-value pairs.
   */
  map_agg: standalone_map_agg,

  /**
   * Aggregate function to create an array in the style of Object.entries()
   * given input key and value fields.
   * @param {*} key The object key field.
   * @param {*} value The object value field.
   * @return {[[any, any]]} An array of [key, value] arrays.
   */
  entries_agg: standalone_entries_agg,

  /**
   * Aggregate function to count the number of valid values.
   * Invalid values are null, undefined, or NaN.
   * @param {*} field The data field.
   * @return {number} The count of valid values.
   */
  valid: (field) => standalone_op_op('valid', field),

  /**
   * Aggregate function to count the number of invalid values.
   * Invalid values are null, undefined, or NaN.
   * @param {*} field The data field.
   * @return {number} The count of invalid values.
   */
  invalid: (field) => standalone_op_op('invalid', field),

  /**
   * Aggregate function to count the number of distinct values.
   * @param {*} field The data field.
   * @return {number} The count of distinct values.
   */
  distinct: (field) => standalone_op_op('distinct', field),

  /**
   * Aggregate function to determine the mode (most frequent) value.
   * @param {*} field The data field.
   * @return {number} The mode value.
   */
  mode: (field) => standalone_op_op('mode', field),

  /**
   * Aggregate function to sum values.
   * @param {string} field The data field.
   * @return {number} The sum of the values.
   */
  sum: (field) => standalone_op_op('sum', field),

  /**
   * Aggregate function to multiply values.
   * @param {*} field The data field.
   * @return {number} The product of the values.
   */
  product: (field) => standalone_op_op('product', field),

  /**
   * Aggregate function for the mean (average) value.
   * @param {*} field The data field.
   * @return {number} The mean (average) of the values.
   */
  mean: (field) => standalone_op_op('mean', field),

  /**
   * Aggregate function for the average (mean) value.
   * @param {*} field The data field.
   * @return {number} The average (mean) of the values.
   */
  average: (field) => standalone_op_op('average', field),

  /**
   * Aggregate function for the sample variance.
   * @param {*} field The data field.
   * @return {number} The sample variance of the values.
   */
  variance: (field) => standalone_op_op('variance', field),

  /**
   * Aggregate function for the population variance.
   * @param {*} field The data field.
   * @return {number} The population variance of the values.
   */
  variancep: (field) => standalone_op_op('variancep', field),

  /**
   * Aggregate function for the sample standard deviation.
   * @param {*} field The data field.
   * @return {number} The sample standard deviation of the values.
   */
  stdev: (field) => standalone_op_op('stdev', field),

  /**
   * Aggregate function for the population standard deviation.
   * @param {*} field The data field.
   * @return {number} The population standard deviation of the values.
   */
  stdevp: (field) => standalone_op_op('stdevp', field),

  /**
   * Aggregate function for the minimum value.
   * @param {*} field The data field.
   * @return {number} The minimum value.
   */
  min: (field) => standalone_op_op('min', field),

  /**
   * Aggregate function for the maximum value.
   * @param {*} field The data field.
   * @return {number} The maximum value.
   */
  max: (field) => standalone_op_op('max', field),

  /**
   * Aggregate function to compute the quantile boundary
   * of a data field for a probability threshold.
   * @param {*} field The data field.
   * @param {number} p The probability threshold.
   * @return {number} The quantile value.
   */
  quantile: (field, p) => standalone_op_op('quantile', field, p),

  /**
   * Aggregate function for the median value.
   * This is a shorthand for the 0.5 quantile value.
   * @param {*} field The data field.
   * @return {number} The median value.
   */
  median: (field) => standalone_op_op('median', field),

  /**
   * Aggregate function for the sample covariance between two variables.
   * @param {*} field1 The first data field.
   * @param {*} field2 The second data field.
   * @return {number} The sample covariance of the values.
   */
  covariance: (field1, field2) => standalone_op_op('covariance', [field1, field2]),

  /**
   * Aggregate function for the population covariance between two variables.
   * @param {*} field1 The first data field.
   * @param {*} field2 The second data field.
   * @return {number} The population covariance of the values.
   */
  covariancep: (field1, field2) => standalone_op_op('covariancep', [field1, field2]),

  /**
   * Aggregate function for the product-moment correlation between two variables.
   * To instead compute a rank correlation, compute the average ranks for each
   * variable and then apply this function to the result.
   * @param {*} field1 The first data field.
   * @param {*} field2 The second data field.
   * @return {number} The correlation between the field values.
   */
  corr: (field1, field2) => standalone_op_op('corr', [field1, field2]),

  /**
   * Aggregate function for calculating a binning scheme in terms of
   * the minimum bin boundary, maximum bin boundary, and step size.
   * @param {*} field The data field.
   * @param {number} [maxbins=15] The maximum number of allowed bins.
   * @param {boolean} [nice=true] Flag indicating if the bin min and max
   *  should snap to "nice" human-friendly values.
   * @param {number} [minstep] The minimum allowed step size between bins.
   * @param {number} [step] The exact step size to use between bins.
   *  If specified, the maxbins and minstep arguments are ignored.
   * @return {[number, number, number]} The bin [min, max, and step] values.
   */
  bins: (field, maxbins, nice, minstep) =>
    standalone_op_op('bins', field, [maxbins, nice, minstep]),

  /**
   * Window function to assign consecutive row numbers, starting from 1.
   * @return {number} The row number value.
   */
  row_number: () => standalone_op_op('row_number'),

  /**
   * Window function to assign a rank to each value in a group, starting
   * from 1. Peer values are assigned the same rank. Subsequent ranks
   * reflect the number of prior values: if the first two values tie for
   * rank 1, the third value is assigned rank 3.
   * @return {number} The rank value.
   */
  rank: () => standalone_op_op('rank'),

  /**
   * Window function to assign a fractional (average) rank to each value in
   * a group, starting from 1. Peer values are assigned the average of their
   * indices: if the first two values tie, both will be assigned rank 1.5.
   * @return {number} The peer-averaged rank value.
   */
  avg_rank: () => standalone_op_op('avg_rank'),

  /**
   * Window function to assign a dense rank to each value in a group,
   * starting from 1. Peer values are assigned the same rank. Subsequent
   * ranks do not reflect the number of prior values: if the first two
   * values tie for rank 1, the third value is assigned rank 2.
   * @return {number} The dense rank value.
   */
  dense_rank: () => standalone_op_op('dense_rank'),

  /**
   * Window function to assign a percentage rank to each value in a group.
   * The percent is calculated as (rank - 1) / (group_size - 1).
   * @return {number} The percentage rank value.
   */
  percent_rank: () => standalone_op_op('percent_rank'),

  /**
   * Window function to assign a cumulative distribution value between 0 and 1
   * to each value in a group.
   * @return {number} The cumulative distribution value.
   */
  cume_dist: () => standalone_op_op('cume_dist'),

  /**
   * Window function to assign a quantile (e.g., percentile) value to each
   * value in a group. Accepts an integer parameter indicating the number of
   * buckets to use (e.g., 100 for percentiles, 5 for quintiles).
   * @param {number} num The number of buckets for ntile calculation.
   * @return {number} The quantile value.
   */
  ntile: (num) => standalone_op_op('ntile', null, num),

  /**
   * Window function to assign a value that precedes the current value by
   * a specified number of positions. If no such value exists, returns a
   * default value instead.
   * @param {*} field The data field.
   * @param {number} [offset=1] The lag offset from the current value.
   * @param {*} [defaultValue=undefined] The default value.
   * @return {*} The lagging value.
   */
  lag: (field, offset, defaultValue) => standalone_op_op('lag', field, [offset, defaultValue]),

  /**
   * Window function to assign a value that follows the current value by
   * a specified number of positions. If no such value exists, returns a
   * default value instead.
   * @param {*} field The data field.
   * @param {number} [offset=1] The lead offset from the current value.
   * @param {*} [defaultValue=undefined] The default value.
   * @return {*} The leading value.
   */
  lead: (field, offset, defaultValue) => standalone_op_op('lead', field, [offset, defaultValue]),

  /**
   * Window function to assign the first value in a sliding window frame.
   * @param {*} field The data field.
   * @return {*} The first value in the current frame.
   */
  first_value: (field) => standalone_op_op('first_value', field),

  /**
   * Window function to assign the last value in a sliding window frame.
   * @param {*} field The data field.
   * @return {*} The last value in the current frame.
   */
  last_value: (field) => standalone_op_op('last_value', field),

  /**
   * Window function to assign the nth value in a sliding window frame
   * (counting from 1), or undefined if no such value exists.
   * @param {*} field The data field.
   * @param {number} nth The nth position, starting from 1.
   * @return {*} The nth value in the current frame.
   */
  nth_value: (field, nth) => standalone_op_op('nth_value', field, nth),

  /**
   * Window function to fill in missing values with preceding values.
   * @param {*} field The data field.
   * @param {*} [defaultValue=undefined] The default value.
   * @return {*} The current value if valid, otherwise the first preceding
   *  valid value. If no such value exists, returns the default value.
   */
  fill_down: (field, defaultValue) => standalone_op_op('fill_down', field, defaultValue),

  /**
   * Window function to fill in missing values with subsequent values.
   * @param {*} field The data field.
   * @param {*} [defaultValue=undefined] The default value.
   * @return {*} The current value if valid, otherwise the first subsequent
   *  valid value. If no such value exists, returns the default value.
   */
  fill_up: (field, defaultValue) => standalone_op_op('fill_up', field, defaultValue)
});
;// ../../node_modules/arquero/src/util/unique-name.js


/* harmony default export */ function standalone_unique_name(names, name) {
  names = standalone_is_map_or_set(names) ? names : new Set(names);
  let uname = name;
  let index = 0;

  while (names.has(uname)) {
    uname = name + ++index;
  }

  return uname;
}
;// ../../node_modules/arquero/src/table/regroup.js




/**
 * Regroup table rows in response to a BitSet filter.
 * @param {GroupBySpec} groups The current groupby specification.
 * @param {BitSet} filter The filter to apply.
 */
function standalone_regroup(groups, filter) {
  if (!groups || !filter) return groups;

  // check for presence of rows for each group
  const { keys, rows, size } = groups;
  const map = new Int32Array(size);
  filter.scan(row => map[keys[row]] = 1);

  // check sum, exit early if all groups occur
  const sum = map.reduce((sum, val) => sum + val, 0);
  if (sum === size) return groups;

  // create group index map, filter exemplar rows
  const _rows = Array(sum);
  let _size = 0;
  for (let i = 0; i < size; ++i) {
    if (map[i]) _rows[map[i] = _size++] = rows[i];
  }

  // re-index the group keys
  const _keys = new Uint32Array(keys.length);
  filter.scan(row => _keys[row] = map[keys[row]]);

  return { ...groups, keys: _keys, rows: _rows, size: _size };
}

/**
 * Regroup table rows in response to a re-indexing.
 * This operation may or may not involve filtering of rows.
 * @param {GroupBySpec} groups The current groupby specification.
 * @param {Function} scan Function to scan new row indices.
 * @param {boolean} filter Flag indicating if filtering may occur.
 * @param {number} nrows The number of rows in the new table.
 */
function standalone_reindex(groups, scan, filter, nrows) {
  const { keys, rows, size } = groups;
  let _rows = rows;
  let _size = size;
  let map = null;

  if (filter) {
    // check for presence of rows for each group
    map = new Int32Array(size);
    scan(row => map[keys[row]] = 1);

    // check sum, regroup if not all groups occur
    const sum = map.reduce((sum, val) => sum + val, 0);
    if (sum !== size) {
      // create group index map, filter exemplar rows
      _rows = Array(sum);
      _size = 0;
      for (let i = 0; i < size; ++i) {
        if (map[i]) _rows[map[i] = _size++] = rows[i];
      }
    }
  }

  // re-index the group keys
  let r = -1;
  const _keys = new Uint32Array(nrows);
  const fn = _size !== size
    ? row => _keys[++r] = map[keys[row]]
    : row => _keys[++r] = keys[row];
  scan(fn);

  return { ...groups, keys: _keys, rows: _rows, size: _size };
}

function standalone_regroup_nest(table, idx, obj, type) {
  const agg = type === 'map' || type === true ? standalone_map_agg
    : type === 'entries' ? standalone_entries_agg
    : type === 'object' ? standalone_object_agg
    : standalone_util_error('groups option must be "map", "entries", or "object".');

  const { names } = table.groups();
  const col = standalone_unique_name(table.columnNames(), '_');

  // create table with one column of row objects
  // then aggregate into per-group arrays
  let t = table
    .select()
    .reify(idx)
    .create({ data: { [col]: obj } })
    .rollup({ [col]: standalone_array_agg(col) });

  // create nested structures for each level of grouping
  for (let i = names.length; --i >= 0;) {
    t = t
      .groupby(names.slice(0, i))
      .rollup({ [col]: agg(names[i], col) });
  }

  // return the final aggregated structure
  return t.get(col);
}
;// ../../node_modules/arquero/src/expression/ast/constants.js
const standalone_ArrayPattern = 'ArrayPattern';
const standalone_ArrowFunctionExpression = 'ArrowFunctionExpression';
const standalone_FunctionExpression = 'FunctionExpression';
const standalone_constants_Identifier = 'Identifier';
const standalone_constants_Literal = 'Literal';
const standalone_constants_MemberExpression = 'MemberExpression';
const standalone_constants_ObjectExpression = 'ObjectExpression';
const standalone_ObjectPattern = 'ObjectPattern';
const standalone_constants_Property = 'Property';

const standalone_constants_Column = 'Column';
const standalone_Constant = 'Constant';
const standalone_Dictionary = 'Dictionary';
const standalone_constants_Function = 'Function';
const standalone_Parameter = 'Parameter';
const standalone_constants_Op = 'Op';
;// ../../node_modules/arquero/src/expression/codegen.js



const standalone_codegen_visit = (node, opt) => {
  const f = standalone_visitors[node.type];
  return f
    ? f(node, opt)
    : standalone_util_error(`Unsupported expression construct: ${node.type}`);
};

const standalone_codegen_binary = (node, opt) => {
  return '(' + standalone_codegen_visit(node.left, opt) + ' ' + node.operator + ' ' + standalone_codegen_visit(node.right, opt) + ')';
};

const standalone_func = (node, opt) => {
  return '(' + standalone_list(node.params, opt) + ')=>' + standalone_codegen_visit(node.body, opt);
};

const standalone_call = (node, opt) => {
  return standalone_codegen_visit(node.callee, opt) + '(' + standalone_list(node.arguments, opt) + ')';
};

const standalone_list = (array, opt, delim = ',') => {
  return array.map(node => standalone_codegen_visit(node, opt)).join(delim);
};

const standalone_codegen_name = node => node.computed
  ? `[${standalone_to_string(node.name)}]`
  : `.${node.name}`;

const standalone_codegen_ref = (node, opt, method) => {
  const table = node.table || '';
  return `data${table}${standalone_codegen_name(node)}.${method}(${opt.index}${table})`;
};

const standalone_visitors = {
  Constant: node => node.raw,
  Column: (node, opt) => standalone_codegen_ref(node, opt, 'get'),
  Dictionary: (node, opt) => standalone_codegen_ref(node, opt, 'key'),
  Function: node => `fn.${node.name}`,
  Parameter: node => `$${standalone_codegen_name(node)}`,
  Op: (node, opt) => `op(${standalone_to_string(node.name)},${opt.op || opt.index})`,
  Literal: node => node.raw,
  Identifier: node => node.name,
  TemplateLiteral: (node, opt) => {
    const { quasis, expressions } = node;
    const n = expressions.length;
    let t = quasis[0].value.raw;
    for (let i = 0; i < n;) {
      t += '${' + standalone_codegen_visit(expressions[i], opt) + '}' + quasis[++i].value.raw;
    }
    return '`' + t + '`';
  },
  MemberExpression: (node, opt) => {
    const d = !node.computed;
    const o = standalone_codegen_visit(node.object, opt);
    const p = standalone_codegen_visit(node.property, opt);
    return o + (d ? '.' + p : '[' + p + ']');
  },
  CallExpression: standalone_call,
  NewExpression: (node, opt) => {
    return 'new ' + standalone_call(node, opt);
  },
  ArrayExpression: (node, opt) => {
    return '[' + standalone_list(node.elements, opt) + ']';
  },
  AssignmentExpression: standalone_codegen_binary,
  BinaryExpression: standalone_codegen_binary,
  LogicalExpression: standalone_codegen_binary,
  UnaryExpression: (node, opt) => {
    return '(' + node.operator + standalone_codegen_visit(node.argument, opt) + ')';
  },
  ConditionalExpression: (node, opt) => {
    return '(' + standalone_codegen_visit(node.test, opt) +
      '?' + standalone_codegen_visit(node.consequent, opt) +
      ':' + standalone_codegen_visit(node.alternate, opt) + ')';
  },
  ObjectExpression: (node, opt) => {
    return '({' + standalone_list(node.properties, opt) + '})';
  },
  Property: (node, opt) => {
    const key = standalone_codegen_visit(node.key, opt);
    return (node.computed ? `[${key}]` : key) + ':' + standalone_codegen_visit(node.value, opt);
  },

  ArrowFunctionExpression: standalone_func,
  FunctionExpression: standalone_func,
  FunctionDeclaration: standalone_func,

  ArrayPattern: (node, opt) => {
    return '[' + standalone_list(node.elements, opt) + ']';
  },
  ObjectPattern: (node, opt) => {
    return '{' + standalone_list(node.properties, opt) + '}';
  },
  VariableDeclaration: (node, opt) => {
    return node.kind + ' ' + standalone_list(node.declarations, opt, ',');
  },
  VariableDeclarator: (node, opt) => {
    return standalone_codegen_visit(node.id, opt) + '=' + standalone_codegen_visit(node.init, opt);
  },
  SpreadElement: (node, opt) => {
    return '...' + standalone_codegen_visit(node.argument, opt);
  },

  BlockStatement: (node, opt) => {
    return '{' + standalone_list(node.body, opt, ';') + ';}';
  },
  BreakStatement: () => {
    return 'break';
  },
  ExpressionStatement: (node, opt) => {
    return standalone_codegen_visit(node.expression, opt);
  },
  IfStatement: (node, opt) => {
    return 'if (' + standalone_codegen_visit(node.test, opt) + ')'
      + standalone_codegen_visit(node.consequent, opt)
      + (node.alternate ? ' else ' + standalone_codegen_visit(node.alternate, opt) : '');
  },
  SwitchStatement: (node, opt) => {
    return 'switch (' + standalone_codegen_visit(node.discriminant, opt) + ') {'
     + standalone_list(node.cases, opt, '')
     + '}';
  },
  SwitchCase: (node, opt) => {
    return (node.test ? 'case ' + standalone_codegen_visit(node.test, opt) : 'default')
      + ': '
      + standalone_list(node.consequent, opt, ';') + ';';
  },
  ReturnStatement: (node, opt) => {
    return 'return ' + standalone_codegen_visit(node.argument, opt);
  },
  Program: (node, opt) => standalone_codegen_visit(node.body[0], opt)
};

/* harmony default export */ function standalone_expression_codegen(node, opt = { index: 'row' }) {
  return standalone_codegen_visit(node, opt);
}
;// ../../node_modules/arquero/src/util/bins.js
/* harmony default export */ function standalone_util_bins(min, max, maxbins = 15, nice = true, minstep = 0, step) {
  const base = 10;
  const logb = Math.LN10;

  if (step == null) {
    const level = Math.ceil(Math.log(maxbins) / logb);
    const span = (max - min) || Math.abs(min) || 1;
    const div = [5, 2];

    step = Math.max(
      minstep,
      Math.pow(base, Math.round(Math.log(span) / logb) - level)
    );

    // increase step size if too many bins
    while (Math.ceil(span / step) > maxbins) {
      step *= base;
    }

    // decrease step size if it stays within maxbins
    const n = div.length;
    for (let i = 0; i < n; ++i) {
      const v = step / div[i];
      if (v >= minstep && span / v <= maxbins) {
        step = v;
      }
    }
  }

  // snap to "nice" boundaries
  if (nice) {
    let v = Math.log(step);
    const precision = v >= 0 ? 0 : ~~(-v / logb) + 1;
    const eps = Math.pow(base, -precision - 1);
    v = Math.floor(min / step + eps) * step;
    min = min < v ? v - step : v;
    max = Math.ceil(max / step) * step;
  }

  return [
    min,
    max === min ? min + step : max,
    step
  ];
}
;// ../../node_modules/arquero/src/util/key-function.js





function standalone_key_function_key(value) {
  const type = typeof value;
  return type === 'string' ? `"${value}"`
    : type !== 'object' || !value ? value
    : standalone_is_date(value) ? +value
    : standalone_is_array(value) || standalone_is_typed_array(value) ? `[${value.map(standalone_key_function_key)}]`
    : standalone_is_regexp(value) ? value + ''
    : standalone_objectKey(value);
}

function standalone_objectKey(value) {
  let s = '{';
  let i = -1;
  for (const k in value) {
    if (++i > 0) s += ',';
    s += `"${k}":${standalone_key_function_key(value[k])}`;
  }
  s += '}';
  return s;
}

/* harmony default export */ function standalone_key_function(get, nulls) {
  const n = get.length;
  return n === 1
    ? (row, data) => standalone_key_function_key(get[0](row, data))
    : (row, data) => {
        let s = '';
        for (let i = 0; i < n; ++i) {
          if (i > 0) s += '|';
          const v = get[i](row, data);
          if (nulls && (v == null || v !== v)) return null;
          s += standalone_key_function_key(v);
        }
        return s;
      };
}
;// ../../node_modules/arquero/src/util/distinct-map.js


/* harmony default export */ function standalone_distinct_map() {
  const map = new Map();
  return {
    count() {
      return map.size;
    },
    values() {
      return Array.from(map.values(), _ => _.v);
    },
    increment(v) {
      const k = standalone_key_function_key(v);
      const e = map.get(k);
      e ? ++e.n : map.set(k, { v, n: 1 });
    },
    decrement(v) {
      const k = standalone_key_function_key(v);
      const e = map.get(k);
      e.n === 1 ? map.delete(k) : --e.n;
    },
    forEach(fn) {
      map.forEach(({ v, n }) => fn(v, n));
    }
  };
}
;// ../../node_modules/arquero/src/util/no-op.js
/* harmony default export */ function standalone_no_op() {}
;// ../../node_modules/arquero/src/util/product.js
/* harmony default export */ function standalone_product(values, start = 0, stop = values.length) {
  let prod = values[start++];

  for (let i = start; i < stop; ++i) {
    prod *= values[i];
  }

  return prod;
}
;// ../../node_modules/arquero/src/op/aggregate-functions.js







/**
 * Initialize an aggregate operator.
 */
function standalone_initOp(op) {
  op.init = op.init || standalone_no_op;
  op.add = op.add || standalone_no_op;
  op.rem = op.rem || standalone_no_op;
  return op;
}

function standalone_initProduct(s, value) {
  s.product_v = false;
  return s.product = value;
}

/**
 * Initialize an aggregate operator.
 * @callback AggregateInit
 * @param {object} state The aggregate state object.
 * @return {void}
 */

/**
 * Add a value to an aggregate operator.
 * @callback AggregateAdd
 * @param {object} state The aggregate state object.
 * @param {*} value The value to add.
 * @return {void}
 */

/**
 * Remove a value from an aggregate operator.
 * @callback AggregateRem
 * @param {object} state The aggregate state object.
 * @param {*} value The value to remove.
 * @return {void}
 */

/**
 * Retrive an output value from an aggregate operator.
 * @callback AggregateValue
 * @param {object} state The aggregate state object.
 * @return {*} The output value.
 */

/**
 * An operator instance for an aggregate function.
 * @typedef {object} AggregateOperator
 * @property {AggregateInit} init Initialize the operator.
 * @property {AggregateAdd} add Add a value to the operator state.
 * @property {AggregateRem} rem Remove a value from the operator state.
 * @property {AggregateValue} value Retrieve an output value.
 */

/**
 * Create a new aggregate operator instance.
 * @callback AggregateCreate
 * @param {...any} params The aggregate operator parameters.
 * @return {AggregateOperator} The instantiated aggregate operator.
 */

/**
 * An operator definition for an aggregate function.
 * @typedef {object} AggregateDef
 * @property {AggregateCreate} create Create a new operator instance.
 * @property {number[]} param Two-element array containing the
 *  counts of input fields and additional parameters.
 * @property {string[]} [req] Names of operators required by this one.
 * @property {string[]} [stream] Names of operators required by this one
 *  for streaming operations (value removes).
 */

/**
 * Aggregate operator definitions.
 */
/* harmony default export */ const standalone_aggregate_functions = ({
  /** @type {AggregateDef} */
  count: {
    create: () => standalone_initOp({
      value: s => s.count
    }),
    param: []
  },

  /** @type {AggregateDef} */
  array_agg: {
    create: () => standalone_initOp({
      init: s => s.values = true,
      value: s => s.list.values(s.stream)
    }),
    param: [1]
  },

  /** @type {AggregateDef} */
  object_agg: {
    create: () => standalone_initOp({
      init:  s => s.values = true,
      value: s => Object.fromEntries(s.list.values())
    }),
    param: [2]
  },

  /** @type {AggregateDef} */
  map_agg: {
    create: () => standalone_initOp({
      init:  s => s.values = true,
      value: s => new Map(s.list.values())
    }),
    param: [2]
  },

  /** @type {AggregateDef} */
  entries_agg: {
    create: () => standalone_initOp({
      init:  s => s.values = true,
      value: s => s.list.values(s.stream)
    }),
    param: [2]
  },

  /** @type {AggregateDef} */
  any: {
    create: () => standalone_initOp({
      add: (s, v) => { if (s.any == null) s.any = v; },
      value: s => s.valid ? s.any : standalone_util_null
    }),
    param: [1]
  },

  /** @type {AggregateDef} */
  valid: {
    create: () => standalone_initOp({
      value: s => s.valid
    }),
    param: [1]
  },

  /** @type {AggregateDef} */
  invalid: {
    create: () => standalone_initOp({
      value: s => s.count - s.valid
    }),
    param: [1]
  },

  /** @type {AggregateDef} */
  distinct: {
    create: () => ({
      init: s => s.distinct = standalone_distinct_map(),
      value: s => s.distinct.count() + (s.valid === s.count ? 0 : 1),
      add: (s, v) => s.distinct.increment(v),
      rem: (s, v) => s.distinct.decrement(v)
    }),
    param: [1]
  },

  /** @type {AggregateDef} */
  array_agg_distinct: {
    create: () => standalone_initOp({
      value: s => s.distinct.values()
    }),
    param: [1],
    req: ['distinct']
  },

  /** @type {AggregateDef} */
  mode: {
    create: () => standalone_initOp({
      value: s => {
        let mode = standalone_util_null;
        let max = 0;
        s.distinct.forEach((value, count) => {
          if (count > max) {
            max = count;
            mode = value;
          }
        });
        return mode;
      }
    }),
    param: [1],
    req: ['distinct']
  },

  /** @type {AggregateDef} */
  sum: {
    create: () => ({
      init:  s => s.sum = 0,
      value: s => s.valid ? s.sum : standalone_util_null,
      add: (s, v) => standalone_is_bigint(v)
        ? (s.sum === 0 ? s.sum = v : s.sum += v)
        : s.sum += +v,
      rem: (s, v) => s.sum -= v
    }),
    param: [1]
  },

  /** @type {AggregateDef} */
  product: {
    create: () => ({
      init:  s => standalone_initProduct(s, 1),
      value: s => s.valid
        ? (
            s.product_v
              ? standalone_initProduct(s, standalone_product(s.list.values()))
              : s.product
          )
        : undefined,
      add: (s, v) => standalone_is_bigint(v)
        ? (s.product === 1 ? s.product = v : s.product *= v)
        : s.product *= v,
      rem: (s, v) => (v == 0 || v === Infinity || v === -Infinity)
        ? s.product_v = true
        : s.product /= v
    }),
    param: [1],
    stream: ['array_agg']
  },

  /** @type {AggregateDef} */
  mean: {
    create: () => ({
      init: s => s.mean = 0,
      value: s => s.valid ? s.mean : standalone_util_null,
      add: (s, v) => {
        s.mean_d = v - s.mean;
        s.mean += s.mean_d / s.valid;
      },
      rem: (s, v) => {
        s.mean_d = v - s.mean;
        s.mean -= s.valid ? s.mean_d / s.valid : s.mean;
      }
    }),
    param: [1]
  },

  /** @type {AggregateDef} */
  average: {
    create: () => standalone_initOp({
      value: s => s.valid ? s.mean : standalone_util_null
    }),
    param: [1],
    req: ['mean']
  },

  /** @type {AggregateDef} */
  variance: {
    create: () => ({
      init:  s => s.dev = 0,
      value: s => s.valid > 1 ? s.dev / (s.valid - 1) : standalone_util_null,
      add: (s, v) => s.dev += s.mean_d * (v - s.mean),
      rem: (s, v) => s.dev -= s.mean_d * (v - s.mean)
    }),
    param: [1],
    req: ['mean']
  },

  /** @type {AggregateDef} */
  variancep: {
    create: () => standalone_initOp({
      value: s => s.valid > 1 ? s.dev / s.valid : standalone_util_null
    }),
    param: [1],
    req: ['variance']
  },

  /** @type {AggregateDef} */
  stdev: {
    create: () => standalone_initOp({
      value: s => s.valid > 1 ? Math.sqrt(s.dev / (s.valid - 1)) : standalone_util_null
    }),
    param: [1],
    req: ['variance']
  },

  /** @type {AggregateDef} */
  stdevp: {
    create: () => standalone_initOp({
      value: s => s.valid > 1 ? Math.sqrt(s.dev / s.valid) : standalone_util_null
    }),
    param: [1],
    req: ['variance']
  },

  /** @type {AggregateDef} */
  min: {
    create: () => ({
      init:  s => s.min = standalone_util_null,
      value: s => s.min = (Number.isNaN(s.min) ? s.list.min() : s.min),
      add: (s, v) => { if (v < s.min || s.min === standalone_util_null) s.min = v; },
      rem: (s, v) => { if (v <= s.min) s.min = NaN; }
    }),
    param: [1],
    stream: ['array_agg']
  },

  /** @type {AggregateDef} */
  max: {
    create: () => ({
      init:  s => s.max = standalone_util_null,
      value: s => s.max = (Number.isNaN(s.max) ? s.list.max() : s.max),
      add: (s, v) => { if (v > s.max || s.max === standalone_util_null) s.max = v; },
      rem: (s, v) => { if (v >= s.max) s.max = NaN; }
    }),
    param: [1],
    stream: ['array_agg']
  },

  /** @type {AggregateDef} */
  quantile: {
    create: (p) => standalone_initOp({
      value: s => s.list.quantile(p)
    }),
    param: [1, 1],
    req: ['array_agg']
  },

  /** @type {AggregateDef} */
  median: {
    create: () => standalone_initOp({
      value: s => s.list.quantile(0.5)
    }),
    param: [1],
    req: ['array_agg']
  },

  /** @type {AggregateDef} */
  covariance: {
    create: () => ({
      init:  s => {
        s.cov = s.mean_x = s.mean_y = s.dev_x = s.dev_y = 0;
      },
      value: s => s.valid > 1 ? s.cov / (s.valid - 1) : standalone_util_null,
      add: (s, x, y) => {
        const dx = x - s.mean_x;
        const dy = y - s.mean_y;
        s.mean_x += dx / s.valid;
        s.mean_y += dy / s.valid;
        const dy2 = y - s.mean_y;
        s.dev_x += dx * (x - s.mean_x);
        s.dev_y += dy * dy2;
        s.cov += dx * dy2;
      },
      rem: (s, x, y) => {
        const dx = x - s.mean_x;
        const dy = y - s.mean_y;
        s.mean_x -= s.valid ? dx / s.valid : s.mean_x;
        s.mean_y -= s.valid ? dy / s.valid : s.mean_y;
        const dy2 = y - s.mean_y;
        s.dev_x -= dx * (x - s.mean_x);
        s.dev_y -= dy * dy2;
        s.cov -= dx * dy2;
      }
    }),
    param: [2]
  },

  /** @type {AggregateDef} */
  covariancep: {
    create: () => standalone_initOp({
      value: s => s.valid > 1 ? s.cov / s.valid : standalone_util_null
    }),
    param: [2],
    req: ['covariance']
  },

  /** @type {AggregateDef} */
  corr: {
    create: () => standalone_initOp({
      value: s => s.valid > 1
        ? s.cov / (Math.sqrt(s.dev_x) * Math.sqrt(s.dev_y))
        : standalone_util_null
    }),
    param: [2],
    req: ['covariance']
  },

  /** @type {AggregateDef} */
  bins: {
    create: (maxbins, nice, minstep, step) => standalone_initOp({
      value: s => standalone_util_bins(s.min, s.max, maxbins, nice, minstep, step)
    }),
    param: [1, 4],
    req: ['min', 'max']
  }
});
;// ../../node_modules/arquero/src/op/window-functions.js





/**
 * Initialize a window operator.
 * @callback WindowInit
 * @return {void}
 */

/**
 * Retrieve an output value from a window operator.
 * @callback WindowValue
 * @param {WindowState} state The window state object.
 * @return {*} The output value.
 */

/**
 * An operator instance for a window function.
 * @typedef {object} WindowOperator
 * @property {AggregateInit} init Initialize the operator.
 * @property {AggregateValue} value Retrieve an output value.
 */

/**
 * Create a new window operator instance.
 * @callback WindowCreate
 * @param {...any} params The aggregate operator parameters.
 * @return {WindowOperator} The instantiated window operator.
 */

/**
 * An operator definition for a window function.
 * @typedef {object} WindowDef
 * @property {AggregateCreate} create Create a new operator instance.
 * @property {number[]} param Two-element array containing the
 *  counts of input fields and additional parameters.
 */

const standalone_window_functions_rank = {
  create() {
    let rank;
    return {
      init: () => rank = 1,
      value: w => {
        const i = w.index;
        return (i && !w.peer(i)) ? (rank = i + 1) : rank;
      }
    };
  },
  param: []
};

const standalone_cume_dist = {
  create() {
    let cume;
    return {
      init: () => cume = 0,
      value: w => {
        const { index, peer, size } = w;
        let i = index;
        if (cume < i) {
          while (i + 1 < size && peer(i + 1)) ++i;
          cume = i;
        }
        return (1 + cume) / size;
      }
    };
  },
  param: []
};

/**
 * Window operator definitions.
 */
/* harmony default export */ const standalone_window_functions = ({
  /** @type {WindowDef} */
  row_number: {
    create() {
      return {
        init: standalone_no_op,
        value: w => w.index + 1
      };
    },
    param: []
  },

  /** @type {WindowDef} */
  rank: standalone_window_functions_rank,

  /** @type {WindowDef} */
  avg_rank: {
    create() {
      let j, rank;
      return {
        init: () => (j = -1, rank = 1),
        value: w => {
          const i = w.index;
          if (i >= j) {
            for (rank = j = i + 1; w.peer(j); rank += ++j);
            rank /= (j - i);
          }
          return rank;
        }
      };
    },
    param: []
  },

  /** @type {WindowDef} */
  dense_rank: {
    create() {
      let drank;
      return {
        init: () => drank = 1,
        value: w => {
          const i = w.index;
          return (i && !w.peer(i)) ? ++drank : drank;
        }
      };
    },
    param: []
  },

  /** @type {WindowDef} */
  percent_rank: {
    create() {
      const { init, value } = standalone_window_functions_rank.create();
      return {
        init,
        value: w => (value(w) - 1) / (w.size - 1)
      };
    },
    param: []
  },

  /** @type {WindowDef} */
  cume_dist: standalone_cume_dist,

  /** @type {WindowDef} */
  ntile: {
    create(num) {
      num = +num;
      if (!(num > 0)) standalone_util_error('ntile num must be greater than zero.');
      const { init, value } = standalone_cume_dist.create();
      return {
        init,
        value: w => Math.ceil(num * value(w))
      };
    },
    param: [0, 1]
  },

  /** @type {WindowDef} */
  lag: {
    create(offset, defaultValue = standalone_util_null) {
      offset = +offset || 1;
      return {
        init: standalone_no_op,
        value: (w, f) => {
          const i = w.index - offset;
          return i >= 0 ? w.value(i, f) : defaultValue;
        }
      };
    },
    param: [1, 2]
  },

  /** @type {WindowDef} */
  lead: {
    create(offset, defaultValue = standalone_util_null) {
      offset = +offset || 1;
      return {
        init: standalone_no_op,
        value: (w, f) => {
          const i = w.index + offset;
          return i < w.size ? w.value(i, f) : defaultValue;
        }
      };
    },
    param: [1, 2]
  },

  /** @type {WindowDef} */
  first_value: {
    create() {
      return {
        init: standalone_no_op,
        value: (w, f) => w.value(w.i0, f)
      };
    },
    param: [1]
  },

  /** @type {WindowDef} */
  last_value: {
    create() {
      return {
        init: standalone_no_op,
        value: (w, f) => w.value(w.i1 - 1, f)
      };
    },
    param: [1]
  },

  /** @type {WindowDef} */
  nth_value: {
    create(nth) {
      nth = +nth;
      if (!(nth > 0)) standalone_util_error('nth_value nth must be greater than zero.');
      return {
        init: standalone_no_op,
        value: (w, f) => {
          const i = w.i0 + (nth - 1);
          return i < w.i1 ? w.value(i, f) : standalone_util_null;
        }
      };
    },
    param: [1, 1]
  },

  /** @type {WindowDef} */
  fill_down: {
    create(defaultValue = standalone_util_null) {
      let value;
      return {
        init: () => value = defaultValue,
        value: (w, f) => {
          const v = w.value(w.index, f);
          return standalone_is_valid(v) ? (value = v) : value;
        }
      };
    },
    param: [1, 1]
  },

  /** @type {WindowDef} */
  fill_up: {
    create(defaultValue = standalone_util_null) {
      let value, idx;
      return {
        init: () => (value = defaultValue, idx = -1),
        value: (w, f) => w.index <= idx ? value
          : (idx = standalone_window_functions_find(w, f, w.index)) >= 0 ? (value = w.value(idx, f))
          : (idx = w.size, value = defaultValue)
      };
    },
    param: [1, 1]
  }
});

function standalone_window_functions_find(w, f, i) {
  for (const n = w.size; i < n; ++i) {
    if (standalone_is_valid(w.value(i, f))) return i;
  }
  return -1;
}

;// ../../node_modules/arquero/src/op/index.js







/**
 * Check if an aggregate function with the given name exists.
 * @param {string} name The name of the aggregate function.
 * @return {boolean} True if found, false otherwise.
 */
function standalone_hasAggregate(name) {
  return standalone_util_has(standalone_aggregate_functions, name);
}

/**
 * Check if a window function with the given name exists.
 * @param {string} name The name of the window function.
 * @return {boolean} True if found, false otherwise.
 */
function standalone_hasWindow(name) {
  return standalone_util_has(standalone_window_functions, name);
}

/**
 * Check if an expression function with the given name exists.
 * @param {string} name The name of the function.
 * @return {boolean} True if found, false otherwise.
 */
 function standalone_hasFunction(name) {
  return standalone_util_has(standalone_op_functions, name) || name === 'row_object';
}

/**
 * Get an aggregate function definition.
 * @param {string} name The name of the aggregate function.
 * @return {AggregateDef} The aggregate function definition,
 *  or undefined if not found.
 */
function standalone_getAggregate(name) {
  return standalone_hasAggregate(name) && standalone_aggregate_functions[name];
}

/**
 * Get a window function definition.
 * @param {string} name The name of the window function.
 * @return {WindowDef} The window function definition,
 *  or undefined if not found.
 */
function standalone_getWindow(name) {
  return standalone_hasWindow(name) && standalone_window_functions[name];
}

/**
 * Get an expression function definition.
 * @param {string} name The name of the function.
 * @return {Function} The function instance, or undefined if not found.
 */
function standalone_getFunction(name) {
  return standalone_hasFunction(name) && functions[name];
}
;// ../../node_modules/arquero/src/expression/compile.js


function standalone_compile_compile(code, fn, params) {
  code = `"use strict"; return ${code};`;
  return (Function('fn', '$', code))(fn, params);
}

/* harmony default export */ const standalone_expression_compile = ({
  escape: (code, func, params) => standalone_compile_compile(code, func, params),
  expr:   (code, params) => standalone_compile_compile(`(row,data,op)=>${code}`, standalone_op_functions, params),
  expr2:  (code, params) => standalone_compile_compile(`(row0,data0,row,data)=>${code}`, standalone_op_functions, params),
  join:   (code, params) => standalone_compile_compile(`(row1,data1,row2,data2)=>${code}`, standalone_op_functions, params),
  param:  (code, params) => standalone_compile_compile(code, standalone_op_functions, params)
});
;// ../../node_modules/arquero/src/expression/rewrite.js



const standalone_dictOps = {
  '==': 1,
  '!=': 1,
  '===': 1,
  '!==': 1
};

/**
 * Rewrite AST node to be a table column reference.
 * Additionally optimizes dictionary column operations.
 * @param {object} ref AST node to rewrite to a column reference.
 * @param {string} name The name of the column.
 * @param {number} index The table index of the column.
 * @param {object} col The actual table column instance.
 * @param {object} op Parent AST node operating on the column reference.
 */
/* harmony default export */ function standalone_rewrite(ref, name, index = 0, col, op) {
  ref.type = standalone_constants_Column;
  ref.name = name;
  ref.table = index;

  // proceed only if has parent op and is a dictionary column
  if (op && col && standalone_util_is_function(col.keyFor)) {
    // get other arg if op is an optimizeable operation
    const lit = standalone_dictOps[op.operator]
      ? op.left === ref ? op.right : op.left
      : op.callee && op.callee.name === 'equal'
      ? op.arguments[op.arguments[0] === ref ? 1 : 0]
      : null;

    // rewrite as dictionary lookup if other arg is a literal
    if (lit && lit.type === standalone_constants_Literal) {
      standalone_rewriteDictionary(op, ref, lit, col.keyFor(lit.value));
    }
  }

  return ref;
}

function standalone_rewriteDictionary(op, ref, lit, key) {
  if (key < 0) {
    // value not in dictionary, rewrite op as false literal
    op.type = standalone_constants_Literal;
    op.value = false;
    op.raw = 'false';
  } else {
    // rewrite ref as dict key access
    ref.type = standalone_Dictionary;

    // rewrite literal as target dict key
    lit.value = key;
    lit.raw = key + '';
  }

  return true;
}
;// ../../node_modules/arquero/src/util/entries.js



/* harmony default export */ function standalone_util_entries(value) {
  return standalone_is_array(value) ? value
    : standalone_is_map(value) ? value.entries()
    : value ? Object.entries(value)
    : [];
}
;// ../../node_modules/arquero/src/expression/row-object.js








const standalone_row_object_ROW_OBJECT = 'row_object';

function standalone_rowObjectExpression(node, props) {
  node.type = standalone_constants_ObjectExpression;

  const p = node.properties = [];
  for (const prop of standalone_util_entries(props)) {
    const [name, key] = standalone_is_array(prop) ? prop : [prop, prop];
    p.push({
      type: standalone_constants_Property,
      key: { type: standalone_constants_Literal, raw: standalone_to_string(key) },
      value: standalone_rewrite({ computed: true }, name)
    });
  }

  return node;
}

function standalone_rowObjectCode(props) {
  return standalone_expression_codegen(standalone_rowObjectExpression({}, props));
}

function standalone_rowObjectBuilder(props) {
  return standalone_expression_compile.expr(standalone_rowObjectCode(props));
}
;// ../../node_modules/flatbuffers/js/flatbuffers.mjs
/// @file
/// @addtogroup flatbuffers_javascript_api
/// @{
/// @cond FLATBUFFERS_INTERNAL

/**
 * @fileoverview
 *
 * Need to suppress 'global this' error so the Node.js export line doesn't cause
 * closure compile to error out.
 * @suppress {globalThis}
 */

/**
 * @const
 * @namespace
 */
var standalone_flatbuffers = {};

/**
 * @typedef {number}
 */
standalone_flatbuffers.Offset;

/**
 * @typedef {{
 *   bb: flatbuffers.ByteBuffer,
 *   bb_pos: number
 * }}
 */
standalone_flatbuffers.Table;

/**
 * @type {number}
 * @const
 */
standalone_flatbuffers.SIZEOF_SHORT = 2;

/**
 * @type {number}
 * @const
 */
standalone_flatbuffers.SIZEOF_INT = 4;

/**
 * @type {number}
 * @const
 */
standalone_flatbuffers.FILE_IDENTIFIER_LENGTH = 4;

/**
 * @enum {number}
 */
standalone_flatbuffers.Encoding = {
  UTF8_BYTES: 1,
  UTF16_STRING: 2
};

/**
 * @type {Int32Array}
 * @const
 */
standalone_flatbuffers.int32 = new Int32Array(2);

/**
 * @type {Float32Array}
 * @const
 */
standalone_flatbuffers.float32 = new Float32Array(standalone_flatbuffers.int32.buffer);

/**
 * @type {Float64Array}
 * @const
 */
standalone_flatbuffers.float64 = new Float64Array(standalone_flatbuffers.int32.buffer);

/**
 * @type {boolean}
 * @const
 */
standalone_flatbuffers.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;

////////////////////////////////////////////////////////////////////////////////

/**
 * @constructor
 * @param {number} low
 * @param {number} high
 */
standalone_flatbuffers.Long = function(low, high) {
  /**
   * @type {number}
   * @const
   */
  this.low = low | 0;

  /**
   * @type {number}
   * @const
   */
  this.high = high | 0;
};

/**
 * @param {number} low
 * @param {number} high
 * @returns {flatbuffers.Long}
 */
standalone_flatbuffers.Long.create = function(low, high) {
  // Special-case zero to avoid GC overhead for default values
  return low == 0 && high == 0 ? standalone_flatbuffers.Long.ZERO : new standalone_flatbuffers.Long(low, high);
};

/**
 * @returns {number}
 */
standalone_flatbuffers.Long.prototype.toFloat64 = function() {
  return (this.low >>> 0) + this.high * 0x100000000;
};

/**
 * @param {flatbuffers.Long} other
 * @returns {boolean}
 */
standalone_flatbuffers.Long.prototype.equals = function(other) {
  return this.low == other.low && this.high == other.high;
};

/**
 * @type {flatbuffers.Long}
 * @const
 */
standalone_flatbuffers.Long.ZERO = new standalone_flatbuffers.Long(0, 0);

/// @endcond
////////////////////////////////////////////////////////////////////////////////
/**
 * Create a FlatBufferBuilder.
 *
 * @constructor
 * @param {number=} opt_initial_size
 */
standalone_flatbuffers.Builder = function(opt_initial_size) {
  if (!opt_initial_size) {
    var initial_size = 1024;
  } else {
    var initial_size = opt_initial_size;
  }

  /**
   * @type {flatbuffers.ByteBuffer}
   * @private
   */
  this.bb = standalone_flatbuffers.ByteBuffer.allocate(initial_size);

  /**
   * Remaining space in the ByteBuffer.
   *
   * @type {number}
   * @private
   */
  this.space = initial_size;

  /**
   * Minimum alignment encountered so far.
   *
   * @type {number}
   * @private
   */
  this.minalign = 1;

  /**
   * The vtable for the current table.
   *
   * @type {Array.<number>}
   * @private
   */
  this.vtable = null;

  /**
   * The amount of fields we're actually using.
   *
   * @type {number}
   * @private
   */
  this.vtable_in_use = 0;

  /**
   * Whether we are currently serializing a table.
   *
   * @type {boolean}
   * @private
   */
  this.isNested = false;

  /**
   * Starting offset of the current struct/table.
   *
   * @type {number}
   * @private
   */
  this.object_start = 0;

  /**
   * List of offsets of all vtables.
   *
   * @type {Array.<number>}
   * @private
   */
  this.vtables = [];

  /**
   * For the current vector being built.
   *
   * @type {number}
   * @private
   */
  this.vector_num_elems = 0;

  /**
   * False omits default values from the serialized data
   *
   * @type {boolean}
   * @private
   */
  this.force_defaults = false;
};

standalone_flatbuffers.Builder.prototype.clear = function() {
  this.bb.clear();
  this.space = this.bb.capacity();
  this.minalign = 1;
  this.vtable = null;
  this.vtable_in_use = 0;
  this.isNested = false;
  this.object_start = 0;
  this.vtables = [];
  this.vector_num_elems = 0;
  this.force_defaults = false;
};

/**
 * In order to save space, fields that are set to their default value
 * don't get serialized into the buffer. Forcing defaults provides a
 * way to manually disable this optimization.
 *
 * @param {boolean} forceDefaults true always serializes default values
 */
standalone_flatbuffers.Builder.prototype.forceDefaults = function(forceDefaults) {
  this.force_defaults = forceDefaults;
};

/**
 * Get the ByteBuffer representing the FlatBuffer. Only call this after you've
 * called finish(). The actual data starts at the ByteBuffer's current position,
 * not necessarily at 0.
 *
 * @returns {flatbuffers.ByteBuffer}
 */
standalone_flatbuffers.Builder.prototype.dataBuffer = function() {
  return this.bb;
};

/**
 * Get the bytes representing the FlatBuffer. Only call this after you've
 * called finish().
 *
 * @returns {Uint8Array}
 */
standalone_flatbuffers.Builder.prototype.asUint8Array = function() {
  return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset());
};

/// @cond FLATBUFFERS_INTERNAL
/**
 * Prepare to write an element of `size` after `additional_bytes` have been
 * written, e.g. if you write a string, you need to align such the int length
 * field is aligned to 4 bytes, and the string data follows it directly. If all
 * you need to do is alignment, `additional_bytes` will be 0.
 *
 * @param {number} size This is the of the new element to write
 * @param {number} additional_bytes The padding size
 */
standalone_flatbuffers.Builder.prototype.prep = function(size, additional_bytes) {
  // Track the biggest thing we've ever aligned to.
  if (size > this.minalign) {
    this.minalign = size;
  }

  // Find the amount of alignment needed such that `size` is properly
  // aligned after `additional_bytes`
  var align_size = ((~(this.bb.capacity() - this.space + additional_bytes)) + 1) & (size - 1);

  // Reallocate the buffer if needed.
  while (this.space < align_size + size + additional_bytes) {
    var old_buf_size = this.bb.capacity();
    this.bb = standalone_flatbuffers.Builder.growByteBuffer(this.bb);
    this.space += this.bb.capacity() - old_buf_size;
  }

  this.pad(align_size);
};

/**
 * @param {number} byte_size
 */
standalone_flatbuffers.Builder.prototype.pad = function(byte_size) {
  for (var i = 0; i < byte_size; i++) {
    this.bb.writeInt8(--this.space, 0);
  }
};

/**
 * @param {number} value
 */
standalone_flatbuffers.Builder.prototype.writeInt8 = function(value) {
  this.bb.writeInt8(this.space -= 1, value);
};

/**
 * @param {number} value
 */
standalone_flatbuffers.Builder.prototype.writeInt16 = function(value) {
  this.bb.writeInt16(this.space -= 2, value);
};

/**
 * @param {number} value
 */
standalone_flatbuffers.Builder.prototype.writeInt32 = function(value) {
  this.bb.writeInt32(this.space -= 4, value);
};

/**
 * @param {flatbuffers.Long} value
 */
standalone_flatbuffers.Builder.prototype.writeInt64 = function(value) {
  this.bb.writeInt64(this.space -= 8, value);
};

/**
 * @param {number} value
 */
standalone_flatbuffers.Builder.prototype.writeFloat32 = function(value) {
  this.bb.writeFloat32(this.space -= 4, value);
};

/**
 * @param {number} value
 */
standalone_flatbuffers.Builder.prototype.writeFloat64 = function(value) {
  this.bb.writeFloat64(this.space -= 8, value);
};
/// @endcond

/**
 * Add an `int8` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {number} value The `int8` to add the the buffer.
 */
standalone_flatbuffers.Builder.prototype.addInt8 = function(value) {
  this.prep(1, 0);
  this.writeInt8(value);
};

/**
 * Add an `int16` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {number} value The `int16` to add the the buffer.
 */
standalone_flatbuffers.Builder.prototype.addInt16 = function(value) {
  this.prep(2, 0);
  this.writeInt16(value);
};

/**
 * Add an `int32` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {number} value The `int32` to add the the buffer.
 */
standalone_flatbuffers.Builder.prototype.addInt32 = function(value) {
  this.prep(4, 0);
  this.writeInt32(value);
};

/**
 * Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {flatbuffers.Long} value The `int64` to add the the buffer.
 */
standalone_flatbuffers.Builder.prototype.addInt64 = function(value) {
  this.prep(8, 0);
  this.writeInt64(value);
};

/**
 * Add a `float32` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {number} value The `float32` to add the the buffer.
 */
standalone_flatbuffers.Builder.prototype.addFloat32 = function(value) {
  this.prep(4, 0);
  this.writeFloat32(value);
};

/**
 * Add a `float64` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {number} value The `float64` to add the the buffer.
 */
standalone_flatbuffers.Builder.prototype.addFloat64 = function(value) {
  this.prep(8, 0);
  this.writeFloat64(value);
};

/// @cond FLATBUFFERS_INTERNAL
/**
 * @param {number} voffset
 * @param {number} value
 * @param {number} defaultValue
 */
standalone_flatbuffers.Builder.prototype.addFieldInt8 = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addInt8(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {number} value
 * @param {number} defaultValue
 */
standalone_flatbuffers.Builder.prototype.addFieldInt16 = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addInt16(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {number} value
 * @param {number} defaultValue
 */
standalone_flatbuffers.Builder.prototype.addFieldInt32 = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addInt32(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {flatbuffers.Long} value
 * @param {flatbuffers.Long} defaultValue
 */
standalone_flatbuffers.Builder.prototype.addFieldInt64 = function(voffset, value, defaultValue) {
  if (this.force_defaults || !value.equals(defaultValue)) {
    this.addInt64(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {number} value
 * @param {number} defaultValue
 */
standalone_flatbuffers.Builder.prototype.addFieldFloat32 = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addFloat32(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {number} value
 * @param {number} defaultValue
 */
standalone_flatbuffers.Builder.prototype.addFieldFloat64 = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addFloat64(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {flatbuffers.Offset} value
 * @param {flatbuffers.Offset} defaultValue
 */
standalone_flatbuffers.Builder.prototype.addFieldOffset = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addOffset(value);
    this.slot(voffset);
  }
};

/**
 * Structs are stored inline, so nothing additional is being added. `d` is always 0.
 *
 * @param {number} voffset
 * @param {flatbuffers.Offset} value
 * @param {flatbuffers.Offset} defaultValue
 */
standalone_flatbuffers.Builder.prototype.addFieldStruct = function(voffset, value, defaultValue) {
  if (value != defaultValue) {
    this.nested(value);
    this.slot(voffset);
  }
};

/**
 * Structures are always stored inline, they need to be created right
 * where they're used.  You'll get this assertion failure if you
 * created it elsewhere.
 *
 * @param {flatbuffers.Offset} obj The offset of the created object
 */
standalone_flatbuffers.Builder.prototype.nested = function(obj) {
  if (obj != this.offset()) {
    throw new Error('FlatBuffers: struct must be serialized inline.');
  }
};

/**
 * Should not be creating any other object, string or vector
 * while an object is being constructed
 */
standalone_flatbuffers.Builder.prototype.notNested = function() {
  if (this.isNested) {
    throw new Error('FlatBuffers: object serialization must not be nested.');
  }
};

/**
 * Set the current vtable at `voffset` to the current location in the buffer.
 *
 * @param {number} voffset
 */
standalone_flatbuffers.Builder.prototype.slot = function(voffset) {
  this.vtable[voffset] = this.offset();
};

/**
 * @returns {flatbuffers.Offset} Offset relative to the end of the buffer.
 */
standalone_flatbuffers.Builder.prototype.offset = function() {
  return this.bb.capacity() - this.space;
};

/**
 * Doubles the size of the backing ByteBuffer and copies the old data towards
 * the end of the new buffer (since we build the buffer backwards).
 *
 * @param {flatbuffers.ByteBuffer} bb The current buffer with the existing data
 * @returns {flatbuffers.ByteBuffer} A new byte buffer with the old data copied
 * to it. The data is located at the end of the buffer.
 *
 * uint8Array.set() formally takes {Array<number>|ArrayBufferView}, so to pass
 * it a uint8Array we need to suppress the type check:
 * @suppress {checkTypes}
 */
standalone_flatbuffers.Builder.growByteBuffer = function(bb) {
  var old_buf_size = bb.capacity();

  // Ensure we don't grow beyond what fits in an int.
  if (old_buf_size & 0xC0000000) {
    throw new Error('FlatBuffers: cannot grow buffer beyond 2 gigabytes.');
  }

  var new_buf_size = old_buf_size << 1;
  var nbb = standalone_flatbuffers.ByteBuffer.allocate(new_buf_size);
  nbb.setPosition(new_buf_size - old_buf_size);
  nbb.bytes().set(bb.bytes(), new_buf_size - old_buf_size);
  return nbb;
};
/// @endcond

/**
 * Adds on offset, relative to where it will be written.
 *
 * @param {flatbuffers.Offset} offset The offset to add.
 */
standalone_flatbuffers.Builder.prototype.addOffset = function(offset) {
  this.prep(standalone_flatbuffers.SIZEOF_INT, 0); // Ensure alignment is already done.
  this.writeInt32(this.offset() - offset + standalone_flatbuffers.SIZEOF_INT);
};

/// @cond FLATBUFFERS_INTERNAL
/**
 * Start encoding a new object in the buffer.  Users will not usually need to
 * call this directly. The FlatBuffers compiler will generate helper methods
 * that call this method internally.
 *
 * @param {number} numfields
 */
standalone_flatbuffers.Builder.prototype.startObject = function(numfields) {
  this.notNested();
  if (this.vtable == null) {
    this.vtable = [];
  }
  this.vtable_in_use = numfields;
  for (var i = 0; i < numfields; i++) {
    this.vtable[i] = 0; // This will push additional elements as needed
  }
  this.isNested = true;
  this.object_start = this.offset();
};

/**
 * Finish off writing the object that is under construction.
 *
 * @returns {flatbuffers.Offset} The offset to the object inside `dataBuffer`
 */
standalone_flatbuffers.Builder.prototype.endObject = function() {
  if (this.vtable == null || !this.isNested) {
    throw new Error('FlatBuffers: endObject called without startObject');
  }

  this.addInt32(0);
  var vtableloc = this.offset();

  // Trim trailing zeroes.
  var i = this.vtable_in_use - 1;
  for (; i >= 0 && this.vtable[i] == 0; i--) {}
  var trimmed_size = i + 1;

  // Write out the current vtable.
  for (; i >= 0; i--) {
    // Offset relative to the start of the table.
    this.addInt16(this.vtable[i] != 0 ? vtableloc - this.vtable[i] : 0);
  }

  var standard_fields = 2; // The fields below:
  this.addInt16(vtableloc - this.object_start);
  var len = (trimmed_size + standard_fields) * standalone_flatbuffers.SIZEOF_SHORT;
  this.addInt16(len);

  // Search for an existing vtable that matches the current one.
  var existing_vtable = 0;
  var vt1 = this.space;
outer_loop:
  for (i = 0; i < this.vtables.length; i++) {
    var vt2 = this.bb.capacity() - this.vtables[i];
    if (len == this.bb.readInt16(vt2)) {
      for (var j = standalone_flatbuffers.SIZEOF_SHORT; j < len; j += standalone_flatbuffers.SIZEOF_SHORT) {
        if (this.bb.readInt16(vt1 + j) != this.bb.readInt16(vt2 + j)) {
          continue outer_loop;
        }
      }
      existing_vtable = this.vtables[i];
      break;
    }
  }

  if (existing_vtable) {
    // Found a match:
    // Remove the current vtable.
    this.space = this.bb.capacity() - vtableloc;

    // Point table to existing vtable.
    this.bb.writeInt32(this.space, existing_vtable - vtableloc);
  } else {
    // No match:
    // Add the location of the current vtable to the list of vtables.
    this.vtables.push(this.offset());

    // Point table to current vtable.
    this.bb.writeInt32(this.bb.capacity() - vtableloc, this.offset() - vtableloc);
  }

  this.isNested = false;
  return vtableloc;
};
/// @endcond

/**
 * Finalize a buffer, poiting to the given `root_table`.
 *
 * @param {flatbuffers.Offset} root_table
 * @param {string=} opt_file_identifier
 */
standalone_flatbuffers.Builder.prototype.finish = function(root_table, opt_file_identifier) {
  if (opt_file_identifier) {
    var file_identifier = opt_file_identifier;
    this.prep(this.minalign, standalone_flatbuffers.SIZEOF_INT +
      standalone_flatbuffers.FILE_IDENTIFIER_LENGTH);
    if (file_identifier.length != standalone_flatbuffers.FILE_IDENTIFIER_LENGTH) {
      throw new Error('FlatBuffers: file identifier must be length ' +
        standalone_flatbuffers.FILE_IDENTIFIER_LENGTH);
    }
    for (var i = standalone_flatbuffers.FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) {
      this.writeInt8(file_identifier.charCodeAt(i));
    }
  }
  this.prep(this.minalign, standalone_flatbuffers.SIZEOF_INT);
  this.addOffset(root_table);
  this.bb.setPosition(this.space);
};

/// @cond FLATBUFFERS_INTERNAL
/**
 * This checks a required field has been set in a given table that has
 * just been constructed.
 *
 * @param {flatbuffers.Offset} table
 * @param {number} field
 */
standalone_flatbuffers.Builder.prototype.requiredField = function(table, field) {
  var table_start = this.bb.capacity() - table;
  var vtable_start = table_start - this.bb.readInt32(table_start);
  var ok = this.bb.readInt16(vtable_start + field) != 0;

  // If this fails, the caller will show what field needs to be set.
  if (!ok) {
    throw new Error('FlatBuffers: field ' + field + ' must be set');
  }
};

/**
 * Start a new array/vector of objects.  Users usually will not call
 * this directly. The FlatBuffers compiler will create a start/end
 * method for vector types in generated code.
 *
 * @param {number} elem_size The size of each element in the array
 * @param {number} num_elems The number of elements in the array
 * @param {number} alignment The alignment of the array
 */
standalone_flatbuffers.Builder.prototype.startVector = function(elem_size, num_elems, alignment) {
  this.notNested();
  this.vector_num_elems = num_elems;
  this.prep(standalone_flatbuffers.SIZEOF_INT, elem_size * num_elems);
  this.prep(alignment, elem_size * num_elems); // Just in case alignment > int.
};

/**
 * Finish off the creation of an array and all its elements. The array must be
 * created with `startVector`.
 *
 * @returns {flatbuffers.Offset} The offset at which the newly created array
 * starts.
 */
standalone_flatbuffers.Builder.prototype.endVector = function() {
  this.writeInt32(this.vector_num_elems);
  return this.offset();
};
/// @endcond

/**
 * Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed
 * instead of a string, it is assumed to contain valid UTF-8 encoded data.
 *
 * @param {string|Uint8Array} s The string to encode
 * @return {flatbuffers.Offset} The offset in the buffer where the encoded string starts
 */
standalone_flatbuffers.Builder.prototype.createString = function(s) {
  if (s instanceof Uint8Array) {
    var utf8 = s;
  } else {
    var utf8 = [];
    var i = 0;

    while (i < s.length) {
      var codePoint;

      // Decode UTF-16
      var a = s.charCodeAt(i++);
      if (a < 0xD800 || a >= 0xDC00) {
        codePoint = a;
      } else {
        var b = s.charCodeAt(i++);
        codePoint = (a << 10) + b + (0x10000 - (0xD800 << 10) - 0xDC00);
      }

      // Encode UTF-8
      if (codePoint < 0x80) {
        utf8.push(codePoint);
      } else {
        if (codePoint < 0x800) {
          utf8.push(((codePoint >> 6) & 0x1F) | 0xC0);
        } else {
          if (codePoint < 0x10000) {
            utf8.push(((codePoint >> 12) & 0x0F) | 0xE0);
          } else {
            utf8.push(
              ((codePoint >> 18) & 0x07) | 0xF0,
              ((codePoint >> 12) & 0x3F) | 0x80);
          }
          utf8.push(((codePoint >> 6) & 0x3F) | 0x80);
        }
        utf8.push((codePoint & 0x3F) | 0x80);
      }
    }
  }

  this.addInt8(0);
  this.startVector(1, utf8.length, 1);
  this.bb.setPosition(this.space -= utf8.length);
  for (var i = 0, offset = this.space, bytes = this.bb.bytes(); i < utf8.length; i++) {
    bytes[offset++] = utf8[i];
  }
  return this.endVector();
};

/**
 * A helper function to avoid generated code depending on this file directly.
 *
 * @param {number} low
 * @param {number} high
 * @returns {flatbuffers.Long}
 */
standalone_flatbuffers.Builder.prototype.createLong = function(low, high) {
  return standalone_flatbuffers.Long.create(low, high);
};
////////////////////////////////////////////////////////////////////////////////
/// @cond FLATBUFFERS_INTERNAL
/**
 * Create a new ByteBuffer with a given array of bytes (`Uint8Array`).
 *
 * @constructor
 * @param {Uint8Array} bytes
 */
standalone_flatbuffers.ByteBuffer = function(bytes) {
  /**
   * @type {Uint8Array}
   * @private
   */
  this.bytes_ = bytes;

  /**
   * @type {number}
   * @private
   */
  this.position_ = 0;
};

/**
 * Create and allocate a new ByteBuffer with a given size.
 *
 * @param {number} byte_size
 * @returns {flatbuffers.ByteBuffer}
 */
standalone_flatbuffers.ByteBuffer.allocate = function(byte_size) {
  return new standalone_flatbuffers.ByteBuffer(new Uint8Array(byte_size));
};

standalone_flatbuffers.ByteBuffer.prototype.clear = function() {
  this.position_ = 0;
};

/**
 * Get the underlying `Uint8Array`.
 *
 * @returns {Uint8Array}
 */
standalone_flatbuffers.ByteBuffer.prototype.bytes = function() {
  return this.bytes_;
};

/**
 * Get the buffer's position.
 *
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.position = function() {
  return this.position_;
};

/**
 * Set the buffer's position.
 *
 * @param {number} position
 */
standalone_flatbuffers.ByteBuffer.prototype.setPosition = function(position) {
  this.position_ = position;
};

/**
 * Get the buffer's capacity.
 *
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.capacity = function() {
  return this.bytes_.length;
};

/**
 * @param {number} offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.readInt8 = function(offset) {
  return this.readUint8(offset) << 24 >> 24;
};

/**
 * @param {number} offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.readUint8 = function(offset) {
  return this.bytes_[offset];
};

/**
 * @param {number} offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.readInt16 = function(offset) {
  return this.readUint16(offset) << 16 >> 16;
};

/**
 * @param {number} offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.readUint16 = function(offset) {
  return this.bytes_[offset] | this.bytes_[offset + 1] << 8;
};

/**
 * @param {number} offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.readInt32 = function(offset) {
  return this.bytes_[offset] | this.bytes_[offset + 1] << 8 | this.bytes_[offset + 2] << 16 | this.bytes_[offset + 3] << 24;
};

/**
 * @param {number} offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.readUint32 = function(offset) {
  return this.readInt32(offset) >>> 0;
};

/**
 * @param {number} offset
 * @returns {flatbuffers.Long}
 */
standalone_flatbuffers.ByteBuffer.prototype.readInt64 = function(offset) {
  return new standalone_flatbuffers.Long(this.readInt32(offset), this.readInt32(offset + 4));
};

/**
 * @param {number} offset
 * @returns {flatbuffers.Long}
 */
standalone_flatbuffers.ByteBuffer.prototype.readUint64 = function(offset) {
  return new standalone_flatbuffers.Long(this.readUint32(offset), this.readUint32(offset + 4));
};

/**
 * @param {number} offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.readFloat32 = function(offset) {
  standalone_flatbuffers.int32[0] = this.readInt32(offset);
  return standalone_flatbuffers.float32[0];
};

/**
 * @param {number} offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.readFloat64 = function(offset) {
  standalone_flatbuffers.int32[standalone_flatbuffers.isLittleEndian ? 0 : 1] = this.readInt32(offset);
  standalone_flatbuffers.int32[standalone_flatbuffers.isLittleEndian ? 1 : 0] = this.readInt32(offset + 4);
  return standalone_flatbuffers.float64[0];
};

/**
 * @param {number} offset
 * @param {number|boolean} value
 */
standalone_flatbuffers.ByteBuffer.prototype.writeInt8 = function(offset, value) {
  this.bytes_[offset] = /** @type {number} */(value);
};

/**
 * @param {number} offset
 * @param {number} value
 */
standalone_flatbuffers.ByteBuffer.prototype.writeUint8 = function(offset, value) {
  this.bytes_[offset] = value;
};

/**
 * @param {number} offset
 * @param {number} value
 */
standalone_flatbuffers.ByteBuffer.prototype.writeInt16 = function(offset, value) {
  this.bytes_[offset] = value;
  this.bytes_[offset + 1] = value >> 8;
};

/**
 * @param {number} offset
 * @param {number} value
 */
standalone_flatbuffers.ByteBuffer.prototype.writeUint16 = function(offset, value) {
    this.bytes_[offset] = value;
    this.bytes_[offset + 1] = value >> 8;
};

/**
 * @param {number} offset
 * @param {number} value
 */
standalone_flatbuffers.ByteBuffer.prototype.writeInt32 = function(offset, value) {
  this.bytes_[offset] = value;
  this.bytes_[offset + 1] = value >> 8;
  this.bytes_[offset + 2] = value >> 16;
  this.bytes_[offset + 3] = value >> 24;
};

/**
 * @param {number} offset
 * @param {number} value
 */
standalone_flatbuffers.ByteBuffer.prototype.writeUint32 = function(offset, value) {
    this.bytes_[offset] = value;
    this.bytes_[offset + 1] = value >> 8;
    this.bytes_[offset + 2] = value >> 16;
    this.bytes_[offset + 3] = value >> 24;
};

/**
 * @param {number} offset
 * @param {flatbuffers.Long} value
 */
standalone_flatbuffers.ByteBuffer.prototype.writeInt64 = function(offset, value) {
  this.writeInt32(offset, value.low);
  this.writeInt32(offset + 4, value.high);
};

/**
 * @param {number} offset
 * @param {flatbuffers.Long} value
 */
standalone_flatbuffers.ByteBuffer.prototype.writeUint64 = function(offset, value) {
    this.writeUint32(offset, value.low);
    this.writeUint32(offset + 4, value.high);
};

/**
 * @param {number} offset
 * @param {number} value
 */
standalone_flatbuffers.ByteBuffer.prototype.writeFloat32 = function(offset, value) {
  standalone_flatbuffers.float32[0] = value;
  this.writeInt32(offset, standalone_flatbuffers.int32[0]);
};

/**
 * @param {number} offset
 * @param {number} value
 */
standalone_flatbuffers.ByteBuffer.prototype.writeFloat64 = function(offset, value) {
  standalone_flatbuffers.float64[0] = value;
  this.writeInt32(offset, standalone_flatbuffers.int32[standalone_flatbuffers.isLittleEndian ? 0 : 1]);
  this.writeInt32(offset + 4, standalone_flatbuffers.int32[standalone_flatbuffers.isLittleEndian ? 1 : 0]);
};

/**
 * Return the file identifier.   Behavior is undefined for FlatBuffers whose
 * schema does not include a file_identifier (likely points at padding or the
 * start of a the root vtable).
 * @returns {string}
 */
standalone_flatbuffers.ByteBuffer.prototype.getBufferIdentifier = function() {
  if (this.bytes_.length < this.position_ + standalone_flatbuffers.SIZEOF_INT +
      standalone_flatbuffers.FILE_IDENTIFIER_LENGTH) {
    throw new Error(
        'FlatBuffers: ByteBuffer is too short to contain an identifier.');
  }
  var result = "";
  for (var i = 0; i < standalone_flatbuffers.FILE_IDENTIFIER_LENGTH; i++) {
    result += String.fromCharCode(
        this.readInt8(this.position_ + standalone_flatbuffers.SIZEOF_INT + i));
  }
  return result;
};

/**
 * Look up a field in the vtable, return an offset into the object, or 0 if the
 * field is not present.
 *
 * @param {number} bb_pos
 * @param {number} vtable_offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.__offset = function(bb_pos, vtable_offset) {
  var vtable = bb_pos - this.readInt32(bb_pos);
  return vtable_offset < this.readInt16(vtable) ? this.readInt16(vtable + vtable_offset) : 0;
};

/**
 * Initialize any Table-derived type to point to the union at the given offset.
 *
 * @param {flatbuffers.Table} t
 * @param {number} offset
 * @returns {flatbuffers.Table}
 */
standalone_flatbuffers.ByteBuffer.prototype.__union = function(t, offset) {
  t.bb_pos = offset + this.readInt32(offset);
  t.bb = this;
  return t;
};

/**
 * Create a JavaScript string from UTF-8 data stored inside the FlatBuffer.
 * This allocates a new string and converts to wide chars upon each access.
 *
 * To avoid the conversion to UTF-16, pass flatbuffers.Encoding.UTF8_BYTES as
 * the "optionalEncoding" argument. This is useful for avoiding conversion to
 * and from UTF-16 when the data will just be packaged back up in another
 * FlatBuffer later on.
 *
 * @param {number} offset
 * @param {flatbuffers.Encoding=} opt_encoding Defaults to UTF16_STRING
 * @returns {string|Uint8Array}
 */
standalone_flatbuffers.ByteBuffer.prototype.__string = function(offset, opt_encoding) {
  offset += this.readInt32(offset);

  var length = this.readInt32(offset);
  var result = '';
  var i = 0;

  offset += standalone_flatbuffers.SIZEOF_INT;

  if (opt_encoding === standalone_flatbuffers.Encoding.UTF8_BYTES) {
    return this.bytes_.subarray(offset, offset + length);
  }

  while (i < length) {
    var codePoint;

    // Decode UTF-8
    var a = this.readUint8(offset + i++);
    if (a < 0xC0) {
      codePoint = a;
    } else {
      var b = this.readUint8(offset + i++);
      if (a < 0xE0) {
        codePoint =
          ((a & 0x1F) << 6) |
          (b & 0x3F);
      } else {
        var c = this.readUint8(offset + i++);
        if (a < 0xF0) {
          codePoint =
            ((a & 0x0F) << 12) |
            ((b & 0x3F) << 6) |
            (c & 0x3F);
        } else {
          var d = this.readUint8(offset + i++);
          codePoint =
            ((a & 0x07) << 18) |
            ((b & 0x3F) << 12) |
            ((c & 0x3F) << 6) |
            (d & 0x3F);
        }
      }
    }

    // Encode UTF-16
    if (codePoint < 0x10000) {
      result += String.fromCharCode(codePoint);
    } else {
      codePoint -= 0x10000;
      result += String.fromCharCode(
        (codePoint >> 10) + 0xD800,
        (codePoint & ((1 << 10) - 1)) + 0xDC00);
    }
  }

  return result;
};

/**
 * Retrieve the relative offset stored at "offset"
 * @param {number} offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.__indirect = function(offset) {
  return offset + this.readInt32(offset);
};

/**
 * Get the start of data of a vector whose offset is stored at "offset" in this object.
 *
 * @param {number} offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.__vector = function(offset) {
  return offset + this.readInt32(offset) + standalone_flatbuffers.SIZEOF_INT; // data starts after the length
};

/**
 * Get the length of a vector whose offset is stored at "offset" in this object.
 *
 * @param {number} offset
 * @returns {number}
 */
standalone_flatbuffers.ByteBuffer.prototype.__vector_len = function(offset) {
  return this.readInt32(offset + this.readInt32(offset));
};

/**
 * @param {string} ident
 * @returns {boolean}
 */
standalone_flatbuffers.ByteBuffer.prototype.__has_identifier = function(ident) {
  if (ident.length != standalone_flatbuffers.FILE_IDENTIFIER_LENGTH) {
    throw new Error('FlatBuffers: file identifier must be length ' +
                    standalone_flatbuffers.FILE_IDENTIFIER_LENGTH);
  }
  for (var i = 0; i < standalone_flatbuffers.FILE_IDENTIFIER_LENGTH; i++) {
    if (ident.charCodeAt(i) != this.readInt8(this.position_ + standalone_flatbuffers.SIZEOF_INT + i)) {
      return false;
    }
  }
  return true;
};

/**
 * A helper function to avoid generated code depending on this file directly.
 *
 * @param {number} low
 * @param {number} high
 * @returns {flatbuffers.Long}
 */
standalone_flatbuffers.ByteBuffer.prototype.createLong = function(low, high) {
  return standalone_flatbuffers.Long.create(low, high);
};

// Exports for Node.js and RequireJS


/// @endcond
/// @}

;// ../../node_modules/text-encoding-utf-8/lib/encoding.lib.mjs


// This is free and unencumbered software released into the public domain.
// See LICENSE.md for more information.

//
// Utilities
//

/**
 * @param {number} a The number to test.
 * @param {number} min The minimum value in the range, inclusive.
 * @param {number} max The maximum value in the range, inclusive.
 * @return {boolean} True if a >= min and a <= max.
 */
function standalone_inRange(a, min, max) {
  return min <= a && a <= max;
}

/**
 * @param {*} o
 * @return {Object}
 */
function standalone_ToDictionary(o) {
  if (o === undefined) return {};
  if (o === Object(o)) return o;
  throw TypeError('Could not convert argument to dictionary');
}

/**
 * @param {string} string Input string of UTF-16 code units.
 * @return {!Array.<number>} Code points.
 */
function standalone_stringToCodePoints(string) {
  // https://heycam.github.io/webidl/#dfn-obtain-unicode

  // 1. Let S be the DOMString value.
  var s = String(string);

  // 2. Let n be the length of S.
  var n = s.length;

  // 3. Initialize i to 0.
  var i = 0;

  // 4. Initialize U to be an empty sequence of Unicode characters.
  var u = [];

  // 5. While i < n:
  while (i < n) {

    // 1. Let c be the code unit in S at index i.
    var c = s.charCodeAt(i);

    // 2. Depending on the value of c:

    // c < 0xD800 or c > 0xDFFF
    if (c < 0xD800 || c > 0xDFFF) {
      // Append to U the Unicode character with code point c.
      u.push(c);
    }

    // 0xDC00 ≤ c ≤ 0xDFFF
    else if (0xDC00 <= c && c <= 0xDFFF) {
      // Append to U a U+FFFD REPLACEMENT CHARACTER.
      u.push(0xFFFD);
    }

    // 0xD800 ≤ c ≤ 0xDBFF
    else if (0xD800 <= c && c <= 0xDBFF) {
      // 1. If i = n−1, then append to U a U+FFFD REPLACEMENT
      // CHARACTER.
      if (i === n - 1) {
        u.push(0xFFFD);
      }
      // 2. Otherwise, i < n−1:
      else {
        // 1. Let d be the code unit in S at index i+1.
        var d = string.charCodeAt(i + 1);

        // 2. If 0xDC00 ≤ d ≤ 0xDFFF, then:
        if (0xDC00 <= d && d <= 0xDFFF) {
          // 1. Let a be c & 0x3FF.
          var a = c & 0x3FF;

          // 2. Let b be d & 0x3FF.
          var b = d & 0x3FF;

          // 3. Append to U the Unicode character with code point
          // 2^16+2^10*a+b.
          u.push(0x10000 + (a << 10) + b);

          // 4. Set i to i+1.
          i += 1;
        }

        // 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a
        // U+FFFD REPLACEMENT CHARACTER.
        else  {
          u.push(0xFFFD);
        }
      }
    }

    // 3. Set i to i+1.
    i += 1;
  }

  // 6. Return U.
  return u;
}

/**
 * @param {!Array.<number>} code_points Array of code points.
 * @return {string} string String of UTF-16 code units.
 */
function standalone_codePointsToString(code_points) {
  var s = '';
  for (var i = 0; i < code_points.length; ++i) {
    var cp = code_points[i];
    if (cp <= 0xFFFF) {
      s += String.fromCharCode(cp);
    } else {
      cp -= 0x10000;
      s += String.fromCharCode((cp >> 10) + 0xD800,
                               (cp & 0x3FF) + 0xDC00);
    }
  }
  return s;
}


//
// Implementation of Encoding specification
// https://encoding.spec.whatwg.org/
//

//
// 3. Terminology
//

/**
 * End-of-stream is a special token that signifies no more tokens
 * are in the stream.
 * @const
 */ var standalone_end_of_stream = -1;

/**
 * A stream represents an ordered sequence of tokens.
 *
 * @constructor
 * @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide the
 * stream.
 */
function standalone_Stream(tokens) {
  /** @type {!Array.<number>} */
  this.tokens = [].slice.call(tokens);
}

standalone_Stream.prototype = {
  /**
   * @return {boolean} True if end-of-stream has been hit.
   */
  endOfStream: function() {
    return !this.tokens.length;
  },

  /**
   * When a token is read from a stream, the first token in the
   * stream must be returned and subsequently removed, and
   * end-of-stream must be returned otherwise.
   *
   * @return {number} Get the next token from the stream, or
   * end_of_stream.
   */
   read: function() {
    if (!this.tokens.length)
      return standalone_end_of_stream;
     return this.tokens.shift();
   },

  /**
   * When one or more tokens are prepended to a stream, those tokens
   * must be inserted, in given order, before the first token in the
   * stream.
   *
   * @param {(number|!Array.<number>)} token The token(s) to prepend to the stream.
   */
  prepend: function(token) {
    if (Array.isArray(token)) {
      var tokens = /**@type {!Array.<number>}*/(token);
      while (tokens.length)
        this.tokens.unshift(tokens.pop());
    } else {
      this.tokens.unshift(token);
    }
  },

  /**
   * When one or more tokens are pushed to a stream, those tokens
   * must be inserted, in given order, after the last token in the
   * stream.
   *
   * @param {(number|!Array.<number>)} token The tokens(s) to prepend to the stream.
   */
  push: function(token) {
    if (Array.isArray(token)) {
      var tokens = /**@type {!Array.<number>}*/(token);
      while (tokens.length)
        this.tokens.push(tokens.shift());
    } else {
      this.tokens.push(token);
    }
  }
};

//
// 4. Encodings
//

// 4.1 Encoders and decoders

/** @const */
var standalone_finished = -1;

/**
 * @param {boolean} fatal If true, decoding errors raise an exception.
 * @param {number=} opt_code_point Override the standard fallback code point.
 * @return {number} The code point to insert on a decoding error.
 */
function standalone_decoderError(fatal, opt_code_point) {
  if (fatal)
    throw TypeError('Decoder error');
  return opt_code_point || 0xFFFD;
}

/** @interface */
function standalone_Decoder() {}
standalone_Decoder.prototype = {
  /**
   * @param {Stream} stream The stream of bytes being decoded.
   * @param {number} bite The next byte read from the stream.
   * @return {?(number|!Array.<number>)} The next code point(s)
   *     decoded, or null if not enough data exists in the input
   *     stream to decode a complete code point, or |finished|.
   */
  handler: function(stream, bite) {}
};

/** @interface */
function standalone_Encoder() {}
standalone_Encoder.prototype = {
  /**
   * @param {Stream} stream The stream of code points being encoded.
   * @param {number} code_point Next code point read from the stream.
   * @return {(number|!Array.<number>)} Byte(s) to emit, or |finished|.
   */
  handler: function(stream, code_point) {}
};

//
// 7. API
//

/** @const */ var standalone_DEFAULT_ENCODING = 'utf-8';

// 7.1 Interface TextDecoder

/**
 * @constructor
 * @param {string=} encoding The label of the encoding;
 *     defaults to 'utf-8'.
 * @param {Object=} options
 */
function standalone_encoding_lib_TextDecoder(encoding, options) {
  if (!(this instanceof standalone_encoding_lib_TextDecoder)) {
    return new standalone_encoding_lib_TextDecoder(encoding, options);
  }
  encoding = encoding !== undefined ? String(encoding).toLowerCase() : standalone_DEFAULT_ENCODING;
  if (encoding !== standalone_DEFAULT_ENCODING) {
    throw new Error('Encoding not supported. Only utf-8 is supported');
  }
  options = standalone_ToDictionary(options);

  /** @private @type {boolean} */
  this._streaming = false;
  /** @private @type {boolean} */
  this._BOMseen = false;
  /** @private @type {?Decoder} */
  this._decoder = null;
  /** @private @type {boolean} */
  this._fatal = Boolean(options['fatal']);
  /** @private @type {boolean} */
  this._ignoreBOM = Boolean(options['ignoreBOM']);

  Object.defineProperty(this, 'encoding', {value: 'utf-8'});
  Object.defineProperty(this, 'fatal', {value: this._fatal});
  Object.defineProperty(this, 'ignoreBOM', {value: this._ignoreBOM});
}

standalone_encoding_lib_TextDecoder.prototype = {
  /**
   * @param {ArrayBufferView=} input The buffer of bytes to decode.
   * @param {Object=} options
   * @return {string} The decoded string.
   */
  decode: function decode(input, options) {
    var bytes;
    if (typeof input === 'object' && input instanceof ArrayBuffer) {
      bytes = new Uint8Array(input);
    } else if (typeof input === 'object' && 'buffer' in input &&
               input.buffer instanceof ArrayBuffer) {
      bytes = new Uint8Array(input.buffer,
                             input.byteOffset,
                             input.byteLength);
    } else {
      bytes = new Uint8Array(0);
    }

    options = standalone_ToDictionary(options);

    if (!this._streaming) {
      this._decoder = new standalone_UTF8Decoder({fatal: this._fatal});
      this._BOMseen = false;
    }
    this._streaming = Boolean(options['stream']);

    var input_stream = new standalone_Stream(bytes);

    var code_points = [];

    /** @type {?(number|!Array.<number>)} */
    var result;

    while (!input_stream.endOfStream()) {
      result = this._decoder.handler(input_stream, input_stream.read());
      if (result === standalone_finished)
        break;
      if (result === null)
        continue;
      if (Array.isArray(result))
        code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result));
      else
        code_points.push(result);
    }
    if (!this._streaming) {
      do {
        result = this._decoder.handler(input_stream, input_stream.read());
        if (result === standalone_finished)
          break;
        if (result === null)
          continue;
        if (Array.isArray(result))
          code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result));
        else
          code_points.push(result);
      } while (!input_stream.endOfStream());
      this._decoder = null;
    }

    if (code_points.length) {
      // If encoding is one of utf-8, utf-16be, and utf-16le, and
      // ignore BOM flag and BOM seen flag are unset, run these
      // subsubsteps:
      if (['utf-8'].indexOf(this.encoding) !== -1 &&
          !this._ignoreBOM && !this._BOMseen) {
        // If token is U+FEFF, set BOM seen flag.
        if (code_points[0] === 0xFEFF) {
          this._BOMseen = true;
          code_points.shift();
        } else {
          // Otherwise, if token is not end-of-stream, set BOM seen
          // flag and append token to output.
          this._BOMseen = true;
        }
      }
    }

    return standalone_codePointsToString(code_points);
  }
};

// 7.2 Interface TextEncoder

/**
 * @constructor
 * @param {string=} encoding The label of the encoding;
 *     defaults to 'utf-8'.
 * @param {Object=} options
 */
function standalone_encoding_lib_TextEncoder(encoding, options) {
  if (!(this instanceof standalone_encoding_lib_TextEncoder))
    return new standalone_encoding_lib_TextEncoder(encoding, options);
  encoding = encoding !== undefined ? String(encoding).toLowerCase() : standalone_DEFAULT_ENCODING;
  if (encoding !== standalone_DEFAULT_ENCODING) {
    throw new Error('Encoding not supported. Only utf-8 is supported');
  }
  options = standalone_ToDictionary(options);

  /** @private @type {boolean} */
  this._streaming = false;
  /** @private @type {?Encoder} */
  this._encoder = null;
  /** @private @type {{fatal: boolean}} */
  this._options = {fatal: Boolean(options['fatal'])};

  Object.defineProperty(this, 'encoding', {value: 'utf-8'});
}

standalone_encoding_lib_TextEncoder.prototype = {
  /**
   * @param {string=} opt_string The string to encode.
   * @param {Object=} options
   * @return {Uint8Array} Encoded bytes, as a Uint8Array.
   */
  encode: function encode(opt_string, options) {
    opt_string = opt_string ? String(opt_string) : '';
    options = standalone_ToDictionary(options);

    // NOTE: This option is nonstandard. None of the encodings
    // permitted for encoding (i.e. UTF-8, UTF-16) are stateful,
    // so streaming is not necessary.
    if (!this._streaming)
      this._encoder = new standalone_UTF8Encoder(this._options);
    this._streaming = Boolean(options['stream']);

    var bytes = [];
    var input_stream = new standalone_Stream(standalone_stringToCodePoints(opt_string));
    /** @type {?(number|!Array.<number>)} */
    var result;
    while (!input_stream.endOfStream()) {
      result = this._encoder.handler(input_stream, input_stream.read());
      if (result === standalone_finished)
        break;
      if (Array.isArray(result))
        bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result));
      else
        bytes.push(result);
    }
    if (!this._streaming) {
      while (true) {
        result = this._encoder.handler(input_stream, input_stream.read());
        if (result === standalone_finished)
          break;
        if (Array.isArray(result))
          bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result));
        else
          bytes.push(result);
      }
      this._encoder = null;
    }
    return new Uint8Array(bytes);
  }
};

//
// 8. The encoding
//

// 8.1 utf-8

/**
 * @constructor
 * @implements {Decoder}
 * @param {{fatal: boolean}} options
 */
function standalone_UTF8Decoder(options) {
  var fatal = options.fatal;

  // utf-8's decoder's has an associated utf-8 code point, utf-8
  // bytes seen, and utf-8 bytes needed (all initially 0), a utf-8
  // lower boundary (initially 0x80), and a utf-8 upper boundary
  // (initially 0xBF).
  var /** @type {number} */ utf8_code_point = 0,
      /** @type {number} */ utf8_bytes_seen = 0,
      /** @type {number} */ utf8_bytes_needed = 0,
      /** @type {number} */ utf8_lower_boundary = 0x80,
      /** @type {number} */ utf8_upper_boundary = 0xBF;

  /**
   * @param {Stream} stream The stream of bytes being decoded.
   * @param {number} bite The next byte read from the stream.
   * @return {?(number|!Array.<number>)} The next code point(s)
   *     decoded, or null if not enough data exists in the input
   *     stream to decode a complete code point.
   */
  this.handler = function(stream, bite) {
    // 1. If byte is end-of-stream and utf-8 bytes needed is not 0,
    // set utf-8 bytes needed to 0 and return error.
    if (bite === standalone_end_of_stream && utf8_bytes_needed !== 0) {
      utf8_bytes_needed = 0;
      return standalone_decoderError(fatal);
    }

    // 2. If byte is end-of-stream, return finished.
    if (bite === standalone_end_of_stream)
      return standalone_finished;

    // 3. If utf-8 bytes needed is 0, based on byte:
    if (utf8_bytes_needed === 0) {

      // 0x00 to 0x7F
      if (standalone_inRange(bite, 0x00, 0x7F)) {
        // Return a code point whose value is byte.
        return bite;
      }

      // 0xC2 to 0xDF
      if (standalone_inRange(bite, 0xC2, 0xDF)) {
        // Set utf-8 bytes needed to 1 and utf-8 code point to byte
        // − 0xC0.
        utf8_bytes_needed = 1;
        utf8_code_point = bite - 0xC0;
      }

      // 0xE0 to 0xEF
      else if (standalone_inRange(bite, 0xE0, 0xEF)) {
        // 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0.
        if (bite === 0xE0)
          utf8_lower_boundary = 0xA0;
        // 2. If byte is 0xED, set utf-8 upper boundary to 0x9F.
        if (bite === 0xED)
          utf8_upper_boundary = 0x9F;
        // 3. Set utf-8 bytes needed to 2 and utf-8 code point to
        // byte − 0xE0.
        utf8_bytes_needed = 2;
        utf8_code_point = bite - 0xE0;
      }

      // 0xF0 to 0xF4
      else if (standalone_inRange(bite, 0xF0, 0xF4)) {
        // 1. If byte is 0xF0, set utf-8 lower boundary to 0x90.
        if (bite === 0xF0)
          utf8_lower_boundary = 0x90;
        // 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F.
        if (bite === 0xF4)
          utf8_upper_boundary = 0x8F;
        // 3. Set utf-8 bytes needed to 3 and utf-8 code point to
        // byte − 0xF0.
        utf8_bytes_needed = 3;
        utf8_code_point = bite - 0xF0;
      }

      // Otherwise
      else {
        // Return error.
        return standalone_decoderError(fatal);
      }

      // Then (byte is in the range 0xC2 to 0xF4) set utf-8 code
      // point to utf-8 code point << (6 × utf-8 bytes needed) and
      // return continue.
      utf8_code_point = utf8_code_point << (6 * utf8_bytes_needed);
      return null;
    }

    // 4. If byte is not in the range utf-8 lower boundary to utf-8
    // upper boundary, run these substeps:
    if (!standalone_inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) {

      // 1. Set utf-8 code point, utf-8 bytes needed, and utf-8
      // bytes seen to 0, set utf-8 lower boundary to 0x80, and set
      // utf-8 upper boundary to 0xBF.
      utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
      utf8_lower_boundary = 0x80;
      utf8_upper_boundary = 0xBF;

      // 2. Prepend byte to stream.
      stream.prepend(bite);

      // 3. Return error.
      return standalone_decoderError(fatal);
    }

    // 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary
    // to 0xBF.
    utf8_lower_boundary = 0x80;
    utf8_upper_boundary = 0xBF;

    // 6. Increase utf-8 bytes seen by one and set utf-8 code point
    // to utf-8 code point + (byte − 0x80) << (6 × (utf-8 bytes
    // needed − utf-8 bytes seen)).
    utf8_bytes_seen += 1;
    utf8_code_point += (bite - 0x80) << (6 * (utf8_bytes_needed - utf8_bytes_seen));

    // 7. If utf-8 bytes seen is not equal to utf-8 bytes needed,
    // continue.
    if (utf8_bytes_seen !== utf8_bytes_needed)
      return null;

    // 8. Let code point be utf-8 code point.
    var code_point = utf8_code_point;

    // 9. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes
    // seen to 0.
    utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;

    // 10. Return a code point whose value is code point.
    return code_point;
  };
}

/**
 * @constructor
 * @implements {Encoder}
 * @param {{fatal: boolean}} options
 */
function standalone_UTF8Encoder(options) {
  var fatal = options.fatal;
  /**
   * @param {Stream} stream Input stream.
   * @param {number} code_point Next code point read from the stream.
   * @return {(number|!Array.<number>)} Byte(s) to emit.
   */
  this.handler = function(stream, code_point) {
    // 1. If code point is end-of-stream, return finished.
    if (code_point === standalone_end_of_stream)
      return standalone_finished;

    // 2. If code point is in the range U+0000 to U+007F, return a
    // byte whose value is code point.
    if (standalone_inRange(code_point, 0x0000, 0x007f))
      return code_point;

    // 3. Set count and offset based on the range code point is in:
    var count, offset;
    // U+0080 to U+07FF:    1 and 0xC0
    if (standalone_inRange(code_point, 0x0080, 0x07FF)) {
      count = 1;
      offset = 0xC0;
    }
    // U+0800 to U+FFFF:    2 and 0xE0
    else if (standalone_inRange(code_point, 0x0800, 0xFFFF)) {
      count = 2;
      offset = 0xE0;
    }
    // U+10000 to U+10FFFF: 3 and 0xF0
    else if (standalone_inRange(code_point, 0x10000, 0x10FFFF)) {
      count = 3;
      offset = 0xF0;
    }

    // 4.Let bytes be a byte sequence whose first byte is (code
    // point >> (6 × count)) + offset.
    var bytes = [(code_point >> (6 * count)) + offset];

    // 5. Run these substeps while count is greater than 0:
    while (count > 0) {

      // 1. Set temp to code point >> (6 × (count − 1)).
      var temp = code_point >> (6 * (count - 1));

      // 2. Append to bytes 0x80 | (temp & 0x3F).
      bytes.push(0x80 | (temp & 0x3F));

      // 3. Decrease count by one.
      count -= 1;
    }

    // 6. Return bytes bytes, in order.
    return bytes;
  };
}



;// ../../node_modules/apache-arrow/util/utf8.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/** @ignore @suppress {missingRequire} */
const standalone_Buffer = typeof Buffer === 'function' ? Buffer : null;
/** @ignore */
const standalone_useNativeEncoders = typeof TextDecoder === 'function' && typeof TextEncoder === 'function';
/** @ignore */
const standalone_decodeUtf8 = ((TextDecoder) => {
    if (standalone_useNativeEncoders || !standalone_Buffer) {
        const decoder = new TextDecoder('utf-8');
        return (buffer) => decoder.decode(buffer);
    }
    return (input) => {
        const { buffer, byteOffset, length } = standalone_toUint8Array(input);
        return standalone_Buffer.from(buffer, byteOffset, length).toString();
    };
})(typeof TextDecoder !== 'undefined' ? TextDecoder : standalone_encoding_lib_TextDecoder);
/** @ignore */
const standalone_encodeUtf8 = ((TextEncoder) => {
    if (standalone_useNativeEncoders || !standalone_Buffer) {
        const encoder = new TextEncoder();
        return (value) => encoder.encode(value);
    }
    return (input = '') => standalone_toUint8Array(standalone_Buffer.from(input, 'utf8'));
})(typeof TextEncoder !== 'undefined' ? TextEncoder : standalone_encoding_lib_TextEncoder);

//# sourceMappingURL=utf8.mjs.map

;// ../../node_modules/apache-arrow/io/interfaces.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
const standalone_ITERATOR_DONE = Object.freeze({ done: true, value: void (0) });
/** @ignore */
class standalone_ArrowJSON {
    // @ts-ignore
    constructor(_json) {
        this._json = _json;
    }
    get schema() { return this._json['schema']; }
    get batches() { return (this._json['batches'] || []); }
    get dictionaries() { return (this._json['dictionaries'] || []); }
}
/** @ignore */
class standalone_ReadableInterop {
    tee() {
        return this._getDOMStream().tee();
    }
    pipe(writable, options) {
        return this._getNodeStream().pipe(writable, options);
    }
    pipeTo(writable, options) { return this._getDOMStream().pipeTo(writable, options); }
    pipeThrough(duplex, options) {
        return this._getDOMStream().pipeThrough(duplex, options);
    }
    _getDOMStream() {
        return this._DOMStream || (this._DOMStream = this.toDOMStream());
    }
    _getNodeStream() {
        return this._nodeStream || (this._nodeStream = this.toNodeStream());
    }
}
/** @ignore */
class standalone_AsyncQueue extends standalone_ReadableInterop {
    constructor() {
        super();
        this._values = [];
        this.resolvers = [];
        this._closedPromise = new Promise((r) => this._closedPromiseResolve = r);
    }
    get closed() { return this._closedPromise; }
    async cancel(reason) { await this.return(reason); }
    write(value) {
        if (this._ensureOpen()) {
            this.resolvers.length <= 0
                ? (this._values.push(value))
                : (this.resolvers.shift().resolve({ done: false, value }));
        }
    }
    abort(value) {
        if (this._closedPromiseResolve) {
            this.resolvers.length <= 0
                ? (this._error = { error: value })
                : (this.resolvers.shift().reject({ done: true, value }));
        }
    }
    close() {
        if (this._closedPromiseResolve) {
            const { resolvers } = this;
            while (resolvers.length > 0) {
                resolvers.shift().resolve(standalone_ITERATOR_DONE);
            }
            this._closedPromiseResolve();
            this._closedPromiseResolve = undefined;
        }
    }
    [Symbol.asyncIterator]() { return this; }
    toDOMStream(options) {
        return standalone_adapters.toDOMStream((this._closedPromiseResolve || this._error)
            ? this
            : this._values, options);
    }
    toNodeStream(options) {
        return standalone_adapters.toNodeStream((this._closedPromiseResolve || this._error)
            ? this
            : this._values, options);
    }
    async throw(_) { await this.abort(_); return standalone_ITERATOR_DONE; }
    async return(_) { await this.close(); return standalone_ITERATOR_DONE; }
    async read(size) { return (await this.next(size, 'read')).value; }
    async peek(size) { return (await this.next(size, 'peek')).value; }
    next(..._args) {
        if (this._values.length > 0) {
            return Promise.resolve({ done: false, value: this._values.shift() });
        }
        else if (this._error) {
            return Promise.reject({ done: true, value: this._error.error });
        }
        else if (!this._closedPromiseResolve) {
            return Promise.resolve(standalone_ITERATOR_DONE);
        }
        else {
            return new Promise((resolve, reject) => {
                this.resolvers.push({ resolve, reject });
            });
        }
    }
    _ensureOpen() {
        if (this._closedPromiseResolve) {
            return true;
        }
        throw new Error(`${this} is closed`);
    }
}

//# sourceMappingURL=interfaces.mjs.map

;// ../../node_modules/apache-arrow/util/compat.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
const [standalone_BigIntCtor, standalone_BigIntAvailable] = (() => {
    const BigIntUnavailableError = () => { throw new Error('BigInt is not available in this environment'); };
    function BigIntUnavailable() { throw BigIntUnavailableError(); }
    BigIntUnavailable.asIntN = () => { throw BigIntUnavailableError(); };
    BigIntUnavailable.asUintN = () => { throw BigIntUnavailableError(); };
    return typeof BigInt !== 'undefined' ? [BigInt, true] : [BigIntUnavailable, false];
})();
/** @ignore */
const [standalone_BigInt64ArrayCtor, standalone_BigInt64ArrayAvailable] = (() => {
    const BigInt64ArrayUnavailableError = () => { throw new Error('BigInt64Array is not available in this environment'); };
    class BigInt64ArrayUnavailable {
        static get BYTES_PER_ELEMENT() { return 8; }
        static of() { throw BigInt64ArrayUnavailableError(); }
        static from() { throw BigInt64ArrayUnavailableError(); }
        constructor() { throw BigInt64ArrayUnavailableError(); }
    }
    return typeof BigInt64Array !== 'undefined' ? [BigInt64Array, true] : [BigInt64ArrayUnavailable, false];
})();
/** @ignore */
const [standalone_BigUint64ArrayCtor, standalone_BigUint64ArrayAvailable] = (() => {
    const BigUint64ArrayUnavailableError = () => { throw new Error('BigUint64Array is not available in this environment'); };
    class BigUint64ArrayUnavailable {
        static get BYTES_PER_ELEMENT() { return 8; }
        static of() { throw BigUint64ArrayUnavailableError(); }
        static from() { throw BigUint64ArrayUnavailableError(); }
        constructor() { throw BigUint64ArrayUnavailableError(); }
    }
    return typeof BigUint64Array !== 'undefined' ? [BigUint64Array, true] : [BigUint64ArrayUnavailable, false];
})();



/** @ignore */ const standalone_compat_isNumber = (x) => typeof x === 'number';
/** @ignore */ const standalone_compat_isBoolean = (x) => typeof x === 'boolean';
/** @ignore */ const standalone_compat_isFunction = (x) => typeof x === 'function';
/** @ignore */
const standalone_compat_isObject = (x) => x != null && Object(x) === x;
/** @ignore */
const standalone_isPromise = (x) => {
    return standalone_compat_isObject(x) && standalone_compat_isFunction(x.then);
};
/** @ignore */
const standalone_isObservable = (x) => {
    return standalone_compat_isObject(x) && standalone_compat_isFunction(x.subscribe);
};
/** @ignore */
const standalone_compat_isIterable = (x) => {
    return standalone_compat_isObject(x) && standalone_compat_isFunction(x[Symbol.iterator]);
};
/** @ignore */
const standalone_isAsyncIterable = (x) => {
    return standalone_compat_isObject(x) && standalone_compat_isFunction(x[Symbol.asyncIterator]);
};
/** @ignore */
const standalone_isArrowJSON = (x) => {
    return standalone_compat_isObject(x) && standalone_compat_isObject(x['schema']);
};
/** @ignore */
const standalone_isArrayLike = (x) => {
    return standalone_compat_isObject(x) && standalone_compat_isNumber(x['length']);
};
/** @ignore */
const standalone_isIteratorResult = (x) => {
    return standalone_compat_isObject(x) && ('done' in x) && ('value' in x);
};
/** @ignore */
const standalone_isUnderlyingSink = (x) => {
    return standalone_compat_isObject(x) &&
        standalone_compat_isFunction(x['abort']) &&
        standalone_compat_isFunction(x['close']) &&
        standalone_compat_isFunction(x['start']) &&
        standalone_compat_isFunction(x['write']);
};
/** @ignore */
const standalone_isFileHandle = (x) => {
    return standalone_compat_isObject(x) && standalone_compat_isFunction(x['stat']) && standalone_compat_isNumber(x['fd']);
};
/** @ignore */
const standalone_isFSReadStream = (x) => {
    return standalone_isReadableNodeStream(x) && standalone_compat_isNumber(x['bytesRead']);
};
/** @ignore */
const standalone_isFetchResponse = (x) => {
    return standalone_compat_isObject(x) && standalone_isReadableDOMStream(x['body']);
};
/** @ignore */
const standalone_isWritableDOMStream = (x) => {
    return standalone_compat_isObject(x) &&
        standalone_compat_isFunction(x['abort']) &&
        standalone_compat_isFunction(x['getWriter']) &&
        !(x instanceof standalone_ReadableInterop);
};
/** @ignore */
const standalone_isReadableDOMStream = (x) => {
    return standalone_compat_isObject(x) &&
        standalone_compat_isFunction(x['cancel']) &&
        standalone_compat_isFunction(x['getReader']) &&
        !(x instanceof standalone_ReadableInterop);
};
/** @ignore */
const standalone_isWritableNodeStream = (x) => {
    return standalone_compat_isObject(x) &&
        standalone_compat_isFunction(x['end']) &&
        standalone_compat_isFunction(x['write']) &&
        standalone_compat_isBoolean(x['writable']) &&
        !(x instanceof standalone_ReadableInterop);
};
/** @ignore */
const standalone_isReadableNodeStream = (x) => {
    return standalone_compat_isObject(x) &&
        standalone_compat_isFunction(x['read']) &&
        standalone_compat_isFunction(x['pipe']) &&
        standalone_compat_isBoolean(x['readable']) &&
        !(x instanceof standalone_ReadableInterop);
};

//# sourceMappingURL=compat.mjs.map

;// ../../node_modules/apache-arrow/util/buffer.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


var standalone_ByteBuffer = standalone_flatbuffers.ByteBuffer;

/** @ignore */
const standalone_SharedArrayBuf = (typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : ArrayBuffer);
/** @ignore */
function standalone_collapseContiguousByteRanges(chunks) {
    let result = chunks[0] ? [chunks[0]] : [];
    let xOffset, yOffset, xLen, yLen;
    for (let x, y, i = 0, j = 0, n = chunks.length; ++i < n;) {
        x = result[j];
        y = chunks[i];
        // continue if x and y don't share the same underlying ArrayBuffer, or if x isn't before y
        if (!x || !y || x.buffer !== y.buffer || y.byteOffset < x.byteOffset) {
            y && (result[++j] = y);
            continue;
        }
        ({ byteOffset: xOffset, byteLength: xLen } = x);
        ({ byteOffset: yOffset, byteLength: yLen } = y);
        // continue if the byte ranges of x and y aren't contiguous
        if ((xOffset + xLen) < yOffset || (yOffset + yLen) < xOffset) {
            y && (result[++j] = y);
            continue;
        }
        result[j] = new Uint8Array(x.buffer, xOffset, yOffset - xOffset + yLen);
    }
    return result;
}
/** @ignore */
function standalone_memcpy(target, source, targetByteOffset = 0, sourceByteLength = source.byteLength) {
    const targetByteLength = target.byteLength;
    const dst = new Uint8Array(target.buffer, target.byteOffset, targetByteLength);
    const src = new Uint8Array(source.buffer, source.byteOffset, Math.min(sourceByteLength, targetByteLength));
    dst.set(src, targetByteOffset);
    return target;
}
/** @ignore */
function standalone_joinUint8Arrays(chunks, size) {
    // collapse chunks that share the same underlying ArrayBuffer and whose byte ranges overlap,
    // to avoid unnecessarily copying the bytes to do this buffer join. This is a common case during
    // streaming, where we may be reading partial byte ranges out of the same underlying ArrayBuffer
    let result = standalone_collapseContiguousByteRanges(chunks);
    let byteLength = result.reduce((x, b) => x + b.byteLength, 0);
    let source, sliced, buffer;
    let offset = 0, index = -1, length = Math.min(size || Infinity, byteLength);
    for (let n = result.length; ++index < n;) {
        source = result[index];
        sliced = source.subarray(0, Math.min(source.length, length - offset));
        if (length <= (offset + sliced.length)) {
            if (sliced.length < source.length) {
                result[index] = source.subarray(sliced.length);
            }
            else if (sliced.length === source.length) {
                index++;
            }
            buffer ? standalone_memcpy(buffer, sliced, offset) : (buffer = sliced);
            break;
        }
        standalone_memcpy(buffer || (buffer = new Uint8Array(length)), sliced, offset);
        offset += sliced.length;
    }
    return [buffer || new Uint8Array(0), result.slice(index), byteLength - (buffer ? buffer.byteLength : 0)];
}
function standalone_toArrayBufferView(ArrayBufferViewCtor, input) {
    let value = standalone_isIteratorResult(input) ? input.value : input;
    if (value instanceof ArrayBufferViewCtor) {
        if (ArrayBufferViewCtor === Uint8Array) {
            // Node's `Buffer` class passes the `instanceof Uint8Array` check, but we need
            // a real Uint8Array, since Buffer#slice isn't the same as Uint8Array#slice :/
            return new ArrayBufferViewCtor(value.buffer, value.byteOffset, value.byteLength);
        }
        return value;
    }
    if (!value) {
        return new ArrayBufferViewCtor(0);
    }
    if (typeof value === 'string') {
        value = standalone_encodeUtf8(value);
    }
    if (value instanceof ArrayBuffer) {
        return new ArrayBufferViewCtor(value);
    }
    if (value instanceof standalone_SharedArrayBuf) {
        return new ArrayBufferViewCtor(value);
    }
    if (value instanceof standalone_ByteBuffer) {
        return standalone_toArrayBufferView(ArrayBufferViewCtor, value.bytes());
    }
    return !ArrayBuffer.isView(value) ? ArrayBufferViewCtor.from(value) : value.byteLength <= 0 ? new ArrayBufferViewCtor(0)
        : new ArrayBufferViewCtor(value.buffer, value.byteOffset, value.byteLength / ArrayBufferViewCtor.BYTES_PER_ELEMENT);
}
/** @ignore */ const standalone_toInt8Array = (input) => standalone_toArrayBufferView(Int8Array, input);
/** @ignore */ const standalone_toInt16Array = (input) => standalone_toArrayBufferView(Int16Array, input);
/** @ignore */ const standalone_toInt32Array = (input) => standalone_toArrayBufferView(Int32Array, input);
/** @ignore */ const standalone_toBigInt64Array = (input) => standalone_toArrayBufferView(standalone_BigInt64ArrayCtor, input);
/** @ignore */ const standalone_toUint8Array = (input) => standalone_toArrayBufferView(Uint8Array, input);
/** @ignore */ const standalone_toUint16Array = (input) => standalone_toArrayBufferView(Uint16Array, input);
/** @ignore */ const standalone_toUint32Array = (input) => standalone_toArrayBufferView(Uint32Array, input);
/** @ignore */ const standalone_toBigUint64Array = (input) => standalone_toArrayBufferView(standalone_BigUint64ArrayCtor, input);
/** @ignore */ const standalone_toFloat32Array = (input) => standalone_toArrayBufferView(Float32Array, input);
/** @ignore */ const standalone_toFloat64Array = (input) => standalone_toArrayBufferView(Float64Array, input);
/** @ignore */ const standalone_toUint8ClampedArray = (input) => standalone_toArrayBufferView(Uint8ClampedArray, input);
/** @ignore */
const standalone_pump = (iterator) => { iterator.next(); return iterator; };
/** @ignore */
function* standalone_toArrayBufferViewIterator(ArrayCtor, source) {
    const wrap = function* (x) { yield x; };
    const buffers = (typeof source === 'string') ? wrap(source)
        : (ArrayBuffer.isView(source)) ? wrap(source)
            : (source instanceof ArrayBuffer) ? wrap(source)
                : (source instanceof standalone_SharedArrayBuf) ? wrap(source)
                    : !standalone_compat_isIterable(source) ? wrap(source) : source;
    yield* standalone_pump((function* (it) {
        let r = null;
        do {
            r = it.next(yield standalone_toArrayBufferView(ArrayCtor, r));
        } while (!r.done);
    })(buffers[Symbol.iterator]()));
    return new ArrayCtor();
}
/** @ignore */ const standalone_toInt8ArrayIterator = (input) => standalone_toArrayBufferViewIterator(Int8Array, input);
/** @ignore */ const standalone_toInt16ArrayIterator = (input) => standalone_toArrayBufferViewIterator(Int16Array, input);
/** @ignore */ const standalone_toInt32ArrayIterator = (input) => standalone_toArrayBufferViewIterator(Int32Array, input);
/** @ignore */ const standalone_toUint8ArrayIterator = (input) => standalone_toArrayBufferViewIterator(Uint8Array, input);
/** @ignore */ const standalone_toUint16ArrayIterator = (input) => standalone_toArrayBufferViewIterator(Uint16Array, input);
/** @ignore */ const standalone_toUint32ArrayIterator = (input) => standalone_toArrayBufferViewIterator(Uint32Array, input);
/** @ignore */ const standalone_toFloat32ArrayIterator = (input) => standalone_toArrayBufferViewIterator(Float32Array, input);
/** @ignore */ const standalone_toFloat64ArrayIterator = (input) => standalone_toArrayBufferViewIterator(Float64Array, input);
/** @ignore */ const standalone_toUint8ClampedArrayIterator = (input) => standalone_toArrayBufferViewIterator(Uint8ClampedArray, input);
/** @ignore */
async function* standalone_toArrayBufferViewAsyncIterator(ArrayCtor, source) {
    // if a Promise, unwrap the Promise and iterate the resolved value
    if (standalone_isPromise(source)) {
        return yield* standalone_toArrayBufferViewAsyncIterator(ArrayCtor, await source);
    }
    const wrap = async function* (x) { yield await x; };
    const emit = async function* (source) {
        yield* standalone_pump((function* (it) {
            let r = null;
            do {
                r = it.next(yield r && r.value);
            } while (!r.done);
        })(source[Symbol.iterator]()));
    };
    const buffers = (typeof source === 'string') ? wrap(source) // if string, wrap in an AsyncIterableIterator
        : (ArrayBuffer.isView(source)) ? wrap(source) // if TypedArray, wrap in an AsyncIterableIterator
            : (source instanceof ArrayBuffer) ? wrap(source) // if ArrayBuffer, wrap in an AsyncIterableIterator
                : (source instanceof standalone_SharedArrayBuf) ? wrap(source) // if SharedArrayBuffer, wrap in an AsyncIterableIterator
                    : standalone_compat_isIterable(source) ? emit(source) // If Iterable, wrap in an AsyncIterableIterator and compose the `next` values
                        : !standalone_isAsyncIterable(source) ? wrap(source) // If not an AsyncIterable, treat as a sentinel and wrap in an AsyncIterableIterator
                            : source; // otherwise if AsyncIterable, use it
    yield* standalone_pump((async function* (it) {
        let r = null;
        do {
            r = await it.next(yield standalone_toArrayBufferView(ArrayCtor, r));
        } while (!r.done);
    })(buffers[Symbol.asyncIterator]()));
    return new ArrayCtor();
}
/** @ignore */ const standalone_toInt8ArrayAsyncIterator = (input) => standalone_toArrayBufferViewAsyncIterator(Int8Array, input);
/** @ignore */ const standalone_toInt16ArrayAsyncIterator = (input) => standalone_toArrayBufferViewAsyncIterator(Int16Array, input);
/** @ignore */ const standalone_toInt32ArrayAsyncIterator = (input) => standalone_toArrayBufferViewAsyncIterator(Int32Array, input);
/** @ignore */ const standalone_toUint8ArrayAsyncIterator = (input) => standalone_toArrayBufferViewAsyncIterator(Uint8Array, input);
/** @ignore */ const standalone_toUint16ArrayAsyncIterator = (input) => standalone_toArrayBufferViewAsyncIterator(Uint16Array, input);
/** @ignore */ const standalone_toUint32ArrayAsyncIterator = (input) => standalone_toArrayBufferViewAsyncIterator(Uint32Array, input);
/** @ignore */ const standalone_toFloat32ArrayAsyncIterator = (input) => standalone_toArrayBufferViewAsyncIterator(Float32Array, input);
/** @ignore */ const standalone_toFloat64ArrayAsyncIterator = (input) => standalone_toArrayBufferViewAsyncIterator(Float64Array, input);
/** @ignore */ const standalone_toUint8ClampedArrayAsyncIterator = (input) => standalone_toArrayBufferViewAsyncIterator(Uint8ClampedArray, input);
/** @ignore */
function standalone_rebaseValueOffsets(offset, length, valueOffsets) {
    // If we have a non-zero offset, create a new offsets array with the values
    // shifted by the start offset, such that the new start offset is 0
    if (offset !== 0) {
        valueOffsets = valueOffsets.slice(0, length + 1);
        for (let i = -1; ++i <= length;) {
            valueOffsets[i] += offset;
        }
    }
    return valueOffsets;
}
/** @ignore */
function standalone_compareArrayLike(a, b) {
    let i = 0, n = a.length;
    if (n !== b.length) {
        return false;
    }
    if (n > 0) {
        do {
            if (a[i] !== b[i]) {
                return false;
            }
        } while (++i < n);
    }
    return true;
}

//# sourceMappingURL=buffer.mjs.map

;// ../../node_modules/apache-arrow/io/adapters.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
/* harmony default export */ const standalone_adapters = ({
    fromIterable(source) {
        return standalone_adapters_pump(standalone_adapters_fromIterable(source));
    },
    fromAsyncIterable(source) {
        return standalone_adapters_pump(standalone_fromAsyncIterable(source));
    },
    fromDOMStream(source) {
        return standalone_adapters_pump(standalone_fromDOMStream(source));
    },
    fromNodeStream(stream) {
        return standalone_adapters_pump(standalone_fromNodeStream(stream));
    },
    // @ts-ignore
    toDOMStream(source, options) {
        throw new Error(`"toDOMStream" not available in this environment`);
    },
    // @ts-ignore
    toNodeStream(source, options) {
        throw new Error(`"toNodeStream" not available in this environment`);
    },
});
/** @ignore */
const standalone_adapters_pump = (iterator) => { iterator.next(); return iterator; };
/** @ignore */
function* standalone_adapters_fromIterable(source) {
    let done, threw = false;
    let buffers = [], buffer;
    let cmd, size, bufferLength = 0;
    function byteRange() {
        if (cmd === 'peek') {
            return standalone_joinUint8Arrays(buffers, size)[0];
        }
        [buffer, buffers, bufferLength] = standalone_joinUint8Arrays(buffers, size);
        return buffer;
    }
    // Yield so the caller can inject the read command before creating the source Iterator
    ({ cmd, size } = yield null);
    // initialize the iterator
    let it = standalone_toUint8ArrayIterator(source)[Symbol.iterator]();
    try {
        do {
            // read the next value
            ({ done, value: buffer } = isNaN(size - bufferLength) ?
                it.next(undefined) : it.next(size - bufferLength));
            // if chunk is not null or empty, push it onto the queue
            if (!done && buffer.byteLength > 0) {
                buffers.push(buffer);
                bufferLength += buffer.byteLength;
            }
            // If we have enough bytes in our buffer, yield chunks until we don't
            if (done || size <= bufferLength) {
                do {
                    ({ cmd, size } = yield byteRange());
                } while (size < bufferLength);
            }
        } while (!done);
    }
    catch (e) {
        (threw = true) && (typeof it.throw === 'function') && (it.throw(e));
    }
    finally {
        (threw === false) && (typeof it.return === 'function') && (it.return(null));
    }
    return null;
}
/** @ignore */
async function* standalone_fromAsyncIterable(source) {
    let done, threw = false;
    let buffers = [], buffer;
    let cmd, size, bufferLength = 0;
    function byteRange() {
        if (cmd === 'peek') {
            return standalone_joinUint8Arrays(buffers, size)[0];
        }
        [buffer, buffers, bufferLength] = standalone_joinUint8Arrays(buffers, size);
        return buffer;
    }
    // Yield so the caller can inject the read command before creating the source AsyncIterator
    ({ cmd, size } = (yield null));
    // initialize the iterator
    let it = standalone_toUint8ArrayAsyncIterator(source)[Symbol.asyncIterator]();
    try {
        do {
            // read the next value
            ({ done, value: buffer } = isNaN(size - bufferLength)
                ? await it.next(undefined)
                : await it.next(size - bufferLength));
            // if chunk is not null or empty, push it onto the queue
            if (!done && buffer.byteLength > 0) {
                buffers.push(buffer);
                bufferLength += buffer.byteLength;
            }
            // If we have enough bytes in our buffer, yield chunks until we don't
            if (done || size <= bufferLength) {
                do {
                    ({ cmd, size } = yield byteRange());
                } while (size < bufferLength);
            }
        } while (!done);
    }
    catch (e) {
        (threw = true) && (typeof it.throw === 'function') && (await it.throw(e));
    }
    finally {
        (threw === false) && (typeof it.return === 'function') && (await it.return(new Uint8Array(0)));
    }
    return null;
}
// All this manual Uint8Array chunk management can be avoided if/when engines
// add support for ArrayBuffer.transfer() or ArrayBuffer.prototype.realloc():
// https://github.com/domenic/proposal-arraybuffer-transfer
/** @ignore */
async function* standalone_fromDOMStream(source) {
    let done = false, threw = false;
    let buffers = [], buffer;
    let cmd, size, bufferLength = 0;
    function byteRange() {
        if (cmd === 'peek') {
            return standalone_joinUint8Arrays(buffers, size)[0];
        }
        [buffer, buffers, bufferLength] = standalone_joinUint8Arrays(buffers, size);
        return buffer;
    }
    // Yield so the caller can inject the read command before we establish the ReadableStream lock
    ({ cmd, size } = yield null);
    // initialize the reader and lock the stream
    let it = new standalone_AdaptiveByteReader(source);
    try {
        do {
            // read the next value
            ({ done, value: buffer } = isNaN(size - bufferLength)
                ? await it['read'](undefined)
                : await it['read'](size - bufferLength));
            // if chunk is not null or empty, push it onto the queue
            if (!done && buffer.byteLength > 0) {
                buffers.push(standalone_toUint8Array(buffer));
                bufferLength += buffer.byteLength;
            }
            // If we have enough bytes in our buffer, yield chunks until we don't
            if (done || size <= bufferLength) {
                do {
                    ({ cmd, size } = yield byteRange());
                } while (size < bufferLength);
            }
        } while (!done);
    }
    catch (e) {
        (threw = true) && (await it['cancel'](e));
    }
    finally {
        (threw === false) ? (await it['cancel']())
            : source['locked'] && it.releaseLock();
    }
    return null;
}
/** @ignore */
class standalone_AdaptiveByteReader {
    constructor(source) {
        this.source = source;
        this.byobReader = null;
        this.defaultReader = null;
        try {
            this.supportsBYOB = !!(this.reader = this.getBYOBReader());
        }
        catch (e) {
            this.supportsBYOB = !!!(this.reader = this.getDefaultReader());
        }
    }
    get closed() {
        return this.reader ? this.reader['closed'].catch(() => { }) : Promise.resolve();
    }
    releaseLock() {
        if (this.reader) {
            this.reader.releaseLock();
        }
        this.reader = this.byobReader = this.defaultReader = null;
    }
    async cancel(reason) {
        const { reader, source } = this;
        reader && (await reader['cancel'](reason).catch(() => { }));
        source && (source['locked'] && this.releaseLock());
    }
    async read(size) {
        if (size === 0) {
            return { done: this.reader == null, value: new Uint8Array(0) };
        }
        const result = !this.supportsBYOB || typeof size !== 'number'
            ? await this.getDefaultReader().read()
            : await this.readFromBYOBReader(size);
        !result.done && (result.value = standalone_toUint8Array(result));
        return result;
    }
    getDefaultReader() {
        if (this.byobReader) {
            this.releaseLock();
        }
        if (!this.defaultReader) {
            this.defaultReader = this.source['getReader']();
            // We have to catch and swallow errors here to avoid uncaught promise rejection exceptions
            // that seem to be raised when we call `releaseLock()` on this reader. I'm still mystified
            // about why these errors are raised, but I'm sure there's some important spec reason that
            // I haven't considered. I hate to employ such an anti-pattern here, but it seems like the
            // only solution in this case :/
            this.defaultReader['closed'].catch(() => { });
        }
        return (this.reader = this.defaultReader);
    }
    getBYOBReader() {
        if (this.defaultReader) {
            this.releaseLock();
        }
        if (!this.byobReader) {
            this.byobReader = this.source['getReader']({ mode: 'byob' });
            // We have to catch and swallow errors here to avoid uncaught promise rejection exceptions
            // that seem to be raised when we call `releaseLock()` on this reader. I'm still mystified
            // about why these errors are raised, but I'm sure there's some important spec reason that
            // I haven't considered. I hate to employ such an anti-pattern here, but it seems like the
            // only solution in this case :/
            this.byobReader['closed'].catch(() => { });
        }
        return (this.reader = this.byobReader);
    }
    // This strategy plucked from the example in the streams spec:
    // https://streams.spec.whatwg.org/#example-manual-read-bytes
    async readFromBYOBReader(size) {
        return await standalone_readInto(this.getBYOBReader(), new ArrayBuffer(size), 0, size);
    }
}
/** @ignore */
async function standalone_readInto(reader, buffer, offset, size) {
    if (offset >= size) {
        return { done: false, value: new Uint8Array(buffer, 0, size) };
    }
    const { done, value } = await reader.read(new Uint8Array(buffer, offset, size - offset));
    if (((offset += value.byteLength) < size) && !done) {
        return await standalone_readInto(reader, value.buffer, offset, size);
    }
    return { done, value: new Uint8Array(value.buffer, 0, offset) };
}
/** @ignore */
const standalone_onEvent = (stream, event) => {
    let handler = (_) => resolve([event, _]);
    let resolve;
    return [event, handler, new Promise((r) => (resolve = r) && stream['once'](event, handler))];
};
/** @ignore */
async function* standalone_fromNodeStream(stream) {
    let events = [];
    let event = 'error';
    let done = false, err = null;
    let cmd, size, bufferLength = 0;
    let buffers = [], buffer;
    function byteRange() {
        if (cmd === 'peek') {
            return standalone_joinUint8Arrays(buffers, size)[0];
        }
        [buffer, buffers, bufferLength] = standalone_joinUint8Arrays(buffers, size);
        return buffer;
    }
    // Yield so the caller can inject the read command before we
    // add the listener for the source stream's 'readable' event.
    ({ cmd, size } = yield null);
    // ignore stdin if it's a TTY
    if (stream['isTTY']) {
        yield new Uint8Array(0);
        return null;
    }
    try {
        // initialize the stream event handlers
        events[0] = standalone_onEvent(stream, 'end');
        events[1] = standalone_onEvent(stream, 'error');
        do {
            events[2] = standalone_onEvent(stream, 'readable');
            // wait on the first message event from the stream
            [event, err] = await Promise.race(events.map((x) => x[2]));
            // if the stream emitted an Error, rethrow it
            if (event === 'error') {
                break;
            }
            if (!(done = event === 'end')) {
                // If the size is NaN, request to read everything in the stream's internal buffer
                if (!isFinite(size - bufferLength)) {
                    buffer = standalone_toUint8Array(stream['read'](undefined));
                }
                else {
                    buffer = standalone_toUint8Array(stream['read'](size - bufferLength));
                    // If the byteLength is 0, then the requested amount is more than the stream has
                    // in its internal buffer. In this case the stream needs a "kick" to tell it to
                    // continue emitting readable events, so request to read everything the stream
                    // has in its internal buffer right now.
                    if (buffer.byteLength < (size - bufferLength)) {
                        buffer = standalone_toUint8Array(stream['read'](undefined));
                    }
                }
                // if chunk is not null or empty, push it onto the queue
                if (buffer.byteLength > 0) {
                    buffers.push(buffer);
                    bufferLength += buffer.byteLength;
                }
            }
            // If we have enough bytes in our buffer, yield chunks until we don't
            if (done || size <= bufferLength) {
                do {
                    ({ cmd, size } = yield byteRange());
                } while (size < bufferLength);
            }
        } while (!done);
    }
    finally {
        await cleanup(events, event === 'error' ? err : null);
    }
    return null;
    function cleanup(events, err) {
        buffer = buffers = null;
        return new Promise(async (resolve, reject) => {
            for (const [evt, fn] of events) {
                stream['off'](evt, fn);
            }
            try {
                // Some stream implementations don't call the destroy callback,
                // because it's really a node-internal API. Just calling `destroy`
                // here should be enough to conform to the ReadableStream contract
                const destroy = stream['destroy'];
                destroy && destroy.call(stream, err);
                err = undefined;
            }
            catch (e) {
                err = e || err;
            }
            finally {
                err != null ? reject(err) : resolve();
            }
        });
    }
}

//# sourceMappingURL=adapters.mjs.map

;// ../../node_modules/apache-arrow/vector.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
class standalone_AbstractVector {
}
standalone_AbstractVector.prototype.data = null;


//# sourceMappingURL=vector.mjs.map

;// ../../node_modules/apache-arrow/fb/Schema.mjs
/* tslint:disable:class-name */
/**
 * @enum {number}
 */
var standalone_Schema_org;
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                let MetadataVersion;
                (function (MetadataVersion) {
                    /**
                     * 0.1.0
                     */
                    MetadataVersion[MetadataVersion["V1"] = 0] = "V1";
                    /**
                     * 0.2.0
                     */
                    MetadataVersion[MetadataVersion["V2"] = 1] = "V2";
                    /**
                     * 0.3.0 -> 0.7.1
                     */
                    MetadataVersion[MetadataVersion["V3"] = 2] = "V3";
                    /**
                     * >= 0.8.0
                     */
                    MetadataVersion[MetadataVersion["V4"] = 3] = "V4";
                })(MetadataVersion = flatbuf.MetadataVersion || (flatbuf.MetadataVersion = {}));
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @enum {number}
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                let UnionMode;
                (function (UnionMode) {
                    UnionMode[UnionMode["Sparse"] = 0] = "Sparse";
                    UnionMode[UnionMode["Dense"] = 1] = "Dense";
                })(UnionMode = flatbuf.UnionMode || (flatbuf.UnionMode = {}));
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @enum {number}
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                let Precision;
                (function (Precision) {
                    Precision[Precision["HALF"] = 0] = "HALF";
                    Precision[Precision["SINGLE"] = 1] = "SINGLE";
                    Precision[Precision["DOUBLE"] = 2] = "DOUBLE";
                })(Precision = flatbuf.Precision || (flatbuf.Precision = {}));
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @enum {number}
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                let DateUnit;
                (function (DateUnit) {
                    DateUnit[DateUnit["DAY"] = 0] = "DAY";
                    DateUnit[DateUnit["MILLISECOND"] = 1] = "MILLISECOND";
                })(DateUnit = flatbuf.DateUnit || (flatbuf.DateUnit = {}));
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @enum {number}
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                let TimeUnit;
                (function (TimeUnit) {
                    TimeUnit[TimeUnit["SECOND"] = 0] = "SECOND";
                    TimeUnit[TimeUnit["MILLISECOND"] = 1] = "MILLISECOND";
                    TimeUnit[TimeUnit["MICROSECOND"] = 2] = "MICROSECOND";
                    TimeUnit[TimeUnit["NANOSECOND"] = 3] = "NANOSECOND";
                })(TimeUnit = flatbuf.TimeUnit || (flatbuf.TimeUnit = {}));
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @enum {number}
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                let IntervalUnit;
                (function (IntervalUnit) {
                    IntervalUnit[IntervalUnit["YEAR_MONTH"] = 0] = "YEAR_MONTH";
                    IntervalUnit[IntervalUnit["DAY_TIME"] = 1] = "DAY_TIME";
                })(IntervalUnit = flatbuf.IntervalUnit || (flatbuf.IntervalUnit = {}));
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * ----------------------------------------------------------------------
 * Top-level Type value, enabling extensible type-specific metadata. We can
 * add new logical types to Type without breaking backwards compatibility
 *
 * @enum {number}
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                let Type;
                (function (Type) {
                    Type[Type["NONE"] = 0] = "NONE";
                    Type[Type["Null"] = 1] = "Null";
                    Type[Type["Int"] = 2] = "Int";
                    Type[Type["FloatingPoint"] = 3] = "FloatingPoint";
                    Type[Type["Binary"] = 4] = "Binary";
                    Type[Type["Utf8"] = 5] = "Utf8";
                    Type[Type["Bool"] = 6] = "Bool";
                    Type[Type["Decimal"] = 7] = "Decimal";
                    Type[Type["Date"] = 8] = "Date";
                    Type[Type["Time"] = 9] = "Time";
                    Type[Type["Timestamp"] = 10] = "Timestamp";
                    Type[Type["Interval"] = 11] = "Interval";
                    Type[Type["List"] = 12] = "List";
                    Type[Type["Struct_"] = 13] = "Struct_";
                    Type[Type["Union"] = 14] = "Union";
                    Type[Type["FixedSizeBinary"] = 15] = "FixedSizeBinary";
                    Type[Type["FixedSizeList"] = 16] = "FixedSizeList";
                    Type[Type["Map"] = 17] = "Map";
                    Type[Type["Duration"] = 18] = "Duration";
                    Type[Type["LargeBinary"] = 19] = "LargeBinary";
                    Type[Type["LargeUtf8"] = 20] = "LargeUtf8";
                    Type[Type["LargeList"] = 21] = "LargeList";
                })(Type = flatbuf.Type || (flatbuf.Type = {}));
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * ----------------------------------------------------------------------
 * Endianness of the platform producing the data
 *
 * @enum {number}
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                let Endianness;
                (function (Endianness) {
                    Endianness[Endianness["Little"] = 0] = "Little";
                    Endianness[Endianness["Big"] = 1] = "Big";
                })(Endianness = flatbuf.Endianness || (flatbuf.Endianness = {}));
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * These are stored in the flatbuffer in the Type union below
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Null {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Null
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Null= obj
                     * @returns Null
                     */
                    static getRootAsNull(bb, obj) {
                        return (obj || new Null).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startNull(builder) {
                        builder.startObject(0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endNull(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createNull(builder) {
                        Null.startNull(builder);
                        return Null.endNull(builder);
                    }
                }
                flatbuf.Null = Null;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * A Struct_ in the flatbuffer metadata is the same as an Arrow Struct
 * (according to the physical memory layout). We used Struct_ here as
 * Struct is a reserved word in Flatbuffers
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Struct_ {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Struct_
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Struct_= obj
                     * @returns Struct_
                     */
                    static getRootAsStruct_(bb, obj) {
                        return (obj || new Struct_).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startStruct_(builder) {
                        builder.startObject(0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endStruct_(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createStruct_(builder) {
                        Struct_.startStruct_(builder);
                        return Struct_.endStruct_(builder);
                    }
                }
                flatbuf.Struct_ = Struct_;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class List {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns List
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param List= obj
                     * @returns List
                     */
                    static getRootAsList(bb, obj) {
                        return (obj || new List).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startList(builder) {
                        builder.startObject(0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endList(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createList(builder) {
                        List.startList(builder);
                        return List.endList(builder);
                    }
                }
                flatbuf.List = List;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * Same as List, but with 64-bit offsets, allowing to represent
 * extremely large data values.
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class LargeList {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns LargeList
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param LargeList= obj
                     * @returns LargeList
                     */
                    static getRootAsLargeList(bb, obj) {
                        return (obj || new LargeList).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startLargeList(builder) {
                        builder.startObject(0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endLargeList(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createLargeList(builder) {
                        LargeList.startLargeList(builder);
                        return LargeList.endLargeList(builder);
                    }
                }
                flatbuf.LargeList = LargeList;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class FixedSizeList {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns FixedSizeList
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param FixedSizeList= obj
                     * @returns FixedSizeList
                     */
                    static getRootAsFixedSizeList(bb, obj) {
                        return (obj || new FixedSizeList).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * Number of list items per value
                     *
                     * @returns number
                     */
                    listSize() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startFixedSizeList(builder) {
                        builder.startObject(1);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number listSize
                     */
                    static addListSize(builder, listSize) {
                        builder.addFieldInt32(0, listSize, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endFixedSizeList(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createFixedSizeList(builder, listSize) {
                        FixedSizeList.startFixedSizeList(builder);
                        FixedSizeList.addListSize(builder, listSize);
                        return FixedSizeList.endFixedSizeList(builder);
                    }
                }
                flatbuf.FixedSizeList = FixedSizeList;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * A Map is a logical nested type that is represented as
 *
 * List<entry: Struct<key: K, value: V>>
 *
 * In this layout, the keys and values are each respectively contiguous. We do
 * not constrain the key and value types, so the application is responsible
 * for ensuring that the keys are hashable and unique. Whether the keys are sorted
 * may be set in the metadata for this field
 *
 * In a Field with Map type, the Field has a child Struct field, which then
 * has two children: key type and the second the value type. The names of the
 * child fields may be respectively "entry", "key", and "value", but this is
 * not enforced
 *
 * Map
 *   - child[0] entry: Struct
 *     - child[0] key: K
 *     - child[1] value: V
 *
 * Neither the "entry" field nor the "key" field may be nullable.
 *
 * The metadata is structured so that Arrow systems without special handling
 * for Map can make Map an alias for List. The "layout" attribute for the Map
 * field must have the same contents as a List.
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Map {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Map
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Map= obj
                     * @returns Map
                     */
                    static getRootAsMap(bb, obj) {
                        return (obj || new Map).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * Set to true if the keys within each value are sorted
                     *
                     * @returns boolean
                     */
                    keysSorted() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startMap(builder) {
                        builder.startObject(1);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param boolean keysSorted
                     */
                    static addKeysSorted(builder, keysSorted) {
                        builder.addFieldInt8(0, +keysSorted, +false);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endMap(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createMap(builder, keysSorted) {
                        Map.startMap(builder);
                        Map.addKeysSorted(builder, keysSorted);
                        return Map.endMap(builder);
                    }
                }
                flatbuf.Map = Map;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * A union is a complex type with children in Field
 * By default ids in the type vector refer to the offsets in the children
 * optionally typeIds provides an indirection between the child offset and the type id
 * for each child typeIds[offset] is the id used in the type vector
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Union {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Union
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Union= obj
                     * @returns Union
                     */
                    static getRootAsUnion(bb, obj) {
                        return (obj || new Union).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @returns org.apache.arrow.flatbuf.UnionMode
                     */
                    mode() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? /**  */ (this.bb.readInt16(this.bb_pos + offset)) : org.apache.arrow.flatbuf.UnionMode.Sparse;
                    }
                    /**
                     * @param number index
                     * @returns number
                     */
                    typeIds(index) {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? this.bb.readInt32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
                    }
                    /**
                     * @returns number
                     */
                    typeIdsLength() {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @returns Int32Array
                     */
                    typeIdsArray() {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startUnion(builder) {
                        builder.startObject(2);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.UnionMode mode
                     */
                    static addMode(builder, mode) {
                        builder.addFieldInt16(0, mode, org.apache.arrow.flatbuf.UnionMode.Sparse);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset typeIdsOffset
                     */
                    static addTypeIds(builder, typeIdsOffset) {
                        builder.addFieldOffset(1, typeIdsOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param Array.<number> data
                     * @returns flatbuffers.Offset
                     */
                    static createTypeIdsVector(builder, data) {
                        builder.startVector(4, data.length, 4);
                        for (let i = data.length - 1; i >= 0; i--) {
                            builder.addInt32(data[i]);
                        }
                        return builder.endVector();
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number numElems
                     */
                    static startTypeIdsVector(builder, numElems) {
                        builder.startVector(4, numElems, 4);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endUnion(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createUnion(builder, mode, typeIdsOffset) {
                        Union.startUnion(builder);
                        Union.addMode(builder, mode);
                        Union.addTypeIds(builder, typeIdsOffset);
                        return Union.endUnion(builder);
                    }
                }
                flatbuf.Union = Union;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Int {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Int
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Int= obj
                     * @returns Int
                     */
                    static getRootAsInt(bb, obj) {
                        return (obj || new Int).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @returns number
                     */
                    bitWidth() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @returns boolean
                     */
                    isSigned() {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startInt(builder) {
                        builder.startObject(2);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number bitWidth
                     */
                    static addBitWidth(builder, bitWidth) {
                        builder.addFieldInt32(0, bitWidth, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param boolean isSigned
                     */
                    static addIsSigned(builder, isSigned) {
                        builder.addFieldInt8(1, +isSigned, +false);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endInt(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createInt(builder, bitWidth, isSigned) {
                        Int.startInt(builder);
                        Int.addBitWidth(builder, bitWidth);
                        Int.addIsSigned(builder, isSigned);
                        return Int.endInt(builder);
                    }
                }
                flatbuf.Int = Int;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class FloatingPoint {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns FloatingPoint
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param FloatingPoint= obj
                     * @returns FloatingPoint
                     */
                    static getRootAsFloatingPoint(bb, obj) {
                        return (obj || new FloatingPoint).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @returns org.apache.arrow.flatbuf.Precision
                     */
                    precision() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? /**  */ (this.bb.readInt16(this.bb_pos + offset)) : org.apache.arrow.flatbuf.Precision.HALF;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startFloatingPoint(builder) {
                        builder.startObject(1);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.Precision precision
                     */
                    static addPrecision(builder, precision) {
                        builder.addFieldInt16(0, precision, org.apache.arrow.flatbuf.Precision.HALF);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endFloatingPoint(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createFloatingPoint(builder, precision) {
                        FloatingPoint.startFloatingPoint(builder);
                        FloatingPoint.addPrecision(builder, precision);
                        return FloatingPoint.endFloatingPoint(builder);
                    }
                }
                flatbuf.FloatingPoint = FloatingPoint;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * Unicode with UTF-8 encoding
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Utf8 {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Utf8
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Utf8= obj
                     * @returns Utf8
                     */
                    static getRootAsUtf8(bb, obj) {
                        return (obj || new Utf8).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startUtf8(builder) {
                        builder.startObject(0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endUtf8(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createUtf8(builder) {
                        Utf8.startUtf8(builder);
                        return Utf8.endUtf8(builder);
                    }
                }
                flatbuf.Utf8 = Utf8;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * Opaque binary data
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Binary {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Binary
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Binary= obj
                     * @returns Binary
                     */
                    static getRootAsBinary(bb, obj) {
                        return (obj || new Binary).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startBinary(builder) {
                        builder.startObject(0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endBinary(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createBinary(builder) {
                        Binary.startBinary(builder);
                        return Binary.endBinary(builder);
                    }
                }
                flatbuf.Binary = Binary;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * Same as Utf8, but with 64-bit offsets, allowing to represent
 * extremely large data values.
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class LargeUtf8 {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns LargeUtf8
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param LargeUtf8= obj
                     * @returns LargeUtf8
                     */
                    static getRootAsLargeUtf8(bb, obj) {
                        return (obj || new LargeUtf8).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startLargeUtf8(builder) {
                        builder.startObject(0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endLargeUtf8(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createLargeUtf8(builder) {
                        LargeUtf8.startLargeUtf8(builder);
                        return LargeUtf8.endLargeUtf8(builder);
                    }
                }
                flatbuf.LargeUtf8 = LargeUtf8;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * Same as Binary, but with 64-bit offsets, allowing to represent
 * extremely large data values.
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class LargeBinary {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns LargeBinary
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param LargeBinary= obj
                     * @returns LargeBinary
                     */
                    static getRootAsLargeBinary(bb, obj) {
                        return (obj || new LargeBinary).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startLargeBinary(builder) {
                        builder.startObject(0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endLargeBinary(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createLargeBinary(builder) {
                        LargeBinary.startLargeBinary(builder);
                        return LargeBinary.endLargeBinary(builder);
                    }
                }
                flatbuf.LargeBinary = LargeBinary;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class FixedSizeBinary {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns FixedSizeBinary
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param FixedSizeBinary= obj
                     * @returns FixedSizeBinary
                     */
                    static getRootAsFixedSizeBinary(bb, obj) {
                        return (obj || new FixedSizeBinary).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * Number of bytes per value
                     *
                     * @returns number
                     */
                    byteWidth() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startFixedSizeBinary(builder) {
                        builder.startObject(1);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number byteWidth
                     */
                    static addByteWidth(builder, byteWidth) {
                        builder.addFieldInt32(0, byteWidth, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endFixedSizeBinary(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createFixedSizeBinary(builder, byteWidth) {
                        FixedSizeBinary.startFixedSizeBinary(builder);
                        FixedSizeBinary.addByteWidth(builder, byteWidth);
                        return FixedSizeBinary.endFixedSizeBinary(builder);
                    }
                }
                flatbuf.FixedSizeBinary = FixedSizeBinary;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Bool {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Bool
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Bool= obj
                     * @returns Bool
                     */
                    static getRootAsBool(bb, obj) {
                        return (obj || new Bool).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startBool(builder) {
                        builder.startObject(0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endBool(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createBool(builder) {
                        Bool.startBool(builder);
                        return Bool.endBool(builder);
                    }
                }
                flatbuf.Bool = Bool;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Decimal {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Decimal
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Decimal= obj
                     * @returns Decimal
                     */
                    static getRootAsDecimal(bb, obj) {
                        return (obj || new Decimal).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * Total number of decimal digits
                     *
                     * @returns number
                     */
                    precision() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
                    }
                    /**
                     * Number of digits after the decimal point "."
                     *
                     * @returns number
                     */
                    scale() {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startDecimal(builder) {
                        builder.startObject(2);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number precision
                     */
                    static addPrecision(builder, precision) {
                        builder.addFieldInt32(0, precision, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number scale
                     */
                    static addScale(builder, scale) {
                        builder.addFieldInt32(1, scale, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endDecimal(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createDecimal(builder, precision, scale) {
                        Decimal.startDecimal(builder);
                        Decimal.addPrecision(builder, precision);
                        Decimal.addScale(builder, scale);
                        return Decimal.endDecimal(builder);
                    }
                }
                flatbuf.Decimal = Decimal;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * Date is either a 32-bit or 64-bit type representing elapsed time since UNIX
 * epoch (1970-01-01), stored in either of two units:
 *
 * * Milliseconds (64 bits) indicating UNIX time elapsed since the epoch (no
 *   leap seconds), where the values are evenly divisible by 86400000
 * * Days (32 bits) since the UNIX epoch
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Date {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Date
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Date= obj
                     * @returns Date
                     */
                    static getRootAsDate(bb, obj) {
                        return (obj || new Date).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @returns org.apache.arrow.flatbuf.DateUnit
                     */
                    unit() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? /**  */ (this.bb.readInt16(this.bb_pos + offset)) : org.apache.arrow.flatbuf.DateUnit.MILLISECOND;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startDate(builder) {
                        builder.startObject(1);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.DateUnit unit
                     */
                    static addUnit(builder, unit) {
                        builder.addFieldInt16(0, unit, org.apache.arrow.flatbuf.DateUnit.MILLISECOND);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endDate(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createDate(builder, unit) {
                        Date.startDate(builder);
                        Date.addUnit(builder, unit);
                        return Date.endDate(builder);
                    }
                }
                flatbuf.Date = Date;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * Time type. The physical storage type depends on the unit
 * - SECOND and MILLISECOND: 32 bits
 * - MICROSECOND and NANOSECOND: 64 bits
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Time {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Time
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Time= obj
                     * @returns Time
                     */
                    static getRootAsTime(bb, obj) {
                        return (obj || new Time).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @returns org.apache.arrow.flatbuf.TimeUnit
                     */
                    unit() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? /**  */ (this.bb.readInt16(this.bb_pos + offset)) : org.apache.arrow.flatbuf.TimeUnit.MILLISECOND;
                    }
                    /**
                     * @returns number
                     */
                    bitWidth() {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? this.bb.readInt32(this.bb_pos + offset) : 32;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startTime(builder) {
                        builder.startObject(2);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.TimeUnit unit
                     */
                    static addUnit(builder, unit) {
                        builder.addFieldInt16(0, unit, org.apache.arrow.flatbuf.TimeUnit.MILLISECOND);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number bitWidth
                     */
                    static addBitWidth(builder, bitWidth) {
                        builder.addFieldInt32(1, bitWidth, 32);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endTime(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createTime(builder, unit, bitWidth) {
                        Time.startTime(builder);
                        Time.addUnit(builder, unit);
                        Time.addBitWidth(builder, bitWidth);
                        return Time.endTime(builder);
                    }
                }
                flatbuf.Time = Time;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * Time elapsed from the Unix epoch, 00:00:00.000 on 1 January 1970, excluding
 * leap seconds, as a 64-bit integer. Note that UNIX time does not include
 * leap seconds.
 *
 * The Timestamp metadata supports both "time zone naive" and "time zone
 * aware" timestamps. Read about the timezone attribute for more detail
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Timestamp {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Timestamp
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Timestamp= obj
                     * @returns Timestamp
                     */
                    static getRootAsTimestamp(bb, obj) {
                        return (obj || new Timestamp).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @returns org.apache.arrow.flatbuf.TimeUnit
                     */
                    unit() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? /**  */ (this.bb.readInt16(this.bb_pos + offset)) : org.apache.arrow.flatbuf.TimeUnit.SECOND;
                    }
                    timezone(optionalEncoding) {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startTimestamp(builder) {
                        builder.startObject(2);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.TimeUnit unit
                     */
                    static addUnit(builder, unit) {
                        builder.addFieldInt16(0, unit, org.apache.arrow.flatbuf.TimeUnit.SECOND);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset timezoneOffset
                     */
                    static addTimezone(builder, timezoneOffset) {
                        builder.addFieldOffset(1, timezoneOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endTimestamp(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createTimestamp(builder, unit, timezoneOffset) {
                        Timestamp.startTimestamp(builder);
                        Timestamp.addUnit(builder, unit);
                        Timestamp.addTimezone(builder, timezoneOffset);
                        return Timestamp.endTimestamp(builder);
                    }
                }
                flatbuf.Timestamp = Timestamp;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Interval {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Interval
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Interval= obj
                     * @returns Interval
                     */
                    static getRootAsInterval(bb, obj) {
                        return (obj || new Interval).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @returns org.apache.arrow.flatbuf.IntervalUnit
                     */
                    unit() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? /**  */ (this.bb.readInt16(this.bb_pos + offset)) : org.apache.arrow.flatbuf.IntervalUnit.YEAR_MONTH;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startInterval(builder) {
                        builder.startObject(1);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.IntervalUnit unit
                     */
                    static addUnit(builder, unit) {
                        builder.addFieldInt16(0, unit, org.apache.arrow.flatbuf.IntervalUnit.YEAR_MONTH);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endInterval(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createInterval(builder, unit) {
                        Interval.startInterval(builder);
                        Interval.addUnit(builder, unit);
                        return Interval.endInterval(builder);
                    }
                }
                flatbuf.Interval = Interval;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Duration {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Duration
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Duration= obj
                     * @returns Duration
                     */
                    static getRootAsDuration(bb, obj) {
                        return (obj || new Duration).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @returns org.apache.arrow.flatbuf.TimeUnit
                     */
                    unit() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? /**  */ (this.bb.readInt16(this.bb_pos + offset)) : org.apache.arrow.flatbuf.TimeUnit.MILLISECOND;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startDuration(builder) {
                        builder.startObject(1);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.TimeUnit unit
                     */
                    static addUnit(builder, unit) {
                        builder.addFieldInt16(0, unit, org.apache.arrow.flatbuf.TimeUnit.MILLISECOND);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endDuration(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createDuration(builder, unit) {
                        Duration.startDuration(builder);
                        Duration.addUnit(builder, unit);
                        return Duration.endDuration(builder);
                    }
                }
                flatbuf.Duration = Duration;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * ----------------------------------------------------------------------
 * user defined key value pairs to add custom metadata to arrow
 * key namespacing is the responsibility of the user
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class KeyValue {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns KeyValue
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param KeyValue= obj
                     * @returns KeyValue
                     */
                    static getRootAsKeyValue(bb, obj) {
                        return (obj || new KeyValue).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    key(optionalEncoding) {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                    }
                    value(optionalEncoding) {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startKeyValue(builder) {
                        builder.startObject(2);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset keyOffset
                     */
                    static addKey(builder, keyOffset) {
                        builder.addFieldOffset(0, keyOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset valueOffset
                     */
                    static addValue(builder, valueOffset) {
                        builder.addFieldOffset(1, valueOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endKeyValue(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createKeyValue(builder, keyOffset, valueOffset) {
                        KeyValue.startKeyValue(builder);
                        KeyValue.addKey(builder, keyOffset);
                        KeyValue.addValue(builder, valueOffset);
                        return KeyValue.endKeyValue(builder);
                    }
                }
                flatbuf.KeyValue = KeyValue;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * ----------------------------------------------------------------------
 * Dictionary encoding metadata
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class DictionaryEncoding {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns DictionaryEncoding
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param DictionaryEncoding= obj
                     * @returns DictionaryEncoding
                     */
                    static getRootAsDictionaryEncoding(bb, obj) {
                        return (obj || new DictionaryEncoding).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * The known dictionary id in the application where this data is used. In
                     * the file or streaming formats, the dictionary ids are found in the
                     * DictionaryBatch messages
                     *
                     * @returns flatbuffers.Long
                     */
                    id() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
                    }
                    /**
                     * The dictionary indices are constrained to be positive integers. If this
                     * field is null, the indices must be signed int32
                     *
                     * @param org.apache.arrow.flatbuf.Int= obj
                     * @returns org.apache.arrow.flatbuf.Int|null
                     */
                    indexType(obj) {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? (obj || new org.apache.arrow.flatbuf.Int).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
                    }
                    /**
                     * By default, dictionaries are not ordered, or the order does not have
                     * semantic meaning. In some statistical, applications, dictionary-encoding
                     * is used to represent ordered categorical data, and we provide a way to
                     * preserve that metadata here
                     *
                     * @returns boolean
                     */
                    isOrdered() {
                        let offset = this.bb.__offset(this.bb_pos, 8);
                        return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startDictionaryEncoding(builder) {
                        builder.startObject(3);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Long id
                     */
                    static addId(builder, id) {
                        builder.addFieldInt64(0, id, builder.createLong(0, 0));
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset indexTypeOffset
                     */
                    static addIndexType(builder, indexTypeOffset) {
                        builder.addFieldOffset(1, indexTypeOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param boolean isOrdered
                     */
                    static addIsOrdered(builder, isOrdered) {
                        builder.addFieldInt8(2, +isOrdered, +false);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endDictionaryEncoding(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createDictionaryEncoding(builder, id, indexTypeOffset, isOrdered) {
                        DictionaryEncoding.startDictionaryEncoding(builder);
                        DictionaryEncoding.addId(builder, id);
                        DictionaryEncoding.addIndexType(builder, indexTypeOffset);
                        DictionaryEncoding.addIsOrdered(builder, isOrdered);
                        return DictionaryEncoding.endDictionaryEncoding(builder);
                    }
                }
                flatbuf.DictionaryEncoding = DictionaryEncoding;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * ----------------------------------------------------------------------
 * A field represents a named column in a record / row batch or child of a
 * nested type.
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Field {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Field
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Field= obj
                     * @returns Field
                     */
                    static getRootAsField(bb, obj) {
                        return (obj || new Field).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    name(optionalEncoding) {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                    }
                    /**
                     * Whether or not this field can contain nulls. Should be true in general.
                     *
                     * @returns boolean
                     */
                    nullable() {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
                    }
                    /**
                     * @returns org.apache.arrow.flatbuf.Type
                     */
                    typeType() {
                        let offset = this.bb.__offset(this.bb_pos, 8);
                        return offset ? /**  */ (this.bb.readUint8(this.bb_pos + offset)) : org.apache.arrow.flatbuf.Type.NONE;
                    }
                    /**
                     * This is the type of the decoded value if the field is dictionary encoded.
                     *
                     * @param flatbuffers.Table obj
                     * @returns ?flatbuffers.Table
                     */
                    type(obj) {
                        let offset = this.bb.__offset(this.bb_pos, 10);
                        return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
                    }
                    /**
                     * Present only if the field is dictionary encoded.
                     *
                     * @param org.apache.arrow.flatbuf.DictionaryEncoding= obj
                     * @returns org.apache.arrow.flatbuf.DictionaryEncoding|null
                     */
                    dictionary(obj) {
                        let offset = this.bb.__offset(this.bb_pos, 12);
                        return offset ? (obj || new org.apache.arrow.flatbuf.DictionaryEncoding).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
                    }
                    /**
                     * children apply only to nested data types like Struct, List and Union. For
                     * primitive types children will have length 0.
                     *
                     * @param number index
                     * @param org.apache.arrow.flatbuf.Field= obj
                     * @returns org.apache.arrow.flatbuf.Field
                     */
                    children(index, obj) {
                        let offset = this.bb.__offset(this.bb_pos, 14);
                        return offset ? (obj || new org.apache.arrow.flatbuf.Field).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
                    }
                    /**
                     * @returns number
                     */
                    childrenLength() {
                        let offset = this.bb.__offset(this.bb_pos, 14);
                        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                    }
                    /**
                     * User-defined metadata
                     *
                     * @param number index
                     * @param org.apache.arrow.flatbuf.KeyValue= obj
                     * @returns org.apache.arrow.flatbuf.KeyValue
                     */
                    customMetadata(index, obj) {
                        let offset = this.bb.__offset(this.bb_pos, 16);
                        return offset ? (obj || new org.apache.arrow.flatbuf.KeyValue).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
                    }
                    /**
                     * @returns number
                     */
                    customMetadataLength() {
                        let offset = this.bb.__offset(this.bb_pos, 16);
                        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startField(builder) {
                        builder.startObject(7);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset nameOffset
                     */
                    static addName(builder, nameOffset) {
                        builder.addFieldOffset(0, nameOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param boolean nullable
                     */
                    static addNullable(builder, nullable) {
                        builder.addFieldInt8(1, +nullable, +false);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.Type typeType
                     */
                    static addTypeType(builder, typeType) {
                        builder.addFieldInt8(2, typeType, org.apache.arrow.flatbuf.Type.NONE);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset typeOffset
                     */
                    static addType(builder, typeOffset) {
                        builder.addFieldOffset(3, typeOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset dictionaryOffset
                     */
                    static addDictionary(builder, dictionaryOffset) {
                        builder.addFieldOffset(4, dictionaryOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset childrenOffset
                     */
                    static addChildren(builder, childrenOffset) {
                        builder.addFieldOffset(5, childrenOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param Array.<flatbuffers.Offset> data
                     * @returns flatbuffers.Offset
                     */
                    static createChildrenVector(builder, data) {
                        builder.startVector(4, data.length, 4);
                        for (let i = data.length - 1; i >= 0; i--) {
                            builder.addOffset(data[i]);
                        }
                        return builder.endVector();
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number numElems
                     */
                    static startChildrenVector(builder, numElems) {
                        builder.startVector(4, numElems, 4);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset customMetadataOffset
                     */
                    static addCustomMetadata(builder, customMetadataOffset) {
                        builder.addFieldOffset(6, customMetadataOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param Array.<flatbuffers.Offset> data
                     * @returns flatbuffers.Offset
                     */
                    static createCustomMetadataVector(builder, data) {
                        builder.startVector(4, data.length, 4);
                        for (let i = data.length - 1; i >= 0; i--) {
                            builder.addOffset(data[i]);
                        }
                        return builder.endVector();
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number numElems
                     */
                    static startCustomMetadataVector(builder, numElems) {
                        builder.startVector(4, numElems, 4);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endField(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createField(builder, nameOffset, nullable, typeType, typeOffset, dictionaryOffset, childrenOffset, customMetadataOffset) {
                        Field.startField(builder);
                        Field.addName(builder, nameOffset);
                        Field.addNullable(builder, nullable);
                        Field.addTypeType(builder, typeType);
                        Field.addType(builder, typeOffset);
                        Field.addDictionary(builder, dictionaryOffset);
                        Field.addChildren(builder, childrenOffset);
                        Field.addCustomMetadata(builder, customMetadataOffset);
                        return Field.endField(builder);
                    }
                }
                flatbuf.Field = Field;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * ----------------------------------------------------------------------
 * A Buffer represents a single contiguous memory segment
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Buffer {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Buffer
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * The relative offset into the shared memory page where the bytes for this
                     * buffer starts
                     *
                     * @returns flatbuffers.Long
                     */
                    offset() {
                        return this.bb.readInt64(this.bb_pos);
                    }
                    /**
                     * The absolute length (in bytes) of the memory buffer. The memory is found
                     * from offset (inclusive) to offset + length (non-inclusive).
                     *
                     * @returns flatbuffers.Long
                     */
                    length() {
                        return this.bb.readInt64(this.bb_pos + 8);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Long offset
                     * @param flatbuffers.Long length
                     * @returns flatbuffers.Offset
                     */
                    static createBuffer(builder, offset, length) {
                        builder.prep(8, 16);
                        builder.writeInt64(length);
                        builder.writeInt64(offset);
                        return builder.offset();
                    }
                }
                flatbuf.Buffer = Buffer;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));
/**
 * ----------------------------------------------------------------------
 * A Schema describes the columns in a row batch
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Schema {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Schema
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Schema= obj
                     * @returns Schema
                     */
                    static getRootAsSchema(bb, obj) {
                        return (obj || new Schema).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * endianness of the buffer
                     * it is Little Endian by default
                     * if endianness doesn't match the underlying system then the vectors need to be converted
                     *
                     * @returns org.apache.arrow.flatbuf.Endianness
                     */
                    endianness() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? /**  */ (this.bb.readInt16(this.bb_pos + offset)) : org.apache.arrow.flatbuf.Endianness.Little;
                    }
                    /**
                     * @param number index
                     * @param org.apache.arrow.flatbuf.Field= obj
                     * @returns org.apache.arrow.flatbuf.Field
                     */
                    fields(index, obj) {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? (obj || new org.apache.arrow.flatbuf.Field).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
                    }
                    /**
                     * @returns number
                     */
                    fieldsLength() {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @param number index
                     * @param org.apache.arrow.flatbuf.KeyValue= obj
                     * @returns org.apache.arrow.flatbuf.KeyValue
                     */
                    customMetadata(index, obj) {
                        let offset = this.bb.__offset(this.bb_pos, 8);
                        return offset ? (obj || new org.apache.arrow.flatbuf.KeyValue).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
                    }
                    /**
                     * @returns number
                     */
                    customMetadataLength() {
                        let offset = this.bb.__offset(this.bb_pos, 8);
                        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startSchema(builder) {
                        builder.startObject(3);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.Endianness endianness
                     */
                    static addEndianness(builder, endianness) {
                        builder.addFieldInt16(0, endianness, org.apache.arrow.flatbuf.Endianness.Little);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset fieldsOffset
                     */
                    static addFields(builder, fieldsOffset) {
                        builder.addFieldOffset(1, fieldsOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param Array.<flatbuffers.Offset> data
                     * @returns flatbuffers.Offset
                     */
                    static createFieldsVector(builder, data) {
                        builder.startVector(4, data.length, 4);
                        for (let i = data.length - 1; i >= 0; i--) {
                            builder.addOffset(data[i]);
                        }
                        return builder.endVector();
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number numElems
                     */
                    static startFieldsVector(builder, numElems) {
                        builder.startVector(4, numElems, 4);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset customMetadataOffset
                     */
                    static addCustomMetadata(builder, customMetadataOffset) {
                        builder.addFieldOffset(2, customMetadataOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param Array.<flatbuffers.Offset> data
                     * @returns flatbuffers.Offset
                     */
                    static createCustomMetadataVector(builder, data) {
                        builder.startVector(4, data.length, 4);
                        for (let i = data.length - 1; i >= 0; i--) {
                            builder.addOffset(data[i]);
                        }
                        return builder.endVector();
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number numElems
                     */
                    static startCustomMetadataVector(builder, numElems) {
                        builder.startVector(4, numElems, 4);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endSchema(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset offset
                     */
                    static finishSchemaBuffer(builder, offset) {
                        builder.finish(offset);
                    }
                    static createSchema(builder, endianness, fieldsOffset, customMetadataOffset) {
                        Schema.startSchema(builder);
                        Schema.addEndianness(builder, endianness);
                        Schema.addFields(builder, fieldsOffset);
                        Schema.addCustomMetadata(builder, customMetadataOffset);
                        return Schema.endSchema(builder);
                    }
                }
                flatbuf.Schema = Schema;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_Schema_org || (standalone_Schema_org = {}));

//# sourceMappingURL=Schema.mjs.map

;// ../../node_modules/apache-arrow/fb/Message.mjs
// automatically generated by the FlatBuffers compiler, do not modify

var standalone_org;
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                flatbuf.Schema = standalone_Schema_org.apache.arrow.flatbuf.Schema;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_org || (standalone_org = {}));
/**
 * ----------------------------------------------------------------------
 * The root Message type
 * This union enables us to easily send different message types without
 * redundant storage, and in the future we can easily add new message types.
 *
 * Arrow implementations do not need to implement all of the message types,
 * which may include experimental metadata types. For maximum compatibility,
 * it is best to send data using RecordBatch
 *
 * @enum {number}
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                let MessageHeader;
                (function (MessageHeader) {
                    MessageHeader[MessageHeader["NONE"] = 0] = "NONE";
                    MessageHeader[MessageHeader["Schema"] = 1] = "Schema";
                    MessageHeader[MessageHeader["DictionaryBatch"] = 2] = "DictionaryBatch";
                    MessageHeader[MessageHeader["RecordBatch"] = 3] = "RecordBatch";
                    MessageHeader[MessageHeader["Tensor"] = 4] = "Tensor";
                    MessageHeader[MessageHeader["SparseTensor"] = 5] = "SparseTensor";
                })(MessageHeader = flatbuf.MessageHeader || (flatbuf.MessageHeader = {}));
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_org || (standalone_org = {}));
/**
 * ----------------------------------------------------------------------
 * Data structures for describing a table row batch (a collection of
 * equal-length Arrow arrays)
 * Metadata about a field at some level of a nested type tree (but not
 * its children).
 *
 * For example, a List<Int16> with values [[1, 2, 3], null, [4], [5, 6], null]
 * would have {length: 5, null_count: 2} for its List node, and {length: 6,
 * null_count: 0} for its Int16 node, as separate FieldNode structs
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class FieldNode {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns FieldNode
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * The number of value slots in the Arrow array at this level of a nested
                     * tree
                     *
                     * @returns flatbuffers.Long
                     */
                    length() {
                        return this.bb.readInt64(this.bb_pos);
                    }
                    /**
                     * The number of observed nulls. Fields with null_count == 0 may choose not
                     * to write their physical validity bitmap out as a materialized buffer,
                     * instead setting the length of the bitmap buffer to 0.
                     *
                     * @returns flatbuffers.Long
                     */
                    nullCount() {
                        return this.bb.readInt64(this.bb_pos + 8);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Long length
                     * @param flatbuffers.Long null_count
                     * @returns flatbuffers.Offset
                     */
                    static createFieldNode(builder, length, null_count) {
                        builder.prep(8, 16);
                        builder.writeInt64(null_count);
                        builder.writeInt64(length);
                        return builder.offset();
                    }
                }
                flatbuf.FieldNode = FieldNode;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_org || (standalone_org = {}));
/**
 * A data header describing the shared memory layout of a "record" or "row"
 * batch. Some systems call this a "row batch" internally and others a "record
 * batch".
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class RecordBatch {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns RecordBatch
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param RecordBatch= obj
                     * @returns RecordBatch
                     */
                    static getRootAsRecordBatch(bb, obj) {
                        return (obj || new RecordBatch).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * number of records / rows. The arrays in the batch should all have this
                     * length
                     *
                     * @returns flatbuffers.Long
                     */
                    length() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
                    }
                    /**
                     * Nodes correspond to the pre-ordered flattened logical schema
                     *
                     * @param number index
                     * @param org.apache.arrow.flatbuf.FieldNode= obj
                     * @returns org.apache.arrow.flatbuf.FieldNode
                     */
                    nodes(index, obj) {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? (obj || new org.apache.arrow.flatbuf.FieldNode).__init(this.bb.__vector(this.bb_pos + offset) + index * 16, this.bb) : null;
                    }
                    /**
                     * @returns number
                     */
                    nodesLength() {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                    }
                    /**
                     * Buffers correspond to the pre-ordered flattened buffer tree
                     *
                     * The number of buffers appended to this list depends on the schema. For
                     * example, most primitive arrays will have 2 buffers, 1 for the validity
                     * bitmap and 1 for the values. For struct arrays, there will only be a
                     * single buffer for the validity (nulls) bitmap
                     *
                     * @param number index
                     * @param org.apache.arrow.flatbuf.Buffer= obj
                     * @returns org.apache.arrow.flatbuf.Buffer
                     */
                    buffers(index, obj) {
                        let offset = this.bb.__offset(this.bb_pos, 8);
                        return offset ? (obj || new standalone_Schema_org.apache.arrow.flatbuf.Buffer).__init(this.bb.__vector(this.bb_pos + offset) + index * 16, this.bb) : null;
                    }
                    /**
                     * @returns number
                     */
                    buffersLength() {
                        let offset = this.bb.__offset(this.bb_pos, 8);
                        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startRecordBatch(builder) {
                        builder.startObject(3);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Long length
                     */
                    static addLength(builder, length) {
                        builder.addFieldInt64(0, length, builder.createLong(0, 0));
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset nodesOffset
                     */
                    static addNodes(builder, nodesOffset) {
                        builder.addFieldOffset(1, nodesOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number numElems
                     */
                    static startNodesVector(builder, numElems) {
                        builder.startVector(16, numElems, 8);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset buffersOffset
                     */
                    static addBuffers(builder, buffersOffset) {
                        builder.addFieldOffset(2, buffersOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number numElems
                     */
                    static startBuffersVector(builder, numElems) {
                        builder.startVector(16, numElems, 8);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endRecordBatch(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createRecordBatch(builder, length, nodesOffset, buffersOffset) {
                        RecordBatch.startRecordBatch(builder);
                        RecordBatch.addLength(builder, length);
                        RecordBatch.addNodes(builder, nodesOffset);
                        RecordBatch.addBuffers(builder, buffersOffset);
                        return RecordBatch.endRecordBatch(builder);
                    }
                }
                flatbuf.RecordBatch = RecordBatch;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_org || (standalone_org = {}));
/**
 * For sending dictionary encoding information. Any Field can be
 * dictionary-encoded, but in this case none of its children may be
 * dictionary-encoded.
 * There is one vector / column per dictionary, but that vector / column
 * may be spread across multiple dictionary batches by using the isDelta
 * flag
 *
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class DictionaryBatch {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns DictionaryBatch
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param DictionaryBatch= obj
                     * @returns DictionaryBatch
                     */
                    static getRootAsDictionaryBatch(bb, obj) {
                        return (obj || new DictionaryBatch).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @returns flatbuffers.Long
                     */
                    id() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
                    }
                    /**
                     * @param org.apache.arrow.flatbuf.RecordBatch= obj
                     * @returns org.apache.arrow.flatbuf.RecordBatch|null
                     */
                    data(obj) {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? (obj || new org.apache.arrow.flatbuf.RecordBatch).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
                    }
                    /**
                     * If isDelta is true the values in the dictionary are to be appended to a
                     * dictionary with the indicated id
                     *
                     * @returns boolean
                     */
                    isDelta() {
                        let offset = this.bb.__offset(this.bb_pos, 8);
                        return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startDictionaryBatch(builder) {
                        builder.startObject(3);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Long id
                     */
                    static addId(builder, id) {
                        builder.addFieldInt64(0, id, builder.createLong(0, 0));
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset dataOffset
                     */
                    static addData(builder, dataOffset) {
                        builder.addFieldOffset(1, dataOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param boolean isDelta
                     */
                    static addIsDelta(builder, isDelta) {
                        builder.addFieldInt8(2, +isDelta, +false);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endDictionaryBatch(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    static createDictionaryBatch(builder, id, dataOffset, isDelta) {
                        DictionaryBatch.startDictionaryBatch(builder);
                        DictionaryBatch.addId(builder, id);
                        DictionaryBatch.addData(builder, dataOffset);
                        DictionaryBatch.addIsDelta(builder, isDelta);
                        return DictionaryBatch.endDictionaryBatch(builder);
                    }
                }
                flatbuf.DictionaryBatch = DictionaryBatch;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_org || (standalone_org = {}));
/**
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Message {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Message
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Message= obj
                     * @returns Message
                     */
                    static getRootAsMessage(bb, obj) {
                        return (obj || new Message).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @returns org.apache.arrow.flatbuf.MetadataVersion
                     */
                    version() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? /**  */ (this.bb.readInt16(this.bb_pos + offset)) : standalone_Schema_org.apache.arrow.flatbuf.MetadataVersion.V1;
                    }
                    /**
                     * @returns org.apache.arrow.flatbuf.MessageHeader
                     */
                    headerType() {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? /**  */ (this.bb.readUint8(this.bb_pos + offset)) : org.apache.arrow.flatbuf.MessageHeader.NONE;
                    }
                    /**
                     * @param flatbuffers.Table obj
                     * @returns ?flatbuffers.Table
                     */
                    header(obj) {
                        let offset = this.bb.__offset(this.bb_pos, 8);
                        return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
                    }
                    /**
                     * @returns flatbuffers.Long
                     */
                    bodyLength() {
                        let offset = this.bb.__offset(this.bb_pos, 10);
                        return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
                    }
                    /**
                     * @param number index
                     * @param org.apache.arrow.flatbuf.KeyValue= obj
                     * @returns org.apache.arrow.flatbuf.KeyValue
                     */
                    customMetadata(index, obj) {
                        let offset = this.bb.__offset(this.bb_pos, 12);
                        return offset ? (obj || new standalone_Schema_org.apache.arrow.flatbuf.KeyValue).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
                    }
                    /**
                     * @returns number
                     */
                    customMetadataLength() {
                        let offset = this.bb.__offset(this.bb_pos, 12);
                        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startMessage(builder) {
                        builder.startObject(5);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.MetadataVersion version
                     */
                    static addVersion(builder, version) {
                        builder.addFieldInt16(0, version, standalone_Schema_org.apache.arrow.flatbuf.MetadataVersion.V1);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.MessageHeader headerType
                     */
                    static addHeaderType(builder, headerType) {
                        builder.addFieldInt8(1, headerType, org.apache.arrow.flatbuf.MessageHeader.NONE);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset headerOffset
                     */
                    static addHeader(builder, headerOffset) {
                        builder.addFieldOffset(2, headerOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Long bodyLength
                     */
                    static addBodyLength(builder, bodyLength) {
                        builder.addFieldInt64(3, bodyLength, builder.createLong(0, 0));
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset customMetadataOffset
                     */
                    static addCustomMetadata(builder, customMetadataOffset) {
                        builder.addFieldOffset(4, customMetadataOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param Array.<flatbuffers.Offset> data
                     * @returns flatbuffers.Offset
                     */
                    static createCustomMetadataVector(builder, data) {
                        builder.startVector(4, data.length, 4);
                        for (let i = data.length - 1; i >= 0; i--) {
                            builder.addOffset(data[i]);
                        }
                        return builder.endVector();
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number numElems
                     */
                    static startCustomMetadataVector(builder, numElems) {
                        builder.startVector(4, numElems, 4);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endMessage(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset offset
                     */
                    static finishMessageBuffer(builder, offset) {
                        builder.finish(offset);
                    }
                    static createMessage(builder, version, headerType, headerOffset, bodyLength, customMetadataOffset) {
                        Message.startMessage(builder);
                        Message.addVersion(builder, version);
                        Message.addHeaderType(builder, headerType);
                        Message.addHeader(builder, headerOffset);
                        Message.addBodyLength(builder, bodyLength);
                        Message.addCustomMetadata(builder, customMetadataOffset);
                        return Message.endMessage(builder);
                    }
                }
                flatbuf.Message = Message;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_org || (standalone_org = {}));

//# sourceMappingURL=Message.mjs.map

;// ../../node_modules/apache-arrow/enum.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


var standalone_ArrowType = standalone_Schema_org.apache.arrow.flatbuf.Type;
var standalone_DateUnit = standalone_Schema_org.apache.arrow.flatbuf.DateUnit;
var standalone_enum_TimeUnit = standalone_Schema_org.apache.arrow.flatbuf.TimeUnit;
var standalone_Precision = standalone_Schema_org.apache.arrow.flatbuf.Precision;
var standalone_UnionMode = standalone_Schema_org.apache.arrow.flatbuf.UnionMode;
var standalone_IntervalUnit = standalone_Schema_org.apache.arrow.flatbuf.IntervalUnit;
var standalone_MessageHeader = standalone_org.apache.arrow.flatbuf.MessageHeader;
var standalone_MetadataVersion = standalone_Schema_org.apache.arrow.flatbuf.MetadataVersion;
/**
 * Main data type enumeration.
 *
 * Data types in this library are all *logical*. They can be expressed as
 * either a primitive physical type (bytes or bits of some fixed size), a
 * nested type consisting of other data types, or another data type (e.g. a
 * timestamp encoded as an int64).
 *
 * **Note**: Only enum values 0-17 (NONE through Map) are written to an Arrow
 * IPC payload.
 *
 * The rest of the values are specified here so TypeScript can narrow the type
 * signatures further beyond the base Arrow Types. The Arrow DataTypes include
 * metadata like `bitWidth` that impact the type signatures of the values we
 * accept and return.
 *
 * For example, the `Int8Vector` reads 1-byte numbers from an `Int8Array`, an
 * `Int32Vector` reads a 4-byte number from an `Int32Array`, and an `Int64Vector`
 * reads a pair of 4-byte lo, hi 32-bit integers as a zero-copy slice from the
 * underlying `Int32Array`.
 *
 * Library consumers benefit by knowing the narrowest type, since we can ensure
 * the types across all public methods are propagated, and never bail to `any`.
 * These values are _never_ used at runtime, and they will _never_ be written
 * to the flatbuffers metadata of serialized Arrow IPC payloads.
 */
var standalone_enum_Type;
(function (Type) {
    /** The default placeholder type */
    Type[Type["NONE"] = 0] = "NONE";
    /** A NULL type having no physical storage */
    Type[Type["Null"] = 1] = "Null";
    /** Signed or unsigned 8, 16, 32, or 64-bit little-endian integer */
    Type[Type["Int"] = 2] = "Int";
    /** 2, 4, or 8-byte floating point value */
    Type[Type["Float"] = 3] = "Float";
    /** Variable-length bytes (no guarantee of UTF8-ness) */
    Type[Type["Binary"] = 4] = "Binary";
    /** UTF8 variable-length string as List<Char> */
    Type[Type["Utf8"] = 5] = "Utf8";
    /** Boolean as 1 bit, LSB bit-packed ordering */
    Type[Type["Bool"] = 6] = "Bool";
    /** Precision-and-scale-based decimal type. Storage type depends on the parameters. */
    Type[Type["Decimal"] = 7] = "Decimal";
    /** int32_t days or int64_t milliseconds since the UNIX epoch */
    Type[Type["Date"] = 8] = "Date";
    /** Time as signed 32 or 64-bit integer, representing either seconds, milliseconds, microseconds, or nanoseconds since midnight since midnight */
    Type[Type["Time"] = 9] = "Time";
    /** Exact timestamp encoded with int64 since UNIX epoch (Default unit millisecond) */
    Type[Type["Timestamp"] = 10] = "Timestamp";
    /** YEAR_MONTH or DAY_TIME interval in SQL style */
    Type[Type["Interval"] = 11] = "Interval";
    /** A list of some logical data type */
    Type[Type["List"] = 12] = "List";
    /** Struct of logical types */
    Type[Type["Struct"] = 13] = "Struct";
    /** Union of logical types */
    Type[Type["Union"] = 14] = "Union";
    /** Fixed-size binary. Each value occupies the same number of bytes */
    Type[Type["FixedSizeBinary"] = 15] = "FixedSizeBinary";
    /** Fixed-size list. Each value occupies the same number of bytes */
    Type[Type["FixedSizeList"] = 16] = "FixedSizeList";
    /** Map of named logical types */
    Type[Type["Map"] = 17] = "Map";
    /** Dictionary aka Category type */
    Type[Type["Dictionary"] = -1] = "Dictionary";
    Type[Type["Int8"] = -2] = "Int8";
    Type[Type["Int16"] = -3] = "Int16";
    Type[Type["Int32"] = -4] = "Int32";
    Type[Type["Int64"] = -5] = "Int64";
    Type[Type["Uint8"] = -6] = "Uint8";
    Type[Type["Uint16"] = -7] = "Uint16";
    Type[Type["Uint32"] = -8] = "Uint32";
    Type[Type["Uint64"] = -9] = "Uint64";
    Type[Type["Float16"] = -10] = "Float16";
    Type[Type["Float32"] = -11] = "Float32";
    Type[Type["Float64"] = -12] = "Float64";
    Type[Type["DateDay"] = -13] = "DateDay";
    Type[Type["DateMillisecond"] = -14] = "DateMillisecond";
    Type[Type["TimestampSecond"] = -15] = "TimestampSecond";
    Type[Type["TimestampMillisecond"] = -16] = "TimestampMillisecond";
    Type[Type["TimestampMicrosecond"] = -17] = "TimestampMicrosecond";
    Type[Type["TimestampNanosecond"] = -18] = "TimestampNanosecond";
    Type[Type["TimeSecond"] = -19] = "TimeSecond";
    Type[Type["TimeMillisecond"] = -20] = "TimeMillisecond";
    Type[Type["TimeMicrosecond"] = -21] = "TimeMicrosecond";
    Type[Type["TimeNanosecond"] = -22] = "TimeNanosecond";
    Type[Type["DenseUnion"] = -23] = "DenseUnion";
    Type[Type["SparseUnion"] = -24] = "SparseUnion";
    Type[Type["IntervalDayTime"] = -25] = "IntervalDayTime";
    Type[Type["IntervalYearMonth"] = -26] = "IntervalYearMonth";
})(standalone_enum_Type || (standalone_enum_Type = {}));
var standalone_BufferType;
(function (BufferType) {
    /**
     * used in List type, Dense Union and variable length primitive types (String, Binary)
     */
    BufferType[BufferType["OFFSET"] = 0] = "OFFSET";
    /**
     * actual data, either wixed width primitive types in slots or variable width delimited by an OFFSET vector
     */
    BufferType[BufferType["DATA"] = 1] = "DATA";
    /**
     * Bit vector indicating if each value is null
     */
    BufferType[BufferType["VALIDITY"] = 2] = "VALIDITY";
    /**
     * Type vector used in Union type
     */
    BufferType[BufferType["TYPE"] = 3] = "TYPE";
})(standalone_BufferType || (standalone_BufferType = {}));

//# sourceMappingURL=enum.mjs.map

;// ../../node_modules/apache-arrow/util/bit.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
/** @ignore */
function standalone_getBool(_data, _index, byte, bit) {
    return (byte & 1 << bit) !== 0;
}
/** @ignore */
function standalone_getBit(_data, _index, byte, bit) {
    return (byte & 1 << bit) >> bit;
}
/** @ignore */
function standalone_setBool(bytes, index, value) {
    return value ?
        !!(bytes[index >> 3] |= (1 << (index % 8))) || true :
        !(bytes[index >> 3] &= ~(1 << (index % 8))) && false;
}
/** @ignore */
function standalone_truncateBitmap(offset, length, bitmap) {
    const alignedSize = (bitmap.byteLength + 7) & ~7;
    if (offset > 0 || bitmap.byteLength < alignedSize) {
        const bytes = new Uint8Array(alignedSize);
        // If the offset is a multiple of 8 bits, it's safe to slice the bitmap
        bytes.set(offset % 8 === 0 ? bitmap.subarray(offset >> 3) :
            // Otherwise iterate each bit from the offset and return a new one
            standalone_packBools(standalone_iterateBits(bitmap, offset, length, null, standalone_getBool)).subarray(0, alignedSize));
        return bytes;
    }
    return bitmap;
}
/** @ignore */
function standalone_packBools(values) {
    let xs = [];
    let i = 0, bit = 0, byte = 0;
    for (const value of values) {
        value && (byte |= 1 << bit);
        if (++bit === 8) {
            xs[i++] = byte;
            byte = bit = 0;
        }
    }
    if (i === 0 || bit > 0) {
        xs[i++] = byte;
    }
    let b = new Uint8Array((xs.length + 7) & ~7);
    b.set(xs);
    return b;
}
/** @ignore */
function* standalone_iterateBits(bytes, begin, length, context, get) {
    let bit = begin % 8;
    let byteIndex = begin >> 3;
    let index = 0, remaining = length;
    for (; remaining > 0; bit = 0) {
        let byte = bytes[byteIndex++];
        do {
            yield get(context, index++, byte, bit);
        } while (--remaining > 0 && ++bit < 8);
    }
}
/**
 * Compute the population count (the number of bits set to 1) for a range of bits in a Uint8Array.
 * @param vector The Uint8Array of bits for which to compute the population count.
 * @param lhs The range's left-hand side (or start) bit
 * @param rhs The range's right-hand side (or end) bit
 */
/** @ignore */
function standalone_popcnt_bit_range(data, lhs, rhs) {
    if (rhs - lhs <= 0) {
        return 0;
    }
    // If the bit range is less than one byte, sum the 1 bits in the bit range
    if (rhs - lhs < 8) {
        let sum = 0;
        for (const bit of standalone_iterateBits(data, lhs, rhs - lhs, data, standalone_getBit)) {
            sum += bit;
        }
        return sum;
    }
    // Get the next lowest multiple of 8 from the right hand side
    const rhsInside = rhs >> 3 << 3;
    // Get the next highest multiple of 8 from the left hand side
    const lhsInside = lhs + (lhs % 8 === 0 ? 0 : 8 - lhs % 8);
    return (
    // Get the popcnt of bits between the left hand side, and the next highest multiple of 8
    standalone_popcnt_bit_range(data, lhs, lhsInside) +
        // Get the popcnt of bits between the right hand side, and the next lowest multiple of 8
        standalone_popcnt_bit_range(data, rhsInside, rhs) +
        // Get the popcnt of all bits between the left and right hand sides' multiples of 8
        standalone_popcnt_array(data, lhsInside >> 3, (rhsInside - lhsInside) >> 3));
}
/** @ignore */
function standalone_popcnt_array(arr, byteOffset, byteLength) {
    let cnt = 0, pos = byteOffset | 0;
    const view = new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
    const len = byteLength === void 0 ? arr.byteLength : pos + byteLength;
    while (len - pos >= 4) {
        cnt += standalone_popcnt_uint32(view.getUint32(pos));
        pos += 4;
    }
    while (len - pos >= 2) {
        cnt += standalone_popcnt_uint32(view.getUint16(pos));
        pos += 2;
    }
    while (len - pos >= 1) {
        cnt += standalone_popcnt_uint32(view.getUint8(pos));
        pos += 1;
    }
    return cnt;
}
/** @ignore */
function standalone_popcnt_uint32(uint32) {
    let i = uint32 | 0;
    i = i - ((i >>> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
    return (((i + (i >>> 4)) & 0x0F0F0F0F) * 0x01010101) >>> 24;
}

//# sourceMappingURL=bit.mjs.map

;// ../../node_modules/apache-arrow/visitor.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




class standalone_Visitor {
    visitMany(nodes, ...args) {
        return nodes.map((node, i) => this.visit(node, ...args.map((x) => x[i])));
    }
    visit(...args) {
        return this.getVisitFn(args[0], false).apply(this, args);
    }
    getVisitFn(node, throwIfNotFound = true) {
        return standalone_getVisitFn(this, node, throwIfNotFound);
    }
    visitNull(_node, ..._args) { return null; }
    visitBool(_node, ..._args) { return null; }
    visitInt(_node, ..._args) { return null; }
    visitFloat(_node, ..._args) { return null; }
    visitUtf8(_node, ..._args) { return null; }
    visitBinary(_node, ..._args) { return null; }
    visitFixedSizeBinary(_node, ..._args) { return null; }
    visitDate(_node, ..._args) { return null; }
    visitTimestamp(_node, ..._args) { return null; }
    visitTime(_node, ..._args) { return null; }
    visitDecimal(_node, ..._args) { return null; }
    visitList(_node, ..._args) { return null; }
    visitStruct(_node, ..._args) { return null; }
    visitUnion(_node, ..._args) { return null; }
    visitDictionary(_node, ..._args) { return null; }
    visitInterval(_node, ..._args) { return null; }
    visitFixedSizeList(_node, ..._args) { return null; }
    visitMap(_node, ..._args) { return null; }
}
/** @ignore */
function standalone_getVisitFn(visitor, node, throwIfNotFound = true) {
    let fn = null;
    let dtype = standalone_enum_Type.NONE;
    // tslint:disable
    if (node instanceof standalone_Data) {
        dtype = standalone_inferDType(node.type);
    }
    else if (node instanceof standalone_AbstractVector) {
        dtype = standalone_inferDType(node.type);
    }
    else if (node instanceof standalone_DataType) {
        dtype = standalone_inferDType(node);
    }
    else if (typeof (dtype = node) !== 'number') {
        dtype = standalone_enum_Type[node];
    }
    switch (dtype) {
        case standalone_enum_Type.Null:
            fn = visitor.visitNull;
            break;
        case standalone_enum_Type.Bool:
            fn = visitor.visitBool;
            break;
        case standalone_enum_Type.Int:
            fn = visitor.visitInt;
            break;
        case standalone_enum_Type.Int8:
            fn = visitor.visitInt8 || visitor.visitInt;
            break;
        case standalone_enum_Type.Int16:
            fn = visitor.visitInt16 || visitor.visitInt;
            break;
        case standalone_enum_Type.Int32:
            fn = visitor.visitInt32 || visitor.visitInt;
            break;
        case standalone_enum_Type.Int64:
            fn = visitor.visitInt64 || visitor.visitInt;
            break;
        case standalone_enum_Type.Uint8:
            fn = visitor.visitUint8 || visitor.visitInt;
            break;
        case standalone_enum_Type.Uint16:
            fn = visitor.visitUint16 || visitor.visitInt;
            break;
        case standalone_enum_Type.Uint32:
            fn = visitor.visitUint32 || visitor.visitInt;
            break;
        case standalone_enum_Type.Uint64:
            fn = visitor.visitUint64 || visitor.visitInt;
            break;
        case standalone_enum_Type.Float:
            fn = visitor.visitFloat;
            break;
        case standalone_enum_Type.Float16:
            fn = visitor.visitFloat16 || visitor.visitFloat;
            break;
        case standalone_enum_Type.Float32:
            fn = visitor.visitFloat32 || visitor.visitFloat;
            break;
        case standalone_enum_Type.Float64:
            fn = visitor.visitFloat64 || visitor.visitFloat;
            break;
        case standalone_enum_Type.Utf8:
            fn = visitor.visitUtf8;
            break;
        case standalone_enum_Type.Binary:
            fn = visitor.visitBinary;
            break;
        case standalone_enum_Type.FixedSizeBinary:
            fn = visitor.visitFixedSizeBinary;
            break;
        case standalone_enum_Type.Date:
            fn = visitor.visitDate;
            break;
        case standalone_enum_Type.DateDay:
            fn = visitor.visitDateDay || visitor.visitDate;
            break;
        case standalone_enum_Type.DateMillisecond:
            fn = visitor.visitDateMillisecond || visitor.visitDate;
            break;
        case standalone_enum_Type.Timestamp:
            fn = visitor.visitTimestamp;
            break;
        case standalone_enum_Type.TimestampSecond:
            fn = visitor.visitTimestampSecond || visitor.visitTimestamp;
            break;
        case standalone_enum_Type.TimestampMillisecond:
            fn = visitor.visitTimestampMillisecond || visitor.visitTimestamp;
            break;
        case standalone_enum_Type.TimestampMicrosecond:
            fn = visitor.visitTimestampMicrosecond || visitor.visitTimestamp;
            break;
        case standalone_enum_Type.TimestampNanosecond:
            fn = visitor.visitTimestampNanosecond || visitor.visitTimestamp;
            break;
        case standalone_enum_Type.Time:
            fn = visitor.visitTime;
            break;
        case standalone_enum_Type.TimeSecond:
            fn = visitor.visitTimeSecond || visitor.visitTime;
            break;
        case standalone_enum_Type.TimeMillisecond:
            fn = visitor.visitTimeMillisecond || visitor.visitTime;
            break;
        case standalone_enum_Type.TimeMicrosecond:
            fn = visitor.visitTimeMicrosecond || visitor.visitTime;
            break;
        case standalone_enum_Type.TimeNanosecond:
            fn = visitor.visitTimeNanosecond || visitor.visitTime;
            break;
        case standalone_enum_Type.Decimal:
            fn = visitor.visitDecimal;
            break;
        case standalone_enum_Type.List:
            fn = visitor.visitList;
            break;
        case standalone_enum_Type.Struct:
            fn = visitor.visitStruct;
            break;
        case standalone_enum_Type.Union:
            fn = visitor.visitUnion;
            break;
        case standalone_enum_Type.DenseUnion:
            fn = visitor.visitDenseUnion || visitor.visitUnion;
            break;
        case standalone_enum_Type.SparseUnion:
            fn = visitor.visitSparseUnion || visitor.visitUnion;
            break;
        case standalone_enum_Type.Dictionary:
            fn = visitor.visitDictionary;
            break;
        case standalone_enum_Type.Interval:
            fn = visitor.visitInterval;
            break;
        case standalone_enum_Type.IntervalDayTime:
            fn = visitor.visitIntervalDayTime || visitor.visitInterval;
            break;
        case standalone_enum_Type.IntervalYearMonth:
            fn = visitor.visitIntervalYearMonth || visitor.visitInterval;
            break;
        case standalone_enum_Type.FixedSizeList:
            fn = visitor.visitFixedSizeList;
            break;
        case standalone_enum_Type.Map:
            fn = visitor.visitMap;
            break;
    }
    if (typeof fn === 'function')
        return fn;
    if (!throwIfNotFound)
        return () => null;
    throw new Error(`Unrecognized type '${standalone_enum_Type[dtype]}'`);
}
/** @ignore */
function standalone_inferDType(type) {
    switch (type.typeId) {
        case standalone_enum_Type.Null: return standalone_enum_Type.Null;
        case standalone_enum_Type.Int:
            const { bitWidth, isSigned } = type;
            switch (bitWidth) {
                case 8: return isSigned ? standalone_enum_Type.Int8 : standalone_enum_Type.Uint8;
                case 16: return isSigned ? standalone_enum_Type.Int16 : standalone_enum_Type.Uint16;
                case 32: return isSigned ? standalone_enum_Type.Int32 : standalone_enum_Type.Uint32;
                case 64: return isSigned ? standalone_enum_Type.Int64 : standalone_enum_Type.Uint64;
            }
            // @ts-ignore
            return standalone_enum_Type.Int;
        case standalone_enum_Type.Float:
            switch (type.precision) {
                case standalone_Precision.HALF: return standalone_enum_Type.Float16;
                case standalone_Precision.SINGLE: return standalone_enum_Type.Float32;
                case standalone_Precision.DOUBLE: return standalone_enum_Type.Float64;
            }
            // @ts-ignore
            return standalone_enum_Type.Float;
        case standalone_enum_Type.Binary: return standalone_enum_Type.Binary;
        case standalone_enum_Type.Utf8: return standalone_enum_Type.Utf8;
        case standalone_enum_Type.Bool: return standalone_enum_Type.Bool;
        case standalone_enum_Type.Decimal: return standalone_enum_Type.Decimal;
        case standalone_enum_Type.Time:
            switch (type.unit) {
                case standalone_enum_TimeUnit.SECOND: return standalone_enum_Type.TimeSecond;
                case standalone_enum_TimeUnit.MILLISECOND: return standalone_enum_Type.TimeMillisecond;
                case standalone_enum_TimeUnit.MICROSECOND: return standalone_enum_Type.TimeMicrosecond;
                case standalone_enum_TimeUnit.NANOSECOND: return standalone_enum_Type.TimeNanosecond;
            }
            // @ts-ignore
            return standalone_enum_Type.Time;
        case standalone_enum_Type.Timestamp:
            switch (type.unit) {
                case standalone_enum_TimeUnit.SECOND: return standalone_enum_Type.TimestampSecond;
                case standalone_enum_TimeUnit.MILLISECOND: return standalone_enum_Type.TimestampMillisecond;
                case standalone_enum_TimeUnit.MICROSECOND: return standalone_enum_Type.TimestampMicrosecond;
                case standalone_enum_TimeUnit.NANOSECOND: return standalone_enum_Type.TimestampNanosecond;
            }
            // @ts-ignore
            return standalone_enum_Type.Timestamp;
        case standalone_enum_Type.Date:
            switch (type.unit) {
                case standalone_DateUnit.DAY: return standalone_enum_Type.DateDay;
                case standalone_DateUnit.MILLISECOND: return standalone_enum_Type.DateMillisecond;
            }
            // @ts-ignore
            return standalone_enum_Type.Date;
        case standalone_enum_Type.Interval:
            switch (type.unit) {
                case standalone_IntervalUnit.DAY_TIME: return standalone_enum_Type.IntervalDayTime;
                case standalone_IntervalUnit.YEAR_MONTH: return standalone_enum_Type.IntervalYearMonth;
            }
            // @ts-ignore
            return standalone_enum_Type.Interval;
        case standalone_enum_Type.Map: return standalone_enum_Type.Map;
        case standalone_enum_Type.List: return standalone_enum_Type.List;
        case standalone_enum_Type.Struct: return standalone_enum_Type.Struct;
        case standalone_enum_Type.Union:
            switch (type.mode) {
                case standalone_UnionMode.Dense: return standalone_enum_Type.DenseUnion;
                case standalone_UnionMode.Sparse: return standalone_enum_Type.SparseUnion;
            }
            // @ts-ignore
            return standalone_enum_Type.Union;
        case standalone_enum_Type.FixedSizeBinary: return standalone_enum_Type.FixedSizeBinary;
        case standalone_enum_Type.FixedSizeList: return standalone_enum_Type.FixedSizeList;
        case standalone_enum_Type.Dictionary: return standalone_enum_Type.Dictionary;
    }
    throw new Error(`Unrecognized type '${standalone_enum_Type[type.typeId]}'`);
}
// Add these here so they're picked up by the externs creator
// in the build, and closure-compiler doesn't minify them away
standalone_Visitor.prototype.visitInt8 = null;
standalone_Visitor.prototype.visitInt16 = null;
standalone_Visitor.prototype.visitInt32 = null;
standalone_Visitor.prototype.visitInt64 = null;
standalone_Visitor.prototype.visitUint8 = null;
standalone_Visitor.prototype.visitUint16 = null;
standalone_Visitor.prototype.visitUint32 = null;
standalone_Visitor.prototype.visitUint64 = null;
standalone_Visitor.prototype.visitFloat16 = null;
standalone_Visitor.prototype.visitFloat32 = null;
standalone_Visitor.prototype.visitFloat64 = null;
standalone_Visitor.prototype.visitDateDay = null;
standalone_Visitor.prototype.visitDateMillisecond = null;
standalone_Visitor.prototype.visitTimestampSecond = null;
standalone_Visitor.prototype.visitTimestampMillisecond = null;
standalone_Visitor.prototype.visitTimestampMicrosecond = null;
standalone_Visitor.prototype.visitTimestampNanosecond = null;
standalone_Visitor.prototype.visitTimeSecond = null;
standalone_Visitor.prototype.visitTimeMillisecond = null;
standalone_Visitor.prototype.visitTimeMicrosecond = null;
standalone_Visitor.prototype.visitTimeNanosecond = null;
standalone_Visitor.prototype.visitDenseUnion = null;
standalone_Visitor.prototype.visitSparseUnion = null;
standalone_Visitor.prototype.visitIntervalDayTime = null;
standalone_Visitor.prototype.visitIntervalYearMonth = null;

//# sourceMappingURL=visitor.mjs.map

;// ../../node_modules/apache-arrow/visitor/typecomparator.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_TypeComparator extends standalone_Visitor {
    compareSchemas(schema, other) {
        return (schema === other) || (other instanceof schema.constructor &&
            standalone_typecomparator_instance.compareFields(schema.fields, other.fields));
    }
    compareFields(fields, others) {
        return (fields === others) || (Array.isArray(fields) &&
            Array.isArray(others) &&
            fields.length === others.length &&
            fields.every((f, i) => standalone_typecomparator_instance.compareField(f, others[i])));
    }
    compareField(field, other) {
        return (field === other) || (other instanceof field.constructor &&
            field.name === other.name &&
            field.nullable === other.nullable &&
            standalone_typecomparator_instance.visit(field.type, other.type));
    }
}
function standalone_compareConstructor(type, other) {
    return other instanceof type.constructor;
}
function standalone_compareAny(type, other) {
    return (type === other) || standalone_compareConstructor(type, other);
}
function standalone_compareInt(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.bitWidth === other.bitWidth &&
        type.isSigned === other.isSigned);
}
function standalone_compareFloat(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.precision === other.precision);
}
function standalone_compareFixedSizeBinary(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.byteWidth === other.byteWidth);
}
function standalone_compareDate(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.unit === other.unit);
}
function standalone_compareTimestamp(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.unit === other.unit &&
        type.timezone === other.timezone);
}
function standalone_compareTime(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.unit === other.unit &&
        type.bitWidth === other.bitWidth);
}
function standalone_compareList(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.children.length === other.children.length &&
        standalone_typecomparator_instance.compareFields(type.children, other.children));
}
function standalone_compareStruct(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.children.length === other.children.length &&
        standalone_typecomparator_instance.compareFields(type.children, other.children));
}
function standalone_compareUnion(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.mode === other.mode &&
        type.typeIds.every((x, i) => x === other.typeIds[i]) &&
        standalone_typecomparator_instance.compareFields(type.children, other.children));
}
function standalone_compareDictionary(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.id === other.id &&
        type.isOrdered === other.isOrdered &&
        standalone_typecomparator_instance.visit(type.indices, other.indices) &&
        standalone_typecomparator_instance.visit(type.dictionary, other.dictionary));
}
function standalone_compareInterval(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.unit === other.unit);
}
function standalone_compareFixedSizeList(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.listSize === other.listSize &&
        type.children.length === other.children.length &&
        standalone_typecomparator_instance.compareFields(type.children, other.children));
}
function standalone_compareMap(type, other) {
    return (type === other) || (standalone_compareConstructor(type, other) &&
        type.keysSorted === other.keysSorted &&
        type.children.length === other.children.length &&
        standalone_typecomparator_instance.compareFields(type.children, other.children));
}
standalone_TypeComparator.prototype.visitNull = standalone_compareAny;
standalone_TypeComparator.prototype.visitBool = standalone_compareAny;
standalone_TypeComparator.prototype.visitInt = standalone_compareInt;
standalone_TypeComparator.prototype.visitInt8 = standalone_compareInt;
standalone_TypeComparator.prototype.visitInt16 = standalone_compareInt;
standalone_TypeComparator.prototype.visitInt32 = standalone_compareInt;
standalone_TypeComparator.prototype.visitInt64 = standalone_compareInt;
standalone_TypeComparator.prototype.visitUint8 = standalone_compareInt;
standalone_TypeComparator.prototype.visitUint16 = standalone_compareInt;
standalone_TypeComparator.prototype.visitUint32 = standalone_compareInt;
standalone_TypeComparator.prototype.visitUint64 = standalone_compareInt;
standalone_TypeComparator.prototype.visitFloat = standalone_compareFloat;
standalone_TypeComparator.prototype.visitFloat16 = standalone_compareFloat;
standalone_TypeComparator.prototype.visitFloat32 = standalone_compareFloat;
standalone_TypeComparator.prototype.visitFloat64 = standalone_compareFloat;
standalone_TypeComparator.prototype.visitUtf8 = standalone_compareAny;
standalone_TypeComparator.prototype.visitBinary = standalone_compareAny;
standalone_TypeComparator.prototype.visitFixedSizeBinary = standalone_compareFixedSizeBinary;
standalone_TypeComparator.prototype.visitDate = standalone_compareDate;
standalone_TypeComparator.prototype.visitDateDay = standalone_compareDate;
standalone_TypeComparator.prototype.visitDateMillisecond = standalone_compareDate;
standalone_TypeComparator.prototype.visitTimestamp = standalone_compareTimestamp;
standalone_TypeComparator.prototype.visitTimestampSecond = standalone_compareTimestamp;
standalone_TypeComparator.prototype.visitTimestampMillisecond = standalone_compareTimestamp;
standalone_TypeComparator.prototype.visitTimestampMicrosecond = standalone_compareTimestamp;
standalone_TypeComparator.prototype.visitTimestampNanosecond = standalone_compareTimestamp;
standalone_TypeComparator.prototype.visitTime = standalone_compareTime;
standalone_TypeComparator.prototype.visitTimeSecond = standalone_compareTime;
standalone_TypeComparator.prototype.visitTimeMillisecond = standalone_compareTime;
standalone_TypeComparator.prototype.visitTimeMicrosecond = standalone_compareTime;
standalone_TypeComparator.prototype.visitTimeNanosecond = standalone_compareTime;
standalone_TypeComparator.prototype.visitDecimal = standalone_compareAny;
standalone_TypeComparator.prototype.visitList = standalone_compareList;
standalone_TypeComparator.prototype.visitStruct = standalone_compareStruct;
standalone_TypeComparator.prototype.visitUnion = standalone_compareUnion;
standalone_TypeComparator.prototype.visitDenseUnion = standalone_compareUnion;
standalone_TypeComparator.prototype.visitSparseUnion = standalone_compareUnion;
standalone_TypeComparator.prototype.visitDictionary = standalone_compareDictionary;
standalone_TypeComparator.prototype.visitInterval = standalone_compareInterval;
standalone_TypeComparator.prototype.visitIntervalDayTime = standalone_compareInterval;
standalone_TypeComparator.prototype.visitIntervalYearMonth = standalone_compareInterval;
standalone_TypeComparator.prototype.visitFixedSizeList = standalone_compareFixedSizeList;
standalone_TypeComparator.prototype.visitMap = standalone_compareMap;
/** @ignore */
const standalone_typecomparator_instance = new standalone_TypeComparator();

//# sourceMappingURL=typecomparator.mjs.map

;// ../../node_modules/apache-arrow/type.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/**
 * An abstract base class for classes that encapsulate metadata about each of
 * the logical types that Arrow can represent.
 */
class standalone_DataType {
    /** @nocollapse */ static isNull(x) { return x && x.typeId === standalone_enum_Type.Null; }
    /** @nocollapse */ static isInt(x) { return x && x.typeId === standalone_enum_Type.Int; }
    /** @nocollapse */ static isFloat(x) { return x && x.typeId === standalone_enum_Type.Float; }
    /** @nocollapse */ static isBinary(x) { return x && x.typeId === standalone_enum_Type.Binary; }
    /** @nocollapse */ static isUtf8(x) { return x && x.typeId === standalone_enum_Type.Utf8; }
    /** @nocollapse */ static isBool(x) { return x && x.typeId === standalone_enum_Type.Bool; }
    /** @nocollapse */ static isDecimal(x) { return x && x.typeId === standalone_enum_Type.Decimal; }
    /** @nocollapse */ static isDate(x) { return x && x.typeId === standalone_enum_Type.Date; }
    /** @nocollapse */ static isTime(x) { return x && x.typeId === standalone_enum_Type.Time; }
    /** @nocollapse */ static isTimestamp(x) { return x && x.typeId === standalone_enum_Type.Timestamp; }
    /** @nocollapse */ static isInterval(x) { return x && x.typeId === standalone_enum_Type.Interval; }
    /** @nocollapse */ static isList(x) { return x && x.typeId === standalone_enum_Type.List; }
    /** @nocollapse */ static isStruct(x) { return x && x.typeId === standalone_enum_Type.Struct; }
    /** @nocollapse */ static isUnion(x) { return x && x.typeId === standalone_enum_Type.Union; }
    /** @nocollapse */ static isFixedSizeBinary(x) { return x && x.typeId === standalone_enum_Type.FixedSizeBinary; }
    /** @nocollapse */ static isFixedSizeList(x) { return x && x.typeId === standalone_enum_Type.FixedSizeList; }
    /** @nocollapse */ static isMap(x) { return x && x.typeId === standalone_enum_Type.Map; }
    /** @nocollapse */ static isDictionary(x) { return x && x.typeId === standalone_enum_Type.Dictionary; }
    get typeId() { return standalone_enum_Type.NONE; }
    compareTo(other) {
        return standalone_typecomparator_instance.visit(this, other);
    }
}
standalone_DataType[Symbol.toStringTag] = ((proto) => {
    proto.children = null;
    proto.ArrayType = Array;
    return proto[Symbol.toStringTag] = 'DataType';
})(standalone_DataType.prototype);
/** @ignore */
class standalone_Null extends standalone_DataType {
    toString() { return `Null`; }
    get typeId() { return standalone_enum_Type.Null; }
}
standalone_Null[Symbol.toStringTag] = ((proto) => {
    return proto[Symbol.toStringTag] = 'Null';
})(standalone_Null.prototype);
/** @ignore */
class standalone_Int_ extends standalone_DataType {
    constructor(isSigned, bitWidth) {
        super();
        this.isSigned = isSigned;
        this.bitWidth = bitWidth;
    }
    get typeId() { return standalone_enum_Type.Int; }
    get ArrayType() {
        switch (this.bitWidth) {
            case 8: return this.isSigned ? Int8Array : Uint8Array;
            case 16: return this.isSigned ? Int16Array : Uint16Array;
            case 32: return this.isSigned ? Int32Array : Uint32Array;
            case 64: return this.isSigned ? Int32Array : Uint32Array;
        }
        throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);
    }
    toString() { return `${this.isSigned ? `I` : `Ui`}nt${this.bitWidth}`; }
}
standalone_Int_[Symbol.toStringTag] = ((proto) => {
    proto.isSigned = null;
    proto.bitWidth = null;
    return proto[Symbol.toStringTag] = 'Int';
})(standalone_Int_.prototype);

/** @ignore */
class standalone_Int8 extends standalone_Int_ {
    constructor() { super(true, 8); }
}
/** @ignore */
class standalone_Int16 extends standalone_Int_ {
    constructor() { super(true, 16); }
}
/** @ignore */
class standalone_Int32 extends standalone_Int_ {
    constructor() { super(true, 32); }
}
/** @ignore */
class standalone_Int64 extends standalone_Int_ {
    constructor() { super(true, 64); }
}
/** @ignore */
class standalone_Uint8 extends standalone_Int_ {
    constructor() { super(false, 8); }
}
/** @ignore */
class standalone_Uint16 extends standalone_Int_ {
    constructor() { super(false, 16); }
}
/** @ignore */
class standalone_Uint32 extends standalone_Int_ {
    constructor() { super(false, 32); }
}
/** @ignore */
class standalone_Uint64 extends standalone_Int_ {
    constructor() { super(false, 64); }
}
Object.defineProperty(standalone_Int8.prototype, 'ArrayType', { value: Int8Array });
Object.defineProperty(standalone_Int16.prototype, 'ArrayType', { value: Int16Array });
Object.defineProperty(standalone_Int32.prototype, 'ArrayType', { value: Int32Array });
Object.defineProperty(standalone_Int64.prototype, 'ArrayType', { value: Int32Array });
Object.defineProperty(standalone_Uint8.prototype, 'ArrayType', { value: Uint8Array });
Object.defineProperty(standalone_Uint16.prototype, 'ArrayType', { value: Uint16Array });
Object.defineProperty(standalone_Uint32.prototype, 'ArrayType', { value: Uint32Array });
Object.defineProperty(standalone_Uint64.prototype, 'ArrayType', { value: Uint32Array });
/** @ignore */
class standalone_Float extends standalone_DataType {
    constructor(precision) {
        super();
        this.precision = precision;
    }
    get typeId() { return standalone_enum_Type.Float; }
    get ArrayType() {
        switch (this.precision) {
            case standalone_Precision.HALF: return Uint16Array;
            case standalone_Precision.SINGLE: return Float32Array;
            case standalone_Precision.DOUBLE: return Float64Array;
        }
        // @ts-ignore
        throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);
    }
    toString() { return `Float${(this.precision << 5) || 16}`; }
}
standalone_Float[Symbol.toStringTag] = ((proto) => {
    proto.precision = null;
    return proto[Symbol.toStringTag] = 'Float';
})(standalone_Float.prototype);
/** @ignore */
class standalone_Float16 extends standalone_Float {
    constructor() { super(standalone_Precision.HALF); }
}
/** @ignore */
class standalone_Float32 extends standalone_Float {
    constructor() { super(standalone_Precision.SINGLE); }
}
/** @ignore */
class standalone_Float64 extends standalone_Float {
    constructor() { super(standalone_Precision.DOUBLE); }
}
Object.defineProperty(standalone_Float16.prototype, 'ArrayType', { value: Uint16Array });
Object.defineProperty(standalone_Float32.prototype, 'ArrayType', { value: Float32Array });
Object.defineProperty(standalone_Float64.prototype, 'ArrayType', { value: Float64Array });
/** @ignore */
class standalone_Binary extends standalone_DataType {
    constructor() {
        super();
    }
    get typeId() { return standalone_enum_Type.Binary; }
    toString() { return `Binary`; }
}
standalone_Binary[Symbol.toStringTag] = ((proto) => {
    proto.ArrayType = Uint8Array;
    return proto[Symbol.toStringTag] = 'Binary';
})(standalone_Binary.prototype);
/** @ignore */
class standalone_Utf8 extends standalone_DataType {
    constructor() {
        super();
    }
    get typeId() { return standalone_enum_Type.Utf8; }
    toString() { return `Utf8`; }
}
standalone_Utf8[Symbol.toStringTag] = ((proto) => {
    proto.ArrayType = Uint8Array;
    return proto[Symbol.toStringTag] = 'Utf8';
})(standalone_Utf8.prototype);
/** @ignore */
class standalone_Bool extends standalone_DataType {
    constructor() {
        super();
    }
    get typeId() { return standalone_enum_Type.Bool; }
    toString() { return `Bool`; }
}
standalone_Bool[Symbol.toStringTag] = ((proto) => {
    proto.ArrayType = Uint8Array;
    return proto[Symbol.toStringTag] = 'Bool';
})(standalone_Bool.prototype);
/** @ignore */
class standalone_Decimal extends standalone_DataType {
    constructor(scale, precision) {
        super();
        this.scale = scale;
        this.precision = precision;
    }
    get typeId() { return standalone_enum_Type.Decimal; }
    toString() { return `Decimal[${this.precision}e${this.scale > 0 ? `+` : ``}${this.scale}]`; }
}
standalone_Decimal[Symbol.toStringTag] = ((proto) => {
    proto.scale = null;
    proto.precision = null;
    proto.ArrayType = Uint32Array;
    return proto[Symbol.toStringTag] = 'Decimal';
})(standalone_Decimal.prototype);
/** @ignore */
class standalone_Date_ extends standalone_DataType {
    constructor(unit) {
        super();
        this.unit = unit;
    }
    get typeId() { return standalone_enum_Type.Date; }
    toString() { return `Date${(this.unit + 1) * 32}<${standalone_DateUnit[this.unit]}>`; }
}
standalone_Date_[Symbol.toStringTag] = ((proto) => {
    proto.unit = null;
    proto.ArrayType = Int32Array;
    return proto[Symbol.toStringTag] = 'Date';
})(standalone_Date_.prototype);
/** @ignore */
class standalone_DateDay extends standalone_Date_ {
    constructor() { super(standalone_DateUnit.DAY); }
}
/** @ignore */
class standalone_DateMillisecond extends standalone_Date_ {
    constructor() { super(standalone_DateUnit.MILLISECOND); }
}
/** @ignore */
class standalone_Time_ extends standalone_DataType {
    constructor(unit, bitWidth) {
        super();
        this.unit = unit;
        this.bitWidth = bitWidth;
    }
    get typeId() { return standalone_enum_Type.Time; }
    toString() { return `Time${this.bitWidth}<${standalone_enum_TimeUnit[this.unit]}>`; }
}
standalone_Time_[Symbol.toStringTag] = ((proto) => {
    proto.unit = null;
    proto.bitWidth = null;
    proto.ArrayType = Int32Array;
    return proto[Symbol.toStringTag] = 'Time';
})(standalone_Time_.prototype);

/** @ignore */
class standalone_TimeSecond extends standalone_Time_ {
    constructor() { super(standalone_enum_TimeUnit.SECOND, 32); }
}
/** @ignore */
class standalone_TimeMillisecond extends standalone_Time_ {
    constructor() { super(standalone_enum_TimeUnit.MILLISECOND, 32); }
}
/** @ignore */
class standalone_TimeMicrosecond extends standalone_Time_ {
    constructor() { super(standalone_enum_TimeUnit.MICROSECOND, 64); }
}
/** @ignore */
class standalone_TimeNanosecond extends standalone_Time_ {
    constructor() { super(standalone_enum_TimeUnit.NANOSECOND, 64); }
}
/** @ignore */
class standalone_Timestamp_ extends standalone_DataType {
    constructor(unit, timezone) {
        super();
        this.unit = unit;
        this.timezone = timezone;
    }
    get typeId() { return standalone_enum_Type.Timestamp; }
    toString() { return `Timestamp<${standalone_enum_TimeUnit[this.unit]}${this.timezone ? `, ${this.timezone}` : ``}>`; }
}
standalone_Timestamp_[Symbol.toStringTag] = ((proto) => {
    proto.unit = null;
    proto.timezone = null;
    proto.ArrayType = Int32Array;
    return proto[Symbol.toStringTag] = 'Timestamp';
})(standalone_Timestamp_.prototype);

/** @ignore */
class standalone_TimestampSecond extends standalone_Timestamp_ {
    constructor(timezone) { super(standalone_enum_TimeUnit.SECOND, timezone); }
}
/** @ignore */
class standalone_TimestampMillisecond extends standalone_Timestamp_ {
    constructor(timezone) { super(standalone_enum_TimeUnit.MILLISECOND, timezone); }
}
/** @ignore */
class standalone_TimestampMicrosecond extends standalone_Timestamp_ {
    constructor(timezone) { super(standalone_enum_TimeUnit.MICROSECOND, timezone); }
}
/** @ignore */
class standalone_TimestampNanosecond extends standalone_Timestamp_ {
    constructor(timezone) { super(standalone_enum_TimeUnit.NANOSECOND, timezone); }
}
/** @ignore */
class standalone_Interval_ extends standalone_DataType {
    constructor(unit) {
        super();
        this.unit = unit;
    }
    get typeId() { return standalone_enum_Type.Interval; }
    toString() { return `Interval<${standalone_IntervalUnit[this.unit]}>`; }
}
standalone_Interval_[Symbol.toStringTag] = ((proto) => {
    proto.unit = null;
    proto.ArrayType = Int32Array;
    return proto[Symbol.toStringTag] = 'Interval';
})(standalone_Interval_.prototype);

/** @ignore */
class standalone_IntervalDayTime extends standalone_Interval_ {
    constructor() { super(standalone_IntervalUnit.DAY_TIME); }
}
/** @ignore */
class standalone_IntervalYearMonth extends standalone_Interval_ {
    constructor() { super(standalone_IntervalUnit.YEAR_MONTH); }
}
/** @ignore */
class standalone_List extends standalone_DataType {
    constructor(child) {
        super();
        this.children = [child];
    }
    get typeId() { return standalone_enum_Type.List; }
    toString() { return `List<${this.valueType}>`; }
    get valueType() { return this.children[0].type; }
    get valueField() { return this.children[0]; }
    get ArrayType() { return this.valueType.ArrayType; }
}
standalone_List[Symbol.toStringTag] = ((proto) => {
    proto.children = null;
    return proto[Symbol.toStringTag] = 'List';
})(standalone_List.prototype);
/** @ignore */
class standalone_Struct extends standalone_DataType {
    constructor(children) {
        super();
        this.children = children;
    }
    get typeId() { return standalone_enum_Type.Struct; }
    toString() { return `Struct<{${this.children.map((f) => `${f.name}:${f.type}`).join(`, `)}}>`; }
}
standalone_Struct[Symbol.toStringTag] = ((proto) => {
    proto.children = null;
    return proto[Symbol.toStringTag] = 'Struct';
})(standalone_Struct.prototype);
/** @ignore */
class standalone_Union_ extends standalone_DataType {
    constructor(mode, typeIds, children) {
        super();
        this.mode = mode;
        this.children = children;
        this.typeIds = typeIds = Int32Array.from(typeIds);
        this.typeIdToChildIndex = typeIds.reduce((typeIdToChildIndex, typeId, idx) => {
            return (typeIdToChildIndex[typeId] = idx) && typeIdToChildIndex || typeIdToChildIndex;
        }, Object.create(null));
    }
    get typeId() { return standalone_enum_Type.Union; }
    toString() {
        return `${this[Symbol.toStringTag]}<${this.children.map((x) => `${x.type}`).join(` | `)}>`;
    }
}
standalone_Union_[Symbol.toStringTag] = ((proto) => {
    proto.mode = null;
    proto.typeIds = null;
    proto.children = null;
    proto.typeIdToChildIndex = null;
    proto.ArrayType = Int8Array;
    return proto[Symbol.toStringTag] = 'Union';
})(standalone_Union_.prototype);

/** @ignore */
class standalone_DenseUnion extends standalone_Union_ {
    constructor(typeIds, children) {
        super(standalone_UnionMode.Dense, typeIds, children);
    }
}
/** @ignore */
class standalone_SparseUnion extends standalone_Union_ {
    constructor(typeIds, children) {
        super(standalone_UnionMode.Sparse, typeIds, children);
    }
}
/** @ignore */
class standalone_FixedSizeBinary extends standalone_DataType {
    constructor(byteWidth) {
        super();
        this.byteWidth = byteWidth;
    }
    get typeId() { return standalone_enum_Type.FixedSizeBinary; }
    toString() { return `FixedSizeBinary[${this.byteWidth}]`; }
}
standalone_FixedSizeBinary[Symbol.toStringTag] = ((proto) => {
    proto.byteWidth = null;
    proto.ArrayType = Uint8Array;
    return proto[Symbol.toStringTag] = 'FixedSizeBinary';
})(standalone_FixedSizeBinary.prototype);
/** @ignore */
class standalone_FixedSizeList extends standalone_DataType {
    constructor(listSize, child) {
        super();
        this.listSize = listSize;
        this.children = [child];
    }
    get typeId() { return standalone_enum_Type.FixedSizeList; }
    get valueType() { return this.children[0].type; }
    get valueField() { return this.children[0]; }
    get ArrayType() { return this.valueType.ArrayType; }
    toString() { return `FixedSizeList[${this.listSize}]<${this.valueType}>`; }
}
standalone_FixedSizeList[Symbol.toStringTag] = ((proto) => {
    proto.children = null;
    proto.listSize = null;
    return proto[Symbol.toStringTag] = 'FixedSizeList';
})(standalone_FixedSizeList.prototype);
/** @ignore */
class standalone_Map_ extends standalone_DataType {
    constructor(child, keysSorted = false) {
        super();
        this.children = [child];
        this.keysSorted = keysSorted;
    }
    get typeId() { return standalone_enum_Type.Map; }
    get keyType() { return this.children[0].type.children[0].type; }
    get valueType() { return this.children[0].type.children[1].type; }
    toString() { return `Map<{${this.children[0].type.children.map((f) => `${f.name}:${f.type}`).join(`, `)}}>`; }
}
standalone_Map_[Symbol.toStringTag] = ((proto) => {
    proto.children = null;
    proto.keysSorted = null;
    return proto[Symbol.toStringTag] = 'Map_';
})(standalone_Map_.prototype);
/** @ignore */
const standalone_getId = ((atomicDictionaryId) => () => ++atomicDictionaryId)(-1);
/** @ignore */
class standalone_type_Dictionary extends standalone_DataType {
    constructor(dictionary, indices, id, isOrdered) {
        super();
        this.indices = indices;
        this.dictionary = dictionary;
        this.isOrdered = isOrdered || false;
        this.id = id == null ? standalone_getId() : typeof id === 'number' ? id : id.low;
    }
    get typeId() { return standalone_enum_Type.Dictionary; }
    get children() { return this.dictionary.children; }
    get valueType() { return this.dictionary; }
    get ArrayType() { return this.dictionary.ArrayType; }
    toString() { return `Dictionary<${this.indices}, ${this.dictionary}>`; }
}
standalone_type_Dictionary[Symbol.toStringTag] = ((proto) => {
    proto.id = null;
    proto.indices = null;
    proto.isOrdered = null;
    proto.dictionary = null;
    return proto[Symbol.toStringTag] = 'Dictionary';
})(standalone_type_Dictionary.prototype);
/** @ignore */
function standalone_strideForType(type) {
    let t = type;
    switch (type.typeId) {
        case standalone_enum_Type.Decimal: return 4;
        case standalone_enum_Type.Timestamp: return 2;
        case standalone_enum_Type.Date: return 1 + t.unit;
        case standalone_enum_Type.Interval: return 1 + t.unit;
        case standalone_enum_Type.Int: return 1 + +(t.bitWidth > 32);
        case standalone_enum_Type.Time: return 1 + +(t.bitWidth > 32);
        case standalone_enum_Type.FixedSizeList: return t.listSize;
        case standalone_enum_Type.FixedSizeBinary: return t.byteWidth;
        default: return 1;
    }
}

//# sourceMappingURL=type.mjs.map

;// ../../node_modules/apache-arrow/data.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.





/** @ignore */ const standalone_kUnknownNullCount = -1;
/** @ignore */
class standalone_Data {
    constructor(type, offset, length, nullCount, buffers, childData, dictionary) {
        this.type = type;
        this.dictionary = dictionary;
        this.offset = Math.floor(Math.max(offset || 0, 0));
        this.length = Math.floor(Math.max(length || 0, 0));
        this._nullCount = Math.floor(Math.max(nullCount || 0, -1));
        this.childData = (childData || []).map((x) => x instanceof standalone_Data ? x : x.data);
        let buffer;
        if (buffers instanceof standalone_Data) {
            this.stride = buffers.stride;
            this.values = buffers.values;
            this.typeIds = buffers.typeIds;
            this.nullBitmap = buffers.nullBitmap;
            this.valueOffsets = buffers.valueOffsets;
        }
        else {
            this.stride = standalone_strideForType(type);
            if (buffers) {
                (buffer = buffers[0]) && (this.valueOffsets = buffer);
                (buffer = buffers[1]) && (this.values = buffer);
                (buffer = buffers[2]) && (this.nullBitmap = buffer);
                (buffer = buffers[3]) && (this.typeIds = buffer);
            }
        }
    }
    get typeId() { return this.type.typeId; }
    get ArrayType() { return this.type.ArrayType; }
    get buffers() {
        return [this.valueOffsets, this.values, this.nullBitmap, this.typeIds];
    }
    get byteLength() {
        let byteLength = 0;
        let { valueOffsets, values, nullBitmap, typeIds } = this;
        valueOffsets && (byteLength += valueOffsets.byteLength);
        values && (byteLength += values.byteLength);
        nullBitmap && (byteLength += nullBitmap.byteLength);
        typeIds && (byteLength += typeIds.byteLength);
        return this.childData.reduce((byteLength, child) => byteLength + child.byteLength, byteLength);
    }
    get nullCount() {
        let nullCount = this._nullCount;
        let nullBitmap;
        if (nullCount <= standalone_kUnknownNullCount && (nullBitmap = this.nullBitmap)) {
            this._nullCount = nullCount = this.length - standalone_popcnt_bit_range(nullBitmap, this.offset, this.offset + this.length);
        }
        return nullCount;
    }
    clone(type, offset = this.offset, length = this.length, nullCount = this._nullCount, buffers = this, childData = this.childData) {
        return new standalone_Data(type, offset, length, nullCount, buffers, childData, this.dictionary);
    }
    slice(offset, length) {
        const { stride, typeId, childData } = this;
        // +true === 1, +false === 0, so this means
        // we keep nullCount at 0 if it's already 0,
        // otherwise set to the invalidated flag -1
        const nullCount = +(this._nullCount === 0) - 1;
        const childStride = typeId === 16 /* FixedSizeList */ ? stride : 1;
        const buffers = this._sliceBuffers(offset, length, stride, typeId);
        return this.clone(this.type, this.offset + offset, length, nullCount, buffers, 
        // Don't slice children if we have value offsets (the variable-width types)
        (!childData.length || this.valueOffsets) ? childData : this._sliceChildren(childData, childStride * offset, childStride * length));
    }
    _changeLengthAndBackfillNullBitmap(newLength) {
        if (this.typeId === standalone_enum_Type.Null) {
            return this.clone(this.type, 0, newLength, 0);
        }
        const { length, nullCount } = this;
        // start initialized with 0s (nulls), then fill from 0 to length with 1s (not null)
        const bitmap = new Uint8Array(((newLength + 63) & ~63) >> 3).fill(255, 0, length >> 3);
        // set all the bits in the last byte (up to bit `length - length % 8`) to 1 (not null)
        bitmap[length >> 3] = (1 << (length - (length & ~7))) - 1;
        // if we have a nullBitmap, truncate + slice and set it over the pre-filled 1s
        if (nullCount > 0) {
            bitmap.set(standalone_truncateBitmap(this.offset, length, this.nullBitmap), 0);
        }
        const buffers = this.buffers;
        buffers[standalone_BufferType.VALIDITY] = bitmap;
        return this.clone(this.type, 0, newLength, nullCount + (newLength - length), buffers);
    }
    _sliceBuffers(offset, length, stride, typeId) {
        let arr, { buffers } = this;
        // If typeIds exist, slice the typeIds buffer
        (arr = buffers[standalone_BufferType.TYPE]) && (buffers[standalone_BufferType.TYPE] = arr.subarray(offset, offset + length));
        // If offsets exist, only slice the offsets buffer
        (arr = buffers[standalone_BufferType.OFFSET]) && (buffers[standalone_BufferType.OFFSET] = arr.subarray(offset, offset + length + 1)) ||
            // Otherwise if no offsets, slice the data buffer. Don't slice the data vector for Booleans, since the offset goes by bits not bytes
            (arr = buffers[standalone_BufferType.DATA]) && (buffers[standalone_BufferType.DATA] = typeId === 6 ? arr : arr.subarray(stride * offset, stride * (offset + length)));
        return buffers;
    }
    _sliceChildren(childData, offset, length) {
        return childData.map((child) => child.slice(offset, length));
    }
    //
    // Convenience methods for creating Data instances for each of the Arrow Vector types
    //
    /** @nocollapse */
    static new(type, offset, length, nullCount, buffers, childData, dictionary) {
        if (buffers instanceof standalone_Data) {
            buffers = buffers.buffers;
        }
        else if (!buffers) {
            buffers = [];
        }
        switch (type.typeId) {
            case standalone_enum_Type.Null: return standalone_Data.Null(type, offset, length);
            case standalone_enum_Type.Int: return standalone_Data.Int(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.DATA] || []);
            case standalone_enum_Type.Dictionary: return standalone_Data.Dictionary(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.DATA] || [], dictionary);
            case standalone_enum_Type.Float: return standalone_Data.Float(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.DATA] || []);
            case standalone_enum_Type.Bool: return standalone_Data.Bool(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.DATA] || []);
            case standalone_enum_Type.Decimal: return standalone_Data.Decimal(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.DATA] || []);
            case standalone_enum_Type.Date: return standalone_Data.Date(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.DATA] || []);
            case standalone_enum_Type.Time: return standalone_Data.Time(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.DATA] || []);
            case standalone_enum_Type.Timestamp: return standalone_Data.Timestamp(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.DATA] || []);
            case standalone_enum_Type.Interval: return standalone_Data.Interval(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.DATA] || []);
            case standalone_enum_Type.FixedSizeBinary: return standalone_Data.FixedSizeBinary(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.DATA] || []);
            case standalone_enum_Type.Binary: return standalone_Data.Binary(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.OFFSET] || [], buffers[standalone_BufferType.DATA] || []);
            case standalone_enum_Type.Utf8: return standalone_Data.Utf8(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.OFFSET] || [], buffers[standalone_BufferType.DATA] || []);
            case standalone_enum_Type.List: return standalone_Data.List(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.OFFSET] || [], (childData || [])[0]);
            case standalone_enum_Type.FixedSizeList: return standalone_Data.FixedSizeList(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], (childData || [])[0]);
            case standalone_enum_Type.Struct: return standalone_Data.Struct(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], childData || []);
            case standalone_enum_Type.Map: return standalone_Data.Map(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.OFFSET] || [], (childData || [])[0]);
            case standalone_enum_Type.Union: return standalone_Data.Union(type, offset, length, nullCount || 0, buffers[standalone_BufferType.VALIDITY], buffers[standalone_BufferType.TYPE] || [], buffers[standalone_BufferType.OFFSET] || childData, childData);
        }
        throw new Error(`Unrecognized typeId ${type.typeId}`);
    }
    /** @nocollapse */
    static Null(type, offset, length) {
        return new standalone_Data(type, offset, length, 0);
    }
    /** @nocollapse */
    static Int(type, offset, length, nullCount, nullBitmap, data) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, standalone_toArrayBufferView(type.ArrayType, data), standalone_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Dictionary(type, offset, length, nullCount, nullBitmap, data, dictionary) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, standalone_toArrayBufferView(type.indices.ArrayType, data), standalone_toUint8Array(nullBitmap)], [], dictionary);
    }
    /** @nocollapse */
    static Float(type, offset, length, nullCount, nullBitmap, data) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, standalone_toArrayBufferView(type.ArrayType, data), standalone_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Bool(type, offset, length, nullCount, nullBitmap, data) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, standalone_toArrayBufferView(type.ArrayType, data), standalone_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Decimal(type, offset, length, nullCount, nullBitmap, data) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, standalone_toArrayBufferView(type.ArrayType, data), standalone_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Date(type, offset, length, nullCount, nullBitmap, data) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, standalone_toArrayBufferView(type.ArrayType, data), standalone_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Time(type, offset, length, nullCount, nullBitmap, data) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, standalone_toArrayBufferView(type.ArrayType, data), standalone_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Timestamp(type, offset, length, nullCount, nullBitmap, data) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, standalone_toArrayBufferView(type.ArrayType, data), standalone_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Interval(type, offset, length, nullCount, nullBitmap, data) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, standalone_toArrayBufferView(type.ArrayType, data), standalone_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static FixedSizeBinary(type, offset, length, nullCount, nullBitmap, data) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, standalone_toArrayBufferView(type.ArrayType, data), standalone_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Binary(type, offset, length, nullCount, nullBitmap, valueOffsets, data) {
        return new standalone_Data(type, offset, length, nullCount, [standalone_toInt32Array(valueOffsets), standalone_toUint8Array(data), standalone_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Utf8(type, offset, length, nullCount, nullBitmap, valueOffsets, data) {
        return new standalone_Data(type, offset, length, nullCount, [standalone_toInt32Array(valueOffsets), standalone_toUint8Array(data), standalone_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static List(type, offset, length, nullCount, nullBitmap, valueOffsets, child) {
        return new standalone_Data(type, offset, length, nullCount, [standalone_toInt32Array(valueOffsets), undefined, standalone_toUint8Array(nullBitmap)], child ? [child] : []);
    }
    /** @nocollapse */
    static FixedSizeList(type, offset, length, nullCount, nullBitmap, child) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, undefined, standalone_toUint8Array(nullBitmap)], child ? [child] : []);
    }
    /** @nocollapse */
    static Struct(type, offset, length, nullCount, nullBitmap, children) {
        return new standalone_Data(type, offset, length, nullCount, [undefined, undefined, standalone_toUint8Array(nullBitmap)], children);
    }
    /** @nocollapse */
    static Map(type, offset, length, nullCount, nullBitmap, valueOffsets, child) {
        return new standalone_Data(type, offset, length, nullCount, [standalone_toInt32Array(valueOffsets), undefined, standalone_toUint8Array(nullBitmap)], child ? [child] : []);
    }
    /** @nocollapse */
    static Union(type, offset, length, nullCount, nullBitmap, typeIds, valueOffsetsOrChildren, children) {
        const buffers = [
            undefined, undefined,
            standalone_toUint8Array(nullBitmap),
            standalone_toArrayBufferView(type.ArrayType, typeIds)
        ];
        if (type.mode === standalone_UnionMode.Sparse) {
            return new standalone_Data(type, offset, length, nullCount, buffers, valueOffsetsOrChildren);
        }
        buffers[standalone_BufferType.OFFSET] = standalone_toInt32Array(valueOffsetsOrChildren);
        return new standalone_Data(type, offset, length, nullCount, buffers, children);
    }
}
standalone_Data.prototype.childData = Object.freeze([]);

//# sourceMappingURL=data.mjs.map

;// ../../node_modules/apache-arrow/util/pretty.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
/** @ignore */ const standalone_undf = void (0);
/** @ignore */
function standalone_valueToString(x) {
    if (x === null) {
        return 'null';
    }
    if (x === standalone_undf) {
        return 'undefined';
    }
    switch (typeof x) {
        case 'number': return `${x}`;
        case 'bigint': return `${x}`;
        case 'string': return `"${x}"`;
    }
    // If [Symbol.toPrimitive] is implemented (like in BN)
    // use it instead of JSON.stringify(). This ensures we
    // print BigInts, Decimals, and Binary in their native
    // representation
    if (typeof x[Symbol.toPrimitive] === 'function') {
        return x[Symbol.toPrimitive]('string');
    }
    return ArrayBuffer.isView(x) ? `[${x}]` : JSON.stringify(x);
}

//# sourceMappingURL=pretty.mjs.map

;// ../../node_modules/apache-arrow/builder/valid.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/**
 * Dynamically compile the null values into an `isValid()` function whose
 * implementation is a switch statement. Microbenchmarks in v8 indicate
 * this approach is 25% faster than using an ES6 Map.
 *
 * @example
 * console.log(createIsValidFunction([null, 'N/A', NaN]));
 * `function (x) {
 *     if (x !== x) return false;
 *     switch (x) {
 *         case null:
 *         case "N/A":
 *             return false;
 *     }
 *     return true;
 * }`
 *
 * @ignore
 * @param nullValues
 */
function standalone_createIsValidFunction(nullValues) {
    if (!nullValues || nullValues.length <= 0) {
        // @ts-ignore
        return function isValid(value) { return true; };
    }
    let fnBody = '';
    let noNaNs = nullValues.filter((x) => x === x);
    if (noNaNs.length > 0) {
        fnBody = `
    switch (x) {${noNaNs.map((x) => `
        case ${standalone_valueToCase(x)}:`).join('')}
            return false;
    }`;
    }
    // NaN doesn't equal anything including itself, so it doesn't work as a
    // switch case. Instead we must explicitly check for NaN before the switch.
    if (nullValues.length !== noNaNs.length) {
        fnBody = `if (x !== x) return false;\n${fnBody}`;
    }
    return new Function(`x`, `${fnBody}\nreturn true;`);
}
/** @ignore */
function standalone_valueToCase(x) {
    if (typeof x !== 'bigint') {
        return standalone_valueToString(x);
    }
    else if (standalone_BigIntAvailable) {
        return `${standalone_valueToString(x)}n`;
    }
    return `"${standalone_valueToString(x)}"`;
}

//# sourceMappingURL=valid.mjs.map

;// ../../node_modules/apache-arrow/builder/buffer.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/** @ignore */
const standalone_roundLengthUpToNearest64Bytes = (len, BPE) => ((((len * BPE) + 63) & ~63) || 64) / BPE;
/** @ignore */
const standalone_sliceOrExtendArray = (arr, len = 0) => (arr.length >= len ? arr.subarray(0, len) : standalone_memcpy(new arr.constructor(len), arr, 0));
/** @ignore */
class standalone_BufferBuilder {
    constructor(buffer, stride = 1) {
        this.buffer = buffer;
        this.stride = stride;
        this.BYTES_PER_ELEMENT = buffer.BYTES_PER_ELEMENT;
        this.ArrayType = buffer.constructor;
        this._resize(this.length = buffer.length / stride | 0);
    }
    get byteLength() { return this.length * this.stride * this.BYTES_PER_ELEMENT | 0; }
    get reservedLength() { return this.buffer.length / this.stride; }
    get reservedByteLength() { return this.buffer.byteLength; }
    // @ts-ignore
    set(index, value) { return this; }
    append(value) { return this.set(this.length, value); }
    reserve(extra) {
        if (extra > 0) {
            this.length += extra;
            const stride = this.stride;
            const length = this.length * stride;
            const reserved = this.buffer.length;
            if (length >= reserved) {
                this._resize(reserved === 0
                    ? standalone_roundLengthUpToNearest64Bytes(length * 1, this.BYTES_PER_ELEMENT)
                    : standalone_roundLengthUpToNearest64Bytes(length * 2, this.BYTES_PER_ELEMENT));
            }
        }
        return this;
    }
    flush(length = this.length) {
        length = standalone_roundLengthUpToNearest64Bytes(length * this.stride, this.BYTES_PER_ELEMENT);
        const array = standalone_sliceOrExtendArray(this.buffer, length);
        this.clear();
        return array;
    }
    clear() {
        this.length = 0;
        this._resize(0);
        return this;
    }
    _resize(newLength) {
        return this.buffer = standalone_memcpy(new this.ArrayType(newLength), this.buffer);
    }
}
standalone_BufferBuilder.prototype.offset = 0;
/** @ignore */
class standalone_DataBufferBuilder extends standalone_BufferBuilder {
    last() { return this.get(this.length - 1); }
    get(index) { return this.buffer[index]; }
    set(index, value) {
        this.reserve(index - this.length + 1);
        this.buffer[index * this.stride] = value;
        return this;
    }
}
/** @ignore */
class standalone_BitmapBufferBuilder extends standalone_DataBufferBuilder {
    constructor(data = new Uint8Array(0)) {
        super(data, 1 / 8);
        this.numValid = 0;
    }
    get numInvalid() { return this.length - this.numValid; }
    get(idx) { return this.buffer[idx >> 3] >> idx % 8 & 1; }
    set(idx, val) {
        const { buffer } = this.reserve(idx - this.length + 1);
        const byte = idx >> 3, bit = idx % 8, cur = buffer[byte] >> bit & 1;
        // If `val` is truthy and the current bit is 0, flip it to 1 and increment `numValid`.
        // If `val` is falsey and the current bit is 1, flip it to 0 and decrement `numValid`.
        val ? cur === 0 && ((buffer[byte] |= (1 << bit)), ++this.numValid)
            : cur === 1 && ((buffer[byte] &= ~(1 << bit)), --this.numValid);
        return this;
    }
    clear() {
        this.numValid = 0;
        return super.clear();
    }
}
/** @ignore */
class standalone_OffsetsBufferBuilder extends standalone_DataBufferBuilder {
    constructor(data = new Int32Array(1)) { super(data, 1); }
    append(value) {
        return this.set(this.length - 1, value);
    }
    set(index, value) {
        const offset = this.length - 1;
        const buffer = this.reserve(index - offset + 1).buffer;
        if (offset < index++) {
            buffer.fill(buffer[offset], offset, index);
        }
        buffer[index] = buffer[index - 1] + value;
        return this;
    }
    flush(length = this.length - 1) {
        if (length > this.length) {
            this.set(length - 1, 0);
        }
        return super.flush(length + 1);
    }
}
/** @ignore */
class standalone_WideBufferBuilder extends standalone_BufferBuilder {
    get ArrayType64() {
        return this._ArrayType64 || (this._ArrayType64 = (this.buffer instanceof Int32Array ? standalone_BigInt64ArrayCtor : standalone_BigUint64ArrayCtor));
    }
    set(index, value) {
        this.reserve(index - this.length + 1);
        switch (typeof value) {
            case 'bigint':
                this.buffer64[index] = value;
                break;
            case 'number':
                this.buffer[index * this.stride] = value;
                break;
            default: this.buffer.set(value, index * this.stride);
        }
        return this;
    }
    _resize(newLength) {
        const data = super._resize(newLength);
        const length = data.byteLength / (this.BYTES_PER_ELEMENT * this.stride);
        if (standalone_BigIntAvailable) {
            this.buffer64 = new this.ArrayType64(data.buffer, data.byteOffset, length);
        }
        return data;
    }
}

//# sourceMappingURL=buffer.mjs.map

;// ../../node_modules/apache-arrow/builder.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.






/**
 * An abstract base class for types that construct Arrow Vectors from arbitrary JavaScript values.
 *
 * A `Builder` is responsible for writing arbitrary JavaScript values
 * to ArrayBuffers and/or child Builders according to the Arrow specification
 * for each DataType, creating or resizing the underlying ArrayBuffers as necessary.
 *
 * The `Builder` for each Arrow `DataType` handles converting and appending
 * values for a given `DataType`. The high-level {@link Builder.new `Builder.new()`} convenience
 * method creates the specific `Builder` subclass for the supplied `DataType`.
 *
 * Once created, `Builder` instances support both appending values to the end
 * of the `Builder`, and random-access writes to specific indices
 * (`Builder.prototype.append(value)` is a convenience method for
 * `builder.set(builder.length, value)`). Appending or setting values beyond the
 * Builder's current length may cause the builder to grow its underlying buffers
 * or child Builders (if applicable) to accommodate the new values.
 *
 * After enough values have been written to a `Builder`, `Builder.prototype.flush()`
 * will commit the values to the underlying ArrayBuffers (or child Builders). The
 * internal Builder state will be reset, and an instance of `Data<T>` is returned.
 * Alternatively, `Builder.prototype.toVector()` will flush the `Builder` and return
 * an instance of `Vector<T>` instead.
 *
 * When there are no more values to write, use `Builder.prototype.finish()` to
 * finalize the `Builder`. This does not reset the internal state, so it is
 * necessary to call `Builder.prototype.flush()` or `toVector()` one last time
 * if there are still values queued to be flushed.
 *
 * Note: calling `Builder.prototype.finish()` is required when using a `DictionaryBuilder`,
 * because this is when it flushes the values that have been enqueued in its internal
 * dictionary's `Builder`, and creates the `dictionaryVector` for the `Dictionary` `DataType`.
 *
 * ```ts
 * import { Builder, Utf8 } from 'apache-arrow';
 *
 * const utf8Builder = Builder.new({
 *     type: new Utf8(),
 *     nullValues: [null, 'n/a']
 * });
 *
 * utf8Builder
 *     .append('hello')
 *     .append('n/a')
 *     .append('world')
 *     .append(null);
 *
 * const utf8Vector = utf8Builder.finish().toVector();
 *
 * console.log(utf8Vector.toJSON());
 * // > ["hello", null, "world", null]
 * ```
 *
 * @typeparam T The `DataType` of this `Builder`.
 * @typeparam TNull The type(s) of values which will be considered null-value sentinels.
 */
class standalone_Builder {
    /**
     * Construct a builder with the given Arrow DataType with optional null values,
     * which will be interpreted as "null" when set or appended to the `Builder`.
     * @param {{ type: T, nullValues?: any[] }} options A `BuilderOptions` object used to create this `Builder`.
     */
    constructor({ 'type': type, 'nullValues': nulls }) {
        /**
         * The number of values written to the `Builder` that haven't been flushed yet.
         * @readonly
         */
        this.length = 0;
        /**
         * A boolean indicating whether `Builder.prototype.finish()` has been called on this `Builder`.
         * @readonly
         */
        this.finished = false;
        this.type = type;
        this.children = [];
        this.nullValues = nulls;
        this.stride = standalone_strideForType(type);
        this._nulls = new standalone_BitmapBufferBuilder();
        if (nulls && nulls.length > 0) {
            this._isValid = standalone_createIsValidFunction(nulls);
        }
    }
    /**
     * Create a `Builder` instance based on the `type` property of the supplied `options` object.
     * @param {BuilderOptions<T, TNull>} options An object with a required `DataType` instance
     * and other optional parameters to be passed to the `Builder` subclass for the given `type`.
     *
     * @typeparam T The `DataType` of the `Builder` to create.
     * @typeparam TNull The type(s) of values which will be considered null-value sentinels.
     * @nocollapse
     */
    // @ts-ignore
    static new(options) { }
    /** @nocollapse */
    // @ts-ignore
    static throughNode(options) {
        throw new Error(`"throughNode" not available in this environment`);
    }
    /** @nocollapse */
    // @ts-ignore
    static throughDOM(options) {
        throw new Error(`"throughDOM" not available in this environment`);
    }
    /**
     * Transform a synchronous `Iterable` of arbitrary JavaScript values into a
     * sequence of Arrow Vector<T> following the chunking semantics defined in
     * the supplied `options` argument.
     *
     * This function returns a function that accepts an `Iterable` of values to
     * transform. When called, this function returns an Iterator of `Vector<T>`.
     *
     * The resulting `Iterator<Vector<T>>` yields Vectors based on the
     * `queueingStrategy` and `highWaterMark` specified in the `options` argument.
     *
     * * If `queueingStrategy` is `"count"` (or omitted), The `Iterator<Vector<T>>`
     *   will flush the underlying `Builder` (and yield a new `Vector<T>`) once the
     *   Builder's `length` reaches or exceeds the supplied `highWaterMark`.
     * * If `queueingStrategy` is `"bytes"`, the `Iterator<Vector<T>>` will flush
     *   the underlying `Builder` (and yield a new `Vector<T>`) once its `byteLength`
     *   reaches or exceeds the supplied `highWaterMark`.
     *
     * @param {IterableBuilderOptions<T, TNull>} options An object of properties which determine the `Builder` to create and the chunking semantics to use.
     * @returns A function which accepts a JavaScript `Iterable` of values to
     *          write, and returns an `Iterator` that yields Vectors according
     *          to the chunking semantics defined in the `options` argument.
     * @nocollapse
     */
    static throughIterable(options) {
        return standalone_throughIterable(options);
    }
    /**
     * Transform an `AsyncIterable` of arbitrary JavaScript values into a
     * sequence of Arrow Vector<T> following the chunking semantics defined in
     * the supplied `options` argument.
     *
     * This function returns a function that accepts an `AsyncIterable` of values to
     * transform. When called, this function returns an AsyncIterator of `Vector<T>`.
     *
     * The resulting `AsyncIterator<Vector<T>>` yields Vectors based on the
     * `queueingStrategy` and `highWaterMark` specified in the `options` argument.
     *
     * * If `queueingStrategy` is `"count"` (or omitted), The `AsyncIterator<Vector<T>>`
     *   will flush the underlying `Builder` (and yield a new `Vector<T>`) once the
     *   Builder's `length` reaches or exceeds the supplied `highWaterMark`.
     * * If `queueingStrategy` is `"bytes"`, the `AsyncIterator<Vector<T>>` will flush
     *   the underlying `Builder` (and yield a new `Vector<T>`) once its `byteLength`
     *   reaches or exceeds the supplied `highWaterMark`.
     *
     * @param {IterableBuilderOptions<T, TNull>} options An object of properties which determine the `Builder` to create and the chunking semantics to use.
     * @returns A function which accepts a JavaScript `AsyncIterable` of values
     *          to write, and returns an `AsyncIterator` that yields Vectors
     *          according to the chunking semantics defined in the `options`
     *          argument.
     * @nocollapse
     */
    static throughAsyncIterable(options) {
        return standalone_throughAsyncIterable(options);
    }
    /**
     * Flush the `Builder` and return a `Vector<T>`.
     * @returns {Vector<T>} A `Vector<T>` of the flushed values.
     */
    toVector() { return standalone_AbstractVector.new(this.flush()); }
    get ArrayType() { return this.type.ArrayType; }
    get nullCount() { return this._nulls.numInvalid; }
    get numChildren() { return this.children.length; }
    /**
     * @returns The aggregate length (in bytes) of the values that have been written.
     */
    get byteLength() {
        let size = 0;
        this._offsets && (size += this._offsets.byteLength);
        this._values && (size += this._values.byteLength);
        this._nulls && (size += this._nulls.byteLength);
        this._typeIds && (size += this._typeIds.byteLength);
        return this.children.reduce((size, child) => size + child.byteLength, size);
    }
    /**
     * @returns The aggregate number of rows that have been reserved to write new values.
     */
    get reservedLength() {
        return this._nulls.reservedLength;
    }
    /**
     * @returns The aggregate length (in bytes) that has been reserved to write new values.
     */
    get reservedByteLength() {
        let size = 0;
        this._offsets && (size += this._offsets.reservedByteLength);
        this._values && (size += this._values.reservedByteLength);
        this._nulls && (size += this._nulls.reservedByteLength);
        this._typeIds && (size += this._typeIds.reservedByteLength);
        return this.children.reduce((size, child) => size + child.reservedByteLength, size);
    }
    get valueOffsets() { return this._offsets ? this._offsets.buffer : null; }
    get values() { return this._values ? this._values.buffer : null; }
    get nullBitmap() { return this._nulls ? this._nulls.buffer : null; }
    get typeIds() { return this._typeIds ? this._typeIds.buffer : null; }
    /**
     * Appends a value (or null) to this `Builder`.
     * This is equivalent to `builder.set(builder.length, value)`.
     * @param {T['TValue'] | TNull } value The value to append.
     */
    append(value) { return this.set(this.length, value); }
    /**
     * Validates whether a value is valid (true), or null (false)
     * @param {T['TValue'] | TNull } value The value to compare against null the value representations
     */
    // @ts-ignore
    isValid(value) { return this._isValid(value); }
    /**
     * Write a value (or null-value sentinel) at the supplied index.
     * If the value matches one of the null-value representations, a 1-bit is
     * written to the null `BitmapBufferBuilder`. Otherwise, a 0 is written to
     * the null `BitmapBufferBuilder`, and the value is passed to
     * `Builder.prototype.setValue()`.
     * @param {number} index The index of the value to write.
     * @param {T['TValue'] | TNull } value The value to write at the supplied index.
     * @returns {this} The updated `Builder` instance.
     */
    set(index, value) {
        if (this.setValid(index, this.isValid(value))) {
            this.setValue(index, value);
        }
        return this;
    }
    /**
     * Write a value to the underlying buffers at the supplied index, bypassing
     * the null-value check. This is a low-level method that
     * @param {number} index
     * @param {T['TValue'] | TNull } value
     */
    // @ts-ignore
    setValue(index, value) { this._setValue(this, index, value); }
    setValid(index, valid) {
        this.length = this._nulls.set(index, +valid).length;
        return valid;
    }
    // @ts-ignore
    addChild(child, name = `${this.numChildren}`) {
        throw new Error(`Cannot append children to non-nested type "${this.type}"`);
    }
    /**
     * Retrieve the child `Builder` at the supplied `index`, or null if no child
     * exists at that index.
     * @param {number} index The index of the child `Builder` to retrieve.
     * @returns {Builder | null} The child Builder at the supplied index or null.
     */
    getChildAt(index) {
        return this.children[index] || null;
    }
    /**
     * Commit all the values that have been written to their underlying
     * ArrayBuffers, including any child Builders if applicable, and reset
     * the internal `Builder` state.
     * @returns A `Data<T>` of the buffers and childData representing the values written.
     */
    flush() {
        const buffers = [];
        const values = this._values;
        const offsets = this._offsets;
        const typeIds = this._typeIds;
        const { length, nullCount } = this;
        if (typeIds) { /* Unions */
            buffers[standalone_BufferType.TYPE] = typeIds.flush(length);
            // DenseUnions
            offsets && (buffers[standalone_BufferType.OFFSET] = offsets.flush(length));
        }
        else if (offsets) { /* Variable-width primitives (Binary, Utf8) and Lists */
            // Binary, Utf8
            values && (buffers[standalone_BufferType.DATA] = values.flush(offsets.last()));
            buffers[standalone_BufferType.OFFSET] = offsets.flush(length);
        }
        else if (values) { /* Fixed-width primitives (Int, Float, Decimal, Time, Timestamp, and Interval) */
            buffers[standalone_BufferType.DATA] = values.flush(length);
        }
        nullCount > 0 && (buffers[standalone_BufferType.VALIDITY] = this._nulls.flush(length));
        const data = standalone_Data.new(this.type, 0, length, nullCount, buffers, this.children.map((child) => child.flush()));
        this.clear();
        return data;
    }
    /**
     * Finalize this `Builder`, and child builders if applicable.
     * @returns {this} The finalized `Builder` instance.
     */
    finish() {
        this.finished = true;
        this.children.forEach((child) => child.finish());
        return this;
    }
    /**
     * Clear this Builder's internal state, including child Builders if applicable, and reset the length to 0.
     * @returns {this} The cleared `Builder` instance.
     */
    clear() {
        this.length = 0;
        this._offsets && (this._offsets.clear());
        this._values && (this._values.clear());
        this._nulls && (this._nulls.clear());
        this._typeIds && (this._typeIds.clear());
        this.children.forEach((child) => child.clear());
        return this;
    }
}
standalone_Builder.prototype.length = 1;
standalone_Builder.prototype.stride = 1;
standalone_Builder.prototype.children = null;
standalone_Builder.prototype.finished = false;
standalone_Builder.prototype.nullValues = null;
standalone_Builder.prototype._isValid = () => true;
/** @ignore */
class standalone_FixedWidthBuilder extends standalone_Builder {
    constructor(opts) {
        super(opts);
        this._values = new standalone_DataBufferBuilder(new this.ArrayType(0), this.stride);
    }
    setValue(index, value) {
        const values = this._values;
        values.reserve(index - values.length + 1);
        return super.setValue(index, value);
    }
}
/** @ignore */
class standalone_VariableWidthBuilder extends standalone_Builder {
    constructor(opts) {
        super(opts);
        this._pendingLength = 0;
        this._offsets = new standalone_OffsetsBufferBuilder();
    }
    setValue(index, value) {
        const pending = this._pending || (this._pending = new Map());
        const current = pending.get(index);
        current && (this._pendingLength -= current.length);
        this._pendingLength += value.length;
        pending.set(index, value);
    }
    setValid(index, isValid) {
        if (!super.setValid(index, isValid)) {
            (this._pending || (this._pending = new Map())).set(index, undefined);
            return false;
        }
        return true;
    }
    clear() {
        this._pendingLength = 0;
        this._pending = undefined;
        return super.clear();
    }
    flush() {
        this._flush();
        return super.flush();
    }
    finish() {
        this._flush();
        return super.finish();
    }
    _flush() {
        const pending = this._pending;
        const pendingLength = this._pendingLength;
        this._pendingLength = 0;
        this._pending = undefined;
        if (pending && pending.size > 0) {
            this._flushPending(pending, pendingLength);
        }
        return this;
    }
}
/** @ignore */
function standalone_throughIterable(options) {
    const { ['queueingStrategy']: queueingStrategy = 'count' } = options;
    const { ['highWaterMark']: highWaterMark = queueingStrategy !== 'bytes' ? 1000 : 2 ** 14 } = options;
    const sizeProperty = queueingStrategy !== 'bytes' ? 'length' : 'byteLength';
    return function* (source) {
        let numChunks = 0;
        let builder = standalone_Builder.new(options);
        for (const value of source) {
            if (builder.append(value)[sizeProperty] >= highWaterMark) {
                ++numChunks && (yield builder.toVector());
            }
        }
        if (builder.finish().length > 0 || numChunks === 0) {
            yield builder.toVector();
        }
    };
}
/** @ignore */
function standalone_throughAsyncIterable(options) {
    const { ['queueingStrategy']: queueingStrategy = 'count' } = options;
    const { ['highWaterMark']: highWaterMark = queueingStrategy !== 'bytes' ? 1000 : 2 ** 14 } = options;
    const sizeProperty = queueingStrategy !== 'bytes' ? 'length' : 'byteLength';
    return async function* (source) {
        let numChunks = 0;
        let builder = standalone_Builder.new(options);
        for await (const value of source) {
            if (builder.append(value)[sizeProperty] >= highWaterMark) {
                ++numChunks && (yield builder.toVector());
            }
        }
        if (builder.finish().length > 0 || numChunks === 0) {
            yield builder.toVector();
        }
    };
}

//# sourceMappingURL=builder.mjs.map

;// ../../node_modules/apache-arrow/builder/bool.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/** @ignore */
class standalone_BoolBuilder extends standalone_Builder {
    constructor(options) {
        super(options);
        this._values = new standalone_BitmapBufferBuilder();
    }
    setValue(index, value) {
        this._values.set(index, +value);
    }
}

//# sourceMappingURL=bool.mjs.map

;// ../../node_modules/apache-arrow/builder/null.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_NullBuilder extends standalone_Builder {
    // @ts-ignore
    setValue(index, value) { }
    setValid(index, valid) {
        this.length = Math.max(index + 1, this.length);
        return valid;
    }
}

//# sourceMappingURL=null.mjs.map

;// ../../node_modules/apache-arrow/builder/date.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_DateBuilder extends standalone_FixedWidthBuilder {
}
/** @ignore */
class standalone_DateDayBuilder extends standalone_DateBuilder {
}
/** @ignore */
class standalone_DateMillisecondBuilder extends standalone_DateBuilder {
}

//# sourceMappingURL=date.mjs.map

;// ../../node_modules/apache-arrow/builder/decimal.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_DecimalBuilder extends standalone_FixedWidthBuilder {
}

//# sourceMappingURL=decimal.mjs.map

;// ../../node_modules/apache-arrow/builder/dictionary.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/** @ignore */
class standalone_DictionaryBuilder extends standalone_Builder {
    constructor({ 'type': type, 'nullValues': nulls, 'dictionaryHashFunction': hashFn }) {
        super({ type: new standalone_type_Dictionary(type.dictionary, type.indices, type.id, type.isOrdered) });
        this._nulls = null;
        this._dictionaryOffset = 0;
        this._keysToIndices = Object.create(null);
        this.indices = standalone_Builder.new({ 'type': this.type.indices, 'nullValues': nulls });
        this.dictionary = standalone_Builder.new({ 'type': this.type.dictionary, 'nullValues': null });
        if (typeof hashFn === 'function') {
            this.valueToKey = hashFn;
        }
    }
    get values() { return this.indices.values; }
    get nullCount() { return this.indices.nullCount; }
    get nullBitmap() { return this.indices.nullBitmap; }
    get byteLength() { return this.indices.byteLength + this.dictionary.byteLength; }
    get reservedLength() { return this.indices.reservedLength + this.dictionary.reservedLength; }
    get reservedByteLength() { return this.indices.reservedByteLength + this.dictionary.reservedByteLength; }
    isValid(value) { return this.indices.isValid(value); }
    setValid(index, valid) {
        const indices = this.indices;
        valid = indices.setValid(index, valid);
        this.length = indices.length;
        return valid;
    }
    setValue(index, value) {
        let keysToIndices = this._keysToIndices;
        let key = this.valueToKey(value);
        let idx = keysToIndices[key];
        if (idx === undefined) {
            keysToIndices[key] = idx = this._dictionaryOffset + this.dictionary.append(value).length - 1;
        }
        return this.indices.setValue(index, idx);
    }
    flush() {
        const type = this.type;
        const prev = this._dictionary;
        const curr = this.dictionary.toVector();
        const data = this.indices.flush().clone(type);
        data.dictionary = prev ? prev.concat(curr) : curr;
        this.finished || (this._dictionaryOffset += curr.length);
        this._dictionary = data.dictionary;
        this.clear();
        return data;
    }
    finish() {
        this.indices.finish();
        this.dictionary.finish();
        this._dictionaryOffset = 0;
        this._keysToIndices = Object.create(null);
        return super.finish();
    }
    clear() {
        this.indices.clear();
        this.dictionary.clear();
        return super.clear();
    }
    valueToKey(val) {
        return typeof val === 'string' ? val : `${val}`;
    }
}

//# sourceMappingURL=dictionary.mjs.map

;// ../../node_modules/apache-arrow/builder/fixedsizebinary.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_FixedSizeBinaryBuilder extends standalone_FixedWidthBuilder {
}

//# sourceMappingURL=fixedsizebinary.mjs.map

;// ../../node_modules/apache-arrow/util/math.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
const standalone_f64 = new Float64Array(1);
const standalone_u32 = new Uint32Array(standalone_f64.buffer);
/**
 * Convert uint16 (logically a float16) to a JS float64. Inspired by numpy's `npy_half_to_double`:
 * https://github.com/numpy/numpy/blob/5a5987291dc95376bb098be8d8e5391e89e77a2c/numpy/core/src/npymath/halffloat.c#L29
 * @param h {number} the uint16 to convert
 * @private
 * @ignore
 */
function standalone_uint16ToFloat64(h) {
    let expo = (h & 0x7C00) >> 10;
    let sigf = (h & 0x03FF) / 1024;
    let sign = (-1) ** ((h & 0x8000) >> 15);
    switch (expo) {
        case 0x1F: return sign * (sigf ? NaN : 1 / 0);
        case 0x00: return sign * (sigf ? 6.103515625e-5 * sigf : 0);
    }
    return sign * (2 ** (expo - 15)) * (1 + sigf);
}
/**
 * Convert a float64 to uint16 (assuming the float64 is logically a float16). Inspired by numpy's `npy_double_to_half`:
 * https://github.com/numpy/numpy/blob/5a5987291dc95376bb098be8d8e5391e89e77a2c/numpy/core/src/npymath/halffloat.c#L43
 * @param d {number} The float64 to convert
 * @private
 * @ignore
 */
function standalone_float64ToUint16(d) {
    if (d !== d) {
        return 0x7E00;
    } // NaN
    standalone_f64[0] = d;
    // Magic numbers:
    // 0x80000000 = 10000000 00000000 00000000 00000000 -- masks the 32nd bit
    // 0x7ff00000 = 01111111 11110000 00000000 00000000 -- masks the 21st-31st bits
    // 0x000fffff = 00000000 00001111 11111111 11111111 -- masks the 1st-20th bit
    let sign = (standalone_u32[1] & 0x80000000) >> 16 & 0xFFFF;
    let expo = (standalone_u32[1] & 0x7ff00000), sigf = 0x0000;
    if (expo >= 0x40f00000) {
        //
        // If exponent overflowed, the float16 is either NaN or Infinity.
        // Rules to propagate the sign bit: mantissa > 0 ? NaN : +/-Infinity
        //
        // Magic numbers:
        // 0x40F00000 = 01000000 11110000 00000000 00000000 -- 6-bit exponent overflow
        // 0x7C000000 = 01111100 00000000 00000000 00000000 -- masks the 27th-31st bits
        //
        // returns:
        // qNaN, aka 32256 decimal, 0x7E00 hex, or 01111110 00000000 binary
        // sNaN, aka 32000 decimal, 0x7D00 hex, or 01111101 00000000 binary
        // +inf, aka 31744 decimal, 0x7C00 hex, or 01111100 00000000 binary
        // -inf, aka 64512 decimal, 0xFC00 hex, or 11111100 00000000 binary
        //
        // If mantissa is greater than 23 bits, set to +Infinity like numpy
        if (standalone_u32[0] > 0) {
            expo = 0x7C00;
        }
        else {
            expo = (expo & 0x7C000000) >> 16;
            sigf = (standalone_u32[1] & 0x000fffff) >> 10;
        }
    }
    else if (expo <= 0x3f000000) {
        //
        // If exponent underflowed, the float is either signed zero or subnormal.
        //
        // Magic numbers:
        // 0x3F000000 = 00111111 00000000 00000000 00000000 -- 6-bit exponent underflow
        //
        sigf = 0x100000 + (standalone_u32[1] & 0x000fffff);
        sigf = 0x100000 + (sigf << ((expo >> 20) - 998)) >> 21;
        expo = 0;
    }
    else {
        //
        // No overflow or underflow, rebase the exponent and round the mantissa
        // Magic numbers:
        // 0x200 = 00000010 00000000 -- masks off the 10th bit
        //
        // Ensure the first mantissa bit (the 10th one) is 1 and round
        expo = (expo - 0x3f000000) >> 10;
        sigf = ((standalone_u32[1] & 0x000fffff) + 0x200) >> 10;
    }
    return sign | expo | sigf & 0xFFFF;
}

//# sourceMappingURL=math.mjs.map

;// ../../node_modules/apache-arrow/builder/float.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/** @ignore */
class standalone_FloatBuilder extends standalone_FixedWidthBuilder {
}
/** @ignore */
class standalone_Float16Builder extends standalone_FloatBuilder {
    setValue(index, value) {
        // convert JS float64 to a uint16
        this._values.set(index, standalone_float64ToUint16(value));
    }
}
/** @ignore */
class standalone_Float32Builder extends standalone_FloatBuilder {
    setValue(index, value) {
        this._values.set(index, value);
    }
}
/** @ignore */
class standalone_Float64Builder extends standalone_FloatBuilder {
    setValue(index, value) {
        this._values.set(index, value);
    }
}

//# sourceMappingURL=float.mjs.map

;// ../../node_modules/apache-arrow/util/bn.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/** @ignore */
const standalone_isArrowBigNumSymbol = Symbol.for('isArrowBigNum');
/** @ignore */
function standalone_BigNum(x, ...xs) {
    if (xs.length === 0) {
        return Object.setPrototypeOf(standalone_toArrayBufferView(this['TypedArray'], x), this.constructor.prototype);
    }
    return Object.setPrototypeOf(new this['TypedArray'](x, ...xs), this.constructor.prototype);
}
standalone_BigNum.prototype[standalone_isArrowBigNumSymbol] = true;
standalone_BigNum.prototype.toJSON = function () { return `"${standalone_bignumToString(this)}"`; };
standalone_BigNum.prototype.valueOf = function () { return standalone_bignumToNumber(this); };
standalone_BigNum.prototype.toString = function () { return standalone_bignumToString(this); };
standalone_BigNum.prototype[Symbol.toPrimitive] = function (hint = 'default') {
    switch (hint) {
        case 'number': return standalone_bignumToNumber(this);
        case 'string': return standalone_bignumToString(this);
        case 'default': return standalone_bignumToBigInt(this);
    }
    // @ts-ignore
    return standalone_bignumToString(this);
};
/** @ignore */
function standalone_SignedBigNum(...args) { return standalone_BigNum.apply(this, args); }
/** @ignore */
function standalone_UnsignedBigNum(...args) { return standalone_BigNum.apply(this, args); }
/** @ignore */
function standalone_DecimalBigNum(...args) { return standalone_BigNum.apply(this, args); }
Object.setPrototypeOf(standalone_SignedBigNum.prototype, Object.create(Int32Array.prototype));
Object.setPrototypeOf(standalone_UnsignedBigNum.prototype, Object.create(Uint32Array.prototype));
Object.setPrototypeOf(standalone_DecimalBigNum.prototype, Object.create(Uint32Array.prototype));
Object.assign(standalone_SignedBigNum.prototype, standalone_BigNum.prototype, { 'constructor': standalone_SignedBigNum, 'signed': true, 'TypedArray': Int32Array, 'BigIntArray': standalone_BigInt64ArrayCtor });
Object.assign(standalone_UnsignedBigNum.prototype, standalone_BigNum.prototype, { 'constructor': standalone_UnsignedBigNum, 'signed': false, 'TypedArray': Uint32Array, 'BigIntArray': standalone_BigUint64ArrayCtor });
Object.assign(standalone_DecimalBigNum.prototype, standalone_BigNum.prototype, { 'constructor': standalone_DecimalBigNum, 'signed': true, 'TypedArray': Uint32Array, 'BigIntArray': standalone_BigUint64ArrayCtor });
/** @ignore */
function standalone_bignumToNumber(bn) {
    let { buffer, byteOffset, length, 'signed': signed } = bn;
    let words = new Int32Array(buffer, byteOffset, length);
    let number = 0, i = 0, n = words.length, hi, lo;
    while (i < n) {
        lo = words[i++];
        hi = words[i++];
        signed || (hi = hi >>> 0);
        number += (lo >>> 0) + (hi * (i ** 32));
    }
    return number;
}
/** @ignore */
let standalone_bignumToString;
/** @ignore */
let standalone_bignumToBigInt;
if (!standalone_BigIntAvailable) {
    standalone_bignumToString = standalone_decimalToString;
    standalone_bignumToBigInt = standalone_bignumToString;
}
else {
    standalone_bignumToBigInt = ((a) => a.byteLength === 8 ? new a['BigIntArray'](a.buffer, a.byteOffset, 1)[0] : standalone_decimalToString(a));
    standalone_bignumToString = ((a) => a.byteLength === 8 ? `${new a['BigIntArray'](a.buffer, a.byteOffset, 1)[0]}` : standalone_decimalToString(a));
}
/** @ignore */
function standalone_decimalToString(a) {
    let digits = '';
    let base64 = new Uint32Array(2);
    let base32 = new Uint16Array(a.buffer, a.byteOffset, a.byteLength / 2);
    let checks = new Uint32Array((base32 = new Uint16Array(base32).reverse()).buffer);
    let i = -1, n = base32.length - 1;
    do {
        for (base64[0] = base32[i = 0]; i < n;) {
            base32[i++] = base64[1] = base64[0] / 10;
            base64[0] = ((base64[0] - base64[1] * 10) << 16) + base32[i];
        }
        base32[i] = base64[1] = base64[0] / 10;
        base64[0] = base64[0] - base64[1] * 10;
        digits = `${base64[0]}${digits}`;
    } while (checks[0] || checks[1] || checks[2] || checks[3]);
    return digits ? digits : `0`;
}
/** @ignore */
class standalone_BN {
    /** @nocollapse */
    static new(num, isSigned) {
        switch (isSigned) {
            case true: return new standalone_SignedBigNum(num);
            case false: return new standalone_UnsignedBigNum(num);
        }
        switch (num.constructor) {
            case Int8Array:
            case Int16Array:
            case Int32Array:
            case standalone_BigInt64ArrayCtor:
                return new standalone_SignedBigNum(num);
        }
        if (num.byteLength === 16) {
            return new standalone_DecimalBigNum(num);
        }
        return new standalone_UnsignedBigNum(num);
    }
    /** @nocollapse */
    static signed(num) {
        return new standalone_SignedBigNum(num);
    }
    /** @nocollapse */
    static unsigned(num) {
        return new standalone_UnsignedBigNum(num);
    }
    /** @nocollapse */
    static decimal(num) {
        return new standalone_DecimalBigNum(num);
    }
    constructor(num, isSigned) {
        return standalone_BN.new(num, isSigned);
    }
}

//# sourceMappingURL=bn.mjs.map

;// ../../node_modules/apache-arrow/builder/int.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
class standalone_IntBuilder extends standalone_FixedWidthBuilder {
    setValue(index, value) {
        this._values.set(index, value);
    }
}
/** @ignore */
class standalone_Int8Builder extends standalone_IntBuilder {
}
/** @ignore */
class standalone_Int16Builder extends standalone_IntBuilder {
}
/** @ignore */
class standalone_Int32Builder extends standalone_IntBuilder {
}
/** @ignore */
class standalone_Int64Builder extends standalone_IntBuilder {
    constructor(options) {
        if (options['nullValues']) {
            options['nullValues'] = options['nullValues'].map(standalone_toBigInt);
        }
        super(options);
        this._values = new standalone_WideBufferBuilder(new Int32Array(0), 2);
    }
    get values64() { return this._values.buffer64; }
    isValid(value) { return super.isValid(standalone_toBigInt(value)); }
}
/** @ignore */
class standalone_Uint8Builder extends standalone_IntBuilder {
}
/** @ignore */
class standalone_Uint16Builder extends standalone_IntBuilder {
}
/** @ignore */
class standalone_Uint32Builder extends standalone_IntBuilder {
}
/** @ignore */
class standalone_Uint64Builder extends standalone_IntBuilder {
    constructor(options) {
        if (options['nullValues']) {
            options['nullValues'] = options['nullValues'].map(standalone_toBigInt);
        }
        super(options);
        this._values = new standalone_WideBufferBuilder(new Uint32Array(0), 2);
    }
    get values64() { return this._values.buffer64; }
    isValid(value) { return super.isValid(standalone_toBigInt(value)); }
}
const standalone_toBigInt = ((memo) => (value) => {
    if (ArrayBuffer.isView(value)) {
        memo.buffer = value.buffer;
        memo.byteOffset = value.byteOffset;
        memo.byteLength = value.byteLength;
        value = standalone_bignumToBigInt(memo);
        memo.buffer = null;
    }
    return value;
})({ 'BigIntArray': standalone_BigInt64ArrayCtor });

//# sourceMappingURL=int.mjs.map

;// ../../node_modules/apache-arrow/builder/time.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_TimeBuilder extends standalone_FixedWidthBuilder {
}
/** @ignore */
class standalone_TimeSecondBuilder extends standalone_TimeBuilder {
}
/** @ignore */
class standalone_TimeMillisecondBuilder extends standalone_TimeBuilder {
}
/** @ignore */
class standalone_TimeMicrosecondBuilder extends standalone_TimeBuilder {
}
/** @ignore */
class standalone_TimeNanosecondBuilder extends standalone_TimeBuilder {
}

//# sourceMappingURL=time.mjs.map

;// ../../node_modules/apache-arrow/builder/timestamp.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_TimestampBuilder extends standalone_FixedWidthBuilder {
}
/** @ignore */
class standalone_TimestampSecondBuilder extends standalone_TimestampBuilder {
}
/** @ignore */
class standalone_TimestampMillisecondBuilder extends standalone_TimestampBuilder {
}
/** @ignore */
class standalone_TimestampMicrosecondBuilder extends standalone_TimestampBuilder {
}
/** @ignore */
class standalone_TimestampNanosecondBuilder extends standalone_TimestampBuilder {
}

//# sourceMappingURL=timestamp.mjs.map

;// ../../node_modules/apache-arrow/builder/interval.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_IntervalBuilder extends standalone_FixedWidthBuilder {
}
/** @ignore */
class standalone_IntervalDayTimeBuilder extends standalone_IntervalBuilder {
}
/** @ignore */
class standalone_IntervalYearMonthBuilder extends standalone_IntervalBuilder {
}

//# sourceMappingURL=interval.mjs.map

;// ../../node_modules/apache-arrow/builder/binary.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.



/** @ignore */
class standalone_BinaryBuilder extends standalone_VariableWidthBuilder {
    constructor(opts) {
        super(opts);
        this._values = new standalone_BufferBuilder(new Uint8Array(0));
    }
    get byteLength() {
        let size = this._pendingLength + (this.length * 4);
        this._offsets && (size += this._offsets.byteLength);
        this._values && (size += this._values.byteLength);
        this._nulls && (size += this._nulls.byteLength);
        return size;
    }
    setValue(index, value) {
        return super.setValue(index, standalone_toUint8Array(value));
    }
    _flushPending(pending, pendingLength) {
        const offsets = this._offsets;
        const data = this._values.reserve(pendingLength).buffer;
        let index = 0, length = 0, offset = 0, value;
        for ([index, value] of pending) {
            if (value === undefined) {
                offsets.set(index, 0);
            }
            else {
                length = value.length;
                data.set(value, offset);
                offsets.set(index, length);
                offset += length;
            }
        }
    }
}

//# sourceMappingURL=binary.mjs.map

;// ../../node_modules/apache-arrow/builder/utf8.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
class standalone_Utf8Builder extends standalone_VariableWidthBuilder {
    constructor(opts) {
        super(opts);
        this._values = new standalone_BufferBuilder(new Uint8Array(0));
    }
    get byteLength() {
        let size = this._pendingLength + (this.length * 4);
        this._offsets && (size += this._offsets.byteLength);
        this._values && (size += this._values.byteLength);
        this._nulls && (size += this._nulls.byteLength);
        return size;
    }
    setValue(index, value) {
        return super.setValue(index, standalone_encodeUtf8(value));
    }
    // @ts-ignore
    _flushPending(pending, pendingLength) { }
}
standalone_Utf8Builder.prototype._flushPending = standalone_BinaryBuilder.prototype._flushPending;

//# sourceMappingURL=utf8.mjs.map

;// ../../node_modules/apache-arrow/builder/run.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_Run {
    get length() { return this._values.length; }
    get(index) { return this._values[index]; }
    clear() { this._values = null; return this; }
    bind(values) {
        if (values instanceof standalone_AbstractVector) {
            return values;
        }
        this._values = values;
        return this;
    }
}

//# sourceMappingURL=run.mjs.map

;// ../../node_modules/apache-arrow/vector/row.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */ const standalone_kParent = Symbol.for('parent');
/** @ignore */ const standalone_kRowIndex = Symbol.for('rowIndex');
/** @ignore */ const standalone_kKeyToIdx = Symbol.for('keyToIdx');
/** @ignore */ const standalone_kIdxToVal = Symbol.for('idxToVal');
/** @ignore */ const standalone_kCustomInspect = Symbol.for('nodejs.util.inspect.custom');
class standalone_row_Row {
    constructor(parent, numKeys) {
        this[standalone_kParent] = parent;
        this.size = numKeys;
    }
    entries() { return this[Symbol.iterator](); }
    has(key) { return this.get(key) !== undefined; }
    get(key) {
        let val = undefined;
        if (key !== null && key !== undefined) {
            const ktoi = this[standalone_kKeyToIdx] || (this[standalone_kKeyToIdx] = new Map());
            let idx = ktoi.get(key);
            if (idx !== undefined) {
                const itov = this[standalone_kIdxToVal] || (this[standalone_kIdxToVal] = new Array(this.size));
                ((val = itov[idx]) !== undefined) || (itov[idx] = val = this.getValue(idx));
            }
            else if ((idx = this.getIndex(key)) > -1) {
                ktoi.set(key, idx);
                const itov = this[standalone_kIdxToVal] || (this[standalone_kIdxToVal] = new Array(this.size));
                ((val = itov[idx]) !== undefined) || (itov[idx] = val = this.getValue(idx));
            }
        }
        return val;
    }
    set(key, val) {
        if (key !== null && key !== undefined) {
            const ktoi = this[standalone_kKeyToIdx] || (this[standalone_kKeyToIdx] = new Map());
            let idx = ktoi.get(key);
            if (idx === undefined) {
                ktoi.set(key, idx = this.getIndex(key));
            }
            if (idx > -1) {
                const itov = this[standalone_kIdxToVal] || (this[standalone_kIdxToVal] = new Array(this.size));
                itov[idx] = this.setValue(idx, val);
            }
        }
        return this;
    }
    clear() { throw new Error(`Clearing ${this[Symbol.toStringTag]} not supported.`); }
    delete(_) { throw new Error(`Deleting ${this[Symbol.toStringTag]} values not supported.`); }
    *[Symbol.iterator]() {
        const ki = this.keys();
        const vi = this.values();
        const ktoi = this[standalone_kKeyToIdx] || (this[standalone_kKeyToIdx] = new Map());
        const itov = this[standalone_kIdxToVal] || (this[standalone_kIdxToVal] = new Array(this.size));
        for (let k, v, i = 0, kr, vr; !((kr = ki.next()).done || (vr = vi.next()).done); ++i) {
            k = kr.value;
            v = vr.value;
            itov[i] = v;
            ktoi.has(k) || ktoi.set(k, i);
            yield [k, v];
        }
    }
    forEach(callbackfn, thisArg) {
        const ki = this.keys();
        const vi = this.values();
        const callback = thisArg === undefined ? callbackfn :
            (v, k, m) => callbackfn.call(thisArg, v, k, m);
        const ktoi = this[standalone_kKeyToIdx] || (this[standalone_kKeyToIdx] = new Map());
        const itov = this[standalone_kIdxToVal] || (this[standalone_kIdxToVal] = new Array(this.size));
        for (let k, v, i = 0, kr, vr; !((kr = ki.next()).done || (vr = vi.next()).done); ++i) {
            k = kr.value;
            v = vr.value;
            itov[i] = v;
            ktoi.has(k) || ktoi.set(k, i);
            callback(v, k, this);
        }
    }
    toArray() { return [...this.values()]; }
    toJSON() {
        const obj = {};
        this.forEach((val, key) => obj[key] = val);
        return obj;
    }
    inspect() { return this.toString(); }
    [standalone_kCustomInspect]() { return this.toString(); }
    toString() {
        const str = [];
        this.forEach((val, key) => {
            key = standalone_valueToString(key);
            val = standalone_valueToString(val);
            str.push(`${key}: ${val}`);
        });
        return `{ ${str.join(', ')} }`;
    }
}
standalone_row_Row[Symbol.toStringTag] = ((proto) => {
    Object.defineProperties(proto, {
        'size': { writable: true, enumerable: false, configurable: false, value: 0 },
        [standalone_kParent]: { writable: true, enumerable: false, configurable: false, value: null },
        [standalone_kRowIndex]: { writable: true, enumerable: false, configurable: false, value: -1 },
    });
    return proto[Symbol.toStringTag] = 'Row';
})(standalone_row_Row.prototype);
class standalone_MapRow extends standalone_row_Row {
    constructor(slice) {
        super(slice, slice.length);
        return standalone_createRowProxy(this);
    }
    keys() {
        return this[standalone_kParent].getChildAt(0)[Symbol.iterator]();
    }
    values() {
        return this[standalone_kParent].getChildAt(1)[Symbol.iterator]();
    }
    getKey(idx) {
        return this[standalone_kParent].getChildAt(0).get(idx);
    }
    getIndex(key) {
        return this[standalone_kParent].getChildAt(0).indexOf(key);
    }
    getValue(index) {
        return this[standalone_kParent].getChildAt(1).get(index);
    }
    setValue(index, value) {
        this[standalone_kParent].getChildAt(1).set(index, value);
    }
}
class standalone_StructRow extends standalone_row_Row {
    constructor(parent) {
        super(parent, parent.type.children.length);
        return standalone_defineRowProxyProperties(this);
    }
    *keys() {
        for (const field of this[standalone_kParent].type.children) {
            yield field.name;
        }
    }
    *values() {
        for (const field of this[standalone_kParent].type.children) {
            yield this[field.name];
        }
    }
    getKey(idx) {
        return this[standalone_kParent].type.children[idx].name;
    }
    getIndex(key) {
        return this[standalone_kParent].type.children.findIndex((f) => f.name === key);
    }
    getValue(index) {
        return this[standalone_kParent].getChildAt(index).get(this[standalone_kRowIndex]);
    }
    setValue(index, value) {
        return this[standalone_kParent].getChildAt(index).set(this[standalone_kRowIndex], value);
    }
}
Object.setPrototypeOf(standalone_row_Row.prototype, Map.prototype);
/** @ignore */
const standalone_defineRowProxyProperties = (() => {
    const desc = { enumerable: true, configurable: false, get: null, set: null };
    return (row) => {
        let idx = -1, ktoi = row[standalone_kKeyToIdx] || (row[standalone_kKeyToIdx] = new Map());
        const getter = (key) => function () { return this.get(key); };
        const setter = (key) => function (val) { return this.set(key, val); };
        for (const key of row.keys()) {
            ktoi.set(key, ++idx);
            desc.get = getter(key);
            desc.set = setter(key);
            row.hasOwnProperty(key) || (desc.enumerable = true, Object.defineProperty(row, key, desc));
            row.hasOwnProperty(idx) || (desc.enumerable = false, Object.defineProperty(row, idx, desc));
        }
        desc.get = desc.set = null;
        return row;
    };
})();
/** @ignore */
const standalone_createRowProxy = (() => {
    if (typeof Proxy === 'undefined') {
        return standalone_defineRowProxyProperties;
    }
    const has = standalone_row_Row.prototype.has;
    const get = standalone_row_Row.prototype.get;
    const set = standalone_row_Row.prototype.set;
    const getKey = standalone_row_Row.prototype.getKey;
    const RowProxyHandler = {
        isExtensible() { return false; },
        deleteProperty() { return false; },
        preventExtensions() { return true; },
        ownKeys(row) { return [...row.keys()].map((x) => `${x}`); },
        has(row, key) {
            switch (key) {
                case 'getKey':
                case 'getIndex':
                case 'getValue':
                case 'setValue':
                case 'toArray':
                case 'toJSON':
                case 'inspect':
                case 'constructor':
                case 'isPrototypeOf':
                case 'propertyIsEnumerable':
                case 'toString':
                case 'toLocaleString':
                case 'valueOf':
                case 'size':
                case 'has':
                case 'get':
                case 'set':
                case 'clear':
                case 'delete':
                case 'keys':
                case 'values':
                case 'entries':
                case 'forEach':
                case '__proto__':
                case '__defineGetter__':
                case '__defineSetter__':
                case 'hasOwnProperty':
                case '__lookupGetter__':
                case '__lookupSetter__':
                case Symbol.iterator:
                case Symbol.toStringTag:
                case standalone_kParent:
                case standalone_kRowIndex:
                case standalone_kIdxToVal:
                case standalone_kKeyToIdx:
                case standalone_kCustomInspect:
                    return true;
            }
            if (typeof key === 'number' && !row.has(key)) {
                key = row.getKey(key);
            }
            return row.has(key);
        },
        get(row, key, receiver) {
            switch (key) {
                case 'getKey':
                case 'getIndex':
                case 'getValue':
                case 'setValue':
                case 'toArray':
                case 'toJSON':
                case 'inspect':
                case 'constructor':
                case 'isPrototypeOf':
                case 'propertyIsEnumerable':
                case 'toString':
                case 'toLocaleString':
                case 'valueOf':
                case 'size':
                case 'has':
                case 'get':
                case 'set':
                case 'clear':
                case 'delete':
                case 'keys':
                case 'values':
                case 'entries':
                case 'forEach':
                case '__proto__':
                case '__defineGetter__':
                case '__defineSetter__':
                case 'hasOwnProperty':
                case '__lookupGetter__':
                case '__lookupSetter__':
                case Symbol.iterator:
                case Symbol.toStringTag:
                case standalone_kParent:
                case standalone_kRowIndex:
                case standalone_kIdxToVal:
                case standalone_kKeyToIdx:
                case standalone_kCustomInspect:
                    return Reflect.get(row, key, receiver);
            }
            if (typeof key === 'number' && !has.call(receiver, key)) {
                key = getKey.call(receiver, key);
            }
            return get.call(receiver, key);
        },
        set(row, key, val, receiver) {
            switch (key) {
                case standalone_kParent:
                case standalone_kRowIndex:
                case standalone_kIdxToVal:
                case standalone_kKeyToIdx:
                    return Reflect.set(row, key, val, receiver);
                case 'getKey':
                case 'getIndex':
                case 'getValue':
                case 'setValue':
                case 'toArray':
                case 'toJSON':
                case 'inspect':
                case 'constructor':
                case 'isPrototypeOf':
                case 'propertyIsEnumerable':
                case 'toString':
                case 'toLocaleString':
                case 'valueOf':
                case 'size':
                case 'has':
                case 'get':
                case 'set':
                case 'clear':
                case 'delete':
                case 'keys':
                case 'values':
                case 'entries':
                case 'forEach':
                case '__proto__':
                case '__defineGetter__':
                case '__defineSetter__':
                case 'hasOwnProperty':
                case '__lookupGetter__':
                case '__lookupSetter__':
                case Symbol.iterator:
                case Symbol.toStringTag:
                    return false;
            }
            if (typeof key === 'number' && !has.call(receiver, key)) {
                key = getKey.call(receiver, key);
            }
            return has.call(receiver, key) ? !!set.call(receiver, key, val) : false;
        },
    };
    return (row) => new Proxy(row, RowProxyHandler);
})();

//# sourceMappingURL=row.mjs.map

;// ../../node_modules/apache-arrow/util/vector.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
function standalone_clampIndex(source, index, then) {
    const length = source.length;
    const adjust = index > -1 ? index : (length + (index % length));
    return then ? then(source, adjust) : adjust;
}
/** @ignore */
let standalone_tmp;
/** @ignore */
function standalone_vector_clampRange(source, begin, end, then) {
    // Adjust args similar to Array.prototype.slice. Normalize begin/end to
    // clamp between 0 and length, and wrap around on negative indices, e.g.
    // slice(-1, 5) or slice(5, -1)
    let { length: len = 0 } = source;
    let lhs = typeof begin !== 'number' ? 0 : begin;
    let rhs = typeof end !== 'number' ? len : end;
    // wrap around on negative start/end positions
    (lhs < 0) && (lhs = ((lhs % len) + len) % len);
    (rhs < 0) && (rhs = ((rhs % len) + len) % len);
    // ensure lhs <= rhs
    (rhs < lhs) && (standalone_tmp = lhs, lhs = rhs, rhs = standalone_tmp);
    // ensure rhs <= length
    (rhs > len) && (rhs = len);
    return then ? then(source, lhs, rhs) : [lhs, rhs];
}
const standalone_big0 = standalone_BigIntAvailable ? standalone_BigIntCtor(0) : 0;
const standalone_isNaNFast = (value) => value !== value;
/** @ignore */
function standalone_createElementComparator(search) {
    let typeofSearch = typeof search;
    // Compare primitives
    if (typeofSearch !== 'object' || search === null) {
        // Compare NaN
        if (standalone_isNaNFast(search)) {
            return standalone_isNaNFast;
        }
        return typeofSearch !== 'bigint'
            ? (value) => value === search
            : (value) => (standalone_big0 + value) === search;
    }
    // Compare Dates
    if (search instanceof Date) {
        const valueOfSearch = search.valueOf();
        return (value) => value instanceof Date ? (value.valueOf() === valueOfSearch) : false;
    }
    // Compare TypedArrays
    if (ArrayBuffer.isView(search)) {
        return (value) => value ? standalone_compareArrayLike(search, value) : false;
    }
    // Compare Maps and Rows
    if (search instanceof Map) {
        return standalone_creatMapComparator(search);
    }
    // Compare Array-likes
    if (Array.isArray(search)) {
        return standalone_createArrayLikeComparator(search);
    }
    // Compare Vectors
    if (search instanceof standalone_AbstractVector) {
        return standalone_createVectorComparator(search);
    }
    // Compare non-empty Objects
    return standalone_createObjectComparator(search);
}
/** @ignore */
function standalone_createArrayLikeComparator(lhs) {
    const comparators = [];
    for (let i = -1, n = lhs.length; ++i < n;) {
        comparators[i] = standalone_createElementComparator(lhs[i]);
    }
    return standalone_createSubElementsComparator(comparators);
}
/** @ignore */
function standalone_creatMapComparator(lhs) {
    let i = -1;
    const comparators = [];
    lhs.forEach((v) => comparators[++i] = standalone_createElementComparator(v));
    return standalone_createSubElementsComparator(comparators);
}
/** @ignore */
function standalone_createVectorComparator(lhs) {
    const comparators = [];
    for (let i = -1, n = lhs.length; ++i < n;) {
        comparators[i] = standalone_createElementComparator(lhs.get(i));
    }
    return standalone_createSubElementsComparator(comparators);
}
/** @ignore */
function standalone_createObjectComparator(lhs) {
    const keys = Object.keys(lhs);
    // Only compare non-empty Objects
    if (keys.length === 0) {
        return () => false;
    }
    const comparators = [];
    for (let i = -1, n = keys.length; ++i < n;) {
        comparators[i] = standalone_createElementComparator(lhs[keys[i]]);
    }
    return standalone_createSubElementsComparator(comparators, keys);
}
function standalone_createSubElementsComparator(comparators, keys) {
    return (rhs) => {
        if (!rhs || typeof rhs !== 'object') {
            return false;
        }
        switch (rhs.constructor) {
            case Array: return standalone_compareArray(comparators, rhs);
            case Map:
            case standalone_MapRow:
            case standalone_StructRow:
                return standalone_compareObject(comparators, rhs, rhs.keys());
            case Object:
            case undefined: // support `Object.create(null)` objects
                return standalone_compareObject(comparators, rhs, keys || Object.keys(rhs));
        }
        return rhs instanceof standalone_AbstractVector ? standalone_compareVector(comparators, rhs) : false;
    };
}
function standalone_compareArray(comparators, arr) {
    const n = comparators.length;
    if (arr.length !== n) {
        return false;
    }
    for (let i = -1; ++i < n;) {
        if (!(comparators[i](arr[i]))) {
            return false;
        }
    }
    return true;
}
function standalone_compareVector(comparators, vec) {
    const n = comparators.length;
    if (vec.length !== n) {
        return false;
    }
    for (let i = -1; ++i < n;) {
        if (!(comparators[i](vec.get(i)))) {
            return false;
        }
    }
    return true;
}
function standalone_compareObject(comparators, obj, keys) {
    const lKeyItr = keys[Symbol.iterator]();
    const rKeyItr = obj instanceof Map ? obj.keys() : Object.keys(obj)[Symbol.iterator]();
    const rValItr = obj instanceof Map ? obj.values() : Object.values(obj)[Symbol.iterator]();
    let i = 0;
    let n = comparators.length;
    let rVal = rValItr.next();
    let lKey = lKeyItr.next();
    let rKey = rKeyItr.next();
    for (; i < n && !lKey.done && !rKey.done && !rVal.done; ++i, lKey = lKeyItr.next(), rKey = rKeyItr.next(), rVal = rValItr.next()) {
        if (lKey.value !== rKey.value || !comparators[i](rVal.value)) {
            break;
        }
    }
    if (i === n && lKey.done && rKey.done && rVal.done) {
        return true;
    }
    lKeyItr.return && lKeyItr.return();
    rKeyItr.return && rKeyItr.return();
    rValItr.return && rValItr.return();
    return false;
}

//# sourceMappingURL=vector.mjs.map

;// ../../node_modules/apache-arrow/vector/chunked.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
class standalone_Chunked extends standalone_AbstractVector {
    constructor(type, chunks = [], offsets = standalone_calculateOffsets(chunks)) {
        super();
        this._nullCount = -1;
        this._type = type;
        this._chunks = chunks;
        this._chunkOffsets = offsets;
        this._length = offsets[offsets.length - 1];
        this._numChildren = (this._type.children || []).length;
    }
    /** @nocollapse */
    static flatten(...vectors) {
        return standalone_selectChunkArgs(standalone_AbstractVector, vectors);
    }
    /** @nocollapse */
    static concat(...vectors) {
        const chunks = standalone_Chunked.flatten(...vectors);
        return new standalone_Chunked(chunks[0].type, chunks);
    }
    get type() { return this._type; }
    get length() { return this._length; }
    get chunks() { return this._chunks; }
    get typeId() { return this._type.typeId; }
    get VectorName() { return `Chunked<${this._type}>`; }
    get data() {
        return this._chunks[0] ? this._chunks[0].data : null;
    }
    get ArrayType() { return this._type.ArrayType; }
    get numChildren() { return this._numChildren; }
    get stride() { return this._chunks[0] ? this._chunks[0].stride : 1; }
    get byteLength() {
        return this._chunks.reduce((byteLength, chunk) => byteLength + chunk.byteLength, 0);
    }
    get nullCount() {
        let nullCount = this._nullCount;
        if (nullCount < 0) {
            this._nullCount = nullCount = this._chunks.reduce((x, { nullCount }) => x + nullCount, 0);
        }
        return nullCount;
    }
    get indices() {
        if (standalone_DataType.isDictionary(this._type)) {
            if (!this._indices) {
                const chunks = this._chunks;
                this._indices = (chunks.length === 1
                    ? chunks[0].indices
                    : standalone_Chunked.concat(...chunks.map((x) => x.indices)));
            }
            return this._indices;
        }
        return null;
    }
    get dictionary() {
        if (standalone_DataType.isDictionary(this._type)) {
            return this._chunks[this._chunks.length - 1].data.dictionary;
        }
        return null;
    }
    *[Symbol.iterator]() {
        for (const chunk of this._chunks) {
            yield* chunk;
        }
    }
    clone(chunks = this._chunks) {
        return new standalone_Chunked(this._type, chunks);
    }
    concat(...others) {
        return this.clone(standalone_Chunked.flatten(this, ...others));
    }
    slice(begin, end) {
        return standalone_vector_clampRange(this, begin, end, this._sliceInternal);
    }
    getChildAt(index) {
        if (index < 0 || index >= this._numChildren) {
            return null;
        }
        let columns = this._children || (this._children = []);
        let child, field, chunks;
        if (child = columns[index]) {
            return child;
        }
        if (field = (this._type.children || [])[index]) {
            chunks = this._chunks
                .map((vector) => vector.getChildAt(index))
                .filter((vec) => vec != null);
            if (chunks.length > 0) {
                return (columns[index] = new standalone_Chunked(field.type, chunks));
            }
        }
        return null;
    }
    search(index, then) {
        let idx = index;
        // binary search to find the child vector and value indices
        let offsets = this._chunkOffsets, rhs = offsets.length - 1;
        // return early if out of bounds, or if there's just one child
        if (idx < 0) {
            return null;
        }
        if (idx >= offsets[rhs]) {
            return null;
        }
        if (rhs <= 1) {
            return then ? then(this, 0, idx) : [0, idx];
        }
        let lhs = 0, pos = 0, mid = 0;
        do {
            if (lhs + 1 === rhs) {
                return then ? then(this, lhs, idx - pos) : [lhs, idx - pos];
            }
            mid = lhs + ((rhs - lhs) / 2) | 0;
            idx >= offsets[mid] ? (lhs = mid) : (rhs = mid);
        } while (idx < offsets[rhs] && idx >= (pos = offsets[lhs]));
        return null;
    }
    isValid(index) {
        return !!this.search(index, this.isValidInternal);
    }
    get(index) {
        return this.search(index, this.getInternal);
    }
    set(index, value) {
        this.search(index, ({ chunks }, i, j) => chunks[i].set(j, value));
    }
    indexOf(element, offset) {
        if (offset && typeof offset === 'number') {
            return this.search(offset, (self, i, j) => this.indexOfInternal(self, i, j, element));
        }
        return this.indexOfInternal(this, 0, Math.max(0, offset || 0), element);
    }
    toArray() {
        const { chunks } = this;
        const n = chunks.length;
        let ArrayType = this._type.ArrayType;
        if (n <= 0) {
            return new ArrayType(0);
        }
        if (n <= 1) {
            return chunks[0].toArray();
        }
        let len = 0, src = new Array(n);
        for (let i = -1; ++i < n;) {
            len += (src[i] = chunks[i].toArray()).length;
        }
        if (ArrayType !== src[0].constructor) {
            ArrayType = src[0].constructor;
        }
        let dst = new ArrayType(len);
        let set = ArrayType === Array ? standalone_arraySet : standalone_typedSet;
        for (let i = -1, idx = 0; ++i < n;) {
            idx = set(src[i], dst, idx);
        }
        return dst;
    }
    getInternal({ _chunks }, i, j) { return _chunks[i].get(j); }
    isValidInternal({ _chunks }, i, j) { return _chunks[i].isValid(j); }
    indexOfInternal({ _chunks }, chunkIndex, fromIndex, element) {
        let i = chunkIndex - 1, n = _chunks.length;
        let start = fromIndex, offset = 0, found = -1;
        while (++i < n) {
            if (~(found = _chunks[i].indexOf(element, start))) {
                return offset + found;
            }
            start = 0;
            offset += _chunks[i].length;
        }
        return -1;
    }
    _sliceInternal(self, begin, end) {
        const slices = [];
        const { chunks, _chunkOffsets: chunkOffsets } = self;
        for (let i = -1, n = chunks.length; ++i < n;) {
            const chunk = chunks[i];
            const chunkLength = chunk.length;
            const chunkOffset = chunkOffsets[i];
            // If the child is to the right of the slice boundary, we can stop
            if (chunkOffset >= end) {
                break;
            }
            // If the child is to the left of of the slice boundary, exclude
            if (begin >= chunkOffset + chunkLength) {
                continue;
            }
            // If the child is between both left and right boundaries, include w/o slicing
            if (chunkOffset >= begin && (chunkOffset + chunkLength) <= end) {
                slices.push(chunk);
                continue;
            }
            // If the child overlaps one of the slice boundaries, include that slice
            const from = Math.max(0, begin - chunkOffset);
            const to = Math.min(end - chunkOffset, chunkLength);
            slices.push(chunk.slice(from, to));
        }
        return self.clone(slices);
    }
}
/** @ignore */
function standalone_calculateOffsets(vectors) {
    let offsets = new Uint32Array((vectors || []).length + 1);
    let offset = offsets[0] = 0, length = offsets.length;
    for (let index = 0; ++index < length;) {
        offsets[index] = (offset += vectors[index - 1].length);
    }
    return offsets;
}
/** @ignore */
const standalone_typedSet = (src, dst, offset) => {
    dst.set(src, offset);
    return (offset + src.length);
};
/** @ignore */
const standalone_arraySet = (src, dst, offset) => {
    let idx = offset;
    for (let i = -1, n = src.length; ++i < n;) {
        dst[idx++] = src[i];
    }
    return idx;
};

//# sourceMappingURL=chunked.mjs.map

;// ../../node_modules/apache-arrow/column.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.



class standalone_apache_arrow_column_Column extends standalone_Chunked {
    constructor(field, vectors = [], offsets) {
        vectors = standalone_Chunked.flatten(...vectors);
        super(field.type, vectors, offsets);
        this._field = field;
        if (vectors.length === 1 && !(this instanceof standalone_SingleChunkColumn)) {
            return new standalone_SingleChunkColumn(field, vectors[0], this._chunkOffsets);
        }
    }
    /** @nocollapse */
    static new(...args) {
        let [field, data, ...rest] = args;
        if (typeof field !== 'string' && !(field instanceof standalone_schema_Field)) {
            data = field;
            field = '';
        }
        const chunks = standalone_Chunked.flatten(Array.isArray(data) ? [...data, ...rest] :
            data instanceof standalone_AbstractVector ? [data, ...rest] :
                [standalone_AbstractVector.new(data, ...rest)]);
        if (typeof field === 'string') {
            const type = chunks[0].data.type;
            field = new standalone_schema_Field(field, type, true);
        }
        else if (!field.nullable && chunks.some(({ nullCount }) => nullCount > 0)) {
            field = field.clone({ nullable: true });
        }
        return new standalone_apache_arrow_column_Column(field, chunks);
    }
    get field() { return this._field; }
    get name() { return this._field.name; }
    get nullable() { return this._field.nullable; }
    get metadata() { return this._field.metadata; }
    clone(chunks = this._chunks) {
        return new standalone_apache_arrow_column_Column(this._field, chunks);
    }
    getChildAt(index) {
        if (index < 0 || index >= this.numChildren) {
            return null;
        }
        let columns = this._children || (this._children = []);
        let column, field, chunks;
        if (column = columns[index]) {
            return column;
        }
        if (field = (this.type.children || [])[index]) {
            chunks = this._chunks
                .map((vector) => vector.getChildAt(index))
                .filter((vec) => vec != null);
            if (chunks.length > 0) {
                return (columns[index] = new standalone_apache_arrow_column_Column(field, chunks));
            }
        }
        return null;
    }
}
/** @ignore */
class standalone_SingleChunkColumn extends standalone_apache_arrow_column_Column {
    constructor(field, vector, offsets) {
        super(field, [vector], offsets);
        this._chunk = vector;
    }
    search(index, then) {
        return then ? then(this, 0, index) : [0, index];
    }
    isValid(index) {
        return this._chunk.isValid(index);
    }
    get(index) {
        return this._chunk.get(index);
    }
    set(index, value) {
        this._chunk.set(index, value);
    }
    indexOf(element, offset) {
        return this._chunk.indexOf(element, offset);
    }
}

//# sourceMappingURL=column.mjs.map

;// ../../node_modules/apache-arrow/util/args.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.






const standalone_args_isArray = Array.isArray;
/** @ignore */
const standalone_selectArgs = (Ctor, vals) => src_standalone_selectArgs(Ctor, vals, [], 0);
/** @ignore */
const standalone_selectColumnArgs = (args) => {
    const [fields, values] = src_standalone_selectFieldArgs(args, [[], []]);
    return values.map((x, i) => x instanceof standalone_apache_arrow_column_Column ? standalone_apache_arrow_column_Column.new(x.field.clone(fields[i]), x) :
        x instanceof standalone_AbstractVector ? standalone_apache_arrow_column_Column.new(fields[i], x) :
            standalone_apache_arrow_column_Column.new(fields[i], []));
};
/** @ignore */
const standalone_selectFieldArgs = (args) => src_standalone_selectFieldArgs(args, [[], []]);
/** @ignore */
const standalone_selectChunkArgs = (Ctor, vals) => src_standalone_selectChunkArgs(Ctor, vals, [], 0);
/** @ignore */
const standalone_selectVectorChildrenArgs = (Ctor, vals) => src_standalone_selectVectorChildrenArgs(Ctor, vals, [], 0);
/** @ignore */
const standalone_selectColumnChildrenArgs = (Ctor, vals) => src_standalone_selectColumnChildrenArgs(Ctor, vals, [], 0);
/** @ignore */
function src_standalone_selectArgs(Ctor, vals, res, idx) {
    let value, j = idx;
    let i = -1, n = vals.length;
    while (++i < n) {
        if (standalone_args_isArray(value = vals[i])) {
            j = src_standalone_selectArgs(Ctor, value, res, j).length;
        }
        else if (value instanceof Ctor) {
            res[j++] = value;
        }
    }
    return res;
}
/** @ignore */
function src_standalone_selectChunkArgs(Ctor, vals, res, idx) {
    let value, j = idx;
    let i = -1, n = vals.length;
    while (++i < n) {
        if (standalone_args_isArray(value = vals[i])) {
            j = src_standalone_selectChunkArgs(Ctor, value, res, j).length;
        }
        else if (value instanceof standalone_Chunked) {
            j = src_standalone_selectChunkArgs(Ctor, value.chunks, res, j).length;
        }
        else if (value instanceof Ctor) {
            res[j++] = value;
        }
    }
    return res;
}
/** @ignore */
function src_standalone_selectVectorChildrenArgs(Ctor, vals, res, idx) {
    let value, j = idx;
    let i = -1, n = vals.length;
    while (++i < n) {
        if (standalone_args_isArray(value = vals[i])) {
            j = src_standalone_selectVectorChildrenArgs(Ctor, value, res, j).length;
        }
        else if (value instanceof Ctor) {
            j = src_standalone_selectArgs(standalone_AbstractVector, value.schema.fields.map((_, i) => value.getChildAt(i)), res, j).length;
        }
        else if (value instanceof standalone_AbstractVector) {
            res[j++] = value;
        }
    }
    return res;
}
/** @ignore */
function src_standalone_selectColumnChildrenArgs(Ctor, vals, res, idx) {
    let value, j = idx;
    let i = -1, n = vals.length;
    while (++i < n) {
        if (standalone_args_isArray(value = vals[i])) {
            j = src_standalone_selectColumnChildrenArgs(Ctor, value, res, j).length;
        }
        else if (value instanceof Ctor) {
            j = src_standalone_selectArgs(standalone_apache_arrow_column_Column, value.schema.fields.map((f, i) => standalone_apache_arrow_column_Column.new(f, value.getChildAt(i))), res, j).length;
        }
        else if (value instanceof standalone_apache_arrow_column_Column) {
            res[j++] = value;
        }
    }
    return res;
}
/** @ignore */
const standalone_toKeysAndValues = (xs, [k, v], i) => (xs[0][i] = k, xs[1][i] = v, xs);
/** @ignore */
function src_standalone_selectFieldArgs(vals, ret) {
    let keys, n;
    switch (n = vals.length) {
        case 0: return ret;
        case 1:
            keys = ret[0];
            if (!(vals[0])) {
                return ret;
            }
            if (standalone_args_isArray(vals[0])) {
                return src_standalone_selectFieldArgs(vals[0], ret);
            }
            if (!(vals[0] instanceof standalone_Data || vals[0] instanceof standalone_AbstractVector || vals[0] instanceof standalone_DataType)) {
                [keys, vals] = Object.entries(vals[0]).reduce(standalone_toKeysAndValues, ret);
            }
            break;
        default:
            !standalone_args_isArray(keys = vals[n - 1])
                ? (vals = standalone_args_isArray(vals[0]) ? vals[0] : vals, keys = [])
                : (vals = standalone_args_isArray(vals[0]) ? vals[0] : vals.slice(0, n - 1));
    }
    let fieldIndex = -1;
    let valueIndex = -1;
    let idx = -1, len = vals.length;
    let field;
    let val;
    let [fields, values] = ret;
    while (++idx < len) {
        val = vals[idx];
        if (val instanceof standalone_apache_arrow_column_Column && (values[++valueIndex] = val)) {
            fields[++fieldIndex] = val.field.clone(keys[idx], val.type, true);
        }
        else {
            ({ [idx]: field = idx } = keys);
            if (val instanceof standalone_DataType && (values[++valueIndex] = val)) {
                fields[++fieldIndex] = standalone_schema_Field.new(field, val, true);
            }
            else if (val && val.type && (values[++valueIndex] = val)) {
                val instanceof standalone_Data && (values[valueIndex] = val = standalone_AbstractVector.new(val));
                fields[++fieldIndex] = standalone_schema_Field.new(field, val.type, true);
            }
        }
    }
    return ret;
}

//# sourceMappingURL=args.mjs.map

;// ../../node_modules/apache-arrow/schema.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




class standalone_Schema {
    constructor(fields = [], metadata, dictionaries) {
        this.fields = (fields || []);
        this.metadata = metadata || new Map();
        if (!dictionaries) {
            dictionaries = standalone_generateDictionaryMap(fields);
        }
        this.dictionaries = dictionaries;
    }
    /** @nocollapse */
    static from(...args) {
        return standalone_Schema.new(args[0], args[1]);
    }
    /** @nocollapse */
    static new(...args) {
        return new standalone_Schema(standalone_selectFieldArgs(args)[0]);
    }
    get [Symbol.toStringTag]() { return 'Schema'; }
    toString() {
        return `Schema<{ ${this.fields.map((f, i) => `${i}: ${f}`).join(', ')} }>`;
    }
    compareTo(other) {
        return standalone_typecomparator_instance.compareSchemas(this, other);
    }
    select(...columnNames) {
        const names = columnNames.reduce((xs, x) => (xs[x] = true) && xs, Object.create(null));
        return new standalone_Schema(this.fields.filter((f) => names[f.name]), this.metadata);
    }
    selectAt(...columnIndices) {
        return new standalone_Schema(columnIndices.map((i) => this.fields[i]).filter(Boolean), this.metadata);
    }
    assign(...args) {
        const other = args[0] instanceof standalone_Schema ? args[0]
            : new standalone_Schema(standalone_selectArgs(standalone_schema_Field, args));
        const curFields = [...this.fields];
        const metadata = standalone_mergeMaps(standalone_mergeMaps(new Map(), this.metadata), other.metadata);
        const newFields = other.fields.filter((f2) => {
            const i = curFields.findIndex((f) => f.name === f2.name);
            return ~i ? (curFields[i] = f2.clone({
                metadata: standalone_mergeMaps(standalone_mergeMaps(new Map(), curFields[i].metadata), f2.metadata)
            })) && false : true;
        });
        const newDictionaries = standalone_generateDictionaryMap(newFields, new Map());
        return new standalone_Schema([...curFields, ...newFields], metadata, new Map([...this.dictionaries, ...newDictionaries]));
    }
}
class standalone_schema_Field {
    constructor(name, type, nullable = false, metadata) {
        this.name = name;
        this.type = type;
        this.nullable = nullable;
        this.metadata = metadata || new Map();
    }
    /** @nocollapse */
    static new(...args) {
        let [name, type, nullable, metadata] = args;
        if (args[0] && typeof args[0] === 'object') {
            ({ name } = args[0]);
            (type === undefined) && (type = args[0].type);
            (nullable === undefined) && (nullable = args[0].nullable);
            (metadata === undefined) && (metadata = args[0].metadata);
        }
        return new standalone_schema_Field(`${name}`, type, nullable, metadata);
    }
    get typeId() { return this.type.typeId; }
    get [Symbol.toStringTag]() { return 'Field'; }
    toString() { return `${this.name}: ${this.type}`; }
    compareTo(other) {
        return standalone_typecomparator_instance.compareField(this, other);
    }
    clone(...args) {
        let [name, type, nullable, metadata] = args;
        (!args[0] || typeof args[0] !== 'object')
            ? ([name = this.name, type = this.type, nullable = this.nullable, metadata = this.metadata] = args)
            : ({ name = this.name, type = this.type, nullable = this.nullable, metadata = this.metadata } = args[0]);
        return standalone_schema_Field.new(name, type, nullable, metadata);
    }
}
/** @ignore */
function standalone_mergeMaps(m1, m2) {
    return new Map([...(m1 || new Map()), ...(m2 || new Map())]);
}
/** @ignore */
function standalone_generateDictionaryMap(fields, dictionaries = new Map()) {
    for (let i = -1, n = fields.length; ++i < n;) {
        const field = fields[i];
        const type = field.type;
        if (standalone_DataType.isDictionary(type)) {
            if (!dictionaries.has(type.id)) {
                dictionaries.set(type.id, type.dictionary);
            }
            else if (dictionaries.get(type.id) !== type.dictionary) {
                throw new Error(`Cannot create Schema containing two different dictionaries with the same Id`);
            }
        }
        if (type.children && type.children.length > 0) {
            standalone_generateDictionaryMap(type.children, dictionaries);
        }
    }
    return dictionaries;
}
// Add these here so they're picked up by the externs creator
// in the build, and closure-compiler doesn't minify them away
standalone_Schema.prototype.fields = null;
standalone_Schema.prototype.metadata = null;
standalone_Schema.prototype.dictionaries = null;
standalone_schema_Field.prototype.type = null;
standalone_schema_Field.prototype.name = null;
standalone_schema_Field.prototype.nullable = null;
standalone_schema_Field.prototype.metadata = null;

//# sourceMappingURL=schema.mjs.map

;// ../../node_modules/apache-arrow/builder/list.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.





/** @ignore */
class standalone_ListBuilder extends standalone_VariableWidthBuilder {
    constructor(opts) {
        super(opts);
        this._run = new standalone_Run();
        this._offsets = new standalone_OffsetsBufferBuilder();
    }
    addChild(child, name = '0') {
        if (this.numChildren > 0) {
            throw new Error('ListBuilder can only have one child.');
        }
        this.children[this.numChildren] = child;
        this.type = new standalone_List(new standalone_schema_Field(name, child.type, true));
        return this.numChildren - 1;
    }
    clear() {
        this._run.clear();
        return super.clear();
    }
    _flushPending(pending) {
        const run = this._run;
        const offsets = this._offsets;
        const setValue = this._setValue;
        let index = 0, value;
        for ([index, value] of pending) {
            if (value === undefined) {
                offsets.set(index, 0);
            }
            else {
                offsets.set(index, value.length);
                setValue(this, index, run.bind(value));
            }
        }
    }
}

//# sourceMappingURL=list.mjs.map

;// ../../node_modules/apache-arrow/builder/fixedsizelist.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
class standalone_FixedSizeListBuilder extends standalone_Builder {
    constructor() {
        super(...arguments);
        this._run = new standalone_Run();
    }
    setValue(index, value) {
        super.setValue(index, this._run.bind(value));
    }
    addChild(child, name = '0') {
        if (this.numChildren > 0) {
            throw new Error('FixedSizeListBuilder can only have one child.');
        }
        const childIndex = this.children.push(child);
        this.type = new standalone_FixedSizeList(this.type.listSize, new standalone_schema_Field(name, child.type, true));
        return childIndex;
    }
    clear() {
        this._run.clear();
        return super.clear();
    }
}

//# sourceMappingURL=fixedsizelist.mjs.map

;// ../../node_modules/apache-arrow/builder/map.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.



/** @ignore */
class standalone_MapBuilder extends standalone_VariableWidthBuilder {
    set(index, value) {
        return super.set(index, value);
    }
    setValue(index, value) {
        value = value instanceof Map ? value : new Map(Object.entries(value));
        const pending = this._pending || (this._pending = new Map());
        const current = pending.get(index);
        current && (this._pendingLength -= current.size);
        this._pendingLength += value.size;
        pending.set(index, value);
    }
    addChild(child, name = `${this.numChildren}`) {
        if (this.numChildren > 0) {
            throw new Error('ListBuilder can only have one child.');
        }
        this.children[this.numChildren] = child;
        this.type = new standalone_Map_(new standalone_schema_Field(name, child.type, true), this.type.keysSorted);
        return this.numChildren - 1;
    }
    _flushPending(pending) {
        const offsets = this._offsets;
        const setValue = this._setValue;
        pending.forEach((value, index) => {
            if (value === undefined) {
                offsets.set(index, 0);
            }
            else {
                offsets.set(index, value.size);
                setValue(this, index, value);
            }
        });
    }
}

//# sourceMappingURL=map.mjs.map

;// ../../node_modules/apache-arrow/builder/struct.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.



/** @ignore */
class standalone_StructBuilder extends standalone_Builder {
    addChild(child, name = `${this.numChildren}`) {
        const childIndex = this.children.push(child);
        this.type = new standalone_Struct([...this.type.children, new standalone_schema_Field(name, child.type, true)]);
        return childIndex;
    }
}

//# sourceMappingURL=struct.mjs.map

;// ../../node_modules/apache-arrow/builder/union.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
class standalone_UnionBuilder extends standalone_Builder {
    constructor(options) {
        super(options);
        this._typeIds = new standalone_DataBufferBuilder(new Int8Array(0), 1);
        if (typeof options['valueToChildTypeId'] === 'function') {
            this._valueToChildTypeId = options['valueToChildTypeId'];
        }
    }
    get typeIdToChildIndex() { return this.type.typeIdToChildIndex; }
    append(value, childTypeId) {
        return this.set(this.length, value, childTypeId);
    }
    set(index, value, childTypeId) {
        if (childTypeId === undefined) {
            childTypeId = this._valueToChildTypeId(this, value, index);
        }
        if (this.setValid(index, this.isValid(value))) {
            this.setValue(index, value, childTypeId);
        }
        return this;
    }
    // @ts-ignore
    setValue(index, value, childTypeId) {
        this._typeIds.set(index, childTypeId);
        super.setValue(index, value);
    }
    // @ts-ignore
    addChild(child, name = `${this.children.length}`) {
        const childTypeId = this.children.push(child);
        const { type: { children, mode, typeIds } } = this;
        const fields = [...children, new standalone_schema_Field(name, child.type)];
        this.type = new standalone_Union_(mode, [...typeIds, childTypeId], fields);
        return childTypeId;
    }
    /** @ignore */
    // @ts-ignore
    _valueToChildTypeId(builder, value, offset) {
        throw new Error(`Cannot map UnionBuilder value to child typeId. \
Pass the \`childTypeId\` as the second argument to unionBuilder.append(), \
or supply a \`valueToChildTypeId\` function as part of the UnionBuilder constructor options.`);
    }
}
/** @ignore */
class standalone_SparseUnionBuilder extends standalone_UnionBuilder {
}
/** @ignore */
class standalone_DenseUnionBuilder extends standalone_UnionBuilder {
    constructor(options) {
        super(options);
        this._offsets = new standalone_DataBufferBuilder(new Int32Array(0));
    }
    /** @ignore */
    setValue(index, value, childTypeId) {
        const childIndex = this.type.typeIdToChildIndex[childTypeId];
        this._offsets.set(index, this.getChildAt(childIndex).length);
        return super.setValue(index, value, childTypeId);
    }
}

//# sourceMappingURL=union.mjs.map

;// ../../node_modules/apache-arrow/visitor/set.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.






/** @ignore */
class standalone_SetVisitor extends standalone_Visitor {
}
/** @ignore */
const standalone_setEpochMsToDays = (data, index, epochMs) => { data[index] = (epochMs / 86400000) | 0; };
/** @ignore */
const standalone_setEpochMsToMillisecondsLong = (data, index, epochMs) => {
    data[index] = (epochMs % 4294967296) | 0;
    data[index + 1] = (epochMs / 4294967296) | 0;
};
/** @ignore */
const standalone_setEpochMsToMicrosecondsLong = (data, index, epochMs) => {
    data[index] = ((epochMs * 1000) % 4294967296) | 0;
    data[index + 1] = ((epochMs * 1000) / 4294967296) | 0;
};
/** @ignore */
const standalone_setEpochMsToNanosecondsLong = (data, index, epochMs) => {
    data[index] = ((epochMs * 1000000) % 4294967296) | 0;
    data[index + 1] = ((epochMs * 1000000) / 4294967296) | 0;
};
/** @ignore */
const standalone_setVariableWidthBytes = (values, valueOffsets, index, value) => {
    const { [index]: x, [index + 1]: y } = valueOffsets;
    if (x != null && y != null) {
        values.set(value.subarray(0, y - x), x);
    }
};
/** @ignore */
const standalone_set_setBool = ({ offset, values }, index, val) => {
    const idx = offset + index;
    val ? (values[idx >> 3] |= (1 << (idx % 8))) // true
        : (values[idx >> 3] &= ~(1 << (idx % 8))); // false
};
/** @ignore */
const standalone_setDateDay = ({ values }, index, value) => { standalone_setEpochMsToDays(values, index, value.valueOf()); };
/** @ignore */
const standalone_setDateMillisecond = ({ values }, index, value) => { standalone_setEpochMsToMillisecondsLong(values, index * 2, value.valueOf()); };
/** @ignore */
const standalone_setNumeric = ({ stride, values }, index, value) => { values[stride * index] = value; };
/** @ignore */
const standalone_setFloat16 = ({ stride, values }, index, value) => { values[stride * index] = standalone_float64ToUint16(value); };
/** @ignore */
const standalone_setNumericX2 = (vector, index, value) => {
    switch (typeof value) {
        case 'bigint':
            vector.values64[index] = value;
            break;
        case 'number':
            vector.values[index * vector.stride] = value;
            break;
        default:
            const val = value;
            const { stride, ArrayType } = vector;
            const long = standalone_toArrayBufferView(ArrayType, val);
            vector.values.set(long.subarray(0, stride), stride * index);
    }
};
/** @ignore */
const standalone_setFixedSizeBinary = ({ stride, values }, index, value) => { values.set(value.subarray(0, stride), stride * index); };
/** @ignore */
const standalone_setBinary = ({ values, valueOffsets }, index, value) => standalone_setVariableWidthBytes(values, valueOffsets, index, value);
/** @ignore */
const standalone_setUtf8 = ({ values, valueOffsets }, index, value) => {
    standalone_setVariableWidthBytes(values, valueOffsets, index, standalone_encodeUtf8(value));
};
/* istanbul ignore next */
/** @ignore */
const standalone_setInt = (vector, index, value) => {
    vector.type.bitWidth < 64
        ? standalone_setNumeric(vector, index, value)
        : standalone_setNumericX2(vector, index, value);
};
/* istanbul ignore next */
/** @ignore */
const standalone_setFloat = (vector, index, value) => {
    vector.type.precision !== standalone_Precision.HALF
        ? standalone_setNumeric(vector, index, value)
        : standalone_setFloat16(vector, index, value);
};
/* istanbul ignore next */
const standalone_setDate = (vector, index, value) => {
    vector.type.unit === standalone_DateUnit.DAY
        ? standalone_setDateDay(vector, index, value)
        : standalone_setDateMillisecond(vector, index, value);
};
/** @ignore */
const standalone_setTimestampSecond = ({ values }, index, value) => standalone_setEpochMsToMillisecondsLong(values, index * 2, value / 1000);
/** @ignore */
const standalone_setTimestampMillisecond = ({ values }, index, value) => standalone_setEpochMsToMillisecondsLong(values, index * 2, value);
/** @ignore */
const standalone_setTimestampMicrosecond = ({ values }, index, value) => standalone_setEpochMsToMicrosecondsLong(values, index * 2, value);
/** @ignore */
const standalone_setTimestampNanosecond = ({ values }, index, value) => standalone_setEpochMsToNanosecondsLong(values, index * 2, value);
/* istanbul ignore next */
/** @ignore */
const standalone_setTimestamp = (vector, index, value) => {
    switch (vector.type.unit) {
        case standalone_enum_TimeUnit.SECOND: return standalone_setTimestampSecond(vector, index, value);
        case standalone_enum_TimeUnit.MILLISECOND: return standalone_setTimestampMillisecond(vector, index, value);
        case standalone_enum_TimeUnit.MICROSECOND: return standalone_setTimestampMicrosecond(vector, index, value);
        case standalone_enum_TimeUnit.NANOSECOND: return standalone_setTimestampNanosecond(vector, index, value);
    }
};
/** @ignore */
const standalone_setTimeSecond = ({ values, stride }, index, value) => { values[stride * index] = value; };
/** @ignore */
const standalone_setTimeMillisecond = ({ values, stride }, index, value) => { values[stride * index] = value; };
/** @ignore */
const standalone_setTimeMicrosecond = ({ values }, index, value) => { values.set(value.subarray(0, 2), 2 * index); };
/** @ignore */
const standalone_setTimeNanosecond = ({ values }, index, value) => { values.set(value.subarray(0, 2), 2 * index); };
/* istanbul ignore next */
/** @ignore */
const standalone_setTime = (vector, index, value) => {
    switch (vector.type.unit) {
        case standalone_enum_TimeUnit.SECOND: return standalone_setTimeSecond(vector, index, value);
        case standalone_enum_TimeUnit.MILLISECOND: return standalone_setTimeMillisecond(vector, index, value);
        case standalone_enum_TimeUnit.MICROSECOND: return standalone_setTimeMicrosecond(vector, index, value);
        case standalone_enum_TimeUnit.NANOSECOND: return standalone_setTimeNanosecond(vector, index, value);
    }
};
/** @ignore */
const standalone_setDecimal = ({ values }, index, value) => { values.set(value.subarray(0, 4), 4 * index); };
/** @ignore */
const standalone_setList = (vector, index, value) => {
    const values = vector.getChildAt(0), valueOffsets = vector.valueOffsets;
    for (let idx = -1, itr = valueOffsets[index], end = valueOffsets[index + 1]; itr < end;) {
        values.set(itr++, value.get(++idx));
    }
};
/** @ignore */
const standalone_setMap = (vector, index, value) => {
    const values = vector.getChildAt(0), valueOffsets = vector.valueOffsets;
    const entries = value instanceof Map ? [...value] : Object.entries(value);
    for (let idx = -1, itr = valueOffsets[index], end = valueOffsets[index + 1]; itr < end;) {
        values.set(itr++, entries[++idx]);
    }
};
/** @ignore */ const standalone_setStructArrayValue = (o, v) => (c, _, i) => c && c.set(o, v[i]);
/** @ignore */ const standalone_setStructVectorValue = (o, v) => (c, _, i) => c && c.set(o, v.get(i));
/** @ignore */ const standalone_setStructMapValue = (o, v) => (c, f, _) => c && c.set(o, v.get(f.name));
/** @ignore */ const standalone_setStructObjectValue = (o, v) => (c, f, _) => c && c.set(o, v[f.name]);
/** @ignore */
const standalone_setStruct = (vector, index, value) => {
    const setValue = value instanceof Map ? standalone_setStructMapValue(index, value) :
        value instanceof standalone_AbstractVector ? standalone_setStructVectorValue(index, value) :
            Array.isArray(value) ? standalone_setStructArrayValue(index, value) :
                standalone_setStructObjectValue(index, value);
    vector.type.children.forEach((f, i) => setValue(vector.getChildAt(i), f, i));
};
/* istanbul ignore next */
/** @ignore */
const standalone_setUnion = (vector, index, value) => {
    vector.type.mode === standalone_UnionMode.Dense ?
        standalone_setDenseUnion(vector, index, value) :
        standalone_setSparseUnion(vector, index, value);
};
/** @ignore */
const standalone_setDenseUnion = (vector, index, value) => {
    const childIndex = vector.typeIdToChildIndex[vector.typeIds[index]];
    const child = vector.getChildAt(childIndex);
    child && child.set(vector.valueOffsets[index], value);
};
/** @ignore */
const standalone_setSparseUnion = (vector, index, value) => {
    const childIndex = vector.typeIdToChildIndex[vector.typeIds[index]];
    const child = vector.getChildAt(childIndex);
    child && child.set(index, value);
};
/** @ignore */
const standalone_setDictionary = (vector, index, value) => {
    const key = vector.getKey(index);
    if (key !== null) {
        vector.setValue(key, value);
    }
};
/* istanbul ignore next */
/** @ignore */
const standalone_setIntervalValue = (vector, index, value) => {
    (vector.type.unit === standalone_IntervalUnit.DAY_TIME)
        ? standalone_setIntervalDayTime(vector, index, value)
        : standalone_setIntervalYearMonth(vector, index, value);
};
/** @ignore */
const standalone_setIntervalDayTime = ({ values }, index, value) => { values.set(value.subarray(0, 2), 2 * index); };
/** @ignore */
const standalone_setIntervalYearMonth = ({ values }, index, value) => { values[index] = (value[0] * 12) + (value[1] % 12); };
/** @ignore */
const standalone_setFixedSizeList = (vector, index, value) => {
    const child = vector.getChildAt(0), { stride } = vector;
    for (let idx = -1, offset = index * stride; ++idx < stride;) {
        child.set(offset + idx, value.get(idx));
    }
};
standalone_SetVisitor.prototype.visitBool = standalone_set_setBool;
standalone_SetVisitor.prototype.visitInt = standalone_setInt;
standalone_SetVisitor.prototype.visitInt8 = standalone_setNumeric;
standalone_SetVisitor.prototype.visitInt16 = standalone_setNumeric;
standalone_SetVisitor.prototype.visitInt32 = standalone_setNumeric;
standalone_SetVisitor.prototype.visitInt64 = standalone_setNumericX2;
standalone_SetVisitor.prototype.visitUint8 = standalone_setNumeric;
standalone_SetVisitor.prototype.visitUint16 = standalone_setNumeric;
standalone_SetVisitor.prototype.visitUint32 = standalone_setNumeric;
standalone_SetVisitor.prototype.visitUint64 = standalone_setNumericX2;
standalone_SetVisitor.prototype.visitFloat = standalone_setFloat;
standalone_SetVisitor.prototype.visitFloat16 = standalone_setFloat16;
standalone_SetVisitor.prototype.visitFloat32 = standalone_setNumeric;
standalone_SetVisitor.prototype.visitFloat64 = standalone_setNumeric;
standalone_SetVisitor.prototype.visitUtf8 = standalone_setUtf8;
standalone_SetVisitor.prototype.visitBinary = standalone_setBinary;
standalone_SetVisitor.prototype.visitFixedSizeBinary = standalone_setFixedSizeBinary;
standalone_SetVisitor.prototype.visitDate = standalone_setDate;
standalone_SetVisitor.prototype.visitDateDay = standalone_setDateDay;
standalone_SetVisitor.prototype.visitDateMillisecond = standalone_setDateMillisecond;
standalone_SetVisitor.prototype.visitTimestamp = standalone_setTimestamp;
standalone_SetVisitor.prototype.visitTimestampSecond = standalone_setTimestampSecond;
standalone_SetVisitor.prototype.visitTimestampMillisecond = standalone_setTimestampMillisecond;
standalone_SetVisitor.prototype.visitTimestampMicrosecond = standalone_setTimestampMicrosecond;
standalone_SetVisitor.prototype.visitTimestampNanosecond = standalone_setTimestampNanosecond;
standalone_SetVisitor.prototype.visitTime = standalone_setTime;
standalone_SetVisitor.prototype.visitTimeSecond = standalone_setTimeSecond;
standalone_SetVisitor.prototype.visitTimeMillisecond = standalone_setTimeMillisecond;
standalone_SetVisitor.prototype.visitTimeMicrosecond = standalone_setTimeMicrosecond;
standalone_SetVisitor.prototype.visitTimeNanosecond = standalone_setTimeNanosecond;
standalone_SetVisitor.prototype.visitDecimal = standalone_setDecimal;
standalone_SetVisitor.prototype.visitList = standalone_setList;
standalone_SetVisitor.prototype.visitStruct = standalone_setStruct;
standalone_SetVisitor.prototype.visitUnion = standalone_setUnion;
standalone_SetVisitor.prototype.visitDenseUnion = standalone_setDenseUnion;
standalone_SetVisitor.prototype.visitSparseUnion = standalone_setSparseUnion;
standalone_SetVisitor.prototype.visitDictionary = standalone_setDictionary;
standalone_SetVisitor.prototype.visitInterval = standalone_setIntervalValue;
standalone_SetVisitor.prototype.visitIntervalDayTime = standalone_setIntervalDayTime;
standalone_SetVisitor.prototype.visitIntervalYearMonth = standalone_setIntervalYearMonth;
standalone_SetVisitor.prototype.visitFixedSizeList = standalone_setFixedSizeList;
standalone_SetVisitor.prototype.visitMap = standalone_setMap;
/** @ignore */
const standalone_set_instance = new standalone_SetVisitor();

//# sourceMappingURL=set.mjs.map

;// ../../node_modules/apache-arrow/visitor/builderctor.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.



















/** @ignore */
class standalone_GetBuilderCtor extends standalone_Visitor {
    visitNull() { return standalone_NullBuilder; }
    visitBool() { return standalone_BoolBuilder; }
    visitInt() { return standalone_IntBuilder; }
    visitInt8() { return standalone_Int8Builder; }
    visitInt16() { return standalone_Int16Builder; }
    visitInt32() { return standalone_Int32Builder; }
    visitInt64() { return standalone_Int64Builder; }
    visitUint8() { return standalone_Uint8Builder; }
    visitUint16() { return standalone_Uint16Builder; }
    visitUint32() { return standalone_Uint32Builder; }
    visitUint64() { return standalone_Uint64Builder; }
    visitFloat() { return standalone_FloatBuilder; }
    visitFloat16() { return standalone_Float16Builder; }
    visitFloat32() { return standalone_Float32Builder; }
    visitFloat64() { return standalone_Float64Builder; }
    visitUtf8() { return standalone_Utf8Builder; }
    visitBinary() { return standalone_BinaryBuilder; }
    visitFixedSizeBinary() { return standalone_FixedSizeBinaryBuilder; }
    visitDate() { return standalone_DateBuilder; }
    visitDateDay() { return standalone_DateDayBuilder; }
    visitDateMillisecond() { return standalone_DateMillisecondBuilder; }
    visitTimestamp() { return standalone_TimestampBuilder; }
    visitTimestampSecond() { return standalone_TimestampSecondBuilder; }
    visitTimestampMillisecond() { return standalone_TimestampMillisecondBuilder; }
    visitTimestampMicrosecond() { return standalone_TimestampMicrosecondBuilder; }
    visitTimestampNanosecond() { return standalone_TimestampNanosecondBuilder; }
    visitTime() { return standalone_TimeBuilder; }
    visitTimeSecond() { return standalone_TimeSecondBuilder; }
    visitTimeMillisecond() { return standalone_TimeMillisecondBuilder; }
    visitTimeMicrosecond() { return standalone_TimeMicrosecondBuilder; }
    visitTimeNanosecond() { return standalone_TimeNanosecondBuilder; }
    visitDecimal() { return standalone_DecimalBuilder; }
    visitList() { return standalone_ListBuilder; }
    visitStruct() { return standalone_StructBuilder; }
    visitUnion() { return standalone_UnionBuilder; }
    visitDenseUnion() { return standalone_DenseUnionBuilder; }
    visitSparseUnion() { return standalone_SparseUnionBuilder; }
    visitDictionary() { return standalone_DictionaryBuilder; }
    visitInterval() { return standalone_IntervalBuilder; }
    visitIntervalDayTime() { return standalone_IntervalDayTimeBuilder; }
    visitIntervalYearMonth() { return standalone_IntervalYearMonthBuilder; }
    visitFixedSizeList() { return standalone_FixedSizeListBuilder; }
    visitMap() { return standalone_MapBuilder; }
}
/** @ignore */
const standalone_builderctor_instance = new standalone_GetBuilderCtor();

//# sourceMappingURL=builderctor.mjs.map

;// ../../node_modules/apache-arrow/builder/index.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
/** @ignore */
























/** @nocollapse */
standalone_Builder.new = standalone_newBuilder;
function standalone_newBuilder(options) {
    const type = options.type;
    const builder = new (standalone_builderctor_instance.getVisitFn(type)())(options);
    if (type.children && type.children.length > 0) {
        const children = options['children'] || [];
        const defaultOptions = { 'nullValues': options['nullValues'] };
        const getChildOptions = Array.isArray(children)
            ? ((_, i) => children[i] || defaultOptions)
            : (({ name }) => children[name] || defaultOptions);
        type.children.forEach((field, index) => {
            const { type } = field;
            const opts = getChildOptions(field, index);
            builder.children.push(standalone_newBuilder({ ...opts, type }));
        });
    }
    return builder;
}
Object.keys(standalone_enum_Type)
    .map((T) => standalone_enum_Type[T])
    .filter((T) => typeof T === 'number' && T !== standalone_enum_Type.NONE)
    .forEach((typeId) => {
    const BuilderCtor = standalone_builderctor_instance.visit(typeId);
    BuilderCtor.prototype._setValue = standalone_set_instance.getVisitFn(typeId);
});
standalone_Utf8Builder.prototype._setValue = standalone_set_instance.visitBinary;

//# sourceMappingURL=index.mjs.map

;// ../../node_modules/apache-arrow/fb/File.mjs
// automatically generated by the FlatBuffers compiler, do not modify

/**
 * ----------------------------------------------------------------------
 * Arrow File metadata
 *
 *
 * @constructor
 */
var standalone_File_org;
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Footer {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Footer
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * @param flatbuffers.ByteBuffer bb
                     * @param Footer= obj
                     * @returns Footer
                     */
                    static getRootAsFooter(bb, obj) {
                        return (obj || new Footer).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                    }
                    /**
                     * @returns org.apache.arrow.flatbuf.MetadataVersion
                     */
                    version() {
                        let offset = this.bb.__offset(this.bb_pos, 4);
                        return offset ? /**  */ (this.bb.readInt16(this.bb_pos + offset)) : standalone_Schema_org.apache.arrow.flatbuf.MetadataVersion.V1;
                    }
                    /**
                     * @param org.apache.arrow.flatbuf.Schema= obj
                     * @returns org.apache.arrow.flatbuf.Schema|null
                     */
                    schema(obj) {
                        let offset = this.bb.__offset(this.bb_pos, 6);
                        return offset ? (obj || new standalone_Schema_org.apache.arrow.flatbuf.Schema).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
                    }
                    /**
                     * @param number index
                     * @param org.apache.arrow.flatbuf.Block= obj
                     * @returns org.apache.arrow.flatbuf.Block
                     */
                    dictionaries(index, obj) {
                        let offset = this.bb.__offset(this.bb_pos, 8);
                        return offset ? (obj || new org.apache.arrow.flatbuf.Block).__init(this.bb.__vector(this.bb_pos + offset) + index * 24, this.bb) : null;
                    }
                    /**
                     * @returns number
                     */
                    dictionariesLength() {
                        let offset = this.bb.__offset(this.bb_pos, 8);
                        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @param number index
                     * @param org.apache.arrow.flatbuf.Block= obj
                     * @returns org.apache.arrow.flatbuf.Block
                     */
                    recordBatches(index, obj) {
                        let offset = this.bb.__offset(this.bb_pos, 10);
                        return offset ? (obj || new org.apache.arrow.flatbuf.Block).__init(this.bb.__vector(this.bb_pos + offset) + index * 24, this.bb) : null;
                    }
                    /**
                     * @returns number
                     */
                    recordBatchesLength() {
                        let offset = this.bb.__offset(this.bb_pos, 10);
                        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     */
                    static startFooter(builder) {
                        builder.startObject(4);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param org.apache.arrow.flatbuf.MetadataVersion version
                     */
                    static addVersion(builder, version) {
                        builder.addFieldInt16(0, version, standalone_Schema_org.apache.arrow.flatbuf.MetadataVersion.V1);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset schemaOffset
                     */
                    static addSchema(builder, schemaOffset) {
                        builder.addFieldOffset(1, schemaOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset dictionariesOffset
                     */
                    static addDictionaries(builder, dictionariesOffset) {
                        builder.addFieldOffset(2, dictionariesOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number numElems
                     */
                    static startDictionariesVector(builder, numElems) {
                        builder.startVector(24, numElems, 8);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset recordBatchesOffset
                     */
                    static addRecordBatches(builder, recordBatchesOffset) {
                        builder.addFieldOffset(3, recordBatchesOffset, 0);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param number numElems
                     */
                    static startRecordBatchesVector(builder, numElems) {
                        builder.startVector(24, numElems, 8);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @returns flatbuffers.Offset
                     */
                    static endFooter(builder) {
                        let offset = builder.endObject();
                        return offset;
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Offset offset
                     */
                    static finishFooterBuffer(builder, offset) {
                        builder.finish(offset);
                    }
                    static createFooter(builder, version, schemaOffset, dictionariesOffset, recordBatchesOffset) {
                        Footer.startFooter(builder);
                        Footer.addVersion(builder, version);
                        Footer.addSchema(builder, schemaOffset);
                        Footer.addDictionaries(builder, dictionariesOffset);
                        Footer.addRecordBatches(builder, recordBatchesOffset);
                        return Footer.endFooter(builder);
                    }
                }
                flatbuf.Footer = Footer;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_File_org || (standalone_File_org = {}));
/**
 * @constructor
 */
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                class Block {
                    constructor() {
                        this.bb = null;
                        this.bb_pos = 0;
                    }
                    /**
                     * @param number i
                     * @param flatbuffers.ByteBuffer bb
                     * @returns Block
                     */
                    __init(i, bb) {
                        this.bb_pos = i;
                        this.bb = bb;
                        return this;
                    }
                    /**
                     * Index to the start of the RecordBlock (note this is past the Message header)
                     *
                     * @returns flatbuffers.Long
                     */
                    offset() {
                        return this.bb.readInt64(this.bb_pos);
                    }
                    /**
                     * Length of the metadata
                     *
                     * @returns number
                     */
                    metaDataLength() {
                        return this.bb.readInt32(this.bb_pos + 8);
                    }
                    /**
                     * Length of the data (this is aligned so there can be a gap between this and
                     * the metatdata).
                     *
                     * @returns flatbuffers.Long
                     */
                    bodyLength() {
                        return this.bb.readInt64(this.bb_pos + 16);
                    }
                    /**
                     * @param flatbuffers.Builder builder
                     * @param flatbuffers.Long offset
                     * @param number metaDataLength
                     * @param flatbuffers.Long bodyLength
                     * @returns flatbuffers.Offset
                     */
                    static createBlock(builder, offset, metaDataLength, bodyLength) {
                        builder.prep(8, 24);
                        builder.writeInt64(bodyLength);
                        builder.pad(4);
                        builder.writeInt32(metaDataLength);
                        builder.writeInt64(offset);
                        return builder.offset();
                    }
                }
                flatbuf.Block = Block;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(standalone_File_org || (standalone_File_org = {}));

//# sourceMappingURL=File.mjs.map

;// ../../node_modules/apache-arrow/ipc/metadata/file.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
/* tslint:disable:class-name */


var standalone_Long = standalone_flatbuffers.Long;
var standalone_file_Builder = standalone_flatbuffers.Builder;
var standalone_file_ByteBuffer = standalone_flatbuffers.ByteBuffer;
var standalone_Block = standalone_File_org.apache.arrow.flatbuf.Block;
var standalone_Footer = standalone_File_org.apache.arrow.flatbuf.Footer;



/** @ignore */
class standalone_Footer_ {
    constructor(schema, version = standalone_MetadataVersion.V4, recordBatches, dictionaryBatches) {
        this.schema = schema;
        this.version = version;
        recordBatches && (this._recordBatches = recordBatches);
        dictionaryBatches && (this._dictionaryBatches = dictionaryBatches);
    }
    /** @nocollapse */
    static decode(buf) {
        buf = new standalone_file_ByteBuffer(standalone_toUint8Array(buf));
        const footer = standalone_Footer.getRootAsFooter(buf);
        const schema = standalone_Schema.decode(footer.schema());
        return new standalone_OffHeapFooter(schema, footer);
    }
    /** @nocollapse */
    static encode(footer) {
        const b = new standalone_file_Builder();
        const schemaOffset = standalone_Schema.encode(b, footer.schema);
        standalone_Footer.startRecordBatchesVector(b, footer.numRecordBatches);
        [...footer.recordBatches()].slice().reverse().forEach((rb) => standalone_FileBlock.encode(b, rb));
        const recordBatchesOffset = b.endVector();
        standalone_Footer.startDictionariesVector(b, footer.numDictionaries);
        [...footer.dictionaryBatches()].slice().reverse().forEach((db) => standalone_FileBlock.encode(b, db));
        const dictionaryBatchesOffset = b.endVector();
        standalone_Footer.startFooter(b);
        standalone_Footer.addSchema(b, schemaOffset);
        standalone_Footer.addVersion(b, standalone_MetadataVersion.V4);
        standalone_Footer.addRecordBatches(b, recordBatchesOffset);
        standalone_Footer.addDictionaries(b, dictionaryBatchesOffset);
        standalone_Footer.finishFooterBuffer(b, standalone_Footer.endFooter(b));
        return b.asUint8Array();
    }
    get numRecordBatches() { return this._recordBatches.length; }
    get numDictionaries() { return this._dictionaryBatches.length; }
    *recordBatches() {
        for (let block, i = -1, n = this.numRecordBatches; ++i < n;) {
            if (block = this.getRecordBatch(i)) {
                yield block;
            }
        }
    }
    *dictionaryBatches() {
        for (let block, i = -1, n = this.numDictionaries; ++i < n;) {
            if (block = this.getDictionaryBatch(i)) {
                yield block;
            }
        }
    }
    getRecordBatch(index) {
        return index >= 0
            && index < this.numRecordBatches
            && this._recordBatches[index] || null;
    }
    getDictionaryBatch(index) {
        return index >= 0
            && index < this.numDictionaries
            && this._dictionaryBatches[index] || null;
    }
}

/** @ignore */
class standalone_OffHeapFooter extends standalone_Footer_ {
    constructor(schema, _footer) {
        super(schema, _footer.version());
        this._footer = _footer;
    }
    get numRecordBatches() { return this._footer.recordBatchesLength(); }
    get numDictionaries() { return this._footer.dictionariesLength(); }
    getRecordBatch(index) {
        if (index >= 0 && index < this.numRecordBatches) {
            const fileBlock = this._footer.recordBatches(index);
            if (fileBlock) {
                return standalone_FileBlock.decode(fileBlock);
            }
        }
        return null;
    }
    getDictionaryBatch(index) {
        if (index >= 0 && index < this.numDictionaries) {
            const fileBlock = this._footer.dictionaries(index);
            if (fileBlock) {
                return standalone_FileBlock.decode(fileBlock);
            }
        }
        return null;
    }
}
/** @ignore */
class standalone_FileBlock {
    constructor(metaDataLength, bodyLength, offset) {
        this.metaDataLength = metaDataLength;
        this.offset = typeof offset === 'number' ? offset : offset.low;
        this.bodyLength = typeof bodyLength === 'number' ? bodyLength : bodyLength.low;
    }
    /** @nocollapse */
    static decode(block) {
        return new standalone_FileBlock(block.metaDataLength(), block.bodyLength(), block.offset());
    }
    /** @nocollapse */
    static encode(b, fileBlock) {
        const { metaDataLength } = fileBlock;
        const offset = new standalone_Long(fileBlock.offset, 0);
        const bodyLength = new standalone_Long(fileBlock.bodyLength, 0);
        return standalone_Block.createBlock(b, offset, metaDataLength, bodyLength);
    }
}

//# sourceMappingURL=file.mjs.map

;// ../../node_modules/apache-arrow/io/stream.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.





/** @ignore */
class standalone_AsyncByteQueue extends standalone_AsyncQueue {
    write(value) {
        if ((value = standalone_toUint8Array(value)).byteLength > 0) {
            return super.write(value);
        }
    }
    toString(sync = false) {
        return sync
            ? standalone_decodeUtf8(this.toUint8Array(true))
            : this.toUint8Array(false).then(standalone_decodeUtf8);
    }
    toUint8Array(sync = false) {
        return sync ? standalone_joinUint8Arrays(this._values)[0] : (async () => {
            let buffers = [], byteLength = 0;
            for await (const chunk of this) {
                buffers.push(chunk);
                byteLength += chunk.byteLength;
            }
            return standalone_joinUint8Arrays(buffers, byteLength)[0];
        })();
    }
}
/** @ignore */
class standalone_ByteStream {
    constructor(source) {
        if (source) {
            this.source = new standalone_ByteStreamSource(standalone_adapters.fromIterable(source));
        }
    }
    [Symbol.iterator]() { return this; }
    next(value) { return this.source.next(value); }
    throw(value) { return this.source.throw(value); }
    return(value) { return this.source.return(value); }
    peek(size) { return this.source.peek(size); }
    read(size) { return this.source.read(size); }
}
/** @ignore */
class standalone_AsyncByteStream {
    constructor(source) {
        if (source instanceof standalone_AsyncByteStream) {
            this.source = source.source;
        }
        else if (source instanceof standalone_AsyncByteQueue) {
            this.source = new standalone_AsyncByteStreamSource(standalone_adapters.fromAsyncIterable(source));
        }
        else if (standalone_isReadableNodeStream(source)) {
            this.source = new standalone_AsyncByteStreamSource(standalone_adapters.fromNodeStream(source));
        }
        else if (standalone_isReadableDOMStream(source)) {
            this.source = new standalone_AsyncByteStreamSource(standalone_adapters.fromDOMStream(source));
        }
        else if (standalone_isFetchResponse(source)) {
            this.source = new standalone_AsyncByteStreamSource(standalone_adapters.fromDOMStream(source.body));
        }
        else if (standalone_compat_isIterable(source)) {
            this.source = new standalone_AsyncByteStreamSource(standalone_adapters.fromIterable(source));
        }
        else if (standalone_isPromise(source)) {
            this.source = new standalone_AsyncByteStreamSource(standalone_adapters.fromAsyncIterable(source));
        }
        else if (standalone_isAsyncIterable(source)) {
            this.source = new standalone_AsyncByteStreamSource(standalone_adapters.fromAsyncIterable(source));
        }
    }
    [Symbol.asyncIterator]() { return this; }
    next(value) { return this.source.next(value); }
    throw(value) { return this.source.throw(value); }
    return(value) { return this.source.return(value); }
    get closed() { return this.source.closed; }
    cancel(reason) { return this.source.cancel(reason); }
    peek(size) { return this.source.peek(size); }
    read(size) { return this.source.read(size); }
}
/** @ignore */
class standalone_ByteStreamSource {
    constructor(source) {
        this.source = source;
    }
    cancel(reason) { this.return(reason); }
    peek(size) { return this.next(size, 'peek').value; }
    read(size) { return this.next(size, 'read').value; }
    next(size, cmd = 'read') { return this.source.next({ cmd, size }); }
    throw(value) { return Object.create((this.source.throw && this.source.throw(value)) || standalone_ITERATOR_DONE); }
    return(value) { return Object.create((this.source.return && this.source.return(value)) || standalone_ITERATOR_DONE); }
}
/** @ignore */
class standalone_AsyncByteStreamSource {
    constructor(source) {
        this.source = source;
        this._closedPromise = new Promise((r) => this._closedPromiseResolve = r);
    }
    async cancel(reason) { await this.return(reason); }
    get closed() { return this._closedPromise; }
    async read(size) { return (await this.next(size, 'read')).value; }
    async peek(size) { return (await this.next(size, 'peek')).value; }
    async next(size, cmd = 'read') { return (await this.source.next({ cmd, size })); }
    async throw(value) {
        const result = (this.source.throw && await this.source.throw(value)) || standalone_ITERATOR_DONE;
        this._closedPromiseResolve && this._closedPromiseResolve();
        this._closedPromiseResolve = undefined;
        return Object.create(result);
    }
    async return(value) {
        const result = (this.source.return && await this.source.return(value)) || standalone_ITERATOR_DONE;
        this._closedPromiseResolve && this._closedPromiseResolve();
        this._closedPromiseResolve = undefined;
        return Object.create(result);
    }
}

//# sourceMappingURL=stream.mjs.map

;// ../../node_modules/apache-arrow/io/file.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/** @ignore */
class standalone_RandomAccessFile extends standalone_ByteStream {
    constructor(buffer, byteLength) {
        super();
        this.position = 0;
        this.buffer = standalone_toUint8Array(buffer);
        this.size = typeof byteLength === 'undefined' ? this.buffer.byteLength : byteLength;
    }
    readInt32(position) {
        const { buffer, byteOffset } = this.readAt(position, 4);
        return new DataView(buffer, byteOffset).getInt32(0, true);
    }
    seek(position) {
        this.position = Math.min(position, this.size);
        return position < this.size;
    }
    read(nBytes) {
        const { buffer, size, position } = this;
        if (buffer && position < size) {
            if (typeof nBytes !== 'number') {
                nBytes = Infinity;
            }
            this.position = Math.min(size, position + Math.min(size - position, nBytes));
            return buffer.subarray(position, this.position);
        }
        return null;
    }
    readAt(position, nBytes) {
        const buf = this.buffer;
        const end = Math.min(this.size, position + nBytes);
        return buf ? buf.subarray(position, end) : new Uint8Array(nBytes);
    }
    close() { this.buffer && (this.buffer = null); }
    throw(value) { this.close(); return { done: true, value }; }
    return(value) { this.close(); return { done: true, value }; }
}
/** @ignore */
class standalone_AsyncRandomAccessFile extends standalone_AsyncByteStream {
    constructor(file, byteLength) {
        super();
        this.position = 0;
        this._handle = file;
        if (typeof byteLength === 'number') {
            this.size = byteLength;
        }
        else {
            this._pending = (async () => {
                this.size = (await file.stat()).size;
                delete this._pending;
            })();
        }
    }
    async readInt32(position) {
        const { buffer, byteOffset } = await this.readAt(position, 4);
        return new DataView(buffer, byteOffset).getInt32(0, true);
    }
    async seek(position) {
        this._pending && await this._pending;
        this.position = Math.min(position, this.size);
        return position < this.size;
    }
    async read(nBytes) {
        this._pending && await this._pending;
        const { _handle: file, size, position } = this;
        if (file && position < size) {
            if (typeof nBytes !== 'number') {
                nBytes = Infinity;
            }
            let pos = position, offset = 0, bytesRead = 0;
            let end = Math.min(size, pos + Math.min(size - pos, nBytes));
            let buffer = new Uint8Array(Math.max(0, (this.position = end) - pos));
            while ((pos += bytesRead) < end && (offset += bytesRead) < buffer.byteLength) {
                ({ bytesRead } = await file.read(buffer, offset, buffer.byteLength - offset, pos));
            }
            return buffer;
        }
        return null;
    }
    async readAt(position, nBytes) {
        this._pending && await this._pending;
        const { _handle: file, size } = this;
        if (file && (position + nBytes) < size) {
            const end = Math.min(size, position + nBytes);
            const buffer = new Uint8Array(end - position);
            return (await file.read(buffer, 0, nBytes, position)).buffer;
        }
        return new Uint8Array(nBytes);
    }
    async close() { const f = this._handle; this._handle = null; f && await f.close(); }
    async throw(value) { await this.close(); return { done: true, value }; }
    async return(value) { await this.close(); return { done: true, value }; }
}

//# sourceMappingURL=file.mjs.map

;// ../../node_modules/apache-arrow/util/int.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
/** @ignore */
const standalone_carryBit16 = 1 << 16;
/** @ignore */
function standalone_intAsHex(value) {
    if (value < 0) {
        value = 0xFFFFFFFF + value + 1;
    }
    return `0x${value.toString(16)}`;
}
/** @ignore */
const standalone_kInt32DecimalDigits = 8;
/** @ignore */
const standalone_kPowersOfTen = [1,
    10,
    100,
    1000,
    10000,
    100000,
    1000000,
    10000000,
    100000000];
/** @ignore */
class standalone_BaseInt64 {
    constructor(buffer) {
        this.buffer = buffer;
    }
    high() { return this.buffer[1]; }
    low() { return this.buffer[0]; }
    _times(other) {
        // Break the left and right numbers into 16 bit chunks
        // so that we can multiply them without overflow.
        const L = new Uint32Array([
            this.buffer[1] >>> 16,
            this.buffer[1] & 0xFFFF,
            this.buffer[0] >>> 16,
            this.buffer[0] & 0xFFFF
        ]);
        const R = new Uint32Array([
            other.buffer[1] >>> 16,
            other.buffer[1] & 0xFFFF,
            other.buffer[0] >>> 16,
            other.buffer[0] & 0xFFFF
        ]);
        let product = L[3] * R[3];
        this.buffer[0] = product & 0xFFFF;
        let sum = product >>> 16;
        product = L[2] * R[3];
        sum += product;
        product = (L[3] * R[2]) >>> 0;
        sum += product;
        this.buffer[0] += sum << 16;
        this.buffer[1] = (sum >>> 0 < product ? standalone_carryBit16 : 0);
        this.buffer[1] += sum >>> 16;
        this.buffer[1] += L[1] * R[3] + L[2] * R[2] + L[3] * R[1];
        this.buffer[1] += (L[0] * R[3] + L[1] * R[2] + L[2] * R[1] + L[3] * R[0]) << 16;
        return this;
    }
    _plus(other) {
        const sum = (this.buffer[0] + other.buffer[0]) >>> 0;
        this.buffer[1] += other.buffer[1];
        if (sum < (this.buffer[0] >>> 0)) {
            ++this.buffer[1];
        }
        this.buffer[0] = sum;
    }
    lessThan(other) {
        return this.buffer[1] < other.buffer[1] ||
            (this.buffer[1] === other.buffer[1] && this.buffer[0] < other.buffer[0]);
    }
    equals(other) {
        return this.buffer[1] === other.buffer[1] && this.buffer[0] == other.buffer[0];
    }
    greaterThan(other) {
        return other.lessThan(this);
    }
    hex() {
        return `${standalone_intAsHex(this.buffer[1])} ${standalone_intAsHex(this.buffer[0])}`;
    }
}
/** @ignore */
class standalone_int_Uint64 extends standalone_BaseInt64 {
    times(other) {
        this._times(other);
        return this;
    }
    plus(other) {
        this._plus(other);
        return this;
    }
    /** @nocollapse */
    static from(val, out_buffer = new Uint32Array(2)) {
        return standalone_int_Uint64.fromString(typeof (val) === 'string' ? val : val.toString(), out_buffer);
    }
    /** @nocollapse */
    static fromNumber(num, out_buffer = new Uint32Array(2)) {
        // Always parse numbers as strings - pulling out high and low bits
        // directly seems to lose precision sometimes
        // For example:
        //     > -4613034156400212000 >>> 0
        //     721782784
        // The correct lower 32-bits are 721782752
        return standalone_int_Uint64.fromString(num.toString(), out_buffer);
    }
    /** @nocollapse */
    static fromString(str, out_buffer = new Uint32Array(2)) {
        const length = str.length;
        let out = new standalone_int_Uint64(out_buffer);
        for (let posn = 0; posn < length;) {
            const group = standalone_kInt32DecimalDigits < length - posn ?
                standalone_kInt32DecimalDigits : length - posn;
            const chunk = new standalone_int_Uint64(new Uint32Array([parseInt(str.substr(posn, group), 10), 0]));
            const multiple = new standalone_int_Uint64(new Uint32Array([standalone_kPowersOfTen[group], 0]));
            out.times(multiple);
            out.plus(chunk);
            posn += group;
        }
        return out;
    }
    /** @nocollapse */
    static convertArray(values) {
        const data = new Uint32Array(values.length * 2);
        for (let i = -1, n = values.length; ++i < n;) {
            standalone_int_Uint64.from(values[i], new Uint32Array(data.buffer, data.byteOffset + 2 * i * 4, 2));
        }
        return data;
    }
    /** @nocollapse */
    static multiply(left, right) {
        let rtrn = new standalone_int_Uint64(new Uint32Array(left.buffer));
        return rtrn.times(right);
    }
    /** @nocollapse */
    static add(left, right) {
        let rtrn = new standalone_int_Uint64(new Uint32Array(left.buffer));
        return rtrn.plus(right);
    }
}
/** @ignore */
class standalone_int_Int64 extends standalone_BaseInt64 {
    negate() {
        this.buffer[0] = ~this.buffer[0] + 1;
        this.buffer[1] = ~this.buffer[1];
        if (this.buffer[0] == 0) {
            ++this.buffer[1];
        }
        return this;
    }
    times(other) {
        this._times(other);
        return this;
    }
    plus(other) {
        this._plus(other);
        return this;
    }
    lessThan(other) {
        // force high bytes to be signed
        const this_high = this.buffer[1] << 0;
        const other_high = other.buffer[1] << 0;
        return this_high < other_high ||
            (this_high === other_high && this.buffer[0] < other.buffer[0]);
    }
    /** @nocollapse */
    static from(val, out_buffer = new Uint32Array(2)) {
        return standalone_int_Int64.fromString(typeof (val) === 'string' ? val : val.toString(), out_buffer);
    }
    /** @nocollapse */
    static fromNumber(num, out_buffer = new Uint32Array(2)) {
        // Always parse numbers as strings - pulling out high and low bits
        // directly seems to lose precision sometimes
        // For example:
        //     > -4613034156400212000 >>> 0
        //     721782784
        // The correct lower 32-bits are 721782752
        return standalone_int_Int64.fromString(num.toString(), out_buffer);
    }
    /** @nocollapse */
    static fromString(str, out_buffer = new Uint32Array(2)) {
        // TODO: Assert that out_buffer is 0 and length = 2
        const negate = str.startsWith('-');
        const length = str.length;
        let out = new standalone_int_Int64(out_buffer);
        for (let posn = negate ? 1 : 0; posn < length;) {
            const group = standalone_kInt32DecimalDigits < length - posn ?
                standalone_kInt32DecimalDigits : length - posn;
            const chunk = new standalone_int_Int64(new Uint32Array([parseInt(str.substr(posn, group), 10), 0]));
            const multiple = new standalone_int_Int64(new Uint32Array([standalone_kPowersOfTen[group], 0]));
            out.times(multiple);
            out.plus(chunk);
            posn += group;
        }
        return negate ? out.negate() : out;
    }
    /** @nocollapse */
    static convertArray(values) {
        const data = new Uint32Array(values.length * 2);
        for (let i = -1, n = values.length; ++i < n;) {
            standalone_int_Int64.from(values[i], new Uint32Array(data.buffer, data.byteOffset + 2 * i * 4, 2));
        }
        return data;
    }
    /** @nocollapse */
    static multiply(left, right) {
        let rtrn = new standalone_int_Int64(new Uint32Array(left.buffer));
        return rtrn.times(right);
    }
    /** @nocollapse */
    static add(left, right) {
        let rtrn = new standalone_int_Int64(new Uint32Array(left.buffer));
        return rtrn.plus(right);
    }
}
/** @ignore */
class standalone_Int128 {
    constructor(buffer) {
        this.buffer = buffer;
        // buffer[3] MSB (high)
        // buffer[2]
        // buffer[1]
        // buffer[0] LSB (low)
    }
    high() {
        return new standalone_int_Int64(new Uint32Array(this.buffer.buffer, this.buffer.byteOffset + 8, 2));
    }
    low() {
        return new standalone_int_Int64(new Uint32Array(this.buffer.buffer, this.buffer.byteOffset, 2));
    }
    negate() {
        this.buffer[0] = ~this.buffer[0] + 1;
        this.buffer[1] = ~this.buffer[1];
        this.buffer[2] = ~this.buffer[2];
        this.buffer[3] = ~this.buffer[3];
        if (this.buffer[0] == 0) {
            ++this.buffer[1];
        }
        if (this.buffer[1] == 0) {
            ++this.buffer[2];
        }
        if (this.buffer[2] == 0) {
            ++this.buffer[3];
        }
        return this;
    }
    times(other) {
        // Break the left and right numbers into 32 bit chunks
        // so that we can multiply them without overflow.
        const L0 = new standalone_int_Uint64(new Uint32Array([this.buffer[3], 0]));
        const L1 = new standalone_int_Uint64(new Uint32Array([this.buffer[2], 0]));
        const L2 = new standalone_int_Uint64(new Uint32Array([this.buffer[1], 0]));
        const L3 = new standalone_int_Uint64(new Uint32Array([this.buffer[0], 0]));
        const R0 = new standalone_int_Uint64(new Uint32Array([other.buffer[3], 0]));
        const R1 = new standalone_int_Uint64(new Uint32Array([other.buffer[2], 0]));
        const R2 = new standalone_int_Uint64(new Uint32Array([other.buffer[1], 0]));
        const R3 = new standalone_int_Uint64(new Uint32Array([other.buffer[0], 0]));
        let product = standalone_int_Uint64.multiply(L3, R3);
        this.buffer[0] = product.low();
        let sum = new standalone_int_Uint64(new Uint32Array([product.high(), 0]));
        product = standalone_int_Uint64.multiply(L2, R3);
        sum.plus(product);
        product = standalone_int_Uint64.multiply(L3, R2);
        sum.plus(product);
        this.buffer[1] = sum.low();
        this.buffer[3] = (sum.lessThan(product) ? 1 : 0);
        this.buffer[2] = sum.high();
        let high = new standalone_int_Uint64(new Uint32Array(this.buffer.buffer, this.buffer.byteOffset + 8, 2));
        high.plus(standalone_int_Uint64.multiply(L1, R3))
            .plus(standalone_int_Uint64.multiply(L2, R2))
            .plus(standalone_int_Uint64.multiply(L3, R1));
        this.buffer[3] += standalone_int_Uint64.multiply(L0, R3)
            .plus(standalone_int_Uint64.multiply(L1, R2))
            .plus(standalone_int_Uint64.multiply(L2, R1))
            .plus(standalone_int_Uint64.multiply(L3, R0)).low();
        return this;
    }
    plus(other) {
        let sums = new Uint32Array(4);
        sums[3] = (this.buffer[3] + other.buffer[3]) >>> 0;
        sums[2] = (this.buffer[2] + other.buffer[2]) >>> 0;
        sums[1] = (this.buffer[1] + other.buffer[1]) >>> 0;
        sums[0] = (this.buffer[0] + other.buffer[0]) >>> 0;
        if (sums[0] < (this.buffer[0] >>> 0)) {
            ++sums[1];
        }
        if (sums[1] < (this.buffer[1] >>> 0)) {
            ++sums[2];
        }
        if (sums[2] < (this.buffer[2] >>> 0)) {
            ++sums[3];
        }
        this.buffer[3] = sums[3];
        this.buffer[2] = sums[2];
        this.buffer[1] = sums[1];
        this.buffer[0] = sums[0];
        return this;
    }
    hex() {
        return `${standalone_intAsHex(this.buffer[3])} ${standalone_intAsHex(this.buffer[2])} ${standalone_intAsHex(this.buffer[1])} ${standalone_intAsHex(this.buffer[0])}`;
    }
    /** @nocollapse */
    static multiply(left, right) {
        let rtrn = new standalone_Int128(new Uint32Array(left.buffer));
        return rtrn.times(right);
    }
    /** @nocollapse */
    static add(left, right) {
        let rtrn = new standalone_Int128(new Uint32Array(left.buffer));
        return rtrn.plus(right);
    }
    /** @nocollapse */
    static from(val, out_buffer = new Uint32Array(4)) {
        return standalone_Int128.fromString(typeof (val) === 'string' ? val : val.toString(), out_buffer);
    }
    /** @nocollapse */
    static fromNumber(num, out_buffer = new Uint32Array(4)) {
        // Always parse numbers as strings - pulling out high and low bits
        // directly seems to lose precision sometimes
        // For example:
        //     > -4613034156400212000 >>> 0
        //     721782784
        // The correct lower 32-bits are 721782752
        return standalone_Int128.fromString(num.toString(), out_buffer);
    }
    /** @nocollapse */
    static fromString(str, out_buffer = new Uint32Array(4)) {
        // TODO: Assert that out_buffer is 0 and length = 4
        const negate = str.startsWith('-');
        const length = str.length;
        let out = new standalone_Int128(out_buffer);
        for (let posn = negate ? 1 : 0; posn < length;) {
            const group = standalone_kInt32DecimalDigits < length - posn ?
                standalone_kInt32DecimalDigits : length - posn;
            const chunk = new standalone_Int128(new Uint32Array([parseInt(str.substr(posn, group), 10), 0, 0, 0]));
            const multiple = new standalone_Int128(new Uint32Array([standalone_kPowersOfTen[group], 0, 0, 0]));
            out.times(multiple);
            out.plus(chunk);
            posn += group;
        }
        return negate ? out.negate() : out;
    }
    /** @nocollapse */
    static convertArray(values) {
        // TODO: Distinguish between string and number at compile-time
        const data = new Uint32Array(values.length * 4);
        for (let i = -1, n = values.length; ++i < n;) {
            standalone_Int128.from(values[i], new Uint32Array(data.buffer, data.byteOffset + 4 * 4 * i, 4));
        }
        return data;
    }
}

//# sourceMappingURL=int.mjs.map

;// ../../node_modules/apache-arrow/visitor/vectorloader.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.









/** @ignore */
class standalone_VectorLoader extends standalone_Visitor {
    constructor(bytes, nodes, buffers, dictionaries) {
        super();
        this.nodesIndex = -1;
        this.buffersIndex = -1;
        this.bytes = bytes;
        this.nodes = nodes;
        this.buffers = buffers;
        this.dictionaries = dictionaries;
    }
    visit(node) {
        return super.visit(node instanceof standalone_schema_Field ? node.type : node);
    }
    visitNull(type, { length, } = this.nextFieldNode()) { return standalone_Data.Null(type, 0, length); }
    visitBool(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Bool(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitInt(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Int(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitFloat(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Float(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitUtf8(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Utf8(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readOffsets(type), this.readData(type)); }
    visitBinary(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Binary(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readOffsets(type), this.readData(type)); }
    visitFixedSizeBinary(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.FixedSizeBinary(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitDate(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Date(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitTimestamp(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Timestamp(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitTime(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Time(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitDecimal(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Decimal(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitList(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.List(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readOffsets(type), this.visit(type.children[0])); }
    visitStruct(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Struct(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.visitMany(type.children)); }
    visitUnion(type) { return type.mode === standalone_UnionMode.Sparse ? this.visitSparseUnion(type) : this.visitDenseUnion(type); }
    visitDenseUnion(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Union(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readTypeIds(type), this.readOffsets(type), this.visitMany(type.children)); }
    visitSparseUnion(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Union(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readTypeIds(type), this.visitMany(type.children)); }
    visitDictionary(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Dictionary(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type.indices), this.readDictionary(type)); }
    visitInterval(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Interval(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitFixedSizeList(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.FixedSizeList(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.visit(type.children[0])); }
    visitMap(type, { length, nullCount } = this.nextFieldNode()) { return standalone_Data.Map(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readOffsets(type), this.visit(type.children[0])); }
    nextFieldNode() { return this.nodes[++this.nodesIndex]; }
    nextBufferRange() { return this.buffers[++this.buffersIndex]; }
    readNullBitmap(type, nullCount, buffer = this.nextBufferRange()) {
        return nullCount > 0 && this.readData(type, buffer) || new Uint8Array(0);
    }
    readOffsets(type, buffer) { return this.readData(type, buffer); }
    readTypeIds(type, buffer) { return this.readData(type, buffer); }
    readData(_type, { length, offset } = this.nextBufferRange()) {
        return this.bytes.subarray(offset, offset + length);
    }
    readDictionary(type) {
        return this.dictionaries.get(type.id);
    }
}
/** @ignore */
class standalone_JSONVectorLoader extends standalone_VectorLoader {
    constructor(sources, nodes, buffers, dictionaries) {
        super(new Uint8Array(0), nodes, buffers, dictionaries);
        this.sources = sources;
    }
    readNullBitmap(_type, nullCount, { offset } = this.nextBufferRange()) {
        return nullCount <= 0 ? new Uint8Array(0) : standalone_packBools(this.sources[offset]);
    }
    readOffsets(_type, { offset } = this.nextBufferRange()) {
        return standalone_toArrayBufferView(Uint8Array, standalone_toArrayBufferView(Int32Array, this.sources[offset]));
    }
    readTypeIds(type, { offset } = this.nextBufferRange()) {
        return standalone_toArrayBufferView(Uint8Array, standalone_toArrayBufferView(type.ArrayType, this.sources[offset]));
    }
    readData(type, { offset } = this.nextBufferRange()) {
        const { sources } = this;
        if (standalone_DataType.isTimestamp(type)) {
            return standalone_toArrayBufferView(Uint8Array, standalone_int_Int64.convertArray(sources[offset]));
        }
        else if ((standalone_DataType.isInt(type) || standalone_DataType.isTime(type)) && type.bitWidth === 64) {
            return standalone_toArrayBufferView(Uint8Array, standalone_int_Int64.convertArray(sources[offset]));
        }
        else if (standalone_DataType.isDate(type) && type.unit === standalone_DateUnit.MILLISECOND) {
            return standalone_toArrayBufferView(Uint8Array, standalone_int_Int64.convertArray(sources[offset]));
        }
        else if (standalone_DataType.isDecimal(type)) {
            return standalone_toArrayBufferView(Uint8Array, standalone_Int128.convertArray(sources[offset]));
        }
        else if (standalone_DataType.isBinary(type) || standalone_DataType.isFixedSizeBinary(type)) {
            return standalone_binaryDataFromJSON(sources[offset]);
        }
        else if (standalone_DataType.isBool(type)) {
            return standalone_packBools(sources[offset]);
        }
        else if (standalone_DataType.isUtf8(type)) {
            return standalone_encodeUtf8(sources[offset].join(''));
        }
        return standalone_toArrayBufferView(Uint8Array, standalone_toArrayBufferView(type.ArrayType, sources[offset].map((x) => +x)));
    }
}
/** @ignore */
function standalone_binaryDataFromJSON(values) {
    // "DATA": ["49BC7D5B6C47D2","3F5FB6D9322026"]
    // There are definitely more efficient ways to do this... but it gets the
    // job done.
    const joined = values.join('');
    const data = new Uint8Array(joined.length / 2);
    for (let i = 0; i < joined.length; i += 2) {
        data[i >> 1] = parseInt(joined.substr(i, 2), 16);
    }
    return data;
}

//# sourceMappingURL=vectorloader.mjs.map

;// ../../node_modules/apache-arrow/visitor/typeassembler.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

var standalone_typeassembler_Long = standalone_flatbuffers.Long;


var standalone_typeassembler_Null = standalone_Schema_org.apache.arrow.flatbuf.Null;
var standalone_Int = standalone_Schema_org.apache.arrow.flatbuf.Int;
var standalone_FloatingPoint = standalone_Schema_org.apache.arrow.flatbuf.FloatingPoint;
var standalone_typeassembler_Binary = standalone_Schema_org.apache.arrow.flatbuf.Binary;
var standalone_typeassembler_Bool = standalone_Schema_org.apache.arrow.flatbuf.Bool;
var standalone_typeassembler_Utf8 = standalone_Schema_org.apache.arrow.flatbuf.Utf8;
var standalone_typeassembler_Decimal = standalone_Schema_org.apache.arrow.flatbuf.Decimal;
var standalone_typeassembler_Date = standalone_Schema_org.apache.arrow.flatbuf.Date;
var standalone_typeassembler_Time = standalone_Schema_org.apache.arrow.flatbuf.Time;
var standalone_Timestamp = standalone_Schema_org.apache.arrow.flatbuf.Timestamp;
var standalone_Interval = standalone_Schema_org.apache.arrow.flatbuf.Interval;
var standalone_typeassembler_List = standalone_Schema_org.apache.arrow.flatbuf.List;
var standalone_typeassembler_Struct = standalone_Schema_org.apache.arrow.flatbuf.Struct_;
var standalone_typeassembler_Union = standalone_Schema_org.apache.arrow.flatbuf.Union;
var standalone_DictionaryEncoding = standalone_Schema_org.apache.arrow.flatbuf.DictionaryEncoding;
var standalone_typeassembler_FixedSizeBinary = standalone_Schema_org.apache.arrow.flatbuf.FixedSizeBinary;
var standalone_typeassembler_FixedSizeList = standalone_Schema_org.apache.arrow.flatbuf.FixedSizeList;
var standalone_typeassembler_Map_ = standalone_Schema_org.apache.arrow.flatbuf.Map;
/** @ignore */
class standalone_TypeAssembler extends standalone_Visitor {
    visit(node, builder) {
        return (node == null || builder == null) ? undefined : super.visit(node, builder);
    }
    visitNull(_node, b) {
        standalone_typeassembler_Null.startNull(b);
        return standalone_typeassembler_Null.endNull(b);
    }
    visitInt(node, b) {
        standalone_Int.startInt(b);
        standalone_Int.addBitWidth(b, node.bitWidth);
        standalone_Int.addIsSigned(b, node.isSigned);
        return standalone_Int.endInt(b);
    }
    visitFloat(node, b) {
        standalone_FloatingPoint.startFloatingPoint(b);
        standalone_FloatingPoint.addPrecision(b, node.precision);
        return standalone_FloatingPoint.endFloatingPoint(b);
    }
    visitBinary(_node, b) {
        standalone_typeassembler_Binary.startBinary(b);
        return standalone_typeassembler_Binary.endBinary(b);
    }
    visitBool(_node, b) {
        standalone_typeassembler_Bool.startBool(b);
        return standalone_typeassembler_Bool.endBool(b);
    }
    visitUtf8(_node, b) {
        standalone_typeassembler_Utf8.startUtf8(b);
        return standalone_typeassembler_Utf8.endUtf8(b);
    }
    visitDecimal(node, b) {
        standalone_typeassembler_Decimal.startDecimal(b);
        standalone_typeassembler_Decimal.addScale(b, node.scale);
        standalone_typeassembler_Decimal.addPrecision(b, node.precision);
        return standalone_typeassembler_Decimal.endDecimal(b);
    }
    visitDate(node, b) {
        standalone_typeassembler_Date.startDate(b);
        standalone_typeassembler_Date.addUnit(b, node.unit);
        return standalone_typeassembler_Date.endDate(b);
    }
    visitTime(node, b) {
        standalone_typeassembler_Time.startTime(b);
        standalone_typeassembler_Time.addUnit(b, node.unit);
        standalone_typeassembler_Time.addBitWidth(b, node.bitWidth);
        return standalone_typeassembler_Time.endTime(b);
    }
    visitTimestamp(node, b) {
        const timezone = (node.timezone && b.createString(node.timezone)) || undefined;
        standalone_Timestamp.startTimestamp(b);
        standalone_Timestamp.addUnit(b, node.unit);
        if (timezone !== undefined) {
            standalone_Timestamp.addTimezone(b, timezone);
        }
        return standalone_Timestamp.endTimestamp(b);
    }
    visitInterval(node, b) {
        standalone_Interval.startInterval(b);
        standalone_Interval.addUnit(b, node.unit);
        return standalone_Interval.endInterval(b);
    }
    visitList(_node, b) {
        standalone_typeassembler_List.startList(b);
        return standalone_typeassembler_List.endList(b);
    }
    visitStruct(_node, b) {
        standalone_typeassembler_Struct.startStruct_(b);
        return standalone_typeassembler_Struct.endStruct_(b);
    }
    visitUnion(node, b) {
        standalone_typeassembler_Union.startTypeIdsVector(b, node.typeIds.length);
        const typeIds = standalone_typeassembler_Union.createTypeIdsVector(b, node.typeIds);
        standalone_typeassembler_Union.startUnion(b);
        standalone_typeassembler_Union.addMode(b, node.mode);
        standalone_typeassembler_Union.addTypeIds(b, typeIds);
        return standalone_typeassembler_Union.endUnion(b);
    }
    visitDictionary(node, b) {
        const indexType = this.visit(node.indices, b);
        standalone_DictionaryEncoding.startDictionaryEncoding(b);
        standalone_DictionaryEncoding.addId(b, new standalone_typeassembler_Long(node.id, 0));
        standalone_DictionaryEncoding.addIsOrdered(b, node.isOrdered);
        if (indexType !== undefined) {
            standalone_DictionaryEncoding.addIndexType(b, indexType);
        }
        return standalone_DictionaryEncoding.endDictionaryEncoding(b);
    }
    visitFixedSizeBinary(node, b) {
        standalone_typeassembler_FixedSizeBinary.startFixedSizeBinary(b);
        standalone_typeassembler_FixedSizeBinary.addByteWidth(b, node.byteWidth);
        return standalone_typeassembler_FixedSizeBinary.endFixedSizeBinary(b);
    }
    visitFixedSizeList(node, b) {
        standalone_typeassembler_FixedSizeList.startFixedSizeList(b);
        standalone_typeassembler_FixedSizeList.addListSize(b, node.listSize);
        return standalone_typeassembler_FixedSizeList.endFixedSizeList(b);
    }
    visitMap(node, b) {
        standalone_typeassembler_Map_.startMap(b);
        standalone_typeassembler_Map_.addKeysSorted(b, node.keysSorted);
        return standalone_typeassembler_Map_.endMap(b);
    }
}
/** @ignore */
const standalone_typeassembler_instance = new standalone_TypeAssembler();

//# sourceMappingURL=typeassembler.mjs.map

;// ../../node_modules/apache-arrow/ipc/metadata/json.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
function standalone_schemaFromJSON(_schema, dictionaries = new Map()) {
    return new standalone_Schema(standalone_schemaFieldsFromJSON(_schema, dictionaries), standalone_customMetadataFromJSON(_schema['customMetadata']), dictionaries);
}
/** @ignore */
function standalone_recordBatchFromJSON(b) {
    return new src_standalone_RecordBatch(b['count'], standalone_fieldNodesFromJSON(b['columns']), standalone_buffersFromJSON(b['columns']));
}
/** @ignore */
function standalone_dictionaryBatchFromJSON(b) {
    return new src_standalone_DictionaryBatch(standalone_recordBatchFromJSON(b['data']), b['id'], b['isDelta']);
}
/** @ignore */
function standalone_schemaFieldsFromJSON(_schema, dictionaries) {
    return (_schema['fields'] || []).filter(Boolean).map((f) => standalone_schema_Field.fromJSON(f, dictionaries));
}
/** @ignore */
function standalone_fieldChildrenFromJSON(_field, dictionaries) {
    return (_field['children'] || []).filter(Boolean).map((f) => standalone_schema_Field.fromJSON(f, dictionaries));
}
/** @ignore */
function standalone_fieldNodesFromJSON(xs) {
    return (xs || []).reduce((fieldNodes, column) => [
        ...fieldNodes,
        new src_standalone_FieldNode(column['count'], standalone_nullCountFromJSON(column['VALIDITY'])),
        ...standalone_fieldNodesFromJSON(column['children'])
    ], []);
}
/** @ignore */
function standalone_buffersFromJSON(xs, buffers = []) {
    for (let i = -1, n = (xs || []).length; ++i < n;) {
        const column = xs[i];
        column['VALIDITY'] && buffers.push(new standalone_BufferRegion(buffers.length, column['VALIDITY'].length));
        column['TYPE'] && buffers.push(new standalone_BufferRegion(buffers.length, column['TYPE'].length));
        column['OFFSET'] && buffers.push(new standalone_BufferRegion(buffers.length, column['OFFSET'].length));
        column['DATA'] && buffers.push(new standalone_BufferRegion(buffers.length, column['DATA'].length));
        buffers = standalone_buffersFromJSON(column['children'], buffers);
    }
    return buffers;
}
/** @ignore */
function standalone_nullCountFromJSON(validity) {
    return (validity || []).reduce((sum, val) => sum + +(val === 0), 0);
}
/** @ignore */
function standalone_fieldFromJSON(_field, dictionaries) {
    let id;
    let keys;
    let field;
    let dictMeta;
    let type;
    let dictType;
    // If no dictionary encoding
    if (!dictionaries || !(dictMeta = _field['dictionary'])) {
        type = standalone_typeFromJSON(_field, standalone_fieldChildrenFromJSON(_field, dictionaries));
        field = new standalone_schema_Field(_field['name'], type, _field['nullable'], standalone_customMetadataFromJSON(_field['customMetadata']));
    }
    // tslint:disable
    // If dictionary encoded and the first time we've seen this dictionary id, decode
    // the data type and child fields, then wrap in a Dictionary type and insert the
    // data type into the dictionary types map.
    else if (!dictionaries.has(id = dictMeta['id'])) {
        // a dictionary index defaults to signed 32 bit int if unspecified
        keys = (keys = dictMeta['indexType']) ? standalone_indexTypeFromJSON(keys) : new standalone_Int32();
        dictionaries.set(id, type = standalone_typeFromJSON(_field, standalone_fieldChildrenFromJSON(_field, dictionaries)));
        dictType = new standalone_type_Dictionary(type, keys, id, dictMeta['isOrdered']);
        field = new standalone_schema_Field(_field['name'], dictType, _field['nullable'], standalone_customMetadataFromJSON(_field['customMetadata']));
    }
    // If dictionary encoded, and have already seen this dictionary Id in the schema, then reuse the
    // data type and wrap in a new Dictionary type and field.
    else {
        // a dictionary index defaults to signed 32 bit int if unspecified
        keys = (keys = dictMeta['indexType']) ? standalone_indexTypeFromJSON(keys) : new standalone_Int32();
        dictType = new standalone_type_Dictionary(dictionaries.get(id), keys, id, dictMeta['isOrdered']);
        field = new standalone_schema_Field(_field['name'], dictType, _field['nullable'], standalone_customMetadataFromJSON(_field['customMetadata']));
    }
    return field || null;
}
/** @ignore */
function standalone_customMetadataFromJSON(_metadata) {
    return new Map(Object.entries(_metadata || {}));
}
/** @ignore */
function standalone_indexTypeFromJSON(_type) {
    return new standalone_Int_(_type['isSigned'], _type['bitWidth']);
}
/** @ignore */
function standalone_typeFromJSON(f, children) {
    const typeId = f['type']['name'];
    switch (typeId) {
        case 'NONE': return new standalone_Null();
        case 'null': return new standalone_Null();
        case 'binary': return new standalone_Binary();
        case 'utf8': return new standalone_Utf8();
        case 'bool': return new standalone_Bool();
        case 'list': return new standalone_List((children || [])[0]);
        case 'struct': return new standalone_Struct(children || []);
        case 'struct_': return new standalone_Struct(children || []);
    }
    switch (typeId) {
        case 'int': {
            const t = f['type'];
            return new standalone_Int_(t['isSigned'], t['bitWidth']);
        }
        case 'floatingpoint': {
            const t = f['type'];
            return new standalone_Float(standalone_Precision[t['precision']]);
        }
        case 'decimal': {
            const t = f['type'];
            return new standalone_Decimal(t['scale'], t['precision']);
        }
        case 'date': {
            const t = f['type'];
            return new standalone_Date_(standalone_DateUnit[t['unit']]);
        }
        case 'time': {
            const t = f['type'];
            return new standalone_Time_(standalone_enum_TimeUnit[t['unit']], t['bitWidth']);
        }
        case 'timestamp': {
            const t = f['type'];
            return new standalone_Timestamp_(standalone_enum_TimeUnit[t['unit']], t['timezone']);
        }
        case 'interval': {
            const t = f['type'];
            return new standalone_Interval_(standalone_IntervalUnit[t['unit']]);
        }
        case 'union': {
            const t = f['type'];
            return new standalone_Union_(standalone_UnionMode[t['mode']], (t['typeIds'] || []), children || []);
        }
        case 'fixedsizebinary': {
            const t = f['type'];
            return new standalone_FixedSizeBinary(t['byteWidth']);
        }
        case 'fixedsizelist': {
            const t = f['type'];
            return new standalone_FixedSizeList(t['listSize'], (children || [])[0]);
        }
        case 'map': {
            const t = f['type'];
            return new standalone_Map_((children || [])[0], t['keysSorted']);
        }
    }
    throw new Error(`Unrecognized type: "${typeId}"`);
}

//# sourceMappingURL=json.mjs.map

;// ../../node_modules/apache-arrow/ipc/metadata/message.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.








var standalone_message_Long = standalone_flatbuffers.Long;
var standalone_message_Builder = standalone_flatbuffers.Builder;
var standalone_message_ByteBuffer = standalone_flatbuffers.ByteBuffer;
var standalone_message_Type = standalone_Schema_org.apache.arrow.flatbuf.Type;
var src_standalone_Field = standalone_Schema_org.apache.arrow.flatbuf.Field;
var src_standalone_Schema = standalone_Schema_org.apache.arrow.flatbuf.Schema;
var standalone_message_Buffer = standalone_Schema_org.apache.arrow.flatbuf.Buffer;
var standalone_Message = standalone_org.apache.arrow.flatbuf.Message;
var standalone_KeyValue = standalone_Schema_org.apache.arrow.flatbuf.KeyValue;
var standalone_FieldNode = standalone_org.apache.arrow.flatbuf.FieldNode;
var standalone_Endianness = standalone_Schema_org.apache.arrow.flatbuf.Endianness;
var standalone_RecordBatch = standalone_org.apache.arrow.flatbuf.RecordBatch;
var standalone_DictionaryBatch = standalone_org.apache.arrow.flatbuf.DictionaryBatch;

/**
 * @ignore
 * @private
 **/
class src_standalone_Message {
    constructor(bodyLength, version, headerType, header) {
        this._version = version;
        this._headerType = headerType;
        this.body = new Uint8Array(0);
        header && (this._createHeader = () => header);
        this._bodyLength = typeof bodyLength === 'number' ? bodyLength : bodyLength.low;
    }
    /** @nocollapse */
    static fromJSON(msg, headerType) {
        const message = new src_standalone_Message(0, standalone_MetadataVersion.V4, headerType);
        message._createHeader = standalone_messageHeaderFromJSON(msg, headerType);
        return message;
    }
    /** @nocollapse */
    static decode(buf) {
        buf = new standalone_message_ByteBuffer(standalone_toUint8Array(buf));
        const _message = standalone_Message.getRootAsMessage(buf);
        const bodyLength = _message.bodyLength();
        const version = _message.version();
        const headerType = _message.headerType();
        const message = new src_standalone_Message(bodyLength, version, headerType);
        message._createHeader = standalone_decodeMessageHeader(_message, headerType);
        return message;
    }
    /** @nocollapse */
    static encode(message) {
        let b = new standalone_message_Builder(), headerOffset = -1;
        if (message.isSchema()) {
            headerOffset = standalone_Schema.encode(b, message.header());
        }
        else if (message.isRecordBatch()) {
            headerOffset = src_standalone_RecordBatch.encode(b, message.header());
        }
        else if (message.isDictionaryBatch()) {
            headerOffset = src_standalone_DictionaryBatch.encode(b, message.header());
        }
        standalone_Message.startMessage(b);
        standalone_Message.addVersion(b, standalone_MetadataVersion.V4);
        standalone_Message.addHeader(b, headerOffset);
        standalone_Message.addHeaderType(b, message.headerType);
        standalone_Message.addBodyLength(b, new standalone_message_Long(message.bodyLength, 0));
        standalone_Message.finishMessageBuffer(b, standalone_Message.endMessage(b));
        return b.asUint8Array();
    }
    /** @nocollapse */
    static from(header, bodyLength = 0) {
        if (header instanceof standalone_Schema) {
            return new src_standalone_Message(0, standalone_MetadataVersion.V4, standalone_MessageHeader.Schema, header);
        }
        if (header instanceof src_standalone_RecordBatch) {
            return new src_standalone_Message(bodyLength, standalone_MetadataVersion.V4, standalone_MessageHeader.RecordBatch, header);
        }
        if (header instanceof src_standalone_DictionaryBatch) {
            return new src_standalone_Message(bodyLength, standalone_MetadataVersion.V4, standalone_MessageHeader.DictionaryBatch, header);
        }
        throw new Error(`Unrecognized Message header: ${header}`);
    }
    get type() { return this.headerType; }
    get version() { return this._version; }
    get headerType() { return this._headerType; }
    get bodyLength() { return this._bodyLength; }
    header() { return this._createHeader(); }
    isSchema() { return this.headerType === standalone_MessageHeader.Schema; }
    isRecordBatch() { return this.headerType === standalone_MessageHeader.RecordBatch; }
    isDictionaryBatch() { return this.headerType === standalone_MessageHeader.DictionaryBatch; }
}
/**
 * @ignore
 * @private
 **/
class src_standalone_RecordBatch {
    constructor(length, nodes, buffers) {
        this._nodes = nodes;
        this._buffers = buffers;
        this._length = typeof length === 'number' ? length : length.low;
    }
    get nodes() { return this._nodes; }
    get length() { return this._length; }
    get buffers() { return this._buffers; }
}
/**
 * @ignore
 * @private
 **/
class src_standalone_DictionaryBatch {
    constructor(data, id, isDelta = false) {
        this._data = data;
        this._isDelta = isDelta;
        this._id = typeof id === 'number' ? id : id.low;
    }
    get id() { return this._id; }
    get data() { return this._data; }
    get isDelta() { return this._isDelta; }
    get length() { return this.data.length; }
    get nodes() { return this.data.nodes; }
    get buffers() { return this.data.buffers; }
}
/**
 * @ignore
 * @private
 **/
class standalone_BufferRegion {
    constructor(offset, length) {
        this.offset = typeof offset === 'number' ? offset : offset.low;
        this.length = typeof length === 'number' ? length : length.low;
    }
}
/**
 * @ignore
 * @private
 **/
class src_standalone_FieldNode {
    constructor(length, nullCount) {
        this.length = typeof length === 'number' ? length : length.low;
        this.nullCount = typeof nullCount === 'number' ? nullCount : nullCount.low;
    }
}
/** @ignore */
function standalone_messageHeaderFromJSON(message, type) {
    return (() => {
        switch (type) {
            case standalone_MessageHeader.Schema: return standalone_Schema.fromJSON(message);
            case standalone_MessageHeader.RecordBatch: return src_standalone_RecordBatch.fromJSON(message);
            case standalone_MessageHeader.DictionaryBatch: return src_standalone_DictionaryBatch.fromJSON(message);
        }
        throw new Error(`Unrecognized Message type: { name: ${standalone_MessageHeader[type]}, type: ${type} }`);
    });
}
/** @ignore */
function standalone_decodeMessageHeader(message, type) {
    return (() => {
        switch (type) {
            case standalone_MessageHeader.Schema: return standalone_Schema.decode(message.header(new src_standalone_Schema()));
            case standalone_MessageHeader.RecordBatch: return src_standalone_RecordBatch.decode(message.header(new standalone_RecordBatch()), message.version());
            case standalone_MessageHeader.DictionaryBatch: return src_standalone_DictionaryBatch.decode(message.header(new standalone_DictionaryBatch()), message.version());
        }
        throw new Error(`Unrecognized Message type: { name: ${standalone_MessageHeader[type]}, type: ${type} }`);
    });
}
standalone_schema_Field['encode'] = standalone_encodeField;
standalone_schema_Field['decode'] = standalone_decodeField;
standalone_schema_Field['fromJSON'] = standalone_fieldFromJSON;
standalone_Schema['encode'] = standalone_encodeSchema;
standalone_Schema['decode'] = standalone_decodeSchema;
standalone_Schema['fromJSON'] = standalone_schemaFromJSON;
src_standalone_RecordBatch['encode'] = standalone_encodeRecordBatch;
src_standalone_RecordBatch['decode'] = standalone_decodeRecordBatch;
src_standalone_RecordBatch['fromJSON'] = standalone_recordBatchFromJSON;
src_standalone_DictionaryBatch['encode'] = standalone_encodeDictionaryBatch;
src_standalone_DictionaryBatch['decode'] = standalone_decodeDictionaryBatch;
src_standalone_DictionaryBatch['fromJSON'] = standalone_dictionaryBatchFromJSON;
src_standalone_FieldNode['encode'] = standalone_encodeFieldNode;
src_standalone_FieldNode['decode'] = standalone_decodeFieldNode;
standalone_BufferRegion['encode'] = standalone_encodeBufferRegion;
standalone_BufferRegion['decode'] = standalone_decodeBufferRegion;
/** @ignore */
function standalone_decodeSchema(_schema, dictionaries = new Map()) {
    const fields = standalone_decodeSchemaFields(_schema, dictionaries);
    return new standalone_Schema(fields, standalone_decodeCustomMetadata(_schema), dictionaries);
}
/** @ignore */
function standalone_decodeRecordBatch(batch, version = standalone_MetadataVersion.V4) {
    return new src_standalone_RecordBatch(batch.length(), standalone_decodeFieldNodes(batch), standalone_decodeBuffers(batch, version));
}
/** @ignore */
function standalone_decodeDictionaryBatch(batch, version = standalone_MetadataVersion.V4) {
    return new src_standalone_DictionaryBatch(src_standalone_RecordBatch.decode(batch.data(), version), batch.id(), batch.isDelta());
}
/** @ignore */
function standalone_decodeBufferRegion(b) {
    return new standalone_BufferRegion(b.offset(), b.length());
}
/** @ignore */
function standalone_decodeFieldNode(f) {
    return new src_standalone_FieldNode(f.length(), f.nullCount());
}
/** @ignore */
function standalone_decodeFieldNodes(batch) {
    const nodes = [];
    for (let f, i = -1, j = -1, n = batch.nodesLength(); ++i < n;) {
        if (f = batch.nodes(i)) {
            nodes[++j] = src_standalone_FieldNode.decode(f);
        }
    }
    return nodes;
}
/** @ignore */
function standalone_decodeBuffers(batch, version) {
    const bufferRegions = [];
    for (let b, i = -1, j = -1, n = batch.buffersLength(); ++i < n;) {
        if (b = batch.buffers(i)) {
            // If this Arrow buffer was written before version 4,
            // advance the buffer's bb_pos 8 bytes to skip past
            // the now-removed page_id field
            if (version < standalone_MetadataVersion.V4) {
                b.bb_pos += (8 * (i + 1));
            }
            bufferRegions[++j] = standalone_BufferRegion.decode(b);
        }
    }
    return bufferRegions;
}
/** @ignore */
function standalone_decodeSchemaFields(schema, dictionaries) {
    const fields = [];
    for (let f, i = -1, j = -1, n = schema.fieldsLength(); ++i < n;) {
        if (f = schema.fields(i)) {
            fields[++j] = standalone_schema_Field.decode(f, dictionaries);
        }
    }
    return fields;
}
/** @ignore */
function standalone_decodeFieldChildren(field, dictionaries) {
    const children = [];
    for (let f, i = -1, j = -1, n = field.childrenLength(); ++i < n;) {
        if (f = field.children(i)) {
            children[++j] = standalone_schema_Field.decode(f, dictionaries);
        }
    }
    return children;
}
/** @ignore */
function standalone_decodeField(f, dictionaries) {
    let id;
    let field;
    let type;
    let keys;
    let dictType;
    let dictMeta;
    // If no dictionary encoding
    if (!dictionaries || !(dictMeta = f.dictionary())) {
        type = standalone_decodeFieldType(f, standalone_decodeFieldChildren(f, dictionaries));
        field = new standalone_schema_Field(f.name(), type, f.nullable(), standalone_decodeCustomMetadata(f));
    }
    // tslint:disable
    // If dictionary encoded and the first time we've seen this dictionary id, decode
    // the data type and child fields, then wrap in a Dictionary type and insert the
    // data type into the dictionary types map.
    else if (!dictionaries.has(id = dictMeta.id().low)) {
        // a dictionary index defaults to signed 32 bit int if unspecified
        keys = (keys = dictMeta.indexType()) ? standalone_decodeIndexType(keys) : new standalone_Int32();
        dictionaries.set(id, type = standalone_decodeFieldType(f, standalone_decodeFieldChildren(f, dictionaries)));
        dictType = new standalone_type_Dictionary(type, keys, id, dictMeta.isOrdered());
        field = new standalone_schema_Field(f.name(), dictType, f.nullable(), standalone_decodeCustomMetadata(f));
    }
    // If dictionary encoded, and have already seen this dictionary Id in the schema, then reuse the
    // data type and wrap in a new Dictionary type and field.
    else {
        // a dictionary index defaults to signed 32 bit int if unspecified
        keys = (keys = dictMeta.indexType()) ? standalone_decodeIndexType(keys) : new standalone_Int32();
        dictType = new standalone_type_Dictionary(dictionaries.get(id), keys, id, dictMeta.isOrdered());
        field = new standalone_schema_Field(f.name(), dictType, f.nullable(), standalone_decodeCustomMetadata(f));
    }
    return field || null;
}
/** @ignore */
function standalone_decodeCustomMetadata(parent) {
    const data = new Map();
    if (parent) {
        for (let entry, key, i = -1, n = parent.customMetadataLength() | 0; ++i < n;) {
            if ((entry = parent.customMetadata(i)) && (key = entry.key()) != null) {
                data.set(key, entry.value());
            }
        }
    }
    return data;
}
/** @ignore */
function standalone_decodeIndexType(_type) {
    return new standalone_Int_(_type.isSigned(), _type.bitWidth());
}
/** @ignore */
function standalone_decodeFieldType(f, children) {
    const typeId = f.typeType();
    switch (typeId) {
        case standalone_message_Type.NONE: return new standalone_Null();
        case standalone_message_Type.Null: return new standalone_Null();
        case standalone_message_Type.Binary: return new standalone_Binary();
        case standalone_message_Type.Utf8: return new standalone_Utf8();
        case standalone_message_Type.Bool: return new standalone_Bool();
        case standalone_message_Type.List: return new standalone_List((children || [])[0]);
        case standalone_message_Type.Struct_: return new standalone_Struct(children || []);
    }
    switch (typeId) {
        case standalone_message_Type.Int: {
            const t = f.type(new standalone_Schema_org.apache.arrow.flatbuf.Int());
            return new standalone_Int_(t.isSigned(), t.bitWidth());
        }
        case standalone_message_Type.FloatingPoint: {
            const t = f.type(new standalone_Schema_org.apache.arrow.flatbuf.FloatingPoint());
            return new standalone_Float(t.precision());
        }
        case standalone_message_Type.Decimal: {
            const t = f.type(new standalone_Schema_org.apache.arrow.flatbuf.Decimal());
            return new standalone_Decimal(t.scale(), t.precision());
        }
        case standalone_message_Type.Date: {
            const t = f.type(new standalone_Schema_org.apache.arrow.flatbuf.Date());
            return new standalone_Date_(t.unit());
        }
        case standalone_message_Type.Time: {
            const t = f.type(new standalone_Schema_org.apache.arrow.flatbuf.Time());
            return new standalone_Time_(t.unit(), t.bitWidth());
        }
        case standalone_message_Type.Timestamp: {
            const t = f.type(new standalone_Schema_org.apache.arrow.flatbuf.Timestamp());
            return new standalone_Timestamp_(t.unit(), t.timezone());
        }
        case standalone_message_Type.Interval: {
            const t = f.type(new standalone_Schema_org.apache.arrow.flatbuf.Interval());
            return new standalone_Interval_(t.unit());
        }
        case standalone_message_Type.Union: {
            const t = f.type(new standalone_Schema_org.apache.arrow.flatbuf.Union());
            return new standalone_Union_(t.mode(), t.typeIdsArray() || [], children || []);
        }
        case standalone_message_Type.FixedSizeBinary: {
            const t = f.type(new standalone_Schema_org.apache.arrow.flatbuf.FixedSizeBinary());
            return new standalone_FixedSizeBinary(t.byteWidth());
        }
        case standalone_message_Type.FixedSizeList: {
            const t = f.type(new standalone_Schema_org.apache.arrow.flatbuf.FixedSizeList());
            return new standalone_FixedSizeList(t.listSize(), (children || [])[0]);
        }
        case standalone_message_Type.Map: {
            const t = f.type(new standalone_Schema_org.apache.arrow.flatbuf.Map());
            return new standalone_Map_((children || [])[0], t.keysSorted());
        }
    }
    throw new Error(`Unrecognized type: "${standalone_message_Type[typeId]}" (${typeId})`);
}
/** @ignore */
function standalone_encodeSchema(b, schema) {
    const fieldOffsets = schema.fields.map((f) => standalone_schema_Field.encode(b, f));
    src_standalone_Schema.startFieldsVector(b, fieldOffsets.length);
    const fieldsVectorOffset = src_standalone_Schema.createFieldsVector(b, fieldOffsets);
    const metadataOffset = !(schema.metadata && schema.metadata.size > 0) ? -1 :
        src_standalone_Schema.createCustomMetadataVector(b, [...schema.metadata].map(([k, v]) => {
            const key = b.createString(`${k}`);
            const val = b.createString(`${v}`);
            standalone_KeyValue.startKeyValue(b);
            standalone_KeyValue.addKey(b, key);
            standalone_KeyValue.addValue(b, val);
            return standalone_KeyValue.endKeyValue(b);
        }));
    src_standalone_Schema.startSchema(b);
    src_standalone_Schema.addFields(b, fieldsVectorOffset);
    src_standalone_Schema.addEndianness(b, standalone_platformIsLittleEndian ? standalone_Endianness.Little : standalone_Endianness.Big);
    if (metadataOffset !== -1) {
        src_standalone_Schema.addCustomMetadata(b, metadataOffset);
    }
    return src_standalone_Schema.endSchema(b);
}
/** @ignore */
function standalone_encodeField(b, field) {
    let nameOffset = -1;
    let typeOffset = -1;
    let dictionaryOffset = -1;
    let type = field.type;
    let typeId = field.typeId;
    if (!standalone_DataType.isDictionary(type)) {
        typeOffset = standalone_typeassembler_instance.visit(type, b);
    }
    else {
        typeId = type.dictionary.typeId;
        dictionaryOffset = standalone_typeassembler_instance.visit(type, b);
        typeOffset = standalone_typeassembler_instance.visit(type.dictionary, b);
    }
    const childOffsets = (type.children || []).map((f) => standalone_schema_Field.encode(b, f));
    const childrenVectorOffset = src_standalone_Field.createChildrenVector(b, childOffsets);
    const metadataOffset = !(field.metadata && field.metadata.size > 0) ? -1 :
        src_standalone_Field.createCustomMetadataVector(b, [...field.metadata].map(([k, v]) => {
            const key = b.createString(`${k}`);
            const val = b.createString(`${v}`);
            standalone_KeyValue.startKeyValue(b);
            standalone_KeyValue.addKey(b, key);
            standalone_KeyValue.addValue(b, val);
            return standalone_KeyValue.endKeyValue(b);
        }));
    if (field.name) {
        nameOffset = b.createString(field.name);
    }
    src_standalone_Field.startField(b);
    src_standalone_Field.addType(b, typeOffset);
    src_standalone_Field.addTypeType(b, typeId);
    src_standalone_Field.addChildren(b, childrenVectorOffset);
    src_standalone_Field.addNullable(b, !!field.nullable);
    if (nameOffset !== -1) {
        src_standalone_Field.addName(b, nameOffset);
    }
    if (dictionaryOffset !== -1) {
        src_standalone_Field.addDictionary(b, dictionaryOffset);
    }
    if (metadataOffset !== -1) {
        src_standalone_Field.addCustomMetadata(b, metadataOffset);
    }
    return src_standalone_Field.endField(b);
}
/** @ignore */
function standalone_encodeRecordBatch(b, recordBatch) {
    const nodes = recordBatch.nodes || [];
    const buffers = recordBatch.buffers || [];
    standalone_RecordBatch.startNodesVector(b, nodes.length);
    nodes.slice().reverse().forEach((n) => src_standalone_FieldNode.encode(b, n));
    const nodesVectorOffset = b.endVector();
    standalone_RecordBatch.startBuffersVector(b, buffers.length);
    buffers.slice().reverse().forEach((b_) => standalone_BufferRegion.encode(b, b_));
    const buffersVectorOffset = b.endVector();
    standalone_RecordBatch.startRecordBatch(b);
    standalone_RecordBatch.addLength(b, new standalone_message_Long(recordBatch.length, 0));
    standalone_RecordBatch.addNodes(b, nodesVectorOffset);
    standalone_RecordBatch.addBuffers(b, buffersVectorOffset);
    return standalone_RecordBatch.endRecordBatch(b);
}
/** @ignore */
function standalone_encodeDictionaryBatch(b, dictionaryBatch) {
    const dataOffset = src_standalone_RecordBatch.encode(b, dictionaryBatch.data);
    standalone_DictionaryBatch.startDictionaryBatch(b);
    standalone_DictionaryBatch.addId(b, new standalone_message_Long(dictionaryBatch.id, 0));
    standalone_DictionaryBatch.addIsDelta(b, dictionaryBatch.isDelta);
    standalone_DictionaryBatch.addData(b, dataOffset);
    return standalone_DictionaryBatch.endDictionaryBatch(b);
}
/** @ignore */
function standalone_encodeFieldNode(b, node) {
    return standalone_FieldNode.createFieldNode(b, new standalone_message_Long(node.length, 0), new standalone_message_Long(node.nullCount, 0));
}
/** @ignore */
function standalone_encodeBufferRegion(b, node) {
    return standalone_message_Buffer.createBuffer(b, new standalone_message_Long(node.offset, 0), new standalone_message_Long(node.length, 0));
}
/** @ignore */
const standalone_platformIsLittleEndian = (function () {
    const buffer = new ArrayBuffer(2);
    new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
    // Int16Array uses the platform's endianness.
    return new Int16Array(buffer)[0] === 256;
})();

//# sourceMappingURL=message.mjs.map

;// ../../node_modules/apache-arrow/ipc/message.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


var standalone_ipc_message_ByteBuffer = standalone_flatbuffers.ByteBuffer;






/** @ignore */ const standalone_invalidMessageType = (type) => `Expected ${standalone_MessageHeader[type]} Message in stream, but was null or length 0.`;
/** @ignore */ const standalone_nullMessage = (type) => `Header pointer of flatbuffer-encoded ${standalone_MessageHeader[type]} Message is null or length 0.`;
/** @ignore */ const standalone_invalidMessageMetadata = (expected, actual) => `Expected to read ${expected} metadata bytes, but only read ${actual}.`;
/** @ignore */ const standalone_invalidMessageBodyLength = (expected, actual) => `Expected to read ${expected} bytes for message body, but only read ${actual}.`;
/** @ignore */
class standalone_MessageReader {
    constructor(source) {
        this.source = source instanceof standalone_ByteStream ? source : new standalone_ByteStream(source);
    }
    [Symbol.iterator]() { return this; }
    next() {
        let r;
        if ((r = this.readMetadataLength()).done) {
            return standalone_ITERATOR_DONE;
        }
        // ARROW-6313: If the first 4 bytes are continuation indicator (-1), read
        // the next 4 for the 32-bit metadata length. Otherwise, assume this is a
        // pre-v0.15 message, where the first 4 bytes are the metadata length.
        if ((r.value === -1) &&
            (r = this.readMetadataLength()).done) {
            return standalone_ITERATOR_DONE;
        }
        if ((r = this.readMetadata(r.value)).done) {
            return standalone_ITERATOR_DONE;
        }
        return r;
    }
    throw(value) { return this.source.throw(value); }
    return(value) { return this.source.return(value); }
    readMessage(type) {
        let r;
        if ((r = this.next()).done) {
            return null;
        }
        if ((type != null) && r.value.headerType !== type) {
            throw new Error(standalone_invalidMessageType(type));
        }
        return r.value;
    }
    readMessageBody(bodyLength) {
        if (bodyLength <= 0) {
            return new Uint8Array(0);
        }
        const buf = standalone_toUint8Array(this.source.read(bodyLength));
        if (buf.byteLength < bodyLength) {
            throw new Error(standalone_invalidMessageBodyLength(bodyLength, buf.byteLength));
        }
        // 1. Work around bugs in fs.ReadStream's internal Buffer pooling, see: https://github.com/nodejs/node/issues/24817
        // 2. Work around https://github.com/whatwg/streams/blob/0ebe4b042e467d9876d80ae045de3843092ad797/reference-implementation/lib/helpers.js#L126
        return /* 1. */ (buf.byteOffset % 8 === 0) &&
            /* 2. */ (buf.byteOffset + buf.byteLength) <= buf.buffer.byteLength ? buf : buf.slice();
    }
    readSchema(throwIfNull = false) {
        const type = standalone_MessageHeader.Schema;
        const message = this.readMessage(type);
        const schema = message && message.header();
        if (throwIfNull && !schema) {
            throw new Error(standalone_nullMessage(type));
        }
        return schema;
    }
    readMetadataLength() {
        const buf = this.source.read(standalone_PADDING);
        const bb = buf && new standalone_ipc_message_ByteBuffer(buf);
        const len = bb && bb.readInt32(0) || 0;
        return { done: len === 0, value: len };
    }
    readMetadata(metadataLength) {
        const buf = this.source.read(metadataLength);
        if (!buf) {
            return standalone_ITERATOR_DONE;
        }
        if (buf.byteLength < metadataLength) {
            throw new Error(standalone_invalidMessageMetadata(metadataLength, buf.byteLength));
        }
        return { done: false, value: src_standalone_Message.decode(buf) };
    }
}
/** @ignore */
class standalone_AsyncMessageReader {
    constructor(source, byteLength) {
        this.source = source instanceof standalone_AsyncByteStream ? source
            : standalone_isFileHandle(source)
                ? new standalone_AsyncRandomAccessFile(source, byteLength)
                : new standalone_AsyncByteStream(source);
    }
    [Symbol.asyncIterator]() { return this; }
    async next() {
        let r;
        if ((r = await this.readMetadataLength()).done) {
            return standalone_ITERATOR_DONE;
        }
        // ARROW-6313: If the first 4 bytes are continuation indicator (-1), read
        // the next 4 for the 32-bit metadata length. Otherwise, assume this is a
        // pre-v0.15 message, where the first 4 bytes are the metadata length.
        if ((r.value === -1) &&
            (r = await this.readMetadataLength()).done) {
            return standalone_ITERATOR_DONE;
        }
        if ((r = await this.readMetadata(r.value)).done) {
            return standalone_ITERATOR_DONE;
        }
        return r;
    }
    async throw(value) { return await this.source.throw(value); }
    async return(value) { return await this.source.return(value); }
    async readMessage(type) {
        let r;
        if ((r = await this.next()).done) {
            return null;
        }
        if ((type != null) && r.value.headerType !== type) {
            throw new Error(standalone_invalidMessageType(type));
        }
        return r.value;
    }
    async readMessageBody(bodyLength) {
        if (bodyLength <= 0) {
            return new Uint8Array(0);
        }
        const buf = standalone_toUint8Array(await this.source.read(bodyLength));
        if (buf.byteLength < bodyLength) {
            throw new Error(standalone_invalidMessageBodyLength(bodyLength, buf.byteLength));
        }
        // 1. Work around bugs in fs.ReadStream's internal Buffer pooling, see: https://github.com/nodejs/node/issues/24817
        // 2. Work around https://github.com/whatwg/streams/blob/0ebe4b042e467d9876d80ae045de3843092ad797/reference-implementation/lib/helpers.js#L126
        return /* 1. */ (buf.byteOffset % 8 === 0) &&
            /* 2. */ (buf.byteOffset + buf.byteLength) <= buf.buffer.byteLength ? buf : buf.slice();
    }
    async readSchema(throwIfNull = false) {
        const type = standalone_MessageHeader.Schema;
        const message = await this.readMessage(type);
        const schema = message && message.header();
        if (throwIfNull && !schema) {
            throw new Error(standalone_nullMessage(type));
        }
        return schema;
    }
    async readMetadataLength() {
        const buf = await this.source.read(standalone_PADDING);
        const bb = buf && new standalone_ipc_message_ByteBuffer(buf);
        const len = bb && bb.readInt32(0) || 0;
        return { done: len === 0, value: len };
    }
    async readMetadata(metadataLength) {
        const buf = await this.source.read(metadataLength);
        if (!buf) {
            return standalone_ITERATOR_DONE;
        }
        if (buf.byteLength < metadataLength) {
            throw new Error(standalone_invalidMessageMetadata(metadataLength, buf.byteLength));
        }
        return { done: false, value: src_standalone_Message.decode(buf) };
    }
}
/** @ignore */
class standalone_JSONMessageReader extends standalone_MessageReader {
    constructor(source) {
        super(new Uint8Array(0));
        this._schema = false;
        this._body = [];
        this._batchIndex = 0;
        this._dictionaryIndex = 0;
        this._json = source instanceof standalone_ArrowJSON ? source : new standalone_ArrowJSON(source);
    }
    next() {
        const { _json } = this;
        if (!this._schema) {
            this._schema = true;
            const message = src_standalone_Message.fromJSON(_json.schema, standalone_MessageHeader.Schema);
            return { done: false, value: message };
        }
        if (this._dictionaryIndex < _json.dictionaries.length) {
            const batch = _json.dictionaries[this._dictionaryIndex++];
            this._body = batch['data']['columns'];
            const message = src_standalone_Message.fromJSON(batch, standalone_MessageHeader.DictionaryBatch);
            return { done: false, value: message };
        }
        if (this._batchIndex < _json.batches.length) {
            const batch = _json.batches[this._batchIndex++];
            this._body = batch['columns'];
            const message = src_standalone_Message.fromJSON(batch, standalone_MessageHeader.RecordBatch);
            return { done: false, value: message };
        }
        this._body = [];
        return standalone_ITERATOR_DONE;
    }
    readMessageBody(_bodyLength) {
        return flattenDataSources(this._body);
        function flattenDataSources(xs) {
            return (xs || []).reduce((buffers, column) => [
                ...buffers,
                ...(column['VALIDITY'] && [column['VALIDITY']] || []),
                ...(column['TYPE'] && [column['TYPE']] || []),
                ...(column['OFFSET'] && [column['OFFSET']] || []),
                ...(column['DATA'] && [column['DATA']] || []),
                ...flattenDataSources(column['children'])
            ], []);
        }
    }
    readMessage(type) {
        let r;
        if ((r = this.next()).done) {
            return null;
        }
        if ((type != null) && r.value.headerType !== type) {
            throw new Error(standalone_invalidMessageType(type));
        }
        return r.value;
    }
    readSchema() {
        const type = standalone_MessageHeader.Schema;
        const message = this.readMessage(type);
        const schema = message && message.header();
        if (!message || !schema) {
            throw new Error(standalone_nullMessage(type));
        }
        return schema;
    }
}
/** @ignore */
const standalone_PADDING = 4;
/** @ignore */
const standalone_MAGIC_STR = 'ARROW1';
/** @ignore */
const standalone_MAGIC = new Uint8Array(standalone_MAGIC_STR.length);
for (let i = 0; i < standalone_MAGIC_STR.length; i += 1 | 0) {
    standalone_MAGIC[i] = standalone_MAGIC_STR.charCodeAt(i);
}
/** @ignore */
function standalone_checkForMagicArrowString(buffer, index = 0) {
    for (let i = -1, n = standalone_MAGIC.length; ++i < n;) {
        if (standalone_MAGIC[i] !== buffer[index + i]) {
            return false;
        }
    }
    return true;
}
/** @ignore */
const standalone_magicLength = standalone_MAGIC.length;
/** @ignore */
const standalone_magicAndPadding = standalone_magicLength + standalone_PADDING;
/** @ignore */
const standalone_magicX2AndPadding = standalone_magicLength * 2 + standalone_PADDING;

//# sourceMappingURL=message.mjs.map

;// ../../node_modules/apache-arrow/visitor/vectorassembler.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.








/** @ignore */
class standalone_VectorAssembler extends standalone_Visitor {
    constructor() {
        super();
        this._byteLength = 0;
        this._nodes = [];
        this._buffers = [];
        this._bufferRegions = [];
    }
    /** @nocollapse */
    static assemble(...args) {
        const assembler = new standalone_VectorAssembler();
        const vectorChildren = standalone_selectVectorChildrenArgs(standalone_recordbatch_RecordBatch, args);
        const [assembleResult = assembler] = assembler.visitMany(vectorChildren);
        return assembleResult;
    }
    visit(vector) {
        if (!standalone_DataType.isDictionary(vector.type)) {
            const { data, length, nullCount } = vector;
            if (length > 2147483647) {
                /* istanbul ignore next */
                throw new RangeError('Cannot write arrays larger than 2^31 - 1 in length');
            }
            if (!standalone_DataType.isNull(vector.type)) {
                standalone_addBuffer.call(this, nullCount <= 0
                    ? new Uint8Array(0) // placeholder validity buffer
                    : standalone_truncateBitmap(data.offset, length, data.nullBitmap));
            }
            this.nodes.push(new src_standalone_FieldNode(length, nullCount));
        }
        return super.visit(vector);
    }
    visitNull(_nullV) {
        return this;
    }
    visitDictionary(vector) {
        // Assemble the indices here, Dictionary assembled separately.
        return this.visit(vector.indices);
    }
    get nodes() { return this._nodes; }
    get buffers() { return this._buffers; }
    get byteLength() { return this._byteLength; }
    get bufferRegions() { return this._bufferRegions; }
}
/** @ignore */
function standalone_addBuffer(values) {
    const byteLength = (values.byteLength + 7) & ~7; // Round up to a multiple of 8
    this.buffers.push(values);
    this.bufferRegions.push(new standalone_BufferRegion(this._byteLength, byteLength));
    this._byteLength += byteLength;
    return this;
}
/** @ignore */
function standalone_assembleUnion(vector) {
    const { type, length, typeIds, valueOffsets } = vector;
    // All Union Vectors have a typeIds buffer
    standalone_addBuffer.call(this, typeIds);
    // If this is a Sparse Union, treat it like all other Nested types
    if (type.mode === standalone_UnionMode.Sparse) {
        return standalone_assembleNestedVector.call(this, vector);
    }
    else if (type.mode === standalone_UnionMode.Dense) {
        // If this is a Dense Union, add the valueOffsets buffer and potentially slice the children
        if (vector.offset <= 0) {
            // If the Vector hasn't been sliced, write the existing valueOffsets
            standalone_addBuffer.call(this, valueOffsets);
            // We can treat this like all other Nested types
            return standalone_assembleNestedVector.call(this, vector);
        }
        else {
            // A sliced Dense Union is an unpleasant case. Because the offsets are different for
            // each child vector, we need to "rebase" the valueOffsets for each child
            // Union typeIds are not necessary 0-indexed
            const maxChildTypeId = typeIds.reduce((x, y) => Math.max(x, y), typeIds[0]);
            const childLengths = new Int32Array(maxChildTypeId + 1);
            // Set all to -1 to indicate that we haven't observed a first occurrence of a particular child yet
            const childOffsets = new Int32Array(maxChildTypeId + 1).fill(-1);
            const shiftedOffsets = new Int32Array(length);
            // If we have a non-zero offset, then the value offsets do not start at
            // zero. We must a) create a new offsets array with shifted offsets and
            // b) slice the values array accordingly
            const unshiftedOffsets = standalone_rebaseValueOffsets(-valueOffsets[0], length, valueOffsets);
            for (let typeId, shift, index = -1; ++index < length;) {
                if ((shift = childOffsets[typeId = typeIds[index]]) === -1) {
                    shift = childOffsets[typeId] = unshiftedOffsets[typeId];
                }
                shiftedOffsets[index] = unshiftedOffsets[index] - shift;
                ++childLengths[typeId];
            }
            standalone_addBuffer.call(this, shiftedOffsets);
            // Slice and visit children accordingly
            for (let child, childIndex = -1, numChildren = type.children.length; ++childIndex < numChildren;) {
                if (child = vector.getChildAt(childIndex)) {
                    const typeId = type.typeIds[childIndex];
                    const childLength = Math.min(length, childLengths[typeId]);
                    this.visit(child.slice(childOffsets[typeId], childLength));
                }
            }
        }
    }
    return this;
}
/** @ignore */
function standalone_assembleBoolVector(vector) {
    // Bool vector is a special case of FlatVector, as its data buffer needs to stay packed
    let values;
    if (vector.nullCount >= vector.length) {
        // If all values are null, just insert a placeholder empty data buffer (fastest path)
        return standalone_addBuffer.call(this, new Uint8Array(0));
    }
    else if ((values = vector.values) instanceof Uint8Array) {
        // If values is already a Uint8Array, slice the bitmap (fast path)
        return standalone_addBuffer.call(this, standalone_truncateBitmap(vector.offset, vector.length, values));
    }
    // Otherwise if the underlying data *isn't* a Uint8Array, enumerate the
    // values as bools and re-pack them into a Uint8Array. This code isn't
    // reachable unless you're trying to manipulate the Data internals,
    // we we're only doing this for safety.
    /* istanbul ignore next */
    return standalone_addBuffer.call(this, standalone_packBools(vector));
}
/** @ignore */
function standalone_assembleFlatVector(vector) {
    return standalone_addBuffer.call(this, vector.values.subarray(0, vector.length * vector.stride));
}
/** @ignore */
function standalone_assembleFlatListVector(vector) {
    const { length, values, valueOffsets } = vector;
    const firstOffset = valueOffsets[0];
    const lastOffset = valueOffsets[length];
    const byteLength = Math.min(lastOffset - firstOffset, values.byteLength - firstOffset);
    // Push in the order FlatList types read their buffers
    standalone_addBuffer.call(this, standalone_rebaseValueOffsets(-valueOffsets[0], length, valueOffsets)); // valueOffsets buffer first
    standalone_addBuffer.call(this, values.subarray(firstOffset, firstOffset + byteLength)); // sliced values buffer second
    return this;
}
/** @ignore */
function standalone_assembleListVector(vector) {
    const { length, valueOffsets } = vector;
    // If we have valueOffsets (MapVector, ListVector), push that buffer first
    if (valueOffsets) {
        standalone_addBuffer.call(this, standalone_rebaseValueOffsets(valueOffsets[0], length, valueOffsets));
    }
    // Then insert the List's values child
    return this.visit(vector.getChildAt(0));
}
/** @ignore */
function standalone_assembleNestedVector(vector) {
    return this.visitMany(vector.type.children.map((_, i) => vector.getChildAt(i)).filter(Boolean))[0];
}
standalone_VectorAssembler.prototype.visitBool = standalone_assembleBoolVector;
standalone_VectorAssembler.prototype.visitInt = standalone_assembleFlatVector;
standalone_VectorAssembler.prototype.visitFloat = standalone_assembleFlatVector;
standalone_VectorAssembler.prototype.visitUtf8 = standalone_assembleFlatListVector;
standalone_VectorAssembler.prototype.visitBinary = standalone_assembleFlatListVector;
standalone_VectorAssembler.prototype.visitFixedSizeBinary = standalone_assembleFlatVector;
standalone_VectorAssembler.prototype.visitDate = standalone_assembleFlatVector;
standalone_VectorAssembler.prototype.visitTimestamp = standalone_assembleFlatVector;
standalone_VectorAssembler.prototype.visitTime = standalone_assembleFlatVector;
standalone_VectorAssembler.prototype.visitDecimal = standalone_assembleFlatVector;
standalone_VectorAssembler.prototype.visitList = standalone_assembleListVector;
standalone_VectorAssembler.prototype.visitStruct = standalone_assembleNestedVector;
standalone_VectorAssembler.prototype.visitUnion = standalone_assembleUnion;
standalone_VectorAssembler.prototype.visitInterval = standalone_assembleFlatVector;
standalone_VectorAssembler.prototype.visitFixedSizeList = standalone_assembleListVector;
standalone_VectorAssembler.prototype.visitMap = standalone_assembleListVector;

//# sourceMappingURL=vectorassembler.mjs.map

;// ../../node_modules/apache-arrow/visitor/jsontypeassembler.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/** @ignore */
class standalone_JSONTypeAssembler extends standalone_Visitor {
    visit(node) {
        return node == null ? undefined : super.visit(node);
    }
    visitNull({ typeId }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase() };
    }
    visitInt({ typeId, bitWidth, isSigned }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase(), 'bitWidth': bitWidth, 'isSigned': isSigned };
    }
    visitFloat({ typeId, precision }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase(), 'precision': standalone_Precision[precision] };
    }
    visitBinary({ typeId }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase() };
    }
    visitBool({ typeId }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase() };
    }
    visitUtf8({ typeId }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase() };
    }
    visitDecimal({ typeId, scale, precision }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase(), 'scale': scale, 'precision': precision };
    }
    visitDate({ typeId, unit }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase(), 'unit': standalone_DateUnit[unit] };
    }
    visitTime({ typeId, unit, bitWidth }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase(), 'unit': standalone_enum_TimeUnit[unit], bitWidth };
    }
    visitTimestamp({ typeId, timezone, unit }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase(), 'unit': standalone_enum_TimeUnit[unit], timezone };
    }
    visitInterval({ typeId, unit }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase(), 'unit': standalone_IntervalUnit[unit] };
    }
    visitList({ typeId }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase() };
    }
    visitStruct({ typeId }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase() };
    }
    visitUnion({ typeId, mode, typeIds }) {
        return {
            'name': standalone_ArrowType[typeId].toLowerCase(),
            'mode': standalone_UnionMode[mode],
            'typeIds': [...typeIds]
        };
    }
    visitDictionary(node) {
        return this.visit(node.dictionary);
    }
    visitFixedSizeBinary({ typeId, byteWidth }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase(), 'byteWidth': byteWidth };
    }
    visitFixedSizeList({ typeId, listSize }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase(), 'listSize': listSize };
    }
    visitMap({ typeId, keysSorted }) {
        return { 'name': standalone_ArrowType[typeId].toLowerCase(), 'keysSorted': keysSorted };
    }
}

//# sourceMappingURL=jsontypeassembler.mjs.map

;// ../../node_modules/apache-arrow/visitor/jsonvectorassembler.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.










/** @ignore */
class standalone_JSONVectorAssembler extends standalone_Visitor {
    /** @nocollapse */
    static assemble(...args) {
        return new standalone_JSONVectorAssembler().visitMany(standalone_selectColumnChildrenArgs(standalone_recordbatch_RecordBatch, args));
    }
    visit(column) {
        const { data, name, length } = column;
        const { offset, nullCount, nullBitmap } = data;
        const type = standalone_DataType.isDictionary(column.type) ? column.type.indices : column.type;
        const buffers = Object.assign([], data.buffers, { [standalone_BufferType.VALIDITY]: undefined });
        return {
            'name': name,
            'count': length,
            'VALIDITY': standalone_DataType.isNull(type) ? undefined
                : nullCount <= 0 ? Array.from({ length }, () => 1)
                    : [...standalone_iterateBits(nullBitmap, offset, length, null, standalone_getBit)],
            ...super.visit(standalone_AbstractVector.new(data.clone(type, offset, length, 0, buffers)))
        };
    }
    visitNull() { return {}; }
    visitBool({ values, offset, length }) {
        return { 'DATA': [...standalone_iterateBits(values, offset, length, null, standalone_getBool)] };
    }
    visitInt(vector) {
        return {
            'DATA': vector.type.bitWidth < 64
                ? [...vector.values]
                : [...standalone_bigNumsToStrings(vector.values, 2)]
        };
    }
    visitFloat(vector) {
        return { 'DATA': [...vector.values] };
    }
    visitUtf8(vector) {
        return { 'DATA': [...vector], 'OFFSET': [...vector.valueOffsets] };
    }
    visitBinary(vector) {
        return { 'DATA': [...standalone_binaryToString(vector)], OFFSET: [...vector.valueOffsets] };
    }
    visitFixedSizeBinary(vector) {
        return { 'DATA': [...standalone_binaryToString(vector)] };
    }
    visitDate(vector) {
        return {
            'DATA': vector.type.unit === standalone_DateUnit.DAY
                ? [...vector.values]
                : [...standalone_bigNumsToStrings(vector.values, 2)]
        };
    }
    visitTimestamp(vector) {
        return { 'DATA': [...standalone_bigNumsToStrings(vector.values, 2)] };
    }
    visitTime(vector) {
        return {
            'DATA': vector.type.unit < standalone_enum_TimeUnit.MICROSECOND
                ? [...vector.values]
                : [...standalone_bigNumsToStrings(vector.values, 2)]
        };
    }
    visitDecimal(vector) {
        return { 'DATA': [...standalone_bigNumsToStrings(vector.values, 4)] };
    }
    visitList(vector) {
        return {
            'OFFSET': [...vector.valueOffsets],
            'children': vector.type.children.map((f, i) => this.visit(new standalone_apache_arrow_column_Column(f, [vector.getChildAt(i)])))
        };
    }
    visitStruct(vector) {
        return {
            'children': vector.type.children.map((f, i) => this.visit(new standalone_apache_arrow_column_Column(f, [vector.getChildAt(i)])))
        };
    }
    visitUnion(vector) {
        return {
            'TYPE': [...vector.typeIds],
            'OFFSET': vector.type.mode === standalone_UnionMode.Dense ? [...vector.valueOffsets] : undefined,
            'children': vector.type.children.map((f, i) => this.visit(new standalone_apache_arrow_column_Column(f, [vector.getChildAt(i)])))
        };
    }
    visitInterval(vector) {
        return { 'DATA': [...vector.values] };
    }
    visitFixedSizeList(vector) {
        return {
            'children': vector.type.children.map((f, i) => this.visit(new standalone_apache_arrow_column_Column(f, [vector.getChildAt(i)])))
        };
    }
    visitMap(vector) {
        return {
            'OFFSET': [...vector.valueOffsets],
            'children': vector.type.children.map((f, i) => this.visit(new standalone_apache_arrow_column_Column(f, [vector.getChildAt(i)])))
        };
    }
}
/** @ignore */
function* standalone_binaryToString(vector) {
    for (const octets of vector) {
        yield octets.reduce((str, byte) => {
            return `${str}${('0' + (byte & 0xFF).toString(16)).slice(-2)}`;
        }, '').toUpperCase();
    }
}
/** @ignore */
function* standalone_bigNumsToStrings(values, stride) {
    for (let i = -1, n = values.length / stride; ++i < n;) {
        yield `${standalone_BN.new(values.subarray((i + 0) * stride, (i + 1) * stride), false)}`;
    }
}

//# sourceMappingURL=jsonvectorassembler.mjs.map

;// ../../node_modules/apache-arrow/ipc/writer.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

















class standalone_RecordBatchWriter extends standalone_ReadableInterop {
    constructor(options) {
        super();
        this._position = 0;
        this._started = false;
        // @ts-ignore
        this._sink = new standalone_AsyncByteQueue();
        this._schema = null;
        this._dictionaryBlocks = [];
        this._recordBatchBlocks = [];
        this._dictionaryDeltaOffsets = new Map();
        standalone_compat_isObject(options) || (options = { autoDestroy: true, writeLegacyIpcFormat: false });
        this._autoDestroy = (typeof options.autoDestroy === 'boolean') ? options.autoDestroy : true;
        this._writeLegacyIpcFormat = (typeof options.writeLegacyIpcFormat === 'boolean') ? options.writeLegacyIpcFormat : false;
    }
    /** @nocollapse */
    // @ts-ignore
    static throughNode(options) {
        throw new Error(`"throughNode" not available in this environment`);
    }
    /** @nocollapse */
    static throughDOM(
    // @ts-ignore
    writableStrategy, 
    // @ts-ignore
    readableStrategy) {
        throw new Error(`"throughDOM" not available in this environment`);
    }
    toString(sync = false) {
        return this._sink.toString(sync);
    }
    toUint8Array(sync = false) {
        return this._sink.toUint8Array(sync);
    }
    writeAll(input) {
        if (standalone_isPromise(input)) {
            return input.then((x) => this.writeAll(x));
        }
        else if (standalone_isAsyncIterable(input)) {
            return standalone_writeAllAsync(this, input);
        }
        return standalone_writeAll(this, input);
    }
    get closed() { return this._sink.closed; }
    [Symbol.asyncIterator]() { return this._sink[Symbol.asyncIterator](); }
    toDOMStream(options) { return this._sink.toDOMStream(options); }
    toNodeStream(options) { return this._sink.toNodeStream(options); }
    close() {
        return this.reset()._sink.close();
    }
    abort(reason) {
        return this.reset()._sink.abort(reason);
    }
    finish() {
        this._autoDestroy ? this.close() : this.reset(this._sink, this._schema);
        return this;
    }
    reset(sink = this._sink, schema = null) {
        if ((sink === this._sink) || (sink instanceof standalone_AsyncByteQueue)) {
            this._sink = sink;
        }
        else {
            this._sink = new standalone_AsyncByteQueue();
            if (sink && standalone_isWritableDOMStream(sink)) {
                this.toDOMStream({ type: 'bytes' }).pipeTo(sink);
            }
            else if (sink && standalone_isWritableNodeStream(sink)) {
                this.toNodeStream({ objectMode: false }).pipe(sink);
            }
        }
        if (this._started && this._schema) {
            this._writeFooter(this._schema);
        }
        this._started = false;
        this._dictionaryBlocks = [];
        this._recordBatchBlocks = [];
        this._dictionaryDeltaOffsets = new Map();
        if (!schema || !(schema.compareTo(this._schema))) {
            if (schema === null) {
                this._position = 0;
                this._schema = null;
            }
            else {
                this._started = true;
                this._schema = schema;
                this._writeSchema(schema);
            }
        }
        return this;
    }
    write(payload) {
        let schema = null;
        if (!this._sink) {
            throw new Error(`RecordBatchWriter is closed`);
        }
        else if (payload === null || payload === undefined) {
            return this.finish() && undefined;
        }
        else if (payload instanceof standalone_table_Table && !(schema = payload.schema)) {
            return this.finish() && undefined;
        }
        else if (payload instanceof standalone_recordbatch_RecordBatch && !(schema = payload.schema)) {
            return this.finish() && undefined;
        }
        if (schema && !schema.compareTo(this._schema)) {
            if (this._started && this._autoDestroy) {
                return this.close();
            }
            this.reset(this._sink, schema);
        }
        if (payload instanceof standalone_recordbatch_RecordBatch) {
            if (!(payload instanceof standalone_InternalEmptyPlaceholderRecordBatch)) {
                this._writeRecordBatch(payload);
            }
        }
        else if (payload instanceof standalone_table_Table) {
            this.writeAll(payload.chunks);
        }
        else if (standalone_compat_isIterable(payload)) {
            this.writeAll(payload);
        }
    }
    _writeMessage(message, alignment = 8) {
        const a = alignment - 1;
        const buffer = src_standalone_Message.encode(message);
        const flatbufferSize = buffer.byteLength;
        const prefixSize = !this._writeLegacyIpcFormat ? 8 : 4;
        const alignedSize = (flatbufferSize + prefixSize + a) & ~a;
        const nPaddingBytes = alignedSize - flatbufferSize - prefixSize;
        if (message.headerType === standalone_MessageHeader.RecordBatch) {
            this._recordBatchBlocks.push(new standalone_FileBlock(alignedSize, message.bodyLength, this._position));
        }
        else if (message.headerType === standalone_MessageHeader.DictionaryBatch) {
            this._dictionaryBlocks.push(new standalone_FileBlock(alignedSize, message.bodyLength, this._position));
        }
        // If not in legacy pre-0.15.0 mode, write the stream continuation indicator
        if (!this._writeLegacyIpcFormat) {
            this._write(Int32Array.of(-1));
        }
        // Write the flatbuffer size prefix including padding
        this._write(Int32Array.of(alignedSize - prefixSize));
        // Write the flatbuffer
        if (flatbufferSize > 0) {
            this._write(buffer);
        }
        // Write any padding
        return this._writePadding(nPaddingBytes);
    }
    _write(chunk) {
        if (this._started) {
            const buffer = standalone_toUint8Array(chunk);
            if (buffer && buffer.byteLength > 0) {
                this._sink.write(buffer);
                this._position += buffer.byteLength;
            }
        }
        return this;
    }
    _writeSchema(schema) {
        return this._writeMessage(src_standalone_Message.from(schema));
    }
    // @ts-ignore
    _writeFooter(schema) {
        // eos bytes
        return this._writeLegacyIpcFormat
            ? this._write(Int32Array.of(0))
            : this._write(Int32Array.of(-1, 0));
    }
    _writeMagic() {
        return this._write(standalone_MAGIC);
    }
    _writePadding(nBytes) {
        return nBytes > 0 ? this._write(new Uint8Array(nBytes)) : this;
    }
    _writeRecordBatch(batch) {
        const { byteLength, nodes, bufferRegions, buffers } = standalone_VectorAssembler.assemble(batch);
        const recordBatch = new src_standalone_RecordBatch(batch.length, nodes, bufferRegions);
        const message = src_standalone_Message.from(recordBatch, byteLength);
        return this
            ._writeDictionaries(batch)
            ._writeMessage(message)
            ._writeBodyBuffers(buffers);
    }
    _writeDictionaryBatch(dictionary, id, isDelta = false) {
        this._dictionaryDeltaOffsets.set(id, dictionary.length + (this._dictionaryDeltaOffsets.get(id) || 0));
        const { byteLength, nodes, bufferRegions, buffers } = standalone_VectorAssembler.assemble(dictionary);
        const recordBatch = new src_standalone_RecordBatch(dictionary.length, nodes, bufferRegions);
        const dictionaryBatch = new src_standalone_DictionaryBatch(recordBatch, id, isDelta);
        const message = src_standalone_Message.from(dictionaryBatch, byteLength);
        return this
            ._writeMessage(message)
            ._writeBodyBuffers(buffers);
    }
    _writeBodyBuffers(buffers) {
        let buffer;
        let size, padding;
        for (let i = -1, n = buffers.length; ++i < n;) {
            if ((buffer = buffers[i]) && (size = buffer.byteLength) > 0) {
                this._write(buffer);
                if ((padding = ((size + 7) & ~7) - size) > 0) {
                    this._writePadding(padding);
                }
            }
        }
        return this;
    }
    _writeDictionaries(batch) {
        for (let [id, dictionary] of batch.dictionaries) {
            let offset = this._dictionaryDeltaOffsets.get(id) || 0;
            if (offset === 0 || (dictionary = dictionary.slice(offset)).length > 0) {
                const chunks = 'chunks' in dictionary ? dictionary.chunks : [dictionary];
                for (const chunk of chunks) {
                    this._writeDictionaryBatch(chunk, id, offset > 0);
                    offset += chunk.length;
                }
            }
        }
        return this;
    }
}
/** @ignore */
class standalone_RecordBatchStreamWriter extends standalone_RecordBatchWriter {
    /** @nocollapse */
    static writeAll(input, options) {
        const writer = new standalone_RecordBatchStreamWriter(options);
        if (standalone_isPromise(input)) {
            return input.then((x) => writer.writeAll(x));
        }
        else if (standalone_isAsyncIterable(input)) {
            return standalone_writeAllAsync(writer, input);
        }
        return standalone_writeAll(writer, input);
    }
}
/** @ignore */
class standalone_RecordBatchFileWriter extends standalone_RecordBatchWriter {
    /** @nocollapse */
    static writeAll(input) {
        const writer = new standalone_RecordBatchFileWriter();
        if (standalone_isPromise(input)) {
            return input.then((x) => writer.writeAll(x));
        }
        else if (standalone_isAsyncIterable(input)) {
            return standalone_writeAllAsync(writer, input);
        }
        return standalone_writeAll(writer, input);
    }
    constructor() {
        super();
        this._autoDestroy = true;
    }
    // @ts-ignore
    _writeSchema(schema) {
        return this._writeMagic()._writePadding(2);
    }
    _writeFooter(schema) {
        const buffer = standalone_Footer_.encode(new standalone_Footer_(schema, standalone_MetadataVersion.V4, this._recordBatchBlocks, this._dictionaryBlocks));
        return super
            ._writeFooter(schema) // EOS bytes for sequential readers
            ._write(buffer) // Write the flatbuffer
            ._write(Int32Array.of(buffer.byteLength)) // then the footer size suffix
            ._writeMagic(); // then the magic suffix
    }
}
/** @ignore */
class standalone_RecordBatchJSONWriter extends standalone_RecordBatchWriter {
    constructor() {
        super();
        this._autoDestroy = true;
        this._recordBatches = [];
        this._dictionaries = [];
    }
    /** @nocollapse */
    static writeAll(input) {
        return new standalone_RecordBatchJSONWriter().writeAll(input);
    }
    _writeMessage() { return this; }
    // @ts-ignore
    _writeFooter(schema) { return this; }
    _writeSchema(schema) {
        return this._write(`{\n  "schema": ${JSON.stringify({ fields: schema.fields.map(standalone_fieldToJSON) }, null, 2)}`);
    }
    _writeDictionaries(batch) {
        if (batch.dictionaries.size > 0) {
            this._dictionaries.push(batch);
        }
        return this;
    }
    _writeDictionaryBatch(dictionary, id, isDelta = false) {
        this._dictionaryDeltaOffsets.set(id, dictionary.length + (this._dictionaryDeltaOffsets.get(id) || 0));
        this._write(this._dictionaryBlocks.length === 0 ? `    ` : `,\n    `);
        this._write(`${standalone_dictionaryBatchToJSON(dictionary, id, isDelta)}`);
        this._dictionaryBlocks.push(new standalone_FileBlock(0, 0, 0));
        return this;
    }
    _writeRecordBatch(batch) {
        this._writeDictionaries(batch);
        this._recordBatches.push(batch);
        return this;
    }
    close() {
        if (this._dictionaries.length > 0) {
            this._write(`,\n  "dictionaries": [\n`);
            for (const batch of this._dictionaries) {
                super._writeDictionaries(batch);
            }
            this._write(`\n  ]`);
        }
        if (this._recordBatches.length > 0) {
            for (let i = -1, n = this._recordBatches.length; ++i < n;) {
                this._write(i === 0 ? `,\n  "batches": [\n    ` : `,\n    `);
                this._write(`${standalone_recordBatchToJSON(this._recordBatches[i])}`);
                this._recordBatchBlocks.push(new standalone_FileBlock(0, 0, 0));
            }
            this._write(`\n  ]`);
        }
        if (this._schema) {
            this._write(`\n}`);
        }
        this._dictionaries = [];
        this._recordBatches = [];
        return super.close();
    }
}
/** @ignore */
function standalone_writeAll(writer, input) {
    let chunks = input;
    if (input instanceof standalone_table_Table) {
        chunks = input.chunks;
        writer.reset(undefined, input.schema);
    }
    for (const batch of chunks) {
        writer.write(batch);
    }
    return writer.finish();
}
/** @ignore */
async function standalone_writeAllAsync(writer, batches) {
    for await (const batch of batches) {
        writer.write(batch);
    }
    return writer.finish();
}
/** @ignore */
function standalone_fieldToJSON({ name, type, nullable }) {
    const assembler = new standalone_JSONTypeAssembler();
    return {
        'name': name, 'nullable': nullable,
        'type': assembler.visit(type),
        'children': (type.children || []).map(standalone_fieldToJSON),
        'dictionary': !standalone_DataType.isDictionary(type) ? undefined : {
            'id': type.id,
            'isOrdered': type.isOrdered,
            'indexType': assembler.visit(type.indices)
        }
    };
}
/** @ignore */
function standalone_dictionaryBatchToJSON(dictionary, id, isDelta = false) {
    const field = new standalone_schema_Field(`${id}`, dictionary.type, dictionary.nullCount > 0);
    const columns = standalone_JSONVectorAssembler.assemble(new standalone_apache_arrow_column_Column(field, [dictionary]));
    return JSON.stringify({
        'id': id,
        'isDelta': isDelta,
        'data': {
            'count': dictionary.length,
            'columns': columns
        }
    }, null, 2);
}
/** @ignore */
function standalone_recordBatchToJSON(records) {
    return JSON.stringify({
        'count': records.length,
        'columns': standalone_JSONVectorAssembler.assemble(records)
    }, null, 2);
}

//# sourceMappingURL=writer.mjs.map

;// ../../node_modules/apache-arrow/util/recordbatch.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




const standalone_noopBuf = new Uint8Array(0);
const standalone_nullBufs = (bitmapLength) => [
    standalone_noopBuf, standalone_noopBuf, new Uint8Array(bitmapLength), standalone_noopBuf
];
/** @ignore */
function standalone_ensureSameLengthData(schema, chunks, batchLength = chunks.reduce((l, c) => Math.max(l, c.length), 0)) {
    let data;
    let field;
    let i = -1, n = chunks.length;
    const fields = [...schema.fields];
    const batchData = [];
    const bitmapLength = ((batchLength + 63) & ~63) >> 3;
    while (++i < n) {
        if ((data = chunks[i]) && data.length === batchLength) {
            batchData[i] = data;
        }
        else {
            (field = fields[i]).nullable || (fields[i] = fields[i].clone({ nullable: true }));
            batchData[i] = data ? data._changeLengthAndBackfillNullBitmap(batchLength)
                : standalone_Data.new(field.type, 0, batchLength, batchLength, standalone_nullBufs(bitmapLength));
        }
    }
    return [new standalone_Schema(fields), batchLength, batchData];
}
/** @ignore */
function standalone_distributeColumnsIntoRecordBatches(columns) {
    return standalone_distributeVectorsIntoRecordBatches(new standalone_Schema(columns.map(({ field }) => field)), columns);
}
/** @ignore */
function standalone_distributeVectorsIntoRecordBatches(schema, vecs) {
    return standalone_uniformlyDistributeChunksAcrossRecordBatches(schema, vecs.map((v) => v instanceof standalone_Chunked ? v.chunks.map((c) => c.data) : [v.data]));
}
/** @ignore */
function standalone_uniformlyDistributeChunksAcrossRecordBatches(schema, columns) {
    const fields = [...schema.fields];
    const batchArgs = [];
    const memo = { numBatches: columns.reduce((n, c) => Math.max(n, c.length), 0) };
    let numBatches = 0, batchLength = 0;
    let i = -1, numColumns = columns.length;
    let child, childData = [];
    while (memo.numBatches-- > 0) {
        for (batchLength = Number.POSITIVE_INFINITY, i = -1; ++i < numColumns;) {
            childData[i] = child = columns[i].shift();
            batchLength = Math.min(batchLength, child ? child.length : batchLength);
        }
        if (isFinite(batchLength)) {
            childData = standalone_distributeChildData(fields, batchLength, childData, columns, memo);
            if (batchLength > 0) {
                batchArgs[numBatches++] = [batchLength, childData.slice()];
            }
        }
    }
    return [
        schema = new standalone_Schema(fields, schema.metadata),
        batchArgs.map((xs) => new standalone_recordbatch_RecordBatch(schema, ...xs))
    ];
}
/** @ignore */
function standalone_distributeChildData(fields, batchLength, childData, columns, memo) {
    let data;
    let field;
    let length = 0, i = -1, n = columns.length;
    const bitmapLength = ((batchLength + 63) & ~63) >> 3;
    while (++i < n) {
        if ((data = childData[i]) && ((length = data.length) >= batchLength)) {
            if (length === batchLength) {
                childData[i] = data;
            }
            else {
                childData[i] = data.slice(0, batchLength);
                data = data.slice(batchLength, length - batchLength);
                memo.numBatches = Math.max(memo.numBatches, columns[i].unshift(data));
            }
        }
        else {
            (field = fields[i]).nullable || (fields[i] = field.clone({ nullable: true }));
            childData[i] = data ? data._changeLengthAndBackfillNullBitmap(batchLength)
                : standalone_Data.new(field.type, 0, batchLength, batchLength, standalone_nullBufs(bitmapLength));
        }
    }
    return childData;
}

//# sourceMappingURL=recordbatch.mjs.map

;// ../../node_modules/apache-arrow/vector/base.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
class standalone_BaseVector extends standalone_AbstractVector {
    constructor(data, children) {
        super();
        this._children = children;
        this.numChildren = data.childData.length;
        this._bindDataAccessors(this.data = data);
    }
    get type() { return this.data.type; }
    get typeId() { return this.data.typeId; }
    get length() { return this.data.length; }
    get offset() { return this.data.offset; }
    get stride() { return this.data.stride; }
    get nullCount() { return this.data.nullCount; }
    get byteLength() { return this.data.byteLength; }
    get VectorName() { return `${standalone_enum_Type[this.typeId]}Vector`; }
    get ArrayType() { return this.type.ArrayType; }
    get values() { return this.data.values; }
    get typeIds() { return this.data.typeIds; }
    get nullBitmap() { return this.data.nullBitmap; }
    get valueOffsets() { return this.data.valueOffsets; }
    get [Symbol.toStringTag]() { return `${this.VectorName}<${this.type[Symbol.toStringTag]}>`; }
    clone(data, children = this._children) {
        return standalone_AbstractVector.new(data, children);
    }
    concat(...others) {
        return standalone_Chunked.concat(this, ...others);
    }
    slice(begin, end) {
        // Adjust args similar to Array.prototype.slice. Normalize begin/end to
        // clamp between 0 and length, and wrap around on negative indices, e.g.
        // slice(-1, 5) or slice(5, -1)
        return standalone_vector_clampRange(this, begin, end, this._sliceInternal);
    }
    isValid(index) {
        if (this.nullCount > 0) {
            const idx = this.offset + index;
            const val = this.nullBitmap[idx >> 3];
            const mask = (val & (1 << (idx % 8)));
            return mask !== 0;
        }
        return true;
    }
    getChildAt(index) {
        return index < 0 || index >= this.numChildren ? null : ((this._children || (this._children = []))[index] ||
            (this._children[index] = standalone_AbstractVector.new(this.data.childData[index])));
    }
    toJSON() { return [...this]; }
    _sliceInternal(self, begin, end) {
        return self.clone(self.data.slice(begin, end - begin), null);
    }
    // @ts-ignore
    _bindDataAccessors(data) {
        // Implementation in src/vectors/index.ts due to circular dependency/packaging shenanigans
    }
}
standalone_BaseVector.prototype[Symbol.isConcatSpreadable] = true;

//# sourceMappingURL=base.mjs.map

;// ../../node_modules/apache-arrow/vector/binary.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.



/** @ignore */
class standalone_BinaryVector extends standalone_BaseVector {
    asUtf8() {
        return standalone_AbstractVector.new(this.data.clone(new standalone_Utf8()));
    }
}

//# sourceMappingURL=binary.mjs.map

;// ../../node_modules/apache-arrow/vector/bool.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.



/** @ignore */
class standalone_BoolVector extends standalone_BaseVector {
    /** @nocollapse */
    static from(input) {
        return standalone_vectorFromValuesWithType(() => new standalone_Bool(), input);
    }
}

//# sourceMappingURL=bool.mjs.map

;// ../../node_modules/apache-arrow/vector/date.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
class standalone_DateVector extends standalone_BaseVector {
    /** @nocollapse */
    static from(...args) {
        if (args.length === 2) {
            return standalone_vectorFromValuesWithType(() => args[1] === standalone_DateUnit.DAY ? new standalone_DateDay() : new standalone_DateMillisecond(), args[0]);
        }
        return standalone_vectorFromValuesWithType(() => new standalone_DateMillisecond(), args[0]);
    }
}
/** @ignore */
class standalone_DateDayVector extends standalone_DateVector {
}
/** @ignore */
class standalone_DateMillisecondVector extends standalone_DateVector {
}

//# sourceMappingURL=date.mjs.map

;// ../../node_modules/apache-arrow/vector/decimal.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_DecimalVector extends standalone_BaseVector {
}

//# sourceMappingURL=decimal.mjs.map

;// ../../node_modules/apache-arrow/vector/dictionary.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.





/** @ignore */
class standalone_DictionaryVector extends standalone_BaseVector {
    constructor(data) {
        super(data);
        this.indices = standalone_AbstractVector.new(data.clone(this.type.indices));
    }
    /** @nocollapse */
    static from(...args) {
        if (args.length === 3) {
            const [values, indices, keys] = args;
            const type = new standalone_type_Dictionary(values.type, indices, null, null);
            return standalone_AbstractVector.new(standalone_Data.Dictionary(type, 0, keys.length, 0, null, keys, values));
        }
        return standalone_vectorFromValuesWithType(() => args[0].type, args[0]);
    }
    get dictionary() { return this.data.dictionary; }
    reverseLookup(value) { return this.dictionary.indexOf(value); }
    getKey(idx) { return this.indices.get(idx); }
    getValue(key) { return this.dictionary.get(key); }
    setKey(idx, key) { return this.indices.set(idx, key); }
    setValue(key, value) { return this.dictionary.set(key, value); }
}
standalone_DictionaryVector.prototype.indices = null;

//# sourceMappingURL=dictionary.mjs.map

;// ../../node_modules/apache-arrow/vector/fixedsizebinary.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_FixedSizeBinaryVector extends standalone_BaseVector {
}

//# sourceMappingURL=fixedsizebinary.mjs.map

;// ../../node_modules/apache-arrow/vector/fixedsizelist.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_FixedSizeListVector extends standalone_BaseVector {
}

//# sourceMappingURL=fixedsizelist.mjs.map

;// ../../node_modules/apache-arrow/vector/float.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.





/** @ignore */
class standalone_FloatVector extends standalone_BaseVector {
    /** @nocollapse */
    static from(input) {
        let ArrowType = standalone_vectorTypeToDataType(this);
        if ((input instanceof ArrayBuffer) || ArrayBuffer.isView(input)) {
            let InputType = standalone_arrayTypeToDataType(input.constructor) || ArrowType;
            // Special case, infer the Arrow DataType from the input if calling the base
            // FloatVector.from with a TypedArray, e.g. `FloatVector.from(new Float32Array())`
            if (ArrowType === null) {
                ArrowType = InputType;
            }
            // If the DataType inferred from the Vector constructor matches the
            // DataType inferred from the input arguments, return zero-copy view
            if (ArrowType && ArrowType === InputType) {
                let type = new ArrowType();
                let length = input.byteLength / type.ArrayType.BYTES_PER_ELEMENT;
                // If the ArrowType is Float16 but the input type isn't a Uint16Array,
                // let the Float16Builder handle casting the input values to Uint16s.
                if (!standalone_convertTo16Bit(ArrowType, input.constructor)) {
                    return standalone_AbstractVector.new(standalone_Data.Float(type, 0, length, 0, null, input));
                }
            }
        }
        if (ArrowType) {
            // If the DataType inferred from the Vector constructor is different than
            // the DataType inferred from the input TypedArray, or if input isn't a
            // TypedArray, use the Builders to construct the result Vector
            return standalone_vectorFromValuesWithType(() => new ArrowType(), input);
        }
        if ((input instanceof DataView) || (input instanceof ArrayBuffer)) {
            throw new TypeError(`Cannot infer float type from instance of ${input.constructor.name}`);
        }
        throw new TypeError('Unrecognized FloatVector input');
    }
}
/** @ignore */
class standalone_Float16Vector extends standalone_FloatVector {
    // Since JS doesn't have half floats, `toArray()` returns a zero-copy slice
    // of the underlying Uint16Array data. This behavior ensures we don't incur
    // extra compute or copies if you're calling `toArray()` in order to create
    // a buffer for something like WebGL. Buf if you're using JS and want typed
    // arrays of 4-to-8-byte precision, these methods will enumerate the values
    // and clamp to the desired byte lengths.
    toFloat32Array() { return new Float32Array(this); }
    toFloat64Array() { return new Float64Array(this); }
}
/** @ignore */
class standalone_Float32Vector extends standalone_FloatVector {
}
/** @ignore */
class standalone_Float64Vector extends standalone_FloatVector {
}
const standalone_convertTo16Bit = (typeCtor, dataCtor) => {
    return (typeCtor === standalone_Float16) && (dataCtor !== Uint16Array);
};
/** @ignore */
const standalone_arrayTypeToDataType = (ctor) => {
    switch (ctor) {
        case Uint16Array: return standalone_Float16;
        case Float32Array: return standalone_Float32;
        case Float64Array: return standalone_Float64;
        default: return null;
    }
};
/** @ignore */
const standalone_vectorTypeToDataType = (ctor) => {
    switch (ctor) {
        case standalone_Float16Vector: return standalone_Float16;
        case standalone_Float32Vector: return standalone_Float32;
        case standalone_Float64Vector: return standalone_Float64;
        default: return null;
    }
};

//# sourceMappingURL=float.mjs.map

;// ../../node_modules/apache-arrow/vector/interval.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_IntervalVector extends standalone_BaseVector {
}
/** @ignore */
class standalone_IntervalDayTimeVector extends standalone_IntervalVector {
}
/** @ignore */
class standalone_IntervalYearMonthVector extends standalone_IntervalVector {
}

//# sourceMappingURL=interval.mjs.map

;// ../../node_modules/apache-arrow/vector/int.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.







/** @ignore */
class standalone_IntVector extends standalone_BaseVector {
    /** @nocollapse */
    static from(...args) {
        let [input, is64bit = false] = args;
        let ArrowType = standalone_int_vectorTypeToDataType(this, is64bit);
        if ((input instanceof ArrayBuffer) || ArrayBuffer.isView(input)) {
            let InputType = standalone_int_arrayTypeToDataType(input.constructor, is64bit) || ArrowType;
            // Special case, infer the Arrow DataType from the input if calling the base
            // IntVector.from with a TypedArray, e.g. `IntVector.from(new Int32Array())`
            if (ArrowType === null) {
                ArrowType = InputType;
            }
            // If the DataType inferred from the Vector constructor matches the
            // DataType inferred from the input arguments, return zero-copy view
            if (ArrowType && ArrowType === InputType) {
                let type = new ArrowType();
                let length = input.byteLength / type.ArrayType.BYTES_PER_ELEMENT;
                // If the ArrowType is 64bit but the input type is 32bit pairs, update the logical length
                if (standalone_convert32To64Bit(ArrowType, input.constructor)) {
                    length *= 0.5;
                }
                return standalone_AbstractVector.new(standalone_Data.Int(type, 0, length, 0, null, input));
            }
        }
        if (ArrowType) {
            // If the DataType inferred from the Vector constructor is different than
            // the DataType inferred from the input TypedArray, or if input isn't a
            // TypedArray, use the Builders to construct the result Vector
            return standalone_vectorFromValuesWithType(() => new ArrowType(), input);
        }
        if ((input instanceof DataView) || (input instanceof ArrayBuffer)) {
            throw new TypeError(`Cannot infer integer type from instance of ${input.constructor.name}`);
        }
        throw new TypeError('Unrecognized IntVector input');
    }
}
/** @ignore */
class standalone_Int8Vector extends standalone_IntVector {
}
/** @ignore */
class standalone_Int16Vector extends standalone_IntVector {
}
/** @ignore */
class standalone_Int32Vector extends standalone_IntVector {
}
/** @ignore */
class standalone_Int64Vector extends standalone_IntVector {
    toBigInt64Array() {
        return standalone_toBigInt64Array(this.values);
    }
    get values64() {
        return this._values64 || (this._values64 = this.toBigInt64Array());
    }
}
/** @ignore */
class standalone_Uint8Vector extends standalone_IntVector {
}
/** @ignore */
class standalone_Uint16Vector extends standalone_IntVector {
}
/** @ignore */
class standalone_Uint32Vector extends standalone_IntVector {
}
/** @ignore */
class standalone_Uint64Vector extends standalone_IntVector {
    toBigUint64Array() {
        return standalone_toBigUint64Array(this.values);
    }
    get values64() {
        return this._values64 || (this._values64 = this.toBigUint64Array());
    }
}
const standalone_convert32To64Bit = (typeCtor, dataCtor) => {
    return (typeCtor === standalone_Int64 || typeCtor === standalone_Uint64) &&
        (dataCtor === Int32Array || dataCtor === Uint32Array);
};
/** @ignore */
const standalone_int_arrayTypeToDataType = (ctor, is64bit) => {
    switch (ctor) {
        case Int8Array: return standalone_Int8;
        case Int16Array: return standalone_Int16;
        case Int32Array: return is64bit ? standalone_Int64 : standalone_Int32;
        case standalone_BigInt64ArrayCtor: return standalone_Int64;
        case Uint8Array: return standalone_Uint8;
        case Uint16Array: return standalone_Uint16;
        case Uint32Array: return is64bit ? standalone_Uint64 : standalone_Uint32;
        case standalone_BigUint64ArrayCtor: return standalone_Uint64;
        default: return null;
    }
};
/** @ignore */
const standalone_int_vectorTypeToDataType = (ctor, is64bit) => {
    switch (ctor) {
        case standalone_Int8Vector: return standalone_Int8;
        case standalone_Int16Vector: return standalone_Int16;
        case standalone_Int32Vector: return is64bit ? standalone_Int64 : standalone_Int32;
        case standalone_Int64Vector: return standalone_Int64;
        case standalone_Uint8Vector: return standalone_Uint8;
        case standalone_Uint16Vector: return standalone_Uint16;
        case standalone_Uint32Vector: return is64bit ? standalone_Uint64 : standalone_Uint32;
        case standalone_Uint64Vector: return standalone_Uint64;
        default: return null;
    }
};

//# sourceMappingURL=int.mjs.map

;// ../../node_modules/apache-arrow/vector/list.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_ListVector extends standalone_BaseVector {
}

//# sourceMappingURL=list.mjs.map

;// ../../node_modules/apache-arrow/vector/map.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
class standalone_MapVector extends standalone_BaseVector {
    asList() {
        const child = this.type.children[0];
        return standalone_AbstractVector.new(this.data.clone(new standalone_List(child)));
    }
    bind(index) {
        const child = this.getChildAt(0);
        const { [index]: begin, [index + 1]: end } = this.valueOffsets;
        return new standalone_MapRow(child.slice(begin, end));
    }
}

//# sourceMappingURL=map.mjs.map

;// ../../node_modules/apache-arrow/vector/null.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_NullVector extends standalone_BaseVector {
}

//# sourceMappingURL=null.mjs.map

;// ../../node_modules/apache-arrow/vector/struct.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/** @ignore */ const standalone_struct_kRowIndex = Symbol.for('rowIndex');
/** @ignore */
class standalone_StructVector extends standalone_BaseVector {
    bind(index) {
        const proto = this._row || (this._row = new standalone_StructRow(this));
        const bound = Object.create(proto);
        bound[standalone_struct_kRowIndex] = index;
        return bound;
    }
}

//# sourceMappingURL=struct.mjs.map

;// ../../node_modules/apache-arrow/vector/timestamp.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_TimestampVector extends standalone_BaseVector {
}
/** @ignore */
class standalone_TimestampSecondVector extends standalone_TimestampVector {
}
/** @ignore */
class standalone_TimestampMillisecondVector extends standalone_TimestampVector {
}
/** @ignore */
class standalone_TimestampMicrosecondVector extends standalone_TimestampVector {
}
/** @ignore */
class standalone_TimestampNanosecondVector extends standalone_TimestampVector {
}

//# sourceMappingURL=timestamp.mjs.map

;// ../../node_modules/apache-arrow/vector/time.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_TimeVector extends standalone_BaseVector {
}
/** @ignore */
class standalone_TimeSecondVector extends standalone_TimeVector {
}
/** @ignore */
class standalone_TimeMillisecondVector extends standalone_TimeVector {
}
/** @ignore */
class standalone_TimeMicrosecondVector extends standalone_TimeVector {
}
/** @ignore */
class standalone_TimeNanosecondVector extends standalone_TimeVector {
}

//# sourceMappingURL=time.mjs.map

;// ../../node_modules/apache-arrow/vector/union.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_UnionVector extends standalone_BaseVector {
    get typeIdToChildIndex() { return this.data.type.typeIdToChildIndex; }
}
/** @ignore */
class standalone_DenseUnionVector extends standalone_UnionVector {
    get valueOffsets() { return this.data.valueOffsets; }
}
/** @ignore */
class standalone_SparseUnionVector extends standalone_UnionVector {
}

//# sourceMappingURL=union.mjs.map

;// ../../node_modules/apache-arrow/vector/utf8.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
class standalone_Utf8Vector extends standalone_BaseVector {
    /** @nocollapse */
    static from(input) {
        return standalone_vectorFromValuesWithType(() => new standalone_Utf8(), input);
    }
    asBinary() {
        return standalone_AbstractVector.new(this.data.clone(new standalone_Binary()));
    }
}

//# sourceMappingURL=utf8.mjs.map

;// ../../node_modules/apache-arrow/util/fn.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
/** @ignore */
function standalone_partial0(visit) {
    return function () { return visit(this); };
}
/** @ignore */
function standalone_partial1(visit) {
    return function (a) { return visit(this, a); };
}
/** @ignore */
function standalone_partial2(visit) {
    return function (a, b) { return visit(this, a, b); };
}

//# sourceMappingURL=fn.mjs.map

;// ../../node_modules/apache-arrow/visitor/get.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.





/** @ignore */
class standalone_GetVisitor extends standalone_Visitor {
}
/** @ignore */ const standalone_epochDaysToMs = (data, index) => 86400000 * data[index];
/** @ignore */ const standalone_epochMillisecondsLongToMs = (data, index) => 4294967296 * (data[index + 1]) + (data[index] >>> 0);
/** @ignore */ const standalone_epochMicrosecondsLongToMs = (data, index) => 4294967296 * (data[index + 1] / 1000) + ((data[index] >>> 0) / 1000);
/** @ignore */ const standalone_epochNanosecondsLongToMs = (data, index) => 4294967296 * (data[index + 1] / 1000000) + ((data[index] >>> 0) / 1000000);
/** @ignore */ const standalone_epochMillisecondsToDate = (epochMs) => new Date(epochMs);
/** @ignore */ const standalone_epochDaysToDate = (data, index) => standalone_epochMillisecondsToDate(standalone_epochDaysToMs(data, index));
/** @ignore */ const standalone_epochMillisecondsLongToDate = (data, index) => standalone_epochMillisecondsToDate(standalone_epochMillisecondsLongToMs(data, index));
/** @ignore */
const standalone_getNull = (_vector, _index) => null;
/** @ignore */
const standalone_getVariableWidthBytes = (values, valueOffsets, index) => {
    const { [index]: x, [index + 1]: y } = valueOffsets;
    return x != null && y != null ? values.subarray(x, y) : null;
};
/** @ignore */
const standalone_get_getBool = ({ offset, values }, index) => {
    const idx = offset + index;
    const byte = values[idx >> 3];
    return (byte & 1 << (idx % 8)) !== 0;
};
/** @ignore */
const standalone_getDateDay = ({ values }, index) => standalone_epochDaysToDate(values, index);
/** @ignore */
const standalone_getDateMillisecond = ({ values }, index) => standalone_epochMillisecondsLongToDate(values, index * 2);
/** @ignore */
const standalone_getNumeric = ({ stride, values }, index) => values[stride * index];
/** @ignore */
const standalone_getFloat16 = ({ stride, values }, index) => standalone_uint16ToFloat64(values[stride * index]);
/** @ignore */
const standalone_getBigInts = ({ stride, values, type }, index) => standalone_BN.new(values.subarray(stride * index, stride * (index + 1)), type.isSigned);
/** @ignore */
const standalone_getFixedSizeBinary = ({ stride, values }, index) => values.subarray(stride * index, stride * (index + 1));
/** @ignore */
const standalone_getBinary = ({ values, valueOffsets }, index) => standalone_getVariableWidthBytes(values, valueOffsets, index);
/** @ignore */
const standalone_getUtf8 = ({ values, valueOffsets }, index) => {
    const bytes = standalone_getVariableWidthBytes(values, valueOffsets, index);
    return bytes !== null ? standalone_decodeUtf8(bytes) : null;
};
/* istanbul ignore next */
/** @ignore */
const standalone_getInt = (vector, index) => (vector.type.bitWidth < 64
    ? standalone_getNumeric(vector, index)
    : standalone_getBigInts(vector, index));
/* istanbul ignore next */
/** @ignore */
const standalone_getFloat = (vector, index) => (vector.type.precision !== standalone_Precision.HALF
    ? standalone_getNumeric(vector, index)
    : standalone_getFloat16(vector, index));
/* istanbul ignore next */
/** @ignore */
const standalone_getDate = (vector, index) => (vector.type.unit === standalone_DateUnit.DAY
    ? standalone_getDateDay(vector, index)
    : standalone_getDateMillisecond(vector, index));
/** @ignore */
const standalone_getTimestampSecond = ({ values }, index) => 1000 * standalone_epochMillisecondsLongToMs(values, index * 2);
/** @ignore */
const standalone_getTimestampMillisecond = ({ values }, index) => standalone_epochMillisecondsLongToMs(values, index * 2);
/** @ignore */
const standalone_getTimestampMicrosecond = ({ values }, index) => standalone_epochMicrosecondsLongToMs(values, index * 2);
/** @ignore */
const standalone_getTimestampNanosecond = ({ values }, index) => standalone_epochNanosecondsLongToMs(values, index * 2);
/* istanbul ignore next */
/** @ignore */
const standalone_getTimestamp = (vector, index) => {
    switch (vector.type.unit) {
        case standalone_enum_TimeUnit.SECOND: return standalone_getTimestampSecond(vector, index);
        case standalone_enum_TimeUnit.MILLISECOND: return standalone_getTimestampMillisecond(vector, index);
        case standalone_enum_TimeUnit.MICROSECOND: return standalone_getTimestampMicrosecond(vector, index);
        case standalone_enum_TimeUnit.NANOSECOND: return standalone_getTimestampNanosecond(vector, index);
    }
};
/** @ignore */
const standalone_getTimeSecond = ({ values, stride }, index) => values[stride * index];
/** @ignore */
const standalone_getTimeMillisecond = ({ values, stride }, index) => values[stride * index];
/** @ignore */
const standalone_getTimeMicrosecond = ({ values }, index) => standalone_BN.signed(values.subarray(2 * index, 2 * (index + 1)));
/** @ignore */
const standalone_getTimeNanosecond = ({ values }, index) => standalone_BN.signed(values.subarray(2 * index, 2 * (index + 1)));
/* istanbul ignore next */
/** @ignore */
const standalone_getTime = (vector, index) => {
    switch (vector.type.unit) {
        case standalone_enum_TimeUnit.SECOND: return standalone_getTimeSecond(vector, index);
        case standalone_enum_TimeUnit.MILLISECOND: return standalone_getTimeMillisecond(vector, index);
        case standalone_enum_TimeUnit.MICROSECOND: return standalone_getTimeMicrosecond(vector, index);
        case standalone_enum_TimeUnit.NANOSECOND: return standalone_getTimeNanosecond(vector, index);
    }
};
/** @ignore */
const standalone_getDecimal = ({ values }, index) => standalone_BN.decimal(values.subarray(4 * index, 4 * (index + 1)));
/** @ignore */
const standalone_getList = (vector, index) => {
    const child = vector.getChildAt(0), { valueOffsets, stride } = vector;
    return child.slice(valueOffsets[index * stride], valueOffsets[(index * stride) + 1]);
};
/** @ignore */
const standalone_getMap = (vector, index) => {
    return vector.bind(index);
};
/** @ignore */
const standalone_getStruct = (vector, index) => {
    return vector.bind(index);
};
/* istanbul ignore next */
/** @ignore */
const standalone_getUnion = (vector, index) => {
    return vector.type.mode === standalone_UnionMode.Dense ?
        standalone_getDenseUnion(vector, index) :
        standalone_getSparseUnion(vector, index);
};
/** @ignore */
const standalone_getDenseUnion = (vector, index) => {
    const childIndex = vector.typeIdToChildIndex[vector.typeIds[index]];
    const child = vector.getChildAt(childIndex);
    return child ? child.get(vector.valueOffsets[index]) : null;
};
/** @ignore */
const standalone_getSparseUnion = (vector, index) => {
    const childIndex = vector.typeIdToChildIndex[vector.typeIds[index]];
    const child = vector.getChildAt(childIndex);
    return child ? child.get(index) : null;
};
/** @ignore */
const standalone_getDictionary = (vector, index) => {
    return vector.getValue(vector.getKey(index));
};
/* istanbul ignore next */
/** @ignore */
const standalone_getInterval = (vector, index) => (vector.type.unit === standalone_IntervalUnit.DAY_TIME)
    ? standalone_getIntervalDayTime(vector, index)
    : standalone_getIntervalYearMonth(vector, index);
/** @ignore */
const standalone_getIntervalDayTime = ({ values }, index) => values.subarray(2 * index, 2 * (index + 1));
/** @ignore */
const standalone_getIntervalYearMonth = ({ values }, index) => {
    const interval = values[index];
    const int32s = new Int32Array(2);
    int32s[0] = interval / 12 | 0; /* years */
    int32s[1] = interval % 12 | 0; /* months */
    return int32s;
};
/** @ignore */
const standalone_getFixedSizeList = (vector, index) => {
    const child = vector.getChildAt(0), { stride } = vector;
    return child.slice(index * stride, (index + 1) * stride);
};
standalone_GetVisitor.prototype.visitNull = standalone_getNull;
standalone_GetVisitor.prototype.visitBool = standalone_get_getBool;
standalone_GetVisitor.prototype.visitInt = standalone_getInt;
standalone_GetVisitor.prototype.visitInt8 = standalone_getNumeric;
standalone_GetVisitor.prototype.visitInt16 = standalone_getNumeric;
standalone_GetVisitor.prototype.visitInt32 = standalone_getNumeric;
standalone_GetVisitor.prototype.visitInt64 = standalone_getBigInts;
standalone_GetVisitor.prototype.visitUint8 = standalone_getNumeric;
standalone_GetVisitor.prototype.visitUint16 = standalone_getNumeric;
standalone_GetVisitor.prototype.visitUint32 = standalone_getNumeric;
standalone_GetVisitor.prototype.visitUint64 = standalone_getBigInts;
standalone_GetVisitor.prototype.visitFloat = standalone_getFloat;
standalone_GetVisitor.prototype.visitFloat16 = standalone_getFloat16;
standalone_GetVisitor.prototype.visitFloat32 = standalone_getNumeric;
standalone_GetVisitor.prototype.visitFloat64 = standalone_getNumeric;
standalone_GetVisitor.prototype.visitUtf8 = standalone_getUtf8;
standalone_GetVisitor.prototype.visitBinary = standalone_getBinary;
standalone_GetVisitor.prototype.visitFixedSizeBinary = standalone_getFixedSizeBinary;
standalone_GetVisitor.prototype.visitDate = standalone_getDate;
standalone_GetVisitor.prototype.visitDateDay = standalone_getDateDay;
standalone_GetVisitor.prototype.visitDateMillisecond = standalone_getDateMillisecond;
standalone_GetVisitor.prototype.visitTimestamp = standalone_getTimestamp;
standalone_GetVisitor.prototype.visitTimestampSecond = standalone_getTimestampSecond;
standalone_GetVisitor.prototype.visitTimestampMillisecond = standalone_getTimestampMillisecond;
standalone_GetVisitor.prototype.visitTimestampMicrosecond = standalone_getTimestampMicrosecond;
standalone_GetVisitor.prototype.visitTimestampNanosecond = standalone_getTimestampNanosecond;
standalone_GetVisitor.prototype.visitTime = standalone_getTime;
standalone_GetVisitor.prototype.visitTimeSecond = standalone_getTimeSecond;
standalone_GetVisitor.prototype.visitTimeMillisecond = standalone_getTimeMillisecond;
standalone_GetVisitor.prototype.visitTimeMicrosecond = standalone_getTimeMicrosecond;
standalone_GetVisitor.prototype.visitTimeNanosecond = standalone_getTimeNanosecond;
standalone_GetVisitor.prototype.visitDecimal = standalone_getDecimal;
standalone_GetVisitor.prototype.visitList = standalone_getList;
standalone_GetVisitor.prototype.visitStruct = standalone_getStruct;
standalone_GetVisitor.prototype.visitUnion = standalone_getUnion;
standalone_GetVisitor.prototype.visitDenseUnion = standalone_getDenseUnion;
standalone_GetVisitor.prototype.visitSparseUnion = standalone_getSparseUnion;
standalone_GetVisitor.prototype.visitDictionary = standalone_getDictionary;
standalone_GetVisitor.prototype.visitInterval = standalone_getInterval;
standalone_GetVisitor.prototype.visitIntervalDayTime = standalone_getIntervalDayTime;
standalone_GetVisitor.prototype.visitIntervalYearMonth = standalone_getIntervalYearMonth;
standalone_GetVisitor.prototype.visitFixedSizeList = standalone_getFixedSizeList;
standalone_GetVisitor.prototype.visitMap = standalone_getMap;
/** @ignore */
const standalone_get_instance = new standalone_GetVisitor();

//# sourceMappingURL=get.mjs.map

;// ../../node_modules/apache-arrow/visitor/indexof.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.



/** @ignore */
class standalone_IndexOfVisitor extends standalone_Visitor {
}
/** @ignore */
function standalone_nullIndexOf(vector, searchElement) {
    // if you're looking for nulls and the vector isn't empty, we've got 'em!
    return searchElement === null && vector.length > 0 ? 0 : -1;
}
/** @ignore */
function standalone_indexOfNull(vector, fromIndex) {
    const { nullBitmap } = vector.data;
    if (!nullBitmap || vector.nullCount <= 0) {
        return -1;
    }
    let i = 0;
    for (const isValid of standalone_iterateBits(nullBitmap, vector.data.offset + (fromIndex || 0), vector.length, nullBitmap, standalone_getBool)) {
        if (!isValid) {
            return i;
        }
        ++i;
    }
    return -1;
}
/** @ignore */
function standalone_indexOfValue(vector, searchElement, fromIndex) {
    if (searchElement === undefined) {
        return -1;
    }
    if (searchElement === null) {
        return standalone_indexOfNull(vector, fromIndex);
    }
    const compare = standalone_createElementComparator(searchElement);
    for (let i = (fromIndex || 0) - 1, n = vector.length; ++i < n;) {
        if (compare(vector.get(i))) {
            return i;
        }
    }
    return -1;
}
/** @ignore */
function standalone_indexOfUnion(vector, searchElement, fromIndex) {
    // Unions are special -- they do have a nullBitmap, but so can their children.
    // If the searchElement is null, we don't know whether it came from the Union's
    // bitmap or one of its childrens'. So we don't interrogate the Union's bitmap,
    // since that will report the wrong index if a child has a null before the Union.
    const compare = standalone_createElementComparator(searchElement);
    for (let i = (fromIndex || 0) - 1, n = vector.length; ++i < n;) {
        if (compare(vector.get(i))) {
            return i;
        }
    }
    return -1;
}
standalone_IndexOfVisitor.prototype.visitNull = standalone_nullIndexOf;
standalone_IndexOfVisitor.prototype.visitBool = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitInt = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitInt8 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitInt16 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitInt32 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitInt64 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitUint8 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitUint16 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitUint32 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitUint64 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitFloat = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitFloat16 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitFloat32 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitFloat64 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitUtf8 = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitBinary = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitFixedSizeBinary = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitDate = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitDateDay = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitDateMillisecond = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitTimestamp = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitTimestampSecond = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitTimestampMillisecond = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitTimestampMicrosecond = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitTimestampNanosecond = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitTime = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitTimeSecond = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitTimeMillisecond = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitTimeMicrosecond = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitTimeNanosecond = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitDecimal = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitList = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitStruct = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitUnion = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitDenseUnion = standalone_indexOfUnion;
standalone_IndexOfVisitor.prototype.visitSparseUnion = standalone_indexOfUnion;
standalone_IndexOfVisitor.prototype.visitDictionary = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitInterval = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitIntervalDayTime = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitIntervalYearMonth = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitFixedSizeList = standalone_indexOfValue;
standalone_IndexOfVisitor.prototype.visitMap = standalone_indexOfValue;
/** @ignore */
const standalone_indexof_instance = new standalone_IndexOfVisitor();

//# sourceMappingURL=indexof.mjs.map

;// ../../node_modules/apache-arrow/visitor/iterator.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.




/** @ignore */
class standalone_IteratorVisitor extends standalone_Visitor {
}
/** @ignore */
function standalone_nullableIterator(vector) {
    const getFn = standalone_get_instance.getVisitFn(vector);
    return standalone_iterateBits(vector.data.nullBitmap, vector.data.offset, vector.length, vector, (vec, idx, nullByte, nullBit) => ((nullByte & 1 << nullBit) !== 0) ? getFn(vec, idx) : null);
}
/** @ignore */
function standalone_vectorIterator(vector) {
    // If nullable, iterate manually
    if (vector.nullCount > 0) {
        return standalone_nullableIterator(vector);
    }
    const { type, typeId, length } = vector;
    // Fast case, defer to native iterators if possible
    if (vector.stride === 1 && ((typeId === standalone_enum_Type.Timestamp) ||
        (typeId === standalone_enum_Type.Int && type.bitWidth !== 64) ||
        (typeId === standalone_enum_Type.Time && type.bitWidth !== 64) ||
        (typeId === standalone_enum_Type.Float && type.precision > 0 /* Precision.HALF */))) {
        return vector.data.values.subarray(0, length)[Symbol.iterator]();
    }
    // Otherwise, iterate manually
    return (function* (getFn) {
        for (let index = -1; ++index < length;) {
            yield getFn(vector, index);
        }
    })(standalone_get_instance.getVisitFn(vector));
}
standalone_IteratorVisitor.prototype.visitNull = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitBool = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitInt = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitInt8 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitInt16 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitInt32 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitInt64 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitUint8 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitUint16 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitUint32 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitUint64 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitFloat = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitFloat16 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitFloat32 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitFloat64 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitUtf8 = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitBinary = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitFixedSizeBinary = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitDate = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitDateDay = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitDateMillisecond = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitTimestamp = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitTimestampSecond = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitTimestampMillisecond = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitTimestampMicrosecond = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitTimestampNanosecond = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitTime = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitTimeSecond = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitTimeMillisecond = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitTimeMicrosecond = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitTimeNanosecond = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitDecimal = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitList = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitStruct = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitUnion = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitDenseUnion = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitSparseUnion = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitDictionary = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitInterval = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitIntervalDayTime = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitIntervalYearMonth = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitFixedSizeList = standalone_vectorIterator;
standalone_IteratorVisitor.prototype.visitMap = standalone_vectorIterator;
/** @ignore */
const standalone_iterator_instance = new standalone_IteratorVisitor();

//# sourceMappingURL=iterator.mjs.map

;// ../../node_modules/apache-arrow/visitor/toarray.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.



/** @ignore */
class standalone_ToArrayVisitor extends standalone_Visitor {
}
/** @ignore */
function standalone_arrayOfVector(vector) {
    const { type, length, stride } = vector;
    // Fast case, return subarray if possible
    switch (type.typeId) {
        case standalone_enum_Type.Int:
        case standalone_enum_Type.Float:
        case standalone_enum_Type.Decimal:
        case standalone_enum_Type.Time:
        case standalone_enum_Type.Timestamp:
            return vector.data.values.subarray(0, length * stride);
    }
    // Otherwise if not primitive, slow copy
    return [...standalone_iterator_instance.visit(vector)];
}
standalone_ToArrayVisitor.prototype.visitNull = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitBool = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitInt = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitInt8 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitInt16 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitInt32 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitInt64 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitUint8 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitUint16 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitUint32 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitUint64 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitFloat = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitFloat16 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitFloat32 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitFloat64 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitUtf8 = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitBinary = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitFixedSizeBinary = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitDate = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitDateDay = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitDateMillisecond = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitTimestamp = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitTimestampSecond = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitTimestampMillisecond = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitTimestampMicrosecond = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitTimestampNanosecond = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitTime = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitTimeSecond = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitTimeMillisecond = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitTimeMicrosecond = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitTimeNanosecond = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitDecimal = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitList = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitStruct = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitUnion = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitDenseUnion = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitSparseUnion = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitDictionary = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitInterval = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitIntervalDayTime = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitIntervalYearMonth = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitFixedSizeList = standalone_arrayOfVector;
standalone_ToArrayVisitor.prototype.visitMap = standalone_arrayOfVector;
/** @ignore */
const standalone_toarray_instance = new standalone_ToArrayVisitor();

//# sourceMappingURL=toarray.mjs.map

;// ../../node_modules/apache-arrow/visitor/bytewidth.mjs
/* istanbul ignore file */


/** @ignore */ const standalone_bytewidth_sum = (x, y) => x + y;
/** @ignore */ const standalone_variableWidthColumnErrorMessage = (type) => `Cannot compute the byte width of variable-width column ${type}`;
/** @ignore */
class standalone_ByteWidthVisitor extends standalone_Visitor {
    visitNull(____) { return 0; }
    visitInt(type) { return type.bitWidth / 8; }
    visitFloat(type) { return type.ArrayType.BYTES_PER_ELEMENT; }
    visitBinary(type) { throw new Error(standalone_variableWidthColumnErrorMessage(type)); }
    visitUtf8(type) { throw new Error(standalone_variableWidthColumnErrorMessage(type)); }
    visitBool(____) { return 1 / 8; }
    visitDecimal(____) { return 16; }
    visitDate(type) { return (type.unit + 1) * 4; }
    visitTime(type) { return type.bitWidth / 8; }
    visitTimestamp(type) { return type.unit === standalone_enum_TimeUnit.SECOND ? 4 : 8; }
    visitInterval(type) { return (type.unit + 1) * 4; }
    visitList(type) { throw new Error(standalone_variableWidthColumnErrorMessage(type)); }
    visitStruct(type) { return this.visitFields(type.children).reduce(standalone_bytewidth_sum, 0); }
    visitUnion(type) { return this.visitFields(type.children).reduce(standalone_bytewidth_sum, 0); }
    visitFixedSizeBinary(type) { return type.byteWidth; }
    visitFixedSizeList(type) { return type.listSize * this.visitFields(type.children).reduce(standalone_bytewidth_sum, 0); }
    visitMap(type) { return this.visitFields(type.children).reduce(standalone_bytewidth_sum, 0); }
    visitDictionary(type) { return this.visit(type.indices); }
    visitFields(fields) { return (fields || []).map((field) => this.visit(field.type)); }
    visitSchema(schema) { return this.visitFields(schema.fields).reduce(standalone_bytewidth_sum, 0); }
}
/** @ignore */
const standalone_bytewidth_instance = new standalone_ByteWidthVisitor();

//# sourceMappingURL=bytewidth.mjs.map

;// ../../node_modules/apache-arrow/visitor/vectorctor.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.



















/** @ignore */
class standalone_GetVectorConstructor extends standalone_Visitor {
    visitNull() { return standalone_NullVector; }
    visitBool() { return standalone_BoolVector; }
    visitInt() { return standalone_IntVector; }
    visitInt8() { return standalone_Int8Vector; }
    visitInt16() { return standalone_Int16Vector; }
    visitInt32() { return standalone_Int32Vector; }
    visitInt64() { return standalone_Int64Vector; }
    visitUint8() { return standalone_Uint8Vector; }
    visitUint16() { return standalone_Uint16Vector; }
    visitUint32() { return standalone_Uint32Vector; }
    visitUint64() { return standalone_Uint64Vector; }
    visitFloat() { return standalone_FloatVector; }
    visitFloat16() { return standalone_Float16Vector; }
    visitFloat32() { return standalone_Float32Vector; }
    visitFloat64() { return standalone_Float64Vector; }
    visitUtf8() { return standalone_Utf8Vector; }
    visitBinary() { return standalone_BinaryVector; }
    visitFixedSizeBinary() { return standalone_FixedSizeBinaryVector; }
    visitDate() { return standalone_DateVector; }
    visitDateDay() { return standalone_DateDayVector; }
    visitDateMillisecond() { return standalone_DateMillisecondVector; }
    visitTimestamp() { return standalone_TimestampVector; }
    visitTimestampSecond() { return standalone_TimestampSecondVector; }
    visitTimestampMillisecond() { return standalone_TimestampMillisecondVector; }
    visitTimestampMicrosecond() { return standalone_TimestampMicrosecondVector; }
    visitTimestampNanosecond() { return standalone_TimestampNanosecondVector; }
    visitTime() { return standalone_TimeVector; }
    visitTimeSecond() { return standalone_TimeSecondVector; }
    visitTimeMillisecond() { return standalone_TimeMillisecondVector; }
    visitTimeMicrosecond() { return standalone_TimeMicrosecondVector; }
    visitTimeNanosecond() { return standalone_TimeNanosecondVector; }
    visitDecimal() { return standalone_DecimalVector; }
    visitList() { return standalone_ListVector; }
    visitStruct() { return standalone_StructVector; }
    visitUnion() { return standalone_UnionVector; }
    visitDenseUnion() { return standalone_DenseUnionVector; }
    visitSparseUnion() { return standalone_SparseUnionVector; }
    visitDictionary() { return standalone_DictionaryVector; }
    visitInterval() { return standalone_IntervalVector; }
    visitIntervalDayTime() { return standalone_IntervalDayTimeVector; }
    visitIntervalYearMonth() { return standalone_IntervalYearMonthVector; }
    visitFixedSizeList() { return standalone_FixedSizeListVector; }
    visitMap() { return standalone_MapVector; }
}
/** @ignore */
const standalone_vectorctor_instance = new standalone_GetVectorConstructor();

//# sourceMappingURL=vectorctor.mjs.map

;// ../../node_modules/apache-arrow/vector/index.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.





































/** @nocollapse */
standalone_AbstractVector.new = standalone_newVector;
/** @nocollapse */
standalone_AbstractVector.from = standalone_vectorFrom;
/** @ignore */
function standalone_newVector(data, ...args) {
    return new (standalone_vectorctor_instance.getVisitFn(data)())(data, ...args);
}
/** @ignore */
function standalone_vectorFromValuesWithType(newDataType, input) {
    if (standalone_compat_isIterable(input)) {
        return standalone_AbstractVector.from({ 'nullValues': [null, undefined], type: newDataType(), 'values': input });
    }
    else if (standalone_isAsyncIterable(input)) {
        return standalone_AbstractVector.from({ 'nullValues': [null, undefined], type: newDataType(), 'values': input });
    }
    const { 'values': values = [], 'type': type = newDataType(), 'nullValues': nullValues = [null, undefined], } = { ...input };
    return standalone_compat_isIterable(values)
        ? standalone_AbstractVector.from({ nullValues, ...input, type })
        : standalone_AbstractVector.from({ nullValues, ...input, type });
}
function standalone_vectorFrom(input) {
    const { 'values': values = [], ...options } = { 'nullValues': [null, undefined], ...input };
    if (standalone_compat_isIterable(values)) {
        const chunks = [...standalone_Builder.throughIterable(options)(values)];
        return (chunks.length === 1 ? chunks[0] : standalone_Chunked.concat(chunks));
    }
    return (async (chunks) => {
        const transform = standalone_Builder.throughAsyncIterable(options);
        for await (const chunk of transform(values)) {
            chunks.push(chunk);
        }
        return (chunks.length === 1 ? chunks[0] : standalone_Chunked.concat(chunks));
    })([]);
}
//
// We provide the following method implementations for code navigability purposes only.
// They're overridden at runtime below with the specific Visitor implementation for each type,
// short-circuiting the usual Visitor traversal and reducing intermediate lookups and calls.
// This comment is here to remind you to not set breakpoints in these function bodies, or to inform
// you why the breakpoints you have already set are not being triggered. Have a great day!
//
standalone_BaseVector.prototype.get = function baseVectorGet(index) {
    return standalone_get_instance.visit(this, index);
};
standalone_BaseVector.prototype.set = function baseVectorSet(index, value) {
    return standalone_set_instance.visit(this, index, value);
};
standalone_BaseVector.prototype.indexOf = function baseVectorIndexOf(value, fromIndex) {
    return standalone_indexof_instance.visit(this, value, fromIndex);
};
standalone_BaseVector.prototype.toArray = function baseVectorToArray() {
    return standalone_toarray_instance.visit(this);
};
standalone_BaseVector.prototype.getByteWidth = function baseVectorGetByteWidth() {
    return standalone_bytewidth_instance.visit(this.type);
};
standalone_BaseVector.prototype[Symbol.iterator] = function baseVectorSymbolIterator() {
    return standalone_iterator_instance.visit(this);
};
standalone_BaseVector.prototype._bindDataAccessors = standalone_bindBaseVectorDataAccessors;
// Perf: bind and assign the operator Visitor methods to each of the Vector subclasses for each Type
Object.keys(standalone_enum_Type)
    .map((T) => standalone_enum_Type[T])
    .filter((T) => typeof T === 'number')
    .filter((typeId) => typeId !== standalone_enum_Type.NONE)
    .forEach((typeId) => {
    const VectorCtor = standalone_vectorctor_instance.visit(typeId);
    VectorCtor.prototype['get'] = standalone_partial1(standalone_get_instance.getVisitFn(typeId));
    VectorCtor.prototype['set'] = standalone_partial2(standalone_set_instance.getVisitFn(typeId));
    VectorCtor.prototype['indexOf'] = standalone_partial2(standalone_indexof_instance.getVisitFn(typeId));
    VectorCtor.prototype['toArray'] = standalone_partial0(standalone_toarray_instance.getVisitFn(typeId));
    VectorCtor.prototype['getByteWidth'] = standalone_partialType0(standalone_bytewidth_instance.getVisitFn(typeId));
    VectorCtor.prototype[Symbol.iterator] = standalone_partial0(standalone_iterator_instance.getVisitFn(typeId));
});
/** @ignore */
function standalone_partialType0(visit) {
    return function () { return visit(this.type); };
}
/** @ignore */
function standalone_wrapNullableGet(fn) {
    return function (i) { return this.isValid(i) ? fn.call(this, i) : null; };
}
/** @ignore */
function standalone_wrapNullableSet(fn) {
    return function (i, a) {
        if (standalone_setBool(this.nullBitmap, this.offset + i, !(a === null || a === undefined))) {
            fn.call(this, i, a);
        }
    };
}
/** @ignore */
function standalone_bindBaseVectorDataAccessors() {
    const nullBitmap = this.nullBitmap;
    if (nullBitmap && nullBitmap.byteLength > 0) {
        this.get = standalone_wrapNullableGet(this.get);
        this.set = standalone_wrapNullableSet(this.set);
    }
}

//# sourceMappingURL=index.mjs.map

;// ../../node_modules/apache-arrow/table.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.










class standalone_table_Table extends standalone_Chunked {
    constructor(...args) {
        let schema = null;
        if (args[0] instanceof standalone_Schema) {
            schema = args.shift();
        }
        let chunks = standalone_selectArgs(standalone_recordbatch_RecordBatch, args);
        if (!schema && !(schema = chunks[0] && chunks[0].schema)) {
            throw new TypeError('Table must be initialized with a Schema or at least one RecordBatch');
        }
        chunks[0] || (chunks[0] = new standalone_InternalEmptyPlaceholderRecordBatch(schema));
        super(new standalone_Struct(schema.fields), chunks);
        this._schema = schema;
        this._chunks = chunks;
    }
    /** @nocollapse */
    static empty(schema = new standalone_Schema([])) { return new standalone_table_Table(schema, []); }
    /** @nocollapse */
    static from(input) {
        if (!input) {
            return standalone_table_Table.empty();
        }
        if (typeof input === 'object') {
            let table = standalone_compat_isIterable(input['values']) ? standalone_tableFromIterable(input)
                : standalone_isAsyncIterable(input['values']) ? standalone_tableFromAsyncIterable(input)
                    : null;
            if (table !== null) {
                return table;
            }
        }
        let reader = standalone_RecordBatchReader.from(input);
        if (standalone_isPromise(reader)) {
            return (async () => await standalone_table_Table.from(await reader))();
        }
        if (reader.isSync() && (reader = reader.open())) {
            return !reader.schema ? standalone_table_Table.empty() : new standalone_table_Table(reader.schema, [...reader]);
        }
        return (async (opening) => {
            const reader = await opening;
            const schema = reader.schema;
            const batches = [];
            if (schema) {
                for await (let batch of reader) {
                    batches.push(batch);
                }
                return new standalone_table_Table(schema, batches);
            }
            return standalone_table_Table.empty();
        })(reader.open());
    }
    /** @nocollapse */
    static async fromAsync(source) {
        return await standalone_table_Table.from(source);
    }
    /** @nocollapse */
    static fromStruct(vector) {
        return standalone_table_Table.new(vector.data.childData, vector.type.children);
    }
    /** @nocollapse */
    static new(...cols) {
        return new standalone_table_Table(...standalone_distributeColumnsIntoRecordBatches(standalone_selectColumnArgs(cols)));
    }
    get schema() { return this._schema; }
    get length() { return this._length; }
    get chunks() { return this._chunks; }
    get numCols() { return this._numChildren; }
    clone(chunks = this._chunks) {
        return new standalone_table_Table(this._schema, chunks);
    }
    getColumn(name) {
        return this.getColumnAt(this.getColumnIndex(name));
    }
    getColumnAt(index) {
        return this.getChildAt(index);
    }
    getColumnIndex(name) {
        return this._schema.fields.findIndex((f) => f.name === name);
    }
    getChildAt(index) {
        if (index < 0 || index >= this.numChildren) {
            return null;
        }
        let field, child;
        const fields = this._schema.fields;
        const columns = this._children || (this._children = []);
        if (child = columns[index]) {
            return child;
        }
        if (field = fields[index]) {
            const chunks = this._chunks
                .map((chunk) => chunk.getChildAt(index))
                .filter((vec) => vec != null);
            if (chunks.length > 0) {
                return (columns[index] = new standalone_apache_arrow_column_Column(field, chunks));
            }
        }
        return null;
    }
    // @ts-ignore
    serialize(encoding = 'binary', stream = true) {
        const Writer = !stream
            ? standalone_RecordBatchFileWriter
            : standalone_RecordBatchStreamWriter;
        return Writer.writeAll(this).toUint8Array(true);
    }
    count() {
        return this._length;
    }
    select(...columnNames) {
        const nameToIndex = this._schema.fields.reduce((m, f, i) => m.set(f.name, i), new Map());
        return this.selectAt(...columnNames.map((columnName) => nameToIndex.get(columnName)).filter((x) => x > -1));
    }
    selectAt(...columnIndices) {
        const schema = this._schema.selectAt(...columnIndices);
        return new standalone_table_Table(schema, this._chunks.map(({ length, data: { childData } }) => {
            return new standalone_recordbatch_RecordBatch(schema, length, columnIndices.map((i) => childData[i]).filter(Boolean));
        }));
    }
    assign(other) {
        const fields = this._schema.fields;
        const [indices, oldToNew] = other.schema.fields.reduce((memo, f2, newIdx) => {
            const [indices, oldToNew] = memo;
            const i = fields.findIndex((f) => f.name === f2.name);
            ~i ? (oldToNew[i] = newIdx) : indices.push(newIdx);
            return memo;
        }, [[], []]);
        const schema = this._schema.assign(other.schema);
        const columns = [
            ...fields.map((_f, i, _fs, j = oldToNew[i]) => (j === undefined ? this.getColumnAt(i) : other.getColumnAt(j))),
            ...indices.map((i) => other.getColumnAt(i))
        ].filter(Boolean);
        return new standalone_table_Table(...standalone_distributeVectorsIntoRecordBatches(schema, columns));
    }
}
function standalone_tableFromIterable(input) {
    const { type } = input;
    if (type instanceof standalone_Struct) {
        return standalone_table_Table.fromStruct(standalone_StructVector.from(input));
    }
    return null;
}
function standalone_tableFromAsyncIterable(input) {
    const { type } = input;
    if (type instanceof standalone_Struct) {
        return standalone_StructVector.from(input).then((vector) => standalone_table_Table.fromStruct(vector));
    }
    return null;
}

//# sourceMappingURL=table.mjs.map

;// ../../node_modules/apache-arrow/recordbatch.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.











class standalone_recordbatch_RecordBatch extends standalone_StructVector {
    constructor(...args) {
        let data;
        let schema = args[0];
        let children;
        if (args[1] instanceof standalone_Data) {
            [, data, children] = args;
        }
        else {
            const fields = schema.fields;
            const [, length, childData] = args;
            data = standalone_Data.Struct(new standalone_Struct(fields), 0, length, 0, null, childData);
        }
        super(data, children);
        this._schema = schema;
    }
    /** @nocollapse */
    static from(options) {
        if (standalone_compat_isIterable(options['values'])) {
            return standalone_table_Table.from(options);
        }
        return standalone_table_Table.from(options);
    }
    /** @nocollapse */
    static new(...args) {
        const [fs, xs] = standalone_selectFieldArgs(args);
        const vs = xs.filter((x) => x instanceof standalone_AbstractVector);
        return new standalone_recordbatch_RecordBatch(...standalone_ensureSameLengthData(new standalone_Schema(fs), vs.map((x) => x.data)));
    }
    clone(data, children = this._children) {
        return new standalone_recordbatch_RecordBatch(this._schema, data, children);
    }
    concat(...others) {
        const schema = this._schema, chunks = standalone_Chunked.flatten(this, ...others);
        return new standalone_table_Table(schema, chunks.map(({ data }) => new standalone_recordbatch_RecordBatch(schema, data)));
    }
    get schema() { return this._schema; }
    get numCols() { return this._schema.fields.length; }
    get dictionaries() {
        return this._dictionaries || (this._dictionaries = standalone_DictionaryCollector.collect(this));
    }
    select(...columnNames) {
        const nameToIndex = this._schema.fields.reduce((m, f, i) => m.set(f.name, i), new Map());
        return this.selectAt(...columnNames.map((columnName) => nameToIndex.get(columnName)).filter((x) => x > -1));
    }
    selectAt(...columnIndices) {
        const schema = this._schema.selectAt(...columnIndices);
        const childData = columnIndices.map((i) => this.data.childData[i]).filter(Boolean);
        return new standalone_recordbatch_RecordBatch(schema, this.length, childData);
    }
}
/**
 * An internal class used by the `RecordBatchReader` and `RecordBatchWriter`
 * implementations to differentiate between a stream with valid zero-length
 * RecordBatches, and a stream with a Schema message, but no RecordBatches.
 * @see https://github.com/apache/arrow/pull/4373
 * @ignore
 * @private
 */
/* tslint:disable:class-name */
class standalone_InternalEmptyPlaceholderRecordBatch extends standalone_recordbatch_RecordBatch {
    constructor(schema) {
        super(schema, 0, schema.fields.map((f) => standalone_Data.new(f.type, 0, 0, 0)));
    }
}
/** @ignore */
class standalone_DictionaryCollector extends standalone_Visitor {
    constructor() {
        super(...arguments);
        this.dictionaries = new Map();
    }
    static collect(batch) {
        return new standalone_DictionaryCollector().visit(batch.data, new standalone_Struct(batch.schema.fields)).dictionaries;
    }
    visit(data, type) {
        if (standalone_DataType.isDictionary(type)) {
            return this.visitDictionary(data, type);
        }
        else {
            data.childData.forEach((child, i) => this.visit(child, type.children[i].type));
        }
        return this;
    }
    visitDictionary(data, type) {
        const dictionary = data.dictionary;
        if (dictionary && dictionary.length > 0) {
            this.dictionaries.set(type.id, dictionary);
        }
        return this;
    }
}

//# sourceMappingURL=recordbatch.mjs.map

;// ../../node_modules/apache-arrow/ipc/reader.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.











class standalone_RecordBatchReader extends standalone_ReadableInterop {
    constructor(impl) {
        super();
        this._impl = impl;
    }
    get closed() { return this._impl.closed; }
    get schema() { return this._impl.schema; }
    get autoDestroy() { return this._impl.autoDestroy; }
    get dictionaries() { return this._impl.dictionaries; }
    get numDictionaries() { return this._impl.numDictionaries; }
    get numRecordBatches() { return this._impl.numRecordBatches; }
    get footer() { return this._impl.isFile() ? this._impl.footer : null; }
    isSync() { return this._impl.isSync(); }
    isAsync() { return this._impl.isAsync(); }
    isFile() { return this._impl.isFile(); }
    isStream() { return this._impl.isStream(); }
    next() {
        return this._impl.next();
    }
    throw(value) {
        return this._impl.throw(value);
    }
    return(value) {
        return this._impl.return(value);
    }
    cancel() {
        return this._impl.cancel();
    }
    reset(schema) {
        this._impl.reset(schema);
        this._DOMStream = undefined;
        this._nodeStream = undefined;
        return this;
    }
    open(options) {
        const opening = this._impl.open(options);
        return standalone_isPromise(opening) ? opening.then(() => this) : this;
    }
    readRecordBatch(index) {
        return this._impl.isFile() ? this._impl.readRecordBatch(index) : null;
    }
    [Symbol.iterator]() {
        return this._impl[Symbol.iterator]();
    }
    [Symbol.asyncIterator]() {
        return this._impl[Symbol.asyncIterator]();
    }
    toDOMStream() {
        return standalone_adapters.toDOMStream((this.isSync()
            ? { [Symbol.iterator]: () => this }
            : { [Symbol.asyncIterator]: () => this }));
    }
    toNodeStream() {
        return standalone_adapters.toNodeStream((this.isSync()
            ? { [Symbol.iterator]: () => this }
            : { [Symbol.asyncIterator]: () => this }), { objectMode: true });
    }
    /** @nocollapse */
    // @ts-ignore
    static throughNode(options) {
        throw new Error(`"throughNode" not available in this environment`);
    }
    /** @nocollapse */
    static throughDOM(
    // @ts-ignore
    writableStrategy, 
    // @ts-ignore
    readableStrategy) {
        throw new Error(`"throughDOM" not available in this environment`);
    }
    /** @nocollapse */
    static from(source) {
        if (source instanceof standalone_RecordBatchReader) {
            return source;
        }
        else if (standalone_isArrowJSON(source)) {
            return standalone_fromArrowJSON(source);
        }
        else if (standalone_isFileHandle(source)) {
            return standalone_fromFileHandle(source);
        }
        else if (standalone_isPromise(source)) {
            return (async () => await standalone_RecordBatchReader.from(await source))();
        }
        else if (standalone_isFetchResponse(source) || standalone_isReadableDOMStream(source) || standalone_isReadableNodeStream(source) || standalone_isAsyncIterable(source)) {
            return standalone_fromAsyncByteStream(new standalone_AsyncByteStream(source));
        }
        return standalone_fromByteStream(new standalone_ByteStream(source));
    }
    /** @nocollapse */
    static readAll(source) {
        if (source instanceof standalone_RecordBatchReader) {
            return source.isSync() ? standalone_readAllSync(source) : standalone_readAllAsync(source);
        }
        else if (standalone_isArrowJSON(source) || ArrayBuffer.isView(source) || standalone_compat_isIterable(source) || standalone_isIteratorResult(source)) {
            return standalone_readAllSync(source);
        }
        return standalone_readAllAsync(source);
    }
}
//
// Since TS is a structural type system, we define the following subclass stubs
// so that concrete types exist to associate with with the interfaces below.
//
// The implementation for each RecordBatchReader is hidden away in the set of
// `RecordBatchReaderImpl` classes in the second half of this file. This allows
// us to export a single RecordBatchReader class, and swap out the impl based
// on the io primitives or underlying arrow (JSON, file, or stream) at runtime.
//
// Async/await makes our job a bit harder, since it forces everything to be
// either fully sync or fully async. This is why the logic for the reader impls
// has been duplicated into both sync and async variants. Since the RBR
// delegates to its impl, an RBR with an AsyncRecordBatchFileReaderImpl for
// example will return async/await-friendly Promises, but one with a (sync)
// RecordBatchStreamReaderImpl will always return values. Nothing should be
// different about their logic, aside from the async handling. This is also why
// this code looks highly structured, as it should be nearly identical and easy
// to follow.
//
/** @ignore */
class standalone_RecordBatchStreamReader extends standalone_RecordBatchReader {
    constructor(_impl) {
        super(_impl);
        this._impl = _impl;
    }
    [Symbol.iterator]() { return this._impl[Symbol.iterator](); }
    async *[Symbol.asyncIterator]() { yield* this[Symbol.iterator](); }
}
/** @ignore */
class standalone_AsyncRecordBatchStreamReader extends standalone_RecordBatchReader {
    constructor(_impl) {
        super(_impl);
        this._impl = _impl;
    }
    [Symbol.iterator]() { throw new Error(`AsyncRecordBatchStreamReader is not Iterable`); }
    [Symbol.asyncIterator]() { return this._impl[Symbol.asyncIterator](); }
}
/** @ignore */
class standalone_RecordBatchFileReader extends standalone_RecordBatchStreamReader {
    constructor(_impl) {
        super(_impl);
        this._impl = _impl;
    }
}
/** @ignore */
class standalone_AsyncRecordBatchFileReader extends standalone_AsyncRecordBatchStreamReader {
    constructor(_impl) {
        super(_impl);
        this._impl = _impl;
    }
}
/** @ignore */
class standalone_RecordBatchReaderImpl {
    constructor(dictionaries = new Map()) {
        this.closed = false;
        this.autoDestroy = true;
        this._dictionaryIndex = 0;
        this._recordBatchIndex = 0;
        this.dictionaries = dictionaries;
    }
    get numDictionaries() { return this._dictionaryIndex; }
    get numRecordBatches() { return this._recordBatchIndex; }
    isSync() { return false; }
    isAsync() { return false; }
    isFile() { return false; }
    isStream() { return false; }
    reset(schema) {
        this._dictionaryIndex = 0;
        this._recordBatchIndex = 0;
        this.schema = schema;
        this.dictionaries = new Map();
        return this;
    }
    _loadRecordBatch(header, body) {
        return new standalone_recordbatch_RecordBatch(this.schema, header.length, this._loadVectors(header, body, this.schema.fields));
    }
    _loadDictionaryBatch(header, body) {
        const { id, isDelta, data } = header;
        const { dictionaries, schema } = this;
        const dictionary = dictionaries.get(id);
        if (isDelta || !dictionary) {
            const type = schema.dictionaries.get(id);
            return (dictionary && isDelta ? dictionary.concat(standalone_AbstractVector.new(this._loadVectors(data, body, [type])[0])) :
                standalone_AbstractVector.new(this._loadVectors(data, body, [type])[0]));
        }
        return dictionary;
    }
    _loadVectors(header, body, types) {
        return new standalone_VectorLoader(body, header.nodes, header.buffers, this.dictionaries).visitMany(types);
    }
}
/** @ignore */
class standalone_RecordBatchStreamReaderImpl extends standalone_RecordBatchReaderImpl {
    constructor(source, dictionaries) {
        super(dictionaries);
        this._reader = !standalone_isArrowJSON(source)
            ? new standalone_MessageReader(this._handle = source)
            : new standalone_JSONMessageReader(this._handle = source);
    }
    isSync() { return true; }
    isStream() { return true; }
    [Symbol.iterator]() {
        return this;
    }
    cancel() {
        if (!this.closed && (this.closed = true)) {
            this.reset()._reader.return();
            this._reader = null;
            this.dictionaries = null;
        }
    }
    open(options) {
        if (!this.closed) {
            this.autoDestroy = standalone_shouldAutoDestroy(this, options);
            if (!(this.schema || (this.schema = this._reader.readSchema()))) {
                this.cancel();
            }
        }
        return this;
    }
    throw(value) {
        if (!this.closed && this.autoDestroy && (this.closed = true)) {
            return this.reset()._reader.throw(value);
        }
        return standalone_ITERATOR_DONE;
    }
    return(value) {
        if (!this.closed && this.autoDestroy && (this.closed = true)) {
            return this.reset()._reader.return(value);
        }
        return standalone_ITERATOR_DONE;
    }
    next() {
        if (this.closed) {
            return standalone_ITERATOR_DONE;
        }
        let message, { _reader: reader } = this;
        while (message = this._readNextMessageAndValidate()) {
            if (message.isSchema()) {
                this.reset(message.header());
            }
            else if (message.isRecordBatch()) {
                this._recordBatchIndex++;
                const header = message.header();
                const buffer = reader.readMessageBody(message.bodyLength);
                const recordBatch = this._loadRecordBatch(header, buffer);
                return { done: false, value: recordBatch };
            }
            else if (message.isDictionaryBatch()) {
                this._dictionaryIndex++;
                const header = message.header();
                const buffer = reader.readMessageBody(message.bodyLength);
                const vector = this._loadDictionaryBatch(header, buffer);
                this.dictionaries.set(header.id, vector);
            }
        }
        if (this.schema && this._recordBatchIndex === 0) {
            this._recordBatchIndex++;
            return { done: false, value: new standalone_InternalEmptyPlaceholderRecordBatch(this.schema) };
        }
        return this.return();
    }
    _readNextMessageAndValidate(type) {
        return this._reader.readMessage(type);
    }
}
/** @ignore */
class standalone_AsyncRecordBatchStreamReaderImpl extends standalone_RecordBatchReaderImpl {
    constructor(source, dictionaries) {
        super(dictionaries);
        this._reader = new standalone_AsyncMessageReader(this._handle = source);
    }
    isAsync() { return true; }
    isStream() { return true; }
    [Symbol.asyncIterator]() {
        return this;
    }
    async cancel() {
        if (!this.closed && (this.closed = true)) {
            await this.reset()._reader.return();
            this._reader = null;
            this.dictionaries = null;
        }
    }
    async open(options) {
        if (!this.closed) {
            this.autoDestroy = standalone_shouldAutoDestroy(this, options);
            if (!(this.schema || (this.schema = (await this._reader.readSchema())))) {
                await this.cancel();
            }
        }
        return this;
    }
    async throw(value) {
        if (!this.closed && this.autoDestroy && (this.closed = true)) {
            return await this.reset()._reader.throw(value);
        }
        return standalone_ITERATOR_DONE;
    }
    async return(value) {
        if (!this.closed && this.autoDestroy && (this.closed = true)) {
            return await this.reset()._reader.return(value);
        }
        return standalone_ITERATOR_DONE;
    }
    async next() {
        if (this.closed) {
            return standalone_ITERATOR_DONE;
        }
        let message, { _reader: reader } = this;
        while (message = await this._readNextMessageAndValidate()) {
            if (message.isSchema()) {
                await this.reset(message.header());
            }
            else if (message.isRecordBatch()) {
                this._recordBatchIndex++;
                const header = message.header();
                const buffer = await reader.readMessageBody(message.bodyLength);
                const recordBatch = this._loadRecordBatch(header, buffer);
                return { done: false, value: recordBatch };
            }
            else if (message.isDictionaryBatch()) {
                this._dictionaryIndex++;
                const header = message.header();
                const buffer = await reader.readMessageBody(message.bodyLength);
                const vector = this._loadDictionaryBatch(header, buffer);
                this.dictionaries.set(header.id, vector);
            }
        }
        if (this.schema && this._recordBatchIndex === 0) {
            this._recordBatchIndex++;
            return { done: false, value: new standalone_InternalEmptyPlaceholderRecordBatch(this.schema) };
        }
        return await this.return();
    }
    async _readNextMessageAndValidate(type) {
        return await this._reader.readMessage(type);
    }
}
/** @ignore */
class standalone_RecordBatchFileReaderImpl extends standalone_RecordBatchStreamReaderImpl {
    constructor(source, dictionaries) {
        super(source instanceof standalone_RandomAccessFile ? source : new standalone_RandomAccessFile(source), dictionaries);
    }
    get footer() { return this._footer; }
    get numDictionaries() { return this._footer ? this._footer.numDictionaries : 0; }
    get numRecordBatches() { return this._footer ? this._footer.numRecordBatches : 0; }
    isSync() { return true; }
    isFile() { return true; }
    open(options) {
        if (!this.closed && !this._footer) {
            this.schema = (this._footer = this._readFooter()).schema;
            for (const block of this._footer.dictionaryBatches()) {
                block && this._readDictionaryBatch(this._dictionaryIndex++);
            }
        }
        return super.open(options);
    }
    readRecordBatch(index) {
        if (this.closed) {
            return null;
        }
        if (!this._footer) {
            this.open();
        }
        const block = this._footer && this._footer.getRecordBatch(index);
        if (block && this._handle.seek(block.offset)) {
            const message = this._reader.readMessage(standalone_MessageHeader.RecordBatch);
            if (message && message.isRecordBatch()) {
                const header = message.header();
                const buffer = this._reader.readMessageBody(message.bodyLength);
                const recordBatch = this._loadRecordBatch(header, buffer);
                return recordBatch;
            }
        }
        return null;
    }
    _readDictionaryBatch(index) {
        const block = this._footer && this._footer.getDictionaryBatch(index);
        if (block && this._handle.seek(block.offset)) {
            const message = this._reader.readMessage(standalone_MessageHeader.DictionaryBatch);
            if (message && message.isDictionaryBatch()) {
                const header = message.header();
                const buffer = this._reader.readMessageBody(message.bodyLength);
                const vector = this._loadDictionaryBatch(header, buffer);
                this.dictionaries.set(header.id, vector);
            }
        }
    }
    _readFooter() {
        const { _handle } = this;
        const offset = _handle.size - standalone_magicAndPadding;
        const length = _handle.readInt32(offset);
        const buffer = _handle.readAt(offset - length, length);
        return standalone_Footer_.decode(buffer);
    }
    _readNextMessageAndValidate(type) {
        if (!this._footer) {
            this.open();
        }
        if (this._footer && this._recordBatchIndex < this.numRecordBatches) {
            const block = this._footer && this._footer.getRecordBatch(this._recordBatchIndex);
            if (block && this._handle.seek(block.offset)) {
                return this._reader.readMessage(type);
            }
        }
        return null;
    }
}
/** @ignore */
class standalone_AsyncRecordBatchFileReaderImpl extends standalone_AsyncRecordBatchStreamReaderImpl {
    constructor(source, ...rest) {
        const byteLength = typeof rest[0] !== 'number' ? rest.shift() : undefined;
        const dictionaries = rest[0] instanceof Map ? rest.shift() : undefined;
        super(source instanceof standalone_AsyncRandomAccessFile ? source : new standalone_AsyncRandomAccessFile(source, byteLength), dictionaries);
    }
    get footer() { return this._footer; }
    get numDictionaries() { return this._footer ? this._footer.numDictionaries : 0; }
    get numRecordBatches() { return this._footer ? this._footer.numRecordBatches : 0; }
    isFile() { return true; }
    isAsync() { return true; }
    async open(options) {
        if (!this.closed && !this._footer) {
            this.schema = (this._footer = await this._readFooter()).schema;
            for (const block of this._footer.dictionaryBatches()) {
                block && await this._readDictionaryBatch(this._dictionaryIndex++);
            }
        }
        return await super.open(options);
    }
    async readRecordBatch(index) {
        if (this.closed) {
            return null;
        }
        if (!this._footer) {
            await this.open();
        }
        const block = this._footer && this._footer.getRecordBatch(index);
        if (block && (await this._handle.seek(block.offset))) {
            const message = await this._reader.readMessage(standalone_MessageHeader.RecordBatch);
            if (message && message.isRecordBatch()) {
                const header = message.header();
                const buffer = await this._reader.readMessageBody(message.bodyLength);
                const recordBatch = this._loadRecordBatch(header, buffer);
                return recordBatch;
            }
        }
        return null;
    }
    async _readDictionaryBatch(index) {
        const block = this._footer && this._footer.getDictionaryBatch(index);
        if (block && (await this._handle.seek(block.offset))) {
            const message = await this._reader.readMessage(standalone_MessageHeader.DictionaryBatch);
            if (message && message.isDictionaryBatch()) {
                const header = message.header();
                const buffer = await this._reader.readMessageBody(message.bodyLength);
                const vector = this._loadDictionaryBatch(header, buffer);
                this.dictionaries.set(header.id, vector);
            }
        }
    }
    async _readFooter() {
        const { _handle } = this;
        _handle._pending && await _handle._pending;
        const offset = _handle.size - standalone_magicAndPadding;
        const length = await _handle.readInt32(offset);
        const buffer = await _handle.readAt(offset - length, length);
        return standalone_Footer_.decode(buffer);
    }
    async _readNextMessageAndValidate(type) {
        if (!this._footer) {
            await this.open();
        }
        if (this._footer && this._recordBatchIndex < this.numRecordBatches) {
            const block = this._footer.getRecordBatch(this._recordBatchIndex);
            if (block && await this._handle.seek(block.offset)) {
                return await this._reader.readMessage(type);
            }
        }
        return null;
    }
}
/** @ignore */
class standalone_RecordBatchJSONReaderImpl extends standalone_RecordBatchStreamReaderImpl {
    constructor(source, dictionaries) {
        super(source, dictionaries);
    }
    _loadVectors(header, body, types) {
        return new standalone_JSONVectorLoader(body, header.nodes, header.buffers, this.dictionaries).visitMany(types);
    }
}
//
// Define some helper functions and static implementations down here. There's
// a bit of branching in the static methods that can lead to the same routines
// being executed, so we've broken those out here for readability.
//
/** @ignore */
function standalone_shouldAutoDestroy(self, options) {
    return options && (typeof options['autoDestroy'] === 'boolean') ? options['autoDestroy'] : self['autoDestroy'];
}
/** @ignore */
function* standalone_readAllSync(source) {
    const reader = standalone_RecordBatchReader.from(source);
    try {
        if (!reader.open({ autoDestroy: false }).closed) {
            do {
                yield reader;
            } while (!(reader.reset().open()).closed);
        }
    }
    finally {
        reader.cancel();
    }
}
/** @ignore */
async function* standalone_readAllAsync(source) {
    const reader = await standalone_RecordBatchReader.from(source);
    try {
        if (!(await reader.open({ autoDestroy: false })).closed) {
            do {
                yield reader;
            } while (!(await reader.reset().open()).closed);
        }
    }
    finally {
        await reader.cancel();
    }
}
/** @ignore */
function standalone_fromArrowJSON(source) {
    return new standalone_RecordBatchStreamReader(new standalone_RecordBatchJSONReaderImpl(source));
}
/** @ignore */
function standalone_fromByteStream(source) {
    const bytes = source.peek((standalone_magicLength + 7) & ~7);
    return bytes && bytes.byteLength >= 4 ? !standalone_checkForMagicArrowString(bytes)
        ? new standalone_RecordBatchStreamReader(new standalone_RecordBatchStreamReaderImpl(source))
        : new standalone_RecordBatchFileReader(new standalone_RecordBatchFileReaderImpl(source.read()))
        : new standalone_RecordBatchStreamReader(new standalone_RecordBatchStreamReaderImpl(function* () { }()));
}
/** @ignore */
async function standalone_fromAsyncByteStream(source) {
    const bytes = await source.peek((standalone_magicLength + 7) & ~7);
    return bytes && bytes.byteLength >= 4 ? !standalone_checkForMagicArrowString(bytes)
        ? new standalone_AsyncRecordBatchStreamReader(new standalone_AsyncRecordBatchStreamReaderImpl(source))
        : new standalone_RecordBatchFileReader(new standalone_RecordBatchFileReaderImpl(await source.read()))
        : new standalone_AsyncRecordBatchStreamReader(new standalone_AsyncRecordBatchStreamReaderImpl(async function* () { }()));
}
/** @ignore */
async function standalone_fromFileHandle(source) {
    const { size } = await source.stat();
    const file = new standalone_AsyncRandomAccessFile(source, size);
    if (size >= standalone_magicX2AndPadding) {
        if (standalone_checkForMagicArrowString(await file.readAt(0, (standalone_magicLength + 7) & ~7))) {
            return new standalone_AsyncRecordBatchFileReader(new standalone_AsyncRecordBatchFileReaderImpl(file));
        }
    }
    return new standalone_AsyncRecordBatchStreamReader(new standalone_AsyncRecordBatchStreamReaderImpl(file));
}

//# sourceMappingURL=reader.mjs.map

;// ../../node_modules/apache-arrow/io/whatwg/iterable.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/** @ignore */
function standalone_toDOMStream(source, options) {
    if (standalone_isAsyncIterable(source)) {
        return standalone_asyncIterableAsReadableDOMStream(source, options);
    }
    if (standalone_compat_isIterable(source)) {
        return standalone_iterableAsReadableDOMStream(source, options);
    }
    /* istanbul ignore next */
    throw new Error(`toDOMStream() must be called with an Iterable or AsyncIterable`);
}
/** @ignore */
function standalone_iterableAsReadableDOMStream(source, options) {
    let it = null;
    const bm = (options && options.type === 'bytes') || false;
    const hwm = options && options.highWaterMark || (2 ** 24);
    return new ReadableStream({
        ...options,
        start(controller) { next(controller, it || (it = source[Symbol.iterator]())); },
        pull(controller) { it ? (next(controller, it)) : controller.close(); },
        cancel() { (it && (it.return && it.return()) || true) && (it = null); }
    }, { highWaterMark: bm ? hwm : undefined, ...options });
    function next(controller, it) {
        let buf;
        let r = null;
        let size = controller.desiredSize || null;
        while (!(r = it.next(bm ? size : null)).done) {
            if (ArrayBuffer.isView(r.value) && (buf = standalone_toUint8Array(r.value))) {
                size != null && bm && (size = size - buf.byteLength + 1);
                r.value = buf;
            }
            controller.enqueue(r.value);
            if (size != null && --size <= 0) {
                return;
            }
        }
        controller.close();
    }
}
/** @ignore */
function standalone_asyncIterableAsReadableDOMStream(source, options) {
    let it = null;
    const bm = (options && options.type === 'bytes') || false;
    const hwm = options && options.highWaterMark || (2 ** 24);
    return new ReadableStream({
        ...options,
        async start(controller) { await next(controller, it || (it = source[Symbol.asyncIterator]())); },
        async pull(controller) { it ? (await next(controller, it)) : controller.close(); },
        async cancel() { (it && (it.return && await it.return()) || true) && (it = null); },
    }, { highWaterMark: bm ? hwm : undefined, ...options });
    async function next(controller, it) {
        let buf;
        let r = null;
        let size = controller.desiredSize || null;
        while (!(r = await it.next(bm ? size : null)).done) {
            if (ArrayBuffer.isView(r.value) && (buf = standalone_toUint8Array(r.value))) {
                size != null && bm && (size = size - buf.byteLength + 1);
                r.value = buf;
            }
            controller.enqueue(r.value);
            if (size != null && --size <= 0) {
                return;
            }
        }
        controller.close();
    }
}

//# sourceMappingURL=iterable.mjs.map

;// ../../node_modules/apache-arrow/io/whatwg/builder.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
function standalone_builderThroughDOMStream(options) {
    return new standalone_BuilderTransform(options);
}
/** @ignore */
class standalone_BuilderTransform {
    constructor(options) {
        // Access properties by string indexers to defeat closure compiler
        this._numChunks = 0;
        this._finished = false;
        this._bufferedSize = 0;
        const { ['readableStrategy']: readableStrategy, ['writableStrategy']: writableStrategy, ['queueingStrategy']: queueingStrategy = 'count', ...builderOptions } = options;
        this._controller = null;
        this._builder = standalone_Builder.new(builderOptions);
        this._getSize = queueingStrategy !== 'bytes' ? standalone_chunkLength : standalone_chunkByteLength;
        const { ['highWaterMark']: readableHighWaterMark = queueingStrategy === 'bytes' ? 2 ** 14 : 1000 } = { ...readableStrategy };
        const { ['highWaterMark']: writableHighWaterMark = queueingStrategy === 'bytes' ? 2 ** 14 : 1000 } = { ...writableStrategy };
        this['readable'] = new ReadableStream({
            ['cancel']: () => { this._builder.clear(); },
            ['pull']: (c) => { this._maybeFlush(this._builder, this._controller = c); },
            ['start']: (c) => { this._maybeFlush(this._builder, this._controller = c); },
        }, {
            'highWaterMark': readableHighWaterMark,
            'size': queueingStrategy !== 'bytes' ? standalone_chunkLength : standalone_chunkByteLength,
        });
        this['writable'] = new WritableStream({
            ['abort']: () => { this._builder.clear(); },
            ['write']: () => { this._maybeFlush(this._builder, this._controller); },
            ['close']: () => { this._maybeFlush(this._builder.finish(), this._controller); },
        }, {
            'highWaterMark': writableHighWaterMark,
            'size': (value) => this._writeValueAndReturnChunkSize(value),
        });
    }
    _writeValueAndReturnChunkSize(value) {
        const bufferedSize = this._bufferedSize;
        this._bufferedSize = this._getSize(this._builder.append(value));
        return this._bufferedSize - bufferedSize;
    }
    _maybeFlush(builder, controller) {
        if (controller === null) {
            return;
        }
        if (this._bufferedSize >= controller.desiredSize) {
            ++this._numChunks && this._enqueue(controller, builder.toVector());
        }
        if (builder.finished) {
            if (builder.length > 0 || this._numChunks === 0) {
                ++this._numChunks && this._enqueue(controller, builder.toVector());
            }
            if (!this._finished && (this._finished = true)) {
                this._enqueue(controller, null);
            }
        }
    }
    _enqueue(controller, chunk) {
        this._bufferedSize = 0;
        this._controller = null;
        chunk === null ? controller.close() : controller.enqueue(chunk);
    }
}
/** @ignore */ const standalone_chunkLength = (chunk) => chunk.length;
/** @ignore */ const standalone_chunkByteLength = (chunk) => chunk.byteLength;

//# sourceMappingURL=builder.mjs.map

;// ../../node_modules/apache-arrow/io/whatwg/reader.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


/** @ignore */
function standalone_recordBatchReaderThroughDOMStream(writableStrategy, readableStrategy) {
    const queue = new standalone_AsyncByteQueue();
    let reader = null;
    const readable = new ReadableStream({
        async cancel() { await queue.close(); },
        async start(controller) { await next(controller, reader || (reader = await open())); },
        async pull(controller) { reader ? await next(controller, reader) : controller.close(); }
    });
    return { writable: new WritableStream(queue, { 'highWaterMark': 2 ** 14, ...writableStrategy }), readable };
    async function open() {
        return await (await standalone_RecordBatchReader.from(queue)).open(readableStrategy);
    }
    async function next(controller, reader) {
        let size = controller.desiredSize;
        let r = null;
        while (!(r = await reader.next()).done) {
            controller.enqueue(r.value);
            if (size != null && --size <= 0) {
                return;
            }
        }
        controller.close();
    }
}

//# sourceMappingURL=reader.mjs.map

;// ../../node_modules/apache-arrow/io/whatwg/writer.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
function standalone_recordBatchWriterThroughDOMStream(writableStrategy, readableStrategy) {
    const writer = new this(writableStrategy);
    const reader = new standalone_AsyncByteStream(writer);
    const readable = new ReadableStream({
        type: 'bytes',
        async cancel() { await reader.cancel(); },
        async pull(controller) { await next(controller); },
        async start(controller) { await next(controller); },
    }, { 'highWaterMark': 2 ** 14, ...readableStrategy });
    return { writable: new WritableStream(writer, writableStrategy), readable };
    async function next(controller) {
        let buf = null;
        let size = controller.desiredSize;
        while (buf = await reader.read(size || null)) {
            controller.enqueue(buf);
            if (size != null && (size -= buf.byteLength) <= 0) {
                return;
            }
        }
        controller.close();
    }
}

//# sourceMappingURL=writer.mjs.map

;// ../../node_modules/apache-arrow/compute/predicate.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/** @ignore */
class standalone_predicate_Value {
    eq(other) {
        if (!(other instanceof standalone_predicate_Value)) {
            other = new standalone_predicate_Literal(other);
        }
        return new standalone_Equals(this, other);
    }
    le(other) {
        if (!(other instanceof standalone_predicate_Value)) {
            other = new standalone_predicate_Literal(other);
        }
        return new standalone_LTeq(this, other);
    }
    ge(other) {
        if (!(other instanceof standalone_predicate_Value)) {
            other = new standalone_predicate_Literal(other);
        }
        return new standalone_GTeq(this, other);
    }
    lt(other) {
        return new standalone_Not(this.ge(other));
    }
    gt(other) {
        return new standalone_Not(this.le(other));
    }
    ne(other) {
        return new standalone_Not(this.eq(other));
    }
}
/** @ignore */
class standalone_predicate_Literal extends standalone_predicate_Value {
    constructor(v) {
        super();
        this.v = v;
    }
}
/** @ignore */
class standalone_Col extends standalone_predicate_Value {
    constructor(name) {
        super();
        this.name = name;
    }
    bind(batch) {
        if (!this.colidx) {
            // Assume column index doesn't change between calls to bind
            //this.colidx = cols.findIndex(v => v.name.indexOf(this.name) != -1);
            this.colidx = -1;
            const fields = batch.schema.fields;
            for (let idx = -1; ++idx < fields.length;) {
                if (fields[idx].name === this.name) {
                    this.colidx = idx;
                    break;
                }
            }
            if (this.colidx < 0) {
                throw new Error(`Failed to bind Col "${this.name}"`);
            }
        }
        const vec = this.vector = batch.getChildAt(this.colidx);
        return (idx) => vec.get(idx);
    }
}
/** @ignore */
class standalone_Predicate {
    and(...expr) { return new standalone_predicate_And(this, ...expr); }
    or(...expr) { return new standalone_predicate_Or(this, ...expr); }
    not() { return new standalone_Not(this); }
}
/** @ignore */
class standalone_ComparisonPredicate extends standalone_Predicate {
    constructor(left, right) {
        super();
        this.left = left;
        this.right = right;
    }
    bind(batch) {
        if (this.left instanceof standalone_predicate_Literal) {
            if (this.right instanceof standalone_predicate_Literal) {
                return this._bindLitLit(batch, this.left, this.right);
            }
            else { // right is a Col
                return this._bindLitCol(batch, this.left, this.right);
            }
        }
        else { // left is a Col
            if (this.right instanceof standalone_predicate_Literal) {
                return this._bindColLit(batch, this.left, this.right);
            }
            else { // right is a Col
                return this._bindColCol(batch, this.left, this.right);
            }
        }
    }
}
/** @ignore */
class standalone_CombinationPredicate extends standalone_Predicate {
    constructor(...children) {
        super();
        this.children = children;
    }
}
// add children to prototype so it doesn't get mangled in es2015/umd
standalone_CombinationPredicate.prototype.children = Object.freeze([]); // freeze for safety
/** @ignore */
class standalone_predicate_And extends standalone_CombinationPredicate {
    constructor(...children) {
        // Flatten any Ands
        children = children.reduce((accum, p) => {
            return accum.concat(p instanceof standalone_predicate_And ? p.children : p);
        }, []);
        super(...children);
    }
    bind(batch) {
        const bound = this.children.map((p) => p.bind(batch));
        return (idx, batch) => bound.every((p) => p(idx, batch));
    }
}
/** @ignore */
class standalone_predicate_Or extends standalone_CombinationPredicate {
    constructor(...children) {
        // Flatten any Ors
        children = children.reduce((accum, p) => {
            return accum.concat(p instanceof standalone_predicate_Or ? p.children : p);
        }, []);
        super(...children);
    }
    bind(batch) {
        const bound = this.children.map((p) => p.bind(batch));
        return (idx, batch) => bound.some((p) => p(idx, batch));
    }
}
/** @ignore */
class standalone_Equals extends standalone_ComparisonPredicate {
    _bindLitLit(_batch, left, right) {
        const rtrn = left.v == right.v;
        return () => rtrn;
    }
    _bindColCol(batch, left, right) {
        const left_func = left.bind(batch);
        const right_func = right.bind(batch);
        return (idx, batch) => left_func(idx, batch) == right_func(idx, batch);
    }
    _bindColLit(batch, col, lit) {
        const col_func = col.bind(batch);
        if (col.vector instanceof standalone_DictionaryVector) {
            let key;
            const vector = col.vector;
            if (vector.dictionary !== this.lastDictionary) {
                key = vector.reverseLookup(lit.v);
                this.lastDictionary = vector.dictionary;
                this.lastKey = key;
            }
            else {
                key = this.lastKey;
            }
            if (key === -1) {
                // the value doesn't exist in the dictionary - always return
                // false
                // TODO: special-case of PredicateFunc that encapsulates this
                // "always false" behavior. That way filtering operations don't
                // have to bother checking
                return () => false;
            }
            else {
                return (idx) => {
                    return vector.getKey(idx) === key;
                };
            }
        }
        else {
            return (idx, cols) => col_func(idx, cols) == lit.v;
        }
    }
    _bindLitCol(batch, lit, col) {
        // Equals is commutative
        return this._bindColLit(batch, col, lit);
    }
}
/** @ignore */
class standalone_LTeq extends standalone_ComparisonPredicate {
    _bindLitLit(_batch, left, right) {
        const rtrn = left.v <= right.v;
        return () => rtrn;
    }
    _bindColCol(batch, left, right) {
        const left_func = left.bind(batch);
        const right_func = right.bind(batch);
        return (idx, cols) => left_func(idx, cols) <= right_func(idx, cols);
    }
    _bindColLit(batch, col, lit) {
        const col_func = col.bind(batch);
        return (idx, cols) => col_func(idx, cols) <= lit.v;
    }
    _bindLitCol(batch, lit, col) {
        const col_func = col.bind(batch);
        return (idx, cols) => lit.v <= col_func(idx, cols);
    }
}
/** @ignore */
class standalone_GTeq extends standalone_ComparisonPredicate {
    _bindLitLit(_batch, left, right) {
        const rtrn = left.v >= right.v;
        return () => rtrn;
    }
    _bindColCol(batch, left, right) {
        const left_func = left.bind(batch);
        const right_func = right.bind(batch);
        return (idx, cols) => left_func(idx, cols) >= right_func(idx, cols);
    }
    _bindColLit(batch, col, lit) {
        const col_func = col.bind(batch);
        return (idx, cols) => col_func(idx, cols) >= lit.v;
    }
    _bindLitCol(batch, lit, col) {
        const col_func = col.bind(batch);
        return (idx, cols) => lit.v >= col_func(idx, cols);
    }
}
/** @ignore */
class standalone_Not extends standalone_Predicate {
    constructor(child) {
        super();
        this.child = child;
    }
    bind(batch) {
        const func = this.child.bind(batch);
        return (idx, batch) => !func(idx, batch);
    }
}
/** @ignore */
class standalone_CustomPredicate extends standalone_Predicate {
    constructor(next, bind_) {
        super();
        this.next = next;
        this.bind_ = bind_;
    }
    bind(batch) {
        this.bind_(batch);
        return this.next;
    }
}
function standalone_lit(v) { return new standalone_predicate_Literal(v); }
function standalone_col(n) { return new standalone_Col(n); }
function standalone_and(...p) { return new standalone_predicate_And(...p); }
function standalone_predicate_or(...p) { return new standalone_predicate_Or(...p); }
function standalone_predicate_custom(next, bind) {
    return new standalone_CustomPredicate(next, bind);
}

//# sourceMappingURL=predicate.mjs.map

;// ../../node_modules/apache-arrow/compute/dataframe.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.






standalone_table_Table.prototype.countBy = function (name) { return new standalone_DataFrame(this.chunks).countBy(name); };
standalone_table_Table.prototype.scan = function (next, bind) { return new standalone_DataFrame(this.chunks).scan(next, bind); };
standalone_table_Table.prototype.scanReverse = function (next, bind) { return new standalone_DataFrame(this.chunks).scanReverse(next, bind); };
standalone_table_Table.prototype.filter = function (predicate) { return new standalone_DataFrame(this.chunks).filter(predicate); };
class standalone_DataFrame extends standalone_table_Table {
    filter(predicate) {
        return new standalone_FilteredDataFrame(this.chunks, predicate);
    }
    scan(next, bind) {
        const batches = this.chunks, numBatches = batches.length;
        for (let batchIndex = -1; ++batchIndex < numBatches;) {
            // load batches
            const batch = batches[batchIndex];
            if (bind) {
                bind(batch);
            }
            // yield all indices
            for (let index = -1, numRows = batch.length; ++index < numRows;) {
                next(index, batch);
            }
        }
    }
    scanReverse(next, bind) {
        const batches = this.chunks, numBatches = batches.length;
        for (let batchIndex = numBatches; --batchIndex >= 0;) {
            // load batches
            const batch = batches[batchIndex];
            if (bind) {
                bind(batch);
            }
            // yield all indices
            for (let index = batch.length; --index >= 0;) {
                next(index, batch);
            }
        }
    }
    countBy(name) {
        const batches = this.chunks, numBatches = batches.length;
        const count_by = typeof name === 'string' ? new standalone_Col(name) : name;
        // Assume that all dictionary batches are deltas, which means that the
        // last record batch has the most complete dictionary
        count_by.bind(batches[numBatches - 1]);
        const vector = count_by.vector;
        if (!standalone_DataType.isDictionary(vector.type)) {
            throw new Error('countBy currently only supports dictionary-encoded columns');
        }
        const countByteLength = Math.ceil(Math.log(vector.length) / Math.log(256));
        const CountsArrayType = countByteLength == 4 ? Uint32Array :
            countByteLength >= 2 ? Uint16Array : Uint8Array;
        const counts = new CountsArrayType(vector.dictionary.length);
        for (let batchIndex = -1; ++batchIndex < numBatches;) {
            // load batches
            const batch = batches[batchIndex];
            // rebind the countBy Col
            count_by.bind(batch);
            const keys = count_by.vector.indices;
            // yield all indices
            for (let index = -1, numRows = batch.length; ++index < numRows;) {
                let key = keys.get(index);
                if (key !== null) {
                    counts[key]++;
                }
            }
        }
        return new standalone_CountByResult(vector.dictionary, standalone_IntVector.from(counts));
    }
}
/** @ignore */
class standalone_CountByResult extends standalone_table_Table {
    constructor(values, counts) {
        const schema = new standalone_Schema([
            new standalone_schema_Field('values', values.type),
            new standalone_schema_Field('counts', counts.type)
        ]);
        super(new standalone_recordbatch_RecordBatch(schema, counts.length, [values, counts]));
    }
    toJSON() {
        const values = this.getColumnAt(0);
        const counts = this.getColumnAt(1);
        const result = {};
        for (let i = -1; ++i < this.length;) {
            result[values.get(i)] = counts.get(i);
        }
        return result;
    }
}
/** @ignore */
class standalone_FilteredDataFrame extends standalone_DataFrame {
    constructor(batches, predicate) {
        super(batches);
        this._predicate = predicate;
    }
    scan(next, bind) {
        // inlined version of this:
        // this.parent.scan((idx, columns) => {
        //     if (this.predicate(idx, columns)) next(idx, columns);
        // });
        const batches = this._chunks;
        const numBatches = batches.length;
        for (let batchIndex = -1; ++batchIndex < numBatches;) {
            // load batches
            const batch = batches[batchIndex];
            const predicate = this._predicate.bind(batch);
            let isBound = false;
            // yield all indices
            for (let index = -1, numRows = batch.length; ++index < numRows;) {
                if (predicate(index, batch)) {
                    // bind batches lazily - if predicate doesn't match anything
                    // in the batch we don't need to call bind on the batch
                    if (bind && !isBound) {
                        bind(batch);
                        isBound = true;
                    }
                    next(index, batch);
                }
            }
        }
    }
    scanReverse(next, bind) {
        const batches = this._chunks;
        const numBatches = batches.length;
        for (let batchIndex = numBatches; --batchIndex >= 0;) {
            // load batches
            const batch = batches[batchIndex];
            const predicate = this._predicate.bind(batch);
            let isBound = false;
            // yield all indices
            for (let index = batch.length; --index >= 0;) {
                if (predicate(index, batch)) {
                    // bind batches lazily - if predicate doesn't match anything
                    // in the batch we don't need to call bind on the batch
                    if (bind && !isBound) {
                        bind(batch);
                        isBound = true;
                    }
                    next(index, batch);
                }
            }
        }
    }
    count() {
        // inlined version of this:
        // let sum = 0;
        // this.parent.scan((idx, columns) => {
        //     if (this.predicate(idx, columns)) ++sum;
        // });
        // return sum;
        let sum = 0;
        const batches = this._chunks;
        const numBatches = batches.length;
        for (let batchIndex = -1; ++batchIndex < numBatches;) {
            // load batches
            const batch = batches[batchIndex];
            const predicate = this._predicate.bind(batch);
            // yield all indices
            for (let index = -1, numRows = batch.length; ++index < numRows;) {
                if (predicate(index, batch)) {
                    ++sum;
                }
            }
        }
        return sum;
    }
    *[Symbol.iterator]() {
        // inlined version of this:
        // this.parent.scan((idx, columns) => {
        //     if (this.predicate(idx, columns)) next(idx, columns);
        // });
        const batches = this._chunks;
        const numBatches = batches.length;
        for (let batchIndex = -1; ++batchIndex < numBatches;) {
            // load batches
            const batch = batches[batchIndex];
            // TODO: bind batches lazily
            // If predicate doesn't match anything in the batch we don't need
            // to bind the callback
            const predicate = this._predicate.bind(batch);
            // yield all indices
            for (let index = -1, numRows = batch.length; ++index < numRows;) {
                if (predicate(index, batch)) {
                    yield batch.get(index);
                }
            }
        }
    }
    filter(predicate) {
        return new standalone_FilteredDataFrame(this._chunks, this._predicate.and(predicate));
    }
    countBy(name) {
        const batches = this._chunks, numBatches = batches.length;
        const count_by = typeof name === 'string' ? new standalone_Col(name) : name;
        // Assume that all dictionary batches are deltas, which means that the
        // last record batch has the most complete dictionary
        count_by.bind(batches[numBatches - 1]);
        const vector = count_by.vector;
        if (!standalone_DataType.isDictionary(vector.type)) {
            throw new Error('countBy currently only supports dictionary-encoded columns');
        }
        const countByteLength = Math.ceil(Math.log(vector.length) / Math.log(256));
        const CountsArrayType = countByteLength == 4 ? Uint32Array :
            countByteLength >= 2 ? Uint16Array : Uint8Array;
        const counts = new CountsArrayType(vector.dictionary.length);
        for (let batchIndex = -1; ++batchIndex < numBatches;) {
            // load batches
            const batch = batches[batchIndex];
            const predicate = this._predicate.bind(batch);
            // rebind the countBy Col
            count_by.bind(batch);
            const keys = count_by.vector.indices;
            // yield all indices
            for (let index = -1, numRows = batch.length; ++index < numRows;) {
                let key = keys.get(index);
                if (key !== null && predicate(index, batch)) {
                    counts[key]++;
                }
            }
        }
        return new standalone_CountByResult(vector.dictionary, standalone_IntVector.from(counts));
    }
}

//# sourceMappingURL=dataframe.mjs.map

;// ../../node_modules/apache-arrow/Arrow.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
























/** @ignore */
const standalone_util = {
    ...standalone_bn_namespaceObject,
    ...standalone_util_int_namespaceObject,
    ...standalone_bit_namespaceObject,
    ...standalone_util_math_namespaceObject,
    ...standalone_util_buffer_namespaceObject,
    ...standalone_util_vector_namespaceObject
};

//# sourceMappingURL=Arrow.mjs.map

;// ../../node_modules/apache-arrow/Arrow.dom.mjs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.








standalone_adapters.toDOMStream = standalone_toDOMStream;
standalone_Builder['throughDOM'] = standalone_builderThroughDOMStream;
standalone_RecordBatchReader['throughDOM'] = standalone_recordBatchReaderThroughDOMStream;
standalone_RecordBatchWriter['throughDOM'] = standalone_recordBatchWriterThroughDOMStream;


//# sourceMappingURL=Arrow.dom.mjs.map

;// ../../node_modules/arquero/src/arrow/arrow-types.js
// Hardwire Arrow type ids to sidestep dependency
// https://github.com/apache/arrow/blob/master/js/src/enum.ts

/* harmony default export */ const standalone_arrow_types = ({
  /** The default placeholder type */
  NONE: 0,
  /** A NULL type having no physical storage */
  Null: 1,
  /** Signed or unsigned 8, 16, 32, or 64-bit little-endian integer */
  Int: 2,
  /** 2, 4, or 8-byte floating point value */
  Float: 3,
  /** Variable-length bytes (no guarantee of UTF8-ness) */
  Binary: 4,
  /** UTF8 variable-length string as List<Char> */
  Utf8: 5,
  /** Boolean as 1 bit, LSB bit-packed ordering */
  Bool: 6,
  /** Precision-and-scale-based decimal type. Storage type depends on the parameters. */
  Decimal: 7,
  /** int32_t days or int64_t milliseconds since the UNIX epoch */
  Date: 8,
  /** Time as signed 32 or 64-bit integer, representing either seconds, milliseconds, microseconds, or nanoseconds since midnight since midnight */
  Time: 9,
  /** Exact timestamp encoded with int64 since UNIX epoch (Default unit millisecond) */
  Timestamp: 10,
  /** YEAR_MONTH or DAY_TIME interval in SQL style */
  Interval: 11,
  /** A list of some logical data type */
  List: 12,
  /** Struct of logical types */
  Struct: 13,
  /** Union of logical types */
  Union: 14,
  /** Fixed-size binary. Each value occupies the same number of bytes */
  FixedSizeBinary: 15,
  /** Fixed-size list. Each value occupies the same number of bytes */
  FixedSizeList: 16,
  /** Map of named logical types */
  Map: 17,

  /** Dictionary aka Category type */
  Dictionary: -1,
  Int8: -2,
  Int16: -3,
  Int32: -4,
  Int64: -5,
  Uint8: -6,
  Uint16: -7,
  Uint32: -8,
  Uint64: -9,
  Float16: -10,
  Float32: -11,
  Float64: -12,
  DateDay: -13,
  DateMillisecond: -14,
  TimestampSecond: -15,
  TimestampMillisecond: -16,
  TimestampMicrosecond: -17,
  TimestampNanosecond: -18,
  TimeSecond: -19,
  TimeMillisecond: -20,
  TimeMicrosecond: -21,
  TimeNanosecond: -22,
  DenseUnion: -23,
  SparseUnion: -24,
  IntervalDayTime: -25,
  IntervalYearMonth: -26
});
;// ../../node_modules/arquero/src/arrow/builder/util.js


function standalone_ceil64Bytes(length, bpe = 1) {
  return ((((length * bpe) + 63) & ~63) || 64) / bpe;
}

function standalone_util_array(Type, length, bpe = Type.BYTES_PER_ELEMENT) {
  return new Type(standalone_ceil64Bytes(length, bpe));
}

function standalone_arrowData(d) {
  return d instanceof standalone_Data
    ? d
    : standalone_Data.new(d.type, 0, d.length, d.nulls, d.buffers, null, d.dict);
}

function standalone_arrowVector(data) {
  return standalone_AbstractVector.new(standalone_arrowData(data));
}

const standalone_util_encoder = new TextEncoder();

function standalone_util_encode(data, idx, str) {
  const bytes = standalone_util_encoder.encode(str);
  data.set(bytes, idx);
  return bytes.length;
}

function standalone_encodeInto(data, idx, str) {
  return standalone_util_encoder.encodeInto(str, data.subarray(idx)).written;
}

const standalone_writeUtf8 = standalone_util_encoder.encodeInto ? standalone_encodeInto : standalone_util_encode;
;// ../../node_modules/arquero/src/arrow/builder/array-builder.js


/* harmony default export */ function standalone_array_builder(type, length) {
  const data = standalone_util_array(type.ArrayType, length);
  return {
    set(value, index) { data[index] = value; },
    data: () => ({ type, length, buffers: [null, data] })
  };
}
;// ../../node_modules/arquero/src/arrow/builder/bool-builder.js


/* harmony default export */ function standalone_bool_builder(type, length) {
  const data = standalone_util_array(type.ArrayType, length / 8);
  return {
    set(value, index) {
      if (value) data[index >> 3] |= (1 << (index % 8));
    },
    data: () => ({ type, length, buffers: [null, data] })
  };
}
;// ../../node_modules/arquero/src/arrow/builder/date-day-builder.js


/* harmony default export */ function standalone_date_day_builder(type, length) {
  const data = standalone_util_array(type.ArrayType, length);
  return {
    set(value, index) { data[index] = (value / 86400000) | 0; },
    data: () => ({ type, length, buffers: [null, data] })
  };
}
;// ../../node_modules/arquero/src/arrow/builder/date-millis-builder.js


/* harmony default export */ function standalone_date_millis_builder(type, length) {
  const data = standalone_util_array(type.ArrayType, length << 1);
  return {
    set(value, index) {
      const i = index << 1;
      data[  i] = (value % 4294967296) | 0;
      data[i+1] = (value / 4294967296) | 0;
    },
    data: () => ({ type, length, buffers: [null, data] })
  };
}
;// ../../node_modules/arquero/src/arrow/builder/default-builder.js


/* harmony default export */ function standalone_default_builder(type) {
  const b = standalone_Builder.new({
    type,
    nullValues: [null, undefined],
    highWaterMark: Infinity
  });
  return {
    set(value, index) { b.set(index, value); },
    data: () => b.finish().flush()
  };
}
;// ../../node_modules/arquero/src/arrow/builder/utf8-builder.js


/* harmony default export */ function standalone_utf8_builder(type, length, strlen) {
  const offset = standalone_util_array(Int32Array, length + 1);
  const buf = standalone_util_array(Uint8Array, 3 * strlen);

  let idx = 0;

  return {
    set(value, index) {
      idx += standalone_writeUtf8(buf, idx, value);
      offset[index + 1] = idx;
    },
    data: () => {
      // slice utf buffer if over-allocated
      const dlen = standalone_ceil64Bytes(idx);
      const data = buf.length > dlen ? buf.subarray(0, dlen) : buf;
      return { type, length, buffers: [offset, data] };
    }
  };
}
;// ../../node_modules/arquero/src/arrow/builder/dictionary-builder.js



/* harmony default export */ function standalone_dictionary_builder(type, length) {
  const values = [];
  const data = standalone_util_array(type.indices.ArrayType, length);
  const keys = Object.create(null);

  let next = -1;
  let strlen = 0;

  return {
    set(value, index) {
      const v = String(value);
      let k = keys[v];
      if (k === undefined) {
        strlen += v.length;
        keys[v] = k = ++next;
        values.push(v);
      }
      data[index] = k;
    },
    data: () => ({
      type,
      length,
      buffers: [null, data],
      dict: standalone_dictionary(type.dictionary, values, strlen)
    })
  };
}

function standalone_dictionary(type, values, strlen) {
  const b = standalone_utf8_builder(type, values.length, strlen);
  values.forEach(b.set);
  return standalone_arrowVector(b.data());
}
;// ../../node_modules/arquero/src/arrow/builder/valid-builder.js


/* harmony default export */ function standalone_valid_builder(builder, length) {
  const valid = standalone_util_array(Uint8Array, length / 8);
  let nulls = 0;

  return {
    set(value, index) {
      if (value == null) {
        ++nulls;
      } else {
        builder.set(value, index);
        valid[index >> 3] |= (1 << (index % 8));
      }
    },
    data: () => {
      const d = builder.data();
      if (nulls) {
        d.nulls = nulls;
        d.buffers[2] = valid;
      }
      return d;
    }
  };
}
;// ../../node_modules/arquero/src/arrow/builder/index.js









/* harmony default export */ function standalone_builder(type, nrows, nullable = true) {
  let method;

  switch (type.typeId) {
    case standalone_arrow_types.Int:
      method = type.bitWidth < 64 ? standalone_array_builder : null;
      break;
    case standalone_arrow_types.Float:
      method = type.precision > 0 ? standalone_array_builder : null;
      break;
    case standalone_arrow_types.Dictionary:
      // check sub-types against builder assumptions
      // if check fails, fallback to default builder
      method = (
        type.dictionary.typeId === standalone_arrow_types.Utf8 &&
        type.indices.typeId === standalone_arrow_types.Int &&
        type.indices.bitWidth < 64
      ) ? standalone_dictionary_builder : null;
      break;
    case standalone_arrow_types.Bool:
      method = standalone_bool_builder;
      break;
    case standalone_arrow_types.Date:
      method = type.unit ? standalone_date_millis_builder : standalone_date_day_builder;
      break;
  }

  return method == null ? standalone_default_builder(type)
    : nullable ? standalone_valid_builder(method(type, nrows), nrows)
    : method(type, nrows);
}
;// ../../node_modules/arquero/src/arrow/encode/data-from.js



function standalone_dataFromArray(array, type) {
  const length = array.length;
  const size = standalone_ceil64Bytes(length, array.BYTES_PER_ELEMENT);

  let data = array;
  if (length !== size) {
    data = new array.constructor(size);
    data.set(array);
  }

  return standalone_arrowData({ type, length, buffers: [null, data] });
}

function standalone_dataFromScan(nrows, scan, column, type, nullable = true) {
  const b = standalone_builder(type, nrows, nullable);
  scan(column, b.set);
  return standalone_arrowData(b.data());
}
;// ../../node_modules/arquero/src/arrow/builder/resolve-type.js





/* harmony default export */ function standalone_resolve_type(type) {
  if (type instanceof standalone_DataType || type == null) {
    return type;
  }

  switch (type) {
    case standalone_arrow_types.Binary:
      return new standalone_Binary();
    case standalone_arrow_types.Bool:
      return new standalone_Bool();
    case standalone_arrow_types.DateDay:
      return new standalone_DateDay();
    case standalone_arrow_types.DateMillisecond:
    case standalone_arrow_types.Date:
      return new standalone_DateMillisecond();
    case standalone_arrow_types.Dictionary:
      return new standalone_type_Dictionary(new standalone_Utf8(), new standalone_Int32());
    case standalone_arrow_types.Float16:
      return new standalone_Float16();
    case standalone_arrow_types.Float32:
      return new standalone_Float32();
    case standalone_arrow_types.Float64:
    case standalone_arrow_types.Float:
      return new standalone_Float64();
    case standalone_arrow_types.Int8:
      return new standalone_Int8();
    case standalone_arrow_types.Int16:
      return new standalone_Int16();
    case standalone_arrow_types.Int32:
    case standalone_arrow_types.Int:
      return new standalone_Int32();
    case standalone_arrow_types.Int64:
      return new standalone_Int64();
    case standalone_arrow_types.IntervalDayTime:
      return new standalone_IntervalDayTime();
    case standalone_arrow_types.Interval:
    case standalone_arrow_types.IntervalYearMonth:
      return new standalone_IntervalYearMonth();
    case standalone_arrow_types.Null:
      return new standalone_Null();
    case standalone_arrow_types.TimeMicrosecond:
      return new standalone_TimeMicrosecond();
    case standalone_arrow_types.TimeMillisecond:
    case standalone_arrow_types.Time:
      return new standalone_TimeMillisecond();
    case standalone_arrow_types.TimeNanosecond:
      return new standalone_TimeNanosecond();
    case standalone_arrow_types.TimeSecond:
      return new standalone_TimeSecond();
    case standalone_arrow_types.Uint8:
      return new standalone_Uint8();
    case standalone_arrow_types.Uint16:
      return new standalone_Uint16();
    case standalone_arrow_types.Uint32:
      return new standalone_Uint32();
    case standalone_arrow_types.Uint64:
      return new standalone_Uint64();
    case standalone_arrow_types.Utf8:
      return new standalone_Utf8();
    default:
      standalone_util_error(
        `Unsupported type code: ${standalone_to_string(type)}. ` +
        'Use a data type constructor instead?'
      );
  }
}
;// ../../node_modules/arquero/src/util/is-exact-utc-date.js
/* harmony default export */ function standalone_is_exact_utc_date(d) {
  return d.getUTCHours() === 0
    && d.getUTCMinutes() === 0
    && d.getUTCSeconds() === 0
    && d.getUTCMilliseconds() === 0;
}
;// ../../node_modules/arquero/src/arrow/encode/profiler.js








function standalone_profile(scan, column) {
  const p = standalone_profiler();
  scan(column, p.add);
  return p;
}

function standalone_profiler() {
  const p = {
    count: 0,
    nulls: 0,
    bools: 0,
    nums: 0,
    ints: 0,
    bigints: 0,
    min: Infinity,
    max: -Infinity,
    digits: 0,
    dates: 0,
    utcdays: 0,
    strings: 0,
    strlen: 0,
    arrays: 0,
    minlen: Infinity,
    maxlen: 0,
    structs: 0,

    add(value) {
      ++p.count;
      if (value == null) {
        ++p.nulls;
        return;
      }

      const type = typeof value;
      if (type === 'string') {
        ++p.strings;
      } else if (type === 'number') {
        ++p.nums;
        if (value < p.min) p.min = value;
        if (value > p.max) p.max = value;
        if (Number.isInteger(value)) ++p.ints;
      } else if (type === 'boolean') {
        ++p.bools;
      } else if (type === 'object') {
        if (standalone_is_date(value)) {
          ++p.dates;
          if (standalone_is_exact_utc_date(value)) {
            ++p.utcdays;
          }
        } else if (standalone_is_array_type_isArrayType(value)) {
          ++p.arrays;
          if (value.length < p.minlen) p.minlen = value.length;
          if (value.length > p.maxlen) p.maxlen = value.length;
          const ap = p.array_prof || (p.array_prof = standalone_profiler());
          value.forEach(ap.add);
        } else {
          ++p.structs;
          const sp = p.struct_prof || (p.struct_prof = {});
          for (const key in value) {
            const fp = sp[key] || (sp[key] = standalone_profiler());
            fp.add(value[key]);
          }
        }
      } else if (type === 'bigint') {
        ++p.bigints;
        if (value < p.min) p.min = value;
        if (value > p.max) p.max = value;
      }
    },
    type() {
      return standalone_resolve_type(standalone_infer(p));
    }
  };

  return p;
}

function standalone_infer(p) {
  const valid = p.count - p.nulls;

  if (valid === 0) {
    return standalone_arrow_types.Null;
  }
  else if (p.ints === valid) {
    const v = Math.max(Math.abs(p.min) - 1, p.max);
    return p.min < 0
      ? v >= 2 ** 31 ? standalone_arrow_types.Float64
        : v < (1 << 7) ? standalone_arrow_types.Int8 : v < (1 << 15) ? standalone_arrow_types.Int16 : standalone_arrow_types.Int32
      : v >= 2 ** 32 ? standalone_arrow_types.Float64
        : v < (1 << 8) ? standalone_arrow_types.Uint8 : v < (1 << 16) ? standalone_arrow_types.Uint16 : standalone_arrow_types.Uint32;
  }
  else if (p.nums === valid) {
    return standalone_arrow_types.Float64;
  }
  else if (p.bigints === valid) {
    const v = -p.min > p.max ? -p.min - 1n : p.max;
    return p.min < 0
      ? v < 2 ** 63 ? standalone_arrow_types.Int64
        : standalone_util_error(`BigInt exceeds 64 bits: ${v}`)
      : p.max < 2 ** 64 ? standalone_arrow_types.Uint64
        : standalone_util_error(`BigInt exceeds 64 bits: ${p.max}`);
  }
  else if (p.bools === valid) {
    return standalone_arrow_types.Bool;
  }
  else if (p.utcdays === valid) {
    return standalone_arrow_types.DateDay;
  }
  else if (p.dates === valid) {
    return standalone_arrow_types.DateMillisecond;
  }
  else if (p.arrays === valid) {
    const type = standalone_schema_Field.new('value', p.array_prof.type(), true);
    return p.minlen === p.maxlen
      ? new standalone_FixedSizeList(p.minlen, type)
      : new standalone_List(type);
  }
  else if (p.structs === valid) {
    const sp = p.struct_prof;
    return new standalone_Struct(
      Object.keys(sp).map(name => standalone_schema_Field.new(name, sp[name].type(), true))
    );
  }
  else if (p.strings > 0) {
    return standalone_arrow_types.Dictionary;
  }
  else {
    standalone_util_error('Type inference failure');
  }
}
;// ../../node_modules/arquero/src/arrow/encode/data-from-objects.js




/* harmony default export */ function standalone_data_from_objects(data, name, nrows, scan, type, nullable = true) {
  type = standalone_resolve_type(type);

  // perform type inference if needed
  if (!type) {
    const p = standalone_profile(scan, name);
    nullable = p.nulls > 0;
    type = p.type();
  }

  return standalone_dataFromScan(nrows, scan, name, type, nullable);
}
;// ../../node_modules/arquero/src/arrow/encode/data-from-table.js






/* harmony default export */ function standalone_data_from_table(table, name, nrows, scan, type, nullable = true) {
  type = standalone_resolve_type(type);
  const column = table.column(name);
  const reified = !(table.isFiltered() || table.isOrdered());

  // use existing arrow data if types match
  const vec = standalone_data_from_table_arrowVector(column);
  if (vec && reified && standalone_typeCompatible(vec.type, type)) {
    return vec;
  }

  // if backing data is a typed array, leverage that
  const data = column.data;
  if (standalone_is_typed_array(data)) {
    const dtype = standalone_typeFromArray(data);
    if (reified && dtype && standalone_typeCompatible(dtype, type)) {
      return standalone_dataFromArray(data, dtype);
    } else {
      type = type || dtype;
      nullable = false;
    }
  }

  // perform type inference if needed
  if (!type) {
    const p = standalone_profile(scan, column);
    nullable = p.nulls > 0;
    type = p.type();
  }

  return standalone_dataFromScan(nrows, scan, column, type, nullable);
}

function standalone_data_from_table_arrowVector(value) {
  return value instanceof standalone_AbstractVector ? value
    : value.vector instanceof standalone_AbstractVector ? value.vector
    : null;
}

function standalone_typeFromArray(data) {
  const types = {
    Float32Array:    standalone_Float32,
    Float64Array:    standalone_Float64,
    Int8Array:       standalone_Int8,
    Int16Array:      standalone_Int16,
    Int32Array:      standalone_Int32,
    Uint8Array:      standalone_Uint8,
    Uint16Array:     standalone_Uint16,
    Uint32Array:     standalone_Uint32,
    BigInt64Array:   standalone_Int64,
    BigUint64Array:  standalone_Uint64
  };
  const Type = types[data.constructor.name];
  return Type ? new Type() : null;
}

function standalone_typeCompatible(a, b) {
  return !a || !b ? true : a.compareTo(b);
}
;// ../../node_modules/arquero/src/arrow/encode/scan.js


function standalone_scanArray(data, limit, offset) {
  const n = Math.min(data.length, offset + limit);
  return (name, visit) => {
    for (let i = offset; i < n; ++i) {
      visit(data[i][name], i);
    }
  };
}

function standalone_scanTable(table, limit, offset) {
  const scanAll = offset === 0 && table.numRows() <= limit
               && !table.isFiltered() && !table.isOrdered();

  return (column, visit) => {
    let i = -1;
    scanAll && standalone_is_array_type_isArrayType(column.data)
      ? column.data.forEach(visit)
      : table.scan(
          row => visit(column.get(row), ++i),
          true, limit, offset
        );
  };
}
;// ../../node_modules/arquero/src/arrow/arrow-table.js



function standalone_table() {
  // trap Table access to provide a helpful message
  // when Apache Arrow has not been imported
  try {
    return standalone_table_Table;
  } catch (err) {
    standalone_util_error(
      'Apache Arrow not imported, ' +
      'see https://github.com/uwdata/arquero#usage'
    );
  }
}

function standalone_arrow_table_from(arrow) {
  return arrow && arrow.chunks ? arrow : standalone_table().from(arrow);
}
;// ../../node_modules/arquero/src/arrow/encode/index.js
 // eslint-disable-line no-unused-vars









/**
 * Options for Arrow encoding.
 * @typedef {object} ArrowFormatOptions
 * @property {number} [limit=Infinity] The maximum number of rows to include.
 * @property {number} [offset=0] The row offset indicating how many initial
 *  rows to skip.
 * @property {string[]|(data: object) => string[]} [columns] Ordered list of
 *  column names to include. If function-valued, the function should accept
 *  a dataset as input and return an array of column name strings.
 * @property {object} [types] The Arrow data types to use. If specified,
 *  the input should be an object with column names for keys and Arrow data
 *  types for values. If a column type is not explicitly provided, type
 *  inference will be performed to guess an appropriate type.
 */

/**
 * Create an Apache Arrow table for an input dataset.
 * @param {Array|object} data An input dataset to convert to Arrow format.
 *  If array-valued, the data should consist of an array of objects where
 *  each entry represents a row and named properties represent columns.
 *  Otherwise, the input data should be an Arquero table.
 * @param {ArrowFormatOptions} [options] Encoding options, including
 *  column data types.
 * @return {Table} An Apache Arrow Table instance.
 */
/* harmony default export */ function standalone_arrow_encode(data, options = {}) {
  const { types = {} } = options;
  const { dataFrom, names, nrows, scan } = standalone_encode_init(data, options);
  return standalone_table().new(
    names.map(name => {
      const col = dataFrom(data, name, nrows, scan, types[name]);
      return col.length === nrows
        ? col
        : standalone_util_error('Column length mismatch');
    }),
    names
  );
}

function standalone_encode_init(data, options) {
  const { columns, limit = Infinity, offset = 0 } = options;
  const names = standalone_util_is_function(columns) ? columns(data)
    : standalone_is_array(columns) ? columns
    : null;
  if (standalone_is_array(data)) {
    return {
      dataFrom: standalone_data_from_objects,
      names: names || Object.keys(data[0]),
      nrows: Math.min(limit, data.length - offset),
      scan: standalone_scanArray(data, limit, offset)
    };
  } else if (standalone_isTable(data)) {
    return {
      dataFrom: standalone_data_from_table,
      names: names || data.columnNames(),
      nrows: Math.min(limit, data.numRows() - offset),
      scan: standalone_scanTable(data, limit, offset)
    };
  } else {
    standalone_util_error('Unsupported input data type');
  }
}

function standalone_isTable(data) {
  return data && standalone_util_is_function(data.reify);
}
;// ../../node_modules/arquero/src/format/to-arrow.js

/* harmony default export */ const standalone_to_arrow = (standalone_arrow_encode);
;// ../../node_modules/arquero/src/format/infer.js


function standalone_isExactDateUTC(d) {
  return d.getUTCHours() === 0
    && d.getUTCMinutes() === 0
    && d.getUTCSeconds() === 0
    && d.getUTCMilliseconds() === 0;
}

/* harmony default export */ function standalone_format_infer(scan, options = {}) {
  let count = 0;
  let nulls = 0;
  let dates = 0;
  let dutcs = 0;
  let nums = 0;
  let digits = 0;

  scan(value => {
    ++count;
    if (value == null) {
      ++nulls;
      return;
    }

    const type = typeof value;
    if (type === 'object' && standalone_is_date(value)) {
      ++dates;
      if (standalone_isExactDateUTC(value)) ++dutcs;
    } else if (type === 'number') {
      ++nums;
      if (value === value &&  (value | 0) !== value) {
        const s = value + '';
        const p = s.indexOf('.');
        if (p >= 0) {
          const e = s.indexOf('e');
          const l = e > 0 ? e : s.length;
          digits = Math.max(digits, l - p - 1);
        }
      }
    }
  });

  return {
    align:  (nulls + nums + dates) / count > 0.5 ? 'r' : 'l',
    format: {
      utc:    dates === dutcs,
      digits: Math.min(digits, options.maxdigits || 6)
    }
  };
}
;// ../../node_modules/arquero/src/format/util.js
 // eslint-disable-line no-unused-vars




/**
 * Column selection function.
 * @typedef {(table: Table) => string[]} ColumnSelectFunction
 */

/**
 * Column selection options.
 * @typedef {string[]|ColumnSelectFunction} ColumnSelectOptions
 */

/**
 * Column format options. The object keys should be column names.
 * The object values should be formatting functions or objects.
 * If specified, these override any automatically inferred options.
 * @typedef {Object.<string, import('./value').ValueFormatOptions} ColumnFormatOptions
 */

/**
 * Column alignment options. The object keys should be column names.
 * The object values should be aligment strings, one of 'l' (left),
 * 'c' (center), or 'r' (right).
 * If specified, these override any automatically inferred options.
 * @typedef {Object.<string, 'l'|'c'|'r'>} ColumnAlignOptions
 */

function standalone_columns(table, names) {
  return standalone_util_is_function(names)
    ? names(table)
    : names || table.columnNames();
}

function standalone_util_formats(table, names, options) {
  const formatOpt = options.format || {};
  const alignOpt = options.align || {};
  const format = {};
  const align = {};

  names.forEach(name => {
    const auto = standalone_format_infer(standalone_util_values(table, name), options);
    align[name] = alignOpt[name] || auto.align;
    format[name] = formatOpt[name] || auto.format;
  });

  return { align, format };
}

function standalone_util_values(table, columnName) {
  const column = table.column(columnName);
  return fn => table.scan(row => fn(column.get(row)));
}

function standalone_scan(table, names, limit = 100, offset, ctx) {
  const data = table.data();
  const n = names.length;
  table.scan(row => {
    ctx.row(row);
    for (let i = 0; i < n; ++i) {
      const name = names[i];
      ctx.cell(data[names[i]].get(row), name, i);
    }
  }, true, limit, offset);
}
;// ../../node_modules/arquero/src/format/to-csv.js
 // eslint-disable-line no-unused-vars





/**
 * Options for CSV formatting.
 * @typedef {object} CSVFormatOptions
 * @property {string} [delimiter=','] The delimiter between values.
 * @property {number} [limit=Infinity] The maximum number of rows to print.
 * @property {number} [offset=0] The row offset indicating how many initial rows to skip.
 * @property {import('./util').ColumnSelectOptions} [columns] Ordered list
 *  of column names to include. If function-valued, the function should
 *  accept a table as input and return an array of column name strings.
 * @property {Object.<string, (value: any) => any>} [format] Object of column
 *  format options. The object keys should be column names. The object values
 *  should be formatting functions to invoke to transform column values prior
 *  to output. If specified, these override automatically inferred options.
 */

/**
 * Format a table as a comma-separated values (CSV) string. Other
 * delimiters, such as tabs or pipes ('|'), can be specified using
 * the options argument.
 * @param {ColumnTable} table The table to format.
 * @param {CSVFormatOptions} options The formatting options.
 * @return {string} A delimited-value format string.
 */
/* harmony default export */ function standalone_to_csv(table, options = {}) {
  const names = standalone_columns(table, options.columns);
  const format = options.format || {};
  const delim = options.delimiter || ',';
  const reFormat = new RegExp(`["${delim}\n\r]`);

  const formatValue = value => value == null ? ''
    : standalone_is_date(value) ? standalone_formatUTCDate(value, true)
    : reFormat.test(value += '') ? '"' + value.replace(/"/g, '""') + '"'
    : value;

  const vals = names.map(formatValue);
  let text = '';

  standalone_scan(table, names, options.limit || Infinity, options.offset, {
    row() {
      text += vals.join(delim) + '\n';
    },
    cell(value, name, index) {
      vals[index] = formatValue(format[name] ? format[name](value) : value);
    }
  });

  return text + vals.join(delim);
}
;// ../../node_modules/arquero/src/format/value.js





/**
 * Column format object.
 * @typedef {object} ValueFormatObject
 * @property {boolean} [utc=false] If true, format dates in UTC time.
 * @property {number} [digits=0] The number of fractional digits to include
 *  when formatting numbers.
 * @property {number} [maxlen=30] The maximum string length for formatting
 *  nested object or array values.
 */

/**
 * @callback ValueFormatFunction
 * @param {*} value The value to format.
 * @return {*} A string-coercible or JSON-compatible formatted value.
 */

/**
 * Value format options.
 * @typedef {ValueFormatObject|ValueFormatFunction} ValueFormatOptions
 */

/**
 * Format a value as a string.
 * @param {*} v The value to format.
 * @param {ValueFormatOptions} options Formatting options.
 * @return {string} The formatted string.
 */
/* harmony default export */ function standalone_format_value(v, options = {}) {
  if (standalone_util_is_function(options)) {
    return options(v) + '';
  }

  const type = typeof v;

  if (type === 'object') {
    if (standalone_is_date(v)) {
      return options.utc ? standalone_formatUTCDate(v) : standalone_format_date_formatDate(v);
    } else {
      const s = JSON.stringify(
        v,
        (k, v) => standalone_is_typed_array(v) ? Array.from(v) : v
      );
      const maxlen = options.maxlen || 30;
      return s.length > maxlen
        ? s.slice(0, 28) + '\u2026' + (s[0] === '[' ? ']' : '}')
        : s;
    }
  } else if (type === 'number') {
    const digits = options.digits || 0;
    let a;
    return v !== 0 && ((a = Math.abs(v)) >= 1e18 || a < Math.pow(10, -digits))
      ? v.toExponential(digits)
      : v.toFixed(digits);
  } else {
    return v + '';
  }
}
;// ../../node_modules/arquero/src/util/map-object.js
/* harmony default export */ function standalone_map_object(obj, fn, output = {}) {
  for (const key in obj) {
    output[key] = fn(obj[key], key);
  }
  return output;
}
;// ../../node_modules/arquero/src/format/to-html.js
 // eslint-disable-line no-unused-vars






/**
 * Null format function.
 * @callback NullFormat
 * @param {null|undefined} [value] The value to format.
 * @return {string} The formatted HTML string.
 */

/**
 * CSS style function.
 * @callback StyleFunction
 * @param {string} name The column name.
 * @param {number} row The table row index.
 * @return {string} A CSS style string.
 */

/**
 * CSS style options.
 * @typedef {Object.<string, string | StyleFunction>} StyleOptions
 */

/**
 * Options for HTML formatting.
 * @typedef {object} HTMLFormatOptions
 * @property {number} [limit=Infinity] The maximum number of rows to print.
 * @property {number} [offset=0] The row offset indicating how many initial rows to skip.
 * @property {import('./util').ColumnSelectOptions} [columns] Ordered list
 *  of column names to include. If function-valued, the function should
 *  accept a table as input and return an array of column name strings.
 * @property {import('./util').ColumnAlignOptions} [align] Object of column
 *  alignment options. The object keys should be column names. The object
 *  values should be aligment strings, one of 'l' (left), 'c' (center), or
 *  'r' (right). If specified, these override automatically inferred options.
 * @property {import('./util').ColumnFormatOptions} [format] Object of column
 *  format options. The object keys should be column names. The object values
 *  should be formatting functions or specification objects. If specified,
 *  these override automatically inferred options.
 * @property {NullFormat} [null] Format function for null or undefined values.
 *  If specified, this function will be invoked with the null or undefined
 *  value as the sole input, and the return value will be used as the HTML
 *  output for the value.
 * @property {StyleOptions} [style] CSS styles to include in HTML output.
 *  The object keys should be HTML table tag names: 'table', 'thead',
 *  'tbody', 'tr', 'th', or 'td'. The object values should be strings of
 *  valid CSS style directives (such as "font-weight: bold;") or functions
 *  that take a column name and row as inputs and return a CSS string.
 * @property {number} [maxdigits=6] The maximum number of fractional digits
 *  to include when formatting numbers. This option is passed to the format
 *  inference method and is overridden by any explicit format options.
 */

/**
 * Format a table as an HTML table string.
 * @param {ColumnTable} table The table to format.
 * @param {HTMLFormatOptions} options The formatting options.
 * @return {string} An HTML table string.
 */
/* harmony default export */ function standalone_to_html(table, options = {}) {
  const names = standalone_columns(table, options.columns);
  const { align, format } = standalone_util_formats(table, names, options);
  const style = standalone_styles(options);
  const nullish = options.null;

  const alignValue = a => a === 'c' ? 'center' : a === 'r' ? 'right' : 'left';
  const escape = s => s.replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
  const baseFormat = (value, opt) => escape(standalone_format_value(value, opt));
  const formatter = nullish
    ? (value, opt) => value == null ? nullish(value) : baseFormat(value, opt)
    : baseFormat;

  let r = -1;
  let idx = -1;

  const tag = (tag, name, shouldAlign) => {
    const a = shouldAlign ? alignValue(align[name]) : '';
    const s = style[tag] ? (style[tag](name, idx, r) || '') : '';
    const css = (a ? (`text-align: ${a};` + (s ? ' ' : '')) : '') + s;
    return `<${tag}${css ? ` style="${css}"` : ''}>`;
  };

  let text = tag('table')
    + tag('thead')
    + tag('tr', r)
    + names.map(name => `${tag('th', name, 1)}${name}</th>`).join('')
    + '</tr></thead>'
    + tag('tbody');

  standalone_scan(table, names, options.limit, options.offset, {
    row(row) {
      r = row;
      text += (++idx ? '</tr>' : '') + tag('tr');
    },
    cell(value, name) {
      text += tag('td', name, 1)
        + formatter(value, format[name])
        + '</td>';
    }
  });

  return text + '</tr></tbody></table>';
}

function standalone_styles(options) {
  return standalone_map_object(
    options.style,
    value => standalone_util_is_function(value) ? value : () => value
  );
}
;// ../../node_modules/arquero/src/util/default-true.js
/* harmony default export */ function standalone_default_true(value, trueValue = true, falseValue = false) {
  return (value === undefined || value) ? trueValue : falseValue;
}
;// ../../node_modules/arquero/src/format/to-json.js
 // eslint-disable-line no-unused-vars






/**
 * Options for JSON formatting.
 * @typedef {object} JSONFormatOptions
 * @property {number} [limit=Infinity] The maximum number of rows to print.
 * @property {number} [offset=0] The row offset indicating how many initial
 *  rows to skip.
 * @property {boolean} [schema=true] Flag indicating if table schema metadata
 *  should be included in the JSON output. If false, only the data payload
 *  is included.
 * @property {import('./util').ColumnSelectOptions} [columns] Ordered list
 *  of column names to include. If function-valued, the function should
 *  accept a table as input and return an array of column name strings.
 * @property {Object.<string, (value: any) => any>} [format] Object of column
 *  format options. The object keys should be column names. The object values
 *  should be formatting functions to invoke to transform column values prior
 *  to output. If specified, these override automatically inferred options.
 */

const standalone_to_json_defaultFormatter = value => standalone_is_date(value)
  ? standalone_formatUTCDate(value, true)
  : value;

/**
 * Format a table as a JavaScript Object Notation (JSON) string.
 * @param {ColumnTable} table The table to format.
 * @param {JSONFormatOptions} options The formatting options.
 * @return {string} A JSON string.
 */
/* harmony default export */ function standalone_to_json(table, options = {}) {
  const schema = standalone_default_true(options.schema);
  const format = options.format || {};
  const names = standalone_columns(table, options.columns);
  let text = '{';

  if (schema) {
    text += '"schema":{"fields":'
      + JSON.stringify(names.map(name => ({ name })))
      + '},"data":{';
  }

  names.forEach((name, i) => {
    text += (i ? ',' : '') + JSON.stringify(name) + ':[';

    const column = table.column(name);
    const formatter = format[name] || standalone_to_json_defaultFormatter;
    let r = -1;
    table.scan(row => {
      const value = column.get(row);
      text += (++r ? ',' : '') + JSON.stringify(formatter(value));
    }, true, options.limit, options.offset);

    text += ']';
  });

  return text + '}' + (schema ? '}' : '');
}
;// ../../node_modules/arquero/src/format/to-markdown.js
 // eslint-disable-line no-unused-vars




/**
 * Options for Markdown formatting.
 * @typedef {object} MarkdownFormatOptions
 * @property {number} [limit=Infinity] The maximum number of rows to print.
 * @property {number} [offset=0] The row offset indicating how many initial rows to skip.
 * @property {import('./util').ColumnSelectOptions} [columns] Ordered list
 *  of column names to include. If function-valued, the function should
 *  accept a table as input and return an array of column name strings.
 * @property {import('./util').ColumnAlignOptions} [align] Object of column
 *  alignment options. The object keys should be column names. The object
 *  values should be aligment strings, one of 'l' (left), 'c' (center), or
 *  'r' (right). If specified, these override automatically inferred options.
 * @property {import('./util').ColumnFormatOptions} [format] Object of column
 *  format options. The object keys should be column names. The object values
 *  should be formatting functions or specification objects. If specified,
 *  these override automatically inferred options.
 * @property {number} [maxdigits=6] The maximum number of fractional digits
 *  to include when formatting numbers. This option is passed to the format
 *  inference method and is overridden by any explicit format options.
 */

/**
 * Format a table as a GitHub-Flavored Markdown table string.
 * @param {ColumnTable} table The table to format.
 * @param {MarkdownFormatOptions} options The formatting options.
 * @return {string} A GitHub-Flavored Markdown table string.
 */
/* harmony default export */ function standalone_to_markdown(table, options = {}) {
  const names = standalone_columns(table, options.columns);
  const { align, format } = standalone_util_formats(table, names, options);

  const alignValue = a => a === 'c' ? ':-:' : a === 'r' ? '-:' : ':-';
  const escape = s => s.replace(/\|/g, '\\|');

  let text = '|'
    + names.map(escape).join('|')
    + '|\n|'
    + names.map(name => alignValue(align[name])).join('|')
    + '|';

  standalone_scan(table, names, options.limit, options.offset, {
    row() {
      text += '\n|';
    },
    cell(value, name) {
      text += escape(standalone_format_value(value, format[name])) + '|';
    }
  });

  return text + '\n';
}
;// ../../node_modules/arquero/src/util/assign.js


/* harmony default export */ function standalone_util_assign(map, pairs) {
  for (const [key, value] of standalone_util_entries(pairs)) {
    map.set(key, value);
  }
  return map;
}
;// ../../node_modules/arquero/src/util/escape-regexp.js
/* harmony default export */ function standalone_escape_regexp(str) {
  return str.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');
}
;// ../../node_modules/arquero/src/helpers/selection.js










function standalone_selection_resolve(table, sel, map = new Map()) {
  sel = standalone_is_number(sel) ? table.columnName(sel) : sel;

  if (standalone_is_string(sel)) {
    map.set(sel, sel);
  } else if (standalone_is_array(sel)) {
    sel.forEach(r => standalone_selection_resolve(table, r, map));
  } else if (standalone_util_is_function(sel)) {
    standalone_selection_resolve(table, sel(table), map);
  } else if (standalone_is_object(sel)) {
    standalone_util_assign(map, sel);
  } else {
    standalone_util_error(`Invalid column selection: ${standalone_to_string(sel)}`);
  }

  return map;
}

function standalone_decorate(value, toObject) {
  value.toObject = toObject;
  return value;
}

function standalone_toObject(value) {
  return standalone_is_array(value) ? value.map(standalone_toObject)
    : value && value.toObject ? value.toObject()
    : value;
}

/**
 * Proxy type for SelectHelper function.
 * @typedef {import('../table/transformable').SelectHelper} SelectHelper
 */

/**
 * Select all columns in a table.
 * Returns a function-valued selection compatible with {@link Table#select}.
 * @return {SelectHelper} Selection function compatible with select().
 */
function standalone_selection_all() {
  return standalone_decorate(
    table => table.columnNames(),
    () => ({ all: [] })
  );
}

/**
 * Negate a column selection, selecting all other columns in a table.
 * Returns a function-valued selection compatible with {@link Table#select}.
 * @param {...any} selection The selection to negate. May be a column name,
 *  column index, array of either, or a selection function (e.g., from range).
 * @return {SelectHelper} Selection function compatible with select().
 */
function standalone_not(...selection) {
  selection = selection.flat();
  return standalone_decorate(
    table => {
      const drop = standalone_selection_resolve(table, selection);
      return table.columnNames(name => !drop.has(name));
    },
    () => ({ not: standalone_toObject(selection) })
  );
}

/**
 * Select a contiguous range of columns.
 * @param {string|number} start The name/index of the first selected column.
 * @param {string|number} end The name/index of the last selected column.
 * @return {SelectHelper} Selection function compatible with select().
 */
function standalone_selection_range(start, end) {
  return standalone_decorate(
    table => {
      let i = standalone_is_number(start) ? start : table.columnIndex(start);
      let j = standalone_is_number(end) ? end : table.columnIndex(end);
      if (j < i) { const t = j; j = i; i = t; }
      return table.columnNames().slice(i, j + 1);
    },
    () => ({ range: [start, end] })
  );
}

/**
 * Select all columns whose names match a pattern.
 * @param {string|RegExp} pattern A string or regular expression pattern to match.
 * @return {SelectHelper} Selection function compatible with select().
 */
function standalone_matches(pattern) {
  if (standalone_is_string(pattern)) pattern = RegExp(standalone_escape_regexp(pattern));
  return standalone_decorate(
    table => table.columnNames(name => pattern.test(name)),
    () => ({ matches: [pattern.source, pattern.flags] })
  );
}

/**
 * Select all columns whose names start with a string.
 * @param {string} string The string to match at the start of the column name.
 * @return {SelectHelper} Selection function compatible with select().
 */
function standalone_startswith(string) {
  return standalone_matches(RegExp('^' + escapeRegExp(string)));
}

/**
 * Select all columns whose names end with a string.
 * @param {string} string The string to match at the end of the column name.
 * @return {SelectHelper} Selection function compatible with select().
 */
function standalone_endswith(string) {
  return standalone_matches(RegExp(escapeRegExp(string) + '$'));
}
;// ../../node_modules/arquero/src/util/array-type.js


/* harmony default export */ function standalone_array_type(column) {
  return standalone_is_typed_array(column.data) ? column.data.constructor : Array;
}
;// ../../node_modules/arquero/src/table/column-table.js

















/**
 * Class representing a table backed by a named set of columns.
 */
class standalone_column_table_ColumnTable extends standalone_Table {

  /**
   * Create a new ColumnTable from existing input data.
   * @param {object[]|Iterable<object>|object|Map} values The backing table data values.
   *  If array-valued, should be a list of JavaScript objects with
   *  key-value properties for each column value.
   *  If object- or Map-valued, a table with two columns (one for keys,
   *  one for values) will be created.
   * @param {string[]} [names] The named columns to include.
   * @return {ColumnTable} A new ColumnTable instance.
   */
  static from(values, names) {
    return new standalone_column_table_ColumnTable(standalone_columns_from(values, names), names);
  }

  /**
   * Create a new table for a set of named columns.
   * @param {object|Map} columns
   *  The set of named column arrays. Keys are column names.
   *  The enumeration order of the keys determines the column indices,
   *  unless the names parameter is specified.
   *  Values must be arrays (or array-like values) of identical length.
   * @param {string[]} [names] Ordered list of column names. If specified,
   *  this array determines the column indices. If not specified, the
   *  key enumeration order of the columns object is used.
   * @return {ColumnTable} the instantiated ColumnTable instance.
   */
  static new(columns, names) {
    if (columns instanceof standalone_column_table_ColumnTable) return columns;
    const data = {};
    const keys = [];
    for (const [key, value] of standalone_util_entries(columns)) {
      data[key] = value;
      keys.push(key);
    }
    return new standalone_column_table_ColumnTable(data, names || keys);
  }

  /**
   * Instantiate a new ColumnTable instance.
   * @param {object} columns An object mapping column names to values.
   * @param {string[]} [names] An ordered list of column names.
   * @param {BitSet} [filter] A filtering BitSet.
   * @param {GroupBySpec} [group] A groupby specification.
   * @param {RowComparator} [order] A row comparator function.
   * @param {Params} [params] An object mapping parameter names to values.
   */
  constructor(columns, names, filter, group, order, params) {
    standalone_map_object(columns, standalone_defaultColumnFactory, columns);
    names = names || Object.keys(columns);
    const nrows = names.length ? columns[names[0]].length : 0;
    super(names, nrows, columns, filter, group, order, params);
  }

  /**
   * Create a new table with the same type as this table.
   * The new table may have different data, filter, grouping, or ordering
   * based on the values of the optional configuration argument. If a
   * setting is not specified, it is inherited from the current table.
   * @param {CreateOptions} [options] Creation options for the new table.
   * @return {ColumnTable} A newly created table.
   */
  create({ data, names, filter, groups, order }) {
    const f = filter !== undefined ? filter : this.mask();

    return new standalone_column_table_ColumnTable(
      data || this._data,
      names || (!data ? this._names : null),
      f,
      groups !== undefined ? groups : standalone_regroup(this._group, filter && f),
      order !== undefined ? order : this._order,
      this._params
    );
  }

  /**
   * Create a new table with additional columns drawn from one or more input
   * tables. All tables must have the same numer of rows and are reified
   * prior to assignment. In the case of repeated column names, input table
   * columns overwrite existing columns.
   * @param {...ColumnTable} tables The tables to merge with this table.
   * @return {ColumnTable} A new table with merged columns.
   * @example table.assign(table1, table2)
   */
  assign(...tables) {
    const nrows = this.numRows();
    const base = this.reify();
    const cset = standalone_column_set(base).groupby(base.groups());
    tables.forEach(input => {
      input = standalone_column_table_ColumnTable.new(input);
      if (input.numRows() !== nrows) standalone_util_error('Assign row counts do not match');
      input = input.reify();
      input.columnNames(name => cset.add(name, input.column(name)));
    });
    return this.create(cset.new());
  }

  /**
   * Get the backing set of columns for this table.
   * @return {ColumnData} Object of named column instances.
   */
  columns() {
    return this._data;
  }

  /**
   * Get the column instance with the given name.
   * @param {string} name The column name.
   * @return {ColumnType | undefined} The named column, or undefined if it does not exist.
   */
  column(name) {
    return this._data[name];
  }

  /**
   * Get the column instance at the given index position.
   * @param {number} index The zero-based column index.
   * @return {ColumnType | undefined} The column, or undefined if it does not exist.
   */
  columnAt(index) {
    return this._data[this._names[index]];
  }

  /**
   * Get an array of values contained in a column. The resulting array
   * respects any table filter or orderby criteria.
   * @param {string} name The column name.
   * @param {ArrayConstructor|import('./table').TypedArrayConstructor} [constructor=Array]
   *  The array constructor for instantiating the output array.
   * @return {import('./table').DataValue[]|import('./table).TypedArray} The array of column values.
   */
  array(name, constructor = Array) {
    const column = this.column(name);
    const array = new constructor(this.numRows());
    let idx = -1;
    this.scan(row => array[++idx] = column.get(row), true);
    return array;
  }

  /**
   * Get the value for the given column and row.
   * @param {string} name The column name.
   * @param {number} [row=0] The row index, defaults to zero if not specified.
   * @return {import('./table').DataValue} The table value at (column, row).
   */
  get(name, row = 0) {
    const column = this.column(name);
    return this.isFiltered() || this.isOrdered()
      ? column.get(this.indices()[row])
      : column.get(row);
  }

  /**
   * Returns an accessor ("getter") function for a column. The returned
   * function takes a row index as its single argument and returns the
   * corresponding column value.
   * @param {string} name The column name.
   * @return {import('./table').ColumnGetter} The column getter function.
   */
  getter(name) {
    const column = this.column(name);
    const indices = this.isFiltered() || this.isOrdered() ? this.indices() : null;
    return indices ? row => column.get(indices[row])
      : column ? row => column.get(row)
      : standalone_util_error(`Unrecognized column: ${name}`);
  }

  /**
   * Returns an object representing a table row.
   * @param {number} [row=0] The row index, defaults to zero if not specified.
   * @return {object} A row object with named properties for each column.
   */
  object(row = 0) {
    return standalone_objectBuilder(this)(row);
  }

  /**
   * Returns an array of objects representing table rows.
   * @param {ObjectsOptions} [options] The options for row object generation.
   * @return {object[]} An array of row objects.
   */
  objects(options = {}) {
    const { grouped, limit, offset } = options;

    // generate array of row objects
    const names = standalone_selection_resolve(this, options.columns || standalone_selection_all());
    const create = standalone_rowObjectBuilder(names);
    const obj = [];
    this.scan(
      (row, data) => obj.push(create(row, data)),
      true, limit, offset
    );

    // produce nested output as requested
    if (grouped && this.isGrouped()) {
      const idx = [];
      this.scan(row => idx.push(row), true, limit, offset);
      return standalone_regroup_nest(this, idx, obj, grouped);
    }

    return obj;
  }

  /**
   * Returns an iterator over objects representing table rows.
   * @return {Iterator<object>} An iterator over row objects.
   */
  *[Symbol.iterator]() {
    const create = standalone_objectBuilder(this);
    const n = this.numRows();
    for (let i = 0; i < n; ++i) {
      yield create(i);
    }
  }

  /**
   * Create a new fully-materialized instance of this table.
   * All filter and orderby settings are removed from the new table.
   * Instead, the backing data itself is filtered and ordered as needed.
   * @param {number[]} [indices] Ordered row indices to materialize.
   *  If unspecified, all rows passing the table filter are used.
   * @return {ColumnTable} A reified table.
   */
  reify(indices) {
    const nrows = indices ? indices.length : this.numRows();
    const names = this._names;
    let data, groups;

    if (!indices && !this.isOrdered()) {
      if (!this.isFiltered()) {
        return this; // data already reified
      } else if (nrows === this.totalRows()) {
        data = this.data(); // all rows pass filter, skip copy
      }
    }

    if (!data) {
      const scan = indices ? f => indices.forEach(f) : f => this.scan(f, true);
      const ncols = names.length;
      data = {};

      for (let i = 0; i < ncols; ++i) {
        const name = names[i];
        const prev = this.column(name);
        const curr = data[name] = new (standalone_array_type(prev))(nrows);
        let r = -1;
        scan(row => curr[++r] = prev.get(row));
      }

      if (this.isGrouped()) {
        groups = standalone_reindex(this.groups(), scan, !!indices, nrows);
      }
    }

    return this.create({ data, names, groups, filter: null, order: null });
  }

  /**
   * Apply a sequence of transformations to this table. The output
   * of each transform is passed as input to the next transform, and
   * the output of the last transform is then returned.
   * @param {...(Transform|Transform[])} transforms Transformation
   *  functions to apply to the table in sequence. Each function should
   *  take a single table as input and return a table as output.
   * @return {ColumnTable} The output of the last transform.
   */
  transform(...transforms) {
    return transforms.flat().reduce((t, f) => f(t), this);
  }

  /**
   * Format this table as an Apache Arrow table.
   * @param {ArrowFormatOptions} [options] The formatting options.
   * @return {import('apache-arrow').Table} An Apache Arrow table.
   */
  toArrow(options) {
    return standalone_to_arrow(this, options);
  }

  /**
   * Format this table as binary data in the Apache Arrow IPC format.
   * @param {ArrowFormatOptions} [options] The formatting options.
   * @return {Uint8Array} A new Uint8Array of Arrow-encoded binary data.
   */
  toArrowBuffer(options) {
    return standalone_to_arrow(this, options).serialize();
  }

  /**
   * Format this table as a comma-separated values (CSV) string. Other
   * delimiters, such as tabs or pipes ('|'), can be specified using
   * the options argument.
   * @param {CSVFormatOptions} [options] The formatting options.
   * @return {string} A delimited value string.
   */
  toCSV(options) {
    return standalone_to_csv(this, options);
  }

  /**
   * Format this table as an HTML table string.
   * @param {HTMLFormatOptions} [options] The formatting options.
   * @return {string} An HTML table string.
   */
  toHTML(options) {
    return standalone_to_html(this, options);
  }

  /**
   * Format this table as a JavaScript Object Notation (JSON) string.
   * @param {JSONFormatOptions} [options] The formatting options.
   * @return {string} A JSON string.
   */
  toJSON(options) {
    return standalone_to_json(this, options);
  }

  /**
   * Format this table as a GitHub-Flavored Markdown table string.
   * @param {MarkdownFormatOptions} [options] The formatting options.
   * @return {string} A GitHub-Flavored Markdown table string.
   */
  toMarkdown(options) {
    return standalone_to_markdown(this, options);
  }
}

function standalone_objectBuilder(table) {
  let b = table._builder;

  if (!b) {
    const create = standalone_rowObjectBuilder(table.columnNames());
    const data = table.data();
    if (table.isOrdered() || table.isFiltered()) {
      const indices = table.indices();
      b = row => create(indices[row], data);
    } else {
      b = row => create(row, data);
    }
    table._builder = b;
  }

  return b;
}

/**
 * A table transformation.
 * @typedef {(table: ColumnTable) => ColumnTable} Transform
 */

/**
 * Proxy type for BitSet class.
 * @typedef {import('./table').BitSet} BitSet
 */

/**
 * Proxy type for ColumnType interface.
 * @typedef {import('./column').ColumnType} ColumnType
 */

/**
 * A named collection of columns.
 * @typedef {{[key: string]: ColumnType}} ColumnData
 */

/**
 * Proxy type for GroupBySpec.
 * @typedef {import('./table').GroupBySpec} GroupBySpec
 */

/**
 * Proxy type for RowComparator.
 * @typedef {import('./table').RowComparator} RowComparator
 */

/**
 * Proxy type for Params.
 * @typedef {import('./table').Params} Params
 */

/**
 * Options for Arrow formatting.
 * @typedef {import('../arrow/encode').ArrowFormatOptions} ArrowFormatOptions
 */

/**
 * Options for CSV formatting.
 * @typedef {import('../format/to-csv').CSVFormatOptions} CSVFormatOptions
 */

/**
 * Options for HTML formatting.
 * @typedef {import('../format/to-html').HTMLFormatOptions} HTMLFormatOptions
 */

/**
 * Options for JSON formatting.
 * @typedef {import('../format/to-json').JSONFormatOptions} JSONFormatOptions
 */

/**
 * Options for Markdown formatting.
 * @typedef {import('../format/to-markdown').MarkdownFormatOptions} MarkdownFormatOptions
 */
;// ../../node_modules/arquero/src/engine/reduce/reducer.js
/**
 * Abstract class for custom aggregation operations.
 */
class standalone_Reducer {
  constructor(outputs) {
    this._outputs = outputs;
  }

  size() {
    return this._outputs.length;
  }

  outputs() {
    return this._outputs;
  }

  init(/* columns */) {
    return {};
  }

  add(/* state, row, data */) {
    // no-op, subclasses should override
  }

  rem(/* state, row, data */) {
    // no-op, subclasses should override
  }

  write(/* state, values, index */) {
  }
}
;// ../../node_modules/arquero/src/expression/ast/walk.js
function standalone_walk(node, ctx, visitors, parent) {
  const visit = visitors[node.type] || visitors['Default'];
  if (visit && visit(node, ctx, parent) === false) return;

  const walker = standalone_walkers[node.type];
  if (walker) walker(node, ctx, visitors);
}

const standalone_unary = (node, ctx, visitors) => {
  standalone_walk(node.argument, ctx, visitors, node);
};

const standalone_walk_binary = (node, ctx, visitors) => {
  standalone_walk(node.left, ctx, visitors, node);
  standalone_walk(node.right, ctx, visitors, node);
};

const standalone_ternary = (node, ctx, visitors) => {
  standalone_walk(node.test, ctx, visitors, node);
  standalone_walk(node.consequent, ctx, visitors, node);
  if (node.alternate) standalone_walk(node.alternate, ctx, visitors, node);
};

const standalone_walk_func = (node, ctx, visitors) => {
  standalone_walk_list(node.params, ctx, visitors, node);
  standalone_walk(node.body, ctx, visitors, node);
};

const standalone_walk_call = (node, ctx, visitors) => {
  standalone_walk(node.callee, ctx, visitors, node);
  standalone_walk_list(node.arguments, ctx, visitors, node);
};

const standalone_walk_list = (nodes, ctx, visitors, node) => {
  nodes.forEach(item => standalone_walk(item, ctx, visitors, node));
};

const standalone_walkers = {
  TemplateLiteral: (node, ctx, visitors) => {
    standalone_walk_list(node.expressions, ctx, visitors, node);
    standalone_walk_list(node.quasis, ctx, visitors, node);
  },
  MemberExpression: (node, ctx, visitors) => {
    standalone_walk(node.object, ctx, visitors, node);
    standalone_walk(node.property, ctx, visitors, node);
  },
  CallExpression: standalone_walk_call,
  NewExpression: standalone_walk_call,
  ArrayExpression: (node, ctx, visitors) => {
    standalone_walk_list(node.elements, ctx, visitors, node);
  },
  AssignmentExpression: standalone_walk_binary,
  AwaitExpression: standalone_unary,
  BinaryExpression: standalone_walk_binary,
  LogicalExpression: standalone_walk_binary,
  UnaryExpression: standalone_unary,
  UpdateExpression: standalone_unary,
  ConditionalExpression: standalone_ternary,
  ObjectExpression: (node, ctx, visitors) => {
    standalone_walk_list(node.properties, ctx, visitors, node);
  },
  Property: (node, ctx, visitors) => {
    standalone_walk(node.key, ctx, visitors, node);
    standalone_walk(node.value, ctx, visitors, node);
  },

  ArrowFunctionExpression: standalone_walk_func,
  FunctionExpression: standalone_walk_func,
  FunctionDeclaration: standalone_walk_func,

  VariableDeclaration: (node, ctx, visitors) => {
    standalone_walk_list(node.declarations, ctx, visitors, node);
  },
  VariableDeclarator: (node, ctx, visitors) => {
    standalone_walk(node.id, ctx, visitors, node);
    standalone_walk(node.init, ctx, visitors, node);
  },
  SpreadElement: (node, ctx, visitors) => {
    standalone_walk(node.argument, ctx, visitors, node);
  },

  BlockStatement: (node, ctx, visitors) => {
    standalone_walk_list(node.body, ctx, visitors, node);
  },
  ExpressionStatement: (node, ctx, visitors) => {
    standalone_walk(node.expression, ctx, visitors, node);
  },
  IfStatement: standalone_ternary,
  ForStatement: (node, ctx, visitors) => {
    standalone_walk(node.init, ctx, visitors, node);
    standalone_walk(node.test, ctx, visitors, node);
    standalone_walk(node.update, ctx, visitors, node);
    standalone_walk(node.body, ctx, visitors, node);
  },
  WhileStatement: (node, ctx, visitors) => {
    standalone_walk(node.test, ctx, visitors, node);
    standalone_walk(node.body, ctx, visitors, node);
  },
  DoWhileStatement: (node, ctx, visitors) => {
    standalone_walk(node.body, ctx, visitors, node);
    standalone_walk(node.test, ctx, visitors, node);
  },
  SwitchStatement: (node, ctx, visitors) => {
    standalone_walk(node.discriminant, ctx, visitors, node);
    standalone_walk_list(node.cases, ctx, visitors, node);
  },
  SwitchCase: (node, ctx, visitors) => {
    if (node.test) standalone_walk(node.test, ctx, visitors, node);
    standalone_walk_list(node.consequent, ctx, visitors, node);
  },
  ReturnStatement: standalone_unary,

  Program: (node, ctx, visitors) => {
    standalone_walk(node.body[0], ctx, visitors, node);
  }
};
;// ../../node_modules/arquero/src/expression/ast/clean.js


function standalone_strip(node) {
  delete node.start;
  delete node.end;
  delete node.optional;
}

function standalone_stripMember(node) {
  standalone_strip(node);
  delete node.object;
  delete node.property;
  delete node.computed;
  if (!node.table) delete node.table;
}

/* harmony default export */ function standalone_clean(ast) {
  standalone_walk(ast, null, {
    Column: standalone_stripMember,
    Constant: standalone_stripMember,
    Default: standalone_strip
  });
  return ast;
}
;// ../../node_modules/arquero/src/expression/ast/util.js


function standalone_is(type, node) {
  return node && node.type === type;
}

function standalone_isFunctionExpression(node) {
  return standalone_is(standalone_FunctionExpression, node)
    || standalone_is(standalone_ArrowFunctionExpression, node);
}
;// ../../node_modules/arquero/src/util/to-function.js


/* harmony default export */ function standalone_to_function(value) {
  return standalone_util_is_function(value) ? value : () => value;
}
;// ../../node_modules/arquero/src/expression/parse-escape.js





const standalone_ERROR_ESC_AGGRONLY = 'Escaped functions are not valid as rollup or pivot values.';

/* harmony default export */ function standalone_parse_escape(ctx, spec, params) {
  if (ctx.aggronly) standalone_util_error(standalone_ERROR_ESC_AGGRONLY);

  // generate escaped function invocation code
  const code = '(row,data)=>fn('
    + standalone_rowObjectCode(ctx.table.columnNames())
    + ',$)';

  return { escape: standalone_expression_compile.escape(code, standalone_to_function(spec.expr), params) };
}
;// ../../node_modules/acorn/dist/acorn.mjs
// This file was generated. Do not modify manually!
var standalone_astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];

// This file was generated. Do not modify manually!
var standalone_astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191];

// This file was generated. Do not modify manually!
var standalone_nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65";

// This file was generated. Do not modify manually!
var standalone_nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";

// These are a run-length and offset encoded representation of the
// >0xffff code points that are a valid part of identifiers. The
// offset starts at 0x10000, and each pair of numbers represents an
// offset to the next range, and then a size of the range.

// Reserved word lists for various dialects of the language

var standalone_reservedWords = {
  3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  5: "class enum extends super const export import",
  6: "enum",
  strict: "implements interface let package private protected public static yield",
  strictBind: "eval arguments"
};

// And the keywords

var standalone_ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";

var standalone_keywords$1 = {
  5: standalone_ecma5AndLessKeywords,
  "5module": standalone_ecma5AndLessKeywords + " export import",
  6: standalone_ecma5AndLessKeywords + " const class extends export import super"
};

var standalone_keywordRelationalOperator = /^in(stanceof)?$/;

// ## Character categories

var standalone_nonASCIIidentifierStart = new RegExp("[" + standalone_nonASCIIidentifierStartChars + "]");
var standalone_nonASCIIidentifier = new RegExp("[" + standalone_nonASCIIidentifierStartChars + standalone_nonASCIIidentifierChars + "]");

// This has a complexity linear to the value of the code. The
// assumption is that looking up astral identifier characters is
// rare.
function standalone_isInAstralSet(code, set) {
  var pos = 0x10000;
  for (var i = 0; i < set.length; i += 2) {
    pos += set[i];
    if (pos > code) { return false }
    pos += set[i + 1];
    if (pos >= code) { return true }
  }
  return false
}

// Test whether a given character code starts an identifier.

function standalone_acorn_isIdentifierStart(code, astral) {
  if (code < 65) { return code === 36 }
  if (code < 91) { return true }
  if (code < 97) { return code === 95 }
  if (code < 123) { return true }
  if (code <= 0xffff) { return code >= 0xaa && standalone_nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  if (astral === false) { return false }
  return standalone_isInAstralSet(code, standalone_astralIdentifierStartCodes)
}

// Test whether a given character is part of an identifier.

function standalone_isIdentifierChar(code, astral) {
  if (code < 48) { return code === 36 }
  if (code < 58) { return true }
  if (code < 65) { return false }
  if (code < 91) { return true }
  if (code < 97) { return code === 95 }
  if (code < 123) { return true }
  if (code <= 0xffff) { return code >= 0xaa && standalone_nonASCIIidentifier.test(String.fromCharCode(code)) }
  if (astral === false) { return false }
  return standalone_isInAstralSet(code, standalone_astralIdentifierStartCodes) || standalone_isInAstralSet(code, standalone_astralIdentifierCodes)
}

// ## Token types

// The assignment of fine-grained, information-carrying type objects
// allows the tokenizer to store the information it has about a
// token in a way that is very cheap for the parser to look up.

// All token type variables start with an underscore, to make them
// easy to recognize.

// The `beforeExpr` property is used to disambiguate between regular
// expressions and divisions. It is set on all token types that can
// be followed by an expression (thus, a slash after them would be a
// regular expression).
//
// The `startsExpr` property is used to check if the token ends a
// `yield` expression. It is set on all token types that either can
// directly start an expression (like a quotation mark) or can
// continue an expression (like the body of a string).
//
// `isLoop` marks a keyword as starting a loop, which is important
// to know when parsing a label, in order to allow or disallow
// continue jumps to that label.

var standalone_TokenType = function TokenType(label, conf) {
  if ( conf === void 0 ) conf = {};

  this.label = label;
  this.keyword = conf.keyword;
  this.beforeExpr = !!conf.beforeExpr;
  this.startsExpr = !!conf.startsExpr;
  this.isLoop = !!conf.isLoop;
  this.isAssign = !!conf.isAssign;
  this.prefix = !!conf.prefix;
  this.postfix = !!conf.postfix;
  this.binop = conf.binop || null;
  this.updateContext = null;
};

function standalone_binop(name, prec) {
  return new standalone_TokenType(name, {beforeExpr: true, binop: prec})
}
var standalone_beforeExpr = {beforeExpr: true}, standalone_startsExpr = {startsExpr: true};

// Map keyword names to token types.

var standalone_acorn_keywords = {};

// Succinct definitions of keyword token types
function standalone_kw(name, options) {
  if ( options === void 0 ) options = {};

  options.keyword = name;
  return standalone_acorn_keywords[name] = new standalone_TokenType(name, options)
}

var standalone_types$1 = {
  num: new standalone_TokenType("num", standalone_startsExpr),
  regexp: new standalone_TokenType("regexp", standalone_startsExpr),
  string: new standalone_TokenType("string", standalone_startsExpr),
  name: new standalone_TokenType("name", standalone_startsExpr),
  privateId: new standalone_TokenType("privateId", standalone_startsExpr),
  eof: new standalone_TokenType("eof"),

  // Punctuation token types.
  bracketL: new standalone_TokenType("[", {beforeExpr: true, startsExpr: true}),
  bracketR: new standalone_TokenType("]"),
  braceL: new standalone_TokenType("{", {beforeExpr: true, startsExpr: true}),
  braceR: new standalone_TokenType("}"),
  parenL: new standalone_TokenType("(", {beforeExpr: true, startsExpr: true}),
  parenR: new standalone_TokenType(")"),
  comma: new standalone_TokenType(",", standalone_beforeExpr),
  semi: new standalone_TokenType(";", standalone_beforeExpr),
  colon: new standalone_TokenType(":", standalone_beforeExpr),
  dot: new standalone_TokenType("."),
  question: new standalone_TokenType("?", standalone_beforeExpr),
  questionDot: new standalone_TokenType("?."),
  arrow: new standalone_TokenType("=>", standalone_beforeExpr),
  template: new standalone_TokenType("template"),
  invalidTemplate: new standalone_TokenType("invalidTemplate"),
  ellipsis: new standalone_TokenType("...", standalone_beforeExpr),
  backQuote: new standalone_TokenType("`", standalone_startsExpr),
  dollarBraceL: new standalone_TokenType("${", {beforeExpr: true, startsExpr: true}),

  // Operators. These carry several kinds of properties to help the
  // parser use them properly (the presence of these properties is
  // what categorizes them as operators).
  //
  // `binop`, when present, specifies that this operator is a binary
  // operator, and will refer to its precedence.
  //
  // `prefix` and `postfix` mark the operator as a prefix or postfix
  // unary operator.
  //
  // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  // binary operators with a very low precedence, that should result
  // in AssignmentExpression nodes.

  eq: new standalone_TokenType("=", {beforeExpr: true, isAssign: true}),
  assign: new standalone_TokenType("_=", {beforeExpr: true, isAssign: true}),
  incDec: new standalone_TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  prefix: new standalone_TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  logicalOR: standalone_binop("||", 1),
  logicalAND: standalone_binop("&&", 2),
  bitwiseOR: standalone_binop("|", 3),
  bitwiseXOR: standalone_binop("^", 4),
  bitwiseAND: standalone_binop("&", 5),
  equality: standalone_binop("==/!=/===/!==", 6),
  relational: standalone_binop("</>/<=/>=", 7),
  bitShift: standalone_binop("<</>>/>>>", 8),
  plusMin: new standalone_TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  modulo: standalone_binop("%", 10),
  star: standalone_binop("*", 10),
  slash: standalone_binop("/", 10),
  starstar: new standalone_TokenType("**", {beforeExpr: true}),
  coalesce: standalone_binop("??", 1),

  // Keyword token types.
  _break: standalone_kw("break"),
  _case: standalone_kw("case", standalone_beforeExpr),
  _catch: standalone_kw("catch"),
  _continue: standalone_kw("continue"),
  _debugger: standalone_kw("debugger"),
  _default: standalone_kw("default", standalone_beforeExpr),
  _do: standalone_kw("do", {isLoop: true, beforeExpr: true}),
  _else: standalone_kw("else", standalone_beforeExpr),
  _finally: standalone_kw("finally"),
  _for: standalone_kw("for", {isLoop: true}),
  _function: standalone_kw("function", standalone_startsExpr),
  _if: standalone_kw("if"),
  _return: standalone_kw("return", standalone_beforeExpr),
  _switch: standalone_kw("switch"),
  _throw: standalone_kw("throw", standalone_beforeExpr),
  _try: standalone_kw("try"),
  _var: standalone_kw("var"),
  _const: standalone_kw("const"),
  _while: standalone_kw("while", {isLoop: true}),
  _with: standalone_kw("with"),
  _new: standalone_kw("new", {beforeExpr: true, startsExpr: true}),
  _this: standalone_kw("this", standalone_startsExpr),
  _super: standalone_kw("super", standalone_startsExpr),
  _class: standalone_kw("class", standalone_startsExpr),
  _extends: standalone_kw("extends", standalone_beforeExpr),
  _export: standalone_kw("export"),
  _import: standalone_kw("import", standalone_startsExpr),
  _null: standalone_kw("null", standalone_startsExpr),
  _true: standalone_kw("true", standalone_startsExpr),
  _false: standalone_kw("false", standalone_startsExpr),
  _in: standalone_kw("in", {beforeExpr: true, binop: 7}),
  _instanceof: standalone_kw("instanceof", {beforeExpr: true, binop: 7}),
  _typeof: standalone_kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  _void: standalone_kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  _delete: standalone_kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
};

// Matches a whole line break (where CRLF is considered a single
// line break). Used to count lines.

var standalone_lineBreak = /\r\n?|\n|\u2028|\u2029/;
var standalone_lineBreakG = new RegExp(standalone_lineBreak.source, "g");

function standalone_isNewLine(code) {
  return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
}

function standalone_nextLineBreak(code, from, end) {
  if ( end === void 0 ) end = code.length;

  for (var i = from; i < end; i++) {
    var next = code.charCodeAt(i);
    if (standalone_isNewLine(next))
      { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  }
  return -1
}

var standalone_nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;

var standalone_skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;

var standalone_acorn_ref = Object.prototype;
var standalone_acorn_hasOwnProperty = standalone_acorn_ref.hasOwnProperty;
var standalone_acorn_toString = standalone_acorn_ref.toString;

var standalone_hasOwn = Object.hasOwn || (function (obj, propName) { return (
  standalone_acorn_hasOwnProperty.call(obj, propName)
); });

var standalone_acorn_isArray = Array.isArray || (function (obj) { return (
  standalone_acorn_toString.call(obj) === "[object Array]"
); });

var standalone_regexpCache = Object.create(null);

function standalone_wordsRegexp(words) {
  return standalone_regexpCache[words] || (standalone_regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"))
}

function standalone_codePointToString(code) {
  // UTF-16 Decoding
  if (code <= 0xFFFF) { return String.fromCharCode(code) }
  code -= 0x10000;
  return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
}

var standalone_loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;

// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.

var standalone_Position = function Position(line, col) {
  this.line = line;
  this.column = col;
};

standalone_Position.prototype.offset = function offset (n) {
  return new standalone_Position(this.line, this.column + n)
};

var standalone_SourceLocation = function SourceLocation(p, start, end) {
  this.start = start;
  this.end = end;
  if (p.sourceFile !== null) { this.source = p.sourceFile; }
};

// The `getLineInfo` function is mostly useful when the
// `locations` option is off (for performance reasons) and you
// want to find the line/column position for a given character
// offset. `input` should be the code string that the offset refers
// into.

function standalone_getLineInfo(input, offset) {
  for (var line = 1, cur = 0;;) {
    var nextBreak = standalone_nextLineBreak(input, cur, offset);
    if (nextBreak < 0) { return new standalone_Position(line, offset - cur) }
    ++line;
    cur = nextBreak;
  }
}

// A second argument must be given to configure the parser process.
// These options are recognized (only `ecmaVersion` is required):

var standalone_defaultOptions = {
  // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
  // (the latest version the library supports). This influences
  // support for strict mode, the set of reserved words, and support
  // for new syntax features.
  ecmaVersion: null,
  // `sourceType` indicates the mode the code should be parsed in.
  // Can be either `"script"` or `"module"`. This influences global
  // strict mode and parsing of `import` and `export` declarations.
  sourceType: "script",
  // `onInsertedSemicolon` can be a callback that will be called when
  // a semicolon is automatically inserted. It will be passed the
  // position of the inserted semicolon as an offset, and if
  // `locations` is enabled, it is given the location as a `{line,
  // column}` object as second argument.
  onInsertedSemicolon: null,
  // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  // trailing commas.
  onTrailingComma: null,
  // By default, reserved words are only enforced if ecmaVersion >= 5.
  // Set `allowReserved` to a boolean value to explicitly turn this on
  // an off. When this option has the value "never", reserved words
  // and keywords can also not be used as property names.
  allowReserved: null,
  // When enabled, a return at the top level is not considered an
  // error.
  allowReturnOutsideFunction: false,
  // When enabled, import/export statements are not constrained to
  // appearing at the top of the program, and an import.meta expression
  // in a script isn't considered an error.
  allowImportExportEverywhere: false,
  // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  // When enabled, await identifiers are allowed to appear at the top-level scope,
  // but they are still not allowed in non-async functions.
  allowAwaitOutsideFunction: null,
  // When enabled, super identifiers are not constrained to
  // appearing in methods and do not raise an error when they appear elsewhere.
  allowSuperOutsideMethod: null,
  // When enabled, hashbang directive in the beginning of file is
  // allowed and treated as a line comment. Enabled by default when
  // `ecmaVersion` >= 2023.
  allowHashBang: false,
  // By default, the parser will verify that private properties are
  // only used in places where they are valid and have been declared.
  // Set this to false to turn such checks off.
  checkPrivateFields: true,
  // When `locations` is on, `loc` properties holding objects with
  // `start` and `end` properties in `{line, column}` form (with
  // line being 1-based and column 0-based) will be attached to the
  // nodes.
  locations: false,
  // A function can be passed as `onToken` option, which will
  // cause Acorn to call that function with object in the same
  // format as tokens returned from `tokenizer().getToken()`. Note
  // that you are not allowed to call the parser from the
  // callback—that will corrupt its internal state.
  onToken: null,
  // A function can be passed as `onComment` option, which will
  // cause Acorn to call that function with `(block, text, start,
  // end)` parameters whenever a comment is skipped. `block` is a
  // boolean indicating whether this is a block (`/* */`) comment,
  // `text` is the content of the comment, and `start` and `end` are
  // character offsets that denote the start and end of the comment.
  // When the `locations` option is on, two more parameters are
  // passed, the full `{line, column}` locations of the start and
  // end of the comments. Note that you are not allowed to call the
  // parser from the callback—that will corrupt its internal state.
  // When this option has an array as value, objects representing the
  // comments are pushed to it.
  onComment: null,
  // Nodes have their start and end characters offsets recorded in
  // `start` and `end` properties (directly on the node, rather than
  // the `loc` object, which holds line/column data. To also add a
  // [semi-standardized][range] `range` property holding a `[start,
  // end]` array with the same numbers, set the `ranges` option to
  // `true`.
  //
  // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  ranges: false,
  // It is possible to parse multiple files into a single AST by
  // passing the tree produced by parsing the first file as
  // `program` option in subsequent parses. This will add the
  // toplevel forms of the parsed file to the `Program` (top) node
  // of an existing parse tree.
  program: null,
  // When `locations` is on, you can pass this to record the source
  // file in every node's `loc` object.
  sourceFile: null,
  // This value, if given, is stored in every node, whether
  // `locations` is on or off.
  directSourceFile: null,
  // When enabled, parenthesized expressions are represented by
  // (non-standard) ParenthesizedExpression nodes
  preserveParens: false
};

// Interpret and default an options object

var standalone_warnedAboutEcmaVersion = false;

function standalone_getOptions(opts) {
  var options = {};

  for (var opt in standalone_defaultOptions)
    { options[opt] = opts && standalone_hasOwn(opts, opt) ? opts[opt] : standalone_defaultOptions[opt]; }

  if (options.ecmaVersion === "latest") {
    options.ecmaVersion = 1e8;
  } else if (options.ecmaVersion == null) {
    if (!standalone_warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
      standalone_warnedAboutEcmaVersion = true;
      console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
    }
    options.ecmaVersion = 11;
  } else if (options.ecmaVersion >= 2015) {
    options.ecmaVersion -= 2009;
  }

  if (options.allowReserved == null)
    { options.allowReserved = options.ecmaVersion < 5; }

  if (!opts || opts.allowHashBang == null)
    { options.allowHashBang = options.ecmaVersion >= 14; }

  if (standalone_acorn_isArray(options.onToken)) {
    var tokens = options.onToken;
    options.onToken = function (token) { return tokens.push(token); };
  }
  if (standalone_acorn_isArray(options.onComment))
    { options.onComment = standalone_pushComment(options, options.onComment); }

  return options
}

function standalone_pushComment(options, array) {
  return function(block, text, start, end, startLoc, endLoc) {
    var comment = {
      type: block ? "Block" : "Line",
      value: text,
      start: start,
      end: end
    };
    if (options.locations)
      { comment.loc = new standalone_SourceLocation(this, startLoc, endLoc); }
    if (options.ranges)
      { comment.range = [start, end]; }
    array.push(comment);
  }
}

// Each scope gets a bitset that may contain these flags
var
    standalone_SCOPE_TOP = 1,
    standalone_SCOPE_FUNCTION = 2,
    standalone_SCOPE_ASYNC = 4,
    standalone_SCOPE_GENERATOR = 8,
    standalone_SCOPE_ARROW = 16,
    standalone_SCOPE_SIMPLE_CATCH = 32,
    standalone_SCOPE_SUPER = 64,
    standalone_SCOPE_DIRECT_SUPER = 128,
    standalone_SCOPE_CLASS_STATIC_BLOCK = 256,
    standalone_SCOPE_VAR = standalone_SCOPE_TOP | standalone_SCOPE_FUNCTION | standalone_SCOPE_CLASS_STATIC_BLOCK;

function standalone_functionFlags(async, generator) {
  return standalone_SCOPE_FUNCTION | (async ? standalone_SCOPE_ASYNC : 0) | (generator ? standalone_SCOPE_GENERATOR : 0)
}

// Used in checkLVal* and declareName to determine the type of a binding
var
    standalone_BIND_NONE = 0, // Not a binding
    standalone_BIND_VAR = 1, // Var-style binding
    standalone_BIND_LEXICAL = 2, // Let- or const-style binding
    standalone_BIND_FUNCTION = 3, // Function declaration
    standalone_BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
    standalone_BIND_OUTSIDE = 5; // Special case for function names as bound inside the function

var standalone_Parser = function Parser(options, input, startPos) {
  this.options = options = standalone_getOptions(options);
  this.sourceFile = options.sourceFile;
  this.keywords = standalone_wordsRegexp(standalone_keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  var reserved = "";
  if (options.allowReserved !== true) {
    reserved = standalone_reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
    if (options.sourceType === "module") { reserved += " await"; }
  }
  this.reservedWords = standalone_wordsRegexp(reserved);
  var reservedStrict = (reserved ? reserved + " " : "") + standalone_reservedWords.strict;
  this.reservedWordsStrict = standalone_wordsRegexp(reservedStrict);
  this.reservedWordsStrictBind = standalone_wordsRegexp(reservedStrict + " " + standalone_reservedWords.strictBind);
  this.input = String(input);

  // Used to signal to callers of `readWord1` whether the word
  // contained any escape sequences. This is needed because words with
  // escape sequences must not be interpreted as keywords.
  this.containsEsc = false;

  // Set up token state

  // The current position of the tokenizer in the input.
  if (startPos) {
    this.pos = startPos;
    this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
    this.curLine = this.input.slice(0, this.lineStart).split(standalone_lineBreak).length;
  } else {
    this.pos = this.lineStart = 0;
    this.curLine = 1;
  }

  // Properties of the current token:
  // Its type
  this.type = standalone_types$1.eof;
  // For tokens that include more information than their type, the value
  this.value = null;
  // Its start and end offset
  this.start = this.end = this.pos;
  // And, if locations are used, the {line, column} object
  // corresponding to those offsets
  this.startLoc = this.endLoc = this.curPosition();

  // Position information for the previous token
  this.lastTokEndLoc = this.lastTokStartLoc = null;
  this.lastTokStart = this.lastTokEnd = this.pos;

  // The context stack is used to superficially track syntactic
  // context to predict whether a regular expression is allowed in a
  // given position.
  this.context = this.initialContext();
  this.exprAllowed = true;

  // Figure out if it's a module code.
  this.inModule = options.sourceType === "module";
  this.strict = this.inModule || this.strictDirective(this.pos);

  // Used to signify the start of a potential arrow function
  this.potentialArrowAt = -1;
  this.potentialArrowInForAwait = false;

  // Positions to delayed-check that yield/await does not exist in default parameters.
  this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  // Labels in scope.
  this.labels = [];
  // Thus-far undefined exports.
  this.undefinedExports = Object.create(null);

  // If enabled, skip leading hashbang line.
  if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
    { this.skipLineComment(2); }

  // Scope tracking for duplicate variable names (see scope.js)
  this.scopeStack = [];
  this.enterScope(standalone_SCOPE_TOP);

  // For RegExp validation
  this.regexpState = null;

  // The stack of private names.
  // Each element has two properties: 'declared' and 'used'.
  // When it exited from the outermost class definition, all used private names must be declared.
  this.privateNameStack = [];
};

var standalone_prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };

standalone_Parser.prototype.parse = function parse () {
  var node = this.options.program || this.startNode();
  this.nextToken();
  return this.parseTopLevel(node)
};

standalone_prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & standalone_SCOPE_FUNCTION) > 0 };

standalone_prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & standalone_SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };

standalone_prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & standalone_SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };

standalone_prototypeAccessors.canAwait.get = function () {
  for (var i = this.scopeStack.length - 1; i >= 0; i--) {
    var scope = this.scopeStack[i];
    if (scope.inClassFieldInit || scope.flags & standalone_SCOPE_CLASS_STATIC_BLOCK) { return false }
    if (scope.flags & standalone_SCOPE_FUNCTION) { return (scope.flags & standalone_SCOPE_ASYNC) > 0 }
  }
  return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
};

standalone_prototypeAccessors.allowSuper.get = function () {
  var ref = this.currentThisScope();
    var flags = ref.flags;
    var inClassFieldInit = ref.inClassFieldInit;
  return (flags & standalone_SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
};

standalone_prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & standalone_SCOPE_DIRECT_SUPER) > 0 };

standalone_prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };

standalone_prototypeAccessors.allowNewDotTarget.get = function () {
  var ref = this.currentThisScope();
    var flags = ref.flags;
    var inClassFieldInit = ref.inClassFieldInit;
  return (flags & (standalone_SCOPE_FUNCTION | standalone_SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
};

standalone_prototypeAccessors.inClassStaticBlock.get = function () {
  return (this.currentVarScope().flags & standalone_SCOPE_CLASS_STATIC_BLOCK) > 0
};

standalone_Parser.extend = function extend () {
    var plugins = [], len = arguments.length;
    while ( len-- ) plugins[ len ] = arguments[ len ];

  var cls = this;
  for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  return cls
};

standalone_Parser.parse = function parse (input, options) {
  return new this(options, input).parse()
};

standalone_Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  var parser = new this(options, input, pos);
  parser.nextToken();
  return parser.parseExpression()
};

standalone_Parser.tokenizer = function tokenizer (input, options) {
  return new this(options, input)
};

Object.defineProperties( standalone_Parser.prototype, standalone_prototypeAccessors );

var standalone_pp$9 = standalone_Parser.prototype;

// ## Parser utilities

var standalone_literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;
standalone_pp$9.strictDirective = function(start) {
  if (this.options.ecmaVersion < 5) { return false }
  for (;;) {
    // Try to find string literal.
    standalone_skipWhiteSpace.lastIndex = start;
    start += standalone_skipWhiteSpace.exec(this.input)[0].length;
    var match = standalone_literal.exec(this.input.slice(start));
    if (!match) { return false }
    if ((match[1] || match[2]) === "use strict") {
      standalone_skipWhiteSpace.lastIndex = start + match[0].length;
      var spaceAfter = standalone_skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
      var next = this.input.charAt(end);
      return next === ";" || next === "}" ||
        (standalone_lineBreak.test(spaceAfter[0]) &&
         !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
    }
    start += match[0].length;

    // Skip semicolon, if any.
    standalone_skipWhiteSpace.lastIndex = start;
    start += standalone_skipWhiteSpace.exec(this.input)[0].length;
    if (this.input[start] === ";")
      { start++; }
  }
};

// Predicate that tests whether the next token is of the given
// type, and if yes, consumes it as a side effect.

standalone_pp$9.eat = function(type) {
  if (this.type === type) {
    this.next();
    return true
  } else {
    return false
  }
};

// Tests whether parsed token is a contextual keyword.

standalone_pp$9.isContextual = function(name) {
  return this.type === standalone_types$1.name && this.value === name && !this.containsEsc
};

// Consumes contextual keyword if possible.

standalone_pp$9.eatContextual = function(name) {
  if (!this.isContextual(name)) { return false }
  this.next();
  return true
};

// Asserts that following token is given contextual keyword.

standalone_pp$9.expectContextual = function(name) {
  if (!this.eatContextual(name)) { this.unexpected(); }
};

// Test whether a semicolon can be inserted at the current position.

standalone_pp$9.canInsertSemicolon = function() {
  return this.type === standalone_types$1.eof ||
    this.type === standalone_types$1.braceR ||
    standalone_lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
};

standalone_pp$9.insertSemicolon = function() {
  if (this.canInsertSemicolon()) {
    if (this.options.onInsertedSemicolon)
      { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
    return true
  }
};

// Consume a semicolon, or, failing that, see if we are allowed to
// pretend that there is a semicolon at this position.

standalone_pp$9.semicolon = function() {
  if (!this.eat(standalone_types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
};

standalone_pp$9.afterTrailingComma = function(tokType, notNext) {
  if (this.type === tokType) {
    if (this.options.onTrailingComma)
      { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
    if (!notNext)
      { this.next(); }
    return true
  }
};

// Expect a token of a given type. If found, consume it, otherwise,
// raise an unexpected token error.

standalone_pp$9.expect = function(type) {
  this.eat(type) || this.unexpected();
};

// Raise an unexpected token error.

standalone_pp$9.unexpected = function(pos) {
  this.raise(pos != null ? pos : this.start, "Unexpected token");
};

var standalone_DestructuringErrors = function DestructuringErrors() {
  this.shorthandAssign =
  this.trailingComma =
  this.parenthesizedAssign =
  this.parenthesizedBind =
  this.doubleProto =
    -1;
};

standalone_pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  if (!refDestructuringErrors) { return }
  if (refDestructuringErrors.trailingComma > -1)
    { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
};

standalone_pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  if (!refDestructuringErrors) { return false }
  var shorthandAssign = refDestructuringErrors.shorthandAssign;
  var doubleProto = refDestructuringErrors.doubleProto;
  if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  if (shorthandAssign >= 0)
    { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  if (doubleProto >= 0)
    { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
};

standalone_pp$9.checkYieldAwaitInDefaultParams = function() {
  if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
    { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  if (this.awaitPos)
    { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
};

standalone_pp$9.isSimpleAssignTarget = function(expr) {
  if (expr.type === "ParenthesizedExpression")
    { return this.isSimpleAssignTarget(expr.expression) }
  return expr.type === "Identifier" || expr.type === "MemberExpression"
};

var standalone_pp$8 = standalone_Parser.prototype;

// ### Statement parsing

// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node.  Optionally takes a
// `program` argument.  If present, the statements will be appended
// to its body instead of creating a new node.

standalone_pp$8.parseTopLevel = function(node) {
  var exports = Object.create(null);
  if (!node.body) { node.body = []; }
  while (this.type !== standalone_types$1.eof) {
    var stmt = this.parseStatement(null, true, exports);
    node.body.push(stmt);
  }
  if (this.inModule)
    { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
      {
        var name = list[i];

        this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
      } }
  this.adaptDirectivePrologue(node.body);
  this.next();
  node.sourceType = this.options.sourceType;
  return this.finishNode(node, "Program")
};

var standalone_loopLabel = {kind: "loop"}, standalone_switchLabel = {kind: "switch"};

standalone_pp$8.isLet = function(context) {
  if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  standalone_skipWhiteSpace.lastIndex = this.pos;
  var skip = standalone_skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  // For ambiguous cases, determine if a LexicalDeclaration (or only a
  // Statement) is allowed here. If context is not empty then only a Statement
  // is allowed. However, `let [` is an explicit negative lookahead for
  // ExpressionStatement, so special-case it first.
  if (nextCh === 91 || nextCh === 92) { return true } // '[', '\'
  if (context) { return false }

  if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral
  if (standalone_acorn_isIdentifierStart(nextCh, true)) {
    var pos = next + 1;
    while (standalone_isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
    if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
    var ident = this.input.slice(next, pos);
    if (!standalone_keywordRelationalOperator.test(ident)) { return true }
  }
  return false
};

// check 'async [no LineTerminator here] function'
// - 'async /*foo*/ function' is OK.
// - 'async /*\n*/ function' is invalid.
standalone_pp$8.isAsyncFunction = function() {
  if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
    { return false }

  standalone_skipWhiteSpace.lastIndex = this.pos;
  var skip = standalone_skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length, after;
  return !standalone_lineBreak.test(this.input.slice(this.pos, next)) &&
    this.input.slice(next, next + 8) === "function" &&
    (next + 8 === this.input.length ||
     !(standalone_isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
};

// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.

standalone_pp$8.parseStatement = function(context, topLevel, exports) {
  var starttype = this.type, node = this.startNode(), kind;

  if (this.isLet(context)) {
    starttype = standalone_types$1._var;
    kind = "let";
  }

  // Most types of statements are recognized by the keyword they
  // start with. Many are trivial to parse, some require a bit of
  // complexity.

  switch (starttype) {
  case standalone_types$1._break: case standalone_types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  case standalone_types$1._debugger: return this.parseDebuggerStatement(node)
  case standalone_types$1._do: return this.parseDoStatement(node)
  case standalone_types$1._for: return this.parseForStatement(node)
  case standalone_types$1._function:
    // Function as sole body of either an if statement or a labeled statement
    // works, but not when it is part of a labeled statement that is the sole
    // body of an if statement.
    if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
    return this.parseFunctionStatement(node, false, !context)
  case standalone_types$1._class:
    if (context) { this.unexpected(); }
    return this.parseClass(node, true)
  case standalone_types$1._if: return this.parseIfStatement(node)
  case standalone_types$1._return: return this.parseReturnStatement(node)
  case standalone_types$1._switch: return this.parseSwitchStatement(node)
  case standalone_types$1._throw: return this.parseThrowStatement(node)
  case standalone_types$1._try: return this.parseTryStatement(node)
  case standalone_types$1._const: case standalone_types$1._var:
    kind = kind || this.value;
    if (context && kind !== "var") { this.unexpected(); }
    return this.parseVarStatement(node, kind)
  case standalone_types$1._while: return this.parseWhileStatement(node)
  case standalone_types$1._with: return this.parseWithStatement(node)
  case standalone_types$1.braceL: return this.parseBlock(true, node)
  case standalone_types$1.semi: return this.parseEmptyStatement(node)
  case standalone_types$1._export:
  case standalone_types$1._import:
    if (this.options.ecmaVersion > 10 && starttype === standalone_types$1._import) {
      standalone_skipWhiteSpace.lastIndex = this.pos;
      var skip = standalone_skipWhiteSpace.exec(this.input);
      var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
      if (nextCh === 40 || nextCh === 46) // '(' or '.'
        { return this.parseExpressionStatement(node, this.parseExpression()) }
    }

    if (!this.options.allowImportExportEverywhere) {
      if (!topLevel)
        { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
      if (!this.inModule)
        { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
    }
    return starttype === standalone_types$1._import ? this.parseImport(node) : this.parseExport(node, exports)

    // If the statement does not start with a statement keyword or a
    // brace, it's an ExpressionStatement or LabeledStatement. We
    // simply start parsing an expression, and afterwards, if the
    // next token is a colon and the expression was a simple
    // Identifier node, we switch to interpreting it as a label.
  default:
    if (this.isAsyncFunction()) {
      if (context) { this.unexpected(); }
      this.next();
      return this.parseFunctionStatement(node, true, !context)
    }

    var maybeName = this.value, expr = this.parseExpression();
    if (starttype === standalone_types$1.name && expr.type === "Identifier" && this.eat(standalone_types$1.colon))
      { return this.parseLabeledStatement(node, maybeName, expr, context) }
    else { return this.parseExpressionStatement(node, expr) }
  }
};

standalone_pp$8.parseBreakContinueStatement = function(node, keyword) {
  var isBreak = keyword === "break";
  this.next();
  if (this.eat(standalone_types$1.semi) || this.insertSemicolon()) { node.label = null; }
  else if (this.type !== standalone_types$1.name) { this.unexpected(); }
  else {
    node.label = this.parseIdent();
    this.semicolon();
  }

  // Verify that there is an actual destination to break or
  // continue to.
  var i = 0;
  for (; i < this.labels.length; ++i) {
    var lab = this.labels[i];
    if (node.label == null || lab.name === node.label.name) {
      if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
      if (node.label && isBreak) { break }
    }
  }
  if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
};

standalone_pp$8.parseDebuggerStatement = function(node) {
  this.next();
  this.semicolon();
  return this.finishNode(node, "DebuggerStatement")
};

standalone_pp$8.parseDoStatement = function(node) {
  this.next();
  this.labels.push(standalone_loopLabel);
  node.body = this.parseStatement("do");
  this.labels.pop();
  this.expect(standalone_types$1._while);
  node.test = this.parseParenExpression();
  if (this.options.ecmaVersion >= 6)
    { this.eat(standalone_types$1.semi); }
  else
    { this.semicolon(); }
  return this.finishNode(node, "DoWhileStatement")
};

// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.

standalone_pp$8.parseForStatement = function(node) {
  this.next();
  var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  this.labels.push(standalone_loopLabel);
  this.enterScope(0);
  this.expect(standalone_types$1.parenL);
  if (this.type === standalone_types$1.semi) {
    if (awaitAt > -1) { this.unexpected(awaitAt); }
    return this.parseFor(node, null)
  }
  var isLet = this.isLet();
  if (this.type === standalone_types$1._var || this.type === standalone_types$1._const || isLet) {
    var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
    this.next();
    this.parseVar(init$1, true, kind);
    this.finishNode(init$1, "VariableDeclaration");
    if ((this.type === standalone_types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
      if (this.options.ecmaVersion >= 9) {
        if (this.type === standalone_types$1._in) {
          if (awaitAt > -1) { this.unexpected(awaitAt); }
        } else { node.await = awaitAt > -1; }
      }
      return this.parseForIn(node, init$1)
    }
    if (awaitAt > -1) { this.unexpected(awaitAt); }
    return this.parseFor(node, init$1)
  }
  var startsWithLet = this.isContextual("let"), isForOf = false;
  var containsEsc = this.containsEsc;
  var refDestructuringErrors = new standalone_DestructuringErrors;
  var initPos = this.start;
  var init = awaitAt > -1
    ? this.parseExprSubscripts(refDestructuringErrors, "await")
    : this.parseExpression(true, refDestructuringErrors);
  if (this.type === standalone_types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
    if (awaitAt > -1) { // implies `ecmaVersion >= 9` (see declaration of awaitAt)
      if (this.type === standalone_types$1._in) { this.unexpected(awaitAt); }
      node.await = true;
    } else if (isForOf && this.options.ecmaVersion >= 8) {
      if (init.start === initPos && !containsEsc && init.type === "Identifier" && init.name === "async") { this.unexpected(); }
      else if (this.options.ecmaVersion >= 9) { node.await = false; }
    }
    if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
    this.toAssignable(init, false, refDestructuringErrors);
    this.checkLValPattern(init);
    return this.parseForIn(node, init)
  } else {
    this.checkExpressionErrors(refDestructuringErrors, true);
  }
  if (awaitAt > -1) { this.unexpected(awaitAt); }
  return this.parseFor(node, init)
};

standalone_pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  this.next();
  return this.parseFunction(node, standalone_FUNC_STATEMENT | (declarationPosition ? 0 : standalone_FUNC_HANGING_STATEMENT), false, isAsync)
};

standalone_pp$8.parseIfStatement = function(node) {
  this.next();
  node.test = this.parseParenExpression();
  // allow function declarations in branches, but only in non-strict mode
  node.consequent = this.parseStatement("if");
  node.alternate = this.eat(standalone_types$1._else) ? this.parseStatement("if") : null;
  return this.finishNode(node, "IfStatement")
};

standalone_pp$8.parseReturnStatement = function(node) {
  if (!this.inFunction && !this.options.allowReturnOutsideFunction)
    { this.raise(this.start, "'return' outside of function"); }
  this.next();

  // In `return` (and `break`/`continue`), the keywords with
  // optional arguments, we eagerly look for a semicolon or the
  // possibility to insert one.

  if (this.eat(standalone_types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  else { node.argument = this.parseExpression(); this.semicolon(); }
  return this.finishNode(node, "ReturnStatement")
};

standalone_pp$8.parseSwitchStatement = function(node) {
  this.next();
  node.discriminant = this.parseParenExpression();
  node.cases = [];
  this.expect(standalone_types$1.braceL);
  this.labels.push(standalone_switchLabel);
  this.enterScope(0);

  // Statements under must be grouped (by label) in SwitchCase
  // nodes. `cur` is used to keep the node that we are currently
  // adding statements to.

  var cur;
  for (var sawDefault = false; this.type !== standalone_types$1.braceR;) {
    if (this.type === standalone_types$1._case || this.type === standalone_types$1._default) {
      var isCase = this.type === standalone_types$1._case;
      if (cur) { this.finishNode(cur, "SwitchCase"); }
      node.cases.push(cur = this.startNode());
      cur.consequent = [];
      this.next();
      if (isCase) {
        cur.test = this.parseExpression();
      } else {
        if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
        sawDefault = true;
        cur.test = null;
      }
      this.expect(standalone_types$1.colon);
    } else {
      if (!cur) { this.unexpected(); }
      cur.consequent.push(this.parseStatement(null));
    }
  }
  this.exitScope();
  if (cur) { this.finishNode(cur, "SwitchCase"); }
  this.next(); // Closing brace
  this.labels.pop();
  return this.finishNode(node, "SwitchStatement")
};

standalone_pp$8.parseThrowStatement = function(node) {
  this.next();
  if (standalone_lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
    { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  node.argument = this.parseExpression();
  this.semicolon();
  return this.finishNode(node, "ThrowStatement")
};

// Reused empty array added for node fields that are always empty.

var standalone_empty$1 = [];

standalone_pp$8.parseCatchClauseParam = function() {
  var param = this.parseBindingAtom();
  var simple = param.type === "Identifier";
  this.enterScope(simple ? standalone_SCOPE_SIMPLE_CATCH : 0);
  this.checkLValPattern(param, simple ? standalone_BIND_SIMPLE_CATCH : standalone_BIND_LEXICAL);
  this.expect(standalone_types$1.parenR);

  return param
};

standalone_pp$8.parseTryStatement = function(node) {
  this.next();
  node.block = this.parseBlock();
  node.handler = null;
  if (this.type === standalone_types$1._catch) {
    var clause = this.startNode();
    this.next();
    if (this.eat(standalone_types$1.parenL)) {
      clause.param = this.parseCatchClauseParam();
    } else {
      if (this.options.ecmaVersion < 10) { this.unexpected(); }
      clause.param = null;
      this.enterScope(0);
    }
    clause.body = this.parseBlock(false);
    this.exitScope();
    node.handler = this.finishNode(clause, "CatchClause");
  }
  node.finalizer = this.eat(standalone_types$1._finally) ? this.parseBlock() : null;
  if (!node.handler && !node.finalizer)
    { this.raise(node.start, "Missing catch or finally clause"); }
  return this.finishNode(node, "TryStatement")
};

standalone_pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {
  this.next();
  this.parseVar(node, false, kind, allowMissingInitializer);
  this.semicolon();
  return this.finishNode(node, "VariableDeclaration")
};

standalone_pp$8.parseWhileStatement = function(node) {
  this.next();
  node.test = this.parseParenExpression();
  this.labels.push(standalone_loopLabel);
  node.body = this.parseStatement("while");
  this.labels.pop();
  return this.finishNode(node, "WhileStatement")
};

standalone_pp$8.parseWithStatement = function(node) {
  if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  this.next();
  node.object = this.parseParenExpression();
  node.body = this.parseStatement("with");
  return this.finishNode(node, "WithStatement")
};

standalone_pp$8.parseEmptyStatement = function(node) {
  this.next();
  return this.finishNode(node, "EmptyStatement")
};

standalone_pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
    {
    var label = list[i$1];

    if (label.name === maybeName)
      { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  } }
  var kind = this.type.isLoop ? "loop" : this.type === standalone_types$1._switch ? "switch" : null;
  for (var i = this.labels.length - 1; i >= 0; i--) {
    var label$1 = this.labels[i];
    if (label$1.statementStart === node.start) {
      // Update information about previous labels on this node
      label$1.statementStart = this.start;
      label$1.kind = kind;
    } else { break }
  }
  this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  this.labels.pop();
  node.label = expr;
  return this.finishNode(node, "LabeledStatement")
};

standalone_pp$8.parseExpressionStatement = function(node, expr) {
  node.expression = expr;
  this.semicolon();
  return this.finishNode(node, "ExpressionStatement")
};

// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).

standalone_pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  if ( node === void 0 ) node = this.startNode();

  node.body = [];
  this.expect(standalone_types$1.braceL);
  if (createNewLexicalScope) { this.enterScope(0); }
  while (this.type !== standalone_types$1.braceR) {
    var stmt = this.parseStatement(null);
    node.body.push(stmt);
  }
  if (exitStrict) { this.strict = false; }
  this.next();
  if (createNewLexicalScope) { this.exitScope(); }
  return this.finishNode(node, "BlockStatement")
};

// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.

standalone_pp$8.parseFor = function(node, init) {
  node.init = init;
  this.expect(standalone_types$1.semi);
  node.test = this.type === standalone_types$1.semi ? null : this.parseExpression();
  this.expect(standalone_types$1.semi);
  node.update = this.type === standalone_types$1.parenR ? null : this.parseExpression();
  this.expect(standalone_types$1.parenR);
  node.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node, "ForStatement")
};

// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.

standalone_pp$8.parseForIn = function(node, init) {
  var isForIn = this.type === standalone_types$1._in;
  this.next();

  if (
    init.type === "VariableDeclaration" &&
    init.declarations[0].init != null &&
    (
      !isForIn ||
      this.options.ecmaVersion < 8 ||
      this.strict ||
      init.kind !== "var" ||
      init.declarations[0].id.type !== "Identifier"
    )
  ) {
    this.raise(
      init.start,
      ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
    );
  }
  node.left = init;
  node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  this.expect(standalone_types$1.parenR);
  node.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
};

// Parse a list of variable declarations.

standalone_pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {
  node.declarations = [];
  node.kind = kind;
  for (;;) {
    var decl = this.startNode();
    this.parseVarId(decl, kind);
    if (this.eat(standalone_types$1.eq)) {
      decl.init = this.parseMaybeAssign(isFor);
    } else if (!allowMissingInitializer && kind === "const" && !(this.type === standalone_types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
      this.unexpected();
    } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === standalone_types$1._in || this.isContextual("of")))) {
      this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
    } else {
      decl.init = null;
    }
    node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
    if (!this.eat(standalone_types$1.comma)) { break }
  }
  return node
};

standalone_pp$8.parseVarId = function(decl, kind) {
  decl.id = this.parseBindingAtom();
  this.checkLValPattern(decl.id, kind === "var" ? standalone_BIND_VAR : standalone_BIND_LEXICAL, false);
};

var standalone_FUNC_STATEMENT = 1, standalone_FUNC_HANGING_STATEMENT = 2, standalone_FUNC_NULLABLE_ID = 4;

// Parse a function declaration or literal (depending on the
// `statement & FUNC_STATEMENT`).

// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
standalone_pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  this.initFunction(node);
  if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
    if (this.type === standalone_types$1.star && (statement & standalone_FUNC_HANGING_STATEMENT))
      { this.unexpected(); }
    node.generator = this.eat(standalone_types$1.star);
  }
  if (this.options.ecmaVersion >= 8)
    { node.async = !!isAsync; }

  if (statement & standalone_FUNC_STATEMENT) {
    node.id = (statement & standalone_FUNC_NULLABLE_ID) && this.type !== standalone_types$1.name ? null : this.parseIdent();
    if (node.id && !(statement & standalone_FUNC_HANGING_STATEMENT))
      // If it is a regular function declaration in sloppy mode, then it is
      // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
      // mode depends on properties of the current scope (see
      // treatFunctionsAsVar).
      { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? standalone_BIND_VAR : standalone_BIND_LEXICAL : standalone_BIND_FUNCTION); }
  }

  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(standalone_functionFlags(node.async, node.generator));

  if (!(statement & standalone_FUNC_STATEMENT))
    { node.id = this.type === standalone_types$1.name ? this.parseIdent() : null; }

  this.parseFunctionParams(node);
  this.parseFunctionBody(node, allowExpressionBody, false, forInit);

  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, (statement & standalone_FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
};

standalone_pp$8.parseFunctionParams = function(node) {
  this.expect(standalone_types$1.parenL);
  node.params = this.parseBindingList(standalone_types$1.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
};

// Parse a class declaration or literal (depending on the
// `isStatement` parameter).

standalone_pp$8.parseClass = function(node, isStatement) {
  this.next();

  // ecma-262 14.6 Class Definitions
  // A class definition is always strict mode code.
  var oldStrict = this.strict;
  this.strict = true;

  this.parseClassId(node, isStatement);
  this.parseClassSuper(node);
  var privateNameMap = this.enterClassBody();
  var classBody = this.startNode();
  var hadConstructor = false;
  classBody.body = [];
  this.expect(standalone_types$1.braceL);
  while (this.type !== standalone_types$1.braceR) {
    var element = this.parseClassElement(node.superClass !== null);
    if (element) {
      classBody.body.push(element);
      if (element.type === "MethodDefinition" && element.kind === "constructor") {
        if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); }
        hadConstructor = true;
      } else if (element.key && element.key.type === "PrivateIdentifier" && standalone_isPrivateNameConflicted(privateNameMap, element)) {
        this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
      }
    }
  }
  this.strict = oldStrict;
  this.next();
  node.body = this.finishNode(classBody, "ClassBody");
  this.exitClassBody();
  return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
};

standalone_pp$8.parseClassElement = function(constructorAllowsSuper) {
  if (this.eat(standalone_types$1.semi)) { return null }

  var ecmaVersion = this.options.ecmaVersion;
  var node = this.startNode();
  var keyName = "";
  var isGenerator = false;
  var isAsync = false;
  var kind = "method";
  var isStatic = false;

  if (this.eatContextual("static")) {
    // Parse static init block
    if (ecmaVersion >= 13 && this.eat(standalone_types$1.braceL)) {
      this.parseClassStaticBlock(node);
      return node
    }
    if (this.isClassElementNameStart() || this.type === standalone_types$1.star) {
      isStatic = true;
    } else {
      keyName = "static";
    }
  }
  node.static = isStatic;
  if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
    if ((this.isClassElementNameStart() || this.type === standalone_types$1.star) && !this.canInsertSemicolon()) {
      isAsync = true;
    } else {
      keyName = "async";
    }
  }
  if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(standalone_types$1.star)) {
    isGenerator = true;
  }
  if (!keyName && !isAsync && !isGenerator) {
    var lastValue = this.value;
    if (this.eatContextual("get") || this.eatContextual("set")) {
      if (this.isClassElementNameStart()) {
        kind = lastValue;
      } else {
        keyName = lastValue;
      }
    }
  }

  // Parse element name
  if (keyName) {
    // 'async', 'get', 'set', or 'static' were not a keyword contextually.
    // The last token is any of those. Make it the element name.
    node.computed = false;
    node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
    node.key.name = keyName;
    this.finishNode(node.key, "Identifier");
  } else {
    this.parseClassElementName(node);
  }

  // Parse element value
  if (ecmaVersion < 13 || this.type === standalone_types$1.parenL || kind !== "method" || isGenerator || isAsync) {
    var isConstructor = !node.static && standalone_checkKeyName(node, "constructor");
    var allowsDirectSuper = isConstructor && constructorAllowsSuper;
    // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
    if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
    node.kind = isConstructor ? "constructor" : kind;
    this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  } else {
    this.parseClassField(node);
  }

  return node
};

standalone_pp$8.isClassElementNameStart = function() {
  return (
    this.type === standalone_types$1.name ||
    this.type === standalone_types$1.privateId ||
    this.type === standalone_types$1.num ||
    this.type === standalone_types$1.string ||
    this.type === standalone_types$1.bracketL ||
    this.type.keyword
  )
};

standalone_pp$8.parseClassElementName = function(element) {
  if (this.type === standalone_types$1.privateId) {
    if (this.value === "constructor") {
      this.raise(this.start, "Classes can't have an element named '#constructor'");
    }
    element.computed = false;
    element.key = this.parsePrivateIdent();
  } else {
    this.parsePropertyName(element);
  }
};

standalone_pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  // Check key and flags
  var key = method.key;
  if (method.kind === "constructor") {
    if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
    if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  } else if (method.static && standalone_checkKeyName(method, "prototype")) {
    this.raise(key.start, "Classes may not have a static property named prototype");
  }

  // Parse value
  var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);

  // Check value
  if (method.kind === "get" && value.params.length !== 0)
    { this.raiseRecoverable(value.start, "getter should have no params"); }
  if (method.kind === "set" && value.params.length !== 1)
    { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  if (method.kind === "set" && value.params[0].type === "RestElement")
    { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }

  return this.finishNode(method, "MethodDefinition")
};

standalone_pp$8.parseClassField = function(field) {
  if (standalone_checkKeyName(field, "constructor")) {
    this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  } else if (field.static && standalone_checkKeyName(field, "prototype")) {
    this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  }

  if (this.eat(standalone_types$1.eq)) {
    // To raise SyntaxError if 'arguments' exists in the initializer.
    var scope = this.currentThisScope();
    var inClassFieldInit = scope.inClassFieldInit;
    scope.inClassFieldInit = true;
    field.value = this.parseMaybeAssign();
    scope.inClassFieldInit = inClassFieldInit;
  } else {
    field.value = null;
  }
  this.semicolon();

  return this.finishNode(field, "PropertyDefinition")
};

standalone_pp$8.parseClassStaticBlock = function(node) {
  node.body = [];

  var oldLabels = this.labels;
  this.labels = [];
  this.enterScope(standalone_SCOPE_CLASS_STATIC_BLOCK | standalone_SCOPE_SUPER);
  while (this.type !== standalone_types$1.braceR) {
    var stmt = this.parseStatement(null);
    node.body.push(stmt);
  }
  this.next();
  this.exitScope();
  this.labels = oldLabels;

  return this.finishNode(node, "StaticBlock")
};

standalone_pp$8.parseClassId = function(node, isStatement) {
  if (this.type === standalone_types$1.name) {
    node.id = this.parseIdent();
    if (isStatement)
      { this.checkLValSimple(node.id, standalone_BIND_LEXICAL, false); }
  } else {
    if (isStatement === true)
      { this.unexpected(); }
    node.id = null;
  }
};

standalone_pp$8.parseClassSuper = function(node) {
  node.superClass = this.eat(standalone_types$1._extends) ? this.parseExprSubscripts(null, false) : null;
};

standalone_pp$8.enterClassBody = function() {
  var element = {declared: Object.create(null), used: []};
  this.privateNameStack.push(element);
  return element.declared
};

standalone_pp$8.exitClassBody = function() {
  var ref = this.privateNameStack.pop();
  var declared = ref.declared;
  var used = ref.used;
  if (!this.options.checkPrivateFields) { return }
  var len = this.privateNameStack.length;
  var parent = len === 0 ? null : this.privateNameStack[len - 1];
  for (var i = 0; i < used.length; ++i) {
    var id = used[i];
    if (!standalone_hasOwn(declared, id.name)) {
      if (parent) {
        parent.used.push(id);
      } else {
        this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
      }
    }
  }
};

function standalone_isPrivateNameConflicted(privateNameMap, element) {
  var name = element.key.name;
  var curr = privateNameMap[name];

  var next = "true";
  if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
    next = (element.static ? "s" : "i") + element.kind;
  }

  // `class { get #a(){}; static set #a(_){} }` is also conflict.
  if (
    curr === "iget" && next === "iset" ||
    curr === "iset" && next === "iget" ||
    curr === "sget" && next === "sset" ||
    curr === "sset" && next === "sget"
  ) {
    privateNameMap[name] = "true";
    return false
  } else if (!curr) {
    privateNameMap[name] = next;
    return false
  } else {
    return true
  }
}

function standalone_checkKeyName(node, name) {
  var computed = node.computed;
  var key = node.key;
  return !computed && (
    key.type === "Identifier" && key.name === name ||
    key.type === "Literal" && key.value === name
  )
}

// Parses module export declaration.

standalone_pp$8.parseExportAllDeclaration = function(node, exports) {
  if (this.options.ecmaVersion >= 11) {
    if (this.eatContextual("as")) {
      node.exported = this.parseModuleExportName();
      this.checkExport(exports, node.exported, this.lastTokStart);
    } else {
      node.exported = null;
    }
  }
  this.expectContextual("from");
  if (this.type !== standalone_types$1.string) { this.unexpected(); }
  node.source = this.parseExprAtom();
  if (this.options.ecmaVersion >= 16)
    { node.attributes = this.parseWithClause(); }
  this.semicolon();
  return this.finishNode(node, "ExportAllDeclaration")
};

standalone_pp$8.parseExport = function(node, exports) {
  this.next();
  // export * from '...'
  if (this.eat(standalone_types$1.star)) {
    return this.parseExportAllDeclaration(node, exports)
  }
  if (this.eat(standalone_types$1._default)) { // export default ...
    this.checkExport(exports, "default", this.lastTokStart);
    node.declaration = this.parseExportDefaultDeclaration();
    return this.finishNode(node, "ExportDefaultDeclaration")
  }
  // export var|const|let|function|class ...
  if (this.shouldParseExportStatement()) {
    node.declaration = this.parseExportDeclaration(node);
    if (node.declaration.type === "VariableDeclaration")
      { this.checkVariableExport(exports, node.declaration.declarations); }
    else
      { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
    node.specifiers = [];
    node.source = null;
  } else { // export { x, y as z } [from '...']
    node.declaration = null;
    node.specifiers = this.parseExportSpecifiers(exports);
    if (this.eatContextual("from")) {
      if (this.type !== standalone_types$1.string) { this.unexpected(); }
      node.source = this.parseExprAtom();
      if (this.options.ecmaVersion >= 16)
        { node.attributes = this.parseWithClause(); }
    } else {
      for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
        // check for keywords used as local names
        var spec = list[i];

        this.checkUnreserved(spec.local);
        // check if export is defined
        this.checkLocalExport(spec.local);

        if (spec.local.type === "Literal") {
          this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
        }
      }

      node.source = null;
    }
    this.semicolon();
  }
  return this.finishNode(node, "ExportNamedDeclaration")
};

standalone_pp$8.parseExportDeclaration = function(node) {
  return this.parseStatement(null)
};

standalone_pp$8.parseExportDefaultDeclaration = function() {
  var isAsync;
  if (this.type === standalone_types$1._function || (isAsync = this.isAsyncFunction())) {
    var fNode = this.startNode();
    this.next();
    if (isAsync) { this.next(); }
    return this.parseFunction(fNode, standalone_FUNC_STATEMENT | standalone_FUNC_NULLABLE_ID, false, isAsync)
  } else if (this.type === standalone_types$1._class) {
    var cNode = this.startNode();
    return this.parseClass(cNode, "nullableID")
  } else {
    var declaration = this.parseMaybeAssign();
    this.semicolon();
    return declaration
  }
};

standalone_pp$8.checkExport = function(exports, name, pos) {
  if (!exports) { return }
  if (typeof name !== "string")
    { name = name.type === "Identifier" ? name.name : name.value; }
  if (standalone_hasOwn(exports, name))
    { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  exports[name] = true;
};

standalone_pp$8.checkPatternExport = function(exports, pat) {
  var type = pat.type;
  if (type === "Identifier")
    { this.checkExport(exports, pat, pat.start); }
  else if (type === "ObjectPattern")
    { for (var i = 0, list = pat.properties; i < list.length; i += 1)
      {
        var prop = list[i];

        this.checkPatternExport(exports, prop);
      } }
  else if (type === "ArrayPattern")
    { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
      var elt = list$1[i$1];

        if (elt) { this.checkPatternExport(exports, elt); }
    } }
  else if (type === "Property")
    { this.checkPatternExport(exports, pat.value); }
  else if (type === "AssignmentPattern")
    { this.checkPatternExport(exports, pat.left); }
  else if (type === "RestElement")
    { this.checkPatternExport(exports, pat.argument); }
};

standalone_pp$8.checkVariableExport = function(exports, decls) {
  if (!exports) { return }
  for (var i = 0, list = decls; i < list.length; i += 1)
    {
    var decl = list[i];

    this.checkPatternExport(exports, decl.id);
  }
};

standalone_pp$8.shouldParseExportStatement = function() {
  return this.type.keyword === "var" ||
    this.type.keyword === "const" ||
    this.type.keyword === "class" ||
    this.type.keyword === "function" ||
    this.isLet() ||
    this.isAsyncFunction()
};

// Parses a comma-separated list of module exports.

standalone_pp$8.parseExportSpecifier = function(exports) {
  var node = this.startNode();
  node.local = this.parseModuleExportName();

  node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  this.checkExport(
    exports,
    node.exported,
    node.exported.start
  );

  return this.finishNode(node, "ExportSpecifier")
};

standalone_pp$8.parseExportSpecifiers = function(exports) {
  var nodes = [], first = true;
  // export { x, y as z } [from '...']
  this.expect(standalone_types$1.braceL);
  while (!this.eat(standalone_types$1.braceR)) {
    if (!first) {
      this.expect(standalone_types$1.comma);
      if (this.afterTrailingComma(standalone_types$1.braceR)) { break }
    } else { first = false; }

    nodes.push(this.parseExportSpecifier(exports));
  }
  return nodes
};

// Parses import declaration.

standalone_pp$8.parseImport = function(node) {
  this.next();

  // import '...'
  if (this.type === standalone_types$1.string) {
    node.specifiers = standalone_empty$1;
    node.source = this.parseExprAtom();
  } else {
    node.specifiers = this.parseImportSpecifiers();
    this.expectContextual("from");
    node.source = this.type === standalone_types$1.string ? this.parseExprAtom() : this.unexpected();
  }
  if (this.options.ecmaVersion >= 16)
    { node.attributes = this.parseWithClause(); }
  this.semicolon();
  return this.finishNode(node, "ImportDeclaration")
};

// Parses a comma-separated list of module imports.

standalone_pp$8.parseImportSpecifier = function() {
  var node = this.startNode();
  node.imported = this.parseModuleExportName();

  if (this.eatContextual("as")) {
    node.local = this.parseIdent();
  } else {
    this.checkUnreserved(node.imported);
    node.local = node.imported;
  }
  this.checkLValSimple(node.local, standalone_BIND_LEXICAL);

  return this.finishNode(node, "ImportSpecifier")
};

standalone_pp$8.parseImportDefaultSpecifier = function() {
  // import defaultObj, { x, y as z } from '...'
  var node = this.startNode();
  node.local = this.parseIdent();
  this.checkLValSimple(node.local, standalone_BIND_LEXICAL);
  return this.finishNode(node, "ImportDefaultSpecifier")
};

standalone_pp$8.parseImportNamespaceSpecifier = function() {
  var node = this.startNode();
  this.next();
  this.expectContextual("as");
  node.local = this.parseIdent();
  this.checkLValSimple(node.local, standalone_BIND_LEXICAL);
  return this.finishNode(node, "ImportNamespaceSpecifier")
};

standalone_pp$8.parseImportSpecifiers = function() {
  var nodes = [], first = true;
  if (this.type === standalone_types$1.name) {
    nodes.push(this.parseImportDefaultSpecifier());
    if (!this.eat(standalone_types$1.comma)) { return nodes }
  }
  if (this.type === standalone_types$1.star) {
    nodes.push(this.parseImportNamespaceSpecifier());
    return nodes
  }
  this.expect(standalone_types$1.braceL);
  while (!this.eat(standalone_types$1.braceR)) {
    if (!first) {
      this.expect(standalone_types$1.comma);
      if (this.afterTrailingComma(standalone_types$1.braceR)) { break }
    } else { first = false; }

    nodes.push(this.parseImportSpecifier());
  }
  return nodes
};

standalone_pp$8.parseWithClause = function() {
  var nodes = [];
  if (!this.eat(standalone_types$1._with)) {
    return nodes
  }
  this.expect(standalone_types$1.braceL);
  var attributeKeys = {};
  var first = true;
  while (!this.eat(standalone_types$1.braceR)) {
    if (!first) {
      this.expect(standalone_types$1.comma);
      if (this.afterTrailingComma(standalone_types$1.braceR)) { break }
    } else { first = false; }

    var attr = this.parseImportAttribute();
    var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
    if (standalone_hasOwn(attributeKeys, keyName))
      { this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'"); }
    attributeKeys[keyName] = true;
    nodes.push(attr);
  }
  return nodes
};

standalone_pp$8.parseImportAttribute = function() {
  var node = this.startNode();
  node.key = this.type === standalone_types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
  this.expect(standalone_types$1.colon);
  if (this.type !== standalone_types$1.string) {
    this.unexpected();
  }
  node.value = this.parseExprAtom();
  return this.finishNode(node, "ImportAttribute")
};

standalone_pp$8.parseModuleExportName = function() {
  if (this.options.ecmaVersion >= 13 && this.type === standalone_types$1.string) {
    var stringLiteral = this.parseLiteral(this.value);
    if (standalone_loneSurrogate.test(stringLiteral.value)) {
      this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
    }
    return stringLiteral
  }
  return this.parseIdent(true)
};

// Set `ExpressionStatement#directive` property for directive prologues.
standalone_pp$8.adaptDirectivePrologue = function(statements) {
  for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
    statements[i].directive = statements[i].expression.raw.slice(1, -1);
  }
};
standalone_pp$8.isDirectiveCandidate = function(statement) {
  return (
    this.options.ecmaVersion >= 5 &&
    statement.type === "ExpressionStatement" &&
    statement.expression.type === "Literal" &&
    typeof statement.expression.value === "string" &&
    // Reject parenthesized strings.
    (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  )
};

var standalone_pp$7 = standalone_Parser.prototype;

// Convert existing expression atom to assignable pattern
// if possible.

standalone_pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 6 && node) {
    switch (node.type) {
    case "Identifier":
      if (this.inAsync && node.name === "await")
        { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
      break

    case "ObjectPattern":
    case "ArrayPattern":
    case "AssignmentPattern":
    case "RestElement":
      break

    case "ObjectExpression":
      node.type = "ObjectPattern";
      if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
      for (var i = 0, list = node.properties; i < list.length; i += 1) {
        var prop = list[i];

      this.toAssignable(prop, isBinding);
        // Early error:
        //   AssignmentRestProperty[Yield, Await] :
        //     `...` DestructuringAssignmentTarget[Yield, Await]
        //
        //   It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
        if (
          prop.type === "RestElement" &&
          (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
        ) {
          this.raise(prop.argument.start, "Unexpected token");
        }
      }
      break

    case "Property":
      // AssignmentProperty has type === "Property"
      if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
      this.toAssignable(node.value, isBinding);
      break

    case "ArrayExpression":
      node.type = "ArrayPattern";
      if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
      this.toAssignableList(node.elements, isBinding);
      break

    case "SpreadElement":
      node.type = "RestElement";
      this.toAssignable(node.argument, isBinding);
      if (node.argument.type === "AssignmentPattern")
        { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
      break

    case "AssignmentExpression":
      if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
      node.type = "AssignmentPattern";
      delete node.operator;
      this.toAssignable(node.left, isBinding);
      break

    case "ParenthesizedExpression":
      this.toAssignable(node.expression, isBinding, refDestructuringErrors);
      break

    case "ChainExpression":
      this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
      break

    case "MemberExpression":
      if (!isBinding) { break }

    default:
      this.raise(node.start, "Assigning to rvalue");
    }
  } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  return node
};

// Convert list of expression atoms to binding list.

standalone_pp$7.toAssignableList = function(exprList, isBinding) {
  var end = exprList.length;
  for (var i = 0; i < end; i++) {
    var elt = exprList[i];
    if (elt) { this.toAssignable(elt, isBinding); }
  }
  if (end) {
    var last = exprList[end - 1];
    if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
      { this.unexpected(last.argument.start); }
  }
  return exprList
};

// Parses spread element.

standalone_pp$7.parseSpread = function(refDestructuringErrors) {
  var node = this.startNode();
  this.next();
  node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  return this.finishNode(node, "SpreadElement")
};

standalone_pp$7.parseRestBinding = function() {
  var node = this.startNode();
  this.next();

  // RestElement inside of a function parameter must be an identifier
  if (this.options.ecmaVersion === 6 && this.type !== standalone_types$1.name)
    { this.unexpected(); }

  node.argument = this.parseBindingAtom();

  return this.finishNode(node, "RestElement")
};

// Parses lvalue (assignable) atom.

standalone_pp$7.parseBindingAtom = function() {
  if (this.options.ecmaVersion >= 6) {
    switch (this.type) {
    case standalone_types$1.bracketL:
      var node = this.startNode();
      this.next();
      node.elements = this.parseBindingList(standalone_types$1.bracketR, true, true);
      return this.finishNode(node, "ArrayPattern")

    case standalone_types$1.braceL:
      return this.parseObj(true)
    }
  }
  return this.parseIdent()
};

standalone_pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (first) { first = false; }
    else { this.expect(standalone_types$1.comma); }
    if (allowEmpty && this.type === standalone_types$1.comma) {
      elts.push(null);
    } else if (allowTrailingComma && this.afterTrailingComma(close)) {
      break
    } else if (this.type === standalone_types$1.ellipsis) {
      var rest = this.parseRestBinding();
      this.parseBindingListItem(rest);
      elts.push(rest);
      if (this.type === standalone_types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); }
      this.expect(close);
      break
    } else {
      elts.push(this.parseAssignableListItem(allowModifiers));
    }
  }
  return elts
};

standalone_pp$7.parseAssignableListItem = function(allowModifiers) {
  var elem = this.parseMaybeDefault(this.start, this.startLoc);
  this.parseBindingListItem(elem);
  return elem
};

standalone_pp$7.parseBindingListItem = function(param) {
  return param
};

// Parses assignment pattern around given atom if possible.

standalone_pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  left = left || this.parseBindingAtom();
  if (this.options.ecmaVersion < 6 || !this.eat(standalone_types$1.eq)) { return left }
  var node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.right = this.parseMaybeAssign();
  return this.finishNode(node, "AssignmentPattern")
};

// The following three functions all verify that a node is an lvalue —
// something that can be bound, or assigned to. In order to do so, they perform
// a variety of checks:
//
// - Check that none of the bound/assigned-to identifiers are reserved words.
// - Record name declarations for bindings in the appropriate scope.
// - Check duplicate argument names, if checkClashes is set.
//
// If a complex binding pattern is encountered (e.g., object and array
// destructuring), the entire pattern is recursively checked.
//
// There are three versions of checkLVal*() appropriate for different
// circumstances:
//
// - checkLValSimple() shall be used if the syntactic construct supports
//   nothing other than identifiers and member expressions. Parenthesized
//   expressions are also correctly handled. This is generally appropriate for
//   constructs for which the spec says
//
//   > It is a Syntax Error if AssignmentTargetType of [the production] is not
//   > simple.
//
//   It is also appropriate for checking if an identifier is valid and not
//   defined elsewhere, like import declarations or function/class identifiers.
//
//   Examples where this is used include:
//     a += …;
//     import a from '…';
//   where a is the node to be checked.
//
// - checkLValPattern() shall be used if the syntactic construct supports
//   anything checkLValSimple() supports, as well as object and array
//   destructuring patterns. This is generally appropriate for constructs for
//   which the spec says
//
//   > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
//   > an ArrayLiteral and AssignmentTargetType of [the production] is not
//   > simple.
//
//   Examples where this is used include:
//     (a = …);
//     const a = …;
//     try { … } catch (a) { … }
//   where a is the node to be checked.
//
// - checkLValInnerPattern() shall be used if the syntactic construct supports
//   anything checkLValPattern() supports, as well as default assignment
//   patterns, rest elements, and other constructs that may appear within an
//   object or array destructuring pattern.
//
//   As a special case, function parameters also use checkLValInnerPattern(),
//   as they also support defaults and rest constructs.
//
// These functions deliberately support both assignment and binding constructs,
// as the logic for both is exceedingly similar. If the node is the target of
// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
// should be set to the appropriate BIND_* constant, like BIND_VAR or
// BIND_LEXICAL.
//
// If the function is called with a non-BIND_NONE bindingType, then
// additionally a checkClashes object may be specified to allow checking for
// duplicate argument names. checkClashes is ignored if the provided construct
// is an assignment (i.e., bindingType is BIND_NONE).

standalone_pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  if ( bindingType === void 0 ) bindingType = standalone_BIND_NONE;

  var isBind = bindingType !== standalone_BIND_NONE;

  switch (expr.type) {
  case "Identifier":
    if (this.strict && this.reservedWordsStrictBind.test(expr.name))
      { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
    if (isBind) {
      if (bindingType === standalone_BIND_LEXICAL && expr.name === "let")
        { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
      if (checkClashes) {
        if (standalone_hasOwn(checkClashes, expr.name))
          { this.raiseRecoverable(expr.start, "Argument name clash"); }
        checkClashes[expr.name] = true;
      }
      if (bindingType !== standalone_BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
    }
    break

  case "ChainExpression":
    this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
    break

  case "MemberExpression":
    if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
    break

  case "ParenthesizedExpression":
    if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
    return this.checkLValSimple(expr.expression, bindingType, checkClashes)

  default:
    this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  }
};

standalone_pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  if ( bindingType === void 0 ) bindingType = standalone_BIND_NONE;

  switch (expr.type) {
  case "ObjectPattern":
    for (var i = 0, list = expr.properties; i < list.length; i += 1) {
      var prop = list[i];

    this.checkLValInnerPattern(prop, bindingType, checkClashes);
    }
    break

  case "ArrayPattern":
    for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
      var elem = list$1[i$1];

    if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
    }
    break

  default:
    this.checkLValSimple(expr, bindingType, checkClashes);
  }
};

standalone_pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  if ( bindingType === void 0 ) bindingType = standalone_BIND_NONE;

  switch (expr.type) {
  case "Property":
    // AssignmentProperty has type === "Property"
    this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
    break

  case "AssignmentPattern":
    this.checkLValPattern(expr.left, bindingType, checkClashes);
    break

  case "RestElement":
    this.checkLValPattern(expr.argument, bindingType, checkClashes);
    break

  default:
    this.checkLValPattern(expr, bindingType, checkClashes);
  }
};

// The algorithm used to determine whether a regexp can appear at a
// given point in the program is loosely based on sweet.js' approach.
// See https://github.com/mozilla/sweet.js/wiki/design


var standalone_TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  this.token = token;
  this.isExpr = !!isExpr;
  this.preserveSpace = !!preserveSpace;
  this.override = override;
  this.generator = !!generator;
};

var standalone_acorn_types = {
  b_stat: new standalone_TokContext("{", false),
  b_expr: new standalone_TokContext("{", true),
  b_tmpl: new standalone_TokContext("${", false),
  p_stat: new standalone_TokContext("(", false),
  p_expr: new standalone_TokContext("(", true),
  q_tmpl: new standalone_TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  f_stat: new standalone_TokContext("function", false),
  f_expr: new standalone_TokContext("function", true),
  f_expr_gen: new standalone_TokContext("function", true, false, null, true),
  f_gen: new standalone_TokContext("function", false, false, null, true)
};

var standalone_pp$6 = standalone_Parser.prototype;

standalone_pp$6.initialContext = function() {
  return [standalone_acorn_types.b_stat]
};

standalone_pp$6.curContext = function() {
  return this.context[this.context.length - 1]
};

standalone_pp$6.braceIsBlock = function(prevType) {
  var parent = this.curContext();
  if (parent === standalone_acorn_types.f_expr || parent === standalone_acorn_types.f_stat)
    { return true }
  if (prevType === standalone_types$1.colon && (parent === standalone_acorn_types.b_stat || parent === standalone_acorn_types.b_expr))
    { return !parent.isExpr }

  // The check for `tt.name && exprAllowed` detects whether we are
  // after a `yield` or `of` construct. See the `updateContext` for
  // `tt.name`.
  if (prevType === standalone_types$1._return || prevType === standalone_types$1.name && this.exprAllowed)
    { return standalone_lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  if (prevType === standalone_types$1._else || prevType === standalone_types$1.semi || prevType === standalone_types$1.eof || prevType === standalone_types$1.parenR || prevType === standalone_types$1.arrow)
    { return true }
  if (prevType === standalone_types$1.braceL)
    { return parent === standalone_acorn_types.b_stat }
  if (prevType === standalone_types$1._var || prevType === standalone_types$1._const || prevType === standalone_types$1.name)
    { return false }
  return !this.exprAllowed
};

standalone_pp$6.inGeneratorContext = function() {
  for (var i = this.context.length - 1; i >= 1; i--) {
    var context = this.context[i];
    if (context.token === "function")
      { return context.generator }
  }
  return false
};

standalone_pp$6.updateContext = function(prevType) {
  var update, type = this.type;
  if (type.keyword && prevType === standalone_types$1.dot)
    { this.exprAllowed = false; }
  else if (update = type.updateContext)
    { update.call(this, prevType); }
  else
    { this.exprAllowed = type.beforeExpr; }
};

// Used to handle edge cases when token context could not be inferred correctly during tokenization phase

standalone_pp$6.overrideContext = function(tokenCtx) {
  if (this.curContext() !== tokenCtx) {
    this.context[this.context.length - 1] = tokenCtx;
  }
};

// Token-specific context update code

standalone_types$1.parenR.updateContext = standalone_types$1.braceR.updateContext = function() {
  if (this.context.length === 1) {
    this.exprAllowed = true;
    return
  }
  var out = this.context.pop();
  if (out === standalone_acorn_types.b_stat && this.curContext().token === "function") {
    out = this.context.pop();
  }
  this.exprAllowed = !out.isExpr;
};

standalone_types$1.braceL.updateContext = function(prevType) {
  this.context.push(this.braceIsBlock(prevType) ? standalone_acorn_types.b_stat : standalone_acorn_types.b_expr);
  this.exprAllowed = true;
};

standalone_types$1.dollarBraceL.updateContext = function() {
  this.context.push(standalone_acorn_types.b_tmpl);
  this.exprAllowed = true;
};

standalone_types$1.parenL.updateContext = function(prevType) {
  var statementParens = prevType === standalone_types$1._if || prevType === standalone_types$1._for || prevType === standalone_types$1._with || prevType === standalone_types$1._while;
  this.context.push(statementParens ? standalone_acorn_types.p_stat : standalone_acorn_types.p_expr);
  this.exprAllowed = true;
};

standalone_types$1.incDec.updateContext = function() {
  // tokExprAllowed stays unchanged
};

standalone_types$1._function.updateContext = standalone_types$1._class.updateContext = function(prevType) {
  if (prevType.beforeExpr && prevType !== standalone_types$1._else &&
      !(prevType === standalone_types$1.semi && this.curContext() !== standalone_acorn_types.p_stat) &&
      !(prevType === standalone_types$1._return && standalone_lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
      !((prevType === standalone_types$1.colon || prevType === standalone_types$1.braceL) && this.curContext() === standalone_acorn_types.b_stat))
    { this.context.push(standalone_acorn_types.f_expr); }
  else
    { this.context.push(standalone_acorn_types.f_stat); }
  this.exprAllowed = false;
};

standalone_types$1.colon.updateContext = function() {
  if (this.curContext().token === "function") { this.context.pop(); }
  this.exprAllowed = true;
};

standalone_types$1.backQuote.updateContext = function() {
  if (this.curContext() === standalone_acorn_types.q_tmpl)
    { this.context.pop(); }
  else
    { this.context.push(standalone_acorn_types.q_tmpl); }
  this.exprAllowed = false;
};

standalone_types$1.star.updateContext = function(prevType) {
  if (prevType === standalone_types$1._function) {
    var index = this.context.length - 1;
    if (this.context[index] === standalone_acorn_types.f_expr)
      { this.context[index] = standalone_acorn_types.f_expr_gen; }
    else
      { this.context[index] = standalone_acorn_types.f_gen; }
  }
  this.exprAllowed = true;
};

standalone_types$1.name.updateContext = function(prevType) {
  var allowed = false;
  if (this.options.ecmaVersion >= 6 && prevType !== standalone_types$1.dot) {
    if (this.value === "of" && !this.exprAllowed ||
        this.value === "yield" && this.inGeneratorContext())
      { allowed = true; }
  }
  this.exprAllowed = allowed;
};

// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser


var standalone_pp$5 = standalone_Parser.prototype;

// Check if property name clashes with already added.
// Object/class getters and setters are not allowed to clash —
// either with each other or with an init property — and in
// strict mode, init properties are also not allowed to be repeated.

standalone_pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
    { return }
  if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
    { return }
  var key = prop.key;
  var name;
  switch (key.type) {
  case "Identifier": name = key.name; break
  case "Literal": name = String(key.value); break
  default: return
  }
  var kind = prop.kind;
  if (this.options.ecmaVersion >= 6) {
    if (name === "__proto__" && kind === "init") {
      if (propHash.proto) {
        if (refDestructuringErrors) {
          if (refDestructuringErrors.doubleProto < 0) {
            refDestructuringErrors.doubleProto = key.start;
          }
        } else {
          this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
        }
      }
      propHash.proto = true;
    }
    return
  }
  name = "$" + name;
  var other = propHash[name];
  if (other) {
    var redefinition;
    if (kind === "init") {
      redefinition = this.strict && other.init || other.get || other.set;
    } else {
      redefinition = other.init || other[kind];
    }
    if (redefinition)
      { this.raiseRecoverable(key.start, "Redefinition of property"); }
  } else {
    other = propHash[name] = {
      init: false,
      get: false,
      set: false
    };
  }
  other[kind] = true;
};

// ### Expression parsing

// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function(s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.

// Parse a full expression. The optional arguments are used to
// forbid the `in` operator (in for loops initalization expressions)
// and provide reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).

standalone_pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  if (this.type === standalone_types$1.comma) {
    var node = this.startNodeAt(startPos, startLoc);
    node.expressions = [expr];
    while (this.eat(standalone_types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
    return this.finishNode(node, "SequenceExpression")
  }
  return expr
};

// Parse an assignment expression. This includes applications of
// operators like `+=`.

standalone_pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  if (this.isContextual("yield")) {
    if (this.inGenerator) { return this.parseYield(forInit) }
    // The tokenizer will assume an expression is allowed after
    // `yield`, but this isn't that kind of yield
    else { this.exprAllowed = false; }
  }

  var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  if (refDestructuringErrors) {
    oldParenAssign = refDestructuringErrors.parenthesizedAssign;
    oldTrailingComma = refDestructuringErrors.trailingComma;
    oldDoubleProto = refDestructuringErrors.doubleProto;
    refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  } else {
    refDestructuringErrors = new standalone_DestructuringErrors;
    ownDestructuringErrors = true;
  }

  var startPos = this.start, startLoc = this.startLoc;
  if (this.type === standalone_types$1.parenL || this.type === standalone_types$1.name) {
    this.potentialArrowAt = this.start;
    this.potentialArrowInForAwait = forInit === "await";
  }
  var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  if (this.type.isAssign) {
    var node = this.startNodeAt(startPos, startLoc);
    node.operator = this.value;
    if (this.type === standalone_types$1.eq)
      { left = this.toAssignable(left, false, refDestructuringErrors); }
    if (!ownDestructuringErrors) {
      refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
    }
    if (refDestructuringErrors.shorthandAssign >= left.start)
      { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
    if (this.type === standalone_types$1.eq)
      { this.checkLValPattern(left); }
    else
      { this.checkLValSimple(left); }
    node.left = left;
    this.next();
    node.right = this.parseMaybeAssign(forInit);
    if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
    return this.finishNode(node, "AssignmentExpression")
  } else {
    if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  }
  if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  return left
};

// Parse a ternary conditional (`?:`) operator.

standalone_pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprOps(forInit, refDestructuringErrors);
  if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  if (this.eat(standalone_types$1.question)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.test = expr;
    node.consequent = this.parseMaybeAssign();
    this.expect(standalone_types$1.colon);
    node.alternate = this.parseMaybeAssign(forInit);
    return this.finishNode(node, "ConditionalExpression")
  }
  return expr
};

// Start the precedence parser.

standalone_pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
};

// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.

standalone_pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  var prec = this.type.binop;
  if (prec != null && (!forInit || this.type !== standalone_types$1._in)) {
    if (prec > minPrec) {
      var logical = this.type === standalone_types$1.logicalOR || this.type === standalone_types$1.logicalAND;
      var coalesce = this.type === standalone_types$1.coalesce;
      if (coalesce) {
        // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
        // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
        prec = standalone_types$1.logicalAND.binop;
      }
      var op = this.value;
      this.next();
      var startPos = this.start, startLoc = this.startLoc;
      var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
      var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
      if ((logical && this.type === standalone_types$1.coalesce) || (coalesce && (this.type === standalone_types$1.logicalOR || this.type === standalone_types$1.logicalAND))) {
        this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
      }
      return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
    }
  }
  return left
};

standalone_pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  var node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.operator = op;
  node.right = right;
  return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
};

// Parse unary operators, both prefix and postfix.

standalone_pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  var startPos = this.start, startLoc = this.startLoc, expr;
  if (this.isContextual("await") && this.canAwait) {
    expr = this.parseAwait(forInit);
    sawUnary = true;
  } else if (this.type.prefix) {
    var node = this.startNode(), update = this.type === standalone_types$1.incDec;
    node.operator = this.value;
    node.prefix = true;
    this.next();
    node.argument = this.parseMaybeUnary(null, true, update, forInit);
    this.checkExpressionErrors(refDestructuringErrors, true);
    if (update) { this.checkLValSimple(node.argument); }
    else if (this.strict && node.operator === "delete" && standalone_isLocalVariableAccess(node.argument))
      { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
    else if (node.operator === "delete" && standalone_isPrivateFieldAccess(node.argument))
      { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
    else { sawUnary = true; }
    expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  } else if (!sawUnary && this.type === standalone_types$1.privateId) {
    if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); }
    expr = this.parsePrivateIdent();
    // only could be private fields in 'in', such as #x in obj
    if (this.type !== standalone_types$1._in) { this.unexpected(); }
  } else {
    expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
    if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
    while (this.type.postfix && !this.canInsertSemicolon()) {
      var node$1 = this.startNodeAt(startPos, startLoc);
      node$1.operator = this.value;
      node$1.prefix = false;
      node$1.argument = expr;
      this.checkLValSimple(expr);
      this.next();
      expr = this.finishNode(node$1, "UpdateExpression");
    }
  }

  if (!incDec && this.eat(standalone_types$1.starstar)) {
    if (sawUnary)
      { this.unexpected(this.lastTokStart); }
    else
      { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  } else {
    return expr
  }
};

function standalone_isLocalVariableAccess(node) {
  return (
    node.type === "Identifier" ||
    node.type === "ParenthesizedExpression" && standalone_isLocalVariableAccess(node.expression)
  )
}

function standalone_isPrivateFieldAccess(node) {
  return (
    node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
    node.type === "ChainExpression" && standalone_isPrivateFieldAccess(node.expression) ||
    node.type === "ParenthesizedExpression" && standalone_isPrivateFieldAccess(node.expression)
  )
}

// Parse call, dot, and `[]`-subscript expressions.

standalone_pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
    { return expr }
  var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  if (refDestructuringErrors && result.type === "MemberExpression") {
    if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
    if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
    if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  }
  return result
};

standalone_pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
      this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
      this.potentialArrowAt === base.start;
  var optionalChained = false;

  while (true) {
    var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);

    if (element.optional) { optionalChained = true; }
    if (element === base || element.type === "ArrowFunctionExpression") {
      if (optionalChained) {
        var chainNode = this.startNodeAt(startPos, startLoc);
        chainNode.expression = element;
        element = this.finishNode(chainNode, "ChainExpression");
      }
      return element
    }

    base = element;
  }
};

standalone_pp$5.shouldParseAsyncArrow = function() {
  return !this.canInsertSemicolon() && this.eat(standalone_types$1.arrow)
};

standalone_pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
};

standalone_pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  var optionalSupported = this.options.ecmaVersion >= 11;
  var optional = optionalSupported && this.eat(standalone_types$1.questionDot);
  if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }

  var computed = this.eat(standalone_types$1.bracketL);
  if (computed || (optional && this.type !== standalone_types$1.parenL && this.type !== standalone_types$1.backQuote) || this.eat(standalone_types$1.dot)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.object = base;
    if (computed) {
      node.property = this.parseExpression();
      this.expect(standalone_types$1.bracketR);
    } else if (this.type === standalone_types$1.privateId && base.type !== "Super") {
      node.property = this.parsePrivateIdent();
    } else {
      node.property = this.parseIdent(this.options.allowReserved !== "never");
    }
    node.computed = !!computed;
    if (optionalSupported) {
      node.optional = optional;
    }
    base = this.finishNode(node, "MemberExpression");
  } else if (!noCalls && this.eat(standalone_types$1.parenL)) {
    var refDestructuringErrors = new standalone_DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.yieldPos = 0;
    this.awaitPos = 0;
    this.awaitIdentPos = 0;
    var exprList = this.parseExprList(standalone_types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
    if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      if (this.awaitIdentPos > 0)
        { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      this.awaitIdentPos = oldAwaitIdentPos;
      return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit)
    }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;
    this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
    var node$1 = this.startNodeAt(startPos, startLoc);
    node$1.callee = base;
    node$1.arguments = exprList;
    if (optionalSupported) {
      node$1.optional = optional;
    }
    base = this.finishNode(node$1, "CallExpression");
  } else if (this.type === standalone_types$1.backQuote) {
    if (optional || optionalChained) {
      this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
    }
    var node$2 = this.startNodeAt(startPos, startLoc);
    node$2.tag = base;
    node$2.quasi = this.parseTemplate({isTagged: true});
    base = this.finishNode(node$2, "TaggedTemplateExpression");
  }
  return base
};

// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.

standalone_pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
  // If a division operator appears in an expression position, the
  // tokenizer got confused, and we force it to read a regexp instead.
  if (this.type === standalone_types$1.slash) { this.readRegexp(); }

  var node, canBeArrow = this.potentialArrowAt === this.start;
  switch (this.type) {
  case standalone_types$1._super:
    if (!this.allowSuper)
      { this.raise(this.start, "'super' keyword outside a method"); }
    node = this.startNode();
    this.next();
    if (this.type === standalone_types$1.parenL && !this.allowDirectSuper)
      { this.raise(node.start, "super() call outside constructor of a subclass"); }
    // The `super` keyword can appear at below:
    // SuperProperty:
    //     super [ Expression ]
    //     super . IdentifierName
    // SuperCall:
    //     super ( Arguments )
    if (this.type !== standalone_types$1.dot && this.type !== standalone_types$1.bracketL && this.type !== standalone_types$1.parenL)
      { this.unexpected(); }
    return this.finishNode(node, "Super")

  case standalone_types$1._this:
    node = this.startNode();
    this.next();
    return this.finishNode(node, "ThisExpression")

  case standalone_types$1.name:
    var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
    var id = this.parseIdent(false);
    if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(standalone_types$1._function)) {
      this.overrideContext(standalone_acorn_types.f_expr);
      return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
    }
    if (canBeArrow && !this.canInsertSemicolon()) {
      if (this.eat(standalone_types$1.arrow))
        { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
      if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === standalone_types$1.name && !containsEsc &&
          (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
        id = this.parseIdent(false);
        if (this.canInsertSemicolon() || !this.eat(standalone_types$1.arrow))
          { this.unexpected(); }
        return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
      }
    }
    return id

  case standalone_types$1.regexp:
    var value = this.value;
    node = this.parseLiteral(value.value);
    node.regex = {pattern: value.pattern, flags: value.flags};
    return node

  case standalone_types$1.num: case standalone_types$1.string:
    return this.parseLiteral(this.value)

  case standalone_types$1._null: case standalone_types$1._true: case standalone_types$1._false:
    node = this.startNode();
    node.value = this.type === standalone_types$1._null ? null : this.type === standalone_types$1._true;
    node.raw = this.type.keyword;
    this.next();
    return this.finishNode(node, "Literal")

  case standalone_types$1.parenL:
    var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
    if (refDestructuringErrors) {
      if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
        { refDestructuringErrors.parenthesizedAssign = start; }
      if (refDestructuringErrors.parenthesizedBind < 0)
        { refDestructuringErrors.parenthesizedBind = start; }
    }
    return expr

  case standalone_types$1.bracketL:
    node = this.startNode();
    this.next();
    node.elements = this.parseExprList(standalone_types$1.bracketR, true, true, refDestructuringErrors);
    return this.finishNode(node, "ArrayExpression")

  case standalone_types$1.braceL:
    this.overrideContext(standalone_acorn_types.b_expr);
    return this.parseObj(false, refDestructuringErrors)

  case standalone_types$1._function:
    node = this.startNode();
    this.next();
    return this.parseFunction(node, 0)

  case standalone_types$1._class:
    return this.parseClass(this.startNode(), false)

  case standalone_types$1._new:
    return this.parseNew()

  case standalone_types$1.backQuote:
    return this.parseTemplate()

  case standalone_types$1._import:
    if (this.options.ecmaVersion >= 11) {
      return this.parseExprImport(forNew)
    } else {
      return this.unexpected()
    }

  default:
    return this.parseExprAtomDefault()
  }
};

standalone_pp$5.parseExprAtomDefault = function() {
  this.unexpected();
};

standalone_pp$5.parseExprImport = function(forNew) {
  var node = this.startNode();

  // Consume `import` as an identifier for `import.meta`.
  // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  this.next();

  if (this.type === standalone_types$1.parenL && !forNew) {
    return this.parseDynamicImport(node)
  } else if (this.type === standalone_types$1.dot) {
    var meta = this.startNodeAt(node.start, node.loc && node.loc.start);
    meta.name = "import";
    node.meta = this.finishNode(meta, "Identifier");
    return this.parseImportMeta(node)
  } else {
    this.unexpected();
  }
};

standalone_pp$5.parseDynamicImport = function(node) {
  this.next(); // skip `(`

  // Parse node.source.
  node.source = this.parseMaybeAssign();

  if (this.options.ecmaVersion >= 16) {
    if (!this.eat(standalone_types$1.parenR)) {
      this.expect(standalone_types$1.comma);
      if (!this.afterTrailingComma(standalone_types$1.parenR)) {
        node.options = this.parseMaybeAssign();
        if (!this.eat(standalone_types$1.parenR)) {
          this.expect(standalone_types$1.comma);
          if (!this.afterTrailingComma(standalone_types$1.parenR)) {
            this.unexpected();
          }
        }
      } else {
        node.options = null;
      }
    } else {
      node.options = null;
    }
  } else {
    // Verify ending.
    if (!this.eat(standalone_types$1.parenR)) {
      var errorPos = this.start;
      if (this.eat(standalone_types$1.comma) && this.eat(standalone_types$1.parenR)) {
        this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
      } else {
        this.unexpected(errorPos);
      }
    }
  }

  return this.finishNode(node, "ImportExpression")
};

standalone_pp$5.parseImportMeta = function(node) {
  this.next(); // skip `.`

  var containsEsc = this.containsEsc;
  node.property = this.parseIdent(true);

  if (node.property.name !== "meta")
    { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  if (containsEsc)
    { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
    { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }

  return this.finishNode(node, "MetaProperty")
};

standalone_pp$5.parseLiteral = function(value) {
  var node = this.startNode();
  node.value = value;
  node.raw = this.input.slice(this.start, this.end);
  if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  this.next();
  return this.finishNode(node, "Literal")
};

standalone_pp$5.parseParenExpression = function() {
  this.expect(standalone_types$1.parenL);
  var val = this.parseExpression();
  this.expect(standalone_types$1.parenR);
  return val
};

standalone_pp$5.shouldParseArrow = function(exprList) {
  return !this.canInsertSemicolon()
};

standalone_pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  if (this.options.ecmaVersion >= 6) {
    this.next();

    var innerStartPos = this.start, innerStartLoc = this.startLoc;
    var exprList = [], first = true, lastIsComma = false;
    var refDestructuringErrors = new standalone_DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
    this.yieldPos = 0;
    this.awaitPos = 0;
    // Do not save awaitIdentPos to allow checking awaits nested in parameters
    while (this.type !== standalone_types$1.parenR) {
      first ? first = false : this.expect(standalone_types$1.comma);
      if (allowTrailingComma && this.afterTrailingComma(standalone_types$1.parenR, true)) {
        lastIsComma = true;
        break
      } else if (this.type === standalone_types$1.ellipsis) {
        spreadStart = this.start;
        exprList.push(this.parseParenItem(this.parseRestBinding()));
        if (this.type === standalone_types$1.comma) {
          this.raiseRecoverable(
            this.start,
            "Comma is not permitted after the rest element"
          );
        }
        break
      } else {
        exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
      }
    }
    var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
    this.expect(standalone_types$1.parenR);

    if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(standalone_types$1.arrow)) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
    }

    if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
    if (spreadStart) { this.unexpected(spreadStart); }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;

    if (exprList.length > 1) {
      val = this.startNodeAt(innerStartPos, innerStartLoc);
      val.expressions = exprList;
      this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
    } else {
      val = exprList[0];
    }
  } else {
    val = this.parseParenExpression();
  }

  if (this.options.preserveParens) {
    var par = this.startNodeAt(startPos, startLoc);
    par.expression = val;
    return this.finishNode(par, "ParenthesizedExpression")
  } else {
    return val
  }
};

standalone_pp$5.parseParenItem = function(item) {
  return item
};

standalone_pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
};

// New's precedence is slightly tricky. It must allow its argument to
// be a `[]` or dot subscript expression, but not a call — at least,
// not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.

var standalone_acorn_empty = [];

standalone_pp$5.parseNew = function() {
  if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  var node = this.startNode();
  this.next();
  if (this.options.ecmaVersion >= 6 && this.type === standalone_types$1.dot) {
    var meta = this.startNodeAt(node.start, node.loc && node.loc.start);
    meta.name = "new";
    node.meta = this.finishNode(meta, "Identifier");
    this.next();
    var containsEsc = this.containsEsc;
    node.property = this.parseIdent(true);
    if (node.property.name !== "target")
      { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
    if (containsEsc)
      { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
    if (!this.allowNewDotTarget)
      { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
    return this.finishNode(node, "MetaProperty")
  }
  var startPos = this.start, startLoc = this.startLoc;
  node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
  if (this.eat(standalone_types$1.parenL)) { node.arguments = this.parseExprList(standalone_types$1.parenR, this.options.ecmaVersion >= 8, false); }
  else { node.arguments = standalone_acorn_empty; }
  return this.finishNode(node, "NewExpression")
};

// Parse template expression.

standalone_pp$5.parseTemplateElement = function(ref) {
  var isTagged = ref.isTagged;

  var elem = this.startNode();
  if (this.type === standalone_types$1.invalidTemplate) {
    if (!isTagged) {
      this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
    }
    elem.value = {
      raw: this.value.replace(/\r\n?/g, "\n"),
      cooked: null
    };
  } else {
    elem.value = {
      raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
      cooked: this.value
    };
  }
  this.next();
  elem.tail = this.type === standalone_types$1.backQuote;
  return this.finishNode(elem, "TemplateElement")
};

standalone_pp$5.parseTemplate = function(ref) {
  if ( ref === void 0 ) ref = {};
  var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;

  var node = this.startNode();
  this.next();
  node.expressions = [];
  var curElt = this.parseTemplateElement({isTagged: isTagged});
  node.quasis = [curElt];
  while (!curElt.tail) {
    if (this.type === standalone_types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
    this.expect(standalone_types$1.dollarBraceL);
    node.expressions.push(this.parseExpression());
    this.expect(standalone_types$1.braceR);
    node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  }
  this.next();
  return this.finishNode(node, "TemplateLiteral")
};

standalone_pp$5.isAsyncProp = function(prop) {
  return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
    (this.type === standalone_types$1.name || this.type === standalone_types$1.num || this.type === standalone_types$1.string || this.type === standalone_types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === standalone_types$1.star)) &&
    !standalone_lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
};

// Parse an object literal or binding pattern.

standalone_pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  var node = this.startNode(), first = true, propHash = {};
  node.properties = [];
  this.next();
  while (!this.eat(standalone_types$1.braceR)) {
    if (!first) {
      this.expect(standalone_types$1.comma);
      if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(standalone_types$1.braceR)) { break }
    } else { first = false; }

    var prop = this.parseProperty(isPattern, refDestructuringErrors);
    if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
    node.properties.push(prop);
  }
  return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
};

standalone_pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  if (this.options.ecmaVersion >= 9 && this.eat(standalone_types$1.ellipsis)) {
    if (isPattern) {
      prop.argument = this.parseIdent(false);
      if (this.type === standalone_types$1.comma) {
        this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
      }
      return this.finishNode(prop, "RestElement")
    }
    // Parse argument.
    prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
    // To disallow trailing comma via `this.toAssignable()`.
    if (this.type === standalone_types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
      refDestructuringErrors.trailingComma = this.start;
    }
    // Finish
    return this.finishNode(prop, "SpreadElement")
  }
  if (this.options.ecmaVersion >= 6) {
    prop.method = false;
    prop.shorthand = false;
    if (isPattern || refDestructuringErrors) {
      startPos = this.start;
      startLoc = this.startLoc;
    }
    if (!isPattern)
      { isGenerator = this.eat(standalone_types$1.star); }
  }
  var containsEsc = this.containsEsc;
  this.parsePropertyName(prop);
  if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
    isAsync = true;
    isGenerator = this.options.ecmaVersion >= 9 && this.eat(standalone_types$1.star);
    this.parsePropertyName(prop);
  } else {
    isAsync = false;
  }
  this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  return this.finishNode(prop, "Property")
};

standalone_pp$5.parseGetterSetter = function(prop) {
  prop.kind = prop.key.name;
  this.parsePropertyName(prop);
  prop.value = this.parseMethod(false);
  var paramCount = prop.kind === "get" ? 0 : 1;
  if (prop.value.params.length !== paramCount) {
    var start = prop.value.start;
    if (prop.kind === "get")
      { this.raiseRecoverable(start, "getter should have no params"); }
    else
      { this.raiseRecoverable(start, "setter should have exactly one param"); }
  } else {
    if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
      { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  }
};

standalone_pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  if ((isGenerator || isAsync) && this.type === standalone_types$1.colon)
    { this.unexpected(); }

  if (this.eat(standalone_types$1.colon)) {
    prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
    prop.kind = "init";
  } else if (this.options.ecmaVersion >= 6 && this.type === standalone_types$1.parenL) {
    if (isPattern) { this.unexpected(); }
    prop.kind = "init";
    prop.method = true;
    prop.value = this.parseMethod(isGenerator, isAsync);
  } else if (!isPattern && !containsEsc &&
             this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
             (prop.key.name === "get" || prop.key.name === "set") &&
             (this.type !== standalone_types$1.comma && this.type !== standalone_types$1.braceR && this.type !== standalone_types$1.eq)) {
    if (isGenerator || isAsync) { this.unexpected(); }
    this.parseGetterSetter(prop);
  } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
    if (isGenerator || isAsync) { this.unexpected(); }
    this.checkUnreserved(prop.key);
    if (prop.key.name === "await" && !this.awaitIdentPos)
      { this.awaitIdentPos = startPos; }
    prop.kind = "init";
    if (isPattern) {
      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
    } else if (this.type === standalone_types$1.eq && refDestructuringErrors) {
      if (refDestructuringErrors.shorthandAssign < 0)
        { refDestructuringErrors.shorthandAssign = this.start; }
      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
    } else {
      prop.value = this.copyNode(prop.key);
    }
    prop.shorthand = true;
  } else { this.unexpected(); }
};

standalone_pp$5.parsePropertyName = function(prop) {
  if (this.options.ecmaVersion >= 6) {
    if (this.eat(standalone_types$1.bracketL)) {
      prop.computed = true;
      prop.key = this.parseMaybeAssign();
      this.expect(standalone_types$1.bracketR);
      return prop.key
    } else {
      prop.computed = false;
    }
  }
  return prop.key = this.type === standalone_types$1.num || this.type === standalone_types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
};

// Initialize empty function node.

standalone_pp$5.initFunction = function(node) {
  node.id = null;
  if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  if (this.options.ecmaVersion >= 8) { node.async = false; }
};

// Parse object or class method.

standalone_pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;

  this.initFunction(node);
  if (this.options.ecmaVersion >= 6)
    { node.generator = isGenerator; }
  if (this.options.ecmaVersion >= 8)
    { node.async = !!isAsync; }

  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(standalone_functionFlags(isAsync, node.generator) | standalone_SCOPE_SUPER | (allowDirectSuper ? standalone_SCOPE_DIRECT_SUPER : 0));

  this.expect(standalone_types$1.parenL);
  node.params = this.parseBindingList(standalone_types$1.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
  this.parseFunctionBody(node, false, true, false);

  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, "FunctionExpression")
};

// Parse arrow function expression with given parameters.

standalone_pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;

  this.enterScope(standalone_functionFlags(isAsync, false) | standalone_SCOPE_ARROW);
  this.initFunction(node);
  if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }

  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;

  node.params = this.toAssignableList(params, true);
  this.parseFunctionBody(node, true, false, forInit);

  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node, "ArrowFunctionExpression")
};

// Parse function body and check parameters.

standalone_pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  var isExpression = isArrowFunction && this.type !== standalone_types$1.braceL;
  var oldStrict = this.strict, useStrict = false;

  if (isExpression) {
    node.body = this.parseMaybeAssign(forInit);
    node.expression = true;
    this.checkParams(node, false);
  } else {
    var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
    if (!oldStrict || nonSimple) {
      useStrict = this.strictDirective(this.end);
      // If this is a strict mode function, verify that argument names
      // are not repeated, and it does not try to bind the words `eval`
      // or `arguments`.
      if (useStrict && nonSimple)
        { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
    }
    // Start a new scope with regard to labels and the `inFunction`
    // flag (restore them to their old value afterwards).
    var oldLabels = this.labels;
    this.labels = [];
    if (useStrict) { this.strict = true; }

    // Add the params to varDeclaredNames to ensure that an error is thrown
    // if a let/const declaration in the function clashes with one of the params.
    this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
    // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
    if (this.strict && node.id) { this.checkLValSimple(node.id, standalone_BIND_OUTSIDE); }
    node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
    node.expression = false;
    this.adaptDirectivePrologue(node.body.body);
    this.labels = oldLabels;
  }
  this.exitScope();
};

standalone_pp$5.isSimpleParamList = function(params) {
  for (var i = 0, list = params; i < list.length; i += 1)
    {
    var param = list[i];

    if (param.type !== "Identifier") { return false
  } }
  return true
};

// Checks function params for various disallowed patterns such as using "eval"
// or "arguments" and duplicate parameters.

standalone_pp$5.checkParams = function(node, allowDuplicates) {
  var nameHash = Object.create(null);
  for (var i = 0, list = node.params; i < list.length; i += 1)
    {
    var param = list[i];

    this.checkLValInnerPattern(param, standalone_BIND_VAR, allowDuplicates ? null : nameHash);
  }
};

// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).

standalone_pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (!first) {
      this.expect(standalone_types$1.comma);
      if (allowTrailingComma && this.afterTrailingComma(close)) { break }
    } else { first = false; }

    var elt = (void 0);
    if (allowEmpty && this.type === standalone_types$1.comma)
      { elt = null; }
    else if (this.type === standalone_types$1.ellipsis) {
      elt = this.parseSpread(refDestructuringErrors);
      if (refDestructuringErrors && this.type === standalone_types$1.comma && refDestructuringErrors.trailingComma < 0)
        { refDestructuringErrors.trailingComma = this.start; }
    } else {
      elt = this.parseMaybeAssign(false, refDestructuringErrors);
    }
    elts.push(elt);
  }
  return elts
};

standalone_pp$5.checkUnreserved = function(ref) {
  var start = ref.start;
  var end = ref.end;
  var name = ref.name;

  if (this.inGenerator && name === "yield")
    { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  if (this.inAsync && name === "await")
    { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  if (this.currentThisScope().inClassFieldInit && name === "arguments")
    { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
    { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  if (this.keywords.test(name))
    { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  if (this.options.ecmaVersion < 6 &&
    this.input.slice(start, end).indexOf("\\") !== -1) { return }
  var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  if (re.test(name)) {
    if (!this.inAsync && name === "await")
      { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
    this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  }
};

// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.

standalone_pp$5.parseIdent = function(liberal) {
  var node = this.parseIdentNode();
  this.next(!!liberal);
  this.finishNode(node, "Identifier");
  if (!liberal) {
    this.checkUnreserved(node);
    if (node.name === "await" && !this.awaitIdentPos)
      { this.awaitIdentPos = node.start; }
  }
  return node
};

standalone_pp$5.parseIdentNode = function() {
  var node = this.startNode();
  if (this.type === standalone_types$1.name) {
    node.name = this.value;
  } else if (this.type.keyword) {
    node.name = this.type.keyword;

    // To fix https://github.com/acornjs/acorn/issues/575
    // `class` and `function` keywords push new context into this.context.
    // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
    // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
    if ((node.name === "class" || node.name === "function") &&
      (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
      this.context.pop();
    }
    this.type = standalone_types$1.name;
  } else {
    this.unexpected();
  }
  return node
};

standalone_pp$5.parsePrivateIdent = function() {
  var node = this.startNode();
  if (this.type === standalone_types$1.privateId) {
    node.name = this.value;
  } else {
    this.unexpected();
  }
  this.next();
  this.finishNode(node, "PrivateIdentifier");

  // For validating existence
  if (this.options.checkPrivateFields) {
    if (this.privateNameStack.length === 0) {
      this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
    } else {
      this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
    }
  }

  return node
};

// Parses yield expression inside generator.

standalone_pp$5.parseYield = function(forInit) {
  if (!this.yieldPos) { this.yieldPos = this.start; }

  var node = this.startNode();
  this.next();
  if (this.type === standalone_types$1.semi || this.canInsertSemicolon() || (this.type !== standalone_types$1.star && !this.type.startsExpr)) {
    node.delegate = false;
    node.argument = null;
  } else {
    node.delegate = this.eat(standalone_types$1.star);
    node.argument = this.parseMaybeAssign(forInit);
  }
  return this.finishNode(node, "YieldExpression")
};

standalone_pp$5.parseAwait = function(forInit) {
  if (!this.awaitPos) { this.awaitPos = this.start; }

  var node = this.startNode();
  this.next();
  node.argument = this.parseMaybeUnary(null, true, false, forInit);
  return this.finishNode(node, "AwaitExpression")
};

var standalone_pp$4 = standalone_Parser.prototype;

// This function is used to raise exceptions on parse errors. It
// takes an offset integer (into the current `input`) to indicate
// the location of the error, attaches the position to the end
// of the error message, and then raises a `SyntaxError` with that
// message.

standalone_pp$4.raise = function(pos, message) {
  var loc = standalone_getLineInfo(this.input, pos);
  message += " (" + loc.line + ":" + loc.column + ")";
  var err = new SyntaxError(message);
  err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  throw err
};

standalone_pp$4.raiseRecoverable = standalone_pp$4.raise;

standalone_pp$4.curPosition = function() {
  if (this.options.locations) {
    return new standalone_Position(this.curLine, this.pos - this.lineStart)
  }
};

var standalone_pp$3 = standalone_Parser.prototype;

var standalone_acorn_Scope = function Scope(flags) {
  this.flags = flags;
  // A list of var-declared names in the current lexical scope
  this.var = [];
  // A list of lexically-declared names in the current lexical scope
  this.lexical = [];
  // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  this.functions = [];
  // A switch to disallow the identifier reference 'arguments'
  this.inClassFieldInit = false;
};

// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.

standalone_pp$3.enterScope = function(flags) {
  this.scopeStack.push(new standalone_acorn_Scope(flags));
};

standalone_pp$3.exitScope = function() {
  this.scopeStack.pop();
};

// The spec says:
// > At the top level of a function, or script, function declarations are
// > treated like var declarations rather than like lexical declarations.
standalone_pp$3.treatFunctionsAsVarInScope = function(scope) {
  return (scope.flags & standalone_SCOPE_FUNCTION) || !this.inModule && (scope.flags & standalone_SCOPE_TOP)
};

standalone_pp$3.declareName = function(name, bindingType, pos) {
  var redeclared = false;
  if (bindingType === standalone_BIND_LEXICAL) {
    var scope = this.currentScope();
    redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
    scope.lexical.push(name);
    if (this.inModule && (scope.flags & standalone_SCOPE_TOP))
      { delete this.undefinedExports[name]; }
  } else if (bindingType === standalone_BIND_SIMPLE_CATCH) {
    var scope$1 = this.currentScope();
    scope$1.lexical.push(name);
  } else if (bindingType === standalone_BIND_FUNCTION) {
    var scope$2 = this.currentScope();
    if (this.treatFunctionsAsVar)
      { redeclared = scope$2.lexical.indexOf(name) > -1; }
    else
      { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
    scope$2.functions.push(name);
  } else {
    for (var i = this.scopeStack.length - 1; i >= 0; --i) {
      var scope$3 = this.scopeStack[i];
      if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & standalone_SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
          !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
        redeclared = true;
        break
      }
      scope$3.var.push(name);
      if (this.inModule && (scope$3.flags & standalone_SCOPE_TOP))
        { delete this.undefinedExports[name]; }
      if (scope$3.flags & standalone_SCOPE_VAR) { break }
    }
  }
  if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
};

standalone_pp$3.checkLocalExport = function(id) {
  // scope.functions must be empty as Module code is always strict.
  if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
      this.scopeStack[0].var.indexOf(id.name) === -1) {
    this.undefinedExports[id.name] = id;
  }
};

standalone_pp$3.currentScope = function() {
  return this.scopeStack[this.scopeStack.length - 1]
};

standalone_pp$3.currentVarScope = function() {
  for (var i = this.scopeStack.length - 1;; i--) {
    var scope = this.scopeStack[i];
    if (scope.flags & standalone_SCOPE_VAR) { return scope }
  }
};

// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
standalone_pp$3.currentThisScope = function() {
  for (var i = this.scopeStack.length - 1;; i--) {
    var scope = this.scopeStack[i];
    if (scope.flags & standalone_SCOPE_VAR && !(scope.flags & standalone_SCOPE_ARROW)) { return scope }
  }
};

var standalone_acorn_Node = function Node(parser, pos, loc) {
  this.type = "";
  this.start = pos;
  this.end = 0;
  if (parser.options.locations)
    { this.loc = new standalone_SourceLocation(parser, loc); }
  if (parser.options.directSourceFile)
    { this.sourceFile = parser.options.directSourceFile; }
  if (parser.options.ranges)
    { this.range = [pos, 0]; }
};

// Start an AST node, attaching a start offset.

var standalone_pp$2 = standalone_Parser.prototype;

standalone_pp$2.startNode = function() {
  return new standalone_acorn_Node(this, this.start, this.startLoc)
};

standalone_pp$2.startNodeAt = function(pos, loc) {
  return new standalone_acorn_Node(this, pos, loc)
};

// Finish an AST node, adding `type` and `end` properties.

function standalone_finishNodeAt(node, type, pos, loc) {
  node.type = type;
  node.end = pos;
  if (this.options.locations)
    { node.loc.end = loc; }
  if (this.options.ranges)
    { node.range[1] = pos; }
  return node
}

standalone_pp$2.finishNode = function(node, type) {
  return standalone_finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
};

// Finish node at given position

standalone_pp$2.finishNodeAt = function(node, type, pos, loc) {
  return standalone_finishNodeAt.call(this, node, type, pos, loc)
};

standalone_pp$2.copyNode = function(node) {
  var newNode = new standalone_acorn_Node(this, node.start, this.startLoc);
  for (var prop in node) { newNode[prop] = node[prop]; }
  return newNode
};

// This file was generated by "bin/generate-unicode-script-values.js". Do not modify manually!
var standalone_scriptValuesAddedInUnicode = "Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz";

// This file contains Unicode properties extracted from the ECMAScript specification.
// The lists are extracted like so:
// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)

// #table-binary-unicode-properties
var standalone_ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
var standalone_ecma10BinaryProperties = standalone_ecma9BinaryProperties + " Extended_Pictographic";
var standalone_ecma11BinaryProperties = standalone_ecma10BinaryProperties;
var standalone_ecma12BinaryProperties = standalone_ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
var standalone_ecma13BinaryProperties = standalone_ecma12BinaryProperties;
var standalone_ecma14BinaryProperties = standalone_ecma13BinaryProperties;

var standalone_unicodeBinaryProperties = {
  9: standalone_ecma9BinaryProperties,
  10: standalone_ecma10BinaryProperties,
  11: standalone_ecma11BinaryProperties,
  12: standalone_ecma12BinaryProperties,
  13: standalone_ecma13BinaryProperties,
  14: standalone_ecma14BinaryProperties
};

// #table-binary-unicode-properties-of-strings
var standalone_ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";

var standalone_unicodeBinaryPropertiesOfStrings = {
  9: "",
  10: "",
  11: "",
  12: "",
  13: "",
  14: standalone_ecma14BinaryPropertiesOfStrings
};

// #table-unicode-general-category-values
var standalone_unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";

// #table-unicode-script-values
var standalone_ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
var standalone_ecma10ScriptValues = standalone_ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
var standalone_ecma11ScriptValues = standalone_ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
var standalone_ecma12ScriptValues = standalone_ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
var standalone_ecma13ScriptValues = standalone_ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
var standalone_ecma14ScriptValues = standalone_ecma13ScriptValues + " " + standalone_scriptValuesAddedInUnicode;

var standalone_unicodeScriptValues = {
  9: standalone_ecma9ScriptValues,
  10: standalone_ecma10ScriptValues,
  11: standalone_ecma11ScriptValues,
  12: standalone_ecma12ScriptValues,
  13: standalone_ecma13ScriptValues,
  14: standalone_ecma14ScriptValues
};

var standalone_acorn_data = {};
function standalone_buildUnicodeData(ecmaVersion) {
  var d = standalone_acorn_data[ecmaVersion] = {
    binary: standalone_wordsRegexp(standalone_unicodeBinaryProperties[ecmaVersion] + " " + standalone_unicodeGeneralCategoryValues),
    binaryOfStrings: standalone_wordsRegexp(standalone_unicodeBinaryPropertiesOfStrings[ecmaVersion]),
    nonBinary: {
      General_Category: standalone_wordsRegexp(standalone_unicodeGeneralCategoryValues),
      Script: standalone_wordsRegexp(standalone_unicodeScriptValues[ecmaVersion])
    }
  };
  d.nonBinary.Script_Extensions = d.nonBinary.Script;

  d.nonBinary.gc = d.nonBinary.General_Category;
  d.nonBinary.sc = d.nonBinary.Script;
  d.nonBinary.scx = d.nonBinary.Script_Extensions;
}

for (var standalone_i = 0, standalone_acorn_list = [9, 10, 11, 12, 13, 14]; standalone_i < standalone_acorn_list.length; standalone_i += 1) {
  var standalone_ecmaVersion = standalone_acorn_list[standalone_i];

  standalone_buildUnicodeData(standalone_ecmaVersion);
}

var standalone_pp$1 = standalone_Parser.prototype;

// Track disjunction structure to determine whether a duplicate
// capture group name is allowed because it is in a separate branch.
var standalone_BranchID = function BranchID(parent, base) {
  // Parent disjunction branch
  this.parent = parent;
  // Identifies this set of sibling branches
  this.base = base || this;
};

standalone_BranchID.prototype.separatedFrom = function separatedFrom (alt) {
  // A branch is separate from another branch if they or any of
  // their parents are siblings in a given disjunction
  for (var self = this; self; self = self.parent) {
    for (var other = alt; other; other = other.parent) {
      if (self.base === other.base && self !== other) { return true }
    }
  }
  return false
};

standalone_BranchID.prototype.sibling = function sibling () {
  return new standalone_BranchID(this.parent, this.base)
};

var standalone_RegExpValidationState = function RegExpValidationState(parser) {
  this.parser = parser;
  this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
  this.unicodeProperties = standalone_acorn_data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
  this.source = "";
  this.flags = "";
  this.start = 0;
  this.switchU = false;
  this.switchV = false;
  this.switchN = false;
  this.pos = 0;
  this.lastIntValue = 0;
  this.lastStringValue = "";
  this.lastAssertionIsQuantifiable = false;
  this.numCapturingParens = 0;
  this.maxBackReference = 0;
  this.groupNames = Object.create(null);
  this.backReferenceNames = [];
  this.branchID = null;
};

standalone_RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  var unicodeSets = flags.indexOf("v") !== -1;
  var unicode = flags.indexOf("u") !== -1;
  this.start = start | 0;
  this.source = pattern + "";
  this.flags = flags;
  if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
    this.switchU = true;
    this.switchV = true;
    this.switchN = true;
  } else {
    this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
    this.switchV = false;
    this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  }
};

standalone_RegExpValidationState.prototype.raise = function raise (message) {
  this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
};

// If u flag is given, this returns the code point at the index (it combines a surrogate pair).
// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
standalone_RegExpValidationState.prototype.at = function at (i, forceU) {
    if ( forceU === void 0 ) forceU = false;

  var s = this.source;
  var l = s.length;
  if (i >= l) {
    return -1
  }
  var c = s.charCodeAt(i);
  if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
    return c
  }
  var next = s.charCodeAt(i + 1);
  return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
};

standalone_RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
    if ( forceU === void 0 ) forceU = false;

  var s = this.source;
  var l = s.length;
  if (i >= l) {
    return l
  }
  var c = s.charCodeAt(i), next;
  if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
      (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
    return i + 1
  }
  return i + 2
};

standalone_RegExpValidationState.prototype.current = function current (forceU) {
    if ( forceU === void 0 ) forceU = false;

  return this.at(this.pos, forceU)
};

standalone_RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
    if ( forceU === void 0 ) forceU = false;

  return this.at(this.nextIndex(this.pos, forceU), forceU)
};

standalone_RegExpValidationState.prototype.advance = function advance (forceU) {
    if ( forceU === void 0 ) forceU = false;

  this.pos = this.nextIndex(this.pos, forceU);
};

standalone_RegExpValidationState.prototype.eat = function eat (ch, forceU) {
    if ( forceU === void 0 ) forceU = false;

  if (this.current(forceU) === ch) {
    this.advance(forceU);
    return true
  }
  return false
};

standalone_RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) {
    if ( forceU === void 0 ) forceU = false;

  var pos = this.pos;
  for (var i = 0, list = chs; i < list.length; i += 1) {
    var ch = list[i];

      var current = this.at(pos, forceU);
    if (current === -1 || current !== ch) {
      return false
    }
    pos = this.nextIndex(pos, forceU);
  }
  this.pos = pos;
  return true
};

/**
 * Validate the flags part of a given RegExpLiteral.
 *
 * @param {RegExpValidationState} state The state to validate RegExp.
 * @returns {void}
 */
standalone_pp$1.validateRegExpFlags = function(state) {
  var validFlags = state.validFlags;
  var flags = state.flags;

  var u = false;
  var v = false;

  for (var i = 0; i < flags.length; i++) {
    var flag = flags.charAt(i);
    if (validFlags.indexOf(flag) === -1) {
      this.raise(state.start, "Invalid regular expression flag");
    }
    if (flags.indexOf(flag, i + 1) > -1) {
      this.raise(state.start, "Duplicate regular expression flag");
    }
    if (flag === "u") { u = true; }
    if (flag === "v") { v = true; }
  }
  if (this.options.ecmaVersion >= 15 && u && v) {
    this.raise(state.start, "Invalid regular expression flag");
  }
};

function standalone_hasProp(obj) {
  for (var _ in obj) { return true }
  return false
}

/**
 * Validate the pattern part of a given RegExpLiteral.
 *
 * @param {RegExpValidationState} state The state to validate RegExp.
 * @returns {void}
 */
standalone_pp$1.validateRegExpPattern = function(state) {
  this.regexp_pattern(state);

  // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  // parsing contains a |GroupName|, reparse with the goal symbol
  // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  // exception if _P_ did not conform to the grammar, if any elements of _P_
  // were not matched by the parse, or if any Early Error conditions exist.
  if (!state.switchN && this.options.ecmaVersion >= 9 && standalone_hasProp(state.groupNames)) {
    state.switchN = true;
    this.regexp_pattern(state);
  }
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
standalone_pp$1.regexp_pattern = function(state) {
  state.pos = 0;
  state.lastIntValue = 0;
  state.lastStringValue = "";
  state.lastAssertionIsQuantifiable = false;
  state.numCapturingParens = 0;
  state.maxBackReference = 0;
  state.groupNames = Object.create(null);
  state.backReferenceNames.length = 0;
  state.branchID = null;

  this.regexp_disjunction(state);

  if (state.pos !== state.source.length) {
    // Make the same messages as V8.
    if (state.eat(0x29 /* ) */)) {
      state.raise("Unmatched ')'");
    }
    if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
      state.raise("Lone quantifier brackets");
    }
  }
  if (state.maxBackReference > state.numCapturingParens) {
    state.raise("Invalid escape");
  }
  for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
    var name = list[i];

    if (!state.groupNames[name]) {
      state.raise("Invalid named capture referenced");
    }
  }
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
standalone_pp$1.regexp_disjunction = function(state) {
  var trackDisjunction = this.options.ecmaVersion >= 16;
  if (trackDisjunction) { state.branchID = new standalone_BranchID(state.branchID, null); }
  this.regexp_alternative(state);
  while (state.eat(0x7C /* | */)) {
    if (trackDisjunction) { state.branchID = state.branchID.sibling(); }
    this.regexp_alternative(state);
  }
  if (trackDisjunction) { state.branchID = state.branchID.parent; }

  // Make the same message as V8.
  if (this.regexp_eatQuantifier(state, true)) {
    state.raise("Nothing to repeat");
  }
  if (state.eat(0x7B /* { */)) {
    state.raise("Lone quantifier brackets");
  }
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
standalone_pp$1.regexp_alternative = function(state) {
  while (state.pos < state.source.length && this.regexp_eatTerm(state)) {}
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
standalone_pp$1.regexp_eatTerm = function(state) {
  if (this.regexp_eatAssertion(state)) {
    // Handle `QuantifiableAssertion Quantifier` alternative.
    // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
    // is a QuantifiableAssertion.
    if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
      // Make the same message as V8.
      if (state.switchU) {
        state.raise("Invalid quantifier");
      }
    }
    return true
  }

  if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
    this.regexp_eatQuantifier(state);
    return true
  }

  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
standalone_pp$1.regexp_eatAssertion = function(state) {
  var start = state.pos;
  state.lastAssertionIsQuantifiable = false;

  // ^, $
  if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
    return true
  }

  // \b \B
  if (state.eat(0x5C /* \ */)) {
    if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
      return true
    }
    state.pos = start;
  }

  // Lookahead / Lookbehind
  if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
    var lookbehind = false;
    if (this.options.ecmaVersion >= 9) {
      lookbehind = state.eat(0x3C /* < */);
    }
    if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
      this.regexp_disjunction(state);
      if (!state.eat(0x29 /* ) */)) {
        state.raise("Unterminated group");
      }
      state.lastAssertionIsQuantifiable = !lookbehind;
      return true
    }
  }

  state.pos = start;
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
standalone_pp$1.regexp_eatQuantifier = function(state, noError) {
  if ( noError === void 0 ) noError = false;

  if (this.regexp_eatQuantifierPrefix(state, noError)) {
    state.eat(0x3F /* ? */);
    return true
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
standalone_pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  return (
    state.eat(0x2A /* * */) ||
    state.eat(0x2B /* + */) ||
    state.eat(0x3F /* ? */) ||
    this.regexp_eatBracedQuantifier(state, noError)
  )
};
standalone_pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  var start = state.pos;
  if (state.eat(0x7B /* { */)) {
    var min = 0, max = -1;
    if (this.regexp_eatDecimalDigits(state)) {
      min = state.lastIntValue;
      if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
        max = state.lastIntValue;
      }
      if (state.eat(0x7D /* } */)) {
        // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
        if (max !== -1 && max < min && !noError) {
          state.raise("numbers out of order in {} quantifier");
        }
        return true
      }
    }
    if (state.switchU && !noError) {
      state.raise("Incomplete quantifier");
    }
    state.pos = start;
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
standalone_pp$1.regexp_eatAtom = function(state) {
  return (
    this.regexp_eatPatternCharacters(state) ||
    state.eat(0x2E /* . */) ||
    this.regexp_eatReverseSolidusAtomEscape(state) ||
    this.regexp_eatCharacterClass(state) ||
    this.regexp_eatUncapturingGroup(state) ||
    this.regexp_eatCapturingGroup(state)
  )
};
standalone_pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  var start = state.pos;
  if (state.eat(0x5C /* \ */)) {
    if (this.regexp_eatAtomEscape(state)) {
      return true
    }
    state.pos = start;
  }
  return false
};
standalone_pp$1.regexp_eatUncapturingGroup = function(state) {
  var start = state.pos;
  if (state.eat(0x28 /* ( */)) {
    if (state.eat(0x3F /* ? */)) {
      if (this.options.ecmaVersion >= 16) {
        var addModifiers = this.regexp_eatModifiers(state);
        var hasHyphen = state.eat(0x2D /* - */);
        if (addModifiers || hasHyphen) {
          for (var i = 0; i < addModifiers.length; i++) {
            var modifier = addModifiers.charAt(i);
            if (addModifiers.indexOf(modifier, i + 1) > -1) {
              state.raise("Duplicate regular expression modifiers");
            }
          }
          if (hasHyphen) {
            var removeModifiers = this.regexp_eatModifiers(state);
            if (!addModifiers && !removeModifiers && state.current() === 0x3A /* : */) {
              state.raise("Invalid regular expression modifiers");
            }
            for (var i$1 = 0; i$1 < removeModifiers.length; i$1++) {
              var modifier$1 = removeModifiers.charAt(i$1);
              if (
                removeModifiers.indexOf(modifier$1, i$1 + 1) > -1 ||
                addModifiers.indexOf(modifier$1) > -1
              ) {
                state.raise("Duplicate regular expression modifiers");
              }
            }
          }
        }
      }
      if (state.eat(0x3A /* : */)) {
        this.regexp_disjunction(state);
        if (state.eat(0x29 /* ) */)) {
          return true
        }
        state.raise("Unterminated group");
      }
    }
    state.pos = start;
  }
  return false
};
standalone_pp$1.regexp_eatCapturingGroup = function(state) {
  if (state.eat(0x28 /* ( */)) {
    if (this.options.ecmaVersion >= 9) {
      this.regexp_groupSpecifier(state);
    } else if (state.current() === 0x3F /* ? */) {
      state.raise("Invalid group");
    }
    this.regexp_disjunction(state);
    if (state.eat(0x29 /* ) */)) {
      state.numCapturingParens += 1;
      return true
    }
    state.raise("Unterminated group");
  }
  return false
};
// RegularExpressionModifiers ::
//   [empty]
//   RegularExpressionModifiers RegularExpressionModifier
standalone_pp$1.regexp_eatModifiers = function(state) {
  var modifiers = "";
  var ch = 0;
  while ((ch = state.current()) !== -1 && standalone_isRegularExpressionModifier(ch)) {
    modifiers += standalone_codePointToString(ch);
    state.advance();
  }
  return modifiers
};
// RegularExpressionModifier :: one of
//   `i` `m` `s`
function standalone_isRegularExpressionModifier(ch) {
  return ch === 0x69 /* i */ || ch === 0x6d /* m */ || ch === 0x73 /* s */
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
standalone_pp$1.regexp_eatExtendedAtom = function(state) {
  return (
    state.eat(0x2E /* . */) ||
    this.regexp_eatReverseSolidusAtomEscape(state) ||
    this.regexp_eatCharacterClass(state) ||
    this.regexp_eatUncapturingGroup(state) ||
    this.regexp_eatCapturingGroup(state) ||
    this.regexp_eatInvalidBracedQuantifier(state) ||
    this.regexp_eatExtendedPatternCharacter(state)
  )
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
standalone_pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  if (this.regexp_eatBracedQuantifier(state, true)) {
    state.raise("Nothing to repeat");
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
standalone_pp$1.regexp_eatSyntaxCharacter = function(state) {
  var ch = state.current();
  if (standalone_isSyntaxCharacter(ch)) {
    state.lastIntValue = ch;
    state.advance();
    return true
  }
  return false
};
function standalone_isSyntaxCharacter(ch) {
  return (
    ch === 0x24 /* $ */ ||
    ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
    ch === 0x2E /* . */ ||
    ch === 0x3F /* ? */ ||
    ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
    ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  )
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
// But eat eager.
standalone_pp$1.regexp_eatPatternCharacters = function(state) {
  var start = state.pos;
  var ch = 0;
  while ((ch = state.current()) !== -1 && !standalone_isSyntaxCharacter(ch)) {
    state.advance();
  }
  return state.pos !== start
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
standalone_pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  var ch = state.current();
  if (
    ch !== -1 &&
    ch !== 0x24 /* $ */ &&
    !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
    ch !== 0x2E /* . */ &&
    ch !== 0x3F /* ? */ &&
    ch !== 0x5B /* [ */ &&
    ch !== 0x5E /* ^ */ &&
    ch !== 0x7C /* | */
  ) {
    state.advance();
    return true
  }
  return false
};

// GroupSpecifier ::
//   [empty]
//   `?` GroupName
standalone_pp$1.regexp_groupSpecifier = function(state) {
  if (state.eat(0x3F /* ? */)) {
    if (!this.regexp_eatGroupName(state)) { state.raise("Invalid group"); }
    var trackDisjunction = this.options.ecmaVersion >= 16;
    var known = state.groupNames[state.lastStringValue];
    if (known) {
      if (trackDisjunction) {
        for (var i = 0, list = known; i < list.length; i += 1) {
          var altID = list[i];

          if (!altID.separatedFrom(state.branchID))
            { state.raise("Duplicate capture group name"); }
        }
      } else {
        state.raise("Duplicate capture group name");
      }
    }
    if (trackDisjunction) {
      (known || (state.groupNames[state.lastStringValue] = [])).push(state.branchID);
    } else {
      state.groupNames[state.lastStringValue] = true;
    }
  }
};

// GroupName ::
//   `<` RegExpIdentifierName `>`
// Note: this updates `state.lastStringValue` property with the eaten name.
standalone_pp$1.regexp_eatGroupName = function(state) {
  state.lastStringValue = "";
  if (state.eat(0x3C /* < */)) {
    if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
      return true
    }
    state.raise("Invalid capture group name");
  }
  return false
};

// RegExpIdentifierName ::
//   RegExpIdentifierStart
//   RegExpIdentifierName RegExpIdentifierPart
// Note: this updates `state.lastStringValue` property with the eaten name.
standalone_pp$1.regexp_eatRegExpIdentifierName = function(state) {
  state.lastStringValue = "";
  if (this.regexp_eatRegExpIdentifierStart(state)) {
    state.lastStringValue += standalone_codePointToString(state.lastIntValue);
    while (this.regexp_eatRegExpIdentifierPart(state)) {
      state.lastStringValue += standalone_codePointToString(state.lastIntValue);
    }
    return true
  }
  return false
};

// RegExpIdentifierStart ::
//   UnicodeIDStart
//   `$`
//   `_`
//   `\` RegExpUnicodeEscapeSequence[+U]
standalone_pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  var start = state.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state.current(forceU);
  state.advance(forceU);

  if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
    ch = state.lastIntValue;
  }
  if (standalone_isRegExpIdentifierStart(ch)) {
    state.lastIntValue = ch;
    return true
  }

  state.pos = start;
  return false
};
function standalone_isRegExpIdentifierStart(ch) {
  return standalone_acorn_isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
}

// RegExpIdentifierPart ::
//   UnicodeIDContinue
//   `$`
//   `_`
//   `\` RegExpUnicodeEscapeSequence[+U]
//   <ZWNJ>
//   <ZWJ>
standalone_pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  var start = state.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state.current(forceU);
  state.advance(forceU);

  if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
    ch = state.lastIntValue;
  }
  if (standalone_isRegExpIdentifierPart(ch)) {
    state.lastIntValue = ch;
    return true
  }

  state.pos = start;
  return false
};
function standalone_isRegExpIdentifierPart(ch) {
  return standalone_isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
standalone_pp$1.regexp_eatAtomEscape = function(state) {
  if (
    this.regexp_eatBackReference(state) ||
    this.regexp_eatCharacterClassEscape(state) ||
    this.regexp_eatCharacterEscape(state) ||
    (state.switchN && this.regexp_eatKGroupName(state))
  ) {
    return true
  }
  if (state.switchU) {
    // Make the same message as V8.
    if (state.current() === 0x63 /* c */) {
      state.raise("Invalid unicode escape");
    }
    state.raise("Invalid escape");
  }
  return false
};
standalone_pp$1.regexp_eatBackReference = function(state) {
  var start = state.pos;
  if (this.regexp_eatDecimalEscape(state)) {
    var n = state.lastIntValue;
    if (state.switchU) {
      // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
      if (n > state.maxBackReference) {
        state.maxBackReference = n;
      }
      return true
    }
    if (n <= state.numCapturingParens) {
      return true
    }
    state.pos = start;
  }
  return false
};
standalone_pp$1.regexp_eatKGroupName = function(state) {
  if (state.eat(0x6B /* k */)) {
    if (this.regexp_eatGroupName(state)) {
      state.backReferenceNames.push(state.lastStringValue);
      return true
    }
    state.raise("Invalid named reference");
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
standalone_pp$1.regexp_eatCharacterEscape = function(state) {
  return (
    this.regexp_eatControlEscape(state) ||
    this.regexp_eatCControlLetter(state) ||
    this.regexp_eatZero(state) ||
    this.regexp_eatHexEscapeSequence(state) ||
    this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
    (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
    this.regexp_eatIdentityEscape(state)
  )
};
standalone_pp$1.regexp_eatCControlLetter = function(state) {
  var start = state.pos;
  if (state.eat(0x63 /* c */)) {
    if (this.regexp_eatControlLetter(state)) {
      return true
    }
    state.pos = start;
  }
  return false
};
standalone_pp$1.regexp_eatZero = function(state) {
  if (state.current() === 0x30 /* 0 */ && !standalone_acorn_isDecimalDigit(state.lookahead())) {
    state.lastIntValue = 0;
    state.advance();
    return true
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
standalone_pp$1.regexp_eatControlEscape = function(state) {
  var ch = state.current();
  if (ch === 0x74 /* t */) {
    state.lastIntValue = 0x09; /* \t */
    state.advance();
    return true
  }
  if (ch === 0x6E /* n */) {
    state.lastIntValue = 0x0A; /* \n */
    state.advance();
    return true
  }
  if (ch === 0x76 /* v */) {
    state.lastIntValue = 0x0B; /* \v */
    state.advance();
    return true
  }
  if (ch === 0x66 /* f */) {
    state.lastIntValue = 0x0C; /* \f */
    state.advance();
    return true
  }
  if (ch === 0x72 /* r */) {
    state.lastIntValue = 0x0D; /* \r */
    state.advance();
    return true
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
standalone_pp$1.regexp_eatControlLetter = function(state) {
  var ch = state.current();
  if (standalone_isControlLetter(ch)) {
    state.lastIntValue = ch % 0x20;
    state.advance();
    return true
  }
  return false
};
function standalone_isControlLetter(ch) {
  return (
    (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
    (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  )
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
standalone_pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  if ( forceU === void 0 ) forceU = false;

  var start = state.pos;
  var switchU = forceU || state.switchU;

  if (state.eat(0x75 /* u */)) {
    if (this.regexp_eatFixedHexDigits(state, 4)) {
      var lead = state.lastIntValue;
      if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
        var leadSurrogateEnd = state.pos;
        if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
          var trail = state.lastIntValue;
          if (trail >= 0xDC00 && trail <= 0xDFFF) {
            state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
            return true
          }
        }
        state.pos = leadSurrogateEnd;
        state.lastIntValue = lead;
      }
      return true
    }
    if (
      switchU &&
      state.eat(0x7B /* { */) &&
      this.regexp_eatHexDigits(state) &&
      state.eat(0x7D /* } */) &&
      standalone_isValidUnicode(state.lastIntValue)
    ) {
      return true
    }
    if (switchU) {
      state.raise("Invalid unicode escape");
    }
    state.pos = start;
  }

  return false
};
function standalone_isValidUnicode(ch) {
  return ch >= 0 && ch <= 0x10FFFF
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
standalone_pp$1.regexp_eatIdentityEscape = function(state) {
  if (state.switchU) {
    if (this.regexp_eatSyntaxCharacter(state)) {
      return true
    }
    if (state.eat(0x2F /* / */)) {
      state.lastIntValue = 0x2F; /* / */
      return true
    }
    return false
  }

  var ch = state.current();
  if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
    state.lastIntValue = ch;
    state.advance();
    return true
  }

  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
standalone_pp$1.regexp_eatDecimalEscape = function(state) {
  state.lastIntValue = 0;
  var ch = state.current();
  if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
    do {
      state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
      state.advance();
    } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
    return true
  }
  return false
};

// Return values used by character set parsing methods, needed to
// forbid negation of sets that can match strings.
var standalone_CharSetNone = 0; // Nothing parsed
var standalone_CharSetOk = 1; // Construct parsed, cannot contain strings
var standalone_CharSetString = 2; // Construct parsed, can contain strings

// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
standalone_pp$1.regexp_eatCharacterClassEscape = function(state) {
  var ch = state.current();

  if (standalone_isCharacterClassEscape(ch)) {
    state.lastIntValue = -1;
    state.advance();
    return standalone_CharSetOk
  }

  var negate = false;
  if (
    state.switchU &&
    this.options.ecmaVersion >= 9 &&
    ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */)
  ) {
    state.lastIntValue = -1;
    state.advance();
    var result;
    if (
      state.eat(0x7B /* { */) &&
      (result = this.regexp_eatUnicodePropertyValueExpression(state)) &&
      state.eat(0x7D /* } */)
    ) {
      if (negate && result === standalone_CharSetString) { state.raise("Invalid property name"); }
      return result
    }
    state.raise("Invalid property name");
  }

  return standalone_CharSetNone
};

function standalone_isCharacterClassEscape(ch) {
  return (
    ch === 0x64 /* d */ ||
    ch === 0x44 /* D */ ||
    ch === 0x73 /* s */ ||
    ch === 0x53 /* S */ ||
    ch === 0x77 /* w */ ||
    ch === 0x57 /* W */
  )
}

// UnicodePropertyValueExpression ::
//   UnicodePropertyName `=` UnicodePropertyValue
//   LoneUnicodePropertyNameOrValue
standalone_pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  var start = state.pos;

  // UnicodePropertyName `=` UnicodePropertyValue
  if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
    var name = state.lastStringValue;
    if (this.regexp_eatUnicodePropertyValue(state)) {
      var value = state.lastStringValue;
      this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
      return standalone_CharSetOk
    }
  }
  state.pos = start;

  // LoneUnicodePropertyNameOrValue
  if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
    var nameOrValue = state.lastStringValue;
    return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue)
  }
  return standalone_CharSetNone
};

standalone_pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  if (!standalone_hasOwn(state.unicodeProperties.nonBinary, name))
    { state.raise("Invalid property name"); }
  if (!state.unicodeProperties.nonBinary[name].test(value))
    { state.raise("Invalid property value"); }
};

standalone_pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  if (state.unicodeProperties.binary.test(nameOrValue)) { return standalone_CharSetOk }
  if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return standalone_CharSetString }
  state.raise("Invalid property name");
};

// UnicodePropertyName ::
//   UnicodePropertyNameCharacters
standalone_pp$1.regexp_eatUnicodePropertyName = function(state) {
  var ch = 0;
  state.lastStringValue = "";
  while (standalone_isUnicodePropertyNameCharacter(ch = state.current())) {
    state.lastStringValue += standalone_codePointToString(ch);
    state.advance();
  }
  return state.lastStringValue !== ""
};

function standalone_isUnicodePropertyNameCharacter(ch) {
  return standalone_isControlLetter(ch) || ch === 0x5F /* _ */
}

// UnicodePropertyValue ::
//   UnicodePropertyValueCharacters
standalone_pp$1.regexp_eatUnicodePropertyValue = function(state) {
  var ch = 0;
  state.lastStringValue = "";
  while (standalone_isUnicodePropertyValueCharacter(ch = state.current())) {
    state.lastStringValue += standalone_codePointToString(ch);
    state.advance();
  }
  return state.lastStringValue !== ""
};
function standalone_isUnicodePropertyValueCharacter(ch) {
  return standalone_isUnicodePropertyNameCharacter(ch) || standalone_acorn_isDecimalDigit(ch)
}

// LoneUnicodePropertyNameOrValue ::
//   UnicodePropertyValueCharacters
standalone_pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  return this.regexp_eatUnicodePropertyValue(state)
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
standalone_pp$1.regexp_eatCharacterClass = function(state) {
  if (state.eat(0x5B /* [ */)) {
    var negate = state.eat(0x5E /* ^ */);
    var result = this.regexp_classContents(state);
    if (!state.eat(0x5D /* ] */))
      { state.raise("Unterminated character class"); }
    if (negate && result === standalone_CharSetString)
      { state.raise("Negated character class may contain strings"); }
    return true
  }
  return false
};

// https://tc39.es/ecma262/#prod-ClassContents
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
standalone_pp$1.regexp_classContents = function(state) {
  if (state.current() === 0x5D /* ] */) { return standalone_CharSetOk }
  if (state.switchV) { return this.regexp_classSetExpression(state) }
  this.regexp_nonEmptyClassRanges(state);
  return standalone_CharSetOk
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
standalone_pp$1.regexp_nonEmptyClassRanges = function(state) {
  while (this.regexp_eatClassAtom(state)) {
    var left = state.lastIntValue;
    if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
      var right = state.lastIntValue;
      if (state.switchU && (left === -1 || right === -1)) {
        state.raise("Invalid character class");
      }
      if (left !== -1 && right !== -1 && left > right) {
        state.raise("Range out of order in character class");
      }
    }
  }
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
standalone_pp$1.regexp_eatClassAtom = function(state) {
  var start = state.pos;

  if (state.eat(0x5C /* \ */)) {
    if (this.regexp_eatClassEscape(state)) {
      return true
    }
    if (state.switchU) {
      // Make the same message as V8.
      var ch$1 = state.current();
      if (ch$1 === 0x63 /* c */ || standalone_acorn_isOctalDigit(ch$1)) {
        state.raise("Invalid class escape");
      }
      state.raise("Invalid escape");
    }
    state.pos = start;
  }

  var ch = state.current();
  if (ch !== 0x5D /* ] */) {
    state.lastIntValue = ch;
    state.advance();
    return true
  }

  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
standalone_pp$1.regexp_eatClassEscape = function(state) {
  var start = state.pos;

  if (state.eat(0x62 /* b */)) {
    state.lastIntValue = 0x08; /* <BS> */
    return true
  }

  if (state.switchU && state.eat(0x2D /* - */)) {
    state.lastIntValue = 0x2D; /* - */
    return true
  }

  if (!state.switchU && state.eat(0x63 /* c */)) {
    if (this.regexp_eatClassControlLetter(state)) {
      return true
    }
    state.pos = start;
  }

  return (
    this.regexp_eatCharacterClassEscape(state) ||
    this.regexp_eatCharacterEscape(state)
  )
};

// https://tc39.es/ecma262/#prod-ClassSetExpression
// https://tc39.es/ecma262/#prod-ClassUnion
// https://tc39.es/ecma262/#prod-ClassIntersection
// https://tc39.es/ecma262/#prod-ClassSubtraction
standalone_pp$1.regexp_classSetExpression = function(state) {
  var result = standalone_CharSetOk, subResult;
  if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) {
    if (subResult === standalone_CharSetString) { result = standalone_CharSetString; }
    // https://tc39.es/ecma262/#prod-ClassIntersection
    var start = state.pos;
    while (state.eatChars([0x26, 0x26] /* && */)) {
      if (
        state.current() !== 0x26 /* & */ &&
        (subResult = this.regexp_eatClassSetOperand(state))
      ) {
        if (subResult !== standalone_CharSetString) { result = standalone_CharSetOk; }
        continue
      }
      state.raise("Invalid character in character class");
    }
    if (start !== state.pos) { return result }
    // https://tc39.es/ecma262/#prod-ClassSubtraction
    while (state.eatChars([0x2D, 0x2D] /* -- */)) {
      if (this.regexp_eatClassSetOperand(state)) { continue }
      state.raise("Invalid character in character class");
    }
    if (start !== state.pos) { return result }
  } else {
    state.raise("Invalid character in character class");
  }
  // https://tc39.es/ecma262/#prod-ClassUnion
  for (;;) {
    if (this.regexp_eatClassSetRange(state)) { continue }
    subResult = this.regexp_eatClassSetOperand(state);
    if (!subResult) { return result }
    if (subResult === standalone_CharSetString) { result = standalone_CharSetString; }
  }
};

// https://tc39.es/ecma262/#prod-ClassSetRange
standalone_pp$1.regexp_eatClassSetRange = function(state) {
  var start = state.pos;
  if (this.regexp_eatClassSetCharacter(state)) {
    var left = state.lastIntValue;
    if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) {
      var right = state.lastIntValue;
      if (left !== -1 && right !== -1 && left > right) {
        state.raise("Range out of order in character class");
      }
      return true
    }
    state.pos = start;
  }
  return false
};

// https://tc39.es/ecma262/#prod-ClassSetOperand
standalone_pp$1.regexp_eatClassSetOperand = function(state) {
  if (this.regexp_eatClassSetCharacter(state)) { return standalone_CharSetOk }
  return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state)
};

// https://tc39.es/ecma262/#prod-NestedClass
standalone_pp$1.regexp_eatNestedClass = function(state) {
  var start = state.pos;
  if (state.eat(0x5B /* [ */)) {
    var negate = state.eat(0x5E /* ^ */);
    var result = this.regexp_classContents(state);
    if (state.eat(0x5D /* ] */)) {
      if (negate && result === standalone_CharSetString) {
        state.raise("Negated character class may contain strings");
      }
      return result
    }
    state.pos = start;
  }
  if (state.eat(0x5C /* \ */)) {
    var result$1 = this.regexp_eatCharacterClassEscape(state);
    if (result$1) {
      return result$1
    }
    state.pos = start;
  }
  return null
};

// https://tc39.es/ecma262/#prod-ClassStringDisjunction
standalone_pp$1.regexp_eatClassStringDisjunction = function(state) {
  var start = state.pos;
  if (state.eatChars([0x5C, 0x71] /* \q */)) {
    if (state.eat(0x7B /* { */)) {
      var result = this.regexp_classStringDisjunctionContents(state);
      if (state.eat(0x7D /* } */)) {
        return result
      }
    } else {
      // Make the same message as V8.
      state.raise("Invalid escape");
    }
    state.pos = start;
  }
  return null
};

// https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents
standalone_pp$1.regexp_classStringDisjunctionContents = function(state) {
  var result = this.regexp_classString(state);
  while (state.eat(0x7C /* | */)) {
    if (this.regexp_classString(state) === standalone_CharSetString) { result = standalone_CharSetString; }
  }
  return result
};

// https://tc39.es/ecma262/#prod-ClassString
// https://tc39.es/ecma262/#prod-NonEmptyClassString
standalone_pp$1.regexp_classString = function(state) {
  var count = 0;
  while (this.regexp_eatClassSetCharacter(state)) { count++; }
  return count === 1 ? standalone_CharSetOk : standalone_CharSetString
};

// https://tc39.es/ecma262/#prod-ClassSetCharacter
standalone_pp$1.regexp_eatClassSetCharacter = function(state) {
  var start = state.pos;
  if (state.eat(0x5C /* \ */)) {
    if (
      this.regexp_eatCharacterEscape(state) ||
      this.regexp_eatClassSetReservedPunctuator(state)
    ) {
      return true
    }
    if (state.eat(0x62 /* b */)) {
      state.lastIntValue = 0x08; /* <BS> */
      return true
    }
    state.pos = start;
    return false
  }
  var ch = state.current();
  if (ch < 0 || ch === state.lookahead() && standalone_isClassSetReservedDoublePunctuatorCharacter(ch)) { return false }
  if (standalone_isClassSetSyntaxCharacter(ch)) { return false }
  state.advance();
  state.lastIntValue = ch;
  return true
};

// https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator
function standalone_isClassSetReservedDoublePunctuatorCharacter(ch) {
  return (
    ch === 0x21 /* ! */ ||
    ch >= 0x23 /* # */ && ch <= 0x26 /* & */ ||
    ch >= 0x2A /* * */ && ch <= 0x2C /* , */ ||
    ch === 0x2E /* . */ ||
    ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ ||
    ch === 0x5E /* ^ */ ||
    ch === 0x60 /* ` */ ||
    ch === 0x7E /* ~ */
  )
}

// https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter
function standalone_isClassSetSyntaxCharacter(ch) {
  return (
    ch === 0x28 /* ( */ ||
    ch === 0x29 /* ) */ ||
    ch === 0x2D /* - */ ||
    ch === 0x2F /* / */ ||
    ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ ||
    ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  )
}

// https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
standalone_pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
  var ch = state.current();
  if (standalone_isClassSetReservedPunctuator(ch)) {
    state.lastIntValue = ch;
    state.advance();
    return true
  }
  return false
};

// https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
function standalone_isClassSetReservedPunctuator(ch) {
  return (
    ch === 0x21 /* ! */ ||
    ch === 0x23 /* # */ ||
    ch === 0x25 /* % */ ||
    ch === 0x26 /* & */ ||
    ch === 0x2C /* , */ ||
    ch === 0x2D /* - */ ||
    ch >= 0x3A /* : */ && ch <= 0x3E /* > */ ||
    ch === 0x40 /* @ */ ||
    ch === 0x60 /* ` */ ||
    ch === 0x7E /* ~ */
  )
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
standalone_pp$1.regexp_eatClassControlLetter = function(state) {
  var ch = state.current();
  if (standalone_acorn_isDecimalDigit(ch) || ch === 0x5F /* _ */) {
    state.lastIntValue = ch % 0x20;
    state.advance();
    return true
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
standalone_pp$1.regexp_eatHexEscapeSequence = function(state) {
  var start = state.pos;
  if (state.eat(0x78 /* x */)) {
    if (this.regexp_eatFixedHexDigits(state, 2)) {
      return true
    }
    if (state.switchU) {
      state.raise("Invalid escape");
    }
    state.pos = start;
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
standalone_pp$1.regexp_eatDecimalDigits = function(state) {
  var start = state.pos;
  var ch = 0;
  state.lastIntValue = 0;
  while (standalone_acorn_isDecimalDigit(ch = state.current())) {
    state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
    state.advance();
  }
  return state.pos !== start
};
function standalone_acorn_isDecimalDigit(ch) {
  return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
standalone_pp$1.regexp_eatHexDigits = function(state) {
  var start = state.pos;
  var ch = 0;
  state.lastIntValue = 0;
  while (standalone_acorn_isHexDigit(ch = state.current())) {
    state.lastIntValue = 16 * state.lastIntValue + standalone_hexToInt(ch);
    state.advance();
  }
  return state.pos !== start
};
function standalone_acorn_isHexDigit(ch) {
  return (
    (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
    (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
    (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  )
}
function standalone_hexToInt(ch) {
  if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
    return 10 + (ch - 0x41 /* A */)
  }
  if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
    return 10 + (ch - 0x61 /* a */)
  }
  return ch - 0x30 /* 0 */
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
// Allows only 0-377(octal) i.e. 0-255(decimal).
standalone_pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  if (this.regexp_eatOctalDigit(state)) {
    var n1 = state.lastIntValue;
    if (this.regexp_eatOctalDigit(state)) {
      var n2 = state.lastIntValue;
      if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
        state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
      } else {
        state.lastIntValue = n1 * 8 + n2;
      }
    } else {
      state.lastIntValue = n1;
    }
    return true
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
standalone_pp$1.regexp_eatOctalDigit = function(state) {
  var ch = state.current();
  if (standalone_acorn_isOctalDigit(ch)) {
    state.lastIntValue = ch - 0x30; /* 0 */
    state.advance();
    return true
  }
  state.lastIntValue = 0;
  return false
};
function standalone_acorn_isOctalDigit(ch) {
  return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
standalone_pp$1.regexp_eatFixedHexDigits = function(state, length) {
  var start = state.pos;
  state.lastIntValue = 0;
  for (var i = 0; i < length; ++i) {
    var ch = state.current();
    if (!standalone_acorn_isHexDigit(ch)) {
      state.pos = start;
      return false
    }
    state.lastIntValue = 16 * state.lastIntValue + standalone_hexToInt(ch);
    state.advance();
  }
  return true
};

// Object type used to represent tokens. Note that normally, tokens
// simply exist as properties on the parser object. This is only
// used for the onToken callback and the external tokenizer.

var standalone_Token = function Token(p) {
  this.type = p.type;
  this.value = p.value;
  this.start = p.start;
  this.end = p.end;
  if (p.options.locations)
    { this.loc = new standalone_SourceLocation(p, p.startLoc, p.endLoc); }
  if (p.options.ranges)
    { this.range = [p.start, p.end]; }
};

// ## Tokenizer

var standalone_pp = standalone_Parser.prototype;

// Move to the next token

standalone_pp.next = function(ignoreEscapeSequenceInKeyword) {
  if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
    { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  if (this.options.onToken)
    { this.options.onToken(new standalone_Token(this)); }

  this.lastTokEnd = this.end;
  this.lastTokStart = this.start;
  this.lastTokEndLoc = this.endLoc;
  this.lastTokStartLoc = this.startLoc;
  this.nextToken();
};

standalone_pp.getToken = function() {
  this.next();
  return new standalone_Token(this)
};

// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined")
  { standalone_pp[Symbol.iterator] = function() {
    var this$1$1 = this;

    return {
      next: function () {
        var token = this$1$1.getToken();
        return {
          done: token.type === standalone_types$1.eof,
          value: token
        }
      }
    }
  }; }

// Toggle strict mode. Re-reads the next number or string to please
// pedantic tests (`"use strict"; 010;` should fail).

// Read a single token, updating the parser object's token-related
// properties.

standalone_pp.nextToken = function() {
  var curContext = this.curContext();
  if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }

  this.start = this.pos;
  if (this.options.locations) { this.startLoc = this.curPosition(); }
  if (this.pos >= this.input.length) { return this.finishToken(standalone_types$1.eof) }

  if (curContext.override) { return curContext.override(this) }
  else { this.readToken(this.fullCharCodeAtPos()); }
};

standalone_pp.readToken = function(code) {
  // Identifier or keyword. '\uXXXX' sequences are allowed in
  // identifiers, so '\' also dispatches to that.
  if (standalone_acorn_isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
    { return this.readWord() }

  return this.getTokenFromCode(code)
};

standalone_pp.fullCharCodeAtPos = function() {
  var code = this.input.charCodeAt(this.pos);
  if (code <= 0xd7ff || code >= 0xdc00) { return code }
  var next = this.input.charCodeAt(this.pos + 1);
  return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
};

standalone_pp.skipBlockComment = function() {
  var startLoc = this.options.onComment && this.curPosition();
  var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  this.pos = end + 2;
  if (this.options.locations) {
    for (var nextBreak = (void 0), pos = start; (nextBreak = standalone_nextLineBreak(this.input, pos, this.pos)) > -1;) {
      ++this.curLine;
      pos = this.lineStart = nextBreak;
    }
  }
  if (this.options.onComment)
    { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
                           startLoc, this.curPosition()); }
};

standalone_pp.skipLineComment = function(startSkip) {
  var start = this.pos;
  var startLoc = this.options.onComment && this.curPosition();
  var ch = this.input.charCodeAt(this.pos += startSkip);
  while (this.pos < this.input.length && !standalone_isNewLine(ch)) {
    ch = this.input.charCodeAt(++this.pos);
  }
  if (this.options.onComment)
    { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
                           startLoc, this.curPosition()); }
};

// Called at the start of the parse and after every token. Skips
// whitespace and comments, and.

standalone_pp.skipSpace = function() {
  loop: while (this.pos < this.input.length) {
    var ch = this.input.charCodeAt(this.pos);
    switch (ch) {
    case 32: case 160: // ' '
      ++this.pos;
      break
    case 13:
      if (this.input.charCodeAt(this.pos + 1) === 10) {
        ++this.pos;
      }
    case 10: case 8232: case 8233:
      ++this.pos;
      if (this.options.locations) {
        ++this.curLine;
        this.lineStart = this.pos;
      }
      break
    case 47: // '/'
      switch (this.input.charCodeAt(this.pos + 1)) {
      case 42: // '*'
        this.skipBlockComment();
        break
      case 47:
        this.skipLineComment(2);
        break
      default:
        break loop
      }
      break
    default:
      if (ch > 8 && ch < 14 || ch >= 5760 && standalone_nonASCIIwhitespace.test(String.fromCharCode(ch))) {
        ++this.pos;
      } else {
        break loop
      }
    }
  }
};

// Called at the end of every token. Sets `end`, `val`, and
// maintains `context` and `exprAllowed`, and skips the space after
// the token, so that the next one's `start` will point at the
// right position.

standalone_pp.finishToken = function(type, val) {
  this.end = this.pos;
  if (this.options.locations) { this.endLoc = this.curPosition(); }
  var prevType = this.type;
  this.type = type;
  this.value = val;

  this.updateContext(prevType);
};

// ### Token reading

// This is the function that is called to fetch the next token. It
// is somewhat obscure, because it works in character codes rather
// than characters, and because operator parsing has been inlined
// into it.
//
// All in the name of speed.
//
standalone_pp.readToken_dot = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next >= 48 && next <= 57) { return this.readNumber(true) }
  var next2 = this.input.charCodeAt(this.pos + 2);
  if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
    this.pos += 3;
    return this.finishToken(standalone_types$1.ellipsis)
  } else {
    ++this.pos;
    return this.finishToken(standalone_types$1.dot)
  }
};

standalone_pp.readToken_slash = function() { // '/'
  var next = this.input.charCodeAt(this.pos + 1);
  if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  if (next === 61) { return this.finishOp(standalone_types$1.assign, 2) }
  return this.finishOp(standalone_types$1.slash, 1)
};

standalone_pp.readToken_mult_modulo_exp = function(code) { // '%*'
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  var tokentype = code === 42 ? standalone_types$1.star : standalone_types$1.modulo;

  // exponentiation operator ** and **=
  if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
    ++size;
    tokentype = standalone_types$1.starstar;
    next = this.input.charCodeAt(this.pos + 2);
  }

  if (next === 61) { return this.finishOp(standalone_types$1.assign, size + 1) }
  return this.finishOp(tokentype, size)
};

standalone_pp.readToken_pipe_amp = function(code) { // '|&'
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code) {
    if (this.options.ecmaVersion >= 12) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 === 61) { return this.finishOp(standalone_types$1.assign, 3) }
    }
    return this.finishOp(code === 124 ? standalone_types$1.logicalOR : standalone_types$1.logicalAND, 2)
  }
  if (next === 61) { return this.finishOp(standalone_types$1.assign, 2) }
  return this.finishOp(code === 124 ? standalone_types$1.bitwiseOR : standalone_types$1.bitwiseAND, 1)
};

standalone_pp.readToken_caret = function() { // '^'
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) { return this.finishOp(standalone_types$1.assign, 2) }
  return this.finishOp(standalone_types$1.bitwiseXOR, 1)
};

standalone_pp.readToken_plus_min = function(code) { // '+-'
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code) {
    if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
        (this.lastTokEnd === 0 || standalone_lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
      // A `-->` line comment
      this.skipLineComment(3);
      this.skipSpace();
      return this.nextToken()
    }
    return this.finishOp(standalone_types$1.incDec, 2)
  }
  if (next === 61) { return this.finishOp(standalone_types$1.assign, 2) }
  return this.finishOp(standalone_types$1.plusMin, 1)
};

standalone_pp.readToken_lt_gt = function(code) { // '<>'
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  if (next === code) {
    size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
    if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(standalone_types$1.assign, size + 1) }
    return this.finishOp(standalone_types$1.bitShift, size)
  }
  if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
      this.input.charCodeAt(this.pos + 3) === 45) {
    // `<!--`, an XML-style comment that should be interpreted as a line comment
    this.skipLineComment(4);
    this.skipSpace();
    return this.nextToken()
  }
  if (next === 61) { size = 2; }
  return this.finishOp(standalone_types$1.relational, size)
};

standalone_pp.readToken_eq_excl = function(code) { // '=!'
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) { return this.finishOp(standalone_types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
    this.pos += 2;
    return this.finishToken(standalone_types$1.arrow)
  }
  return this.finishOp(code === 61 ? standalone_types$1.eq : standalone_types$1.prefix, 1)
};

standalone_pp.readToken_question = function() { // '?'
  var ecmaVersion = this.options.ecmaVersion;
  if (ecmaVersion >= 11) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 46) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 < 48 || next2 > 57) { return this.finishOp(standalone_types$1.questionDot, 2) }
    }
    if (next === 63) {
      if (ecmaVersion >= 12) {
        var next2$1 = this.input.charCodeAt(this.pos + 2);
        if (next2$1 === 61) { return this.finishOp(standalone_types$1.assign, 3) }
      }
      return this.finishOp(standalone_types$1.coalesce, 2)
    }
  }
  return this.finishOp(standalone_types$1.question, 1)
};

standalone_pp.readToken_numberSign = function() { // '#'
  var ecmaVersion = this.options.ecmaVersion;
  var code = 35; // '#'
  if (ecmaVersion >= 13) {
    ++this.pos;
    code = this.fullCharCodeAtPos();
    if (standalone_acorn_isIdentifierStart(code, true) || code === 92 /* '\' */) {
      return this.finishToken(standalone_types$1.privateId, this.readWord1())
    }
  }

  this.raise(this.pos, "Unexpected character '" + standalone_codePointToString(code) + "'");
};

standalone_pp.getTokenFromCode = function(code) {
  switch (code) {
  // The interpretation of a dot depends on whether it is followed
  // by a digit or another two dots.
  case 46: // '.'
    return this.readToken_dot()

  // Punctuation tokens.
  case 40: ++this.pos; return this.finishToken(standalone_types$1.parenL)
  case 41: ++this.pos; return this.finishToken(standalone_types$1.parenR)
  case 59: ++this.pos; return this.finishToken(standalone_types$1.semi)
  case 44: ++this.pos; return this.finishToken(standalone_types$1.comma)
  case 91: ++this.pos; return this.finishToken(standalone_types$1.bracketL)
  case 93: ++this.pos; return this.finishToken(standalone_types$1.bracketR)
  case 123: ++this.pos; return this.finishToken(standalone_types$1.braceL)
  case 125: ++this.pos; return this.finishToken(standalone_types$1.braceR)
  case 58: ++this.pos; return this.finishToken(standalone_types$1.colon)

  case 96: // '`'
    if (this.options.ecmaVersion < 6) { break }
    ++this.pos;
    return this.finishToken(standalone_types$1.backQuote)

  case 48: // '0'
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
    if (this.options.ecmaVersion >= 6) {
      if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
      if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
    }

  // Anything else beginning with a digit is an integer, octal
  // number, or float.
  case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
    return this.readNumber(false)

  // Quotes produce strings.
  case 34: case 39: // '"', "'"
    return this.readString(code)

  // Operators are parsed inline in tiny state machines. '=' (61) is
  // often referred to. `finishOp` simply skips the amount of
  // characters it is given as second argument, and returns a token
  // of the type given by its first argument.
  case 47: // '/'
    return this.readToken_slash()

  case 37: case 42: // '%*'
    return this.readToken_mult_modulo_exp(code)

  case 124: case 38: // '|&'
    return this.readToken_pipe_amp(code)

  case 94: // '^'
    return this.readToken_caret()

  case 43: case 45: // '+-'
    return this.readToken_plus_min(code)

  case 60: case 62: // '<>'
    return this.readToken_lt_gt(code)

  case 61: case 33: // '=!'
    return this.readToken_eq_excl(code)

  case 63: // '?'
    return this.readToken_question()

  case 126: // '~'
    return this.finishOp(standalone_types$1.prefix, 1)

  case 35: // '#'
    return this.readToken_numberSign()
  }

  this.raise(this.pos, "Unexpected character '" + standalone_codePointToString(code) + "'");
};

standalone_pp.finishOp = function(type, size) {
  var str = this.input.slice(this.pos, this.pos + size);
  this.pos += size;
  return this.finishToken(type, str)
};

standalone_pp.readRegexp = function() {
  var escaped, inClass, start = this.pos;
  for (;;) {
    if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
    var ch = this.input.charAt(this.pos);
    if (standalone_lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
    if (!escaped) {
      if (ch === "[") { inClass = true; }
      else if (ch === "]" && inClass) { inClass = false; }
      else if (ch === "/" && !inClass) { break }
      escaped = ch === "\\";
    } else { escaped = false; }
    ++this.pos;
  }
  var pattern = this.input.slice(start, this.pos);
  ++this.pos;
  var flagsStart = this.pos;
  var flags = this.readWord1();
  if (this.containsEsc) { this.unexpected(flagsStart); }

  // Validate pattern
  var state = this.regexpState || (this.regexpState = new standalone_RegExpValidationState(this));
  state.reset(start, pattern, flags);
  this.validateRegExpFlags(state);
  this.validateRegExpPattern(state);

  // Create Literal#value property value.
  var value = null;
  try {
    value = new RegExp(pattern, flags);
  } catch (e) {
    // ESTree requires null if it failed to instantiate RegExp object.
    // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  }

  return this.finishToken(standalone_types$1.regexp, {pattern: pattern, flags: flags, value: value})
};

// Read an integer in the given radix. Return null if zero digits
// were read, the integer value otherwise. When `len` is given, this
// will return `null` unless the integer has exactly `len` digits.

standalone_pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  // `len` is used for character escape sequences. In that case, disallow separators.
  var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;

  // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  // and isn't fraction part nor exponent part. In that case, if the first digit
  // is zero then disallow separators.
  var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;

  var start = this.pos, total = 0, lastCode = 0;
  for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
    var code = this.input.charCodeAt(this.pos), val = (void 0);

    if (allowSeparators && code === 95) {
      if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
      if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
      if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
      lastCode = code;
      continue
    }

    if (code >= 97) { val = code - 97 + 10; } // a
    else if (code >= 65) { val = code - 65 + 10; } // A
    else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
    else { val = Infinity; }
    if (val >= radix) { break }
    lastCode = code;
    total = total * radix + val;
  }

  if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  if (this.pos === start || len != null && this.pos - start !== len) { return null }

  return total
};

function standalone_stringToNumber(str, isLegacyOctalNumericLiteral) {
  if (isLegacyOctalNumericLiteral) {
    return parseInt(str, 8)
  }

  // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  return parseFloat(str.replace(/_/g, ""))
}

function standalone_stringToBigInt(str) {
  if (typeof BigInt !== "function") {
    return null
  }

  // `BigInt(value)` throws syntax error if the string contains numeric separators.
  return BigInt(str.replace(/_/g, ""))
}

standalone_pp.readRadixNumber = function(radix) {
  var start = this.pos;
  this.pos += 2; // 0x
  var val = this.readInt(radix);
  if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
    val = standalone_stringToBigInt(this.input.slice(start, this.pos));
    ++this.pos;
  } else if (standalone_acorn_isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  return this.finishToken(standalone_types$1.num, val)
};

// Read an integer, octal integer, or floating-point number.

standalone_pp.readNumber = function(startsWithDot) {
  var start = this.pos;
  if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  if (octal && this.strict) { this.raise(start, "Invalid number"); }
  var next = this.input.charCodeAt(this.pos);
  if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
    var val$1 = standalone_stringToBigInt(this.input.slice(start, this.pos));
    ++this.pos;
    if (standalone_acorn_isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
    return this.finishToken(standalone_types$1.num, val$1)
  }
  if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  if (next === 46 && !octal) { // '.'
    ++this.pos;
    this.readInt(10);
    next = this.input.charCodeAt(this.pos);
  }
  if ((next === 69 || next === 101) && !octal) { // 'eE'
    next = this.input.charCodeAt(++this.pos);
    if (next === 43 || next === 45) { ++this.pos; } // '+-'
    if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  }
  if (standalone_acorn_isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }

  var val = standalone_stringToNumber(this.input.slice(start, this.pos), octal);
  return this.finishToken(standalone_types$1.num, val)
};

// Read a string value, interpreting backslash-escapes.

standalone_pp.readCodePoint = function() {
  var ch = this.input.charCodeAt(this.pos), code;

  if (ch === 123) { // '{'
    if (this.options.ecmaVersion < 6) { this.unexpected(); }
    var codePos = ++this.pos;
    code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
    ++this.pos;
    if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  } else {
    code = this.readHexChar(4);
  }
  return code
};

standalone_pp.readString = function(quote) {
  var out = "", chunkStart = ++this.pos;
  for (;;) {
    if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === quote) { break }
    if (ch === 92) { // '\'
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(false);
      chunkStart = this.pos;
    } else if (ch === 0x2028 || ch === 0x2029) {
      if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
      ++this.pos;
      if (this.options.locations) {
        this.curLine++;
        this.lineStart = this.pos;
      }
    } else {
      if (standalone_isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
      ++this.pos;
    }
  }
  out += this.input.slice(chunkStart, this.pos++);
  return this.finishToken(standalone_types$1.string, out)
};

// Reads template string tokens.

var standalone_INVALID_TEMPLATE_ESCAPE_ERROR = {};

standalone_pp.tryReadTemplateToken = function() {
  this.inTemplateElement = true;
  try {
    this.readTmplToken();
  } catch (err) {
    if (err === standalone_INVALID_TEMPLATE_ESCAPE_ERROR) {
      this.readInvalidTemplateToken();
    } else {
      throw err
    }
  }

  this.inTemplateElement = false;
};

standalone_pp.invalidStringToken = function(position, message) {
  if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
    throw standalone_INVALID_TEMPLATE_ESCAPE_ERROR
  } else {
    this.raise(position, message);
  }
};

standalone_pp.readTmplToken = function() {
  var out = "", chunkStart = this.pos;
  for (;;) {
    if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
      if (this.pos === this.start && (this.type === standalone_types$1.template || this.type === standalone_types$1.invalidTemplate)) {
        if (ch === 36) {
          this.pos += 2;
          return this.finishToken(standalone_types$1.dollarBraceL)
        } else {
          ++this.pos;
          return this.finishToken(standalone_types$1.backQuote)
        }
      }
      out += this.input.slice(chunkStart, this.pos);
      return this.finishToken(standalone_types$1.template, out)
    }
    if (ch === 92) { // '\'
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(true);
      chunkStart = this.pos;
    } else if (standalone_isNewLine(ch)) {
      out += this.input.slice(chunkStart, this.pos);
      ++this.pos;
      switch (ch) {
      case 13:
        if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
      case 10:
        out += "\n";
        break
      default:
        out += String.fromCharCode(ch);
        break
      }
      if (this.options.locations) {
        ++this.curLine;
        this.lineStart = this.pos;
      }
      chunkStart = this.pos;
    } else {
      ++this.pos;
    }
  }
};

// Reads a template token to search for the end, without validating any escape sequences
standalone_pp.readInvalidTemplateToken = function() {
  for (; this.pos < this.input.length; this.pos++) {
    switch (this.input[this.pos]) {
    case "\\":
      ++this.pos;
      break

    case "$":
      if (this.input[this.pos + 1] !== "{") { break }
      // fall through
    case "`":
      return this.finishToken(standalone_types$1.invalidTemplate, this.input.slice(this.start, this.pos))

    case "\r":
      if (this.input[this.pos + 1] === "\n") { ++this.pos; }
      // fall through
    case "\n": case "\u2028": case "\u2029":
      ++this.curLine;
      this.lineStart = this.pos + 1;
      break
    }
  }
  this.raise(this.start, "Unterminated template");
};

// Used to read escaped characters

standalone_pp.readEscapedChar = function(inTemplate) {
  var ch = this.input.charCodeAt(++this.pos);
  ++this.pos;
  switch (ch) {
  case 110: return "\n" // 'n' -> '\n'
  case 114: return "\r" // 'r' -> '\r'
  case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  case 117: return standalone_codePointToString(this.readCodePoint()) // 'u'
  case 116: return "\t" // 't' -> '\t'
  case 98: return "\b" // 'b' -> '\b'
  case 118: return "\u000b" // 'v' -> '\u000b'
  case 102: return "\f" // 'f' -> '\f'
  case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  case 10: // ' \n'
    if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
    return ""
  case 56:
  case 57:
    if (this.strict) {
      this.invalidStringToken(
        this.pos - 1,
        "Invalid escape sequence"
      );
    }
    if (inTemplate) {
      var codePos = this.pos - 1;

      this.invalidStringToken(
        codePos,
        "Invalid escape sequence in template string"
      );
    }
  default:
    if (ch >= 48 && ch <= 55) {
      var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
      var octal = parseInt(octalStr, 8);
      if (octal > 255) {
        octalStr = octalStr.slice(0, -1);
        octal = parseInt(octalStr, 8);
      }
      this.pos += octalStr.length - 1;
      ch = this.input.charCodeAt(this.pos);
      if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
        this.invalidStringToken(
          this.pos - 1 - octalStr.length,
          inTemplate
            ? "Octal literal in template string"
            : "Octal literal in strict mode"
        );
      }
      return String.fromCharCode(octal)
    }
    if (standalone_isNewLine(ch)) {
      // Unicode new line characters after \ get removed from output in both
      // template literals and strings
      if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
      return ""
    }
    return String.fromCharCode(ch)
  }
};

// Used to read character escape sequences ('\x', '\u', '\U').

standalone_pp.readHexChar = function(len) {
  var codePos = this.pos;
  var n = this.readInt(16, len);
  if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  return n
};

// Read an identifier, and return it as a string. Sets `this.containsEsc`
// to whether the word contained a '\u' escape.
//
// Incrementally adds only escaped chars, adding other chunks as-is
// as a micro-optimization.

standalone_pp.readWord1 = function() {
  this.containsEsc = false;
  var word = "", first = true, chunkStart = this.pos;
  var astral = this.options.ecmaVersion >= 6;
  while (this.pos < this.input.length) {
    var ch = this.fullCharCodeAtPos();
    if (standalone_isIdentifierChar(ch, astral)) {
      this.pos += ch <= 0xffff ? 1 : 2;
    } else if (ch === 92) { // "\"
      this.containsEsc = true;
      word += this.input.slice(chunkStart, this.pos);
      var escStart = this.pos;
      if (this.input.charCodeAt(++this.pos) !== 117) // "u"
        { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
      ++this.pos;
      var esc = this.readCodePoint();
      if (!(first ? standalone_acorn_isIdentifierStart : standalone_isIdentifierChar)(esc, astral))
        { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
      word += standalone_codePointToString(esc);
      chunkStart = this.pos;
    } else {
      break
    }
    first = false;
  }
  return word + this.input.slice(chunkStart, this.pos)
};

// Read an identifier or keyword token. Will check for reserved
// words when necessary.

standalone_pp.readWord = function() {
  var word = this.readWord1();
  var type = standalone_types$1.name;
  if (this.keywords.test(word)) {
    type = standalone_acorn_keywords[word];
  }
  return this.finishToken(type, word)
};

// Acorn is a tiny, fast JavaScript parser written in JavaScript.
//
// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
// various contributors and released under an MIT license.
//
// Git repositories for Acorn are available at
//
//     http://marijnhaverbeke.nl/git/acorn
//     https://github.com/acornjs/acorn.git
//
// Please use the [github bug tracker][ghbt] to report issues.
//
// [ghbt]: https://github.com/acornjs/acorn/issues
//
// [walk]: util/walk.js


var standalone_acorn_version = "8.14.0";

standalone_Parser.acorn = {
  Parser: standalone_Parser,
  version: standalone_acorn_version,
  defaultOptions: standalone_defaultOptions,
  Position: standalone_Position,
  SourceLocation: standalone_SourceLocation,
  getLineInfo: standalone_getLineInfo,
  Node: standalone_acorn_Node,
  TokenType: standalone_TokenType,
  tokTypes: standalone_types$1,
  keywordTypes: standalone_acorn_keywords,
  TokContext: standalone_TokContext,
  tokContexts: standalone_acorn_types,
  isIdentifierChar: standalone_isIdentifierChar,
  isIdentifierStart: standalone_acorn_isIdentifierStart,
  Token: standalone_Token,
  isNewLine: standalone_isNewLine,
  lineBreak: standalone_lineBreak,
  lineBreakG: standalone_lineBreakG,
  nonASCIIwhitespace: standalone_nonASCIIwhitespace
};

// The main exported interface (under `self.acorn` when in the
// browser) is a `parse` function that takes a code string and returns
// an abstract syntax tree as specified by the [ESTree spec][estree].
//
// [estree]: https://github.com/estree/estree

function standalone_acorn_parse(input, options) {
  return standalone_Parser.parse(input, options)
}

// This function tries to parse a single expression at a given
// offset in a string. Useful for parsing mixed-language formats
// that embed JavaScript expressions.

function standalone_parseExpressionAt(input, pos, options) {
  return standalone_Parser.parseExpressionAt(input, pos, options)
}

// Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenizer` export provides an interface to the tokenizer.

function standalone_tokenizer(input, options) {
  return standalone_Parser.tokenizer(input, options)
}



;// ../../node_modules/arquero/src/expression/constants.js
/* harmony default export */ const standalone_expression_constants = ({
  undefined: 'void(0)',
  Infinity:  'Number.POSITIVE_INFINITY',
  NaN:       'Number.NaN',
  E:         'Math.E',
  LN2:       'Math.LN2',
  LN10:      'Math.LN10',
  LOG2E:     'Math.LOG2E',
  LOG10E:    'Math.LOG10E',
  PI:        'Math.PI',
  SQRT1_2:   'Math.SQRT1_2',
  SQRT2:     'Math.SQRT2'
});
;// ../../node_modules/arquero/src/expression/parse-expression.js















const standalone_PARSER_OPT = { ecmaVersion: 11 };
const standalone_DEFAULT_PARAM_ID = '$';
const standalone_DEFAULT_TUPLE_ID = 'd';
const standalone_DEFAULT_TUPLE_ID1 = 'd1';
const standalone_DEFAULT_TUPLE_ID2 = 'd2';

const standalone_NO = msg => (node, ctx) => ctx.error(node, msg + ' not allowed');
const standalone_ERROR_AGGREGATE = standalone_NO('Aggregate function');
const standalone_ERROR_WINDOW = standalone_NO('Window function');
const standalone_ERROR_ARGUMENT = 'Invalid argument';
const standalone_ERROR_COLUMN = 'Invalid column reference';
const standalone_ERROR_AGGRONLY = standalone_ERROR_COLUMN + ' (must be input to an aggregate function)';
const standalone_ERROR_FUNCTION = 'Invalid function call';
const standalone_ERROR_MEMBER = 'Invalid member expression';
const standalone_ERROR_OP_PARAMETER = 'Invalid operator parameter';
const standalone_ERROR_PARAM = 'Invalid param reference';
const standalone_ERROR_VARIABLE = 'Invalid variable reference';
const standalone_ERROR_VARIABLE_OP = 'Variable not accessible in operator call';
const standalone_ERROR_DECLARATION = 'Unsupported variable declaration';
const standalone_ERROR_DESTRUCTURE = 'Unsupported destructuring pattern';
const standalone_ERROR_CLOSURE = 'Table expressions do not support closures';
const standalone_ERROR_ESCAPE = 'Use aq.escape(fn) to use a function as-is (including closures)';
const standalone_ERROR_USE_PARAMS = 'use table.params({ name: value }) to define dynamic parameters';
const standalone_ERROR_ADD_FUNCTION = 'use aq.addFunction(name, fn) to add new op functions';
const standalone_ERROR_VARIABLE_NOTE = `\nNote: ${standalone_ERROR_CLOSURE}. ${standalone_ERROR_ESCAPE}, or ${standalone_ERROR_USE_PARAMS}.`;
const standalone_ERROR_FUNCTION_NOTE = `\nNote: ${standalone_ERROR_CLOSURE}. ${standalone_ERROR_ESCAPE}, or ${standalone_ERROR_ADD_FUNCTION}.`;
const standalone_ERROR_ROW_OBJECT = `The ${standalone_row_object_ROW_OBJECT} method is not valid in multi-table expressions.`;

function standalone_parse_expression_parseExpression(ctx, spec) {
  const ast = standalone_parseAST(spec);
  let node = ctx.root = ast;
  ctx.spec = spec;
  ctx.tuple = null;
  ctx.tuple1 = null;
  ctx.tuple2 = null;
  ctx.$param = null;
  ctx.$op = 0;
  ctx.scope = new Set();
  ctx.paramsRef = new Map();
  ctx.columnRef = new Map();

  // parse input column parameters
  // if no function def, assume default tuple identifiers
  if (standalone_isFunctionExpression(node)) {
    standalone_parseFunction(node, ctx);
    node = node.body;
  } else if (ctx.join) {
    ctx.scope.add(ctx.tuple1 = standalone_DEFAULT_TUPLE_ID1);
    ctx.scope.add(ctx.tuple2 = standalone_DEFAULT_TUPLE_ID2);
    ctx.scope.add(ctx.$param = standalone_DEFAULT_PARAM_ID);
  } else {
    ctx.scope.add(ctx.tuple = standalone_DEFAULT_TUPLE_ID);
    ctx.scope.add(ctx.$param = standalone_DEFAULT_PARAM_ID);
  }

  // rewrite column references & function calls
  standalone_walk(node, ctx, standalone_parse_expression_visitors);

  return ctx.root;
}

function standalone_parseAST(expr) {
  try {
    const code = expr.field ? standalone_parse_expression_fieldRef(expr)
      : standalone_is_array(expr) ? standalone_to_string(expr)
      : expr;
    return standalone_acorn_parse(`expr=(${code})`, standalone_PARSER_OPT).body[0].expression.right;
  } catch (err) {
    standalone_util_error(`Expression parse error: ${expr+''}`, err);
  }
}

function standalone_parse_expression_fieldRef(expr) {
  const col = JSON.stringify(expr+'');
  return !(expr.table || 0) ? `d=>d[${col}]` : `(a,b)=>b[${col}]`;
}

const standalone_parse_expression_visitors = {
  FunctionDeclaration: standalone_NO('Function definitions'),
  ForStatement: standalone_NO('For loops'),
  ForOfStatement: standalone_NO('For-of loops'),
  ForInStatement: standalone_NO('For-in loops'),
  WhileStatement: standalone_NO('While loops'),
  DoWhileStatement: standalone_NO('Do-while loops'),
  AwaitExpression: standalone_NO('Await expressions'),
  ArrowFunctionExpression: standalone_NO('Function definitions'),
  AssignmentExpression: standalone_NO('Assignments'),
  FunctionExpression: standalone_NO('Function definitions'),
  NewExpression: standalone_NO('Use of "new"'),
  UpdateExpression: standalone_NO('Update expressions'),

  VariableDeclarator(node, ctx) {
    standalone_handleDeclaration(node.id, ctx);
  },
  Identifier(node, ctx, parent) {
    if (standalone_handleIdentifier(node, ctx, parent) && !ctx.scope.has(node.name)) {
      // handle identifier passed responsibility here
      // raise error if identifier not defined in scope
      ctx.error(node, standalone_ERROR_VARIABLE, standalone_ERROR_VARIABLE_NOTE);
    }
  },
  CallExpression(node, ctx) {
    const name = standalone_functionName(node.callee);
    const def = standalone_getAggregate(name) || standalone_getWindow(name);

    // parse operator and rewrite invocation
    if (def) {
      if ((ctx.join || ctx.aggregate === false) && standalone_hasAggregate(def)) {
        standalone_ERROR_AGGREGATE(node, ctx);
      }
      if ((ctx.join || ctx.window === false) && standalone_hasWindow(def)) {
        standalone_ERROR_WINDOW(node, ctx);
      }

      ctx.$op = 1;
      if (ctx.ast) {
        standalone_updateFunctionNode(node, name, ctx);
        node.arguments.forEach(arg => standalone_walk(arg, ctx, standalone_opVisitors));
      } else {
        const op = ctx.op(standalone_parse_expression_parseOperator(ctx, def, name, node.arguments));
        Object.assign(node, { type: standalone_constants_Op, name: op.id });
      }
      ctx.$op = 0;
      return false;
    } else if (standalone_hasFunction(name)) {
      standalone_updateFunctionNode(node, name, ctx);
    } else {
      ctx.error(node, standalone_ERROR_FUNCTION, standalone_ERROR_FUNCTION_NOTE);
    }
  },
  MemberExpression(node, ctx, parent) {
    const { object, property } = node;

    // bail if left head is not an identifier
    // in this case we will recurse and handle it later
    if (!standalone_is(standalone_constants_Identifier, object)) return;
    const { name } = object;

    // allow use of Math prefix to access constant values
    if (standalone_isMath(node) && standalone_is(standalone_constants_Identifier, property)
        && standalone_util_has(standalone_expression_constants, property.name)) {
      standalone_updateConstantNode(node, property.name);
      return;
    }

    const index = name === ctx.tuple ? 0
      : name === ctx.tuple1 ? 1
      : name === ctx.tuple2 ? 2
      : -1;

    if (index >= 0) {
      // replace member expression with column ref
      return standalone_spliceMember(node, index, ctx, standalone_checkColumn, parent);
    } else if (name === ctx.$param) {
      // replace member expression with param ref
      return standalone_spliceMember(node, index, ctx, standalone_checkParam);
    } else if (ctx.paramsRef.has(name)) {
      standalone_updateParameterNode(node, ctx.paramsRef.get(name));
    } else if (ctx.columnRef.has(name)) {
      standalone_updateColumnNode(object, name, ctx, node);
    } else if (standalone_util_has(ctx.params, name)) {
      standalone_updateParameterNode(object, name);
    }
  }
};

function standalone_spliceMember(node, index, ctx, check, parent) {
  const { property, computed } = node;
  let name;

  if (!computed) {
    name = property.name;
  } else if (standalone_is(standalone_constants_Literal, property)) {
    name = property.value;
  } else try {
    name = ctx.param(property);
  } catch (e) {
    ctx.error(node, standalone_ERROR_MEMBER);
  }

  check(node, name, index, ctx, parent);
  return false;
}

const standalone_opVisitors = {
  ...standalone_parse_expression_visitors,
  VariableDeclarator: standalone_NO('Variable declaration in operator call'),
  Identifier(node, ctx, parent) {
    if (standalone_handleIdentifier(node, ctx, parent)) {
      ctx.error(node, standalone_ERROR_VARIABLE_OP);
    }
  },
  CallExpression(node, ctx) {
    const name = standalone_functionName(node.callee);

    // rewrite if built-in function
    if (standalone_hasFunction(name)) {
      standalone_updateFunctionNode(node, name, ctx);
    } else {
      ctx.error(node, standalone_ERROR_FUNCTION, standalone_ERROR_FUNCTION_NOTE);
    }
  }
};

function standalone_parseFunction(node, ctx) {
  if (node.generator) standalone_NO('Generator functions')(node, ctx);
  if (node.async) standalone_NO('Async functions')(node, ctx);

  const { params } = node;
  const len = params.length;
  const setc = index => (name, key) => ctx.columnRef.set(name, [key, index]);
  const setp = (name, key) => ctx.paramsRef.set(name, key);

  if (!len) {
    // do nothing
  } else if (ctx.join) {
    standalone_parseRef(ctx, params[0], 'tuple1', setc(1));
    if (len > 1) standalone_parseRef(ctx, params[1], 'tuple2', setc(2));
    if (len > 2) standalone_parseRef(ctx, params[2], '$param', setp);
  } else {
    standalone_parseRef(ctx, params[0], 'tuple', setc(0));
    if (len > 1) standalone_parseRef(ctx, params[1], '$param', setp);
  }

  ctx.root = node.body;
}

function standalone_parseRef(ctx, node, refName, alias) {
  if (standalone_is(standalone_constants_Identifier, node)) {
    ctx.scope.add(node.name);
    ctx[refName] = node.name;
  } else if (standalone_is(standalone_ObjectPattern, node)) {
    node.properties.forEach(p => {
      const key = standalone_is(standalone_constants_Identifier, p.key) ? p.key.name
        : standalone_is(standalone_constants_Literal, p.key) ? p.key.value
        : ctx.error(p, standalone_ERROR_ARGUMENT);
      if (!standalone_is(standalone_constants_Identifier, p.value)) {
        ctx.error(p.value, standalone_ERROR_DESTRUCTURE);
      }
      alias(p.value.name, key);
    });
  }
}

function standalone_parse_expression_parseOperator(ctx, def, name, args) {
  const fields = [];
  const params = [];
  const idxFields = def.param[0] || 0;
  const idxParams = idxFields + (def.param[1] || 0);

  args.forEach((arg, index) => {
    if (index < idxFields) {
      standalone_walk(arg, ctx, standalone_opVisitors);
      fields.push(ctx.field(arg));
    } else if (index < idxParams) {
      standalone_walk(arg, ctx, standalone_opVisitors);
      params.push(ctx.param(arg));
    } else {
      ctx.error(arg, standalone_ERROR_OP_PARAMETER);
    }
  });

  return { name, fields, params, ...(ctx.spec.window || {}) };
}

function standalone_functionName(node) {
  return standalone_is(standalone_constants_Identifier, node) ? node.name
    : !standalone_is(standalone_constants_MemberExpression, node) ? null
    : standalone_isMath(node) ? standalone_rewriteMath(node.property.name)
    : node.property.name;
}

function standalone_isMath(node) {
  return standalone_is(standalone_constants_Identifier, node.object) && node.object.name === 'Math';
}

function standalone_rewriteMath(name) {
  return name === 'max' ? 'greatest'
    : name === 'min' ? 'least'
    : name;
}

function standalone_handleIdentifier(node, ctx, parent) {
  const { name } = node;

  if (standalone_is(standalone_constants_MemberExpression, parent) && parent.property === node) {
    // do nothing: check head node, not nested properties
  } else if (standalone_is(standalone_constants_Property, parent) && parent.key === node) {
    // do nothing: identifiers allowed in object expressions
  } else if (ctx.paramsRef.has(name)) {
    standalone_updateParameterNode(node, ctx.paramsRef.get(name));
  } else if (ctx.columnRef.has(name)) {
    standalone_updateColumnNode(node, name, ctx, parent);
  } else if (standalone_util_has(ctx.params, name)) {
    standalone_updateParameterNode(node, name);
  } else if (standalone_util_has(standalone_expression_constants, name)) {
    standalone_updateConstantNode(node, name);
  } else {
    return true;
  }
}

function standalone_checkColumn(node, name, index, ctx, parent) {
  // check column existence if we have a backing table
  const table = index === 0 ? ctx.table
    : index > 0 ? ctx.join[index - 1]
    : null;
  const col = table && table.column(name);
  if (table && !col) {
    ctx.error(node, standalone_ERROR_COLUMN);
  }

  // check if column reference is valid in current context
  if (ctx.aggronly && !ctx.$op) {
    ctx.error(node, standalone_ERROR_AGGRONLY);
  }

  // rewrite ast node as a column access
  standalone_rewrite(node, name, index, col, parent);
}

function standalone_updateColumnNode(node, key, ctx, parent) {
  const [name, index] = ctx.columnRef.get(key);
  standalone_checkColumn(node, name, index, ctx, parent);
}

function standalone_checkParam(node, name, index, ctx) {
  if (ctx.params && !standalone_util_has(ctx.params, name)) {
    ctx.error(node, standalone_ERROR_PARAM);
  }
  standalone_updateParameterNode(node, name);
}

function standalone_updateParameterNode(node, name) {
  node.type = standalone_Parameter;
  node.name = name;
}

function standalone_updateConstantNode(node, name) {
  node.type = standalone_Constant;
  node.name = name;
  node.raw = standalone_expression_constants[name];
}

function standalone_updateFunctionNode(node, name, ctx) {
  if (name === standalone_row_object_ROW_OBJECT) {
    const t = ctx.table;
    if (!t) ctx.error(node, standalone_ERROR_ROW_OBJECT);
    standalone_rowObjectExpression(node,
      node.arguments.length
        ? node.arguments.map(node => {
            const col = ctx.param(node);
            const name = standalone_is_number(col) ? t.columnName(col) : col;
            if (!t.column(name)) ctx.error(node, standalone_ERROR_COLUMN);
            return name;
          })
        : t.columnNames()
    );
  } else {
    node.callee = { type: standalone_constants_Function, name };
  }
}

function standalone_handleDeclaration(node, ctx) {
  if (standalone_is(standalone_constants_Identifier, node)) {
    ctx.scope.add(node.name);
  } else if (standalone_is(standalone_ArrayPattern, node)) {
    node.elements.forEach(elm => standalone_handleDeclaration(elm, ctx));
  } else if (standalone_is(standalone_ObjectPattern, node)) {
    node.properties.forEach(prop => standalone_handleDeclaration(prop.value, ctx));
  } else {
    ctx.error(node.id, standalone_ERROR_DECLARATION);
  }
}
;// ../../node_modules/arquero/src/expression/parse.js












const standalone_ANNOTATE = { [standalone_constants_Column]: 1, [standalone_constants_Op]: 1 };

/* harmony default export */ function standalone_expression_parse(input, opt = {}) {
  const generate = opt.generate || standalone_expression_codegen;
  const compiler = opt.compiler || standalone_expression_compile;
  const params = standalone_getParams(opt);
  const fields = {};
  const opcall = {};
  const names = [];
  const exprs = [];
  let fieldId = 0;
  let opId = -1;

  const compileExpr = opt.join ? compiler.join
    : opt.index == 1 ? compiler.expr2
    : compiler.expr;

  // parser context
  const ctx = {
    op(op) {
      const key = standalone_opKey(op);
      return opcall[key] || (op.id = ++opId, opcall[key] = op);
    },
    field(node) {
      const code = generate(node);
      return fields[code] || (fields[code] = ++fieldId);
    },
    param(node) {
      return standalone_is(standalone_constants_Literal, node)
        ? node.value
        : compiler.param(generate(node), params);
    },
    value(name, node) {
      names.push(name);
      const e = node.escape || (opt.ast
        ? standalone_clean(node)
        : compileExpr(generate(node), params));
      exprs.push(e);
      // annotate expression if it is a direct column or op access
      // this permits downstream optimizations
      if (standalone_ANNOTATE[node.type] && e !== node && standalone_is_object(e)) {
        e.field = node.name;
      }
    },
    error(node, msg, note = '') {
      // both expresions and fields are parsed
      // with added code prefixes of length 6!
      const i = node.start - 6;
      const j = node.end - 6;
      const snippet = String(ctx.spec).slice(i, j);
      standalone_util_error(`${msg}: "${snippet}"${note}`);
    }
  };

  // copy all options to context, potentially overwriting methods
  Object.assign(ctx, opt, { params });

  // parse each expression
  for (const [name, value] of standalone_util_entries(input)) {
    ctx.value(
      name + '',
      value.escape
        ? standalone_parse_escape(ctx, value, params)
        : standalone_parse_expression_parseExpression(ctx, value)
    );
  }

  // return expression asts if requested
  if (opt.ast) {
    return { names, exprs };
  }

  // compile input field accessors
  const f = [];
  for (const key in fields) {
    f[fields[key]] = compiler.expr(key, params);
  }

  // resolve input fields to operations
  const ops = Object.values(opcall);
  ops.forEach(op => op.fields = op.fields.map(id => f[id]));

  return { names, exprs, ops };
}

function standalone_opKey(op) {
  let key = `${op.name}(${op.fields.concat(op.params).join(',')})`;
  if (op.frame) {
    const frame = op.frame.map(v => Number.isFinite(v) ? Math.abs(v) : -1);
    key += `[${frame},${!!op.peers}]`;
  }
  return key;
}

function standalone_getParams(opt) {
  return (opt.table ? standalone_getTableParams(opt.table)
    : opt.join ? {
        ...standalone_getTableParams(opt.join[1]),
        ...standalone_getTableParams(opt.join[0])
      }
    : {}) || {};
}

function standalone_getTableParams(table) {
  return table && standalone_util_is_function(table.params) ? table.params() : {};
}
;// ../../node_modules/arquero/src/query/constants.js
const standalone_Expr = 'Expr';
const standalone_ExprList = 'ExprList';
const standalone_ExprNumber = 'ExprNumber';
const standalone_ExprObject = 'ExprObject';
const standalone_JoinKeys = 'JoinKeys';
const standalone_JoinValues = 'JoinValues';
const standalone_Options = 'Options';
const standalone_OrderbyKeys = 'OrderKeys';
const standalone_SelectionList = 'SelectionList';
const standalone_TableRef = 'TableRef';
const standalone_TableRefList = 'TableRefList';

const standalone_constants_Descending = 'Descending';
const standalone_constants_Query = 'Query';
const standalone_Selection = 'Selection';
const standalone_constants_Verb = 'Verb';
const standalone_constants_Window = 'Window';
;// ../../node_modules/arquero/src/helpers/wrap.js


/**
 * Annotate an expression in an object wrapper.
 * @param {string|Function|object} expr An expression to annotate.
 * @param {object} properties The properties to annotate with.
 * @return {object} A new wrapped expression object.
 */
/* harmony default export */ function standalone_helpers_wrap(expr, properties) {
  return expr && expr.expr
    ? new standalone_Wrapper({ ...expr, ...properties })
    : new standalone_Wrapper(properties, expr);
}

class standalone_Wrapper {
  constructor(properties, expr) {
    this.expr = expr;
    Object.assign(this, properties);
  }
  toString() {
    return String(this.expr);
  }
  toObject() {
    return {
      ...this,
      expr: this.toString(),
      ...(standalone_util_is_function(this.expr) ? { func: true } : {})
    };
  }
}
;// ../../node_modules/arquero/src/helpers/desc.js


/**
 * Annotate a table expression to indicate descending sort order.
 * @param {string|Function|object} expr The table expression to annotate.
 * @return {object} A wrapped expression indicating descending sort.
 * @example desc('colA')
 * @example desc(d => d.colA)
 */
/* harmony default export */ function standalone_desc(expr) {
  return standalone_helpers_wrap(expr, { desc: true });
}
;// ../../node_modules/arquero/src/helpers/field.js


/**
 * Annotate an expression to indicate it is a string field reference.
 * @param {string|object} expr The column name, or an existing wrapped
 *  expression for a column name.
 * @param {string} [name] The column name to use. If provided, will
 *  overwrite the input expression value.
 * @param {number} [table=0] The table index of the field, in case of
 *  expressions over multiple tables.
 * @return A wrapped expression for a named column.
 * @example field('colA')
 */
/* harmony default export */ function standalone_helpers_field(expr, name, table = 0) {
  const props = table ? { field: true, table } : { field: true };
  return standalone_helpers_wrap(
    expr,
    name ? { expr: name, ...props } : props
  );
}
;// ../../node_modules/arquero/src/helpers/rolling.js


/**
 * Annotate a table expression to compute rolling aggregate or window
 * functions within a sliding window frame. For example, to specify a
 * rolling 7-day average centered on the current day, use rolling with
 * a frame value of [-3, 3].
 * @param {string|Function|object} expr The table expression to annotate.
 * @param {[number?, number?]} [frame=[-Infinity, 0]] The sliding window frame
 *  offsets. Each entry indicates an offset from the current value. If an
 *  entry is non-finite, the frame will be unbounded in that direction,
 *  including all preceding or following values. If unspecified, the frame
 *  will include the current values and all preceding values.
 * @param {boolean} [includePeers=false] Indicates if the sliding window frame
 *  should ignore peer (tied) values. If false (the default), the window frame
 *  boundaries are insensitive to peer values. If `true`, the window frame
 *  expands to include all peers. This parameter only affects operations that
 *  depend on the window frame: aggregate functions and the first_value,
 *  last_value, and nth_value window functions.
 * @return A new wrapped expression annotated with rolling window parameters.
 * @example rolling(d => mean(d.colA), [-3, 3])
 * @example rolling(d => last_value(d.colA), null, true)
 */
/* harmony default export */ function standalone_rolling(expr, frame, includePeers) {
  return standalone_helpers_wrap(expr, {
    window: {
      frame: frame || [-Infinity, 0],
      peers: !!includePeers
    }
  });
}
;// ../../node_modules/arquero/src/query/util.js














function standalone_util_func(expr) {
  const f = d => d;
  f.toString = () => expr;
  return f;
}

function standalone_getTable(catalog, ref) {
  ref = ref && standalone_util_is_function(ref.query) ? ref.query() : ref;
  return ref && standalone_util_is_function(ref.evaluate)
    ? ref.evaluate(null, catalog)
    : catalog(ref);
}

function standalone_isSelection(value) {
  return standalone_is_object(value) && (
    standalone_is_array(value.all) ||
    standalone_is_array(value.matches) ||
    standalone_is_array(value.not) ||
    standalone_is_array(value.range)
  );
}

function standalone_util_toObject(value) {
  return value && standalone_util_is_function(value.toObject) ? value.toObject()
    : standalone_util_is_function(value) ? { expr: String(value), func: true }
    : standalone_is_array(value) ? value.map(standalone_util_toObject)
    : standalone_is_object(value) ? standalone_map_object(value, _ => standalone_util_toObject(_))
    : value;
}

function standalone_fromObject(value) {
  return standalone_is_array(value) ? value.map(standalone_fromObject)
    : !standalone_is_object(value) ? value
    : standalone_is_array(value.verbs) ? standalone_query_Query.from(value)
    : standalone_is_array(value.all) ? standalone_selection_all()
    : standalone_is_array(value.range) ? standalone_selection_range(...value.range)
    : standalone_is_array(value.match) ? standalone_matches(RegExp(...value.match))
    : standalone_is_array(value.not) ? standalone_not(value.not.map(standalone_util_toObject))
    : standalone_fromExprObject(value);
}

function standalone_fromExprObject(value) {
  let output = value;
  let expr = value.expr;

  if (expr != null) {
    if (value.field === true) {
      output = expr = standalone_helpers_field(expr);
    } else if (value.func === true) {
      output = expr = standalone_util_func(expr);
    }

    if (standalone_is_object(value.window)) {
      const { frame, peers } = value.window;
      output = expr = standalone_rolling(expr, frame, peers);
    }

    if (value.desc === true) {
      output = standalone_desc(expr);
    }
  }

  return value === output
    ? standalone_map_object(value, _ => standalone_fromObject(_))
    : output;
}

function standalone_joinKeys(keys) {
  return standalone_is_array(keys) ? keys.map(standalone_parseJoinKeys)
    : keys;
}

function standalone_parseJoinKeys(keys) {
  const list = [];

  standalone_to_array(keys).forEach(param => {
    standalone_is_number(param) ? list.push(param)
      : standalone_is_string(param) ? list.push(standalone_helpers_field(param, null))
      : standalone_is_object(param) && param.expr ? list.push(param)
      : standalone_util_is_function(param) ? list.push(param)
      : standalone_util_error(`Invalid key value: ${param+''}`);
  });

  return list;
}

function standalone_joinValues(values) {
  return standalone_is_array(values)
    ? values.map(standalone_parseJoinValues)
    : values;
}

function standalone_parseJoinValues(values, index) {
  return index < 2 ? standalone_to_array(values) : values;
}

function standalone_orderbyKeys(keys) {
  const list = [];

  keys.forEach(param => {
    const expr = param.expr != null ? param.expr : param;
    if (standalone_is_object(expr) && !standalone_util_is_function(expr)) {
      for (const key in expr) {
        list.push(expr[key]);
      }
    } else {
      param = standalone_is_number(expr) ? expr
        : standalone_is_string(expr) ? standalone_helpers_field(param)
        : standalone_util_is_function(expr) ? param
        : standalone_util_error(`Invalid orderby field: ${param+''}`);
      list.push(param);
    }
  });

  return list;
}
;// ../../node_modules/arquero/src/query/to-ast.js













const standalone_to_ast_Methods = {
  [standalone_Expr]: standalone_astExpr,
  [standalone_ExprList]: standalone_astExprList,
  [standalone_ExprNumber]: standalone_astExprNumber,
  [standalone_ExprObject]: standalone_astExprObject,
  [standalone_JoinKeys]: standalone_astJoinKeys,
  [standalone_JoinValues]: standalone_astJoinValues,
  [standalone_OrderbyKeys]: standalone_astExprList,
  [standalone_SelectionList]: standalone_astSelectionList
};

/* harmony default export */ function standalone_to_ast(value, type, propTypes) {
  return type === standalone_TableRef ? standalone_astTableRef(value)
    : type === standalone_TableRefList ? value.map(standalone_astTableRef)
    : standalone_ast(standalone_util_toObject(value), type, propTypes);
}

function standalone_ast(value, type, propTypes) {
  return type === standalone_Options
    ? (value ? standalone_astOptions(value, propTypes) : value)
    : standalone_to_ast_Methods[type](value);
}

function standalone_astOptions(value, types = {}) {
  const output = {};
  for (const key in value) {
    const prop = value[key];
    output[key] = types[key] ? standalone_ast(prop, types[key]) : prop;
  }
  return output;
}

function standalone_astParse(expr, opt) {
  return standalone_expression_parse({ expr }, { ...opt, ast: true }).exprs[0];
}

function standalone_astColumn(name) {
  return { type: standalone_constants_Column, name };
}

function standalone_astColumnIndex(index) {
  return { type: standalone_constants_Column, index };
}

function standalone_astExprObject(obj, opt) {
  if (standalone_is_string(obj)) {
    return standalone_astParse(obj, opt);
  }

  if (obj.expr) {
    let ast;
    if (obj.field === true) {
      ast = standalone_astColumn(obj.expr);
    } else if (obj.func === true) {
      ast = standalone_astExprObject(obj.expr, opt);
    }
    if (ast) {
      if (obj.desc) {
        ast = { type: standalone_constants_Descending, expr: ast };
      }
      if (obj.window) {
        ast = { type: standalone_constants_Window, expr: ast, ...obj.window };
      }
      return ast;
    }
  }

  return Object.keys(obj)
    .map(key => ({
      ...standalone_astExprObject(obj[key], opt),
      as: key
    }));
}

function standalone_astSelection(sel) {
  const type = standalone_Selection;
  return sel.all ? { type, operator: 'all' }
    : sel.not ? { type, operator: 'not', arguments: standalone_astExprList(sel.not) }
    : sel.range ? { type, operator: 'range', arguments: standalone_astExprList(sel.range) }
    : sel.matches ? { type, operator: 'matches', arguments: sel.matches }
    : standalone_util_error('Invalid input');
}

function standalone_astSelectionList(arr) {
  return standalone_to_array(arr).map(standalone_astSelectionItem).flat();
}

function standalone_astSelectionItem(val) {
  return standalone_isSelection(val) ? standalone_astSelection(val)
    : standalone_is_number(val) ? standalone_astColumnIndex(val)
    : standalone_is_string(val) ? standalone_astColumn(val)
    : standalone_is_object(val) ? Object.keys(val)
      .map(name => ({ type: standalone_constants_Column, name, as: val[name] }))
    : standalone_util_error('Invalid input');
}

function standalone_astExpr(val) {
  return standalone_isSelection(val) ? standalone_astSelection(val)
    : standalone_is_number(val) ? standalone_astColumnIndex(val)
    : standalone_is_string(val) ? standalone_astColumn(val)
    : standalone_is_object(val) ? standalone_astExprObject(val)
    : standalone_util_error('Invalid input');
}

function standalone_astExprList(arr) {
  return standalone_to_array(arr).map(standalone_astExpr).flat();
}

function standalone_astExprNumber(val) {
  return standalone_is_number(val) ? val : standalone_astExprObject(val);
}

function standalone_astJoinKeys(val) {
  return standalone_is_array(val)
    ? val.map(standalone_astExprList)
    : standalone_astExprObject(val, { join: true });
}

function standalone_astJoinValues(val) {
  return standalone_is_array(val)
    ? val.map((v, i) => i < 2
        ? standalone_astExprList(v)
        : standalone_astExprObject(v, { join: true })
      )
    : standalone_astExprObject(val, { join: true });
}

function standalone_astTableRef(value) {
  return value && standalone_util_is_function(value.toAST)
    ? value.toAST()
    : value;
}
;// ../../node_modules/arquero/src/query/verb.js








/**
 * Model an Arquero verb as a serializable object.
 */
class standalone_Verb {

  /**
   * Construct a new verb instance.
   * @param {string} verb The verb name.
   * @param {object[]} schema Schema describing verb parameters.
   * @param {any[]} params Array of parameter values.
   */
  constructor(verb, schema = [], params = []) {
    this.verb = verb;
    this.schema = schema;
    schema.forEach((s, index) => {
      const type = s.type;
      const param = params[index];
      const value = type === standalone_JoinKeys ? standalone_joinKeys(param)
        : type === standalone_JoinValues ? standalone_joinValues(param)
        : type === standalone_OrderbyKeys ? standalone_orderbyKeys(param)
        : param;
      this[s.name] = value !== undefined ? value : s.default;
    });
  }

  /**
   * Create new verb instance from the given serialized object.
   * @param {object} object A serialized verb representation, such as
   *  those generated by Verb.toObject.
   * @returns {Verb} The instantiated verb.
   */
  static from(object) {
    const verb = standalone_verb_Verbs[object.verb];
    const params = (verb.schema || [])
      .map(({ name }) => standalone_fromObject(object[name]));
    return verb(...params);
  }

  /**
   * Evaluate this verb against a given table and catalog.
   * @param {Table} table The Arquero table to process.
   * @param {Function} catalog A table lookup function that accepts a table
   *  name string as input and returns a corresponding Arquero table.
   * @returns {Table} The resulting Arquero table.
   */
  evaluate(table, catalog) {
    const params = this.schema.map(({ name, type }) => {
      const value = this[name];
      return type === standalone_TableRef ? standalone_getTable(catalog, value)
        : type === standalone_TableRefList ? value.map(t => standalone_getTable(catalog, t))
        : value;
    });
    return table[this.verb](...params);
  }

  /**
   * Serialize this verb as a JSON-compatible object. The resulting
   * object can be passed to Verb.from to re-instantiate this verb.
   * @returns {object} A JSON-compatible object representing this verb.
   */
  toObject() {
    const obj = { verb: this.verb };
    this.schema.forEach(({ name }) => {
      obj[name] = standalone_util_toObject(this[name]);
    });
    return obj;
  }

  /**
   * Serialize this verb to a JSON-compatible abstract syntax tree.
   * All table expressions will be parsed and represented as AST instances
   * using a modified form of the Mozilla JavaScript AST format.
   * This method can be used to output parsed and serialized representations
   * to translate Arquero verbs to alternative data processing platforms.
   * @returns {object} A JSON-compatible abstract syntax tree object.
   */
  toAST() {
    const obj = { type: standalone_constants_Verb, verb: this.verb };
    this.schema.forEach(({ name, type, props }) => {
      obj[name] = standalone_to_ast(this[name], type, props);
    });
    return obj;
  }
}

/**
 * Verb parameter type.
 * @typedef {Expr|ExprList|ExprNumber|ExprObject|JoinKeys|JoinValues|Options|OrderbyKeys|SelectionList|TableRef|TableRefList} ParamType
 */

/**
 * Verb parameter schema.
 * @typedef {object} ParamDef
 * @property {string} name The name of the parameter.
 * @property {ParamType} type The type of the parameter.
 * @property {{ [key: string]: ParamType }} [props] Types for non-literal properties.
 */

/**
 * Create a new constructors.
 * @param {string} name The name of the verb.
 * @param {ParamDef[]} schema The verb parameter schema.
 * @return {Function} A verb constructor function.
 */
function standalone_verb_createVerb(name, schema) {
  return Object.assign(
    (...params) => new standalone_Verb(name, schema, params),
    { schema }
  );
}

/**
 * A lookup table of verb classes.
 */
const standalone_verb_Verbs = {
  count:      standalone_verb_createVerb('count', [
                { name: 'options', type: standalone_Options }
              ]),
  derive:     standalone_verb_createVerb('derive', [
                { name: 'values', type: standalone_ExprObject },
                { name: 'options', type: standalone_Options,
                  props: { before: standalone_SelectionList, after: standalone_SelectionList }
                }
              ]),
  filter:     standalone_verb_createVerb('filter', [
                { name: 'criteria', type: standalone_ExprObject }
              ]),
  groupby:    standalone_verb_createVerb('groupby', [
                { name: 'keys', type: standalone_ExprList }
              ]),
  orderby:    standalone_verb_createVerb('orderby', [
                { name: 'keys', type: standalone_OrderbyKeys }
              ]),
  relocate:   standalone_verb_createVerb('relocate', [
                { name: 'columns', type: standalone_SelectionList },
                { name: 'options', type: standalone_Options,
                  props: { before: standalone_SelectionList, after: standalone_SelectionList }
                }
              ]),
  rename:     standalone_verb_createVerb('rename', [
                { name: 'columns', type: standalone_SelectionList }
              ]),
  rollup:     standalone_verb_createVerb('rollup', [
                { name: 'values', type: standalone_ExprObject }
              ]),
  sample:     standalone_verb_createVerb('sample', [
                { name: 'size', type: standalone_ExprNumber },
                { name: 'options', type: standalone_Options, props: { weight: standalone_Expr } }
              ]),
  select:     standalone_verb_createVerb('select', [
                { name: 'columns', type: standalone_SelectionList }
              ]),
  ungroup:    standalone_verb_createVerb('ungroup'),
  unorder:    standalone_verb_createVerb('unorder'),
  reify:      standalone_verb_createVerb('reify'),
  dedupe:     standalone_verb_createVerb('dedupe', [
                { name: 'keys', type: standalone_ExprList, default: [] }
              ]),
  impute:     standalone_verb_createVerb('impute', [
                { name: 'values', type: standalone_ExprObject },
                { name: 'options', type: standalone_Options, props: { expand: standalone_ExprList } }
              ]),
  fold:       standalone_verb_createVerb('fold', [
                { name: 'values', type: standalone_ExprList },
                { name: 'options', type: standalone_Options }
              ]),
  pivot:      standalone_verb_createVerb('pivot', [
                { name: 'keys', type: standalone_ExprList },
                { name: 'values', type: standalone_ExprList },
                { name: 'options', type: standalone_Options }
              ]),
  spread:     standalone_verb_createVerb('spread', [
                { name: 'values', type: standalone_ExprList },
                { name: 'options', type: standalone_Options }
              ]),
  unroll:     standalone_verb_createVerb('unroll', [
                { name: 'values', type: standalone_ExprList },
                { name: 'options', type: standalone_Options, props: { drop: standalone_ExprList } }
              ]),
  lookup:     standalone_verb_createVerb('lookup', [
                { name: 'table', type: standalone_TableRef },
                { name: 'on', type: standalone_JoinKeys },
                { name: 'values', type: standalone_ExprList }
              ]),
  join:       standalone_verb_createVerb('join', [
                { name: 'table', type: standalone_TableRef },
                { name: 'on', type: standalone_JoinKeys },
                { name: 'values', type: standalone_JoinValues },
                { name: 'options', type: standalone_Options }
              ]),
  cross:      standalone_verb_createVerb('cross', [
                { name: 'table', type: standalone_TableRef },
                { name: 'values', type: standalone_JoinValues },
                { name: 'options', type: standalone_Options }
              ]),
  semijoin:   standalone_verb_createVerb('semijoin', [
                { name: 'table', type: standalone_TableRef },
                { name: 'on', type: standalone_JoinKeys }
              ]),
  antijoin:   standalone_verb_createVerb('antijoin', [
                { name: 'table', type: standalone_TableRef },
                { name: 'on', type: standalone_JoinKeys }
              ]),
  concat:     standalone_verb_createVerb('concat', [
                { name: 'tables', type: standalone_TableRefList }
              ]),
  union:      standalone_verb_createVerb('union', [
                { name: 'tables', type: standalone_TableRefList }
              ]),
  intersect:  standalone_verb_createVerb('intersect', [
                { name: 'tables', type: standalone_TableRefList }
              ]),
  except:     standalone_verb_createVerb('except', [
                { name: 'tables', type: standalone_TableRefList }
              ])
};
;// ../../node_modules/arquero/src/query/query.js




/**
 * Create a new query instance. The query interface provides
 * a table-like verb API to construct a query that can be
 * serialized or evaluated against Arquero tables.
 * @param {string} [tableName] The name of the table to query. If
 *  provided, will be used as the default input table to pull from
 *  a provided catalog to run the query against.
 * @return {Query} A new builder instance.
 */
function standalone_query(tableName) {
  return new standalone_query_Query(null, null, tableName);
}

/**
 * Create a new query instance from a serialized object.
 * @param {object} object A serialized query representation, such as
 *  those generated by query(...).toObject().
 * @returns {Query} The instantiated query instance.
 */
function standalone_queryFrom(object) {
  return standalone_query_Query.from(object);
}

/**
 * Model a query as a collection of serializble verbs.
 * Provides a table-like interface for constructing queries.
 */
class standalone_query_Query extends standalone_Transformable {

  /**
   * Construct a new query instance.
   * @param {Verb[]} verbs An array of verb instances.
   * @param {object} [params] Optional query parameters, corresponding
   *  to parameter references in table expressions.
   * @param {string} [table] Optional name of the table to query.
   */
  constructor(verbs, params, table) {
    super(params);
    this._verbs = verbs || [];
    this._table = table;
  }

  /**
   * Create a new query instance from the given serialized object.
   * @param {QueryObject} object A serialized query representation, such as
   *  those generated by Query.toObject.
   * @returns {Query} The instantiated query.
   */
  static from({ verbs, table, params }) {
    return new standalone_query_Query(verbs.map(standalone_Verb.from), params, table);
  }

  /**
   * Provide an informative object string tag.
   */
  get [Symbol.toStringTag]() {
    if (!this._verbs) return 'Object'; // bail if called on prototype
    const ns = this._verbs.length;
    return `Query: ${ns} verbs` + (this._table ? ` on '${this._table}'` : '');
  }

  /**
   * Return the number of verbs in this query.
   */
  get length() {
    return this._verbs.length;
  }

  /**
   * Return the name of the table this query applies to.
   * @return {string} The name of the source table, or undefined.
   */
  get tableName() {
    return this._table;
  }

  /**
   * Get or set table expression parameter values.
   * If called with no arguments, returns the current parameter values
   * as an object. Otherwise, adds the provided parameters to this
   * query's parameter set and returns the table. Any prior parameters
   * with names matching the input parameters are overridden.
   * @param {object} values The parameter values.
   * @return {Query|object} The current parameter values (if called
   *  with no arguments) or this query.
   */
  params(values) {
    if (arguments.length) {
      this._params = { ...this._params, ...values };
      return this;
    } else {
      return this._params;
    }
  }

  /**
   * Evaluate this query against a given table and catalog.
   * @param {Table} table The Arquero table to process.
   * @param {Function} catalog A table lookup function that accepts a table
   *  name string as input and returns a corresponding Arquero table.
   * @returns {Table} The resulting Arquero table.
   */
  evaluate(table, catalog) {
    table = table || catalog(this._table);
    for (const verb of this._verbs) {
      table = verb.evaluate(table.params(this._params), catalog);
    }
    return table;
  }

  /**
   * Serialize this query as a JSON-compatible object. The resulting
   * object can be passed to Query.from to re-instantiate this query.
   * @returns {object} A JSON-compatible object representing this query.
   */
  toObject() {
    return src_standalone_serialize(this, 'toObject');
  }

  /**
   * Serialize this query as a JSON-compatible object. The resulting
   * object can be passed to Query.from to re-instantiate this query.
   * This method simply returns the result of toObject, but is provided
   * as a separate method to allow later customization of JSON export.
   * @returns {object} A JSON-compatible object representing this query.
   */
  toJSON() {
    return this.toObject();
  }

  /**
   * Serialize this query to a JSON-compatible abstract syntax tree.
   * All table expressions will be parsed and represented as AST instances
   * using a modified form of the Mozilla JavaScript AST format.
   * This method can be used to output parsed and serialized representations
   * to translate Arquero queries to alternative data processing platforms.
   * @returns {object} A JSON-compatible abstract syntax tree object.
   */
  toAST() {
    return src_standalone_serialize(this, 'toAST', { type: standalone_constants_Query });
  }
}

/**
 * Serialized object representation of a query.
 * @typedef {object} QueryObject
 * @property {object[]} verbs An array of verb definitions.
 * @property {object} [params] An object of parameter values.
 * @property {string} [table] The name of the table to query.
 */

function src_standalone_serialize(query, method, props) {
  return {
    ...props,
    verbs: query._verbs.map(verb => verb[method]()),
    ...(query._params ? { params: query._params } : null),
    ...(query._table ? { table: query._table } : null)
  };
}

function standalone_query_append(qb, verb) {
  return new standalone_query_Query(
    qb._verbs.concat(verb),
    qb._params,
    qb._table
  );
}

function standalone_query_addQueryVerb(name, verb) {
  standalone_query_Query.prototype[name] = function(...args) {
    return standalone_query_append(this, verb(...args));
  };
}

// Internal verb handlers
for (const name in standalone_verb_Verbs) {
  const verb = standalone_verb_Verbs[name];
  standalone_query_Query.prototype['__' + name] = function(qb, ...args) {
    return standalone_query_append(qb, verb(...args));
  };
}
;// ../../node_modules/arquero/package.json
const standalone_arquero_package_namespaceObject = {"rE":"4.8.8"};
;// ../../node_modules/arquero/src/arrow/arrow-column.js







const standalone_isList = id => id === Type.List || id === Type.FixedSizeList;

/**
 * Create an Arquero column that proxies access to an Arrow column.
 * @param {object} arrow An Apache Arrow column.
 * @return {import('../table/column').ColumnType} An Arquero-compatible column.
 */
function standalone_arrow_column_arrowColumn(arrow, nested) {
  if (arrow.dictionary) return arrowDictionary(arrow);
  const { typeId, chunks, length, numChildren } = arrow;
  const vector = chunks && chunks.length === 1 ? chunks[0] : arrow;
  const get = numChildren && nested ? standalone_getNested(vector)
    : numChildren ? standalone_arrow_column_memoize(standalone_getNested(vector))
    : typeId === Type.Utf8 ? standalone_arrow_column_memoize(row => vector.get(row))
    : null;

  return get
    ? { vector, length, get, [Symbol.iterator]: () => standalone_arrow_column_iterator(length, get) }
    : vector;
}

function standalone_arrow_column_memoize(get) {
  const values = [];
  return row => {
    const v = values[row];
    return v !== undefined ? v : (values[row] = get(row));
  };
}

function* standalone_arrow_column_iterator(n, get) {
  for (let i = 0; i < n; ++i) {
    yield get(i);
  }
}

const standalone_arrayFrom = vector => vector.numChildren
  ? repeat(vector.length, standalone_getNested(vector))
  : vector.nullCount ? [...vector]
  : vector.toArray();

const standalone_getNested = vector => standalone_isList(vector.typeId) ? standalone_arrow_column_getList(vector)
  : vector.typeId === Type.Struct ? standalone_arrow_column_getStruct(vector)
  : error(`Unsupported Arrow type: ${toString(vector.VectorName)}`);

const standalone_arrow_column_getList = vector => vector.nullCount
  ? row => vector.isValid(row) ? standalone_arrayFrom(vector.get(row)) : null
  : row => standalone_arrayFrom(vector.get(row));

function standalone_arrow_column_getStruct(vector) {
  const props = [];
  const code = [];
  vector.type.children.forEach((field, i) => {
    props.push(standalone_arrow_column_arrowColumn(vector.getChildAt(i), true));
    code.push(`${toString(field.name)}:_${i}.get(row)`);
  });
  const get = unroll('row', '({' + code + '})', props);

  return vector.nullCount
    ? row => vector.isValid(row) ? get(row) : null
    : get;
}
;// ../../node_modules/arquero/src/format/from-arrow.js







/**
 * Options for Apache Arrow import.
 * @typedef {object} ArrowOptions
 * @property {import('../table/transformable').Select} columns
 *  An ordered set of columns to import. The input may consist of column name
 *  strings, column integer indices, objects with current column names as keys
 *  and new column names as values (for renaming), or selection helper
 *  functions such as {@link all}, {@link not}, or {@link range}.
 */

/**
 * Create a new table backed by an Apache Arrow table instance.
 * @param {object} arrow An Apache Arrow data table or byte buffer.
 * @param {ArrowOptions} options Options for Arrow import.
 * @return {ColumnTable} A new table containing the imported values.
 */
/* harmony default export */ function standalone_from_arrow(arrow, options = {}) {
  arrow = from(arrow);
  const { chunks, length, schema } = arrow;

  // resolve column selection
  const fields = schema.fields.map(f => f.name);
  const sel = resolve({
    columnNames: test => test ? fields.filter(test) : fields.slice(),
    columnIndex: name => fields.indexOf(name)
  }, options.columns || all());

  // build Arquero columns for backing Arrow columns
  const cols = columnSet();
  sel.forEach((name, key) => {
    cols.add(name, arrowColumn(arrow.getColumn(key)));
  });

  // build row filter bit mask as needed
  const bits = arrow.count() !== length ? new BitSet(length) : null;
  if (bits) {
    let b = 0;
    let c = 0;
    arrow.scan(
      idx => bits.set(b + idx),
      batch => { while (chunks[c] !== batch) b += chunks[c++].length; }
    );
  }

  return new ColumnTable(cols.data, cols.names, bits);
}
;// ../../node_modules/arquero/src/util/parse-values.js



const standalone_parseBoolean = [ // boolean
  v => (v === 'true') || (v === 'false'),
  v => v === 'false' ? false : true
];

const standalone_parse_values_parseNumber = [ // number
  v => v === 'NaN' || (v = +v) === v,
  v => +v
];

const standalone_parseDate = [ // iso date
  standalone_is_iso_date_string,
  v => new Date(Date.parse(v))
];

function standalone_numberParser(options) {
  const { decimal } = options;
  return decimal && decimal !== '.'
    ? standalone_parse_values_parseNumber.map(f => s => f(s && s.replace(decimal, '.')))
    : standalone_parse_values_parseNumber;
}

/* harmony default export */ function standalone_parse_values(values, options) {
  const types = [standalone_parseBoolean, standalone_numberParser(options), standalone_parseDate];
  const n = types.length;
  for (let i = 0; i < n; ++i) {
    const [test, parser] = types[i];
    if (standalone_check(values, test)) {
      return parser;
    }
  }
  return identity;
}

function standalone_check(values, test) {
  const n = values.length;
  for (let i = 0; i < n; ++i) {
    const v = values[i];
    if (v != null && !test(v)) {
      return false;
    }
  }
  return true;
}
;// ../../node_modules/arquero/src/format/from-text-rows.js






function standalone_defaultNames(n, off = 0) {
  return repeat(n - off, i => `col${i + off + 1}`);
}

/* harmony default export */ function standalone_from_text_rows(next, names, options) {
  let row = next();
  const n = row.length;
  const automax = +options.autoMax || 1000;
  const values = repeat(n, () => []);
  names = names
    ? names.length < n ? [...names, standalone_defaultNames(n, names.length)] : names
    : standalone_defaultNames(n);

  // read in initial rows to guess types
  let idx = 0;
  for (; idx < automax && row; ++idx, row = next()) {
    for (let i = 0; i < n; ++i) {
      values[i].push(row[i] === '' ? null : row[i]);
    }
  }

  // initialize parsers
  const parsers = standalone_getParsers(names, values, options);

  // apply parsers
  parsers.forEach((parse, i) => {
    if (parse === identity) return;
    const v = values[i];
    for (let r = 0; r < idx; ++r) {
      if (v[r] != null) v[r] = parse(v[r]);
    }
  });

  // parse remainder of file
  for (; row; row = next()) {
    for (let i = 0; i < n; ++i) {
      values[i].push(row[i] ? parsers[i](row[i]) : null);
    }
  }

  const columns = {};
  names.forEach((name, i) => columns[name] = values[i]);
  return new ColumnTable(columns, names);
}

function standalone_getParsers(names, values, options) {
  const { parse = {} } = options;
  const noParse = options.autoType === false;

  return names.map(
    (name, i) => isFunction(parse[name]) ? parse[name]
      : noParse ? identity
      : valueParser(values[i], options)
  );
}
;// ../../node_modules/arquero/src/format/parse/constants.js
const standalone_constants_EOL = {};
const standalone_constants_EOF = {};
const standalone_constants_QUOTE = 34;
const standalone_constants_NEWLINE = 10;
const standalone_constants_RETURN = 13;
;// ../../node_modules/arquero/src/format/parse/parse-delimited.js




// Adapted from d3-dsv: https://github.com/d3/d3-dsv/blob/master/src/dsv.js
// Copyright 2013-2016 Mike Bostock
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the name of the author nor the names of contributors may be used to
//   endorse or promote products derived from this software without specific prior
//   written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/* harmony default export */ function standalone_parse_delimited(text, { delimiter = ',', skip, comment }) {
  if (delimiter.length !== 1) {
    error(`Text "delimiter" should be a single character, found "${delimiter}"`);
  }
  const delimCode = delimiter.charCodeAt(0);

  let N = text.length;
  let I = 0; // current character index
  let t; // current token
  let eof = N <= 0; // current token followed by EOF?
  let eol = false; // current token followed by EOL?

  // Strip the trailing newline.
  if (text.charCodeAt(N - 1) === NEWLINE) --N;
  if (text.charCodeAt(N - 1) === RETURN) --N;

  function token() {
    if (eof) return EOF;
    if (eol) return eol = false, EOL;

    // Unescape quotes.
    const j = I;
    let i, c;
    if (text.charCodeAt(j) === QUOTE) {
      while (I++ < N && text.charCodeAt(I) !== QUOTE || text.charCodeAt(++I) === QUOTE);
      if ((i = I) >= N) eof = true;
      else if ((c = text.charCodeAt(I++)) === NEWLINE) eol = true;
      else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }
      return text.slice(j + 1, i - 1).replace(/""/g, '"');
    }

    // Find next delimiter or newline.
    while (I < N) {
      if ((c = text.charCodeAt(i = I++)) === NEWLINE) eol = true;
      else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }
      else if (c !== delimCode) continue;
      return text.slice(j, i);
    }

    // Return last token before EOF.
    return eof = true, text.slice(j, N);
  }

  function next() {
    if ((t = token()) !== EOF) {
      const row = [];
      while (t !== EOL && t !== EOF) row.push(t), t = token();
      return row;
    }
  }

  return filter(
    next, skip,
    comment && (x => (x && x[0] || '').startsWith(comment))
  );
}
;// ../../node_modules/arquero/src/format/from-csv.js
 // eslint-disable-line no-unused-vars




/**
 * Options for CSV parsing.
 * @typedef {object} CSVParseOptions
 * @property {string} [delimiter=','] Single-character delimiter between values.
 * @property {string} [decimal='.'] Single-character numeric decimal separator.
 * @property {boolean} [header=true] Flag to specify presence of header row.
 *  If true, assumes the CSV contains a header row with column names. If false,
 *  indicates the CSV does not contain a header row; columns are given the
 *  names 'col1', 'col2', etc unless the *names* option is specified.
 * @property {string[]} [names] An array of column names to use for header-less
 *  CSV files. This option is ignored if the header option is true.
 * @property {number} [skip=0] The number of lines to skip before reading data.
 * @property {string} [comment] A string used to identify comment lines. Any
 *  lines that start with the comment pattern are skipped.
 * @property {boolean} [autoType=true] Flag for automatic type inference.
 * @property {number} [autoMax=1000] Maximum number of initial values to use
 *  for type inference.
 * @property {Object.<string, (value: string) => any>} [parse] Object of
 *  column parsing options. The object keys should be column names. The object
 *  values should be parsing functions that transform values upon input.
 */

/**
 * Parse a comma-separated values (CSV) string into a table. Other
 * delimiters, such as tabs or pipes ('|'), can be specified using
 * the options argument. By default, automatic type inference is performed
 * for input values; string values that match the ISO standard
 * date format are parsed into JavaScript Date objects. To disable this
 * behavior, set the autoType option to false. To perform custom parsing
 * of input column values, use the parse option.
 * @param {string} text A string in a delimited-value format.
 * @param {CSVParseOptions} options The formatting options.
 * @return {ColumnTable} A new table containing the parsed values.
 */
/* harmony default export */ function standalone_from_csv(text, options = {}) {
  const next = parseDelimited(text, options);
  return fromTextRows(
    next,
    options.header !== false ? next() : options.names,
    options
  );
}
;// ../../node_modules/arquero/src/format/parse/parse-lines.js



/* harmony default export */ function standalone_parse_lines(text, { skip, comment }) {
  let N = text.length;
  let I = 0; // current character index

  // Strip the trailing newline.
  if (text.charCodeAt(N - 1) === NEWLINE) --N;
  if (text.charCodeAt(N - 1) === RETURN) --N;

  function read() {
    if (I >= N) return;

    const j = I;
    let eol = false;
    let i, c;

    // Find next newline.
    while (I < N) {
      if ((c = text.charCodeAt(i = I++)) === NEWLINE) eol = true;
      else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }
      if (eol) return text.slice(j, i);
    }

    // Return last line before EOF.
    return text.slice(j, N);
  }

  return filter(
    read, skip,
    comment && (x => (x || '').startsWith(comment))
  );
}
;// ../../node_modules/arquero/src/format/from-fixed.js
 // eslint-disable-line no-unused-vars





/**
 * Options for fixed width file parsing.
 * @typedef {object} FixedParseOptions
 * @property {[number, number][]} [positions] Array of start, end indices for
 *  fixed-width columns.
 * @property {number[]} [widths] Array of fixed column widths. This option is
 *  ignored if the positions property is specified.
 * @property {string[]} [names] An array of column names. The array length
 *  should match the length of the positions array. If not specified or
 *  shorter than the positions array, default column names are generated.
 * @property {string} [decimal='.'] Single-character numeric decimal separator.
 * @property {number} [skip=0] The number of lines to skip before reading data.
 * @property {string} [comment] A string used to identify comment lines. Any
 *  lines that start with the comment pattern are skipped.
 * @property {boolean} [autoType=true] Flag for automatic type inference.
 * @property {number} [autoMax=1000] Maximum number of initial values to use
 *  for type inference.
 * @property {Object.<string, (value: string) => any>} [parse] Object of
 *  column parsing options. The object keys should be column names. The object
 *  values should be parsing functions that transform values upon input.
 */

/**
 * Parse a fixed-width file (FWF) string into a table. By default, automatic
 * type inference is performed for input values; string values that match the
 * ISO standard date format are parsed into JavaScript Date objects. To
 * disable this behavior, set the autoType option to false. To perform custom
 * parsing of input column values, use the parse option.
 * @param {string} text A string in a fixed-width file format.
 * @param {FixedParseOptions} options The formatting options.
 * @return {ColumnTable} A new table containing the parsed values.
 */
/* harmony default export */ function standalone_from_fixed(text, options = {}) {
  const read = parseLines(text, options);
  const p = standalone_positions(options);
  return fromTextRows(
    () => {
      const line = read();
      if (line) {
        return p.map(([i, j]) => line.slice(i, j).trim());
      }
    },
    options.names,
    options
  );
}

function standalone_positions({ positions, widths }) {
  if (!positions && !widths) {
    error('Fixed width files require a "positions" or "widths" option');
  }
  let i = 0;
  return positions || widths.map(w => [i, i += w]);
}
;// ../../node_modules/arquero/src/format/from-json.js








/**
 * Options for JSON parsing.
 * @typedef {object} JSONParseOptions
 * @property {boolean} [autoType=true] Flag controlling automatic type
 *  inference. If false, date parsing for input JSON strings is disabled.
 * @property {Object.<string, (value: any) => any>} [parse] Object of column
 *  parsing options. The object keys should be column names. The object values
 *  should be parsing functions that transform values upon input.
 */

/**
 * Parse JavaScript Object Notation (JSON) data into a table.
 * The expected JSON data format is an object with column names for keys
 * and column value arrays for values. By default string values that match
 * the ISO standard date format are parsed into JavaScript Date objects.
 * To disable this behavior, set the autoType option to false. To perform
 * custom parsing of input column values, use the parse option. Auto-type
 * parsing is not performed for columns with custom parse options.
 * The data payload can also be provided as the "data" property of an
 * enclosing object, with an optional "schema" property containing table
 * metadata such as a "fields" array of ordered column information.
 * @param {string|object} data A string in JSON format, or pre-parsed object.
 * @param {JSONParseOptions} options The formatting options.
 * @return {ColumnTable} A new table containing the parsed values.
 */
/* harmony default export */ function standalone_from_json(json, options = {}) {
  const autoType = defaultTrue(options.autoType);

  // parse string input
  if (isString(json)) {
    json = JSON.parse(json);
  }

  // separate schema and data, as needed
  let data = json.data, names;
  if (isObject(data) && !isArrayType(data)) {
    if (json.schema && json.schema.fields) {
      names = json.schema.fields.map(f => f.name);
    }
  } else {
    data = json;
  }

  // parse values as necessary
  if (autoType || options.parse) {
    const parsers = options.parse || {};
    for (const name in data) {
      const col = data[name];
      const len = col.length;
      if (parsers[name]) {
        // apply custom parser
        for (let i = 0; i < len; ++i) {
          col[i] = parsers[name](col[i]);
        }
      } else if (autoType) {
        // apply autoType parser
        for (let i = 0; i < len; ++i) {
          const val = col[i];
          if (isString(val) && isISODateString(val) && !isDigitString(val)) {
            col[i] = new Date(val);
          }
        }
      }
    }
  }

  return new ColumnTable(data, names);
}
;// ../../node_modules/arquero/src/verbs/dedupe.js
/* harmony default export */ function standalone_dedupe(table, keys = []) {
  return table
    .groupby(keys.length ? keys : table.columnNames())
    .filter('row_number() === 1')
    .ungroup()
    .reify();
}
;// ../../node_modules/arquero/src/engine/select.js




/* harmony default export */ function standalone_engine_select(table, columns) {
  const cols = standalone_column_set();

  columns.forEach((value, curr) => {
    const next = standalone_is_string(value) ? value : curr;
    if (next) {
      const col = table.column(curr) || standalone_util_error(`Unrecognized column: ${curr}`);
      cols.add(next, col);
    }
  });

  return table.create(cols);
}
;// ../../node_modules/arquero/src/verbs/relocate.js




/* harmony default export */ function standalone_relocate(table, columns, { before, after } = {}) {
  const bef = before != null;
  const aft = after != null;

  if (!(bef || aft)) {
    standalone_util_error('relocate requires a before or after option.');
  }
  if (bef && aft) {
    standalone_util_error('relocate accepts only one of the before or after options.');
  }

  columns = standalone_selection_resolve(table, columns);
  const anchors = [...standalone_selection_resolve(table, bef ? before : after).keys()];
  const anchor = bef ? anchors[0] : anchors.pop();
  const select = new Map();

  // marshal inputs to select in desired order
  table.columnNames().forEach(name => {
    // check if we should assign the current column
    const assign = !columns.has(name);

    // at anchor column, insert relocated columns
    if (name === anchor) {
      if (aft && assign) select.set(name, name);
      for (const [key, value] of columns) {
        select.set(key, value);
      }
      if (aft) return; // exit if current column has been handled
    }

    if (assign) select.set(name, name);
  });

  return standalone_engine_select(table, select);
}
;// ../../node_modules/arquero/src/util/concat.js
/* harmony default export */ function standalone_concat(list, fn = (x => x), delim = '') {
  const n = list.length;
  if (!n) return '';

  let s = fn(list[0], 0);
  for (let i = 1; i < n; ++i) {
    s += delim + fn(list[i], i);
  }

  return s;
}
;// ../../node_modules/arquero/src/util/unroll.js
/* harmony default export */ function standalone_util_unroll(args, code, ...lists) {
  const v = ['_', '$'];
  const a = v.slice(0, lists.length);
  a.push('"use strict"; const '
    + lists
        .map((l, j) => l.map((_, i) => `${v[j]}${i} = ${v[j]}[${i}]`).join(', '))
        .join(', ')
    + `; return (${args}) => ${code};`
  );
  return Function(...a)(...lists);
}
;// ../../node_modules/arquero/src/util/ascending.js
/* harmony default export */ function standalone_util_ascending(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
;// ../../node_modules/arquero/src/util/min.js


/* harmony default export */ function standalone_util_min(values, start = 0, stop = values.length) {
  let min = stop ? values[start++] : standalone_util_null;

  for (let i = start; i < stop; ++i) {
    if (min > values[i]) {
      min = values[i];
    }
  }

  return min;
}
;// ../../node_modules/arquero/src/util/max.js


/* harmony default export */ function standalone_util_max(values, start = 0, stop = values.length) {
  let max = stop ? values[start++] : standalone_util_null;

  for (let i = start; i < stop; ++i) {
    if (max < values[i]) {
      max = values[i];
    }
  }

  return max;
}
;// ../../node_modules/arquero/src/util/to-numeric.js


/* harmony default export */ function standalone_to_numeric(value) {
  return standalone_is_bigint(value) ? value : +value;
}
;// ../../node_modules/arquero/src/util/quantile.js




function standalone_util_quantile_quantile(values, p) {
  const n = values.length;

  if (!n) return standalone_util_null;
  if ((p = +p) <= 0 || n < 2) return standalone_to_numeric(values[0]);
  if (p >= 1) return standalone_to_numeric(values[n - 1]);

  const i = (n - 1) * p;
  const i0 = Math.floor(i);
  const v0 = standalone_to_numeric(values[i0]);
  return standalone_is_bigint(v0)
    ? v0
    : v0 + (standalone_to_numeric(values[i0 + 1]) - v0) * (i - i0);
}
;// ../../node_modules/arquero/src/util/value-list.js





class standalone_ValueList {
  constructor(values) {
    this._values = values || [];
    this._sorted = null;
    this._start = 0;
  }

  values(copy) {
    if (this._start) {
      this._values = this._values.slice(this._start);
      this._start = 0;
    }
    return copy
      ? this._values.slice()
      : this._values;
  }

  add(value) {
    this._values.push(value);
    this._sorted = null;
  }

  rem() {
    this._start += 1;
    this._sorted = null;
  }

  min() {
    return this._sorted && this._sorted.length
      ? this._sorted[0]
      : standalone_util_min(this._values, this._start);
  }

  max() {
    return this._sorted && this._sorted.length
      ? this._sorted[this._sorted.length - 1]
      : standalone_util_max(this._values, this._start);
  }

  quantile(p) {
    if (!this._sorted) {
      this._sorted = this.values(true);
      this._sorted.sort(standalone_util_ascending);
    }
    return standalone_util_quantile_quantile(this._sorted, p);
  }
}
;// ../../node_modules/arquero/src/engine/reduce/field-reducer.js








const standalone_field_reducer_update = (ops, args, fn) => standalone_util_unroll(
  args,
  '{' + standalone_concat(ops, (_, i) => `_${i}.${fn}(${args});`) + '}',
  ops
);

/* harmony default export */ function standalone_field_reducer(oplist, stream) {
  const { ops, output } = standalone_expand(oplist, stream);
  const fields = oplist[0].fields;
  const n = fields.length;
  const cls = n === 0 ? standalone_FieldReducer
    : n === 1 ? standalone_Field1Reducer
    : n === 2 ? standalone_Field2Reducer
    : standalone_util_error('Unsupported field count: ' + n);
  return new cls(fields, ops, output, stream);
}

function standalone_expand(oplist, stream) {
  const has = {};
  const ops = [];

  function add(name, params = []) {
    // check key
    const key = name + ':' + params;
    if (has[key]) return has[key];

    // get op instance
    const def = standalone_getAggregate(name);
    const op = def.create(...params);

    // add required dependencies
    if (stream < 0 && def.stream) {
      def.stream.forEach(name => add(name, []));
    }
    if (def.req) {
      def.req.forEach(name => add(name, []));
    }

    // update state
    has[key] = op;
    ops.push(op);

    return op;
  }

  const output = oplist.map(item => {
    const op = add(item.name, item.params);
    op.output = item.id;
    return op;
  });

  return { ops, output };
}

class standalone_FieldReducer extends standalone_Reducer {
  constructor(fields, ops, outputs, stream) {
    super(outputs);
    this._op = ops;
    this._fields = fields;
    this._stream = !!stream;
  }

  init() {
    const state = { count: 0, valid: 0, stream: this._stream };
    this._op.forEach(op => op.init(state));

    // value list requested
    if (state.values) {
      state.list = new standalone_ValueList();
    }

    return state;
  }

  write(state, values, index) {
    const op = this._outputs;
    const n = op.length;
    for (let i = 0; i < n; ++i) {
      values[op[i].output][index] = op[i].value(state);
    }
    return 1;
  }

  _add() {
  }

  _rem() {
  }

  add(state) {
    ++state.count;
  }

  rem(state) {
    --state.count;
  }
}

class standalone_Field1Reducer extends standalone_FieldReducer {
  constructor(fields, ops, outputs, stream) {
    super(fields, ops, outputs, stream);

    // unroll op invocations for performance
    const args = ['state', 'v1', 'v2'];
    this._add = standalone_field_reducer_update(ops, args, 'add');
    this._rem = standalone_field_reducer_update(ops, args, 'rem');
  }

  add(state, row, data) {
    const value = this._fields[0](row, data);
    ++state.count;
    if (standalone_is_valid(value)) {
      ++state.valid;
      if (state.list) state.list.add(value);
      this._add(state, value);
    }
  }

  rem(state, row, data) {
    const value = this._fields[0](row, data);
    --state.count;
    if (standalone_is_valid(value)) {
      --state.valid;
      if (state.list) state.list.rem();
      this._rem(state, value);
    }
  }
}

class standalone_Field2Reducer extends standalone_FieldReducer {
  constructor(fields, ops, outputs, stream) {
    super(fields, ops, outputs, stream);

    // unroll op invocations for performance
    const args = ['state', 'v1', 'v2'];
    this._add = standalone_field_reducer_update(ops, args, 'add');
    this._rem = standalone_field_reducer_update(ops, args, 'rem');
  }

  add(state, row, data) {
    const value1 = this._fields[0](row, data);
    const value2 = this._fields[1](row, data);
    ++state.count;
    if (standalone_is_valid(value1) && standalone_is_valid(value2)) {
      ++state.valid;
      if (state.list) state.list.add([value1, value2]);
      this._add(state, value1, value2);
    }
  }

  rem(state, row, data) {
    const value1 = this._fields[0](row, data);
    const value2 = this._fields[1](row, data);
    --state.count;
    if (standalone_is_valid(value1) && standalone_is_valid(value2)) {
      --state.valid;
      if (state.list) state.list.rem();
      this._rem(state, value1, value2);
    }
  }
}
;// ../../node_modules/arquero/src/engine/reduce/util.js



function standalone_aggregateGet(table, ops, get) {
  if (ops.length) {
    const data = table.data();
    const { keys } = table.groups() || {};
    const result = standalone_aggregate(table, ops);
    const op = keys
      ? (name, row) => result[name][keys[row]]
      : name => result[name][0];
    get = get.map(f => row => f(row, data, op));
  }

  return get;
}

function standalone_aggregate(table, ops, result) {
  if (!ops.length) return result; // early exit

  // instantiate aggregators and result store
  const aggrs = standalone_reducers(ops);
  const groups = table.groups();
  const size = groups ? groups.size : 1;
  result = result || standalone_util_repeat(ops.length, () => Array(size));

  // compute aggregates, extract results
  if (size > 1) {
    aggrs.forEach(aggr => {
      const cells = standalone_reduceGroups(table, aggr, groups);
      for (let i = 0; i < size; ++i) {
        aggr.write(cells[i], result, i);
      }
    });
  } else {
    aggrs.forEach(aggr => {
      const cell = standalone_reduceFlat(table, aggr);
      aggr.write(cell, result, 0);
    });
  }

  return result;
}

function standalone_reducers(ops, stream) {
  const aggrs = [];
  const fields = {};

  // group operators by field inputs
  for (const op of ops) {
    const key = op.fields.map(f => f + '').join(',');
    (fields[key] || (fields[key] = [])).push(op);
  }

  // generate a field reducer for each field
  for (const key in fields) {
    aggrs.push(standalone_field_reducer(fields[key], stream));
  }

  return aggrs;
}

function standalone_reduceFlat(table, reducer) {
  // initialize aggregation cell
  const cell = reducer.init();

  // compute aggregate values
  // inline the following for performance:
  // table.scan((row, data) => reducer.add(cell, row, data));
  const n = table.totalRows();
  const data = table.data();
  const bits = table.mask();

  if (table.isOrdered()) {
    const idx = table.indices();
    for (let i = 0; i < n; ++i) {
      reducer.add(cell, idx[i], data);
    }
  } else if (bits) {
    for (let i = bits.next(0); i >= 0; i = bits.next(i + 1)) {
      reducer.add(cell, i, data);
    }
  } else {
    for (let i = 0; i < n; ++i) {
      reducer.add(cell, i, data);
    }
  }

  return cell;
}

function standalone_reduceGroups(table, reducer, groups) {
  const { keys, size } = groups;

  // initialize aggregation cells
  const cells = standalone_util_repeat(size, () => reducer.init());

  // compute aggregate values
  // inline the following for performance:
  // table.scan((row, data) => reducer.add(cells[keys[row]], row, data));
  const data = table.data();

  if (table.isOrdered()) {
    const idx = table.indices();
    const m = idx.length;
    for (let i = 0; i < m; ++i) {
      const row = idx[i];
      reducer.add(cells[keys[row]], row, data);
    }
  } else if (table.isFiltered()) {
    const bits = table.mask();
    for (let i = bits.next(0); i >= 0; i = bits.next(i + 1)) {
      reducer.add(cells[keys[i]], i, data);
    }
  } else {
    const n = table.totalRows();
    for (let i = 0; i < n; ++i) {
      reducer.add(cells[keys[i]], i, data);
    }
  }

  return cells;
}

function standalone_groupOutput(cols, groups) {
  const { get, names, rows, size } = groups;

  // write group values to output columns
  const m = names.length;
  for (let j = 0; j < m; ++j) {
    const col = cols.add(names[j], Array(size));
    const val = get[j];
    for (let i = 0; i < size; ++i) {
      col[i] = val(rows[i]);
    }
  }
}
;// ../../node_modules/arquero/src/util/bisector.js
/* harmony default export */ function standalone_util_bisector(compare) {
  return {
    left(a, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a.length;
      while (lo < hi) {
        const mid = lo + hi >>> 1;
        if (compare(a[mid], x) < 0) lo = mid + 1;
        else hi = mid;
      }
      return lo;
    },
    right(a, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a.length;
      while (lo < hi) {
        const mid = lo + hi >>> 1;
        if (compare(a[mid], x) > 0) hi = mid;
        else lo = mid + 1;
      }
      return lo;
    }
  };
}

;// ../../node_modules/arquero/src/engine/window/window-state.js





const standalone_window_state_bisect = standalone_util_bisector(standalone_util_ascending);

/* harmony default export */ function standalone_window_state(data, frame, adjust, ops, aggrs) {
  let rows, peer, cells, result, key;
  const isPeer = index => peer[index - 1] === peer[index];
  const numOps = ops.length;
  const numAgg = aggrs.length;

  const evaluate = ops.length
    ? standalone_util_unroll(
        ['w', 'r', 'k'],
        '{' + standalone_concat(ops, (_, i) => `r[_${i}.id][k]=_${i}.value(w,_${i}.get);`) + '}',
        ops
      )
    : () => {};

  const w = {
    i0: 0,
    i1: 0,
    index: 0,
    size: 0,
    peer: isPeer,

    init(partition, peers, results, group) {
      w.index = w.i0 = w.i1 = 0;
      w.size = peers.length;
      rows = partition;
      peer = peers;
      result = results;
      key = group;

      // initialize aggregates
      cells = aggrs ? aggrs.map(aggr => aggr.init()) : null;

      // initialize window ops
      for (let i = 0; i < numOps; ++i) {
        ops[i].init();
      }

      return w;
    },

    value(index, get) {
      return get(rows[index], data);
    },

    step(idx) {
      const [f0, f1] = frame;
      const n = w.size;
      const p0 = w.i0;
      const p1 = w.i1;

      w.i0 = f0 != null ? Math.max(0, idx - Math.abs(f0)) : 0;
      w.i1 = f1 != null ? Math.min(n, idx + Math.abs(f1) + 1) : n;
      w.index = idx;

      if (adjust) {
        if (w.i0 > 0 && isPeer(w.i0)) {
          w.i0 = standalone_window_state_bisect.left(peer, peer[w.i0]);
        }
        if (w.i1 < n && isPeer(w.i1)) {
          w.i1 = standalone_window_state_bisect.right(peer, peer[w.i1 - 1]);
        }
      }

      // evaluate aggregates
      for (let i = 0; i < numAgg; ++i) {
        const aggr = aggrs[i];
        const cell = cells[i];
        for (let j = p0; j < w.i0; ++j) {
          aggr.rem(cell, rows[j], data);
        }
        for (let j = p1; j < w.i1; ++j) {
          aggr.add(cell, rows[j], data);
        }
        aggr.write(cell, result, key);
      }

      // evaluate window ops
      evaluate(w, result, key);

      return result;
    }
  };

  return w;
}
;// ../../node_modules/arquero/src/engine/window/window.js






const standalone_frameValue = op =>
  (op.frame || [null, null]).map(v => Number.isFinite(v) ? Math.abs(v) : null);

const standalone_peersValue = op => !!op.peers;

function standalone_windowOp(spec) {
  const { id, name, fields = [], params = [] } = spec;
  const op = standalone_getWindow(name).create(...params);
  if (fields.length) op.get = fields[0];
  op.id = id;
  return op;
}

function standalone_window_window(table, cols, exprs, result = {}, ops) {
  // instantiate window states
  const data = table.data();
  const states = standalone_windowStates(ops, data);
  const nstate = states.length;

  const write = standalone_util_unroll(
    ['r', 'd', 'op'],
    '{' + standalone_concat(cols, (_, i) => `_${i}[r] = $${i}(r, d, op);`) + '}',
    cols, exprs
  );

  // scan each ordered partition
  table.partitions().forEach((rows, key) => {
    const size = rows.length;
    const peers = standalone_windowPeers(table, rows);

    // initialize window states
    for (let i = 0; i < nstate; ++i) {
      states[i].init(rows, peers, result, key);
    }

    // calculate window values per-row
    const op = id => result[id][key];
    for (let index = 0; index < size; ++index) {
      // advance window frame, updates result object
      for (let i = 0; i < nstate; ++i) {
        states[i].step(index);
      }
      write(rows[index], data, op);
    }
  });
}

function standalone_windowStates(ops, data) {
  const map = {};

  // group operations by window frame parameters
  ops.forEach(op => {
    const frame = standalone_frameValue(op);
    const peers = standalone_peersValue(op);
    const key = `${frame},${peers}`;
    const { aggOps, winOps } = map[key] || (map[key] = {
      frame,
      peers,
      aggOps: [],
      winOps: []
    });
    standalone_hasAggregate(op.name)
      ? aggOps.push(op)
      : winOps.push(standalone_windowOp(op));
  });

  return Object.values(map).map(_ => standalone_window_state(
    data, _.frame, _.peers, _.winOps,
    standalone_reducers(_.aggOps, _.frame[0] != null ? -1 : 1)
  ));
}

function standalone_windowPeers(table, rows) {
  if (table.isOrdered()) {
    // generate peer ids for sort equality checking
    const compare = table.comparator();
    const data = table.data();
    const nrows = rows.length;
    const peers = new Uint32Array(nrows);
    for (let i = 1, index = 0; i < nrows; ++i) {
      peers[i] = compare(rows[i - 1], rows[i], data) ? ++index : index;
    }
    return peers;
  } else {
    // no sort, no peers: reuse row indices as peer ids
    return rows;
  }
}
;// ../../node_modules/arquero/src/engine/derive.js






function standalone_isWindowed(op) {
  return standalone_hasWindow(op.name) ||
    op.frame && (
      Number.isFinite(op.frame[0]) ||
      Number.isFinite(op.frame[1])
    );
}

/* harmony default export */ function standalone_engine_derive(table, { names, exprs, ops }, options = {}) {
  // instantiate output data
  const total = table.totalRows();
  const cols = standalone_column_set(options.drop ? null : table);
  const data = names.map(name => cols.add(name, Array(total)));

  // analyze operations, compute non-windowed aggregates
  const [ aggOps, winOps ] = standalone_segmentOps(ops);

  const size = table.isGrouped() ? table.groups().size : 1;
  const result = standalone_aggregate(
    table, aggOps,
    standalone_util_repeat(ops.length, () => Array(size))
  );

  // perform table scans to generate output values
  winOps.length
    ? standalone_window_window(table, data, exprs, result, winOps)
    : standalone_derive_output(table, data, exprs, result);

  return table.create(cols);
}

function standalone_segmentOps(ops) {
  const aggOps = [];
  const winOps = [];
  const n = ops.length;

  for (let i = 0; i < n; ++i) {
    const op = ops[i];
    op.id = i;
    (standalone_isWindowed(op) ? winOps : aggOps).push(op);
  }

  return [aggOps, winOps];
}

function standalone_derive_output(table, cols, exprs, result) {
  const bits = table.mask();
  const data = table.data();
  const { keys } = table.groups() || {};
  const op = keys
    ? (id, row) => result[id][keys[row]]
    : id => result[id][0];

  const m = cols.length;
  for (let j = 0; j < m; ++j) {
    const get = exprs[j];
    const col = cols[j];

    // inline the following for performance:
    // table.scan((i, data) => col[i] = get(i, data, op));
    if (bits) {
      for (let i = bits.next(0); i >= 0; i = bits.next(i + 1)) {
        col[i] = get(i, data, op);
      }
    } else {
      const n = table.totalRows();
      for (let i = 0; i < n; ++i) {
        col[i] = get(i, data, op);
      }
    }
  }
}
;// ../../node_modules/arquero/src/verbs/derive.js




/* harmony default export */ function standalone_verbs_derive(table, values, options = {}) {
  const dt = standalone_engine_derive(table, standalone_expression_parse(values, { table }), options);

  return options.drop || (options.before == null && options.after == null)
    ? dt
    : standalone_relocate(dt,
        Object.keys(values).filter(name => !table.column(name)),
        options
      );
}
;// ../../node_modules/arquero/src/verbs/except.js
/* harmony default export */ function standalone_except(table, others) {
  if (others.length === 0) return table;
  const names = table.columnNames();
  return others.reduce((a, b) => a.antijoin(b.select(names)), table).dedupe();
}
;// ../../node_modules/arquero/src/table/bit-set.js
const standalone_ONE = 0x80000000;
const standalone_bit_set_ALL = 0xFFFFFFFF;

/**
 * Represent an indexable set of bits.
 */
class standalone_bit_set_BitSet {
  /**
   * Instantiate a new BitSet instance.
   * @param {number} size The number of bits.
   */
  constructor(size) {
    this._size = size;
    this._bits = new Uint32Array(Math.ceil(size / 32));
  }

  /**
   * The number of bits.
   * @return {number}
   */
  get length() {
    return this._size;
  }

  /**
   * The number of bits set to one.
   * https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
   * @return {number}
   */
  count() {
    const n = this._bits.length;
    let count = 0;
    for (let i = 0; i < n; ++i) {
      for (let b = this._bits[i]; b; ++count) {
        b &= b - 1;
      }
    }
    return count;
  }

  /**
   * Get the bit at a given index.
   * @param {number} i The bit index.
   */
  get(i) {
    return this._bits[i >> 5] & (standalone_ONE >>> i);
  }

  /**
   * Set the bit at a given index to one.
   * @param {number} i The bit index.
   */
  set(i) {
    this._bits[i >> 5] |= (standalone_ONE >>> i);
  }

  /**
   * Clear the bit at a given index to zero.
   * @param {number} i The bit index.
   */
  clear(i) {
    this._bits[i >> 5] &= ~(standalone_ONE >>> i);
  }

  /**
   * Scan the bits, invoking a callback function with the index of
   * each non-zero bit.
   * @param {(i: number) => void} fn A callback function.
   */
  scan(fn) {
    for (let i = this.next(0); i >= 0; i = this.next(i + 1)) {
      fn(i);
    }
  }

  /**
   * Get the next non-zero bit starting from a given index.
   * @param {number} i The bit index.
   */
  next(i) {
    const bits = this._bits;
    const n = bits.length;

    let index = i >> 5;
    let curr = bits[index] & (standalone_bit_set_ALL >>> i);

    for (; index < n; curr = bits[++index]) {
      if (curr !== 0) {
        return (index << 5) + Math.clz32(curr);
      }
    }

    return -1;
  }

  /**
   * Return the index of the nth non-zero bit.
   * @param {number} n The number of non-zero bits to advance.
   * @return {number} The index of the nth non-zero bit.
   */
  nth(n) {
    let i = this.next(0);
    while (n-- && i >= 0) i = this.next(i + 1);
    return i;
  }

  /**
   * Negate all bits in this bitset.
   * Modifies this BitSet in place.
   * @return {this}
   */
  not() {
    const bits = this._bits;
    const n = bits.length;

    // invert all bits
    for (let i = 0; i < n; ++i) {
      bits[i] = ~bits[i];
    }

    // unset extraneous trailing bits
    const tail = this._size % 32;
    if (tail) {
      bits[n - 1] &= standalone_ONE >> (tail - 1);
    }

    return this;
  }

  /**
   * Compute the logical AND of this BitSet and another.
   * @param {BitSet} bitset The BitSet to combine with.
   * @return {BitSet} This BitSet updated with the logical AND.
   */
  and(bitset) {
    if (bitset) {
      const a = this._bits;
      const b = bitset._bits;
      const n = a.length;

      for (let i = 0; i < n; ++i) {
        a[i] &= b[i];
      }
    }
    return this;
  }

  /**
   * Compute the logical OR of this BitSet and another.
   * @param {BitSet} bitset The BitSet to combine with.
   * @return {BitSet} This BitSet updated with the logical OR.
   */
  or(bitset) {
    if (bitset) {
      const a = this._bits;
      const b = bitset._bits;
      const n = a.length;

      for (let i = 0; i < n; ++i) {
        a[i] |= b[i];
      }
    }
    return this;
  }
}
;// ../../node_modules/arquero/src/engine/filter.js


/* harmony default export */ function standalone_engine_filter(table, predicate) {
  const n = table.totalRows();
  const bits = table.mask();
  const data = table.data();
  const filter = new standalone_bit_set_BitSet(n);

  // inline the following for performance:
  // table.scan((row, data) => { if (predicate(row, data)) filter.set(row); });
  if (bits) {
    for (let i = bits.next(0); i >= 0; i = bits.next(i + 1)) {
      if (predicate(i, data)) filter.set(i);
    }
  } else {
    for (let i = 0; i < n; ++i) {
      if (predicate(i, data)) filter.set(i);
    }
  }

  return table.create({ filter });
}
;// ../../node_modules/arquero/src/verbs/filter.js




/* harmony default export */ function standalone_verbs_filter(table, criteria) {
  const test = standalone_expression_parse({ p: criteria }, { table });
  let predicate = test.exprs[0];
  if (test.ops.length) {
    const { data } = standalone_engine_derive(table, test, { drop: true }).column('p');
    predicate = row => data[row];
  }
  return standalone_engine_filter(table, predicate);
}
;// ../../node_modules/arquero/src/engine/unroll.js




/* harmony default export */ function standalone_engine_unroll(table, { names = [], exprs = [], ops = [] }, options = {}) {
  if (!names.length) return table;

  const limit = options.limit > 0 ? +options.limit : Infinity;
  const index = options.index
    ? options.index === true ? 'index' : options.index + ''
    : null;
  const drop = new Set(options.drop);
  const get = standalone_aggregateGet(table, ops, exprs);

  // initialize output columns
  const cols = standalone_column_set();
  const nset = new Set(names);
  const priors = [];
  const copies = [];
  const unroll = [];

  // original and copied columns
  table.columnNames().forEach(name => {
    if (!drop.has(name)) {
      const col = cols.add(name, []);
      if (!nset.has(name)) {
        priors.push(table.column(name));
        copies.push(col);
      }
    }
  });

  // unrolled output columns
  names.forEach(name => {
    if (!drop.has(name)) {
      if (!cols.has(name)) cols.add(name, []);
      unroll.push(cols.data[name]);
    }
  });

  // index column, if requested
  const icol = index ? cols.add(index, []) : null;

  let start = 0;
  const m = priors.length;
  const n = unroll.length;

  const copy = (row, maxlen) => {
    for (let i = 0; i < m; ++i) {
      copies[i].length = start + maxlen;
      copies[i].fill(priors[i].get(row), start, start + maxlen);
    }
  };

  const indices = icol
    ? (row, maxlen) => {
        for (let i = 0; i < maxlen; ++i) {
          icol[row + i] = i;
        }
      }
    : () => {};

  if (n === 1) {
    // optimize common case of one array-valued column
    const fn = get[0];
    const col = unroll[0];

    table.scan((row, data) => {
      // extract array data
      const array = standalone_to_array(fn(row, data));
      const maxlen = Math.min(array.length, limit);

      // copy original table data
      copy(row, maxlen);

      // copy unrolled array data
      for (let j = 0; j < maxlen; ++j) {
        col[start + j] = array[j];
      }

      // fill in array indices
      indices(start, maxlen);

      start += maxlen;
    });
  } else {
    table.scan((row, data) => {
      let maxlen = 0;

      // extract parallel array data
      const arrays = get.map(fn => {
        const value = standalone_to_array(fn(row, data));
        maxlen = Math.min(Math.max(maxlen, value.length), limit);
        return value;
      });

      // copy original table data
      copy(row, maxlen);

      // copy unrolled array data
      for (let i = 0; i < n; ++i) {
        const col = unroll[i];
        const arr = arrays[i];
        for (let j = 0; j < maxlen; ++j) {
          col[start + j] = arr[j];
        }
      }

      // fill in array indices
      indices(start, maxlen);

      start += maxlen;
    });
  }

  return table.create(cols.new());
}
;// ../../node_modules/arquero/src/engine/fold.js



/* harmony default export */ function standalone_fold(table, { names = [], exprs = [], ops = [] }, options = {}) {
  if (names.length === 0) return table;

  const [k = 'key', v = 'value'] = options.as || [];
  const vals = standalone_aggregateGet(table, ops, exprs);

  return standalone_engine_unroll(
    table,
    {
      names: [k, v],
      exprs: [() => names, (row, data) => vals.map(fn => fn(row, data))]
    },
    { ...options, drop: names }
  );
}
;// ../../node_modules/arquero/src/verbs/util/parse.js











/* harmony default export */ function standalone_util_parse(name, table, params, options = { window: false }) {
  const exprs = new Map();

  const marshal = param => {
    param = standalone_is_number(param) ? table.columnName(param) : param;
    standalone_is_string(param) ? exprs.set(param, standalone_helpers_field(param))
      : standalone_util_is_function(param) ? standalone_selection_resolve(table, param).forEach(marshal)
      : standalone_is_object(param) ? standalone_util_assign(exprs, param)
      : standalone_util_error(`Invalid ${name} value: ${param+''}`);
  };

  standalone_to_array(params).forEach(marshal);

  if (options.preparse) {
    options.preparse(exprs);
  }

  return standalone_expression_parse(exprs, { table, ...options });
}
;// ../../node_modules/arquero/src/verbs/fold.js



/* harmony default export */ function standalone_verbs_fold(table, values, options) {
  return standalone_fold(table, standalone_util_parse('fold', table, values), options);
}
;// ../../node_modules/arquero/src/engine/impute.js






/* harmony default export */ function standalone_impute(table, values, keys, arrays) {
  const write = keys && keys.length;
  return standalone_impute_impute(
    write ? standalone_impute_expand(table, keys, arrays) : table,
    values,
    write
  );
}

function standalone_impute_impute(table, { names, exprs, ops }, write) {
  const gets = standalone_aggregateGet(table, ops, exprs);
  const cols = write ? null : standalone_column_set(table);
  const rows = table.totalRows();

  names.forEach((name, i) => {
    const col = table.column(name);
    const out = write ? col.data : cols.add(name, Array(rows));
    const get = gets[i];

    table.scan(idx => {
      const v = col.get(idx);
      out[idx] = !standalone_is_valid(v) ? get(idx) : v;
    });
  });

  return write ? table : table.create(cols);
}

function standalone_impute_expand(table, keys, values) {
  const groups = table.groups();
  const data = table.data();

  // expansion keys and accessors
  const keyNames = (groups ? groups.names : []).concat(keys);
  const keyGet = (groups ? groups.get : [])
    .concat(keys.map(key => table.getter(key)));

  // build hash of existing rows
  const hash = new Set();
  const keyTable = standalone_key_function(keyGet);
  table.scan((idx, data) => hash.add(keyTable(idx, data)));

  // initialize output table data
  const names = table.columnNames();
  const cols = standalone_column_set();
  const out = names.map(name => cols.add(name, []));
  names.forEach((name, i) => {
    const old = data[name];
    const col = out[i];
    table.scan(row => col.push(old.get(row)));
  });

  // enumerate expanded value sets and augment output table
  const keyEnum = standalone_key_function(keyGet.map((k, i) => a => a[i]));
  const set = standalone_util_unroll(
    'v',
    '{' + out.map((_, i) => `_${i}.push(v[$${i}]);`).join('') + '}',
    out, names.map(name => keyNames.indexOf(name))
  );

  if (groups) {
    let row = groups.keys.length;
    const prod = values.reduce((p, a) => p * a.length, groups.size);
    const keys = new Uint32Array(prod + (row - hash.size));
    keys.set(groups.keys);
    standalone_enumerate(groups, values, (vec, idx) => {
      if (!hash.has(keyEnum(vec))) {
        set(vec);
        keys[row++] = idx[0];
      }
    });
    cols.groupby({ ...groups, keys });
  } else {
    standalone_enumerate(groups, values, vec => {
      if (!hash.has(keyEnum(vec))) set(vec);
    });
  }

  return table.create(cols.new());
}

function standalone_enumerate(groups, values, callback) {
  const offset = groups ? groups.get.length : 0;
  const pad = groups ? 1 : 0;
  const len = pad + values.length;
  const lens = new Int32Array(len);
  const idxs = new Int32Array(len);
  const set = [];

  if (groups) {
    const { get, rows, size } = groups;
    lens[0] = size;
    set.push((vec, idx) => {
      const row = rows[idx];
      for (let i = 0; i < offset; ++i) {
        vec[i] = get[i](row);
      }
    });
  }

  values.forEach((a, i) => {
    const j = i + offset;
    lens[i + pad] = a.length;
    set.push((vec, idx) => vec[j] = a[idx]);
  });

  const vec = Array(offset + values.length);

  // initialize value vector
  for (let i = 0; i < len; ++i) {
    set[i](vec, 0);
  }
  callback(vec, idxs);

  // enumerate all combinations of values
  for (let i = len - 1; i >= 0;) {
    const idx = ++idxs[i];
    if (idx < lens[i]) {
      set[i](vec, idx);
      callback(vec, idxs);
      i = len - 1;
    } else {
      idxs[i] = 0;
      set[i](vec, 0);
      --i;
    }
  }
}
;// ../../node_modules/arquero/src/engine/rollup.js



/* harmony default export */ function standalone_rollup(table, { names, exprs, ops }) {
  // output data
  const cols = standalone_column_set();
  const groups = table.groups();

  // write groupby fields to output
  if (groups) standalone_groupOutput(cols, groups);

  // compute and write aggregate output
  standalone_rollup_output(names, exprs, groups, standalone_aggregate(table, ops), cols);

  // return output table
  return table.create(cols.new());
}

function standalone_rollup_output(names, exprs, groups, result = [], cols) {
  if (!exprs.length) return;
  const size = groups ? groups.size : 1;
  const op = (id, row) => result[id][row];
  const n = names.length;

  for (let i = 0; i < n; ++i) {
    const get = exprs[i];
    if (get.field != null) {
      // if expression is op only, use aggregates directly
      cols.add(names[i], result[get.field]);
    } else if (size > 1) {
      // if multiple groups, evaluate expression for each
      const col = cols.add(names[i], Array(size));
      for (let j = 0; j < size; ++j) {
        col[j] = get(j, null, op);
      }
    } else {
      // if only one group, no need to loop
      cols.add(names[i], [ get(0, null, op) ]);
    }
  }
}
;// ../../node_modules/arquero/src/verbs/impute.js








/* harmony default export */ function standalone_verbs_impute(table, values, options = {}) {
  values = standalone_expression_parse(values, { table });

  values.names.forEach(name =>
    table.column(name) ? 0 : standalone_util_error(`Invalid impute column ${standalone_to_string(name)}`)
  );

  if (options.expand) {
    const opt = { preparse: standalone_preparse, aggronly: true };
    const params = standalone_util_parse('impute', table, options.expand, opt);
    const result = standalone_rollup(table.ungroup(), params);
    return standalone_impute(
      table, values, params.names,
      params.names.map(name => result.get(name, 0))
    );
  } else {
    return standalone_impute(table, values);
  }
}

// map direct field reference to "unique" aggregate
function standalone_preparse(map) {
  map.forEach((value, key) =>
    value.field ? map.set(key, standalone_array_agg_distinct(value + '')) : 0
  );
}
;// ../../node_modules/arquero/src/verbs/intersect.js
/* harmony default export */ function standalone_verbs_intersect(table, others) {
  const names = table.columnNames();
  return others.length
    ? others.reduce((a, b) => a.semijoin(b.select(names)), table).dedupe()
    : table.reify([]);
}
;// ../../node_modules/arquero/src/engine/join/lookup.js
function standalone_rowLookup(table, hash) {
  const lut = new Map();
  table.scan((row, data) => {
    const key = hash(row, data);
    if (key != null && key === key) {
      lut.set(key, row);
    }
  });
  return lut;
}

function standalone_indexLookup(idx, data, hash) {
  const lut = new Map();
  const n = idx.length;
  for (let i = 0; i < n; ++i) {
    const row = idx[i];
    const key = hash(row, data);
    if (key != null && key === key) {
      lut.has(key)
        ? lut.get(key).push(i)
        : lut.set(key, [i]);
    }
  }
  return lut;
}
;// ../../node_modules/arquero/src/engine/join.js






function standalone_emitter(columns, getters) {
  const args = ['i', 'a', 'j', 'b'];
  return standalone_util_unroll(
    args,
    '{' + standalone_concat(columns, (_, i) => `_${i}.push($${i}(${args}));`) + '}',
    columns, getters
  );
}

/* harmony default export */ function standalone_engine_join(tableL, tableR, predicate, { names, exprs }, options = {}) {
  // initialize data for left table
  const dataL = tableL.data();
  const idxL = tableL.indices(false);
  const nL = idxL.length;
  const hitL = new Int32Array(nL);

  // initialize data for right table
  const dataR = tableR.data();
  const idxR = tableR.indices(false);
  const nR = idxR.length;
  const hitR = new Int32Array(nR);

  // initialize output data
  const ncols = names.length;
  const cols = standalone_column_set();
  const columns = Array(ncols);
  const getters = Array(ncols);
  for (let i = 0; i < names.length; ++i) {
    columns[i] = cols.add(names[i], []);
    getters[i] = exprs[i];
  }
  const emit = standalone_emitter(columns, getters);

  // perform join
  const join = standalone_is_array(predicate) ? standalone_hashJoin : standalone_loopJoin;
  join(emit, predicate, dataL, dataR, idxL, idxR, hitL, hitR, nL, nR);

  if (options.left) {
    for (let i = 0; i < nL; ++i) {
      if (!hitL[i]) {
        emit(idxL[i], dataL, -1, dataR);
      }
    }
  }

  if (options.right) {
    for (let j = 0; j < nR; ++j) {
      if (!hitR[j]) {
        emit(-1, dataL, idxR[j], dataR);
      }
    }
  }

  return tableL.create(cols.new());
}

function standalone_loopJoin(emit, predicate, dataL, dataR, idxL, idxR, hitL, hitR, nL, nR) {
  // perform nested-loops join
  for (let i = 0; i < nL; ++i) {
    const rowL = idxL[i];
    for (let j = 0; j < nR; ++j) {
      const rowR = idxR[j];
      if (predicate(rowL, dataL, rowR, dataR)) {
        emit(rowL, dataL, rowR, dataR);
        hitL[i] = 1;
        hitR[j] = 1;
      }
    }
  }
}

function standalone_hashJoin(emit, [keyL, keyR], dataL, dataR, idxL, idxR, hitL, hitR, nL, nR) {
  // determine which table to hash
  let dataScan, keyScan, hitScan, idxScan;
  let dataHash, keyHash, hitHash, idxHash;
  let emitScan = emit;
  if (nL >= nR) {
    dataScan = dataL; keyScan = keyL; hitScan = hitL; idxScan = idxL;
    dataHash = dataR; keyHash = keyR; hitHash = hitR; idxHash = idxR;
  } else {
    dataScan = dataR; keyScan = keyR; hitScan = hitR; idxScan = idxR;
    dataHash = dataL; keyHash = keyL; hitHash = hitL; idxHash = idxL;
    emitScan = (i, a, j, b) => emit(j, b, i, a);
  }

  // build lookup table
  const lut = standalone_indexLookup(idxHash, dataHash, keyHash);

  // scan other table
  const m = idxScan.length;
  for (let j = 0; j < m; ++j) {
    const rowScan = idxScan[j];
    const list = lut.get(keyScan(rowScan, dataScan));
    if (list) {
      const n = list.length;
      for (let k = 0; k < n; ++k) {
        const i = list[k];
        emitScan(rowScan, dataScan, idxHash[i], dataHash);
        hitHash[i] = 1;
      }
      hitScan[j] = 1;
    }
  }
}
;// ../../node_modules/arquero/src/verbs/util/parse-key.js










/* harmony default export */ function standalone_parse_key(name, table, params) {
  const exprs = new Map();

  standalone_to_array(params).forEach((param, i) => {
    param = standalone_is_number(param) ? table.columnName(param) : param;
    standalone_is_string(param) ? exprs.set(i, standalone_helpers_field(param))
      : standalone_util_is_function(param) || standalone_is_object(param) && param.expr ? exprs.set(i, param)
      : standalone_util_error(`Invalid ${name} key value: ${param+''}`);
  });

  const fn = standalone_expression_parse(exprs, { table, aggregate: false, window: false });
  return standalone_key_function(fn.exprs, true);
}
;// ../../node_modules/arquero/src/util/intersect.js
function standalone_intersect_intersect(a, b) {
  const set = new Set(b);
  return a.filter(x => set.has(x));
}
;// ../../node_modules/arquero/src/verbs/util/join-keys.js






function standalone_inferKeys(tableL, tableR, on) {
  if (!on) {
    // perform natural join if join condition not provided
    const isect = standalone_intersect_intersect(tableL.columnNames(), tableR.columnNames());
    if (!isect.length) standalone_util_error('Natural join requires shared column names.');
    on = [isect, isect];
  } else if (standalone_is_string(on)) {
    on = [on, on];
  } else if (standalone_is_array(on) && on.length === 1) {
    on = [on[0], on[0]];
  }

  return on;
}

function standalone_keyPredicate(tableL, tableR, onL, onR) {
  if (onL.length !== onR.length) {
    standalone_util_error('Mismatched number of join keys');
  }
  return [
    standalone_parse_key('join', tableL, onL),
    standalone_parse_key('join', tableR, onR)
  ];
}
;// ../../node_modules/arquero/src/verbs/join.js










const standalone_OPT_L = { aggregate: false, window: false };
const standalone_OPT_R = { ...standalone_OPT_L, index: 1 };

/* harmony default export */ function standalone_verbs_join(tableL, tableR, on, values, options = {}) {
  on = standalone_inferKeys(tableL, tableR, on);
  const optParse = { join: [tableL, tableR] };
  let predicate;

  if (standalone_is_array(on)) {
    const [onL, onR] = on.map(standalone_to_array);
    predicate = standalone_keyPredicate(tableL, tableR, onL, onR);

    if (!values) {
      // infer output columns, suppress duplicated key columns
      values = standalone_inferValues(tableL, onL, onR, options);
    }
  } else {
    predicate = standalone_expression_parse({ on }, optParse).exprs[0];

    if (!values) {
      // include all table columns if values not provided
      values = [standalone_selection_all(), standalone_selection_all()];
    }
  }

  return standalone_engine_join(
    tableL, tableR, predicate,
    standalone_parseValues(tableL, tableR, values, optParse, options && options.suffix),
    options
  );
}

function standalone_inferValues(tableL, onL, onR, options) {
  const isect = [];
  onL.forEach((s, i) => standalone_is_string(s) && s === onR[i] ? isect.push(s) : 0);
  const vR = standalone_not(isect);

  if (options.left && options.right) {
    // for full join, merge shared key columns together
    const shared = new Set(isect);
    return [
      tableL.columnNames().map(s => {
        const c = `[${standalone_to_string(s)}]`;
        return shared.has(s)
          ? { [s]: `(a, b) => a${c} == null ? b${c} : a${c}` }
          : s;
      }),
      vR
    ];
  }

  return options.right ? [vR, standalone_selection_all()] : [standalone_selection_all(), vR];
}

function standalone_parseValues(tableL, tableR, values, optParse, suffix = []) {
  if (standalone_is_array(values)) {
    let vL, vR, vJ, n = values.length;
    vL = vR = vJ = { names: [], exprs: [] };

    if (n--) {
      vL = standalone_util_parse('join', tableL, values[0], optParse);
    }
    if (n--) {
      vR = standalone_util_parse('join', tableR, values[1], standalone_OPT_R);
    }
    if (n--) {
      vJ = standalone_expression_parse(values[2], optParse);
    }

    // handle name collisions
    const rename = new Set();
    const namesL = new Set(vL.names);
    vR.names.forEach(name => {
      if (namesL.has(name)) {
        rename.add(name);
      }
    });
    if (rename.size) {
      standalone_rekey(vL.names, rename, suffix[0] || '_1');
      standalone_rekey(vR.names, rename, suffix[1] || '_2');
    }

    return {
      names: vL.names.concat(vR.names, vJ.names),
      exprs: vL.exprs.concat(vR.exprs, vJ.exprs)
    };
  } else {
    return standalone_expression_parse(values, optParse);
  }
}

function standalone_rekey(names, rename, suffix) {
  names.forEach((name, i) => rename.has(name)
    ? (names[i] = name + suffix)
    : 0);
}
;// ../../node_modules/arquero/src/engine/join-filter.js




/* harmony default export */ function standalone_join_filter(tableL, tableR, predicate, options = {}) {
  // calculate semi-join filter mask
  const filter = new standalone_bit_set_BitSet(tableL.totalRows());
  const join = standalone_is_array(predicate) ? standalone_hashSemiJoin : standalone_loopSemiJoin;
  join(filter, tableL, tableR, predicate);

  // if anti-join, negate the filter
  if (options.anti) {
    filter.not().and(tableL.mask());
  }

  return tableL.create({ filter });
}

function standalone_hashSemiJoin(filter, tableL, tableR, [keyL, keyR]) {
  // build lookup table
  const lut = standalone_rowLookup(tableR, keyR);

  // scan table, update filter with matches
  tableL.scan((rowL, data) => {
    const rowR = lut.get(keyL(rowL, data));
    if (rowR >= 0) filter.set(rowL);
  });
}

function standalone_loopSemiJoin(filter, tableL, tableR, predicate) {
  const nL = tableL.numRows();
  const nR = tableR.numRows();
  const dataL = tableL.data();
  const dataR = tableR.data();

  if (tableL.isFiltered() || tableR.isFiltered()) {
    // use indices as at least one table is filtered
    const idxL = tableL.indices(false);
    const idxR = tableR.indices(false);
    for (let i = 0; i < nL; ++i) {
      const rowL = idxL[i];
      for (let j = 0; j < nR; ++j) {
        if (predicate(rowL, dataL, idxR[j], dataR)) {
          filter.set(rowL);
          break;
        }
      }
    }
  } else {
    // no filters, enumerate row indices directly
    for (let i = 0; i < nL; ++i) {
      for (let j = 0; j < nR; ++j) {
        if (predicate(i, dataL, j, dataR)) {
          filter.set(i);
          break;
        }
      }
    }
  }
}

// export default function(tableL, tableR, predicate, options = {}) {
//   const filter = new BitSet(tableL.totalRows());
//   const nL = tableL.numRows();
//   const nR = tableR.numRows();
//   const dataL = tableL.data();
//   const dataR = tableR.data();

//   if (tableL.isFiltered() || tableR.isFiltered()) {
//     // use indices as at least one table is filtered
//     const idxL = tableL.indices(false);
//     const idxR = tableR.indices(false);
//     for (let i = 0; i < nL; ++i) {
//       const rowL = idxL[i];
//       for (let j = 0; j < nR; ++j) {
//         if (predicate(rowL, dataL, idxR[j], dataR)) {
//           filter.set(rowL);
//           break;
//         }
//       }
//     }
//   } else {
//     // no filters, enumerate row indices directly
//     for (let i = 0; i < nL; ++i) {
//       for (let j = 0; j < nR; ++j) {
//         if (predicate(i, dataL, j, dataR)) {
//           filter.set(i);
//           break;
//         }
//       }
//     }
//   }

//   // if anti-join, negate the filter
//   if (options.anti) {
//     filter.not().and(tableL.mask());
//   }

//   return tableL.create({ filter });
// }
;// ../../node_modules/arquero/src/verbs/join-filter.js






/* harmony default export */ function standalone_verbs_join_filter(tableL, tableR, on, options) {
  on = standalone_inferKeys(tableL, tableR, on);

  const predicate = standalone_is_array(on)
    ? standalone_keyPredicate(tableL, tableR, ...on.map(standalone_to_array))
    : standalone_expression_parse({ on }, { join: [tableL, tableR] }).exprs[0];

  return standalone_join_filter(tableL, tableR, predicate, options);
}
;// ../../node_modules/arquero/src/engine/lookup.js







/* harmony default export */ function standalone_engine_lookup(tableL, tableR, [keyL, keyR], { names, exprs, ops }) {
  // instantiate output data
  const cols = standalone_column_set(tableL);
  const total = tableL.totalRows();
  names.forEach(name => cols.add(name, Array(total).fill(standalone_util_null)));

  // build lookup table
  const lut = standalone_rowLookup(tableR, keyR);

  // generate setter function for lookup match
  const set = standalone_util_unroll(
    ['lr', 'rr', 'data'],
    '{' + standalone_concat(names, (_, i) => `_[${i}][lr] = $[${i}](rr, data);`) + '}',
    names.map(name => cols.data[name]),
    standalone_aggregateGet(tableR, ops, exprs)
  );

  // find matching rows, set values on match
  const dataR = tableR.data();
  tableL.scan((lrow, data) => {
    const rrow = lut.get(keyL(lrow, data));
    if (rrow >= 0) set(lrow, rrow, dataR);
  });

  return tableL.create(cols);
}
;// ../../node_modules/arquero/src/verbs/lookup.js





/* harmony default export */ function standalone_verbs_lookup(tableL, tableR, on, values) {
  on = standalone_inferKeys(tableL, tableR, on);
  return standalone_engine_lookup(
    tableL,
    tableR,
    [ standalone_parse_key('lookup', tableL, on[0]), standalone_parse_key('lookup', tableR, on[1]) ],
    standalone_util_parse('lookup', tableR, values)
  );
}
;// ../../node_modules/arquero/src/engine/pivot.js



const standalone_opt = (value, defaultValue) => value != null ? value : defaultValue;

/* harmony default export */ function standalone_pivot(table, on, values, options = {}) {
  const { keys, keyColumn } = standalone_pivot_pivotKeys(table, on, options);
  const vsep = standalone_opt(options.valueSeparator, '_');
  const namefn = values.names.length > 1
    ? (i, name) => name + vsep + keys[i]
    : i => keys[i];

  // perform separate aggregate operations for each key
  // if keys do not match, emit NaN so aggregate skips it
  // use custom toString method for proper field resolution
  const results = keys.map(
    k => standalone_aggregate(table, values.ops.map(op => {
      const fields = op.fields.map(f => {
        const fn = (r, d) => k === keyColumn[r] ? f(r, d) : NaN;
        fn.toString = () => k + ':' + f + '';
        return fn;
      });
      return { ...op, fields };
    }))
  );

  return table.create(standalone_pivot_output(values, namefn, table.groups(), results));
}

function standalone_pivot_pivotKeys(table, on, options) {
  const limit = options.limit > 0 ? +options.limit : Infinity;
  const sort = standalone_opt(options.sort, true);
  const ksep = standalone_opt(options.keySeparator, '_');

  // construct key accessor function
  const get = standalone_aggregateGet(table, on.ops, on.exprs);
  const key = get.length === 1
    ? get[0]
    : (row, data) => get.map(fn => fn(row, data)).join(ksep);

  // generate vector of per-row key values
  const kcol = Array(table.totalRows());
  table.scan((row, data) => kcol[row] = key(row, data));

  // collect unique key values
  const uniq = standalone_aggregate(
    table.ungroup(),
    [ {
      id: 0,
      name: 'array_agg_distinct',
      fields: [(row => kcol[row])], params: []
    } ]
  )[0][0];

  // get ordered set of unique key values
  const keys = sort ? uniq.sort() : uniq;

  // return key values
  return {
    keys: Number.isFinite(limit) ? keys.slice(0, limit) : keys,
    keyColumn: kcol
  };
}

function standalone_pivot_output({ names, exprs }, namefn, groups, results) {
  const size = groups ? groups.size : 1;
  const cols = standalone_column_set();
  const m = results.length;
  const n = names.length;

  let result;
  const op = (id, row) => result[id][row];

  // write groupby fields to output
  if (groups) standalone_groupOutput(cols, groups);

  // write pivot values to output
  for (let i = 0; i < n; ++i) {
    const get = exprs[i];
    if (get.field != null) {
      // if expression is op only, use aggregates directly
      for (let j = 0; j < m; ++j) {
        cols.add(namefn(j, names[i]), results[j][get.field]);
      }
    } else if (size > 1) {
      // if multiple groups, evaluate expression for each
      for (let j = 0; j < m; ++j) {
        result = results[j];
        const col = cols.add(namefn(j, names[i]), Array(size));
        for (let k = 0; k < size; ++k) {
          col[k] = get(k, null, op);
        }
      }
    } else {
      // if only one group, no need to loop
      for (let j = 0; j < m; ++j) {
        result = results[j];
        cols.add(namefn(j, names[i]), [ get(0, null, op) ]);
      }
    }
  }

  return cols.new();
}
;// ../../node_modules/arquero/src/verbs/pivot.js




// TODO: enforce aggregates only (no output changes) for values
/* harmony default export */ function standalone_verbs_pivot(table, on, values, options) {
  return standalone_pivot(
    table,
    standalone_util_parse('fold', table, on),
    standalone_util_parse('fold', table, values, { preparse: standalone_pivot_preparse, aggronly: true }),
    options
  );
}

// map direct field reference to "any" aggregate
function standalone_pivot_preparse(map) {
  map.forEach((value, key) =>
    value.field ? map.set(key, standalone_any(value + '')) : 0
  );
}
;// ../../node_modules/arquero/src/verbs/rename.js



/* harmony default export */ function standalone_rename(table, columns) {
  const map = new Map();
  table.columnNames(x => (map.set(x, x), 0));
  return standalone_engine_select(table, standalone_selection_resolve(table, columns, map));
}
;// ../../node_modules/arquero/src/verbs/rollup.js



/* harmony default export */ function standalone_verbs_rollup(table, values) {
  return standalone_rollup(table, standalone_expression_parse(values, { table, aggronly: true }));
}
;// ../../node_modules/arquero/src/util/sample.js




/* harmony default export */ function standalone_sample(buffer, replace, index, weight) {
  return (
    replace
      ? (weight ? standalone_sampleRW : standalone_sampleRU)
      : (weight ? standalone_sampleNW : standalone_sampleNU)
  )(buffer.length, buffer, index, weight);
}

// uniform sampling with replacement
// uses straightforward uniform sampling
function standalone_sampleRU(size, buffer, index) {
  const n = index.length;
  for (let i = 0; i < size; ++i) {
    buffer[i] = index[(n * standalone_random_random()) | 0];
  }
  return buffer;
}

// weighted sampling with replacement
// uses binary search lookup against cumulative weight
function standalone_sampleRW(size, buffer, index, weight) {
  const n = index.length;
  const w = new Float64Array(n);

  let sum = 0;
  for (let i = 0; i < n; ++i) {
    w[i] = (sum += weight(index[i]));
  }

  const bisect = standalone_util_bisector(standalone_util_ascending).right;
  for (let i = 0; i < size; ++i) {
    buffer[i] = index[bisect(w, sum * standalone_random_random())];
  }
  return buffer;
}

// uniform sampling without replacement
// uses reservoir sampling to build out the sample
// https://en.wikipedia.org/wiki/Reservoir_sampling
function standalone_sampleNU(size, buffer, index) {
  const n = index.length;
  if (size >= n) return index;

  for (let i = 0; i < size; ++i) {
    buffer[i] = index[i];
  }

  for (let i = size; i < n; ++i) {
    const j = i * standalone_random_random();
    if (j < size) {
      buffer[j | 0] = index[i];
    }
  }

  return buffer;
}

// weighted sample without replacement
// uses method of Efraimidis and Spirakis
// TODO: could use min-heap to improve efficiency
function standalone_sampleNW(size, buffer, index, weight) {
  const n = index.length;
  if (size >= n) return index;

  const w = new Float32Array(n);
  const k = new Uint32Array(n);
  for (let i = 0; i < n; ++i) {
    k[i] = i;
    w[i] = -Math.log(standalone_random_random()) / weight(index[i]);
  }

  k.sort((a, b) => w[a] - w[b]);
  for (let i = 0; i < size; ++i) {
    buffer[i] = index[k[i]];
  }
  return buffer;
}
;// ../../node_modules/arquero/src/util/shuffle.js


/* harmony default export */ function standalone_util_shuffle(array, lo = 0, hi = array.length) {
  let n = hi - (lo = +lo);

  while (n) {
    const i = standalone_random_random() * n-- | 0;
    const v = array[n + lo];
    array[n + lo] = array[i + lo];
    array[i + lo] = v;
  }

  return array;
}
;// ../../node_modules/arquero/src/engine/sample.js



/* harmony default export */ function standalone_engine_sample(table, size, weight, options = {}) {
  const { replace, shuffle } = options;
  const parts = table.partitions(false);

  let total = 0;
  size = parts.map((idx, group) => {
    let s = size(group);
    total += (s = (replace ? s : Math.min(idx.length, s)));
    return s;
  });

  const samples = new Uint32Array(total);
  let curr = 0;

  parts.forEach((idx, group) => {
    const sz = size[group];
    const buf = samples.subarray(curr, curr += sz);

    if (!replace && sz === idx.length) {
      // sample size === data size, no replacement
      // no need to sample, just copy indices
      buf.set(idx);
    } else {
      standalone_sample(buf, replace, idx, weight);
    }
  });

  if (shuffle !== false && (parts.length > 1 || !replace)) {
    // sampling with replacement methods shuffle, so in
    // that case a single partition is already good to go
    standalone_util_shuffle(samples);
  }

  return table.reify(samples);
}
;// ../../node_modules/arquero/src/verbs/sample.js







/* harmony default export */ function standalone_verbs_sample(table, size, options = {}) {
  return standalone_engine_sample(
    table,
    standalone_parseSize(table, size),
    standalone_parseWeight(table, options.weight),
    options
  );
}

const standalone_sample_get = col => row => col.get(row) || 0;

function standalone_parseSize(table, size) {
  return standalone_is_number(size)
    ? () => size
    : standalone_sample_get(standalone_rollup(table, standalone_expression_parse({ size }, { table })).column('size'));
}

function standalone_parseWeight(table, w) {
  if (w == null) return null;
  w = standalone_is_number(w) ? table.columnName(w) : w;
  return standalone_sample_get(
    standalone_is_string(w)
      ? table.column(w)
      : standalone_engine_derive(table, standalone_expression_parse({ w }, { table }), { drop: true }).column('w')
  );
}
;// ../../node_modules/arquero/src/verbs/select.js



/* harmony default export */ function standalone_verbs_select(table, columns) {
  return standalone_engine_select(table, standalone_selection_resolve(table, columns));
}
;// ../../node_modules/arquero/src/engine/spread.js





/* harmony default export */ function standalone_engine_spread(table, { names, exprs, ops = [] }, options = {}) {
  if (names.length === 0) return table;

  // ignore 'as' if there are multiple field names
  const as = (names.length === 1 && options.as) || [];
  const drop = options.drop == null ? true : !!options.drop;
  const limit = options.limit == null
    ? as.length || Infinity
    : Math.max(1, +options.limit || 1);

  const get = standalone_aggregateGet(table, ops, exprs);
  const cols = standalone_column_set();
  const map = names.reduce((map, name, i) => map.set(name, i), new Map());

  const add = (index, name) => {
    const columns = standalone_spread_spread(table, get[index], limit);
    const n = columns.length;
    for (let i = 0; i < n; ++i) {
      cols.add(as[i] || `${name}_${i + 1}`, columns[i]);
    }
  };

  table.columnNames().forEach(name => {
    if (map.has(name)) {
      if (!drop) cols.add(name, table.column(name));
      add(map.get(name), name);
      map.delete(name);
    } else {
      cols.add(name, table.column(name));
    }
  });

  map.forEach(add);

  return table.create(cols);
}

function standalone_spread_spread(table, get, limit) {
  const nrows = table.totalRows();
  const columns = [];

  table.scan((row, data) => {
    const values = standalone_to_array(get(row, data));
    const n = Math.min(values.length, limit);
    while (columns.length < n) {
      columns.push(Array(nrows).fill(standalone_util_null));
    }
    for (let i = 0; i < n; ++i) {
      columns[i][row] = values[i];
    }
  });

  return columns;
}
;// ../../node_modules/arquero/src/verbs/spread.js



/* harmony default export */ function standalone_verbs_spread(table, values, options) {
  return standalone_engine_spread(table, standalone_util_parse('spread', table, values), options);
}
;// ../../node_modules/arquero/src/verbs/union.js
/* harmony default export */ function standalone_verbs_union(table, others) {
  return table.concat(others).dedupe();
}
;// ../../node_modules/arquero/src/verbs/unroll.js



/* harmony default export */ function standalone_verbs_unroll(table, values, options) {
  return standalone_engine_unroll(
    table,
    standalone_util_parse('unroll', table, values),
    options && options.drop
      ? { ...options, drop: standalone_util_parse('unroll', table, options.drop).names }
      : options
  );
}
;// ../../node_modules/arquero/src/engine/groupby.js



/* harmony default export */ function standalone_groupby(table, exprs) {
  return table.create({
    groups: standalone_createGroups(table, exprs)
  });
}

function standalone_createGroups(table, { names = [], exprs = [], ops = [] }) {
  const n = names.length;
  if (n === 0) return null;

  // check for optimized path when grouping by a single field
  // use pre-calculated groups if available
  if (n === 1 && !table.isFiltered() && exprs[0].field) {
    const col = table.column(exprs[0].field);
    if (col.groups) return col.groups(names);
  }

  let get = standalone_aggregateGet(table, ops, exprs);
  const getKey = standalone_key_function(get);
  const nrows = table.totalRows();
  const keys = new Uint32Array(nrows);
  const index = {};
  const rows = [];

  // inline table scan for performance
  const data = table.data();
  const bits = table.mask();
  if (bits) {
    for (let i = bits.next(0); i >= 0; i = bits.next(i + 1)) {
      const key = getKey(i, data) + '';
      const val = index[key];
      keys[i] = val != null ? val : (index[key] = rows.push(i) - 1);
    }
  } else {
    for (let i = 0; i < nrows; ++i) {
      const key = getKey(i, data) + '';
      const val = index[key];
      keys[i] = val != null ? val : (index[key] = rows.push(i) - 1);
    }
  }

  if (!ops.length) {
    // capture data in closure, so no interaction with select
    get = get.map(f => row => f(row, data));
  }

  return { keys, get, names, rows, size: rows.length };
}
;// ../../node_modules/arquero/src/verbs/groupby.js



/* harmony default export */ function standalone_verbs_groupby(table, values) {
  return standalone_groupby(table, standalone_util_parse('groupby', table, values));
}
;// ../../node_modules/arquero/src/engine/orderby.js
/* harmony default export */ function standalone_orderby(table, comparator) {
  return table.create({ order: comparator });
}

;// ../../node_modules/arquero/src/expression/compare.js




// generate code to compare a single field
const standalone_compare_compare = (u, v, lt, gt) =>
  `((u = ${u}) < (v = ${v}) || u == null) && v != null ? ${lt}
    : (u > v || v == null) && u != null ? ${gt}
    : ((v = v instanceof Date ? +v : v), (u = u instanceof Date ? +u : u)) !== u && v === v ? ${lt}
    : v !== v && u === u ? ${gt} : `;

/* harmony default export */ function standalone_expression_compare(table, fields) {
  // parse expressions, generate code for both a and b values
  const names = [];
  const exprs = [];
  const fn = [];
  let keys = null, opA = '0', opB = '0';
  if (table.isGrouped()) {
    keys = table.groups().keys;
    opA = 'ka';
    opB = 'kb';
  }
  const { ops } = standalone_expression_parse(fields, {
    table,
    value: (name, node) => {
      names.push(name);
      if (node.escape) {
        // if an escaped function, invoke it directly
        const f = i => `fn[${fn.length}](${i}, data)`;
        exprs.push([f('a'), f('b')]);
        fn.push(node.escape);
      } else {
        // generate code to extract values to compare
        exprs.push([
          standalone_expression_codegen(node, { index: 'a', op: opA }),
          standalone_expression_codegen(node, { index: 'b', op: opB })
        ]);
      }
    },
    window: false
  });

  // calculate aggregate values if needed
  const result = standalone_aggregate(table, ops);
  const op = (id, row) => result[id][row];

  // generate comparison code for each field
  const n = names.length;
  let code = 'return (a, b) => {'
    + (op && table.isGrouped() ? 'const ka = keys[a], kb = keys[b];' : '')
    + 'let u, v; return ';
  for (let i = 0; i < n; ++i) {
    const o = fields.get(names[i]).desc ? -1 : 1;
    const [u, v] = exprs[i];
    code += standalone_compare_compare(u, v, -o, o);
  }
  code += '0;};';

  // instantiate and return comparator function
  return Function('op', 'keys', 'fn', 'data', code)(op, keys, fn, table.data());
}
;// ../../node_modules/arquero/src/verbs/orderby.js









/* harmony default export */ function standalone_verbs_orderby(table, values) {
  return standalone_orderby(table, standalone_orderby_parseValues(table, values));
}

function standalone_orderby_parseValues(table, params) {
  let index = -1;
  const exprs = new Map();
  const add = val => exprs.set(++index + '', val);

  params.forEach(param => {
    const expr = param.expr != null ? param.expr : param;

    if (standalone_is_object(expr) && !standalone_util_is_function(expr)) {
      for (const key in expr) add(expr[key]);
    } else {
      add(
        standalone_is_number(expr) ? standalone_helpers_field(param, table.columnName(expr))
          : standalone_is_string(expr) ? standalone_helpers_field(param)
          : standalone_util_is_function(expr) ? param
          : standalone_util_error(`Invalid orderby field: ${param+''}`)
      );
    }
  });

  return standalone_expression_compare(table, exprs);
}
;// ../../node_modules/arquero/src/engine/concat.js



/* harmony default export */ function standalone_engine_concat(table, others) {
  const trows = table.numRows();
  const nrows = trows + others.reduce((n, t) => n + t.numRows(), 0);
  if (trows === nrows) return table;

  const tables = [table, ...others];
  const cols = standalone_column_set();

  table.columnNames().forEach(name => {
    const arr = Array(nrows);
    let row = 0;
    tables.forEach(table => {
      const col = table.column(name) || { get: () => standalone_util_null };
      table.scan(trow => arr[row++] = col.get(trow));
    });
    cols.add(name, arr);
  });

  return table.create(cols.new());
}
;// ../../node_modules/arquero/src/engine/reduce.js



/* harmony default export */ function standalone_engine_reduce(table, reducer) {
  const cols = standalone_column_set();
  const groups = table.groups();

  // initialize groups
  const { get, names = [], rows, size = 1 } = groups || {};
  const counts = new Uint32Array(size + 1);
  names.forEach(name => cols.add(name, null));

  // compute reduced values
  const cells = groups
    ? standalone_reduceGroups(table, reducer, groups)
    : [ standalone_reduceFlat(table, reducer) ];

  // initialize output columns
  reducer.outputs().map(name => cols.add(name, []));

  // write reduced values to output columns
  const n = counts.length - 1;
  let len = 0;
  for (let i = 0; i < n; ++i) {
    len += counts[i + 1] = reducer.write(cells[i], cols.data, counts[i]);
  }

  // write group values to output columns
  if (groups) {
    const data = table.data();
    names.forEach((name, index) => {
      const column = cols.data[name] = Array(len);
      const getter = get[index];
      for (let i = 0, j = 0; i < size; ++i) {
        column.fill(getter(rows[i], data), j, j += counts[i + 1]);
      }
    });
  }

  return table.create(cols.new());
}
;// ../../node_modules/arquero/src/engine/ungroup.js
/* harmony default export */ function standalone_ungroup(table) {
  return table.isGrouped()
    ? table.create({ groups: null })
    : table;
}
;// ../../node_modules/arquero/src/engine/unorder.js
/* harmony default export */ function standalone_unorder(table) {
  return table.isOrdered()
    ? table.create({ order: null })
    : table;
}
;// ../../node_modules/arquero/src/verbs/index.js





























/* harmony default export */ const standalone_verbs = ({
  __antijoin: (table, other, on) =>
    standalone_verbs_join_filter(table, other, on, { anti: true }),
  __count: (table, options = {}) =>
    standalone_verbs_rollup(table, { [options.as || 'count']: standalone_op_api_count() }),
  __cross: (table, other, values, options) =>
    standalone_verbs_join(table, other, () => true, values, {
      ...options, left: true, right: true
    }),
  __concat: standalone_engine_concat,
  __dedupe: standalone_dedupe,
  __derive: standalone_verbs_derive,
  __except: standalone_except,
  __filter: standalone_verbs_filter,
  __fold: standalone_verbs_fold,
  __impute: standalone_verbs_impute,
  __intersect: standalone_verbs_intersect,
  __join: standalone_verbs_join,
  __lookup: standalone_verbs_lookup,
  __pivot: standalone_verbs_pivot,
  __relocate: standalone_relocate,
  __rename: standalone_rename,
  __rollup: standalone_verbs_rollup,
  __sample: standalone_verbs_sample,
  __select: standalone_verbs_select,
  __semijoin: standalone_verbs_join_filter,
  __spread: standalone_verbs_spread,
  __union: standalone_verbs_union,
  __unroll: standalone_verbs_unroll,
  __groupby: standalone_verbs_groupby,
  __orderby: standalone_verbs_orderby,
  __ungroup: standalone_ungroup,
  __unorder: standalone_unorder,
  __reduce: standalone_engine_reduce
});
;// ../../node_modules/arquero/src/table/index.js



// Add verb implementations to ColumnTable prototype
Object.assign(standalone_column_table_ColumnTable.prototype, standalone_verbs);

/**
 * Create a new table for a set of named columns.
 * @param {object|Map} columns
 *  The set of named column arrays. Keys are column names.
 *  The enumeration order of the keys determines the column indices,
 *  unless the names parameter is specified.
 *  Values must be arrays (or array-like values) of identical length.
 * @param {string[]} [names] Ordered list of column names. If specified,
 *  this array determines the column indices. If not specified, the
 *  key enumeration order of the columns object is used.
 * @return {ColumnTable} the instantiated table
 * @example table({ colA: ['a', 'b', 'c'], colB: [3, 4, 5] })
 */
function standalone_table_table(columns, names) {
  return ColumnTable.new(columns, names);
}

/**
 * Create a new table from an existing object, such as an array of
 * objects or a set of key-value pairs.
 * @param {object|Array|Map} values Data values to populate the table.
 *  If array-valued or iterable, imports rows for each non-null value,
 *  using the provided column names as keys for each row object. If no
 *  names are provided, the first non-null object's own keys are used.
 *  If object- or Map-valued, create columns for the keys and values.
 * @param {string[]} [names] Column names to include.
 *  For object or Map values, specifies the key and value column names.
 *  Otherwise, specifies the keys to look up on each row object.
 * @return {ColumnTable} the instantiated table.
 * @example from([ { colA: 1, colB: 2 }, { colA: 3, colB: 4 } ])
 */
function standalone_table_from(values, names) {
  return ColumnTable.from(values, names);
}
;// ../../node_modules/arquero/src/format/load-url.js
 // eslint-disable-line no-unused-vars








/**
 * Options for file loading.
 * @typedef {object} LoadOptions
 * @property {'arrayBuffer'|'text'|'json'} [as='text'] A string indicating
 *  the data type of the file. One of 'arrayBuffer', 'json', or 'text'.
 * @property {(data: *, options?: object) => ColumnTable} [using] A function
 *  that accepts a data payload (e.g., string or buffer) and an options object
 *  as input and returns an Arquero table (such as fromCSV or fromJSON).
 * @property {object} [fetch] Options to pass to the HTTP fetch method
 *  when loading a URL.
 */

/**
 * Load data from a file and return a Promise for an Arquero table.
 * A specific format parser can be provided with the *using* option,
 * otherwise CSV format is assumed. The options to this method are
 * passed as the second argument to the format parser.
 * @param {string} url The URL to load.
 * @param {LoadOptions & object} options The loading and formatting options.
 * @return {Promise<ColumnTable>} A Promise for an Arquero table.
 * @example aq.load('data/table.csv')
 * @example aq.load('data/table.json', { using: aq.fromJSON })
 * @example aq.load('data/table.json', { using: aq.from })
 */
function standalone_load_url_load(url, options = {}) {
  const parse = options.using || fromCSV;
  return fetch(url, options.fetch)
    .then(res => res[options.as || 'text']())
    .then(data => parse(data, options));
}

/**
 * Load an Arrow file from a URL and return a Promise for an Arquero table.
 * @param {string} url The URL to load.
 * @param {LoadOptions & import('./from-arrow').ArrowOptions} options Arrow format options.
 * @return {Promise<ColumnTable>} A Promise for an Arquero table.
 * @example aq.loadArrow('data/table.arrow')
 */
function standalone_loadArrow(url, options) {
  return standalone_load_url_load(url, { ...options, as: 'arrayBuffer', using: fromArrow });
}

/**
 * Load a CSV file from a URL and return a Promise for an Arquero table.
 * @param {string} url The URL to load.
 * @param {LoadOptions & import('./from-csv').CSVParseOptions} options CSV format options.
 * @return {Promise<ColumnTable>} A Promise for an Arquero table.
 * @example aq.loadCSV('data/table.csv')
 * @example aq.loadTSV('data/table.tsv', { delimiter: '\t' })
 */
function standalone_loadCSV(url, options) {
  return standalone_load_url_load(url, { ...options, as: 'text', using: fromCSV });
}

/**
 * Load a fixed width file from a URL and return a Promise for an Arquero table.
 * @param {string} url The URL to load.
 * @param {LoadOptions & import('./from-fixed').FixedParseOptions} options Fixed width format options.
 * @return {Promise<ColumnTable>} A Promise for an Arquero table.
 * @example aq.loadFixedWidth('data/table.txt', { names: ['name', 'city', state'], widths: [10, 20, 2] })
 */
 function standalone_loadFixed(url, options) {
  return standalone_load_url_load(url, { ...options, as: 'text', using: fromFixed });
}

/**
 * Load a JSON file from a URL and return a Promise for an Arquero table.
 * If the loaded JSON is array-valued, an array-of-objects format is assumed
 * and the aq.from method is used to construct the table. Otherwise, a
 * column object format is assumed and aq.fromJSON is applied.
 * @param {string} url The URL to load.
 * @param {LoadOptions & import('./from-json').JSONParseOptions} options JSON format options.
 * @return {Promise<ColumnTable>} A Promise for an Arquero table.
 * @example aq.loadJSON('data/table.json')
 */
function standalone_loadJSON(url, options) {
  return standalone_load_url_load(url, { ...options, as: 'json', using: standalone_load_url_parseJSON });
}

function standalone_load_url_parseJSON(data, options) {
  return isArray(data) ? from(data) : fromJSON(data, options);
}
;// ../../node_modules/arquero/src/helpers/bin.js
/**
 * Options for binning number values.
 * @typedef {object} BinOptions
 * @property {number} [maxbins] The maximum number of bins.
 * @property {number} [minstep] The minimum step size between bins.
 * @property {number} [step] The exact step size to use between bins.
 *  If specified, the maxbins and minstep options are ignored.
 * @property {boolean} [nice=true] Flag indicating if bins should
 *  snap to "nice" human-friendly values such as multiples of ten.
 * @property {number} [offset=0] Step offset for bin boundaries.
 *  The default floors to the lower bin boundary. A value of 1 snaps
 *  one step higher to the upper bin boundary, and so on.
 */

/**
 * Generate a table expression that performs uniform binning of
 * number values. The resulting string can be used as part of the
 * input to table transformation verbs.
 * @param {string} name The name of the column to bin.
 * @param {BinOptions} [options] Binning scheme options.
 * @return {string} A table expression string for binned values.
 * @example bin('colA', { maxbins: 20 })
 */
/* harmony default export */ function standalone_helpers_bin(name, options = {}) {
  const field = `d[${JSON.stringify(name)}]`;
  const { maxbins, nice, minstep, step, offset } = options;
  const args = [maxbins, nice, minstep, step];

  let n = args.length;
  while (n && args[--n] == null) args.pop();
  const a = args.length ? ', ' + args.map(a => a + '').join(', ') : '';

  return `d => op.bin(${field}, ...op.bins(${field}${a}), ${offset || 0})`;
}
;// ../../node_modules/arquero/src/verbs/helpers/agg.js
 // eslint-disable-line no-unused-vars

/**
 * Convenience function for computing a single aggregate value for
 * a table. Equivalent to ungrouping a table, applying a rollup verb
 * for a single aggregate, and extracting the resulting value.
 * @param {Table} table A table instance.
 * @param {import('../../table/transformable').TableExpr} expr An
 *   aggregate table expression to evaluate.
 * @return {import('../../table/table').DataValue} The aggregate value.
 * @example agg(table, op.max('colA'))
 * @example agg(table, d => [op.min('colA'), op.max('colA')])
 */
function standalone_agg(table, expr) {
  return table.ungroup().rollup({ _: expr }).get('_');
}
;// ../../node_modules/arquero/src/register.js













const standalone_onIllegal = (name, type) =>
  error(`Illegal ${type} name: ${toString(name)}`);

const standalone_onDefined = (name, type) =>
  error(`The ${type} ${toString(name)} is already defined. Use override option?`);

const standalone_onReserve = (name, type) =>
  error(`The ${type} name ${toString(name)} is reserved and can not be overridden.`);

function standalone_register_check(name, options, obj = ops, type = 'function') {
  if (!name) standalone_onIllegal(name, type);
  if (!options.override && has(obj, name)) standalone_onDefined(name, type);
}

// -- Op Functions --------------------------------------------------

function standalone_verifyFunction(name, def, object, options) {
  return object[name] === def || standalone_register_check(name, options);
}

/**
 * Register an aggregate or window operation.
 * @param {string} name The name of the operation
 * @param {AggregateDef|WindowDef} def The operation definition.
 * @param {object} object The registry object to add the definition to.
 * @param {RegisterOptions} [options] Registration options.
 */
function standalone_addOp(name, def, object, options = {}) {
  if (standalone_verifyFunction(name, def, object, options)) return;
  const [nf = 0, np = 0] = def.param;
  object[name] = def;
  ops[name] = (...params) => op(
    name,
    params.slice(0, nf),
    params.slice(nf, nf + np)
  );
}

/**
 * Register a custom aggregate function.
 * @param {string} name The name to use for the aggregate function.
 * @param {AggregateDef} def The aggregate operator definition.
 * @param {RegisterOptions} [options] Function registration options.
 * @throws If a function with the same name is already registered and
 *  the override option is not specified.
 */
function standalone_addAggregateFunction(name, def, options) {
  standalone_addOp(name, def, aggregateFunctions, options);
}

/**
 * Register a custom window function.
 * @param {string} name The name to use for the window function.
 * @param {WindowDef} def The window operator definition.
 * @param {RegisterOptions} [options] Function registration options.
 * @throws If a function with the same name is already registered and
 *  the override option is not specified.
 */
function standalone_addWindowFunction(name, def, options) {
  standalone_addOp(name, def, windowFunctions, options);
}

/**
 * Register a function for use within table expressions.
 * If only a single argument is provided, it will be assumed to be a
 * function and the system will try to extract its name.
 * @param {string} name The name to use for the function.
 * @param {Function} fn A standard JavaScript function.
 * @param {RegisterOptions} [options] Function registration options.
 * @throws If a function with the same name is already registered and
 *  the override option is not specified, or if no name is provided
 *  and the input function is anonymous.
 */
function standalone_addFunction(name, fn, options = {}) {
  if (arguments.length === 1) {
    fn = name;
    name = fn.name;
    if (name === '' || name === 'anonymous') {
      error('Anonymous function provided, please include a name argument.');
    } else if (name === ROW_OBJECT) {
      standalone_onReserve(ROW_OBJECT, 'function');
    }
  }
  if (standalone_verifyFunction(name, fn, functions, options)) return;
  functions[name] = fn;
  ops[name] = fn;
}

// -- Table Methods and Verbs ---------------------------------------

const standalone_proto = standalone_column_table_ColumnTable.prototype;

/**
 * Reserved table/query methods that must not be overwritten.
 */
let standalone_RESERVED;

function standalone_addReserved(obj) {
  for (; obj; obj = Object.getPrototypeOf(obj)) {
    Object.getOwnPropertyNames(obj).forEach(name => standalone_RESERVED[name] = 1);
  }
}

function standalone_verifyTableMethod(name, fn, options) {
  const type = 'method';

  // exit early if duplicate re-assignment
  if (standalone_proto[name] && standalone_proto[name].fn === fn) return true;

  // initialize reserved properties to avoid overriding internals
  if (!standalone_RESERVED) {
    standalone_RESERVED = {};
    standalone_addReserved(standalone_proto);
    standalone_addReserved(Query.prototype);
  }

  // perform name checks
  if (standalone_RESERVED[name]) standalone_onReserve(name, type);
  if ((name + '')[0] === '_') standalone_onIllegal(name, type);
  standalone_register_check(name, options, standalone_proto, type);
}

/**
 * Register a new table method. A new method will be added to the column
 * table prototype. When invoked from a table, the registered method will
 * be invoked with the table as the first argument, followed by all the
 * provided arguments.
 * @param {string} name The name of the table method.
 * @param {Function} method The table method.
 * @param {RegisterOptions} options
 */
function standalone_addTableMethod(name, method, options = {}) {
  if (standalone_verifyTableMethod(name, method, options)) return;
  standalone_proto[name] = function(...args) { return method(this, ...args); };
  standalone_proto[name].fn = method;
}

/**
 * Register a new transformation verb.
 * @param {string} name The name of the verb.
 * @param {Function} method The verb implementation.
 * @param {ParamDef[]} params The verb parameter schema.
 * @param {RegisterOptions} options Function registration options.
 */
function standalone_addVerb(name, method, params, options = {}) {
  // register table method first
  // if that doesn't throw, add serializable verb entry
  standalone_addTableMethod(name, method, options);
  addQueryVerb(name, Verbs[name] = createVerb(name, params));
}

// -- Package Bundles -----------------------------------------------

const standalone_PACKAGE = 'arquero_package';

/**
 * Add an extension package of functions, table methods, and/or verbs.
 * @param {Package|PackageBundle} bundle The package of extensions.
 * @throws If package validation fails.
 */
function standalone_addPackage(bundle, options = {}) {
  const pkg = bundle && bundle[standalone_PACKAGE] || bundle;
  const parts = {
    functions: [
      (name, def, opt) => standalone_verifyFunction(name, def, functions, opt),
      standalone_addFunction
    ],
    aggregateFunctions: [
      (name, def, opt) => standalone_verifyFunction(name, def, aggregateFunctions, opt),
      standalone_addAggregateFunction
    ],
    windowFunctions: [
      (name, def, opt) => standalone_verifyFunction(name, def, windowFunctions, opt),
      standalone_addWindowFunction
    ],
    tableMethods: [
      standalone_verifyTableMethod,
      standalone_addTableMethod
    ],
    verbs: [
      (name, obj, opt) => standalone_verifyTableMethod(name, obj.method, opt),
      (name, obj, opt) => standalone_addVerb(name, obj.method, obj.params, opt)
    ]
  };

  function scan(index) {
    for (const key in parts) {
      const part = parts[key];
      const p = pkg[key];
      for (const name in p) part[index](name, p[name], options);
    }
  }
  scan(0); // first validate package, throw if validation fails
  scan(1); // then add package content
}

/**
 * Aggregate function definition.
 * @typedef {import('./op/aggregate-functions').AggregateDef} AggregateDef
 */

/**
 * Window function definition.
 * @typedef {import('./op/window-functions').WindowDef} WindowDef
 */

/**
 * Verb parameter definition.
 * @typedef {import('./query/verb').ParamDef} ParamDef
 */

/**
 * Verb definition.
 * @typedef {object} VerbDef
 * @property {Function} method A function implementing the verb.
 * @property {ParamDef[]} params The verb parameter schema.
 */

/**
 * Verb parameter definition.
 * @typedef {object} ParamDef
 * @property {string} name The verb parameter name.
 * @property {ParamType} type The verb parameter type.
 */

/**
 * A package of op function and table method definitions.
 * @typedef {object} Package
 * @property {{[name: string]: Function}} [functions] Standard function entries.
 * @property {{[name: string]: AggregateDef}} [aggregateFunctions] Aggregate function entries.
 * @property {{[name: string]: WindowDef}} [windowFunctions] Window function entries.
 * @property {{[name: string]: Function}} [tableMethods] Table method entries.
 * @property {{[name: string]: VerbDef}} [verbs] Verb entries.
 */

/**
 * An object containing an extension package.
 * @typedef {object} PackageBundle
 * @property {Package} arquero.package The package bundle.
 */

/**
 * Options for registering new functions.
 * @typedef {object} RegisterOptions
 * @property {boolean} [override=false] Flag indicating if the added
 *  function can override an existing function with the same name.
 */
;// ../../node_modules/arquero/src/index.js
// export internal class definitions










const standalone_internal = {
  Table: standalone_Table,
  ColumnTable: standalone_column_table_ColumnTable,
  Transformable: standalone_Transformable,
  Query: standalone_query_Query,
  Reducer: standalone_Reducer,
  Verb: standalone_Verb,
  Verbs: standalone_verb_Verbs,
  columnFactory: standalone_columnFactory,
  parse: standalone_expression_parse,
  walk_ast: standalone_walk
};

// export public API

const standalone_arquero_src_version = standalone_arquero_package_namespaceObject.rE;






















;// ../../canvas_viz/dist/elements/CanvasVegaLite.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/canvas_viz/dist/elements/CanvasVegaLite.svelte generated by Svelte v3.59.2 */







function standalone_CanvasVegaLite_svelte_create_fragment(ctx) {
	let vegalite;
	let current;

	vegalite = new standalone_VegaLite_svelte({
			props: {
				spec: /*parsedSpec*/ ctx[1],
				data: /*parsedData*/ ctx[0],
				options: /*options*/ ctx[2],
				signalListeners: {
					select: /*handleSelect*/ ctx[3],
					brush: /*handleBrush*/ ctx[4]
				}
			}
		});

	return {
		c() {
			standalone_create_component(vegalite.$$.fragment);
		},
		m(target, anchor) {
			standalone_mount_component(vegalite, target, anchor);
			current = true;
		},
		p(ctx, [dirty]) {
			const vegalite_changes = {};
			if (dirty & /*parsedSpec*/ 2) vegalite_changes.spec = /*parsedSpec*/ ctx[1];
			if (dirty & /*parsedData*/ 1) vegalite_changes.data = /*parsedData*/ ctx[0];
			if (dirty & /*options*/ 4) vegalite_changes.options = /*options*/ ctx[2];
			vegalite.$set(vegalite_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(vegalite.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(vegalite.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			standalone_destroy_component(vegalite, detaching);
		}
	};
}

function standalone_binnedStringResolver(resolver, table) {
	const reduced_table = table.groupby(resolver.columnName).count();
	return { values: reduced_table };
}

function standalone_CanvasVegaLite_svelte_instance($$self, $$props, $$invalidate) {
	let reducedData;
	let { data = {} } = $$props;
	let { spec } = $$props;
	let { table } = $$props;
	let { filteredTable } = $$props;
	let { showUnfilteredData } = $$props;
	let { width = undefined } = $$props;
	let { height = undefined } = $$props;
	let { resolver = undefined } = $$props;
	const dispatch = standalone_createEventDispatcher();
	let parsedData = {};
	let parsedSpec = undefined;
	let parsedSpecRaw = undefined;
	let parsedSpecFiltered = undefined;
	let options = { actions: false };

	function parseSpecs(spec, data, reducedData, showUnfilteredData) {
		$$invalidate(1, parsedSpec = spec);
		parsedSpecRaw = Object.assign(Object.assign({}, spec), { params: [] });
		parsedSpecFiltered = Object.assign({}, spec);
		$$invalidate(0, parsedData = data);

		if (typeof data.values === "string") {
			const stringData = data.values;

			if (stringData && stringData === "arrow_table") {
				parsedSpecFiltered.data = reducedData.filtered;
				parsedSpecRaw.data = reducedData.raw;

				if (showUnfilteredData) {
					parsedSpecRaw.mark = Object.assign(Object.assign({}, parsedSpecRaw.mark), { color: "#dcdcdc" });

					$$invalidate(1, parsedSpec = {
						layer: [
							Object.assign({}, parsedSpecRaw),
							Object.assign({}, parsedSpecFiltered)
						]
					});
				} else {
					$$invalidate(1, parsedSpec = Object.assign({}, parsedSpecFiltered));
				}

				$$invalidate(0, parsedData = {});
			}
		}
	}

	function extractData(resolver, table, filteredTable) {
		if (resolver === undefined) {
			return {
				filtered: { values: filteredTable },
				raw: { values: table }
			};
		}

		switch (resolver.type) {
			case standalone_ResolverType.NUMBER:
				return {
					filtered: numberResolver(resolver, filteredTable),
					raw: numberResolver(resolver, table)
				};
			default:
				return {
					filtered: standalone_binnedStringResolver(resolver, filteredTable),
					raw: standalone_binnedStringResolver(resolver, table)
				};
		}
	}

	function numberResolver(resolver, table) {
		const reducedTable = table.groupby({
			bin_0: standalone_helpers_bin(resolver.columnName, { maxbins: 20 }),
			bin_1: standalone_helpers_bin(resolver.columnName, { maxbins: 20, offset: 1 })
		}).count();

		return { values: reducedTable };
	}

	function handleSelect(_, value) {
		dispatch("select", { value });
	}

	function handleBrush(_, value) {
		dispatch("brush", { value });
	}

	$$self.$$set = $$props => {
		if ('data' in $$props) $$invalidate(5, data = $$props.data);
		if ('spec' in $$props) $$invalidate(6, spec = $$props.spec);
		if ('table' in $$props) $$invalidate(7, table = $$props.table);
		if ('filteredTable' in $$props) $$invalidate(8, filteredTable = $$props.filteredTable);
		if ('showUnfilteredData' in $$props) $$invalidate(9, showUnfilteredData = $$props.showUnfilteredData);
		if ('width' in $$props) $$invalidate(10, width = $$props.width);
		if ('height' in $$props) $$invalidate(11, height = $$props.height);
		if ('resolver' in $$props) $$invalidate(12, resolver = $$props.resolver);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*width*/ 1024) {
			$: if (width) $$invalidate(2, options.width = width, options);
		}

		if ($$self.$$.dirty & /*height*/ 2048) {
			$: if (height) $$invalidate(2, options.height = height, options);
		}

		if ($$self.$$.dirty & /*resolver, table, filteredTable*/ 4480) {
			$: $$invalidate(13, reducedData = extractData(resolver, table, filteredTable));
		}

		if ($$self.$$.dirty & /*spec, data, reducedData, showUnfilteredData*/ 8800) {
			$: parseSpecs(spec, data, reducedData, showUnfilteredData);
		}
	};

	return [
		parsedData,
		parsedSpec,
		options,
		handleSelect,
		handleBrush,
		data,
		spec,
		table,
		filteredTable,
		showUnfilteredData,
		width,
		height,
		resolver,
		reducedData
	];
}

class standalone_CanvasVegaLite extends standalone_SvelteComponent {
	constructor(options) {
		super();

		standalone_init(this, options, standalone_CanvasVegaLite_svelte_instance, standalone_CanvasVegaLite_svelte_create_fragment, standalone_safe_not_equal, {
			data: 5,
			spec: 6,
			table: 7,
			filteredTable: 8,
			showUnfilteredData: 9,
			width: 10,
			height: 11,
			resolver: 12
		});
	}
}

/* harmony default export */ const standalone_CanvasVegaLite_svelte = (standalone_CanvasVegaLite);
;// ./src/SummaryListElement.svelte
/* src/SummaryListElement.svelte generated by Svelte v3.59.2 */





function standalone_SummaryListElement_svelte_create_if_block(ctx) {
	let div1;
	let div0;
	let textfield;
	let updating_value;
	let current;

	function textfield_value_binding(value) {
		/*textfield_value_binding*/ ctx[8](value);
	}

	let textfield_props = { placeholder: "Chart Title" };

	if (/*value*/ ctx[4] !== void 0) {
		textfield_props.value = /*value*/ ctx[4];
	}

	textfield = new standalone_TextField_svelte({ props: textfield_props });
	standalone_binding_callbacks.push(() => standalone_bind(textfield, 'value', textfield_value_binding));

	return {
		c() {
			div1 = standalone_internal_element("div");
			div0 = standalone_internal_element("div");
			standalone_create_component(textfield.$$.fragment);
			standalone_attr(div0, "class", "flex-grow");
			standalone_attr(div1, "class", "flex m-1");
		},
		m(target, anchor) {
			standalone_insert(target, div1, anchor);
			standalone_append(div1, div0);
			standalone_mount_component(textfield, div0, null);
			current = true;
		},
		p(ctx, dirty) {
			const textfield_changes = {};

			if (!updating_value && dirty & /*value*/ 16) {
				updating_value = true;
				textfield_changes.value = /*value*/ ctx[4];
				standalone_add_flush_callback(() => updating_value = false);
			}

			textfield.$set(textfield_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(textfield.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(textfield.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div1);
			standalone_destroy_component(textfield);
		}
	};
}

function standalone_SummaryListElement_svelte_create_fragment(ctx) {
	let div;
	let t;
	let canvasvegalite;
	let div_class_value;
	let current;
	let if_block = /*editMode*/ ctx[3] && standalone_SummaryListElement_svelte_create_if_block(ctx);

	canvasvegalite = new standalone_CanvasVegaLite_svelte({
			props: {
				data: /*typedData*/ ctx[5].data,
				spec: /*typedData*/ ctx[5].spec,
				resolver: /*typedData*/ ctx[5].resolver,
				table: /*table*/ ctx[1],
				filteredTable: /*filteredTable*/ ctx[2],
				showUnfilteredData: /*canvasSpec*/ ctx[0].showUnfilteredData
			}
		});

	return {
		c() {
			div = standalone_internal_element("div");
			if (if_block) if_block.c();
			t = standalone_space();
			standalone_create_component(canvasvegalite.$$.fragment);

			standalone_attr(div, "class", div_class_value = "" + ((/*editMode*/ ctx[3]
			? 'border border-button_outline'
			: '') + " rounded m-1 flex flex-col"));
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);
			if (if_block) if_block.m(div, null);
			standalone_append(div, t);
			standalone_mount_component(canvasvegalite, div, null);
			current = true;
		},
		p(ctx, [dirty]) {
			if (/*editMode*/ ctx[3]) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*editMode*/ 8) {
						standalone_transition_in(if_block, 1);
					}
				} else {
					if_block = standalone_SummaryListElement_svelte_create_if_block(ctx);
					if_block.c();
					standalone_transition_in(if_block, 1);
					if_block.m(div, t);
				}
			} else if (if_block) {
				standalone_group_outros();

				standalone_transition_out(if_block, 1, 1, () => {
					if_block = null;
				});

				standalone_check_outros();
			}

			const canvasvegalite_changes = {};
			if (dirty & /*typedData*/ 32) canvasvegalite_changes.data = /*typedData*/ ctx[5].data;
			if (dirty & /*typedData*/ 32) canvasvegalite_changes.spec = /*typedData*/ ctx[5].spec;
			if (dirty & /*typedData*/ 32) canvasvegalite_changes.resolver = /*typedData*/ ctx[5].resolver;
			if (dirty & /*table*/ 2) canvasvegalite_changes.table = /*table*/ ctx[1];
			if (dirty & /*filteredTable*/ 4) canvasvegalite_changes.filteredTable = /*filteredTable*/ ctx[2];
			if (dirty & /*canvasSpec*/ 1) canvasvegalite_changes.showUnfilteredData = /*canvasSpec*/ ctx[0].showUnfilteredData;
			canvasvegalite.$set(canvasvegalite_changes);

			if (!current || dirty & /*editMode*/ 8 && div_class_value !== (div_class_value = "" + ((/*editMode*/ ctx[3]
			? 'border border-button_outline'
			: '') + " rounded m-1 flex flex-col"))) {
				standalone_attr(div, "class", div_class_value);
			}
		},
		i(local) {
			if (current) return;
			standalone_transition_in(if_block);
			standalone_transition_in(canvasvegalite.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(if_block);
			standalone_transition_out(canvasvegalite.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div);
			if (if_block) if_block.d();
			standalone_destroy_component(canvasvegalite);
		}
	};
}

function standalone_SummaryListElement_svelte_instance($$self, $$props, $$invalidate) {
	let typedData;
	let title;
	let { canvasSpec } = $$props;
	let { element } = $$props;
	let { table } = $$props;
	let { filteredTable } = $$props;
	let { editMode = false } = $$props;
	let value = '';
	const dispatch = standalone_createEventDispatcher();

	function textfield_value_binding(value$1) {
		value = value$1;
		((($$invalidate(4, value), $$invalidate(7, title)), $$invalidate(5, typedData)), $$invalidate(6, element));
	}

	$$self.$$set = $$props => {
		if ('canvasSpec' in $$props) $$invalidate(0, canvasSpec = $$props.canvasSpec);
		if ('element' in $$props) $$invalidate(6, element = $$props.element);
		if ('table' in $$props) $$invalidate(1, table = $$props.table);
		if ('filteredTable' in $$props) $$invalidate(2, filteredTable = $$props.filteredTable);
		if ('editMode' in $$props) $$invalidate(3, editMode = $$props.editMode);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*element*/ 64) {
			$: $$invalidate(5, typedData = element.data);
		}

		if ($$self.$$.dirty & /*typedData*/ 32) {
			$: $$invalidate(7, title = typedData.spec.title === undefined
			? ''
			: typedData.spec.title);
		}

		if ($$self.$$.dirty & /*title*/ 128) {
			$: $$invalidate(4, value = title);
		}

		if ($$self.$$.dirty & /*value, typedData, element*/ 112) {
			$: {
				if (value !== typedData.spec.title) {
					dispatch('update', {
						element: Object.assign(Object.assign({}, element), {
							data: Object.assign(Object.assign({}, typedData), {
								spec: Object.assign(Object.assign({}, typedData.spec), { title: value })
							})
						}),
						oldElement: element
					});
				}
			}
		}
	};

	return [
		canvasSpec,
		table,
		filteredTable,
		editMode,
		value,
		typedData,
		element,
		title,
		textfield_value_binding
	];
}

class standalone_SummaryListElement extends standalone_SvelteComponent {
	constructor(options) {
		super();

		standalone_init(this, options, standalone_SummaryListElement_svelte_instance, standalone_SummaryListElement_svelte_create_fragment, standalone_safe_not_equal, {
			canvasSpec: 0,
			element: 6,
			table: 1,
			filteredTable: 2,
			editMode: 3
		});
	}
}

/* harmony default export */ const standalone_SummaryListElement_svelte = (standalone_SummaryListElement);
;// ./src/SummaryNumberElement.svelte
/* src/SummaryNumberElement.svelte generated by Svelte v3.59.2 */


function standalone_SummaryNumberElement_svelte_create_fragment(ctx) {
	let div;
	let p0;
	let t0;
	let t1;
	let t2;
	let p1;
	let t3_value = /*data*/ ctx[0].toLocaleString() + "";
	let t3;
	let div_class_value;

	return {
		c() {
			div = standalone_internal_element("div");
			p0 = standalone_internal_element("p");
			t0 = standalone_internal_text(/*name*/ ctx[1]);
			t1 = standalone_internal_text(":");
			t2 = standalone_space();
			p1 = standalone_internal_element("p");
			t3 = standalone_internal_text(t3_value);
			standalone_attr(p0, "class", "font-bold mr-2");

			standalone_attr(div, "class", div_class_value = "" + ((/*editMode*/ ctx[2]
			? 'border border-button_outline '
			: '') + " flex p-2 m-1 rounded"));
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);
			standalone_append(div, p0);
			standalone_append(p0, t0);
			standalone_append(p0, t1);
			standalone_append(div, t2);
			standalone_append(div, p1);
			standalone_append(p1, t3);
		},
		p(ctx, [dirty]) {
			if (dirty & /*name*/ 2) standalone_set_data(t0, /*name*/ ctx[1]);
			if (dirty & /*data*/ 1 && t3_value !== (t3_value = /*data*/ ctx[0].toLocaleString() + "")) standalone_set_data(t3, t3_value);

			if (dirty & /*editMode*/ 4 && div_class_value !== (div_class_value = "" + ((/*editMode*/ ctx[2]
			? 'border border-button_outline '
			: '') + " flex p-2 m-1 rounded"))) {
				standalone_attr(div, "class", div_class_value);
			}
		},
		i: standalone_noop,
		o: standalone_noop,
		d(detaching) {
			if (detaching) standalone_detach(div);
		}
	};
}

function standalone_SummaryNumberElement_svelte_instance($$self, $$props, $$invalidate) {
	let { data } = $$props;
	let { name } = $$props;
	let { editMode } = $$props;

	$$self.$$set = $$props => {
		if ('data' in $$props) $$invalidate(0, data = $$props.data);
		if ('name' in $$props) $$invalidate(1, name = $$props.name);
		if ('editMode' in $$props) $$invalidate(2, editMode = $$props.editMode);
	};

	return [data, name, editMode];
}

class standalone_SummaryNumberElement extends standalone_SvelteComponent {
	constructor(options) {
		super();
		standalone_init(this, options, standalone_SummaryNumberElement_svelte_instance, standalone_SummaryNumberElement_svelte_create_fragment, standalone_safe_not_equal, { data: 0, name: 1, editMode: 2 });
	}
}

/* harmony default export */ const standalone_SummaryNumberElement_svelte = (standalone_SummaryNumberElement);
;// ../../node_modules/svelte/easing/index.mjs


/*
Adapted from https://github.com/mattdesl
Distributed under MIT License https://github.com/mattdesl/eases/blob/master/LICENSE.md
*/
function standalone_backInOut(t) {
    const s = 1.70158 * 1.525;
    if ((t *= 2) < 1)
        return 0.5 * (t * t * ((s + 1) * t - s));
    return 0.5 * ((t -= 2) * t * ((s + 1) * t + s) + 2);
}
function standalone_backIn(t) {
    const s = 1.70158;
    return t * t * ((s + 1) * t - s);
}
function standalone_backOut(t) {
    const s = 1.70158;
    return --t * t * ((s + 1) * t + s) + 1;
}
function standalone_bounceOut(t) {
    const a = 4.0 / 11.0;
    const b = 8.0 / 11.0;
    const c = 9.0 / 10.0;
    const ca = 4356.0 / 361.0;
    const cb = 35442.0 / 1805.0;
    const cc = 16061.0 / 1805.0;
    const t2 = t * t;
    return t < a
        ? 7.5625 * t2
        : t < b
            ? 9.075 * t2 - 9.9 * t + 3.4
            : t < c
                ? ca * t2 - cb * t + cc
                : 10.8 * t * t - 20.52 * t + 10.72;
}
function standalone_bounceInOut(t) {
    return t < 0.5
        ? 0.5 * (1.0 - standalone_bounceOut(1.0 - t * 2.0))
        : 0.5 * standalone_bounceOut(t * 2.0 - 1.0) + 0.5;
}
function standalone_bounceIn(t) {
    return 1.0 - standalone_bounceOut(1.0 - t);
}
function standalone_circInOut(t) {
    if ((t *= 2) < 1)
        return -0.5 * (Math.sqrt(1 - t * t) - 1);
    return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
}
function standalone_circIn(t) {
    return 1.0 - Math.sqrt(1.0 - t * t);
}
function standalone_circOut(t) {
    return Math.sqrt(1 - --t * t);
}
function standalone_easing_cubicInOut(t) {
    return t < 0.5 ? 4.0 * t * t * t : 0.5 * Math.pow(2.0 * t - 2.0, 3.0) + 1.0;
}
function standalone_cubicIn(t) {
    return t * t * t;
}
function standalone_easing_cubicOut(t) {
    const f = t - 1.0;
    return f * f * f + 1.0;
}
function standalone_elasticInOut(t) {
    return t < 0.5
        ? 0.5 *
            Math.sin(((+13.0 * Math.PI) / 2) * 2.0 * t) *
            Math.pow(2.0, 10.0 * (2.0 * t - 1.0))
        : 0.5 *
            Math.sin(((-13.0 * Math.PI) / 2) * (2.0 * t - 1.0 + 1.0)) *
            Math.pow(2.0, -10.0 * (2.0 * t - 1.0)) +
            1.0;
}
function standalone_elasticIn(t) {
    return Math.sin((13.0 * t * Math.PI) / 2) * Math.pow(2.0, 10.0 * (t - 1.0));
}
function standalone_elasticOut(t) {
    return (Math.sin((-13.0 * (t + 1.0) * Math.PI) / 2) * Math.pow(2.0, -10.0 * t) + 1.0);
}
function standalone_expoInOut(t) {
    return t === 0.0 || t === 1.0
        ? t
        : t < 0.5
            ? +0.5 * Math.pow(2.0, 20.0 * t - 10.0)
            : -0.5 * Math.pow(2.0, 10.0 - t * 20.0) + 1.0;
}
function standalone_expoIn(t) {
    return t === 0.0 ? t : Math.pow(2.0, 10.0 * (t - 1.0));
}
function standalone_expoOut(t) {
    return t === 1.0 ? t : 1.0 - Math.pow(2.0, -10.0 * t);
}
function standalone_quadInOut(t) {
    t /= 0.5;
    if (t < 1)
        return 0.5 * t * t;
    t--;
    return -0.5 * (t * (t - 2) - 1);
}
function standalone_quadIn(t) {
    return t * t;
}
function standalone_quadOut(t) {
    return -t * (t - 2.0);
}
function standalone_quartInOut(t) {
    return t < 0.5
        ? +8.0 * Math.pow(t, 4.0)
        : -8.0 * Math.pow(t - 1.0, 4.0) + 1.0;
}
function standalone_quartIn(t) {
    return Math.pow(t, 4.0);
}
function standalone_quartOut(t) {
    return Math.pow(t - 1.0, 3.0) * (1.0 - t) + 1.0;
}
function standalone_quintInOut(t) {
    if ((t *= 2) < 1)
        return 0.5 * t * t * t * t * t;
    return 0.5 * ((t -= 2) * t * t * t * t + 2);
}
function standalone_quintIn(t) {
    return t * t * t * t * t;
}
function standalone_quintOut(t) {
    return --t * t * t * t * t + 1;
}
function standalone_sineInOut(t) {
    return -0.5 * (Math.cos(Math.PI * t) - 1);
}
function standalone_sineIn(t) {
    const v = Math.cos(t * Math.PI * 0.5);
    if (Math.abs(v) < 1e-14)
        return 1;
    else
        return 1 - v;
}
function standalone_sineOut(t) {
    return Math.sin((t * Math.PI) / 2);
}



;// ../../node_modules/svelte/transition/index.mjs



/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

function standalone_rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

function standalone_transition_blur(node, { delay = 0, duration = 400, easing = cubicInOut, amount = 5, opacity = 0 } = {}) {
    const style = getComputedStyle(node);
    const target_opacity = +style.opacity;
    const f = style.filter === 'none' ? '' : style.filter;
    const od = target_opacity * (1 - opacity);
    const [value, unit] = split_css_unit(amount);
    return {
        delay,
        duration,
        easing,
        css: (_t, u) => `opacity: ${target_opacity - (od * u)}; filter: ${f} blur(${u * value}${unit});`
    };
}
function standalone_fade(node, { delay = 0, duration = 400, easing = standalone_internal_identity } = {}) {
    const o = +getComputedStyle(node).opacity;
    return {
        delay,
        duration,
        easing,
        css: t => `opacity: ${t * o}`
    };
}
function standalone_fly(node, { delay = 0, duration = 400, easing = cubicOut, x = 0, y = 0, opacity = 0 } = {}) {
    const style = getComputedStyle(node);
    const target_opacity = +style.opacity;
    const transform = style.transform === 'none' ? '' : style.transform;
    const od = target_opacity * (1 - opacity);
    const [xValue, xUnit] = split_css_unit(x);
    const [yValue, yUnit] = split_css_unit(y);
    return {
        delay,
        duration,
        easing,
        css: (t, u) => `
			transform: ${transform} translate(${(1 - t) * xValue}${xUnit}, ${(1 - t) * yValue}${yUnit});
			opacity: ${target_opacity - (od * u)}`
    };
}
function standalone_slide(node, { delay = 0, duration = 400, easing = standalone_easing_cubicOut, axis = 'y' } = {}) {
    const style = getComputedStyle(node);
    const opacity = +style.opacity;
    const primary_property = axis === 'y' ? 'height' : 'width';
    const primary_property_value = parseFloat(style[primary_property]);
    const secondary_properties = axis === 'y' ? ['top', 'bottom'] : ['left', 'right'];
    const capitalized_secondary_properties = secondary_properties.map((e) => `${e[0].toUpperCase()}${e.slice(1)}`);
    const padding_start_value = parseFloat(style[`padding${capitalized_secondary_properties[0]}`]);
    const padding_end_value = parseFloat(style[`padding${capitalized_secondary_properties[1]}`]);
    const margin_start_value = parseFloat(style[`margin${capitalized_secondary_properties[0]}`]);
    const margin_end_value = parseFloat(style[`margin${capitalized_secondary_properties[1]}`]);
    const border_width_start_value = parseFloat(style[`border${capitalized_secondary_properties[0]}Width`]);
    const border_width_end_value = parseFloat(style[`border${capitalized_secondary_properties[1]}Width`]);
    return {
        delay,
        duration,
        easing,
        css: t => 'overflow: hidden;' +
            `opacity: ${Math.min(t * 20, 1) * opacity};` +
            `${primary_property}: ${t * primary_property_value}px;` +
            `padding-${secondary_properties[0]}: ${t * padding_start_value}px;` +
            `padding-${secondary_properties[1]}: ${t * padding_end_value}px;` +
            `margin-${secondary_properties[0]}: ${t * margin_start_value}px;` +
            `margin-${secondary_properties[1]}: ${t * margin_end_value}px;` +
            `border-${secondary_properties[0]}-width: ${t * border_width_start_value}px;` +
            `border-${secondary_properties[1]}-width: ${t * border_width_end_value}px;`
    };
}
function standalone_transition_scale(node, { delay = 0, duration = 400, easing = cubicOut, start = 0, opacity = 0 } = {}) {
    const style = getComputedStyle(node);
    const target_opacity = +style.opacity;
    const transform = style.transform === 'none' ? '' : style.transform;
    const sd = 1 - start;
    const od = target_opacity * (1 - opacity);
    return {
        delay,
        duration,
        easing,
        css: (_t, u) => `
			transform: ${transform} scale(${1 - (sd * u)});
			opacity: ${target_opacity - (od * u)}
		`
    };
}
function standalone_transition_draw(node, { delay = 0, speed, duration, easing = cubicInOut } = {}) {
    let len = node.getTotalLength();
    const style = getComputedStyle(node);
    if (style.strokeLinecap !== 'butt') {
        len += parseInt(style.strokeWidth);
    }
    if (duration === undefined) {
        if (speed === undefined) {
            duration = 800;
        }
        else {
            duration = len / speed;
        }
    }
    else if (typeof duration === 'function') {
        duration = duration(len);
    }
    return {
        delay,
        duration,
        easing,
        css: (_, u) => `
			stroke-dasharray: ${len};
			stroke-dashoffset: ${u * len};
		`
    };
}
function standalone_crossfade(_a) {
    var { fallback } = _a, defaults = standalone_rest(_a, ["fallback"]);
    const to_receive = new Map();
    const to_send = new Map();
    function crossfade(from_node, node, params) {
        const { delay = 0, duration = d => Math.sqrt(d) * 30, easing = cubicOut } = assign(assign({}, defaults), params);
        const from = from_node.getBoundingClientRect();
        const to = node.getBoundingClientRect();
        const dx = from.left - to.left;
        const dy = from.top - to.top;
        const dw = from.width / to.width;
        const dh = from.height / to.height;
        const d = Math.sqrt(dx * dx + dy * dy);
        const style = getComputedStyle(node);
        const transform = style.transform === 'none' ? '' : style.transform;
        const opacity = +style.opacity;
        return {
            delay,
            duration: is_function(duration) ? duration(d) : duration,
            easing,
            css: (t, u) => `
				opacity: ${t * opacity};
				transform-origin: top left;
				transform: ${transform} translate(${u * dx}px,${u * dy}px) scale(${t + (1 - t) * dw}, ${t + (1 - t) * dh});
			`
        };
    }
    function transition(items, counterparts, intro) {
        return (node, params) => {
            items.set(params.key, node);
            return () => {
                if (counterparts.has(params.key)) {
                    const other_node = counterparts.get(params.key);
                    counterparts.delete(params.key);
                    return crossfade(other_node, node, params);
                }
                // if the node is disappearing altogether
                // (i.e. wasn't claimed by the other list)
                // then we need to supply an outro
                items.delete(params.key);
                return fallback && fallback(node, params, intro);
            };
        };
    }
    return [
        transition(to_send, to_receive, false),
        transition(to_receive, to_send, true)
    ];
}



;// ./src/SelectedQueries.svelte
/* src/SelectedQueries.svelte generated by Svelte v3.59.2 */






function standalone_get_each_context(ctx, list, i) {
	const child_ctx = ctx.slice();
	child_ctx[4] = list[i];
	return child_ctx;
}

// (32:6) {#if query.icon !== undefined}
function standalone_SelectedQueries_svelte_create_if_block(ctx) {
	let fa;
	let current;
	fa = new standalone_fa_svelte({ props: { icon: /*query*/ ctx[4].icon } });

	return {
		c() {
			standalone_create_component(fa.$$.fragment);
		},
		m(target, anchor) {
			standalone_mount_component(fa, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			const fa_changes = {};
			if (dirty & /*selectedQueries*/ 1) fa_changes.icon = /*query*/ ctx[4].icon;
			fa.$set(fa_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			standalone_destroy_component(fa, detaching);
		}
	};
}

// (26:2) {#each selectedQueries as query}
function standalone_create_each_block(ctx) {
	let div;
	let t0;
	let span;
	let t1_value = /*query*/ ctx[4].name + "";
	let t1;
	let t2;
	let div_transition;
	let current;
	let mounted;
	let dispose;
	let if_block = /*query*/ ctx[4].icon !== undefined && standalone_SelectedQueries_svelte_create_if_block(ctx);

	function click_handler() {
		return /*click_handler*/ ctx[2](/*query*/ ctx[4]);
	}

	return {
		c() {
			div = standalone_internal_element("div");
			if (if_block) if_block.c();
			t0 = standalone_space();
			span = standalone_internal_element("span");
			t1 = standalone_internal_text(t1_value);
			t2 = standalone_space();
			standalone_attr(span, "class", "pl-1");
			standalone_attr(div, "class", "flex flex-grow justify-center items-center m-1 p-1 border rounded cursor-pointer bg-midgrey");
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);
			if (if_block) if_block.m(div, null);
			standalone_append(div, t0);
			standalone_append(div, span);
			standalone_append(span, t1);
			standalone_append(div, t2);
			current = true;

			if (!mounted) {
				dispose = standalone_listen(div, "click", click_handler);
				mounted = true;
			}
		},
		p(new_ctx, dirty) {
			ctx = new_ctx;

			if (/*query*/ ctx[4].icon !== undefined) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*selectedQueries*/ 1) {
						standalone_transition_in(if_block, 1);
					}
				} else {
					if_block = standalone_SelectedQueries_svelte_create_if_block(ctx);
					if_block.c();
					standalone_transition_in(if_block, 1);
					if_block.m(div, t0);
				}
			} else if (if_block) {
				standalone_group_outros();

				standalone_transition_out(if_block, 1, 1, () => {
					if_block = null;
				});

				standalone_check_outros();
			}

			if ((!current || dirty & /*selectedQueries*/ 1) && t1_value !== (t1_value = /*query*/ ctx[4].name + "")) standalone_set_data(t1, t1_value);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(if_block);

			standalone_add_render_callback(() => {
				if (!current) return;
				if (!div_transition) div_transition = standalone_create_bidirectional_transition(div, standalone_slide, {}, true);
				div_transition.run(1);
			});

			current = true;
		},
		o(local) {
			standalone_transition_out(if_block);
			if (!div_transition) div_transition = standalone_create_bidirectional_transition(div, standalone_slide, {}, false);
			div_transition.run(0);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div);
			if (if_block) if_block.d();
			if (detaching && div_transition) div_transition.end();
			mounted = false;
			dispose();
		}
	};
}

function standalone_SelectedQueries_svelte_create_fragment(ctx) {
	let div;
	let current;
	let each_value = /*selectedQueries*/ ctx[0];
	let each_blocks = [];

	for (let i = 0; i < each_value.length; i += 1) {
		each_blocks[i] = standalone_create_each_block(standalone_get_each_context(ctx, each_value, i));
	}

	const out = i => standalone_transition_out(each_blocks[i], 1, 1, () => {
		each_blocks[i] = null;
	});

	return {
		c() {
			div = standalone_internal_element("div");

			for (let i = 0; i < each_blocks.length; i += 1) {
				each_blocks[i].c();
			}

			standalone_attr(div, "class", "flex flex-col");
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);

			for (let i = 0; i < each_blocks.length; i += 1) {
				if (each_blocks[i]) {
					each_blocks[i].m(div, null);
				}
			}

			current = true;
		},
		p(ctx, [dirty]) {
			if (dirty & /*previousQuery, selectedQueries, undefined*/ 3) {
				each_value = /*selectedQueries*/ ctx[0];
				let i;

				for (i = 0; i < each_value.length; i += 1) {
					const child_ctx = standalone_get_each_context(ctx, each_value, i);

					if (each_blocks[i]) {
						each_blocks[i].p(child_ctx, dirty);
						standalone_transition_in(each_blocks[i], 1);
					} else {
						each_blocks[i] = standalone_create_each_block(child_ctx);
						each_blocks[i].c();
						standalone_transition_in(each_blocks[i], 1);
						each_blocks[i].m(div, null);
					}
				}

				standalone_group_outros();

				for (i = each_value.length; i < each_blocks.length; i += 1) {
					out(i);
				}

				standalone_check_outros();
			}
		},
		i(local) {
			if (current) return;

			for (let i = 0; i < each_value.length; i += 1) {
				standalone_transition_in(each_blocks[i]);
			}

			current = true;
		},
		o(local) {
			each_blocks = each_blocks.filter(Boolean);

			for (let i = 0; i < each_blocks.length; i += 1) {
				standalone_transition_out(each_blocks[i]);
			}

			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div);
			standalone_destroy_each(each_blocks, detaching);
		}
	};
}

function standalone_SelectedQueries_svelte_instance($$self, $$props, $$invalidate) {
	let { selectedQueries } = $$props;
	const dispatch = standalone_createEventDispatcher();

	function previousQuery(query) {
		dispatch('previousQuery', { query });
	}

	const click_handler = query => previousQuery(query);

	$$self.$$set = $$props => {
		if ('selectedQueries' in $$props) $$invalidate(0, selectedQueries = $$props.selectedQueries);
	};

	return [selectedQueries, previousQuery, click_handler];
}

class standalone_SelectedQueries extends standalone_SvelteComponent {
	constructor(options) {
		super();
		standalone_init(this, options, standalone_SelectedQueries_svelte_instance, standalone_SelectedQueries_svelte_create_fragment, standalone_safe_not_equal, { selectedQueries: 0 });
	}
}

/* harmony default export */ const standalone_SelectedQueries_svelte = (standalone_SelectedQueries);
;// ./src/NextQueries.svelte
/* src/NextQueries.svelte generated by Svelte v3.59.2 */






function standalone_NextQueries_svelte_get_each_context(ctx, list, i) {
	const child_ctx = ctx.slice();
	child_ctx[5] = list[i];
	return child_ctx;
}

// (32:6) {#if query.icon !== undefined}
function standalone_NextQueries_svelte_create_if_block(ctx) {
	let fa;
	let current;

	fa = new standalone_fa_svelte({
			props: {
				color: "#7f7f7f",
				icon: /*query*/ ctx[5].icon
			}
		});

	return {
		c() {
			standalone_create_component(fa.$$.fragment);
		},
		m(target, anchor) {
			standalone_mount_component(fa, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			const fa_changes = {};
			if (dirty & /*nextQueries*/ 1) fa_changes.icon = /*query*/ ctx[5].icon;
			fa.$set(fa_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			standalone_destroy_component(fa, detaching);
		}
	};
}

// (27:2) {#each nextQueries as query}
function standalone_NextQueries_svelte_create_each_block(ctx) {
	let div;
	let t0;
	let span;
	let t1_value = /*query*/ ctx[5].name + "";
	let t1;
	let t2;
	let current;
	let mounted;
	let dispose;
	let if_block = /*query*/ ctx[5].icon !== undefined && standalone_NextQueries_svelte_create_if_block(ctx);

	function click_handler() {
		return /*click_handler*/ ctx[3](/*query*/ ctx[5]);
	}

	return {
		c() {
			div = standalone_internal_element("div");
			if (if_block) if_block.c();
			t0 = standalone_space();
			span = standalone_internal_element("span");
			t1 = standalone_internal_text(t1_value);
			t2 = standalone_space();
			standalone_attr(span, "class", "pl-1 text-darkgrey");
			standalone_attr(div, "class", "flex flex-grow justify-center items-center m-1 p-1 border border-midgrey rounded cursor-pointer");
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);
			if (if_block) if_block.m(div, null);
			standalone_append(div, t0);
			standalone_append(div, span);
			standalone_append(span, t1);
			standalone_append(div, t2);
			current = true;

			if (!mounted) {
				dispose = standalone_listen(div, "click", click_handler);
				mounted = true;
			}
		},
		p(new_ctx, dirty) {
			ctx = new_ctx;

			if (/*query*/ ctx[5].icon !== undefined) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*nextQueries*/ 1) {
						standalone_transition_in(if_block, 1);
					}
				} else {
					if_block = standalone_NextQueries_svelte_create_if_block(ctx);
					if_block.c();
					standalone_transition_in(if_block, 1);
					if_block.m(div, t0);
				}
			} else if (if_block) {
				standalone_group_outros();

				standalone_transition_out(if_block, 1, 1, () => {
					if_block = null;
				});

				standalone_check_outros();
			}

			if ((!current || dirty & /*nextQueries*/ 1) && t1_value !== (t1_value = /*query*/ ctx[5].name + "")) standalone_set_data(t1, t1_value);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(if_block);
			current = true;
		},
		o(local) {
			standalone_transition_out(if_block);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div);
			if (if_block) if_block.d();
			mounted = false;
			dispose();
		}
	};
}

function standalone_NextQueries_svelte_create_fragment(ctx) {
	let div;
	let div_transition;
	let current;
	let each_value = /*nextQueries*/ ctx[0];
	let each_blocks = [];

	for (let i = 0; i < each_value.length; i += 1) {
		each_blocks[i] = standalone_NextQueries_svelte_create_each_block(standalone_NextQueries_svelte_get_each_context(ctx, each_value, i));
	}

	const out = i => standalone_transition_out(each_blocks[i], 1, 1, () => {
		each_blocks[i] = null;
	});

	return {
		c() {
			div = standalone_internal_element("div");

			for (let i = 0; i < each_blocks.length; i += 1) {
				each_blocks[i].c();
			}

			standalone_attr(div, "class", "flex flex-wrap");
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);

			for (let i = 0; i < each_blocks.length; i += 1) {
				if (each_blocks[i]) {
					each_blocks[i].m(div, null);
				}
			}

			current = true;
		},
		p(ctx, [dirty]) {
			if (dirty & /*querySelected, nextQueries, undefined*/ 3) {
				each_value = /*nextQueries*/ ctx[0];
				let i;

				for (i = 0; i < each_value.length; i += 1) {
					const child_ctx = standalone_NextQueries_svelte_get_each_context(ctx, each_value, i);

					if (each_blocks[i]) {
						each_blocks[i].p(child_ctx, dirty);
						standalone_transition_in(each_blocks[i], 1);
					} else {
						each_blocks[i] = standalone_NextQueries_svelte_create_each_block(child_ctx);
						each_blocks[i].c();
						standalone_transition_in(each_blocks[i], 1);
						each_blocks[i].m(div, null);
					}
				}

				standalone_group_outros();

				for (i = each_value.length; i < each_blocks.length; i += 1) {
					out(i);
				}

				standalone_check_outros();
			}
		},
		i(local) {
			if (current) return;

			for (let i = 0; i < each_value.length; i += 1) {
				standalone_transition_in(each_blocks[i]);
			}

			standalone_add_render_callback(() => {
				if (!current) return;
				if (!div_transition) div_transition = standalone_create_bidirectional_transition(div, standalone_fade, {}, true);
				div_transition.run(1);
			});

			current = true;
		},
		o(local) {
			each_blocks = each_blocks.filter(Boolean);

			for (let i = 0; i < each_blocks.length; i += 1) {
				standalone_transition_out(each_blocks[i]);
			}

			if (!div_transition) div_transition = standalone_create_bidirectional_transition(div, standalone_fade, {}, false);
			div_transition.run(0);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div);
			standalone_destroy_each(each_blocks, detaching);
			if (detaching && div_transition) div_transition.end();
		}
	};
}

function standalone_NextQueries_svelte_instance($$self, $$props, $$invalidate) {
	let nextQueries;
	let { currentQuery } = $$props;
	const dispatch = standalone_createEventDispatcher();

	function querySelected(query) {
		dispatch('querySelected', { query });
	}

	const click_handler = query => querySelected(query);

	$$self.$$set = $$props => {
		if ('currentQuery' in $$props) $$invalidate(2, currentQuery = $$props.currentQuery);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*currentQuery*/ 4) {
			$: $$invalidate(0, nextQueries = currentQuery.next);
		}
	};

	return [nextQueries, querySelected, currentQuery, click_handler];
}

class standalone_NextQueries extends standalone_SvelteComponent {
	constructor(options) {
		super();
		standalone_init(this, options, standalone_NextQueries_svelte_instance, standalone_NextQueries_svelte_create_fragment, standalone_safe_not_equal, { currentQuery: 2 });
	}
}

/* harmony default export */ const standalone_NextQueries_svelte = (standalone_NextQueries);
;// ./src/SummaryChartSelection.svelte
/* src/SummaryChartSelection.svelte generated by Svelte v3.59.2 */








function standalone_SummaryChartSelection_svelte_create_fragment(ctx) {
	let div1;
	let div0;
	let selectedqueries;
	let t;
	let nextqueries;
	let div1_transition;
	let current;

	selectedqueries = new standalone_SelectedQueries_svelte({
			props: {
				selectedQueries: /*selectedQueries*/ ctx[0]
			}
		});

	selectedqueries.$on("previousQuery", /*previousQuery*/ ctx[3]);

	nextqueries = new standalone_NextQueries_svelte({
			props: { currentQuery: /*currentQuery*/ ctx[1] }
		});

	nextqueries.$on("querySelected", /*querySelected*/ ctx[2]);

	return {
		c() {
			div1 = standalone_internal_element("div");
			div0 = standalone_internal_element("div");
			standalone_create_component(selectedqueries.$$.fragment);
			t = standalone_space();
			standalone_create_component(nextqueries.$$.fragment);
			standalone_attr(div0, "class", "flex flex-col");
			standalone_attr(div1, "class", "flex flex-col p-2 bg-lightgrey border-midgrey border-2 rounded select-none");
		},
		m(target, anchor) {
			standalone_insert(target, div1, anchor);
			standalone_append(div1, div0);
			standalone_mount_component(selectedqueries, div0, null);
			standalone_append(div0, t);
			standalone_mount_component(nextqueries, div0, null);
			current = true;
		},
		p(ctx, [dirty]) {
			const selectedqueries_changes = {};
			if (dirty & /*selectedQueries*/ 1) selectedqueries_changes.selectedQueries = /*selectedQueries*/ ctx[0];
			selectedqueries.$set(selectedqueries_changes);
			const nextqueries_changes = {};
			if (dirty & /*currentQuery*/ 2) nextqueries_changes.currentQuery = /*currentQuery*/ ctx[1];
			nextqueries.$set(nextqueries_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(selectedqueries.$$.fragment, local);
			standalone_transition_in(nextqueries.$$.fragment, local);

			standalone_add_render_callback(() => {
				if (!current) return;
				if (!div1_transition) div1_transition = standalone_create_bidirectional_transition(div1, standalone_fade, {}, true);
				div1_transition.run(1);
			});

			current = true;
		},
		o(local) {
			standalone_transition_out(selectedqueries.$$.fragment, local);
			standalone_transition_out(nextqueries.$$.fragment, local);
			if (!div1_transition) div1_transition = standalone_create_bidirectional_transition(div1, standalone_fade, {}, false);
			div1_transition.run(0);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div1);
			standalone_destroy_component(selectedqueries);
			standalone_destroy_component(nextqueries);
			if (detaching && div1_transition) div1_transition.end();
		}
	};
}

function standalone_SummaryChartSelection_svelte_instance($$self, $$props, $$invalidate) {
	let { table } = $$props;
	const dispatch = standalone_createEventDispatcher();
	let selectedQueries = [];
	let currentQuery = standalone_getQueryTree(table);

	function querySelected(event) {
		const query = event.detail.query;

		if (typeof query.next === 'function') {
			dispatch('elementSelected', {
				element: query.next(selectedQueries.map(query => query.name), table)
			});

			$$invalidate(1, currentQuery = standalone_getQueryTree(table));
			$$invalidate(0, selectedQueries = []);
		} else {
			$$invalidate(0, selectedQueries = [...selectedQueries, query]);
			$$invalidate(1, currentQuery = query);
		}
	}

	function previousQuery(event) {
		const previousQuery = event.detail.query;
		const index = selectedQueries.findIndex(query => query === previousQuery);

		if (index === 0) {
			$$invalidate(1, currentQuery = standalone_getQueryTree(table));
			$$invalidate(0, selectedQueries = []);
		} else {
			$$invalidate(1, currentQuery = selectedQueries[index - 1]);
			selectedQueries.slice(index - 1);
		}
	}

	$$self.$$set = $$props => {
		if ('table' in $$props) $$invalidate(4, table = $$props.table);
	};

	return [selectedQueries, currentQuery, querySelected, previousQuery, table];
}

class standalone_SummaryChartSelection extends standalone_SvelteComponent {
	constructor(options) {
		super();
		standalone_init(this, options, standalone_SummaryChartSelection_svelte_instance, standalone_SummaryChartSelection_svelte_create_fragment, standalone_safe_not_equal, { table: 4 });
	}
}

/* harmony default export */ const standalone_SummaryChartSelection_svelte = (standalone_SummaryChartSelection);
;// ./src/CanvasSummary.svelte
/* src/CanvasSummary.svelte generated by Svelte v3.59.2 */















function standalone_CanvasSummary_svelte_get_each_context(ctx, list, i) {
	const child_ctx = ctx.slice();
	child_ctx[24] = list[i];
	return child_ctx;
}

function standalone_get_each_context_1(ctx, list, i) {
	const child_ctx = ctx.slice();
	child_ctx[24] = list[i];
	return child_ctx;
}

// (73:8) 
function standalone_CanvasSummary_svelte_create_icon_slot(ctx) {
	let fa;
	let current;

	fa = new standalone_fa_svelte({
			props: {
				icon: /*editMode*/ ctx[6] ? standalone_faCheck/* faCheck */.e6 : standalone_faEdit/* faEdit */.MT,
				slot: "icon"
			}
		});

	return {
		c() {
			standalone_create_component(fa.$$.fragment);
		},
		m(target, anchor) {
			standalone_mount_component(fa, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			const fa_changes = {};
			if (dirty & /*editMode*/ 64) fa_changes.icon = /*editMode*/ ctx[6] ? standalone_faCheck/* faCheck */.e6 : standalone_faEdit/* faEdit */.MT;
			fa.$set(fa_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			standalone_destroy_component(fa, detaching);
		}
	};
}

// (74:8) 
function standalone_CanvasSummary_svelte_create_text_slot(ctx) {
	let span;
	let t_value = (/*editMode*/ ctx[6] ? 'Done' : 'Edit') + "";
	let t;

	return {
		c() {
			span = standalone_internal_element("span");
			t = standalone_internal_text(t_value);
			standalone_attr(span, "slot", "text");
		},
		m(target, anchor) {
			standalone_insert(target, span, anchor);
			standalone_append(span, t);
		},
		p(ctx, dirty) {
			if (dirty & /*editMode*/ 64 && t_value !== (t_value = (/*editMode*/ ctx[6] ? 'Done' : 'Edit') + "")) standalone_set_data(t, t_value);
		},
		d(detaching) {
			if (detaching) standalone_detach(span);
		}
	};
}

// (66:2) <ComponentHeader     title={'Summary'}     description={widgetSpec.description}     {container}   >
function standalone_create_default_slot(ctx) {
	let div;
	let iconbutton;
	let current;

	iconbutton = new standalone_IconButton_svelte({
			props: {
				$$slots: {
					text: [standalone_CanvasSummary_svelte_create_text_slot],
					icon: [standalone_CanvasSummary_svelte_create_icon_slot]
				},
				$$scope: { ctx }
			}
		});

	iconbutton.$on("click", /*click_handler*/ ctx[17]);

	return {
		c() {
			div = standalone_internal_element("div");
			standalone_create_component(iconbutton.$$.fragment);
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);
			standalone_mount_component(iconbutton, div, null);
			current = true;
		},
		p(ctx, dirty) {
			const iconbutton_changes = {};

			if (dirty & /*$$scope, editMode*/ 536870976) {
				iconbutton_changes.$$scope = { dirty, ctx };
			}

			iconbutton.$set(iconbutton_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(iconbutton.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(iconbutton.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div);
			standalone_destroy_component(iconbutton);
		}
	};
}

// (78:2) {#if editMode}
function standalone_create_if_block_3(ctx) {
	let summarychartselection;
	let current;
	summarychartselection = new standalone_SummaryChartSelection_svelte({ props: { table: /*$table*/ ctx[5] } });
	summarychartselection.$on("elementSelected", /*addElement*/ ctx[13]);

	return {
		c() {
			standalone_create_component(summarychartselection.$$.fragment);
		},
		m(target, anchor) {
			standalone_mount_component(summarychartselection, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			const summarychartselection_changes = {};
			if (dirty & /*$table*/ 32) summarychartselection_changes.table = /*$table*/ ctx[5];
			summarychartselection.$set(summarychartselection_changes);
		},
		i(local) {
			if (current) return;
			standalone_transition_in(summarychartselection.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(summarychartselection.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			standalone_destroy_component(summarychartselection, detaching);
		}
	};
}

// (125:4) {:else}
function standalone_CanvasSummary_svelte_create_else_block(ctx) {
	let p;

	return {
		c() {
			p = standalone_internal_element("p");
			p.textContent = "There was no data found to display in the summary charts.";
		},
		m(target, anchor) {
			standalone_insert(target, p, anchor);
		},
		p: standalone_noop,
		i: standalone_noop,
		o: standalone_noop,
		d(detaching) {
			if (detaching) standalone_detach(p);
		}
	};
}

// (82:4) {#if CharacterData.length > 0 || numberData.length > 0}
function standalone_CanvasSummary_svelte_create_if_block(ctx) {
	let div0;
	let t;
	let div1;
	let current;
	let each_value_1 = /*numberData*/ ctx[9];
	let each_blocks_1 = [];

	for (let i = 0; i < each_value_1.length; i += 1) {
		each_blocks_1[i] = standalone_create_each_block_1(standalone_get_each_context_1(ctx, each_value_1, i));
	}

	const out = i => standalone_transition_out(each_blocks_1[i], 1, 1, () => {
		each_blocks_1[i] = null;
	});

	let each_value = /*chartData*/ ctx[8];
	let each_blocks = [];

	for (let i = 0; i < each_value.length; i += 1) {
		each_blocks[i] = standalone_CanvasSummary_svelte_create_each_block(standalone_CanvasSummary_svelte_get_each_context(ctx, each_value, i));
	}

	const out_1 = i => standalone_transition_out(each_blocks[i], 1, 1, () => {
		each_blocks[i] = null;
	});

	return {
		c() {
			div0 = standalone_internal_element("div");

			for (let i = 0; i < each_blocks_1.length; i += 1) {
				each_blocks_1[i].c();
			}

			t = standalone_space();
			div1 = standalone_internal_element("div");

			for (let i = 0; i < each_blocks.length; i += 1) {
				each_blocks[i].c();
			}

			standalone_attr(div0, "class", "flex flex-wrap");
			standalone_attr(div1, "class", "flex flex-wrap");
		},
		m(target, anchor) {
			standalone_insert(target, div0, anchor);

			for (let i = 0; i < each_blocks_1.length; i += 1) {
				if (each_blocks_1[i]) {
					each_blocks_1[i].m(div0, null);
				}
			}

			standalone_insert(target, t, anchor);
			standalone_insert(target, div1, anchor);

			for (let i = 0; i < each_blocks.length; i += 1) {
				if (each_blocks[i]) {
					each_blocks[i].m(div1, null);
				}
			}

			current = true;
		},
		p(ctx, dirty) {
			if (dirty & /*removeElement, numberData, faTimes, editMode*/ 4672) {
				each_value_1 = /*numberData*/ ctx[9];
				let i;

				for (i = 0; i < each_value_1.length; i += 1) {
					const child_ctx = standalone_get_each_context_1(ctx, each_value_1, i);

					if (each_blocks_1[i]) {
						each_blocks_1[i].p(child_ctx, dirty);
						standalone_transition_in(each_blocks_1[i], 1);
					} else {
						each_blocks_1[i] = standalone_create_each_block_1(child_ctx);
						each_blocks_1[i].c();
						standalone_transition_in(each_blocks_1[i], 1);
						each_blocks_1[i].m(div0, null);
					}
				}

				standalone_group_outros();

				for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
					out(i);
				}

				standalone_check_outros();
			}

			if (dirty & /*removeElement, chartData, faTimes, editMode, $table, $filteredTable, $canvasSpec, updateElement*/ 23904) {
				each_value = /*chartData*/ ctx[8];
				let i;

				for (i = 0; i < each_value.length; i += 1) {
					const child_ctx = standalone_CanvasSummary_svelte_get_each_context(ctx, each_value, i);

					if (each_blocks[i]) {
						each_blocks[i].p(child_ctx, dirty);
						standalone_transition_in(each_blocks[i], 1);
					} else {
						each_blocks[i] = standalone_CanvasSummary_svelte_create_each_block(child_ctx);
						each_blocks[i].c();
						standalone_transition_in(each_blocks[i], 1);
						each_blocks[i].m(div1, null);
					}
				}

				standalone_group_outros();

				for (i = each_value.length; i < each_blocks.length; i += 1) {
					out_1(i);
				}

				standalone_check_outros();
			}
		},
		i(local) {
			if (current) return;

			for (let i = 0; i < each_value_1.length; i += 1) {
				standalone_transition_in(each_blocks_1[i]);
			}

			for (let i = 0; i < each_value.length; i += 1) {
				standalone_transition_in(each_blocks[i]);
			}

			current = true;
		},
		o(local) {
			each_blocks_1 = each_blocks_1.filter(Boolean);

			for (let i = 0; i < each_blocks_1.length; i += 1) {
				standalone_transition_out(each_blocks_1[i]);
			}

			each_blocks = each_blocks.filter(Boolean);

			for (let i = 0; i < each_blocks.length; i += 1) {
				standalone_transition_out(each_blocks[i]);
			}

			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div0);
			standalone_destroy_each(each_blocks_1, detaching);
			if (detaching) standalone_detach(t);
			if (detaching) standalone_detach(div1);
			standalone_destroy_each(each_blocks, detaching);
		}
	};
}

// (91:12) {#if editMode}
function standalone_create_if_block_2(ctx) {
	let button;
	let fa;
	let current;
	let mounted;
	let dispose;
	fa = new standalone_fa_svelte({ props: { icon: standalone_faTimes/* faTimes */.GR } });

	function click_handler_1() {
		return /*click_handler_1*/ ctx[18](/*element*/ ctx[24]);
	}

	return {
		c() {
			button = standalone_internal_element("button");
			standalone_create_component(fa.$$.fragment);
			standalone_attr(button, "class", "absolute top-0 right-0");
		},
		m(target, anchor) {
			standalone_insert(target, button, anchor);
			standalone_mount_component(fa, button, null);
			current = true;

			if (!mounted) {
				dispose = standalone_listen(button, "click", click_handler_1);
				mounted = true;
			}
		},
		p(new_ctx, dirty) {
			ctx = new_ctx;
		},
		i(local) {
			if (current) return;
			standalone_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(button);
			standalone_destroy_component(fa);
			mounted = false;
			dispose();
		}
	};
}

// (84:8) {#each numberData as element}
function standalone_create_each_block_1(ctx) {
	let div;
	let summarynumberelement;
	let t0;
	let t1;
	let current;

	summarynumberelement = new standalone_SummaryNumberElement_svelte({
			props: {
				data: /*element*/ ctx[24].data,
				name: /*element*/ ctx[24].name,
				editMode: /*editMode*/ ctx[6]
			}
		});

	let if_block = /*editMode*/ ctx[6] && standalone_create_if_block_2(ctx);

	return {
		c() {
			div = standalone_internal_element("div");
			standalone_create_component(summarynumberelement.$$.fragment);
			t0 = standalone_space();
			if (if_block) if_block.c();
			t1 = standalone_space();
			standalone_attr(div, "class", "relative");
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);
			standalone_mount_component(summarynumberelement, div, null);
			standalone_append(div, t0);
			if (if_block) if_block.m(div, null);
			standalone_append(div, t1);
			current = true;
		},
		p(ctx, dirty) {
			const summarynumberelement_changes = {};
			if (dirty & /*numberData*/ 512) summarynumberelement_changes.data = /*element*/ ctx[24].data;
			if (dirty & /*numberData*/ 512) summarynumberelement_changes.name = /*element*/ ctx[24].name;
			if (dirty & /*editMode*/ 64) summarynumberelement_changes.editMode = /*editMode*/ ctx[6];
			summarynumberelement.$set(summarynumberelement_changes);

			if (/*editMode*/ ctx[6]) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*editMode*/ 64) {
						standalone_transition_in(if_block, 1);
					}
				} else {
					if_block = standalone_create_if_block_2(ctx);
					if_block.c();
					standalone_transition_in(if_block, 1);
					if_block.m(div, t1);
				}
			} else if (if_block) {
				standalone_group_outros();

				standalone_transition_out(if_block, 1, 1, () => {
					if_block = null;
				});

				standalone_check_outros();
			}
		},
		i(local) {
			if (current) return;
			standalone_transition_in(summarynumberelement.$$.fragment, local);
			standalone_transition_in(if_block);
			current = true;
		},
		o(local) {
			standalone_transition_out(summarynumberelement.$$.fragment, local);
			standalone_transition_out(if_block);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div);
			standalone_destroy_component(summarynumberelement);
			if (if_block) if_block.d();
		}
	};
}

// (114:12) {#if editMode}
function standalone_CanvasSummary_svelte_create_if_block_1(ctx) {
	let button;
	let fa;
	let current;
	let mounted;
	let dispose;
	fa = new standalone_fa_svelte({ props: { icon: standalone_faTimes/* faTimes */.GR } });

	function click_handler_2() {
		return /*click_handler_2*/ ctx[20](/*element*/ ctx[24]);
	}

	return {
		c() {
			button = standalone_internal_element("button");
			standalone_create_component(fa.$$.fragment);
			standalone_attr(button, "class", "absolute top-0 right-0");
		},
		m(target, anchor) {
			standalone_insert(target, button, anchor);
			standalone_mount_component(fa, button, null);
			current = true;

			if (!mounted) {
				dispose = standalone_listen(button, "click", click_handler_2);
				mounted = true;
			}
		},
		p(new_ctx, dirty) {
			ctx = new_ctx;
		},
		i(local) {
			if (current) return;
			standalone_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			standalone_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(button);
			standalone_destroy_component(fa);
			mounted = false;
			dispose();
		}
	};
}

// (103:8) {#each chartData as element}
function standalone_CanvasSummary_svelte_create_each_block(ctx) {
	let div;
	let summarylistelement;
	let t0;
	let t1;
	let current;

	summarylistelement = new standalone_SummaryListElement_svelte({
			props: {
				table: /*$table*/ ctx[5],
				filteredTable: /*$filteredTable*/ ctx[10],
				canvasSpec: /*$canvasSpec*/ ctx[11],
				element: /*element*/ ctx[24],
				editMode: /*editMode*/ ctx[6]
			}
		});

	summarylistelement.$on("update", /*update_handler*/ ctx[19]);
	let if_block = /*editMode*/ ctx[6] && standalone_CanvasSummary_svelte_create_if_block_1(ctx);

	return {
		c() {
			div = standalone_internal_element("div");
			standalone_create_component(summarylistelement.$$.fragment);
			t0 = standalone_space();
			if (if_block) if_block.c();
			t1 = standalone_space();
			standalone_attr(div, "class", "relative");
		},
		m(target, anchor) {
			standalone_insert(target, div, anchor);
			standalone_mount_component(summarylistelement, div, null);
			standalone_append(div, t0);
			if (if_block) if_block.m(div, null);
			standalone_append(div, t1);
			current = true;
		},
		p(ctx, dirty) {
			const summarylistelement_changes = {};
			if (dirty & /*$table*/ 32) summarylistelement_changes.table = /*$table*/ ctx[5];
			if (dirty & /*$filteredTable*/ 1024) summarylistelement_changes.filteredTable = /*$filteredTable*/ ctx[10];
			if (dirty & /*$canvasSpec*/ 2048) summarylistelement_changes.canvasSpec = /*$canvasSpec*/ ctx[11];
			if (dirty & /*chartData*/ 256) summarylistelement_changes.element = /*element*/ ctx[24];
			if (dirty & /*editMode*/ 64) summarylistelement_changes.editMode = /*editMode*/ ctx[6];
			summarylistelement.$set(summarylistelement_changes);

			if (/*editMode*/ ctx[6]) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*editMode*/ 64) {
						standalone_transition_in(if_block, 1);
					}
				} else {
					if_block = standalone_CanvasSummary_svelte_create_if_block_1(ctx);
					if_block.c();
					standalone_transition_in(if_block, 1);
					if_block.m(div, t1);
				}
			} else if (if_block) {
				standalone_group_outros();

				standalone_transition_out(if_block, 1, 1, () => {
					if_block = null;
				});

				standalone_check_outros();
			}
		},
		i(local) {
			if (current) return;
			standalone_transition_in(summarylistelement.$$.fragment, local);
			standalone_transition_in(if_block);
			current = true;
		},
		o(local) {
			standalone_transition_out(summarylistelement.$$.fragment, local);
			standalone_transition_out(if_block);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div);
			standalone_destroy_component(summarylistelement);
			if (if_block) if_block.d();
		}
	};
}

function standalone_CanvasSummary_svelte_create_fragment(ctx) {
	let div1;
	let componentheader;
	let t0;
	let t1;
	let div0;
	let current_block_type_index;
	let if_block1;
	let div1_class_value;
	let current;

	componentheader = new standalone_ComponentHeader_svelte({
			props: {
				title: 'Summary',
				description: /*widgetSpec*/ ctx[3].description,
				container: /*container*/ ctx[7],
				$$slots: { default: [standalone_create_default_slot] },
				$$scope: { ctx }
			}
		});

	let if_block0 = /*editMode*/ ctx[6] && standalone_create_if_block_3(ctx);
	const if_block_creators = [standalone_CanvasSummary_svelte_create_if_block, standalone_CanvasSummary_svelte_create_else_block];
	const if_blocks = [];

	function select_block_type(ctx, dirty) {
		if (CharacterData.length > 0 || /*numberData*/ ctx[9].length > 0) return 0;
		return 1;
	}

	current_block_type_index = select_block_type(ctx, -1);
	if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);

	return {
		c() {
			div1 = standalone_internal_element("div");
			standalone_create_component(componentheader.$$.fragment);
			t0 = standalone_space();
			if (if_block0) if_block0.c();
			t1 = standalone_space();
			div0 = standalone_internal_element("div");
			if_block1.c();
			standalone_attr(div0, "class", "flex flex-col overflow-auto");

			standalone_attr(div1, "class", div1_class_value = "flex flex-col p-2 " + (/*fullSize*/ ctx[4]
			? 'h-full'
			: standalone_mapHeight(/*widgetSpec*/ ctx[3].height)));
		},
		m(target, anchor) {
			standalone_insert(target, div1, anchor);
			standalone_mount_component(componentheader, div1, null);
			standalone_append(div1, t0);
			if (if_block0) if_block0.m(div1, null);
			standalone_append(div1, t1);
			standalone_append(div1, div0);
			if_blocks[current_block_type_index].m(div0, null);
			/*div0_binding*/ ctx[21](div0);
			current = true;
		},
		p(ctx, [dirty]) {
			const componentheader_changes = {};
			if (dirty & /*widgetSpec*/ 8) componentheader_changes.description = /*widgetSpec*/ ctx[3].description;
			if (dirty & /*container*/ 128) componentheader_changes.container = /*container*/ ctx[7];

			if (dirty & /*$$scope, editMode*/ 536870976) {
				componentheader_changes.$$scope = { dirty, ctx };
			}

			componentheader.$set(componentheader_changes);

			if (/*editMode*/ ctx[6]) {
				if (if_block0) {
					if_block0.p(ctx, dirty);

					if (dirty & /*editMode*/ 64) {
						standalone_transition_in(if_block0, 1);
					}
				} else {
					if_block0 = standalone_create_if_block_3(ctx);
					if_block0.c();
					standalone_transition_in(if_block0, 1);
					if_block0.m(div1, t1);
				}
			} else if (if_block0) {
				standalone_group_outros();

				standalone_transition_out(if_block0, 1, 1, () => {
					if_block0 = null;
				});

				standalone_check_outros();
			}

			let previous_block_index = current_block_type_index;
			current_block_type_index = select_block_type(ctx, dirty);

			if (current_block_type_index === previous_block_index) {
				if_blocks[current_block_type_index].p(ctx, dirty);
			} else {
				standalone_group_outros();

				standalone_transition_out(if_blocks[previous_block_index], 1, 1, () => {
					if_blocks[previous_block_index] = null;
				});

				standalone_check_outros();
				if_block1 = if_blocks[current_block_type_index];

				if (!if_block1) {
					if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
					if_block1.c();
				} else {
					if_block1.p(ctx, dirty);
				}

				standalone_transition_in(if_block1, 1);
				if_block1.m(div0, null);
			}

			if (!current || dirty & /*fullSize, widgetSpec*/ 24 && div1_class_value !== (div1_class_value = "flex flex-col p-2 " + (/*fullSize*/ ctx[4]
			? 'h-full'
			: standalone_mapHeight(/*widgetSpec*/ ctx[3].height)))) {
				standalone_attr(div1, "class", div1_class_value);
			}
		},
		i(local) {
			if (current) return;
			standalone_transition_in(componentheader.$$.fragment, local);
			standalone_transition_in(if_block0);
			standalone_transition_in(if_block1);
			current = true;
		},
		o(local) {
			standalone_transition_out(componentheader.$$.fragment, local);
			standalone_transition_out(if_block0);
			standalone_transition_out(if_block1);
			current = false;
		},
		d(detaching) {
			if (detaching) standalone_detach(div1);
			standalone_destroy_component(componentheader);
			if (if_block0) if_block0.d();
			if_blocks[current_block_type_index].d();
			/*div0_binding*/ ctx[21](null);
		}
	};
}

function standalone_CanvasSummary_svelte_instance($$self, $$props, $$invalidate) {
	let elements;
	let numberData;
	let chartData;

	let $table,
		$$unsubscribe_table = standalone_noop,
		$$subscribe_table = () => ($$unsubscribe_table(), $$unsubscribe_table = standalone_subscribe(table, $$value => $$invalidate(5, $table = $$value)), table);

	let $filteredTable,
		$$unsubscribe_filteredTable = standalone_noop,
		$$subscribe_filteredTable = () => ($$unsubscribe_filteredTable(), $$unsubscribe_filteredTable = standalone_subscribe(filteredTable, $$value => $$invalidate(10, $filteredTable = $$value)), filteredTable);

	let $canvasSpec,
		$$unsubscribe_canvasSpec = standalone_noop,
		$$subscribe_canvasSpec = () => ($$unsubscribe_canvasSpec(), $$unsubscribe_canvasSpec = standalone_subscribe(canvasSpec, $$value => $$invalidate(11, $canvasSpec = $$value)), canvasSpec);

	$$self.$$.on_destroy.push(() => $$unsubscribe_table());
	$$self.$$.on_destroy.push(() => $$unsubscribe_filteredTable());
	$$self.$$.on_destroy.push(() => $$unsubscribe_canvasSpec());
	let { canvasSpec } = $$props;
	$$subscribe_canvasSpec();
	let { table } = $$props;
	$$subscribe_table();
	let { filteredTable } = $$props;
	$$subscribe_filteredTable();
	let { widgetSpec } = $$props;
	let { fullSize = false } = $$props;
	const dispatch = standalone_createEventDispatcher();
	let editMode = false;
	let userSpecUpdate = false;
	let container;

	function updateSpecElements(newElements) {
		const newSpec = Object.assign(Object.assign({}, widgetSpec), { summaryElements: newElements });
		dispatch('specChanged', { spec: newSpec });
	}

	function removeElement(element) {
		$$invalidate(15, userSpecUpdate = true);
		let newElements = elements.filter(el => el.name !== element.name || el.data !== element.data);
		updateSpecElements(newElements);
	}

	function addElement(event) {
		$$invalidate(15, userSpecUpdate = true);
		let newElements = [...elements, event.detail.element];
		updateSpecElements(newElements);
	}

	function updateElement(element, oldElement) {
		$$invalidate(15, userSpecUpdate = true);
		let elementIndex = elements.findIndex(el => el.name === oldElement.name && el.data === oldElement.data);
		const newElements = elements.slice();
		newElements[elementIndex] = element;
		updateSpecElements(newElements);
	}

	const click_handler = () => $$invalidate(6, editMode = !editMode);
	const click_handler_1 = element => removeElement(element);
	const update_handler = event => updateElement(event.detail.element, event.detail.oldElement);
	const click_handler_2 = element => removeElement(element);

	function div0_binding($$value) {
		standalone_binding_callbacks[$$value ? 'unshift' : 'push'](() => {
			container = $$value;
			$$invalidate(7, container);
		});
	}

	$$self.$$set = $$props => {
		if ('canvasSpec' in $$props) $$subscribe_canvasSpec($$invalidate(0, canvasSpec = $$props.canvasSpec));
		if ('table' in $$props) $$subscribe_table($$invalidate(1, table = $$props.table));
		if ('filteredTable' in $$props) $$subscribe_filteredTable($$invalidate(2, filteredTable = $$props.filteredTable));
		if ('widgetSpec' in $$props) $$invalidate(3, widgetSpec = $$props.widgetSpec);
		if ('fullSize' in $$props) $$invalidate(4, fullSize = $$props.fullSize);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*widgetSpec, userSpecUpdate, $table*/ 32808) {
			$: $$invalidate(16, elements = widgetSpec.summaryElements.length === 0 && !userSpecUpdate
			? standalone_extractColumnElements($table)
			: widgetSpec.summaryElements);
		}

		if ($$self.$$.dirty & /*elements*/ 65536) {
			$: $$invalidate(9, numberData = elements.filter(row => typeof row.data === 'number'));
		}

		if ($$self.$$.dirty & /*elements*/ 65536) {
			$: $$invalidate(8, chartData = elements.filter(row => typeof row.data !== 'number'));
		}
	};

	return [
		canvasSpec,
		table,
		filteredTable,
		widgetSpec,
		fullSize,
		$table,
		editMode,
		container,
		chartData,
		numberData,
		$filteredTable,
		$canvasSpec,
		removeElement,
		addElement,
		updateElement,
		userSpecUpdate,
		elements,
		click_handler,
		click_handler_1,
		update_handler,
		click_handler_2,
		div0_binding
	];
}

class standalone_CanvasSummary extends standalone_SvelteComponent {
	constructor(options) {
		super();

		standalone_init(this, options, standalone_CanvasSummary_svelte_instance, standalone_CanvasSummary_svelte_create_fragment, standalone_safe_not_equal, {
			canvasSpec: 0,
			table: 1,
			filteredTable: 2,
			widgetSpec: 3,
			fullSize: 4
		});
	}
}

/* harmony default export */ const standalone_CanvasSummary_svelte = (standalone_CanvasSummary);
;// ./src/standalone.ts
/**
 * Copyright 2024 BetterWithData
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


var __webpack_exports__CanvasSummary = __webpack_exports__.z;
export { __webpack_exports__CanvasSummary as CanvasSummary };

//# sourceMappingURL=CanvasSummary.js.map